id
stringlengths
3
8
content
stringlengths
100
981k
9932776
import json from flask import Flask, request, abort from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import ( MessageEvent, FollowEvent, JoinEvent, TextSendMessage, TemplateSendMessage, TextMessage, ButtonsTemplate, ...
9932821
import json import jsonpickle from powernad.Connector.restapi import RestApi from powernad.Object.AdKeyword.AdKeywordObject import AdKeywordObject from powernad.Object.AdKeyword.ManagedKeywordObject import ManagedKeywordObject from powernad.Common.CommonFunctions import CommonFunctions from typing import List AdKeywor...
9932848
from unittest import mock from unittest.mock import MagicMock import pendulum import pytest from airflow.exceptions import TaskDeferred from airflow.models import DAG, DagRun, TaskInstance from airflow.providers.cncf.kubernetes.utils.pod_manager import PodLoggingStatus from airflow.utils import timezone from astronom...
9932852
import io as sysio import time import numba import numpy as np from scipy.interpolate import interp1d from det3d.ops.nms.nms_gpu import rotate_iou_gpu_eval from det3d.core.bbox import box_np_ops from det3d.datasets.utils.eval import box3d_overlap_kernel from det3d.datasets.utils.eval import box3d_overlap from det3d.d...
9932875
import sys from pavilion import commands class Poof(commands.Command): def __init__(self): super().__init__('poof', 'Goes POOF!') def run(self, pav_cfg, args): pass
9932879
from __future__ import print_function, unicode_literals import datetime from flask import render_template, request, flash, redirect, url_for, jsonify, session from weblab.core.wl import weblab_api from weblab.core.i18n import gettext from weblab.core.exc import SessionNotFoundError # ../../client/index.html%(localiz...
9932882
from threading import Event from typing import Optional, Type, Iterator, AnyStr, Iterable, List, \ BinaryIO, Union from fpipe.utils.const import PIPE_BUFFER_SIZE class BytesLoop(BinaryIO): def __init__(self, buf_size: int = PIPE_BUFFER_SIZE): self.__buffer = bytearray() self....
9932888
import pytest from ..covariance import covariance, covariance_matrix def test_covariance(): X = [69, 74, 68, 70, 72, 67, 66, 70, 76, 68, 72, 79, 74, 67, 66, 71, 74, 75, 75, 76] Y = [ 153, 175, 155, 135, 172, 150, 115, 137, 200, 1...
9932895
from .unet_model import UNet from .Backward_warp_layer import Backward_warp from .FlowNet_model import FlowNet from .net_utils import * from .MultiscaleWarpingNet import * from .MWNet_2Stage import * from .SupervisedCrossNet import SupervisedCrossNet from .SupervisedFlowNet import SupervisedFlowNet
9932912
import os import socket def get_world_size() -> int: """ Get the number of processes in the default process group. Returns: The world size of the default process group. """ return int(os.environ.get("WORLD_SIZE", 1)) def get_rank() -> int: """ Get the rank of the default process...
9932944
import FWCore.ParameterSet.Config as cms lightpftrackprod = cms.EDProducer("LightPFTrackProducer", TrackQuality = cms.string('highPurity'), UseQuality = cms.bool(True), TkColList = cms.VInputTag(cms.InputTag("generalTracks"), cms.InputTag("secStep"), cms.InputTag("thStep")) )
9932967
import _cffi_backend from .ESAPI import ESAPI try: from .FAPI import * except NotImplementedError: pass from .TCTILdr import * from .TCTI import TCTI from .types import * from .TSS2_Exception import TSS2_Exception
9933008
import unittest import requests from requests_file import FileAdapter import os, stat import tempfile import shutil import platform class FileRequestTestCase(unittest.TestCase): def setUp(self): self._session = requests.Session() self._session.mount("file://", FileAdapter()) def _pathToURL(s...
9933030
from random import randint from retrying import retry import apysc as ap from apysc._animation.animation_width_for_ellipse_interface import \ AnimationWidthForEllipseInterface from tests.testing_helper import assert_attrs class TestAnimationWidthForEllipseInterface: @retry(stop_max_attempt_numb...
9933035
from rdr_service.model.code import CodeType from tests.helpers.unittest_base import BaseTestCase class CheckPpiDataApiTest(BaseTestCase): def setUp(self): super(CheckPpiDataApiTest, self).setUp(with_consent_codes=True) self.participant_summary = self.data_generator.create_database_participant_sum...
9933052
import logging import torch.nn as nn from models.utils import get_concat, get_mlp __all__ = [ 'ExperimentModel', ] logger = logging.getLogger(__name__) class ExperimentModel(nn.Module): labels_count = 1 def forward(self, *input): raise NotImplementedError() def get_single_device(self): ...
9933069
from plugins import plugin_base import re from bs4 import BeautifulSoup class HitomiScraper(plugin_base.PluginBase): ''' Class for hitomi.la Scraper. Inherits from PluginBase. ''' # Note, this scraper works a bit different from the other 3. Most notably in the scrap methods def gen_gal_name(s...
9933095
import numpy as np import tensorflow as tf from tensorflow.keras.applications.vgg16 import preprocess_input # Download this file using keras first. _default_vgg_weights = f'{os.environ["HOME"]}/.keras/models/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5' def get_vgg_model(input_shape=(384,384,3), layer_names=['b...
9933110
import os.path from bottle import Bottle, static_file, HTTPError from ..plugin.session import SessionPlugin from ..session import SessionManager class FontAwesome(Bottle): def __init__(self, session_factory: SessionManager, lib_path: str, valid_status=None): super(FontAwesome, self).__init__() ...
9933131
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factoriza...
9933155
import pytest from amitools.vamos.atypes import BitFieldType def atypes_bitfield_test(): @BitFieldType class MyBF: a = 1 b = 2 c = 4 # to_strs assert MyBF.to_strs(1) == ["a"] assert MyBF.to_str(1) == "a" assert MyBF.to_strs(5) == ["a", "c"] assert MyBF.to_str(5) ==...
9933160
import cv2 from kamane.all import * pictures_directory = "pic_carver/pictures" faces_directory = "pic_carver/faces" pcap_file= "bhp.pcap" def face_detect(path, file_name): img = cv2.imread(path) cascade = cv2.CascadeClassifier("haarcascade_frontalface.alt.xml") rects = cascade.detectMultiScale(img, 1.3, 4...
9933195
import pathlib import pytest from zntrack.core.functions.decorator import NodeConfig def test_not_supported_outs(): with pytest.raises(ValueError): NodeConfig(outs=25) with pytest.raises(ValueError): NodeConfig(outs=[25]) with pytest.raises(ValueError): NodeConfig(outs={"path": 2...
9933201
import pyOcean_cpu as ocean device = ocean.cpu dtypes = [ocean.bool, ocean.int8, ocean.uint8] for dtype in dtypes : print("\n========= Tensor %s (%s) =========" % (dtype.name, device.name)) a = ocean.asTensor([0,1,-1],dtype,device) print(a) print(ocean.bitwiseNot(a)) print(~a) print(ocean.logicalNot...
9933209
import mesh_tensorflow as mtf import tensorflow.compat.v1 as tf from tensorflow.python.tpu import tpu_estimator import mesh_tensorflow.transformer as mtf_transformer from .optimizers import get_optimizer from .utils import mode_to_str, get_graph_info, create_host_call, simd_mesh_setup, scalar_summary from .dalle_mtf im...
9933239
import pytest from .context import tweet_sentiment, SENTIMENT_VALUES def test_model_load(): model = tweet_sentiment.load() pred = model.predict(['<NAME> haber bu']) assert SENTIMENT_VALUES[pred[0]] == 'POSITIVE' probability = model.predict_proba(['harika bir haber bu']) assert probability.shape...
9933283
from PIL import Image from PIL import ImageFilter from PIL.ImageFilter import ( BLUR, CONTOUR, DETAIL, EDGE_ENHANCE, EDGE_ENHANCE_MORE, EMBOSS, FIND_EDGES, SMOOTH, SMOOTH_MORE, SHARPEN ) img = Image.open('Images/plane.jpg') for f in ( BLUR, CONTOUR, DETAIL, EDGE_ENHANCE, EDGE_ENHANCE_MORE, ...
9933296
import unicodedata def remove_diacritic( s ): ''' Accept a unicode string, and return a normal string without any diacritical marks. ''' try: return unicodedata.normalize('NFKD', '{}'.format(s)).encode('ASCII', 'ignore').decode() except: return s def normalize( s ): return remove_diacritic( s.replace('.','...
9933316
from unittest import mock from rest_framework import status from lego.apps.users.models import AbakusGroup, User from lego.utils.test_utils import BaseAPITestCase class ContactViewSetTestCase(BaseAPITestCase): fixtures = [ "initial_files.yaml", "initial_abakus_groups.yaml", "development...
9933317
def parse_list(x): return [int(i.strip()) for i in x.split(',')] class MainConfig: def __init__(self, main_config): self.num_epochs = int(main_config['TRAINING']['num_epochs']) self.batch_size = int(main_config['TRAINING']['batch_size']) self.eval_every = int(main_config['TRAINING...
9933327
from .common import NetCDF4, expects_file_info __all__ = [ 'OceanRAIN', ] class OceanRAIN(NetCDF4): """File handler that can read data from OceanRAIN NetCDF4 files. This object handles OceanRAIN V1.0 NetCDF4 files such as they are compatible with :mod:`typhon.collocations`, i.e.: * rename *lati...
9933333
from moha.io.log import log,timer import numpy as np __all__ = ['PopulationAnalysisMulliken','PopulationAnalysisLowdin'] class PopulationAnalysis(object): """Population Analysis solver. Attributes ---------- mol Chemical molecule. basis_set Basis set of the molecule ...
9933336
if __name__ == "__main__": data_list = ['a', 'e', 'i', 'o', 'i', 'u'] # element 'i' is searched index = data_list.index('i') # index is printed print('The index of e: {}'.format(index)) # list remove del data_list[0] print('data_list:', data_list) data_list.remove('e') print('...
9933354
from machine import I2C import nes, lcd, sys, time from sound import CubeAudio from fpioa_manager import fm from Maix import FPIOA, GPIO i2c = I2C(I2C.I2C3, freq=500*1000, sda=27, scl=24) CubeAudio.init(i2c) tmp = CubeAudio.check() print(tmp) CubeAudio.ready(volume=100) fm.register(13,fm.fpioa.I2S0_MCLK, force=True)...
9933367
import base64 import json import platform import sys import requests from ..exceptions import Auth0Error, RateLimitError from time import sleep from random import randint UNKNOWN_ERROR = 'a0.sdk.internal.unknown' class RestClientOptions(object): """Configuration object for RestClient. Used for configuring ...
9933391
from argparse import ArgumentParser import os parser = ArgumentParser(description='Airflow Fargate Example') parser.add_argument('number', help='number', type=int) def delete_file(file_path): try: os.remove(file_path) print("Successfully deleted file: " + file_path) except OSError: pri...
9933437
from django import forms from taggit.tests.models import Food, DirectFood, CustomPKFood, OfficialFood class FoodForm(forms.ModelForm): class Meta: model = Food class DirectFoodForm(forms.ModelForm): class Meta: model = DirectFood class CustomPKFoodForm(forms.ModelForm): class Meta: ...
9933457
import math import random # Implements https://arxiv.org/pdf/1603.05346v2.pdf class KLLSketch: __slots__ = [ '_k', '_c', '_compactors', '_H', '_size', '_max_size' ] def __init__(self, k=128): if k <= 0: raise ValueError("invalid k") ...
9933483
from abc import ABCMeta from pathlib import Path import unittest import subprocess import json import uuid from typing import List from dataclasses import dataclass from tests.mpv_ipc import MpvIPC @dataclass class MpvEvent: event_name: str args: list class BaseTestCase(unittest.TestCase, metaclass=ABCMeta): ...
9933521
class StringIterator: def findCount(self): j = self.ind + 1 while j < self.n and self.s[j].isnumeric(): j += 1 self.count = int(self.s[self.ind + 1:j]) self.new = j def __init__(self, compressedString): self.s, self.n = compressedString, len(compressedString) ...
9933561
from __future__ import print_function, unicode_literals import io import re from struct import pack, unpack from sys import version_info __all__ = ["Image", "ImageError", "VERSION"] VERSION = "1.1.0" def dec_byte(data, size=1, littleEndian=True): """Decode some data from bytes. Args: data (bytes)...
9933621
import webapp2 import json from google.appengine.api import urlfetch class ShortenHandler(webapp2.RequestHandler): def post(self): url = "https://www.googleapis.com/urlshortener/v1/url" headers = { "Content-Type": "application/json" } payload = { "key": "AIzaSyAl280d28vAJd_6431Uc0N5AwHMowThy8c", "longUr...
9933668
from qgl2.qgl2 import qbit, concur, qgl2decl from qgl2.qgl1 import MEAS, X90, Y90 @qgl2decl def test_loops(a:qbit, b:qbit): with concur: while True: v1 = MEAS(a) if v1: break X90(a, 1.0, 2.0) X90(a, 1.0, 2.0) while True: ...
9933720
from expects import * import time from common.helper.traffic import (make_traffic_definition, make_traffic_duration, make_traffic_load, make_traffic_template) import client.api import client.models SEQ_MODIFIER_P...
9933728
from sys import platform from setuptools import setup __version__ = '1.3.2' with open('README.rst') as f: long_description = f.read() setup( name='pyarmor-webui', version=__version__, description='A webui tool used to obfuscate and pack python scripts based on pyarmor', long_description=long_desc...
9933771
from collections import defaultdict class Twitter(object): def __init__(self): self.tweets = defaultdict(list) self.followers = defaultdict(set) self.t = 0 def postTweet(self, userId, tweetId): self.tweets[userId].append((self.t, tweetId)) self.t += 1 def getNewsF...
9933870
import os.path as osp from ogb.nodeproppred import PygNodePropPredDataset, Evaluator import torch_geometric.transforms as T from torch_geometric.nn import LabelPropagation root = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'OGB') dataset = PygNodePropPredDataset( 'ogbn-arxiv', root, transform=T.Co...
9933873
input = """ c Programma riscritto in nogood 0 p cnf 6 3 -1 -4 0 1 -5 0 3 2 -6 0 """ output = """ sat """
9933883
def sformat(data, string, add_field): """Function to format string with group match results. **Arguments** * data - match results data * string - string to format * add_field - name of the key to assign formatting results to """ try: data[add_field] = string.format(**data) exce...
9933907
from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Any import re # ===================================== # Schema for 'show bfd sessions' # ===================================== class ShowBfdSessionsSchema(MetaParser): """ Schema for "show bfd sessions" command """ schem...
9933912
from rest_framework.fields import Field from openbook_common.utils.model_loaders import get_post_model from openbook_communities.models import CommunityMembership from openbook_posts.models import PostReaction, PostCommentReaction class ReactionField(Field): def __init__(self, reaction_serializer=None, **kwargs)...
9933940
from kivy.lang import Builder from kivy.uix.floatlayout import FloatLayout from kivy.properties import ObjectProperty from kivy.uix.popup import Popup from kivy.uix.button import Button from kivy.utils import platform from nsz.gui.GuiPath import * Builder.load_file(getGuiPath('layout/OpenFileDialog.kv')) class OpenF...
9933988
import os import discord from discord.ext import commands from discord_slash import SlashCommand from dotenv import load_dotenv import lib.check import lib.database import lib.embed load_dotenv() if os.name == 'nt': data_directory = 'json\\' else: data_directory = 'json/' class Mybot(co...
9933999
from datetime import datetime, timedelta import os from requests import get from nba_py.constants import League HAS_PANDAS = True try: from pandas import DataFrame except ImportError: HAS_PANDAS = False HAS_REQUESTS_CACHE = True CACHE_EXPIRE_MINUTES = int(os.getenv('NBA_PY_CACHE_EXPIRE_MINUTES', 10)) try: ...
9934090
from fypy.model.levy.LevyModel import LevyModel from fypy.model.FourierModel import Cumulants from fypy.termstructures.ForwardCurve import ForwardCurve from fypy.termstructures.DiscountCurve import DiscountCurve import numpy as np from typing import List, Tuple, Optional, Union class VarianceGamma(LevyModel): def...
9934119
from socket import * import struct import sys import time TIME1970 = 2208988800L # Thanks to F.Lundh client = socket( AF_INET, SOCK_DGRAM ) data = '\x1b' + 47 * '\0' client.sendto( data, ( sys.argv[1], 123 )) data, address = client.recvfrom( 1024 ) if data: print 'Response received from:', address t = st...
9934135
def get_models(class_name): if class_name == 'DeterministicInverseModel': from .deterministic_inverse_model import DeterministicInverseModel return DeterministicInverseModel if class_name == 'DiscretizedInverseModel': from .discretized_inverse_model import DiscretizedInverseModel ...
9934143
import onnx from onnx import TensorProto, helper if_body = helper.make_graph( [ # need to use main_graph_initializer in a way that can't be constant folded helper.make_node("Add", ["state_var_in", "main_graph_initializer"], ["add_out"], "If_add"), helper.make_node("Cast", ["add_out"], ["out...
9934182
from .base import * # noqa # Override static and media URL for prefix in WSGI server. # https://code.djangoproject.com/ticket/25598 STATIC_URL = '/staging/static/' MEDIA_URL = '/staging/media/'
9934183
import os import sys import zipimport sys.frozen = True FILE_NAME = sys.executable DIR_NAME = os.path.dirname(sys.executable) TF_CPU_LIB = "%s/lib/python3.5-cpu" % os.path.dirname(DIR_NAME) TF_GPU_LIB = "%s/lib/python3.5-gpu" % os.path.dirname(DIR_NAME) if os.path.exists("/usr/local/cuda"): tf_lib = TF_GPU_LIB e...
9934238
from beastling.util import xml from beastling.util.misc import FromOptions class BaseClock(FromOptions): __type__ = None __distribution__ = None def __init__(self, clock_config, global_config): FromOptions.__init__(self, clock_config, global_config) # By default, whether or not to estimat...
9934241
from unittest import TestCase import pytest from paypal.express.models import ExpressTransaction as Transaction @pytest.mark.django_db class TransactionTests(TestCase): def test_password_is_not_saved(self): payload = 'PAYMENTACTION=Sale&PAYERID=7ZTRBDFYYA47W&CURRENCYCODE=GBP&TOKEN=<KEY>&AMT=6.99&PWD=<P...
9934265
from pandas_genomics.scalars import Variant from pandas_genomics import sim def test(): var = Variant(chromosome="1", position=123456, ref="T", alt=["A"]) gta = sim.generate_random_gt(var, alt_allele_freq=0.3) var2 = Variant(chromosome="1", position=223456, ref="T", alt=["A", "C"]) gta_2 = sim.generat...
9934292
def valid_card(card_number): total = 0 for i, a in enumerate(reversed(card_number.replace(' ', ''))): if i % 2: current = int(a) * 2 total += current - 9 if current > 8 else current else: total += int(a) return total % 10 == 0
9934311
import click from .apply import apply @click.command(short_help="Create API definition.") @click.option( '--values', '-vf', 'values_file', type=click.Path(exists=True), required=False, help="Path of values file. By default `Graviteeio` is loaded in the current directory either with the extension `.json`o...
9934324
import qctests.CSIRO_long_gradient import util.testingProfile import numpy ##### CSIRO_long_gradient --------------------------------------------------- def test_CSIRO_long_gradient(): ''' Spot-check the nominal behavior of the CSIRO long gradient test. ''' # nominal p = util.testingProfile.fakeP...
9934331
import json import jieba import matplotlib.pyplot as plt from collections import Counter from wordcloud import WordCloud jieba.set_dictionary('dict.txt.big') # 對繁體中文斷詞較準確的字典檔 def jieba_test(): s = 'Python是非常強的的程式語言, 簡潔友好的語法特別容易上手, 又有許多第三方函式庫的支援。 ' \ 'Python是完全物件導向的語言, 有益於減少程式碼的重複性。' \ 'Python的設...
9934366
import torch import torch.nn as nn import torch.nn.functional as F from deepxml.attentionxml import Embedding, LSTMEncoder from deepxml.meshprobenet import MeSHProbes from deepxml.cornet import CorNet from deepxml.bertxml import BaseBertModel class PlainC(nn.Module): def __init__(self, labels_num, context_size):...
9934373
import time from datetime import datetime proc_meminfo = None proc_zoneinfo = None mem = 0 last_measurement = None proc_stat = None meminfo_required_fields = [ 'MemFree', 'Active(file)', 'Inactive(file)', 'SReclaimable' ] def time_now(): # from https://stackoverflow.com/questions/11743019/conve...
9934384
import xbmcgui class ListItem: id = 0 label = "" label2 = None def __init__(self, id, label): self.id = id self.label = label def to_list_item(self, addon, addon_base): return addon_base, xbmcgui.ListItem(label=self.label), False
9934408
import click from screeps_loan import app from screeps_loan.models import users import screeps_loan.screeps_client as screeps_client from screeps_loan.auth_user import AuthPlayer import screeps_loan.models.alliances as alliances_model @app.cli.command() @click.argument('user') def clear_user_alliance(user): us...
9934431
from django.test.testcases import TestCase from 臺灣言語服務.models import 訓練過渡格式 from django.core.management import call_command class 台華雙語試驗(TestCase): def test句數正確(self): call_command('icorpus臺華平行新聞語料庫') self.assertGreater(訓練過渡格式.資料數量(), 83544 - 10)
9934437
from setuptools import setup snaptools_version = '1.4.8' setup( name='snaptools', version=snaptools_version, author='<NAME>', author_email='<EMAIL>', license='LICENSE', packages=['snaptools'], description='A module for working with snap files in Python', url='https://gi...
9934444
from __future__ import print_function import sys import numpy as np import os if __name__ == '__main__': import matplotlib matplotlib.use('Agg') from astrometry.util.fits import fits_table, merge_tables from astrometry.util.file import trymakedirs from legacypipe.survey import LegacySurveyData ''' This scrip...
9934466
import asyncio import logging import pytest from trinity.protocol.eth.peer import ETHPeer from trinity.protocol.eth.commands import GetBlockHeaders, GetNodeData from trinity.protocol.eth.requests import ( HeaderRequest, NodeDataRequest, ) from tests.trinity.core.peer_helpers import ( get_directly_linked_...
9934479
from typing import Type, Dict from .base import BaseProtocol # To register a custom ALP, make it a subclass of BaseProtocol and import it here from .http import HTTPProtocol from .tls import TLSProtocol ALP_MAP: Dict[int, Type[BaseProtocol]] = {} for proto in BaseProtocol.__subclasses__(): for port in proto.port...
9934533
from urllib.parse import urlparse import click from globus_cli.constants import EXPLICIT_NULL def nullable_multi_callback(null="null"): """ A callback which converts multiple=True options as follows: - empty results, [] => None - [<null>,] => [] - anything else => passthrough This makes the...
9934553
from fastapi import APIRouter from . import custom_pages, site_settings settings_router = APIRouter() settings_router.include_router(custom_pages.public_router) settings_router.include_router(custom_pages.admin_router) settings_router.include_router(site_settings.public_router) settings_router.include_router(site_se...
9934558
import sys char_ = None def readchar_(): global char_ if char_ == None: char_ = sys.stdin.read(1) return char_ def skipchar(): global char_ char_ = None return def stdinsep(): while True: c = readchar_() if c == '\n' or c == '\t' or c == '\r' or c == ' ': ...
9934611
import kivy kivy.require('1.4.0') import os from android.broadcast import BroadcastReceiver from collections import deque from kivy.logger import Logger from kivy.core.text import Label as CoreLabel from kivy.properties import StringProperty, BooleanProperty from kivy.core.window import Window from kivy.uix.button im...
9934614
import math def EliminaGaussiana(A,b): for k in range(0,n-1): pivo = A[k][k] l_pivo = k for i in range(k+1,n-1): if (abs(A[i][k]) > abs(pivo)): pivo = A[i][k] l_pivo = i if pivo == 0: break if l_pivo != k: for j in range(0,n): troca = A[k][j] A[k][j] = A[l_pivo][j] A[l_pivo][j] ...
9934710
import logging import pytest import json import os logger = logging.getLogger(__name__) def test_get(nc): data = next(nc.vendor_bills.get_all_generator()) logger.debug('data = %s', data) assert data, 'get all generator didnt work' internal_id = data['internalId'] data = nc.vendor_bills.get(intern...
9934714
from .instrument import Instrument import numpy as np import math class SNRInstrument(Instrument): """ Simple instrument model that, for a given wavelength-independant, signal-to-noise ratio, compute resulting noise from it. Parameters ---------- SNR: float Signal-to-noise ratio...
9934718
import unittest import numpy as np # import os from statistical_clear_sky.algorithm.initialization.linearization_helper\ import LinearizationHelper class TestLinealizationHelper(unittest.TestCase): ''' Unit test for obtaining initial data of Right Vectors component r0, which is used as a denomoniator of n...
9934719
import pygame from pygame.locals import * from bee import Bee pygame.init() screen = pygame.display.set_mode((600, 600), 0) bgColor = 0, 120, 0 screen.fill(bgColor) pygame.display.flip() pygame.display.set_caption('Sprite Lesson 1') Bee.loadImage() bee = Bee(screen.get_rect()) drawingGroup = pygame.sprite.RenderUpdate...
9934722
import Dataset import time import scipy import scipy.io import scipy.misc import matplotlib.pyplot as plt from ulti import my_imshow, psnr, epe, save_snapshot, load_snapshot, load_params, save_params, yes_no_promt import numpy as np import os import re class Solver(object): def __init__(self, dataset_train, da...
9934740
import glob import os import argparse import csv import cv2 parser = argparse.ArgumentParser(description="Generate a video annotation file.") parser.add_argument("-d", "--data-dir", type=str) parser.add_argument("-o", "--video-annotations", type=str) parser.add_argument("-o", "--output-file", type=str, default="hype...
9934750
import math from unittest import TestCase import simplejson as S class TestFloat(TestCase): def test_floats(self): for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100, 3.1]: self.assertEquals(float(S.dumps(num)), num) self.assertEquals(S.loads(S.dumps(num)), num) ...
9934779
import unittest from should_dsl import should from fluidity import StateMachine, state, transition class Door(StateMachine): state('closed') state('open') initial_state = 'closed' transition(from_='closed', event='open', to='open', action='open_action') transition(from_='open', event='close', to='...
9934803
c.NotebookApp.certfile = "/etc/letsencrypt/cert.pem" c.NotebookApp.keyfile = "/etc/letsencrypt/privkey.pem" c.NotebookApp.ip = "*" c.NotebookApp.open_browser = False c.NotebookApp.port = 8888 c.NotebookApp.notebook_dir = "/home/jovyan/notebooks"
9934811
import json import pytest from lightbus.message import EventMessage from lightbus.serializers.blob import BlobMessageSerializer, BlobMessageDeserializer pytestmark = pytest.mark.unit def test_blob_serializer(): serializer = BlobMessageSerializer() serialized = serializer( EventMessage(api_name="my....
9934813
import itertools import re from tornado.httpclient import (HTTPError as HTTPClientError) import mimetypes import asyncio from tornado.ioloop import IOLoop import time from .constants import (NB_TYPE,UNTITLED_FILE,FOLDER_SEPERATOR,UNTITLED_NB,UNTITLED_FOLDER,CHECKPOINT_NAME) from tornado.web import HTTPError as HTTPSer...
9934825
import matplotlib.pyplot as plt from structure_factor.point_pattern import PointPattern from structure_factor.point_processes import HomogeneousPoissonPointProcess from structure_factor.spatial_windows import BoxWindow point_process = HomogeneousPoissonPointProcess(intensity=1) window = BoxWindow([[-50, 50], [-50, 5...
9934854
import time import zmq import pandas as pd from brightml.timer import ZmqTimer, ZmqTimerManager from brightml.utils import save_sample from brightml.features import p, d from brightml.features import get_features from brightml.brightness import BrightnessManager from brightml.pipeline import get_classifier_pipeline...
9934895
from gazette.spiders.base.doem import DoemGazetteSpider class BaInhambupeSpider(DoemGazetteSpider): TERRITORY_ID = "2913705" name = "ba_inhambupe" state_city_url_part = "ba/inhambupe"
9934902
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class SitetreeConfig(AppConfig): """Sitetree configuration.""" name: str = 'sitetree' verbose_name: str = _('Site Trees')
9934959
import pytest from django.db.utils import IntegrityError from usaspending_api import settings from usaspending_api.references.models import Definition from usaspending_api.references.management.commands.load_glossary import load_glossary def test_glossary_load(db): """ Ensure definition guide data can can b...
9934976
import gym import unittest import numpy as np from ..simulator import ETS2 from .env import SimulatorEnv class ETS2Env(SimulatorEnv): def __init__(self, *args, **kwargs): kwargs['simulator'] = ETS2() super().__init__(*args, **kwargs) # region Unit Tests class TestETS2Env(unittest.TestCase): ...
9935067
import numpy as np import matplotlib.pyplot as plt from keras import backend as K from keras.layers import Input from keras.applications.inception_v3 import InceptionV3 # ランダム画像から始める img_noise = np.random.uniform(size=(1, 299, 299, 3)) + 100.0 # draw_image(img_noise) # input_tensorはバッチを入れない3Dテンソル input_tensor = Inpu...
9935078
from koursaros.repo_creds import get_creds import click from shutil import copytree, rmtree @click.group() def build(): """Build docker images.""" @build.command() @click.argument('flow_path') @click.option('-p', '--push') @click.option('-c', '--creds') @click.option('-n', '--no-caches', multiple=True) @click.p...