id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3210657 | import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
import numpy as np
import os, cv2
import copy
import seaborn as sns
%matplotlib inline
def parse_annotation(ann_dir, img_dir, labels=[]):
'''
output:
- Each element of the train_image is a dictionary containing the annoation infoma... |
3210670 | import sys
class Env:
platform = None
is_linux = False
is_darwin = False
def __init__(self):
self._check_platform()
def _check_platform(self):
self.platform = sys.platform
if self.platform == 'linux':
self.is_linux = True
elif self.platform == 'darwin':... |
3210700 | import torch
import torch.nn.functional as F
import dgl
from dgl.nn import GraphConv, AvgPooling, MaxPooling
from utils import topk, get_batch_id
class SAGPool(torch.nn.Module):
"""The Self-Attention Pooling layer in paper
`Self Attention Graph Pooling <https://arxiv.org/pdf/1904.08082.pdf>`
Args:
... |
3210737 | from django.urls import path
from .views import *
urlpatterns = [
path('', InitiatePaymentView.as_view(), name='index'),
path('initiate/', InitiatePaymentView.as_view(), name='initiate'),
path('validate/', VerifyCheckoutView.as_view(), name='validate'),
path('status/<str:order_id>/', StatusCheckView.a... |
3210747 | from numpy import loadtxt, degrees, arcsin, arctan2, sort, unique, ones, zeros_like, array
from mpl_toolkits.basemap import Basemap
import reverse_geocoder as rg
import randomcolor
def domino(lol):
# Takes a list (length n) of lists (length 2)
# and returns a list of indices order,
# such that lol[order[i]... |
3210764 | import logging
import numpy as np
import hypothesis.strategies as hst
from hypothesis import HealthCheck, given, example, settings
from qcodes.dataset.measurements import Measurement
@given(n_points=hst.integers(min_value=1, max_value=100))
@example(n_points=5)
@settings(deadline=None, suppress_health_check=(Health... |
3210796 | import errno
import os
import sys
from contextlib import contextmanager
from cbfeeds import CbFeed, CbFeedInfo
from tempfile import NamedTemporaryFile
import logging
from logging.handlers import RotatingFileHandler
import time
class AlreadyRunningError(Exception):
pass
# TODO: investigate psutil package instead ... |
3210840 | import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
import warnings
from matplotlib import style
from collections import Counter
style.use('fivethirtyeight')
import pandas as pd
import random
benign_class = 2
malignant_class = 4
def k_nearest_neighbors(data,predict,k=3):
if len(data) >= k:
... |
3210847 | import os
import time
import requests
from tweepy.parsers import JSONParser
from tweepy.error import TweepError, RateLimitError, is_rate_limit_error_message
from tweepy.models import Status
MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json'
POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/... |
3210859 | from configargparse import ArgumentParser, ArgumentDefaultsHelpFormatter, \
YAMLConfigFileParser
import os
ENV_VAR_PREFIX = 'DOCTORINNA_'
def setup_args_parser() -> ArgumentParser:
parser = ArgumentParser(
auto_env_var_prefix=ENV_VAR_PREFIX,
default_config_files=['config.yml'],
confi... |
3210874 | from boa3.boa3 import Boa3
from boa3.exception import CompilerError, CompilerWarning
from boa3.model.type.type import Type
from boa3.neo.vm.opcode.Opcode import Opcode
from boa3.neo.vm.type.Integer import Integer
from boa3_test.tests.boa_test import BoaTest
from boa3_test.tests.test_classes.testengine import TestEngine... |
3210882 | import argparse
import numpy as np
from data_loader import load_data
from train import train
np.random.seed(555)
parser = argparse.ArgumentParser()
# movie
parser.add_argument('--dataset', type=str, default='movie', help='which dataset to use')
parser.add_argument('--n_epochs', type=int, default=20, help='the numbe... |
3210904 | import unittest
import numpy as np
import matplotlib.pyplot as plt
import lmfit
from pycqed.analysis.tools.plotting import SI_prefix_and_scale_factor
from pycqed.analysis.tools.plotting import set_xlabel, set_ylabel
from pycqed.analysis.tools.plotting import SI_val_to_msg_str
from pycqed.analysis.tools.plotting import... |
3210911 | import os
import shutil
import subprocess
print " "
print "==============================="
print "| Frostfall Release Builder |"
print "| \/ |"
print "| _\_\/\/_/_ |"
print "| _\_\/_/_ |"
print "| __/_/\_\__ |"
print "| / /\/\ \ ... |
3210914 | from setuptools import setup
setup(name='kfn',
version='0.1',
description='Kubeflow notebook component builder',
url='https://github.com/bartgras/kf-notebook-component',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['kfn', 'kfn.test'],
install_require... |
3210922 | import datetime
from django.urls import reverse
from systori.lib.testing import ClientTestCase
from ..project.factories import ProjectFactory
from .factories import JobFactory, GroupFactory, TaskFactory, LineItemFactory
from .models import Task, Job, ProgressReport, ExpendReport
from .views import JobCopy, JobPaste
... |
3210935 | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from time import sleep
from datetime import datetime
import random
import io
from django.core.cache import cache, caches
class Command(BaseCommand):
help = 'Health check push worker'
def handle(self, *args, **op... |
3210980 | import logging
from pathlib import Path
from decouple import config
from tenacity import retry_if_exception_type
from tenacity import wait_chain, wait_fixed, wait_random
from tenacity import stop_after_delay
from .utils import head_tail, choices, repeat
from .exceptions import RateLimitedError
from .utils import cas... |
3211026 | import os
import numpy as np
import pandas as pd
import random
seed = 10
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
train_transaction = pd.read_csv('../input/train_transaction.csv')
test_transaction = pd.read_csv('../input/test_transaction.csv')
train_transa... |
3211042 | from .cBugTranslation import cBugTranslation;
aoBugTranslations = [];
# OOBW@Stack (hide irrelevant frames only)
aoBugTranslations.append(cBugTranslation(
srzOriginalBugTypeId = r"OOBW:Stack",
azs0rbAppliesOnlyToTopStackFrame = [
rb".*!__security_check_cookie",
],
));
|
3211048 | from urllib import parse
from celery import shared_task, states
from celery.canvas import group
from django.conf import settings
from django.db import transaction
from extras.tasks import CurrentUserTaskMixin
from registry.models import CatalougeService, WebFeatureService, WebMapService
from registry.models.metadata i... |
3211050 | import os
import tensorflow as tf
import sys
sys.path.append(sys.argv[1])
from tensorflow_slurm_utils import tf_server_from_slurm
c, n, i = tf_server_from_slurm(ps_number=int(sys.argv[2]))
t = 0
if sys.argv[3] == 'True':
t += 1
if sys.argv[4] == 'True':
t += 1
if n == 'worker':
if t == 2:
if sys.a... |
3211096 | from libcloud.container.types import Provider
from libcloud.container.providers import get_driver
cls = get_driver(Provider.GKE)
conn = cls('<EMAIL>',
'libcloud.json', project='testproject')
conn.list_clusters()
|
3211101 | from .base import * # NOQA
from .factory import * # NOQA
def factory_for(*args, **kwargs):
return DriverFactory.factory(*args, **kwargs)
|
3211103 | import os
def data_dir():
"""
Returns the data directory that contains files for data and
documentation.
"""
return os.path.join(os.path.dirname(__file__), 'data')
def test_dir():
"""
Returns the data directory that contains example files for tests and
documentation.
"""
... |
3211105 | import uuid
from rest_framework.response import Response
from rest_framework.views import APIView
from test_project.api.serializers import ItemSerializer
from test_project.api.swagger.auto_schemas import post_item_auto_schema
class Items(APIView):
@post_item_auto_schema()
def post(self, request, version: in... |
3211149 | import os, csv, json, shutil
from data_tools.coco_tools import read_json
from PIL import Image
def reduce_data(oidata, catmid2name, keep_classes=[]):
"""
Reduce the amount of data by only keeping images that are in the classes we want.
:param oidata: oidata, as outputted by parse_open_images
:param ca... |
3211161 | from . import CppBindingGenerator as cbg
import ctypes
from .common import *
FFTWindow = cbg.Enum('Altseed2', 'FFTWindow')
with FFTWindow as enum:
enum.brief = cbg.Description()
enum.brief.add('ja', '音のスペクトル解析に使用する窓関数')
enum.add('Rectangular')
enum.add('Triangle')
enum.add('Hamming')
enum.add(... |
3211218 | from __future__ import absolute_import
from .keyexchangeexception import KeyExchangeException
from .missingkeyexception import MissingKeyException
|
3211270 | from autoflow.workflow.components.classification_base import AutoFlowClassificationAlgorithm
__all__=["GaussianNB"]
class GaussianNB(AutoFlowClassificationAlgorithm):
class__ = "GaussianNB"
module__ = "sklearn.naive_bayes"
OVR__ = True
|
3211272 | from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
class RemoteDebuggingNotEnabled(BaseResourceValueCheck):
def __init__(self):
name = "Ensure that remote debugging is not enabled for app servi... |
3211280 | from .method_in_imported_module import aa, hh
from .other_method_in_imported_module import CC, DD
def cc():
return aa(3)
#pythran export dd(int)
def dd(o):
return hh(o)
XX = cc() + [3]
YY = CC()
#pythran export bb()
def bb():
return XX, YY, DD()
|
3211309 | import datetime
import os
import time
import json
import requests
from api import Xuanke, Login
from django.http import HttpResponse
from info.models import Students
from mp.models import Config
from info.views import update_cookies
with open('config.json', mode='r', encoding='utf-8') as f:
config = json.loads(f.... |
3211318 | import bleach
from api import ALLOWED_TAGS, ALLOWED_ATTRIBUTES, ALLOWED_STYLES
# pylint: disable=W1402
def smart_unicode(s, encoding='utf8'):
""" Convert str to unicode. If s is unicode, return itself.
>>> smart_unicode('')
u''
>>> smart_unicode('abc')
u'abc'
>>> smart_unicode('\xe4\xbd\xa0\xe... |
3211354 | from ursina import *
import os, shutil
# import imageio # gets imported in convert_to_gif
class VideoRecorder(Entity):
def __init__(self, duration=5, name='untitled_video', **kwargs):
super().__init__()
self.recording = False
self.file_path = Path(application.asset_folder) / 'video_temp... |
3211372 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^re/$', views.re_home, name='re'),
url(r'', views.route, name='route'),
]
|
3211398 | from hrmachine import Machine, Letter
from hrmachine.utils import string_to_values
def test_string_to_values():
expected = [Letter.P, Letter.Y, Letter.T, Letter.H, Letter.O, Letter.N]
assert string_to_values('python') == expected
expected = [Letter.L, Letter.I, Letter.N, Letter.U, Letter.X, 0]
assert... |
3211403 | import argparse
import girder_worker
import os
import sys
def get_config(section, option):
return girder_worker.config.get(section, option)
def set_config(section, option, value):
if not girder_worker.config.has_section(section):
girder_worker.config.add_section(section)
girder_worker.config.set... |
3211455 | import matplotlib
matplotlib.use('Qt4Agg') # necessary for mac pls don't remove -- needs to be before pyplot is imported but after matplotlib is imported
from matplotlib import pyplot as plt
from PyQt4 import QtCore
import math, re, numpy as np
from Bio import Phylo
from ete3 import Tree, TreeNode
from cStringIO impor... |
3211458 | from typing import Optional
from . import BasicType
class ReplyKeyboardRemove(BasicType):
fields = {
'remove_keyboard': BasicType.bool_interpreter,
'selective': BasicType.bool_interpreter
}
def __init__(self, obj=None):
super(ReplyKeyboardRemove, self).__init__(obj)
@classme... |
3211480 | from functools import lru_cache
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.constants import LOOKUP_SEP
from treebeard.mp_tree import MP_Node
from wagtail.core import hooks
from wagtail.core.models import Page
from .field_adapters import adapter_registry
fr... |
3211528 | import subprocess
import textwrap
import socket
import vim
import sys
import os
import imp
from ui import DebugUI
from dbgp import DBGP
def vim_init():
'''put DBG specific keybindings here -- e.g F1, whatever'''
vim.command('ca dbg Dbg')
def vim_quit():
'''remove DBG specific keybindings'''
vim.comma... |
3211565 | sm.lockUI()
FANZY = 1500010
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.sendNext("#bBleh! I almost drowned!#k")
sm.setSpeakerID(FANZY)
sm.sendSay("There must be some kind of enchantment to keep people from swimming across.")
sm.flipDialoguePlayerAsSpeaker()
sm.sendSay("#bYou could have told me that ... |
3211581 | import datetime
import random
from factory import faker, fuzzy, SubFactory
from factory.django import DjangoModelFactory
from symposion.schedule.models import Schedule, Day, Slot, SlotKind
from symposion.conference.models import Section, Conference
from symposion.proposals.models import ProposalKind
class Conferenc... |
3211586 | from vkwave.bots import SimpleLongPollBot
from vkwave.bots.addons.class_based_handlers import BaseHandler
bot = SimpleLongPollBot(tokens="MyToken", group_id=123456789)
@bot.message_handler(bot.text_filter("привет"))
class HelloHandler(BaseHandler):
async def handle(self, event: bot.SimpleBotEvent) -> str:
... |
3211639 | from torch import nn
from ..layers import TFEncoder, TFDecoder
from ..utils.nn import LabelSmoothingLoss
from . import SimultaneousNMT
class SimultaneousTFNMT(SimultaneousNMT):
def __init__(self, opts):
"""
Creates a SimultaneousNMTTransformer.
:param opts: The options.
"""
... |
3211651 | from .chart import Chart
import plotly.express as px
class ScatterChart(Chart):
def __init__(self, dataframe, kwargs):
"""
Constructs all the necessary attributes for the ScatterChart object
Parameters:
dataframe (pandas.Dataframe): The dataframe
"""
Chart.__ini... |
3211698 | import torch
import torch.nn
import torch.nn.functional as F
from typing import Dict, Any
from dataclasses import dataclass
from ..common import separate_output_digits
from ..result import Result
from ..model_interface import ModelInterface
@dataclass
class TupleRunResult(Result):
reference_order: torch.Tensor
... |
3211769 | import os.path
import pytest
from Registry import Registry
@pytest.fixture
def hive():
path = os.path.join(os.path.dirname(__file__), "reg_samples", "issue22.hive")
return Registry.Registry(path)
|
3211779 | s = r"""
.a.fy
int dimension(10) target x
int dimension(:) pointer y
y => x[3:5]
"""
from fython.test import *
writer(s)
w = load('.a', force=1, release=1, verbose=0)
# print(open(w.module.url.fortran_path, 'r').read())
|
3211811 | import json
from textwrap import dedent
class TestAddHostAttr:
def test_no_args(self, host):
result = host.run('stack add host attr attr=test value=True')
assert result.rc == 255
assert result.stderr == dedent('''\
error - "host" argument is required
{host ...} {attr=string} {value=string} [shadow=boolea... |
3211847 | import sublime
import sublime_plugin
from related import *
class RelatedFilesCommand(sublime_plugin.WindowCommand):
def run(self, index=None):
active_file_path = self.__active_file_path()
if active_file_path:
# Builds a list of related files for the current open file.
self... |
3211853 | import argparse
import unittest
from unittest import mock
import tensorflow as tf
import numpy as np
import shared.utils as utils
from Inception_V3 import custom_baseline
from Inception_V3.custom_baseline import build_custom_model
class TestCustomInceptionV3Model(unittest.TestCase):
@classmethod
def setUpC... |
3211863 | from typing import Tuple
import numpy as np
from app.pipelines import Pipeline
class TextToSpeechPipeline(Pipeline):
def __init__(self, model_id: str):
# IMPLEMENT_THIS
# Preload all the elements you are going to need at inference.
# For instance your model, processors, tokenizer that mig... |
3211883 | from flask import Flask, render_template, request
import logging
import os
import json
import uuid
from utils.efetch_helper import EfetchHelper
from werkzeug.utils import secure_filename
DEFAULTS = {'index': '*'}
def create_app(elastic_url, cache_directory, max_file_size, plugins_file, default_path, debug):
"""Cr... |
3211892 | from django.db import models
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse
import socket
class Site(models.Model):
"""Records for sites that group capture nodes into geographical or logical units."""
name = models.SlugField(max_length=15, unique=True,
... |
3211910 | import torch
from registry import registry
from models.model_base import Model, StandardTransform, StandardNormalization
from mldb.utils import load_model_state_dict
model_params = {
'resnet18_ssl': { 'arch': 'resnet18',
'eval_batch_size': 256,
'img_crop_size': 224,
... |
3211924 | from os.path import devnull
from subprocess import Popen, PIPE
import pandas as pd
from ukbrest.common.utils.datagen import get_temp_file_name
def qctool(bgen_file, debug=False):
random_gen_file = get_temp_file_name('.gen')
with open(devnull, 'w') as devnull_file:
if not debug:
stderr_f... |
3211939 | dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
syncbn = True
data = dict(
videos_per_gpu=4, # total batch size is 8Gpus*4 == 32
workers_per_gpu=4,
train=dict(
type='CtPDataset',
data_source=dict(
type='JsonClsDataSource',
a... |
3211968 | from pyradioconfig.parts.ocelot.calculators.calc_agc import CALC_AGC_ocelot
class Calc_AGC_Bobcat(CALC_AGC_ocelot):
def calc_agc_misc(self, model):
super().calc_agc_misc(model)
#Enable peak detector freeze
self._reg_write(model.vars.AGC_CTRL4_FRZPKDEN, 1)
# MCUW_RADIO_CFG-1856: S... |
3212004 | import numpy as np
from math import log
class StateRelation(object):
"""
Abstract state relation object that contains the generally used atributes
in state relations (b,Dc).
Attributes
----------
b : float
Rate and state empirical parameter b.
Dc : float
Critical slip dista... |
3212019 | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Sum
from django.utils import timezone
from results.models import ResultManual
from results.slackbot import slackbot
from results.calculations import calculated_percent
def update_vote_percent(electiondate_arg):
## all... |
3212055 | import scipy
import scipy.sparse.linalg
import torch
import torch.nn as nn
from hodgeautograd import HodgeEigensystem
class HodgeNetModel(nn.Module):
"""Main HodgeNet model.
The model inputs a batch of meshes and outputs features per vertex or
pooled to faces or the entire mesh.
"""
def __init_... |
3212067 | import numpy as np
import cv2 as cv
import glob
import matplotlib.pyplot as plt
import sys
from PIL import Image
import argparse
import os
# convenience code to annotate calibration points by clicking
# python localization.py dataset/beach/map.png dataset/beach/calib_map.txt --click
if '--click' in sys.argv:
input... |
3212074 | import os
from sfaira.versions.metadata import CelltypeUniverse, OntologyCl, OntologyUberon
from sfaira.unit_tests import DIR_TEMP
"""
CelltypeUniverse
"""
def test_universe_io():
if not os.path.exists(DIR_TEMP):
os.mkdir(DIR_TEMP)
tmp_fn = os.path.join(DIR_TEMP, "universe_temp.csv")
targets = [... |
3212186 | import os
def testdata_path(path):
basepath = os.path.dirname(os.path.abspath(__file__))
return os.path.realpath(os.path.join(basepath, "testdata", path))
def get_filename(response):
content_disposition = response.headers.get("Content-Disposition")
if content_disposition:
parts = content_di... |
3212196 | import io
import pathlib
from abc import ABC, abstractclassmethod
class SerpentFile(ABC):
"""Most basic interface for a Serpent file
Parameters
----------
filename : str, optional
Helpful identifier for the source of data
Attributes
----------
filename : str or None
Name ... |
3212229 | import math
import numpy as np
print(math.__name__)
# math
print(np.__name__)
# numpy
import hello
print(hello.__name__)
# hello
hello.func()
# Hello!
# __name__ is hello
|
3212241 | import numpy as np
# how MSE works:
# Takes each predictions deviance from the actual value, squares it, then
# averages the squared values. The Gauss-Markov theorem guarantees that the
# solution to linear regression is the best in the sense that the
# coefficients have the smallest expected squared error.
def MSE(ta... |
3212260 | from distutils.core import setup
from setuptools import find_packages
setup(name='youtube_livechat_messages',
version='0.1.0',
description='Youtube LiveChatMessages API wrapper ',
author='uehara1414',
author_email='<EMAIL>',
url='https://github.com/uehara1414/youtube_livechat_messages',
... |
3212282 | from __future__ import print_function
import os
import sys
import multiprocessing
import time
import json
import uuid
import functools
import gzip
import vcr
import vcr.cassette
import vcr.errors
import vcr.serialize
import vcr.request
from flowy import restart
from flowy import wait
from flowy import TaskError
from ... |
3212285 | import os
from appdirs import user_data_dir
SETTINGS_FILE = os.path.join(user_data_dir("pipdownload", ""), "settings.json")
|
3212294 | import re
# Refreshes the iUI HTML documentation (iui_docs.html), regenerating it from the
# code comments in iui.js
def refresh():
# read in the comments from iui.js
iui_source = open('web-app/iui/iui.js')
comments_list = get_multiline_comments(iui_source.read())
comments_list = [convert_to_html(comment) f... |
3212376 | import atexit
import copy
import json
import logging
import os
import select
import signal
import subprocess
import sys
import threading
DEFAULT_OPTIONS = {
'formatid': 'gen7randombattle',
'p1': {
'name': 'p1',
},
'p2': {
'name': 'p2',
},
}
def _timeout():
sys.stderr.write('Timeout occurred while... |
3212394 | from .util import *
from .readers import *
from .filters import *
from .batches import *
from .graphics import *
from .validation import *
|
3212403 | import torch
import os
from utils import *
import numpy as np
def prune(model, compress_rate, criterion, optimizer, train_loader, test_loader, arch, save_dir, epochs,
layer_begin, layer_end, layer_inter, skip_downsample, learning_rate, lr_adjust, print_freq):
best_prec1 = 0
filename = os.path.join(save_dir, 'c... |
3212432 | import numpy as np
import pickle
class SMPLModel():
'''Simplified SMPL model. All pose-induced transformation is ignored. Also ignore beta.'''
def __init__(self, model_path):
with open(model_path, 'rb') as f:
params = pickle.load(f)
self.J_regressor = params['J_regressor']
... |
3212439 | from pymetamap import MetaMap
import csv
from flask import Flask, render_template, request, session, send_from_directory, g, redirect, url_for, abort, flash
import os
import json
# create the application object
app = Flask(__name__)
#when the user comes to the main page, send them to the home template
@app.route('/')... |
3212460 | import os
from unittest import TestCase
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tnsnames.aliasFinder import AliasFinder
from tnsnames.tnsnamesLexer import tnsnamesLexer
from tnsnames.tnsnamesParser import tnsnamesParser
__author__ = 'dirkfuchs'
class TestAliasFinder(TestCase):
_... |
3212476 | from jpype import *
from time import sleep
sleepInterval = 0.4
startJVM(getDefaultJVMPath(),
"-ea -cp .")
testPkg = JPackage('org').wg3i.test
Example = testPkg.Example
it = Example()
it.setVisible(True)
sleep(1)
it.clickOnButton()
sleep(1)
it.clickOnCheckBox()
sleep(1)
it.clickOnButton()
sleep(1)
it.cli... |
3212482 | from py_tests_common import *
def EnableIfDeclaration_Test0():
c_program_text= """
fn enable_if( true ) Foo() {}
"""
tests_lib.build_program( c_program_text )
def EnableIfDeclaration_Test1():
c_program_text= """
class C polymorph
{
fn virtual enable_if( true ) Foo( this ) {}
}
"""
tests_lib.build_p... |
3212589 | from datetime import timedelta
from sqlalchemy.sql import func
from flask import request
from zeus.api.utils import stats
from zeus.config import db
from zeus.models import Build, User
from zeus.utils import timezone
from .base import Resource
STAT_CHOICES = frozenset(
("builds.errored", "builds.total", "users.... |
3212614 | import torch
import torch.nn as nn
from torch.autograd import Variable
class ConvLSTMCell(nn.Module):
def __init__(self, input_channels, hidden_channels, kernel_size):
super(ConvLSTMCell, self).__init__()
assert hidden_channels % 2 == 0
self.input_channels = input_channels
self.h... |
3212631 | import torch
import torch.nn as nn
from networks.base.basenet import BaseNet
from networks.base.resnet import ResNet34
from networks.base.modules import Correlation, MatchingFeatRegression
class RelaPoseMNet(BaseNet):
def __init__(self, config):
print('Build up RelaPoseMNet model...')
super().__ini... |
3212665 | from datetime import datetime, timedelta
import pytz
from dateutil.parser import parse
def _parseDate(self, date):
#model '2017-12-01T12:00:00+00:00'
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+%Z").replace(tzinfo=pytz.utc)
print(pytz.timezone("UTC"))
startdate = "2018-06-21T09:36:03+02:00"
print(pars... |
3212675 | import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
from . import database
from .common import *
from .citationhunt import *
from .stats import *
from .leaderboard import *
from .intersections import *
fr... |
3212699 | from __future__ import unicode_literals
from nose.plugins.attrib import attr
from nose.tools import nottest
from mogwai.tests import BaseMogwaiTestCase
from mogwai._compat import PY2
from .base_tests import GraphPropertyBaseClassTestCase
from mogwai.properties.properties import DateTime, GraphProperty
from mogwai.model... |
3212735 | import sys
sys.path.append('../..')
import unittest
import numpy as np
import pandas as pd
from sklearn import linear_model
from ramp.estimators import (Probabilities,
BinaryProbabilities,
wrap_sklearn_like_estimator)
from ramp import shortcuts
from ramp.tests... |
3212767 | from arm.logicnode.arm_nodes import *
class RandomColorNode(ArmLogicTreeNode):
"""Generates a random color."""
bl_idname = 'LNRandomColorNode'
bl_label = 'Random Color'
arm_version = 1
def arm_init(self, context):
self.add_output('ArmColorSocket', 'Color')
|
3212778 | import traceback
from django.conf import settings
from django.http import HttpResponse
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import exception_handler
def genericApiException(ex, engine=None):
msg = "No error data"
if not eng... |
3212821 | from LSP.plugin.core.typing import Tuple
from lsp_utils import NpmClientHandler
import os
def plugin_loaded():
LspBashPlugin.setup()
def plugin_unloaded():
LspBashPlugin.cleanup()
class LspBashPlugin(NpmClientHandler):
package_name = __package__
server_directory = "language-server"
server_bina... |
3212857 | import tensorflow as tf
def get_matched_features(features_a, features_b, sinkhorn_lambda, nr_sinkhorn_iter):
n = features_a.get_shape().as_list()[1]
fa_batch1, fa_batch2 = tf.split(features_a, 2, axis=0)
fb_batch1, fb_batch2 = tf.split(features_b, 2, axis=0)
# calculate all distances
dist_a1_a2 ... |
3212862 | from mock import MagicMock, patch
@patch("socket.socket")
def test_sendCommand(socket):
from paradrop.lib.misc.pdinstall import sendCommand
command = "install"
data = {
'sources': ["paradrop_0.1.0_all.snap"]
}
sock = MagicMock()
socket.return_value = sock
assert sendCommand(comm... |
3212906 | import unittest
from pyquante2 import rhf,basisset,h2,mp2
class test_mp2(unittest.TestCase):
def test_h2(self):
bfs = basisset(h2,'6-31g**')
solver=rhf(h2,bfs)
solver.converge()
nvirt = len(bfs)-h2.nocc()
emp2 = mp2(solver.i2,solver.orbs,solver.orbe,h2.nocc(),len(bfs)-h2.noc... |
3212924 | from typing import List
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
columns, rows = len(matrix[0]), len(matrix)
for column in range(columns - 1):
current = matrix[0][column]
for row in range(1, rows):
if column + row >= colum... |
3212952 | from PyObjCTools.TestSupport import *
from Foundation import *
class TestNSDateFormatter (TestCase):
def testOutput(self):
formatter = NSDateFormatter.alloc().init()
formatter.setDateFormat_("yyyy/mm/dd")
self.assertResultIsBOOL(NSDateFormatter.getObjectValue_forString_range_error_)
... |
3212964 | from __future__ import unicode_literals
import abc
import logging
import six
import semantic_version
from lymph.utils import observables, hash_id
from lymph.core.versioning import compatible, serialize_version
logger = logging.getLogger(__name__)
# Event types propagated by Service when instances change.
ADDED = '... |
3212972 | import pytest
def test_stringhash(string_hash):
assert string_hash.hash('abc') == 0
assert string_hash.hash('def') == 1
assert string_hash.hash('abc') == 0
def test_unhash(string_hash):
assert string_hash.unhash(string_hash.hash('abc')) == 'abc'
with pytest.raises(ValueError):
string_ha... |
3213035 | import nbformat
import sys
from nbconvert.preprocessors import ExecutePreprocessor
with open(sys.argv[1]) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600)
ep.preprocess(nb, {'metadata': {'path': 'tests/'}}) |
3213042 | from typing import Any, Dict, List, Union
import cryptomarket.args as args
from cryptomarket.websockets.client_auth import ClientAuth
class AccountClient(ClientAuth):
"""AccountClient connects via websocket to cryptomarket to get account information of the user. uses SHA256 as auth method and authenticates automa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.