id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11558052 | import pytest
import numpy as np
from astropy.time import Time
from ..astropy import _checkTime
def test__checkTime():
# Create an array of epochs
times = np.linspace(59580, 59590, 100)
# Test that an error is raised when times are not
# an astropy time object
with pytest.raises(TypeError):
... |
11558074 | import os
import time
import glob
import pytest
import logging
import nbformat
import subprocess
from nbconvert.preprocessors import ExecutePreprocessor
logging.basicConfig(level=logging.INFO)
EXECUTE_NOTEBOOKS = []
AVOID_NOTEBOOKS = [
'docs/examples/advanced_use_cases/building_a_dashboard.ipynb',
'docs/exam... |
11558077 | from typing import *
from enum import Enum
class LanguageId(Enum):
Unknown = -1
Vernac = 1
Gallina = 2
Ltac = 3
Comment = 4
# code-mixed lids are only assigned on sentences but not tokens
LtacMixedWithGallina = 11
VernacMixedWithGallina = 12
def debug_repr(self) -> str:
... |
11558082 | import pathlib
import shutil
from abc import ABC, abstractmethod
from dataclasses import dataclass
from os import path
from jinja2 import Environment, PackageLoader
jinja = Environment(loader=PackageLoader("splashgen"), autoescape=False)
_assigned_component = None
class Component(ABC):
jinja = jinja
build... |
11558116 | from scrapy.http import Request, TextResponse
def mock_response(file_name=None, url=None):
"""
Create a fake Scrapy HTTP response
file_name can be a relative file path or the desired contents of the mock
"""
if not url:
url = 'http://www.ubc.ca'
request = Request(url=url)
if file_... |
11558181 | from __future__ import print_function
import os, time
from weeutil.weeutil import startOfInterval
interval = 195
os.environ['TZ'] = 'America/Los_Angeles'
time.tzset()
start_ts = time.mktime(time.strptime("2013-07-04 01:57:35", "%Y-%m-%d %H:%M:%S"))
print(start_ts)
rev = int(start_ts/interval)
start_ts = rev * interv... |
11558183 | import torch.nn as nn
import torchvision.models as models
from .helper import init, make_standard_block
class VGG(nn.Module):
def __init__(self, use_bn=True): # Original implementation doesn't use BN
super(VGG, self).__init__()
if use_bn:
vgg = models.vgg19(pretrained=True)
... |
11558218 | import time
import os
import math
import argparse
from glob import glob
from collections import OrderedDict
import random
import warnings
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import pandas as pd
import joblib
import cv2
import yaml
from lib.utils.vis i... |
11558219 | from builtins import object
class MockUtils(object):
class Placeholder(object):
def __init__(self):
self.args = None
self.kwargs = None
self.times = 0
@staticmethod
def raise_(exception):
raise exception
@staticmethod
def called_with(target, m... |
11558237 | import numpy as np
import pytest
import torch
import torch.nn.functional as F
from meddlr.ops.categorical import categorical_to_one_hot, logits_to_prob, one_hot_to_categorical
@pytest.mark.parametrize("use_numpy", [False, True])
def test_categorical_to_one_hot(use_numpy):
labels = torch.tensor([3, 0, 1, 0, 2, 0,... |
11558244 | import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from skimage.transform import rotate, AffineTransform, warp
from skimage.util import random_noise
from tensorflow.kera... |
11558292 | import re
from config.Config import Config
from engine.component.TemplateModuleComponent import TemplateModuleComponent
from enums.Language import Language
class DefineComponent(TemplateModuleComponent):
def __init__(self, code=None, language=Language.CPP):
placeholder = Config().get("PLACEHOLDERS", "DEF... |
11558297 | import pytest
from mach import exceptions, templates
@pytest.mark.parametrize(
"url, zone",
(
("https://api.labd.io", "labd.io"),
("https://api.test.mach-examples.net", "test.mach-examples.net"),
("api.test.mach-examples.net", "test.mach-examples.net"),
("http://api.test.mach-e... |
11558328 | from flask import Flask, render_template, redirect, url_for, request
from werkzeug.utils import secure_filename
import os
from aqg.app1 import Application
from aqg.utils.summarizer import TextSummarizer
from aqg.utils.pdfgenration import pdfgeneration
from aqg.utils.mail_agent import mail_agent as ma
from aqg.utils.pdf... |
11558348 | import itertools
from string import Template
import numpy as np
from PuzzleLib.Compiler.Codegen.Types import half_t, float_t
from PuzzleLib.Cuda.Utils import roundUpDiv
transformTmpl = Template("""
extern "C"
__global__ void transform2d$ext($T * __restrict__ dst, const $T * __restrict__ src, int dstOffset, int src... |
11558384 | class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
size = len(nums)
if size < 3:
return max(nums)
first = float('-inf')
second = float('-inf')
third = float('-inf')
for n in nums:
... |
11558387 | import os
import numpy as np
import pickle
import tensorflow as tf
def vgg_block(outputs, params, name, data_format, num_conv):
for i in range(num_conv):
layer_name = name + "_" + str(i + 1)
w = np.swapaxes(np.swapaxes(np.swapaxes(params[layer_name][0], 0, 3), 1, 2), 0, 1)
b = params[lay... |
11558430 | import argparse
import logging
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
def check_nans(df):
""" Auxiliary function for data wrangling logs """
n_rows = len(df)
check_df = {'col': [], 'dtype': [], 'nan_prc': []}
for col in df.columns:
check_d... |
11558445 | import json
import os
import platform
import sys
TESTING_BOX = os.path.exists('/etc/canvas/testing')
TESTING = 'test' in sys.argv
STAGING = os.path.exists('/etc/canvas/staging')
DRAWQUEST_ADMIN = os.path.exists('/etc/canvas/drawquest_admin')
DRAWQUEST_SEARCH = os.path.exists('/etc/canvas/drawquest_search')
PRODUCTION ... |
11558457 | from django.conf.urls.defaults import *
urlpatterns = patterns('examples.hello.views',
(r'^html/$', 'hello_html'),
(r'^text/$', 'hello_text'),
(r'^write/$', 'hello_write'),
(r'^metadata/$', 'metadata'),
(r'^getdata/$', 'get_data'),
(r'^postdata/$', 'post_data'),
)
|
11558476 | import numpy as np
import gym
from copy import deepcopy as copy
import tensorflow as tf
from abc import ABC, abstractmethod
import os
def single_elem_support(func):
"""aop func"""
type_list = (type([]), type(()), type(np.array(1)))
def wrapper(*args, **kwargs):
"""wrapper func"""
res = fu... |
11558528 | from .PackagerBase import PackagerBase
class PluginPackager(PackagerBase):
'''
Provides functionality for packaging an Unreal plugin.
'''
def __init__(self, root, version, archive='{name}-{version}-{platform}', strip_debug=False, strip_manifests=False, stage=[], verbose=True):
'''
Creates a new PluginPackage... |
11558536 | from django.urls import path, include
from . import views
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.logout_view, name='logout'),
path('', include('django.contrib.auth.urls')),
]
|
11558600 | import os
import vim
import time
import json
import ghost_log
import single_server
import vim_websocket_handler
_is_updating_from_remote = False
def start_server():
if not single_server.start_server():
return
for _ in range(3):
time.sleep(.1)
vim.command("let g:channel = ch_open('loca... |
11558609 | import emcee
import numpy as np
from robo.acquisition_functions.information_gain import InformationGain
class InformationGainPerUnitCost(InformationGain):
def __init__(self, model, cost_model,
lower, upper,
is_env_variable,
sampling_acquisition=None,
... |
11558623 | import argparse
import asyncio
import json
import logging
import os
from .bot import Bot
from .entity_manager import EntityManager
from .db import MongoDBConnector
from .discord import Client
from .sites import AtCoder, CodeChef, Codeforces, SiteContainer
logger = logging.getLogger(__name__)
DISCORD_TOKEN = os.envir... |
11558711 | import requests
import time
import re
from jinja2 import Environment, select_autoescape
from tqdm import trange
from bs4 import BeautifulSoup
DOMAIN = "https://www.resetera.com"
BASE_URL = DOMAIN + "/forums/video-games.7/page-{}"
HEADERS = {
'User-Agent': 'ResetERA user minimaxir',
}
MAX_PAGES = 1000
... |
11558737 | import copy
import logging
from bson.objectid import ObjectId
from flask import url_for
from flask_wtf import FlaskForm
from wtforms import SelectField, StringField
from scout.constants import CHROMOSOMES_38, EXPORT_HEADER
from scout.server.blueprints.variants.controllers import (
compounds_need_updating,
gen... |
11558757 | d = [{"a":2, "b":3}, {"c":2, "d":3}, {"e":2, "f":3}]
i = 2
vct = [10, 20, 30, 40]
vct[13] = 40
vct[1:i+1] = 40
i = 20
def test(k, v):
for u in range(0,k + 2,1):
if u+3==5:
u += 2*v
print("U==2:", u)
else:
u -= 1-v
print("U:", u)
while (v > 10):
... |
11558789 | import gym
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, Dense, Flatten, Lambda
class DQNNetwork(Model):
"""
Class for DQN model architecture.
"""
def __init__(self, num_actions: int, agent_history_length: int):
super(DQNNetwork, se... |
11558791 | import os
import shutil
from datetime import datetime
from tempfile import TemporaryDirectory
from unittest import TestCase
from hypothesis.strategies import (
dates, datetimes, dictionaries, fixed_dictionaries, lists, text
)
from hypothesis import assume, given
from stl.db import ARCHIVE_DT_FORMAT
from stl.db im... |
11558809 | import itertools
from typing import List
from bridgebots.deal import Card
from bridgebots.deal_enums import Direction, Rank, Suit
class RotationPermutation:
def __init__(self, suits: List[Suit]):
self.suits = suits
self.sorted_deck = [Card(suit, rank) for suit in suits for rank in Rank]
s... |
11558814 | import logging
class BaseConverter(object):
"""
BaseConverter to inherit new converters from. This is the preferred method to create support for new file-formats.
Please note, that you will need to implement the convert-method, which has to return a dictionary as specified.
You can pass additional (ar... |
11558839 | from fire.core import FireError
class CliError(FireError):
"""Exception used by the CLI when command cannot be executed."""
|
11558860 | import sys
IS_PY3 = sys.version_info[0] == 3
if IS_PY3:
from http.client import NO_CONTENT
from email import encoders as Encoders
from urllib.parse import quote, urlencode
unicode = str
bytes = bytes
else:
from email import Encoders
from httplib import NO_CONTENT
from urllib import quo... |
11558896 | import toolbox
import numpy as np
import pylab
#extract shot record
data, params = toolbox.initialise("prepro.su")
mask = data['fldr'] == 221
shot = data[mask].copy()
#agc
toolbox.agc(shot, None, **params)
params['primary'] = 'fldr'
params['secondary'] = 'tracf'
params['wiggle'] = True
toolbox.display(shot, **params)... |
11558911 | from io import StringIO
import pytest
from django.core.management import CommandError
from django.core.management import call_command
from pytest_mock import MockFixture
def test_should_call_start_processing(mocker: MockFixture):
mock_start_processing = mocker.patch("django_stomp.management.commands.pubsub.start... |
11558933 | import click
settings = dict(help_option_names=['-h', '--help'])
from .commands import init, install, ls, uninstall
@click.group(options_metavar='', subcommand_metavar='<command>', context_settings=settings)
def cli():
"""
Hi! This is a small command line tool called `pim` for making it easy to publish Python... |
11558937 | import os
import unittest
from unittest import mock
import tablib
from django.test import TestCase
from django.utils.encoding import force_str
from tablib.core import UnsupportedFormat
from import_export.formats import base_formats
class FormatTest(TestCase):
def setUp(self):
self.format = base_formats... |
11558957 | from abc import ABC
import numpy as np
import airsim
import gym
# from tasks import Shaping
from jsbsim_simulator import Simulation
from jsbsim_aircraft import Aircraft, cessna172P, ball, x8
from debug_utils import *
import jsbsim_properties as prp
from simple_pid import PID
from autopilot import X8Autopilot
... |
11558965 | import os, sys, subprocess, json, datetime
from shutil import copyfile
DEBUG = False
if len(sys.argv) != 3:
print("Usage: " + sys.argv[0] + " input_dir output_dir")
exit()
input_dir = sys.argv[1]
output_dir = sys.argv[2]
json_data = []
input_files = []
for file in os.listdir(input_dir):
if file.endswit... |
11558996 | import os
import argparse
from current_models import CURRENT_MODELS, MODEL_CAT_TO_GOOGLE_DIR
# 512 always performs best for our models.
max_sents = {128: 11, 256: 5, 384: 3, 512: 3}
# max_sents = {64: 23, 128:11, 256: 5, 384: 3, 512: 3}
bert_lrs = [1e-5, 2e-5]
task_lrs = [1e-4, 2e-4, 3e-4] #, 5e-4, 1e-3]
def get_conf... |
11559007 | import logging
import gluoncv as gcv
gcv.utils.check_version('0.8.0')
from gluoncv.auto.estimators import ImageClassificationEstimator
from gluoncv.auto.tasks.utils import config_to_nested
from d8.image_classification import Dataset
if __name__ == '__main__':
# specify hyperparameters
config = {
'da... |
11559023 | from alchemtest.gmx import load_expanded_ensemble_case_1
from alchemlyb.parsing.util import anyopen
def test_gzip():
"""Test that gzip reads .gz files in the correct (text) mode.
"""
dataset = load_expanded_ensemble_case_1()
for leg in dataset['data']:
for filename in dataset['data'][leg]:
... |
11559039 | import argparse
from bitstring import BitArray
from PIL import Image
argparser = argparse.ArgumentParser(description="Converts 24-bit BMP image to 8-bit RRRGGGBB pixels in COE format")
argparser.add_argument("INPUT", help="Input file path")
argparser.add_argument("OUTPUT", help="Output file path")
args = argparser.par... |
11559088 | from nox.lib import core, openflow, packet
from nox.lib.core import Component
from nox.lib.packet import ethernet, ipv4, dns
from nox.coreapps.pyrt.pycomponent import CONTINUE
from twisted.python import log
from collections import defaultdict
import curses
class DnsSpy(Component):
def __init__(self, ctxt):
... |
11559097 | import json
import requests
import urllib.parse
class RequestHandler(object):
def __init__(self, endpoint, api_key):
self.endpoint = endpoint
self.api_key = api_key
def __to_canonical_querystring(self, params):
canonical_querystring = ""
# parameters have to be sorted alphabet... |
11559126 | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
__all__ = [
'VGG', 'vgg16',
]
model_urls = {
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
}
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self... |
11559132 | from nltk.corpus.reader import CategorizedCorpusReader, ChunkedCorpusReader
from nltk.corpus.reader import ConllCorpusReader, ConllChunkCorpusReader
class CategorizedChunkedCorpusReader(CategorizedCorpusReader, ChunkedCorpusReader):
"""
A reader for chunked corpora whose documents are divided into categories
based ... |
11559142 | import os
# the token of the @CryptoCoinsInfoBot
TOKEN_BOT = 'put_here'
YOUR_TELEGRAM_ALIAS = 'put_here'
# do APIs requests with pause
TIME_INTERVAL = 3600
# old CoinMarketCap public API
# COINMARKET_API_URL_COINLIST = 'https://api.coinmarketcap.com/v1/ticker/?limit=0'
# new pro API
CMC_API_KEY = "put_here"
COINMA... |
11559143 | from .tensordict import TensorDict
from .tensorlist import TensorList
__all__ = [TensorDict, TensorList]
|
11559149 | from huobi.client.algo import AlgoClient
from huobi.constant import *
from huobi.utils import *
symbol_test = "adausdt"
account_id = g_account_id
algo_client = AlgoClient(api_key=g_api_key, secret_key=g_secret_key)
order_id = algo_client.create_order(symbol=symbol_test, account_id=account_id, order_side=OrderSide.BUY... |
11559163 | from __future__ import absolute_import, division, print_function
from .version import version as __version__
from .api import glue, read_notebook, read_notebooks
|
11559186 | import json
import sys
from tqdm import tqdm
from my.corenlp_interface import CoreNLPInterface
in_path = sys.argv[1]
out_path = sys.argv[2]
url = sys.argv[3]
port = int(sys.argv[4])
data = json.load(open(in_path, 'r'))
h = CoreNLPInterface(url, port)
def find_all(a_str, sub):
start = 0
while True:
... |
11559223 | from __future__ import division
from math import cos, sin, fabs, pi
from random import randint
from sfml import sf
# define some constants
game_size = sf.Vector2(800, 600)
paddle_size = sf.Vector2(25, 100)
ball_radius = 10.
# create the window of the application
w, h = game_size
window = sf.RenderWindow(sf.VideoMo... |
11559252 | import os
import pickle
from fuzzywuzzy import fuzz
from play import play_wav
from listen import recognize_speech_from_mic
def keyword_match(keyword):
results = []
chapter_texts = os.listdir("data/texts")
chapter_texts.sort()
flag = False
for chapter_name in chapter_texts:
pickle_path = o... |
11559268 | import numpy as np
from deap.helpers import getOutputShape
from deap.mappers import PhotonicConvolverMapper
from deap.mappers import ModulatorArrayMapper
from deap.mappers import PWBArrayMapper
def convDEAP(image, kernel, stride, bias=0, normval=255):
"""
Image is a 3D matrix with index values row, col, dept... |
11559276 | import numpy as np
import torch
#diabetes prevalence for china
#https://jamanetwork.com/journals/jama/fullarticle/1734701
male = np.array([5.2755905511811, 8.346456692913385, 13.543307086614174, 17.95275590551181, 20.708661417322837, 21.653543307086615])
female = np.array([4.015748031496061, 5.1181102362204705, 9.0551... |
11559277 | import ctypes
from ctypes import wintypes
_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD
def get_short_path_name(long_name):
"""
Gets the short path name of a given long pat... |
11559285 | import numpy as np
from .fast import reduce_sum, reduce_prod, reduce_mean, reduce_std
from .table import Table
def reduce_by_key(table, column_name, func, check_sorted=True):
"""
Func is a string
:param table:
:param column_name:
:param func:
:param check_sorted:
:return:
"""
key_... |
11559287 | def test_simple_comment(check_output):
check_output('''
main() {
extrn putchar;
/* a comment */
putchar('a');
}
''', 'a')
def test_comment_stops_at_first_terminator(check_output):
check_output('''
main() {
extrn putchar;
/*... |
11559330 | from __future__ import absolute_import
import unet_collection.keras_vision_transformer
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D, concatenate
from unet_collection.keras_vision_transformer import swin_layers
f... |
11559383 | class Ladder:
"""
Ladder object. It starts at some lower position and ends at a higher position.
"""
def __init__(self, start: int, end: int):
self.start = start
self.end = end
|
11559398 | import warnings
warnings.warn(
"pyschema.contrib.avro is deprecated and will be removed.\n"
"Please use the pyschema_extensions.avro package instead.",
DeprecationWarning,
stacklevel=2
)
import pyschema_extensions.avro
from pyschema_extensions.avro import *
|
11559439 | import logging
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Submit, Column
from django import forms
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from YtManagerApp.views.forms.auth import ExtendedUserCreationForm, ExtendedAuthenticationFor... |
11559446 | import numpy as np
import mmcv
from mmdet.models import DETECTORS, TwoStageDetector
from monorun.core import draw_box_3d_pred, show_bev
@DETECTORS.register_module()
class MonoRUnDetector(TwoStageDetector):
def simple_test(self, img, img_metas, proposals=None, rescale=False,
**kwargs):
... |
11559475 | import os
import unittest
from typing import Tuple
from unittest.case import TestCase
from eth_typing.evm import ChecksumAddress
from web3 import Web3
from moonworm.contracts import ERC1155
from moonworm.web3_util import build_transaction, submit_transaction
from ..manage import deploy_ERC1155
def read_testnet_env... |
11559495 | import os
import sys
import yaml
# To update the package version number, edit CITATION.cff
citationfile = os.path.join(sys.exec_prefix, 'citation/grlc', 'CITATION.cff')
with open(citationfile, 'r') as f:
data = yaml.safe_load(f)
__version__ = data['version']
|
11559514 | import os
import pathlib
import yaml
import panel as pn
import param
import requests
from panel.reactive import ReactiveHTML
from lumen.sources import Source
from .base import WizardItem
from .fast import FastComponent
from .gallery import Gallery, GalleryItem
from .state import state
ASSETS_DIR = pathlib.Path(__f... |
11559525 | import os
import sys
from insights.client.constants import InsightsConstants as constants
from insights.client.apps.ansible.playbook_verifier import verify, loadPlaybookYaml, PlaybookVerificationError
skipVerify = False
def read_playbook():
"""
Read in the stringified playbook yaml from stdin
"""
unv... |
11559539 | import pytest
from numpy import allclose, arange, array, asarray, dot, cov, corrcoef, float64
from thunder.series.readers import fromlist, fromarray
from thunder.images.readers import fromlist as img_fromlist
pytestmark = pytest.mark.usefixtures("eng")
def test_map(eng):
data = fromlist([array([1, 2]), array([3... |
11559541 | from .samplerate import AudioSampleRate, audio_sample_rate
from soundfile import SoundFile
from io import BytesIO
from zounds.core import IdentityDimension, ArrayWithUnits
from .timeseries import TimeDimension, TimeSlice
from .duration import Picoseconds, Seconds
from .samplerate import SampleRate
import numpy as np
... |
11559556 | from ..model_tests_utils import (
status_codes,
DELETE,
PUT,
POST,
GET,
ERROR,
random_model_dict,
check_status_code,
compare_data
)
from core.models import (
OutcomeTemplate,
ExperimentTemplate,
)
outcome_test_data = {}
outcome_tests = [
##----TEST 0----##
#creates an expe... |
11559590 | import requests
import sys
import exchange_client
from exchange_client import smart_open
import json
import os
import tempfile
'''Make a request to an eXchange non-paginated API.
@Param api_uri String -- API's URI (does not include the "base" URI)
@Param data_set_type String -- name of the data set t... |
11559641 | from quasimodo.assertion_validation.content_comparator import ContentComparator
from quasimodo.cache.mongodb_cache import MongoDBCache
from quasimodo.parameters_reader import ParametersReader
import logging
import wikipedia
parameters_reader = ParametersReader()
DEFAULT_MONGODB_LOCATION = parameters_reader.get_paramet... |
11559672 | from rest_framework import serializers as rest_serializers
from geotrek.authent import models as authent_models
class StructureSerializer(rest_serializers.ModelSerializer):
class Meta:
model = authent_models.Structure
fields = ('id', 'name')
|
11559673 | import defcon
from fontParts.base import BaseKerning
from fontParts.fontshell.base import RBaseObject
class RKerning(RBaseObject, BaseKerning):
wrapClass = defcon.Kerning
def _items(self):
return self.naked().items()
def _contains(self, key):
return key in self.naked()
def _setItem... |
11559692 | import logging
import sys
import numpy as np
import tvm
import tvm.testing
from tvm import te
from tvm import autotvm
from tvm.contrib import nvcc, cc
# check whether the gpu has tensorcore
if not tvm.gpu(0).exist or not tvm.runtime.enabled("cuda"):
raise Exception("skip building this tutorial because cuda is not... |
11559705 | import os
import sys
from subprocess import run, PIPE, STDOUT
import click
from hobbit import ROOT_PATH
def dev_init(all_, hooks, pipenv):
run('git init', shell=True)
if all_ or hooks:
HOOKS_PATH = os.path.join(ROOT_PATH, 'static', 'hooks')
run(f'cp -r {HOOKS_PATH}/* .git/hooks', shell=True... |
11559769 | import fastai
from fastai.vision import *
from torch.utils.data.dataloader import default_collate
from torch.utils.data import Sampler, SequentialSampler, RandomSampler
import sklearn
# Modification to ImageDataBunch to allow to give a list of custome samplers.
class ImageDataBunch(ImageDataBunch):
@classmethod
... |
11559799 | from __future__ import division
import numpy as np
#Single value as opposed to mean/std image
#Perhaps we want to change it to one value per color channel
def calc_mean_std(X):
mean = np.mean(X)
std = np.std(X)
return mean, std
def normalize(data, mean, std):
return (data-mean)/std
|
11559816 | from bag_transfer.rights.views import (RightsAPIAdminView, RightsCreateView,
RightsDetailView, RightsUpdateView)
from django.conf.urls import url
app_name = 'rights'
urlpatterns = [
url(r"^add/$", RightsCreateView.as_view(), name="add"),
url(r"^(?P<pk>\d+)/$", RightsDeta... |
11559848 | from . import UVSubToolBar as _UVSubToolBar
import re
import maya.mel as mel
import sys
import maya.cmds as cmds
import os
from PySide.QtCore import *
from PySide.QtGui import *
from maya.app.general.UVSubToolBar import UVSubToolBar
from random import randint
class UVEditBar(UVSubToolBar):
def UVLatticeButtoncmd... |
11559852 | import sqlite3
import pandas as pd
conn = sqlite3.connect("menu.db")
c = conn.cursor()
print(pd.read_sql_query("SELECT * FROM Sandwiches", conn))
print("-------")
print(pd.read_sql_query("SELECT name, my_cost FROM Sandwiches WHERE my_cost>5", conn))
print("-------")
x = pd.read_sql_query("SELECT name, my_cost FROM S... |
11559882 | import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
x = [-26, -15.6464, -9.8422, -6.0, -4.0, -2.68, -2.3, -1.8, -1.26, -0.61, 0, 0.61, 1.26, 2.1, 2.68, 4.4704] # relative velocity values
y = [.76, .504, 0.34, 0.29, 0.25, 0.22, 0.19, 0.13, 0.053, 0.017, 0, -0.015, -0.042, -0.13, ... |
11559948 | from flask import Blueprint, render_template
from platypush.backend.http.app import template_folder
from platypush.backend.http.app.utils import authenticate, get_websocket_port
from platypush.backend.http.utils import HttpUtils
dashboard = Blueprint('dashboard', __name__, template_folder=template_folder)
# Declare ... |
11559969 | import time
from os import PathLike
from typing import Iterable
from typing import Optional
from loguru import logger
from extract_emails.errors import BrowserImportError
try:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
except ModuleNotFoundError:
msg = "ChromeB... |
11559987 | from typing import List, Optional
import logging
from collections import Counter
from itertools import cycle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from pandas import DataFrame
from scipy.cluster import hierarchy
from scipy.spatial.distance import pdist
from hyperclus... |
11560016 | import random
import re
import shlex
import subprocess
import time
from threading import Thread
import httpx # type: ignore
import pytest
import mosec
TEST_PORT = "5000"
URL = f"http://0.0.0.0:{TEST_PORT}"
@pytest.fixture
def http_client():
client = httpx.Client()
yield client
client.close()
@pytest... |
11560020 | import os
import Ngl, Nio
from utils import *
dirc = os.path.join("$NCARGTEST","nclscripts","cdf_files")
b = Nio.open_file(os.path.join(dirc,"wrftest_for.nc"))
tk_for = b.variables["tk"][:]
rh_for = b.variables["rh"][:]
tk_m_for = multid(tk_for,[3,2,2])
rh_m_for = multid(rh_for,[3,2,2])
filename = "wrfout... |
11560026 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import copy
import math
from transformers import Wav2Vec2Model,Wav2Vec2Config
from transformers.modeling_outputs import BaseModelOutput
from typing import Optional, Tuple
_CONFIG_FOR_DOC = "Wav2Vec2Config"
# the implementation of Wav... |
11560060 | from binding import *
from ..namespace import llvm
@llvm.Class()
class AssemblyAnnotationWriter:
_include_ = "llvm/Assembly/AssemblyAnnotationWriter.h"
|
11560076 | import requests
import json
import pymysql
import sys
SUCCESS = "SUCCESS"
FAILED = "FAILED"
def create_db(dbname, dbuser, dbpassword, rdsendpoint, rdsuser, rdspassword):
create_db_query = f"CREATE DATABASE {dbname};"
create_user_query = f"CREATE USER '{dbuser}'@'%' IDENTIFIED BY '{dbpassword}';"
grant_qu... |
11560083 | import re
from tempfile import TemporaryDirectory
import pytest
from aqt.archives import TargetConfig
from aqt.exceptions import UpdaterError
from aqt.helper import Settings
from aqt.updater import Updater
@pytest.fixture(autouse=True)
def setup_settings():
Settings.load_settings()
@pytest.mark.parametrize(
... |
11560132 | from models import db, Product
import setup
app = setup.create_app()
items = [
{
'name': 'Product 1',
'slug': 'product-1',
'image': 'apple.png',
'price': 1
},
{
'name': 'Product 2',
'slug': 'product-2',
'image': 'banana.png',
'price': 2
}... |
11560175 | import gym
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Reshape
from keras.layers.embeddings import Embedding
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy
from rl.memory import SequentialMemory
ENV... |
11560244 | from ursina import *
from ursina.shaders import basic_lighting_shader
from ursinanetworking import *
BLOCKS_PARENT = Entity()
class Block(Button):
def __init__(self, position = (0,0,0)):
super().__init__(
parent = BLOCKS_PARENT,
position = position,
model = "block",
... |
11560261 | import unittest
from ccdc.protein import Protein
from ccdc.io import MoleculeReader
from hotspots.hs_io import HotspotReader, HotspotWriter
from hotspots.result import Results
from hotspots.grid_extension import Grid
from hotspots.calculation import Runner
from hotspots.wrapper_pymol import PyMOLFile, PyMOLC... |
11560266 | import click
from typing import Dict
from dumpit import pdumpit
from aenum import MultiValueEnum
class DefaultQueryParams(MultiValueEnum):
"""Default set of query parameters."""
msg_type = 'msgtype', 'simple or extended (extended cost more credits)'
protocol = 'protocol', 'Response type. Use one of the f... |
11560299 | import numpy as np
class BaseDataLoaders(object):
def __init__(self, name):
self.data_size = None
self.indexes = None
self.name = name
def _shuffle_indexes(self):
np.random.shuffle(self.indexes)
def _shuffle_batch_indexes(self):
np.random.shuffle(self.batch_indexe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.