id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1742991 | import logging
from datetime import datetime
from goosepaper.goosepaper import Goosepaper
from goosepaper.reddit import RedditHeadlineStoryProvider
from goosepaper.rss import RSSFeedStoryProvider
from goosepaper.twitter import MultiTwitterStoryProvider
from goosepaper.weather import WeatherStoryProvider
from goosepape... |
1742997 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def nlohmann():
if "nlohmann" not in native.existing_rules():
http_archive(
name = "nlohmann",
build_file = "//third_party/nlohmann:nlohmann.BUILD",
url = "https://github.com/nlohmann/json/releases/down... |
1743041 | from .table_meta import * # noqa
from .data_parser import * # noqa
# from .generate_nl_description import * # noqa
|
1743110 | from unittest.mock import ANY, Mock, call
import flask
import pytest
from marshmallow import Schema, fields
from sqlalchemy import Column, Integer, String, sql
from flask_resty import (
Api,
ApiError,
AuthenticationBase,
AuthorizeModifyMixin,
GenericModelView,
HasAnyCredentialsAuthorization,
... |
1743127 | from unittest.mock import MagicMock
import numpy as np
import pytest
import tensorflow as tf
from tensorflow import keras
from chitra.trainer import Dataset, InterpretModel, Trainer, create_cnn
dataset = Dataset("./")
cnn = create_cnn("mobilenetv2", num_classes=1000, keras_applications=False)
trainer = Trainer(datas... |
1743146 | import pytest
from stp_zmq.test.helper import create_and_prep_stacks, \
check_stacks_communicating, add_counters_to_ping_pong
def sent_ping_counts(*stacks):
return {s.name: s.sent_ping_count for s in stacks}
def sent_pong_counts(*stacks):
return {s.name: s.sent_pong_count for s in stacks}
def recv_pi... |
1743156 | from django.apps import AppConfig
from django.conf import settings
class ReaderConfig(AppConfig):
name = 'reader' |
1743219 | from __future__ import print_function
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
import numpy as np
from copy import deepcopy
from utils.model_utils import calc_emd, calc_cd
# Number of children per tree levels for 2048 output points... |
1743248 | def selfDescriptiveNumber(num):
"""
-- Self-Descriptive Number
-- See: http://en.wikipedia.org/wiki/Self-descriptive_number
-- Checks if the given number is self-descriptive
-- num : a number, in base 10
-- returns : true if the number is self-descriptive, false otherwise
"""
sdNum=0 #create self-des... |
1743311 | from taurex.core import Singleton
from taurex.log import Logger
import inspect
import pkg_resources
class ClassFactory(Singleton):
"""
A factory the discovers new
classes from plugins
"""
def init(self):
self.log = Logger('ClassFactory')
self.extension_paths = []
self.rel... |
1743326 | from keras.models import load_model
from keras.models import Model
from keras import backend as K
from PIL import Image
import numpy as np
import os
import csv
LETTERSTR = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
def toonehot(text):
labellist = []
for letter in text:
onehot = [0 for _ in range(34)]
... |
1743327 | import asyncio
from parkour.apigateway import ApiGateway
from parkour.base import Base
from parkour.chat import Chat
from parkour.commands import Commands
from parkour.graphs import RoomGraphs
from parkour.logs import Logs
from parkour.records import Records
from parkour.reports import Reports
from parkour.sanctions i... |
1743343 | from enum import Enum, unique
@unique
class ImageType(Enum):
REGULAR = "0"
SNAP = "1"
STICKER = "2"
RESERVED_3 = "3"
IMAGE_ANIMATED = "4"
STICKER_ANIMATED = "5"
RESERVED_6 = "6"
RESERVED_7 = "7"
@unique
class VideoType(Enum):
REGULAR = "8"
SNAP = "9"
PTS = "A"
PTS_B =... |
1743356 | import tensorflow as tf
import numpy as np
import sys
import json
import sys
sys.path.append('../')
from lm.modeling import GroverModel, GroverConfig, _top_p_sample, sample
from sample.encoder import get_encoder, format_context, _tokenize_article_pieces, extract_generated_target
from tqdm import tqdm
import argparse
... |
1743364 | from typing import Iterable
import pytest
from faker import Faker
from gotrue import SyncGoTrueClient
from gotrue.exceptions import APIError
from gotrue.types import User
GOTRUE_URL = "http://localhost:9999"
TEST_TWILIO = False
@pytest.fixture(name="client")
def create_client() -> Iterable[SyncGoTrueClient]:
w... |
1743375 | import geosoft.gxpy.gx as gx
import geosoft.gxpy.grid as gxgrid
# create context
gxc = gx.GXpy()
# open grid
grid_surfer = gxgrid.Grid.open('elevation_surfer.grd(SRF;VER=V7)')
# copy the grid to an ER Mapper format grid file
grid_erm = gxgrid.Grid.copy(grid_surfer, 'elevation.ers(ERM)', overwrite=True)
exit()
|
1743377 | from IntervalReport import *
class BindingPatterns(IntervalTracker):
'''output summary counts of binding patterns.
The empty pattern is excluded.
'''
pattern = "(.*)_binding"
def __call__(self, track):
return self.getAll( """SELECT pattern, COUNT(*) as counts
... |
1743378 | from typing import Dict, Union, Any
from e2e.Libs.BLS import Signature
from e2e.Classes.Consensus.Element import Element, SignedElement
from e2e.Classes.Consensus.Verification import Verification, SignedVerification
from e2e.Classes.Consensus.SendDifficulty import SendDifficulty, SignedSendDifficulty
from e2e.Classes... |
1743427 | import os
from glob import glob
import argparse
import json
import warnings
from enum import Enum
"""
script checks solution files for Style Change Detection Task for PAN@CLEF21
"""
class ParseError(Enum):
""" ENUM for possible errors when parsing solution json """
INVALID_JSON = 'JSON not valid/parseable.'
... |
1743450 | class ConnectionInterrupted(Exception):
def __init__(self, connection, parent=None):
self.connection = connection
def __str__(self) -> str:
error_type = type(self.__cause__).__name__
error_msg = str(self.__cause__)
return f"Redis {error_type}: {error_msg}"
class CompressorErro... |
1743514 | import json
import os
import numpy as np
import pandas as pd
import pickle
from nesta.packages.crunchbase.predict.model import train
from nesta.packages.crunchbase.crunchbase_collect import predict_health_flag
TEST_PATH = os.path.dirname(__file__)
TRAINING_DATA = f'{TEST_PATH}/integration_test_training_data.csv'
UNL... |
1743535 | import os
import argparse
import json
from random import choice
import numpy as np
from h3ds.dataset import H3DS
from h3ds.log import logger
def main(h3ds_path, h3ds_token):
h3ds = H3DS(path=h3ds_path)
h3ds.download(token=h3ds_token)
scene_id = choice(h3ds.scenes())
# A scene can be loaded in its ... |
1743539 | from .autoencoder_estimator import AutoEncoderEstimator
from .base import BaseModule
from .classifier import Classifier
from .hourglass_estimator import HourglassEstimator
from .margipose_estimator import MargiposeEstimator
|
1743543 | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SalesmanCheckoutApp(AppConfig):
name = 'salesman.checkout'
label = 'salesmancheckout'
verbose_name = _("Checkout")
|
1743551 | from decimal import Decimal
import datetime
import unittest
import pytz
from dsmr_parser import obis_references as obis
from dsmr_parser import telegram_specifications
from dsmr_parser.exceptions import InvalidChecksumError, ParseError
from dsmr_parser.objects import CosemObject, MBusObject
from dsmr_parser.parsers ... |
1743587 | from __future__ import print_function
import unittest
import json
from bs4 import BeautifulSoup
from knowledge_repo import KnowledgeRepository
from knowledge_repo.app.models import Comment, Post, User
from knowledge_repo.app.proxies import db_session
class CommentTest(unittest.TestCase):
def setUp(self):
... |
1743617 | import re
from urllib.parse import urlencode
import requests
from flask import Blueprint, current_app, redirect, request, url_for, jsonify
from flask import session as flask_session
from backend.blueprints.spa_api.service_layers.utils import with_session
from backend.blueprints.steam import get_steam_profile_or_rando... |
1743626 | import helium
import unittest
import os
class TestBinaryInputFile(unittest.TestCase):
datadir = os.getenv('HEDATADIR', os.getenv('HOME', 'c:/') + '/Helium/data')
def test_data_dir(self):
self.assertTrue(os.path.isdir(self.datadir))
def test_fps(self):
pass
if __name__ == '__main__':
... |
1743632 | from unittest.mock import MagicMock
import pytest
from wellcomeml.io.epmc.client import EPMCClient
@pytest.fixture
def epmc_client():
return EPMCClient(
max_retries=3
)
def test_search(epmc_client):
epmc_client._execute_query = MagicMock()
epmc_client.search(
"session", "query", res... |
1743651 | import json
import os
import torch
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
from transformers import AutoTokenizer
from torchfly.text.datasets import Seq2SeqDataset
# pylint:disable=no-member
class TextRLCollator:
def __init__(self, config, tokenizer):
... |
1743688 | from typing import Dict
from allennlp.models.model import Model
from allennlp.data.vocabulary import Vocabulary
from allennlp.modules.conditional_random_field import ConditionalRandomField, allowed_transitions
from transformers.modeling_bert import BertModel, BertForPreTraining, BertConfig
from transformers.tokenizati... |
1743718 | import struct
class BinaryReader():
def __init__(self, fh):
self.fh = fh
self._N_size = struct.calcsize("@N")
self._P_size = struct.calcsize("@P")
def seek(self, pos, whence=0):
return self.fh.seek(pos, whence)
def read(self, length):
buf = self.fh.read(length)
... |
1743730 | import logging
from traitlets import Unicode, Integer, List
from traitlets.config import Application
from conda_store_server.app import CondaStore
class CondaStoreWorker(Application):
aliases = {
"config": "CondaStoreWorker.config_file",
}
log_level = Integer(
logging.INFO,
help... |
1743739 | from . import app
from . import Controller
controller = Controller.Controller()
@app.route('/')
def index():
return '找到更多好玩的东西:http://kingname.info'
@app.route('/<user>/register')
def register(user):
return controller.register(user)
@app.route('/<user>')
def check(user):
return controller.check_find_... |
1743742 | from datetime import datetime
import sqlalchemy as sa
from sqlalchemy.orm import relationship
from . import SQLAlchemyBase
from src.domain_logic.blog_domain import BlogDomain
class Blog(SQLAlchemyBase):
__tablename__ = "blogs"
id: int = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
title: st... |
1743818 | import re
import numpy as np
from os.path import join
from epub_conversion import convert_wiki_to_lines
from epub_conversion.wiki_decoder import almost_smart_open
from .wikipedia_language_codes import LANGUAGE_CODES
from .file import true_exists
from .bash import execute_bash
from .successor_mask import (
load_re... |
1743839 | import re
from ..punctuation import ALPHA_LOWER, ALPHA
from ...symbols import ORTH, NORM
_exc = {}
_abbr_period_exc = [
{ORTH: "A.B.D.", NORM: "Amerika"},
{ORTH: "Alb.", NORM: "albay"},
{ORTH: "Ank.", NORM: "Ankara"},
{ORTH: "Ar.Gör."},
{ORTH: "Arş.Gör."},
{ORTH: "Asb.", NORM: "astsubay"},
... |
1743849 | from mstrio.project_objects.datasets.cube_cache import CubeCache, list_cube_caches
from mstrio.connection import Connection
from datetime import datetime, timezone
from typing import List, Union
def _get_datetime(date):
"""String to date time conversion"""
return datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.00... |
1743859 | import os
from collections import defaultdict
import numpy as np
try:
import matplotlib
if not os.environ.get('DISPLAY'):
# Use non-interactive Agg backend
matplotlib.use('Agg')
import matplotlib.pyplot as plt
except ImportError:
import platform
if platform.python_implementation() =... |
1743874 | import pytest
import os
import pandas as pd
from primrose.readers.mysql_reader import MySQLReader
from primrose.configuration.configuration import Configuration
import mysql.connector
from primrose.data_object import DataObject, DataObjectResponseType
from unittest.mock import patch
def test_necessary_config():
... |
1743880 | import tensorflow as tf
from Models.BasicModel import BasicModel
class Model(BasicModel):
def __init__(self,
learning_rate,
init_word_embed,
init_idiom_embed,
size_embed=200,
num_units=100, # make sure that num_units = size_embed ... |
1743883 | from .rpc import worker_client
from .rpc import worker_server
from .rpc import scheduler_client
from .rpc import scheduler_server
|
1743921 | import numpy as np
from .. import tools
from ..algo import Algo
class DynamicCRP(Algo):
# use logarithm of prices
PRICE_TYPE = "ratio"
def __init__(self, n=None, min_history=None, **kwargs):
self.n = n
self.opt_weights_kwargs = kwargs
if min_history is None:
if n is N... |
1743952 | import spacy
from allennlp.common import Params
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data.tokenizers import Token, SpacyTokenizer
class TestSpacyTokenizer(AllenNlpTestCase):
def setup_method(self):
super().setup_method()
self.word_tokenizer = SpacyTokenizer()
de... |
1743953 | import os
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from logging import getLogger as get_logger
from math import ceil
from statistics import mean
from typing import Optional
from megfile.errors import S3FileChangedError, patch_method, raise_s3_error, s... |
1744095 | import numpy as np
import scipy.signal as signal
from scipy.interpolate import interp1d
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from astropy.io import fits
import emcee
import corner
import copy
import time
import os
import sys
import smart
def makeModel(teff, logg=5,... |
1744123 | import json
import re
from typing import List, Optional
from pydantic import BaseModel
from ..collection import MsgTypes
from ..model import GroupMsg
# at
class UserExtItem(BaseModel):
QQNick: str
QQUid: int
class AT(BaseModel):
Content: str
UserExt: List[UserExtItem]
UserID: List[int]
def a... |
1744154 | import random
from threading import Thread
import math
import rospy
import time
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
class Darwin:
"""
Client ROS class for manipulating Darwin OP in Gazebo
"""
def __init__(self,ns="/darwin/"):... |
1744213 | import logging
import os
from pathlib import Path
from shutil import copyfile, which
import click
from snowshu.configs import IS_IN_DOCKER
from snowshu.core.replica.replica_factory import ReplicaFactory
from snowshu.core.replica.replica_manager import ReplicaManager
from snowshu.logger import Logger
# Always check f... |
1744255 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .sample.ctdet import CTDetDataset
from .sample.ctdetSpotNet2 import CTDetDatasetSpotNet2
from .sample.ctdetSpotNetVid import CTDetDatasetSpotNetVid
from .sample.ctdetVid import CTDetDatasetVid
from .datas... |
1744272 | from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class MediaIds(Base):
__tablename__ = 'Media ids'
id = Column(Integer, primary_key=True)
file_id = Column(String(255))
filename = Column(String(255))
|
1744325 | from collections import OrderedDict
from htmlparsing import HTMLParsing, Selector
class ItemType(type):
def __new__(cls, what, bases=None, attrdict=None):
__fields__ = OrderedDict()
for name, selector in attrdict.items():
if isinstance(selector, Selector):
__fields__[... |
1744343 | from typing import Optional
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QVBoxLayout, QLineEdit, QTreeWidget, QTreeWidgetItem, QPushButton
from angr.analyses.decompiler.decompilation_options import options as dec_options
from angr.analyses.decompiler.optimization_passes import get_optimization... |
1744386 | import pytest
from frictionless import system, Plugin, Type, Resource, Schema, Field, describe
# General
def test_type_custom(custom_plugin):
schema = Schema(
fields=[
Field(name="integer", type="integer"),
Field(name="custom", type="custom"),
]
)
with Resource(pa... |
1744388 | import sys
import os
from glob2 import glob
import nibabel as nib
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from skimage.morphology import ball, binary_dilation, binary_closing
def get_foldernames(base_path, no_small=False):
walker = [x[0] for x in os.walk(base_pa... |
1744394 | class FamilyPlacementType(Enum,IComparable,IFormattable,IConvertible):
"""
The type of placement required for a given family.
enum FamilyPlacementType,values: Adaptive (8),CurveBased (5),CurveBasedDetail (6),CurveDrivenStructural (7),Invalid (9),OneLevelBased (0),OneLevelBasedHosted (1),TwoLevelsBased (2),... |
1744454 | from collections import Mapping, Set, Sequence
# dual python 2/3 compatability, inspired by the "six" library
string_types = (str, unicode) if str is bytes else (str, bytes)
iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()
def objwalk(obj, path=(), memo=None):
if memo is None:
m... |
1744509 | from __future__ import unicode_literals
from .client import get_client
def list(user_id):
client = get_client()
page_size = 100
offset = 0
return client.get('/users/{0}/tracks'.format(user_id), order='created_at',
limit=page_size,
... |
1744520 | import subprocess
import time
from aiohttp import web
from selenium.webdriver import Chrome
import pywebio
import template
import util
from pywebio.input import *
from pywebio.platform.aiohttp import static_routes, webio_handler
from pywebio.utils import to_coroutine, run_as_function
def target():
template.basi... |
1744556 | from bokeh.io import save
from bokeh.models.dom import Div, Styles
from bokeh.plotting import figure
p0 = figure(width=200, height=200)
p1 = figure(width=200, height=200)
p2 = figure(width=200, height=200)
p3 = figure(width=200, height=200)
p0.rect(x=0, y=0, width=1, height=1, fill_color="red")
p1.rect(x=0, y=0, widt... |
1744560 | print("\033[1;30m{}\033[0m".format(' 字体颜色:白色'))
print("\033[1;31m{}\033[0m".format(' 字体颜色:红色'))
print("\033[1;32m{}\033[0m".format(' 字体颜色:深黄色'))
print("\033[1;33m{}\033[0m".format(' 字体颜色:浅黄色'))
print("\033[1;34m{}\033[0m".format(' 字体颜色:蓝色'))
print("\033[1;35m{}\033[0m".format(' 字体颜色:淡紫色'))
print("\033[1;36m{}\033[0m".f... |
1744576 | import sys
import json
import os
import numpy as np
from scipy.optimize import linear_sum_assignment
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
import cv2
import pylab as pl
from numpy import linalg as LA
import random
import math
from mpl_toolkits.mplot3d import axes3d, Axes3D
from... |
1744583 | from rest_framework import exceptions, status, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .service import NotificationService
class NotificationViewSet(viewsets.ViewSet):
permission_classes = (IsAuthenticated,)
def list(self, request, *a... |
1744584 | from torch.utils import data
class BaseDataset(data.Dataset):
def __init__(self):
super().__init__()
@staticmethod
def _offset_and_limit(dataset_list, offset, limit):
dataset_list = dataset_list[offset:]
if limit:
dataset_list = dataset_list[:limit]
return data... |
1744606 | class Solution:
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
ss = [0]
up, down = 1, -1
for i, ch in enumerate(S):
if ch == "I":
ss.append(up)
up += 1
else:
ss.append(... |
1744625 | from pyquaternion import Quaternion
import inverse_kinematics
from visual_mpc.envs.util.interpolation import QuinticSpline
import logging
from intera_core_msgs.msg import EndpointState
from threading import Condition
import rospy
import numpy as np
from geometry_msgs.msg import Quaternion as Quaternion_msg
CONTROL_RA... |
1744630 | from typing import Union
from boa3.builtin import public
@public
def main(arg: Union[str, bool]) -> str:
if isinstance(arg, str):
return arg
else:
return 'boolean'
|
1744635 | import math
from typing import List
"""
You have a very large square wall and a circular dartboard placed on
the wall. You have been challenged to throw darts into
the board blindfolded. Darts thrown at the wall are represented
as an array of points on a 2D plane.
Return the maximum number of points that are with... |
1744665 | import time
import torch
from torch.utils.data import Dataset, DataLoader
from data import LJspeechDataset, collate_fn_synthesize
from model import WaveVAE
from torch.distributions.normal import Normal
import librosa
import os
import argparse
parser = argparse.ArgumentParser(description='Synthesize WaveVAE of LJSpeec... |
1744671 | from kwonly_args import kwonly_defaults
from .parser import ParserListener
class ObjectBuilderParams(object):
# By creating a subclass of this class and overriding these
# attributes you can change the default values of __init__().
default_object_creator = None
default_array_creator = None
defaul... |
1744681 | import os
from parglare import Grammar, Parser
this_folder = os.path.dirname(__file__)
model_str = '''
modelID 42
component myComponent {
in SomeInputSlot
out SomeOutputSlot
}
'''
def test_imported_actions_connect_by_symbol_name():
g = Grammar.from_file(os.path.join(this_folder, 'by_symbol_name/model.pg... |
1744685 | def load_global_step_from_predefined_list(exp):
global_step_dict = {'20180124_max20_2M': '1155015',
}
if exp not in global_step_dict.keys():
global_step_dict[exp] = '0'
global_step = global_step_dict[exp]
return global_step
def fancy_exp_name(exp):
fancy_dict = {'A... |
1744706 | import threading, atexit, sys
import time
try:
from thread import start_new_thread
except:
from _thread import start_new_thread
class MyError(Exception):
def __init__(self, msg):
return Exception.__init__(self)
def _atexit():
print('TEST SUCEEDED')
sys.stderr.write('TEST SUCEEDED\n')
... |
1744820 | import numpy as np
import numpy.ma as ma
import warnings
import numba
try:
import scipy.sparse as sp
SCIPY_INSTALLED = True
except ImportError:
SCIPY_INSTALLED = False
class InvalidValuesWarning(UserWarning):
pass
def _pad_list(x, padding_val=-999):
if not isinstance(x, list):
raise Typ... |
1744823 | import unittest
import random
import validate_docbr as docbr
def get_random_number_str(length):
numbers = '0123456789'
return ''.join(random.choice(numbers) for i in range(length))
class TestValidateDocs(unittest.TestCase):
"""Testa a função validate_docs"""
def test_correct_argument(self):
... |
1744880 | import _common as common
import ymake
import os
def onios_app_settings(unit, *args):
tail, kv = common.sort_by_keywords(
{'OS_VERSION': 1, 'DEVICES': -1},
args
)
if tail:
ymake.report_configure_error('Bad IOS_COMMON_SETTINGS usage - unknown data: ' + str(tail))
if kv.get('OS_VER... |
1744912 | from chainercv.chainer_experimental.datasets.sliceable import GetterDataset
from chainercv.chainer_experimental.datasets.sliceable.sliceable_dataset \
import _is_iterable
class TransformDataset(GetterDataset):
"""A sliceable version of :class:`chainer.datasets.TransformDataset`.
Note that it requires :ob... |
1744937 | import multiprocessing
import random
import time
import typing
import numpy as np
from transformers import GPT2TokenizerFast
from .dataclass import ModelParameter
from .utils_core import chunks, color_print
def render_video(model_output: typing.List[typing.Tuple[np.ndarray, typing.List[str]]],
coun... |
1744953 | from lib.receiver.Receiver import Receiver
from plugins.proxy_url_plugin import plugin as ProxyURL
import logging
import subprocess
import json
import os
dirname = os.path.dirname(os.path.realpath(__file__)) + "/../../"
class Proxy(Receiver):
def __init__(self, configuration, module, report_path):
Recei... |
1744971 | import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from mpl_toolkits.mplot3d import Axes3D
def plotSwarm( sim, t ):
fig = plt.figure()
ax = fig.gca(projection='3d')
locations = []
directions = []
for fish in... |
1744989 | from .mapper import ApiResponse, ApiResponseInterface
from .mapper.types import Timestamp, AnyType
from .model import User
__all__ = ['BlockedListResponse']
class BlockedListResponseInterface(ApiResponseInterface):
blocked_list: [User]
next_max_id: str
page_size: AnyType
class BlockedListResponse(ApiRe... |
1745051 | import numpy as np
def moving_average(data, window_size=5):
"""
Moving average.
Parameters
----------
data : array_like
An array of values.
window_size : int, optional
Moving average window size.
Returns
-------
result : array_like
Moving averaged array.
... |
1745155 | import sys
from unittest import TestCase
from kazoo.protocol import paths
if sys.version_info > (3, ): # pragma: nocover
def u(s):
return s
else: # pragma: nocover
def u(s):
return unicode(s, "unicode_escape")
class NormPathTestCase(TestCase):
def test_normpath(self):
self.as... |
1745175 | import argparse
import fileinput
import os
import subprocess
import sys
parser = argparse.ArgumentParser(description='Compile all GLSL shaders')
parser.add_argument('--glslang', type=str, help='path to glslangvalidator executable')
parser.add_argument('--g', action='store_true', help='compile with debug symbols')
args... |
1745197 | import pytest
from allennlp.common import Params
from allennlp.common.testing import ModelTestCase
from allennlp.models import Model
from allennlp_models import generation # noqa: F401
from tests import FIXTURES_ROOT
class BartTest(ModelTestCase):
def setup_method(self):
super().setup_method()
se... |
1745253 | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['MVCNN', 'mvcnn']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class MVCNN(nn.Module):
def __init__(self, num_classes=1000):
super(MVCNN, self).__init__()
... |
1745297 | from django.contrib.auth.views import LogoutView
from django.urls import include, path
from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_urls
from two_factor.urls import urlpatterns as tf_urls
from two_factor.views import LoginView
from .views import SecureView
urlpatterns = [
path(
'a... |
1745327 | from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponseRedirect
from django.views import View
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login,logout
from django.utils.decorators import method_decorator
from django.... |
1745341 | from setuptools import setup
setup(
name='Herd',
version='0.1.1',
author='<NAME>',
author_email='<EMAIL>',
packages=['herd', 'herd.BitTornado', 'herd.BitTornado.BT1'],
scripts=[],
url='https://github.com/russss/Herd',
description='A simpler implementation of Twitter Murder in python. D... |
1745402 | import re
def getFolder():
""" return the folder where this module is located"""
folderWithFileName = __file__
if(folderWithFileName[-1]=='c'):
fileName = __name__+".pyc"
else :
fileName = __name__+".py"
folderLength = len(folderWithFileName) - len(fileName)
folderWithoutF... |
1745432 | import torch
from npt.datasets.base import BaseDataset
class CIFAR10Dataset(BaseDataset):
def __init__(self, c):
super().__init__(
fixed_test_set_index=None)
self.c = c
def load(self):
"""
Classification dataset.
Target in last column.
60 000 rows... |
1745437 | import copy
import logging
import numpy as np
import operator
import torch
import torch.utils.data
import json
from detectron2.utils.comm import get_world_size
from detectron2.data import samplers
from torch.utils.data.sampler import BatchSampler, Sampler
from detectron2.data.common import DatasetFromList, MapDataset
... |
1745446 | from django.core.management.base import BaseCommand
from django.utils import translation
from django.conf import settings
from froide.account.models import User
class Command(BaseCommand):
help = "Sends mail to all users"
def handle(self, *args, **options):
translation.activate(settings.LANGUAGE_COD... |
1745459 | from __future__ import absolute_import
from collections import defaultdict
from flask_restful.reqparse import RequestParser
from itertools import groupby
from sqlalchemy.orm import contains_eager, joinedload, subqueryload_all
from typing import List # NOQA
from changes.api.base import APIView
from changes.api.serial... |
1745463 | import numpy as np
from gradman import Module, Tensor
class Linear(Module):
def __init__(self, idim, odim):
super(Linear, self).__init__()
self.w = Tensor(np.random.randn(idim, odim))
self.b = Tensor(np.random.randn(1, odim))
self.params = ["w", "b"]
def forward(self, i):
... |
1745498 | from bot.bot import Bot
from bot.handler import MessageHandler
from bot.constant import ParseMode
from bot.types import Format
import logging.config
logging.config.fileConfig("logging.ini")
TOKEN = "" #your token here
bot = Bot(token=TOKEN, api_url_base="")
def message_cb(bot, event):
bot.send_text(chat_id=eve... |
1745514 | import argparse
import logging
import csv
import json
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
logger = logging.getLogger()
def story_hit2json(args):
out = []
with open(args.story_hit_csv) as... |
1745522 | import numpy as np
from gdsfactory.simulation.modes.find_mode_dispersion import find_mode_dispersion
from gdsfactory.simulation.modes.get_mode_solver_rib import get_mode_solver_rib
def test_find_modes_dispersion():
ms = get_mode_solver_rib(wg_width=0.45)
modes = find_mode_dispersion(mode_solver=ms)
m1 = ... |
1745588 | from clusto.test import testbase
from clusto.schema import *
from clusto.drivers.base import *
class TestClustoCounter(testbase.ClustoTestBase):
def testCounterDefault(self):
e = Entity('e1')
c = Counter(e, 'key1')
self.assertEqual(c.value, 0)
d = Counter(e, 'key2', start=10)
... |
1745626 | from __future__ import annotations
from dataclasses import make_dataclass
from warnings import warn
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.regression.rolling import RollingOLS
from pqr.utils import align
def extract_annualizer(df_or_series: pd.DataFrame | pd.Series) ->... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.