text
stringlengths
3.07k
12.6k
from __future__ import absolute_import import os,sys import numpy as np from Bio.PDB.Polypeptide import is_aa from computeFeatures.structStep.myPDBParser import myPDBParser as PDBParser from ..StructFeatComputer import StructFeatComputer from utils import myMakeDir, tryToRemove #utils is at the root of the package c...
#!/usr/bin/env python3 import yaml import glob from jinja2 import Template from os.path import basename, splitext from subprocess import check_output from collections import defaultdict def convert_markdown_to_tex(markdown): return check_output( ["pandoc", "--from=markdown", "--to=latex"], univer...
import PIL import markdown from django.db import models from django.utils.text import slugify # $1 USD in other currencies TO_USD = { "EUR": 0.82, "SGD": 1.33, "AUD": 1.3, "USD": 1.0, "RMB": 6.48, "INR": 73.0, "GBP": 0.73, "CHF": 0.89, "HKD": 7.75, "CAD": 1.27 } CURRENCY_SYMBOL...
import numpy as np import scipy.signal import torch import torch.nn as nn from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence def combined_shape(length, shape=None): if shape is None: return (length,) return (length, shape) if np.isscalar(shape) else (length, *shape...
import tensorflow as tf import numpy as np """ The file is the implementation of the VGG-16 neural network """ NUM_LABELS = 25 def get_weights(shape, regularizer): weights = tf.get_variable('weights', shape=shape, initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.ad...
import os import sys import argparse import numpy import json import pprint import subprocess import errno import socket import serial import time from datetime import datetime from collections import OrderedDict # IoT2 imports import iot2_settings import setup_result_collection import iot2_measure_static_flash_and_ra...
# mypy: ignore-errors import abc from typing import Iterator, Mapping, Sequence, Tuple, Optional, List from typing import TypeVar from sortedcontainers import SortedDict E = TypeVar("E") # element class CumSequence(Sequence[E]): """ ABC for Cumulative max/min sequences that efficiently store cumulative min/...
from docx import Document import aspose.words as aw from docx.enum.text import WD_BREAK from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Inches from volume_meter import * from docx2pdf import convert def create_qa(self): # Table data in a form of list print(self.qa); data...
import datetime import fnmatch import regex from merc import errors from merc import util class ChannelUser(object): def __init__(self, channel, user): self.channel = channel self.user = user self.is_voiced = False self.is_halfop = False self.is_operator = False self.is_admin = False s...
''' functions to add derived metrics to the dictionaries of metrics please use the examples to add more Existing list of prewritten metrics: add_IPC(metrics) - Instructions per Cycle add_CPI(metrics) - Cycles per instruction add_VIPC(metrics) - vector instructions per cycle...
import pandas as pd import numpy as np import logging logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s') def read_csv_chunks_simple(file, passed_df=None, join_how='inner', sep=',', chunksize=10000, dtype=None, index_col=None): temp_df = pd.DataFrame() if passed_df i...
""" Various tests that a triangulation must past to be a valid toroidal 1+1d simplicial manifold.""" from itertools import combinations from collections import defaultdict from cdtea import simplicial from cdtea.util.triangulation_utils import time_sep # These tests assume 1+1d with toroidal topology def twice_as_m...
import pandas as pd import numpy as np from statsmodels.distributions.empirical_distribution import ECDF from matplotlib import pyplot as plt import json from ai4netmon.Analysis.bias import bias_utils as bu ## data parameters CDF_features = ['AS_rank_numberAsns', 'AS_rank_numberPrefixes', 'AS_rank_numberAddresses','AS...
# Copyright 2021 Condenser Author 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...
#!/usr/bin/env python from __future__ import print_function from soma import aims import numpy as np import glob import os import json def get_scale(img, divisions=21, x_shift=-5): y = [img.getSize()[1] * ((float(i) + 0.5) / divisions) for i in range(divisions)] x = x_shift if x < 0: x ...
""" A module for plotting candlesticks """ import pandas as pd from pyalgotrading.constants import PlotType def import_with_install(package_import_name, package_install_name=None, dependancies=()): """ Helps import 'package' even if its not installed. If package is installed, it will be imported and ret...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `fpipy.raw` module.""" import numpy as np import xarray as xr import xarray.testing as xrt import fpipy.raw as fpr import fpipy.conventions as c from fpipy.raw import BayerPattern def test_read_calibration_format(calib_seq): assert type(calib_seq) is x...
# -*- coding: utf-8 -*- import cv2 import os import dlib from scipy import misc import numpy as np from PIL import Image def getBound(img, shape): xMin = len(img[0]) xMax = 0 yMin = len(img) yMax = 0 for i in range(shape.num_parts): if (shape.part(i).x < xMin): x...
from rpython.rlib.objectmodel import we_are_translated from rpython.rlib.rarithmetic import maxint from rpython.rtyper.lltypesystem import lltype, rffi from pypy.interpreter.error import OperationError, oefmt from pypy.module._hpy_universal.apiset import API @API.func("HPy HPyLong_FromLong(HPyContext *ctx, long value...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import glob import json import argparse import Adafruit_DHT from datetime import datetime from inky import InkyPHAT from PIL import Image, ImageDraw, ImageFont from font_fredoka_one import FredokaOne try: import requests except ImportError: exit("This sc...
import tensorflow as tf import numpy as np import os import sys import time import cv2 from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image # Helper code def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(ima...
import flask import numpy as np import os import requests import sys from cv2 import cv2 as cv from socket import AF_INET, SOCK_DGRAM, INADDR_ANY, IPPROTO_IP, IP_ADD_MEMBERSHIP, SOL_SOCKET, SO_REUSEADDR, socket, inet_aton, error as socket_error import struct from threading import Thread import imagehash from PIL import...
# SPDX-License-Identifier: Apache-2.0 # Copyright 2021 EPAM Systems """ Wrappers for yaml.Node that provide better API """ from typing import Optional, List, Tuple, Iterator, Union from yaml.nodes import MappingNode, ScalarNode, SequenceNode, Node from yaml.constructor import SafeConstructor from yaml.representer imp...
# Copyright (c) 2013,2014 <NAME> # 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 follo...
#!/usr/bin/env python import argparse import csv import logging import sys from itertools import chain from pathlib import Path logger = logging.getLogger() def parse_args(args=None): Description = "Create samplesheet with FTP download links and md5ums from sample information obtained via 'sra_ids_to_runinfo....
from datetime import datetime from pathlib import Path from qcpump.pumps.base import STRING, BasePump, DIRECTORY, BOOLEAN, MULTCHOICE from qcpump.pumps.common.qatrack import QATrackFetchAndPostTextFile, QATrackFetchAndPostBinaryFile class BaseQATrackGenericUploader: TEST_LIST_CONFIG = { 'name': "Test L...
from decimal import Decimal import operator _MININT = -(2 ** 64 - 1) _MAXINT = 2 ** 64 - 1 class Metadata(dict): """ Represents Cardano transaction metadata. Inherits from :class:`dict` but passes all keys and values through validity check. :param mapping: a sequence of (key, value) pairs ...
import numpy as np import numba as nb from Bio import pairwise2 from Bio.Seq import Seq from Bio.SubsMat import MatrixInfo from Bio.Alphabet import generic_dna from Bio import SeqUtils def initialStep(V0, V1, InSeq, In, M, Dir, isLocal = False): d = 8 for i in range(V0.shape[0]): top = np.iinfo(np.int1...
from typing import List, Dict, Callable, Tuple from math import sqrt import random import gym from regym.rl_algorithms.MCTS.selection_strategies import UCB1, PUCT from regym.rl_algorithms.MCTS.simultaneous_open_loop_node import SimultaneousOpenLoopNode from regym.rl_algorithms.MCTS.util import random_rollout_policy ...
#!/usr/bin/env python # encoding: utf-8 """ """ from common.decorators import exception_wrapper __author__ = 'adonis' import re import httplib import urllib import web import requests import requests_unixsocket import logging from teslafaas.common.const import ALL_HEADERS, NON_WSGI_HEADER from teslafaas.common.util_...
import numpy as np from IMLearn.learners.classifiers import Perceptron, LDA, GaussianNaiveBayes from typing import Tuple from utils import * from os import path import plotly.graph_objects as go from plotly.subplots import make_subplots from matplotlib import pyplot as plt from math import atan2, pi def load_dataset...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Configurations of the analysis.""" import yaml __all__ = [ 'parse_config' ] DEFAULT_MAP_CONFIG = { # About radial bins 'rad': { 'n_rad': 18, 'r_min': 0.5, 'r_max': None, 'linear': False, }, 'detect': { 'threshold': 1e8, 'bkg_ratio':...
import os, hashlib, binascii as ba import base64, re import time, math from colors import * # from functools import lru_cache from numba import jit from cachetools.func import * from cachy import * def iif(a,b,c):return b if a else c import json def obj2json(obj): return json.dumps(obj, ensure_ascii=False, sort_...
import pickle import numpy as np import pygame from time import sleep #Duplicate of the Arduino map function (needed for processing autoencoder data) def map(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min class number: def __init__(self, imag...
# Copyright 2018 Blade Team of Tencent. 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 applicab...
""" Support for Mongoengine ODM. .. note:: Support for Mongoengine_ is in early development. :: from mixer.backend.mongoengine import mixer class User(Document): created_at = DateTimeField(default=datetime.datetime.now) email = EmailField(required=True) first_name = StringField(max_l...
import json import os # Parse ISO date import dateutil.parser as dapa import pandas as pd from matplotlib import pyplot as plt import numpy as np strategy_indices = { 'FIXED': 0, 'OPTIMIZED': 1, 'FINED': 2 } strategy_labels = { 0: 'FIX({} ,{})', 1: 'OPT({}, {})', 2: 'FIN({}, {})' } legend_la...
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import spi, sensor from esphome.const import ( CONF_CURRENT, CONF_ID, CONF_POWER, CONF_VOLTAGE, UNIT_VOLT, UNIT_AMPERE, UNIT_WATT, DEVICE_CLASS_POWER, DEVICE_CLASS_CURRENT, DEVICE_CLASS_VO...
from itertools import groupby # If you have problems with 'rufv' show=True, # enable the console compatbility mode to use # more common characters. compat = False if compat: vbar = '|' hbar = '-' intersection = '+' else: vbar = '│' hbar = '─' intersection = '┼' def ruf(pol, x): """For th...
# coding=utf-8 """ All commands that create & use the local copies of the Google Calendar data. """ from __future__ import absolute_import, print_function import requests from icalendar import Calendar from ..config import config, ICAL_PATH from ..utils import nice_format from .parser import subparsers import six f...
import xml.dom.minidom doc = xml.dom.minidom.parse("mqtt_topic.xml") file = open("mqtt_topic.py", "w+") def get_childnode(node): childs = [] for n in node.childNodes: if type(n) == xml.dom.minidom.Element: childs.append(n.tagName) return childs def print_subscribe_all(node, parent_n...
"""Generic Rest Adapter datatype representation and management The generic rest adapter "types" differ from the types used in the designer. """ from typing import Optional, Dict, Union, Type, Any from enum import Enum import json import logging from pydantic import create_model # pylint: disable=no-name-in-module...
import click import os import pandas as pd import torch import logging import random import numpy as np import logging import ray from itertools import tee import pickle from sklearn.metrics import roc_auc_score, precision_recall_curve, auc from ray import tune from ray.tune import track from ray.tune.suggest.ax import...
''' Tools for generating fractals. <NAME>, 2019 ''' import numpy; import os; import numba; MAX_ITERATIONS=1000 NEXT_PLOT_NUM=0 # Wether or not to output information to the terminal when running. PRINT_MESSAGES=True # Have constantly updating filename def NEXT_PLOT(suffix=''): global NEXT_PLOT_NUM NEXT...
""" Integrated gradient saliency maps Created on 04/30/2020 @author: RH """ import saliency import os import sys import cv2 import numpy as np import tensorflow as tf import data_input2 as data_input # image to double def im2double(im): return cv2.normalize(im.astype('float'), None, 0.0, 1.0, cv2.NORM_MINMAX) ...
from os.path import join, abspath, dirname from nose.tools import raises from indra.statements import Complex, Phosphorylation from indra.sources import hprd test_dir = join(abspath(dirname(__file__)), 'hprd_tests_data') id_file = join(test_dir, 'HPRD_ID_MAPPINGS.txt') def test_process_complexes(): cplx_file ...
# Copyright (c) 2018 Spotify AB # # 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...
"""Mixins for reducing the amount of boilerplate in the main wrapper class.""" import gtwrap.interface_parser as parser import gtwrap.template_instantiator as instantiator class CheckMixin: """Mixin to provide various checks.""" # Data types that are primitive types not_ptr_type = ['int', 'double', 'bool...
# -*- coding:utf-8 -*- # author: gfjiangly # time: 2019/5/6 18:40 # e-mail: <EMAIL> # software: PyCharm """ General Dataset Classes """ import random import torch import torch.utils.data as data import cv2 import numpy as np class AnnotationTransform(object): """Transforms a ELEVATOR annotation into a Tensor of b...
'''interface with serlib.cparser module We'll use platform defined C-types int (np.intc) and long long int (np.ulonglong) for maximal portability because python C-api does not support fixed width C types: https://docs.python.org/3/c-api/long.html For numpy reference see https://numpy.org/devdocs/user/basics.types.html...
# MIT License # # Copyright (c) 2020 <NAME> # # 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,...
from unittest.mock import patch from pytest import mark @mark.parametrize('return_code, pretend, world', [(b'0', False, False), (b'0', True, False), (b'0', True, True), (b'1', False, False), (b'1', False, True), (b'1'...
import os import cv2 import time from . import darknetanpr as darknet import imutils, imagezmq def convertBack(x, y, w, h): xmin = int(round(x - (w / 2))) xmax = int(round(x + (w / 2))) ymin = int(round(y - (h / 2))) ymax = int(round(y + (h / 2))) return xmin, ymin, xmax, ymax def cropDetected(det...
import re from datetime import datetime from typing import Any from SlyAPI import * from SlyAPI.oauth1 import OAuth1 from .twitter_upload import Media, TwitterUpload from .common import make_with_self RE_TWEET_LINK = re.compile(r'https://twitter\.com/(?P<user>[a-z0-9_]+)/status/(?P<tweet_id>\d+)', re.IGNORECASE) RE_U...
#!/usr/bin/env python """ @author: <NAME> """ from spatialmath import SE3 from spatialmath.base.argcheck import getvector from spatialmath.base import r2q import numpy as np import copy _mpl = False try: from matplotlib import colors as mpc _mpl = True except ImportError: # pragma nocover pass CONST_...
import random import csv from typing import Iterator, Union, List from torch.utils.data.sampler import Sampler import numpy as np from ..datapaths import DATAPATHS_MAPPING class LengthTrainSampler(Sampler): def __init__( self, source: str, field: str, max_len: float, # 16K * 320...
"""Mercado Bitcoin's Trade API implementation. For more information about data structure, methods and stuff, go to https://www.mercadobitcoin.com.br/trade-api """ import requests import hashlib import urllib import hmac import json import time from random import randint from .labels import Coin, Url, Method class...
#!/usr/bin/python # encoding=utf8 update_settings = { 'github_slug': 'mutdmour/alfred-workflow-cheatsheet', } import sys import os from workflow import Workflow, ICON_INFO, ICON_WARNING import cPickle wf = None log = None apps = None custom = None nothing_found_error_text = 'Nothing found' app_icons_dir = os.p...
class Client: tree_header = ['Nombre', 'Apellidos', 'DNI', 'Tlf 1', 'Tlf 2', 'e-mail', 'ID Cliente', 'Importe', 'Observaciones'] default_header_map = [1 for _ in tree_header] default_header_map[tree_header.index('ID Cliente')] = 0 default_header_map[tree_header.index('Observaciones')] = 0 def __ini...
# -*- coding: utf-8 -*- import os import click import logging import requests from tqdm import tqdm from requests.adapters import HTTPAdapter from multiprocessing import Queue from multiprocessing import Manager from multiprocessing import Pool as ProcessPool from multiprocessing.pool import ThreadPool from six.moves...
# sphinx_gallery_thumbnail_number = 4 from __future__ import absolute_import from . import _graph as __graph from ._graph import * from .. import Configuration from . import opt from . opt import multicut from . opt import lifted_multicut from . opt import mincut from . opt import minstcut import numpy from functool...
""" The filehelp-system allows for defining help files outside of the game. These will be treated as non-command help entries and displayed in the same way as help entries created using the `sethelp` default command. After changing an entry on-disk you need to reload the server to have the change show in-game. An file...
import discord from discord.ext import commands,tasks import datetime import math import random from discord.ext.commands.errors import CommandNotFound import youtube_dl from discord_minesweeper import * recomendacoes = [] with open('lista_de_filmes.txt','r') as recomendacao: for linha in recomendacao: re...
# GUI Application automation and testing library # Copyright (C) 2006 <NAME> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at your optio...
import glob import logging import os from math import ceil from typing import Dict, List, Tuple import luigi import numpy as np from luigi.util import common_params, inherits, requires from netCDF4 import Dataset, Group, Variable from scipy import linalg from iasi.composition import Composition, CompositionException ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 11 20:21:34 2020 @author: nickcostanzino """ def NN_structure(layers, perceptrons): A = list() for n in range(layers): A.append(perceptrons) return tuple(A) def NN_structures(layers, perceptrons): A = list() for i ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 25 14:36:02 2021 @author: endocv202<EMAIL> """ # import network import os import os.path as osp import argparse import numpy as np import torch import torch.nn as nn from PIL import Image import skimage from skimage import io from skimage.transfor...
#!/usr/bin/env python """This is the module that holds the GUI for the Activity Logger. Classes: ActivityLoggerGUI: The class for the GUI for the Activity Logger. You have to create an instance (no arguments taken) and then call show() on it to show the window. Functions: show_window() -> No...
import os from datetime import datetime from src.domain.model_couple import solve_couples from src.services.csv_reader import CsvReader from src.domain.solver import solve_routes ### Should # HOTELS_DATA_FILE = os.path.join(os.path.dirname(__file__), '..', 'data', 'hotels-generalites.csv') # EMPLOYEES_DATA_FILE = os...
import copy import torch from corgie import constants, exceptions from corgie.log import logger as corgie_logger from corgie.boundingcube import BoundingCube from corgie.layers.base import register_layer_type, BaseLayerType from corgie import helpers class VolumetricLayer(BaseLayerType): def __init__(self, data...
""" Utilities, ... Some stuff is likely not needed, and will be pruned, later... """ import re import os import sys import random from itertools import tee import requests # import contextily as ctx from geographiclib.geodesic import Geodesic from geopy.geocoders import Here from geopy.distance import geodesic from ...
#!/usr/bin/env python # # util.py # # Utility classes # # Copyright 2017 <NAME> # COBHUNI Project, Universität Hamburg # # 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.a...
# encoding: utf-8 from datetime import date, datetime, time import motor.motor_asyncio import numpy as np import pandas as pd from dateutil.relativedelta import relativedelta from rqalpha.const import INSTRUMENT_TYPE from rqalpha.model.instrument import Instrument from rqalpha.utils.datetime_func import convert_date_t...
import itertools import logging import os import geopandas as gpd import numpy as np import pandas as pd import tqdm from scipy.spatial import KDTree from shapely.geometry import LineString, Point, Polygon from delft3dfmpy.converters import hydamo_to_dflowrr from delft3dfmpy.core import checks, geometry from delft...
import numpy as np import matplotlib.pyplot as plt from gym.spaces import Discrete, Box from tfg.games import GameEnv, WHITE, BLACK class ConnectN(GameEnv): def __init__(self, n=4, rows=6, cols=7): if rows < n and cols < n: raise ValueError("invalid board shape and number to connect") ...
# further developed by <NAME>, <NAME>, <NAME> and <NAME> import random import sort_task_set import math import numpy import task USet=[] PSet=[] possiblePeriods = [1, 2, 5, 10, 50, 100, 200, 1000] def init(): global USet,PSet USet=[] PSet=[] def taskGeneration_rounded( numTasks, uTotal ): random.se...
import datetime import time class Hash_Logging_Object(object): def __init__( self, handlers,logging_key,depth): self.handlers = handlers self.logging_key = logging_key self.depth = depth self.handler = self.handlers[logging_key] #self.handler.delete_all() # useful...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Lingaro import traceback from robot.api import logger try: # noinspection PyCompatibility import unicode as str except ImportError: # python3 pass # noinspection PyCompatibility,PyUnresolvedReferences class Operator(str): pa...
# -*- coding: utf-8 -*- from django.conf import settings from django.shortcuts import render from django.urls import reverse from django.http import HttpResponseRedirect from djforms.athletics.soccer import BCC from djforms.athletics.soccer import INSURANCE_TO_LIST from djforms.athletics.soccer import TO_LIST ...
from dataclasses import dataclass from typing import Tuple, List import ase.data import numpy as np from networkx import Graph from rdkit import Chem import graphdg.parse.tools as tools from graphdg.parse.extended_graph import mol_to_extended_graph from graphdg.tools import GLOBALS, NODES, EDGES, SENDERS, RECEIVERS, ...
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals from scrapy.exceptions import IgnoreRequest from urllib.parse import parse_qsl,urlencode,urlsplit,urluns...
"MIME handling" import base64 from io import BytesIO import mimetypes from email import encoders, charset from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.base import MIMEBase from email.mime.audio import MIMEAudio from email imp...
# Packages import os import numpy as np import pandas as pd import datetime import matplotlib.pyplot as plt # Self-defined modules import utility from data_loader import DataLoader def _add_fitness_fatigue(dataframe): dataframe['Date'] = pd.to_datetime(dataframe.Date) dataframe['Fatigue (ATL)'] = dataframe.ro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Defines classes related to 2D polygons. """ class Vertex: def __init__(self, coordinates, **kwargs): self.coordinates = coordinates if 'prev' in kwargs: self.set_prev(kwargs['prev']) if 'next' in kwargs: self.set_ne...
from enum import Enum import asyncio import random import logging import time logger = logging.getLogger(__name__) class PeerState(Enum): LEADER = 1 CANDIDATE = 2 FOLLOWER = 3 TERMINATING = 4 class RaftConsensus: def __init__(self, communicator, registry, ...
from keras.models import Sequential, load_model from keras.layers import Dense, Reshape, Flatten, Conv2D, Conv2DTranspose, BatchNormalization, Activation from keras.layers.advanced_activations import LeakyReLU from keras.optimizers import Adam, SGD from keras.backend import clear_session import numpy as np import os i...
from donut import email_utils import flask import smtplib from donut.modules.core.helpers import get_name_and_email from donut.modules.groups import helpers as groups def get_past_messages(group_id, limit=5): """Returns a list of past sent messages""" query = """ SELECT newsgroup_post_id, subject, messag...
from core.base_environment import * import numpy as np from overrides import overrides from pyhelper_fns import vis_utils def str2action(cmd): cmd = cmd.strip() if cmd == 'w': #up ctrl = [0, 0.1] elif cmd == 'a': #left ctrl = [-0.1, 0] elif cmd == 'd': #right ctrl = [0.1, 0] elif cmd ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright 2021 <NAME> <<EMAIL>> # Description: Utilities for pretty-printing Kokkos::UnorderedMap # # Distributed under terms of the 3-clause BSD license. import gdb import argparse import numpy as np import pandas as pd from collections.abc import It...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import struct import numpy as np import subprocess import matplotlib.pyplot as plt from collections import namedtuple # N - number of oscillators # freq - oscillator frequency (N elements) # phase - oscillator phases (N elements) # k - coupling coeffici...
import re import os import psutil import argparse import requests from os import _exit,path,devnull from sys import stdout from time import sleep from random import choice from argparse import ArgumentParser from traceback import print_exc from threading import Thread,Lock,enumerate as list_threads from user_agent impo...
import numpy as np from itertools import product from itertools import permutations def choose_nums(big, small): """ This function takes 2 inputs (number of big number and number of small numbers) and returns a list of appropriate randomized inetegers """ #test inputs assert type(big) is int, "...
import numpy as np import torch import time import gym from a2c_ppo_acktr import utils from a2c_ppo_acktr.envs import make_vec_envs from common.common import * import pyrobotdesign as rd def evaluate(args, actor_critic, ob_rms, env_name, seed, num_processes, device): eval_envs = make_vec_envs(env_name, seed + nu...
import numpy as np import torch import torchvision from torchvision import transforms from torch.utils.data import DataLoader, random_split import cv2 import matplotlib.pyplot as plt from torchvision.datasets import CIFAR10 from PIL import Image def to_RGB(image:Image)->Image: if image.mode == 'RGB':return image ...
from websocket import create_connection import requests, json, threading, select, multiprocessing, time, os from datetime import datetime class User: def __init__(self, user_id, username, avatar, discriminator, public_flags, nick=None): self.user_id = user_id self.username = username self.n...
from __future__ import print_function import matplotlib as plt import numpy as np from skimage.io import imread from skimage import exposure, color from skimage.transform import resize import keras from keras import backend as K from keras.datasets import cifar10 from keras.models import Sequential from keras.layers i...
from datetime import date import pytest import responses import re from personio_py import PersonioError, Absence, Employee from tests.test_mock_api import mock_personio, compare_labeled_attributes, mock_employees from tests.mock_data import json_dict_absence_alan, json_dict_absence_types, json_dict_empty_response,\ ...
from telegram import ReplyKeyboardMarkup, KeyboardButton, Update, CallbackQuery import logging import threading def handler(func): """ Every handler should have this decorator """ def wrapper(*args, **kwargs): self = args[0] bot = args[1] update = args[2] update_or_quer...
from functools import wraps from typing import List, Callable import numpy as np LETTER_SIGNATURE = "fruits_letter" LETTER_NAME = "fruits_name" BOUND_LETTER_TYPE = Callable[[np.ndarray, int], np.ndarray] FREE_LETTER_TYPE = Callable[[int], BOUND_LETTER_TYPE] class ExtendedLetter: """Class for an extended letter...
from __future__ import absolute_import from __future__ import print_function import argparse import os import sys import string import subprocess, logging from threading import Thread import time import socket import commands def get_mpi_env(envs): """get the mpirun command for setting the envornment support...