content
stringlengths
5
1.05M
# Written by Måns Andersson import pygame import sys import socket import json import threading pygame.init() # This variable holds the entire state of the game state = { "players": [], "blockades": [], "bombs": [], "snowflakes": [], "placed_bombs": [], "explosions": [], "winner": -1, } #...
from aiosql_mysql.adapters.pymysql import PyMySQLAdaptor from aiosql_mysql.adapters.asyncmy import AsyncMySQLAdapter
#!/usr/bin/env python import argparse import os import shutil def parse_args(): ap = argparse.ArgumentParser() ap.add_argument("--check-basename", nargs="+", action="append", metavar=("PATH ...", "BASE")) ap.add_argument("--copy", nargs="+", action="append", metavar=("SRC", "DEST")) return ap.parse...
'''Reading Dilution Status''' from pathlib import Path from datetime import datetime from time import mktime from os import listdir from numpy import diff from pyqum.instrument.analyzer import derivative, curve class bluefors: def __init__(self): self.LogPath = Path(r'\\BLUEFORSAS\BlueLogs') self...
#!/usr/bin/env python """ @author: Dan Salo, Jan 2017 Purpose: Implement Convolutional Variational Autoencoder for Semi-Supervision with partially-labeled MNIST dataset. MNIST Dataset will be downloaded and batched automatically. """ from tensorbase.base import Model, Layers from tensorbase.data import Mnist from s...
from traceback import format_exc from urlparse import urlparse from telnetlib import Telnet import httplib import sys try: import simplejson as json except ImportError: import json from basicserver import BasicVirtualServer from clusto.exceptions import DriverException import clusto class KVMVirtualServer(Ba...
import pytest try: from jupyter_server_mathjax.app import STATIC_ASSETS_PATH HAS_JSMX = True except Exception: # pragma: no cover STATIC_ASSETS_PATH = None HAS_JSMX = False EXCURSIONS = [ [False, ["--ignore-sys-prefix"]], [False, ["--disable-addons", "mathjax"]], ] if STATIC_ASSETS_PATH: ...
import pytest import numpy as np from pipex import H5Storage, channel_map, map, source, PRecord def test_h5storage(): storage = H5Storage("/tmp") image = np.array([[0, 0], [0, 0]], dtype=np.uint8) bucket = storage['pipex_test/test_pstorage'] pl = [1, 2, 3] >> channel_map('image', lambda _: image) >>...
import numpy as np from typing import Callable from autoarray.plot.abstract_plotters import Plotter from autoarray.plot.mat_wrap.visuals import Visuals1D from autoarray.plot.mat_wrap.visuals import Visuals2D from autoarray.plot.mat_wrap.include import Include1D from autoarray.plot.mat_wrap.include import Includ...
# safety path definitions
import html import re _CAMEL_CASE_RE = re.compile(r'([a-z])([A-Z])') def format_label(label: str) -> str: return _CAMEL_CASE_RE.sub(r'\1 \2', label).lower().replace('_', ' ') def preformat_html(solution: str) -> str: return '<pre>%s</pre>' % html.escape(solution).replace('\n', '<br />')
import sys import os from nose.tools import assert_equal ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(ROOT_DIR, '..')) from component.intent.request import Request from component.intent.response import Response class TestIntentResponse(object): def test_create_response_from_r...
from keras.models import Model from keras.layers import Conv2D, Input, BatchNormalization, LeakyReLU, ZeroPadding2D, UpSampling2D, Dense, Flatten, Activation, Reshape, Lambda from keras.layers.merge import add, concatenate import tensorflow as tf from keras import backend as K ANC_VALS = [[116,90, 156,198, 373,326...
print("matrícula")
#!/usr/bin/env python __all__ = ["nemo"]
# Author: Thomas Porturas <thomas.porturas.eras@gmail.com> from . import model_utilities as mu from .data_preprocessing import process_files from .figure_pipeline import run_pipeline from .data_nl_processing import NlpForLdaInput from .compare_models import CompareModels, run_model_comparison from .optimize_mallet impo...
cidade = input('Digite o produto de uma cidade: ').strip().upper() print('A cidade começa com a palavra Santo? {}'.format('SANTO' in cidade[:5]))
from direct.showbase.DirectObject import DirectObject from panda3d.core import * class Castle(DirectObject): def __init__(self, pos,hpr,sc): self.model = loader.loadModel("models/castle") self.model.setPos(pos.getX(),pos.getY(),pos.getZ()) self.model.setHpr(hpr.getX(),hpr.getY(),hpr.getZ()) self.model...
# optional -> get data based on the specified location
# # # Server side image processing # Adding PCA dimensionality reduction # from __future__ import print_function from time import time from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn.svm import SVC from sklearn.externals import joblib from sklearn.deco...
__author__ = 'OpenSlides Team <support@openslides.org>' __description__ = 'Presentation and assembly system' __version__ = '2.0.1-dev'
import torch from torch import nn from torch.nn import functional as F class mlp_classifier(nn.Module): def __init__(self, in_dim, hidden_dims=None, bn=True, drop_rate=0.0, num_classes=2): super(mlp_classifier, self).__init__() self.drop_rate = drop_rate modules = [] if hidden_dims...
""" Created on 01 March 2016 @author: Mojtaba Haghighatlari """ from __future__ import print_function from builtins import range import warnings import os import time import pandas as pd from lxml import objectify, etree from chemml.utils import std_datetime_str from chemml.utils import bool_formatter from chemml.util...
from sqlalchemy.ext.asyncio import create_async_engine from ..utils.config import Config from ..utils.singleton import Singleton class Database(Singleton): def __init__(self): self.engine = create_async_engine(Config.url, echo=True, future=True, pool_pre_ping=True) async def execute(self, sql): ...
#!/usr/bin/python # Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source # Project (AJOSP) Contributors and others. # # SPDX-License-Identifier: Apache-2.0 # # All rights reserved. This program and the accompanying materials are # made available under the terms of the Apache License, Ve...
from django.urls import path from django.conf.urls import url from evento import views from .views import ConsolidadoEvento urlpatterns = [ path('evento/', views.HomeView.as_view(), name='homeEvento'), path('evento/<int:pk>/', views.EventoDetailView.as_view(), name='evento_detail'), path('evento/create/',...
from django.shortcuts import render from .models import Profile, Skills from django.core.mail import send_mail # Create your views here. def index(request): profile = Profile.objects.all() skills = Skills.objects.all() context = { 'profile': profile, 'skills': skills, } if requ...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
import requests from bs4 import BeautifulSoup url = "https://www.bolsamadrid.es/esp/aspx/Empresas/InfHistorica.aspx?ISIN=ES0125220311&ClvEmis=25220" historico = requests.get(url) soup = BeautifulSoup(historico.text, 'html.parser') #Obtener la primera fecha del historico stock_price_list = soup.find(id='ctl00_Con...
# Generated by Django 3.1 on 2020-09-16 06:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('package', '0006_auto_20200916_1440'), ] operations = [ migrations.RenameField( model_name='packageline', old_nam...
import json import shutil import os from . import utils class PatchesCollection(object): def __init__(self, path): self.path = path self.json_path = os.path.join(self.path, 'patches.json') self.exists = os.path.isfile(self.json_path) self.patches_json = {} self.images = [] self.m...
import logging import os from abc import abstractmethod, ABC from msgraph_async import GraphAdminClient from msgraph_async.common import GraphClientException from ModernRelay import exceptions class DeliveryAgentBase(ABC): """ Abstract base class for delivery agents. Extend this class and attach the de...
import os import boto3 ssm = boto3.client("ssm") SHADOW_ENDPOINT_SSM = os.environ.get("SHADOW_ENDPOINT_SSM") def lambda_handler(event, context): print(event) shadow_endpont_name = dict(event)["job_name"] response = ssm.put_parameter( Name=SHADOW_ENDPOINT_SSM, Value=shadow_endpont_name, Overwr...
import pygame from os import path from sys import argv class Button: def __init__(self, position, value, label): filePath = path.dirname(argv[0]) self.buttonSound = pygame.mixer.Sound(filePath+"/resources/audio/button.wav") self.buttonSound.set_volume(.25) self.buttonSoundChannel =...
import sys import asyncio import threading from pathlib import Path import asyncio import time import pytest from nextline import Nextline ##__________________________________________________________________|| statement = """ import script script.run() """.strip() ##________________________________________________...
import pygame def lePlaylistDeArquivo(NomeArq): arquivo = open(NomeArq, 'r') linhas = [] for linha in arquivo: linhaLida = linha.strip().split('#') linhas.append(linhaLida) arquivo.close return linhas def listar_playlist(playlist): for lista in playlist: print(f'Ba...
# Create yearly and monthly mean files for chosen vars import sys import numpy as np import pandas as pd from netCDF4 import Dataset import xarray as xr import dask from dask.diagnostics import ProgressBar import os, fnmatch from resource import * #import matplotlib.pyplot as plt import calendar import plot_maps3 das...
import numpy as np import matplotlib.pyplot as plt from skimage import feature, transform from bagnets.pytorch import Bottleneck from keras.preprocessing import image as KImage import time import torch import torch.nn as nn import math import logging from torch.utils import model_zoo model_urls = { 'bagnet...
""" 树结构 - 总经理办公室 |- 财务部门 |- 业务部门 |- 销售一组 |- 销售二组 |- 生产部门 |- 研发组 |- 测试组 """ class Node: def __init__(self, name, duty): self.name = name self.duty = duty self.children = [] def add(self, obj): self.children.append(obj) def remov...
from math import exp from curves import getPropellerArray from simulation import runSimulation from writeInput import writeInput L = 0.257 # propeller's length def computeI(r,c): # r and c are the radius and chord arrays given to the simulation # you can give them by hand or use the return values of 'getPrope...
from time import clock, sleep import sys import signal import math import logging from ev3dev.auto import Motor, LargeMotor, GyroSensor, PowerSupply from device import read_device, set_duty g_log = logging.getLogger(__name__) ######################################################################## ## ## Runner_stub:R...
#KZ: SQL Injection - we use the open areas to try and get an admin password from django.test import TestCase, Client from django.urls import reverse from django.http import HttpRequest from LegacySite.models import * from LegacySite.views import * import json import io class SQLTest(TestCase): def setUp(self): ...
#!/usr/bin/env python """Parse vcard stream from stdin, output a CSV for consumption by Office365 """ import sys import csv from collections import namedtuple, OrderedDict vcard_collection = [] FIELDS_CSV = 'ExternalEmailAddress Name FirstName LastName StreetAddress City StateorProvince PostalCode Phone MobilePhone...
# tdr.py # ================================================================================ # BOOST SOFTWARE LICENSE # # Copyright 2020 BitWise Laboratories Inc. # Original Author.......Jim Waschura # Contact...............info@bitwiselabs.com # # Permission is hereby granted, free of charge, to any person or organizat...
import json import numpy as np import os import os.path as osp from PIL import Image from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import random import torch from torch.utils.data import Dataset class HICODetDataset(Dataset): def __init__(self, cfg, data_root...
#!/usr/bin/env python # Copyright 2017 Calico LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
from dataclasses import InitVar from dataclasses import dataclass from dataclasses import field from typing import Iterable from typing import List from typing import Tuple @dataclass(frozen=True) class Line: x1: int y1: int x2: int y2: int def is_straight(self) -> bool: return self.x1 ==...
import numpy as np import pandas as pd def zonal_stats(zones, values, stats=['mean', 'max', 'min', 'std', 'var']): """Calculate statistics for each zone defined by a zone dataset, based on values from another dataset (value raster). A single output value is computed for each zone in the input zon...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from telemetry.v1beta3 import GenericEvents_Beta3_pb2 as telemetry_dot_v1beta3_dot_GenericEvents__Beta3__pb2 from telemetry.v1beta3 import TelemetryService_Beta3...
"""Ex 012 - Faça um algoritimo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.""" print('-' * 10, '>Ex 012,', '-' * 10) #Criando variáveis e recebendo dados. val_pro = float(input('Qual valor do produto: R$')) desc = 0.05 novo_val_pro = val_pro - val_pro * desc #imprimindo dados para o u...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: mlagents/envs/communicator_objects/unity_rl_input.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from g...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-23 19:54 from __future__ import unicode_literals import collective_blog.models.blog import collective_blog.models.comment import collective_blog.models.post from django.conf import settings from django.db import migrations, models import django.db.models.de...
import numpy as np from scipy.integrate import simps from StochasticMechanics import Stochastic from Building import * from BuildingProperties import * from Hazards import Stationary import copy import time import matplotlib.pyplot as plt from scipy import integrate import time class PerformanceOpt(Stochastic): ...
import os.path as path from pathlib import Path import csv from datetime import datetime import platform filepath = str(Path(__file__).parents[2])+'/data/' def player_to_csv(player_entry): global filepath now = datetime.now() if platform.system() == 'Windows': timestamp = now.strftime("%m/%d/%Y %T") el...
import time import torch import os from options.test_options import TestOptions from data import create_dataset from models import create_model import random from PIL import Image import numpy as np import glob from torchvision import transforms input_folder = ["/root/FaceDataset/FFHQ/images256x256/", "/root/FaceDatas...
# -*- coding: utf-8 -*- # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
# -*- coding: utf-8 -*- """Example Box local settings file. Copy this file to local.py and change these settings. """ # Get an app key and secret at https://www.box.com/developers/apps BOX_KEY = None BOX_SECRET = None
import struct import subprocess import bisect import collections SAMP = struct.Struct("IIQ4QIIQ") class SamplerFile(object): NTRACE = 4 FLAGS, COUNT, RIP, TRACE0 = range(4) LATENCY, SOURCE, LOAD_ADDRESS = range(TRACE0+NTRACE, TRACE0+NTRACE+3) def __init__(self, fp): if isinstance(fp, basestri...
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ GUIDES = { 'issue': { 'id': 1, 'page': 'issue', 'cue': _('Click here for a tour of the issue page'), 'required_targets': ['exception'], 'steps': [ { '...
# -*- coding: utf-8 -*- """ A mock database driver module. """ class MockConnection(object): """ A mock Connection object. :param \**kwargs: Accepts anything. """ def __init__(self, **kwargs): self.kwargs = kwargs # Used to determine if the connection is "open" or not. s...
# Generated by Django 3.2.2 on 2021-05-09 13:29 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Parliament1", fields=[ ("id", models.AutoField(p...
from flask import Flask, request from pprint import pprint app = Flask(__name__) bot = None @app.route("/", methods=[ 'GET', 'POST' ]) def index(): json_data = request.get_json() message_id = json_data[ "data" ][ "id" ] message_info = bot.get_message_details( message_id=message_id ).json() if m...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-28 03:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comic', '0003_auto_20170128_0217'), ] operations = [ migrations.AlterField(...
11110000 00001111 11110000 00001111 11110000 11111111 11000011 00111100
class LRUCache: def __init__(self, max_size=128): self._max_size = max_size self._cache_by_key = {} self._cache_by_use = _LRUCacheList() def query(self, key): if key not in self._cache_by_key: return None node = self._cache_by_key[key] self._cache_b...
import pytest import simple_skidl_parts.analog.vdiv as vdiv from skidl import * def test_vdiv1(): gnd, vin, vout = Net("GND"), Net("Vin"), Net("OUT") v = vdiv.vdiv(vin, vout, gnd, ratio=3.0) generate_netlist(file_=open("/tmp/lala.net", "w"))
# Copyright 2022 neomadas-dev # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer...
import argparse # Apply the edits of a single annotator to generate the corrected sentences. def main(args): m2 = open(args.m2_file).read().strip().split("\n\n") out = open(args.out, "w") # Do not apply edits with these error types skip = {"noop", "UNK", "Um"} for sent in m2: sent = sent.split("\n") orig_sen...
""" Short demo of drone functionality. For the full list of available commands check: https://djitellopy.readthedocs.io/en/latest/tello/ """ from tello import Drone with Drone() as d: d.start_video('video.avi') d.takeoff() d.move_forward(50) d.rotate_clockwise(360) d.wait(5.0) d.land()
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-10-10 21:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='disk'...
import os from aws_cdk import ( core, aws_lambda, aws_lambda_event_sources as sources, aws_iam as iam, aws_s3 as s3, aws_sns as sns, aws_dynamodb as dynamo, aws_events as events, aws_events_targets as event_targets, ) class JobSummaryStack(core.Stack): def __init__(self, ...
# USAGE # python simple_thresholding.py --image ../images/coins.png # Import the necessary packages import numpy as np import argparse import cv2 # Construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args =...
from gencon_miner import GenconMiner, __version__ def test_version(): assert __version__ == '0.1.6' def test_url_extract(): miner = GenconMiner(url='http://google.com') data = miner.extract('title') assert data[-1].text == 'Google' def test_text_extract(): import requests html_data = requests...
#pj17 ones = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine') teens = ('ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen') tenties = ('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety') ten_to_str = {3:'thous...
# coding: utf-8 # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import unicode_literals from six.moves import xrange as range from nbdime import patch from nbdime.diff_format import is_valid_diff from nbdime.diffing.lcs import diff_from_lcs from n...
from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import auth from django.template.context_processors import csrf from django.contrib.auth import login, logout, authenticate from django.contrib.auth.f...
import Customer class Order: def __init__(self, productname, productcode): self.productname = productname self.productcode = productcode
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 17-9-4 下午11:46 @Author : TangZongYu @Desc : """ import jieba.posseg as pseg words = pseg.cut("想学习机器学习") for word in words: print word,word.flag
# The list `values[low:high]` has `high - low` elements. For example, # `values[1:4]` has the 3 elements `values[1]`, `values[2]`, and `values[3]`. # Note that the expression will only work if `high` is less than the total # length of the list `values`.
from django.contrib.auth.models import User from stock.models import Stock, Portfolio, StockSelection, Currency from stock.forms import PortfolioForm from django.contrib.auth.models import User from stock import module_stock as ms from pprint import pprint bruno = User.objects.get(username='bvermeulen') john = User.obj...
# Copyright (c) 2009-2012 testtools developers. See LICENSE for details. from unittest import TestSuite def test_suite(): from testtools.tests.matchers import ( test_basic, test_const, test_datastructures, test_dict, test_doctest, test_exception, test_file...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/SupplyDelivery) on 2020-02-03. # 2020, SMART Health IT. import sys from dataclasses import dataclass, field from typing import ClassVar, Optional, List from .backboneelement import Backbone...
import FWCore.ParameterSet.Config as cms # configuration to model pileup for initial physics phase from SimGeneral.MixingModule.mixObjects_cfi import theMixObjects from SimGeneral.MixingModule.mixPoolSource_cfi import * from SimGeneral.MixingModule.digitizers_cfi import * mix = cms.EDProducer("MixingModule", digi...
# -*- coding: utf-8 -*- # Django settings for truffe2 project. from django.utils.translation import ugettext_lazy as _ from os.path import abspath, dirname, join, normpath DJANGO_ROOT = dirname(abspath(__file__)) + '/../' DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com')...
if __name__ == '__main__': input = open('input', 'r').readlines() depth = 0 horizontal = 0 for line in input: (direction, amount) = line.split(' ') if direction == 'forward': horizontal += int(amount) elif direction == 'down': depth += int(amount) ...
import unittest import heapq import random import threading from garage.threads import utils class UtilsTest(unittest.TestCase): def test_atomic_int(self): i = utils.AtomicInt() self.assertEqual(0, i.get_and_add(0)) self.assertEqual(0, i.get_and_add(1)) self.assertEqual(1, i.get...
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import multiprocessing import sys import rumps rumps.debug_mode(True) from voiceplay import __title__ as vp_title from voiceplay.cli.argparser.argparser import MyArgumentParser, Help from voiceplay.logger import logger from voiceplay.utils.updatecheck import check_up...
from dataclasses import dataclass from flask import Flask, render_template @dataclass class ErrorPage: error_code: int message: str long_message: str = None class HttpErrorHandler: def __init__(self, app: Flask, error_page: ErrorPage, page_template_file: str, template_arguments={}): ...
########################################################################################### #created by : Naveen #last modified :3/1/20 ############################################################################################ import browserhistory as bh import qr def cf(): dict_obj = bh.get_browserhist...
"Pymaker, the better `make`" __version__ = '0.0.1' from importlib import import_module from inspect import signature from pathlib import Path from pymaker.settings import cli_args import argparse import os import subprocess import sys import pickle from doc import doc @doc def r(s): if type(s) is list: p...
# XXX: Make sure to import panda3d_kivy BEFORE anything Kivy-related from panda3d_kivy.core.window import PandaWindow from kivy.app import App as KivyApp from kivy.base import runTouchApp from kivy.lang import parser class App(KivyApp): def __init__(self, panda_app, display_region=None, **kwargs): super(...
"""Set up Flask and flasgger.""" import os import traceback import logging from flask import Flask, Blueprint from flask_mail import Mail from flask_restful import Api from flask_cors import CORS from flasgger import Swagger import werkzeug from manager import logging_config logger = logging.getLogger(__name__) ap...
# coding: utf-8 # --------------------------------------------------------------------------------------------------------------------- # # Florida International University # # This software is a "Camilo Valdes Work" under the terms of the United States Copyright Act. # Please ...
import os import string import requests import urllib.parse def getBingResponse(zipCode): '''Get's Bing API Response from a Zip Code Location Query''' apiKey = os.environ['BING_API_KEY'] payload = f'http://dev.virtualearth.net/REST/v1/Locations/{zipCode}?maxResults=1&key={apiKey}' return requests.get(p...
import json import requests from django.conf import settings from Category.models import Category, City def get_permission(request): """ 获取登录用户的权限列表 :param request: Django 的request对象 :return: 城市列表 分类列表 """ categories = Category.objects.all() cities = City.objects.all() city_list = [city ...
from typing import List, Optional from uuid import UUID from c4maker_server.adapters.models import DiagramDB, UserAccessDB from c4maker_server.adapters.mysql.mysql_client import MySQLClient from c4maker_server.domain.entities.diagram import Diagram from c4maker_server.domain.entities.user import User from c4maker_serv...
#!/usr/bin/python3 import argparse from datetime import datetime from logger import logger import sys from tablib import Dataset from request_utils import * from presets import * from bdl_query import BDLMultiCityQuery, BDLMultiVariableQuery from explore import explore_subjects class Requests: births = "births" ...
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. ''' Defines the `CachedType` metaclass. See its documentation for more details. ''' from python_toolbox.sleek_reffing import SleekCallArgs class SelfPlaceholder: '''Placeholder for `self` when storing call-args.''' class C...
#!/usr/bin/env python3 import os import argparse import csv import glob import meadow_parser_funcs import posixpath parser = argparse.ArgumentParser() parser.add_argument('--input', '-i', action='store', dest='input_path', type=str, help='full path to input folder') parser.add_argument('--output', '-o', action='stor...
""" The :mod:`ramp_database.utils` module provides tools to setup and connect to the RAMP database. """ from contextlib import contextmanager import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.engine.url import URL from .model import Model def setup_db(confi...