id
stringlengths
3
8
content
stringlengths
100
981k
9837672
import responses from trycourier.client import Courier @responses.activate def test_success_list(): responses.add( responses.GET, 'https://api.courier.com/notifications', status=200, content_type='application/json', body='{"paging": {"cursor":null,"more":false}, "results":...
9837682
import starry import numpy as np from scipy.linalg import block_diag from scipy.sparse import diags import pytest @pytest.fixture(scope="module", params=[1, 2]) def map(request): nc = request.param map = starry.DopplerMap(ydeg=10, udeg=2, nt=3, nc=nc, veq=50000) map.load(maps=["spot", "earth"][:nc]) y...
9837692
from torchgen.api.types import ( DispatcherSignature, ) from torchgen.model import ( BaseTy, OptionalType, BaseType, ListType, NativeFunction, Type, Argument, Return, SchemaKind, Tag ) from torchgen.api.translate import translate from torchgen.context import method_with_native_function from torchgen.utils i...
9837696
from asyncio import ensure_future from io import BytesIO from typing import Union, List, Dict from World.Chat.Builders.ChatPacketBuilder import ChatPacketBuilder from World.WorldPacket.Constants.WorldOpCode import WorldOpCode from World.Region.model import Region from World.Object.Unit.Player.model import Player from ...
9837700
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from mpl_toolkits.mplot3d import Axes3D nb_samples = 1000 nb_features = 3 nb_epochs = 200 batch_size ...
9837708
from enum import Enum from queue import PriorityQueue import numpy as np import operator as op import time from enum import Enum from queue import PriorityQueue import matplotlib.pyplot as plt class Action(Enum): """ Actions when doing 2.5D A* search. Actions are only stored as how the will alter the loca...
9837713
import simplefix with open('definition.txt') as f: t = f.read() p = simplefix.FixParser() p.append_buffer(t) # Mark end of FIX message (see simplefix issue#13) p.append_buffer(b'\x0110=000\x01') m = p.get_message() print(m)
9837737
from . import DaemonCommand class ScannerCommand(DaemonCommand): args_sections = ['scanner', 'shotgun', 'core'] def add_arguments(self, parser): parser.add_argument('-f', '--full', action='store_true', help='Force a full scan. Convenience for `--scan-since 0` and `--scan-interval 0`', ...
9837740
import torch.nn as nn import torch.utils.data import torch.nn.functional as F from models.dgcnn import get_graph_feature class get_model(nn.Module): def __init__(self, output_channels=40, normal_channel=True): super(get_model, self).__init__() self.normal_channel = normal_channel self.k = ...
9837755
import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Run2_2016_cff import Run2_2016 from Configuration.Eras.Modifier_tracker_apv_vfp30_2016_cff import tracker_apv_vfp30_2016 Run2_2016_HIPM = cms.ModifierChain(Run2_2016, tracker_apv_vfp30_2016)
9837757
import pytest import ray import pandas as pd import numpy as np from sklearn.compose import ColumnTransformer from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.tree import DecisionTreeClassifier from skl...
9837773
import re import os import astunparse_noparen as ast_unparse from .transformers import * # Detects 17-19 digit integers within quotes (snowflake detection) snowflake_regex = re.compile(r"['\"](\d{17,19})['\"]") def get_result(code, **kwargs): """Performs conversion of a given string of code. ...
9837904
from sys import argv from random import randrange, shuffle from flask import Flask, render_template, url_for, request from flask_httpauth import HTTPBasicAuth from mafia_params import * app = Flask(__name__) auth = HTTPBasicAuth() auth_GOD = HTTPBasicAuth() preshared_key = "" id = 0 nPlayers = 0 roles = [] ip2role_ind...
9837962
import FWCore.ParameterSet.Config as cms from SimGeneral.MixingModule.trackingTruthProducer_cfi import trackingParticles trackingParticlesSelection = cms.PSet( lipTP = cms.double(1000), chargedOnlyTP = cms.bool(True), stableOnlyTP = cms.bool(False), pdgIdTP = cms.vint32(), signalOnlyTP = cms.bool(F...
9837993
def actor(): while True: try: msg = yield # 获取消息 print(msg, end="") except RuntimeError: print('Actor退出') p = actor() next(p) # 准备接收 p.send("你好~") p.send("小明") p.close()
9838024
import os import mmap from typing import List import torch import numpy as np import torchtext import torch from torch import nn from torchtext.vocab import Vocab from typing import Tuple import pickle import nltk import argparse from nltk.translate.bleu_score import SmoothingFunction chencherry = SmoothingFunction() ...
9838106
import torch import cv2 import numpy as np import os def load_dir(path, start, end): lmss = [] imgs_paths = [] for i in range(start, end): if os.path.isfile(os.path.join(path, str(i) + '.lms')): lms = np.loadtxt(os.path.join( path, str(i) + '.lms'), dtype=np.float32) ...
9838120
from yozuch.view import view DEBUG = True RST_OPTIONS = { 'add_heading_permalink': True, } THEME_NAME = 'test' THEME_CONFIG = { 'foo': 'bar', } VIEWS = ( view('/', 'blog-index'), view('/paginated_index.html', 'blog-index', posts_per_page=1, pagination_url='/page/{number}/', template='blog_i...
9838137
import numpy as np from allrank.click_models.base import RandomClickModel from tests.click_models import click def test_random_click_model_single(): click_model = RandomClickModel(1) np.random.seed(42) assert click(click_model, [], [1]) == [1] assert click(click_model, [], [1, 2]) == [0, 1] asser...
9838150
from summarize.modules.generate_probability_functions.generate_probability_function import GenerateProbabilityFunction from summarize.modules.generate_probability_functions.onmt import ONMTGenerateProbabilityFunction from summarize.modules.generate_probability_functions.see2017 import See2017GenerateProbabilityFunction...
9838156
import operator from rsqueakvm import constants from rsqueakvm.model.numeric import W_LargeInteger from rsqueakvm.model.variable import W_BytesObject from rsqueakvm.primitives import prim_holder from rsqueakvm.test.test_primitives import MockFrame from rpython.rlib.rarithmetic import intmask, r_uint from rpython.rlib...
9838183
import io import sys import shlex import random import difflib import datetime as dt import subprocess as sp import pkg_resources import rich import rich.box import rich.table from bumpver import v2version def update(content, marker, value): begin_marker = f"<!-- BEGIN {marker} -->" end_marker = f"<!-- EN...
9838185
import numpy as np import scipy __all__ = ['arburg','arburg_cov'] from ... import operators #----------------------------------------- def ar_burg(x, order): ''' The autoregressive model approximation, based on the Burg itterative approximation that minimize forece and back variance ...
9838240
import csv import numpy as np import sklearn as sk from sklearn import linear_model from sklearn import preprocessing from sklearn.impute import SimpleImputer def calculate_accuracy(dataset): X = dataset[:, 1:-1] y = dataset[:, -1] X_train, X_test, y_train, y_test = sk.model_selection.train_test_split(X,...
9838266
from exporters.logger.base_logger import TransformLogger from exporters.pipeline.base_pipeline_item import BasePipelineItem class BaseTransform(BasePipelineItem): """ This module receives a batch and writes it where needed. It can implement the following methods: """ def __init__(self, options, metad...
9838271
import sys import os from basic.common import ROOT_PATH,checkToSkip,CmdOptions,printError,printStatus,makedirsforfile from basic.annotationtable import readConcepts,writeConcepts,writeAnnotations,annotationsExist,conceptsExist from positiveengine import PositiveEngine,SelectivePositiveEngine from negativeengine impo...
9838279
import argparse from mead.utils import convert_path from speed_test.run import run, add from speed_test.report import report, query, explore def print_help(p): def ph(*args, **kwargs): p.print_help() return ph def main(): parser = argparse.ArgumentParser(prog='Baseline Speed Test.', description=...
9838299
from typing import Union, Iterable from uninas.optimization.benchmarks.mini.benchmark import MiniNASBenchmark from uninas.optimization.benchmarks.mini.result import MiniResult from uninas.optimization.hpo.uninas.values import ValueSpace from uninas.utils.args import Namespace class MiniNASSurrogateBenchmark(MiniNASBe...
9838304
from a10sdk.common.A10BaseClass import A10BaseClass class RouteMap(A10BaseClass): """Class Description:: Configure route-map. Class route-map supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param uuid: {"description": "...
9838325
import re import setuptools from distutils.core import setup _ = setuptools # don't warn about this unused import; it might have side effects VERSION = '0.3.13' if __name__ == '__main__': with open("README.md", 'r') as readme: description = readme.read() # Patch the relative links to absolute ...
9838339
import os import unittest from argparse import ArgumentParser from functools import reduce from os import listdir from os.path import isfile, join, dirname, abspath, expanduser import requests_mock from clanvas.clanvas import Clanvas from tests.register import register_uris login_requirements = {'user': {'self', 'pr...
9838349
from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from models.model_utils import (ConvBlock2D, ConvBlock3D, ResBlock2D, rotate_tensor3d, rotate_tensor2d) class GraspingModelSceneOnly(nn.Module): def __init__...
9838368
from __future__ import annotations from typing import Dict, TYPE_CHECKING, List, Union, AbstractSet, Set from tarjan import tarjan from configuration import config from src.genotype.neat.mutation_record import MutationRecords if TYPE_CHECKING: from src.genotype.neat.genome import Genome from src.genotype.ne...
9838373
import numpy as np import scipy.sparse import tensorflow as tf class ProductFn: """Abstract class. Instances can be passed to function `fsvd`. An intance of (a concrete implementation of) this class would hold an implicit matrix `M`, such that, this class is able to multiply it with another matrix `m` (by im...
9838426
import os import random from multiprocessing import cpu_count import numpy as np import paddle from PIL import Image # 测试图片的预处理 def train_mapper(sample): img, crop_size = sample img = Image.open(img) # 随机水平翻转 r1 = random.random() if r1 > 0.5: img = img.transpose(Image.FLIP_LEFT_RIGHT) ...
9838434
import asyncio import json import sys import urllib.error import urllib.parse import urllib.request from asyncio import AbstractEventLoop from typing import Any, Optional class FailedRequestError(Exception): def __init__(self, status, data) -> None: super().__init__( f"The response status code...
9838439
import os import sys import json import time try: from aceinna.devices.message_center import DeviceMessageCenter from aceinna.devices.parser_manager import ParserManager from aceinna.framework.utils import helper from mocker.communicator import MockCommunicator from mocker.devices import helper as ...
9838442
import django if django.VERSION < (3, 2): default_app_config = 'data_migration.apps.DataMigrationsConfig'
9838493
import requests from .RequestHandler import RequestHandler ApiError = requests.HTTPError class ThrowOnErrorHandler(RequestHandler): def after_request( self, region: str, endpoint_name: str, method_name: str, url: str, response: requests.Response, ) -> None: ...
9838500
import os MAIN_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..") ASSETS_DIR = os.path.join(MAIN_DIR, "assets") ASSETS_IMAGES_DIR = os.path.join(ASSETS_DIR, "images") ASSETS_VIDEOS_DIR = os.path.join(ASSETS_DIR, "videos") MODELS_DIR = os.path.join(MAIN_DIR, "models") MODELS_FACE_DETECTOR_DIR = os....
9838593
import pickle from pathlib import Path from typing import Any from mkreports import Report def pickle_roundtrip(obj: Any, file: Path): """ Pickle an item into a temporary file and then reload and compare. """ with file.open("wb") as f: pickle.dump(obj, f) with file.open("rb") as f: ...
9838618
import os import requests class OutPutUse(object): def __init__(self): self.real_download = True self.save_root_dir = 'output' def download_and_save(self, url, mj_name): print('正在下载图片:', mj_name, url) if self.real_download is False: return save_dir = self.s...
9838640
from joblib import Parallel, delayed, cpu_count def f(x): return x * 2 if __name__ == '__main__': inputs = list(range(10)) print('Input :', inputs) builtin_outputs = list(map(f, inputs)) print('Built-in:', builtin_outputs) #number of threads to use pool_size = cpu_count() * 2 prin...
9838643
description = "Read result from input job, add it to itself and return it." # "jobs" is a list (or tuple) of jobs assigned by the build script. # Entries that are left unassigned are set to None. jobs = ('first',) def synthesis(): # All items in the jobs variable will be populated by Job objects # when executed. ...
9838648
from mock import patch from testtools import TestCase from charmhelpers.contrib.templating.pyformat import render from charmhelpers.core import hookenv class PyFormatTest(TestCase): @patch.object(hookenv, 'execution_environment') def test_renders_using_environment(self, execution_environment): execut...
9838654
import arrayfire as af from arrayfire.library import Dtype import collections import math import numpy as np from types import ModuleType import typing as tp from ._arith import \ exp, \ log, \ minimum, \ sqrt, \ minimum from ._array import asscalar, ndarray from ._conversion import \ convert_n...
9838664
import torch import torch.nn as nn import sys from models.rnn import RNN from models.lstm import LSTM from models.gru import GRU class SentimentClassifier(nn.Module): def __init__(self, vocab_sz, n_hidden, rnn_type='RNN'): super(SentimentClassifier, self).__init__() self.embedding = nn.Embedding(...
9838667
from __future__ import (absolute_import, division, print_function) __metaclass__ = type # Server-generated name for the Notes field NOTES_FIELD_LABEL = "notesPlain" # 1Password Connect Ansible Collection Version # Auto-updated during release process COLLECTION_VERSION = "2.2.0" GENERATE_NEVER = "never" GENERATE_ALW...
9838702
from office365.sharepoint.client_context import ClientContext from tests import test_site_url, settings ctx = ClientContext(test_site_url) ctx.with_user_credentials(settings.get('user_credentials', 'username'), settings.get('user_credentials', 'password')) web = ctx.web.get().execute_query()...
9838718
import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend as K from ..utils import ( check_numpy_array, check_tensor, is_vfunction, is_qfunction, is_policy) from ..base.mixins import ActionSpaceMixin from ..base.errors import ActionSpaceError from ..policies.base import BasePolicy ...
9838736
import validators class InputValuesCheck(object): @staticmethod def checkPollingTime(value): value = int(value) if isinstance(value, int) and value > 0: return else: print("Polling time should be an integer > 0") raise ValueError @staticmethod ...
9838767
import os import glob def make_doctree(out_dir): doctree = "" root_dir = os.path.join(os.pardir) source_files = sorted(glob.glob(os.path.join(root_dir, "wormpose", "**", "[!_]*.py"), recursive=True)) for source_file in source_files: source_file = os.path.relpath(source_file, root_dir) ...
9838798
from typing import Literal import streamlit as st import sqlite3 from .provider.sqlite.settings import SQLITE_SETTINGS def _sqlite_hash_func(allow_db_create=False, if_table_exists: Literal['ignore', 'recreate'] = 'ignore'): path = SQLITE_SETTINGS.DB_PATH db = SQLITE_SETTINGS.DB hash_key = f'{path}|{db}|{al...
9838811
from django.core.management.base import BaseCommand import feedparser from dateutil import parser from podcasts.models import Episode class Command(BaseCommand): def handle(self, *args, **options): feed = feedparser.parse("https://realpython.com/podcasts/rpp/feed") podcast_title = feed.channel.t...
9838815
from . import _PYRA_SCRAMBLER, trim #------------------------------------------------------------------------------ @trim def get_WCA_scramble(): """ Gets a WCA scramble of a Pyraminx. """ return _PYRA_SCRAMBLER.call("pyra_scrambler.getPyraWCAScramble") @trim def get_optimal_scramble(): """ Gets an optim...
9838844
PARAMS = [ {"label":"distribute", "value": "true"}, {"label":"train_with_eval", "value": "true"}, {"label":"eval_data_dir", "value": "/cache/data/eval"}, {"label":"data_dir", "value": "/cache/data/train"}, {"label":"enable_save_ckpt", "value": "false"}, {"label":"enable_lossscale", "value": "tru...
9838850
from typing import * @overload def _is_string_like(obj: _io.BytesIO): """ usage.statsmodels: 1 """ ... @overload def _is_string_like(obj: str): """ usage.statsmodels: 1 """ ... @overload def _is_string_like(obj: pathlib.PosixPath): """ usage.statsmodels: 1 """ ... ...
9838852
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.cgd import cgd def test_cgd(): """Test module cgd.py by downloading cgd.csv and testing shape of extracted data has 203 rows and 16 column...
9838917
import numpy as np import argparse, sys, os, time import progressbar from keras.optimizers import SGD from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping, CSVLogger from datasets import UT, NTU_V2, SBU, NTU from datasets.data_generator import DataGeneratorSeq ...
9838918
import re import json import requests class LetvSpider(object): COMMENT_URL = 'http://api.my.le.com/vcm/api/list?jsonp=jQuery171029717156927084076_1504105496754&' \ 'cid=2&type=video&rows=20&page=1&sort=&source=1&listType=1&xid={xid}&pid={pid}&' \ 'ctype=cmt%2Cimg%2Cvote' ...
9838928
from __future__ import print_function import keras.backend as K import keras.losses as losses import keras.optimizers as optimizers import numpy as np from collections import deque from keras.layers.advanced_activations import LeakyReLU from keras.layers import Input, RepeatVector, Reshape from keras.layers import Up...
9838934
import os import shutil import unittest from rdflib import Graph from fhirtordf.fhirtordf import DEFAULT_FHIR_MV from fhirtordf.rdfsupport.rdfcompare import rdf_compare_split from tests import TEST_DIR from tests.utils import USE_BUILD_SERVER from tests.utils.base_test_case import test_fhir_server from tests.utils.ou...
9838950
import numpy as np import numba from scipy.fftpack import fft, ifft, fftshift from scipy.signal import hanning import random def get_seeds_signals(fs: int, fft_size: int=None, noise_length: int=None): if fft_size == None: fft_size = int(1024 * (2 ** np.ceil(np.log2(fs / 48000)))) if noise_length == No...
9838991
import re from .resource_service import ResourceService from .resource import Resource import logging import botocore class S3Bucket(Resource): def __init__(self, session, region, bucket) -> None: self.bucket = bucket self.region = region self.logger = logging.getLogger(__name__) s...
9839011
import numpy as np import theano import theano.tensor as T from utils.savers import save_pickle from utils.loaders import load_pickle def get_optimizer(argv): if argv.opt_type == 'adam': return Adam(argv=argv, lr=argv.lr, grad_clip=argv.grad_clip) return SGD(argv=argv, lr=argv.lr, grad_clip=argv.grad...
9839026
import json from django.db.models.query import QuerySet from django.http import HttpResponse from django.core import serializers class HttpResponseNotImplemented(HttpResponse): status_code = 501 class JSONResponse(HttpResponse): """ A subclass of django.http.HttpResponse which serializes its content ...
9839048
import pandas as pd from utils import * df = pd.read_csv("../feature/state_labels_with_muslim.csv") cols = df.columns.drop(["StateID", "StateName"]) for c in cols: df[c] = df[c].str.replace(",", "").astype("float32") train.merge(df, how="left", left_on="State", right_on="StateID")[cols].to_feather("../feature/mus...
9839053
from os import path from sys import argv import joblib from models import model2 if __name__ == '__main__': #_, weight_file = argv weight_file = 'weights-improvement__016-0.022715.hdf5' assert(path.exists(weight_file)) model = model2(weights_path=weight_file) attrs = ['BalacingElements', 'ColorHarm...
9839071
import random from aalpy.base import Automaton, AutomatonState class McState(AutomatonState): def __init__(self, state_id, output): super().__init__(state_id) self.output = output # transitions is a list of tuples (Node(output), probability) self.transitions = list() class Marko...
9839074
import os import pprint import requests import typing import urllib GITHUB_GRAPHQL_API = 'https://api.github.com/graphql' GITHUB_V3_REST_API = 'https://api.github.com' class GitHubClient: def __init__(self, repo_owner, repo_name): if not 'GH_TOKEN' in os.environ: raise Exception("GH_TOKEN en...
9839097
from .photo import Photo def rotate(photo, params, show=False): _photo = Photo(photo).rotate(**_parse(params)) _photo.save('rotate-' + photo) if show: _photo.show() def _parse(params): _len = len(params) return dict(angle = (int(params[0]) if _len > 0 else None), fill = (str(params...
9839101
from typing import Dict from botocore.paginate import Paginator class ListPlacements(Paginator): def paginate(self, projectName: str, PaginationConfig: Dict = None) -> Dict: """ Creates an iterator that will paginate through responses from :py:meth:`IoT1ClickProjects.Client.list_placements`. ...
9839123
from unittest.mock import MagicMock import pytest from flask import testing from pytest_mock import MockerFixture from slackclient import SlackClient from werkzeug.datastructures import Headers from werkzeug.test import Client from omnibot.app import app from omnibot.routes import api app.register_blueprint(api.blue...
9839131
import numpy as np import cffi import os from awrams.utils.nodegraph import nodes from awrams.utils import geo, extents from awrams.utils.helpers import as_int from awrams.utils.mapping_types import gen_coordset ffi = cffi.FFI() ffi.cdef("void undo_thing(double *in, double *out, int xn, int yn, int scalefac);...
9839170
import py from pypy.lang.gameboy.timer import * from pypy.lang.gameboy.interrupt import * from pypy.lang.gameboy import constants def get_timer(): return Timer(Interrupt()) # ------------------------------------------------------------------------------ def test_reset(timer=None): if timer is None: ...
9839175
from app import app from flask import render_template, url_for, request, redirect, flash, abort import os from app.utils import check_for_err, create_tmp, create_video from werkzeug.datastructures import FileStorage @app.route("/", methods=["GET"]) def index(): """Home page """ return render_template("ind...
9839189
import math import cmath import mpmath import matplotlib.pyplot as plt from bigfloat import * import numpy as np class K_B: def __init__(self): pass def f(self, t): return t ** (- 0.5) def df(self, t): return - 0.5 * t ** (- 1.5) class K_component: def __init__(self, ti, ...
9839250
from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from studygroups.models import Meeting from studygroups.models.learningcircle import generate_meeting_reminder class Command(BaseCommand): help = 'Transitional command to generate reminders for all meetings in the ...
9839254
import base64 import json from typing import Any, Dict import requests from fastapi import HTTPException, Request from google.cloud import pubsub_v1 # type: ignore from src.constants import ( DOCKER, LOCAL_SUBSCRIBER, PROD, PROJECT_ID, PUBSUB_PUB, PUBSUB_TOKEN, ) """ EMULATOR FUNTIONS """ ...
9839296
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "ROT" addresses_name = "2021-03-15T11:29:31.675704/Democracy_Club__06May2021.tsv" stations_name = "2021-03-15T11:29:31.675704/Democracy_Club__06May2021.tsv" ...
9839308
class Solution: """ @param m: an integer @param n: an integer @param ops: List[List[int]] @return: return an integer """ def maxCount(self, m, n, ops): # write your code here for op in ops: m = min(m, op[0]) n = min(n, op[1]) return m * n
9839317
from django.core.management.base import BaseCommand # from user.models import User # from mailing_list.models import EmailRecipient class Command(BaseCommand): def handle(self, *args, **options): # TODO: Alter this because we have removed the is_subscribed field # EmailRecipient.objects.all().upd...
9839334
import sys from twisted.python import log from twisted.internet import reactor from autobahn.twisted.websocket import connectWS from autobahn.wamp1.protocol import WampClientFactory, \ WampClientProtocol import argparse import requests import json import os import datetime import ...
9839354
import sys fi=open('GSE70630_OG_processed_data_v2.txt') fo=open('GSE70630_OG_processed_data_v2_MGH54.txt','w') #fo=open('GSE70630_OG_processed_data_v2_MGH36.txt','w') #fo=open('GSE70630_OG_processed_data_v2_MGH53.txt','w') #fo=open('GSE70630_OG_processed_data_v2_MGH60.txt','w') #fo=open('GSE70630_OG_processed_data_v2_M...
9839398
import os import torch from torch import nn import glog as log class Codec(nn.Module): def __init__(self, img_size, in_channels, compress_mode=1, resize=None, use_tanh=True): super(Codec, self).__init__() self.compress_mode = compress_mode self.use_tanh = use_tanh work...
9839438
from autorop import PwnState from pwn import ELF, ROP def load_libc(state: PwnState) -> ELF: """Load the libc specified in the given state into a pwntools' ``ELF``. Arguments: state: The state, with the following set - ``libc``: Path to ``target``'s libc. - ``libc_base``: Bas...
9839481
import functools import time import typing as t from .types import DecoratedFunc # timer function def timed(func: DecoratedFunc) -> DecoratedFunc: """Print the runtime of the decorated function""" @functools.wraps(func) def timed_wrapper(*args, **kwargs): start_time = time.perf_counter() ...
9839495
import sys import random from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication from rx import Observable from rx.subjects import Subject from rx.concurrency import QtScheduler from client.client_window import ClientWindow REFRESH_STOCK_INTERVAL = 100 def random_stock(x): symbol_names = [ ['...
9839508
import pylab as pl import numpy as np import mpl_toolkits ef=12.6128 # Fermi energy x = np.loadtxt('fe_slice_x.dat') dimx=x.size y = np.loadtxt('fe_slice_y.dat') dimy=y.size bands=np.loadtxt('fe_slice_bands.dat') numbands=bands.size/dimx/dimy bands2=bands.reshape((dimx,dimy,numbands)) #title('Fermi contours of bcc ...
9839510
from typing import List from boa3.builtin import public @public def main(a: List[bool], value: bool) -> int: return a.index(value)
9839514
from socket import * import time from optparse import OptionParser import logging class monitor_TCP(): def __init__(self, opts): self.rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP) self.rawSocket.bind((opts.listen, 0)) def listen_SYN(self): # Function holds till it receives a packet data = se...
9839590
import logging import os import pytest import tempfile import actions.tree import actions.drop import actions.tamper import actions.duplicate import actions.utils import actions.strategy import evaluator import evolve import common import netifaces from scapy.all import IP, TCP from pprint import pprint @pytest.mar...
9839653
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import argparse seeds = { "diehard": [ [0, 0, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 1, 1], ], "boat": [[1, 1, 0], [1, 0, 1], [0, 1, 0]], "r_pentomino": [[0, 1, ...
9839661
from loguru import logger from fastapi import HTTPException import os from jinja2 import Environment, FileSystemLoader templates_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') jinja_env = Environment(loader=FileSystemLoader(templates_path)) class WGMHTTPException(HTTPException): de...
9839687
import json from google.appengine.ext import ndb from CONSTANTS import MOVE_TYPES class InvalidMove(Exception): pass class BaseModel(ndb.Model): created = ndb.DateTimeProperty(auto_now_add=True) modified = ndb.DateTimeProperty(auto_now=True) class Pool(BaseModel): setup = ndb.JsonProperty(requir...
9839688
from oem_framework.format import Format from oem_framework.plugin import Plugin import logging try: from oem_format_msgpack.packer import Packer import msgpack except ImportError: Packer = None msgpack = None log = logging.getLogger(__name__) class MessagePackFormat(Format, Plugin): __key__ = '...
9839692
class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num...
9839701
import logging from collections import namedtuple from functools import lru_cache from operator import attrgetter import numpy import soundfile from audio_to_midi import midi_writer, notes class Note: __slots__ = ["pitch", "velocity", "count"] def __init__(self, pitch, velocity, count=0): self.pit...
9839731
import os from torchvision import transforms import torch import pickle from .build_vocab import Vocabulary from .models import ( EncoderCNN, YoloEncoder, DecoderLayoutRNN, DecoderRNN ) from .im_args import get_arg_parse import numpy as np from PIL import Image def load_image(image_path): image = ...
9839784
from pytest import fixture from cfripper.model.enums import RuleGranularity, RuleMode, RuleRisk from cfripper.model.result import Failure from cfripper.rules.privilege_escalation import PrivilegeEscalationRule from tests.utils import compare_lists_of_failures, get_cfmodel_from @fixture() def valid_role_inline_policy...