id
stringlengths
3
8
content
stringlengths
100
981k
9927924
import sys import pytest @pytest.mark.spark_test def test_import_spark_session(spark_session): """ Test if its possible to import spark """ try: import pyspark from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession except ImportError: pyte...
9927925
from __future__ import absolute_import # import auth modules into client package from .oauth import Account from .oauth import Organization from .oauth import Link from .oauth import OAuth from .oauth import OAuthToken
9927987
class Solution: # @param A : tuple of integers # @param B : tuple of integers # @return a list of integers def intersect(self, A, B): s1 = 0 s2 = 0 e1 = len(A) e2 = len(B) intersection = [] while s2 < e2 and s1 < e1: if A[s1] == B[s2]: ...
9927989
from typing import List import torch from catalyst.dl import RunnerState, CriterionCallback, Callback, CallbackOrder import numpy as np class MixupInputCallback(Callback): """ Callback to do mixup augmentation. Paper: https://arxiv.org/abs/1710.09412 Note: MixupCallback is inherited from Cr...
9928039
input = """ a. b. c. q :- p. p :- q. sth :- a,p,q,b. sth :- undefined. sth :- not defined. sth :- not q, not b, not a, not p. sth :- not defined1, not defined2, not defined3. sth :- a, not defined1. sth :- not defined1, b, not defined2. """ output = """ {a, b, c, sth} """
9928099
import os, shutil import pytest import numpy as np from numpy.testing import assert_array_equal from spikeinterface.extractors import NumpySorting from spikeinterface.comparison import compare_multiple_sorters, MultiSortingComparison def setup_module(): if os.path.exists('saved_multisorting_comparison'): ...
9928111
from pycsp3.problems.data.parsing import * data["distances"] = [numbers_in(line) for line in remaining_lines()]
9928136
class Agencia: def __init__(self, nombre, direccion): self.nombre = nombre self.direccion = direccion def getNombre(self): return self.nombre def getDireccion(self): return self.direccion
9928167
from .PBXResolver import * from .PBX_Base_Target import * from .PBX_Constants import * class PBXFrameworkTarget(PBX_Base_Target): def __init__(self, lookup_func, dictionary, project, identifier): super(PBXFrameworkTarget, self).__init__(lookup_func, dictionary, project, identifier); if kPBX_TA...
9928181
import tensorflow as tf def _activation_summary(x): """Helper to create summaries for activations. Creates a summary that provides a histogram of activations. Creates a summary that measures the sparsity of activations. Args: x: Tensor """ tf.summary.histogram(x.op.name + '/activati...
9928182
import argparse import pprint import statistics from os import listdir import os from os.path import isfile, join from shutil import copyfile from collections import defaultdict import sys sys.path.append('../') from lama.lama_utils import load_file from lama.model import Roberta from lama.batch_eval_KB_completion impo...
9928263
description = r''' This is just an example. It doesn't even try to do anything useful. You can run it to see that your installation works. ''' def analysis(sliceno): return sliceno def synthesis(analysis_res): print("Sum of all sliceno:", sum(analysis_res))
9928278
import cartolafc api = cartolafc.Api(email='<EMAIL>', password='<PASSWORD>', attempts=5, redis_url='redis://localhost:6379/0') print(api.amigos()) print(api.clubes()) print(api.liga(nome='Virtus Premier League')) print(api.liga(nome='Nacional', page=2)) print(api.liga(nome='Nacional', page=3, order_by=cartolafc.RODAD...
9928280
from distutils.core import setup, Extension from Cython.Build import cythonize extension = Extension( "py_ssock_wrap", ["py_ssock_wrap.pyx"], libraries=["ssock_wrap"] , extra_link_args=["-L./ "], ) setup( ext_modules=cythonize([extension]) )
9928307
from kivy.uix.widget import Widget from kivy.lang import Builder Builder.load_file('backgrounds/background1.kv') class BackGround1(Widget): pass
9928329
from typing import List class Solution: def minMoves(self, nums: List[int]) -> int: minValue = min(nums) return sum(nums) - minValue * len(nums)
9928381
from sqlalchemy.orm import relationship from DB.BaseModel import BaseModel from Config.Run.config import Config class SkillTemplate(BaseModel): __tablename__ = 'skill_template' id = BaseModel.column(type='integer', primary_key=True) entry = BaseModel.column(type=...
9928387
import os import io import json import time import logging import hashlib from datetime import datetime import requests from instascrape.constants import USER_ID_URL from instascrape.exceptions import NotFoundError logger = logging.getLogger("instascrape") def data_dumper(dest: str, filename: str, data: dict, *, w...
9928476
import numpy as np import pandas as pd __all__ = ['kl_divergence', 'js_divergence', 'mutual_information_rate', 'pointwise_mutual_information_rate'] def kl_divergence(x, y, continuous=False, bucket_num=1000): """kl divergence. Args: x: pd.Series, sample feature value. y: pd.Series, sample ...
9928480
import logging import peewee from typing import List, Tuple, Iterable, Union from playhouse.postgres_ext import ArrayField, SQL from slim.support.peewee.data_record import PeeweeDataRecord from slim.utils import sentinel from ...base.sqlquery import SQL_OP, SQLQueryOrder, SQLQueryInfo, DataRecord, SQLValuesToWrite fr...
9928494
from typing import Optional from pydantic import BaseModel class Pagination(BaseModel): limit: int offset: int order_by: Optional[str]
9928501
import logging from human_services.addresses.models import Address, AddressType from human_services.locations.models import LocationAddress from bc211.import_icarol_xml.parser import compute_address_id LOGGER = logging.getLogger(__name__) def create_address_for_location(location, address_dto, counters): address ...
9928504
import os import sys import tensorflow as tf import numpy as np import imageio import json import random # Misc utils def img2mse(x, y): return tf.reduce_mean(tf.square(x - y)) def mse2psnr(x): return -10.*tf.log(x)/tf.log(10.) def to8b(x): return (255*np.clip(x, 0, 1)).astype(np.uint8) # Positional encoding ...
9928509
from tests.modules.FlaskModule.API.BaseAPITest import BaseAPITest import random from opentera.db.models.TeraDeviceType import TeraDeviceType class UserQueryDeviceSubTypesTest(BaseAPITest): login_endpoint = '/api/user/login' test_endpoint = '/api/user/devicesubtypes' def setUp(self): pass def...
9928512
import os import unittest from fastNLP.io import ModelSaver, ModelLoader from fastNLP.models import CNNText class TestModelIO(unittest.TestCase): def test_save_and_load(self): model = CNNText((10, 10), 2) saver = ModelSaver('tmp') loader = ModelLoader() saver.save_pytorch(model) ...
9928520
from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import text import os import subprocess import logging class ZTECM(object): """Process ZTE configuration management data""" def __init__(self): #@TODO: Refactor sqlalchemy_db_uri ...
9928521
from datetime import datetime def error(message): now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") with open("data/error.log", "a", encoding="utf-8") as errorFile: text = ("[" + dt_string + "] ") + message + '\n' errorFile.write(text) errorFile.close() def msg(messag...
9928577
from datetime import date, datetime from django.test import TestCase from pytz import timezone from v1.util.datetimes import convert_date, end_of_time_period class TestDateTime(TestCase): def test_convert_string(self): test_date_string = "2019-10-31" converted = convert_date(test_date_string, "...
9928581
import os, fileinput, shutil bundleDirPath = os.path.abspath("bundle") os.makedirs(bundleDirPath, exist_ok=True) for dllInfo in fileinput.input(): dllInfo = dllInfo.strip() dllInfoParts = dllInfo.split(sep=" ") dllName = dllInfoParts[0] dllPath = dllInfoParts[2] dllBundlePath = os.path.join(bundle...
9928626
from fabric import operations from fabric.api import local def build(): local("docker-compose build") local("docker build -t eahub:latest .") local("y | docker system prune") def run(): local("docker-compose run --service-ports web") # with ipdb support # local('docker-compose up') # without i...
9928633
import socket IP = "127.0.0.1" PORT = 1234 # Create a TCP connection sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((IP, PORT)) # Send message to server sock.sendall("8bit-Unity is easy!") # Wait for reply data = sock.recv(256) sock.close() print 'Echoed from TCP server: "%s"...
9928684
import hmac import hashlib import json import base64 import time import sys HEADER_MODEL = { 'alg': 'HMAC-SHA256', 'typ': 'JWT' } PAYLOAD_MODEL = { 'sub': 'User_XXX', 'exp': '1234567890' } # from smalltrain.utils.gg_setting import GGSetting from smalltrain.utils.gg_setting import GGSetting def get_...
9928711
import json from random import randint from django.db import transaction from django.db.models import Q from django.shortcuts import HttpResponse, redirect from django.urls import reverse from django.views.generic import FormView from django.views.generic import UpdateView from django.views.generic import View from dj...
9928725
import torch import torch.nn as nn from torch.nn import functional as F from torch.autograd import Variable from torch import optim import numpy as np import math, random # Generating a noisy multi-sin wave def sine_2(X, signal_freq=60.): return (np.sin(2 * np.pi * (X) / signal_freq) + np.sin(4 * np.pi * (X) / s...
9928747
from typing import List from typing import Dict from botocore.paginate import Paginator class DescribeEcsClusters(Paginator): def paginate(self, EcsClusterArns: List = None, StackId: str = None, PaginationConfig: Dict = None) -> Dict: """ Creates an iterator that will paginate through responses fr...
9928779
import argparse from lib.functions import * class LedStrip: def __init__(self, usersettings, ledsettings): self.usersettings = usersettings self.ledsettings = ledsettings self.brightness_percent = int(self.usersettings.get_setting_value("brightness_percent")) self.led_number = int...
9928812
from flask_restful import Resource import pgn # Import games list from app import db # Eco # Shows a single eco code class EcoCode(Resource): def get(self): # TODO: implement this if we have more detailed info on # the individual chess openings return {'eco': 'B22'} # EcoCodeList # ...
9928873
from datetime import datetime import re from regparser.tree.xml_parser.tree_utils import get_node_text def parse_date_sentence(sentence): """Return the date type + date in this sentence (if one exists).""" # Search for month date, year at the end of the sentence sentence = sentence.lower().strip() ...
9928881
import torch @torch.no_grad() def generate(): """ 随机生成动漫头像,并根据netd的分数选择较好的 """ # for k_, v_ in kwargs.items(): # setattr(opt, k_, v_) device = t.device('cuda') if opt.gpu else t.device('cpu') netg, netd = NetG(opt).eval(), NetD(opt).eval() noises = t.randn(opt.gen_search_num, op...
9928882
from pyspark.sql import SparkSession from pyspark.ml.linalg import SparseVector, VectorUDT, Vectors from pyspark.sql.types import * from pyspark.rdd import RDD, PipelinedRDD import numpy as np import re import subprocess import os import time #preprocessor for asm files class preprocessor_asm(object): ''' prep...
9928930
a = '¢пр' print(a[0], a[0:1]) print(a[1], a[1:2]) print(a[2], a[2:3]) try: print(a[3]) except IndexError: print("IndexError") print(a[3:4]) print(a[-1]) print(a[-2], a[-2:-1]) print(a[-3], a[-3:-2]) try: print(a[-4]) except IndexError: print("IndexError") print(a[-4:-3]) print(a[0:2]) print(a[1:3]) p...
9928938
import sys import os import openmdao.main import webbrowser def view_docs(browser=None): """A script (``openmdao docs``) points to this. It just pops up a browser to view the openmdao Sphinx docs. If the docs are not already built, it builds them before viewing; but if the docs already exist, ...
9928946
from chainerkfac import communicators # NOQA from chainerkfac import optimizers # NOQA from chainerkfac.communicators import create_communicator # NOQA
9928953
import torch.nn as nn import torch from torch import Tensor from typing import Callable __all__ = ['SignificanceLoss'] class SignificanceLoss(nn.Module): r''' General class for implementing significance-based loss functions, e.g. Asimov Loss (https://arxiv.org/abs/1806.00322). For compatability with usin...
9928977
import re from inspect import getsourcelines from textwrap import dedent from typing import Optional import discord from aiohttp import ClientSession from bot import constants from discord.ext.commands import Command doc_reg_class = r'("""|\'\'\')([\s\S]*?)(\1\s*)' class Source: """Displays information about th...
9928997
import cPickle as pickle import cudamat as cm import ctc_fast as ctc import numpy as np import numpy.linalg as nl import pdb class NNet: def __init__(self,inputDim,outputDim,layerSize,numLayers,maxBatch, train=True, temporalLayer=-1, reg=0.0): # Initialize cublas cm.cublas_init() ...
9929000
import pytest @pytest.fixture def proxy_return(): return { 'token': 'https://some-url/token', 'login': 'https://some-url/login', 'lift': 'https://some-url/api/proxy/B', 'gen_certificate': 'https://some-url/gen_cert' }
9929033
import numpy as np import paddle import paddle.fluid as fluid from paddle.fluid.dygraph.nn import Conv2D, Pool2D, BatchNorm, Linear class Template(fluid.dygraph.Layer): def __init__(self, args): super(Template, self).__init__() self.args = args if args.backbone == 'Conv4': fro...
9929035
from datetime import datetime from django.db import models from django.utils.html import format_html from mdeditor.fields import MDTextField class Tag(models.Model): """ 文章标签 """ class Meta: # **表名 db_table = "blog_tag" # **菜单名 verbose_name = "文章标签" verbose_nam...
9929084
import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from pytorch2keras.converter import pytorch_to_keras class LayerTest(nn.Module): def __init__(self, kernel_size=3, padding=1, stride=1): super(LayerTest, self).__init__() self.pool = nn.AvgPool2d(kernel_size...
9929132
import py import os from subprocess import Popen, PIPE import rpython rpythondir = os.path.dirname(os.path.realpath(rpython.__file__)) rpythonroot = os.path.dirname(rpythondir) default_retval = '?', '?' def maywarn(err, repo_type='Mercurial'): if not err: return from rpython.tool.ansi_print import Ans...
9929139
import json from sqlalchemy.sql import text from rdr_service.dao.bigquery_sync_dao import BigQuerySyncDao, BigQueryGenerator from rdr_service.model.bq_base import BQRecord from rdr_service.model.bq_workbench_researcher import BQRWBResearcherSchema, BQRWBInstitutionalAffiliationsSchema, \ BQRWBResearcher, BQRWBIns...
9929159
import random from support.ticket import SupportTicket class CustomerSupport: def __init__(self): self.tickets: list[SupportTicket] = [] def add_ticket(self, ticket: SupportTicket): self.tickets.append(ticket) def process_tickets(self, processing_strategy: str = "fifo"): # if it...
9929165
class BinaryNotFoundError(Exception): """If a necessary executable is not found in the PATH on the system""" pass
9929185
import base64 import json from django.test import Client, TestCase from django_prbac.models import Role from mock import Mock, patch from corehq.apps.accounting.models import ( BillingAccount, DefaultProductPlan, SoftwarePlanEdition, Subscription, SubscriptionAdjustment, ) from corehq.apps.domain...
9929191
from .base import Optimizer class UsagePage(Optimizer): precedence = 10 def __init__(self, stream): self.stream = stream self.page = None def append(self, item): from ..item import Item, GlobalItem, LocalItem, UsagePage, Usage from ...util import NamedConstant from...
9929208
import inspect import time from concurrent.futures import Future from satella.coding import wraps from satella.coding.typing import NoArgCallable from .base import MetricLevel class MeasurableMixin: """ Add a .measure() method, useful for HistogramMetric and SummaryMetric """ __slots__ = () def ...
9929236
import requests import re import time from lxml import etree import random class DaZhongDianPing: def __init__(self, shop_review_url, user_cookie): # 商家评论详情页 url self.url = shop_review_url # 商家评论详情页源码 self.html = str() # 页面字体大小 self.font_size = 14 # 页面引用的 cs...
9929250
from django.shortcuts import render from .forms import ContactForm def index(request): form = ContactForm() context = {'form' : form} return render(request, 'index.html', context)
9929296
from functools import partial import jax import jax.numpy as jnp import numpy as np from jax import random import cr.sparse as crs from cr.sparse import pursuit import cr.sparse.data as crdata import cr.sparse.dict as crdict from cr.sparse.ef import RecoveryPerformance from cr.sparse.pursuit import omp from cr.spars...
9929305
from __future__ import absolute_import, division, print_function import cctbx.array_family.flex # import dependency import boost_adaptbx.boost.python as bp ext = bp.import_ext("mmtbx_bulk_solvent_ext") from mmtbx_bulk_solvent_ext import * from mmtbx.bulk_solvent.multi_mask_bulk_solvent import multi_mask_bulk_solvent #...
9929363
from lamb import utils try: # for now, fail silently if this doesn't work. import svgling import svgling.html except: pass import copy, enum from xml.etree import ElementTree Element = ElementTree.Element SubElement = ElementTree.SubElement def log_warning(m): from lamb import meta meta.logger...
9929376
from __future__ import unicode_literals SECRET_KEY = 'not-secret-anymore' TIME_ZONE = 'UTC' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'rest_framework', ...
9929397
from enum import IntEnum import re class SymbolKind(IntEnum): Unknown = 0 File = 1 Module = 2 Namespace = 3 Package = 4 Class = 5 Method = 6 Property = 7 Field = 8 Constructor = 9 Enum = 10 Interface = 11 Function = 12 Variable = 13 Constant = 14 String ...
9929441
from django import forms from complaints.models import Complaint class ComplaintForm(forms.ModelForm): def save(self, request=None, *args, **kwargs): kwargs['commit'] = False obj = super(ComplaintForm, self).save(*args, **kwargs) obj.save(request) return obj class Meta: ...
9929453
import os import sys class Data: def __init__(self, baseline_quality, envelope_quality,no_cgs, total_points): self.baseline_quality = baseline_quality self.envelope_quality = envelope_quality self.no_cgs = no_cgs self.total_points = total_points def display_record(self): print("\t\t\t\t Bas...
9929464
import os from natsort import natsorted from glob import glob def mkdirs(paths): if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths) def mkdir(path): if not os.path.exists(path): os.makedirs(path) def get_last_pa...
9929474
import requests def run_query(query, variables): request = requests.post('https://graphql.anilist.co', json={'query': query, 'variables': variables}) if request.status_code == 200: return request.json() elif request.status_code == 404: print ("Invalid search.") return e...
9929478
import uuid from decimal import Decimal from django.core.urlresolvers import reverse_lazy as reverse from rest_framework import status from wallet.tests.factories import WalletFactory, WalletTrxFactory from wallet import enums from foobar.wallet import Money from foobar.rest.fields import MoneyField from .base import A...
9929566
from __future__ import annotations import abc import json from typing import TYPE_CHECKING from litebot.errors import ArgumentError from litebot.core.minecraft import Player if TYPE_CHECKING: from litebot.core.minecraft.commands import ServerCommandContext class ArgumentType(abc.ABC): """Different argument ...
9929596
from enum import Enum, unique BASE_URL = 'https://api.weixin.qq.com/cgi-bin/express/business' URL_SET = { # 账号管理接口 'bind_account': 'account/bind', 'get_all_account': 'account/getall', # 下单接口 'get_all_delivery': 'delivery/getall', 'add_order': 'order/add', 'cancel_order': 'order/cancel', ...
9929602
from .compose import Compose from .formating import ImageToTensor, Collect from .loading import LoadImageFromFile from .crop import PairedRandomCrop from .normalization import RescaleToZeroOne, Normalize from .augmentation import Flip from .resize import RandomResizedCrop, Resize from .colorjitter import Bgr2Gray, Colo...
9929632
import FWCore.ParameterSet.Config as cms process = cms.Process("LA") process.load("Configuration.StandardSequences.Services_cff") process.load("Configuration.StandardSequences.Geometry_cff") process.load("Configuration.StandardSequences.MagneticField_38T_cff") process.load("Configuration.StandardSequences....
9929710
class Solution: def findDuplicate(self, paths: List[str]) -> List[List[str]]: dic = {} for path in paths: dire = path.split(' ')[0] files = path.split(' ')[1:] for file in files: content = file[file.find('(') + 1:file.find(')',file.find('(') + 1)]...
9929720
import datetime from dataclasses import dataclass from typing import Any @dataclass class Instrument: id: int code: str description: str active_status: str @dataclass class ShareGroup: id: int name: str description: str capital_range_min: int modified_by: str modified_date: d...
9929725
import pytest import demistomock as demisto from CommonServerPython import entryTypes NORMAL = [ { "Type": entryTypes["note"], "HumanReadable": "tha output!", } ] ERROR = [ { "Type": entryTypes["error"], "Contents": "", } ] def executeCommand(result=NORMAL, error=Fal...
9929731
import sublime, sublime_plugin import threading import subprocess import os import sys class GitCommitMsgThread(threading.Thread): def __init__(self, view): threading.Thread.__init__(self) self.view = view selected = view.sel()[0] self.file_name = view.file_name() self.start_line = view.rowcol(se...
9929734
set_name(0x800A4C50, "VID_OpenModule__Fv", SN_NOWARN) set_name(0x800A4D10, "InitScreens__Fv", SN_NOWARN) set_name(0x800A4E00, "MEM_SetupMem__Fv", SN_NOWARN) set_name(0x800A4E2C, "SetupWorkRam__Fv", SN_NOWARN) set_name(0x800A4EBC, "SYSI_Init__Fv", SN_NOWARN) set_name(0x800A4FE0, "GM_Open__Fv", SN_NOWARN) set_name(0x800A...
9929742
import os from unittest.mock import patch import pytest import subprocess from flow.cloud.gcappengine.gcappengine import GCAppEngine from unittest.mock import MagicMock from flow.buildconfig import BuildConfig mock_build_config_dict = { "projectInfo": { "name": "MyProjectName", "language": "java", ...
9929747
import pprint print([100] > [-100]) # True print([1, 2, 100] > [1, 2, -100]) # True print([1, 2, 100] > [1, 100]) # False l_2d = [[20, 3, 100], [1, 200, 30], [300, 10, 2]] pprint.pprint(l_2d, width=20) # [[20, 3, 100], # [1, 200, 30], # [300, 10, 2]] pprint.pprint(sorted(l_2d), width=20) # [[1, 200, 30], # [20,...
9929748
from io import BytesIO from random import randint from PIL import Image, ImageDraw from flask import send_file from utils import http from utils.endpoint import Endpoint, setup from utils.textutils import wrap, render_text_with_emoji @setup class Youtube(Endpoint): params = ['avatar0', 'username0', 'text'] ...
9929835
from django.db import models # Create your models here. class DocumentImage(models.Model): image_id = models.AutoField(primary_key=True) image_url = models.ImageField(upload_to='documents/') pub_date = models.DateTimeField(auto_now=True)
9929892
import os import sys from docutils import nodes from docutils.parsers.rst import Directive def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def macro_role(name, rawtext, text, lineno, inliner, options={}, content=[]): app = inliner.document.settings.env.app d...
9929896
from jai import Jai import numpy as np import pandas as pd import pytest INVALID_URL = 'http://google.com' VALID_URL = 'http://localhost:8001' AUTH_KEY = "sdk_test" def test_names_exception(): with pytest.raises(ValueError): j = Jai(url=INVALID_URL, auth_key=AUTH_KEY) j.names def test_info_exce...
9929949
import os import torch import torch.nn as nn import shutil import torch.nn.functional as F from sklearn.cluster import KMeans # from spherecluster import SphericalKMeans import numpy as np import random import ipdb def get_random_recover_index(num): list_rand = list(range(num)) random.shuffle(list_rand) l...
9929969
from stratx.partdep import * from articles.pd.support import * from timeit import default_timer as timer import numpy as np from test_catmerge import stratify_cats def speed_ModelID(): "I believe none of this is in the JIT path; repeated runs are same speed" np.random.seed(1) n = 20_000 min_samples_...
9929991
import pytest from util.assemble import SPYMHeader, SPYM_HDR_LEN ideal_from_sections = SPYMHeader() ideal_from_sections.text_size = 4 ideal_from_sections.data_off = ideal_from_sections.text_off + 4 ideal_from_sections.data_size = 4 def headers_are_same(one, two): return all([one.interp_off == two.interp_off, ...
9930002
from typing import Tuple, Optional, Union, Callable, List import random import os import math import torch import torch.nn.functional as F import nibabel from torch.utils.data import Dataset import numpy as np import misc from data import augmentation class LITSSegmentationTraining(Dataset): """ This class ...
9930049
import numpy as np import os,sys,time import torch import random import string import yaml from easydict import EasyDict as edict import util from util import log # torch.backends.cudnn.enabled = False # torch.backends.cudnn.benchmark = False # torch.backends.cudnn.deterministic = True def parse_arguments(args): ...
9930075
from addons.base.serializer import StorageAddonSerializer from addons.gitlab.api import GitLabClient from addons.gitlab.exceptions import GitLabError from website.util import api_url_for class GitLabSerializer(StorageAddonSerializer): addon_short_name = 'gitlab' # Include host information with more informati...
9930091
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa: F401 from .. import style def make_axes(fig_width, wpad_edge=0, wpad_mid=0.05, hpad_top=0.05, hpad_bottom=0.05, small_sq_width=0.07): sq_width = (1. - 2 * wpad_edge - small_sq_width - 4 * wpad_mid) /...
9930101
import json from . import globals from . import ts4 from .util import * class Address: """The :class:`Address <Address>` object, which contains an Address entity. """ def __init__(self, addr): """Constructs :class:`Address <Address>` object. :param str addr: A string representing the ...
9930140
import numpy as np from scipy.stats import unitary_group from qlazy import QState def generate_qstate(qid_0, qid_1, entangle=True): # random pure state (entangle or not) if entangle == True: dim = 2**len(qid_0+qid_1) vec = np.array([0.0]*dim) vec[0] = 1.0 mat = unitary_group.rvs(di...
9930144
import pglet from pglet import LineChart from pglet.linechart import Point, Data def test_verticalbarchart_add(): lc = LineChart(legend=True, tooltips=True, stroke_width=4, y_min=0, y_max=100, y_ticks=2, y_format='{y}%', x_type='number', lines=[ Data(color='yellow', legend='ye...
9930168
import re import numpy as np nstats = 5 def readstats(fname): ''' locals,totals,itrs = readstats(fname) Read a diagstats text file into record arrays (or dictionaries). Parameters ---------- fname : string name of diagstats file to read Returns ------- locals : record ar...
9930172
import pytest import socket import os import tarfile import configparser import pandas as pd from pandas.util.testing import assert_frame_equal from oasislmf.api.client import APIClient # ------------ load command line optios -------------------- # cli_test_conf = os.environ.get('PY_CONFIG', '/var/oasis/test/conf....
9930188
import shutil import click import mock import os import pytest from click.testing import CliRunner from sigopt.cli import cli from sigopt.run_context import RunContext class TestRunCli(object): @pytest.fixture def run_context(self): run = RunContext(mock.Mock(), mock.Mock(assignments={"fixed1": 0, "fixed2": ...
9930190
import pyautogui import time import os import sys import serial from citrus import citrus_packet from citrus import citrus_file from loading import loading_simple from loading import loading_bar # Used for loading a custom application to the CitrusOS and execute it #while True: # var = pyautogui.position() # p...
9930216
import abc import string import six from pyffx.ffx import FFX @six.add_metaclass(abc.ABCMeta) class Codec(object): def __init__(self, ffx, radix): self.ffx = ffx if hasattr(ffx, 'encrypt') else FFX(ffx) self.radix = radix def encrypt(self, v): return self.unpack(self.ffx.encrypt(self...
9930231
import os import tensorflow as tf from config import config, MEAN_COLOR from paths import INIT_WEIGHTS_DIR slim = tf.contrib.slim ATROUS_CKPT = os.path.join(INIT_WEIGHTS_DIR, 'atrous.ckpt') DEFAULT_SCOPE = 'vgg_16' DEFAULT_SSD_SCOPE = 'ssd' class VGG(object): def __init__(self, config, training=True, weight_dec...