id
stringlengths
3
8
content
stringlengths
100
981k
11472234
import torch import torch.nn as nn import torchvision.models as models import torch.nn.functional as F import math from .image_proc import * from .geometry import * class L1Loss(nn.Module): def __init__(self): super(L1Loss, self).__init__() def forward(self, output, target, weight=None, mean=False): ...
11472237
import os import uuid import shlex import subprocess import requests props_file_name = f"corenlp_server-{uuid.uuid4().hex[:16]}.props" class ShouldRetryException(Exception): """ Exception raised if the service should retry the request. """ pass def write_corenlp_props(annotators): props_dict = {'annota...
11472254
import numpy as np from heuristics.conditions import ( CompositeCondition, Condition, NearestOpponentDistanceCondition, OccupiedCellsCondition, PlayerInBiggestRegionCondition ) class LategameCondition(Condition): """ Check if we are in the LategameCondition.""" def __init__(self): """Initiali...
11472299
import pytest from badoo.setup import Credentials, Setup, _Browser, _Badoo from badoo.yaml import YamlFromPath _user: str = "user" _pass: str = "<PASSWORD>" @pytest.fixture(scope="module") def credentials() -> Credentials: return Credentials(username=_user, password=_<PASSWORD>) @pytest.fixture(scope="module")...
11472310
import angr import pyvex import archinfo import ailment block_bytes = bytes.fromhex("554889E54883EC40897DCC488975C048C745F89508400048C745F0B6064000488B45C04883C008488B00BEA70840004889C7E883FEFFFF") block_addr = 0x4006c6 def test_convert_from_vex_irsb(): arch = archinfo.arch_from_id('AMD64') manager = ailme...
11472337
from gdsctools.volcano import VolcanoANOVA from gdsctools import ANOVA, ic50_test def test_volcano_plot(): an = ANOVA(ic50_test) an.features.df = an.features.df[an.features.df.columns[0:10]] an = ANOVA(ic50_test, genomic_features=an.features.df) results = an.anova_all() # try the constructors ...
11472348
import logging from bots import config_discordbot as cfg from openbb_terminal.decorators import log_start_end from openbb_terminal.stocks.due_diligence import marketwatch_model logger = logging.getLogger(__name__) @log_start_end(log=logger) def sec_command(ticker=""): """Displays sec filings [Market Watch]""" ...
11472351
from __future__ import print_function import astropy.units as astropy_units import numpy as np import six from scipy.interpolate import RegularGridInterpolator from astromodels.functions.function import Function1D, FunctionMeta from astromodels.utils import _get_data_file_path from astromodels.utils.logging import se...
11472375
import functools def only_if_awake(state): ''' Decorator that ensures a function only runs when the node is awake. If not, the node drops the request. ''' def callable(f): @functools.wraps(f) def wrapped(*args, **kwargs): if state["awake"]: return f(*args, **kwargs) els...
11472377
from .relations import Relations class Point(Relations): def from_json(self, data): super(Point, self).from_json(data) self.coords = data['coords'] self.type = data['type'] def to_json(self): data = super(Point, self).to_json() data['coords'] = self.coords data[...
11472394
import os import tempfile try: from PyQt5.QtGui import QImage from PyQt5.QtCore import Qt except ImportError: from PySide2.QtGui import QImage from PySide2.QtCore import Qt import hou from .db import connect from .image import loadImage from .operation import InterruptableOperation class MaterialPr...
11472404
import cv2 import numpy import pytesseract import xml.etree.ElementTree as ET from datetime import datetime import pandas as pd import random def show_result(image): cv2.imshow("image", image) cv2.waitKey(5000) def show_result_rectangle(image, x1, y1, x2, y2, color, weight): cv2.rectangle(image, (x1, y1),...
11472410
import basevcstest import vcs import os import cdms2 import MV2 class TestVCSAnimateMeshfill(basevcstest.VCSBaseTest): def testVCSAnimateMeshfill(self): f = cdms2.open(os.path.join(vcs.sample_data, "sampleCurveGrid4.nc")) s = f("sample") s2 = MV2.resize(s, (4, 32, 48)) t = cdms2.cr...
11472422
import os import h5py import logging import mxnet as mx import numpy as np import pandas as pd import math from data import utils from config import DATA_PATH, TRAIN_PROP, EVAL_PROP def get_grids(): x0, y0 = 116.25, 39.83 x1, y1 = 116.64, 40.12 rows, cols = 32, 32 size_x, size_y = (x1 - x0) / rows,...
11472438
from .respone_template import ResponseTemplate from .tweet_response_round_robin import TweetResponseRoundRobin from .twitter_bot_response_log import TwitterBotResponseLog from .twitter_bot_visit_log import TwitterBotVisitLog __all__ = ['ResponseTemplate', 'TweetResponseRoundRobin', 'TwitterBotResponseLog', 'TwitterBot...
11472446
cluster = { # node names 'nodes': { # masters 'node_1': {'host': '127.0.0.1', 'port': 63791}, 'node_2': {'host': '127.0.0.1', 'port': 63792}, } }
11472477
import dnacauldron as dc repo = dc.SequenceRepository() repo.import_records(folder="parts_and_oligos") plan = dc.AssemblyPlan.from_spreadsheet( path="basic_assembly.csv", assembly_class="from_spreadsheet" ) simulation = plan.simulate(repo) simulation.write_report("output") print ("Done! see output/ folder for the ...
11472487
from django.contrib import admin from django.contrib.auth.views import LoginView from django.urls import include, path, re_path import debug_toolbar from . import views from .models import NonAsciiRepr urlpatterns = [ re_path( r"^resolving1/(.+)/(.+)/$", views.resolving_view, name="positional-resolving" ...
11472520
from UE4Parse.BinaryReader import BinaryStream from UE4Parse.Assets.Objects.Structs import Vector class FBox: position: int Min: Vector.FVector Max: Vector.FVector bIsValid: bool def __init__(self, reader: BinaryStream): self.position = reader.base_stream.tell() self.Min = Vector....
11472549
from datagen.DataGen import DataGen from datagen.SavingDataGen import SavingDataGen from datagen.PytorchDataset import PytorchDataset
11472560
import os # it raises an error if not found CODE_PATH = os.environ['SURVEY_CODE'] if 'SURVEY_CODE' in os.environ else os.path.join(os.environ['HOME'], 'github', 'jingwei') ROOT_PATH = os.environ['SURVEY_DATA'] if 'SURVEY_DATA' in os.environ else os.path.join(os.environ['HOME'], 'VisualSearch') OUTPUT_PATH = os.environ...
11472581
from anthemtool.toc.layout import Layout class FrostbiteGame: """ Represents a Frostbite game instance. """ def __init__(self, path: str) -> None: """ Load the game data files from /Data and /Patch. """ self.path = path # Initialize layouts self.layout...
11472589
from __future__ import absolute_import, division, print_function from six.moves import range from scitbx.matrix import sqr,col from math import sin,cos,pi from scitbx.array_family import flex import sys class one_sensor(object): def __init__(self,image,sensor,manager): self.image = image self.sensor = sensor ...
11472602
from __future__ import annotations import gc import json import logging import os import collections import copy from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.utils.data from iopath.common.file_io import g_pathmgr from pytorchvideo.data.clip_sampling import ClipSampler,...
11472642
import sys, os sys.path.insert(1, os.path.join("..","..","..")) import h2o from tests import pyunit_utils from h2o.estimators.gbm import H2OGradientBoostingEstimator def checkpoint_new_category_in_predictor(): sv1 = h2o.upload_file(pyunit_utils.locate("smalldata/iris/setosa_versicolor.csv")) sv2 = h2o.upload_file...
11472669
import json from os import environ as os_environ from re import findall as re_findall from socket import AF_INET, AF_INET6, inet_pton from asyncio_socks_server.exceptions import LoadFileError from asyncio_socks_server.values import SocksAtyp def get_socks_atyp_from_host(host: str) -> int: """Get the address type...
11472708
from aequitas.plot.commons.style.classes import Shape, Bubble from aequitas.plot.commons.style.sizes import Disparity_Chart from aequitas.plot.commons.style import color as Colors import altair as alt import math def get_chart_size_range(length, padding): """Calculate the chart size range for a given axis based ...
11472712
import argparse import pathlib import siml def main(): parser = argparse.ArgumentParser() parser.add_argument( 'settings_yaml', type=pathlib.Path, help='YAML file name of settings.') parser.add_argument( '-o', '--out-dir', type=pathlib.Path, default=None, ...
11472741
def default(dummy=0): pass def defaultWithSpaces(dummy = 0): pass def defaultFloat(dummy=0.1): pass
11472760
class IsolatorConstants: WIDTH_HEIGHT_RATIO_MIN = 0.31 WIDTH_HEIGHT_RATIO_MAX = 0.75 PIXEL_RATIO_MIN = 25 PIXEL_RATIO_MAX = 75 ADDITION_MEAN = 45 THRESHOLD_LOWER = 20 THRESHOLD_UPPER = 200
11472767
from datetime import datetime from logging import getLogger import time from google.cloud import logging_v2 from googleapiclient import discovery from googleapiclient import errors from kubeflow.fairing import utils from kubeflow.fairing import http_utils from kubeflow.fairing.deployers.deployer import DeployerInterf...
11472782
from ramp.store import Storable class Result(Storable): def __init__(self, x_train, x_test, y_train, y_test, y_preds, model_def, fitted_model, original_data): """ Class for storing the result of a single model fit. """ self.x_train = x_train self.x_test = x_test sel...
11472783
from ...base import BaseParser class PaymentDetail(BaseParser): @property def credit_card_bin(self): return self._dict.get('credit_card_bin') @property def avs_result_code(self): return self._dict.get('avs_result_code') @property def cvv_result_code(self): return sel...
11472827
from typing import Tuple from ground.base import (Context, Location) from ground.hints import Point from hypothesis import given from orient.planar import point_in_polygon from sect.decomposition import Graph from tests.utils import Polygon from . import strategies @given(strategies.context...
11472847
import ast def get_pypackage_dependencies(pycode:str, package_name:str, is_init:bool): tree = ast.parse(pycode) deps = set() for node in tree.body: if isinstance(node, ast.Import): for name in node.names: dep = name.name if package_name is None or not dep....
11472941
import demistomock as demisto from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import from CommonServerUserPython import * # noqa from typing import Dict, Any, List, Optional import traceback ''' COMMAND FUNCTION ''' def enrich(current_list: List[Dict[str, Any]], enrich_list: List[Dict[s...
11472971
from ncbi_genome_download import jobs def test_job_eq(): args = ['foo', 'bar', 'baz', 'blub'] job_a = jobs.DownloadJob(*args) job_b = jobs.DownloadJob(*args) job_c = jobs.DownloadJob('this', 'one', 'is', 'different') assert job_a == job_b assert job_a != job_c assert job_b != args
11472974
from test_plus.test import TestCase from digestiflow.test_utils import SetupUserMixin, SetupProjectMixin from ..forms import BarcodeSetForm from ..tests import SetupBarcodeSetMixin class BarcodeSetFormTest(SetupBarcodeSetMixin, SetupProjectMixin, SetupUserMixin, TestCase): """Test ``BarcodeSetForm``""" def ...
11473005
import subprocess import threading import os from .linux_system_backend import LinuxBackend from opsbro.log import LoggerFactory # Global logger for this part logger = LoggerFactory.create_logger('system-packages') class DnfBackend(LinuxBackend): RPM_PACKAGE_FILE_PATH = '/var/lib/rpm/Packages' # seems to be li...
11473022
from mpython import * from yeelight import * my_wifi = wifi() # 连接到与YeeLight相同的局域网内 my_wifi.connectWiFi("","") discover_bulbs() # 发现局域网内YeeLight的设备信息 bulb=Bulb("192.168.0.7") # 构建Bulb类用于控制,传入IP参数 bulb.turn_on() # 开灯 sleep(2) bulb.turn_off() # 关灯 sleep...
11473038
from spacy.lang.fr import French from spacy.tokens import Doc nlp = French() # Définis la fonction getter def get_has_number(doc): # Retourne si un token quelconque du doc renvoie True pour token.like_num return any(token.like_num for token in doc) # Déclare l'extension de propriété de Doc "has_number" # av...
11473121
from django.utils.text import slugify from unidecode import unidecode def clean_form_field_name(label): # unidecode will return an ascii string while slugify wants a # unicode string on the other hand, slugify returns a safe-string # which will be converted to a normal str return str(slugify(str(unide...
11473139
ROWS = 30 COLUMNS = 100 import time import os from ctypes import * STD_OUTPUT_HANDLE = -11 class COORD(Structure): pass COORD._fields_ = [("X", c_short), ("Y", c_short)] class Stack: pass def loadFile(fileName): # load grid from file and return as pointer to return 'TO-DO' # pointer to grid as p...
11473144
from seamless.core import context, cell ctx = context(toplevel=True) ctx.bytes1 = cell("bytes") ctx.bytes1.set(b'this is a bytes value') ctx.bin = cell("binary") ctx.bytes1.connect(ctx.bin) ctx.bytes2 = cell("bytes") ctx.bin.connect(ctx.bytes2) ctx.mix = cell("mixed") ctx.bytes1.connect(ctx.mix) ctx.bytes3 = cell("...
11473152
from django.apps import AppConfig class CarsConfig(AppConfig): name = 'src.cars' verbose_name = "Modulo de Carros"
11473189
import io import json import os import urllib.request as url_lib import zipfile from packaging.version import parse as version_parser EXTENSION_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUGGER_DEST = os.path.join(EXTENSION_ROOT, "pythonFiles", "lib", "python") DEBUGGER_PACKAGE = "debugpy" D...
11473207
import io from ...migration import MigrationContext from ...testing import assert_raises from ...testing import config from ...testing import eq_ from ...testing import is_false from ...testing import is_true from ...testing.fixtures import TestBase class MigrationTransactionTest(TestBase): __backend__ = True ...
11473229
import pytest from plenum.test.delayers import cDelay from plenum.test.helper import sdk_send_random_and_check, checkViewNoForNodes, assertExp, get_pp_seq_no from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data from plenum.test.node_request.helper import sdk_ensure_pool_functional from plenum.te...
11473231
from mprl.rl.common.util import set_policies_to_train_in_trainer # def get_ed_fixed_scheduler(best_response_iterations, equilibrium_policy_iterations, # trainable_tmp_policy_key, static_tmp_policy_key): # # def ed_fixed_scheduler(trainer, eval_data): # if 'is_training_best_respo...
11473238
def get_latest_packages(): return [ {'name': 'flask', 'version': '1.2.3'}, {'name': 'sqlalchemy', 'version': '2.2.0'}, {'name': 'passlib', 'version': '3.0.0'}, ]
11473243
from copy import deepcopy import pytest from mock import mock @pytest.fixture def cmd_node(): return { "name": "new_cmd", "cmd": "cmd_obj", "children": {} } @pytest.fixture def cmd_node2(): return { "name": "child_cmd", "cmd": "cmd_obj", "children": {} ...
11473286
import torch import torch.nn as nn import torch.nn.functional as F from .segbase import SegBaseModel from .model_zoo import MODEL_REGISTRY __all__ = ["ContextNet"] @MODEL_REGISTRY.register() class ContextNet(SegBaseModel): def __init__(self): super(ContextNet, self).__init__(need_backbone=False) ...
11473323
from fetcher.utils import map_attributes def collect_attributes(attributes, mapping, field, value, debug_state=None): collected = {x['attributes'][field]: x['attributes'][value] for x in attributes} return map_attributes(collected, mapping, debug_state) def handle_ak(res, mapping): # collect values ...
11473345
import tre fz = tre.Fuzzyness(maxerr = 3) print fz pt = tre.compile("<NAME>", tre.EXTENDED) data = """ In addition to fundamental contributions in several branches of theoretical computer science, <NAME> is the creator of the TeX computer typesetting system, the related METAFONT font definition language and rendering...
11473387
from __future__ import print_function import sys import os import unittest import logging os.environ['ENABLE_CNNL_TRYCATCH'] = 'OFF' # pylint: disable=C0413 import torch cur_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(cur_dir + "/../../") from common_utils import testinfo, TestCase # pylint: di...
11473407
from enum import Enum from typing import Optional from dataclasses import dataclass from thirdweb.constants.chains import ChainId class GasSpeed(Enum): STANDARD = "standard" FAST = "fast" FASTEST = "fastest" @dataclass class GasSettings(object): """ The gas settings for the SDK. :param max...
11473409
import tensorflow as tf import numpy as np class TextCNN(object): """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. "https://github.com/dennybritz/cnn-text-classification-tf" """ def __init__( self, sequence_length, nu...
11473416
import sys import getopt from utils import fast_imgs2video imgdir = '' fps = 24 music_name = None output_video = '' thread = 1 qscale = 0.01 if sys.argv[1] in ['-h', '--help']: print("""pytoflow version 1.1 usage: python3 imgs2video.py [[option] [value]]... options: --fdir the directory of the frames. --...
11473425
class TestImport: def test_import(self): from jupyterlab_nbconvert_nocode.nbconvert_functions import ( export_html, export_pdf, )
11473434
import fnmatch class OrderedAttributes(object): __visit_name__ = 'ordered_attributes' def __init__(self, data=None, defaults=None): self._dict = {} self._keys = [] self._defaults = defaults or {} if data: for k, v in data: self[k] = v def _get...
11473443
import copy import logging import os import numpy as np import torch.utils.data import torchvision from PIL import Image from .heatmap import putGaussianMaps from .paf import putVecMaps from . import transforms, utils def kp_connections(keypoints): kp_lines = [ [keypoints.index('neck'), keypoints.index('r...
11473483
from bluedot.btcomm import BluetoothClient from datetime import datetime from time import sleep from signal import pause def data_received(data): print("recv - {}".format(data)) print("Connecting") c = BluetoothClient("devpi", data_received) print("Sending") try: while True: c.send("hi {} \n".format(...
11473486
import argparse import json import logging import os import random from builtins import ValueError from collections import defaultdict from io import open import numpy as np import torch import yaml from easydict import EasyDict as edict from tqdm import tqdm from evaluator import final_evaluate from mmt.metrics impo...
11473487
def coin_change_problem(coins, amount): """ Find out maximum number of ways in which a amount can be obtained using fixed value coins. Time Complexity : O((type of coins)*amount) :param coins: Iterable of elements containing value of coins. :param amount: It is value which is to be obtained wit...
11473489
def create_model(switch_prob=0.1, noise_level=1e-8, startprob=[1.0, 0.0]): """Create an HMM with binary state variable and 1D Gaussian observations The probability to switch to the other state is `switch_prob`. Two observation models have mean 1.0 and -1.0 respectively. `noise_level` specifies the stand...
11473506
import pandas as pd import numpy as np from rex import MultiYearWaveX, WaveX import sys def region_selection(lat_lon): ''' Returns the name of the predefined region in which the given coordinates reside. Can be used to check if the passed lat/lon pair is within the WPTO hindcast dataset. Parameters ...
11473523
import torch import paddle from pd.resnet import resnet50 def torch2paddle(): model = resnet50() model_state_dict = model.state_dict() torch_path = "./tch/resnet50.pth" paddle_path = "./pd/resnet50.pdparams" torch_state_dict = torch.load(torch_path) fc_names = ["fc"] paddle_state_dict = ...
11473524
from extractors.appearance_feature_extractor import * from extractors.motion_feature_extractor import * from extractors.init_feature_extractor import * from extractors.classification_feature_extractor import *
11473549
from __future__ import annotations import math import os import random from typing import TYPE_CHECKING, List if TYPE_CHECKING: from src.genotype.neat.species import Species os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/' from graphviz import Digraph def get_graph_from_species(sp...
11473565
import os import codecs # https://github.com/janpipek/iso639-python # Python 3.4+ compatibility if 'unicode' not in dir(): unicode = str __version__ = '0.1.4' class NonExistentLanguageError(RuntimeError): pass def find(whatever=None, language=None, iso639_1=None, iso639_2=None, native=None): ...
11473596
from glue.viewers.common.viewer import Viewer from glue.viewers.common.utils import get_viewer_tools class ViewerWithTools(Viewer): inherit_tools = True tools = ['save'] subtools = {'save': []} def test_get_viewer_tools(): class CustomViewer1(ViewerWithTools): pass tools, subtools = ge...
11473600
import logging import os from pathlib import Path from typing import Any, Dict import tabula from django.conf import settings from django.core.management import BaseCommand from django.db import transaction from associations.models import Association from base import logic, parsing from base.middleware import env fro...
11473621
from unittest.mock import MagicMock, call import pytest from afancontrol import trigger from afancontrol.config import Actions, AlertCommands, TempName, TriggerConfig from afancontrol.report import Report from afancontrol.temp import TempCelsius, TempStatus from afancontrol.trigger import PanicTrigger, ThresholdTrigg...
11473628
from conans import ConanFile, AutoToolsBuildEnvironment, tools from conans.errors import ConanInvalidConfiguration import os required_conan_version = ">=1.33.0" class PixmanConan(ConanFile): name = "pixman" description = "Pixman is a low-level software library for pixel manipulation" topics = ("pixman", ...
11473639
import zmq import zmq.decorators as zmqd @zmqd.context() @zmqd.socket(zmq.PULL) def fn(ctx, skt): print(type(ctx)) print(type(skt)) pass fn()
11473645
import threading from Queue import Queue class TaskQueue(Queue): def __init__(self): Queue.__init__(self) self.all_tasks_done = threading.Condition(self.mutex) self.unfinished_tasks = 0 def _put(self, item): Queue._put(self, item) self.unfinished_tasks += 1 ...
11473648
from __future__ import annotations from common_utils.check_utils import check_required_keys from common_utils.base.basic import BasicLoadableObject from .handlers import NDDS_Annotation_Object_Handler from .objects import CameraData class NDDS_Annotation(BasicLoadableObject['NDDS_Annotation']): def __init__( ...
11473665
def test_import_star(): """ Test that `from svg.charts import *` imports all the modules """ mod_src = 'from svg.charts import *\n' code = compile(mod_src, 'test_import_star_module.py', 'exec') ns = {} exec(code, ns) assert 'graph' in ns assert 'plot' in ns
11473743
from fusion.criterion.loss import ABaseLoss, AE from fusion.criterion.misc import CanonicalCorrelation from fusion.criterion.misc.utils import total_loss_summation from fusion.model.misc import ModelOutput from torch import Tensor from typing import Optional, Tuple, Any, Dict class DCCAE(ABaseLoss): def __init__...
11473751
import asyncio from typing import Any, Dict, List, Callable from pytest import mark, raises from graphql.language import parse from graphql.pyutils import SimplePubSub from graphql.type import ( GraphQLArgument, GraphQLBoolean, GraphQLField, GraphQLInt, GraphQLList, GraphQLObjectType, Gra...
11473756
import time from consoleme.handlers.base import BaseHandler class AuthHandler(BaseHandler): async def prepare(self): try: if self.request.method.lower() in ["options", "post"]: return await super(AuthHandler, self).prepare() except: # noqa # No...
11473767
from django.db import models # Create your models here. class Privileges(models.Model): auth_obj = models.CharField(max_length=50) select_host = models.SmallIntegerField() update_host = models.SmallIntegerField() insert_host = models.SmallIntegerField() delete_host = models.SmallIntegerField() ...
11473787
from .data_wrapper import try_import_data_wrapper, register_data_wrapper, fetch_data_wrapper from .model_wrapper import ( try_import_model_wrapper, register_model_wrapper, fetch_model_wrapper, ModelWrapper, EmbeddingModelWrapper, )
11473828
import open3d as o3d import time import numpy as np import os import json import pdb LABEL_COLORS = np.array([ (0, 0, 0), # None (70, 70, 70), # Building (100, 40, 40), # Fences (55, 90, 80), # Other (255, 255, 0), # Pedestrian (153, 153, 153), # Pole (157, 234, 50), # RoadLines ...
11473852
from optimus.server.functions import run, code, engine, session, create_session, delete_session, features class Engine: def __init__(self, config=None, session=None, **kwargs): if session is not None: self.id = session.id else: self.id = "default" if i...
11473891
from __future__ import division from chainer.dataset import dataset_mixin from abc import ABCMeta, abstractmethod import os from PIL import Image from PIL import ImageOps import numpy import six import skimage.filters from skimage.color import rgb2lab from skimage import exposure import cv2 import time import typing f...
11473906
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(2, 2), index=['1', '3'], columns=['key_1', 'val_1'] ) df = df.reindex(['1', '2', '3']) print(df['val_1'].isnull())
11473907
import unittest from earth_distances import distance class Tests(unittest.TestCase): TESTS = { "Basics": [ { "input": ['51°28′48″N 0°0′0″E', '46°12′0″N, 6°9′0″E'], "answer": 739.227_134_742_523_7, }, { "input": ['33°51′31...
11473912
def load_input(): data = list() with open('input') as fd: for line in fd: value = line.strip() data.append(int(value)) return data def main(): data = load_input() # First task count = 0 for i in range(len(data)-1): if data[i+1] - data[i] > 0: ...
11473942
import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms, datasets from PIL import Image from skimage import io, transform import os import numpy as np import random class NH_HazeDataset(Dataset): def __init__(self, hazed_image_files, dehazed_image_files, root_dir, crop=Fals...
11473993
import requests from boucanpy.cli.base import BaseCommand from boucanpy.db.models.zone import Zone class ApiZonesList(BaseCommand): name = "api-zone-list" aliases = ["api-zones"] description = "list zones via API" path = "/api/v1/zone" @classmethod def parser(cls, parser): parser.add_...
11474011
import tensorflow as tf from xcenternet.tensorboard.visualization import draw_bounding_boxes, visualize_heatmap class ResultImageLogCallback(tf.keras.callbacks.Callback): def __init__(self, data, config, pred_model, freq=1, log_dir=None): super().__init__() self.data = data self.config = ...
11474033
import numpy as np import pytest from garage.envs import PointEnv from garage.experiment.task_sampler import SetTaskSampler from garage.np.policies import FixedPolicy from garage.sampler import LocalSampler, WorkerFactory def test_update_envs_env_update(): max_episode_length = 16 env = PointEnv() policy ...
11474106
from keras.models import Sequential from keras.layers.convolutional import Conv3D from keras.layers.convolutional_recurrent import ConvLSTM2D from keras.callbacks import EarlyStopping import h5py def read_dataset(path=None, split=0.8, print_shape=False): hdf5_file = h5py.File(path, "r") x = hdf5_file["sim_dat...
11474135
from boto3_type_annotations.cloudwatch.client import Client from boto3_type_annotations.cloudwatch.service_resource import ServiceResource from boto3_type_annotations.cloudwatch.service_resource import Alarm from boto3_type_annotations.cloudwatch.service_resource import Metric from boto3_type_annotations.cloudwatch.ser...
11474151
import pymysql import approzium from .._misc import patch from .._mysql import MYSQLNativePassword, get_auth_resp def _scramble_native_password(context, salt): # use normal method if not Approzium connection if not isinstance(context, dict): return pymysql._auth.scramble_native_password(context, sal...
11474167
import uuid from django.conf import settings from django.core.files.storage import default_storage from django.db import models from django.urls import reverse from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from easy_thumbnails.fields import ThumbnailerImageField from mode...
11474264
from __future__ import absolute_import, division, print_function, unicode_literals from echomesh.base import Settings from echomesh.element import Element from echomesh.sound.CPlayer import CPlayer from echomesh.util import Log LOGGER = Log.logger(__name__) class Audio(Element.Element): def __init__(self, parent...
11474273
import numpy as np from numpy import ones import keras from keras.models import Model from keras import backend from matplotlib import pyplot import argparse import tensorflow as tf import matplotlib.pyplot as plt from model import * from utils import * ############################################################ p...
11474284
from django.contrib.auth.signals import user_logged_in from rest_framework import permissions, generics, response, status from . import serializers, utils class ObtainTokenView(generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ permission_classes = ( permi...