text
stringlengths
3.07k
12.6k
import pulseio from math import e, exp, pi, sin from kmk.extensions import Extension, InvalidExtensionEnvironment from kmk.keys import make_key class AnimationModes: OFF = 0 STATIC = 1 STATIC_STANDBY = 2 BREATHING = 3 USER = 4 class LED(Extension): def __init__( self, led_p...
# # Copyright (c) 2021, NVIDIA CORPORATION. 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 appl...
import requests from dotenv import load_dotenv from os import environ from terminaltables import AsciiTable def get_area_id_from_hh(area_name): area_url = 'https://api.hh.ru/areas' response = requests.get(area_url) response.raise_for_status() countries = response.json() for country in countr...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
# -*- coding: utf-8 -*- # # Copyright (c) 2020~2999 - Cologler <<EMAIL>> # ---------- # # ---------- import typing import xml.etree.ElementTree as et def filter_by_tag(tag): 'create a filter which filter by tag' return lambda x: et.iselement(x) and x.tag == tag class ElementsFilterProxy: __slots__ = ('...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Utility functions and classes """ from . import generators import os from . import config from .reg import Register from .enum import EnumValue from .bitfield import BitField from .regmap import RegisterMap from pathlib import Path def str2int(val, base=None): "...
from graph.graph import * import pytest # 1) Node can be successfully added to the graph ### # 2) An edge can be successfully added to the graph ### # 3) A collection of all nodes can be properly retrieved from the graph ### # 4) All appropriate neighbors can be retrieved from the graph ### # 5) Neighbors are re...
# Copyright (C) 2013 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
# coding=utf-8 """ plots.py Library for plotting functions """ import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.dates as mdates def read_meterconfig(ini_file, parameter): f1 = open(ini_file,"r") for line in f1.readlines(): line_list = line.split('=') ...
import logging from django.db import models from django.utils import timezone from django_celery_beat.models import IntervalSchedule, PeriodicTask from vanir.core.token.models import Coin, Token from vanir.plugins.models import PluginBase from vanir.plugins.new_coin_bot.choices import DiscoverMethod, ScheduleScrap, S...
import asyncio import collections import itertools import json import logging import secrets import signal import string import sys from .logger import ( logged, get_child_logger, ) Context = collections.namedtuple( 'Context', ['logger', 'metrics', 'raven_client', 'redis_client', 'session', 'es_semaphore...
# Authors: <NAME> <<EMAIL>> # # Copyright (c) Schneider Electric Industries, 2020. All right reserved. import sys import pytest from six import with_metaclass from valid8 import ValidationError from vtypes.core import VTypeMeta from vtypes import vtype, is_vtype, VType @pytest.mark.parametrize('val_to_test,valid_...
# -*- coding: utf-8 -*- """ Created on Thu Feb 17 09:50:31 2022 @author: gbournigal """ import streamlit as st import numpy as np import pandas as pd import plotly.express as px calificaciones = ["A", "B", "C", "D1", "D2", "E"] ## Aquí se definen las probabilidades de transición para cada calificación. ## Pueden ...
import json import pytricia from src.reader import FileReader from src.dl.download_zoom import ZoomCidrDownloader from src.pytrie_support import PytrieSupport from src.whois import whois def run_test(): # 128 bits needed for holding IPv6 pyt = pytricia.PyTricia(128) support = PytrieSupport() # read all the...
__author__ = 'thor' import re import pandas as pd import numpy as np import pickle import os import ut as ms # import ut.parse.html2text_formated as html2text_formated from pattern.web import plaintext import ut.pstr.trans from ut.semantics.termstats import TermStats from ut.slurp.yboss import Yboss class YbossText...
import csv from pprint import pprint import numpy as np from numba import njit, types, typed from time import time import sys from model.filters.boxed import Boxed @njit def _redmean(r1, g1, b1, r2, g2, b2): redAvg = (r1 + r2) / 2 return (2 + redAvg / 2) * (r2 - r1)**2 + (4 * (g2 - g1)**2) + (2+ (25...
""" This file has a JWT Implementation with encryption of Payload. Usage is so easy. You must provide ENCRYPT_PASSWORD and (optionally ENCRYPT_SALT) into the Sanic app config. >>> from sanic import Sanic >>> app = Sanic() >>> app.config.ENCRYPT_PASSWORD = "<PASSWORD>" >>> import sanic_jwt import AuthenticationEncrypt...
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np # 0: tokens, 1: pos, 2: mask_s, 3: labels class JointClassifier(nn.Module): def __init__(self, args, emb_matrix=None): super().__init__() self.args = args se...
import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from dash.dependencies import Input, Output, State import pandas as pd import pickle ########### Initiate the app external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__nam...
import tensorflow_federated as tff import tensorflow.compat.v1 as tf import numpy as np import os ### FL config BATCH_TYPE = tff.NamedTupleType([ ('x', tff.TensorType(tf.float32, [None, 784])), ('y', tff.TensorType(tf.int32, [None]))]) MODEL_TYPE = tff.NamedTupleType([ ('weights', tff.TensorType(tf.float3...
# -*- coding: utf-8 -*- from collections import defaultdict import os import json import _pickle as cPickle import zipfile import urllib.request import logging import tarfile import pathlib import time import re t = time.time() logging.basicConfig( level=logging.INFO, format="%(asctime)s %(module)s %(lineno)d ...
import os import cv2 from numpy.lib.function_base import average import argparse import numpy as np import os.path as osp from tqdm import tqdm from mtcnn.mtcnn import MTCNN def parse_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) defau...
import unittest import numpy as np import numpy.testing as npt from sparse_dot_mkl import dot_product_mkl from sparse_dot_mkl.tests.test_mkl import MATRIX_1, MATRIX_2, make_matrixes class TestDenseDenseMultiplication(unittest.TestCase): order = "C" double_dtype = np.float64 single_dtype = np.float32 ...
import logging import queue from Common import * logger = logging.getLogger(__name__) class Point: def __init__(self): self.x = 0 self.y = 0 def __init__(self, x, y): self.x = x self.y = y def move(self, roboDirection): dx = 0 dy = 0 if roboDirec...
# # Copyright 2013 Google 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...
import datetime import logging import re import threading import sys import warnings try: import Queue except ImportError: import queue as Queue import decorator import pytz TIMEZONE_REGEX = re.compile(r'([-+])(\d\d):?(\d\d)$') CACHED_TIMEZONES = {} LOGGERS = {} LOGGER_STDOUT_FORMAT = '[%(asctime)s] [%(n...
# Imported modules and functions import json import time import datetime import getJson as gJ import errors from sqlalchemy import create_engine # Open keys file to access API key with open("keys.json", "r") as keys_file: keys_handle = json.load(keys_file) def weather_scraper(): """Function to return data f...
# ANOTHER TEST WITH FIXED SEEDS ## Seed value ## Apparently you may use different seed values at each stage #seed_value= 1337 # ## 1. Set `PYTHONHASHSEED` environment variable at a fixed value #import os #os.environ['PYTHONHASHSEED']=str(seed_value) # ## 2. Set `python` built-in pseudo-random generator at a fixed value...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 14 12:53:46 2019 @author: ritikagupta """ import matplotlib.pyplot as plt from scipy import signal from scipy.io import wavfile import pandas as pd import os import numpy as np testData = pd.read_csv('data_speech_commands_v0.02/testing_list.txt', ...
from __future__ import unicode_literals from httplib import NO_CONTENT, BAD_REQUEST from django.conf import settings from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse from django.db.models import Count from django.contrib.auth import get_user_model from django.contrib.auth.deco...
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application, rationalize, \ convert_xor, parse_expr from PyQt5 import QtGui from pyqtgraph import setConfigOption, PlotWidget from re import compile, search from numpy import vectorize, arange, array from sympy import lambdify ...
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2013 <NAME>, Opera Software ASA # # 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...
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2018 DataONE # # Licensed under the Apache License, Version 2.0 (t...
import sys import yaml import argparse import datetime import traceback import subprocess from collections import deque from io import TextIOWrapper from concurrent import futures from typing import Dict from queue import Queue from pprint import pprint from reposync.validation import is_configuration_valid from repo...
# SPDX-License-Identifier: BSD-2-Clause import os import util from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QFileDialog from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QMessageBox from PyQt5.QtWidgets import QPushButton from...
from argparse import ( ArgumentParser, Namespace, ) from typing import ( Dict, Iterable, Optional, Tuple, ) import numpy as np import torch from torch import nn from utils.misc import ( optional_string, iterable_to_str, ) from .contextual_loss import ContextualLoss from .color_transfe...
""" Convert color to HEX code Support: RGB, CMYK, HSL, HSV Conversion translated from https://www.rapidtables.com/convert/color/ """ dec_hex_dict = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "A", 11: "B", 12: "C...
import sys import os import time import d3dshot import keyboard from PIL import Image import ffmpeg """ returns the platform. Possible values: Windows -> win32 """ def get_operating_system(): return sys.platform """ returns the path of the temporary directory for a specific platform. """ def get_parent_d...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
""" Algorithmic Thinking Project 4 Matching RNA or DNA sequences """ def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score): """ [Input] alphabet: set of characters diag_score: score for diagonal off_diag_score: score for not in diagonal dash_score: score for...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from erpnext.stock import get_warehouse_account, get_company_default_inventory_account class TestAccount(unittest.TestCas...
from __future__ import annotations import time from typing import List, TYPE_CHECKING import config import utils from utils.util import add_cmd if TYPE_CHECKING: from utils.database import SeenDB from zirc.event import Event from zirc.wrappers import connection_wrapper from bot import Bot ...
import re def is_payload_accept(data, filter_condition): if "regx" in filter_condition: pass else: keys_filter = filter_condition.keys() status_filter = True for k in keys_filter: try: array_conditons = filter_condition[k] if data[k]...
import argparse import glob import json import os import cc3d import cv2 import cyfusion import dt import deep_surfel as dsurf import numpy as np def sdf_from_depth(destination_path, depth_maps, Ks, Rs, Ts, cam2world, resolution, box_size): truncation_factor = 10 voxel_size = 1. / resolution truncation =...
"""Tests for functions in projects.py""" import tempfile import os import pytest import shutil ACTIVE_PROJECT = 'project1' pytestmark = pytest.mark.usefixtures('reset_projects_dir') @pytest.fixture() def init_project_to_add(request): base_path = os.path.dirname(os.path.realpath(__file__)) project_template...
"""Wonk data models.""" import copy import json import re from typing import Any, Dict, List, Set, Tuple, Union from .constants import ACTION_KEYS, JSON_ARGS, RESOURCE_KEYS, StatementKey Statement = Dict[str, Any] Policy = Dict[str, Any] class InternalStatement: """An intermediate representation of an AWS poli...
import logging import signal import os import json import subprocess import re import boto3 import requests os.environ['PATH'] = os.environ['PATH'] + ":" + os.environ.get('LAMBDA_TASK_ROOT', '.') + '/bin' LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) SUCCESS = "SUCCESS" FAILED = "FAILED" EXIT_SUCCESS =...
import asyncio import os import json import webbrowser import logging from autobahn.asyncio.websocket import WebSocketServerFactory, WebSocketServerProtocol class Sofi(object): def __init__(self): self.interface = SofiEventProcessor() self.server = SofiEventServer(processor=self.interface) d...
""" matlab_magic ============ Magic command interface for interactive work with Matlab(R) via the pymatbridge """ from shutil import rmtree import numpy as np import IPython from IPython.core.displaypub import publish_display_data from IPython.core.magic import (Magics, magics_class, ...
import os import operator import subprocess import multiprocessing from .. utils import * from .. process import * from .. task import * from .. package import * __all__ = ["BCL2FastQ"] class BCL2FastQ(Process): Command = "bcl2fastq" Arguments = [ ProcessArgument(name="min_log_level", argument="-l", ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License...
from competition_and_mutation import Competition, MoranStyleComp, normal_fitness_dist, uniform_fitness_dist from colourscales import get_colourscale_with_random_mutation_colour import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np def example1(): # Run a single simulation of algorithm 1 ...
from collections import defaultdict from urllib import parse from http import HTTPStatus, cookies import uuid from aenum import extend_enum from waspy import exceptions from waspy.parser import parsers from .router import Methods extend_enum(HTTPStatus, 'INVALID_REQUEST', (430, 'Invalid Request', ...
from typing import Union, List, Callable, Dict, Tuple, Optional, Any, Type, Iterable from .util import recurse_dict, pop_if def extract_definitions(paths: Dict[str, Any], missing: List[type]) -> Dict[str, Any]: """Extract `definitions` from generated openAPI spec for :mod:`flask` app endpoints. Args: ...
from .meta import Meta, MetaFilter, metapreparemethod # find(): 找出文档中所有的书签 # replace(): 对[@xxx]这样的写法引用书签 # 可以实现对标题编号的引用 # 引用嵌套采用域代码的形式进行引用,不在这里处理 # 写代码记得写注释!!! import panflute as pf def refNumStr(citationId: str): return pf.RawInline(f'<w:fldSimple w:instr=" REF {citationId} \\r \\h \\t "/>', ...
import os import meetup.api import json, csv import requests import datetime import urllib from datetime import datetime from datetime import timedelta from PIL import Image from PIL import ImageFont from PIL import ImageDraw #--------------------- # Function Definitions #--------------------- def getEventFromURL(url...
#!/usr/bin/env python3 """jello - query JSON at the command line with python syntax""" import os import sys import textwrap import json import signal from contextlib import redirect_stdout import io import ast __version__ = '0.3.1' def ctrlc(signum, frame): """exit with error on SIGINT""" sys.exit(1) def ...
import numpy as np from scipy.special import sph_harm # calcualte coordinates with SH expansion def sph2cart(coeff, phi, theta): x = 0 y = 0 z = 0 index = 0 for n in range(9): order = [*range(-n,n+1)] for m in range(2*n+1): x += coeff[index,0]*sph_harm(order[m], n, theta...
import pandas as pd import datetime import pymmwr as pm ''' Get the epidemiological year, week and date of a given date. ''' def get_epi_data(date): # The format format_str = '%Y-%m-%d' dt = datetime.datetime.strptime(date, format_str).date() epi = pm.date_to_epiweek(dt) return e...
#!/usr/bin/env python """ ############################################################################# Copyright : (C) 2017 by Teledomic.eu All rights reserved Name : timon.commands Description : cli entry for timon entry point for timon command line tool #######################################################...
## little game where random letters in words ## are greyed out and the child has to ## write in the correct letter ## easiest levels are only lowercase ## harder letters use capitals import sys import pygame import random score=0 level=0 width=640 height=480 lettersToGreyOutCount=1 greyed=[] ## array with 1 wh...
""" Module for testing the ChangeLog class. """ class TestChangeLog01: def test_changelog01m01(self): """ Unit test method (make linter happy) """ from gatenlp.document import Document, OFFSET_TYPE_JAVA from gatenlp.changelog import ChangeLog from gatenlp.offsetmap...
import pprint import re from collections import defaultdict from obo import Ontology, TermSubset, SynonymType, SynonymScope, Definition, XRef from obo.stanzas import Term, Instance, Stanza, Typedef, Relationship class ParseException(Exception): def __init__(self, message, value=None): super().__init__(':...
from django.shortcuts import render from django.views.decorators.http import require_GET,require_POST from django.views.generic import View from apps.news.models import NewsCategory,News,Comment from utils import restful_res from django.views.decorators.http import require_POST,require_GET from .forms import WriteNewsF...
import math import time PI = 3.141592653589793 # math.pi sin = math.sin cos = math.cos tan = math.tan asin = math.asin atan = math.atan2 acos = math.acos rad = PI / 180.0 e = rad * 23.4397 # obliquity of the Earth dayMs = 1000 * 60 * 60 * 24 J1970 = 2440588 J2000 = 2451545 J0 = 0.0009 times = [ (-0.833,...
""" A module for manipulating images. """ from __future__ import annotations from typing import List from enum import Enum import numpy as np import PIL.Image import PIL.ImageDraw import PIL.ImageOps IMAGE_WIDTH = 64 """A default image width.""" IMAGE_HEIGHT = 64 """A default image height.""" IMAGE_CHANNELS = 3 ""...
import radiotap as r def test_ac_rate_1(): """ Frame 1: 4865 bytes on wire (38920 bits), 188 bytes captured (1504 bits) Radiotap Header v0, Length 38 Header revision: 0 Header pad: 0 Header length: 38 Present flags MAC timestamp: 270036265 Flags: 0x40 Channel frequency: 5180 [A 36] ...
# -*- coding: utf-8 -*- # Copyright © 2018, 2019 <NAME> <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for # any purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS...
""" Cyber Observable Expression 2.1 definitions Selected CybOX 2.1 objects used by OpenC2. Abstract syntax information extracted from XSD source documents. """ __version__ = "0.1" __meta__ = { "namespace": "http://cybox.mitre.org/objects", "sources": {"HostnameObject": "Hostname_Object.xsd", ...
from typing import Optional, Union import numpy as np import gym import optuna from stable_baselines3.common.callbacks import BaseCallback, EvalCallback from stable_baselines3.common.vec_env import VecEnv class ExtendedEvalCallback(EvalCallback): """ Extends Eval Callback by adding a new child callback calle...
from django.http import HttpResponseRedirect from django.shortcuts import render from . import forms import json from main_app import crawler, runner from io import StringIO from django.http import JsonResponse import logging import getpass logger = logging.getLogger("django") # Create your views here. def index(requ...
"""Test module for imager profile app.""" import tempfile from django.conf import settings from django.core.files import File from django.core.files.uploadedfile import SimpleUploadedFile as Sup from django.test import Client from django.test import TestCase import factory from imager_images.forms import NewAlbumFor...
import numpy as np from enum import Enum import heapq class CustomerTypes(Enum): Innovator = 99 Early_Adopter = 96.5 Early_Majority = 83 Late_Majority = 49 Laggard = 15 class Product(object): def __init__(self): self.version = 0 self.price = np.infinite self.innovatio...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #encoding=utf-8 from selenium import webdriver import requests from bs4 import BeautifulSoup import time import random import os import re from requests.packages import urllib3 # 建立一个目录 de...
import os, sys, pickle, json, argparse from matplotlib import pyplot as plt import matplotlib matplotlib.use('svg') import seaborn as sns import numpy as np import pandas as pd parser = argparse.ArgumentParser() parser.add_argument('-i', type=str, default='/tmp/out.pkl', help='pd dataframe dumped by gather-cubic.py')...
# -*- coding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1428210864.385142 _enable_loop = True _template_filename = '/Users/Nate/chf_dmp/catalog/templates/event.html' _template_uri = 'event.html...
#! /usr/bin/env python3 """ You have five coins, with these chances of heads: 1: 0% 2: 25% 3: 50%: 4: 75% 5: 100% Pick a coin at random, keep flipping 1. If you get heads, what is the chance it is coin X? 2. If you get heads on flip 1, what is the chance of heads on flip 2? 3. If the first head is on flip 5, what is...
# !/usr/bin/python """ Copyright ©️: 2020 Seniatical / _-*™#7519 License: Apache 2.0 A permissive license whose main conditions require preservation of copyright and license notices. Contributors provide an express grant of patent rights. Licensed works, modifications, and larger works may be distributed under differe...
"""Core entities: base classes and full implementations.""" # TODO: Some of the docstrings parts should be moved to docs. # TODO: Add logging. # TODO: Fix snippet formatting in docstrings. from typing import TypeVar, Dict, Optional, Union from pydantic import BaseSettings from nodzz.basic_types import JSONType, JSON...
import matplotlib.pyplot as plt import matplotlib.animation as anim from matplotlib.offsetbox import AnchoredText import time as tim import numpy as np import math as mth ''' def calculateCumOccupancy(results): occupancySum = [0] for i in range(1,len(results[2])): occupancySum.append((occupancySum[i-1]*...
import csv import cv2 import os from os import path import random from datetime import datetime from keras import backend as K from keras.layers import Activation, Bidirectional, Conv2D, Dense, LSTM, Input, Lambda, MaxPooling2D, Reshape from keras.models import Model from keras.preprocessing import sequence import num...
"""Optimisation module""" # Authors: <NAME> <<EMAIL>> # License: BSD (3-clause) import time import numpy as np from .loss_grad import _grad_u_k def cdclinmodel( u0, constants=dict(), max_iter=100, early_stopping=False, eps=np.finfo(np.float64).eps, obj=None, benchmark=False): """ Coordinate desc...
import asyncio import json import typing as t from urllib.parse import urljoin import signal import aiohttp from . import exceptions class Response(t.NamedTuple): content: bytes status: int def _exit_handler( sig_num: 'signal.Signals', flag: t.List[bool], consumer: 'KafkaBridgeConsumer' ) -> N...
import socket import subprocess from queue import Empty, Queue from threading import Thread from time import sleep from typing import List, Tuple import docker from hurricane.testing.actors import TestPublisher class HurricaneBaseDriver(object): proc = None log_lines = [] base_command = [] coverage_...
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from sklearn.utils import shuffle from facial.util import getImageData, error_rate, init_weight_and_bias, y2indicator from facial.ann_tf import HiddenLayer # image dimensions are expected to be: N x width x height x color # filter shapes are ...
import urllib.request import os from pathlib import Path import requests import json def http_download_file_list(links_to_file_list, **kwargs): """ Downloads a list of files from the flat Iron from a list of links. Same options behaviour as http_download_file :param links_to_file_list: list of http l...
import re from contextlib import ExitStack from . import GroupParameterItem from .basetypes import GroupParameter, Parameter, ParameterItem from .qtenum import QtEnumParameter from ... import functions as fn from ...Qt import QtCore from ...SignalProxy import SignalProxy from ...widgets.PenPreviewLabel import PenPrevi...
# coding: utf-8 import sys, time from pymodbus.client.sync import ModbusSerialClient # code for a decorator that put a try catch around the function # the idea is to return True if everything is fine or the error message otherwise def trycatch(func): errors = (Exception, ) def wrapper(*args, **kwargs): ...
import pandas as pd from bokeh.layouts import row, widgetbox from bokeh.models import Select from bokeh.palettes import Category20c from bokeh.plotting import curdoc, figure from bokeh.models import HoverTool from bokeh.models import ColumnDataSource """ To run within CMD: bokeh serve --show bokehServ...
# Snake game import pygame from pygame.locals import * from pygame import mixer import time import random # Size of block of snake and to update length SIZE = 40 # Define apple class Apple: # Default call def __init__(self, parent_screen): self.parent_screen = parent_screen ...
#!/usr/bin/env python import sys from icecube import clsim, icetray, dataclasses # skip out if I3CLSimServer was not built try: clsim.I3CLSimServer except AttributeError: sys.exit(0) import time import tempfile from multiprocessing import Process try: # PY2 from Queue import Queue except ImportError: ...
from utils.url import URL from utils.http import get_html from utils.excel import ExcelConvertible, to_excel from utils.pool import distribute_work from bs4 import BeautifulSoup import re class TabelogURL(URL): def __init__(self, ken, city, page): """ :param ken: :type ken: str :p...
import socket import struct import select import msg_pb2 FRAME_HEAD_FORMAT = 'IIII' FRAME_HEAD_BYTES = 4*4 MSG_CMD_FORMAT = 'H' MSG_CMD_BYTES = 2 def MSG_GET_CMD_RESPONS(cmd): return cmd | 0x8000 def printFrameHead(frame_head): print(f"frame_len: {frame_head['frame_len']}, " f"frame_idx:...
from unicodedata import category from django.core.management.base import BaseCommand, CommandError from workflows.models import Category, AbstractWidget, AbstractInput, AbstractOutput, AbstractOption from django.core import serializers from optparse import make_option import uuid class Command(BaseCommand): ...
import torch from .base import Manifold import geoopt.linalg.batch_linalg __all__ = [ "Sphere", "SphereSubspaceIntersection", "SphereSubspaceComplementIntersection", ] class Sphere(Manifold): r""" Sphere manifold induced by the following constraint .. math:: \|x\|=1 """ nd...
"""Read public data source, load as BigQuery table.""" import configparser import itertools import logging import logging.handlers import math import multiprocessing import os import pathlib import sys import time from types import SimpleNamespace import geopandas import numpy import pandas import hexpop def parse_...
import numpy as np import numba as nb from optfolio.utils import is_close_to_zero @nb.jit(nopython=True) def non_dominated_fronts(return_obj : np.ndarray, volatility_obj: np.ndarray, constraints_val : np.ndarray) -> (np.ndarray, np.ndarray): domination_counts = np.zeros(len(return_obj), dtype=np.int32) domin...
# -*- coding: utf-8 -*- # # Copyright © Autogator Project Contributors # Licensed under the terms of the MIT License # (see autogator/__init__.py for details) import os os.environ['PATH'] = "C:\\Program Files\\ThorLabs\\Kinesis" + ";" + os.environ['PATH'] import atexit import pyvisa as visa import VISAresourceExtenti...
import os import platform import shutil import subprocess import sys def parse_argv(): options = {} options['build'] = False options['clean'] = False options['test'] = False options['use_avx'] = False options['compiler'] = None options['config'] = 'Release' options['cpu'] = 'x64' for i in range(1, len(sys.ar...