text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python3
""" api access for google sheets (and friends)
Usage:
googapis auth (sheets|docs|drive)... [options] [--drive-scope=<SCOPE>...]
Examples:
googapis auth sheets
Options:
--store-file=<PATH>... write to a specific store file
-n --readonly set the readonly scope
-... | 3,133 | 905 |
class Solution:
def findPermutation(self, s: str) -> List[int]:
ans = [i for i in range(1, len(s) + 2)]
# for each D* group (s[i..j]), reverse ans[i..j + 1]
i = -1
j = -1
def getNextIndex(c: chr, start: int) -> int:
for i in range(start, len(s)):
if s[i] == c:
return i
... | 517 | 214 |
from django.contrib import admin
# from models import PasswordReset
#
# class PasswordResetAdmin(admin.ModelAdmin):
# list_display = ["user", "temp_key", "timestamp", "reset"]
#
# admin.site.register(PasswordReset, PasswordResetAdmin)
| 242 | 70 |
"""
WayScript Errors
"""
class MissingCredentialsError(Exception):
"""Error thrown when a workspace integration does not have requisite credentials"""
pass
| 165 | 44 |
import numpy as np
from itertools import product
from tensorflow.keras.models import load_model
from sklearn.feature_selection import SelectKBest, f_regression
from joblib import load
import random as rnd
class Gridex:
def __init__(self, target, name, ext, feat, steps, th, adap = None):
print("GridEx -"... | 10,112 | 3,221 |
import xmltodict
from browsers import load_firefox
GOOGLE_SITEMAP_URL = "https://careers.google.com/jobs/sitemap"
def get_xml():
browser = load_firefox()
browser.get(GOOGLE_SITEMAP_URL)
jobs_data = xmltodict.parse(browser.page_source)
browser.quit()
return jobs_data
def get_jobs():
jobs_dat... | 630 | 217 |
# Testing Upload image feature
import tempfile
import os
from PIL import Image
# ----------------
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework import test
from rest_framework.test import APIClient
... | 9,162 | 2,984 |
import requests
from lxml import html
import os
import sys
sys.path.append("..")
header = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"}
def adafruitScrape(link):
link = link.strip()
response = requests.get(link,headers=head... | 1,666 | 579 |
import pdb
import subprocess
from functools import partial, wraps
from math import prod
from pathlib import Path
from pprint import pprint
from string import (
ascii_lowercase,
digits as ascii_digits,
)
from typing import Any, Callable, List, Iterable, Optional, Union
from toolz import ( # type: ignore
com... | 5,288 | 1,843 |
from abc import ABC, abstractmethod
class Abstract(ABC):
PRICE = 0
@abstractmethod
def __init__(self, name, age):
self.name = name
self.age = age
@abstractmethod
def show_name_capitalize(self):
return self.name.title()
@abstractmethod
def show_price(self):
... | 349 | 107 |
import npyscreen
import os
import getpass
import subprocess
class mainform(npyscreen.ActionForm):
def create(self):
self.OSPath = "/SYS64 3.7/"
self.full_path = os.getcwd()
self.CurrentPath = ""
self.dir_path = os.path.dirname(os.path.realpath(__file__))
opt_values = ["jdos... | 2,463 | 704 |
#!/usr/bin/python
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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... | 2,665 | 795 |
3# -*- coding: utf-8 -*-
"""
Created on Thu May 28 14:31:02 2020
@author: Lucas
"""
import random
acertos = 0
erros = 0
perguntas = 0
print("Programa educativo matematico")
print("""Digite a opção desejada
[1] para Soma
[2] para subtração
[3] para divisão
[4] para multiplicação""")
opção = int... | 3,209 | 1,194 |
# taken largely from https://github.com/ianvonseggern1/note-prediction
from pydub import AudioSegment
import pydub.scipy_effects
import numpy as np
import scipy
import matplotlib.pyplot as plt
from solo_generation_esac import *
from utils import frequency_spectrum, \
calculate_distance, \
classify_note_attemp... | 4,763 | 1,543 |
# Copyright 2021 The Trieste Contributors
#
# 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... | 2,720 | 929 |
# Generated by Django 2.1.2 on 2018-11-23 23:42
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
... | 1,558 | 429 |
from compas_cloud import Proxy
import time
print("\n starting a new Proxy and by default starts a server in background")
proxy = Proxy(background=True)
time.sleep(3)
print("\n restarting the background server and open a new one in a prompt console")
proxy.background = False
proxy.restart()
time.sleep(3)
print("\n ch... | 493 | 146 |
#-----------------SUPERMARKET MANAGEMENT SYSTEM--------------------
items = []
while True:
print('------------------Welcome to the supermarket------------------')
print('1. View items\n2. Add items for sale\n3. Purchase items\n4. Search items \n5. Edit items\n6. Exit')
choice = int(input('Enter the number o... | 3,871 | 915 |
"""Contains the links that can be downloaded."""
from hashlib import sha1
import logging
import os
from pathlib import Path
import re
import warnings
from bs4 import BeautifulSoup
from requests import Response
import unidecode
from vcm.core.exceptions import AlgorithmFailureError, MoodleError, ResponseError
from vcm.... | 23,993 | 6,676 |
def main():
import pipedef
pipe = pipedef.Pipeline()
# ============================== GLOBAL PROPERTIES =================================
# global pipeline config
pipe.config = {
'_pipeline:_edge': {'capacity': 5},
}
# ============================== INPUT FRAME LIST =============... | 7,472 | 2,332 |
from flask import Flask, request, render_template
import pandas as pd
import joblib
# Declare a Flask app
app = Flask(__name__)
def model_predict(i):
if i==1:
return "Normal"
else:
return "Abnormal"
@app.route('/', methods=['GET', 'POST'])
# Main function here
def main():
# If a form... | 1,918 | 665 |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('faq', views.faq, name='faq'),
path('account/me/password/', views.change_password, name='user-password'),
path('account/me/', views.view_user, name='user'),
path('account/<int:user_id... | 864 | 296 |
import unittest
from dcp.leetcode.str.find_and_replace import findReplaceString
class Test_FindAndReplace(unittest.TestCase):
def test_case1(self):
str_in = "jjievdtjfb"
indexes, sources, targets = [4,6,1], ["md","tjgb","jf"], ["foe","oov","e"]
actual = findReplaceString(str_in... | 424 | 142 |
import json
from abc import ABCMeta, abstractmethod
import six
from moto.sts.models import ACCOUNT_ID
@six.add_metaclass(ABCMeta)
class TestConfig:
"""Provides the interface to use for creating test configurations.
This class will provide the interface for what information will be
needed for the SageMa... | 5,606 | 1,574 |
#!/usr/bin/env python
# coding: utf-8
# # Virtual environments
# #### Attribution
#
# The conda virtual environment section of this guide
# was originally published at http://geohackweek.github.io/ under a CC-BY license
# and has been updated to reflect recent changes in conda,
# as well as modified slightly to fit ... | 22,904 | 6,332 |
import base64
import datetime, pytz
from re import X
import io
from matplotlib import pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from scipy import spatial
from skyfield.api import load, Star
from skyfield.projections import build_stereographic_projection
from ..astro.angdi... | 5,748 | 2,323 |
# 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Ent... | 884 | 234 |
from pipeline.pipeline import pipeline | 38 | 8 |
# - *- coding: utf- 8 - *-
from aiogram import Router
from tgbot.routers.user.user_menu import router_user_menu
# Подключение хендлеров для юзера
def setup_user_handlers(user_router: Router):
user_router.include_router(router_user_menu)
| 244 | 91 |
# -*- coding: utf-8 -*-
from .grammar import SchemaGrammar
class SQLiteSchemaGrammar(SchemaGrammar):
_modifiers = ['unsigned', 'nullable', 'default', 'increment']
_serials = ['big_integer', 'integer']
def compile_rename_column(self, blueprint, command, connection):
"""
Compile a rename... | 10,161 | 3,073 |
#
# PySNMP MIB module ASCEND-MIBVDSL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBVDSL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:28:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | 21,050 | 8,690 |
import time
print(time.time())
# DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
# print(time.clock())
print(time.process_time())
print(time.perf_counter())
| 262 | 82 |
import unittest
import strongr.clouddomain.model.gateways
import strongr.core
import strongr.core.domain.clouddomain
class TestInterDomainEvent(unittest.TestCase):
def test_salt_job_finished_escalation_to_inter(self):
intra_domain_event_factory = strongr.clouddomain.model.gateways.Gateways.intra_domain_e... | 857 | 270 |
#!/usr/bin/env python
'''
Sync markdown notes with an external folder like dropbox.
Notes will be named *.txt in the external folder and *.md in git.
The script will use proper git commands to do things such as, delete or add new files to git and reflect any git-side changes in the external folder.
This script is int... | 967 | 268 |
import abc
import logging
import zwoasi
from catkit.config import CONFIG_INI
import catkit.hardware.zwo.ZwoCamera
# Convert zwoasi module to a class such that it can be inherited.
ZwoASI = type("ZwoASI", (), zwoasi.__dict__)
class ZwoEmulator(ZwoASI):
""" Class to emulate of the zwoasi library. """
imple... | 3,706 | 1,157 |
# Copyright 2019 The FastEstimator 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
#
# Unless required by appl... | 2,371 | 701 |
from .test_config import EMPTY
from scripta import parse
from unittest import TestCase
class ParseTest(TestCase):
def test_parse(self):
actual = vars(parse.parse(['foo']))
expected = dict(EMPTY, sources=['foo'], svg='')
assert actual == expected
| 276 | 79 |
from pybithumb.core import *
from pandas import DataFrame
import pandas as pd
import datetime
import math
class Bithumb:
@staticmethod
def _convert_unit(unit):
try:
unit = math.floor(unit * 10000) / 10000
return unit
except:
return 0
... | 1,502 | 524 |
import struct
import zlib
from wrpg.piaf.common import (
header_structure,
file_entry_structure,
file_entry_size,
get_data_offset,
header_size,
header_check_size,
header_data_size)
class ParserError(Exception):
pass
class ParserMagicHeaderError(ParserError):
pass
class ParserCheck... | 2,959 | 885 |
# Generated by Django 3.0.5 on 2020-05-06 22:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0008_notificationmodel'),
]
operations = [
migrations.AlterField(
model_name='notificationmodel',
name='ent... | 384 | 124 |
import numpy as np
import cv2
img = cv2.imread('city2.jpg',0)
rows,cols = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('image cv2',dst)
cv2.waitKey(0)
# to save the image
# cv2.imwrite('image1.png',img)
cv2.destroyAllWindows()
| 301 | 139 |
# Copyright 2021, Peter Birch, mailto:peter@lightlogic.co.uk
#
# 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 l... | 1,160 | 357 |
#coding:utf-8
import pandas as pd
import matplotlib.pyplot as plt
import pyecharts.options as opts
from pyecharts.charts import Line
df = pd.read_csv(u'标普500市盈率历史数据.txt', sep='\t')
y = df['市盈率 (PE Ratio)']
plt.plot(y.values)
plt.show() | 239 | 116 |
import tensorflow as tf
import tensorflow.contrib.slim as slim
from util.util import *
def generator(inputs, scope='g_net',n_levels=2):
n, h, w, c = inputs.get_shape().as_list()
x_unwrap = []
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
with slim.arg_scope([slim.conv2d, slim.conv2d_transpos... | 3,510 | 1,314 |
import dataclasses
class RawCode(typing.NamedTuple):
lang: str
code: str
@dataclasses.dataclass
class TaskModel:
raw_task: RawTask
question: str
answer: str
gif_url: str
raw_codes: typing.List[RawCode]
input_data: str
output_data: str
| 298 | 116 |
from fit.messages import Message
from fit.types.extended import Sport, WorkoutCapabilities, MessageIndex, \
Intensity, WktStepTarget, WktStepDuration
from fit.types.general import UInt16, String, UInt32
class Workout(Message):
msg_type = 26
sport = Sport(4)
capabilities = WorkoutCapabilities(5)
n... | 781 | 280 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from fakebotdetector import __version__
def get_long_description():
"""Return the README"""
return open('README.md', 'r', encoding='utf8').read()
setup(
name='django-fake-bot-detector',
version=__version__,
url='https:/... | 1,335 | 398 |
/usr/lib64/python3.7/__future__.py | 34 | 18 |
from jnpr.junos import Device
from lxml import etree
dev = Device(host='xxxx', user='demo', password='demo123', gather_facts=False)
dev.open()
cnf = dev.rpc.get_config()
#cnf = dev.rpc.get_config(filter_xml=etree.XML('<configuration><interfaces/></configuration>'))
print etree.tostring(cnf)
| 294 | 109 |
ies = []
ies.append({ "iei" : "", "value" : "Selected NAS security algorithms", "type" : "security algorithms", "reference" : "9.9.3.23", "presence" : "M", "format" : "V", "length" : "1"})
ies.append({ "iei" : "", "value" : "NAS key set identifier", "type" : "key set identifier", "reference" : "9.9.3.21", "presence" : ... | 1,032 | 433 |
import sys
from hummingbot.core.api_throttler.data_types import RateLimit
# REST endpoints
BASE_PATH_URL = "https://api.kucoin.com"
PUBLIC_WS_DATA_PATH_URL = "/api/v1/bullet-public"
PRIVATE_WS_DATA_PATH_URL = "/api/v1/bullet-private"
TICKER_PRICE_CHANGE_PATH_URL = "/api/v1/market/allTickers"
EXCHANGE_INFO_PATH_URL = ... | 2,158 | 943 |
from PIL import Image
import numpy as np
from tqdm import tqdm
def histogram_equalization(x):
hist, bins = np.histogram(x.flatten(), 255, [0, 256])
cdf = hist.cumsum()
cdf_m = np.ma.masked_equal(cdf,0)
cdf_m = (cdf_m - cdf_m.min())*255.0/(cdf_m.max()-cdf_m.min())
cdf = np.ma.filled(cdf_m,0).astyp... | 3,586 | 1,573 |
import numpy as np
from models import SEM, clear_sem
from sklearn import metrics
import pandas as pd
from scipy.special import logsumexp
def logsumexp_mean(x):
return logsumexp(x) - np.log(len(x))
def batch_experiment(sem_kwargs, n_train=1400, n_test=600, progress_bar=True):
# define the graph structure for ... | 4,911 | 2,201 |
"""
The :mod:`mlshell.producers.dataset` contains examples of `Dataset` class for
empty data object creation and `DataProducer` class for filling it.
:class:`mlshell.Dataset` proposes unified interface to interact with underlying
data. Intended to be used in :class:`mlshell.Workflow`. For new data formats
no need to e... | 28,818 | 7,812 |
a, b = map(int, input().split())
print((a%b)*(b%a)+1) | 53 | 27 |
"""
this file contains tuned obs function and reward function
fix ttc calculate
"""
import math
import gym
import numpy as np
from smarts.core.agent import AgentSpec
from smarts.core.agent_interface import AgentInterface
from smarts.core.agent_interface import OGM, NeighborhoodVehicles
from smarts.core.controllers im... | 21,356 | 7,448 |
"""Test suite for optimizers.constant."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import ast
import pytest
from pycc.asttools import parse
from pycc.optimizers import constant
source = """
ONE = 1
TWO = 2
T... | 1,156 | 399 |
# -*- coding: utf-8 -*-
__author__ = 'alsbi'
from multiprocessing import Process
from websockify import WebSocketProxy
class Proxy():
port = {}
@classmethod
def get_port(cls,
uuid):
if uuid in Proxy.port:
return Proxy.port[uuid]
port = list(set(range(50000, ... | 2,079 | 613 |
from .massthings import MassThings
__red_end_user_data_statement__ = (
"This cog does not persistently store data or metadata about users."
# "<s>If you are using this cog, user data storage will probably be much less significant thing then API abuse</s>"
)
def setup(bot):
bot.add_cog(MassThings(bot))
| 318 | 99 |
# Copyright (c) 2010, individual contributors (see AUTHORS file)
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" ... | 1,528 | 559 |
# flake8: noqa
"""
Copyright 2021 - Present Okta, 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 at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in ... | 2,101 | 556 |
import discord
from discord.ext import commands
import json
from utils import error, RARITY_DICT
from parse_profile import get_profile_data
from extract_ids import extract_internal_names
# Create the master list!
from text_files.accessory_list import talisman_upgrades
# Get a list of all accessories
ACCESSORIES = []... | 3,203 | 989 |
import os
import cv2
from lib import lib
images_dir = "images"
faces_dir = "images/faces"
def main():
files = os.listdir(images_dir)
for file_name in files:
full_path = images_dir + "/" + file_name
if not os.path.isfile(full_path):
continue
print("Processing " + full_pa... | 725 | 266 |
"""
Google Sheets interaction lib. Configuration settings:
[gapps]
api_scope = https://www.googleapis.com/auth/spreadsheets
spreadsheet_id =
spreadsheet_range =
"""
import configparser
import traceback
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
#... | 1,806 | 542 |
import sys
import pandas as pd
from sqlalchemy import create_engine
import re
import numpy as np
import nltk
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from nltk import pos_tag, ne_chunk
nltk.download('punkt')
nltk.download('stopwords')
nl... | 5,142 | 1,574 |
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
def norm_ball(p):
step = np.pi/128
THETA = np.arange(0, 2*np.pi+step, step)
X = np.mat(np.zeros((2,len(THETA))))
for i, theta in enumerate(THETA):
x = (np.cos(theta), np.sin(theta))
a = (1/(np.abs(x[0])**p + np... | 976 | 457 |
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
import logging
import warnings
class Countries(APIClassTemplate):
"""
The Countries Object in the FMC.
"""
VALID_JSON_DATA = ["id", "name", "iso2", "iso3"]
VALID_FOR_KWARGS = VALID_JSON_DATA + []
URL_SUFFIX = "/object/countries"... | 1,170 | 368 |
def check_dependencies(settings):
pyver = sys.version_info[:2]
if pyver < PYTHON_2_MIN_VERSION or (3, 0) <= pyver < PYTHON_3_MIN_VERSION:
dependency_error("Python %s or %s+ is required." % (PYTHON_2_MIN_VERSION_STR, PYTHON_3_MIN_VERSION_STR))
if not is_exe_in_path("node"):
dependency_error("node (from NodeJS) wa... | 6,281 | 2,171 |
from fastapi import APIRouter, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from pathlib import Path
TEMPLATES = (
str(Path(__file__).resolve().parent.parent.parent.parent) + r"\design\templates"
)
templates_view = APIRouter()
templates = Jinja2Temp... | 525 | 165 |
# 002_movies.py
def migrate(migrator, database, fake=False, **kwargs):
# an example class for demonstrating CRUD...
migrator.sql("""CREATE TABLE movies(
id serial PRIMARY KEY NOT NULL,
created timestamp not null default CURRENT_TIMESTAMP,
modified timestamp not null default CURRENT_T... | 528 | 164 |
from torch import nn
from tqdm import tqdm
import math
from train.utils import get_batch, repackage_hidden
def train(model, criterion, optimizer, num_tokens, train_data, epoch_no, epochs,
batch_size=256, sequence_length=6):
# Turn on training mode which enables dropout.
assert num_tokens is not None... | 1,528 | 482 |
import web
if "__main__" == __name__:
u = "https://www.ebay.de/sch/Mobel-Wohnen/11700/i.html?_from=R40&LH_BIN=1&_nkw=kaffeetisch&_dcat=38205&rt=nc&_mPrRngCbx=1&_udlo=4&_udhi=29"
r = web.fetch(u)
print r.status_code
| 225 | 135 |
"""Day 24: Lobby layout
Coordinate system taken from
https://www.redblobgames.com/grids/hexagons/#coordinates
"""
from collections import defaultdict
from day23 import REAL_INPUT
from typing import Dict, List, Tuple
MOVES = {
"e": [1, -1, 0],
"w": [-1, 1, 0],
"se": [0, -1, 1],
"sw": [-1, 0, 1],
... | 4,961 | 1,991 |
# -*- coding: utf-8 -*-
from .reader import SteinerTreeProblem, Reader, ReaderORLibrary
from .graph import UndirectedWeightedGraph
from .graph import UndirectedWeightedGraph as UWGraph
from .graph import UndirectedWeightedGraph as Graph
from .graph import UndirectedGraph
from .graph import UndirectedGraph as UGra... | 464 | 150 |
"""create user table
Revision ID: 37881a97d680
Revises: d8f500d9168
Create Date: 2014-02-10 15:52:50.366173
"""
# revision identifiers, used by Alembic.
revision = '37881a97d680'
down_revision = 'd8f500d9168'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'users',
... | 840 | 334 |
# -*- coding: utf-8 -*-
import click
import logging
from pathlib import Path
#from dotenv import find_dotenv, load_dotenv
import pandas as pd
import tqdm
import numpy as np
#@click.command()
#@click.argument('input_filepath', type=click.Path(exists=True))
#@click.argument('output_filepath', type=click.Path())
def main... | 2,235 | 762 |
import asyncio
import time
import zmq
import zmq.asyncio
from pymunk import Vec2d
from zmq import Socket
from .constants import SERVER_TICK
from .events.events import PlayerEvent
from .events.movement import apply_movement
from .events.states import GameState, PlayerState
async def main():
future = asyncio.Futu... | 1,989 | 699 |
from django.conf.urls import include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path
import mds.apis.agency_api.v0_3.urls
import mds.authent.urls
urlpatterns = [
# TODO(hcauwelier) Backwards compat, to remove with MDS 0.3
path(
"mds/v0.... | 1,045 | 360 |
from cerberus import errors
from cerberus.tests import assert_fail, assert_success
def test_schema(validator):
field = 'a_dict'
subschema_field = 'address'
assert_success({field: {subschema_field: 'i live here', 'city': 'in my own town'}})
assert_fail(
schema={
field: {
... | 1,945 | 557 |
import logging
logger = logging.getLogger(__name__)
from .profiler import Profiler
from . import config, resnet
profiler = Profiler("classify.py")
import os
import cv2
import dlib
import numpy as np
import tensorflow as tf
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
profiler.... | 4,216 | 1,318 |
import unittest
class AddTests(unittest.TestCase):
def test_other_two_plus_one_is_three_passed(self):
print("checking 2 + 1")
self.assertEqual(3, 2 + 1)
def test_other_two_plus_two_is_five_failed(self):
print("checking 2 + 2")
self.assertEqual(5, 2 + 2)
@unittest.skip("Sk... | 478 | 183 |
import tensorflow as tf
import argument_sr
from os.path import join
from PIL import Image
import os
from numpy import array
"""
fliker image data by pil
"""
def pil_batch_queue():
lrs ,hr2s , hr4s = argument_sr.options.get_pil_file_list()
lrs = array(lrs)
hr2s = array(hr2s)
hr4s = array(hr4s)
... | 6,318 | 2,456 |
import logging
LOG_LEVELS = {
logging.NOTSET: 'sample',
logging.DEBUG: 'debug',
logging.INFO: 'info',
logging.WARNING: 'warning',
logging.ERROR: 'error',
logging.FATAL: 'fatal',
}
DEFAULT_LOG_LEVEL = 'error'
LOG_LEVELS_MAP = {v: k for k, v in LOG_LEVELS.items()}
LEVEL_LABELS = {
logging.N... | 483 | 189 |
import os
import logging
import re
from datetime import datetime
from stat import ST_CTIME
from zipfile import ZipFile
from dipper import config
from dipper.sources.Source import Source
from dipper.models.Model import Model
from dipper.models.assoc.InteractionAssoc import InteractionAssoc
from dipper.models.Dataset i... | 15,927 | 5,235 |
from .eLABJournalPager import *
class Experiments(eLABJournalPager):
pass | 80 | 27 |
from dataclasses import dataclass
from typing import Any, Sequence
@dataclass(eq=False, frozen=True)
class TextSegment:
text_id: str
segment_ref: Any
segment: Sequence[str]
is_sentence_start: bool
is_in_range: bool
is_range_start: bool
is_empty: bool
def __repr__(self) -> str:
... | 581 | 194 |
# -*- coding: utf-8 -*-
import os
import unittest
from StringIO import StringIO
from mimecat import (Catalogue, _canonicalize_extension,
_parse_file, _parse_line)
TEST_MIME_TYPES = """
# This file maps Internet media types to unique file extension(s).
# Although created for httpd, this file is us... | 10,084 | 3,297 |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"summary": "00_core.ipynb",
"plot": "00_core.ipynb",
"perf": "00_core.ipynb"}
modules = ["ks.py"]
doc_url = "https://JiaxiangBU.github.io/pyks/"
git_url = "https://github.com/fastai/pyks/... | 374 | 157 |
from __future__ import print_function
"""
Author: Emmanuel Salawu
Email: dr.emmanuel.salawu@gmail.com
Copyright 2016 Emmanuel Salawu
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 L... | 17,404 | 6,368 |
from tunepy2 import Genome
from tunepy2.interfaces import AbstractOptimizer, AbstractGenomeFactory, AbstractConvergenceCriterion
class BasicOptimizer(AbstractOptimizer):
"""
A very simple optimizer that builds new Genomes until convergence is satisfied.
"""
def __init__(
self,
... | 1,745 | 488 |
from copy import deepcopy
from .classic import ClassicGRN
import numpy as np
import tensorflow as tf
class GPUGRN(ClassicGRN):
def __init__(self):
pass
def reset(self):
self.concentration = np.ones(
len(self.identifiers)) * (1.0/len(self.identifiers))
self.tf_input_conc =... | 4,759 | 1,594 |
# modified for custom training and testing on GPU by Utkarsh Patel
from classifiers import AbstractTokenizedDocumentClassifier
from embeddings import WordEmbeddings
from nnclassifiers import StackedLSTMTokenizedDocumentClassifier, CNNTokenizedDocumentClassifier
from nnclassifiers_experimental import StructuredSelfAtte... | 10,892 | 3,250 |
import pytest
import numpy as np
from ardent.utilities import _validate_scalar_to_multi
from ardent.utilities import _validate_ndarray
from ardent.utilities import _validate_xyz_resolution
from ardent.utilities import _compute_axes
from ardent.utilities import _compute_coords
from ardent.utilities import _multiply_by... | 10,594 | 3,708 |
import requests, libvoikko, json, collections, sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
print("Need a url that points to a text file")
sys.exit(0)
r = requests.get(filename)
normalized = r.text.split()
v = libvoikko.Voikko("fi")
word_forms = [
(word, v.analyze(word)) for word in normal... | 1,550 | 587 |
from re import compile
IMPERSONAL_EXPRESSIONS = [
compile('^(\.*)nós[\s|\.|$]'),
compile('Nos\s| nos[\s|$]|-nos[\s|$]'),
compile('[N|(\.|\s)n]oss[a|o]'),
compile('\w*[e|a]mos[,|\.|\s|$]')
]
| 208 | 103 |
from .utils.compatibility import *
from .utils.der import parse, encodeConstructed, encodePrimitive, DerFieldType
from .utils.binary import hexFromByteString, byteStringFromHex, base64FromByteString, byteStringFromBase64
class Signature:
def __init__(self, r, s, recoveryId=None):
self.r = r
self.... | 1,648 | 497 |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... | 28,636 | 7,869 |
"""Main module."""
import asyncio
import logging
from pathlib import Path
from asynccpu import ProcessTaskPoolExecutor
from showroompodcast import CONFIG
from showroompodcast.archiving_task_manager import ArchivingTaskManager
from showroompodcast.showroom_archiver import TIME_TO_FORCE_TARMINATION, ShowroomArchiver
fr... | 1,691 | 511 |
# coding=utf-8
import requests
from PyQt5.QtCore import QThread, pyqtSignal
from urllib import request, parse
from utils import LogTools
sysLog = LogTools.SysLogs()
class Http:
signal = None # 括号里填写信号传递的参数
# init 初始化部分
def __init__(self):
self.signal = pyqtSignal(object)
# ===============... | 3,239 | 1,265 |
import re
import typing
import xml.etree.ElementTree as ET
from unicodedata import name
from typing import *
from jinja2 import Template
keylayout_file = 'keylayout_file'
keylayout_xml = keylayout_file + '.xml'
keylayout_html = keylayout_file + '.html'
TOFU = '\ufffd'
def mapindex_by_modifier(map_to_modifier: Dict[i... | 6,293 | 2,063 |