id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1619008 | import aes128
import Print
import os
import shutil
import json
import listmanager
from Fs import Nsp as squirrelNSP
from Fs import Xci as squirrelXCI
from Fs import factory
from Fs.Nca import NcaHeader
from Fs import Nca
from Fs.File import MemoryFile
from Fs import Ticket
import sq_tools
import io
from ... |
1619041 | import io
from datetime import timedelta
from typing import Union, Optional
from .response import KustoStreamingResponseDataSet
from .._decorators import documented_by, aio_documented_by
from ..aio.streaming_response import StreamingDataSetEnumerator, JsonTokenReader
from ..client import KustoClient as KustoClientSync... |
1619082 | import os
import sys
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))))
sys.path.append(BASE_DIR)
from tools.path import ILSVRC2012_path
from simpleAICV.classification import backbones
from simpleAICV.classification import losses
import torchvision... |
1619088 | import os, sys
sys.path.append(os.path.realpath(os.path.dirname(__file__)))
import reaper_pp
import glm_pp
|
1619098 | import sys
import subprocess
import re
pal_warn = re.compile("Warning.*pal")
pal_dont_treat_as_warn = re.compile("Warning.*PAL_INSECURE")
proc = subprocess.Popen(sys.argv[1].split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in proc.stdout:
print line
if len(pal_warn.findall(line)) > 0:
... |
1619103 | import numpy as np
from deep_utils.utils.box_utils.boxes import Point
class VideoWriterCV:
def __init__(self, save_path, width, height, fourcc="XVID", fps=30, colorful=True, in_source='Numpy'):
import cv2
point = Point.point2point((width, height), in_source=in_source, to_source=Point.PointSource.C... |
1619111 | import logging
from typing import Optional, Tuple, Union
import numpy as np
import pandas as pd
import torch
from anndata import AnnData
from scvi import REGISTRY_KEYS
from scvi._compat import Literal
from scvi.data import AnnDataManager
from scvi.data.fields import CategoricalObsField, LayerField, NumericalObsField
... |
1619176 | import unittest
from fluentcheck.classes import Check
from fluentcheck.exceptions import CheckError
class TestDictsAssertions(unittest.TestCase):
def test_is_dict(self):
res = Check({}).is_dict()
self.assertIsInstance(res, Check)
try:
Check(123).is_dict()
self.fail... |
1619217 | import heapq
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param intervals: the given k sorted interval lists
@return: the new sorted interval list
"""
def mergeKSortedIntervalLis... |
1619381 | import time
import sys
from urllib.parse import parse_qs
from urllib.parse import urlparse
from oktaawscli.version import __version__
class OktaAuthMfaApp():
""" Handles per-app Okta MFA """
def __init__(self, logger, session, verify_ssl, auth_url):
self.session = session
self.logger = logger
... |
1619476 | from __future__ import absolute_import
from django.views.generic import View
from raven.contrib.django.models import client
from sentry.web.frontend.error_500 import Error500View
class DebugTriggerErrorView(View):
def get(self, request):
try:
raise ValueError('An example error')
exce... |
1619484 | from common.constant import StatusCode, ResponseStatus
from common.logger import get_logger
from common.repository import Repository
from common.utils import Utils, handle_exception_with_slack_notification, generate_lambda_response, make_response_body
from wallets.config import NETWORKS, NETWORK_ID, SLACK_HOOK
from wal... |
1619487 | import os.path
import sys
import anuga
from anuga import myid, numprocs, finalize, barrier
from anuga import Inlet_operator, Boyd_box_operator
"""
This test exercises the parallel culvert
"""
verbose = True
length = 40.
width = 16.
dx = dy = 2 # Resolution: Length of subdivisions on both axes
#---... |
1619501 | import os
from pathlib import Path
from unittest import mock
@mock.patch("click.get_app_dir", autospec=True)
def test_new_config(gad, tmp_path: Path, monkeypatch):
# TODO - is there a way to run this within the normal test framework, i.e. perhaps unloading/reloading datapane module so we can
# setup our mock... |
1619521 | import taichi as ti
import numpy as np
A = np.array([
[0, 1, 0],
[1, 0, 1],
[0, 1, 0],
])
def conv(A, B):
m, n = A.shape
s, t = B.shape
C = np.zeros((m + s - 1, n + t - 1), dtype=A.dtype)
for i in range(m):
for j in range(n):
for k in range(s):
for l in range(t):
... |
1619522 | import distutils.core, shutil, os, py2exe, subprocess, os, re, platform
' grep imports from first line of python files in given folder '
def grepimports(dir):
imports = set()
IMPORT_ = 'import '
for f in os.listdir(dir):
p = os.path.join(dir, f)
if not p.endswith("py"): continue
... |
1619575 | from clickhouse_driver import Client
import datetime
import pytz
import os
import datetime
import time
import sys
from urllib.parse import urlparse
url = os.environ.get('DATABASE_URL',"tcp://default@localhost/default?compression=lz4")
url = urlparse(url)._replace(scheme='clickhouse').geturl()
client = Client.from_u... |
1619619 | import numpy as np
def differential_evolution(fobj, bounds, mut=0.8, crossprob=0.7, popsize=30, gens=1000, mode='best/1'):
# Gets number of parameters (length of genome vector)
num_params = len(bounds)
# Initializes the population genomes with values drawn from uniform distribution in the range [0,1]
... |
1619646 | import os
import sys
class Config(object):
"""Configuration variables for this test suite
This creates a variable named CONFIG (${CONFIG} when included
in a test as a variable file.
Example:
*** Settings ***
| Variable | ../resources/config.py
*** Test Cases ***
| Example
| | l... |
1619698 | import numpy as np
from pybasicbayes.distributions import AutoRegression, DiagonalRegression, Regression
def get_empirical_ar_params(train_datas, params):
"""
Estimate the parameters of an AR observation model
by fitting a single AR model to the entire dataset.
"""
assert isinstance(train_datas, ... |
1619711 | from predicthq import Client
# Please copy paste your access token here
# or read our Quickstart documentation if you don't have a token yet
# https://docs.predicthq.com/guides/quickstart/
ACCESS_TOKEN = 'abc123'
phq = Client(access_token=ACCESS_TOKEN)
# broadcasts and events endpoints use the same approach for sea... |
1619741 | from .betfairstream import BetfairStream, HistoricalStream, HistoricalGeneratorStream
from .listener import BaseListener, StreamListener
from .stream import MarketStream, OrderStream
|
1619762 | from __future__ import annotations
from django import forms
from django.contrib.auth.forms import UserChangeForm as BaseUserChangeForm
from django.contrib.auth.forms import UserCreationForm as BaseUserCreationForm
from jcasts.shared.typedefs import User
class UserChangeForm(BaseUserChangeForm):
class Meta(BaseU... |
1619791 | import time
import numpy as np
from typing import List, Dict
from .base import BaseInstrument
from zhinst.toolkit.control.node_tree import Parameter
from zhinst.toolkit.interface import LoggerModule
_logger = LoggerModule(__name__)
MAPPINGS = {
"edge": {1: "rising", 2: "falling", 3: "both"},
"eventcount_mod... |
1619798 | def so_32(n):
"""Finds the symmetry preserving HNFs for the simple orthorhombic lattices
with a determinant of n. Assuming A = [[1,0,0],[0,2,0],[0,0,3]].
Args:
n (int): The determinant of the HNFs.
Returns:
srHNFs (list of lists): The symmetry preserving HNFs.
"""
from opf_pyt... |
1619816 | from pkg_resources import DistributionNotFound
from pkg_resources import get_distribution
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
pass
from .koopman import Koopman
from .koopman_continuous import KoopmanContinuous
__all__ = [
"Koopman",
"KoopmanContinuous",... |
1619826 | import json
import matplotlib.pyplot as plt
def autolabel(ax, rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%0.4f' % float(height),
... |
1619844 | r"""
Concentration of the eigenvalues
================================
The eigenvalues of the graph Laplacian concentrates to the same value as the
graph becomes full.
"""
import numpy as np
from matplotlib import pyplot as plt
import pygsp as pg
n_neighbors = [1, 2, 5, 8]
fig, axes = plt.subplots(3, len(n_neighbors... |
1619860 | import scipy.misc
import random
xs = []
ys = []
#points to the end of the last batch
train_batch_pointer = 0
val_batch_pointer = 0
#read data.txt
with open("driving_dataset/data.txt") as f:
for line in f:
xs.append("driving_dataset/" + line.split()[0])
#the paper by Nvidia uses the inverse of the... |
1619880 | from __future__ import print_function
import operator
from arcapix.fs.gpfs import ManagementPolicy, MapReduceRule
# create a policy object
p = ManagementPolicy()
# define a map function
def mapfn(f):
# returns a set of any file xattr names
try:
return set(f.xattrs.split())
except AttributeError... |
1619882 | from pathlib import Path
import typer
APP_NAME = "my-super-cli-app"
def main():
app_dir = typer.get_app_dir(APP_NAME)
app_dir_path = Path(app_dir)
app_dir_path.mkdir(parents=True, exist_ok=True)
config_path: Path = Path(app_dir) / "config.json"
if not config_path.is_file():
config_path.w... |
1619891 | import attr
import typing
from kgtk.kgtkformat import KgtkFormat
@attr.s(slots=True, frozen=False)
class KgtkMergeColumns:
"""Merge columns from multiple KgtkReaders, respecting predefined column
names with aliases.
"""
# For attrs 19.1.0 and later:
column_names: typing.List[str] = attr.ib(valid... |
1619905 | import glob
import os
import sys
import time
import cv2
import numpy as np
import png
from ip_basic import depth_map_utils
from ip_basic import vis_utils
def main():
"""Depth maps are saved to the 'outputs' folder.
"""
##############################
# Options
##############################
... |
1619913 | import optparse
from optparse import OptionParser
import sys
import base64
import binascii
import os
import random
from random import randrange
if ((len(sys.argv) < 5 or len(sys.argv) > 5) and '-h' not in sys.argv):
print("Usage: %s -s <C2 Server IP/domain> -p <C2 Server Port>" % sys.argv[0])
sys.exit(1)
pars... |
1619932 | import re
from dataclasses import dataclass
regex = r"978[-0-9]{10,15}"
pattern = re.compile(regex)
@dataclass(init=False, eq=True, frozen=True)
class Isbn:
"""Isbn represents an ISBN code as a value object"""
value: str
def __init__(self, value: str):
if pattern.match(value) is None:
... |
1619937 | from autodesk.scheduler import Scheduler
from autodesk.states import UP, DOWN
from pandas import Timedelta
def test_active_for_30minutes_with_60minute_limit_and_desk_down():
active_time = Timedelta(minutes=30)
limits = (Timedelta(minutes=60), Timedelta(minutes=30))
scheduler = Scheduler(limits)
delay... |
1619939 | from __future__ import absolute_import, division, print_function
from scitbx.math import tensor_rank_2_gradient_transform_matrix
from scitbx import matrix
from scitbx.array_family import flex
import cmath
import math
from six.moves import zip
mtps = -2 * math.pi**2
class structure_factor:
def __init__(self, xray_s... |
1620007 | import sys
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap_year ( year ):
return year % 4 == 0 and ( year % 100 != 0 or year % 400 == 0 )
def julian_day (month, day, year):
jday = 0
for m in range(month):
jday += days_in_month[m]
if m == 2 and is_leap_year(... |
1620027 | import tvm
from tvm.autotvm.measure.measure import Builder, Runner, MeasureResult, MeasureErrorNo
from flextensor.ppa_model import measure_latency
from flextensor.utils import get_iter_info
import time
class ModelBuilder(Builder):
def __init__(self, *args, **kwargs):
super(ModelBuilder, self).__init__(*ar... |
1620040 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys, pkg_resources, imp
def __bootstrap__():
global __bootstrap__, __loader__, __file__
__file__ = pkg_resources.resource_filename(__name__, 'cython_nms.so')
__loader__ = None
del __bootstrap__,... |
1620097 | from dataclasses import dataclass
from random import random, choice
from .. import database as db
@dataclass
class Location:
longitude: float
latitude: float
def random_location() -> Location:
"""Returns random location (lon, lat) while prioritizing (95% chance) areas with a lot of objects to export.""... |
1620111 | import json
import logging
from django.db import transaction
from node.blockchain.facade import BlockchainFacade
from node.blockchain.inner_models import (
CoinTransferSignedChangeRequestMessage, Node, NodeDeclarationSignedChangeRequestMessage,
PVScheduleUpdateSignedChangeRequestMessage, SignedChangeRequest
)... |
1620122 | import FWCore.ParameterSet.Config as cms
process = cms.Process("HLTBTAG")
process.load("L1TriggerConfig.L1GtConfigProducers.L1GtConfig_cff")
process.load("DQMServices.Components.EDMtoMEConverter_cff")
process.load("HLTriggerOffline.Btag.HltBtagValidation_cff")
#process.load("HLTriggerOffline.Btag.HltBtagValidationFast... |
1620134 | import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import numpy as np
try:
numeric_types = (int, float, long)
except NameError:
numeric_types = (int, float)
class SimpleVectorPlotter(object):
"""Plots vector data represented a... |
1620135 | from ....Methods import ParentMissingError
def get_is_stator(self):
"""Return True if the parent lamination is stator and False if is a rotor
Parameters
----------
self : Slot
A Slot object
Returns
-------
is_stator: bool
True if the Lamination is a stator and False if no... |
1620145 | import os
import hashlib
import shutil
import curses
import curses.wrapper
from progressBar import progressBar
# Something went wrong during installation
class InstallerException(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
class Installer:
def ... |
1620181 | from greenonbrown import green_on_brown
from imutils.video import count_frames, FileVideoStream
import numpy as np
import imutils
import glob
import cv2
import csv
import os
def frame_analysis(exgFile: str, exgsFile: str, hueFile: str, exhuFile: str, HDFile: str):
baseName = os.path.splitext(os.path.basename(exhuF... |
1620187 | from CommonServerPython import * # noqa: F403
from CommonServerUserPython import * # noqa: F403
import ansible_runner # pylint: disable=E0401
import json
from typing import Dict, cast, List, Union, Any
# Dict to Markdown Converter adapted from https://github.com/PolBaladas/torsimany/
def dict2md(json_block: Unio... |
1620226 | import cv2
import numpy as np
import os.path
from cv2 import WINDOW_NORMAL
from face_detection import find_faces
ESC = 27
def start_webcam(model_emotion, model_gender, window_size, window_name='live', update_time=50):
cv2.namedWindow(window_name, WINDOW_NORMAL)
if window_size:
width, height = window_... |
1620247 | import os
import logging
from getpass import getpass
from skcom.crypto import decrypt_text
def main():
logger = logging.getLogger('helper')
cfg_path = os.path.expanduser(r'~\.skcom\skcom.yaml')
try:
# 解密
with open(cfg_path + '.enc', 'rb') as enc_file:
secret = enc... |
1620281 | import torch
import itertools
import pytest
from piq import InformationWeightedSSIMLoss, information_weighted_ssim
from typing import Tuple, List
from skimage.io import imread
from contextlib import contextmanager
@contextmanager
def raise_nothing(enter_result=None):
yield enter_result
@pytest.fixture(scope='mo... |
1620309 | from main import absorbdict
# 送信元または宛先IPがAnyかつそのゾーンがUntrust以外の場合そのポリシーはリストに(Any*2)個追加する
# 送信元または宛先IPがVIPかつプロトコルがANYの場合そのポリシーはリストに(該当するVIP)個追加する
service_element_num = 1
src_address_element_num = 1
dst_address_element_num = 1
pre_services = {'"PING"': {"icmp": ''},
'"ICMP-ANY"': {"icmp": ''},
... |
1620330 | from sklearn.neighbors import KDTree
from os.path import join, exists, dirname, abspath
import numpy as np
import pandas as pd
import os, sys, glob, pickle
import nibabel as nib
from multiprocessing import Process
import concurrent.futures
from tqdm import tqdm
from scipy import ndimage
import argparse
BASE_DIR = dir... |
1620354 | from hathor.conf import HathorSettings
from hathor.simulator import FakeConnection
from tests import unittest
settings = HathorSettings()
class SyncV1HathorCapabilitiesTestCase(unittest.SyncV1Params, unittest.TestCase):
def test_capabilities(self):
network = 'testnet'
manager1 = self.create_peer(... |
1620361 | from typing import List
from .asset import Asset
from .jinja_renderer import JinjaRenderer
from .logging import getLogger
from .paths import Paths
from .process import fail
from .factset import Factset
logger = getLogger(__name__)
paths = Paths()
class Assetset():
"""A collection of Assets (external files) for u... |
1620371 | from .TftEndpoint import TftEndpoint
class SummonerEndpoint(TftEndpoint):
def __init__(self, url: str, **kwargs):
nurl = "/summoner/v1/summoners" + url
super().__init__(nurl, **kwargs)
class SummonerApiUrls:
by_account = SummonerEndpoint("/by-account/{encrypted_account_id}")
by_name = Su... |
1620392 | from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Text
from sqlalchemy.orm import relationship
from app.models.base import Base
class PredictBuildings(Base):
gid = Column(Integer, primary_key=True, autoincrement=True)
geom = Column(Text)
task_id = Column(Integer, primary_key=True)
... |
1620408 | import cv2 as cv
import numpy as np
img = cv.imread(r'C:\Users\PIYUS\Desktop\Image Processing\learning\Resources\Photos\park.jpg')
cv.imshow("Img", img)
blank = np.zeros(img.shape[:2], dtype='uint8')
b , g , r = cv.split(img)
# even after splitting how to get the actual color in place?
blue = cv.merge([b, blank, bla... |
1620434 | from __future__ import unicode_literals
from django.utils.safestring import mark_safe
def setting_widget(instance):
return mark_safe(
'''
<strong>{}</strong>
<p class="small">{}</p>
'''.format(instance, instance.help_text or '')
)
|
1620456 | import time
import pickle
from pathlib import Path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError
from aircal.export import INSERT_ACTION, UPDATE_ACTION, DELETE_ACTION
SC... |
1620473 | import argparse
def get_parser():
"""Returns an arguments parser"""
parser = argparse.ArgumentParser(description="Background Matting on Videos.")
parser.add_argument(
"-n", "--name", type=str, required=True, help="Name of processing."
)
parser.add_argument(
"-i", "--input", type=st... |
1620492 | from database.conn import db
from database.models import RawFacebookComments, RawTwitterComments, RawInstagramComments, RawYouTubeComments, RawHashtagComments
from peewee import *
from playhouse.migrate import *
if __name__ == "__main__":
db.connect()
db.create_tables([
RawFacebookComments,
Ra... |
1620547 | from cs231n.layers import *
from cs231n.fast_layers import *
def affine_relu_forward(x, w, b):
"""
Convenience layer that perorms an affine transform followed by a ReLU
Inputs:
- x: Input to the affine layer
- w, b: Weights for the affine layer
Returns a tuple of:
- out: Output from the ReLU
- cache... |
1620549 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^apply/$', views.coupon_apply, name='apply'),
]
|
1620578 | import numpy as np
import tensorflow as tf
from deepchem.models import TensorGraph
from deepchem.models.tensorgraph.layers import Feature, Conv1D, Dense, Flatten, Reshape, Squeeze, Transpose, \
CombineMeanStd, Repeat, GRU, L2Loss, Concat, SoftMax, Constant, Variable, Add, Multiply, InteratomicL2Distances, \
Sof... |
1620584 | from typing import Generator, Optional, Sequence, Union
from libcst import (
Assign,
AssignTarget,
Decorator,
FlattenSentinel,
ImportFrom,
ImportStar,
Module,
Name,
RemovalSentinel,
)
from libcst import matchers as m
from django_codemod.constants import DJANGO_1_9, DJANGO_2_0
from ... |
1620626 | import re
import os
import yaml
import random
import logging
import shutil
import numpy as np
import oneflow as flow
import argparse
from otrans.model import End2EndModel, LanguageModel
from otrans.train.scheduler import BuildOptimizer, BuildScheduler
from otrans.train.trainer import Trainer
from otrans.utils import co... |
1620633 | from rest_framework import viewsets
from rest_framework import mixins
from .models import Library
from .serializers import LibrarySerializer
from .permissions import IsRegisteredInLibrary
class LibraryViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Library.objects.all()
serializer_cl... |
1620640 | print("This line will be printed.")
x = 1
if x == 1:
# indented four spaces
print("x is 1.")
print("Goodbye, World!") |
1620643 | import argparse
from aumbry.cli import upload, edit, view
def parse_arguments(argv=None):
parser = argparse.ArgumentParser(
'aumbry',
description='CLI Tool for Aumbry'
)
subparsers = parser.add_subparsers()
upload.setup_arguments(subparsers)
edit.setup_arguments(subparsers)
... |
1620654 | from rest_framework.status import HTTP_400_BAD_REQUEST
ERROR_GROUP_USER_IS_LAST_ADMIN = (
"ERROR_GROUP_USER_IS_LAST_ADMIN",
HTTP_400_BAD_REQUEST,
"The related user is the last admin in the group. He must delete the group or "
"give someone else admin permissions.",
)
|
1620682 | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
import scipy.stats
flags = pd.read_csv("../dataviz/datasets/countries.csv").filter_rows("organisations >> un").split_columns('country', "|").explode('country').set_index('country').drop_duplicates(subset='flag', keep='first')
continents = flags.groupby("con... |
1620737 | class SolutionSort:
def longestWord(self, words: List[str]) -> str:
word_set = set(words)
# sort the words on the length and then the lexical word
words.sort(key = lambda s: (-len(s), s))
# Greedily to find the first word that qualifies
for word in words:
if all... |
1620761 | import os
from datetime import datetime
from enum import Enum
from mongoengine import (
DateTimeField,
Document,
DoesNotExist,
IntField,
ListField,
ReferenceField,
StringField,
signals,
)
from stpmex.resources import Orden
from speid import STP_EMPRESA
from speid.exc import MalformedOr... |
1620773 | from binaryninja import *
from multiprocessing import *
def get_address_from_sig(bv, sigList):
br = BinaryReader(bv)
result = 0
length = len(sigList) - 1
for search_func in bv.functions:
br.seek(search_func.start)
while bv.get_functions_containing(br.offset + length) != None and search_func in bv.get_funct... |
1620830 | import os
DATABASES = {
"default": {
"ENGINE": "django.db.backends.%s" % os.getenv("DB_BACKEND", "sqlite3"),
"NAME": os.getenv("DB_NAME", ":memory:"),
"USER": os.getenv("DB_USER"),
"PASSWORD": os.getenv("DB_PASSWORD"),
"HOST": os.getenv("DB_HOST", ""),
"PORT": os.ge... |
1620868 | import os
import argparse
from tqdm import tqdm
from tqdm.notebook import tqdm
from transformers import AdamW
from transformers.optimization import WarmupLinearSchedule
from data_loader import *
def calc_accuracy(X,Y):
max_vals, max_indices = torch.max(X, 1)
train_acc = (max_indices == Y).sum().data.cpu().n... |
1620873 | from flask import Flask, render_template
from Models import *
from CharsApi import BB_Chars_API
app = Flask(__name__)
api = BB_Chars_API()
@app.route('/')
def index():
characters = Characters.select()
return render_template('index.html', api=characters)
if __name__ == '__main__':
app.run(host="0.0.0.0"... |
1620920 | import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageMath
from scipy.stats import norm
def draw_curve(fn, draw,rgba=(250,255,0)):
x = 0
eps=1.0
for _ in range(1000):
pt1 = np.array([x,fn(x)])
pt2 = np.array([x+eps,fn(x+eps)])
x=x+eps
draw.line((pt1[0],pt1[1]... |
1620933 | import functools
import json
import logging
from datetime import timedelta
from requests.exceptions import ConnectionError
from requests_oauthlib import OAuth2Session
_LOGGER = logging.getLogger(__name__)
class MieleClient(object):
DEVICES_URL = "https://api.mcs3.miele.com/v1/devices"
ACTION_URL = "https://... |
1620947 | import torch
from torch.autograd import Variable
import torch.nn.functional as F
def one_hot_embedding(labels, num_classes):
'''
Embedding labels to one-hot form.
Args:
labels: (LongTensor) class labels, sized [N,].
num_classes: (int) number of classes.
Returns:
(tensor) encoded labe... |
1620978 | import typing
from collections import namedtuple
from django.utils import timezone
from django.db import transaction
from functools import cached_property
from rssant_common.validator import FeedUnionId
from rssant_common.detail import Detail
from rssant_config import MAX_FEED_COUNT
from rssant_feedlib import FeedRes... |
1620990 | if __name__ == "__main__":
#import cProfile, pstats, io
#pr = cProfile.Profile()
#pr.enable()
import sys
init_modules = set(sys.modules.keys())
while True:
from core import repl
from core.error import ReloadException, QuitException
try:
repl.Repl().run(Tru... |
1620996 | import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Demag, Zeeman, UniaxialAnisotropy
from finmag.energies.zeeman import TimeZeemanPython
import matplotlib.pyplot as plt
from finmag.util.f... |
1621009 | import time
from bot_python_sdk.bot_service import BoTService
from bot_python_sdk.device_status import DeviceStatus
from bot_python_sdk.configuration_store import ConfigurationStore
from bot_python_sdk.logger import Logger
LOCATION = 'Pairing Service'
RESOURCE = 'pair'
POLLING_INTERVAL_IN_SECONDS = 10
MAXIMUM_TRIES =... |
1621022 | import os.path
import pytest
from testsuite.databases.pgsql import discover
SQLDATA_PATH = os.path.join(
os.path.dirname(__file__), 'static/postgresql/schemas',
)
MIGRATIONS = os.path.join(
os.path.dirname(__file__), 'static/postgresql/migrations',
)
@pytest.fixture(scope='session')
def pgsql_local(pgsql_... |
1621026 | import torch as th
import torch.nn as nn
import torch.nn.functional as F
class NoiseRNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(NoiseRNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.... |
1621047 | n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
c = 0
a.sort()
b.sort()
r1 = a if len(a)>len(b) else b
r2 = a if len(a)<len(b) else b
for i in range(min(n,m)):
if r1[i]!=r2[i]:
if r2[i] not in r1:
c = c+1
elif r1[i] not in r2:
... |
1621062 | from typing import List, Tuple
import pp
from pp.component import Component
@pp.autoname
def coupler_straight(
length: float = 10.0,
width: float = 0.5,
gap: float = 0.27,
layer: Tuple[int, int] = pp.LAYER.WG,
layers_cladding: List[Tuple[int, int]] = [pp.LAYER.WGCLAD],
cladding_offset: float =... |
1621073 | from collections import ChainMap
class ScopedChainMap(ChainMap):
def getlevel(self, k, default_value=None, default_level=None):
"Look up a key and the level where it's stored, returning defaults if it doesn't exist"
for i, mapping in enumerate(self.maps):
try:
return ma... |
1621074 | def print_full_name(a, b):
print("Hello %s %s! You just delved into python." % (a, b))
return
if __name__ == '__main__':
first_name = raw_input()
last_name = raw_input()
print_full_name(first_name, last_name)
|
1621081 | from django.template.loader import render_to_string
from wagtail.core import blocks
class BaseStaticBlock(blocks.StaticBlock):
"""
This is used instead of blocks.StaticBlock to control markup in admin and apply styling
"""
def render_form(self, value, prefix='', errors=None):
return render_to_... |
1621095 | import unittest
from vdebug.opts import Options,OptionsError
class OptionsTest(unittest.TestCase):
def tearDown(self):
Options.instance = None
def test_has_instance(self):
Options.set({1:"hello", 2:"world"})
self.assertIsInstance(Options.inst(), Options)
def test_get_option(self)... |
1621212 | from __future__ import absolute_import
from django.db import models
from django.test import TestCase
from .models import Author, Book
signal_output = []
def pre_save_test(signal, sender, instance, **kwargs):
signal_output.append('pre_save signal, %s' % instance)
if kwargs.get('raw'):
signal_output.... |
1621252 | import json
import os
import shlex
import shutil
import subprocess
import tarfile
import glob
from pathlib import Path
from typing import List
import wget
from pesto.cli import PROCESSING_FACTORY_PATH
from pesto.cli.core.build_config import BuildConfig
from pesto.cli.core.config_loader import ConfigLoader
from pesto.... |
1621255 | import functools
import inspect
import six
import lasagne.layers.base
import pymc3 as pm
from pymc3.memoize import hashable
from gelato.specs.dist import get_default_spec, FlatSpec
from gelato.specs.base import DistSpec
__all__ = [
'LayerModelMeta',
'Layer',
'MergeLayer',
'bayes'
]
class LayerModelM... |
1621256 | import os
from BERT_DATA import CombineBertData
split = "train"
files = "/scratch365/yding4/bert_project/bert_prep_working_dir/" \
"hdf5_lower_case_1_seq_len_128_max_pred_20_masked_lm_prob_0.15_random_seed_12345_dupe_factor_5/wikicorpus_en"
path = files
if not os.path.exists(path):
raise FileNotFoundErr... |
1621257 | import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import norm
def prepare_input(y, X, end_time):
y0, y1 = y[np.isnan(y[:, 1])], y[~np.isnan(y[:, 1])]
x0, x1 = X[np.isnan(y[:, 1])], X[~np.isnan(y[:, 1])]
diagonal0, diagonal1 = coo_matrix((y0.shape[0], y0.shape[0])), coo_matr... |
1621293 | import sys
import time
import ecal.core.core as ecal_core
from ecal.core.publisher import StringPublisher
if __name__ == "__main__":
# initialize eCAL API. The name of our Process will be "Python Hello World Publisher"
ecal_core.initialize(sys.argv, "Python Hello World Publisher")
# Create a String Publisher t... |
1621302 | import unittest
import commands
import models
class TestGold(unittest.TestCase):
def test_number_gold_credit(self):
self.assertEqual(12, commands.reddit_gold.number_gold_credit())
commands.reddit_gold.store_user_buy(models.User('just-an-dev'), 1, None)
self.assertEqual(11, commands.reddit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.