text stringlengths 2 999k |
|---|
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import binascii
import datetime
import inspect
import logging
import os
from pathlib import Path
from . import exceptions
logger = logging.getLogger(__name__)
def generate_token(n=24, *args, **kwargs):
return str(binascii.hexlify(os.urandom(n)), "utf-8")
def build_claim_iss(attr, *args, **kwargs):
return... |
from rest_framework.serializers import (
HyperlinkedIdentityField,
ModelSerializer,
SerializerMethodField
)
from comments.api.serializers import CommentSerializer
from comments.models import Comment
from posts.models import Post
class PostCreateUpdateSerializer(ModelSerializer):
class Meta:
... |
# @generated
# This file was generated by running `python -m dagster.grpc.compile`
# Do not edit this file directly, and do not attempt to recompile it using
# grpc_tools.protoc directly, as several changes must be made to the raw output
# pylint: disable=no-member, unused-argument
# Generated by the gRPC Python pro... |
from sqlalchemy.orm import Session
import models, schemas
"""[گرفتن اطلاعات یوزر از دیتا بس با ادی او ]
"""
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
"""[گرفتن تمام یوزر ها از دیتا بیس]
"""
def get_users(db: Session, skip: int =... |
import math, cmath
import numpy as np
from openmdao.api import ImplicitComponent
class ACbus(ImplicitComponent):
"""
Determines the voltage of an AC bus
"""
def initialize(self):
self.options.declare('num_nodes', types=int)
self.options.declare('lines', default=['1', '2'], desc='Name... |
import pytest
@pytest.fixture
def argtest():
class TestArgsClass(object):
cast = str
def __call__(self, arg):
self.arg = arg
return self.cast(arg)
def casted(self, cast):
self.cast = cast
return TestArgsClass()
@pytest.fixture
def invalid():
... |
import subprocess
import os
class new_fifo_window():
def __init__(self, fifo_path):
self.fifo_path = fifo_path
try:
os.mkfifo(fifo_path)
except:
print('fifo already exists, but continue')
self.proc = subprocess.Popen(['xterm', '-e', 'cat %s' % fifo_path])
self.fd = open(fifo_path, 'w')
def write(... |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import copy
import u... |
from modules.botutil import BotUtil
class MongoHelper:
def __init__(self, client):
self.__client = client
self.__games = client.interbellum.games
def create_game(self, chat_id, game_admin):
commit = {
'id': chat_id,
'admin': game_admin,
'players': ... |
# coding=utf-8
"""
To support django-behave
"""
import os
import sys
def run_as_django_behave(formatter_name, feature_names, scenario_n_options):
"""
:param formatter_name: for "-f" argument
:param feature_names: feature names or folders behave arguments
:param scenario_n_options: list of ["-n", "scen... |
from pypy.rpython.lltypesystem import rffi, lltype
from pypy.module.cpyext.test.test_api import BaseApiTest
from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
from pypy.module.cpyext.api import Py_ssize_t, Py_ssize_tP
class TestSliceObject(BaseApiTest):
def test_slice(self, space, api):
... |
from abc import ABC, abstractmethod
class ExplorationPolicy(ABC):
def __init__(self):
pass
@abstractmethod
def update(self, *args):
"""Called at each action"""
raise NotImplementedError
@abstractmethod
def explore(self, *args):
"""Decides what to do as the next a... |
with open("liczby1.txt") as f:
liczby1 = [int(l, 8) for l in f.readlines()]
with open("liczby2.txt") as f:
liczby2 = [int(l, 10) for l in f.readlines()]
same_value_in_same_rows = 0
first_value_bigger = 0
for i in range(len(liczby1)):
num1 = liczby1[i]
num2 = liczby2[i]
if num1 == num2:
sa... |
import unittest
from openmdao.api import Problem, Group, NewtonSolver, ScipyKrylov, NonlinearBlockGS, \
LinearBlockGS, DirectSolver
from openmdao.test_suite.parametric_suite import ParameterizedInstance
from openmdao.utils.assert_utils import assert_rel_error
def _build(solver_class=NewtonSolver, linear_solver_... |
import discord
from discord.ext import commands
import datetime
import editdistance
import re
# road ad regex, thanks road
invitere = r"(?:https?:\/\/)?discord(?:\.gg|app\.com\/invite)?\/(?:#\/)([a-zA-Z0-9-]*)"
# my own regex
invitere2 = r"(http[s]?:\/\/)*discord((app\.com\/invite)|(\.gg))\/(invite\/)?(#\/)?([A-Za-z0-... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import logging
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session, request
from courses import *
# get all sections of corresponding course
# return a list of string
def answer_sections():
year = session.attributes['year']
semester = session.attributes['semester']... |
# Copyright 2021 The Narrenschiff Authors
# 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... |
from __future__ import division, print_function, absolute_import
import math
import random
from collections import deque
import torch
from PIL import Image
from torchvision.transforms import (
Resize, Compose, ToTensor, Normalize, ColorJitter, RandomHorizontalFlip
)
from ..utils.augumentation import SSD_Photometric... |
from django.apps import AppConfig
class GreazeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'greaze'
def ready(self):
import greaze.signals |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
def fix_sys_path(current_path):
"""
logic to have always the correct sys.path
'', web2py/gluon, web2py/site-packages, web2py/ ...
"""
def add_path_first(path):
sys.path = [path] + [p for p in sys.path if (
not ... |
# Time: O(n)
# Space: O(1)
# 1018
# Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted
# as a binary number (from most-significant-bit to least-significant-bit.)
#
# Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5.
# Input: [0,1... |
"""
A P A C H E L I C E N S E
------------
Version 2.0, January 2004
Copyright 2021 Miguel Cruces Fernández
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 cop... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PySymfit(PythonPackage):
"""Symbolic Fitting; fitting as it should be."""
homepage = ... |
# Copyright 2018 The TensorFlow Probability Authors.
#
# 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 o... |
"""
WSGI config for organization project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_... |
# 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
# distributed under t... |
# Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
#
# This software is licensed under the Apache License, Version 2.0 (the
# "License") as published by the Apache Software Foundation.
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import logging
from typing import Any, DefaultDict, Dict, List, Optional
from fbpcp.service.mpc impo... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 TU Wien.
#
# Invenio-Users-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Data-layer definitions for user and group management in Invenio."""
from .api import GroupAggrega... |
# Copyright (c) Xingyi Zhou. All Rights Reserved
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
from pycocotools.cocoeval import COCOeval
from pyquaternion import Quaternion
import numpy as np
import torch
import json
import ... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Handlers for workflow notifications.
This module contains all function needed for handling notification objects
needed by workflow notifications. The exposed functions are the entry points
for callback l... |
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.utils.tensorboard import SummaryWriter
import torch.multiprocessing as mp
import torch.distributed as dist
import torch.utils.data.distributed
import argparse
import os
import json
from models.StyleSpeech import StyleSpeech
fr... |
class CommandError(Exception):
pass
|
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import HTTP_HEADER_ENCODING, authentication
from .exceptions import AuthenticationFailed, InvalidToken, TokenError
from .settings import api_settings
AUTH_HEADER_TYPES = api_settings.AUTH_HEADER_T... |
"""
Django settings for skool project.
Generated by 'django-admin startproject' using Django 2.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# B... |
#!/usr/bin/python
__author__ = 'Thomas Dixon'
__license__ = 'MIT'
from .pysha256 import sha256
def new(m=None):
return sha224(m)
class sha224(sha256):
_h = (0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4)
_output_size = 7
digest_size = 28 |
#
# Copyright 2019, Institute for Systems Biology
#
# 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 o... |
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command to pause executing until database is available"""
def handle(self, *args, **options):
self.stdout.write('Waitin... |
from evennia.utils.utils import variable_from_module
class CharacterHandler():
"""
This handler contains general behaviors, tasks, and mechanics of the character class.
"""
def __init__(self, owner):
self.owner = owner
self.main_class_dic = variable_from_module("characters.character_cla... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_phpcpd_is_installed(host):
f = host.file('/usr/local/bin/phpcpd')
assert f.exists
assert f.user == 'root'
assert f.gro... |
import csv
import requests
df = open("bridgeData3.csv",'r').readlines()
fin = open('final.csv','r').readlines()
finCsv = fin[1:]
# url = https://b2ptc.herokuapp.com/bridges
finalCsv = df[1:]
obj = {}
for i in finalCsv:
x = i.split(',')
obj[x[1]] = {'bridge_name':x[0],'proj_code':x[1],'before_img':x[2],'after_im... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-30 18:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('carts', '0001_initial'),
]
operations = [
migrations.AddField(
... |
"""
This module contains StructuredLogEvent and EventSummary classes.
"""
from collections import defaultdict
import json
import logging
import os
import re
import sys
from datetime import datetime
from prettytable import PrettyTable
from jade.common import JOBS_OUTPUT_DIR
from jade.exceptions import InvalidConfigur... |
"""
Module: 'usocket' on esp32_LoBo 3.2.9
"""
# MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.9', version='ESP32_LoBo_v3.2.9 on 2018-04-12', machine='ESP32 board with ESP32')
# Stubber: 1.1.2
AF_INET = 2
AF_INET6 = 10
IPPROTO_IP = 0
IPPROTO_TCP = 6
IPPROTO_UDP = 17
IP_ADD_MEMBERSHIP = 3
SOCK_DGRAM = 2... |
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... |
# Problem:
# Write a program that reads a number of integer numbers entered by the user and sums them.
num_of_loops = int(input())
sum = 0;
for i in range(1, num_of_loops + 1):
num = int(input())
sum += num
print(sum)
|
import streamlit as st
import pickle
# Text/Title
st.title("Streamlit Tutorials")
# SIDEBARS
st.sidebar.header("About")
st.sidebar.text("This is Streamlit Tut")
# Header/Subheader
st.header("This is a header")
st.subheader("This is a subheader")
# Text
st.text("Hello Streamlit")
# Markdown
st.markdown("### This is... |
#!/usr/bin/env python
# coding: utf-8
import os
import time
import timeit
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from collections im... |
from django.conf import settings
from django import forms
from utils import generate_mailbox_name
class EmailForm(forms.Form):
id = forms.IntegerField(required=False, widget=forms.HiddenInput)
#email_address = ReadOnlyField()
email_address = forms.EmailField()
email_address_prev = forms.EmailField(req... |
import unittest
from webcamlib.Config import Config
from webcamlib.SendAlert import SendAlert
import logging
import os
"""
"unit" test (more of a functional test) to make sure the Sending SMS works
"""
class TestSendSMSMethods(unittest.TestCase):
def setUp(self):
self.config = Config('../config.json')
... |
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as f
from torch.autograd import Variable
import torch.nn.functional as F
class DSRMM(nn.Module):
def __init__(self, args):
""""Constructor of the class."""
super(DSRMM, self).__init__()
self.wv=args.wv
... |
from typing import Any
from fastapi import APIRouter
from fastapi import Depends
from fastapi import status
from sitreps_server import crud
from sitreps_server import schemas
from sqlalchemy.orm import Session
from .deps import get_db
router = APIRouter()
@router.get("/")
def read_code_coverage(
db: Session = ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.clarinet.loss import gaussian_loss, KL_gaussians
import numpy as np
import math
class Conv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, dilation=1, causal=False, mode='SAME'):
super(Conv, self).__init_... |
class Warrior:
def __init__(self, name, weapon):
'实例化时自动调用'
self.name = name
self.weapon = weapon
def speak(self, words):
print("I'm %s, %s" % (self.name, words))
def show_me(self):
print("我是%s, 我是一个战士" % self.name)
if __name__ == '__main__':
gy = Warrior('关羽',... |
from pymoo.model.problem import Problem
class MyProblem(Problem):
def __init__(self):
super().__init__(n_var=1, n_obj=2, n_constr=0, elementwise_evaluation=True)
def _evaluate(self, x, out, *args, **kwargs):
# print("Evaluation")
s = x[0]
s.eval_fitness()
# print(s.fi... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 10 08:45:03 2020
@author: 一叶之秋
"""
import numpy as np
from fawkes.utils import extractor_ls_predict
from fawkes.utils import pairwise_l2_distance
####这里的loaded_images必须进行归一化处理
def compute_points(loaded_images,feature_extractors_ls):
points = np.ze... |
#!/usr/bin/env python
import unittest
import mock
from datetime import datetime
from aws_saml_auth import amazon
from aws_saml_auth import configuration
from os import path
import os
class TestAmazon(unittest.TestCase):
@property
def valid_config(self):
return configuration.Configuration(
... |
#-----------------------------------------------------------------------------------------------------------------------
#Introdução a Programação de Computadores - IPC
#Universidade do Estado do Amazonas - UEA
#Prof. Jucimar Jr.
#Alexandre Marques Uchôa 1715310028
#Jandinne Duarte de Oliveira 1... |
from spike import PrimeHub, LightMatrix, Button, StatusLight, ForceSensor, MotionSensor, Speaker, ColorSensor, App, DistanceSensor, Motor, MotorPair
from spike.control import wait_for_seconds, wait_until, Timer
from math import *
from spike import DistanceSensor
hub = PrimeHub()
distance_sensor = DistanceSensor('C')
... |
def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
print("Let's do some math with just fu... |
# Quals 2009
# Problem B: Watersheds
# Jon Hanson
#
# Declare Variables
#
ifile = 'input.txt'
ofile = 'output.txt'
caselist = []
#
#
#
class CaseMap(object):
def __init__(self,height,width,alts):
self.h = height
self.w = width
self.imap = alts
def printCase(self):
print(str(se... |
"""
Helpers for running tests with `pytest`.
"""
import os
from pathlib import Path
import pytest
from dcos_e2e.backends import ClusterBackend, Docker
@pytest.fixture(scope='session')
def cluster_backend() -> ClusterBackend:
"""
Return a cluster backend to use.
"""
return Docker()
@pytest.fixture(... |
# -*- coding:utf-8 -*-
# Copyright 2018 Huawei Technologies Co.,Ltd.
#
# 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... |
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import sys
import ctypes
import math
import numpy
from pyscf import lib
libfci = lib.load_library('libfci')
def gen_strings4orblist(orb_list, nelec):
'''Generate string from the given orbital list.
Returns:
list of int64. One int... |
"""
This file offers the methods to automatically retrieve the graph Kinetoplastibacterium galatii.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetim... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the BAM Windows Registry plugin."""
from __future__ import unicode_literals
import unittest
from dfdatetime import filetime as dfdatetime_filetime
from dfvfs.path import fake_path_spec
from dfwinreg import definitions as dfwinreg_definitions
from dfwinreg i... |
from Exercise_112.utilitiescev import Coin
from Exercise_112.utilitiescev import Data
r = Data.readmoney("Type a value: ")
Coin.resume(r, 80, 35)
|
#!/home/claudbae/Documents/awardus/virtual/bin/python
# When the django-admin.py deprecation ends, remove this script.
import warnings
from django.core import management
try:
from django.utils.deprecation import RemovedInDjango40Warning
except ImportError:
raise ImportError(
'django-admin.py was depre... |
import django
from fluent_faq.admin.base import FaqBaseModelAdmin
from fluent_faq.models import FaqQuestion
if django.VERSION >= (1, 8):
# get_all_field_names() was deprecated
_model_fields = [f.name for f in FaqQuestion._meta.get_fields()]
else:
# This also returns any _id fields, but that's not an issue ... |
#!/usr/bin/env python3
# Copyright (c) 2015-2019 The Luascoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test transaction signing using the signrawtransaction* RPCs."""
from test_framework.test_framework im... |
import unittest
from urwid.compat import B
from urwid.escape import str_util
class DecodeOneTest(unittest.TestCase):
def gwt(self, ch, exp_ord, exp_pos):
ch = B(ch)
o, pos = str_util.decode_one(ch,0)
assert o==exp_ord, " got:%r expected:%r" % (o, exp_ord)
assert pos==exp_pos, " go... |
"""
False positive heuristic filters that are shared across all plugin types.
This abstraction allows for development of later ML work, or further
heuristical determinations (e.g. word filter, entropy comparator).
"""
import re
import string
def is_found_with_aho_corasick(secret, automaton):
"""
:type secret:... |
'''
This is active only when deployed via UWSGI
'''
import logging, time, shutil, subprocess
from django.core import management
from biostar.utils.decorators import spool, timer
import time
logger = logging.getLogger("engine")
@timer(250)
def send_emails(*args ,**kwargs):
"""
Sends queued emails
"""
... |
##########################################################################
#
# Copyright 2008-2010 VMware, Inc.
# All Rights Reserved.
#
# 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 withou... |
# Copyright 2018 Google Inc. 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
#
# Unless required by applicable law or ... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
... |
import io
import sys
import traceback
from userbot.utils import admin_cmd
@borg.on(admin_cmd("exec"))
async def _(event):
if event.fwd_from:
return
await event.edit("Processing ...")
cmd = event.text.split(" ", maxsplit=1)[1]
reply_to_id = event.message.id
if event.reply_to_msg_id:
... |
# Copyright 2019, The TensorFlow Authors.
#
# 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 ... |
from . import fontgen, save
from .font import Font
from .icon import IconSet
from .kle import KleFile
from .layout import Layout
from .profile import Profile
class Context:
def __init__(self, name):
self.name = name
self.kle = None
self.font = None
self.icons = []
self.pro... |
import asyncio
import http
import typing
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import PlainTextResponse, Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class HTTPException(Exception):
def __init__(self, sta... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from re import search
from shutil import rmtree
from os import environ, path, makedirs, getenv, remove
from sublime import... |
# -*- coding: utf-8 -*-
module_list = [
"Apache-Solr",
"CMS",
"Drupal",
"F5",
"Fastjson",
"IIS",
"IOT",
"Jboss",
"Linux-local",
"Nexus",
"OA-System",
"Shiro",
"Spring",
"Struts2",
"Tomcat",
"WebFramework",
"Weblogic",
"Webmin",
"Windows",
... |
from __future__ import unicode_literals
from django.test import TestCase
class StartpageTest(TestCase):
def test_get(self):
response = self.client.get('/')
print(response)
self.assertEqual(response.status_code, 302)
class SimpleTest(TestCase):
def test_basic_addition(self):
... |
# -*- coding:utf-8 -*-
"""
什么是数据结构
--> 存储、组织数据的方式
数据的种类有很多:字符串、整数、浮点、...
组织各种数据的方式:即数据元素之间的关系
列表、字典、元组、...
数据的结构有两种形式:
物理形式:顺序表、链表
逻辑形式:集合、线性、树形、图形
"""
# 数据结构形式 : 物理➕逻辑
"""
物理形式:顺序表、链表
逻辑形式:集合、线性、树形、图形
"""
# 算法: --> 为了实现业务目的各种分析{方法和思路}
"""
算法复杂度:
时间复杂度:代码执行的时间
全称:渐近时间复杂度
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import json
import math
import os
import shutil
import sys
import time
from os.path import exists, join, split
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
... |
#!/usr/bin/env python
"""uwb_tracker_node.py: Streams tracked positions based on UWB multi-range messages."""
from __future__ import print_function
__author__ = "Benjamin Hepp"
__email__ = "benjamin.hepp@inf.ethz.ch"
__copyright__ = "Copyright 2016 Benjamin Hepp"
import select
import numpy as np
import... |
import bz2
from collections import deque, defaultdict
from logging import getLogger
import typing
import operator
import networkx
import requests
from pandas.io import json
from sortedcontainers import SortedList
from cachetools import LRUCache, cachedmethod, TTLCache
logger = getLogger(__name__)
def build_repod... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2012 OpenStack Foundation
# 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.... |
from datetime import date
from messaging.messaging_system import db
from messaging.models import DatabaseModel
from messaging.models.users import User
class Message(DatabaseModel):
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
sender = db.Column(db.ForeignKey(User.id), nullable=... |
from bot.decorators import error_handler
from bot.Cats_more_pages import MorePagesCats
import requests
URL_DOGS = 'https://izpriuta.ru/sobaki'
class MorePagesDogs: # The class for pages-parsing dogs
def __init__(self, url):
self.url = url
@error_handler
def parse_dogs(self):
html = requ... |
import sys
DEBUGGING = True
def start_debug():
if DEBUGGING is True:
PYDEV_SRC_DIR = "C:\pleiades\eclipse\plugins\org.python.pydev_4.5.3.201601211913\pysrc"
# 環境に応じて書き換えが必要
if PYDEV_SRC_DIR not in sys.path:
sys.path.append(PYDEV_SRC_DIR)
import pydevd
py... |
from typing import (
Tuple,
Union,
)
from eth_typing import (
Hash32,
)
from eth2.beacon.types.blocks import (
BaseBeaconBlock,
)
from eth2.beacon.typing import (
SlotNumber,
)
from trinity._utils.les import (
gen_request_id,
)
from trinity.protocol.common.exchanges import BaseExchange
from... |
from enum import Enum
class CollectionChangeAction(Enum):
ADD = 1
EXTEND = 2
REMOVE = 3
REVERSED = 4
CLEAR = 5
INDEX = 6
|
"""
Subpackage ``var`` has helping functions such as:
- image filtering,
- shapes extraction (annulus, squares subimages, circular apertures),
- 2d fitting (Gaussian, Moffat),
- wavelet transform definition,
- Q/U to Qphi/Uphi image conversion (for polarimetric data).
"""
from .coords import *
from .shapes import *
f... |
#!/usr/bin/env python
import math
import moviepy
import moviepy.editor
import numpy
import PIL
import PIL.Image
import PIL.ImageFont
import PIL.ImageDraw
intX = 32
intY = 436 - 64
objImages = [ {
'strFile': 'official - caffe.png',
'strText': 'official - Caffe'
}, {
'strFile': 'this - pytorch.png',
'strText': 'th... |
import torch.nn as nn
import torch.nn as nn
from foundations import hparams
from lottery.desc import LotteryDesc
from models import base
from pruning import sparse_global
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(base.Model):
"""Character-level CNN designed for text classif... |
import functools
import time
import json
from flask import (
Blueprint, request
)
from hiscore_server.db import (get_db, db_add_row, db_get_hiscore_data)
bp = Blueprint('hiscores', __name__, url_prefix='/hiscores')
@bp.route('/')
def hello_world():
return 'Hello, this is the Hi Scores Server!'
@bp.route('/li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.