id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1740381 | import json
from maestro_api.db.models.user import User, UserRole
from maestro_api.db.models.workspace import Workspace
def test_user_all(client):
name = "User 1"
email = "<EMAIL>"
workspace_ids = ["6076d1e3a216ff15b6e95e1f"]
role = UserRole.ADMIN.value
User(name=name, email=email, role=role, w... |
1740391 | import location_extractor
from re import findall, IGNORECASE
from .table import extract_locations_from_tables
from .webpage import extract_locations_from_webpage
# http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/
def find_ngrams(input_list, n):
return [" ".join(ngram) for ngram in zip(*... |
1740408 | import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject
from addonmanager import AddonManagerWindow
GObject.threads_init()
if __name__ == "__main__":
win = AddonManagerWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
|
1740413 | from django.apps import AppConfig
class AutoRacingScoreboardConfig(AppConfig):
name = 'auto_racing_scoreboard'
|
1740424 | from PyQt5.QtCore import Qt
vkeyToAndroidMaps = {
Qt.Key_Home: 'KEYCODE_HOME',
Qt.Key_Back: 'KEYCODE_BACK',
Qt.Key_Call: 'KEYCODE_CALL',
Qt.Key_ToggleCallHangup: 'KEYCODE_ENDCALL',
Qt.Key_0: 'KEYCODE_0',
Qt.Key_1: 'KEYCODE_1',
Qt.Key_2: 'KEYCODE_2',
Qt.Key_3: 'KEYCODE_3',
Qt.Key_4: ... |
1740467 | import os
import subprocess
import sys
# Check and install dependencies.
PYTHON_EXE_PATH = sys.executable
PYTHON_DIR_PATH = os.path.dirname(PYTHON_EXE_PATH)
def install_pip():
command = [PYTHON_EXE_PATH, "-m", "ensurepip", "--upgrade"]
subprocess.run(command)
def install_package(package_name):
comman... |
1740473 | import numpy as np
import os
from matplotlib import pyplot as plt
import tikzplotlib
def beautify(ax):
ax.set_frame_on(True)
ax.minorticks_on()
ax.grid(True)
ax.grid(linestyle=':')
ax.tick_params(which='both', direction='in',
bottom=True, labelbottom=True,
... |
1740509 | from flask import Flask
from flask_cors import CORS
from util.encoder import JSONEncoder
from werkzeug.contrib.fixers import ProxyFix
from config import settings
class MyFlask(Flask):
def get_send_file_max_age(self, name):
# This disables caching for static js and css files,
# which is helpful fo... |
1740511 | import io
from . import *
@beast.on(beastx_cmd("json"))
async def _(event):
if event.fwd_from:
return
the_real_message = None
reply_to_id = None
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
the_real_message = previous_message.string... |
1740512 | from pyramid.renderers import JSON
from restful_auto_service.renderers.abstract_renderer import RendererAbstractBase
class JSONRendererFactory(JSON, RendererAbstractBase):
def can_serialize_value(self, value):
return True # how do we know?
|
1740525 | from lionhearted import settings
import os
import django
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lionhearted.settings")
django.setup()
from postmark.core import PMMail
from django.utils import timezone
from datetime import timedelta
from forum.models import *
from django.db.models import Max
from ... |
1740554 | import os
os.environ["KERAS_BACKEND"] = "tensorflow"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import time
import collections
import argparse
import numpy as np
import sklearn.neighbors
import tensorflow as tf
import keras
import dca_modpp.io
import Cell_BLAST as cb
import utils
N_EMPIRICAL = 10000
MAJORITY_THRESHOLD... |
1740595 | import sys
import py
from pypy.translator.test.snippet import try_raise_choose
from pypy.rlib.rarithmetic import r_uint, ovfcheck, ovfcheck_lshift
from pypy.rpython.test.test_exception import BaseTestException
from pypy.translator.llvm.test.runtest import *
class TestLLVMException(LLVMTest, BaseTestException):
de... |
1740643 | import os
import threading
class RunThread(threading.Thread):
def __init__(self, command):
super().__init__()
self.command = command
def run(self):
os.system(self.command)
|
1740646 | import unittest
import torch
class TensorTestCase(unittest.TestCase):
def assertTensorNotEqual(self, expected, actual):
equal = torch.equal(expected, actual)
if equal:
self.fail("Tensors did match but weren't supposed to: expected {},"
" actual {}.".format(expect... |
1740651 | from __future__ import print_function
# L1 Trigger DQM sequence (L1T)
#
# authors previous versions - see CVS
#
# <NAME> 2011-05-25 revised version of L1 Trigger DQM
import FWCore.ParameterSet.Config as cms
process = cms.Process("DQM")
#----------------------------
# Event Source
#
# for live online DQM in P5
... |
1740670 | import tensorflow as tf
import numpy as np
import logging
import logging.config
import time
from config import get_logging_config, args, evaluation_logfile, train_dir
from config import config as net_config
from paths import CKPT_ROOT
from utils import decode_bboxes, batch_iou
from skimage.transform import resize as ... |
1740675 | from __future__ import division, print_function, absolute_import
from scipy.stats import betabinom, hypergeom, bernoulli, boltzmann
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal, assert_allclose
def test_hypergeom_logpmf():
# symmetries test
# f(k,N,K,n) = f(n-k,N,N-K,n) = f(... |
1740680 | class AsyncSwitchStacks:
def __init__(self, session):
super().__init__()
self._session = session
async def getNetworkSwitchStacks(self, networkId: str):
"""
**List the switch stacks in a network**
https://developer.cisco.com/meraki/api/#!get-network-switch-stacks
... |
1740736 | import os
import pytest
import tempfile
import rastercube.io as io
import tests.utils as test_utils
@pytest.fixture()
def tempdir(request):
"""
This is a fixture that provides a prefix for the temporary directory
to use for scripts tests. This is useful to test both on fs and hdfs
http://doc.pytest.o... |
1740790 | import requests
from flask_restful import Resource
from flask import (
request,
g,
render_template,
redirect,
request,
url_for,
flash,
current_app,
Response,
)
from datetime import datetime
from ..models import User, Permission, login_manager
from flask_jwt_extended import create_acc... |
1740820 | import re
import unittest
from unittest.mock import patch
from click.testing import CliRunner
from tests.util import read_data, DETERMINISTIC_HEADER, skip_if_exception
try:
import blackd
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
except ImportError:
has_... |
1740828 | import re
from .cyrillic_letters_and_marks import cyrillic_letters_and_marks
from .latin_accent_chars import latin_accent_chars
from .valid_url_balanced_parens import valid_url_balanced_parens
from ..regex_supplant import regex_supplant
valid_url_path_ending_chars = regex_supplant(
re.compile(
r'[\+\-a-z#... |
1740869 | from PySide2.QtWidgets import QDialog, QLabel, QComboBox, QTableWidget, QTableWidgetItem, \
QDialogButtonBox, QGridLayout, QHeaderView, QAbstractItemView
from ..controller import BinsyncController
#
# MenuDialog Box for Binsync Actions
#
class MenuDialog(QDialog):
"""
The dialog shown when right clicki... |
1740875 | import logging
import subprocess
import tempfile
from aladdin.config import load_git_configs
from aladdin.lib.docker import DockerCommands, Tag
from aladdin.lib.git import Git
from aladdin.lib.k8s.helm import Helm
from aladdin.lib.utils import working_directory
from aladdin.lib.project_conf import ProjectConf
from ala... |
1740896 | from asposebarcode import Settings
from com.aspose.barcode import BarCodeBuilder
from com.aspose.barcode import Symbology
class CreatingPdf417Barcode:
def __init__(self):
dataDir = Settings.dataDir + 'WorkingWith2DBarcodes/Basic2DBarcodeFeatures/CreatingPdf417Barcode/'
# Instantiate barc... |
1740912 | import logging
from colorlog import ColoredFormatter
import os
from enum import Enum
import threading
"""
Common class for all NHD functions.
"""
class NHDCommon:
NHD_LOGFMT = '%(asctime)s.%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s'
NHD_DATEFMT = '%Y-%m-%d:%H:%M:%S'
NHD_LOGCOLOR = {... |
1740926 | import logging
from paip import logic
def main():
x = logic.Var('x')
y = logic.Var('y')
a = logic.Var('a')
more = logic.Var('more')
member_first = logic.Clause(
logic.Relation('member', (x, logic.Relation('pair', (x, more)))))
member_last = logic.Clause(
logic.Relation('member... |
1740936 | import inspect
# code from https://github.com/hartikainen/serializable/blob/master/serializable/serializable.py
class Serializable(object):
def __initialize(self, locals_):
if getattr(self, "_Serializable__initialized", False):
return
signature = inspect.signature(self.__init__)
... |
1740942 | from data_loaders.language_model_loader import LanguageModelLoader
from models.language_model import LanguageModel
from models.language_trainer import LanguageTrainer
from models.language_wrapper import LanguageWrapper
from helpers import constants
import torch
from helpers import torch_utils, utils
from torch.auto... |
1740961 | import os
import requests
from pymessenger2 import Element, QuickReply
from pymessenger2.buttons import URLButton, PostbackButton
from pymessenger2.bot import Bot
TOKEN = os.environ.get('TOKEN')
APP_SECRET = os.environ.get('APP_SECRET')
bot = Bot(TOKEN, app_secret=APP_SECRET)
recipient_id = os.environ.get('RECIPIEN... |
1740993 | import sys
import os
def compute_line_limits(w, rect):
'''For a line defined as ax + by + c = 0, find its two endpoints within the bounding box [x1, y1, x2, y2]'''
# First check the sign of the four points.
a, b, c = w
x1, y1, x2, y2 = rect
ax1 = a * x1
ax2 = a * x2
by1 = b * y1
by2 = ... |
1741007 | from unicorn.arm_const import *
from unicorn.unicorn_const import *
from ...util import crash
"""
Quick and unoptimized implementation of dynamic memory management allowing to
detect UAF, double free, heap overflow and some heap underflow issues.
"""
wilderness = 0xff000000
free_chunks = {}
allocated_chunks = {}
PAGE... |
1741044 | MV_FLAG = 4096 # Multi-value flag
PT_UNSPECIFIED = 0
PT_NULL = 1
PT_I2 = 2
PT_LONG = 3
PT_R4 = 4
PT_DOUBLE = 5
PT_CURRENCY = 6
PT_APPTIME = 7
PT_ERROR = 10
PT_BOOLEAN = 11
PT_OBJECT = 13
PT_I8 = 20
PT_STRING8 = 30
PT_UNICODE = 31
PT_SYSTIME = 64
PT_CLSID = 72
PT_BINARY = 258
PT_SHORT = PT_I2
PT_I4 = PT_LONG
PT_FLOAT... |
1741070 | import rabbitpy
message = rabbitpy.get(queue_name='mqtt-messages')
if message:
message.pprint(True)
message.ack()
else:
print('No message in queue')
|
1741197 | from django.urls import re_path
from jarbas.core.views import CompanyDetailView
app_name = 'core'
urlpatterns = [
re_path(
r'^company/(?P<cnpj>\d{14})/$',
CompanyDetailView.as_view(),
name='company-detail'
),
]
|
1741223 | from ..utils import load_pretrained
from .blocks import ResNet, ResNetBlock
__all__ = ['resnext50_32x4', 'resnext101_32x4', 'resnext101_32x8', 'resnext101_32x16',
'resnext101_32x32', 'resnext101_32x48', 'resnext101_64x4', 'resnext152']
META = {
'resnext50_32x4': ['resnext50_32x4.pth', 'https://drive.go... |
1741286 | from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import sys
import datetime
DEFAULT_PAGE_FILENAME = 'index.html'
SERVER_PORT = 8080
class HTTPHoneypot(BaseHTTPRequestHandler):
def __init__(self, *args):
with open(DEFAULT_PAGE_FILENAME, 'rb') as fi:
self.default_page = fi... |
1741320 | from abc import ABC
from enums.Language import Language
class TemplateModuleComponent(ABC):
def __init__(self, code=None, placeholder=None, trail=False):
self.placeholder = placeholder
self.__code = code
self.trail = trail
@property
def code(self):
if not self.trail:
... |
1741409 | import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("CondCore.CondDB.CondDB_cfi")
process.CondDB.connect = 'sqlite_file:blob.db'
process.source = cms.Source("EmptyIOVSource",
lastValue = cms.uint64(1),
timetype = cms.string('Run'),
firstValue = cms.uint64(1),
interval =... |
1741419 | dataset_type = 'NuScenesMonoDataset'
data_root = 'data/nuscenes/'
class_names = [
'car', 'truck', 'trailer', 'bus', 'construction_vehicle', 'bicycle',
'motorcycle', 'pedestrian', 'traffic_cone', 'barrier'
]
# Input modality for nuScenes dataset, this is consistent with the submission
# format which requires the... |
1741470 | from __future__ import print_function
""" The functions implemented here are standard benchmarks from literature. """
__author__ = '<NAME>, <EMAIL>'
from scipy import power, exp, cos, sqrt, rand, sin, floor, dot, ones, sign, randn, prod
from scipy.linalg import orth
from math import pi
from random import shuffle
fr... |
1741495 | from src.augmented_reality_service import AugmentedRealityService
if __name__ == "__main__":
# Starting AR Service
ar_service = AugmentedRealityService()
ar_service.set_service_parameter_json("data/aruco_params.json")
#ar_service.set_service_parameter_json("data/nft_params.json")
ar_service.run_... |
1741526 | import colorsys
import os
import time
import numpy as np
import tensorflow as tf
from PIL import ImageDraw, ImageFont
from tensorflow.keras.layers import Input, Lambda
from tensorflow.keras.models import Model
from nets.yolo import yolo_body
from utils.utils import cvtColor, get_classes, preprocess_input, ... |
1741530 | from theano import *
import theano.tensor as T
from theano import function
a = T.dscalar('a')
b = T.dscalar('b')
c = a + b
f = function([a, b], c)
print (f)
|
1741542 | from typing import Tuple, Union
import torch
from torch.nn.utils import clip_grad_norm_
from rl_algorithms.common.abstract.learner import TensorTuple
import rl_algorithms.common.helper_functions as common_utils
from rl_algorithms.ddpg.learner import DDPGLearner
from rl_algorithms.registry import LEARNERS
@LEARNERS.... |
1741557 | import unittest
from quasimodo.data_structures.generated_fact import GeneratedFact
from quasimodo.data_structures.multiple_source_occurrence import MultipleSourceOccurrence
class TestGeneratedFact(unittest.TestCase):
def test_fact_transformation(self):
gf = GeneratedFact("elephant", "eat", "zebra", "", ... |
1741584 | from django.urls import path, reverse_lazy
from . import views
from django.views.generic import TemplateView
# namespace:route_name
app_name='forums'
urlpatterns = [
path('', views.ForumListView.as_view(), name='all'),
path('forum/<int:pk>', views.ForumDetailView.as_view(), name='forum_detail'),
path('for... |
1741684 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.coal_miners import coal_miners
def test_coal_miners():
"""Test module coal_miners.py by downloading
coal_miners.csv and testing shape of
e... |
1741715 | import logging
import math
from libtbx import phil
from rstbx.array_family import (
flex, # required to load scitbx::af::shared<rstbx::Direction> to_python converter
)
from rstbx.dps_core import SimpleSamplerTool
from scitbx import matrix
from dials.algorithms.indexing import DialsIndexError
from .strategy impo... |
1741720 | import numba as nb
import numpy as np
@nb.jit(nopython=True)
def cob(result):
horizontal = [result[0]]
vertical = [result[0]]
for x in result[1:]:
horizontal.append(vertical[-1])
vertical.append(x)
horizontal.append(x)
vertical.append(x)
return horizontal, vertical
re... |
1741721 | import discord
class ListEmbed:
def __init__(self, title, description, author=None):
self.title = title
self.description = description
self.list_items = []
self.author = author
if self.author:
self.name = self.author.display_name
self.icon_url = auth... |
1741728 | import os
# Logstash settings
LOGSTASH_PORT = 1717
LOGSTASH_IP = "localhost"
# DB settings
DB_HOST = 'THE_API_ADDRESS_GOES_HERE'
DB_SECRET = 'THESECRETPASSPHRASEGOESHERE'
# RabbitMQ settings
RABBIT_USERNAME = os.environ['RABBIT_USERNAME']
RABBIT_PASSWORD = os.environ['RABBIT_PASSWORD']
RABBIT_ENDPOINT = os.environ['... |
1741768 | def setup_routes(app, handler, project_root):
router = app.router
h = handler
router.add_get('/', h.index, name='index')
router.add_post('/moderate', h.moderate, name='moderate')
router.add_static(
'/static/', path=str(project_root / 'static'),
name='static')
|
1741783 | import sys
sys.path.append("..")
from barry.config import setup
from barry.fitter import Fitter
from barry.models.test import TestModel
from barry.datasets.test import TestDataset
from barry.samplers import DynestySampler
if __name__ == "__main__":
pfn, dir_name, file = setup(__file__)
model = TestModel()
... |
1741814 | from pitop import Camera, Pitop
from pitop.labs import WebController
photobooth = Pitop()
photobooth.add_component(Camera())
def save_photo(data):
photobooth.camera.current_frame().save(f'{data["name"]}.jpg')
controller = WebController(
get_frame=photobooth.camera.get_frame, message_handlers={"save_photo":... |
1741873 | import torch
from tango.common.registrable import Registrable
class Optimizer(torch.optim.Optimizer, Registrable):
"""
A :class:`~tango.common.Registrable` version of a PyTorch
:class:`torch.optim.Optimizer`.
All `built-in PyTorch optimizers
<https://pytorch.org/docs/stable/optim.html#algorithms... |
1741885 | import spacy
from spacy.matcher import Matcher
nlp = spacy.load("de_core_news_sm")
matcher = Matcher(nlp.vocab)
doc = nlp(
"Zu den Features der App gehören ein wunderschönes farbenfrohes Design, "
"intelligente Suche, automatisierte Labels und Sprachsteuerung."
)
# Schreibe ein Pattern für ein Adjektiv, ein ... |
1741954 | from os import path
from setuptools import setup, find_packages
#this should hopefully allow us to have a more pypi friendly, always up to date readme
readMeDir = path.abspath(path.dirname(__file__))
with open(path.join(readMeDir, 'README.md'), encoding='utf-8') as readFile:
long_desc = readFile.read()
VERSION ... |
1741981 | import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
)
import pandas._testing as tm
def test_to_numpy(idx):
result = idx.to_numpy()
exp = idx.values
tm.assert_numpy_array_equal(result, exp)
def test_to_frame():
tuples = [(1, "one"), (1, "two"), (2... |
1741990 | import hashlib
import hmac
ALGORITHM_TO_DIGESTMOD = {
"null": "null", # Returns an empty digest; used for special key-id 0
"hmac-sha-1": "sha1", # HMAC-SHA-xxx(secret, payload) digest
"hmac-sha-224": "sha224",
"hmac-sha-256": "sha256",
"hmac-sha-384": "sha384",
"hmac-s... |
1741995 | import numpy as np
from PuzzleLib.Cuda.Utils import SharedArray, shareMemTest, randomTest
from PuzzleLib.Hip import Driver as HipDriver
class HipSharedArray(SharedArray):
GPUArray = HipDriver.GPUArray
def unittest():
from PuzzleLib.Hip import Backend
for deviceIdx in range(Backend.getDeviceCount()):
bnd = Ba... |
1742029 | from .utps import *
print('WARNING: the submodule algopy.utps is deprecated and tagged for removal!')
|
1742062 | class Team:
def setTeam(self,team):
self.team = team
def showTeam(self):
print(self.team)
class Tipe_Hero:
def setTipe(self,tipe):
self.tipe = tipe
def showTipe(self):
print(self.tipe)
class Hero(Team,Tipe_Hero):
def __init__(self,name,health):
self.name = name
self.health = health
Ucup = Hero... |
1742076 | import json
from rdr_service.config import GoogleCloudDatastoreConfigProvider
class ConfigClient:
def __init__(self, gcp_env):
self.gcp_env = gcp_env
def _get_config(self, config_root, config_key='current_config'):
config_data_str, _ = self.gcp_env.get_latest_config_from_bucket(config_root, ... |
1742112 | import optparse
import os
import shutil
import stat
import sys
import cx_Freeze
__all__ = ["main"]
USAGE = \
"""
%prog [options] [SCRIPT]
Freeze a Python script and all of its referenced modules to a base
executable which can then be distributed without requiring a Python
installation."""
VERSION = \
"""
%%prog %s... |
1742134 | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import QuerySetMiddleware
from mock import Mock
import json
class TestQuerySetMiddleware(TestCase):
def setUp(self):
self.middleware = QuerySetMiddleware()
self.request = Mock()
sel... |
1742176 | from django.apps import AppConfig
class CommentsXtdTestsConfig(AppConfig):
name = 'django_comments_tree.tests'
verbose_name = 'django-comments-tree tests'
|
1742190 | import sys
from dataclasses import asdict, dataclass
from functools import partial
from json import dumps as sdumps
import pytest
try:
from ujson import dumps as udumps
NO_UJSON = False
DEFAULT_DUMPS = udumps
except ModuleNotFoundError:
NO_UJSON = True
DEFAULT_DUMPS = partial(sdumps, separators... |
1742196 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
import numpy as np
class Covariance(nn.Module):
def __init__(self,
cov_type='norm',
remove_mean=True,
dimension_reduction=None,
input_dim=2048,
... |
1742212 | import FWCore.ParameterSet.Config as cms
EcalTrivialConditionRetriever = cms.ESSource("EcalTrivialConditionRetriever",
TotLumi = cms.untracked.double(0.0),
InstLumi = cms.untracked.double(0.0),
producedEcalChannelStatus = cms.untracked.bool(True),
producedEcalDQMTowerStatus = cms.untracked.bool(True),
... |
1742224 | from setuptools import find_packages, setup
install_requires = [
"Django>=1.11",
"cryptography",
"djangorestframework",
"pyjwt",
"requests",
]
docs_require = [
"sphinx>=1.4.0",
]
tests_require = [
"coverage[toml]==5.0.3",
"pytest==5.3.5",
"pytest-django==3.8.0",
"pytest-cov==2... |
1742250 | import angr
import simuvex
import cle
import os
import json
# imports for graph handling
import networkx as nx
from networkx.readwrite import json_graph
def generateCFG(binary, max_size, analysisType = 'Fast'):
response = {}
try:
# Create the angr project for the binary
project = angr.Project(... |
1742256 | from pyderman.util import github
import re
def get_url(version='latest', _os=None, _os_bit=None):
urls = github.find_links('mozilla', 'geckodriver', version)
for u in urls:
target = '%s%s.' % (_os, _os_bit) if _os != 'mac' else 'macos.'
if _os == 'mac-sur':
target = 'macos-aarch64.'
if target in u:
ver ... |
1742364 | from som.primitives.primitives import Primitives
from som.vmobjects.primitive import UnaryPrimitive
def _holder(rcvr):
return rcvr.get_holder()
def _signature(rcvr):
return rcvr.get_signature()
class InvokablePrimitivesBase(Primitives):
def install_primitives(self):
self._install_instance_prim... |
1742399 | def m(id, part = None):
"""
Provide any measure (that we know of) about this design. This acts as a
central registry for measures to not clutter the global namespace. "m" for "measure".
Most numbers can be adjusted, allowing customization beyond the rather simple parameters in
the OpenSCAD Customi... |
1742469 | import random
import os
import collections
import string
import shell
from hypothesis.database import ExampleDatabase
from hypothesis import given, settings, HealthCheck
from hypothesis.strategies import text, lists, composite, integers, randoms, sampled_from
from test_util import run, rm_whitespace, rm_whitespace, clo... |
1742472 | from load_data import Data
import numpy as np
import torch
import time
from collections import defaultdict
import argparse
import scipy.sparse as sp
from utils_NoGE import *
from model_NoGE import *
torch.manual_seed(1337)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.is_available... |
1742477 | import os
import math
import mxnet as mx
import numpy as np
# MXNET_CPU_WORKER_NTHREADS must be greater than 1 for custom op to work on CPU
os.environ['MXNET_CPU_WORKER_NTHREADS'] = '2'
class LSoftmaxOp(mx.operator.CustomOp):
'''LSoftmax from <Large-Margin Softmax Loss for Convolutional Neural Networks>
'''... |
1742479 | from setup_common import setup_waveflow
setup_waveflow(
name="waveflow_gpu",
install_requires=[
"tensorflow_gpu>=1.6.0"
]
)
|
1742521 | from setuptools import setup, find_packages
setup(
name='Flask-YouTube',
version='0.4',
license='MIT',
description='Flask extension to allow easy embedding of YouTube videos',
author='<NAME>',
author_email='<EMAIL>',
platforms='any',
install_requires=['Flask'],
packages=find_package... |
1742558 | class Solution:
def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
sm = sum(calories[:k])
points = (sm > upper) - (sm < lower)
for i in range(k, len(calories)):
sm += calories[i] - calories[i - k]
points += (sm > upper) - (sm < ... |
1742639 | from bokeh.models import Div
class VibroP_Message:
def __init__( self, Color = "red",
Size = 4,
FontStyle = "b",
MessageHeader = 'Message: ',
Width = 500,
Height = 20 ):
"""
The class represents a widget ba... |
1742642 | from arjuna import *
@test
def check_local_projopt(request):
assert C("local.projopt") == 1
@test
def check_linked_projopt(request):
assert C("linked1.projopt") == "linked1"
assert C("linked2.projopt") == "linked2"
@test
def check_linked1_projopt_overriden_linked2(request):
assert C("l1.projopt.over.... |
1742657 | import requests_mock
import json
from device_registry import app
def add_device(identifier, name, device_type, controller_name, room_identifier):
"""Helper function to post a new device to the registry and return the response."""
# Create a test client
with app.test_client() as c:
return c.post('... |
1742660 | import logging
from fastapi import APIRouter, Depends, Header
from starlette import status
from ...models.domains.files import FileDownloadOut
from ...modules.pennsieve import PennsieveApiClient
from ..dependencies.pennsieve import get_pennsieve_api_client
router = APIRouter()
log = logging.getLogger(__file__)
@ro... |
1742684 | import pytest
from xarray import DataArray
import scipy.stats as st
from numpy import (
argmin,
array,
concatenate,
dot,
exp,
eye,
kron,
nan,
reshape,
sqrt,
zeros,
)
from numpy.random import RandomState
from numpy.testing import assert_allclose, assert_array_equal
from pandas... |
1742705 | from django.db import models
class ListModel(models.Model):
company_name = models.CharField(max_length=255, verbose_name="Company Name")
company_city = models.CharField(max_length=255, verbose_name="Company City")
company_address = models.CharField(max_length=255, verbose_name="Company Address")
compan... |
1742722 | from .sensor_log import SensorLogService # noqa
from .sensor_stream import SensorStreamService # noqa
|
1742730 | import re
from html.parser import HTMLParser
from typing import Any, Dict, Iterator, List, Optional, Tuple
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.text.paragraph import Paragraph
from docx.text.run import Run
from tinycss2 import parse_declaration_li... |
1742739 | import json
import os
import shutil
import time
import pandas as pd
import numpy as np
import pathlib
import geopandas as gpd
import pysal as ps
from sklearn import cluster
from sklearn.preprocessing import scale
# Data reading & Processing
app_path = pathlib.Path(__file__).parent.resolve()
data_path = pathlib.Path(... |
1742745 | from django.contrib.auth import get_user_model
from ems_admin.forms import UserForm, SolitonUserEditForm
from ems_admin.models import AuditTrail
from ems_auth.models import SolitonUser
User = get_user_model()
def get_user(id) -> User:
user = User.objects.get(pk=id)
return user
def get_bound_user_form(user... |
1742758 | import demistomock as demisto
from GIBIncidentUpdateIncludingClosed import prevent_duplication
EXISTING_INCIDENT = [
{
"Contents": {
"total": 1,
"data": [
{"id": "1",
"gibid": "12v"}
]
}
}
]
INCOMING_INCIDENT = {"gibid": "12v... |
1742769 | from . import backslashes
from . import blank_lines
from . import builtins
from . import comments
from . import debugging
from . import declerations
from . import duplications
from . import imports
from . import indents
from . import mutables
from . import naming
from . import raise_exception
from . import single_quote... |
1742881 | import sys, os
import pandas as pd
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "winerama.settings")
import django
django.setup()
from django.contrib.auth.models import User
def save_user_from_row(user_row):
user = User()
user.id = user_row[0]
user.username = user_row[1]
user.save()
i... |
1742885 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
sys.path.append('utils')
import json
import numpy as np
from .utils.box import *
from .utils.draw import *
from .utils.infrastructure import *
from .utils.detbox import *
def save_results(re... |
1742901 | from pathlib import Path
import logging
def find_resource(res):
current = Path(__file__).parent
while True:
fp = current / res
if fp.exists():
logging.debug("Found {} at {}".format(res, fp))
return fp
current = current.parent |
1742946 | import heapq
import sys
si = sys.stdin.readline
n = int(si())
dy = [0] * (n + 2)
# 초기값 채우기
dy[1], dy[2] = 1, 2
# 점화식을 토대로 dy 배열 채우기
for i in range(3, n + 1):
dy[i] = (dy[i - 1] + dy[i - 2]) % 10007
print(dy[n])
|
1742957 | from django import forms
from django.shortcuts import render
from django.contrib.auth import get_user_model
from .decorators import superuser_required
from airmozilla.manage.forms import BaseForm
from airmozilla.main.models import (
Event,
SuggestedEvent,
EventEmail,
EventRevision,
EventAssignment,... |
1742970 | import requests
import sys
from pingdomlib.check import PingdomCheck
from pingdomlib.contact import PingdomContact
from pingdomlib.reports import PingdomEmailReport, PingdomSharedReport
server_address = 'https://api.pingdom.com'
api_version = '2.0'
class Pingdom(object):
"""Main connection object to interact wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.