id
stringlengths
3
8
content
stringlengths
100
981k
9953609
import logging from logging.handlers import TimedRotatingFileHandler logger = logging.getLogger(__name__) from nymms.reactor.handlers.Handler import Handler class LogHandler(Handler): """ A basic handler to send alerts to a log file via python's logging module. """ def _setup_logger(self): i...
9953648
from constants.globals import DEBUG from constants.mock_values import * from service.general_network_service import eth_rpc_request def is_eth_node_fully_synced(node_ip) -> bool: if DEBUG: return not eth_is_syncing_mock is_syncing = eth_rpc_request(node_ip, method="eth_syncing").json()['result'] ...
9953679
from distutils.core import setup #files = files = ["enums/*"] setup(name='agescx', version='0.7', description='Age of Empires 2 .scx reading module', author='<NAME>', author_email='<EMAIL>', url='http://www.st.fmph.uniba.sk/~derevjanik7/rp1/', packages=['agescx', 'a...
9953683
from twisted.python import log from sys import stdout log.startLogging(stdout) from twisted.internet.protocol import Protocol, Factory class EchoProtocol(Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(Factory): protocol = EchoProtocol from txws import WebSocketF...
9953688
from flask.testing import FlaskClient from app import create_app, db from app.models import Framework, FrameworkLot class TestClient(FlaskClient): """This is a custom Test Client for handling the creation of a dedicated application context on a per request basis. Flask-SQLAlchemy attaches its db operations ...
9953716
import torch import torch.nn as nn from copy import deepcopy from xnas.spaces.OFA.ops import * from xnas.spaces.OFA.utils import min_divisible_value __all__ = ["WSConv_Network", "MobileNetV3", "MobileNetV3Large"] class WSConv_Network(nn.Module): """Network with all Conv2d replaced by Weight Standard Conv2d."""...
9953724
from functools import wraps as _wraps from time import time as _time from nonebot import CommandSession as _CommandSession from nonebot import on_command as _on_command from nonebot.command import CommandHandler_T from nonebot.permission import GROUP_MEMBER, SUPERUSER from .logging import logger as _logger from .typi...
9953731
from __future__ import unicode_literals from .classes import * # NOQA default_app_config = 'mailer.apps.MailerApp'
9953743
import statistics import json import energyusage import energyusage.locate as locate with open("./energyusage/data/json/energy-mix-intl.json") as file: data = json.load(file) max = "" median = "" min = "" countries = [] for country in data: c = data[country] total, breakdown = c['total'], [c['coal'], c['p...
9953773
from unittest import mock from rest_framework import status, test from waldur_mastermind.invoices.tests import factories, fixtures class InvoiceItemDeleteTest(test.APITransactionTestCase): def setUp(self): self.fixture = fixtures.InvoiceFixture() def delete_invoice_item(self, user): self.cl...
9953780
from typing import Any, Type from blacksmith.typing import ( ClientName, HTTPMethod, Json, Path, ResourceName, Service, ServiceName, Version, ) class ConfigurationError(Exception): """Raised if there is a conflict for client and service.""" def __init__(self, client: ClientNa...
9953781
import cv2 from centersnap import CenterSnap from centersnap.utils import load_img_NOCS model_path = "models/CenterSnap_sim.onnx" # Read rgb image and depth map # Download data from the original repository: https://www.dropbox.com/s/yfenvre5fhx3oda/nocs_test_subset.tar.gz img_path = "test/scene_2/0073_color.png" dep...
9953792
import ctypes # Get memory address 0, your kernel shouldn't allow this: ctypes.string_at(0) ############################################################################## import ctypes try: # Get memory address 0, your kernel shouldn't allow this: ctypes.string_at(0) except Exception as e: print('Got ex...
9953813
OS_SHELL_MAPPINGS = { 'ubuntu':'bash', 'alpine':'sh', 'debian':'bash', 'centos':'bash', 'oracle':'bash', 'opensuse':'bash', 'fedora':'bash' }
9953847
import numpy as np import scipy from sklearn.model_selection import (train_test_split, KFold) from sklearn import metrics class KNN(): def __init__(self, k=3): self.k = k def fit(self, X_train, Y_train): self.X_train = X_train self.Y_train = Y_train def score(self, X, target): ...
9953881
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from manopth.rodrigues_layer import batch_rodrigues from hocontact.hodatasets.hoquery import TransQueries from hocontact.models.bases import hourglass from hocontact.models.contacthead import PointNetContactHead from hoc...
9953927
from rlo.expression import Expression from rlo.expression_util import deep_copy_with_types from rlo import rewrites from rlo import sparser from ksc.type import Type def test_rule_breaks_alpha_conversion(): var0 = Expression.Variable( "var0", Type.Tuple(Type.Tensor(1, Type.Float), Type.Tensor(1, T...
9953936
import unittest import import_ipynb import pandas as pd import pandas.testing as pd_testing import numpy.testing as np_testing class Test(unittest.TestCase): def setUp(self): import Exercise1_01 self.exercises = Exercise1_01 self.algorithm = ['Linear Regression', 'Logistic Regression', 'RandomForest', 'a3c']...
9953975
from collections import OrderedDict from scipy.spatial.transform import Rotation as R from scipy.spatial.transform import Slerp import numpy as np import json import multiprocessing as mp from tqdm import tqdm def pretty_print(ob): print(json.dumps(ob, indent=4)) def euler_to_rot(angles): # Euler ZYX to Rot...
9954012
import argparse import os import os.path as path import glob import torch import torch.nn as nn import logging from others.logging import set_logger, init_logger import train_abstractive as train_abs import models.data_loader as data_ldr import models.model_builder as model_bld import models.predictor as pred_abs from ...
9954014
import pytest from genalog.text.lcs import LCS @pytest.fixture( params=[ ("", ""), # empty ("abcde", "ace"), # naive case ] ) def lcs(request): str1, str2 = request.param return LCS(str1, str2) def test_lcs_init(lcs): assert lcs._lcs_len is not None assert lcs._lcs is not ...
9954021
from .categorizedStyle import categorizedStyle from .classification import Classification from .classifiedStyle import ClassifiedStyle from .featureLabel import FeatureLabel from .postgres import Pg from .rasterStyle import RasterStyle from .simpleStyle import SimpleStyle from .support import RasterColorPalette, Vector...
9954058
import json from datetime import datetime, date from enum import Enum from olo.sql_ast_translators.sql_ast_translator import SQLASTTranslator from olo.context import context, alias_only_context from olo.utils import compare_operator_precedence, is_sql_ast, car from olo.compat import ( Decimal, long, unicode, ) c...
9954081
from .common import * from .block import * from .detects import * detect_type = (DetectX, DetectV5)
9954084
import typing from cauldron import environ def remove_key(key: str, persists: bool = True): """ Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param persists: """ environ.configs.remove(key, include...
9954128
from pygame.math import Vector2 from vgdl.core import Action, Color GREEN = Color((0, 200, 0)) BLUE = Color((0, 0, 200)) RED = Color((200, 0, 0)) GRAY = Color((90, 90, 90)) WHITE = Color((250, 250, 250)) BROWN = Color((140, 120, 100)) BLACK = Color((0, 0, 0)) ORANGE = Color((250, 160, 0)) YELLOW = Color((250, 250, 0))...
9954160
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import dlib import glob import h5py from skimage import io import time import numpy as np import collections from imutils import face_utils import cv2 from scipy.misc import...
9954187
import json import sys if __name__ == "__main__": new_data_json = open(sys.argv[3], "w+") a = json.load(open(sys.argv[1], "r")) b = json.load(open(sys.argv[2], "r")) new_data = { "bleu": (a["bleu"] + b["bleu"]) / 2, "score": (a["score"] + b["score"]) / 2, } json.dump(new_data, new_data_json)...
9954335
import unittest from huggingmolecules import MatConfig, MatFeaturizer from huggingmolecules.configuration.configuration_mat import MAT_CONFIG_ARCH from tests.featurization.expected.featurization_expected_mat import expected_batch, expected_encoded_smiles from tests.featurization.featurization_base import Featurization...
9954338
from typing import Optional, Sequence from model.specs import ( SignedBeaconBlock, SLOTS_PER_EPOCH, ) from model.validatorlib import ( honest_propose, slashable_propose ) from model.validators.ASAPValidator import ASAPValidator ############################# # Main new function handling different scenarios t...
9954348
import argparse from pathlib import Path parser = argparse.ArgumentParser() parser.add_argument('input', type=Path) parser.add_argument('output', type=Path) parser.add_argument('--prefix', default='') argument = parser.parse_args() input = argument.input # type: Path output = argument.output # type: Path paths = l...
9954358
import argparse import os from frag.utils.network_utils import get_driver,add_attr,add_edge,add_node from tqdm import tqdm if __name__ == "__main__": parser = argparse.ArgumentParser(description='Upload Nodes, Edges and Attributes') parser.add_argument('--base_dir') args = parser.parse_args() driver...
9954374
import os import urllib.request import subprocess import glob import cv2 import math import numpy as np from config import get_args def load_txt(file_path, mode='trainval'): filename = 'ava_file_names_{}_v2.1.txt'.format(mode) filename = os.path.join(file_path, filename) with open(filename, 'r') as f: ...
9954384
import cPickle as pickle import numpy as np import requests import tensorflow as tf import numpy as np from tensorflow.contrib.session_bundle import exporter VERSION = 44 def create_and_export_model(export_path): x = tf.placeholder(tf.int32, shape=[3]) z = tf.Variable([2]) y = tf.mul(x, z) sess = t...
9954387
import sys import pytest import numpy as np import matplotlib as mpl import flopy import pymake flopypth = flopy.__path__[0] pymakepth = pymake.__path__[0] print("python version: {}".format(sys.version)) print("pytest version: {}".format(pytest.__version__)) print("numpy version: {}".format(np.__version__))...
9954394
import random,sys,struct,string from hashlib import sha256 import SocketServer from Crypto.Util.number import getPrime import numpy as np from flag import FLAG class Task(SocketServer.BaseRequestHandler): def proof_of_work(self): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in x...
9954410
import logging import json from collections import OrderedDict from urllib.parse import urlparse from pulsar.api import Http404, ImproperlyConfigured from pulsar.apps.wsgi import Route from pulsar.utils.httpurl import remove_double_slash from pulsar.utils.importer import module_attribute from lux import models from l...
9954475
import numpy as np from scipy.stats import norm from ._base import GraphWorld class DecisionTree(GraphWorld): """Decision tree from aversive pruning experiments. Attributes ---------- states : array, shape = (n,) Indices of states. n_states : int Total number of states. via...
9954485
import re search_name_re = re.compile(r"^job:([^:]+):(.+)$") def format(category, job_name): return "job:%s:%s" % (category, job_name) def parse(search_name): match = search_name_re.match(search_name) if not match: return None, None category = match.group(1) job_name = match.group(2) ...
9954491
import pytest import unittest from tests.helpers import * __all__ = [ 'pytest', 'unittest' ]
9954529
from setuptools import setup, find_packages setup( name='tusimple_duc', version='1.0.0', author='<NAME> & <NAME>', description='semantic segmentation module on the Cityscapes dataset', install_requires=['configparser', 'numpy', 'Pillow'], url='https://github.com/TuSimple/TuSimple-DUC', pac...
9954541
from .decomposable_attention import DecomposableAttentionEntailment from .multiple_choice_tuple_entailment import MultipleChoiceTupleEntailment entailment_models = { # pylint: disable=invalid-name 'decomposable_attention': DecomposableAttentionEntailment, 'multiple_choice_tuple_attention': MultipleChoi...
9954605
import logging import uuid from pgshovel.interfaces.replication_pb2 import State from pgshovel.interfaces.streams_pb2 import ( BeginOperation, CommitOperation, MutationOperation, RollbackOperation, ) from pgshovel.streams.utilities import ( FormattedBatchIdentifier, FormattedSnapshot, ) from pg...
9954627
from nlgeval import NLGEval def test_oo_api(): with open("examples/hyp.txt") as f: hyp = f.readlines() hyp = [x.strip() for x in hyp] with open("examples/ref1.txt") as f: ref1 = f.readlines() ref1 = [x.strip() for x in ref1] with open("examples/ref2.txt") as f: ref2 ...
9954703
from collections.abc import Iterable def _drop(self, drop=None, like=None): columns = self.columns if isinstance(drop, str): drop = [drop] if not drop is None: for i in "Chromosome Start End".split(): assert not i in drop, "Cannot drop {}".format(i) want_to_drop_strand =...
9954705
class Solution: """ @param: chars: The letter array you should sort by Case @return: nothing """ def sortLetters(self, chars): # write your code here if not chars or len(chars) == 0: return lo, hi = 0, len(chars) - 1 while lo <= hi: while lo <...
9954788
from typing import Mapping, Sequence def sequence_match_logical(): """ Test matching the first element of a sequence is a frog. """ seq = ["🐸", "🐛", "🦋", "🪲"] frogs = 0 for _ in range(100_000): if isinstance(seq, Sequence) and len(seq) > 0 and seq[0] == "🐸": frogs += 1 ...
9954899
class Solution: """ @param arr: An integer array @param k: An integer @return: return the pair of movies index with the longest total duration """ def FlightDetails(self, arr, k): # write your code here movies = sorted((m, i) for i, m in enumerate(arr)) start = 0 ...
9954949
import numpy as np from ..features.preprocessing import undo_preemphasis from ..features.spectral_features import istft def convert_preprocessing_parameters(params): p = params.copy() if 'n_fft' in p: del p['n_fft'] if 'pad_mode' in p: del p['pad_mode'] return p def reconstruct(spec_...
9954955
from biicode.common.migrations.migration_manager import MigrationManager from biicode.client.store.migration_store import MigrationStore from biicode.client.migrations.migrations import get_client_migrations def launch(bii): disk = bii.hive_disk_image migration_store = MigrationStore(disk.hivedb) manager ...
9954978
from __future__ import division cdl_svl_database = { "trans/trans" : { "Gly_nonxpro" : ['?', -1, 121.4, 1.7, 113.3, 2.3, 120.6, 1.6, 116.7, 1.9, 122.7, 1.3], "Gly_xpro" : ['?', -1, 121.4, 1.7, 113.1, 2.3, 121.2, 1.3, 116.7, 1.5, 122.0, 0.9], "IleVal_nonxpro" : ['?', -1, 121.9, 1.7, 111.3, 1.5, 109.4, 2.1,...
9954998
import os from sys import platform if platform == "linux" or platform == "linux2": try: os.system("sudo apt install nodejs") os.system("sudo apt install npm") except: os.system("sudo yum install nodejs") os.system("sudo yum install npm") os.system("npm install -g localtunne...
9955006
import numpy as np import logging import copy import numbers from scipy.special import logsumexp from sklearn.base import BaseEstimator from sklearn.utils.validation import check_is_fitted, NotFittedError from .preprocessing import DataWindow from . import core from .plotting import _plot_ratemap from .auxiliary imp...
9955028
import os from prefect.run_configs import LocalRun def test_no_args(): config = LocalRun() assert config.env is None assert config.working_dir is None assert config.labels == set() def test_all_args(tmpdir): working_dir = str(tmpdir) config = LocalRun( env={"hello": "world"}, ...
9955086
from django.contrib.auth.models import User import djclick as click from miqa.core.models import Project from miqa.core.rest.project import import_data @click.command() @click.option('--csv', type=click.Path(exists=True)) @click.option('--username', type=click.STRING, help='username for project creator') def command...
9955100
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import torchvision as tv # pre, post processing modules def softmax_aggregate(predicted_seg, object_ids): bg_seg, _ = torch.stack([seg[:, 0, :, :] for seg in predicted_seg.values()], dim=1).min(dim=1) bg_seg...
9955128
from beacon.nn.module import Module from beacon.nn import Linear from beacon.functional import functions as F class GRU(Module): def __init__(self, inputs, outputs): """ GRU Module - Fully gated unit. ## Parameters inputs: `int` - number of input features outputs: `int` -...
9955135
from datetime import datetime from flask import jsonify, abort, request, current_app from .. import main from app import db from app.main.encryption import hashpw, checkpw from app.main.validators import valid_user_authentication_submission, valid_create_user_submission, valid_email_address from app.main.views import g...
9955148
import aiorwlock import enum import contextlib import copy import io import logging import numpy import pathlib import tensorflow as tf import uuid from abc import ABCMeta, abstractmethod from datetime import datetime from typing import Sequence, Union from tensorcraft import errors from tensorcraft import signal fro...
9955171
import pint from . import util units = ("meter", "kilometer", "second", "minute", "angstrom") other_units = ("meter", "angstrom", "kilometer/second", "angstrom/minute") all_values = ("int", "float", "complex") ureg = None data = {} def setup(*args): global ureg, data data["int"] = 1 data["float"] =...
9955181
from stix.indicator import Indicator from stix.campaign import Campaign, RelatedIndicator from cybox.objects.address_object import Address from stix.core import STIXPackage def main(): package = STIXPackage() # Create the indicator indicator = Indicator(title="IP Address for known C2 Channel") indica...
9955184
import FWCore.ParameterSet.Config as cms from L1TriggerConfig.CSCTFConfigProducers.CSCTFConfigProducer_cfi import * from L1TriggerConfig.CSCTFConfigProducers.L1MuCSCPtLutRcdSrc_cfi import * from L1TriggerConfig.CSCTFConfigProducers.L1MuCSCTFAlignmentRcdSrc_cfi import * from L1TriggerConfig.CSCTFConfigProducers.L1MuCSC...
9955185
from sly import Parser from o_lexer import OLexer class OParser(Parser): """ Parser for the O Language """ tokens = OLexer.tokens precedence = ( ('right', PLUSASGN, MINUSASGN, STARASGN, SLASHASGN, MODULOASGN, ANDASGN, ORASGN, XORASGN, SHLASGN, SHRASGN), ('left', OR), ...
9955187
import numpy as np from surfinpy import bulk_mu_vs_mu from surfinpy import utils as ut from surfinpy import data import unittest from numpy.testing import assert_almost_equal import os test_data = os.path.join(os.path.dirname(__file__), 'H2O.txt') class Testbulk_mu_vs_mu(unittest.TestCase): def test_normalise_p...
9955196
import re from collections import defaultdict from heapq import nlargest from operator import itemgetter def tokenize(lines): """ Split text by space and puctuation into sentences :param lines: sequence of text containing line :return: yield tokenized text line by line """ tokenizer = re.compi...
9955269
from transformers import BertForQuestionAnswering, BertTokenizerFast from utils.data import get_dataloader from utils.env import enable_reproduce, get_device from utils.model import model_function def train(): enable_reproduce() # You can safely ignore the warning message (it pops up because new prediction h...
9955273
import urllib import urllib.parse import urllib.request import simplejson googleGeocodeUrl = 'http://maps.googleapis.com/maps/api/geocode/json?' def get_coordinates(query, from_sensor=False): query = query.encode('utf-8') params = { 'address': query, 'sensor': "true" if from_sensor else "false...
9955308
if not exists(Pattern("___xQI.png").similar(0.60)): exit(1) click(Pattern("___xQI.png").similar(0.60).targetOffset(16,0)) sleep(1) if exists("Pupma.png"): doubleClick("Pupma.png") exit(0)
9955385
import os SIMPLEFLOW_ENV = os.getenv("SIMPLEFLOW_ENV", "production") # Constants useful for defining SWF timeouts MINUTE = 60 HOUR = 60 * MINUTE DAY = 24 * HOUR # Formatting limits MAX_REASON_LENGTH = 256 MAX_DETAILS_LENGTH = 32768 MAX_EXECUTION_CONTEXT_LENGTH = 32768 MAX_HEARTBEAT_DETAILS_LENGTH = 2048 MAX_IDENTITY...
9955416
import time import traceback from talon import Module, actions, cron, noise, ui try: from talon.ui import Element except ImportError: Element = type(None) HISS_DEBUG_ENABLED = True mod = Module() setting_enabled = mod.setting( "hiss_to_debug_accessibility", type=bool, default=False, desc="Us...
9955440
def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] stack = [] while root: stack.append(root) root = root.left while stack: tmp = stack.pop() res.append(tmp.val) if tmp.right: t = tmp.right #add all left ...
9955444
import types from collections import deque, namedtuple from pycsp3.classes.entities import Node, TypeNode, ECtr, EMetaCtr from pycsp3.classes.main.constraints import ( ScalarProduct, PartialConstraint, ConstraintSum, ConstraintElement, ConstraintElementMatrix, ConstraintInstantiation, auxiliary, global_ind...
9955473
import sys from .tool import Tool from amitools.vamos.cfg import PathParser from amitools.vamos.path import VamosPathManager, AmiPathError class PathTool(Tool): def __init__(self): Tool.__init__(self, "path", "path conversion utilities") self.path_parser = None self.path_mgr = None d...
9955566
import torch from torch.autograd import Variable import torch.nn.functional as F from .performance import calculate_performance from sklearn.metrics import classification_report, confusion_matrix, accuracy_score def test(dataloader, net, criterion, optimizer, opt): # net.train() test_loss = 0 correct = 0 ...
9955590
import sys from prebuild_common import variant_types, pointer_variant_types, variant_enable_flags, proto_types path = '' if (len(sys.argv) > 1): path = sys.argv[1] header = open(path + '/blob_creator.hpp', 'w') header.write('// Automatically generated file, DO NOT EDIT!\n') header.write('#include "caffe/common.h...
9955611
DEBUG = True SECRET_KEY = 'yoursecret' STRIPE_API_KEY = 'yourapisecret' BCRYPT_LEVEL = 13 MAIL_FROM_EMAIL = "<EMAIL>" SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:1234@server/fos' SQLALCHEMY_TRACK_MODIFICATIONS = True SERVER_NAME = 'fos.dev' DEBUG_TB_INTERCEPT_REDIRECTS = False UPLOADS_DEFAULT_DEST = "public" UPLOAD...
9955626
from enum import Enum, auto RSA_ID_LENGTH = 13 DATE_OF_BIRTH_FORMAT = "%y%m%d" GENDER_FEMALE_MIN = 0 GENDER_FEMALE_MAX = 4999 GENDER_MALE_MIN = 5000 GENDER_MALE_MAX = 9999 SA_CITIZEN_DIGIT = "0" PERMANENT_RESIDENT_DIGIT = "1" RACE_DIGIT = "8" # used until 1980s class Gender(Enum): FEMALE = auto() MALE = aut...
9955694
from typing import NamedTuple, Optional class RenderedFileEntry(NamedTuple): body: str path: Optional[str] filename: str
9955715
from unittest import TestCase import gym import numpy as np from pysc2.lib.static_data import UNIT_TYPES, UPGRADES from sc2_imitation_learning.environment.sc2_environment import get_scalar_feature, SC2InterfaceConfig, Feature, \ get_screen_feature, get_minimap_feature, LookupFeature, AvailableActionsFeature, Padd...
9955762
import torch import subprocess from torch.utils.cpp_extension import CUDAExtension def check_cuda_torch_binary_vs_bare_metal(): # command line CUDA cuda_dir = torch.utils.cpp_extension.CUDA_HOME cuda_call = [cuda_dir + "/bin/nvcc", "-V"] raw_output = subprocess.check_output(cuda_call, universal_newli...
9955771
import tensorflow as tf import numpy as np from collections import Counter from bunch import Bunch import os, sys from model_io import model_io from optimizer import distributed_optimizer as optimizer from utils.bert import bert_utils try: from distributed_single_sentence_classification.model_interface import model_z...
9955790
from bitmovin_api_sdk.notifications.webhooks.encoding.encodings.encoding_status_changed.encoding_status_changed_api import EncodingStatusChangedApi
9955800
import asyncio def safe_invoke_callback(callback, *args, **kwargs): if asyncio.iscoroutinefunction(callback): asyncio.create_task(callback(*args, **kwargs)) else: callback(*args, **kwargs)
9955827
import pytest from e2e_tests.conftest import run_test_tcp_single_client_single_short_echo, \ run_test_tcp_single_client_multiple_short_echo, run_test_tcp_single_client_single_long_echo, \ run_test_tcp_multiple_clients_single_short_echo, run_tunneler_container, TunnelerType, TunneledType, TestPorts, \ TLS_S...
9955844
print list() # lists l = [1,2,3,4] print list([]) print list([1,2,3,4]) l2 = list(l) l[3] = 10 print l, l2 # tuples t = (1,2,3,4) print list(()) print list((1,2,3,4)) print list(t) # dictionaries d = {1:2,3:4} print list({}) print list(d) print list(d.keys()) print list(d.values())
9955857
from docker.errors import ContainerError from custom_image_cli.validation_tool.validation_tests import base_check class CheckLocalJobRun(base_check.BaseCheck): def __init__(self, image_uri, docker_cmd, log): self.image_uri = image_uri self.docker_cmd = docker_cmd self.log = log se...
9955858
from pseudo.pseudo_tree import Node class TreeTransformer: ''' visits recursively nodes of the tree with defined transform_<node_type> methods and transforms in place ''' before = None after = None whitelist = None # if a set, transform only those nodes, optimization current_class = ...
9955913
import matplotlib.pyplot as plt from matplotlib import ticker import os import os.path as osp import numpy as np import sys import mmcv from matplotlib.pyplot import axvline from matplotlib.pyplot import MultipleLocator import platform cur_dir = osp.dirname(osp.abspath(__file__)) sys.path.insert(0, osp.join(cur_dir, "...
9955926
import os import geckodriver_autoinstaller from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.webdriver.support import exp...
9955968
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def get_pad(in_, ksize, stride, atrous=1): out_ = np.ceil(float(in_)/stride) return int(((out_ - 1) * stride + atrous*(ksize-1) + 1 - in_)/2) class GatedConv2dWithActivation(nn.Module): """ Gated Convlution layer ...
9955971
import argparse import numpy as np from os import path import struct from internal import db_handling def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--sift_feature_dir', required=True) parser.add_argument('--nvm_file', required=True) parser.add_argument('--database_file', r...
9955975
from ...configs.kaggle.constants import NAME from ...configs.kaggle.kaggle_competitions import KAGGLE_COMPETITIONS, FITTING_PROFILES, PREDICTORS def get_full_benchmark(datasets_subset=None, profiles_subset=None, predictors_subset=None): """ Can optionally specify just a subset of benchmark to run """ datasets...
9956000
import numpy as np from bayesnet.array.broadcast import broadcast_to from bayesnet.linalg.cholesky import cholesky from bayesnet.linalg.det import det from bayesnet.linalg.logdet import logdet from bayesnet.linalg.solve import solve from bayesnet.math.exp import exp from bayesnet.math.sqrt import sqrt from bayesnet.ran...
9956039
from __main__ import app from flask import Flask, render_template, request, url_for, flash, redirect, Response, session @app.route('/') def index(): return render_template('public.html')
9956068
from flask import Flask, jsonify app = Flask('app') @app.route('/') def hello(): return jsonify({'hello': 'world'}) app.run(port='8080')
9956107
import torch.nn as nn import torch.utils.model_zoo as model_zoo from load_data import NUM_CHANNEL model_urls = { 'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth', } class VGG(nn.Module): def __init__(self, features, init_weights=True): super(VGG, self).__init__() self.fe...
9956119
from util import * cont, ip = create_container() print ip run_command(cont, "ip link") delete_container(cont)
9956136
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hqadmin', '0002_vcmmigrationaudit'), ] operations = [ migrations.RenameModel( old_name='VCMMigrationAudit', new_name='VCMMigration', ), ]
9956141
def recurrev(string, start, end): if start >= end: return string[start] , string[end] = string[end] , string[start] recurrev(string , start+1 , end - 1) n = input("Enter sentence: ") m = n.split() recurrev(m , 0 , len(m) - 1) print(" ".join(m))
9956203
import argparse from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * from lxml import etree import re import time import datetime import sys spark = SparkSession.builder.getOrCreate() sc = spark.sparkContext ### SO 25407550 log4jLogger = sc._jvm.org.apache.log4j LOG...