text
stringlengths
3.07k
12.6k
import pytest import numpy as np from .tracker import Tracker def generate_emitter(x=1.0, y=1.0, start=0, stop=10, dx=0.0, dy=0.0, dark=None): if dark is None: dark = [] if not isinstance(dark, list): dark = [dark] result = [] for step, n in enumerate(range(start, stop)): i...
import os import textwrap from abc import ABC from copy import deepcopy from logging import debug from pathlib import Path from types import SimpleNamespace from cli_ui import debug as verbose from cli_ui import fatal from mergedeep import merge from yamlpath.common import Parsers from yamlpath.wrappers import Console...
import ply.lex as lex import re from collections import deque # List of token names. This is always required from .mutualTranslation import * class Stack(object): def __init__(self): self.stack = deque() def is_empty(self): return len(self.stack) == 0 def push(self, data)...
################################################################################ ## ## 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 op...
# -*- coding: utf-8 -*- from marshmallow import ( fields, post_dump, post_load, pre_load, Schema, SchemaOpts, ) from webargs import validate from werkzeug.routing import ( BaseConverter, ValidationError, ) from pyethapp.jsonrpc import ( address_encoder, data_encoder, data_de...
import numpy as np # import keras from keras.models import Sequential, Model from keras.layers import Dense, Activation, Flatten, CuDNNLSTM, Input, Concatenate from keras.optimizers import Adam # keras-rl agent from rl.agents.dqn import DQNAgent from rl.policy import BoltzmannQPolicy, EpsGreedyQPolicy from rl.memory ...
#!/usr/bin/python # -*- coding: utf-8 -*- # imports, globals # -------------------------------------------------------------- #time import time # gpio import RPi.GPIO as gpio gpio.setmode(gpio.BCM) # Using a dictionary as a lookup table to give a name to gpio_function() return code pin_use = {0:"GPIO.OUT", 1:"GPI...
import numpy as np import numpy.testing as npt import pandas as pd import pytest from pandas.util import testing as pdt from .. import draw from ..ipu.ipu import _FrequencyAndConstraints @pytest.fixture def seed(request): current = np.random.get_state() def fin(): np.random.set_state(current) re...
import sys import warnings from functools import wraps import numpy as np from numpy.testing import assert_array_equal from numpy.testing import assert_array_almost_equal from numpy.testing import assert_allclose from numpy.testing import assert_almost_equal from numpy.testing import assert_approx_equal from numpy.te...
from sqlalchemy.test.testing import assert_raises, assert_raises_message import sqlalchemy as sa from sqlalchemy.test import testing from sqlalchemy.orm import scoped_session from sqlalchemy import Integer, String, ForeignKey from sqlalchemy.test.schema import Table, Column from sqlalchemy.orm import mapper, relationsh...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import json from collections import OrderedDict, defaultdict, namedtuple import six import six.moves.html_parser from couchdbkit import ResourceNotFound from django.core.exceptions import ObjectDoesNotExist ...
# Copyright 2021 QHAna plugin runner contributors. # # 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 ...
#!/usr/bin/env python __all__ = ['eis_plot_fit'] import os import sys from pathlib import Path import numpy as np import matplotlib.pyplot as plt import eispac speed_of_light_km = 299792.458 vmin = -20 #-40. # velocity min scaling in km/s vmax = 20 #40. # velocity max scaling in km/s wmin = 25 # width min scaling...
import os from flask import current_app, Flask, Blueprint from flask.blueprints import BlueprintSetupState from flask import send_from_directory from flask_security import login_required, roles_accepted import pandas as pd import rq_dashboard from humanize import naturaldelta from flexmeasures.auth.policy import ADMI...
from __future__ import print_function import sys import os import logging import shutil import muteria.common.mix as common_mix import muteria.repositoryandcode.codes_convert_support as ccs from muteria.repositoryandcode.callback_object import DefaultCallbackObject from muteria.drivers import DriversUtils ERROR_HA...
from collections import defaultdict from itertools import product from addok.config import config from addok.db import DB from addok.helpers import scripts from addok.pairs import pair_key def no_tokens_but_housenumbers_and_geohash(helper): if not helper.tokens and helper.housenumbers and helper.geohash_key: ...
#!/usr/bin/env python3 # Copyright 2018 Stanford 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 applicab...
# -*- coding: utf-8 -*- """ format-sql Makes your SQL readable. Copyright (c) 2014-2015, <NAME> (<EMAIL>) All rights reserved. """ import re from collections import OrderedDict class StringNotTerminated(Exception): pass class Token: AS = 'AS' ASC = 'ASC' COMMA = ',' COMPARE = 'compare' DES...
#!/bin/env python3 from tkinter import messagebox, Tk from subprocess import run, PIPE, Popen from os.path import join, basename from os import readlink from time import sleep #from inotify_simple import INotify, flags ''' The following code by <NAME>, from inofify_simple: ''' import os import enum import collectio...
from ledfx.utils import BaseRegistry, RegistryLoader from abc import abstractmethod from threading import Thread from ledfx.events import DeviceUpdateEvent, Event import voluptuous as vol import numpy as np import importlib import pkgutil import logging import time import os import re _LOGGER = logging.getLogger(__nam...
from collections import defaultdict from django.utils.functional import cached_property from wagtail.core import hooks from wagtail.core.models import Page, Locale class PageIndex: """ An in-memory index of pages to remove the need to query the database. Each entry in the index is a unique page by trans...
import logging import os import re import sys from dbnd._core.current import try_get_databand_context from dbnd._core.utils.basics.text_banner import safe_string from dbnd._core.utils.project.project_fs import databand_lib_path, project_path logger = logging.getLogger(__name__) _inner_call_functions_regexp = re.com...
from __future__ import print_function from nose.tools import assert_equal, assert_in, assert_is def assert_almost_equal(actual, expected, decimal=7, ctx=None): if hasattr(actual, "__iter__"): for a, e in zip(actual, expected): try: assert_almost_equal(a, e, decimal=decimal) ...
from typing import Dict import requests import yaml ### ZigBee constants # ZigBee client type from EIBClient import EIBClientListener, EIBClientFactory from common import printGroup, printValue from core.DeviceBase import KNXDDevice from core.util.BasicUtil import log from core.util.ZigBeeUtil import zigbee_utils ZI...
import math import os import cv2 import dlib import numpy as np def detect_face(model): model_path = os.path.join(os.getcwd(), "assets", "models", model) faces = dlib.get_frontal_face_detector() landmarks = dlib.shape_predictor(model_path) return faces, landmarks def load_assets(filename): im...
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apa...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding Ltd. # # 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-...
import subprocess import os from pathlib import Path import random import math import argparse import numpy as np import PIL.Image import dnnlib import dnnlib.tflib as tflib import re import sys import pretrained_networks from tqdm import tqdm import pickle network_pkl = "gdrive:networks/stylegan2-ffhq-config-f.pkl" ...
import os import re import shutil import uuid import json import base64 import logging from datetime import datetime import requests from bs4 import BeautifulSoup from flask import * from flask_security import current_user from dtech_instagram.app import app from dtech_instagram.db import db from dtech_instagram.mode...
# -*- coding: utf-8 -*- import idaapi import idautils import ida_bytes import ida_diskio import idc import operator import yara import os import glob VERSION = "0.2" YARARULES_CFGFILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "findcrypt3.rules") try: class Kp_Menu_Context(idaapi.action_handler_t...
# -*- coding: utf-8 -*- from django.conf import settings from django.core.mail import send_mail from django.db import models from django.template import Context from django.template.loader import get_template from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class MediaPatronag...
"""Separates an SVG map into files to represent each of its component countries, while retaining some context. This script is tied heavily into our country map file, but the script could be modified to resize images, provide more context, etc. TODO: this script has several bugs, including generating multiple zoom clas...
__doc__ = """ Module contains callback classes to save simulation data for rod-like objects """ __all__ = ["CallBackBaseClass", "MyCallBack", "ExportCallBack"] import warnings import os import sys import numpy as np class CallBackBaseClass: """ This is the base class for callbacks for rod-like objects. ...
#!/usr/bin/python3 from podcomm.definitions import * import requests import simplejson as json from Crypto.Cipher import AES import os import base64 import argparse ROOT_URL = "http://127.0.0.1:4444" configureLogging() logger = getLogger() def get_auth_params(): with open(DATA_PATH + KEY_FILE, "rb") as keyfile...
import tleToTrueAnomaly as ttte import keplerToCartesianOrbital as ktco import cartOrbitalToInertial as coti import inertialToRotationalFrame as itrf import altAzFromGPS as aafg import gps import tleData as tled from math import * import matplotlib.pyplot as plt import num...
# ./pyxb/bundles/dc/raw/dcmitype.py # -*- coding: utf-8 -*- # PyXB bindings for NM:049d2b1ce34c6b814456fe5b9055f12be5a680b0 # Generated 2016-09-18 17:34:12.276080 by PyXB version 1.2.5 using Python 2.7.12.final.0 # Namespace http://purl.org/dc/dcmitype/ [xmlns:dcmitype] from __future__ import unicode_literals import p...
# -*- coding: utf-8 -*- """ python-reporter: """ import re import os import sys import json import codecs import logging from uuid import UUID, uuid4 from collections import OrderedDict from contextlib import contextmanager from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy import Column, Intege...
from typing import Callable, List, Mapping, Optional, Tuple from operator import le, gt import numpy as np from gbart.modified_bartpy.errors import NoSplittableVariableException, NoPrunableNodeException from gbart.modified_bartpy.mutation import TreeMutation, GrowMutation, PruneMutation from gbart.modified_bartpy.nod...
# Lint as: python3 # 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 agr...
''' Author: <NAME> (<EMAIL>) Mar 2022 ''' import argparse import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Disable tensorflow debugging logs import time import tensorflow as tf import tensorflow_text as text from model import GPT from utils import * from hparams import hparams AUTOTUNE = tf.data.experiment...
from fastapi import Depends from datetime import datetime from app.core.config import src_path, src_ext from app.crud.case import get_case_list_by_query, create_case_with_analysis_and_count from app.crud.user import get_all_division_group_by_group from app.models.case import CaseCreateModel, AnalysisCreateModel, CountC...
""" Support for Syslog-based networking devices. For now, support is limited to hostapd and dnsmasq. Example syslog lines: <30>Dec 31 13:03:21 router hostapd: wlan1: STA a4:77:33:e3:17:7c WPA: group key handshake completed (RSN) <29>Dec 31 13:05:15 router hostapd: wlan0: AP-STA-CONNECTED 64:20:0c:37:52:82 ...
# Author: <NAME>, <NAME> import argparse import json import numpy as np import os import pickle import sys import time import torch import dataloaders import models from steps.unit_analysis import (comp_code_to_wordprec, comp_word_to_coderecall, get_high_prec_words, comp_code_norms, ...
"""Hash your files for easy identification.""" import hashlib import logging import os from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from typing import Dict from flexget import plugin from flexget.event import event from flexget.logger import FlexGetLogger from .cunit import IECUnit...
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import math from layers.attention import SelfAttention class MultiAttention(nn.Module): def __init__(self, input_size=1024, output_size=1024, freq=10000, pos_enc=None, num_segments=None, heads=1, fusion=Non...
""" Compute the aggregate effects for each individual neuron. Save the effects as $model_neuron_effects.csv. Usage: python compute_and_save_neuron_agg_effect.py $result_file_path $model_name """ import os import sys import pandas as pd def analyze_effect_results(results_df, effect, word, alt, savefig=None): ...
from collections import defaultdict from scipy import spatial import numpy as np import torch from collections import defaultdict from src.modules.lcfcn import lcfcn_loss from scipy import spatial import numpy as np import torch from collections import defaultdict from scipy import spatial import numpy as np import...
# Program that outputs DHT22 values to SSD1306 on ESP32 (DOIT DEVIT V1 ESP32-WROOM-32). # The values can also be read via MQTT, # The MQTT remote control of the output on GPIO1 does not work! from mqtt_as import MQTTClient, config import uasyncio as asyncio import machine import dht from color_setup import ssd # On...
import keras import keras.backend as K import numpy as np import matplotlib.pyplot as plt import os.path import csv from math import ceil from keras.preprocessing.image import DirectoryIterator, ImageDataGenerator dataset = 'chairs' # one of 'faces' 'chairs' 'celeba' z_dims = 32 beta = 10 batches = 2000000 batch_siz...
# -*- coding: utf-8 -*- """Hive JSON-RPC API server.""" import os import logging from datetime import datetime #from sqlalchemy.engine.url import make_url from sqlalchemy.exc import OperationalError from aiohttp import web #from aiopg.sa import create_engine from jsonrpcserver import config from jsonrpcserver.async_me...
import haystack.forms from crispy_forms.helper import FormHelper from dal import autocomplete from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.forms import ModelForm, BooleanField from core.layout import * from core.models import User, Organization class LoginForm(Authentication...
from collections import defaultdict from scipy import stats import pandas as pd def get_critical_nbhds(neighborhoods, predictions_df, precisions_df, recalls_df, p_thresh=0.5): critical_nbhds_test_1 = defaultdict(list) critical_nbhds_test_2 = defaultdict(list) for uid, nbhd in neighborhoods.items(): ...
# coding: utf-8 import sys import json import requests import logging from .constants import (ORCID_PUBLIC_BASE_URL, ORCID_SANDBOX_BASE_URL) from .utils import dictmapper, u, MappingRule as to from .exceptions import NotFoundException # # configure logger # _logger_depth = 'INFO' logger = logging.getLogger("#orci...
import numpy as np import csv import os import glob from scipy.ndimage import imread import yaml from collections import OrderedDict def _load_images(tiny_imagenet_base_path, val_only=False): # Load dataset ds_base_path = tiny_imagenet_base_path with open(os.path.join(ds_base_path, 'wnids.txt'), 'rt') a...
# -*- coding: utf-8 -*- # # Copyright (c) 2016 B-Open Solutions srl - http://bopen.eu # # python 2 support via python-future from __future__ import absolute_import, unicode_literals import subprocess import pytest from elevation import datasource def test_srtm3_tile_ilonlat(): # values from http://srtm.csi.cgi...
# 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! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Implements the interface of the results_processor module. Provides functions to parse command line arguments and process options. """ import argparse im...
#!/usr/bin/env python """ Botan doc generation script (C) 2014,2015,2017 <NAME> Botan is released under the Simplified BSD License (see license.txt) """ import sys import optparse # pylint: disable=deprecated-module import subprocess import shutil import logging import json import tempfile import os import stat de...
import datetime from fake_useragent import UserAgent import requests import re from bs4 import BeautifulSoup as bs import time import random def print_run_time(func): def wrapper(*args, **kw): local_time = time.time() func(*args, **kw) spendTime=int(time.time() - local_time) print(...
import gzip import pandas as pd import pkg_resources from Bio import SeqIO from crispy import logger as LOG from dualguide import read_gi_library DPATH = pkg_resources.resource_filename("data", "dualguide/") RPATH = pkg_resources.resource_filename("notebooks", "dualguide/reports/") STYPES = ["sgRNA1", "sgRNA2", "Scaf...
from django.contrib.admin.utils import lookup_field from django.contrib.admin.helpers import AdminForm as DjangoAdminForm from django.contrib.admin.helpers import Fieldset as DjangoFieldSet from django.contrib.admin.helpers import Fieldline as DjangoFieldLine from django.contrib.admin.helpers import AdminReadonlyField ...
import glob import re import numpy as np import os import random def atof(text): try: retval = float(text) except ValueError: retval = text return retval def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_...
import contextlib import logging import yaml import os from teuthology import packaging from teuthology.orchestra import run from teuthology.parallel import parallel log = logging.getLogger(__name__) @contextlib.contextmanager def install(ctx, config): """ Installs rh ceph on all hosts in ctx. :param c...
import streamlit as st import pandas as pd from sklearn.model_selection import train_test_split from Models.SVC import svc_param_selector from Models.LogisticRegression import lr_param_selector from Models.DecisionTree import dt_param_selector from Models.RandomForet import rf_param_selector from Models.RidgeClassifier...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' A program that converts the input image file into a numpy array and constructs from it a graph representation of the the walkable area. ''' # pylint: disable=w0511, C0103, C0301, r1710 import argparse import pprint import sys from pathlib import Path from textwrap i...
# -*- encoding: utf-8 -*- # # 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, so...
# encoding = utf-8 from tkinter import * from decimal import Decimal import re, math text_string = "" root = Tk() root.title('My Calculator') top_frame = Frame(root) top_frame.pack(side=TOP) mid_frame = Frame(root) mid_frame.pack() bottom_frame = Frame(root) bottom_frame.pack(side=BOTTOM) botton_texts = ['x²', 'x∧y',...
#!/usr/bin/python import urwid import mainview """ NOTES ----- This module builds the widget to show the edit view for the table. """ class EditTableInfo: def __init__(self): self.rename_name = "" self.add_field = "" self.add_query_string = "" self.add_current = 0 def show_table_edit(frame, body,...
import os import csv import json import argparse from constants import VALID_TAGS def getTagsInFolder(tags_path): """ Check the provided folder for json files and return it in a list :param tags_path: string - The path where tag jsons are stored :return: tags: list - A list containing the paths to each...
""" Copyright 2011 <NAME> <<EMAIL>> This file is provided to you 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...
import logging import timeit import torch from .manifolds import RiemannianManifold, EuclideanManifold, SphericalManifold, ProductManifold, PoincareBall from sacred import Experiment from sacred.observers import FileStorageObserver from .data.data_ingredient import data_ingredient, load_dataset, get_adjacency_dict f...
from api.models import Photo from api.models import Person from api.models import LongRunningJob import os import datetime from tqdm import tqdm import hashlib import pytz from config import image_dirs import time import api.util as util from api.flags import \ is_auto_albums_being_processed, \ is_photos_bei...
from __future__ import absolute_import import datetime import smtplib from configparser import ConfigParser from email.header import make_header from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from time import sleep import requests...
''' Created on Dec 5, 2016 @author: julien ''' import json import logging import numpy from os import path from random import Random from deap import creator, base, tools from minos.model.build import ModelBuilder from minos.tf_utils import cpu_device toolbox = base.Toolbox() rand = Random() def random_individual...
import datetime import uuid from django.conf import settings from django.contrib.auth.models import User from django.core import serializers from django.db import models from django.db.models.query import QuerySet from django.template.defaultfilters import slugify from django.utils import timezone from dateutil impor...
#!/usr/bin/env python # $Id: test_settings.py 6159 2009-10-09 07:17:59Z milde $ # Author: <NAME> <<EMAIL>> # Copyright: This module has been placed in the public domain. """ Tests of runtime settings. """ import sys import os import difflib import pprint import warnings import unittest import DocutilsTestSupport ...
import json from collections import namedtuple, MutableMapping import six from graphql import get_default_backend from graphql.error import format_error as default_format_error from graphql.execution import ExecutionResult from .error import HttpQueryError # Necessary for static type checking if False: # flake8: no...
from typing import NamedTuple, Optional, Awaitable, List, Callable, NoReturn import pathlib import csv import websockets from src.lib.ainput import ainput from src.lib.ff import get_cropped_segment, play_segment from src.CONFIG import MESSAGES from .input_parser import Input, print_player_controls, get_user_input CS...
# -*- coding: utf-8 -*- """ This program performs logistic regression on three types of datasets which can be generated using sklearn. @author: Randeep """ import numpy as np from sklearn.datasets import make_moons, make_circles, make_blobs from matplotlib import pyplot from pandas import DataFrame SPLIT_RATIO = 90 ...
""" The qiprofile unit of measurement MongoDB data model. This uom module is an advisory module for quantity display and conversion. Quantities are always stored in a canonical unit documented in the field. """ import decimal from numbers import Number import mongoengine from mongoengine import fields class Decimal...
# # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initial Developer of the Original Code is # <NAME> <<EMAIL>> # f...
from __future__ import absolute_import, print_function, division import logging import numpy as np import os from io import BytesIO from .common import BaseHandler, MultiDatasetHandler from ..models import GenericModel, REGRESSION_MODELS from ..thread_pool import run_cpu_bound from six.moves import range from six.move...
import pygame from typing import Callable, List import random class MazeDensity: NORMAL = 4 HIGH = 2 LOW = 8 class Colors: RED = (255, 255, 0) GREEN = (0, 255, 0) BLUE = (0, 255, 0) YELLOW = (255, 255, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) PURPLE = (128, 0, 128) OR...
""" The MIT License (MIT) Copyright (c) 2017-2018 <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,...
import os from datetime import datetime from eve import Eve from flask import render_template, request, jsonify from chess_game.daos.board_dao import BoardDao from chess_game.daos.game_dao import GameDao from chess_game.daos.mongo import MongoDatabase from chess_game.daos.player_dao import PlayerDao from chess_game.m...
import nltk from sklearn.base import BaseEstimator from gensim.models.doc2vec import TaggedDocument, Doc2Vec from nltk.tokenize import word_tokenize import scipy import numpy as np from gensim.models import Word2Vec class Doc2VecModel(BaseEstimator): """Performs a gensim Doc2Vec transformation of the input docume...
import copy import time def get_puzzle_input(filepath): field = [] with open(filepath) as f: for line in f: l = [int(x) for x in line.rstrip()] field.append(l) return field def dynamical_programming(field): # find lowest cost/risk to start from <<start>> and end at ev...
# -*- coding: utf-8 -*- ### System ### import struct ### Local ### from .midi.events import * def as_midi_bytes(text): midi_bytes = b"" X = iter(text) for c in X: if c == "\\": cc = next(X) if cc == "\\": midi_bytes += struct.pack("B", ord(cc)) ...
#!/usr/bin/python # -*- coding: utf-8 -*- # ProDy: A Python Package for Protein Dynamics Analysis # # Copyright (C) 2010-2012 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either vers...
import seaborn as sns import pandas as pd import cdlib import matplotlib.pyplot as plt __all__ = ["plot_com_properties_relation", "plot_com_stat", "plot_sim_matrix"] # "plot_scoring", def plot_sim_matrix(clusterings, scoring): """ Plot a similarity matrix between a list of clusterings, using the provided sco...
import ctypes import os import platform from collections import namedtuple import freetype import freetype.ft_enums import numpy as np from glm import ivec2 from engine.lib.np_helper import map_ct_pointer _font_names_cache = () class FTFace: def __init__(self, name, size=(16, 16), dpi=(96, 96), lcd=False, colo...
#!/usr/bin/env python2 """ Tests of pvtools package. """ import unittest import doctest import os import sys sys.path.insert(0, os.path.abspath('..')) import pvtools as pvt class TestVtk(unittest.TestCase): def setUp(self): self.file1 = os.path.join(pvt.PVTOOLS_DIR, "...
''' Author: <NAME> Initial Version: Nov-2020 Function: Define the neural network models ''' import os import torch import torch.nn as nn from mmsddl.get_cfg import DEVICE from pytorch_model_summary import summary from time import sleep from mmsdcommon.util import num_channels, max_fs class HAR_model(nn.Mo...
# Copyright 2019 TerraPower, 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 writi...
# gensim modules import sys import numpy import pickle import logging import multiprocessing from gensim import utils from os.path import isfile, join, exists from os import makedirs from random import shuffle from gensim.models.doc2vec import TaggedDocument from gensim.models import Doc2Vec from sklearn.ensemble impo...
import sys sys.path.append("../") import random import training.next_util_functions as func random_state = 42 random.seed(random_state) def test_build_custom_vocab(): custom_vocab = func.build_custom_vocab("tacred", 10) actual_custom_vocab = { 'SUBJ-PERSON': 10, 'OBJ-PERSON': 11, 'SUBJ-ORGANIZATION': ...
import os from io import BytesIO import tarfile import tempfile from six.moves import urllib import numpy as np from PIL import Image import cv2, pdb, glob, argparse import tensorflow as tf class DeepLabModel(object): """Class to load deeplab model and run inference.""" INPUT_TENSOR_NAME = 'ImageTensor:0' OUTP...
# Copyright 2017 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 required by applica...
from os.path import join from copy import deepcopy from abc import abstractmethod import json from google.protobuf import struct_pb2 import rastervision as rv from rastervision.backend import (BackendConfig, BackendConfigBuilder) from rastervision.protos.backend_pb2 import BackendConfig as BackendConfigMsg from raste...
############################################################################### # Copyright (c) 2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by <NAME>, <EMAIL>. # # LLNL-CODE-734340 # All rights reserved. # This file is part of MaestroWF, Version: 1...