id
stringlengths
3
8
content
stringlengths
100
981k
101659
import argparse parser = argparse.ArgumentParser() parser.add_argument( "--dataset_path", default=None, type=str, required=True, help="Path to the [dev, test] dataset", ) parser.add_argument( "--index_path", default=None, type=str, required=True, help="Path to the indexes of c...
101665
import numpy as np import os import matplotlib.pyplot as plt import glob import re import torch import torch.nn as nn import torch import cv2 import torchvision from torch.utils.data import Dataset, DataLoader, ConcatDataset from torchvision import transforms import tqdm from PIL import Image import albumentations a...
101750
from pathlib import Path from tempfile import TemporaryDirectory from unittest import TestCase from zkviz import zkviz class TestListZettels(TestCase): def test_list_zettels_with_md_extension(self): # Create a temporary folder and write files in it with TemporaryDirectory() as tmpdirname: ...
101775
import dataclasses from types import MethodType from typing import ( # type: ignore Any, Callable, Dict, List, Optional, Tuple, Type, _TypedDictMeta, ) from dictdaora import DictDaora from .decorator import jsondaora from .exceptions import DeserializationError class StringField(Dic...
101827
import numpy as np a = np.arange(10) * 10 print(a) # [ 0 10 20 30 40 50 60 70 80 90] print(a[5]) # 50 print(a[8]) # 80 print(a[[5, 8]]) # [50 80] print(a[[5, 4, 8, 0]]) # [50 40 80 0] print(a[[5, 5, 5, 5]]) # [50 50 50 50] idx = np.array([[5, 4], [8, 0]]) print(idx) # [[5 4] # [8 0]] print(a[idx]) # [[50 40] ...
101831
import csv import json from collections import OrderedDict csvfile = open('./pokedex.csv', 'r') jsonfile = open('./pokedex.json', 'w') jsonNames = ("orderID", "nDex", "name", "type1", "type2", "ability1", "ability2", "hiddenability", "hp", "atk", "def", "spatk", "spdef", "spe", "note", "tier", "image") reader = csv.D...
101834
from __future__ import print_function class Rule(object): def __init__(self): pass def __repr__(self): return self.name() @classmethod def name(cls): return cls.__name__.split('.')[-1] @classmethod def explain(cls): return cls.__doc__ def __cmp__(self, other)...
101846
import operator from django.conf import settings from django.contrib.auth.models import User from rest_framework import serializers from .models import Board, Column, Project, Tag, Todo, Type REPORTER_ATTR = getattr(settings, 'BUDGET_REPORTER_ATTR', 'is_staff') EDITOR_ATTR = getattr(settings, 'BUDGET_EDITOR_ATTR', '...
101861
from pathlib import Path import pytest import sys import ssh2net from ssh2net import SSH2Net from ssh2net.exceptions import ValidationError, SetupTimeout NET2_DIR = ssh2net.__file__ UNIT_TEST_DIR = f"{Path(NET2_DIR).parents[1]}/tests/unit/" def test_init__shell(): test_host = {"setup_host": "my_device ", "aut...
101870
from __future__ import print_function, division from argparse import ArgumentParser import yaml import logging import os import sys import time from subprocess import call from marmot.experiment.import_utils import build_objects, build_object, call_for_each_element, import_class from marmot.experiment.preprocessing_u...
101902
from urllib.parse import urlparse from logging import getLogger from django.conf import settings from django.db import transaction from requests.auth import HTTPBasicAuth from zipa import lattice # pylint: disable=no-name-in-module from zinc import models from zinc.utils.validation import is_ipv6 logger = getLogge...
101908
from using_extend import * f = FooBar() if f.blah(3) != 3: raise RuntimeError, "blah(int)" if f.blah(3.5) != 3.5: raise RuntimeError, "blah(double)" if f.blah("hello") != "hello": raise RuntimeError, "blah(char *)" if f.blah(3, 4) != 7: raise RuntimeError, "blah(int,int)" if f.blah(3.5, 7.5) != (3....
101930
from savu.plugins.plugin_tools import PluginTools class DezingerDeprecatedTools(PluginTools): """A plugin for cleaning x-ray strikes based on statistical evaluation of the near neighbourhood """ def define_parameters(self): """ outlier_mu: visibility: basic dtype...
101939
import asyncio import logging.config from pathlib import Path from symphony.bdk.core.config.loader import BdkConfigLoader from symphony.bdk.core.symphony_bdk import SymphonyBdk async def run(): config = BdkConfigLoader.load_from_symphony_dir("config.yaml") async with SymphonyBdk(config) as bdk: ext_a...
101941
import matplotlib import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import pandas as pd import os import matplotlib.pyplot as plt import sys import itertools mpl.rcParams['legend.fontsize'] = 12 DPI = 5000 input_dir = "/home/pablo/ws/log/trajectories" print("Reading fr...
101972
from test_helper import run_common_tests, failed, passed, get_answer_placeholders, do_not_run_on_check if __name__ == '__main__': do_not_run_on_check() run_common_tests()
101992
from agents import * from models import * import numpy as np import matplotlib matplotlib.use('tkagg') import matplotlib.pyplot as plt import sys import pickle # end class world def speed_profile(file_names): """ This function is to plot speed profiles for several evaluation results. Args: file_nam...
101996
import FWCore.ParameterSet.Config as cms siStripGainESProducer = cms.ESProducer("SiStripGainESProducer", appendToDataLabel = cms.string(''), printDebug = cms.untracked.bool(False), AutomaticNormalization = cms.bool(False), APVGain = cms.VPSet( cms.PSet( Record = cms.string('SiStripA...
101999
from typing import Dict import numpy as np import pytorch_lightning as pl import torch from omegaconf import DictConfig from src.utils.technical_utils import load_obj class LitNER(pl.LightningModule): def __init__(self, cfg: DictConfig, tag_to_idx: Dict): super(LitNER, self).__init__() self.cfg ...
102015
from .state import EOF from .tokens import TokenEof from .tokens_base import TOKEN_COMMAND_UNABBREVIATE from .tokens_base import TokenOfCommand from Vintageous import ex @ex.command('unabbreviate', 'una') class TokenUnabbreviate(TokenOfCommand): def __init__(self, params, *args, **kwargs): super().__init_...
102051
from typedpy import * class Example1(Structure): D = Map(items=[String(), Integer()], default=lambda: {'abc': 0}) _required = []
102055
from django.shortcuts import render, redirect # Create your views here. from django.http import Http404 from homework_app.models import Homework, Comment from django.views.generic.list import ListView from homework_app.forms import CommentForm def homework(request, homework_id): p = Homework.objects.get(pk=homew...
102057
import httpx from statuscheck.services.bases._base import BaseServiceAPI from statuscheck.services.models.generic import ( COMPONENT_TYPE_DEGRADED, COMPONENT_TYPE_GOOD, COMPONENT_TYPE_MAINTENANCE, COMPONENT_TYPE_MAJOR_OUTAGE, COMPONENT_TYPE_PARTIAL_OUTAGE, COMPONENT_TYPE_SECURITY, COMPONENT...
102059
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Layer class MultiMaskedConv2D(Layer): """ Masked multitask 2-dimensional convolutional layer. This layer implements multiple stacks of the convolutional architecture and implements masking consistent with the MANN API to sup...
102094
import logging import time, datetime from thespian.actors import * from thespian.test import * import signal import os class KillMeActor(Actor): def receiveMessage(self, msg, sender): logging.info('EchoActor got %s (%s) from %s', msg, type(msg), sender) self.send(sender, os.getpid()) class Paren...
102208
import numpy as np from .layer_base import LayerBase class ReluLayer(LayerBase): def __init__(self): super().__init__() self.cache = {} def id(self): return "Relu" def forward(self, x): y = np.maximum(x, 0) self.cache["is_negative"] = (x < 0) return y ...
102260
from atcodertools.fmtprediction.models.calculator import CalcNode class Index: """ The model to store index information of a variable, which has a likely the minimal / maximal value and for each dimension. Up to 2 indices are now supported. In most cases, the minimal value is 1 and the m...
102290
import types import datetime from nose.tools import eq_ as orig_eq_ from unittest import skip from allmychanges.utils import first, html_document_fromstring from allmychanges.parsing.pipeline import ( get_markup, extract_metadata, group_by_path, strip_outer_tag, prerender_items, highlight_keywo...
102299
import random from django.core import serializers from django.shortcuts import HttpResponse from .models import DemoData TEMP = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-" # Create your views here. def demo_views(request): result = DemoData.objects.filter( name="".joi...
102302
from werkzeug.utils import find_modules, import_string def import_all(import_name): for module in find_modules(import_name, include_packages=True, recursive=True): import_string(module)
102400
import pytest def test_ec2user_user_group(host): """Check if the ec2-user user created in a ec2-user group and its UID and GUID values is 1000""" assert host.user("ec2-user").exists assert host.group("ec2-user").exists assert host.user("ec2-user").uid == 1000 assert host.user("ec2-user").gid == 10...
102413
import pandas as pd import numpy as np np.random.seed(163) from sklearn.svm import SVC from sklearn.cross_validation import StratifiedKFold # Load the precomputed X mutag feature matrix. print "Loading Feature Matrix..." df=pd.read_csv('X_mutag.csv',header=None) X=np.array(df) # Load the precomputed Y mutag feature...
102435
import datetime, calendar from dateutil.relativedelta import relativedelta from freezegun import freeze_time from doajtest.helpers import DoajTestCase from portality.scripts.prune_marvel import generate_delete_pattern class TestPruneMarvel(DoajTestCase): @classmethod def setUpClass(cls): cls.runs = ...
102460
import time import copy import gobject from phony.base.log import ClassLogger from RPi import GPIO from types import MethodType class Inputs(ClassLogger): _layout = {} _inputs_by_channel = {} _rising_callback_by_channel_name = {} _falling_callback_by_channel_name = {} _pulse_callback_by_channel_name = {} ...
102466
from .transformer import * from .common import * #tf.compat.v1.disable_eager_execution() # #batch_size = 40 #seq_length = 200 #hidden_size = 768 #num_attention_heads =12 #size_per_head = int(hidden_size / num_attention_heads) # #layer_input = tf.compat.v1.placeholder(tf.float32, shape=(batch_size*seq_length, hidden_si...
102475
from copy import deepcopy from pymaclab.dsge.translators import pml_to_dynarepp from pymaclab.dsge.translators import dynarepp_to_pml from pymaclab.dsge.translators import pml_to_pml from pymaclab.dsge.parsers._dsgeparser import ff_chron_str, bb_chron_str class Translators(object): def __init__(self,other=None): ...
102492
import unittest from unittest import mock from apiserver.search import parse_query from apiserver.search import join from apiserver.search.union import name_similarity from .utils import DataTestCase class TestSearch(unittest.TestCase): def test_simple(self): """Test the query generation for a simple se...
102547
import py class TestJitTraceInteraction(object): def test_trace_while_blackholing(self): import sys l = [] printed = [] def trace(frame, event, arg): l.append((frame.f_code.co_name, event)) return trace def g(i, x): if i > x - 10: ...
102551
r=open('all.protein.faa','r') w=open('context.processed.all.protein.faa','w') start = True mem = "" for line in r: if '>' in line and not start: list_char = list(mem.replace('\n','')) list_context = [] list_context_length_before = 1 list_context_length_after = 1 for i in range(len(list_char)): tmp="" ...
102575
import os from pathlib import Path from appdirs import user_data_dir class EnvManager: """Stashes environment variables in a file and retrieves them in (a different process) with get_environ with failover to os.environ """ app_env_dir = Path(user_data_dir("NEBULO")) app_env = app_env_dir / ...
102585
import re import click from matrix_connection import matrix_client from tabulate import tabulate @click.command() @click.argument('pattern', required=False, type=str) def list_rooms(pattern): """List room ids and keys.""" rooms = matrix_client().get_rooms() data = [(rid, room.display_name) f...
102607
import os import unittest from scrapy.http import TextResponse, Request from pdl_scraper.spiders.pdfurl_spider import PdfUrlSpider class TestPdfUrlSpider(unittest.TestCase): def setUp(self): self.spider = PdfUrlSpider() def test_find_pdfurl(self): codigos = ( '00001', ...
102629
from enum import Enum from deprecation import deprecated @deprecated(details="""Enum-value statuses are deprecated since SLIMS 6.4. Unless your SLIMS system still uses them (see Lab Settings), you should use the Status table and cntn_fk_status for status queries.""") class Status(Enum): "...
102645
from mongoengine import * class VersionModel(Document): """ 각 클라이언트의 버전 관리를 위한 collection """ meta = { 'collection': 'versions' } platform = IntField( required=True, primary_key=True ) # 1: Web # 2: Android # 3: IOS version = StringField( r...
102718
import requests import json from bs4 import BeautifulSoup def scrape_creatures(): print 'scraping creatures' url = 'http://ark.gamepedia.com/Entity_IDs' r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') tables = soup.find_all('table') creature_table = tables[2] container =...
102721
import os import datetime import pytest import pandas as pd import geopandas as gpd from shapely.geometry import Point import trackintel as ti @pytest.fixture def testdata_sp_tpls_geolife_long(): """Generate sp and tpls sequences of the original pfs for subsequent testing.""" pfs, _ = ti.io.dataset_reader.r...
102730
import os print "UPDATING..." os.system("cd") os.system('cd /root/ && rm -fr hackers-tool-kit && git clone https://github.com/unkn0wnh4ckr/hackers-tool-kit && echo "[UPDATED]: Restart Your Terminal"')
102731
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class PatreonManagerConfig(AppConfig): name = 'patreonmanager' verbose_name = _("Patreon Manager")
102732
from yaml import load, dump, FullLoader import sys, os class QuietLoaders: def resource_path(self, relative): if hasattr(sys, "_MEIPASS"): return os.path.join(sys._MEIPASS, relative) return os.path.join(relative) def __init__(self): self.settings_path = self.resource_path(os.path.join('data', 'config/sett...
102763
from __future__ import absolute_import, division, print_function import codecs try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict import copy import os import os.path as path import sys import toml import nfldb import nflfan.provider as provider import nflfan.sco...
102809
import numpy as np from model import generate_recommendations user_address = '0x8c373ed467f3eabefd8633b52f4e1b2df00c9fe8' already_rated = ['0x006bea43baa3f7a6f765f14f10a1a1b08334ef45','0x5102791ca02fc3595398400bfe0e33d7b6c82267','0x68d57c9a1c35f63e2c83ee8e49a64e9d70528d25','0xc528c28fec0a90c083328bc45f587ee215760a0f']...
102831
from setuptools import setup, find_packages setup( name="Segy2Segy", version="0.2", packages=find_packages(exclude=["tests*"]), scripts=['core/segy2segy.py'], install_requires=['gdal', 'obspy'], author="<NAME>", author_email="<EMAIL>", description="A command line tool for projecting an...
102866
import torch from torch import nn from torch.nn import functional as F def masked_normalization(logits, mask): scores = F.softmax(logits, dim=-1) # apply the mask - zero out masked timesteps masked_scores = scores * mask.float() # re-normalize the masked scores normed_scores = masked_scores.div(...
102867
from .utils.suite_writer import Suite from contextlib import contextmanager import pytest # pylint: disable=redefined-outer-name def test_expect_failure_not_met(suite, test): test.expect_failure() with _raises_assertion('Test did not fail as expected'): suite.run() def test_expect_error_not_met(su...
102902
from baserow.contrib.database.formula.exceptions import BaserowFormulaException class InvalidNumberOfArguments(BaserowFormulaException): def __init__(self, function_def, num_args): if num_args == 1: error_prefix = "1 argument was" else: error_prefix = f"{num_args} arguments...
102903
from time import time from functools import wraps import matplotlib.pyplot as plt from mandelbrot.python_mandel import compute_mandel as compute_mandel_py from mandelbrot.hybrid_mandel import compute_mandel as compute_mandel_hy from mandelbrot.cython_mandel import compute_mandel as compute_mandel_cy def timer(func, n...
102932
from invitations.adapters import BaseInvitationsAdapter from registration.signals import user_registered class DepartmentInvitationsAdapter(BaseInvitationsAdapter): def get_user_signed_up_signal(self): return user_registered
102985
import numpy from gensim.summarization.bm25 import BM25 class WrappedBM25(BM25): def __init__(self, docs, tokenizer='spacy'): self.docs = docs if tokenizer == 'spacy': try: import spacy except ImportError: raise ImportError('Please install sp...
102997
from torch_rgcn.utils import * from torch.nn.modules.module import Module from torch.nn.parameter import Parameter from torch import nn import math import torch class DistMult(Module): """ DistMult scoring function (from https://arxiv.org/pdf/1412.6575.pdf) """ def __init__(self, indim, ...
103010
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( type='PoseDetDetector', pretrained='pretrained/dla34-ba72cf86.pth', # pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict( type='DLA', return_levels=True, levels=[1, 1, 1, 2, 2, 1], channel...
103066
from bson import ObjectId from odmantic import Model class Player(Model): name: str level: int = 1 document = {"name": "Leeroy", "_id": ObjectId("5f8352a87a733b8b18b0cb27")} user = Player.parse_doc(document) print(repr(user)) #> Player( #> id=ObjectId("5f8352a87a733b8b18b0cb27"), #> name="Leeroy",...
103078
from autogluon.core.utils.feature_selection import * from autogluon.core.utils.utils import unevaluated_fi_df_template import numpy as np from numpy.core.fromnumeric import sort import pandas as pd import pytest def evaluated_fi_df_template(features, importance=None, n=None): rng = np.random.default_rng(0) im...
103083
from unittest import mock from unittest.mock import call from django.test import override_settings from lego.apps.external_sync.external import ldap from lego.apps.users.constants import GROUP_COMMITTEE from lego.apps.users.models import AbakusGroup, User from lego.utils.test_utils import BaseTestCase class LDAPTes...
103094
DOMAIN = "audiconnect" CONF_VIN = "vin" CONF_CARNAME = "carname" CONF_ACTION = "action" MIN_UPDATE_INTERVAL = 5 DEFAULT_UPDATE_INTERVAL = 10 CONF_SPIN = "spin" CONF_REGION = "region" CONF_SERVICE_URL = "service_url" CONF_MUTABLE = "mutable" SIGNAL_STATE_UPDATED = "{}.updated".format(DOMAIN) TRACKER_UPDATE = f"{DOMA...
103105
from soccer_geometry.transformation import Transformation from soccer_geometry.camera import Camera
103110
import os import json import time import torch import itertools import detectron2.utils.comm as comm from fvcore.common.file_io import PathManager from detectron2.config import global_cfg from detectron2.engine.train_loop import HookBase from detectron2.evaluation.testing import flatten_results_dict __all__ = ["EvalHo...
103146
from imghdr import what from os import getenv from json import loads, dumps import flask from rockset import Client, Q from flask_cors import CORS from sys import argv app = flask.Flask(__name__, static_folder='compendium/images') CORS(app) rs = Client(api_key=getenv('RS2_TOKEN') or argv[1], api_server='api.rs2.usw2.r...
103169
from abc import ABC, abstractmethod class Verb(ABC): """ This docstring is used in the help message when doing `htcondor noun verb --help` """ # The options class dict is a nested dict containing kwargs # per option for the add_argument method of ArgumentParser, # see COMMON_OPTIONS in __...
103181
class YamboSpectra(): """ Class to show optical absorption spectra """ def __init__(self,energies,data): self.energies = energies self.data = data
103292
import sys import os import logging import datetime import datetime import json import traceback import copy import random import string import gzip import asyncio from pathlib import Path from collections.abc import Iterable import discord from tqdm import tqdm __version__ = "0.3.3" PBAR_UPDATE_INTERVAL = 100 PBAR_...
103357
from django.apps import AppConfig class OfficialDocumentsCollectionConfig(AppConfig): name = 'official_documents_collection'
103385
import unittest import numpy as np import scipy.sparse from injector import Injector from decai.simulation.data.featuremapping.feature_index_mapper import FeatureIndexMapper from decai.simulation.logging_module import LoggingModule class TestFeatureIndexMapper(unittest.TestCase): @classmethod def setUpClass...
103387
from pyNastran.dev.bdf_vectorized.test.test_coords import * from pyNastran.dev.bdf_vectorized.test.test_mass import * from pyNastran.dev.bdf_vectorized.cards.elements.solid.test_solids import * from pyNastran.dev.bdf_vectorized.cards.elements.shell.test_shell import * from pyNastran.dev.bdf_vectorized.cards.elements.r...
103394
import abc class Metrics(abc.ABC): def __init__(self): raise NotImplementedError @abc.abstractmethod def calculate(self) -> float: raise NotImplementedError class Accuracy(Metrics): def __init__(self): super().__init__() self._num_correct = 0 self._num_sample...
103404
def f(*, b): return b def f(a, *, b): return a + b def f(a, *, b, c): return a + b + c def f(a, *, b=c): return a + b def f(a, *, b=c, c): return a + b + c def f(a, *, b=c, c=d): return a + b + c def f(a, *, b=c, c, d=e): return a + b + c + d def f(a=None, *, b=None): return a + b...
103416
from .Dataset import Dataset from .constants import * from .DataLoader import DataLoader, create_datasets from .Dict import Dict
103438
import json from collections import Iterator from os.path import join from elasticsearch import Elasticsearch from examples.imdb.conf import ES_HOST, ES_USE_AUTH, ES_PASSWORD, ES_USER, DATA_DIR from pandagg.index import DeclarativeIndex, Action from pandagg.mappings import Keyword, Text, Float, Nested, Integer class...
103464
import random import time from agora.retry.backoff import Backoff class Strategy: """Determines whether or not an action should be retried. Strategies are allowed to delay or cause other side effects. """ def should_retry(self, attempts: int, e: Exception) -> bool: """Returns whether or not...
103467
import torch import torch.nn as nn import os from .models import Darknet from .utils.utils import non_max_suppression, rescale_boxes class YoLov3HumanDetector(nn.Module): def __init__(self, weights_path="weights/yolov3.weights", conf_thres=0.8, nms_thres=0.4, img_size=416, device=torch.device("c...
103484
import EchelleJSON as ej import numpy as np # Read all of the file names and convert the strings to UT and JD f = open("files.txt") files = ["{}.json".format(ff[:-6]) for ff in f.readlines()] # Read the HJDN field f = open("HJD.txt", "w") for ff in files: edict = ej.read("jsons_BCV/{}".format(ff)) HJD = edic...
103515
import torch import torch.nn.functional as F def aggregate_sbg(prob, keep_bg=False, hard=False): device = prob.device k, _, h, w = prob.shape ex_prob = torch.zeros((k+1, 1, h, w), device=device) ex_prob[0] = 0.5 ex_prob[1:] = prob ex_prob = torch.clamp(ex_prob, 1e-7, 1-1e-7) logits = torch....
103524
from fastapi import APIRouter from .api.v1.job import router as job_router from .api.v1.record import router as record_router router = APIRouter() router.include_router(job_router) router.include_router(record_router)
103544
import dash_html_components as html import dash_vtk from dash_docs import tools from dash_docs import styles from dash_docs import reusable_components as rc examples = tools.load_examples(__file__) layout = html.Div([ rc.Markdown(''' # Click and Hover Callbacks It's possible to create callbacks based on ...
103604
import argparse, time, sys, os, subprocess class snmpRecon(object): def __init__(self): self.parseArgs() self.paramStrings=['1.3.6.1.2.1.25.1.6.0', '1.3.6.1.2.1.25.4.2.1.2', '1.3.6.1.2.1.25.4.2.1.4', '1.3.6.1.2.1.25.2.3.1.4', '1.3.6.1.2.1.25.6.3.1.2', '1.3.6.1.4.1.77.1.2.25', '1.3.6.1.2.1.6.13.1.3'...
103615
import asyncio import elasticsearch import json import logging import requests import time from urllib.parse import urlencode from datamart_core import Discoverer from datamart_core.common import setup_logging logger = logging.getLogger(__name__) class ZenodoDiscoverer(Discoverer): EXTENSIONS = ('.xls', '.xlsx...
103626
import torch from torch import Tensor from torch.nn import Module class ExponentialMovingAverage(Module): def __init__(self, *size: int, momentum: float = 0.995): super(ExponentialMovingAverage, self).__init__() self.register_buffer("average", torch.ones(*size)) self.register_buffer("init...
103645
from django.conf.urls import url from dojo.engagement import views urlpatterns = [ # engagements and calendar url(r'^calendar$', views.engagement_calendar, name='calendar'), url(r'^calendar/engagements$', views.engagement_calendar, name='engagement_calendar'), url(r'^engagement$', views.engagement, n...
103646
import numpy as np import tensorflow as tf from deep_da.model.util import util_tf """ Models used in DANN paper """ class Model: __base_n_hidden = [3072, 2048] def __init__(self, output_size: int=10, n_hidden: list=None): __n_hidden = n_hidden or self.__base_n_hid...
103651
import os from setuptools import setup PROJECT_NAME = 'actionslog' ROOT = os.path.abspath(os.path.dirname(__file__)) VENV = os.path.join(ROOT, '.venv') VENV_LINK = os.path.join(VENV, 'local') install_requires = [ 'Django>=1.11.20', 'django-jsonfield>=0.9.15', 'pytz>=2015.7', ] project = __import__(PROJEC...
103672
from core.run.event_dispatcher.register import EventRegister def build_runner(model, runner_config, data_source_context, config, event_register: EventRegister): if runner_config['type'] == 'default': from .training.default.builder import build_default_training_runner return build_default_training_...
103692
import socket import asyncio import time import random import json import requests from walkoff_app_sdk.app_base import AppBase class BreachSense(AppBase): __version__ = "1.0.0" app_name = "Breachsense" # this needs to match "name" in api.yaml def __init__(self, redis, logger, console_logger=None): ...
103698
import setuptools setup_args = dict( name="grr-grafanalib-dashboards", description="GRR grafanalib Monitoring Dashboards", license="Apache License, Version 2.0", url="https://github.com/google/grr/tree/master/monitoring/grafana", maintainer="GRR Development Team", maintainer_email="<EMAIL>", packages=set...
103702
from .box import Box from .cylinder import Cylinder from .sphere import Sphere from .random_primitive import RandomPrimitive from .plane import Plane
103710
from __future__ import print_function import click from click.testing import CliRunner from kcleaner import cli runner = CliRunner()
103712
from crypt import mksalt from datetime import datetime, timedelta from typing import List, Optional from arrow.arrow import Arrow from fastapi.encoders import jsonable_encoder import sqlalchemy from sqlalchemy import or_ from sqlalchemy.orm import Session from sqlalchemy.sql.functions import func from app import crud...
103715
import sys import os pattern = sys.argv[1] print(pattern) def get_result_line(i, pattern): filename = pattern.format(i) if os.path.exists(filename): lines = open(filename, 'r').readlines()[-3:] return str(i) + "\t" + '\t'.join([line.split(':')[1].strip() for line in lines]) return None re...
103755
import numpy as np # projection mask of NYUv2 PMASK = np.zeros([480, 640], dtype=np.float64) PMASK[44:471, 40:601] = 1.0 # sorted names METRIC_NAMES = [ 'RMSE', 'Mean RMSE', 'Mean Log10', 'Abs Rel Diff', 'Squa Rel Diff', 'delta < 1.25', 'delta < 1.25^2', 'delta < 1.25^3', ] def get_m...
103779
import torch import torch.nn as nn from loss_functions import AngularPenaltySMLoss class Stem_layer(nn.Module): def __init__(self, in_ch, out_ch, kernel_size, drop_rate, pool_size): super().__init__() dilation = 1 self.conv = nn.Conv1d( in_ch, out_ch, ke...
103801
class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: dict = {} for i in arr : if i in dict : dict[i] += 1 else : dict[i] = 1 count = 0 s = set(dict.values()) ns = len(s) nl = len(...
103803
import pytest from testfixtures import LogCapture @pytest.fixture(autouse=True) def log_capture(): with LogCapture() as capture: yield capture