text string | size int64 | token_count int64 |
|---|---|---|
import ustruct as struct
import sensor
import pyb
import ulogging as logging
logger = logging.Logger(__name__)
class Sensor:
"""A class that represent the Arduino-controlled sensors
Offers an interface for ultrasonics sensors and line sensors (IR).
"""
PIN = 2
SLAVE_ADDRESS = 0x10
def __i... | 4,342 | 1,365 |
from . import logging, config, proxy_fix, formats, request_id
from .flask_init import init_app, init_frontend_app, init_manager
import flask_featureflags
__version__ = '24.4.1'
| 179 | 61 |
from django.http import HttpResponse
from django.shortcuts import render, redirect
from models import User
from django.contrib.auth import authenticate, login
from django.conf import settings
from django.contrib.auth.decorators import login_required
def login(request):
username = request.POST['username']
password =... | 1,453 | 479 |
from .cart import receipt_col as receipt_collection
| 52 | 15 |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""A class for plotting results of the weighted wavelet z-transform analysis.
"""
import matplotlib.gridspec as gs
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator
import numpy as np
import os
import sys
__author__ = "Sebastian Kiehlmann"
__credits... | 14,662 | 4,191 |
"""Python utilities required to load data (image & their annotations) stored in numpy arrays.
Functions `load_numpy_arrays_single_output` & `load_numpy_arrays_emotions_age_only` are deprecated.
Use either the main function `load_data_from_numpy` to load all the applicable arrays
or the supporting `load_anno... | 7,651 | 2,683 |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright (c) 2017, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistrib... | 15,575 | 4,229 |
import sqlite3
import pandas as pd
import re
import random
from bs4 import BeautifulSoup
class Process:
SEQ_LENGTH = 40
sql_transaction = []
dataset = []
cursor_train = None
cursor_validation = None
cursor_test = None
# I know in advance that there are 199819620 rows
NUM_ROWS = 19... | 7,601 | 2,323 |
from .dataloader import PointsDataset, PointsDataLoader | 55 | 17 |
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^view/(?P<pk>[0-9]+)', views.ArticleDetailView.as_view(), name = "detail"),
#url(r'', views.ArticleIndexView.as_view(), name = "index"),
url(r'login', views.Login.as_view()),
url(r'logout', views.Logout.as_view()),
... | 445 | 178 |
"""
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
# setup path
import azlmbr.legacy.general as general
import azlmbr.bus as bus
import azlmbr.editor as editor
im... | 3,035 | 890 |
from dask.distributed import Client
import dask.dataframe as dd
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from IPython.display import display, HTML
from sklearn.cluster import KMeans... | 7,800 | 2,642 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'shen.bas'
__time__ = '2018-01-26'
"""
import pymysql
class SQLManager:
def __init__(self, dbCnfig):
self.DB_CONFIG = dbCnfig
self.conn = None
self.cursor = None
self.msg = ''
self.affect_rows = 0
if not self.connect():
exit(... | 1,756 | 862 |
#!/usr/bin/env python3
# encoding: utf-8
import torch.nn.functional as F
from rls.algorithms.single.dqn import DQN
from rls.common.decorator import iton
from rls.utils.torch_utils import n_step_return
class DDQN(DQN):
"""
Double DQN, https://arxiv.org/abs/1509.06461
Double DQN + LSTM, https... | 1,786 | 722 |
from typing import Tuple
def modular_division(a: int, b: int, n: int) -> int:
assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1
(d, t, s) = extend_gcd(n, a)
return x
def invert_modulo(a: int, n: int) -> int:
(b, x) = extend_euclid(a ,n)
if b < 0:
b = (b % n + n) % n
retur... | 1,394 | 600 |
import tensorflow as tf
from collections import OrderedDict
from arekit.contrib.networks.context.architectures.base.base import SingleInstanceNeuralNetwork
from arekit.contrib.networks.context.configurations.cnn import CNNConfig
from arekit.contrib.networks.tf_helpers import layers
class VanillaCNN(SingleInstanceNeur... | 5,373 | 1,607 |
#!/usr/bin/python3
import os
os.system('wget \
https://opendata.arcgis.com/datasets/6ac5e325468c4cb9b905f1728d6fbf0f_0.csv \
-O hifld_hospital.csv')
| 149 | 82 |
import argparse
import subprocess
import sys
import logging
logger = logging.getLogger("helper")
def azcli(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = process.communicate()
logger.debug(str(out,"utf-8"))
exit_code = process.returncode
if ... | 458 | 148 |
# 44. Wildcard Matching
#
# Implement wildcard pattern matching with support for '?' and '*'.
#
# '?' Matches any single character.
# '*' Matches any sequence of characters (including the empty sequence).
#
# The matching should cover the entire input string (not partial).
#
# The function prototype should be:
# bool i... | 1,622 | 532 |
"""Table for 200 and 100 oscillators with 100 units of energy"""
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def mult(n, r):
return math.factorial(n) / (math.factorial(r) * math.factorial(n-r))
nA = 200
nB = 100
qA = np.arange(0,101,1)
qB = np.arange(101, 0, -1)
... | 1,013 | 517 |
from Vertex import Vertex
import pygame
from Colours import Colours
class Grid:
def createGrid(self, rows, width):
grid = []
space = width // rows
for x in range(rows):
grid.append([])
for i in range(rows):
vertex = Vertex(space, rows, x, i... | 1,184 | 361 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown copyright. The Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are me... | 10,811 | 3,481 |
# pylint: disable=no-member, too-many-locals, no-self-use
"""Vessels File Upload """
import time
from flask import request
# from library.couch_database import CouchDatabase
from library.postgresql_queries import PostgreSQL
from library.couch_queries import Queries
from library.common import Common
from library... | 4,774 | 1,480 |
from .gcn import GCN, DenseGCN
from .gat import GAT
from .clustergcn import ClusterGCN
from .fastgcn import FastGCN
from .dagnn import DAGNN
from .pairnorm import *
from .simpgcn import SimPGCN
from .mlp import MLP
from .tagcn import TAGCN
from .appnp import APPNP, PPNP
# experimantal model
from .experimental.median_g... | 389 | 141 |
"""Test VIMS image module."""
from numpy.testing import assert_array_almost_equal as assert_array
from pytest import approx, fixture, raises
from pyvims import VIMS
from pyvims.errors import VIMSError
@fixture
def img_id():
"""Testing image ID."""
return '1731456416_1'
@fixture
def cube(img_id):
"""T... | 4,412 | 1,937 |
import tensorflow as tf
import numpy as np
from tqdm.notebook import tqdm
class System():
def __init__(self,
num_part,
dim,
Ansatz=None,
External=None,
Internal=None,
Sampler=None
):
self... | 4,239 | 1,463 |
#
# Copyright (c) 2013 Docker, 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 requir... | 8,819 | 2,495 |
class SchemaError(Exception):
def __init__(self, schema, code):
self.schema = schema
self.code = code
msg = schema.errors[code].format(**schema.__dict__)
super().__init__(msg)
class NoCurrentApp(Exception):
pass
class ConfigurationError(Exception):
pass
| 302 | 87 |
from setuptools import setup
setup(
name='torch-dimcheck',
version='0.0.1',
description='Dimensionality annotations for tensor parameters and return values',
packages=['torch_dimcheck'],
author='Michał Tyszkiewicz',
author_email='michal.tyszkiewicz@gmail.com',
)
| 288 | 92 |
#!/usr/bin/env python
from os import (
path as os_path,
mkdir as os_mkdir,
getcwd
)
from argparse import ArgumentParser
from logging import (
Logger,
getLogger
)
from glob import glob
from typing import (
Dict,
)
from colored import fg, bg, attr
from brs_utils import (
create_logger
)
from... | 5,050 | 1,751 |
# -*- coding: utf-8 -*-
# script
import wikilanguages_utils
from wikilanguages_utils import *
# time
import time
import datetime
from dateutil import relativedelta
import calendar
# system
import os
import sys
import shutil
import re
import random
import operator
# databases
import MySQLdb as mdb, MySQLdb.cursors as m... | 136,009 | 48,703 |
# -*- coding: utf-8 -*-
import unittest
import os
from io import StringIO, BytesIO
import h5py
from ribopy import Ribo
from ribopy import create
from ribopy.merge import merge_ribos
from ribopy.settings import *
from ribopy.core.exceptions import *
import sys
test_dir_1 = os.path.dirname(os.path.realpath(__file__))
... | 1,051 | 343 |
from django.urls import path
from rest_framework import routers
from task_management import viewsets
app_name = "task_management"
urlpatterns = [
]
task_router = routers.SimpleRouter()
task_router.register(r'tasks', viewsets.TasksViewSet, base_name='tasks') | 263 | 82 |
from .parsers import request_parser
| 36 | 10 |
import functools
import heapq
import logging
from collections import deque
from threading import Condition, RLock
from typing import Any, Callable, List, NamedTuple, Optional
from pytils.mixins import DaemonHandler
from ._config.time import DEFAULT_TIME_SUPPLIER, TimeSupplier, TimeType, ZERO_DURATION
__all__ = [
... | 4,698 | 1,508 |
import subprocess
import logging
logger = logging.getLogger(__name__)
# Run a command line command and returns stdout
def _run(command):
result = subprocess.run(command, check=True, stdout=subprocess.PIPE, text=True)
result.stdout = result.stdout[:-1]
return result.stdout
def is_playing():
result = subprocess.ru... | 1,473 | 519 |
"""Execute validated & constructed query on device.
Accepts input from front end application, validates the input and
returns errors if input is invalid. Passes validated parameters to
construct.py, which is used to build & run the Netmiko connections or
hyperglass-frr API calls, returns the output back to the front e... | 5,157 | 1,274 |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'GiftUi.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
###################... | 3,377 | 1,086 |
__author__ = "Wild Print"
__maintainer__ = __author__
__email__ = "telegram_coin_bot@rambler.ru"
__license__ = "MIT"
__version__ = "0.0.1"
__all__ = (
"__author__",
"__email__",
"__license__",
"__maintainer__",
"__version__",
)
| 251 | 111 |
import test_agent
print('Logging in')
Meerkat = test_agent.TestAgent(username='meerkat', password='12345678', endpoint='/messages/')
Pangolin = test_agent.TestAgent(username='pangolin', password='12345678', endpoint='/messages/')
Badger = test_agent.TestAgent(username='badger', password='12345678', endpoint='/messages... | 3,200 | 1,123 |
from django.urls import path
from .views import ContactListView
urlpatterns = [
path('', ContactListView.as_view()),
] | 123 | 35 |
from __future__ import absolute_import
from datetime import datetime
from sentry.integrations.github.utils import get_jwt
from sentry.integrations.client import ApiClient
class GitHubClientMixin(ApiClient):
allow_redirects = True
base_url = 'https://api.github.com'
def get_jwt(self):
return ge... | 4,610 | 1,382 |
TT_INT = 'INT' # int
TT_FLOAT = 'FLOAT' # float
TT_STRING = 'STRING' # string
TT_IDENTIFIER = 'IDENTIFIER' # 变量
TT_KEYWORD = 'KEYWORD' # 关键字
TT_PLUS = 'PLUS' # +
TT_MINUS = 'MINUS' # -
TT_MUL = 'MUL' # *
TT_DIV = 'DIV' # /
TT_POW = 'POW' # ^
TT_EQ = 'EQ' # =
TT_LPAREN = 'LPAREN' # (
TT_RPAREN = 'RPAREN' # ... | 1,504 | 711 |
import requests
import json
import pdb
import time
#url_string = "https://api.hooktheory.com/v1/trends/nodes?cp=1"
response = requests.get("https://api.hooktheory.com/v1/trends/nodes?cp=1", headers={'Authorization': "Bearer 0449bff346d2609ac119bfb7d290e9bb"})
hook_result = json.loads(response.text)
json_result = {}
ch... | 1,503 | 562 |
# -*- coding: utf-8 -*-
"""
GuidingCenter class definition
AUTHOR:
Kaan Ozturk <mkozturk@yahoo.com>
2016, Rice University
"""
import numpy as np
from scipy.integrate import ode
import pickle
import rapt.utils as ru
import rapt.flutils as rfu
from rapt import c, params, NonAdiabatic
class GuidingCenter:
... | 24,456 | 7,853 |
""" Unit tests for the HR solver. """
import pytest
from matching import Matching
from matching import Player as Resident
from matching.games import HospitalResident
from matching.players import Hospital
from .params import HOSPITAL_RESIDENT, make_game, make_prefs
@HOSPITAL_RESIDENT
def test_init(resident_names, h... | 5,835 | 1,818 |
import date
import os
def get_time_delta(kline_type = '1_day'):
if kline_type.lower() == '1_day'.lower():
return 0
kline_array = kline_type.split("_")
if len(kline_array) != 2:
raise ValueError('KLine_type {0} not supported'.format(kline_type))
if kline_array[1].lower() == 'min'.lower()... | 1,863 | 671 |
from collections import defaultdict
def check_winner(cards):
for card_index, card in cards.items():
for index in range(5):
complete_line = all([x[1] for x in card[index]])
complete_column = all([card[x][index][1] for x in range(5)])
if complete_line or complete_column:
... | 1,255 | 391 |
from djshed.constants import *
| 31 | 12 |
"""
Demonstrates the hover functionality of mpldatacursor as well as point labels
and a custom formatting function. Notice that overlapping points have both
labels displayed.
"""
import string
import matplotlib.pyplot as plt
import numpy as np
from mpldatacursor import datacursor
np.random.seed(1977)
x, y = np.random.... | 666 | 208 |
import torch
import torch.nn as nn
class FilterResponseNorm(nn.Module):
def __init__(self, num_features, eps=1e-6, use_TLU=True):
super(FilterResponseNorm, self).__init__()
self.num_features = num_features
self.eps = eps
self.use_TLU = use_TLU
self.weight = nn.Parameter(t... | 1,236 | 425 |
# coding=utf-8
# Copyright 2019 The Google AI Language Team 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 ... | 13,062 | 6,093 |
from flask import Flask
from flask_mongoengine import MongoEngine
from src.controllers.user_controller import UserController
db_host = {
'production': 'mongodb://localhost/posts',
'test': 'mongomock://localhost/posts'
}
def create_app(db_host_type: str = 'production') -> Flask:
"""Creates Flask app
A... | 1,018 | 332 |
import random
pc = random.randint(0, 10)
print('''Sou seu computador...
Acabei de pensar em um número entre 0 e 10.
Será que você consegue adivinhar qual foi?''')
player = int(input('Qual é seu palpite? '))
# print(pc, player)
tentativas = 1
while pc != player:
if pc > player:
print('Mais... Tente mais uma ... | 584 | 205 |
from django.template import Library, Node, TemplateSyntaxError
import re
from mumblr.entrytypes import EntryType
register = Library()
class LatestEntriesNode(Node):
def __init__(self, num, var_name):
self.num = int(num or 10)
self.var_name = var_name
def render(self, context):
con... | 985 | 336 |
from time import time
def profile(funcao):
def funcao_wrapper(*args, **kwargs):
inicio = time()
resultado = funcao(*args, **kwargs)
fim = time()
print(fim - inicio)
return resultado
return funcao_wrapper
@profile
def f(n):
return 'Executei f {}'.format(n)
print(f... | 448 | 167 |
#!/usr/bin/env python
# coding=utf-8
from subprocess import Popen, PIPE, check_output
p = 1
USERNAME = "sigurdkb"
IP = "172.16.0.30"
PORT = "445"
new_results = []
correct_pw = ""
cracked = bool(False)
counter = 0
guess_result = ((),)
pw = ''
def connect_smb():
global correct_pw
global cracked
global guess_result... | 1,040 | 443 |
import numpy as np
# import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans
# def plothist(x):
# vmin = x.min()-1
# vmax = x.max()+1
# bins = np.arange(vmin, vmax, (vmax - vmin)/50)
# plt.hist(x, bins=bins)
# plt.show()
# def scatterpred(pred):
# plt.scatter(pred[:,0], pred[:,1])
... | 2,819 | 1,216 |
from .universe import (
Universe,
Particle
)
from .probability import (
Probability
)
from .likelihood import (
Likelihood,
Normal,
Exponential,
LowerUpper,
Logistic,
GaussianMixture,
Relu
)
from .model import (
ModelDistances,
ModelImage,
ModelVolume,
Radius... | 1,378 | 491 |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 13:32:20 2021
#--- ag csv results to single file based on dashboard_dbs
#--- Murilo Vianna (murilodsv@gmail.com)
#--- Jul, 2021.
#--- Dev-log in: https://github.com/Murilodsv/py-jules
@author: muril
"""
# DEBUG import os; os.chdir('C:/Murilo/py-jules'... | 2,668 | 1,054 |
'''
Created on Oct 10, 2012
@author: Brian Jimenez-Garcia
@contact: brian.jimenez@bsc.es
'''
class Color:
def __init__(self, red=0., green=0., blue=0., alpha=1.0):
self.__red = red
self.__green = green
self.__blue = blue
self.__alpha = alpha
def get_rgba(self):
... | 1,294 | 696 |
import argparse
__author__ = 'aabulawi'
class PNCFormatter(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter):
def _expand_help(self, action):
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is argpar... | 917 | 255 |
from toee import *
def OnBeginSpellCast(spell):
print "Nimbus of Light OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Nimbus of Light OnSpellEffect"
spell.duration = 10 * s... | 775 | 288 |
# -*- coding: utf-8 -*-
import datetime
import pyBAScloudAPI as api
def printErrorHandler(exception, json):
print("\t\tException occured in request: ", exception, json)
print("Testing util functions.")
print("\t2021-04-26T10:56:58.000Z = ", api.Util.parseDateTimeString(dateTime="2021-04-26T10:56:58.000Z"))
... | 17,258 | 5,897 |
__COL_GOOD = '\033[32m'
__COL_FAIL = '\033[31m'
__COL_INFO = '\033[34m'
__COL_BOLD = '\033[1m'
__COL_ULIN = '\033[4m'
__COL_ENDC = '\033[0m'
def __TEST__(status, msg, color, args):
args = ", ".join([str(key)+'='+str(args[key]) for key in args.keys()])
if args:
args = "(" + args + ")"
return "[{colo... | 1,498 | 571 |
import cv2
import numpy as np
img = cv2.imread('./images/geometrics_input.png', cv2.IMREAD_GRAYSCALE)
rows, cols = img.shape
# It is used depth of cv2.CV_64F.
sobel_horizontal = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
# Kernel size can be: 1,3,5 or 7.
sobel_vertical = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)... | 604 | 299 |
"""
Instances of the Text class just contain
text. Their main use is as dummy-element
during model development.
"""
from dataclasses import dataclass
from dataladmetadatamodel.connector import ConnectedObject
@dataclass
class Text(ConnectedObject):
content: str
| 269 | 77 |
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from .registry import registry
from .services.webhook import process_webhook_event
__all__ = (
'WebhookView',
)
class WebhookView(APIView):
permission_classes = (AllowAny,)
... | 790 | 221 |
# Copyright 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.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | 161,798 | 47,865 |
from .pyfantasy import Connection
from .pyfantasy import League, Team, Player
from .yahoo_oauth import OAuth2
| 110 | 34 |
import os
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^django_amf_example/', include('django_amf_example.foo.urls')),
# Uncomment the admin/doc line below ... | 898 | 309 |
# coding: utf-8
"""
MolecularMatch MMPower
MMPower API # noqa: E501
OpenAPI spec version: 1.0.0
Contact: support@molecularmatch.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PrivateTrial(object):
"""NOTE: T... | 51,977 | 15,778 |
import argparse
import gym
import gym_module_select
from stable_baselines.common.vec_env import DummyVecEnv
def init_parse_argument():
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--num-exp', help='num experiment episode', type=int, default=10)
args = parser.parse_args()
return args
... | 1,174 | 393 |
"""
Funções (def) - *args **kwargs
"""
# def func(a1, a2, a3, a4, a5, nome=None, a6=None):
# print(a1, a2, a3, a4, a5, nome, a6)
def func(*args, **kwargs):
print(args, kwargs)
lista = [1, 2, 3, 4, 5]
func(*lista, nome='João')
| 238 | 121 |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Vincent Garonne, <vin... | 78,600 | 21,756 |
import os
import json
import requests
url = "https://api.digitalocean.com/v2/images?per_page=999"
headers = {"Authorization" : "Bearer " + os.environ['DIGITALOCEAN_ACCESS_TOKEN']}
r = requests.get(url, headers=headers)
distros = {}
for entry in r.json()["images"]:
s = "(" + str(entry["id"]) + ") " + entry["name"... | 574 | 205 |
"""
Custom integration to integrate Journey with Home Assistant.
For more details about this integration, please refer to
https://github.com/intrinseca/journey
"""
import asyncio
from dataclasses import dataclass
from datetime import timedelta
import logging
import math
from OSMPythonTools.nominatim import NominatimR... | 8,457 | 2,424 |
class Contract:
"""
Model class representing a Cisco ACI Contract
"""
def __init__(self, uid, name, dn):
self.uid = uid
self.name = name
self.dn = dn
def equals(self, con):
return self.dn == con.dn
| 251 | 84 |
#encoding: utf-8
import os
import re
from setuptools import setup, find_packages
# parse version from xdiff/__init__.py
with open(os.path.join(os.path.dirname(__file__), 'xdiff', '__init__.py')) as f:
version = re.compile(r"__version__\s+=\s+'(.*)'", re.I).match(f.read()).group(1)
with open('README.md') as f:
... | 1,015 | 340 |
a, b, n = map(int, input().split())
x = min(b - 1, n)
print(a * x // b - a * (x // b)) | 86 | 43 |
# 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 --------------------------------------------------------------
# If ex... | 2,790 | 790 |
import unittest
from flask_script import Manager, Shell, Server
from app import app, db
from app.fake_populate import populate
manager = Manager(app)
def make_shell_context():
return dict(app=app)
@manager.command
def recreate_db():
"""
Create the SQL database.
"""
db.drop_all()
db.create_all... | 1,193 | 372 |
"""Routes and URIs."""
def includeme(config):
"""Add routes and their URIs."""
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('about', '/about')
config.add_route('details', '/journal/{id:\d+}')
config.add_route('create', '/journal/... | 454 | 165 |
def find_metric_transformation_by_name(metric_transformations, metric_name):
for metric in metric_transformations:
if metric["metricName"] == metric_name:
return metric
def find_metric_transformation_by_namespace(metric_transformations, metric_namespace):
for metric in metric_transformatio... | 2,231 | 558 |
from configparser import ConfigParser
from .databases_config_mixin import get_configured_db_file_path
##################################################################################################
class EvaluationConfigMixin(object):
###########################################################################... | 1,840 | 457 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import DungeonViewSet, RoomViewSet
router = DefaultRouter()
router.register(r"dungeon", DungeonViewSet, basename="dungeon")
router.register(r"room", RoomViewSet, basename="room")
urlpatterns = [
path("", include(ro... | 334 | 102 |
from makememe.generator.prompts.prompt import Prompt
import datetime
from PIL import Image
from makememe.generator.design.image_manager import Image_Manager
class Waiting(Prompt):
name = "Waiting"
description = "waiting"
def __init__(self):
self.instruction = """
###
Message:I've been waiting for... | 1,761 | 551 |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# broadcastify
#------------------------------------------------------------
| 167 | 34 |
import ubermag
import logging
def check_levels(level=logging.WARNING, per_package=None):
packages = [
'discretisedfield',
'mag2exp',
'micromagneticdata',
'micromagneticmodel',
'micromagnetictests',
'oommfc',
'ubermagtable',
'ubermagutil',
]
... | 1,212 | 400 |
from python_helper import log, Test, SettingHelper, RandomHelper, ObjectHelper, TestHelper, ReflectionHelper, Constant
from python_framework import EncapsulateItWithGlobalException, GlobalException, ExceptionHandler, HttpStatus
LOG_HELPER_SETTINGS = {
log.LOG : False,
log.INFO : True,
log.SUCCESS : True,
... | 8,076 | 2,407 |
#-------------------------------------------------------------------------------
# TreeNeighbor
#-------------------------------------------------------------------------------
from PYB11Generator import *
from Neighbor import *
from NeighborAbstractMethods import *
@PYB11template("Dimension")
class TreeNeighbor(Neigh... | 4,007 | 1,069 |
from .base import GnuRecipe
class TkDiffRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(TkDiffRecipe, self).__init__(*args, **kwargs)
self.sha256 = '734bb417184c10072eb64e8d27424533' \
'8e41b7fdeff661b5ef30e89f3e3aa357'
self.name = 'tkdiff'
self.... | 656 | 260 |
from rest_framework import serializers
class HelloSerializer(serializers.Serializer):
"""Serializes a name field for testing out APIView"""
city_name = serializers.CharField(max_length=30)
| 199 | 54 |
import sys
import mock
sys.modules['yum'] = mock.MagicMock()
| 62 | 23 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-30 12:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0005_auto_20180330_1813'),
]
operations = [
... | 1,552 | 495 |
import json, base64
import logging, coloredlogs
import hashlib, copy
from flask_table import Table, Col
logger = logging.getLogger(__name__)
coloredlogs.install(level='INFO')
class Users:
def __init__(self):
self.__users = self.__load_users("json/users.json")
self.__generate_hash_keys()
de... | 2,854 | 845 |
# encoding=utf-8
from airtest.core.win import Windows
import unittest
import numpy
import time
from testconf import try_remove
SNAPSHOT = "win_snapshot.png"
class TestWin(unittest.TestCase):
@classmethod
def setUpClass(cls):
w = Windows()
w.start_app("calc")
time.sleep(1)
cl... | 841 | 304 |
# Import required libraries
import cv2
from os.path import os, dirname
import tensorflow as tf
import numpy as np
from tqdm import tqdm
import random
# List of categories (directories names)
CATEGORIES = ["bad_apple", "bad_grape", "bad_pear", "cherry", "good_apple", "good_avocado", "good_grape", "good_pear", "ripe_avo... | 2,382 | 799 |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# metrics namespaced under 'scylla'
SCYLLA_ALIEN = {
'scylla_alien_receive_batch_queue_length': 'alien.receive_batch_queue_length',
'scylla_alien_total_received_messages': 'alien.total_received_me... | 23,657 | 9,211 |
import logging
from types import MethodType
from urllib.parse import urljoin
import aiohttp
import requests
from json_encoder import json
from .exceptions import ActionNotFound, ActionURLMatchError
from .models import Request
from .request import make_request, make_async_request
logger = logging.getLogger(__name__)
... | 4,820 | 1,282 |