id
stringlengths
3
8
content
stringlengths
100
981k
3283341
import sys, os, os.path, glob import tensorflow as tf import numpy keras_backend = 'tensorflow' os.environ['KERAS_BACKEND'] = keras_backend def load_graph(frozen_graph_filename): # We load the protobuf file from the disk and parse it to retrieve the # unserialized graph_def with tf.gfile.GFile(frozen_gra...
3283370
import FWCore.ParameterSet.Config as cms process = cms.Process("READ") process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring("file:overlap.root")) process.tst = cms.EDAnalyzer("RunLumiEventChecker", eventSequence = cms.untracked.VEventID( cms.EventID(1,0,0), ...
3283375
import numpy as np import matplotlib.pyplot as plt plt.axis([0, 10, 0, 1]) for i in range(10): y = np.random.random() plt.scatter(i, y) plt.plot(i,y) plt.pause(0.05) plt.show()
3283379
import unittest from unittest.mock import MagicMock, patch import requests from conjur.errors import OperationNotCompletedException, InvalidPasswordComplexityException from conjur.controller.user_controller import UserController from conjur.logic.user_logic import UserLogic from conjur.data_object.user_input_data impo...
3283409
t = 22#int(input()) # 1st cycle: (1, 3), (2, 2), (3, 1) # 2nd cycle: (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9 , 1) # 3rd cycle: (10, 12), (11, 11), (12, 10), (13, 9), (14, 8)...(21, 1) # 3, 6, 12 => 1st cycle item value = 3 * 2 ** cycle (0-based) # if t is within cycle starting at: 3 * 2 ** cycle
3283492
import FWCore.ParameterSet.Config as cms process = cms.Process("makeSD") process.configurationMetadata = cms.untracked.PSet( version = cms.untracked.string('$Revision: 1.1 $'), annotation = cms.untracked.string('Onia central skim'), name = cms.untracked.string('$Source: /cvs_server/repositories/CMSSW/CMS...
3283524
from ..broker import Broker class DevicePolicyBroker(Broker): controller = "device_policies" def show(self, **kwargs): """Shows the details for the specified device policy. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``requ...
3283576
import re, os import codecs import logging from polyglot_tokenizer import Tokenizer logger = logging.getLogger(__name__) def load_data(text_type, filename, lang, tokenize_text=False, split_sent=True): data_tuple = [] with codecs.open(filename, 'r', encoding='utf-8') as fp: logger.info('Loading text_ty...
3283591
import numpy as np import numba as nb from neutralocean.traj import _ntp_bottle_to_cast @nb.njit def bfs_conncomp1(G, A, r): """ Find the Connected Component containing 1 reference location using Breadth-first Search Parameters ---------- G : ndarray of bool A 1D array of logicals. ...
3283601
from contextlib import suppress from datetime import datetime from typing import Optional from models_library.projects import ProjectID from models_library.projects_state import RunningState from pydantic import BaseModel, PositiveInt, validator from simcore_postgres_database.models.comp_pipeline import StateType fro...
3283674
class Node: def __init__(self, e): self._element = e self._next = None def is_cyclic(head): """ :type head: Node :rtype: bool """ if not head: return False runner = walker = head while runner._next and runner._next._next: runner = runner._next._next ...
3283700
import unittest from fluent.runtime import FluentBundle, FluentResource from fluent.runtime.errors import FluentFormatError, FluentReferenceError from ..utils import dedent_ftl class TestParameterizedTerms(unittest.TestCase): def setUp(self): self.bundle = FluentBundle(['en-US'], use_isolating=False) ...
3283704
def test_type_ref_empty(): from qlient.schema.models import TypeRef type_ref = TypeRef() assert type_ref.kind is None assert type_ref.name is None assert type_ref.of_type is None assert type_ref.graphql_representation is None def test_type_ref_values(): from qlient.schema.models import Typ...
3283722
from nose.tools import assert_equal import numpy as np import cv_bridge def test_cvtColorForDisplay(): # convert label image to display label = np.zeros((480, 640), dtype=np.int32) height, width = label.shape[:2] label_value = 0 grid_num_y, grid_num_x = 3, 4 for grid_row in xrange(grid_num_y)...
3283738
import torch import torch.nn as nn import torch.nn.functional as F from backbone import (res32_cifar, res50, res10) from modules import GAP, FCNorm, Identity, LWS import copy import numpy as np import cv2 import os class Network(nn.Module): def __init__(self, cfg, mode="train", num_classes=1000): ...
3283770
import dateutil.parser from blockapi.services import BlockchainAPI class EosparkAPI(BlockchainAPI): """ EOS API docs: https://developer.eospark.com/api-doc/https/ Explorer: https://eospark.com """ symbol = 'EOS' base_url = 'https://api.eospark.com/api' rate_limit = 0 coef = 1e-6 ...
3283819
from registration.signals import user_activated from django.contrib.auth import login, authenticate def login_on_activation(sender, user, request, **kwargs): """Logs in the user after activation""" user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) # Registers the function wit...
3283838
from datadog import initialize, api options = { 'api_key': '<DATADOG_API_KEY>', 'app_key': '<DATADOG_APPLICATION_KEY>' } initialize(**options) account_id = "<AWS_ACCOUNT_ID>" lambda_arn = "arn:aws:lambda:<REGION>:<AWS_ACCOUNT_ID>:function:<LAMBDA_FUNCTION_NAME>" api.AwsLogsIntegration.add_log_lambda_arn(acc...
3283860
from django.shortcuts import render from InternetSemLimites.core.models import Provider, State def fame(request): ctx = {'states': _fame_listed_by_states()} return _render_md(request, 'fame', ctx) def shame(request): ctx = {'providers': Provider.objects.shame()} return _render_md(request, 'shame', c...
3283861
import requests from itertools import chain from bs4 import BeautifulSoup, Tag BASE_URL = 'https://mvnrepository.com/artifact/{group}/{artifact}/{number}' class MvnRepository: def __init__(self, http_compression=True): self._session = requests.Session() if not http_compression: self...
3283886
import unittest from pyannotate_tools.annotations.types import AnyType, ClassType, TupleType, UnionType class TestTypes(unittest.TestCase): def test_instance_str(self): # type: () -> None assert str(ClassType('int')) == 'int' assert str(ClassType('List', [ClassType('int')])) == 'List[int]...
3283917
import logging import os import subprocess class DiffException(Exception): pass def diff_strings(output: str, expected_output: str) -> str: mdiff_path = "frontend_tests/zjsunit/mdiff.js" if not os.path.isfile(mdiff_path): # nocoverage msg = "Cannot find mdiff for Markdown diff rendering" ...
3283918
import re import logging from datetime import timedelta from subprocess import Popen, PIPE import torch def get_logger(logfile): """Global logger for every logging""" logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s:%(filename)s:%(lineno)s:...
3283966
import typing from base64 import b64decode from enum import Enum from io import BytesIO from mimetypes import guess_type import re from django.core.exceptions import ValidationError from django.core.files import File from django.forms import Field from django.utils.translation import gettext_lazy as _ from .exception...
3283967
import tensorflow as tf import numpy as np import copy class TextRCNN(object): """ A RNN-CNN for text classification/regression. Uses an embedding layer, followed by a recurrent, convolutional, fully-connected (and softmax) layer. """ def __init__( self, model_type, sequence_length, num_clas...
3283978
import asyncio from asyncio import CancelledError from typing import Any, Awaitable, Sequence, TypeVar, cast, Union from protoactor.actor.exceptions import OperationCancelled, EventLoopMismatch _R = TypeVar('_R') class CancelToken: def __init__(self, name: str, loop: asyncio.AbstractEventLoop = None) -> None: ...
3284021
from snsql.reader.base import Reader from snsql.sql.reader.engine import Engine import importlib from snsql.sql.reader.probe import Probe class SqlReader(Reader): @classmethod def get_reader_class(cls, engine): prefix = "" for eng in Engine.known_engines: if str(eng).lower() == eng...
3284035
import aioredis import asyncio import base64 import pytest import tempfile import sys import base58 import json import os import psutil import random from web3 import Web3 from aioresponses import aioresponses from asynctest.mock import patch from polyswarmclient import Client # THE FOLLOWING KEY IS FOR TESTING PURP...
3284036
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Apache OFBiz XML-RPC Java Deserialization''', "description": '''XML-RPC request are vulnerable to unsafe deserialization and Cross-Site Scripting issues in Apache OFBiz 17.12.03''', "severity":...
3284058
import json import random import string from rest_framework.authtoken.models import Token from rest_framework.test import APIClient class ApiClient(APIClient): def __init__(self, user=None, *args, **kwargs): super().__init__(*args, **kwargs) if user: self.user = user self...
3284099
import math class Solution: def canMeasureWater(self, x: 'int', y: 'int', z: 'int') -> 'bool': if x + y < z: return False if x == 0 and y == 0: return z == 0 return z % math.gcd(x, y) == 0
3284119
from .base_lib import BaseLib class HentaiNexusComCrypt(BaseLib): def __init__(self): super().__init__() self._this = [] self._pads = {} def decode(self, enc): buff = self.base64decode(enc) i = 0 file = 0 key = 0 _hash = 0 _input = [] ...
3284120
import os import openmc import openmc.model import pytest from tests.testing_harness import TestHarness, PyAPITestHarness def make_model(): model = openmc.model.Model() # Materials moderator = openmc.Material(material_id=1) moderator.set_density('g/cc', 1.0) moderator.add_nuclide('H1', 2.0) ...
3284157
import model import dataclasses import asyncio import struct import typing import ujson import time @dataclasses.dataclass class Response: """The format of a Minecraft server response packet.""" version_name: str version_protocol: int player_max: int players_online: int sample: list[dict[str, ...
3284186
initiative_list = [] print ("D&D initiative tracker") print ("Usage: [player name] [roll]") print ('Type "stop" when you are done!') #Adding initiative while True: line = input().split() if (line[0]=='stop'): break try: player_name = str(line[0]) player_initiative = int(line[1]) initiative_list.append(...
3284205
import re from collections import namedtuple import operator import pytest import magma as m import magma if magma.mantle_target == "coreir": output = "coreir" suffix = ".json" else: output = "verilog" suffix = ".v" import mantle from fault.test_vectors import generate_function_test_vectors, \ ...
3284239
import pytest from specklepy.api.models import Stream from specklepy.objects import Base from specklepy.objects.encoding import ObjectArray from specklepy.serialization.base_object_serializer import BaseObjectSerializer from specklepy.transports.sqlite import SQLiteTransport class TestObject: @pytest.fixture(scop...
3284262
import os import pprint import shutil import json from tqdm import tqdm, trange import numpy as np import torch import torch.nn.functional as F from common.utils.load import smart_load_model_state_dict from common.trainer import to_cuda from common.utils.create_logger import create_logger from vqa.data.build import m...
3284272
import os, glob import pandas as pd import cv2 import numpy as np from configparser import ConfigParser, MissingSectionHeaderError, NoSectionError, NoOptionError from pylab import * from simba.rw_dfs import * from simba.drop_bp_cords import * import pyarrow.parquet as pq import pyarrow as pa from simba.interp...
3284277
from __future__ import print_function import os, sys import numpy as np import tensorflow as tf from tensorflow.keras import layers import math import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt class ARCH_cifar10(): def __init__(self): print("Creating CIFAR-10 architectures for ACGAN case") ...
3284280
import ctypes import logging import os import signal from multiprocessing import Process logger = logging.getLogger(__name__) # Covered by integration tests class ExceptionLoggingProcess(Process): # pragma: no cover def run(self) -> None: try: super().run() except Exception as e: ...
3284312
from cocoa.neural.utterance import Utterance from cocoa.neural.utterance import UtteranceBuilder as BaseUtteranceBuilder from symbols import markers, category_markers from core.price_tracker import PriceScaler from cocoa.core.entity import is_entity class UtteranceBuilder(BaseUtteranceBuilder): """ Build a wo...
3284324
from __future__ import unicode_literals import datetime import django from django.test import TestCase, override_settings from django.utils import timezone from .models import Article, Category, Comment class DateTimesTests(TestCase): def test_related_model_traverse(self): a1 = Article.objects.create( ...
3284359
import pytest from assertpy import assert_that from pyppium import driver from pyppium.exception import CapabilitiesNoneException @pytest.mark.unity def test_should_get_driver_platform(mocker, mock_pyppium_instance, mock_desired_caps): spy = mocker.spy(driver, "platform_name") driver.platform_name() spy.a...
3284362
import io from CTFd.models import Challenges, Teams, Users from CTFd.utils.crypto import verify_password from tests.helpers import create_ctfd, destroy_ctfd, gen_challenge, login_as_user def test_export_csv_works(): """Test that CSV exports work properly""" app = create_ctfd() with app.app_context(): ...
3284373
import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Output, Input, State from dash.exceptions import PreventUpdate # This stylesheet makes the buttons and table pretty. external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(_...
3284375
from random import random from coldtype.color.html import NAMED_COLORS from coldtype.interpolation import norm try: import skia except ImportError: skia = None try: from fontTools.ttLib.tables.C_P_A_L_ import Color as FTCPALColor except ImportError: FTCPALColor = None def norm(value, start, stop): ...
3284456
import functools import json import requests def render_html(name, data): return """ <div data-hypernova-key="{name}"></div> <script type="application/json" data-hypernova-key="{name}"> <!--{data}--></script> """.format( name=name, data=json.dumps(data) ) def render_fallb...
3284483
import numpy as np import mistree as mist def test_get_branch_index(): x = np.random.random_sample(50) y = np.random.random_sample(50) mst = mist.GetMST(x=x, y=y) mst.construct_mst() mst.get_degree() mst.get_degree_for_edges() branch_index, branch_index_rejected = mist.get_branch_index(mst...
3284509
from django.contrib import admin from info.models import Students,Teachers from import_export import resources from import_export.admin import ImportExportModelAdmin, ImportExportActionModelAdmin admin.site.site_title="西院助手后台系统" admin.site.site_header="西院助手后台管理" admin.site.index_title="欢迎来到西院助手后台管理" class StuResour...
3284510
from helpers import absolute_sample_path from pdfminer.high_level import extract_pages from pdfminer.layout import LTChar, LTTextBox def test_font_size(): path = absolute_sample_path('font-size-test.pdf') for page in extract_pages(path): for text_box in page: if isinstance(text_box, LTText...
3284542
from .. import LinearExplainer from .. import KernelExplainer from .. import SamplingExplainer from ..explainers import other from .. import __version__ from . import measures from . import methods import sklearn import numpy as np import copy import functools import time import hashlib import os try: import dill a...
3284567
import torch import sys import os sys.path.append(os.getcwd()) from unimodals.common_models import Linear, MaxOut_MLP from datasets.imdb.get_data import get_dataloader from fusions.common_fusions import Concat from objective_functions.objectives_for_supervised_learning import CCA_objective from training_structures.Su...
3284579
from django import VERSION as DJANGO_VERSION if DJANGO_VERSION < (2,): from django.core.urlresolvers import reverse # noqa else: from django.urls import reverse # noqa
3284644
def do(gen, spps): # Note: multiplying by 2.5 tries to make the renders approximately equal-time with T-GPT and GPT. for spp in spps: # Standard path tracing. gen.queuePath( scene = 'crytek_sponza', seed = 0, spp = int(2.5 * spp), frame_time = 1.0, shutter_time = 0.5, frame_count = 240 )
3284651
import numpy as np import torch import torch.nn as nn import functools import open3d from torch.autograd import Function from .base_model import BaseModel from ...utils import MODEL from ..modules.losses import filter_valid_label from ...datasets.augment import SemsegAugmentation if open3d.core.cuda.device_count() > ...
3284656
import argparse from utils import read_data, save_pickle, read_ade_data from biobert_ner.utils_ner import generate_input_files from biobert_re.utils_re import generate_re_input_files from typing import List, Iterator, Dict import warnings import os labels = ['B-DRUG', 'I-DRUG', 'B-STR', 'I-STR', 'B-DUR', 'I-DUR', ...
3284669
import torch.nn as nn import torch as t import torch.nn.functional as F class CondConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, num_experts=1): super(CondConv2d, self).__init_...
3284746
from direct.directnotify import DirectNotifyGlobal from otp.launcher.DummyLauncherBase import DummyLauncherBase from toontown.launcher.ToontownLauncher import ToontownLauncher class ToontownDummyLauncher(DummyLauncherBase, ToontownLauncher): notify = DirectNotifyGlobal.directNotify.newCategory('ToontownDummyLaunch...
3284753
import unittest from vex.parsers.s_cmd import SubstituteLexer from vex.parsers.parsing import RegexToken from vex.parsers.parsing import Lexer from vex.parsers.parsing import EOF class TestRegexToken(unittest.TestCase): def setUp(self): self.token = RegexToken("f[o]+") def testCanTestMem...
3284785
from depot.io import utils from depot.manager import DepotManager from ..interfaces import FileFilter from PIL import Image from io import BytesIO class WithThumbnailFilter(FileFilter): """Uploads a thumbnail together with the file. Takes for granted that the file is an image. The resulting uploaded file...
3284817
from django.conf.urls import patterns, url urlpatterns = patterns( 'gui.dc.dns.views', url(r'^$', 'dc_domain_list', name='dc_domain_list'), url(r'^form/dc/$', 'dc_domain_form', name='dc_domain_form'), url(r'^form/admin/$', 'admin_domain_form', name='admin_domain_form'), url(r'^records/$', 'dc_doma...
3284868
import unittest import hello from hello import cmake_generated_module class HelloTest(unittest.TestCase): def test_hello(self): self.assertEqual(hello.who(), "world") with open("test_hello.completed.txt", "w") as marker: marker.write("") def test_cmake_generated_module(self): ...
3284879
import os import shutil import subprocess import sys import time import pytest import fsspec from fsspec.implementations.cached import CachingFileSystem @pytest.fixture() def m(): """ Fixture providing a memory filesystem. """ m = fsspec.filesystem("memory") m.store.clear() try: yiel...
3284899
from gym.envs.parameter_tuning.convergence import ConvergenceControl from gym.envs.parameter_tuning.train_deep_cnn import CNNClassifierTraining
3284989
import httplib import sys def get_status_code(host, path="/"): """ This function retreives the status code of a website by requesting HEAD data from the host. This means that it only requests the headers. If the host cannot be reached or something else goes wrong, it returns None instead. ...
3285025
import pytest def bunchify(obj): if isinstance(obj, (list, tuple)): return [bunchify(item) for item in obj] if isinstance(obj, dict): return Bunch(obj) return obj class Bunch(dict): def __init__(self, kwargs=None): if kwargs is None: kwargs = {} for key, v...
3285029
from abc import ABCMeta, abstractmethod from CertManager import CertManager import Utils class CertificateTC(object): __metaclass__ = ABCMeta def __init__(self, hostname, port): self.cert_manager = CertManager() self.hostname = hostname self.port = port @abstractmethod def c...
3285065
import numpy as np import os from pickle import dump import string from tqdm import tqdm from utils.model import CNNModel from keras.preprocessing.image import load_img, img_to_array from datetime import datetime as dt # Utility function for pretty printing def mytime(with_date=False): _str = '' if with_date: _str...
3285083
import os import requests import shutil from zipfile import ZipFile from volatility3 import framework from pathlib import Path from glob import glob from django.core.management.base import BaseCommand from django.conf import settings import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) ...
3285089
def clear_table_name(table_name): if "." in table_name: _, table_name = table_name.split(".", 1) # i.e.: 'public.objects' -> 'objects' return table_name def get_table_definition(name, schema, primary_keys=None): primary_keys = primary_keys or [] pk = "" if len(primary_keys) > 0: p...
3285262
import numpy as np import pytest from nlp_profiler.constants import NaN from nlp_profiler.granular_features.chars_spaces_and_whitespaces \ import count_chars, count_whitespaces, count_characters_excluding_whitespaces, \ gather_repeated_whitespaces, count_repeated_whitespaces # noqa text_with_a_number = '2833...
3285277
import asyncio import contextlib import json import logging from typing import (Any, Callable, Coroutine, Dict, Iterator, List, Optional, Type, TypeVar, Union, cast, overload) import backoff import pydantic import websockets import websockets.exceptions from websockets.legacy import client as ws_cl...
3285312
from django.test import TestCase from rest_framework.test import APIRequestFactory, APITestCase from states import apiviews class TestState(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.view = apiviews.StateViewSet.as_view({'get': 'list'}) self.uri = '/api/states/...
3285323
from .config import Config from .dependency_config import DependencyConfig from .install_config import InstallConfig from .setup_config import SetupConfig from .step_config import StepConfig __all__ = ["Config", "DependencyConfig", "InstallConfig", "SetupConfig", "StepConfig"]
3285329
import numpy as np from typing import List from summer import CompartmentalModel from autumn.tools.curve import tanh_based_scaleup from .constants import COMPARTMENTS, Compartment, INFECTIOUS_COMPS def request_outputs( model: CompartmentalModel, cumulative_start_time: float, location_strata: List[str],...
3285354
import os import sys from contextlib import redirect_stdout, redirect_stderr from io import StringIO from unittest import TestCase import flask_unsign_wordlist class FlaskUnsignWordlistTestCase(TestCase): files = ('all', 'github', 'stackoverflow') def test_get(self): for file in self.files: ...
3285386
from __future__ import absolute_import, division, print_function import json import sys import _jsonnet from kpm.render_jsonnet import RenderJsonnet from kpm.template_filters import jsonnet_callbacks #r = RenderJsonnet() #result = r.render_jsonnet(open(sys.argv[1]).read()) def native_bool(b): return ['true', T...
3285401
import asyncio import logging import string from aiokit import AioThing from library.telegram.base import BaseTelegramClient from telethon.tl.functions.channels import GetParticipantsRequest from telethon.tl.types import ChannelParticipantsSearch class AdminLogReader(AioThing): def __init__(self, telegram_config...
3285445
import argparse from .common import valid_file def add_arguments(parent: argparse._SubParsersAction) -> None: parser = parent.add_parser( 'detect', help='Uses a trained model to identify gibberish strings.', ) parser.add_argument( '-m', '--model', required=True, ...
3285463
import barnum, random, time, json, requests, math from mysql.connector import connect, Error from kafka import KafkaProducer # CONFIG userSeedCount = 10000 itemSeedCount = 1000 purchaseGenCount = 1000 purchaseGenEveryMS = 2000 pageviewMultiplier = 75 # Translates to 75x purchases, currently 750/sec o...
3285471
from contextlib import closing from django.contrib import auth from django.core.management import call_command from django.db import connection from django.test import TestCase import models class ViewTestCase(TestCase): def setUp(self): call_command('sync_pgviews', *[], **{}) def test_views_have_...
3285485
from datetime import datetime import threading import sys import os import pickle import re import requests from bs4 import BeautifulSoup import numpy as np import pandas as pd # Import parent class from .FomcBase import FomcBase class FomcMinutes(FomcBase): ''' A convenient class for extracting minutes fro...
3285553
from django.db import models class CodeLanguage(models.Model): name = models.CharField(max_length=32) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class CodeRepository(models.Model): UPDATE_IN_PROGRESS = 0 UPDATE_FINISHED = 1 UPDATE_ERROR...
3285558
import os import sys import argparse import configparser import shutil import utils.data as config from pipelines.train_css import train_css from pipelines.refine_css import refine_css from pipelines.refine_css_demo import refine_css_demo from pipelines.evaluate_dump import evaluate import torch import numpy seed = 1...
3285576
import abc from typing import * from ..column import Column if TYPE_CHECKING: from ..row import Row class RowSet(metaclass=abc.ABCMeta): @abc.abstractmethod def columns(self) -> List[Column]: """ Describe columns in this row set. """ @abc.abstractmethod def iter(self) ->...
3285586
import re from django.apps import AppConfig from fluent_utils.load import import_module_or_none class FluentPagesConfig(AppConfig): name = "fluent_pages" verbose_name = "Fluent Pages" def ready(self): _register_subclass_types() def _register_subclass_types(): """ See if any page type p...
3285590
from math import gcd class Rational: def __init__(self, numer, denom): # abs used for backward compatibility with fractions.gcd gcd_num = abs(gcd(numer, denom)) self.numer = numer // gcd_num self.denom = denom // gcd_num if self.denom < 0: self.numer *= -1 ...
3285592
import pytest import Intel471Actors as feed BUILD_PARAM_DICT_DATA = [ ( {'credentials': {'identifier': 'username', 'password': '<PASSWORD>'}, 'insecure': True, 'fetch_time': '10 minutes', 'proxy': False}, # input 'https://api.intel471.com/v1/actors?actor=*' # expected ), ( ...
3285601
import numpy as np import os import torch import torchvision.models as models from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader import sys import math import torch.nn.init as init import logging from torch.nn.par...
3285602
from celery import states from django.db import models from share.models.fields import DateTimeAwareJSONField from share.models.jobs import get_share_version ALL_STATES = sorted(states.ALL_STATES) TASK_STATE_CHOICES = sorted(zip(ALL_STATES, ALL_STATES)) class CeleryTaskResult(models.Model): # Explicitly defin...
3285609
import logging from universe import vectorized logger = logging.getLogger(__name__) class RandomEnv(vectorized.Wrapper): ''' Randomly sample from a list of env_ids between episodes. Passes a list of env_ids to configure. When done=True, calls env.reset() to sample from the list. ''' def __ini...
3285621
from calendar import timegm from datetime import datetime, timedelta, timezone import jwt import time_machine from pythonit_toolkit.pastaporto.actions import ( Action, PastaportoAction, create_user_auth_pastaporto_action, ) from ward import test @test("create user auth action") async def _(): action ...
3285628
import geopandas as gpd import momepy as mm import numpy as np class TimeDimension: def setup(self): test_file_path = mm.datasets.get_path("bubenec") self.df_buildings = gpd.read_file(test_file_path, layer="buildings") self.df_streets = gpd.read_file(test_file_path, layer="streets") ...
3285633
import unittest from katas.kyu_7.perfect_number_verifier import isPerfect class IsPerfectTestCase(unittest.TestCase): def test_true(self): self.assertTrue(isPerfect(6)) def test_true_2(self): self.assertTrue(isPerfect(28)) def test_true_3(self): self.assertTrue(isPerfect(8128)) ...
3285653
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.gridspec as gridspec import matplotlib.patches as mpatches from scipy.optimize import minimize import time def plant_model(prev_state, dt, pedal, steering): x_t = prev_state[0] y_t = prev_state[1] ...
3285655
from marmot.features.feature_extractor import FeatureExtractor from marmot.util.ngram_window_extractor import left_context, right_context class PairedFeatureExtractor(FeatureExtractor): ''' Paired features: - target token + left context - target token + right context - target token + s...
3285678
import argparse ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True) ap.add_argument("-w", "--width", required=True) args = vars(ap.parse_args()) print(args)
3285704
from setuptools import setup from setuptools import find_packages setup(name='sogou_mrc', version='0.1', description='sogou_mrc', author='<NAME>', install_requires=['numpy', 'tensorflow-gpu==1.12', 'tensorflow-hub', "tqdm", "spacy", "jieba", "stanfordnlp"], packag...
3285731
import pandas as pd import pytest from qac.simq.simq_features import FeatureGenerator DATA = pd.DataFrame([ [0, 'title', 'body', 'tags', 1], [1, 'title', 'body', 'tags', 1], [2, 'title', 'body', 'tags', 1], [3, 'title', 'body', 'tags', 1], [4, 'title', 'body', 'tags', 1], [5, 'title', 'body', ...