reponame
stringlengths 2
39
| files
list | median_score
float64 0
11.5
|
---|---|---|
felipeort | [
{
"content": "# https://docs.python.org/3/library/socket.html\n\nimport socket\nimport dns.resolver\n\n# 0) Vamos a consultar el estado de un buzón de correo utilizando el protocolo POP3\n\nusuario = \"ort-grupo2\"\npassword = \"<PASSWORD>\"\n\ndominio = 'lab.ort.edu.uy' # Nombre de dominio al que quiero enviar correo\n\n\n# 1) Determinar servidor SMTP del dominio lab.ort.edu.uy\n\nrestpuesta_consulta_MX = dns.resolver.resolve(dominio, 'MX')\nprint(\"Respuesta a consulta registro MX: \", \"\\r\\n\", restpuesta_consulta_MX)\n\nmail_exchange = restpuesta_consulta_MX[0].exchange\nprint(\"Mail Exchange: \", \"\\r\\n\", mail_exchange)\nprint(type(mail_exchange))\n\nmail_exchange_str = str(mail_exchange)\nprint(\"Mail Exchange STR: \", \"\\r\\n\", mail_exchange_str)\nprint(type(mail_exchange_str))\n\n# 2) Necesito determinar el registro A del servidor de correo encontrado en (1)\n# 2) Puedo obtenerlo mediante una consulta independiente\n# 2) O puede encontrarse como Additional Record en la consulta anterior\n\nmail_exchange_A = restpuesta_consulta_MX.nameserver\nprint(\"Registro A de Mail Exchange: \", \"\\r\\n\", mail_exchange_A)\nprint(type(mail_exchange_A))\n\n\n# 3) Puedo consultar el estado de la casilla\n\nPUERTO = 110 # Puerto definido por la IANA para POP3\n\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mi_socket:\n mi_socket.connect((mail_exchange_A, PUERTO))\n respuesta = mi_socket.recv(2048)\n\n # Establecemos conexión POP3 con el servidor de correo.\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n # Naturalmente debería contemplar la ocurrencia de errores y manejarlos de forma acorde\n # Por ejemplo utilizando try / catch\n # Pero ese detalle esta más allá del alcance del ejemplo\n\n MENSAJE_POP3 = \"USER\" + \" \" + usuario + \"\\r\\n\"\n print(MENSAJE_POP3)\n mi_socket.sendall(MENSAJE_POP3.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_POP3 = \"PASS\" + \" \" + password + \"\\r\\n\"\n print(MENSAJE_POP3)\n mi_socket.sendall(MENSAJE_POP3.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_POP3 = \"LIST\" + \"\\r\\n\"\n print(MENSAJE_POP3)\n mi_socket.sendall(MENSAJE_POP3.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_POP3 = \"RETR 1\" + \"\\r\\n\"\n print(MENSAJE_POP3)\n mi_socket.sendall(MENSAJE_POP3.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_POP3 = \"DELE 1\" + \"\\r\\n\"\n print(MENSAJE_POP3)\n mi_socket.sendall(MENSAJE_POP3.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_POP3 = \"QUIT\" + \"\\r\\n\"\n print(MENSAJE_POP3)\n mi_socket.sendall(MENSAJE_POP3.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n mi_socket.close()\n\n\n\n\n",
"id": "6917932",
"language": "Python",
"matching_score": 5.365405559539795,
"max_stars_count": 0,
"path": "pop3_simple.py"
},
{
"content": "# https://docs.python.org/3/library/socket.html\n\nimport socket\nimport dns.resolver\n\n# 0) Vamos a enviar un correo desde <EMAIL> a <EMAIL>\n\ncasilla_origen = \"ort-grupo1\"\ncasilla_destino = \"ort-grupo2\"\n\ndominio = 'lab.ort.edu.uy' # Nombre de dominio al que quiero enviar correo\n\n\n# 1) Determinar servidor SMTP del dominio lab.ort.edu.uy\n\nrestpuesta_consulta_MX = dns.resolver.resolve(dominio, 'MX')\nprint(\"Respuesta a consulta registro MX: \", \"\\r\\n\", restpuesta_consulta_MX)\n\nmail_exchange = restpuesta_consulta_MX[0].exchange\nprint(\"Mail Exchange: \", \"\\r\\n\", mail_exchange)\nprint(type(mail_exchange))\n\nmail_exchange_str = str(mail_exchange)\nprint(\"Mail Exchange STR: \", \"\\r\\n\", mail_exchange_str)\nprint(type(mail_exchange_str))\n\n# 2) Necesito determinar el registro A del servidor de correo encontrado en (1)\n# 2) Puedo obtenerlo mediante una consulta independiente\n# 2) O puede encontrarse como Additional Record en la consulta anterior\n\nmail_exchange_A = restpuesta_consulta_MX.nameserver\nprint(\"Registro A de Mail Exchange: \", \"\\r\\n\", mail_exchange_A)\nprint(type(mail_exchange_A))\n\n\n# 3) Puedo comenzar a elaborar el \"sobre\" del correo utilizando el protocolo SMTP\n\nPUERTO = 25 # Puerto definido por la IANA para SMTP\n\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mi_socket:\n mi_socket.connect((mail_exchange_A, PUERTO))\n respuesta = mi_socket.recv(2048)\n\n # Establecemos conexión SMTP con el servidor de correo.\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n # Naturalmente debería contemplar la ocurrencia de errores y manejarlos de forma acorde\n # Por ejemplo utilizando try / catch\n # Pero ese detalle esta más allá del alcance del ejemplo\n\n MENSAJE_SMTP = \"HELO\" + \" \" + dominio + \"\\r\\n\"\n print(MENSAJE_SMTP)\n mi_socket.sendall(MENSAJE_SMTP.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_SMTP = \"MAIL FROM:\" + \" \" + \"<\" + casilla_origen + \">\" + \"\\r\\n\"\n print(MENSAJE_SMTP)\n mi_socket.sendall(MENSAJE_SMTP.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_SMTP = \"RCPT TO:\" + \" \" + \"<\" + casilla_destino + \">\" + \"\\r\\n\"\n print(MENSAJE_SMTP)\n mi_socket.sendall(MENSAJE_SMTP.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n MENSAJE_SMTP = \"DATA\" + \"\\r\\n\"\n print(MENSAJE_SMTP)\n mi_socket.sendall(MENSAJE_SMTP.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n # 4) Dentro del \"sobre\" SMTP va la \"carta\"\n\n DATA = \"From: <EMAIL>\" + \"\\r\\n\" + \"To: <EMAIL> \" + \"\\r\\n\" + \\\n \"Subject: Felicidades\" + \"\\r\\n\" + \"@Feliz año 2021 !\" + \"\\r\\n\" + \".\" + \"\\r\\n\"\n\n print(DATA)\n\n mi_socket.sendall(DATA.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n # 4) La \"carta\" ya fue enviada, puedo cerrar la sesión SMTP\n\n MENSAJE_SMTP = \"QUIT\" + \"\\r\\n\"\n print(MENSAJE_SMTP)\n mi_socket.sendall(MENSAJE_SMTP.encode())\n\n respuesta = mi_socket.recv(2048)\n print('La respuesta recibida es: ')\n print(respuesta.decode())\n\n mi_socket.close()\n\n\n\n\n",
"id": "494903",
"language": "Python",
"matching_score": 1.2427406311035156,
"max_stars_count": 0,
"path": "smtp_simple_send.py"
},
{
"content": "# https://docs.python.org/3/library/socket.html\n\nimport socket\n\n\n# Datos del Laboratorio\n\nSITIO_WEB = 'example.com' \nPUERTO = 80 # Puerto donde escucha el servidor HTTP\n\n#################################################################\n# PRIMERO: Consulto al DNS por el registro A de example.com\n#################################################################\n\nIPv4_SERVIDOR = socket.gethostbyname(SITIO_WEB)\n\nprint('La direccion IPv4 de' + SITIO_WEB + 'es: ')\nprint(IPv4_SERVIDOR)\n\n######################################################################\n# SEGUNDO: Damos formato a un string que represente una consulta HTTP\n######################################################################\n\n# Metodo GET\nGET = \"GET / HTTP/1.1\" + \"\\r\\n\"\n\n# Encabezado HOST\nHOST = \"Host: \" + SITIO_WEB + \"\\r\\n\"\n\n# Encabezado User-Agent\nUSER_AGENT = \"User-agent: \" + \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0\" + \"\\r\\n\"\n\n# Encabezado Accept\nACCEPT = \"Accept: \" + \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\" + \"\\r\\n\"\n\n# Encabezado Accept-Language\nACCEPT_LANGUAGE = \"Accept-Language: \" + \"es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3\" + \"\\r\\n\"\n\n# Encabezado Connection\nCONNECTION = \"Connection: \" + \"keep-alive\" + \"\\r\\n\"\n\n# Concatenamos:\nMENSAJE_HTTP = GET + HOST + ACCEPT + ACCEPT_LANGUAGE + USER_AGENT + CONNECTION + \"\\r\\n\"\n\nprint('El mensaje HTTP es: ')\nprint(MENSAJE_HTTP)\n\n#############################################################################################\n# TERCERO: Creamos un socket TCP tipo STREAM donde escribimos el mensaje y leemos la respueta\n#############################################################################################\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mi_socket:\n mi_socket.connect((IPv4_SERVIDOR, PUERTO))\n mi_socket.sendall(MENSAJE_HTTP.encode('utf-8'))\n respuesta = mi_socket.recv(2048)\n mi_socket.close()\n\nprint('La respuesta recibida es: ')\nprint(respuesta.decode('ascii'))\n",
"id": "9063557",
"language": "Python",
"matching_score": 7.402853965759277,
"max_stars_count": 0,
"path": "cliente_http_sockets.py"
},
{
"content": "# <NAME>: Por más ejemplos consultar:\n# https://docs.python.org/3/library/socket.html\n# https://docs.python.org/3/library/telnetlib.html\n\nimport socket\nfrom telnetlib import Telnet\n\n# Datos del Laboratorio\n\nSITIO_WEB = 'example.com' \nPUERTO = 80 # Puerto donde escucha el servidor HTTP\n\n\n#################################################################\n# PRIMERO: Consulto al DNS por el registro A de SITIO_WEB\n#################################################################\n\nIPv4_SERVIDOR = socket.gethostbyname(SITIO_WEB)\n\nprint('La direccion IPv4 de ' + SITIO_WEB + ' es: ')\nprint(IPv4_SERVIDOR)\n\n######################################################################\n# SEGUNDO: Damos formato a un string que represente una consulta HTTP\n######################################################################\n\n# Metodo GET\nGET = \"GET / HTTP/1.1\" + \"\\r\\n\"\n\n# Encabezado HOST\nHOST = \"Host: \" + SITIO_WEB + \"\\r\\n\"\n\n# Encabezado User-Agent\nUSER_AGENT = \"User-agent: \" + \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0\" + \"\\r\\n\"\n\n# Encabezado Accept\nACCEPT = \"Accept: \" + \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\" + \"\\r\\n\"\n\n# Encabezado Accept-Language\nACCEPT_LANGUAGE = \"Accept-Language: \" + \"es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3\" + \"\\r\\n\"\n\n# Encabezado Connection\nCONNECTION = \"Connection: \" + \"close\" + \"\\r\\n\"\n\n# Concatenamos:\nMENSAJE_HTTP = GET + HOST + ACCEPT + ACCEPT_LANGUAGE + USER_AGENT + CONNECTION + \"\\r\\n\"\n\nprint('El mensaje HTTP es: ')\nprint(MENSAJE_HTTP)\n\n\n#############################################################################################\n# TERCERO: Utilizamos TELNET para establecer una conexion TCP con el puerto 80 del servidor\n# En esta conexion escribimos el mensaje HTTP y leemos la respuesta\n#############################################################################################\n\nwith Telnet(IPv4_SERVIDOR, PUERTO) as mi_telnet:\n mi_telnet.write(MENSAJE_HTTP.encode('ascii'))\n print(mi_telnet.read_all().decode('ascii'))\n mi_telnet.close()\n",
"id": "8846157",
"language": "Python",
"matching_score": 3.7293102741241455,
"max_stars_count": 0,
"path": "cliente_http_telnet.py"
},
{
"content": "# https://docs.python.org/3/library/http.client.html#module-http.client\n\nimport http.client\n\n# Datos del Laboratorio\n\nSITIO_WEB = 'example.com' \n\n##########################################################################\n# PRIMERO y UNICO PASO: Hablo el protocolo HTTP con el servidor\n##########################################################################\n\nconexion = http.client.HTTPConnection(SITIO_WEB)\nconexion.request(\"GET\", \"/\")\nrespuesta = conexion.getresponse()\nprint('Codigo de respuesta: ')\nprint(respuesta.status, respuesta.reason)\ndatos = respuesta.read()\nprint('Datos en la respuesta: ')\nprint(datos.decode('ascii'))\nconexion.close()\n",
"id": "1547455",
"language": "Python",
"matching_score": 1.7168238162994385,
"max_stars_count": 0,
"path": "cliente_http.py"
}
] | 3.72931 |
PradeepKadubandi | [
{
"content": "# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This file is derived from Habitat-Sim - https://github.com/facebookresearch/habitat-sim.git\n\nimport habitat_sim\nimport habitat_sim.agent\nimport habitat_sim.bindings as hsim\n\n\n# build SimulatorConfiguration\ndef make_cfg(SIM):\n sim_cfg = hsim.SimulatorConfiguration()\n\n if SIM.SCENE_ID == \"none\":\n SIM.SCENE_ID = \"data/scene_datasets/habitat-test-scenes/skokloster-castle.glb\"\n sim_cfg.scene_id = SIM.SCENE_ID\n\n sim_cfg.enable_physics = SIM.PHYSICS\n if SIM.PHYSICS:\n sim_cfg.physics_config_file = SIM.PHYSICS_CONFIG_FILE\n # sim_cfg.gpu_device_id = 0\n # sim_cfg.scene.id = settings[\"scene\"]\n\n # define default sensor parameters (see src/esp/Sensor/Sensor.h)\n sensors = dict()\n for i in range(len(SIM.AGENT.SENSORS.NAMES)):\n sensors[SIM.AGENT.SENSORS.NAMES[i]] = {\n \"sensor_type\": getattr(hsim.SensorType, SIM.AGENT.SENSORS.TYPES[i]),\n \"resolution\": [\n SIM.AGENT.SENSORS.RESOLUTIONS[i][0],\n SIM.AGENT.SENSORS.RESOLUTIONS[i][1],\n ],\n \"position\": [\n SIM.AGENT.SENSORS.POSES[i][0],\n SIM.AGENT.SENSORS.POSES[i][1],\n SIM.AGENT.SENSORS.POSES[i][2],\n ],\n \"orientation\": [\n SIM.AGENT.SENSORS.POSES[i][3],\n SIM.AGENT.SENSORS.POSES[i][4],\n SIM.AGENT.SENSORS.POSES[i][5],\n ],\n }\n\n if SIM.noisy:\n # sensors['rgb']['noise_model'] = 'GaussianNoiseModel' # We don't use RGB Noise\n sensors['depth']['noise_model'] = 'RedwoodDepthNoiseModel'\n\n # create sensor specifications\n sensor_specs = []\n for sensor_uuid, sensor_params in sensors.items():\n sensor_spec = hsim.CameraSensorSpec()\n sensor_spec.uuid = sensor_uuid\n sensor_spec.sensor_type = sensor_params[\"sensor_type\"]\n sensor_spec.resolution = sensor_params[\"resolution\"]\n sensor_spec.position = sensor_params[\"position\"]\n sensor_spec.gpu2gpu_transfer = False # Todo: Move this to config\n if SIM.noisy and sensor_uuid in ('depth'):\n sensor_spec.noise_model = sensor_params['noise_model']\n print(\"==== Initialized Sensor Spec: =====\")\n print(\"Sensor uuid: \", sensor_spec.uuid)\n print(\"Sensor type: \", sensor_spec.sensor_type)\n print(\"Sensor position: \", sensor_spec.position)\n print(\"===================================\")\n\n sensor_specs.append(sensor_spec)\n\n # create agent specifications\n # TODO: Accomodate more agents\n agent_cfg = habitat_sim.agent.AgentConfiguration()\n agent_cfg.sensor_specifications = sensor_specs\n # TODO: Move agent actions to config\n agent_cfg.action_space = {\n \"move_forward\": habitat_sim.agent.ActionSpec(\n \"move_forward\", habitat_sim.agent.ActuationSpec(amount=1.0) if not SIM.noisy else \n habitat_sim.agent.PyRobotNoisyActuationSpec(amount=1.0)\n ),\n \"turn_left\": habitat_sim.agent.ActionSpec(\n \"turn_left\", habitat_sim.agent.ActuationSpec(amount=10.0) if not SIM.noisy else \n habitat_sim.agent.PyRobotNoisyActuationSpec(amount=10.0)\n ),\n \"turn_right\": habitat_sim.agent.ActionSpec(\n \"turn_right\", habitat_sim.agent.ActuationSpec(amount=10.0) if not SIM.noisy else \n habitat_sim.agent.PyRobotNoisyActuationSpec(amount=10.0)\n ),\n }\n sim_cfg.default_agent_id = SIM.DEFAULT_AGENT_ID\n # # override action space to no-op to test physics\n # if sim_cfg.enable_physics:\n # agent_cfg.action_space = {\n # \"move_forward\": habitat_sim.agent.ActionSpec(\n # \"move_forward\", habitat_sim.agent.ActuationSpec(amount=0.0)\n # )\n # }\n\n return habitat_sim.Configuration(sim_cfg, [agent_cfg])\n",
"id": "3736211",
"language": "Python",
"matching_score": 1.0906580686569214,
"max_stars_count": 0,
"path": "droidlet/lowlevel/locobot/remote/pyrobot/habitat/sim_utils.py"
},
{
"content": "\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\"\"\"\n\nimport numpy as np\n\nMAX_MAP_SIZE = 4097\nMAP_INIT_SIZE = 1025\nBIG_I = MAX_MAP_SIZE\nBIG_J = MAX_MAP_SIZE\n\n\ndef no_y_l1(self, xyz, k):\n \"\"\" returns the l1 distance between two standard coordinates\"\"\"\n return np.linalg.norm(np.asarray([xyz[0], xyz[2]]) - np.asarray([k[0], k[2]]), ord=1)\n\n\n# TODO tighter integration with reference objects table, main memory update\n# should probably sync PlaceField maps without explicit perception updates\n# Node type for complicated-shaped obstacles that aren't \"objects\" e.g. walls?\n# currently just represented as occupancy cells with no memid\n# FIXME allow multiple memids at a single location in the map\n\n\nclass PlaceField:\n \"\"\"\n maintains a grid-based map of some slice(s) of the world, and \n the state representations needed to track active exploration.\n\n the .place_fields attribute is a dict with keys corresponding to heights, \n and values {\"map\": 2d numpy array, \"updated\": 2d numpy array, \"memids\": 2d numpy array}\n place_fields[h][\"map\"] is an occupany map at the the height h (in agent coordinates)\n a location is 0 if there is nothing there or it is unseen, 1 if occupied \n place_fields[h][\"memids\"] gives a memid index for the ReferenceObject at that location, \n if there is a ReferenceObject linked to that spatial location.\n the PlaceField keeps a mappping from the indices to memids in \n self.index2memid and self.memid2index\n place_fields[h][\"updated\"] gives the last update time of that location (in agent's internal time)\n if -1, it has neer been updated\n\n the .map2real method converts a location from a map to world coords\n the .real2map method converts a location from the world to the map coords\n\n droidlet.interpreter.robot.tasks.CuriousExplore uses the can_examine method to decide \n which objects to explore next:\n 1. for each new candidate coordinate, it fetches the closest examined coordinate.\n 2. if this closest coordinate is within a certain threshold (1 meter) of the current coordinate, \n or if that region has been explored upto a certain number of times (2, for redundancy),\n it is not explored, since a 'close-enough' region in space has already been explored. \n \"\"\"\n\n def __init__(self, memory, pixels_per_unit=1):\n self.get_time = memory.get_time\n\n self.index2memid = []\n self.memid2index = {}\n\n self.examined = {}\n self.examined_id = set()\n self.last = None\n\n self.maps = {}\n self.maybe_add_memid(\"NULL\")\n self.maybe_add_memid(memory.self_memid)\n # FIXME, want slices, esp for mc... init after first perception\n # with h=y2slice(y) instead of using 0\n self.map_size = self.extend_map(h=0)\n\n self.pixels_per_unit = pixels_per_unit\n\n # gives an index allowing quick lookup by memid\n # each entry is keyed by a memid and is a dict\n # {str(h*BIG_I*BIG_J + i*BIG_J + j) : True}\n # for each placed h, i ,j\n self.memid2locs = {}\n\n def ijh2idx(self, i, j, h):\n return str(h * BIG_I * BIG_J + i * BIG_J + j)\n\n def idx2ijh(self, idx):\n idx = int(idx)\n j = idx % BIG_J\n idx = (idx - j) // BIG_J\n i = idx % BIG_I\n h = (idx - i) // BIG_I\n return i, j, h\n\n def pop_memid_loc(self, memid, i, j, h):\n idx = self.hij2idx(h, i, j)\n del self.memid2locs[memid][idx]\n\n def maybe_delete_loc(self, i, j, h, t, memid=\"NULL\"):\n \"\"\"\n remove a loc from the maps and from memid2loc index.\n if memid is set, only removes the loc if the memid matches\n \"\"\"\n current_memid = self.index2memid[int(self.maps[h][\"memids\"][i, j])]\n if memid == \"NULL\" or current_memid == memid:\n self.maps[h][\"memids\"][i, j] = self.memid2index[\"NULL\"]\n self.maps[h][\"map\"][i, j] = 0\n self.maps[h][\"updated\"][i, j] = t\n idx = self.ijh2idx(i, j, h)\n # maybe error/warn if its not there?\n if self.memid2locs.get(memid):\n self.memid2locs[memid].pop(idx, None)\n if len(self.memid2locs[memid]) == 0:\n self.memid2locs.pop(memid, None)\n\n def delete_loc_by_memid(self, memid, t, is_move=False):\n \"\"\"\n remove all locs corresponding to a memid. \n if is_move is set, asserts that there is precisely one loc\n corresponding to the memid\n \"\"\"\n assert memid\n assert memid != \"NULL\"\n count = 0\n for idx in self.memid2locs.get(memid, []):\n i, j, h = self.idx2ijh(idx)\n self.maps[h][\"memids\"][i, j] = 0\n self.maps[h][\"map\"][i, j] = 0\n self.maps[h][\"updated\"][i, j] = t\n count = count + 1\n if is_move and count > 1:\n # eventually allow moving \"large\" objects\n raise Exception(\n \"tried to delete more than one pixel from the place_field by memid with is_move set\"\n )\n self.memid2locs.pop(memid, None)\n\n def update_map(self, changes):\n \"\"\"\n changes is a list of dicts of the form \n {\"pos\": (x, y, z),\n \"memid\": str (default \"NULL\"),\n \"is_obstacle\": bool (default True),\n \"is_move\": bool (default False),\n \"is_delete\": bool (default False) }\n pos is required if is_delete is False. \n all other fields are always optional.\n \n \"is_obstacle\" tells whether the agent can traverse that location\n if \"is_move\" is False, the change is taken as is; if \"is_move\" is True, if the\n change corresponds to a memid, and the memid is located somewhere on the map,\n the old location is removed when the new one is set. For now, to move complicated objects\n that cover many pixels, do not use is_move, and instead move them \"by hand\"\n by issuing a list of changes deleting the old now empty locations and adding the\n new now-filled locations\n \"is_delete\" True without a memid means whatever is in that location is to be removed.\n if a memid is set, the remove will occur only if the memid matches.\n \n the \"is_obstacle\" status can be changed without changing memid etc.\n \"\"\"\n t = self.get_time()\n for c in changes:\n is_delete = c.get(\"is_delete\", False)\n is_move = c.get(\"is_move\", False)\n memid = c.get(\"memid\", \"NULL\")\n p = c.get(\"pos\")\n if p is None:\n assert is_delete\n # if the change is a remove, and is specified by memid:\n if not memid:\n raise Exception(\"tried to update a map location without a location or a memid\")\n # warn if empty TODO?\n self.delete_loc_by_memid(memid, t)\n else:\n x, y, z = p\n h = self.y2slice(y)\n i, j = self.real2map(x, z, h)\n s = max(i - self.map_size + 1, j - self.map_size + 1, -i, -j)\n if s > 0:\n self.extend_map(s)\n i, j = self.real2map(x, z, h)\n s = max(i - self.map_size + 1, j - self.map_size + 1, -i, -j)\n if s > 0:\n # the map can not been extended enough to handle these bc MAX_MAP_SIZE\n # FIXME appropriate warning or error?\n continue\n if is_delete:\n self.maybe_delete_loc(i, j, h, t, memid=memid)\n else:\n if is_move:\n assert memid != \"NULL\"\n self.delete_loc_by_memid(memid, t, is_move=True)\n self.maps[h][\"memids\"][i, j] = self.memid2index.get(\n memid, self.maybe_add_memid(memid)\n )\n self.maps[h][\"map\"][i, j] = c.get(\"is_obstacle\", 1)\n self.maps[h][\"updated\"][i, j] = t\n if not self.memid2locs.get(memid):\n self.memid2locs[memid] = {}\n self.memid2locs[memid][self.ijh2idx(i, j, h)] = True\n\n # FIXME, want slices, esp for mc\n def y2slice(self, y):\n return 0\n\n def real2map(self, x, z, h):\n \"\"\"\n convert an x, z coordinate in agent space to a pixel on the map\n \"\"\"\n n = self.maps[h][\"map\"].shape[0]\n i = x * self.pixels_per_unit\n j = z * self.pixels_per_unit\n i = i + n // 2\n j = j + n // 2\n return round(i), round(j)\n\n def map2real(self, i, j, h):\n \"\"\"\n convert an i, j pixel coordinate in the map to agent space\n \"\"\"\n n = self.maps[h][\"map\"].shape[0]\n i = i - n // 2\n j = j - n // 2\n x = i / self.pixels_per_unit\n z = j / self.pixels_per_unit\n return x, z\n\n def maybe_add_memid(self, memid):\n \"\"\" \n adds an entry to the mapping from memids to ints to put on map.\n these are never removed\n \"\"\"\n idx = self.memid2index.get(memid)\n if idx is None:\n idx = len(self.index2memid)\n self.index2memid.append(memid)\n self.memid2index[memid] = idx\n return idx\n\n def extend_map(self, h=None, extension=1):\n assert extension >= 0\n if not h and len(self.maps) == 1:\n h = list(self.maps.keys())[0]\n if not self.maps.get(h):\n self.maps[h] = {}\n for m, v in {\"updated\": -1, \"map\": 0, \"memids\": 0}.items():\n self.maps[h][m] = v * np.ones((MAP_INIT_SIZE, MAP_INIT_SIZE))\n w = self.maps[h][\"map\"].shape[0]\n new_w = w + 2 * extension\n if new_w > MAX_MAP_SIZE:\n return -1\n for m, v in {\"updated\": -1, \"map\": 0, \"memids\": 0}.items():\n new_map = v * np.ones((new_w, new_w))\n new_map[extension:-extension, extension:-extension] = self.maps[h][m]\n self.maps[h][m] = new_map\n return new_w\n\n def get_closest(self, xyz):\n \"\"\"returns closest examined point to xyz\"\"\"\n c = None\n dist = 1.5\n for k, v in self.examined.items():\n if no_y_l1(k, xyz) < dist:\n dist = no_y_l1(k, xyz)\n c = k\n if c is None:\n self.examined[xyz] = 0\n return xyz\n return c\n\n def update(self, target):\n \"\"\"called each time a region is examined. Updates relevant states.\"\"\"\n self.last = self.get_closest(target[\"xyz\"])\n self.examined_id.add(target[\"eid\"])\n self.examined[self.last] += 1\n\n def clear_examined(self):\n self.examined = {}\n self.examined_id = set()\n self.last = None\n\n def can_examine(self, x):\n \"\"\"decides whether to examine x or not.\"\"\"\n loc = x[\"xyz\"]\n k = self.get_closest(x[\"xyz\"])\n val = True\n if self.last is not None and self.l1(cls.last, k) < 1:\n val = False\n val = self.examined[k] < 2\n print(\n f\"can_examine {x['eid'], x['label'], x['xyz'][:2]}, closest {k[:2]}, can_examine {val}\"\n )\n print(f\"examined[k] = {self.examined[k]}\")\n return val\n\n\nif __name__ == \"__main__\":\n W = {0: {0: {0: True}, 1: {2: {3: True}}}, 1: {5: True}}\n idxs = [0, 1, 2, 3]\n",
"id": "11028709",
"language": "Python",
"matching_score": 1.4603281021118164,
"max_stars_count": 0,
"path": "droidlet/memory/place_field.py"
},
{
"content": "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n''' \nThis script syncs Mephisto (MTurk) allowlists and blocklists between the\nlocal Mephisto DB and shared lists (.txt files) in an S3 bucket.\n\nCurrently implemented are the interaction job and vision annotation job\nlists, but the structure is extendable to future qualifications as well.\n'''\n\nimport argparse\nimport os\nimport logging\nimport boto3\nimport copy\n\nfrom mephisto.data_model.worker import Worker\nfrom mephisto.abstractions.databases.local_database import LocalMephistoDB\nfrom mephisto.tools.data_browser import DataBrowser as MephistoDataBrowser\n\nfrom droidlet_static_html_task.pilot_config import PILOT_ALLOWLIST_QUAL_NAME as interaction_whitelist\nfrom droidlet_static_html_task.pilot_config import PILOT_BLOCK_QUAL_NAME as interaction_blacklist\nfrom vision_annotation_task.pilot_config import PILOT_ALLOWLIST_QUAL_NAME as vision_annotation_whitelist\nfrom vision_annotation_task.pilot_config import PILOT_BLOCK_QUAL_NAME as vision_annotation_blacklist\n\nqual_dict = {\"interaction\": {\n \"allow\": interaction_whitelist, \n \"block\": interaction_blacklist }, \n \"vision_annotation\": {\n \"allow\": vision_annotation_whitelist, \n \"block\": vision_annotation_blacklist } }\n\ndb = LocalMephistoDB()\nmephisto_data_browser = MephistoDataBrowser(db=db)\n\ns3 = boto3.client('s3')\n\nlogging.basicConfig(level=\"INFO\")\n\n\ndef import_s3_lists(bucket: str):\n # Assumed S3 allowlist key example: (bucket)/interaction/allow.txt\n \n output_dict = copy.deepcopy(qual_dict)\n \n for task in output_dict.keys():\n for list_type in output_dict[task].keys():\n key = f\"{task}/{list_type}.txt\"\n try:\n with open('list.txt', 'wb') as f:\n s3.download_fileobj(bucket, key, f)\n logging.info(f\"{task} {list_type}list downloaded successfully\")\n with open('list.txt', 'r') as f:\n output_dict[task][list_type] = [line.strip() for line in f.readlines()]\n except:\n logging.info(f\"{task} {list_type}list not found on S3, creating new S3 {list_type}list\")\n output_dict[task][list_type] = []\n\n os.remove(\"list.txt\")\n return output_dict\n\n\ndef add_workers_to_quals(add_list: list, qual: str):\n\n for turker in add_list:\n #First add the worker to the database, or retrieve them if they already exist\n try:\n db_id = db.new_worker(turker, 'mturk')\n worker = Worker.get(db, db_id)\n except:\n worker = db.find_workers(turker, 'mturk')[0]\n \n # Add the worker to the relevant list\n try:\n db.make_qualification(qual)\n except:\n pass\n else:\n logging.debug(f\"{qual} qualification not exists, so create one\")\n worker.grant_qualification(qual, 1)\n\n #Check to make sure the qualification was added successfully\n if not worker.is_qualified(qual):\n logging.info(f\"!!! {worker} not successfully qualified, debug\")\n else:\n logging.info(f\"Worker {worker.worker_name} added to list {qual}\")\n\n\ndef pull_local_lists():\n # Pull the qual lists from local Mephisto DB into a formatted dict\n\n output_dict = copy.deepcopy(qual_dict)\n\n logging.info(f\"Retrieving qualification lists from local Mephisto DB\")\n for task in output_dict.keys():\n for list_type in output_dict[task].keys():\n # If syncing for the first time, qualifications may not yet exist\n try:\n logging.info(f'attempting to make qualification: {qual_dict[task][list_type]}')\n db.make_qualification(qual_dict[task][list_type])\n except:\n logging.info(f'Qualification {qual_dict[task][list_type]} already exists')\n pass\n qual_list = mephisto_data_browser.get_workers_with_qualification(qual_dict[task][list_type])\n output_dict[task][list_type] = [worker.worker_name.strip(\"\\n\") for worker in qual_list]\n\n return output_dict\n\n\ndef compare_qual_lists(s3_lists: dict, local_lists: dict):\n # Compare two dicts of lists representing the local and S3 states, return a dict with the differences\n\n diff_dict = copy.deepcopy(qual_dict)\n\n logging.info(f\"Comparing qualification lists and checking for differences\")\n for t in diff_dict.keys():\n for l in diff_dict[t].keys():\n diff_dict[t][l] = {}\n diff_dict[t][l][\"s3_exclusive\"] = [x for x in s3_lists[t][l] if x not in local_lists[t][l]]\n diff_dict[t][l][\"local_exclusive\"] = [x for x in local_lists[t][l] if x not in s3_lists[t][l]]\n\n return diff_dict\n\n\ndef update_lists(bucket:str, diff_dict: dict):\n # Iterate through the differences between local and S3 lists and update both to be in sync\n\n for t in diff_dict.keys():\n for l in diff_dict[t].keys():\n for e in diff_dict[t][l].keys():\n\n if e == \"s3_exclusive\" and len(diff_dict[t][l][e]) > 0:\n add_workers_to_quals(diff_dict[t][l][e], qual_dict[t][l])\n\n elif e == \"local_exclusive\" and len(diff_dict[t][l][e]) > 0:\n logging.info(f\"Writing new workers to {t} {l} shared list on S3: {diff_dict[t][l][e]}\")\n\n filename = l + \".txt\"\n with open(filename, \"w\") as f:\n for line in diff_dict[t][l][e]:\n f.write(line.strip('\\n') + '\\n')\n \n upload_key = t + \"/\" + filename\n s3.upload_file(filename, bucket, upload_key)\n logging.info(f\"S3 upload succeeded\")\n \n os.remove(filename)\n\n else:\n logging.info(f\"No {e} workers on {t} {l} list, no update performed\")\n\n return\n\n\ndef main(bucket: str):\n # Pull shared lists from S3 and local qual lists\n s3_list_dict = import_s3_lists(bucket)\n local_list_dict = pull_local_lists()\n\n # Compare them for differences\n diff_dict = compare_qual_lists(s3_list_dict, local_list_dict)\n \n # Update local and s3 lists to match\n update_lists(bucket, diff_dict)\n\n return\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--s3_bucket\", type=str, help=\"S3 bucket where allowlists are stored\")\n opts = parser.parse_args()\n main(opts.s3_bucket)",
"id": "11924951",
"language": "Python",
"matching_score": 1.008400559425354,
"max_stars_count": 0,
"path": "droidlet/tools/crowdsourcing/sync_whitelists.py"
}
] | 1.090658 |
Pendar2 | [
{
"content": "from .tensorboard_cb import *\r\nfrom .version import __version__",
"id": "4645451",
"language": "Python",
"matching_score": 0,
"max_stars_count": 23,
"path": "fastai_tensorboard_callback/__init__.py"
},
{
"content": "from tensorboardX import SummaryWriter\nfrom fastai.basics import *\n\n@dataclass\nclass TensorboardLogger(Callback):\n learn:Learner\n run_name:str\n histogram_freq:int=100\n path:str=None\n def __post_init__(self):\n self.path = self.path or os.path.join(self.learn.path, \"logs\")\n self.log_dir = os.path.join(self.path, self.run_name)\n def on_train_begin(self, **kwargs):\n self.writer = SummaryWriter(log_dir=self.log_dir)\n def on_epoch_end(self, **kwargs):\n iteration = kwargs[\"iteration\"]\n metrics = kwargs[\"last_metrics\"]\n metrics_names = [\"valid_loss\"] + [o.__name__ for o in self.learn.metrics]\n \n for val, name in zip(metrics, metrics_names):\n self.writer.add_scalar(name, val, iteration)\n \n for name, emb in self.learn.model.named_children():\n if isinstance(emb, nn.Embedding):\n self.writer.add_embedding(list(emb.parameters())[0], global_step=iteration, tag=name)\n \n def on_batch_end(self, **kwargs):\n iteration = kwargs[\"iteration\"]\n loss = kwargs[\"last_loss\"]\n \n self.writer.add_scalar(\"learning_rate\", self.learn.opt.lr, iteration)\n self.writer.add_scalar(\"momentum\", self.learn.opt.mom, iteration)\n \n self.writer.add_scalar(\"loss\", loss, iteration)\n if iteration%self.histogram_freq==0:\n for name, param in self.learn.model.named_parameters():\n self.writer.add_histogram(name, param, iteration)\n def on_train_end(self, **kwargs):\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n dummy_input = next(iter(self.learn.data.train_dl))[0]\n self.writer.add_graph(self.learn.model, tuple(dummy_input))\n except Exception as e:\n print(\"Unable to create graph.\")\n print(e)\n self.writer.close()",
"id": "6010134",
"language": "Python",
"matching_score": 0,
"max_stars_count": 23,
"path": "fastai_tensorboard_callback/tensorboard_cb.py"
}
] | 0 |
00-MSME | [
{
"content": "from wtforms.validators import DataRequired, Optional, Length\nfrom wtforms import Form, BooleanField, StringField, PasswordField, validators, SelectMultipleField, IntegerField, FileField, HiddenField, TextAreaField\nfrom wtforms.widgets import TextArea\n\nclass PersonForm(Form):\n\n name = StringField('NAME', validators=[DataRequired()])\n email = StringField('EMAIL', validators=[DataRequired(), validators.Email()])\n\n\nclass EntityForm(Form):\n\n name = StringField('NAME', validators=[DataRequired()])\n description = TextAreaField('DESCRIPTION', [validators.optional(), validators.length(max=1024)])\n serial = StringField('SERIAL')\n configs = SelectMultipleField('CONFIG FILES')\n\n\nclass ConfigForm(Form):\n\n name = StringField('NAME', validators=[DataRequired()])\n path = StringField('PATH /etc/opt/augment00/', validators=[DataRequired()])\n file_text = HiddenField('TEXT', [DataRequired()])\n\n\nclass CommandForm(Form):\n\n command_text = HiddenField('TEXT', [DataRequired()])\n\n",
"id": "10865281",
"language": "Python",
"matching_score": 2.1733505725860596,
"max_stars_count": 1,
"path": "src/forms.py"
},
{
"content": "import logging\nimport json\n\n\nfrom google.appengine.api import users\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import ndb\n\n\nfrom flask import Flask, request, redirect, flash\n\nfrom constants import *\n\napp = Flask(__name__)\n\napp.secret_key = FLASK_SECRET_KEY\n\nfrom models import Person, Entity, ConfigFile\nfrom forms import PersonForm, EntityForm, ConfigForm, CommandForm\nfrom shared import render_login_template, with_person\nfrom augment_exceptions import NonUniqueException\nfrom utilities import firebase\n\n\[email protected]('/person/new', methods=[\"POST\", \"GET\"])\ndef new_person():\n google_user = users.get_current_user()\n if google_user is not None:\n google_id = google_user.user_id()\n existing_user = Person.with_google_id(google_id)\n if existing_user is None:\n form = PersonForm(request.form)\n if request.method == 'POST':\n email = form.email.data\n name = form.name.data\n try:\n Person.create(name, email, google_id)\n flash(\"New account created.\", \"success\")\n return redirect(\"/\")\n except NonUniqueException as e:\n flash(\"Failed to create new account. %s\" % e.message, \"warning\")\n return redirect(\"/\")\n else:\n return render_login_template(\"account-form.html\", form=form)\n else:\n flash(\"Welcome back\", \"info\")\n return redirect(\"/\")\n else:\n return redirect(\"/\")\n\n\n\[email protected]('/person/update', methods=[\"POST\", \"GET\"])\n@with_person\ndef update_person(person=None):\n\n form = PersonForm(request.form, name=person.name, email=person.email)\n if request.method == 'POST':\n email = form.email.data\n name = form.name.data\n try:\n person.name = name\n person.email = email\n\n return redirect(\"/person/account\")\n except NonUniqueException as e:\n flash(\"We couldn't update your account account. %s\" % e.message, \"warning\")\n redirect(\"/person/new\")\n else:\n return render_login_template(\"account-form.html\", form=form)\n\n\[email protected]('/person/regenerate-apikey', methods=[\"POST\"])\n@with_person\ndef regenerate_api_key(person=None):\n person.reset_api_key()\n flash(\"Your API Key has been regenerated\", \"info\")\n return redirect(\"/\")\n\n\[email protected]('/person/delete', methods=[\"POST\"])\n@with_person\ndef delete_person(person=None):\n person.remove()\n return redirect(\"/\")\n\n\n## CRUD for entities\n\[email protected]('/entity/new', methods=[\"POST\", \"GET\"])\n@with_person\ndef new_entity(person=None):\n form = EntityForm(request.form)\n\n form.configs.choices = [(c.key, c.name) for c in person.configs]\n\n if request.method == 'POST':\n\n entity = person.add_new_entity(name=form.name.data,\n description=form.description.data,\n config = [ndb.Key(\"ConfigFile\", k, parent=person.key) for k in form.configs.data if ndb.Key(\"ConfigFile\", k, parent=person.key) is not None]\n )\n\n entity_uuid = entity.key.id()\n flash(\"Your new entity has been created\", \"info\")\n return redirect(\"/entity/%s\" % entity_uuid)\n else:\n return render_login_template(\"entity-form.html\", form=form)\n\n\ndef _allowed_entity(entity_uuid, person):\n\n entity = Entity.get_by_id(entity_uuid)\n if entity is None:\n flash(\"We couldn't find this entity\", \"warning\")\n return None, redirect(\"/\")\n else:\n if entity.person_key == person.key:\n return entity, None\n else:\n flash(\"You can only see your own entities\", \"info\")\n return None, redirect(\"/\")\n\n\n\[email protected]('/entity/<entity_uuid>', methods=[\"GET\"])\n@with_person\ndef entity(entity_uuid, person=None):\n\n entity, rsp = _allowed_entity(entity_uuid, person)\n if entity is None:\n return rsp\n\n creds_json = {\n \"entity_uuid\": entity_uuid,\n \"private_key\": entity.private_key,\n \"public_key\": entity.public_key,\n \"url\": \"%s/api/config/%s\" % (URL_BASE, entity_uuid)\n }\n\n creds = json.dumps(creds_json, indent=4)\n tag = entity_uuid[:8]\n\n return render_login_template(\"entity.html\", entity=entity, person=person, creds=creds, tag=tag)\n\n\n\[email protected]('/entity/<entity_uuid>/update', methods=[\"POST\", \"GET\"])\n@with_person\ndef update_entity(entity_uuid, person=None):\n\n entity, rsp = _allowed_entity(entity_uuid, person)\n if entity is None:\n return rsp\n\n form = EntityForm(request.form,\n name=entity.name,\n description=entity.description,\n serial=entity.serial\n )\n\n form.configs.choices = [(c.key.id(), c.name) for c in person.configs]\n\n if request.method == 'POST':\n entity.config = [ndb.Key(\"ConfigFile\", k, parent=person.key) for k in form.configs.data if ndb.Key(\"ConfigFile\", k, parent=person.key) is not None]\n entity.name = form.name.data\n entity.serial = None if not form.serial.data else form.serial.data\n entity.description = form.description.data\n entity.put()\n\n return redirect(\"/entity/%s\" % entity_uuid)\n else:\n return render_login_template(\"entity-form.html\", form=form)\n\n\[email protected]('/entity/<entity_uuid>/delete', methods=[\"POST\"])\n@with_person\ndef delete_entity(entity_uuid, person=None):\n\n entity, rsp = _allowed_entity(entity_uuid, person)\n if entity is None:\n return rsp\n\n entity.key.delete()\n return redirect(\"/\")\n\n\[email protected]('/entity/<entity_uuid>/regenerate', methods=[\"POST\"])\n@with_person\ndef regenerate(entity_uuid, person=None):\n\n entity, rsp = _allowed_entity(entity_uuid, person)\n if entity is None:\n return rsp\n\n private_key = entity.regenerate_keys()\n # aiven.add_influx_password(entity)\n memcache.add(entity_uuid, private_key, time=5, namespace=\"private\")\n flash(\"Take a copy of the credentials below as you won't see them again\", \"info\")\n return redirect(\"/entity/%s\" % entity_uuid)\n\n\[email protected]('/entity/<entity_uuid>/command', methods=[\"GET\", \"POST\"])\n@with_person\ndef command(entity_uuid, person=None):\n\n entity, rsp = _allowed_entity(entity_uuid, person)\n if entity is None:\n return rsp\n\n form = CommandForm(request.form)\n\n if request.method == 'POST':\n\n command = form.command_text.data\n try:\n as_json = json.loads(command)\n except Exception as e:\n flash(\"Your command wasn't valid json\", \"error\")\n return render_login_template(\"command-form.html\", form=form, entity=entity)\n\n firebase_service = firebase.get_service()\n firebase_service.send_message(entity_uuid, command_json=as_json)\n\n flash(\"Your command has been sent\", \"info\")\n return redirect(\"/entity/%s\" % entity_uuid)\n\n else:\n return render_login_template(\"command-form.html\", form=form, entity=entity)\n\n\n## CRUD for config\n\n\ndef _allowed_config(config_uuid, person):\n config_file = ConfigFile.get_by_id(config_uuid, parent=person.key)\n if config_file is None:\n flash(\"We couldn't find this config file\", \"warning\")\n return None, redirect(\"/\")\n else:\n if config_file.key.parent() == person.key:\n return config_file, None\n else:\n flash(\"You can only see your own config files\", \"warning\")\n return redirect(\"/\")\n\n\[email protected]('/config/<config_uuid>', methods=[\"POST\", \"GET\"])\n@with_person\ndef config(config_uuid, person=None):\n\n config_file, rsp = _allowed_config(config_uuid, person)\n if config_file is None:\n return rsp\n\n return render_login_template(\"config-file.html\", config=config_file, person=person)\n\n\[email protected]('/config/<config_uuid>/update', methods=[\"POST\", \"GET\"])\n@with_person\ndef update_config(config_uuid, person=None):\n\n config_file, rsp = _allowed_config(config_uuid, person)\n if config_file is None:\n return rsp\n\n form = ConfigForm(request.form,\n name=config_file.name,\n path=config_file.path,\n file_text=config_file.text\n )\n\n if request.method == 'POST':\n config_file.name = form.name.data\n config_file.path = form.path.data\n config_file.text = form.file_text.data\n config_file.put()\n\n return redirect(\"/config/%s\" % config_uuid)\n else:\n return render_login_template(\"config-form.html\", form=form, config=config_file)\n\n\[email protected]('/config/<config_uuid>/delete', methods=[\"POST\"])\n@with_person\ndef delete_config(config_uuid, person=None):\n\n config_file, rsp = _allowed_config(config_uuid, person)\n if config_file is None:\n return rsp\n\n config_file.key.delete()\n return redirect(\"/\")\n\n\[email protected]('/config/new', methods=[\"POST\", \"GET\"])\n@with_person\ndef new_config(person=None):\n\n form = ConfigForm(request.form)\n\n if request.method == 'POST':\n config = person.add_config_file(form.name.data,\n form.file_text.data,\n form.path.data\n )\n config_uuid = config.key.id()\n return redirect(\"/config/%s\" % config_uuid)\n else:\n return render_login_template(\"config-form.html\", form=form)\n\n\[email protected](500)\ndef server_error(e):\n # Log the error and stacktrace.\n logging.exception('An error occurred during a request.')\n return 'An internal error occurred.', 500\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"id": "8787505",
"language": "Python",
"matching_score": 3.4467201232910156,
"max_stars_count": 1,
"path": "src/account.py"
},
{
"content": "from config_local import ( FLASK_SECRET_KEY,\n FIREBASE_URL)\n\nURL_BASE = \"http://augment00.org\"\n\n",
"id": "826111",
"language": "Python",
"matching_score": 0.1485789716243744,
"max_stars_count": 1,
"path": "src/constants.py"
},
{
"content": "import logging\nimport json\nfrom functools import wraps\n\nfrom google.appengine.ext import ndb\n\nfrom flask import Flask, request\napp = Flask(__name__)\n\nfrom models import Entity, Person\nfrom utilities import firebase, keys\n\nfrom constants import *\n\n\ndef is_signed(func):\n @wraps(func)\n def decorated_view(*args, **kwargs):\n path = request.path\n print path\n sig = request.values.get(\"sig\")\n if sig is None:\n print \"no sig\"\n return (\"Permission denied\", 401, {})\n parts = path.split(\"/\")\n entity_uuid = parts[-2]\n key = ndb.Key(\"Entity\", entity_uuid)\n entity = key.get()\n if entity is None:\n return (\"Not found\", 403, {})\n ok = keys.verify_sig(path, sig, entity.public_key)\n if not ok:\n print \"not ok\"\n return (\"Permission denied\", 401, {})\n return func(*args, entity=entity, **kwargs)\n return decorated_view\n\n\ndef with_api_key(func):\n @wraps(func)\n def decorated_view(*args, **kwargs):\n as_json = request.get_json(force=True)\n if as_json is None:\n print \"no json\"\n return (\"Permission denied, no json data\", 401, {})\n google_id = as_json.get(\"user_id\")\n api_key = as_json.get(\"api_key\")\n if google_id is None or api_key is None:\n return (\"Permission denied\", 401, {})\n\n person = Person.with_google_id(google_id)\n if person is None:\n return (\"Permission denied\", 401, {})\n\n if person.api_key != api_key:\n return (\"Permission denied\", 401, {})\n\n return func(*args, person=person, **kwargs)\n return decorated_view\n\n\[email protected]('/api/config/<entity_uuid>/<nonce>', methods=[\"GET\"])\n@is_signed\ndef api_config(entity_uuid, nonce, entity=None):\n\n serial = request.values.get(\"serial\")\n if entity.serial is not None and serial != entity.serial:\n return (\"Conflict - Serial doesn't match\", 409, {})\n else:\n if entity.serial is None:\n entity.serial = serial\n entity.put()\n\n return json.dumps(entity.as_json())\n\n\[email protected]('/api/firebase-token/<entity_uuid>/<nonce>', methods=[\"GET\"])\n@is_signed\ndef api_token(entity_uuid, nonce, entity=None):\n\n data = {\n \"entity_uuid\": entity_uuid,\n \"firebase_custom_token\": firebase.create_custom_token(entity_uuid)\n }\n\n return json.dumps(data)\n\n\[email protected]('/api/schema/<entity_uuid>', methods=[\"POST\"])\ndef set_entity_schema(entity_uuid):\n key = ndb.Key(\"Entity\", entity_uuid)\n entity = key.get()\n if entity is None:\n return \"not found\", 403\n else:\n as_json = request.get_json(force=True)\n entity.schema = as_json\n entity.put()\n return \"ok\", 200\n\n\n############################################################\n\n\n\[email protected]('/api/new-entity', methods=[\"POST\"])\n@with_api_key\ndef new_entity(person=None):\n as_json = request.get_json(force=True)\n entity = Entity.create(person.key, name=as_json[\"name\"])\n entity_uuid = entity.key.id()\n return entity_uuid, 201\n\n\[email protected]('/api/entity/<entity_uuid>', methods=[\"GET\"])\n@with_api_key\ndef get_entity_info(entity_uuid, person=None):\n\n key = ndb.Key(\"Entity\", entity_uuid)\n entity = key.get()\n\n if entity is None:\n return \"not found\", 403\n\n if entity.person_key != person.key:\n return (\"Permission denied\", 401, {})\n\n return json.dumps(entity.as_json()), 200\n\n\[email protected]('/api/entity/<entity_uuid>/add-value', methods=[\"POST\"])\n@with_api_key\ndef add_value(entity_uuid, person=None):\n\n key = ndb.Key(\"Entity\", entity_uuid)\n entity = key.get()\n\n if entity.person_key != person.key:\n return (\"Permission denied\", 401, {})\n\n as_json = request.get_json(force=True)\n\n value_name = as_json[\"name\"]\n value = as_json[\"value\"]\n\n if value_name == \"name\":\n entity.name = value\n else:\n entity.template_values[value_name] = value\n\n entity.put()\n return \"ok\", 200\n\n\[email protected]('/api/entity/<entity_uuid>/send-command', methods=[\"POST\"])\n@with_api_key\ndef send_command(entity_uuid, person=None):\n\n key = ndb.Key(\"Entity\", entity_uuid)\n entity = key.get()\n\n if entity.person_key != person.key:\n return (\"Permission denied\", 401, {})\n\n as_json = request.get_json(force=True)\n\n if not frozenset(as_json[\"rpc\"].keys()) == {\"method\", \"params\"}:\n\n return (\"Malformed request\", 400, {})\n\n firebase_service = firebase.get_service()\n firebase_service.send_message(entity_uuid, command_json=as_json[\"rpc\"])\n\n return \"ok\", 200\n\n\[email protected](500)\ndef server_error(e):\n # Log the error and stacktrace.\n logging.exception('An error occurred during a request.')\n return 'An internal error occurred.', 500",
"id": "7825347",
"language": "Python",
"matching_score": 3.859786033630371,
"max_stars_count": 1,
"path": "src/api.py"
},
{
"content": "import random\nimport uuid\nfrom Crypto.PublicKey import RSA\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import users\nfrom base64 import b64encode, b64decode\nfrom jinja2 import Template\n\nfrom utilities import firebase, keys\n\nfrom augment_exceptions import NonUniqueException\nfrom constants import *\n\n\nALPHA_NUMERIC = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\ndef generateNewRandomAlphaNumeric(length):\n random.seed()\n values = []\n for i in range(length):\n values.append(random.choice(ALPHA_NUMERIC))\n return \"\".join(values)\n\n\nclass Name(ndb.Model):\n pass\n\n\nclass Email(ndb.Model):\n pass\n\n\nclass GoogleId(ndb.Model):\n pass\n\n\nclass Person(ndb.Model):\n name_key = ndb.KeyProperty(kind=\"Name\", required=True)\n email_key = ndb.KeyProperty(kind=\"Email\", required=True)\n google_id_key = ndb.KeyProperty(kind=\"GoogleId\")\n api_key = ndb.StringProperty()\n\n\n @classmethod\n def create(cls, name, email, google_id):\n name_key = cls._new_unique_key(Name, name)\n email_key = cls._new_unique_key(Email, email)\n google_id_key = cls._new_unique_key(GoogleId, google_id)\n person_uuid = str(uuid.uuid4())\n api_key = generateNewRandomAlphaNumeric(30)\n person = cls(name_key=name_key,\n email_key=email_key,\n google_id_key=google_id_key,\n id=person_uuid,\n api_key=api_key)\n person.put()\n return person\n\n def get_name(self):\n return self.name_key.id()\n\n def set_name(self, new_name):\n self._set_unique_attribute(Name, \"name_key\", new_name)\n\n def get_email(self):\n return self.email_key.id()\n\n def set_email(self, new_email):\n self._set_unique_attribute(Email, \"email_key\", new_email)\n\n def get_google_id(self):\n return self.google_id_key.id()\n\n @classmethod\n def with_email(cls, email):\n key = ndb.Key(Email, email)\n return cls.query(cls.email_key == key).get()\n\n @classmethod\n def with_name(cls, name):\n key = ndb.Key(Name, name)\n return cls.query(cls.name_key == key).get()\n\n @classmethod\n def with_google_id(cls, google_id):\n key = ndb.Key(GoogleId, google_id)\n return cls.query(cls.google_id_key == key).get()\n\n @staticmethod\n def _new_unique_key(attribute_class, new_value):\n\n new_attribute_key = ndb.Key(attribute_class, new_value)\n existing_attribute_obj = new_attribute_key.get()\n\n if existing_attribute_obj is not None:\n raise NonUniqueException(\"The value %s for %s is adready in use\" % (new_value, attribute_class))\n else:\n new_attribute_obj = attribute_class(key=new_attribute_key)\n new_attribute_obj.put()\n\n return new_attribute_key\n\n\n @ndb.transactional(xg=True)\n def _set_unique_attribute(self, attribute_class, attribute_key_name, new_value):\n\n current_attribute_key = getattr(self, attribute_key_name)\n current_value = current_attribute_key.id()\n\n if current_value == new_value:\n return\n\n new_attribute_key = self._new_unique_key(attribute_class, new_value)\n current_attribute_key.delete()\n setattr(self, attribute_key_name, new_attribute_key)\n self.put()\n\n\n def add_new_entity(self, **kwargs):\n return Entity.create(self.key, **kwargs)\n\n\n @property\n def entities(self):\n return [e for e in Entity.query(Entity.person_key == self.key).iter()]\n\n @property\n def configs(self):\n return [c for c in ConfigFile.query(ancestor=self.key).iter()]\n\n\n def remove(self):\n ndb.delete_multi(ConfigFile.query(ancestor=self.key).iter(keys_only=True))\n ndb.delete_multi(Entity.query(Entity.person_key == self.key).iter(keys_only=True))\n self.name_key.delete()\n self.email_key.delete()\n self.google_id_key.delete()\n self.key.delete()\n\n\n def reset_api_key(self):\n\n self.api_key = generateNewRandomAlphaNumeric(30)\n self.put()\n\n\n\n def add_config_file(self, name, text, path):\n\n config_uuid = str(uuid.uuid4())\n\n config_file = ConfigFile(id=config_uuid,\n parent=self.key,\n name=name,\n text=text,\n path=path)\n config_file.put()\n return config_file\n\n\n name = property(get_name, set_name)\n email = property(get_email, set_email)\n google_id = property(get_google_id)\n\n\nclass ConfigFile(ndb.Model):\n\n name = ndb.StringProperty()\n text = ndb.TextProperty()\n path = ndb.StringProperty()\n\n def as_json(self, entity):\n\n entity_uuid = entity.key.id()\n template_values = entity.template_values\n\n template = Template(self.text)\n\n return {\n \"text\": template.render(uuid=entity_uuid, **template_values),\n \"path\": self.path\n }\n\n\nclass Entity(ndb.Model):\n\n name = ndb.StringProperty()\n description = ndb.TextProperty()\n created = ndb.DateTimeProperty(auto_now_add=True)\n person_key = ndb.KeyProperty(kind=\"Person\", required=True)\n public_key = ndb.TextProperty()\n private_key = ndb.TextProperty()\n serial = ndb.StringProperty()\n config = ndb.KeyProperty(ConfigFile, repeated=True)\n template_values = ndb.JsonProperty(default={})\n schema = ndb.JsonProperty(default={})\n\n\n def as_json(self):\n\n entity_uuid = self.key.id()\n\n return {\n \"name\": self.name,\n \"description\": self.description,\n \"created\": str(self.created),\n \"person_key\": self.person_key.id(),\n \"public_key\": self.public_key,\n \"config\": [c.get().as_json(self) for c in self.config]\n }\n\n\n @property\n def config_files(self):\n configs = [c.get() for c in self.config]\n return configs\n\n def add_config_file(self, config_file):\n key = config_file.key\n if not key in self.config:\n self.config.append(key)\n self.put()\n\n\n def remove_config_file(self, config_file):\n key = config_file.key\n if key in self.config:\n self.config.remove(key)\n self.put()\n\n\n def regenerate_keys(self):\n public, private = keys.newkeys(2048)\n self.private_key = private.exportKey('PEM')\n self.public_key = public.exportKey('PEM')\n self.put()\n\n return self.private_key\n\n\n @classmethod\n def create(cls, person_key, **kwargs):\n\n public, private = keys.newkeys(2048)\n private_key = private.exportKey('PEM')\n public_key = public.exportKey('PEM')\n entity_uuid = str(uuid.uuid4())\n\n entity = cls(id=entity_uuid,\n person_key=person_key,\n public_key=public_key,\n private_key=private_key,\n **kwargs)\n entity.put()\n\n return entity\n\n\n\n\n\n\n\n\n",
"id": "11218136",
"language": "Python",
"matching_score": 3.1314334869384766,
"max_stars_count": 1,
"path": "src/models.py"
},
{
"content": "\n\nclass NonUniqueException(Exception):\n pass",
"id": "1196314",
"language": "Python",
"matching_score": 0.013430426828563213,
"max_stars_count": 1,
"path": "src/augment_exceptions.py"
},
{
"content": "import json\nimport base64\nimport time\nimport datetime\nimport httplib2\n\nfrom google.appengine.api import app_identity\nfrom mode import *\n\n\ndef get_service():\n\n mode = application_mode()\n if mode == APPLICATION_MODE_PRODUCTION:\n firebase_service = FirebaseService()\n elif mode == APPLICATION_MODE_TEST:\n print \"Using dummy firebase service\"\n firebase_service = DummyFirebaseService()\n else:\n print \"Using dummy firebase service\"\n firebase_service = DummyFirebaseService()\n\n return firebase_service\n\n\nfrom constants import FIREBASE_URL\n\n_FIREBASE_SCOPES = [\n 'https://www.googleapis.com/auth/firebase.database',\n 'https://www.googleapis.com/auth/userinfo.email']\n\n_IDENTITY_ENDPOINT = ('https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit')\n\n\ndef create_custom_token(uid, valid_minutes=60):\n \"\"\"Create a secure token for the given id.\n\n This method is used to create secure custom JWT tokens to be passed to\n clients. It takes a unique id (uid) that will be used by Firebase's\n security rules to prevent unauthorized access. In this case, the uid will\n be the channel id which is a combination of user_id and game_key\n \"\"\"\n\n # use the app_identity service from google.appengine.api to get the\n # project's service account email automatically\n client_email = app_identity.get_service_account_name()\n\n # print \"client_email: \", client_email\n\n now = int(time.time())\n # encode the required claims\n # per https://firebase.google.com/docs/auth/server/create-custom-tokens\n payload = base64.b64encode(json.dumps({\n 'iss': client_email,\n 'sub': client_email,\n 'aud': _IDENTITY_ENDPOINT,\n 'uid': uid, # the important parameter, as it will be the channel id\n 'iat': now,\n 'exp': now + (valid_minutes * 60),\n }))\n # add standard header to identify this as a JWT\n header = base64.b64encode(json.dumps({'typ': 'JWT', 'alg': 'RS256'}))\n to_sign = '{}.{}'.format(header, payload)\n # Sign the jwt using the built in app_identity service\n return '{}.{}'.format(to_sign, base64.b64encode(app_identity.sign_blob(to_sign)[1]))\n\n\n\nclass DummyFirebaseService(object):\n\n def send_message(self, u_id, command_json=None):\n\n return None\n\n\nclass FirebaseService(object):\n\n\n def _get_http(self):\n from oauth2client.client import GoogleCredentials\n # from oauth2client.client import GoogleCredentials\n \"\"\"Provides an authed http object.\"\"\"\n http = httplib2.Http()\n # Use application default credentials to make the Firebase calls\n # https://firebase.google.com/docs/reference/rest/database/user-auth\n creds = GoogleCredentials.get_application_default().create_scoped(_FIREBASE_SCOPES)\n creds.authorize(http)\n return http\n\n\n\n def firebase_put(self, path, value=None):\n \"\"\"Writes data to Firebase.\n\n An HTTP PUT writes an entire object at the given database path. Updates to\n fields cannot be performed without overwriting the entire object\n\n Args:\n path - the url to the Firebase object to write.\n value - a json string.\n \"\"\"\n response, content = self._get_http().request(path, method='PUT', body=value)\n return json.loads(content)\n\n\n\n def send_message(self, u_id, command_json=None):\n\n url = '{}/channels/{}.json'.format(FIREBASE_URL, u_id)\n\n dt = datetime.datetime.now()\n ts = dt.strftime(\"%Y%m%d-%H%M%S-%f\")\n message_json = {\n ts: command_json\n }\n\n message = json.dumps(message_json, indent=4)\n\n if message:\n return self._get_http().request(url, 'PATCH', body=message)\n else:\n return self._get_http().request(url, 'DELETE')",
"id": "4039171",
"language": "Python",
"matching_score": 2.1790411472320557,
"max_stars_count": 1,
"path": "src/utilities/firebase.py"
},
{
"content": "import os\n\nAPPLICATION_MODE_TEST = \"test\"\nAPPLICATION_MODE_DEVELOPMENT = \"development\"\nAPPLICATION_MODE_PRODUCTION = \"production\"\n\nAPPLICATION_MODE = None\n\ndef application_mode():\n\n global APPLICATION_MODE\n\n if APPLICATION_MODE is None:\n\n server_software = os.environ.get(\"SERVER_SOFTWARE\")\n\n if server_software is None:\n APPLICATION_MODE = APPLICATION_MODE_PRODUCTION\n elif server_software.startswith(\"Development\"):\n APPLICATION_MODE = APPLICATION_MODE_DEVELOPMENT\n else:\n APPLICATION_MODE = APPLICATION_MODE_PRODUCTION\n\n print \"mode: \", APPLICATION_MODE\n return APPLICATION_MODE",
"id": "11887259",
"language": "Python",
"matching_score": 0.043692100793123245,
"max_stars_count": 1,
"path": "src/utilities/mode.py"
},
{
"content": "import unittest\nimport json\n\n# from google.appengine.api import memcache\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext import testbed\n\nfrom models import Person, Entity, Name\nfrom utilities.firebase import create_custom_token\nimport utilities.keys as keys\n\n\nclass ModelsTestCase(unittest.TestCase):\n\n def setUp(self):\n # First, create an instance of the Testbed class.\n self.testbed = testbed.Testbed()\n # Then activate the testbed, which prepares the service stubs for use.\n self.testbed.activate()\n\n self.policy = testbed.datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)\n # Next, declare which service stubs you want to use.\n self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)\n self.testbed.init_memcache_stub()\n # Clear ndb's in-context cache between tests.\n # This prevents data from leaking between tests.\n # Alternatively, you could disable caching by\n # using ndb.get_context().set_cache_policy(False)\n ndb.get_context().clear_cache()\n\n\n def tearDown(self):\n self.testbed.deactivate()\n\n\n def testAddPerson(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n self.assertIsNotNone(person)\n key = person.key\n got = key.get()\n self.assertIsNotNone(got)\n\n\n def testAddPersonWithSameName(self):\n\n Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n self.assertRaises(Exception, Person.create, \"paul\", \"<EMAIL>\", \"1234567890\")\n\n\n def testChangeName(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n # self.assertEqual(1, len(Name.query().fetch(2)))\n self.assertEqual(person.name, \"paul\")\n person.name = \"sol\"\n self.assertEqual(person.name, \"sol\")\n\n name_key = ndb.Key(Name, \"sol\")\n existing_name = name_key.get()\n self.assertIsNotNone(existing_name)\n\n\n def testChangeNameFail(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n person2 = Person.create(\"sol\", \"<EMAIL>\", \"987654321\")\n # self.assertEqual(1, len(Name.query().fetch(2)))\n self.assertEqual(person.name, \"paul\")\n self.assertEqual(person2.name, \"sol\")\n\n self.assertRaises(Exception, person.set_name, \"sol\")\n\n\nclass ModelsTestCaseWithoutConsistancy(unittest.TestCase):\n\n def setUp(self):\n # First, create an instance of the Testbed class.\n self.testbed = testbed.Testbed()\n # Then activate the testbed, which prepares the service stubs for use.\n self.testbed.activate()\n\n # self.policy = testbed.datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)\n # Next, declare which service stubs you want to use.\n self.testbed.init_datastore_v3_stub()\n self.testbed.init_memcache_stub()\n self.testbed.init_app_identity_stub()\n # Clear ndb's in-context cache between tests.\n # This prevents data from leaking between tests.\n # Alternatively, you could disable caching by\n # using ndb.get_context().set_cache_policy(False)\n ndb.get_context().clear_cache()\n\n\n def tearDown(self):\n self.testbed.deactivate()\n\n\n def testFindByEmail(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n found = Person.with_email(\"<EMAIL>\")\n self.assertEqual(found.name, \"paul\")\n\n\n def testFindByName(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n found = Person.with_name(\"paul\")\n self.assertEqual(found.name, \"paul\")\n\n\n def testFindByGoogleId(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n found = Person.with_google_id(\"123456789\")\n self.assertEqual(found.name, \"paul\")\n\n\n def testFindByGoogleIdNotExisting(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n found = Person.with_google_id(\"asdfghjk\")\n self.assertTrue(found is None)\n\n\n def testAddNewEntity(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n\n\n def testpersonEntities(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n entities = person.entities\n self.assertTrue(len(entities) == 1)\n\n\n def testAddConfigFile(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n\n config_file = person.add_config_file(\"test\", \"a whole bunch of text\", \"a/path/file.txt\")\n\n entity.add_config_file(config_file)\n self.assertTrue(len(entity.config) == 1)\n self.assertEqual(entity.config[0].get().text, \"a whole bunch of text\")\n entity.add_config_file(config_file)\n self.assertTrue(len(entity.config) == 1)\n\n config_file_2 = person.add_config_file(\"test2\", \"another a whole bunch of text\", \"a/path/file.txt\")\n entity.add_config_file(config_file_2)\n self.assertTrue(len(entity.config) == 2)\n\n configs = person.configs\n self.assertTrue(len(configs) == 2)\n\n\n def testRemoveConfigFile(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n\n config_file = person.add_config_file(\"test\", \"a whole bunch of text\", \"a/path/file.txt\")\n\n entity.add_config_file(config_file)\n self.assertTrue(len(entity.config) == 1)\n self.assertEqual(entity.config[0].get().text, \"a whole bunch of text\")\n entity.add_config_file(config_file)\n self.assertTrue(len(entity.config) == 1)\n\n config_file_2 = person.add_config_file(\"test2\", \"another a whole bunch of text\", \"a/path/file.txt\")\n entity.add_config_file(config_file_2)\n self.assertTrue(len(entity.config) == 2)\n entity.remove_config_file(config_file_2)\n self.assertTrue(len(entity.config) == 1)\n\n\n def test_signing(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n url = \"https://augment00.org/entity/12345678\"\n salt = \"asdfghjkl\"\n sig = keys.sign_url(url, entity.private_key, salt)\n mine = keys.verify_sig(url, sig, entity.public_key, salt)\n self.assertTrue(mine)\n\n\n def test_signing_fails(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n url = \"https://augment00.org/entity/12345678\"\n salt = \"asdfghjkl\"\n sig = keys.sign_url(url, entity.private_key, salt)\n mine = keys.verify_sig(url, sig, entity.public_key, \"123456\")\n self.assertFalse(mine)\n\n\n def test_entity_json(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n config_file = person.add_config_file(\"test\", \"A whole bunch of text\\nwith a line return\", \"a/path/file.txt\")\n entity.add_config_file(config_file)\n as_json = entity.as_json()\n\n as_json_string = json.dumps(entity.as_json(), indent=4)\n\n loaded = json.loads(as_json_string)\n\n self.assertEqual(loaded[\"config\"][0][\"text\"], \"A whole bunch of text\\nwith a line return\")\n\n\n\n def test_config_templating(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n config_file = person.add_config_file(\"test\", \"A whole bunch of text\\nwith uuid {{ uuid }}\", \"a/path/file.txt\")\n entity.add_config_file(config_file)\n as_json = entity.as_json()\n\n as_json_string = json.dumps(entity.as_json(), indent=4)\n\n loaded = json.loads(as_json_string)\n\n self.assertEqual(loaded[\"config\"][0][\"text\"], \"A whole bunch of text\\nwith uuid %s\" % entity.key.id())\n\n\n def test_config_firebase(self):\n\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n entity = person.add_new_entity(name=\"elephant\")\n config_file = person.add_config_file(\"test\", '{\"firebase\": \"{{ firebase }}\"}', \"a/path/file.txt\")\n entity.add_config_file(config_file)\n as_json = entity.as_json()\n\n as_json_string = json.dumps(entity.as_json(), indent=4)\n\n loaded = json.loads(as_json_string)\n\n as_json = json.loads(loaded[\"config\"][0][\"text\"])\n\n\n def test_token(self):\n entity_uuid = \"<KEY>\"\n token = create_custom_token(entity_uuid)\n",
"id": "1291403",
"language": "Python",
"matching_score": 4.556753158569336,
"max_stars_count": 1,
"path": "tests/test_models.py"
},
{
"content": "import unittest\nimport json\n\n# from google.appengine.api import memcache\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext import testbed\n\nfrom models import Person, Entity, Name\n\nimport api\n\n\nclass ApiTestCase(unittest.TestCase):\n\n def setUp(self):\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n self.testbed.init_datastore_v3_stub()\n self.testbed.init_memcache_stub()\n self.app = api.app.test_client()\n ndb.get_context().clear_cache()\n\n\n def tearDown(self):\n self.testbed.deactivate()\n\n\n def testAddEntity(self):\n person = Person.create(\"paul\", \"<EMAIL>\", \"123456789\")\n found = Person.with_email(\"<EMAIL>\")\n self.assertEqual(found.name, \"paul\")\n\n self.assertTrue(person.api_key is not None)\n\n data = {\n \"user_id\": person.get_google_id(),\n \"api_key\": person.api_key,\n \"name\": \"test\",\n \"description\": \"fishcakes\"\n }\n\n url = \"/api/new-entity\"\n\n rsp = self.app.post(url, data=json.dumps(data))\n self.assertTrue(rsp.status_code == 201)\n\n entity_uuid = rsp.data\n entity = Entity.get_by_id(entity_uuid)\n self.assertTrue(entity is not None)\n\n return person, entity\n\n\n def testAddValue(self):\n person, entity = self.testAddEntity()\n\n entity_uuid = entity.key.id()\n\n\n data = {\n \"user_id\": person.get_google_id(),\n \"api_key\": person.api_key,\n \"name\": \"test\",\n \"value\": \"fishfinger\"\n }\n\n url = \"/api/entity/%s/add-value\" % entity_uuid\n\n rsp = self.app.post(url, data=json.dumps(data))\n print rsp.status_code\n self.assertTrue(rsp.status_code == 200)\n\n entity = Entity.get_by_id(entity_uuid)\n\n self.assertEqual(entity.template_values[\"test\"], \"fishfinger\")\n\n\n def testSendCommand(self):\n\n person, entity = self.testAddEntity()\n\n entity_uuid = entity.key.id()\n\n\n data = {\n \"user_id\": person.get_google_id(),\n \"api_key\": person.api_key,\n \"rpc\":{\n \"method\": \"test\",\n \"params\": [\"fishfinger\"]\n }\n }\n\n url = \"/api/entity/%s/send-command\" % entity_uuid\n\n rsp = self.app.post(url, data=json.dumps(data))\n print rsp.status_code\n self.assertTrue(rsp.status_code == 200)\n\n\n",
"id": "2648116",
"language": "Python",
"matching_score": 1.125720500946045,
"max_stars_count": 1,
"path": "tests/test_api.py"
},
{
"content": "import json\n\ntry:\n from requests import *\nexcept ImportError, e:\n import urllib\n from google.appengine.api import urlfetch\n\n\n class ResponseWrapper(object):\n\n def __init__(self, response):\n self.response = response\n\n @property\n def status_code(self):\n return int(self.response.status_code)\n\n @property\n def headers(self):\n return self.response.headers\n\n @property\n def content(self):\n return self.response.content\n\n def json(self):\n return json.loads(self.response.content)\n\n\n def get(url, **kwargs):\n return request(\"GET\", url, **kwargs)\n\n\n def post(url, **kwargs):\n return request(\"POST\", url, **kwargs)\n\n\n def request(method, url, **kwargs):\n\n if \"params\" in kwargs.keys():\n querystring = urllib.urlencode(kwargs[\"params\"])\n url = \"%s?%s\" % (url, querystring)\n\n if \"data\" in kwargs.keys():\n data = kwargs[\"data\"]\n if type(data) == type({}):\n payload = urllib.urlencode(data)\n elif type(data) == type(\"\"):\n payload = data\n elif hasattr(data, \"read\"):\n payload = data.read()\n else:\n payload = None\n else:\n payload = None\n\n if \"json\" in kwargs.keys():\n payload = json.dumps(kwargs[\"json\"])\n\n if \"headers\" in kwargs.keys():\n headers = kwargs[\"headers\"]\n else:\n headers = {}\n\n if \"allow_redirects\" in kwargs.keys():\n follow_redirects = kwargs[\"allow_redirects\"]\n else:\n follow_redirects = True\n\n if \"timeout\" in kwargs.keys():\n deadline = kwargs[\"timeout\"]\n else:\n deadline = 5\n\n if \"verify\" in kwargs.keys():\n validate_certificate = kwargs[\"validate_certificate\"]\n else:\n validate_certificate = False\n\n print \"payload\", payload\n print \"headers\", headers\n print url\n\n resp = urlfetch.fetch(url,\n payload=payload,\n method=method,\n headers=headers,\n allow_truncated=False,\n follow_redirects=follow_redirects,\n deadline=deadline,\n validate_certificate=validate_certificate)\n\n return ResponseWrapper(resp)\n\n\n",
"id": "12380471",
"language": "Python",
"matching_score": 0.6433623433113098,
"max_stars_count": 1,
"path": "src/utilities/requests_shim.py"
},
{
"content": "from functools import wraps\n\nfrom flask import Flask, render_template, redirect, request\nfrom google.appengine.api import users\nfrom models import Person\n\n\ndef render_login_template(template, **kwargs):\n\n user = users.get_current_user()\n if user:\n login_url = users.create_logout_url(request.url)\n url_linktext = 'logout'\n else:\n login_url = users.create_login_url(request.url)\n url_linktext = 'login'\n\n return render_template(template, login_url=login_url, url_linktext=url_linktext, **kwargs)\n\n\ndef with_person(func):\n @wraps(func)\n def decorated_view(*args, **kwargs):\n google_user = users.get_current_user()\n if google_user is not None:\n google_id = google_user.user_id()\n person = Person.with_google_id(google_id)\n if person is None:\n return redirect(\"/\")\n else:\n return func(*args, person=person, **kwargs)\n else:\n raise Exception(\"no google user in new_person\")\n return decorated_view\n",
"id": "11314913",
"language": "Python",
"matching_score": 3.351944923400879,
"max_stars_count": 1,
"path": "src/shared.py"
},
{
"content": "import logging\n\nfrom google.appengine.api import users\n\nfrom flask import Flask, redirect, flash\n\nfrom constants import *\n\napp = Flask(__name__)\n\napp.secret_key = FLASK_SECRET_KEY\n\nfrom shared import render_login_template, with_person\nfrom models import Person\n\n\[email protected]('/', methods=[\"GET\"])\ndef home():\n google_user = users.get_current_user()\n if google_user is not None:\n google_id = google_user.user_id()\n person = Person.with_google_id(google_id)\n if person is not None:\n return render_login_template(\"account.html\", person=person)\n else:\n flash(\"choose a name and email to use with your augment00 account\", \"info\")\n return redirect(\"/person/new\")\n else:\n return render_login_template(\"intro.html\")\n\n\[email protected]('/about', methods=[\"GET\"])\ndef about():\n google_user = users.get_current_user()\n if google_user is not None:\n google_id = google_user.user_id()\n person = Person.with_google_id(google_id)\n else:\n person = None\n\n return render_login_template(\"about.html\", person=person)\n\n\[email protected](500)\ndef server_error(e):\n # Log the error and stacktrace.\n logging.exception('An error occurred during a request.')\n return 'An internal error occurred.', 500",
"id": "4944071",
"language": "Python",
"matching_score": 3.263780117034912,
"max_stars_count": 1,
"path": "src/main.py"
},
{
"content": "import logging\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\[email protected]('/admin')\ndef admin_hello():\n return 'augment00 admin'\n\n\[email protected](500)\ndef server_error(e):\n # Log the error and stacktrace.\n logging.exception('An error occurred during a request.')\n return 'An internal error occurred.', 500",
"id": "11951012",
"language": "Python",
"matching_score": 0.7263830900192261,
"max_stars_count": 1,
"path": "src/admin.py"
}
] | 2.176196 |
kazweda | [
{
"content": "# https://coderslegacy.com/python/tkinter-canvas/\n# https://twitter.com/aemkei/status/1378106734871461890\nfrom tkinter import *\n\ndef create_box(canvas, x, y):\n a = 4\n coord = x * a, y * a, x * a + a, y * a + a\n canvas.create_rectangle(\n coord,\n fill=\"grey\"\n )\n\ndef draw_xor(canvas):\n for j in range(256):\n for i in range(256):\n if (i ^ j) % 9:\n create_box(canvas, i, j)\n\nroot = Tk()\n\nframe = Frame(root, width=512, height=512)\nframe.pack()\ncanvas = Canvas(frame, width=512, height=512)\ncanvas.pack()\ndraw_xor(canvas)\n\nroot.mainloop()\n",
"id": "11615930",
"language": "Python",
"matching_score": 0,
"max_stars_count": 1,
"path": "drawxor.py"
},
{
"content": "import json\n\nwith open('project.json') as f:\n df = json.load(f)\n\nr = {}\nfor skey in df['targets'][0]['blocks']:\n k = df['targets'][0]['blocks'][skey]['opcode']\n if k in r:\n r[k] += 1\n else:\n r[k] = 1\nprint(sorted(r.items(), key=lambda x:x[0]))\n",
"id": "2874135",
"language": "Python",
"matching_score": 0,
"max_stars_count": 0,
"path": "filecheck.py"
},
{
"content": "def fibo(x):\n if x == 0:\n return 0\n if x <= 2:\n return 1\n return fibo(x-1) + fibo(x-2)",
"id": "3268546",
"language": "Python",
"matching_score": 1,
"max_stars_count": 0,
"path": "fibonacci.py"
},
{
"content": "import unittest\nimport fibonacci\n\nclass TestFibonacci(unittest.TestCase):\n\n cases = [[0,0],[1,1],[2,1],[3,2]]\n\n def test_fibo(self):\n for i in range(len(self.cases)):\n self.assertAlmostEqual(fibonacci.fibo(self.cases[i][0]), self.cases[i][1])\n\nif __name__ == '__main__':\n unittest.main()\n",
"id": "2795105",
"language": "Python",
"matching_score": 1,
"max_stars_count": 0,
"path": "test-fibonacci.py"
}
] | 0.5 |
muziyongshixin | [{"content":"import argparse\nimport logging\nimport os\nimport pickle\nimport socket\nimport time\n(...TRUNCATED) | 2.294248 |
DE-Bass | [{"content":"\"\"\"\nFrom the 26 March meeting, the plan was:\n1) Fix 2D separation and overall R fl(...TRUNCATED) | 2.210289 |
MTCloudVision | [{"content":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function(...TRUNCATED) | 1.868409 |
spdk | [{"content":"#!/usr/bin/env python\n# BSD LICENSE\n#\n# Copyright(c) 2010-2014 Intel Corporation. Al(...TRUNCATED) | 2.782286 |
maxwellharon | [{"content":"VERSION = (1, 5, 24)\n\ndefault_app_config = 'image.apps.ImageConfig'\n","id":"7475688"(...TRUNCATED) | 1.675606 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 139