text
stringlengths
2
999k
import json import os import sys import disnake from disnake.ext import commands from disnake.ext.commands import Context from helpers import json_manager, checks import logging if not os.path.isfile("../config.json"): sys.exit("'config.json' not found by general-normal! Please add it and try again.") else: ...
from django.apps import AppConfig class MarkersConfig(AppConfig): name = 'markers'
from os import ( startfile, getcwd ) from os.path import join from io import BytesIO from csv import ( writer, excel ) from openpyxl import ( Workbook, load_workbook ) from statistics import ( mean, variance, stdev ) from treetopper.plot import Plot from treetopper.timber import ( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def example1(): """Slice operator. seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ] seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ] seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]] seq[lo...
""" Common logic used by the docker state and execution module This module contains logic to accommodate docker/salt CLI usage, as well as input as formatted by states. """ import copy import logging import salt.utils.args import salt.utils.data import salt.utils.dockermod.translate from salt.exceptions import Comm...
# Copyright (c) 2019 UniMoRe, Matteo Spallanzani import torch from ..utils.utils import xywh2xyxy, bbox_iou def clip_boxes(boxes): boxes[:, [0, 2]] = boxes[:, [0, 2]].clamp(min=0, max=1) boxes[:, [1, 3]] = boxes[:, [1, 3]].clamp(min=0, max=1) def postprocess_pr(pr_outs, conf_thres=0.001, overlap_thres=0.5...
""" This is an implementation of Function Secret Sharing Useful papers are: - Function Secret Sharing- Improvements and Extensions, Boyle 2017 Link: https://eprint.iacr.org/2018/707.pdf - Secure Computation with Preprocessing via Function Secret Sharing, Boyle 2019 Link: https://eprint.iacr.org/2019/1095 Note tha...
#!/usr/bin/env python3 """ Test for local-subnet identifier """ import unittest import netifaces from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.localsubnet import * DATA = { } class TestLimitprocessorIdentifierLocalSubnet(PschedTestBase): """ Test the Identifier """ ...
from PuzzleLib.Cuda.Kernels.RadixSort import backendTest def unittest(): from PuzzleLib.Hip import Backend backendTest(Backend) if __name__ == "__main__": unittest()
import os from setuptools import setup README = """ See the README on `GitHub <https://github.com/uw-it-aca/app_name>`_. """ # The VERSION file is created by travis-ci, based on the tag name version_path = "app_name/VERSION" print(os.path.join(os.path.dirname(__file__), version_path)) VERSION = open(os.path.join(os.p...
from abc import abstractmethod from ml import LabelStudioMLBase class LabelStudioMLBaseHelper(LabelStudioMLBase): @abstractmethod def prepare_tasks(self, tasks, workdir=None, **kwargs): pass @abstractmethod def convert_predictions(self, predictions, **kwargs): pass @abstractmeth...
import requests import urllib import time import hashlib import hmac import itertools try: from urllib.parse import urlencode except ImportError: from urllib import urlencode from .api import Base from .errors import ApiError, ArgumentError def check_values(value, arg, arg_value): if type(value) == type...
from umonitor import __version__ def test_version(): assert __version__ == '0.1.5'
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') # prints out "Greetings!" in the terminal. colors = ['red','orang...
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Class for bitcoinexodusd node under test""" import contextlib import decimal import errno from enum im...
import warnings import numpy as np from skimage import img_as_float from skimage.util.dtype import dtype_range, dtype_limits from skimage._shared.utils import deprecated __all__ = ['histogram', 'cumulative_distribution', 'equalize', 'rescale_intensity', 'adjust_gamma', 'adjust_log', 'adjust_sig...
# Copyright 2020-2022 OpenDR European Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
# coding: utf-8 """Python data types for IB Flex format XML data. These class definitions are introspected by ibflex.parser to type-convert IB data. They're dataclasses, made immutable by passing `Frozen=True` to the class decorator. Class attributes are annotated with PEP 484 type hints. Except for the top-level ...
import os import aiofiles import webbrowser import json as stdlib_json from sanic import Sanic, response from sanic.exceptions import abort from sanic.response import json from pyfy import AsyncSpotify, ClientCreds, AuthError try: from spt_keys import KEYS except: # noqa: E722 from spt_keys_template import ...
""" This test will initialize the display using displayio and draw a solid green background, a smaller purple rectangle, and some yellow text. All drawing is done using native displayio modules. Pinouts are for the 2.4" TFT FeatherWing or Breakout with a Feather M4 or M0. """ import board import terminalio im...
#!/usr/bin/env python3 import argparse import os import subprocess import sys def setup(): global args, workdir programs = ['ruby', 'git', 'apt-cacher-ng', 'make', 'wget'] if args.kvm: programs += ['python-vm-builder', 'qemu-kvm', 'qemu-utils'] elif args.docker: dockers = ['docker.io',...
############################################################################### ## ## Copyright (c) Crossbar.io Technologies GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at...
a = int(input()) for i in range(1,11): total = i*a print('{} x {} = {}'.format(i, a,total))
import copy import torch.nn as nn from rlkit.launchers.launcher_util import setup_logger import rlkit.torch.pytorch_util as ptu from rlkit.core.ma_eval_util import get_generic_ma_path_information def experiment(variant): num_agent = variant['num_agent'] from differential_game import DifferentialGame expl_e...
from django.urls import NoReverseMatch from django.utils import html from django.utils.translation import ugettext as _ from couchdbkit import ResourceNotFound from casexml.apps.case.models import CommCareCaseAction from corehq.apps.case_search.const import ( CASE_COMPUTED_METADATA, SPECIAL_CASE_PROPERTIES, ...
# LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE from nose import SkipTest import numpy as np from numpy.testing import assert_allclose, assert_raises, assert_equal from scipy.sparse import isspmatrix from scipy.spatial.distance import cdist, pdist, squareform from megaman.geometry impor...
import numpy as np import urllib2 as ulib import csv import time if __name__ == '__main__': start_time = time.time() outDir = "Fasta/" listDir = "protein.csv" urlDomain = "http://www.uniprot.org/uniprot/" protList = [] it = 0 #flag for parsing and counter for download variable #Parse csv ...
""" This compat modules is a wrapper of the core os module that forbids usage of specific operations (e.g. chown, chmod, getuid) that would be harmful to the Windows file security model of Certbot. This module is intended to replace standard os module throughout certbot projects (except acme). """ # pylint: disable=fun...
from commons import * import os def pgp_check(): init_directory('./temp') # gpg must exist on your system status = os.system('gpg --version') if status==0: print_up('gpg is found') else: print_err('can\'t find gpg') def verify_publickey_message(pk, msg): # obtain a temp filena...
import unittest import math from Include.Tuple import * # # Tuple Unit tests # class TestTuplePointVector(unittest.TestCase): def test_Tuple_ifWArgumentIsOneTupleIsPoint(self): self.a = Tuple(4.3, -4.2, 3.1, 1.0) self.assertEqual(self.a.x, 4.3) self.assertEqual(self.a.y, -4.2) self...
from collections.abc import Mapping import numpy as np from pickydict import PickyDict from .utils import load_known_key_conversions _key_regex_replacements = {r"\s": "_", r"[!?.,;:]": ""} _key_replacements = load_known_key_conversions() class Metadata: """Class to handle spectrum met...
""" Base settings to build other settings files upon. """ import environ ROOT_DIR = ( environ.Path(__file__) - 3 ) # (webscrape/config/settings/base.py - 3 = webscrape/) APPS_DIR = ROOT_DIR.path("webscrape") env = environ.Env() READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=False) if READ_DOT...
"This creates an HDF5 file with a potentially large number of objects" import sys import numpy import tables filename = sys.argv[1] # Open a new empty HDF5 file fileh = tables.open_file(filename, mode="w") # nlevels -- Number of levels in hierarchy # ngroups -- Number of groups on each level # ndatasets -- Number o...
import logging import os import unittest import pypesto import pypesto.logging class LoggingTest(unittest.TestCase): def test_optimize(self): # logging pypesto.logging.log_to_console(logging.WARN) filename = ".test_logging.tmp" pypesto.logging.log_to_file(logging.DEBUG, filename) ...
from django.urls import path from .views import audit_view urlpatterns = [ path('', audit_view, name="audit") ]
from cashbook.models import CashBookTransaction from controls.models import ModuleSettings, Period from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import F, OuterRef, Subquery, Sum from django.db.models.functions import Coalesce from django.views.generic import TemplateView from purchase...
import os import errno import certifi import requests from deriva.core import urlsplit, get_new_requests_session, stob, make_dirs, DEFAULT_SESSION_CONFIG from deriva.transfer.download import DerivaDownloadError, DerivaDownloadConfigurationError, \ DerivaDownloadAuthenticationError, DerivaDownloadAuthorizationError ...
import unittest from sampleproject_tests import mayaTest from mayatdd.mayatest import insideMaya if insideMaya: from maya import cmds @mayaTest class Test(unittest.TestCase): def testMinimal(self): ''' do something with maya.cmds to prove we're actually running this test in Maya. ''' ...
from app.routers.audio import router AUDIO_SETTINGS_URL = router.url_path_for("audio_settings") GET_CHOICES_URL = router.url_path_for("get_choices") START_AUDIO_URL = router.url_path_for("start_audio") def test_get_settings(audio_test_client): response = audio_test_client.get(url=AUDIO_SETTINGS_URL) assert r...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2015 Enrique Fernandez # Released under the BSD License. # # Authors: # * Enrique Fernandez import Tkinter import rospy from geometry_msgs.msg import Twist, Vector3 import numpy class MouseTeleop(): def __init__(self): # Retrieve params...
from typing import Tuple, Union, Callable, Optional, Sequence from pytest_mock import MockerFixture import pytest import numpy as np import dask.array as da from squidpy.im import ( segment, ImageContainer, SegmentationCustom, SegmentationWatershed, ) from squidpy.im._segment import _SEG_DTYPE from sq...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import argparse import contextlib import os import subprocess from pathlib import Path RESTLER_TEMP_DIR = 'restler_working_dir' @contextlib.contextmanager def usedir(dir): """ Helper for 'with' statements that changes the current directory t...
import urllib from contextlib import suppress from django.conf import settings from django.contrib import messages from django.contrib.auth import login from django.core.exceptions import PermissionDenied, SuspiciousOperation from django.http import FileResponse, Http404, HttpResponseServerError from django.shortcuts ...
# Generated by Django 2.1 on 2019-10-12 09:44 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Stock', fields=[ ('id', models.AutoField(auto...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
import torch import torch.nn as nn import torch.nn.functional as F class MyAwesomeModel(nn.Module): def __init__(self, n_classes): super(MyAwesomeModel, self).__init__() self.feature_extractor = nn.Sequential( nn.Conv2d(in_channels=1, out_channels=6, kernel_size=4, stride=1), ...
from adventofcode.year_2021.day_2021_01 import readable, short def test_readable_part_one(): answer = readable.part1() assert answer == 1616 def test_readable_part_two(): answer = readable.part2() assert answer == 1645 def test_short_part_one(): answer = short.part1() assert answer == 1616...
"""djangoecommerce URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cla...
from stable_baselines.ppo2.run_mujoco import eval_return import cma import numpy as np from stable_baselines.low_dim_analysis.eval_util import * from stable_baselines.low_dim_analysis.common import do_pca, plot_2d, \ dump_rows_write_csv, generate_run_dir, do_proj_on_first_n_IPCA, get_allinone_concat_df from sklear...
import tublatexmaker.latex_creater as convert dict_of_entries = { "(Bahth fī) uṣūl al-fiqh": { "displaytitle": "", "exists": "1", "fulltext": "(Bahth fī) uṣūl al-fiqh", "fullurl": "http://144.173.140.108:8080/tub/index.php/(Bahth_f%C4%AB)_u%E1%B9%A3%C5%ABl_al-fiqh", "namespa...
from typing import Sequence import numpy as np import xarray from xarray import DataArray from xclim.indices.run_length import rle_1d def get_longest_run_start_index( arr: DataArray, window: int = 1, dim: str = "time", ) -> DataArray: return xarray.apply_ufunc( get_index_of_longest_run, ...
# Generated by Django 2.2.7 on 2019-11-20 17:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes', '0001_initial'), ] operations = [ migrations.AlterField( model_name='note', name='media', field=...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
from __future__ import annotations import shutil from betfairlightweight.resources.streamingresources import MarketDefinition from betfairlightweight.resources.bettingresources import MarketCatalogue, MarketBook from betfairlightweight.streaming.listener import StreamListener import sqlalchemy from sqlalchemy.sql.expr...
"""rest_vk_api URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-b...
#!/usr/bin/env python from testWrt import testsetup from testWrt.lib import SSHOpenWrt if __name__ == "__main__": ts = testsetup.create_generic() device = SSHOpenWrt(hostname="192.168.1.1", password="test") ret = device.portscan(22) print(ret)
import csv import logging from datetime import datetime, timedelta from typing import Any, Dict, Optional from scrapy import Spider from sqlalchemy.dialects.postgresql import insert from opennem.core.normalizers import normalize_duid from opennem.db import SessionLocal, get_database_engine from opennem.db.models.open...
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from wtforms.ext.sqlalchemy.fields import QuerySelectField from w...
# -*- coding: utf-8 -*- """ Created on Thu Feb 6 20:55:32 2020 @author: arosso """ from recipe_scrapers import scrape_me # give the url as a string, it can be url from any site listed below # scraper = scrape_me('http://allrecipes.com/Recipe/Apple-Cake-Iv/Detail.aspx') scraper = scrape_me('https://www.101cookbooks....
import numpy as np import pandas as pd from sklearn.cluster import KMeans import itertools import findspark import pyspark from pyspark.sql.functions import pandas_udf, PandasUDFType from pyspark.sql.types import * import time def simulate_sbm_dc_data(sbm_matrix, sample_size=1000, partition_num=10, cluster_num=3): ...
from __future__ import absolute_import import six from string import Formatter class dontexplodedict(object): """ A dictionary that won't throw a KeyError and will return back a sensible default value to be used in string formatting. """ def __init__(self, d=None): self.data = d or {...
import os.path as pt import numpy as np import torchvision.transforms as transforms import torch from torch.utils.data import DataLoader from torchvision.datasets import EMNIST def ceil(x: float): return int(np.ceil(x)) class MyEMNIST(EMNIST): """ Reimplements get_item to transform tensor input to pil imag...
import numpy as np import torch import torch.nn as nn from rgb_stacking.utils.utils import init class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), -1) class Sum(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, x): ...
#!/usr/bin/env python # coding=utf-8 # Stan 2018-08-04 import sys if sys.version_info >= (3,): class aStr(): def __str__(self): return self.__unicode__() def cmp(a, b): return (a > b) - (a < b) # range = range def b(s): return s.encode('utf-8') def u(s): ...
# A four-digit integer is given. Find the sum of even digits in it. # Create a variable "var_int" and assign it a four-digit integer value. # Create a variable "sum_even" and assign it 0. # Find the sum of the even digits in the variable "var_int". var_int = 1184 sum_even = 0 x1 = var_int % 10 var_int //= 10 sum_ev...
# Permafrost Forms from django.conf import settings from django.contrib.auth.models import Permission from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.forms import ModelForm from django.forms.fields import CharField, ChoiceField, BooleanField from django.forms....
import os import numpy as np import pandas as pd from qlib.data.dataset.processor import Processor from qlib.data.dataset.utils import fetch_df_by_index from typing import Dict class HighFreqTrans(Processor): def __init__(self, dtype: str = "bool"): self.dtype = dtype def fit(self, df_features): ...
import torch import torch.nn as nn use_cuda = torch.cuda.is_available() class CNNClassifier(nn.Module): def __init__(self, channel, SHHS=False): super(CNNClassifier, self).__init__() conv1 = nn.Conv2d(1, 10, (1, 200)) pool1 = nn.MaxPool2d((1, 2)) if channel == 1: conv2 =...
from math import sqrt # function with int parameter def my_function(a: str): print(a) my_function(3) # function with type annotation def my_function2(a: str) -> str: return a print(my_function2(3)) # import sqrt from math and use it print(sqrt(9.4323)) # import alias from math # from math import sqrt as square_...
import cv_datetime_utils import cv2 as cv import numpy as np import matplotlib.pyplot as plt import scipy.optimize import json import os def compose_transformations( rotation_vector_1, translation_vector_1, rotation_vector_2, translation_vector_2): rotation_vector_1 = np.asarray(rot...
""" Client Run by the evaluator, sends a TLS Client Hello with the ESNI extension, followed by two test packets. """ import argparse import binascii as bi import os import socket import time socket.setdefaulttimeout(1) from plugins.plugin_client import ClientPlugin class ESNIClient(ClientPlugin): """ Defi...
""" Dump/export our own data to a local file. Script is installed as `location_dump`. """ import argparse import os import os.path import sys from sqlalchemy import text from ichnaea.db import ( configure_db, db_worker_session, ) from ichnaea.geocalc import bbox from ichnaea.log import ( configure_loggi...
#!/usr/bin/python import serial import time ser = serial.Serial( port = '/dev/ttyACM1', baudrate = 9600, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS ) while 1: ser.flush() line = ser.readline().decode().strip() gas...
""" Convert an RDF graph into an image for displaying in the notebook, via GraphViz It has two parts: - conversion from rdf into dot language. Code based in rdflib.utils.rdf2dot - rendering of the dot graph into an image. Code based on ipython-hierarchymagic, which in turn bases it from Sphinx See https://...
""" LUME-Genesis primary class """ from genesis import archive, lattice, parsers, tools, writers import h5py import tempfile from time import time import shutil import os def find_genesis2_executable(genesis_exe=None, verbose=False): """ Searches for the genesis2 executable. """ if ge...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import from telemetry.core import util util.AddDirToPythonPath( util.GetTelemetryDir(), 'third_party', 'websocket-client...
# -*- coding: utf-8 -*- import pytest from wemake_python_styleguide.violations.best_practices import ( BaseExceptionViolation, ) from wemake_python_styleguide.visitors.ast.keywords import ( WrongExceptionTypeVisitor, ) use_base_exception = """ try: execute() except BaseException: raise """ use_excep...
from .functional import *
from . import ac from . import q_learning from . import rnnq_learning AC = ac.ActorCritic MFAC = ac.MFAC IL = q_learning.DQN MFQ = q_learning.MFQ POMFQ = q_learning.POMFQ rnnIL = rnnq_learning.DQN rnnMFQ = rnnq_learning.MFQ def spawn_ai(algo_name, sess, env, handle, human_name, max_steps): if algo_name == 'mfq': ...
from lib.types import IStdin, IStdout def main(stdin: IStdin, stdout: IStdout): stdout.write('*** You are a student at PWN_University and you are all set to graduate at the end of the semester. Unfortunately the night before graduation you learned you were going to fail your last class and now you’re afraid the sc...
"""Constants for the ISY994 Platform.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_COLD, DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_HEAT, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLAS...
from scfmsp.controlflowanalysis.StatusRegister import StatusRegister from scfmsp.controlflowanalysis.instructions.AbstractInstructionBranching import AbstractInstructionBranching class InstructionJz(AbstractInstructionBranching): name = 'jz' def get_execution_time(self): return 2 def get_branchi...
# Import the Twython class from twython import Twython import json import os import pandas as pd from tqdm import tqdm try: os.remove('twitter_dataset.csv') except OSError: pass def main(): old_df = pd.read_csv('data/twitter_dataset_2.csv', lineterminator='\n') #first load the dictonary with the top u...
""" grdfilter - Filter a grid in the space (or time) domain. """ from pygmt.clib import Session from pygmt.helpers import ( GMTTempFile, build_arg_string, fmt_docstring, kwargs_to_strings, use_alias, ) from pygmt.io import load_dataarray @fmt_docstring @use_alias( D="distance", F="filter"...
"""Data structure of RSS and useful functions. """ # # Copyright (c) 2005-2020 shinGETsu Project. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain ...
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) from .kern import Kern import numpy as np from ...core.parameterization import Param from paramz.transformations import Logexp from paramz.caching import Cache_this class Static(Kern): def __init__(se...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="slacksdk", version="0.0.1a", author="Thanakrit Juthamongkhon", author_email="thanakrit.ju.work@gmail.com", description="A minimal slack sdk", long_description=long_description, lon...
# -*- coding: utf-8 -*- # # Copyright (C) 2020 Grzegorz Jacenków. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable...
from openmmtools import testsystems from simtk.openmm.app import * import simtk.unit as unit import logging import numpy as np from openmmtools.constants import kB from openmmtools import respa, utils logger = logging.getLogger(__name__) # Energy unit used by OpenMM unit system from openmmtools import states, inte...
import os import hashlib def _update_sha256(filename, sha256): """ Updates a SHA-256 algorithm with the filename and the contents of a file. """ block_size = 64 * 1024 # 64 KB with open(filename, 'rb') as input_file: while True: data = input_file.read(block_size) i...
def destructure(obj, *params): import operator return operator.itemgetter(*params)(obj) def greet(**kwargs): year, day, puzzle = destructure(kwargs, 'year', 'day', 'puzzle') print('Advent of Code') print(f'-> {year}-{day}-{puzzle}') print('--------------') def load_data(filename): with fil...
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from mixbox import fields import cybox.common from cybox.common.tools import ToolInformationList # internal import stix import stix.bindings.stix_common as stix_common_binding # relative from .vocabs im...
import copy from types import GeneratorType class MergeDict(object): """ A simple class for creating new "virtual" dictionaries that actually look up values in more than one dictionary, passed in the constructor. If a key appears in more than one of the given dictionaries, only the first occurrenc...
import os import sys import dlib import glob import csv import pickle as pp from sklearn.neighbors import KNeighborsClassifier import pandas as pd from sklearn import preprocessing # from sklearn.model_selection import train_test_split import webbrowser from timeit import Timer from keras.preprocessing.image import img...
from dyn2sel.dcs_techniques import DCSTechnique import numpy as np from scipy.stats import mode class DESDDSel(DCSTechnique): def predict(self, ensemble, instances, real_labels=None): return ensemble[ensemble.get_max_accuracy()].predict(instances)
""" This module provide the case to test the coexistance between TDX guest and non TD guest. There are two types of non-TD guest: 1. Boot with legacy BIOS, it is default loader without pass "-loader" or "-bios" option 2. Boot with OVMF UEFI BIOS, will boot with "-loader" => OVMFD.fd compiled from the late...
import sys import pytest from pre_commit_hooks.loaderon_hooks.tests.util.test_helpers import perform_test_on_file_expecting_result from pre_commit_hooks.loaderon_hooks.general_hooks.check_location import main @pytest.fixture(autouse=True) def clean_sys_argv(): sys.argv = [] # Each line is a directory that ...
""" 1) "a" + "bc" -> abc 2) 3 * "bc" -> bcbcbc 3) "3" * "bc" -> error as we can't use the * operator on two strings 4) abcd"[2] -> c (Just takes the character at index 2 in the string. a has index 0 and b index 1) 5) "abcd"[0:2] -> ab (Returns the substring from index 0 all the way to index n -1 in this case b) 6)...
exp_name = 'basicvsr_vimeo90k_bd' # model settings model = dict( type='BasicVSR', generator=dict( type='BasicVSRNet', mid_channels=64, num_blocks=30, spynet_pretrained='pretrained_models/spynet.pth'), pixel_loss=dict(type='CharbonnierLoss', loss_weight=1.0, reduction='mean')...
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from glob import glob from os.path import basename from os.path import splitext from setuptools import find_packages from setuptools import setup with open("README.md", "r") as fh: long_d...