content
stringlengths
5
1.05M
# one possible solution # if it yields a bad result, rerun code class KM(): def __init__(self, k): self.k = k def distances(self, X): """Makes a distance matrix to the centroids of shape (n_samples x n_centroids)""" return np.vstack([np.sum((X-self.centroids[i,:])**2, ax...
import os from dotenv import load_dotenv from discord_key_bot import bot from discord_key_bot.keyparse import parse_key load_dotenv() bot.run(os.environ["TOKEN"])
import random, time def sleep_random(duration: tuple) -> None: """ sleep_random is designed to emulate a human user by pausing execution of the program (sleeping) for a random duration of time between `a` and `b` seconds. :param duration: tuple containing two floats: `a` is the minimum sleep duration ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join tmp_src = join("build", "src") log.set_verbosity(1)...
import json from django.http import HttpResponse from django.template import loader, Template from django.utils.datastructures import SortedDict from urllib import urlencode from tiote import forms, sa from tiote.utils import * import base def browse(request): conn_params = fns.get_conn_params(request, update_db...
from django.db import models from django.utils import timezone import json class Spy(models.Model): CREATE = 'create' CHANGE = 'change' DELETE = 'delete' ACTION_CHOICES = ( (CREATE, 'CREATE'), (CHANGE, 'CHANGE'), (DELETE, 'DELETE'), ) id = models.AutoField(primary_key...
import os from google.cloud.storage import Bucket from google.cloud import storage from google.api_core.exceptions import NotFound from ...Models.Interfaces.IStorageClientWrapper import IStorageClientWrapper from ..DTOs.CloudStorageMetadataDTO import CloudStorageMetadataDTO from ...Models.Converters.JSONConverter impo...
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn.bricks.wrappers import NewEmptyTensorOp, obsolete_torch_version if torch.__version__ == 'parrots': TORCH_VERSION = torch.__version__ else: # torch.__version__ could be 1.3.1+cu92, we only need the first two # for comparison ...
import os import sys lib_path = os.path.realpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'lib')) if lib_path not in sys.path: sys.path[0:0] = [lib_path] PORT = 9090 import redis REDIS_SYNC = redis.StrictRedis(db=0) import brukva REDIS_ASYNC = brukva.Client(selected_db=0) import celery C...
from netbox.api import OrderedDefaultRouter from . import views router = OrderedDefaultRouter() router.APIRootView = views.TopologyViewsRootView router.register('preselectdeviceroles', views.PreSelectDeviceRolesViewSet) router.register('preselecttags', views.PreSelectTagsViewSet) router.register('search', views.Sear...
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
from typing import Dict, Union, Generator, Set from .Grid import Grid, Coordinate from .PuzzleErrors import * class Puzzle: @staticmethod def __get_block_index(value): return (value - 1) // 3 + 1 @staticmethod def __conflicting_cells(position: Coordinate) -> Generator[Coordinate, None, None...
from turtle import * from colorsys import * sides = 2 tracer(5) speed(1) delay(0) hideturtle() bgcolor("black") hue=0 for i in range(1000): color(hsv_to_rgb(hue,1,1)) hue+=0.003 fd(i * 3 // sides + i) lt(360 / sides + 1) width(i * sides / 250) done()
#!/usr/bin/env python from argparse import ArgumentParser, RawDescriptionHelpFormatter from collections import defaultdict import csv from GenericTsvReader import GenericTsvReader from shared_utils import count_lines def parseOptions(): # Process arguments desc = '''Create gene table that handles the total...
#!/usr/bin/env python # coding=utf-8 from __future__ import ( absolute_import, print_function ) import io from glob import glob from os.path import ( basename, dirname, join, splitext ) from setuptools import find_packages, setup def read(*names, **kwargs): return io.open( join(d...
from CommonServerPython import * def main(): params = {k: v for k, v in demisto.params().items() if v is not None} params['indicator_type'] = FeedIndicatorType.IP params['url'] = 'http://www.malwaredomainlist.com/hostslist/ip.txt' params['indicator'] = json.dumps({ "regex": r"^\d{1,3}\.\d{1,...
import random from collections import namedtuple from utils.Segment_tree import SumSegmentTree, MinSegmentTree import numpy as np class Memory: def __init__(self, size): self.size = size self.currentPosition = 0 self.states = [] self.actions = [] self.rewards ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import submitit from compert.train import train_compert, parse_arguments import json import sys if __name__ == "__main__": json_file = sys.argv[1] with open(json_file, "r") as f: commands = [json.loads(line) for line in f.readline...
import sqlite3 class DataBase: def __init__(self): self.connection = sqlite3.connect("VKMessages.db") self.cursor = self.connection.cursor() self.create_table() def create_table(self): self.cursor.execute("""CREATE TABLE IF NOT EXISTS messages ( messag...
import pytest from solid_toolbox.units import Vec, Vec2d def test_vec_ops(): assert Vec(1, 2, 3) + Vec(4, 5, 6) == Vec(5, 7, 9) assert Vec(1, 2, 3) - Vec(4, 5, 6) == Vec(-3, -3, -3) assert Vec(1, 2, 3) * Vec(4, 5, 6) == Vec(4, 10, 18) assert Vec(1, 2, 3) / Vec(4, 5, 6) == Vec(0.25, 0.4, 0.5) asser...
"""Generic testing tools that do NOT depend on Twisted. In particular, this module exposes a set of top-level assert* functions that can be used in place of nose.tools.assert* in method generators (the ones in nose can not, at least as of nose 0.10.4). Note: our testing package contains testing.util, which does depen...
import logging from typing import NamedTuple from uuid import uuid4 from dsm.epaxos.cmd.state import Command, Checkpoint from dsm.epaxos.inst.state import Slot, Ballot, State, Stage from dsm.epaxos.inst.store import InstanceStoreState from dsm.epaxos.net.packet import Packet, PACKET_CLIENT, PACKET_LEADER, PACKET_ACCE...
#!/usr/bin/env python from setuptools import setup, find_packages import sys import platform from glob import glob VERSION = "1.2.2" APP = ['kickstart.py'] COPYRIGHT = "Copyright 2016-2017 by Revar Desmera" with open('README.rst') as f: LONG_DESCR = f.read() extra_options = {} data_files = [] py2app_options =...
import re from configparser import RawConfigParser import os class ConfigObject: """ """ def __init__(self): self.headers = {} self.raw_config_parser = None # set by calling parse_file def __getitem__(self, x): return self.get_header(x) def add_header(self, header_nam...
m, n = map(int, input().split()) a = [int(i) for i in input().split()]
from random import randrange as rr from math import sqrt import timeit def distance(l): s=0 for i in range(1,len(l)): x1,y1=dic[l[i-1]][0],dic[l[i-1]][1] x2,y2=dic[l[i]][0],dic[l[i]][1] s+=sqrt((x2-x1)**2+(y2-y1)**2) return s def dist(i,j): return float(format(sqrt((i[1]-j...
""" MIT License Copyright (c) 2017 s0hvaperuna Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d...
import torch import numpy as np import SimpleITK as sitk num_images = 10 class MyDataset: def __init__(self, paths): self.paths = paths def __len__(self): return len(self.paths) def __getitem__(self, index): image = sitk.ReadImage(self.paths[index]) resampler = sitk.Res...
# 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 # distributed under th...
import typing from PIL import ImageDraw from PIL import Image import numpy as np from .data_enhancer import DataEnhancer class EyeVectorProjEnhancer(DataEnhancer): """Draws projections of eye vectors on a 2d white surface""" def __init__(self, **kwargs): """Constructor""" super().__init__(**...
# system imports import numpy as np import os import argparse # BEAST imports from beast.tools import beast_settings, setup_batch_beast_trim from beast.tools.run import create_filenames from difflib import SequenceMatcher def make_trim_scripts( beast_settings_info, num_subtrim=1, nice=None, prefix=N...
#!/usr/bin/env python """ main.py -- Udacity conference server-side Python App Engine HTTP controller handlers for memcache & task queue access $Id$ created by wesc on 2014 may 24 __author__ = 'wesc+api@google.com (Wesley Chun)' """ import webapp2 from google.appengine.api import app_identity from google.appe...
from typing import Union from datetime import datetime import numpy as np import pandas as pd Timepoint = Union[datetime, np.datetime64, pd.Timestamp, str] class Task: def __init__( self, name: str, start: Timepoint, end: Timepoint, **tags ): """Individual tas...
# Copyright 2002-2011 Nick Mathewson. See LICENSE for licensing information. """mixminion.server.EventStats Classes to gather time-based server statistics""" __all__ = [ 'EventLog', 'NilEventLog' ] import os from threading import RLock from time import time from mixminion.Common import formatTime, LOG, previou...
'''https://leetcode.com/problems/climbing-stairs/ 70. Climbing Stairs Easy 8813 261 Add to List Share You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: n = 2 Output: 2 Explanation:...
#!/usr/bin/env python # encoding: utf-8 import datetime from unittest2 import TestCase from tempodb import DataPoint class DataPointTest(TestCase): def test_init(self): now = datetime.datetime.now() dp = DataPoint(now, 12.34) self.assertEqual(dp.ts, now) self.assertEqual(dp.valu...
import aiorun from .server import Server from backup.config import Config from backup.module import BaseModule from injector import Injector async def main(): config = Config.fromEnvironment() module = BaseModule(config, override_dns=False) injector = Injector(module) await injector.get(Server).start(...
#!/usr/bin/env python import sys import logging from xml.dom.minidom import parseString from screensketch.screenspec.reader import TextReader from screensketch.screenspec.writer import TextWriter from screensketch.screenspec.writer import XMLWriter from screensketch.screenspec.visualization import HTMLRenderer FORMA...
n = 600851475143 prime_factor = 1 i = 2 while i <= n / i: if n % i == 0: prime_factor = i n /= i else: i += 1 if prime_factor < n: prime_factor = n print(prime_factor)
# Copyright (c) 2019, Corey Smith # Distributed under the MIT License. # See LICENCE file in root directory for full terms. """ Neural network latent matrix factorization library. """ import torch import torch.nn as nn # from tqdm import tqdm from pathlib import Path from ..recommender.nn_layers import ScaledEmbeddin...
import json from adapters.base_adapter import Adapter from devices.switch.on_off_switch import OnOffSwitch class WeiserLock(Adapter): def __init__(self, devices): super().__init__(devices) self.switch = OnOffSwitch(devices, 'switch', 'state') self.devices.append(self.switch) def conve...
"""Tests for AIOSkybell.""" import pathlib EMAIL = "test@test.com" PASSWORD = "securepass" def load_fixture(filename) -> str: """Load a fixture.""" return ( pathlib.Path(__file__) .parent.joinpath("fixtures", filename) .read_text(encoding="utf8") )
from heapq import heappush, heappop def find_kth_largest(nums: list, k: int) -> int: h = [] [heappush(h, -num) for num in nums] [heappop(h) for _ in range(k-1)] return -heappop(h) if __name__ == "__main__": nums = list(map(int,input("Enter elements of array: ").split(' '))) k = int(input("En...
import FWCore.ParameterSet.Config as cms import TrackingTools.TrackFitters.KFTrajectoryFitter_cfi LooperTrajectoryFitter = TrackingTools.TrackFitters.KFTrajectoryFitter_cfi.KFTrajectoryFitter.clone( ComponentName = cms.string('LooperFitter'), Propagator = cms.string('PropagatorWithMaterialForLoopers') ) impor...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('admin', '0001_initial'), ('testapp', '0001_initial'), ] operations = [ migrations.CreateModel( ...
from scrapfishin.schema import Recipe _base = { 'source': 'Hello Fresh', 'prep_time': 10, 'difficulty': 'level 1', 'tags': [{'descriptor': 'spice mix'}], } tuscan_heat_spice = Recipe.parse_obj({ **_base, 'title': 'Tuscan Heat Spice', 'ingredient_amounts': [ {'ingredient': {'food':...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import base64 import json import logging import operator import pickle import smtplib import sys import time from collections import defaultdict from datetime import date, datetime from email.message import EmailMessage from io import BytesIO from pathlib import Path from...
from django.apps import apps as django_apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured VERSION = (0, 0, 3) __version__ = ".".join(map(str, VERSION)) def get_comment_model(): setting = getattr(settings, "TREE_COMMENTS_TREE_COMMENT_MODEL", "tree_comments.TreeComment") ...
"""Util.""" import csv import logging import os from decimal import ROUND_CEILING, ROUND_FLOOR, Decimal from pathlib import Path from typing import Any logger = logging.getLogger(__name__) def get_config_path() -> Path: """Get configuration file's path from the environment variable.""" config = os.getenv('TO...
#Dennis Durant import re def print_starsystems(content:str) -> str: pattern = re.compile("\"StarSystem\":\"(.+?)\"") result = pattern.findall(content) list = [] if result: for r in result: list.append(r) return list
#!/usr/bin/env python3 import fnmatch import os from pathlib import Path from time import perf_counter import mistune from jinja2 import Environment as Env from jinja2 import FileSystemLoader, StrictUndefined from minicli import cli, run, wrap HERE = Path(".") environment = Env(loader=FileSystemLoader(str(HERE / "src...
from imageai.Detection.Custom import DetectionModelTrainer trainer = DetectionModelTrainer() trainer.setModelTypeAsYOLOv3() trainer.setDataDirectory(data_directory="Pothole") trainer.setTrainConfig(object_names_array=["Pothole Severity Low","Pothole Severity High","Pothole Severity Medium"], batch_size=4, num_experime...
import numpy as np from knn import KNN from metrics import binary_classification_metrics, multiclass_accuracy def calc_accuracy_multiclass(train_X,train_y, test_X, test_y,num_folds,K): knn_classifier = KNN(k=K) knn_classifier.fit(train_X, train_y) predict = knn_classifier.predict(test_X) #rint('pr...
import pytest from hamcrest import * from vinyldns_python import VinylDNSClient def test_health(shared_zone_test_context): """ Tests that the health check endpoint works """ client = shared_zone_test_context.ok_vinyldns_client client.health()
import py import tox from tox.reporter import error, info, verbosity0, verbosity2, warning from tox.util.lock import hold_lock from .builder import build_package from .local import resolve_package from .view import create_session_view @tox.hookimpl def tox_package(session, venv): """Build an sdist at first call...
#!/usr/bin/python3 """ Class Primer contains all methods needed to get the primer the user needs. """ class Primer: def __init__(self): """\ Init method gathers the primer datafile and uses it in do_primerdict """ self.primerfile = "./deps/primer.data" self.primerdict = self.do_primerdict(self.primerfile) ...
#!/usr/bin/env python import xml.etree.ElementTree from conf import breathe_default_project, breathe_projects doxyxml_dir = breathe_projects[breathe_default_project] index_xml = '{}/index.xml'.format(doxyxml_dir) tree = xml.etree.ElementTree.parse(index_xml).getroot() with open('Structs.rst', 'w') as file: file...
def merge_dict_list(dst, src): stack = [(dst, src)] while stack: current_dst, current_src = stack.pop() for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if isinstance(current_src[key], dic...
from django.db import models # Create your models here. class TestPlan(models.Model): id = models.CharField(max_length=16, verbose_name='Test Plan ID', primary_key=True) name = models.CharField(null=True, max_length=100, verbose_name='Plan Name') comment = models.CharField(null=True, max_length=200...
from tqdm import tqdm import csv import logging import multiprocessing as mp import os import shutil import time import types from typing import List import warnings warnings.simplefilter(action='ignore', category=FutureWarning) from mpi4py.MPI import COMM_WORLD from mpi4py.futures import MPIPoolExecutor import gym i...
import math import random import cv2 import numpy as np from ..utils import * def seg_augmentation_wo_kpts(img, seg): img_h, img_w = img.shape[:2] fg_mask = seg.copy() coords1 = np.where(fg_mask) img_top, img_bot = np.min(coords1[0]), np.max(coords1[0]) shift_range_ratio = 0.2 down_shift...
from __future__ import print_function # to make sure print() on both python 2 and python 3 properly #declare two numbers number1 = 5 number2 = 10 #perform addition of two numbers answer = number1 + number2 #print answer print("Answer is:"+str(answer))
##Copyright (c) 2014 - 2020, The Trustees of Indiana University. ## ##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 a...
import requests import html2text as ht import time import os import json class dropin_wiki_detail(object): '''获取多频百科的某一词条的具体信息''' def wiki_spider(self, typeId, dataId): time.sleep(2.31) #http://duopin_app_api.hearinmusic.com/app/ency/encyDetail?typeId=13&dataId=377 url = 'htt...
from ibeatles.step1.plot import Step1Plot from ibeatles.utilities.retrieve_data_infos import RetrieveGeneralFileInfos, RetrieveSelectedFileDataInfos class Step3GuiHandler(object): def __init__(self, parent=None): self.parent = parent def load_normalized_changed(self, tab_index=0): ...
import discord from redbot.core import commands from .pcx_lib import type_message class bully(commands.Cog): #This Cog takes the previous message and turns it into CaMeL cAsInG @commands.command(aliases=["b"]) async def sarcasm(self, ctx: commands.Context): #Define the command for RedBot m...
#!/usr/bin/env python # # Usage: # CC6UL SBC with PCF8574 Multiplexer connected on I2C1 (pin 33, 34 of RGB connector) # import time import sys from subprocess import call CMD = "i2cset" # I2C-0 BUS = "%d" % 0 # address on bus is 0x38 ADDR = "0x%0.2X" % 0x38 DELAYSHORT = 0.060 DELAYMIN = 0.005 test = call(["which", ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 10 23:56:26 2021 @author: babraham """ import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go from plotly.subplots import make_subplots import os # ===========PLOTTING PROPERTIES/VARIABLES=================...
def dogcal (age): hum = age * 7 return hum age = int(input("Dog age?")) print(dogcal(age))
# -*- coding: utf-8 -*- import json import os import re import tempfile from hashlib import md5 from oslo.config import cfg from ping import quiet_ping from dnsdb.constant.constant import ZONE_MAP, VIEW_ZONE, NORMAL_TO_VIEW from . import commit_on_success from . import db from .models import DnsHeader from .models i...
from django.conf import settings from django.contrib.auth.backends import ModelBackend as BaseModelBackend from django.core.exceptions import ImproperlyConfigured from django.db.models import get_model class ModelBackend(BaseModelBackend): def authenticate(self, username=None, password=None): try: ...
import copy from django.utils.translation import ugettext_lazy as _ from mayan.apps.acls.links import link_acl_list from mayan.apps.documents.permissions import permission_document_view from mayan.apps.navigation.classes import Link from mayan.apps.navigation.utils import get_cascade_condition from .icons import ( ...
import sys from app import app # Init httplib2 import httplib2 h = httplib2.Http(".cache") # HTTP GET /vin:Winery url = "%svin:Winery" % app.REST_API_URL print "GET %s" % url resp, content = h.request(url, "GET") print content # Benchmark from time import time start = time() count = 80 for i in range(count): res...
import sugartensor as tf __author__ = 'namju.kim@kakaobrain.com' # # hyper parameters # latent_dim = 400 # hidden layer dimension num_blocks = 3 # dilated blocks # residual block @tf.sg_sugar_func def sg_res_block(tensor, opt): # default rate opt += tf.sg_opt(size=3, rate=1, causal=False, is_first...
from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") iris = datasets.load_iris() # loads as a Bunch, similar to a dictionary X = iris.data #...
"""Simulation of random streams of data. This module defines: - a generator object `data` modeling an infinite stream of integers - a function `make_finite_stream()` that creates finite streams of data The probability distribution underlying the integers is Gaussian-like with a mean of 42 and a standard deviation of ...
# Generated from /Users/nhphung/Documents/fromSamsungLaptop/Monhoc/KS-NNLT/Materials/Assignments/MC/MC1-Python/Assignment2/upload/src/main/mc/parser/MC.g4 by ANTLR 4.7.1 from antlr4 import * from io import StringIO from typing.io import TextIO import sys from lexererr import * def serializedATN(): with StringIO...
# MIT License # # Copyright (c) 2022 Quandela # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, pub...
import math import datetime import os import pandas import matplotlib.pyplot as plt import numpy import random from unityagents import UnityEnvironment import torch import torch.nn import torch.optim from collections import deque, namedtuple import click DEVICE = torch.device("cuda:0" if torch.cuda.is_available() els...
from flopy.mbase import Package class Mt3dPhc(Package): ''' PHC package class for PHT3D ''' def __init__(self, model, os=2, temp=25, asbin=0, eps_aqu=0, eps_ph=0, scr_output=1, cb_offset=0, smse=['pH', 'pe'], mine=[], ie=[], surf=[], mobkin=[], minkin=[], surf...
from logging import getLogger import numpy as np import pandas as pd logger = getLogger('predict').getChild('BaseDataTranslater') if 'ConfigReader' not in globals(): from ..ConfigReader import ConfigReader if 'LikeWrapper' not in globals(): from ..commons.LikeWrapper import LikeWrapper class BaseDataTransl...
# 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 matplotlib.pyplot as plt from pkg_resources import resource_filename from .analysis import model_history_plot, prediction_parity_plot from .augmentations import ( mixture_animation, prototypical_spectra_plot, single_source_animation, ) from .base import _colorbar, eem_plot from .preprocessing import...
import csv LINES_CSV = 'lines.csv' MVR_CSV = 'mvr.csv' OUT_CSV = 'out.csv' WORD_LEN = 4 INJURY_WORDS = ['injury', 'fatal', 'pi', 'homicide', 'death'] with open(OUT_CSV, 'w', newline='') as out_csvfile: fieldnames = ['svc_code', 'description', 'augusta_risk_type', 'bodily_injury'] writer = csv.DictWriter(out_...
import pytest import asyncio from async_generator import asynccontextmanager import ssz from p2p.peer import ( MsgBuffer, ) from eth2.beacon.types.blocks import ( BeaconBlock, ) from trinity.constants import TO_NETWORKING_BROADCAST_CONFIG from trinity.protocol.bcc.commands import ( BeaconBlocks, ) fro...
# Generated by Django 2.0 on 2019-01-31 07:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0050_auto_20190129_0808'), ] operations = [ migrations.AddField( model_name='projecttodoitem', name='personal_...
import threading class StoppableThread(threading.Thread): """ Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. """ def __init__(self, *args, **kwargs): super(StoppableThread, self).__init__(*args, **kwargs) self._stop_event =...
# Copyright 2021 Zilliz. 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 agree...
ACCESS_KEY = '@@{cred_aws.username}@@' SECRET_KEY = '@@{cred_aws.secret}@@' AWS_REGION = '@@{clusters_geolocation}@@' INSTANCE_ID = '@@{ec2_instance_id}@@' import boto3 boto3.setup_default_session( aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=AWS_REGION ) client = boto3.cli...
#!/usr/bin/env python3 import re MASK_RE = re.compile(r'mask\s*=\s*([01X]+)\s*$') MEM_RE = re.compile(r'mem\[(\d+)\]\s*=\s*(\d+)\s*$') zero_mask = 0 one_mask = 0 mem = {} with open('input.txt', 'r') as instructions: for inst in instructions: if inst.startswith('mask'): m = MASK_RE.match(inst...
import boto3 import botocore import os import sys from urllib.parse import unquote_plus import urllib.request import requests import json import datetime from pytz import timezone from dateutil import parser from requests.auth import HTTPBasicAuth try: requests.packages.urllib3.disable_warnings() except: pa...
""" PyRSM is a python package for exoplanets detection which applies the Regime Switching Model (RSM) framework on ADI (and ADI+SDI) sequences (see Dahlqvist et al. A&A, 2020, 633, A95). The RSM map algorithm relies on one or several PSF subtraction techniques to process one or multiple ADI sequences before computing a...
""" Blocks for noise processing """ import numpy as np from ... import read_config from ...preprocess.filter import butterworth from ...geometry import (n_steps_neigh_channels, order_channels_by_distance) from ...preprocess import standarize from . import util def covariance(recordings, temp...
import random import string from junit_xml import TestSuite, TestCase def rand_duration(): return random.randint(0, 120) + random.random() def rand_string(prefix, size=40): text = "".join( [random.choice(string.ascii_letters + ' ') for _ in range(size)]) return "{} {}".format(prefix, text) de...
import pytest from src.client import _Client @pytest.fixture def mock_config(): class Mock_Config: def __init__(self): self._data = {} def load(self, read_env_data=False): self._data = { "portal_user": "aperture", "portal_passwd": "dummy", ...
"""SynapsePay client library for the SynapsePay platform. This client library is designed to support the SynapsePay API for creating users, linking nodes (accounts), creating transactions between users, and adding subnets. Read more at https://docs.synapsepay.com """ from .client import Client from .api import Users,...
from .tep import * from .utils import * from .race_analysis import *
import cv2 from flask import Flask, request, make_response import base64 import numpy as np import urllib app = Flask(__name__) @app.route('/endpoint', methods=['GET']) def process(): image_url = request.args.get('imageurl') requested_url = urllib.urlopen(image_url) image_array = np.asarray(bytearray(req...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'JobQueueState', ] class JobQueueState(str, Enum): DISABLED = "DISABLED" ENABLED = "ENABLED"
import logging import pandas as pd import requests import redis from . import APP, RQ_CLIENT REDIS_CLIENT = redis.Redis(host=APP.config.get('REDIS_HOST'), db=0) GH_HEADERS = {'Authorization': 'token ' + APP.config.get('GITHUB_TOKEN', '')} # https://stackoverflow.com/questions/17622439/how-to-use-github-api-token-...