id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4835928 | import re
import numpy as np
class MdfFile(object):
"""
Read, modify, export and write the Delft3D mdf file
Examples
--------
>>> import delft3d
>>> mdf = delft3d.MdfFile('example/example1.mdf')
"""
def __init__(self, filename):
self.filename = filename
self.data = se... |
4835992 | from django import forms
from django.utils.translation import ugettext as _
from wagtailimportexport.compat import AdminPageChooser, Page, WAGTAIL_VERSION_2_OR_GREATER
admin_page_params = {
'can_choose_root': True,
'show_edit_link': False,
}
admin_page_export_params = admin_page_params.copy()
if WAGTAIL_VE... |
4836003 | from abstract_stack import AbstractStack
class ArrayStack(AbstractStack):
"""LIFO Stack implementation using a Python list as underlying storage.
"""
def __init__(self):
"""Create an empty stack."""
super().__init__()
self._data = []
def __iter__(self):
p = self._top
... |
4836051 | import argparse
import json
import os
from collections import defaultdict
import os.path as osp
import numpy as np
from PIL import Image
from tqdm import tqdm
def parse_args():
"""Use argparse to get command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--task', '-t', choice... |
4836094 | from app.main import main
from flask import g, url_for, render_template, redirect, request
from flask_babel import lazy_gettext
from app import db
from app.models import Registrant, Clerk
from app.decorators import InSession
from app.services import SessionManager
from app.services.nvris_client import NVRISClient
from ... |
4836171 | import random
import pathlib
import scipy.io as sio
import numpy as np
import nibabel as nib
import torch
from torch.utils.data import Dataset
from utils import normalize_zero_to_one
class IXIData(Dataset):
def __init__(self, data_path, u_mask_path, s_mask_up_path, s_mask_down_path, sample_rate):
super(IX... |
4836183 | import os
import sys
if os.name != "nt":
sys.exit("Error: ship scripts require native Python 2.7. (wrong os.name)")
if sys.version_info[0:2] != (2,7):
sys.exit("Error: ship scripts require native Python 2.7. (wrong version)")
import glob
import shutil
import subprocess
from distutils.spawn import find_executa... |
4836189 | import sys
sys.path.append("../../")
from appJar import gui
with gui() as app:
app.label('hello world')
app.tree("t1",
"""<people>
<person><name>Fred</name><age>45</age><gender>Male</gender></person>
<person><name>Tina</name><age>37</age><gender>Female</gender></person>
<person... |
4836219 | import FWCore.ParameterSet.Config as cms
import sys
subsystem = "Ramdisk"
process = cms.Process(subsystem)
import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
process.load('DQM.Integration.config.inputsource_cfi')
from DQM.Integration.config.inputsource_cfi import options
pro... |
4836231 | from libp2p.crypto.secp256k1 import create_new_key_pair
from libp2p.crypto.serialization import deserialize_private_key, deserialize_public_key
def test_public_key_serialize_deserialize_round_trip():
key_pair = create_new_key_pair()
public_key = key_pair.public_key
public_key_bytes = public_key.serialize... |
4836236 | from django.core.management.base import BaseCommand, CommandError
import pages.location_page.fixtures as location_page_fixtures
'''
Loads service_page fixtures into your joplin environment.
Run with:
pipenv run python joplin/manage.py load_test_location_pages
'''
class Command(BaseCommand):
help = "Lo... |
4836237 | from vit.formatter.end import End
class EndEpoch(End):
def format(self, end, task):
return self.epoch(end)
|
4836245 | import numpy as np, torch
class BatchMiner():
def __init__(self, opt):
self.par = opt
self.name = 'semihard'
def __call__(self, batch, labels):
if isinstance(labels, torch.Tensor): labels = labels.detach().numpy()
bs = batch.size(0)
#Return distance ma... |
4836274 | ctx.tex_radius = ctx.gen_texture.radius.cell()
ctx.tex_radius.set(32)
ctx.tex_filename = ctx.gen_texture.filename.cell()
ctx.tex_filename.set("")
ctx.gen_texture.as_float.cell().set(True)
ctx.gen_texture.output.connect(ctx.texture)
|
4836292 | from django.urls import path
from .views import IdentityViewSet, PersonViewSet
person_list = PersonViewSet.as_view({
'get': 'list',
'post': 'create'
})
person_detail = PersonViewSet.as_view({
'get': 'retrieve',
'patch': 'partial_update',
'delete': 'destroy'
})
identity_detail = IdentityViewSet.as... |
4836305 | import unittest
from unittest.mock import patch, Mock
class TestTestBase(unittest.TestCase):
def assert_forwards(self, class_, method_name, *args,
new_args=None, new_kwargs=None,
meth_args=None, meth_kwargs=None, **kwargs):
def default(x, value):
... |
4836352 | from baconian.test.tests.set_up.setup import TestTensorflowSetup
from baconian.core.util import get_global_arg_dict
class TestCopyGlobally(TestTensorflowSetup):
def test_init_arg_decorator(self):
dqn, local = self.create_dqn()
env_spec = local['env_spec']
mlp_q = local['mlp_q']
dqn... |
4836355 | import re
from pathlib import Path
from typing import Optional, Tuple
from dl_plus.cli.args import Arg
from dl_plus.cli.commands.base import BaseInstallCommand, CommandError
from dl_plus.core import get_extractor_plugin_dir
from dl_plus.pypi import Wheel
PLUGIN_NAME_REGEX = re.compile(
r'^(?:dl-plus-extractor-)?... |
4836381 | from os import path
from glob import glob
from cStringIO import StringIO
import numpy as np
import h5py
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix
from util import sort_nicely, veclen, filter_reindex
def convert_sequence_to_hdf5(filename_pattern, loader_function, hdf_ou... |
4836409 | import os
import pandas as pd
from pandas.testing import assert_frame_equal
import pytest
from pyspark.sql import Row
from splink.maximisation_step import run_maximisation_step
from splink.blocking import block_using_rules
from splink.gammas import add_gammas
from splink.expectation_step import run_expectation_step
f... |
4836412 | import tensorflow as tf
from config import (
LABEL_KEY,
N_CLASSES,
FEATURE_KEY,
transformed_name
)
def _fill_in_missing(x):
default_value = '' if x.dtype == tf.string else 0
return tf.squeeze(
tf.sparse.to_dense(
tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]),
... |
4836434 | from .detector3d_template import Detector3DTemplate
import torch
import numpy as np
EVL_VIS=800
class BtcNet(Detector3DTemplate):
def __init__(self, model_cfg, num_class, dataset, full_config=None):
super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset, full_config=full_config)
... |
4836451 | import numpy as np
from vtk import vtkPolyData
from pcloudpy.core.filters.base import FilterBase
from ..io.converters import get_points_normals_from, get_polydata_from
from pypoisson import poisson_reconstruction
class ScreenedPoisson(FilterBase):
def __init__(self, depth=8, full_depth=5, scale=1.1, samples_pe... |
4836482 | import numpy as np
import tensorflow as tf
def preprocess_flow_batch(flow):
'''
Operation to make flow zero mean and unit variance.
This simplifies the learning procedure.
'''
mean, variance = tf.nn.moments(flow, axes=[1,2], keep_dims=True)
flow = (flow - mean) / tf.sqrt(variance)
return f... |
4836488 | import subprocess
import pytest
from typer.testing import CliRunner
from docs_src.subcommands import tutorial003
runner = CliRunner()
@pytest.fixture()
def mod(monkeypatch):
with monkeypatch.context() as m:
m.syspath_prepend(list(tutorial003.__path__)[0])
from docs_src.subcommands.tutorial003 i... |
4836519 | from usaspending_api.common.containers import Bunch
from usaspending_api.references.models import ObjectClass
OBJECT_CLASSES = None
def reset_object_class_cache():
"""
An unfortunate side effect of globals is that they don't get refreshed automatically
for tests. So, to keep the performance of caching ... |
4836527 | START_NONFUSED="""
#include <cnpy.h>
#include "mkl.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <time.h>
#include <cstdint>
#include <cstring>
#include <dlfcn.h>
#include <x86intrin.h>
// we are doing AC = AB * BC, reduce across the B dimen... |
4836542 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommonAppConfig(AppConfig):
name = 'krules_djangoapps_common'
verbose_name = _('KRules commons') |
4836566 | from sklearn import tree
from sklearn.metrics import accuracy_score
import pandas as pd
import os
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
import itertools
import math
from TMDataset import TMDataset
import const
import util
clas... |
4836567 | from bitmovin.errors import MissingArgumentError
from bitmovin.resources.models import RawID3Tag as RawID3TagResource
from .generic_id3_tag_service import GenericID3TagService
class RawID3(GenericID3TagService):
def __init__(self, http_client, muxing_type_url):
if not muxing_type_url:
raise M... |
4836583 | from __future__ import absolute_import
# import models into model package
from .ap_clk_src_type import APClkSrcType
from .apgps_status_type import APGPSStatusType
from .ap_info import APInfo
from .ap_list import APList
from .ap_list_element import APListElement
from .ap_state_reason_type import APStateReasonType
from ... |
4836602 | from keras import backend as K
from overrides import overrides
from ..masked_layer import MaskedLayer
class Multiply(MaskedLayer):
"""
This ``Layer`` performs elementwise multiplication between two tensors, supporting masking. We
literally just call ``tensor_1 * tensor_2``; the only reason this is a ``L... |
4836612 | import numpy as np
import math
class CU:
'''
纯跟踪控制器
'''
def __init__(self, ld):
'''
纯跟踪控制器初始化
参数:
ld: 预瞄距离
'''
self.ld = ld
def get_deltat(self, model, alpha):
'''
获取前轮转角
参数:
model: 被控模型
alpha: 期望... |
4836624 | import discord, json, requests, re, os, time, discum
from termcolor import colored
from discord import Webhook, RequestsWebhookAdapter
from discord.ext import commands
with open('config.json') as Parsed:
config = json.load(Parsed)
if config.get('embed_colour')[0] == '#':
Embed_Colour = re.sub('#', '0x', config.get(... |
4836634 | from keras.layers import BatchNormalization, Activation, Conv1D, MaxPooling1D, ZeroPadding1D, InputLayer
from keras.models import Sequential
import numpy as np
import librosa
def preprocess(audio):
audio *= 256.0 # SoundNet needs the range to be between -256 and 256
# reshaping the audio data so it fits into... |
4836697 | import serial
from deepstream import get, post
from time import sleep
device = "/dev/oled3"
baud = 9600
# Work in procress, need more records from deepstream
|
4836720 | from itertools import combinations
n = int(input())
array = input().split()
k = int(input())
comb_list = list(combinations(array, k))
a_list = [e for e in comb_list if 'a' in e]
print(len(a_list) / len(comb_list)) |
4836748 | import numpy as np
from rlscore.learner.global_rankrls import GlobalRankRLS
from rlscore.utilities.reader import read_sparse
from rlscore.measure import cindex
train_labels = np.loadtxt("./legacy_tests/data/rank_train.labels")
test_labels = np.loadtxt("./legacy_tests/data/rank_test.labels")
train_features = read_sparse... |
4836792 | import types
#def makeClass(base, path, name):
## class Foo(object):
## def __init__(self):
## pass
## Foo.__class__.__name__ = name
# meta = type(base)
# meta = types._calculate_meta(meta, (base,))
# print('path', path)
# ns = meta.__prepare__(name, (base,), {})
# return meta(pa... |
4836904 | import os
import subprocess
import sys
import yaml
from func_timeout import FunctionTimedOut, func_timeout
from behave import given, then, when
def run_pgmigrate(migr_dir, args):
cmd = [
'coverage', 'run', '-p', '--include=pgmigrate.py', './pgmigrate.py',
'-vvv', '-d', migr_dir, '-c', 'dbname=pg... |
4836906 | import logging
import os
import shutil
from datetime import timedelta
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.utils.dates import days_ago
from airmaps.instruments import settings
from airmaps.instruments import storage
from airmaps.instruments.utils import get... |
4836940 | import bsplines
from lv_model_3d import ThickCappedZEllipsoid
from utils import *
import h5py
import argparse
from phantom_common import load_scale_function
from rotation3d import rot_mat_z
description="""
Create a spline model for a synthetic 3D LV myocardium which
contracts cyclically either according to a s... |
4836949 | import pickle
import dill
import pytest
import autofit as af
@pytest.fixture(
name="optimizer"
)
def make_optimizer():
return af.DynestyStatic(
"name"
)
def test_serialize_optimiser(
optimizer
):
optimizer = pickle.loads(
pickle.dumps(
optimizer
)
)
... |
4836951 | import click
from steinbock._cli.utils import OrderedClickGroup
from steinbock.segmentation._cli.cellprofiler import cellprofiler_cmd_group
from steinbock.segmentation._cli.deepcell import (
deepcell_cli_available,
deepcell_cmd,
)
@click.group(
name="segment",
cls=OrderedClickGroup,
help="Perform... |
4836963 | import sys
import numpy as np
import tensorflow as tf
sys.path.append("../")
from config import FLAGS
class Encoder_vae(object):
def __init__(self, embedding, encoder_input_list, is_training=True, ru=False):
with tf.variable_scope("Encoder_input"):
self.embedding = embedding
sel... |
4836966 | import time
start = time.perf_counter()
for i in range(10000):
x = "aaaaa".replace("a", "e")
print(time.perf_counter() - start)
|
4837004 | from django.template import Context, Template
from django.test import TestCase
from oscar.test.factories import ProductFactory
from tests.factories import StoreFactory, StoreStockFactory
class StoreStockTest(TestCase):
def setUp(self):
self.product = ProductFactory()
self.store1_location = '{"ty... |
4837011 | import os
import pytest
from montreal_forced_aligner.command_line.train_dictionary import run_train_dictionary
from montreal_forced_aligner.command_line.mfa import parser
def test_train_dict(basic_corpus_dir, sick_dict_path, english_acoustic_model, generated_dir,
transcription_acoustic_model, tra... |
4837075 | key = 'put your key here'
sec = 'put your sec here'
token = 'put your token here'
num_iid = 'put your num_iid here'
|
4837115 | import datetime
import os
import sys
from typing import Callable, Dict
from junitparser import Failure, Error, Skipped, TestCase, TestSuite # type: ignore
from ...testpath import TestPath, FilePathNormalizer
CaseEventType = Dict[str, str]
class CaseEvent:
EVENT_TYPE = "case"
TEST_SKIPPED = 2
TEST_PASSED... |
4837144 | import numpy as np
import sys
import argparse
from maddux.predefined_environments import environments
def main():
"""Run CLI to get animation arguments"""
parser = argparse.ArgumentParser(description="Animate a given saved path")
parser.add_argument('-i', '--input', type=str, required=True,
... |
4837170 | from anygraph import Many
class Node(object):
nexts = Many('prevs')
prevs = Many('nexts')
if __name__ == '__main__':
node_1 = Node()
node_2 = Node()
node_3 = Node()
node_1.nexts = [node_2, node_3]
node_2.nexts.include(node_3)
node_3.nexts.include(node_1)
assert set(node_3.prevs... |
4837176 | class Block:
"""Minecraft PI block description. Can be sent to Minecraft.setBlock/s"""
def __init__(self, id, data=0):
self.id = id
self.data = data
def __cmp__(self, rhs):
return hash(self) - hash(rhs)
def __hash__(self):
return (self.id << 8) + self.data
... |
4837215 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '5'
import cv2
import numpy as np
from maskrcnn_benchmark.config import cfg
from demo.predictor import ICDARDemo, RRPNDemo
from maskrcnn_benchmark.utils.visualize import vis_image, write_result_ICDAR_RRPN2polys, zip_dir
from PIL import Image
import time
config... |
4837321 | import tensorflow as tf
import argparse
from model.zi2ziNet.unet import UNet
def inspect_graph():
from pprint import pprint
var_list = tf.global_variables()
collection_list = tf.get_default_graph().get_all_collection_keys()
pprint(var_list)
pprint(tf.get_default_graph().get_tensor_by_name("no_ta... |
4837336 | from webex_skills.supress_warnings import suppress_warnings
def create_nlp(app_path):
try:
with suppress_warnings():
from mindmeld.components.nlp import NaturalLanguageProcessor
except ImportError:
raise ImportError('You must install the extras package webex-assistant-sdk[mindmeld]... |
4837429 | from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import seaborn as sns
import numpy as np
def plot_score_hist(scores, tick_value=None):
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
ax = sns.distplot(scores, ax=ax)
if tick... |
4837451 | import torch
from mmdet.core.bbox import BaseBBoxCoder
from mmdet.core.bbox.builder import BBOX_CODERS
@BBOX_CODERS.register_module()
class CenterPointBBoxCoder(BaseBBoxCoder):
"""Bbox coder for CenterPoint.
Args:
pc_range (list[float]): Range of point cloud.
out_size_factor (int): Downsampl... |
4837452 | def rec_list_dir(path, rec=True):
from os.path import isdir, isfile, exists
from imghdr import what
rst = []
if exists(path):
if isdir(path) and rec:
from os import listdir
from os.path import join
for f in listdir(path):
rst += rec_list_dir(join(path, f))
elif isfile(path) and... |
4837454 | import unittest
from katas.kyu_5.two_joggers import nbr_of_laps
class NumberOfLapsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(nbr_of_laps(5, 3), [3, 5])
def test_equals_2(self):
self.assertEqual(nbr_of_laps(4, 6), [3, 2])
def test_equals_3(self):
self.as... |
4837455 | from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/", responses={"400": {"description": "Bad Request"}})
def home():
raise HTTPException(status_code=400, detail="Bad Request")
|
4837473 | import os
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def write_table():
with open(os.path.join(MODULE_DIR, "data_energies.txt")) as f:
lines = f.readlines()
vor = lines[-2].split()
flo = lines[-1].split()
with open(os.path.join(MODULE_DIR, "table_template.txt")) as f:
tabl... |
4837522 | import unittest
from numpy import pi, array, r_
from numpy.testing import (assert_array_almost_equal,
assert_allclose)
from pybladed.data import BladedRun
from . import utils
# De-duplicate repeated stations in Bladed output
def dedup(x):
return r_[x[::2], x[-1:]]
class BEMModel_aero... |
4837578 | import asyncio
import aiopg
from . import nwdb
from . import core
@core.handler
def set_object(client, key, value):
client.require_clan_role(client.clan_id, 'Admin')
value = json.dumps(value)
with (yield from nwdb.connection()) as conn:
cursor = yield from conn.cursor()
yield from cursor... |
4837579 | from mpipe import (OrderedStage, Pipeline)
def yes(value):
return value
def main():
stage = OrderedStage(yes, 4, disable_result=True)
pipe = Pipeline(stage)
for number in range(10):
pipe.put(number)
pipe.put(None)
count = 0
for _ in pipe.results():
count += 1
print... |
4837610 | import logging
import os
import pytorch_lightning as pl
import torch
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_metric_learning.distances import DotProductSimilarity
from pytorch_metric_learning.losses import SupConLoss
from tqdm.auto import tqdm
from .data_utils import utils
from .data_util... |
4837614 | import os
import numpy as np
from tqdm import tqdm
from data.util import modcrop,bgr2ycbcr,ycbcr2rgb
import torch
from JPEG_module import JPEG
import cv2
dataset_folder = '/media/ybahat/data/Datasets/BSD100_test/BSD100_test_HR'
images_list = os.listdir(dataset_folder)
jpeg_compressor_8 = JPEG.JPEG(compress=True,downs... |
4837619 | from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
nickname = models.CharField(max_length=50, blank=True)
class Meta(AbstractUser.Meta):
pass |
4837647 | import uuid
from .BaseScope import BaseScope
class UUIDPrimaryKeyScope(BaseScope):
"""Global scope class to use UUID4 as primary key."""
def on_boot(self, builder):
builder.set_global_scope(
"_UUID_primary_key", self.set_uuid_create, action="insert"
)
def on_remove(self, buil... |
4837656 | from typing import List
import numpy as np
import torch
class Player(object):
def __init__(self, id=1):
self.id = id
def __eq__(self, other):
if not isinstance(other, Player):
# don't attempt to compare against unrelated types
return NotImplemented
return sel... |
4837674 | from pybaseball.datahelpers import singleton
def test_singleton() -> None:
class MySingleton(singleton.Singleton):
def __init__(self, my_arg: int, my_kwarg: str = 'default'):
self.my_arg = my_arg
self.my_kwarg = my_kwarg
mine = MySingleton(1)
other = MySingleton(2)
ass... |
4837687 | from typing import Tuple, List
from federatedml.util import LOGGER
from federatedml.util import consts
tree_type_dict = {
'guest_feat_only': 0, # use only guest feature to build this tree
'host_feat_only': 1, # use only host feature to build this tree
'normal_tree': 2, # a normal decision tree
'laye... |
4837722 | from itertools import count
import io
from typing import Tuple
def get_code_in_range(code_text: str, start_pos: Tuple[int, int], end_pos: Tuple[int, int]) -> str:
"""
Get the code text given a range in the form (start_line, start_column), (end_line, end_column).
Notes:
* This follow com... |
4837763 | import torch
import torch.nn as nn
from ..builder import BACKBONES
@BACKBONES.register_module()
class VISDIALPRINCIPLES_BACKBONE(nn.Module):
def __init__(self, dropout, nhid, ninp, img_feature_size, dropout_fc):
super().__init__()
self.dropout = dropout
self.nhid = nhid
self.nin... |
4837776 | class MathOperationTypes:
EQUALS = "="
GREATER = ">"
LESS = "<"
EQUALS_OR_LESS = "<="
EQUALS_OR_GREATER = ">="; |
4837784 | from pages.models import Page, Content
from rest_framework import serializers
from django.contrib.auth import get_user_model
from pages import settings
from django.contrib.sites.models import Site
class ContentSerializer(serializers.ModelSerializer):
class Meta:
model = Content
fields = '__all__'
... |
4837823 | from setuptools import setup, find_packages
setup(
name='the-channels',
version="0.5",
namespace_packages=['channels'],
install_requires=['requests', 'beautifulsoup4'],
packages=find_packages(),
)
|
4837857 | import requests
import re
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''ElasticSearch 1.4.0/1.4.2 RCE''',
"description": '''The Groovy scripting engine in Elasticsearch before 1.3.8 and 1.4.x before 1.4.3 allows remote attackers to bypass the sandbox protection m... |
4837873 | from datetime import timedelta
from mimetypes import guess_type
from django.conf import settings
from django.db import models, transaction
from django.utils import timezone
from django.utils.crypto import get_random_string
from structlog import get_logger, threadlocal
from lego.apps.files.exceptions import UnknownFi... |
4837903 | import numpy as np
N = 512
n_dof = 3*N - 3
mol = 6.02214076*10**23
kb = 1.38064852*10**(-23)
T = np.loadtxt("Ref.temp")
ke = np.loadtxt("Ref.kinetic")
virial = np.loadtxt("Ref.virial")
pressure = np.loadtxt("Ref.pressure")
volume = np.loadtxt("Ref.volume")
# compare ke
ke_calc = (n_dof*T*kb*mol)
print (v... |
4837908 | from typing import Optional, Union, List, Any
from . import *
class Constraint(Identified):
"""The Constraint class can be used to assert restrictions on the
relationships of pairs of Feature objects contained by the same
parent Component. Uses of this class include expressing
containment (e.g., a pl... |
4837911 | from setuptools import setup
setup(
name='oboe',
version='0.2',
description='Converts an Obsidian vault into HTML',
url='https://github.com/kmaasrud/oboe',
author='kmaasrud',
author_email='<EMAIL>',
license='MIT',
packages=['oboe'],
install_requires=[
'markdown2',
'regex... |
4837930 | import unittest
import sys
import threading
import random
import time
import stackimpact
from stackimpact.runtime import runtime_info, min_version
# python3 -m unittest discover -v -s tests -p *_test.py
class AgentTestCase(unittest.TestCase):
def test_run_in_main_thread(self):
if runtime_info.OS_WIN:
... |
4837940 | import os
import dolfin as df
from numpy import average
from finmag.energies import Demag
from finmag.field import Field
from finmag.util.meshes import from_geofile
TOL = 1e-3
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
Ms = 1e6
def test_field():
"""
Test the demag field.
H_demag should be eq... |
4837954 | import os
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
TEMPLATES = [
{"BACKEND": "django.template.backends.django.Django... |
4837979 | import json
import pyfiglet
from passlib.utils import generate_password
import random
from redis import Redis
goodfonts = ['banner',
'standard',
'digital',
'f15_____',
'banner3',
'c1______']
def random_font():
#fonts = pyfiglet.FigletFont().getFonts... |
4837988 | from api.api_command import APICommand
from plugins import plugins
class Install(APICommand):
def execute(self, params):
if params not in plugins:
self.send_error('Plugin not found')
return None
plugin = plugins[params]
if (plugin.install()):
self.send... |
4837992 | from frozendict import frozendict
__all__ = ['USBDefs', 'URBDefs']
class AutoDescEnum:
def __init_subclass__(cls, *args, **kwargs):
super().__init_subclass__(*args, **kwargs)
# Build a dict with descriptions for each field value.
# This is used for scapy packet display.
cls.desc ... |
4838001 | try:
import memory_profiler
except ImportError:
print('Please install the memory profiler to run this example')
print('pip install -U memory-profiler')
else:
@memory_profiler.profile
def main():
n = 100000
a = [i for i in range(n)]
b = [i for i in range(n)]
c = list(r... |
4838004 | from agent import streamsets, pipeline, di
from agent.modules import constants
from agent.streamsets import StreamSets
from agent.modules.logger import get_logger
logger = get_logger(__name__, stdout=True)
di.init()
def create_streamsets():
if len(streamsets.repository.get_all()) > 0:
logger.info('You al... |
4838013 | import math
from typing import List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import nltk
nltk.download('punkt')
from tqdm import tqdm
def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should ... |
4838039 | import pytest
from magma import clear_cachedFunctions
import magma
@pytest.fixture(autouse=True)
def magma_test():
import magma.config
magma.config.set_compile_dir('callee_file_dir')
clear_cachedFunctions()
magma.frontend.coreir_.ResetCoreIR()
magma.generator.reset_generator_cache()
|
4838047 | import copy
from typing import (
Callable,
List,
Tuple,
Optional,
Union,
Iterator,
Iterable,
TYPE_CHECKING,
)
import uuid
if TYPE_CHECKING:
import pyarrow
import ray
from ray.data.context import DatasetContext
from ray.data.block import Block
from ray.data.impl.block_list import Bl... |
4838099 | import os, sys
import subprocess, re
# For compatibility:
# https://support.microsoft.com/en-us/topic/howto-specify-serial-ports-larger-than-com9-db9078a5-b7b6-bf00-240f-f749ebfd913e
PORT_USER = 'COM9'
PORT_INTERNAL = 'BLE'
BIN = 'setupc.exe'
def cd_to_install():
# com0com needs to read inf from install path
... |
4838119 | import importlib
import sys
from pyfix.codec import Codec
from pyfix.journaler import DuplicateSeqNoError
from pyfix.message import FIXMessage, MessageDirection
from pyfix.session import *
from enum import Enum
from pyfix.event import FileDescriptorEventRegistration, EventType, TimerEventRegistration
class Connection... |
4838147 | from iconservice import *
from .tokens.IRC2mintable import IRC2Mintable
from .tokens.IRC2burnable import IRC2Burnable
from .utils.checks import *
TAG = 'bnXLM'
TOKEN_NAME = 'Balanced Lumens'
SYMBOL_NAME = 'bnXLM'
DEFAULT_PEG = 'XLM'
DEFAULT_ORACLE_NAME = 'BandChain'
INITIAL_PRICE_ESTIMATE = 21 * 10**16
MIN_UPDATE_TIM... |
4838163 | date_columns = [
'date_onset_symptoms',
'date_admission_hospital',
'date_confirmation',
'travel_history_dates',
'date_death_or_discharge',
]
# REGEX PATTERNS
anchor_wrap = lambda s: f"^{s}$"
boolean_or = lambda l : "|".join([f'({x})' for x in l])
na_string = 'NA'
rgx_empty = '^$'
rgx_na_valu... |
4838186 | import datetime
import json
import logging
import os
import sys
import tempfile
import time
from decimal import Decimal
import boto3
import domovoi
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), 'domovoilib')) # noqa
sys.path.insert(0, pkg_root) # noqa
from dss import stepfunctions, Config, Bu... |
4838207 | class Metadata:
def __init__(self, obj):
"""
See "https://smartystreets.com/docs/cloud/international-street-api#metadata"
"""
self.latitude = obj.get('latitude', None)
self.longitude = obj.get('longitude', None)
self.geocode_precision = obj.get('geocode_precision', No... |
4838246 | class Action:
def __init__(self, txt):
self.txt = txt
def __str__(self):
return '%s: %s' % (self.__class__.__name__, self.__dict__)
class UndoneAction(Action):
def __str__(self):
return '%s: UNDONE' % self.__class__.__name__
class SetResourcesAction(UndoneAction):
pass
class ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.