content
stringlengths
5
1.05M
import matplotlib.pyplot as pl import numpy as np def myplot(flag, *args): size1 = 10 size2 = 4 if flag == 1: # pl.figure(figsize=(size1, size2)) if args: polynomial = args[0] x = np.arange(11, 1, -0.1) y = pow(x, 3) * polynomial[3] + pow(x, ...
#!/usr/bin/env python3 # # command from kubesicher (https://github.com/pflaeging/kubesicher) # # Usage: # ./get-k8sobjects.py -h # usage: get-k8sobjects.py [-h] [-v] [--oc] [-n NAMESPACE] [-d] [-b BASEDIR] # [-t OBJECTTYPES] [-l LABEL] # # Get kubernetes objects as yaml # # optional arguments: ...
from rest_framework.viewsets import ReadOnlyModelViewSet from .serializers import BerrySerializer from .models import Berry class BerryViewSet(ReadOnlyModelViewSet): """Berry API view/presentation (READONLY).""" serializer_class = BerrySerializer queryset = Berry.berries.all()
def torsion(a, b, c, d): # sqrt=math.sqrt, acos=math.acos dr=180./pi v12x, v12y, v12z = a[0] - b[0], a[1]-b[1], a[2]-b[2] v32x, v32y, v32z = c[0] - b[0], c[1]-b[1], c[2]-b[2] v43x, v43y, v43z = d[0] - c[0], d[1]-c[1], d[2]-c[2] vn13x = v12y*v32z - v12z*v32y vn13y = v12z*v32x - v12x*v32z ...
""" Query and deal common tables. """ from evennia.utils import logger from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from muddery.server.utils.exception import MudderyError, ERR class ElementPropertiesMapper(object): """ Object's properties. ...
#! /usr/bin/env python import khmer import numpy as np from khmer.khmer_args import optimal_size import os import sys # The following is for ease of development (so I don't need to keep re-installing the tool) try: from CMash import MinHash as MH except ImportError: try: import MinHash as MH except ImportError: ...
import pandas as pd import numpy as np import scipy.integrate as integrate import thesis_functions.utilities from thesis_functions.initial_conditions import initial_conditions from thesis_functions.initialconditions import InputDataDictionary, SetInitialConditions from thesis_functions.visualization import CreatePlo...
from tqdm import tqdm import numpy as np import torch import torch.nn as nn from ldl.data import get_episodic_loader from model import DLDReversed def train(model, loss_func, train_loader, epochs, silent=False, device=None): for epoch in range(epochs): for batch_i, (x, y) in enumerate(train_loader): ...
import openpyxl from openpyxl import load_workbook import time AW18 = load_workbook(filename = 'C:\\Users\\timde\\Desktop\\KingsofIndigo\\InformatieKoppelen\\AW18.xlsx') SS19 = load_workbook(filename = 'C:\\Users\\timde\\Desktop\\KingsofIndigo\\InformatieKoppelen\\SS19.xlsx') Samen = load_workbook(filename = 'C:\\Use...
# -*- coding:utf-8 -*- import requests import urllib wd = {'q': '长城'} headers = {"User-Agent": "Mozilla/5.0"} # params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode() response = requests.get("https://www.google.com/search?", params=wd, headers=headers) # 查看响应内容,response.text 返回的是Unicode格式的数据 # print response.text #...
# scheduler script from wakeup import wakeup print("wakeup") wakeup()
# Copyright 2017 NeuStar, Inc.All rights reserved. # # 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 a...
import requests import json payload = {'sentence': 'hello'} response = requests.post("https://chatbot-api52.herokuapp.com/predict", data=json.dumps(payload)) print(response.text)
"""Class implementing the lambda response format standards for API Gateway""" from slat.types import JsonapiBody, JsonDict class LambdaProxyResponse: """ ensure we have the correct response format as per https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api...
#! /usr/bin/python2 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # import os import unittest import requests import commonl.testing import tcfl.tc import ttbl.fsdb srcdir = os.path.dirname(__file__) ttbd = commonl.testing.test_ttbd(config_files = [ os.path.join(srcdir, "conf...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2014 Intel Inc. # All Rights Reserved. # 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 #...
import tokenize from . import _checker class Checker( _checker.BaseChecker, ): @classmethod def check( cls, filename, lines, tokens, start_position_to_token, ast_tree, astroid_tree, all_astroid_nodes, ): for token in tokens: ...
from django import forms from django.contrib.auth.models import User from UserPage.models import UserProfile class SignUpForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'password', 'email')
# Holds al the data of a certain column class Cue: # column: an array with this structure: [title, datapoint_1, ..., datapoint_n] def __init__(self, column): # The name of the Cue is the first element of the column. # At the same time, the element is popped out of the column. self.name ...
import numpy as np import nibabel as nb import pandas as pd import sys from nibabel.cifti2 import Cifti2Image from sklearn.linear_model import LinearRegression from scipy.signal import butter, filtfilt from nilearn.signal import clean import matplotlib.pyplot as plt from matplotlib import gridspec as mgs import mat...
""" A Vocabulary maps strings to integers, allowing for strings to be mapped to an out-of-vocabulary token. """ import codecs import gzip import hashlib import logging import os from collections import defaultdict from enum import Enum from pathlib import Path from typing import Callable, Any, List, Dict, Union, Seque...
NO_PENALTY = 'no_penalty' HARD_CODED_PENALTY = 'hard_coded_penalty' UNCERTAINTY_PENALTY = 'uncertainty_penalty' POLICY_ENTROPY_PENALTY = 'policy_entropy_penalty'
from module import Module CONFIGS = [ '.config/kitty' ] PROGRAMS = { 'kitty': 'brew install --cask kitty', } DEPENDENCIES = [ ] class Kitty(Module): def __init__(self): super().__init__( 'kitty', 'Kitty terminal', CONFIGS, PROGRAMS, DE...
# Relational Operators # Relational operators are used to evaluate conditions inside if statements. Some examples of relational operators are: # = = -> equals # >= -> greater than/equal to # <=, etc. = = -> equals integer = int(input("Enter your integers")) if integer==18: print("Equal") else: print("Not...
# REPEATED MATRIX VALUES # O(M * N) time and O(N) space, where M -> number of rows and # N -> number of columns in input matrix def repeatedMatrixValues(matrix): # Write your code here. count, counted = {}, {} for num in matrix[0]: count[num] = 0 counted[num] = False m, n = len(matrix), len(matrix[0]...
import pyJvsip as pv N=6 A = pv.create('cvview_d',N).randn(7) B = A.empty.fill(5.0) C = A.empty.fill(0.0) print('A = '+A.mstring('%+.2f')) print('B = '+B.mstring('%+.2f')) pv.add(A,B,C) print('C = A+B') print('C = '+C.mstring('%+.2f')) """ OUTPUT A = [+0.16+0.50i -0.21-0.75i -0.56-0.09i \ +1.15+0.45i +0.10+0.43i ...
"""Z terminal interface Like ATI Session Manager. Command usage: zti [-h] [--nolog] [--noztirc | --rcfile rcfile] [host] positional arguments: host hostname[:port] to connect/go to optional arguments: -h, --help show this help message and exit --nolog Do not ...
# This program prints and counts how many unique words are in the romeo.txt file txt = "c:/Users/TechFast Australia/Dropbox/Programming/Python/List Exercises/romeo.txt" uniqueWords = [] # List created to store unique words f = open(txt, "r") for x in f: # Loop through romeo.txt splitWords = x.split() # Split e...
"""团队习题集实现 Revision ID: 22ed937444ea Revises: aacb30cf5f40 Create Date: 2020-10-27 16:49:50.311575 """ import ormtypes from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '22ed937444ea' down_revision = 'aacb30cf5f40' branch_labels = None depends_on = None def upgrade...
import requests import json class AlreadySent(Exception): pass class Query: def __init__(self, uri="http://localhost:3000", node=None): if node: self.node = node else: self.node = Node(uri) self._find_clause = None self._where_clauses = [] self._...
# import sys # import json import time from User import User from SerialTransceiver import SerialTransceiver import _thread if __name__ == "__main__": # userinfo = getinfo() # user = User(int(userinfo['instanceID'],0),userinfo['port']) user = User() #获取用户信息 #user.print() serialTransceiver = SerialT...
#!/usr/bin/env python3 import subprocess import os from shutil import copy import sys import shutil import time from itertools import cycle import logging from logging import info, error from typing import NamedTuple, List, Sequence import json from src.file_io import File from src.liberty_parser import LibertyParser,...
#import requests import geopandas as gpd import pandas as pd from .utils_geo import generate_tiles, geometry_to_gdf, generate_manifest, generate_folium_choropleth_map, get_html_iframe from shapely.geometry import shape, MultiPolygon, Polygon from .settings import DEFAULT_CRS, DEFAULT_COORDS #save manifest as wkt to re...
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 11:20:21 2020 @author: Shivani """ #1.PRE-PROCESSING #open file containinng genome MT=open("D:\MEng\SPRING\INTRO BIOINFOR\MTG.txt", "r") contents=MT.read() #store contents of file in an object forw=[] for i in range(0, len(contents)): if content...
import unittest from io import StringIO from unittest import mock from scrapy.utils import trackref class Foo(trackref.object_ref): pass class Bar(trackref.object_ref): pass class TrackrefTestCase(unittest.TestCase): def setUp(self): trackref.live_refs.clear() def test_format_live_refs(...
from .models import Profile, User, QA from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from .utils import crypt, get_key, create_user_key @receiver(post_save, sender=User) def create_profile(sender, instance,created,**kwargs ): if created: Profile.objects.create(user=ins...
# Copyright 2015 Lenovo # # 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, softw...
""" File for structure checks: - Duplicates - Physical Structure - Molecule in structure checks """ import os,json import numpy as np from pymove import Structure,StructDict from pymove.io import read,write from pymatgen.analysis.structure_matcher import (StructureMatcher, ...
import gi gi.require_version("Gtk","3.0") from gi.repository import Gtk import ntpath from pathlib import Path class sushape(Gtk.Box): def __init__(self,parent): self.parent = parent self.glade_file=str(Path(__file__).parent / "sushape.glade") self.builder = Gtk.Builder() self.builde...
from cuescience_shop.models import Client, Address, Order from natspec_utils.decorators import TextSyntax from cart.cart import Cart from django.test.client import Client as TestClient class ClientTestSupport(object): def __init__(self, test_case): self.test_case = test_case self.client = TestClie...
from torch import tensor, long def tensor_loader(*adatas, protein_boolean, sampler, device, celltypes = None, categories = None): if (celltypes is not None) and (categories is not None): return tensor_loader_trihead(*adatas, protein_boolean = protein_boolean, sampler = sampler, device = device, celltypes =...
""" Remove annotatation kmers - Integrate multiple background kmer files (eg. somtic, somatic_and_germline, germline, ref annotation - Add a column in graph (foreground) kmer file to indicate if the kmer also appear in given annotation kmer set """ import pandas as pd import logging import os import sys from .io_ imp...
ThriftInfo = provider(fields = [ "srcs", # The source files in this rule "transitive_srcs", # the transitive version of the above ])
# Membership Operators my_list = [1, 2, 3, "oh no"] if "oh no" in my_list: print("oh no is an element in my_list") else: print("oh no is not an element in my_list") if 4 not in my_list: print("4 is not an element in my_list") else: print("4 is an element in my_list")
class F(object): pass class E(F): pass class G(F, E): pass
from datetime import datetime import pytest from django.core.exceptions import FieldDoesNotExist, ValidationError from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser, Group from django.contrib.sites.models import Site from django.test import TestCase, RequestFactory fr...
from .unsupervised_model import unsupervised_model
''' @queenjobo @ksamocha 16/08/2019 Functions to assign weights to different variant classes ''' import pandas as pd import logging as lg import numpy as np import itertools from scipy import stats import sys def get_loess_weight_dic(wdicpath,cqs, print_flag): ''' create constrained/unconstrained dictionar...
from .transforms import ( Compose, ImageResize, RandomHorizontalFlip, RandomVerticalFlip, ImageNormalization, ToTensor ) __all__ = [ 'Compose', 'ImageResize', 'RandomHorizontalFlip', 'RandomVerticalFlip', 'ImageNormalization', 'ToTensor' ]
#!/usr/bin/env python3 import os import sys from hashlib import md5 import Bio.SeqIO from iggtools.common.argparser import add_subcommand, SUPPRESS from iggtools.common.utils import tsprint, InputStream, retry, command, multithreading_map, find_files, upload, pythonpath from iggtools.models.uhgg import UHGG, get_uhgg_l...
from urllib.parse import urlencode def make_url(url, url_params): params = {**url_params} if "fields" in url_params: if isinstance(params, str): params["fields"] = url_params["fields"] else: params["fields"] = ",".join(url_params["fields"]) return "{}?{}".format(url...
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> # This script can be executed from the Terminal using $ pythonw # dataset: mne_sample from eelbrain import * w = 3 # load sample data ds = datasets.get_mne_sample(sub="modality=='A'", sns=True) # interactive plot plot.TopoButterfly('meg', ds=ds) # plot top...
# -*- coding: utf-8 -*- """TargetArea serializer module. """ from django.conf import settings from django.contrib.postgres.fields.jsonb import KeyTextTransform from django.core.cache import cache from django.db import connection from django.db.models import Case, Count, F, IntegerField, Sum, Value, When from django.db....
from rest_framework import viewsets from .models import Note, NotedModel from .serializers import NoteSerializer, NotedModelSerializer from rest_framework.permissions import IsAuthenticatedOrReadOnly class NoteViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticatedOrReadOnly,) queryset = Note.ob...
''' # This is an 80 character line # INTENT: Pick out the cluster edges so that you can analyze edge statistics 1. Cluster algorithm 2. Count nearest neighbors in largest cluster only --- Break here and plot this data --- 3. Look at contiguous set of l...
import chainer import torch import chainer_pytorch_migration as cpm def _named_children(link): assert isinstance(link, chainer.Link) if isinstance(link, chainer.Chain): for name in link._children: yield name, getattr(link, name) def _named_params(link): assert isinstance(link, chain...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
""" Check SFP status and configure SFP This script covers test case 'Check SFP status and configure SFP' in the SONiC platform test plan: https://github.com/Azure/SONiC/blob/master/doc/pmon/sonic_platform_test_plan.md """ import logging import re import os import time import copy from ansible_host import ansible_host...
# Copyright 2014 MadeiraCloud LTD. import logging from cliff.command import Command class Delete(Command): "Delete your stack, locally or on AWS" log = logging.getLogger(__name__) def get_parser(self, prog_name): parser = super(Delete, self).get_parser(prog_name) parser.add_argument('s...
# coding=UTF-8 # ex:ts=4:sw=4:et=on # Copyright (c) 2013, Mathijs Dumon # All rights reserved. # Complete license can be found in the LICENSE file. from contextlib import contextmanager from mvc.models.base import Model from pyxrd.generic.controllers import ObjectListStoreController from pyxrd.mixture.models impo...
import time import random def timeit(func, *args): t1 = time.time() ret = func(*args) cost_time = (time.time() - t1) * 1000 print("cost time: %sms" % cost_time) try: randint_wrap = random.randint except: # micropython def randint_wrap(a, b): return a + random.getrandbits(32) % (b-a) def rand_str...
import bz2 import json import logging import os.path import pathlib import sys import click @click.group() def main(): """Command line tools""" pass @main.command() @click.argument("src") @click.argument("dst") @click.option("-f", "continue_on_error", is_flag=True) @click.option("--inventory", multiple=Tru...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from cryptography import utils from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons from cryptography.hazmat.pri...
arcpy.AddField_management(in_table="Riffle_channel", field_name="Seq_1", field_type="LONG", field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED") arcpy.CalculateField_management(in_table="Riffle_ch...
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified). __all__ = ['tweet_text', 'check_sig', 'reconfig', 'run_server', 'fastwebhook_install_service'] # Cell import json,tweepy,hmac,hashlib,traceback,shutil,time,fcntl from fastcore.imports import * from fastcore.foundation import * fr...
# -*- coding: utf-8 -*- from wtforms import * from wtforms.validators import DataRequired, Length, Email, Required, EqualTo from flask_wtf import FlaskForm class RegistrationsForm(FlaskForm): """ Форма регистрации аккаунта """ username = StringField('Имя', validators=[ DataRequired(message='Обязательн...
import os import bs4 import requests import re import time import random import sys import pandas as pd # CLI with 3 arguments (script name, number of protocols, party selected) while True: try: if len(sys.argv) != 3: print('Input could not be interpreted. Please insert two arguments:') ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ * create by afterloe * MIT License * version is 1.0 """ import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.OUT) GPIO.setup(6, GPIO.OUT) for i in range(0, 15): GPIO.output(5, GPIO.HIGH) time.sleep(0.5) GPIO....
# Copyright (C) Daniel Carter 2019 # Licensed under the 2-clause BSD licence # Selection of helper functions for graphviz-based graphs import datetime import json import os import re import pygraphviz as pgv _DEVICE_SPECIFIC_COLOR = 'red' _PATCHED_VULNERABILITY_STYLE = 'dashed' def strictify(graph, directed=True):...
from . import CustomChart import plotly.graph_objects as go class ChoroplethMap(CustomChart): # noqa: H601 """Gantt Chart: task and milestone timeline.""" def create_figure(self, df, **kwargs): """Return traces for plotly chart. Args: df_raw: pandas dataframe with columns: `(cat...
"""Module for managing the system properties for the fm_server."""
#!/usr/bin/env python from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import (run_module_suite, assert_allclose, assert_, assert_raises) import pywt # Check that float32, float64, complex64, complex128 are preserved. # Other real types...
def lag(orig: str, num_lags: int = 1) -> str: return orig + f'_{{t - {num_lags}}}'
# -*- coding: utf-8 -*- from django.db import models class Portrait(models.Model): user = models.BooleanField()
import mpylib import opcode class AttrDict: def __init__(self, d): self.d = d def __getattr__(self, k): return self.d[k] op = AttrDict(opcode.opmap) with open("testout.mpy", "wb") as f: mpy = mpylib.MPYOutput(f) mpy.write_header(3, mpylib.MICROPY_PY_BUILTINS_STR_UNICODE | mpylib.M...
import structlog from eth_typing import ChecksumAddress from eth_utils import decode_hex, event_abi_to_log_topic, to_checksum_address from gevent.lock import Semaphore from web3 import Web3 from web3.utils.abi import filter_by_type from web3.utils.events import get_event_data from web3.utils.filters import construct_ev...
from itertools import combinations import sys import collections class Adapter: def __init__(self): self.children = [] self.number_of_children = 0 self.number_of_leaves = 0 def add_child(self, child): self.children.append(child) self.number_of_children = len(self.child...
import os import typing import jk_typing import jk_logging import jk_simpleobjpersistency import jk_utils from jk_appmonitoring import RDirectory, RFileSystem, RFileSystemCollection import jk_mounting from thaniya_common import AppRuntimeBase from thaniya_common.cfg import AbstractAppCfg from thaniya_common.utils ...
# -*- coding: utf-8 -*- from flask import render_template,url_for,request,redirect,flash,abort from taobao import app,db,bcrypt from taobao.models import Customer,Crew,User,CustomerDetail,Supplier,Product,Order,OrderDetail,OrderAddress from taobao.forms import * from flask_login import current_user,logout_user,login_us...
import pythonneat.neat.Genome as Genome import pythonneat.neat.utils.Parameters as Parameters genes = {} def get_innovation(connection_gene): for g in genes.items(): if g[1].in_id == connection_gene.in_id and g[1].out_id == connection_gene.out_id: return g[0] innov = len(genes) + 1 ge...
#!/usr/bin/env python # Copyright 2013 Mirantis, Inc. # # 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 a...
from utils import tune # for params look here # https://github.com/facebook/prophet/blob/master/python/prophet/forecaster.py # docker image gluonts:prophet algo = dict( name="ProphetPredictor", hyperparameters={ "forecaster_name": "gluonts.model.prophet.ProphetPredictor", }, changing_hyperpara...
# coding: utf-8 """ FeatureState.py The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: *...
from register import * import tkMessageBox import sqlite3 from login_page import * from request_pizza import * from menu import * def welcome(): root=Tk() root.geometry("1600x800+0+0") root.title("Pizza Delivery system") root.configure(bg="white") Tops=Frame(root, width=1600...
# Generated by Django 3.0.8 on 2020-09-30 15:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chat', '0016_messagephoto_name_of_file'), ] operations = [ migrations.AddField( model_name='message', name='image_me...
# 3. Информация за скоростта # Да се напише програма, която чете скорост (реално число), въведена от потребителя и отпечатва информация за скоростта. # При скорост до 10 (включително) отпечатайте “slow”. При скорост над 10 и до 50 отпечатайте “average”. # При скорост над 50 и до 150 отпечатайте “fast”. При скорост над ...
# -*- coding: utf-8 -*- __author__ = "苦叶子" """ 公众号: 开源优测 Email: lymking@foxmail.com """ import os import platform import codecs from flask import render_template, send_file, current_app from flask_login import login_required, current_user, logout_user from . import main from ..utils.runner import run_process, d...
#!/usr/bin/env python # -*- coding:utf-8 -*- import torch from utils.utils import permute_and_flatten, decode from utils.box_list import BoxList, cat_boxlist, boxlist_ml_nms, boxlist_iou import pdb def select_over_all_levels(cfg, box_list): result_batch = [] for i in range(len(box_list)): result = bo...
# Author: Mike 'Fuzzy' Partin # Copyright: (c) 2016-2018 # Email: fuzzy@fumanchu.org # License: See LICENSE.md for details # Stdlib imports import os import json # Internal imports from mvm.term import * from mvm.package import * class MvmCmdList(object): def ListPackages(self, installed=True, output=True): ...
import pytest from py_ecc.optimized_bls12_381 import ( G1, G2, multiply, ) from py_ecc.bls.g2_primatives import ( G1_to_pubkey, G2_to_signature, ) from py_ecc.bls import G2Basic # Tests taken from EIP 2333 https://eips.ethereum.org/EIPS/eip-2333 @pytest.mark.parametrize( 'ikm,result_sk', [...
import unittest from flask import Flask from beamdice import dice, create_app REPETITIONS = 100 class TestDice(unittest.TestCase): def test_roll(self): """ Die rolls should be random. That is, over enough repetitions, the die roll should be something other than 6. """ non_six = False for ...
import math import os import struct import unittest import sycomore from sycomore.units import * class TestGRE(unittest.TestCase): def setUp(self): self.species = sycomore.Species(1000*ms, 100*ms, 0.89*um*um/ms) self.m0 = sycomore.Magnetization(0, 0, 1) self.flip_angle = 40*deg se...
# Copyright 2020 The Measurement System Authors # # 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 ag...
import http.client import time def readConn(addr, func): client = http.client.HTTPConnection("localhost:8080") while True: try: client.request("GET", "/" + addr, "ready") response = client.getresponse().read().decode() func(response) except (ConnectionRefusedError, http.client.RemoteDisc...
import asyncio import functools import uuid import uvloop from asyncio import Task from random import randint from typing import Dict, Any import time from tonga.services.coordinator.async_coordinator import async_coordinator class FailToFindKey(KeyError): pass class DBIsLocked(Exception): pass async def...
from typing import Mapping, Collection def to_json(obj): if hasattr(obj, 'to_json'): return obj.to_json() elif isinstance(obj, str): return obj elif isinstance(obj, Mapping): return {to_json(k): to_json(v) for k, v in obj.items()} elif isinstance(obj, Collection): retur...
# Copyright (c) 2014 VMware, Inc. # All Rights Reserved. # # 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...
# Lint as: python3 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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 ...
"""Github two-factor authentication requirement was disabled.""" from helpers.base import ghe_json_message from stream_alert.rule_processor.rules_engine import StreamRules rule = StreamRules.rule @rule(logs=['ghe:general'], matchers=['github_audit'], outputs=['aws-s3:sample-bucket', 'pagerd...