id
stringlengths
3
8
content
stringlengths
100
981k
3299277
import warnings from torch import nn from torchvision import models from torchvision.transforms import transforms class VGGEncoder(nn.Module): def __init__(self, normalize=True, post_activation=True): super().__init__() if normalize: mean = [0.485, 0.456, 0.406] std = [0....
3299279
from builtins import object from django.db.models import Q, Count from django.db.models.aggregates import Sum from django.contrib.contenttypes.models import ContentType from memoize import memoize from moneyed.classes import Money from bluebottle.clients import properties from bluebottle.initiatives.models import ...
3299290
from .geocoding import Geocoding from .isolines import Isolines __all__ = [ 'Geocoding', 'Isolines' ]
3299293
import os import sys from sim_user import SimulatedUser from progress_indicator import ProgressIndicator from config_readers.simulation_config_reader import SimulationConfigReader import gc import logging def main(config_filename): """ The main simulation! For every configuration permutation, create a Sim...
3299294
import numpy as np from Florence import * def explicit_dynamics_mechanics(): """A hyperelastic explicit dynamics example using Mooney Rivlin model of a column under compression with cubic (p=3) hexahedral elements """ mesh = Mesh() mesh.Parallelepiped(upper_right_front_point=(1,1,6),nx=3,ny=3...
3299321
import numpy as np import random import os from .eda import AutoEDA from .data_utils import ohe2cat from .log_utils import info, debug class AutoSample: def __init__(self, y_onehot): self.auto_eda = AutoEDA() self.y_onehot = y_onehot self.sample_num, self.class_num = y_onehot.shape ...
3299383
import magma as m class And2(m.Circuit): name = "And2" io = m.IO(I0=m.In(m.Bit), I1=m.In(m.Bit), O=m.Out(m.Bit)) def test_str_repr_core(): #Dont care what values they return as long as they retun non empty strings assert str(m.Circuit) assert repr(m.Circuit) assert str(m.circuit.CircuitKind)...
3299384
from django.shortcuts import render from django.views.generic.edit import CreateView from .models import Aqua class Add(CreateView): model = Aqua fields = ('title','content','app_name' ) template_name = 'add.html' success_url = '/aqua/'
3299428
import uuid from flask import jsonify, request from flask_login import UserMixin from passlib.hash import pbkdf2_sha256 from pymongo import ReturnDocument from werkzeug.security import check_password_hash, generate_password_hash from bson.objectid import ObjectId from app import mongo, login_manager class User(User...
3299431
from src.gamemodes import game_mode, GameMode, InvalidModeException from src.messages import messages from src.functions import get_players from src.events import EventListener from src import channels, users # original idea by Rossweisse, implemented by Vgr with help from woffle and jacob1 @game_mode("guardian", minp...
3299443
import ptypes, ndk from ptypes import * import functools, operator, itertools, types, math ptypes.setbyteorder(ptypes.config.byteorder.littleendian) ### Primitive types class ULONG(pint.uint32_t): pass class LONG(pint.int32_t): pass class USHORT(pint.uint16_t): pass class BYTE(pint.uint8_t): pass class WORD(pint.uin...
3299446
import websocket import json # https://github.com/aspnet/SignalR/blob/release/2.2/specs/HubProtocol.md ws = None def encode_json(obj): # All JSON messages must be terminated by the ASCII character 0x1E (record separator). # Reference: https://github.com/aspnet/SignalR/blob/release/2.2/specs/HubProtocol.md#js...
3299450
from TLA.Analysis.table_1 import analysis_table from TLA.Analysis.table_2 import analysis_table2 def analyse_data(): analysis_table() analysis_table2() if __name__ == "__main__": analysis_table() analysis_table2()
3299452
import os import arrow from jinja2 import Environment, FileSystemLoader, select_autoescape from lemur.plugins.utils import get_plugin_option loader = FileSystemLoader(searchpath=os.path.dirname(os.path.realpath(__file__))) env = Environment( loader=loader, # nosec: potentially dangerous types esc. autoescape...
3299463
from datasets.custom_dataset_factory_base import CustomDatasetFactoryBase from datasets.interaction_binary_dataset import InteractionBinaryDataset from metrics.result_scorer_f1_binary_factory import ResultScorerF1BinaryFactory class InteractionBinaryDatasetFactory(CustomDatasetFactoryBase): def get_metric_factor...
3299493
from lasagne.layers import Layer class HighwayLayer(Layer): def __init__(self, incoming, layer_class, gate_nonlinearity=None, **kwargs): super(HighwayLayer, self).__init__(incoming) self.H_layer = layer_class(incoming, **kwargs) if gate_nonlinearity: k...
3299565
import urllib.request # 此处其实已经并不能得到正常的网页了,原因有很多 # 1. urllib并不能这样直接搞 https 还需要ssl辅助 # 2. 百度有反爬虫,没伪装成浏览器,就莫得。 def load_data(): url = "https://www.baidu.com" # 系统的urlopen并没有添加代理的功能,需要我们自定义这个功能 # 安全 套阶层 sll 第三方的CA数字证书 # http 80端口 和 https 443端口 # urlopen为什么可以请求数据 handler处理器 # 自己的oepner请求数据 # ...
3299582
from demosys.effects import effect class Empty(effect.Effect): def __init__(self): pass def draw(self, time, frametime, target): pass
3299588
from __future__ import absolute_import import numpy as np import time import fastlmm.util.standardizer as stdizer import warnings #TODO: wrap C-stuff here? def mean_impute(X, imissX=None, maxval=2.0): ''' mean impute an array of floats --------------------------------------------------- X ...
3299594
import os import re import sqlitecollections as sc wd = os.path.dirname(os.path.abspath(__file__)) def define_env(env): env.variables["package_version"] = sc.__version__ env.variables["benchmarks"] = "\n".join( f""" === "{p}" === "dict" {{!benchmark_results/{p}/dict.md!}} === "list"...
3299617
from lib.base import QualysBaseAction __all__ = [ 'AddHostsAction' ] class AddHostsAction(QualysBaseAction): def run(self, hosts, vulnerability_management, policy_compliance): if policy_compliance and vulnerability_management: host_type = 'both' elif policy_compliance and not vuln...
3299647
from enum import Enum, IntEnum from typing import Dict, List from pydantic import BaseModel, Field, root_validator from spectree import SecurityScheme, Tag api_tag = Tag(name="API", description="🐱", externalDocs={"url": "https://pypi.org"}) class Order(IntEnum): asce = 1 desc = 0 class Query(BaseModel):...
3299672
import json import zipfile from collections import Counter import jieba from tqdm import tqdm from config import * from utils import ensure_folder def extract(folder): filename = '{}.zip'.format(folder) print('Extracting {}...'.format(filename)) with zipfile.ZipFile(filename, 'r') as zip_ref: zi...
3299679
import attr from .galaxy import Galaxy @attr.s class AbstractPlayer: name: str = attr.ib(init=False) """ Player's name. Please make it short (less than 12 characters), or you will break the gif and reports. """ def next_turn(self, galaxy: Galaxy, context: dict) -> Galaxy: """ ...
3299680
import unittest from mock import Mock from representor import Representor def adapter(): adapter = Mock() adapter.media_type = "application/hal+json" adapter.parse.return_value = "parsed" adapter.build.return_value = "built" return adapter class TestRepresentor(unittest.TestCase): def setUp(s...
3299712
class BVH(object): def __init__(self): super(BVH, self).__init__() self.root = [] self.channel_values = [] self.channel_dict = {} self.position_values = [] self.position_dict = {} self.display_frame = 2000 def load_from_file(self, bvh_file_path): bvh_file = open(bvh_file_path, 'r') bvh_str = b...
3299749
from django_filters import rest_framework as filters from .models import Plan, Product, Version class PlanFilter(filters.FilterSet): slug = filters.CharFilter(field_name="plan_template__planslug__slug") product = filters.CharFilter(field_name="plan_template__product") class Meta: model = Plan ...
3299754
from typing import Optional, Tuple from functools import partial import transformers from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader, Dataset from torchvision.transforms import transforms from src.datamodules.datasets.dataset_modality import DatasetModality from src.datamodul...
3299767
import pytest from kubernetes.client import V1Capabilities from kubernetes.client import V1EnvVar from kubernetes.client import V1EnvVarSource from kubernetes.client import V1HostPathVolumeSource from kubernetes.client import V1NodeAffinity from kubernetes.client import V1NodeSelector from kubernetes.client import V1No...
3299787
import pygrib import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap grbs = pygrib.open('../sampledata/eumetsat_precip.grb') grb = grbs.readline() fld = grb['values'] lats, lons = grb.latlons() rsphere = (grb.projparams['a'], grb.projparams['b']) lon_0 = grb.projparams['lon_0'] h =...
3299804
import pyOcean_cpu as ocean # This should run on a single thread a = ocean.ones([10,10],ocean.double) print(ocean.sum(a,0)) # Each thread should reduce the result for its outputs a = ocean.ones([100,50],ocean.double) print(ocean.sum(a,0)) # All threads should jointly reduce each output a = ocean.ones([3,10000],ocean...
3299823
import os from os import makedirs from os.path import join, exists import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from .constants import VIZ_ROOT class ImagePreprocess: def __init__(self,input,labels = None): self.suffixes = ('.jpeg', '.jpg', '.p...
3299863
import pyrevolve.revolve_bot.brain class Brain(object): @staticmethod def from_yaml(yaml_brain): brain_type = yaml_brain['type'] if brain_type == pyrevolve.revolve_bot.brain.BrainNN.TYPE: return pyrevolve.revolve_bot.brain.BrainNN.from_yaml(yaml_brain) elif brain_type == ...
3299889
import argparse import mir3.data.linear_decomposition as ld import mir3.module class Extract(mir3.module.Module): def get_help(self): return """extracts the left or right side of a linear decomposition""" def build_arguments(self, parser): parser.add_argument('side', choices=['left', 'right']...
3299966
import unittest import json from mock import patch from zkfarmer.zkfarmer import ZkFarmer from zkfarmer.utils import create_filter from kazoo.testing import KazooTestCase from kazoo.exceptions import BadVersionError class TestZkFarmer(KazooTestCase): def test_list_nonexistent_node(self): """List a node w...
3299971
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("installed_packages", [ ("MariaDB-server"), ("MariaDB-client"), ("python2-PyMySQL"), ("ga...
3299975
import time from typing import Union, Dict, Any, Optional from slack_sdk.web import SlackResponse from slack_bolt.request import BoltRequest from slack_bolt.request.payload_utils import ( is_action, is_event, is_options, is_shortcut, is_slash_command, is_view, is_workflow_step_edit, is...
3300008
import unittest import FlowTexTest import WiseTexTest import GridFileTest import TexGenv2Test import AbaqusTest if __name__ == "__main__": alltests = unittest.TestSuite([FlowTexTest.GetTestSuite(), WiseTexTest.GetTestSuite(), GridFileTest.GetTes...
3300021
import mmcv import json import torch import warnings import numpy as np import os.path as osp import BboxToolkit as bt from math import ceil from itertools import product from mmcv.parallel import collate, scatter from mmdet.datasets.pipelines import Compose from mmdet.ops import RoIAlign, RoIPool, nms, nms_rotated ...
3300040
from six.moves.collections_abc import Sequence import wandb def line_series(xs, ys, keys=None, title=None, xname=None): """ Construct a line series plot. Arguments: xs (array of arrays, or array): Array of arrays of x values ys (array of arrays): Array of y values title (string): ...
3300052
from termcolor import colored def build(buckets): for bucket in buckets: print("-"*60, end="\n\n") print("Profile: {}".format(bucket.profile)) print("Bucket: {}".format(colored(bucket.name, "blue", attrs=["bold"]))) safe = True msg = [] for perm in bucket.permission....
3300072
import pytest from plenum.test import waits from plenum.common.constants import LEDGER_STATUS, AUDIT_LEDGER_ID from plenum.common.messages.node_messages import MessageRep, MessageReq, CatchupReq from plenum.server.catchup.node_leecher_service import NodeLeecherService from plenum.test.delayers import DEFAULT_DELAY fro...
3300082
from typing import Any from typing import Dict from typing import Optional from .protocol import MERGED_KEY from .protocol import MixedStackedModel from ..bases import BAKEBase from ..bases import RDropoutBase from ...types import tensor_dict_type from ...protocol import TrainerState from ...constants import INPUT_KEY...
3300091
from entitykb.models import Token from entitykb.pipeline import WhitespaceTokenizer def test_whitespace_tokenizer(): tokenizer = WhitespaceTokenizer() assert list(tokenizer("one")) == ["one"] tokens = list(tokenizer("one two")) assert tokens == ["one", "two"] assert tokens[0].ws_after assert...
3300112
import torch from cuda import USE_CUDA import torch.nn as nn from timeit import default_timer as timer from learner import Learner ####### LSTM 优化器的训练过程 Learning to learn ############### def Learning_to_learn_global_training(f,optimizer, global_taining_steps, optimizer_Train_Steps, UnRoll_STEPS, Evaluate...
3300170
import sys import os import shutil import glob import platform from pathlib import Path current_path = os.getcwd() module_path = Path(__file__).parent / 'face_alignment' sys.path.insert(0,str(module_path.resolve())) sys.path.insert(0,str(Path(__file__).parent.resolve())) #os.chdir(module_path) #from face_alignment.ap...
3300178
from mundiapi.mundiapi_client import MundiapiClient from mundiapi.models import * from mundiapi.controllers import * from mundiapi.exceptions.error_exception import * MundiapiClient.config.basic_auth_user_name = "YOUR_SECRET_KEY:" charges_controller = charges_controller.ChargesController() chargeId = "ch_8YQ1JeTLzF8z...
3300181
import pandas as pd import numpy as np import os input_data_folder = "../experiments/labeled_logs_csv" output_data_folder = "../experiments/logdata" filenames = ["BPIC15_%s.csv"%municipality for municipality in range(1,6)] case_id_col = "Case ID" activity_col = "Activity" timestamp_col = "Complete Timestamp" label_co...
3300224
from django import template register = template.Library() @register.simple_tag def test_nested(): return '<p>hello world</p>'
3300235
import matplotlib.pyplot as plt import sys def readFile(fileName): iters = [] train_vals = [] oneShot_vals = [] fiveShot_vals = [] with open(fileName) as f: iterFound = False trainFound = False oneFound = False iteration = 0 for line in f: arr = line.split() ...
3300256
from fastapi import APIRouter, BackgroundTasks import logging from src.app.api import _predict from src.app.ml.active_predictor import Data from src.helper import get_job_id logger = logging.getLogger(__name__) router = APIRouter() @router.get("") def test(): return _predict._test() @router.post("") async def...
3300263
import os import sys import json import argparse import re from copy import deepcopy from enum import Enum from datetime import datetime, timedelta, time from collections import defaultdict from dateutil import parser import hashlib gDefaultUser = os.environ["USER"] gDefaultTag = "untagged" class TimestampType(Enum)...
3300314
from bitmovin.resources import Resource from bitmovin.errors import InvalidTypeError from bitmovin.utils import Serializable from .muxing_information_audio_track import MuxingInformationAudioTrack from .muxing_information_video_track import MuxingInformationVideoTrack class MP4MuxingInformation(Resource, Serializabl...
3300325
import numpy.random import pandas import numpy import vtreat # https://github.com/WinVector/pyvtreat import vtreat.util def test_nan_inf(): numpy.random.seed(235) d = pandas.DataFrame( {"x": [1.0, numpy.nan, numpy.inf, -numpy.inf, None, 0], "y": [1, 2, 3, 4, 5, 6]} ) transform = vtreat.Numer...
3300338
import sys import argparse import web3 from autobahn import xbr from test_accounts import addr_owner, addr_alice_market, addr_alice_market_maker1, addr_bob_market, addr_bob_market_maker1, \ addr_charlie_provider, addr_charlie_provider_delegate1, addr_donald_provider, addr_donald_provider_delegate1, \ addr_ed...
3300350
import os from .base_video_dataset import BaseVideoDataset from lib.train.data import jpeg4py_loader import torch from collections import OrderedDict from lib.train.admin import env_settings from lib.utils.lmdb_utils import decode_img, decode_json def get_target_to_image_ratio(seq): anno = torch.Tensor(seq['anno'...
3300363
import os, csv #dictionary function designed to read .csv file from a provided address and given an array to store the values def RCSV(address): csv_reader = csv.DictReader(open(address, 'r'), delimiter=',', quotechar='"') headers = csv_reader.fieldnames input=[] for line in csv_reader: for i in range(len(csv...
3300371
import sys import os import json import logging import unidecode import time import csv import glob import zipfile # allow imports from parent directory sys.path.insert(1, os.path.join(sys.path[0], '..')) from db import connection from utils import extract_short_unit from db_utils import DBUtils CURRENT_PATH = os.pat...
3300438
from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path( 'render_icon_list_modal/', TemplateView.as_view( template_name='faicon_modal.html' ), name='faicon-modal' ), ]
3300467
import torch from ..utils import common_functions as c_f class SlicedWasserstein(torch.nn.Module): """ Implementation of the loss used in [Sliced Wasserstein Discrepancy for Unsupervised Domain Adaptation](https://arxiv.org/abs/1903.04064) """ def __init__(self, m: int = 128): """ ...
3300483
from client.rest import ApiException from expects.matchers import Matcher from expects import expect, equal, have_keys, have_key class has_location(Matcher): def __init__(self, expected): self._expected = expected def _match(self, subject): expect(subject).to(have_key('Location')) retu...
3300486
from .utils import ScannerOptions, ElementType from .scan import scan from .attributes import attributes, AttributeToken class MatchedTag: __slots__ = ('name', 'attributes', 'open', 'close') def __init__(self, name: str, attrs: list, open_range: tuple, close_range: tuple=None): self.name = name ...
3300488
import demistomock as demisto from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import from CommonServerUserPython import * # noqa # pylint: disable=unused-wildcard-import import traceback import dateparser from datetime import timedelta from enum import Enum from typing import List, Dict, An...
3300531
from __future__ import print_function # # I should write a decent test of the python binding... # def dumpSummaries(dbname): db = rdbms.getDB(dbName) tags = db.allTags() for tag in tags.split() : try : # log = db.lastLogEntry(tag) # print log.getState() ...
3300541
from django.utils.version import get_version # VERSION = (1, 9, 0, 'alpha', 0) # __version__ = get_version(VERSION) # https://www.python.org/dev/peps/pep-0440/ VERSION = (1, 2, 60) __version__ = '.'.join(map(str, VERSION))
3300568
from .backends import CalculationBackend, ComputeResources, QueueWorkerResources __all__ = [ ComputeResources, CalculationBackend, QueueWorkerResources, ]
3300598
from typing import Dict, List import os import random import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import numpy as np from ..modules import Module def vae_loss_hook(agent, losses_dict, input_strea...
3300614
import logging import uuid from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import permissions from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from agent_webhooks.utils.credential import Credential, Credenti...
3300624
import time import os # Function for returning a first available key value for appending a new element to a dictionary def getFreeKey(itemsDict): try: for x in range(0, len(itemsDict) + 1): if len(itemsDict[x]) > 0: pass except Exception: pass return(x) # Functi...
3300628
import math from typing import Iterator from cryptography.exceptions import InvalidTag from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.primitives.ciphers.algorithms...
3300634
import asyncio import base64 import json from typing import TYPE_CHECKING, Union import urllib.parse from async_dns.core import DNSMessage, REQUEST, Record, types from ..util import ConnectionHandle if TYPE_CHECKING: from async_dns.resolver import BaseResolver class Response: def __init__(self, status, mes...
3300651
import re import json import pandas as pd from tqdm import tqdm as tqdm import urlexpander from config import * ''' After downloading metadata bout state-level media outlets, this script can be run to merge rows and standardize the columns. <NAME> 2018-05-31 ''' def remove_www(site_str): ''' Best attempt t...
3300668
from typing import List, Tuple import strawberry @strawberry.type class Book: title: str author: "Author" @strawberry.type class Author: name: str books: List[Book] TOLKIEN = Author(name="<NAME>", books=[]) JANSSON = Author(name="<NAME>", books=[]) BOOKS = { 1: Book(title="The Fellowship of...
3300673
import os import github import uuid TOKEN = "REMOVED GITHUB TOKEN" g = github.Github(TOKEN) user = g.get_user() default_repo = user.get_repo("base") for i in range(100): a = str(uuid.uuid4()) try: repo_name = "production-" + a repo = user.create_repo( repo_name, all...
3300679
from __future__ import absolute_import, division, print_function import stripe TEST_RESOURCE_ID = "seti_123" class TestSetupIntent(object): def test_is_listable(self, request_mock): resources = stripe.SetupIntent.list() request_mock.assert_requested("get", "/v1/setup_intents") assert is...
3300717
import requests class Pnr(object): def __init__(self): self.ids = {} #json = requests.get("https://api.coinmarketcap.com/v1/ticker/").json() #for cr in json: #self.ids[cr["symbol"]] = cr["id"] def get_pnr(self, pnrno): try: json = requests.get("https://api.railwayapi.com/v2/pnr-status/pnr/"+pnrno+"/ap...
3300718
import pytest import tornado from voila.static_file_handler import TemplateStaticFileHandler async def test_static_file_absolute_path(app, base_url, http_server_client): response_lab = await http_server_client.fetch(f'{base_url}voila/templates/lab/static/voila.js') assert response_lab.code == 200 abspath...
3300726
import sqlalchemy as sa from internal.entity.base import Base from internal.entity.mixin import TimestampMixin class Application(TimestampMixin, Base): __table_args__ = ( sa.UniqueConstraint('phone'), sa.UniqueConstraint('email'), ) phone = sa.Column(sa.String(255), index=True, nullable...
3300749
import threading import objc from Foundation import * from AppKit import * from PyObjCTools import AppHelper import platform import alp.core as core NSUserNotificationActivationTypeNone = 0 NSUserNotificationActivationTypeContentsClicked = 1 NSUserNotificationActivationTypeActionButtonClicked = 2 class Notification...
3300756
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np # 生成整数型的类型 def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) # 生成字符串型的属性 def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value...
3300772
import signal_tl as stl # Signal(sample_values, sample_times) xs = stl.Signal([0, 2, 1, -2, -1], [0, 2.5, 4.5, 6.5, 9]) ys = stl.Signal([0, -2, 2, 1, -1.5], [0, 2, 6, 8.5, 11]) # Synchronizing signals xs_, ys_ = stl.synchronize(xs, ys) print("x: {}".format(list(xs))) print("y: {}".format(list(ys))) print("\nSyncroni...
3300785
from typing import Any, Callable, TypeVar, Union from ..includes import includes from ..map import map from ..reduce import reduce T = TypeVar('T', bound='List') class List(list): def map(self: T, cb) -> T: return List(map(self, cb)) def reduce(self: T, cb, initializer=None) -> Union[str, int, floa...
3300804
from injector import inject from domain.operation.execution.adapters.execution.ExecuteAdapter import ExecuteAdapter from domain.operation.execution.adapters.execution.ExecuteAdapterFactory import ExecuteAdapterFactory from domain.operation.execution.services.IntegrationExecutionService import IntegrationExecutionServi...
3300810
from olo.libs.compiler.prelude_names import PL_TRANS_FUNC from olo.libs.cache import LRUCache from olo.debug import debug code_cache = LRUCache(128) def compile_src(src): code = code_cache.get(src) if not code: code = compile(src, '<?>', 'eval') code_cache.set(src, code) return code de...
3300899
import torch import torchelie.callbacks as tcb from torchelie.recipes import Recipe def TrainAndTest(model, train_fun, test_fun, train_loader, test_loader, *, test_every=100, visdom_env='main', ...
3300906
import os.path from pathlib import Path import pytest from notesdir.api import Notesdir from notesdir.conf import DirectRepoConf, NotesdirConf def config(): return NotesdirConf(repo_conf=DirectRepoConf(root_paths={'/notes'})) def test_for_user_no_file(fs): with pytest.raises(Exception, match=r'You need to c...
3300919
import sys, json _, input_path, output_path = sys.argv header, *lines = open(input_path).readlines() fout = open(output_path, 'w') fout.write(header) min_gap = 0.1 max_gap = 1.0 prev_offset = None prev_text = None running_shortcut = 0. for line in lines: offset, mode, text = json.loads(line) if prev_offse...
3300926
import xlsxwriter #Create a workbook and add a worksheet workbook = xlsxwriter.Workbook('chart_column.xlsx') worksheet = workbook.add_worksheet() #Create a column chart object chart = workbook.add_chart({'type': 'column'}) #YoY data for company financials data = [ ['Year', '2013', '2014', '2015'], ['Revenue'...
3300957
import os import struct import logging from primitives import * from constants import * from astypes import MalformedFLV from astypes import get_script_data_variable, make_script_data_variable log = logging.getLogger('flvlib.tags') STRICT_PARSING = False def strict_parser(): return globals()['STRICT_PARSING'] ...
3300962
from pitop import Camera from pitop.labs import MessagingBlueprint, VideoBlueprint, WebServer from pitop.processing.algorithms import BallDetector, process_frame_for_line camera = Camera() ball_detector = BallDetector(format="PIL") selected_image_processor = "line_detect" def change_processor(new_image_processor): ...
3301005
import struct from typing import Tuple, Optional, Union from bxcommon.utils.blockchain_utils.ont.ont_object_hash import OntObjectHash from bxgateway import ont_constants from bxgateway.messages.ont.ont_message import OntMessage from bxgateway.messages.ont.ont_message_type import OntMessageType class GetDataOntMessag...
3301026
import os import sys cur_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, cur_dir)
3301100
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ expected = (len(nums) + 1) * len(nums) / 2 return expected - sum(nums)
3301146
import os import torch import logging from datetime import datetime import json import csv logger = logging.getLogger('experiment') def save_config(config_dict, fname=None): """ Save configuration dictionary (n json format). :param config_dict: configuration dictionary :param fname: name of the file...
3301175
from ramda.intersection import intersection from ramda.private.asserts import * def intersection_test(): assert_equal(intersection([1, 2, 3, 4, 4], [7, 6, 5, 4, 3, 4]), [3, 4])
3301196
from collections import defaultdict import pickle as pkl import networkx as nx import numpy as np import random import os import random from itertools import repeat from sklearn.model_selection import StratifiedKFold from homlib import Graph as hlGraph ALL_DATA = ["MUTAG", "PTC_MR", "IMDB-BINARY", "IMDB-MULTI", "NCI1...
3301199
import tensorflow as tf def conv2d_cosnorm(x, w, strides, padding, bias=0.0001): """ conv2d_cosnorm Usage : x : An input Tensor with shape [batch, height, width, channel] w : A convolutional kernel Tensor with shape [height, width, in, out]. (channel == in) strides : strides of conv...
3301200
from hsi_toolkit.util import img_det from hsi_toolkit.util import unmix import numpy as np def abd_detector(hsi_img, tgt_sig, ems, mask = None): """ Abundance of Target when unmixed with background endmembers Inputs: hsi_image - n_row x n_col x n_band hyperspectral image tgt_sig - target signature (n_band x 1 ...
3301208
def to_binary(n): return '{:b}'.format(n & 4294967295) # return '{:b}'.format(n & 0xffffffff) # return '{:b}'.format(n & 0b11111111111111111111111111111111)
3301223
import dataclasses import logging from dataclasses import dataclass from typing import Any, Callable, Generic, Iterable, NoReturn, Tuple, TypeVar, cast from expression.collections import FrozenList, Map, frozenlist, map from expression.core import ( MailboxProcessor, Nothing, Option, Some, TailCall...