id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
151235 | import dash
from dash.dependencies import Input, Output
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
# add an id column and set it as the index
# in this case t... |
151252 | import logging
from collections import deque
from PyQt6.QtWidgets import QWidget, QLabel
from PyQt6.QtCore import pyqtSignal
from core.utils.win32.utilities import get_monitor_hwnd
from core.event_service import EventService
from core.event_enums import KomorebiEvent
from core.widgets.base import BaseWidget
from core.u... |
151288 | import inspect
import unittest
from config.database import DATABASES
from src.masoniteorm.models import Model
from src.masoniteorm.query import QueryBuilder
from src.masoniteorm.query.grammars import MySQLGrammar
from src.masoniteorm.relationships import has_many
from src.masoniteorm.scopes import SoftDeleteScope
from... |
151297 | import horovod.tensorflow as hvd
import os
import tensorflow as tf
from preprocessing import resnet_preprocessing, imagenet_preprocessing, darknet_preprocessing
import functools
def create_dataset(data_dir, batch_size, preprocessing='resnet', validation=False):
filenames = [os.path.join(data_dir, i) for i in os.li... |
151371 | from __future__ import unicode_literals
import yaml
BLOG_AUTHOR = "Stay Static" # (translatable)
BLOG_TITLE = "Nikola Stay Static Sample" # (translatable)
SITE_URL = "http://staystatic.github.io/sites/nikola/"
BLOG_EMAIL = "<EMAIL>"
BLOG_DESCRIPTION = "Nikola demo for Stay Static" # (translatable)
COMMENT_SYSTEM = N... |
151382 | import vcs
import sys
import argparse
import vcs.testing.regression as regression
import os
p =argparse.ArgumentParser()
p.add_argument("-H","--fitToHeight",default=True,action="store_false")
p.add_argument("-u","--units",default="percent")
p.add_argument("-x","--xoffset",default=0,type=float)
p.add_argument("-y","--... |
151411 | import logging
import os
import datetime
import random
import string
from nhd.NHDCommon import NHDCommon
from enum import Enum
from colorlog import ColoredFormatter
from kubernetes import client, config, watch
from kubernetes.client.rest import ApiException
from nhd.Node import Node
from typing import Dict, List, Set, ... |
151428 | import os
def before_all(context):
context.tmpfiles = []
def after_all(context):
for filename in context.tmpfiles:
os.remove(filename)
|
151443 | import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from scipy.stats import multinomial
from ..utils.array import one_hot
from .categorical import CategoricalDist
if tf.__version__ >= '2.0':
tf.random.set_seed(11)
else:
tf.set_random_seed(11)
rnd ... |
151527 | import numpy as np
import torch
import onqg.dataset.Constants as Constants
def get_non_pad_mask(seq):
assert seq.dim() == 2
return seq.ne(Constants.PAD).type(torch.float).unsqueeze(-1)
def get_attn_key_pad_mask(seq_k, seq_q):
''' For masking out the padding part of key sequence. '''
# ... |
151529 | from pylonemutestcase import PylonEmuTestCase
from pypylon import pylon
import unittest
class CallTestSuite(PylonEmuTestCase):
# Tests that you can set the GainRaw parameter of the camera
def test_gain_raw(self):
cam = self.create_first()
cam.Open()
# Set GainRaw to min value (192)
... |
151585 | import torch
from sbibm.metrics import mmd
from .utils import sample_blobs_same
def test_mmd():
X, Y = sample_blobs_same(n=1000)
mmd_1 = mmd(X=X, Y=Y, implementation="tp_sutherland")
mmd_2 = mmd(X=X, Y=Y, implementation="tp_djolonga")
assert torch.allclose(mmd_1, mmd_2, rtol=1e-04, atol=1e-04)
|
151586 | import functools
import warnings
import numpy as np
import numpy.linalg as npla
import sys, os
import time
from PES.compute_covariance import *
from PES.initial_sample import *
from PES.hyper_samples import *
from PES.utilities import *
from PES.sample_minimum import *
from PES.PES import *
from PES.compute... |
151595 | import matplotlib.pyplot as p;
p.switch_backend("SVG")
import mpld3
import seaborn as sns; sns.set()
def Axis_FactorPlot(data, x, y=None, hue=None, row=None, col=None, kind="point"):
sns.set(style="ticks")
ax = sns.factorplot(x=x, y=y, hue=hue, data=data, kind=kind, row=row, col=col)
d = mpld3.fig_to_dict(... |
151634 | import dataclasses
import cefconsole
from wecs.core import System
from wecs.core import and_filter
from wecs.core import Component
class WECSSubconsole(cefconsole.Subconsole):
name = "WECS"
package = 'wecs'
template_dir = 'templates'
html = "wecs.html"
funcs = {
'refresh_wecs_matrix': 'r... |
151635 | from sqlalchemy import Column, Integer, String, Numeric, func, distinct, Boolean
from app import db
class Rais(db.Model):
__tablename__ = 'rais'
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
microregion = Column(String(5), primary_key=True)
state = C... |
151640 | import pandas_flavor as pf
import pandas as pd
from typing import Union
@pf.register_dataframe_method
def move(
df: pd.DataFrame,
source: Union[int, str],
target: Union[int, str],
position: str = "before",
axis: int = 0,
) -> pd.DataFrame:
"""
Move column or row to a position adjacent to ... |
151665 | import torch
import torch.nn as nn
import numpy as np
import FrEIA.framework as Ff
from .. import InvertibleArchitecture
__all__ = ['beta_0', 'beta_1', 'beta_2', 'beta_4', 'beta_8', 'beta_16', 'beta_32', 'beta_inf']
model_base_url = 'https://heibox.uni-heidelberg.de/seafhttp/files/6f91503d-7459-4080-b10a-e979f8b3d2... |
151671 | import pytest
from emrichen import Template
HASHES = {
'MD5': '8b1a9953c4611296a827abf8c47804d7',
'SHA1': 'f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0',
'SHA256': '185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969',
}
@pytest.mark.parametrize('h', sorted(HASHES.items()), ids=sorted(HASHES))
... |
151705 | from distutils.core import setup
from entmax import __version__
setup(name='entmax',
version=__version__,
url="https://github.com/deep-spin/entmax",
author="<NAME>, <NAME>, <NAME>",
author_email="<EMAIL>",
description=("The entmax mapping and its loss, a family of sparse "
... |
151721 | import moai.nn.convolution as mic
import torch
__all__ = [
"StridedConv2d",
]
class StridedConv2d(torch.nn.Module): #TODO: Add optional activation as well?
def __init__(self,
features: int,
kernel_size: int=3,
conv_type: str="conv2d",
stride: int=2,
padding: int=1
... |
151739 | from django.http.response import JsonResponse
from django.views.generic.base import View, TemplateView
from django.views.decorators.csrf import csrf_exempt
from PIL import Image, ImageFilter
from tesserocr import PyTessBaseAPI
class OcrFormView(TemplateView):
template_name = 'documents/ocr_form.html'
ocr_form_vi... |
151742 | from os import listdir
from os.path import isfile, join
import tensorflow as tf
def get_image(path, height, width, preprocess_fn):
png = path.lower().endswith('png')
img_bytes = tf.read_file(path)
image = tf.image.decode_png(img_bytes, channels=3) if png else tf.image.decode_jpeg(img_bytes, channels=3)
... |
151761 | import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.model.user import User
from hakoblog.loader.user import UserLoader
from tests.util import random_string, create_user
def test_find_by_name():
db = DB()
user = create_user()
found_user = UserLoader.find_by_name(db, user.name)
... |
151774 | def solution(l):
parsed = [e.split(".") for e in l]
toSort = [map(int, e) for e in parsed]
sortedINTs = sorted(toSort)
sortedJoined = [('.'.join(str(ee) for ee in e)) for e in sortedINTs]
return sortedJoined |
151821 | import logging
from flask_restplus import Resource
from biolink.datamodel.serializers import compact_association_set, association_results
from ontobio.golr.golr_associations import search_associations, GolrFields
from biolink.api.restplus import api
from biolink import USER_AGENT
from biolink.error_handlers import Ro... |
151844 | from setuptools import setup, find_packages
__version__ = "1.0.a"
setup(name='dfw',
description='Implementation of the Deep Frank Wolfe (DFW) algorithm',
author='<NAME>',
packages=find_packages(),
license="GNU General Public License",
url='https://github.com/oval-group/dfw',
versio... |
151849 | from pathlib import Path
from zipfile import ZipFile
import requests
class Taxonomy():
TAXONOMIES = {
"2013": "https://www.fsa.go.jp/search/20130821/editaxonomy2013New.zip",
"2014": "https://www.fsa.go.jp/search/20140310/1c.zip",
"2015": "https://www.fsa.go.jp/search/20150310/1c.zip",
... |
151864 | import numpy as np
def dtw(series_1, series_2, norm_func = np.linalg.norm):
matrix = np.zeros((len(series_1) + 1, len(series_2) + 1))
matrix[0,:] = np.inf
matrix[:,0] = np.inf
matrix[0,0] = 0
for i, vec1 in enumerate(series_1):
for j, vec2 in enumerate(series_2):
cost = norm_func(vec1 - vec2)
matrix[i + 1... |
151938 | from ..base import MultiGridEnv, MultiGrid
from ..objects import *
class EmptyMultiGrid(MultiGridEnv):
mission = "get to the green square"
metadata = {}
def _gen_grid(self, width, height):
self.grid = MultiGrid((width, height))
self.grid.wall_rect(0, 0, width, height)
self.put_obj... |
151949 | from core.advbase import *
from slot.a import *
def module():
return Yuya
class Yuya(Adv):
a3 = ('primed_crit_chance', 0.05,5)
conf = {}
conf['slots.burn.a'] = Twinfold_Bonds()+Me_and_My_Bestie()
conf['acl'] = """
`dragon, s=1
`s3, not self.s3_buff
`s4
`s1
... |
151964 | from typing import List
from ..error.friendly_error import FriendlyError
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.context import SlashContext
from discord_slash.model import SlashCommandOptionType
from discord_slash.utils.manage_commands import create_option
from googlesearc... |
151967 | import os
from collections import Iterable
def flat(lis):
for item in lis:
if isinstance(item, list):# and not isinstance(item, basestring):
for x in flat(item):
yield x
else:
yield item
def flatten(lis):
return list(flat(lis))
def... |
151978 | from flask_login import login_user
from flaskbb.forum.models import Topic
def test_guest_user_cannot_see_hidden_posts(guest, topic, user,
request_context):
topic.hide(user)
login_user(guest)
assert Topic.query.filter(Topic.id == topic.id).first() is None
def ... |
152013 | import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
standard_exclude = ('*.pyc', '*~... |
152022 | from serpent.game_launcher import GameLauncher, GameLauncherException
from serpent.utilities import is_linux, is_macos, is_windows
import shlex
import subprocess
import webbrowser
class SteamGameLauncher(GameLauncher):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def launch(self, **kwar... |
152035 | import asyncio
import json
import pytest
import privatebinapi
from privatebinapi import common, deletion, download, upload
from tests import MESSAGE, RESPONSE_DATA, SERVERS_AND_FILES
@pytest.mark.parametrize("server, file", SERVERS_AND_FILES)
def test_full(server, file):
send_data = privatebinapi.send(
... |
152076 | from django_bleach.models import BleachField
from tinymce.models import HTMLField
from django.conf import settings
from django.core.validators import URLValidator
from django.db.models import URLField
from django.forms.fields import URLField as FormURLField
################
# JobsURLField #
################
JobsURLV... |
152080 | import os
import tarfile
from github3 import login
token = os.getenv('GITHUB_TOKEN')
gh = login(token=token)
repo = gh.repository('gamechanger', 'dusty')
version = os.getenv('VERSION')
prerelease = os.getenv('PRERELEASE') == 'true'
release_name = version
release = repo.create_release(version, name=release_name, pre... |
152101 | import unittest
import os
import torch
from torch.optim import Optimizer
import apex
from apex.multi_tensor_apply import multi_tensor_applier
from itertools import product
class RefLAMB(Optimizer):
r"""Implements Lamb algorithm.
It has been proposed in `Large Batch Optimization for Deep Learning: Training BE... |
152191 | import pika
import json
from init_judge import initialize_judge
class authenticate_judge():
username = 'Nouser'
password = '<PASSWORD>'
judge_id = 'NULL'
channel = ''
login_status = ''
key = initialize_judge.key()
my_ip = initialize_judge.my_ip()
def login(channel, host, username, password):
authenticate_... |
152265 | from django.db import models
from django.conf import settings
from django.utils import timezone
from .allocation import TASAPIDriver
AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", 'auth.User')
class TASAllocationReport(models.Model):
"""
Keep track of each Allocation Report that is sent to TACC.API
... |
152273 | import inflect
def test_an():
p = inflect.engine()
assert p.an("cat") == "a cat"
assert p.an("ant") == "an ant"
assert p.an("a") == "an a"
assert p.an("b") == "a b"
assert p.an("honest cat") == "an honest cat"
assert p.an("dishonest cat") == "a dishonest cat"
assert p.an("Honolulu sun... |
152330 | import logging
import torch
from algorithms.BaseDistanceEmbedder import BaseDistanceEmbedder
class RawDistanceEmbedder(BaseDistanceEmbedder):
"""
Returns the distance as is for embedding
"""
def __init__(self, max_pos=5):
self.max_pos = max_pos
def logger(self):
return logging.... |
152340 | from setuptools import setup, find_packages
if __name__ == '__main__':
name = 'ppca'
setup(
name = name,
version = "0.0.4",
author = '<NAME>',
author_email = '<EMAIL>',
description = 'Probabilistic PCA',
packages = find_packages(),
classifiers = [
'Develop... |
152342 | from PIL import Image
import StringIO
import urllib
def resize_and_pad_image(img, output_image_dim):
"""Resize the image to make it IMAGE_DIM x IMAGE_DIM pixels in size.
If an image is not square, it will pad the top/bottom or left/right
with black pixels to ensure the image is square.
Args:
img: the in... |
152349 | from __future__ import unicode_literals
class WinRMError(Exception):
""""Generic WinRM error"""
code = 500
class WinRMTransportError(Exception):
"""WinRM errors specific to transport-level problems (unexpected HTTP error codes, etc)"""
@property
def protocol(self):
return self.args[0]
... |
152404 | from torch import nn
import torch
class FactorList(nn.Module):
def __init__(self, parameters=None):
super().__init__()
self.keys = []
self.counter = 0
if parameters is not None:
self.extend(parameters)
def _unique_key(self):
"""Creates a new unique key""... |
152411 | from flask import redirect, render_template, flash, g, session, url_for, request, jsonify
from flask.ext.login import current_user, login_required
from . import main
from .forms import TodoForm
from .. import db
from ..models import User, Todo
from collections import Counter
@main.app_errorhandler(404)
def page_not_f... |
152420 | import sys
from unittest import TestCase, main
from mock import patch, Mock
from pymongo.errors import ConnectionFailure
import ming
from ming import Session
from ming import mim
from ming import create_datastore, create_engine
from ming.datastore import Engine
from ming.exc import MingConfigError
class DummyConnec... |
152421 | import inspect
import json
import os
from pytube import YouTube, Playlist
from pytube.exceptions import RegexMatchError, PytubeError
CONFIGURATIONS = {'destination_path': '', 'video_quality': '',
'audio_quality': '', 'when_unavailable': ''}
CONFIGS_FILE = 'configs.json'
def create_config_file():
... |
152434 | from sevenbridges.meta.fields import IntegerField, DateTimeField
from sevenbridges.meta.resource import Resource
class Rate(Resource):
"""
Rate resource.
"""
limit = IntegerField(read_only=True)
remaining = IntegerField(read_only=True)
reset = DateTimeField(read_only=True)
def __str__(sel... |
152462 | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation
import json
import nibabel as nib
from scipy.ndimage.interpolation import zoom
def save_history(filename, trainer):
"""Save the history from a torchsample trainer to file."""
with open(f... |
152480 | import os
class Config(object):
SECRET_KEY = os.urandom(32)
BOOTSTRAP_SERVE_LOCAL = True
SQLALCHEMY_DATABASE_URI = "sqlite:///app.db"
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
152481 | import calendar
import json
from json.decoder import JSONDecodeError
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from dja... |
152492 | import itertools
import numpy as np
from ..sequences import Genome
def in_silico_mutagenesis_sequences(sequence,
mutate_n_bases=1,
reference_sequence=Genome,
start_position=0,
... |
152527 | import json
import sys
from easyprocess import EasyProcess
python = sys.executable
def pass_env(e):
prog = "import os,json;print(json.dumps(dict(os.environ)))"
s = EasyProcess([python, "-c", prog], env=e).call().stdout
return json.loads(s)
def test_env():
assert len(pass_env(None)) > 0
e = pas... |
152537 | template = "#include \"kernel.h\"\n#include \"ecrobot_interface.h\"\n@@BALANCER@@\n@@VARIABLES@@\n\nvoid ecrobot_device_initialize(void)\n{\n@@INITHOOKS@@\n}\n\nvoid ecrobot_device_terminate(void)\n{\n@@TERMINATEHOOKS@@\n}\n\n/* nxtOSEK hook to be invoked from an ISR in category 2 */\nvoid user_1ms_isr_type2(void){ /* ... |
152568 | from tests.utils import W3CTestCase
class TestTtwfReftestFlexAlignContentCenter(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'ttwf-reftest-flex-align-content-center'))
|
152570 | from scipy import stats
import numpy as np
__all__ = ['chisquare', 'kolsmi']
def kolsmi(dist, fit_result, data):
"""Perform a Kolmogorow-Smirnow-Test for goodness of fit.
This tests the H0 hypothesis, if data is a sample of dist
Args:
dist: A mle.Distribution instance
fit_result... |
152615 | from abc import abstractmethod
from math import ceil, log2
from ..util import SaveLoad, load
class Traversal(SaveLoad):
"""Base image traversal class.
Attributes
----------
classes : `dict`
Image traversal class group.
"""
classes = {}
@abstractmethod
def __call__(self, widt... |
152637 | from django.urls import path
from . import views
app_name = 'posts'
urlpatterns = [
path('create/<int:pk>/', views.create_post, name='create_post'),
] |
152647 | import arcpy
#gdb = r'X:\Env-dat.081\source\yt_courbe_niveau_imperial.gdb'
gdb = r'D:\s\yt_courbe_niveau_imperial.gdb'
def arcpy_listFC(gdb):
arcpy.env.workspace = gdb
print 'Looking in "%s" ' % arcpy.env.workspace
fcs = arcpy.ListFeatureClasses()
return fcs
fcs = arcpy_listFC(gdb)
print 'Feature cl... |
152692 | import matplotlib
matplotlib.use('Agg')
from ecolopy_dev import Community
from ecolopy_dev.utils import draw_shannon_distrib
##test_abund.txt would be the genome abundance / the diploid number of chromosomes
## j_tot is obtained by taking the total number of individuals
com = Community('test_log_abund.txt', j_to... |
152725 | from django.template import Library
from evap.evaluation.models import Semester
from evap.settings import DEBUG, LANGUAGES
register = Library()
@register.inclusion_tag("navbar.html")
def include_navbar(user, language):
return {
"user": user,
"current_language": language,
"languages": LAN... |
152728 | from functools import partial
# from ..config_new import BTE_FILTERS
BTE_FILTERS = ["nodeDegree", "ngd", "drugPhase", "survivalProbability"]
def filter_response(res, criteria):
"""
Filter API response based on filtering criteria
:param res: API Response
:param criteria: filtering criteria
"""
... |
152738 | import random
print('Enter the two different values')
first = input('Enter first side : ')
second = input('Enter second side : ')
fate = [first,second]
x=random.randint(0,1)
print(fate[x])
|
152749 | from django.conf.urls import patterns
from status.views import StatusView, ExtraStatusView
urlpatterns = patterns('status.views',
(r'^/?$', StatusView.as_view()),
(r'^/(?P<machine_name>[^/]+)$', StatusView.as_view()),
(r'^(?P<query>.+)/$', ExtraStatusView.as_view()),
)
|
152759 | from django.utils.translation import ugettext_lazy as _
from mayan.apps.acls.classes import ModelPermission
from mayan.apps.acls.permissions import permission_acl_edit, permission_acl_view
from mayan.apps.common.apps import MayanAppConfig
from mayan.apps.common.menus import (
menu_multi_item, menu_object, menu_sec... |
152761 | class SOAPError(Exception):
"""
**Custom SOAP exception**
Custom SOAP exception class.
Raised whenever an error response has been received during action invocation.
"""
def __init__(self, description, code):
self.description = description
self.error = code
class ... |
152773 | from copy import deepcopy
from .transforms import TRANSFORMS
SCHEME_CACHE = {} # global scheme registry
class Scheme():
def __init__(self, scheme_list, agent_flatten=True):
self.scheme_list = scheme_list
if agent_flatten:
self.agent_flatten() # NEW!
self.t_id_depth = self._g... |
152796 | from django.conf import settings
from django.urls import path
from dictionary.views.detail import Chat, ChatArchive, UserProfile
from dictionary.views.edit import UserPreferences
from dictionary.views.images import ImageList, ImageUpload, ImageDetailProduction, ImageDetailDevelopment
from dictionary.views.list import ... |
152835 | import tensorflow as tf
input = tf.placeholder(tf.string, None)
'''
{
"input": {
"foo": {
"bar": "bar"
}
}
}
'''
root = tf.parse_single_example(input[0], features={
'foo': tf.FixedLenFeature(shape=[], dtype=tf.string),
})
foo = tf.parse_single_example(root['foo'], features={
... |
152922 | from .base import BasePlayer, Option
from .cli import CLIPlayer
# debug.py is not included in published package
try:
from sxm_player.debug.player import DebugPlayer
except ImportError:
DebugPlayer = None # type: ignore
__all__ = ["BasePlayer", "CLIPlayer", "DebugPlayer", "Option"]
|
152945 | import datetime
import os
import sys
from configparser import SafeConfigParser, ConfigParser
import pkg_resources
import logging
from trustworthiness.definitions import OUTPUT_FOLDER
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
c... |
152967 | from brainflow.board_shim import *
from brainflow.exit_codes import *
from brainflow.data_filter import *
from brainflow.ml_model import *
from brainflow.utils import * |
152991 | import sandstone.lib.decorators
from sandstone.lib.handlers.base import BaseHandler
from terminado import TermSocket
class AuthTermSocket(TermSocket,BaseHandler):
@sandstone.lib.decorators.authenticated
def get(self, *args, **kwargs):
return super(AuthTermSocket, self).get(*args, **kwargs)
|
153004 | import os
import dash
def _init_app():
""" Intializes the dash app."""
this_dir = os.path.dirname(os.path.abspath(__file__))
css_file = os.path.join(this_dir, "stylesheet.css")
app = dash.Dash(
__name__,
external_stylesheets=[css_file],
suppress_callback_exceptions=True,
... |
153007 | from ctypes import CDLL, POINTER, byref, c_void_p, c_size_t
from numba import cuda
from numba.cuda import (HostOnlyCUDAMemoryManager, GetIpcHandleMixin,
MemoryPointer, MemoryInfo)
# Open the CUDA runtime DLL and create bindings for the cudaMalloc, cudaFree,
# and cudaMemGetInfo functions.
cud... |
153027 | from appdirs import *
from pathlib import Path
import requests
from tqdm import tqdm
from enum import Enum
COVEO_INTERACTION_DATASET_S3_URL = 'https://reclist-datasets-6d3c836d-6djh887d.s3.us-west-2.amazonaws.com/coveo_sigir.zip'
SPOTIFY_PLAYLIST_DATASET_S3_URL = 'https://reclist-datasets-6d3c836d-6djh887d.s3.us-west-... |
153100 | import numpy as np
import string
from keras.preprocessing.text import Tokenizer
samples = ['The cat sat on the mat.', 'The dog ate my homework.']
print("单词级别")
print("构建标记索引,为每个单词指定唯一索引,从 1 开始")
word_token_index = {}
for sample in samples:
for word in sample.split():
if word not in word_token_index:
... |
153106 | from .abc import ABCErrorHandler
from .error_handler import ErrorHandler
__all__ = ("ABCErrorHandler", "ErrorHandler")
|
153127 | import os
import sys
import boto3
import botocore
import json
import time
from debug import debug_print
from debug import error_print
from botoHelper import get_boto_client
def handler(event, context):
debug_print(json.dumps(event, indent=2))
s3_event = event["Records"][0]["s3"]
s3_bucket = s3_event["buck... |
153153 | import math
def amplitude_to_db(amplitude: float, reference: float = 1e-6) -> float:
"""
Convert amplitude from volts to decibel (dB).
Args:
amplitude: Amplitude in volts
reference: Reference amplitude. Defaults to 1 µV for dB(AE)
Returns:
Amplitude in dB(ref)
"""
ret... |
153166 | import time
import threading
import asyncio
from aiohttp import ClientSession
from aiohttp_proxy import ProxyConnector, ProxyType
class Checker(object):
def __init__(self, proxies: list, proxy_type: str, threads: int, timeout: int, savedir: str):
# Arguments:
self.proxies = set(proxi... |
153254 | from django import template
from django.urls import reverse
from tickets.core.middlewares import get_current_request
register = template.Library()
@register.simple_tag
def is_active(url):
request = get_current_request()
# Main idea is to check if the url and the current path is a match
if request.path =... |
153260 | from typing import Union
import spacy
regex = [r"\bsofa\b"]
method_regex = (
r"sofa.*?((?P<max>max\w*)|(?P<vqheures>24h\w*)|"
r"(?P<admission>admission\w*))(?P<after_value>(.|\n)*)"
)
value_regex = r".*?.[\n\W]*?(\d+)[^h\d]"
score_normalization_str = "score_normalization.sofa"
@spacy.registry.misc(score_... |
153262 | import torch
import torch.nn as nn
from losses import *
from net_pwc import *
from model_base import *
from reblur_package import *
from flow_utils import *
class ModelSelfFlowNet(ModelBase):
def __init__(self, opts):
super(ModelSelfFlowNet, self).__init__()
self.opts = opts
# cr... |
153268 | from urllib.parse import urljoin
import pytest
import requests
from selenium.webdriver.common.keys import Keys
from tests.selenium_tests.conftest import skip_selenium_tests, first_panel_on_excerpts_export_overview_xpath
from tests.selenium_tests.new_excerpt import new_excerpt
@skip_selenium_tests
@pytest.mark.param... |
153392 | def func():
print("func")
func() # $ resolved=func
class MyBase:
def base_method(self):
print("base_method", self)
class MyClass(MyBase):
def method1(self):
print("method1", self)
@classmethod
def cls_method(cls):
print("cls_method", cls)
@staticmethod
def stat... |
153447 | import logging
import os
from collections import namedtuple
import googleapiclient.discovery
import neo4j
from googleapiclient.discovery import Resource
from oauth2client.client import ApplicationDefaultCredentialsError
from oauth2client.client import GoogleCredentials
from cartography.config import Config
from carto... |
153493 | import time
import os
import torch
from utils.utils import NanError
def depth2class(depth, depth_start, depth_interval, depth_num, inv=False):
if not inv:
return (depth - depth_start) / (depth_interval + 1e-9)
else:
depth_end = depth_start + (depth_num-1) * depth_interval
inv_interv =... |
153515 | import argparse
import json
from bart_score import BARTScorer
def main(args):
instances = []
with open(args.input_file, "r") as f:
for line in f:
data = json.loads(line)
instances.append(data)
sources = []
targets = []
for instance in instances:
candidate ... |
153521 | import numpy as np
from .utils import memo, validate_tuple
__all__ = ['binary_mask', 'r_squared_mask', 'cosmask', 'sinmask',
'theta_mask']
@memo
def binary_mask(radius, ndim):
"Elliptical mask in a rectangular array"
radius = validate_tuple(radius, ndim)
points = [np.arange(-rad, rad + 1) for ... |
153571 | from django.conf.urls import url, include
from kitsune.groups import views
group_patterns = [
url(r"^$", views.profile, name="groups.profile"),
url(r"^/edit$", views.edit, name="groups.edit"),
url(r"^/avatar$", views.edit_avatar, name="groups.edit_avatar"),
url(r"^/avatar/delete$", views.delete_avata... |
153641 | import socket
host_1 = '127.0.0.1'
host_2 = '127.0.0.1'
port_1 = 8000
port_2 = 8001
# Server 1 must serve client 1
ServerSock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerSock1.bind(('', serverport1)) # connect server 1 to port 1
ServerSock1.listen(1)
print('(*) Server 1 started on ('+str(host_1)+':'+s... |
153644 | from ScopeFoundry import Measurement
from ScopeFoundry.scanning.base_raster_scan import BaseRaster2DScan
import time
import numpy as np
class BaseNonRaster2DScan(BaseRaster2DScan):
name = "base_non_raster_2Dscan"
def gen_raster_scan(self, gen_arrays=True):
self.Npixels = self.Nh.val*self.Nv.val
... |
153650 | from django.conf.urls.defaults import url, patterns
from django.contrib import admin
from django.shortcuts import render_to_response
from django.template import RequestContext
from django_histograms.utils import Histogram
class HistogramAdmin(admin.ModelAdmin):
histogram_field = None
histogram_months = 2
... |
153697 | from functools import singledispatch
from functools import update_wrapper
class singledispatchmethod:
"""Single-dispatch generic method descriptor.
Supports wrapping existing descriptors and handles non-descriptor
callables as instance methods.
"""
def __init__(self, func):
if not callabl... |
153760 | import yaml
import pandas as pd
import numpy as np
from glob import glob
import sys
# Create the datatable containing the samples, units and paths of all
# fastq files formatted correctly. This is vital for the snakemake
# pipeline, without it, the wildcards can't be created.
with open(sys.argv[1]) as f_:
config ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.