text
stringlengths
3.07k
22.1k
"""Main SDGym benchmarking module.""" import io import logging import multiprocessing as mp import os import types from datetime import datetime, timedelta import humanfriendly import psutil import tqdm from sdgym.data import load_dataset from sdgym.evaluate import compute_scores from sdgym.results import make_leade...
#!/usr/bin/env python # encoding: utf-8 """ Kibana Dashboard Extractor/Loader A small tool to extract dashboards, visualizations, and searches from kibana, that are stored in the elasticsearch index. It is based on the Ruby scripts created by @jim-davis: Modified from https://github.com/jim-davis/kibana-helper-scrip...
import json import time from pathlib import Path from tempfile import TemporaryDirectory from typing import Any, Dict, List import click from kaggle import KaggleApi from kaggle.models.kaggle_models_extended import KernelPushResponse from .. import kernel_proc from ..builders.packaging_system import get_dependencies ...
# coding=utf-8 from __future__ import unicode_literals, division, absolute_import import re import time import logging import multiprocessing import concurrent.futures from datetime import datetime from decimal import Decimal from builtins import * from requests.adapters import HTTPAdapter from flexget import plug...
import datetime import requests_html from urllib.parse import urljoin class LibrusSession(object): def __init__(self): self._html_session = None def login(self, username, password): """ Creates authenticated session. """ self._html_session = requests_html.HTMLSession...
""" This file contains multiple methods to optimise the calculation of the Mandelbrot set in mandelbrot.py. All functions return a detail :math:`\\times` detail numpy array containing the output of the functions implementing the Mandelbrot set. Naive implementation: - naive() implements the computation of the Mande...
""" Contains the models necessary for our application """ import uuid from django.conf import settings from django.db import models from django.contrib.auth.models import User, AbstractUser from django.contrib.postgres.fields import ArrayField from django.utils.translation import gettext_lazy from django.dispatch impor...
import sys sys.path.append('../src/') import os os.environ['KMP_DUPLICATE_LIB_OK']='True' import random import numpy as np from time import time, localtime, strftime import configparser import torch from util.data import Dataset from offlineExp.gru4rec import GRU4Rec from offlineExp.tmf import TMF, TMF_variety, TMF_...
import pytest import datetime from dateutil.tz import tzoffset from decimal import Decimal from pyticketswitch.mixins import JSONMixin, PaginationMixin, SeatPricingMixin class TestJSONMixin: ZULU = tzoffset('ZULU', 0) class Foo(JSONMixin, object): def __init__(self, bar): self.bar = bar...
from hdmm.workload import * from hdmm import templates def __race1(): # single race only, two or more races aggregated # binary encoding: 1 indicates particular race is checked race1 = np.zeros((7, 64)) for i in range(6): race1[i, 2**i] = 1.0 race1[6,:] = 1.0 - race1[0:6].sum(axis=0) re...
import os import xlsxwriter import time import pickle import random import numpy as np import matplotlib.pyplot as plt from classes.quiz import Quiz from classes.save import Save from classes.result import Overall_Results, Result from classes.answer import Picture_Answer, Text_Answer, Answer from classes.school import...
import argparse import sys import math from collections import namedtuple from itertools import count import gym import numpy as np import scipy.optimize from gym import wrappers import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import tor...
import json import datetime import re from peewee import * from playhouse.shortcuts import model_to_dict db = SqliteDatabase(None) def copy_keys(a, b, args): for key in args: a[key] = b.get(key, None) return a def del_keys(d, args): for key in args: if key in d: del d[key] ...
# coding:utf-8 """E(x)hentai components.""" import os import re import requests from bs4 import BeautifulSoup import modules.misc as misc from modules import exception _LOGIN_URL = 'https://forums.e-hentai.org/index.php' _ACCOUNT_URL = 'https://e-hentai.org/home.php' _EXHENTAI_URL = 'https://exhentai.org/' def _ba...
from django.db import models from apps.ventas.producto.models import Producto from datetime import datetime # Create your models here. date = datetime.now() class Proveedor(models.Model): """[summary] Args: models ([Proveedor]): [Contiene la informacion de los proveedores] """ nombre_pro...
import os import torch import torch.nn.functional as F import yaml import copy from ast import literal_eval from typing import Callable, Iterable, List, TypeVar import torch.distributed as dist from typing import Tuple import argparse A = TypeVar("A") B = TypeVar("B") class TimeDistributed(torch.nn.Module): """ ...
# # Copyright (c) <NAME>, <NAME>, <NAME> and others. # Portions copyright (c) <NAME> and <NAME>, Inc. and its affiliates. # # SPDX-License-Identifier: MIT # # Originally from https://github.com/rubygems/rubygems from univers.gem import GemRequirement from univers.gem import GemVersion from univers.gem import InvalidVe...
import random import time from enum import Enum import numpy as np import pandas as pd from scipy import sparse from sklearn.decomposition import NMF from sklearn.metrics import confusion_matrix class CurrencyRating(Enum): CHF = 5 GBP = 6 EUR = 7 USD = 8 NON_SWISS = 10 DEFAULT = 1 def sugge...
# Copyright 2021 Toyota Research Institute. All rights reserved. from collections import OrderedDict import numpy as np from dgp.annotations import ( BoundingBoxOntology, InstanceSegmentationOntology, Ontology, PanopticSegmentation2DAnnotation, SemanticSegmentation2DAnnotation, SemanticSegmentationOntology )...
"""Module for private utilities/helpers for DataIO class.""" import hashlib import json import logging import uuid from collections import OrderedDict from os.path import join from pathlib import Path from . import _oyaml as oyaml logger = logging.getLogger(__name__) def construct_filename( name, pretagname...
""" The library contain functions related to restore functionality. """ ## The script can be run with Python 3.6 or higher version. ## The script requires 'requests' library to make the API calls. import time import common headers = {"Content-Type" : "application/vnd.netbackup+json;version=4.0"} # Perform bulk res...
""" Tests for the common module. Run like: tox -c tox-full.ini -e py27-ubuntu_16_04_64 -- -s burlap/tests/test_common.py::CommonTests::test_satchel_ordering """ from __future__ import print_function import os import sys import tempfile import unittest import getpass from pprint import pprint # try: # impor...
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from enum import IntEnum from ..resnet_realnvp import ResNet from ..realnvp.utils import checkerboard_mask class MaskType(IntEnum): CHECKERBOARD = 0 CHANNEL_WISE = 1 TABULAR = 2 class MaskChannelwise: def __init_...
################################################################### # Route Planner maps the best possible route between two intersections # It uses a combination of Djikstra graph algorithm and A* algorithm ################################################################### import math class RoutePlanner: def __...
#This filter takes a series of TDMS files and converts them to individual part files, where each part is stored in an HDF5 File. import numpy as np import os import h5py import nptdms import re from contextlib import ExitStack from pathlib import Path from typing import Any, AnyStr, Dict, Generator, List, M...
# MIT License # # Copyright (c) 2017 <NAME> # # This file is part of excons. # # 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 # t...
# Copyright 2022 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...
import sys, os sys.path.append(os.path.dirname(os.path.abspath(__file__))+'/../') import numpy as np # Internal from lib.BFPConvertor import BFPConvertor from lib import BFPActivation from lib import BFPFullyConnet # PyTorch import torch import torch.nn as nn import torchvision def conv3x3(in_planes, out_planes, st...
#!/usr/bin/env python from __future__ import print_function import argparse import os import pickle import subprocess import sys from Bio import SeqIO from collections import defaultdict def generate_fasta_entries(input_fasta, output_fasta): """ Converts neoepiscope output FASTAs new FASTA file with IDs as headers, ...
#!/usr/bin/env python # encoding: utf-8 # Originally developed by <NAME> http://almostobsolete.net # Extended by <NAME> <EMAIL> # # Just a work in progress and adapted to what I need right now. # It does uploads (via a file-like object that you write to) and # I've started on downloads. Needs the development version o...
import warnings import math import re from functools import wraps from collections import namedtuple from datetime import datetime import urllib import pytz import cherrypy import gnupg from jinja2 import Environment, PackageLoader from dateutil import parser as date_parser from wtforms import Form, TextField, Passwor...
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # MEASURE - Master Equation Automatic Solver for Unimolecular REactions # # Copyright (c) 2010 by <NAME> (<EMAIL>) # # Permission is hereby granted, free of charge, to any person obtai...
import os from typing import Tuple import matplotlib.pyplot as plt import numpy as np import torch import torchvision.transforms as transforms import torchvision.utils as vutils from PIL import Image from nuscenes.nuscenes import NuScenes from nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud from nu...
import datetime import random import unittest from tzlocal import get_localzone from src.mqtt_connector import MqttConnector from src.process import Process, SwitchSensor, LoopParams from unittest.mock import MagicMock from src.result import ResultState, Result from src.sensor import MockSensor class MockProcess(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import copy import pandas as pd from pomegranate.distributions import IndependentComponentsDistribution from pomegranate.distributions import UniformDistribution, NormalDistribution from pomegranate.distributions import MultivariateDistribution, DiscreteDistribution impor...
from structure_analysis import Struc, output_json rOO_max = 10.89 # 3.3*3.3 def findHydroxylHydrogen(Oxyz, Hcoords, abc): for Hxyz in Hcoords: if calculate_distance2(Oxyz, Hxyz, abc) < 1.0: return Hxyz def hy_bond_from_DB(hmap_data, box, htype, name, feed): run = 'prod-' my_data = {r...
import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import seaborn as sns from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.learning_curve import validation_curve from sklearn.linear_model import LogisticRegression from sk...
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import Generate_Data3 as Generate_Data import keras 1 save_path = Generate_Data.save_path save_rate = 50000 audio_size = Generate_Data.audio_size batch_size = 10 divisor = 4; time_interval = 16; def read_npz(fn): with np.load(fn) as dat...
""" A minimal character-level LSTM model. Written by ZhengHe (@ZhengHe-MD) This is derived from the following scripts: - https://gist.github.com/karpathy/d4dee566867f8291f086 - https://github.com/eliben/deep-learning-samples/blob/master/min-char-rnn/min-char-rnn.py - https://github.com/nicodjimenez/lstm And you might f...
import os import cv2 import pdb import random import numpy as np import pandas as pd from tqdm import tqdm import torch from collections import defaultdict from torchvision import transforms from PIL import Image from torch.utils.data import DataLoader, Dataset, sampler from torchvision.datasets.folder import pil_loade...
import torch.nn.functional import typing as _typing import torch_geometric from torch_geometric.nn.conv import GraphConv from torch_geometric.nn.pool import TopKPooling from torch_geometric.nn.glob import ( global_add_pool, global_max_pool, global_mean_pool ) from ...encoders import base_encoder from .. import base...
from collections import defaultdict from typing import Optional import torch import numpy as np from pytorch_gleam.modeling.models.base_models import BaseLanguageModel from pytorch_gleam.modeling.thresholds import ThresholdModule, MultiClassThresholdModule from pytorch_gleam.modeling.metrics import Metric from pytor...
import numpy as np import torch from torch import nn class MDense(nn.Module): def __init__(self, input_features, output_features): super(MDense, self).__init__() self.weight1 = nn.Parameter(torch.randn(output_features, input_features), requires_grad=True) nn.init.xavier_uniform_(self.wei...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distrib...
import re import sys from hashlib import sha1 import logging import subprocess as sp from pathlib import Path from remake.util import sysrun from remake.setup_logging import setup_stdout_logging from remake.loader import load_remake from remake.task import Task, RescanFileTask from remake.executor.base_executor import...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 14 20:38:48 2020 @author: neil This script is designed to obtain a distribution for the water pockets which respresents a combination of the water occupancy (binary variable) and the water polarisation (continuous variable). For a water molecule to...
# Village People, 2017 import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import numpy as np from .agent import ReportingAgent from models import get_model from utils.torch_types import TorchTypes from collections import namedtuple import time # from termcolor import c...
"""Data Provider implementation module for constructing data based on standard stock indicators The data provider in this module is not indented to be instantiated outside of this module. Instead, upon the importing of this module, the provider will create an instance of itself and register itself with the global D...
import math, random import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Backend.Kernels.Costs import ctcLoss, ctcLossTest from PuzzleLib.Cost.Cost import Cost class CTC(Cost): def __init__(self, blank, vocabsize=None, normalized=False): super().__init__() self.normalized = normalized i...
#!/usr/bin/env python # <NAME> import json import logging import optparse import os import shutil import tempfile import urllib2 from xml.etree.ElementTree import tostring try: # For Python 3.0 and later from shutil import unpack_archive except ImportError: # Fall back to Python 2 import from setuptoo...
import PIL import numpy as np import time import torch from argparse import ArgumentParser from torchvision.transforms import RandomHorizontalFlip, RandomCrop, ToTensor, Normalize, Compose from torch.utils.data import DataLoader, random_split from typing import Optional, Callable, Tuple, Any from pytorch_lightning imp...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import log...
import vtk import h5py import numpy as np from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase import otter.plugins.common as common from otter.plugins.common.Reader import Reader from otter.plugins.common.Reader import BlockInformation, VariableInformation class PetscHDF5DataSetReader(VTKPythonAlgorithmBase): ...
# -*- coding: utf-8 -*- """ Created on Sun Aug 29 18:16:03 2021 Code is partly based on https://git.aweirdimagination.net/perelman/slide-detector @author: <NAME> """ import os import random import argparse import numpy as np import cv2 import torch import torch.nn as nn import decord from decord import VideoReade...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: agent.py # Author: <NAME> <<EMAIL>> import numpy as np import cv2 import tensorflow as tf #assert int(tf.__version__.split('.')[1]) == 9 assert int(np.__version__.split('.')[1]) >= 11 from collections import deque, Counter import random import time from tensorpac...
import math import torch import torch.nn as nn from torch.nn import init BATCHNORM_TRACK_RUNNING_STATS = False BATCHNORM_MOVING_AVERAGE_DECAY = 0.9997 class BNorm_init(nn.BatchNorm2d): def reset_parameters(self): init.uniform_(self.weight, 0, 1) init.zeros_(self.bias) class Conv2d_init(nn.Conv2...
# example from: https://pytorch-lightning.readthedocs.io/en/latest/notebooks/lightning_examples/mnist-hello-world.html # adds on from https://pytorch-lightning.readthedocs.io/en/latest/starter/introduction_guide.html import os import time import numpy as np import torch from pytorch_lightning import LightningModule, ...
#!/usr/bin/env python from __future__ import print_function import sys import numpy as np #This code calculates the aproximate memory footprint of PMPIC (total and per process) #It can thus be used to choose a value of maxparcels to maximise memory usage #number of grid/parcel variables n_grids=32 n_parcels=38 #numb...
import csv import sys import datetime import sqlite3 import os from typing import List, Any, Union, NamedTuple, Tuple from .env import TWDFT_DATA_DIR, INSPECTORS def conv_site_name_to_id(site: str) -> str: db_filename = "twdft.db" db_path = os.path.join(TWDFT_DATA_DIR, db_filename) with sqlite3.connect(...
# from __future__ import print_function from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.uix.listview import ListItemButton from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from docx import Document from docx.sha...
""" @brief Test code for Psf angular integrals over the ROI acceptance cone. The plots are the enclosed Psf as a function of separation between the true source direction and the center of the ROI. The black curves are the values returned from the IPsf::angularIntegral method, and the red data points are the results o...
#!/usr/bin/env python # Full license can be found in License.md # Full author list can be found in .zenodo.json file # DOI:10.5281/zenodo.1199703 # ---------------------------------------------------------------------------- """ pysat user module registry utilities This module allows pysat to provide direct access to ...
import os import numpy as np import torch import torch.nn as nn from torch.nn import Module import neural_renderer as nr from pose.manopth.manopth.manolayer import ManoLayer from .theta_regressor import ThetaRegressor class EncEncoder(nn.Module): def __init__(self, inp_ch, out_ch, name='enc'): super(EncEn...
import logging import os import sys import cv2 import numpy as np import torch import torch.nn as nn import _init_paths from config import cfg, update_config from models.utils import _gather_feat, _transpose_and_gather_feat from tensorrt_model import TRTModel from utils.image import get_affine_transform, transform_pr...
""" Quick Start =========== Installation:: pip install flask-jwt-router Basic Usage:: from flask import Flask from flask_jwt_router import JwtRoutes app = Flask(__name__) # You are required to always set a unique SECRET_KEY for your app app.config["SE...
"""Controller requesting state from datapath.""" # System imports from enum import Enum # Local source tree imports from pyof.foundation.base import GenericMessage, GenericStruct, IntEnum from pyof.foundation.basic_types import ( BinaryData, FixedTypeList, Pad, UBInt8, UBInt16, UBInt32, UBInt64) from pyof.v0x05.c...
from abc import ABC, abstractmethod import textwrap from typing import Union, List, Dict from pydantic import BaseModel from nmea.nmea_utils import convert_bits_to_int, convert_int_to_bits, get_char_of_ascii_code, convert_decimal_to_ascii_code, \ convert_ascii_char_to_ascii6_code, add_padding, add_padding_0_bits,...
from django import template from django.contrib.auth.models import User register = template.Library() from django.shortcuts import render, get_object_or_404 from ..models import Analysis, ProjectComment, Module, Project, File, ParamsComment, Param from ..forms import ProjectEditCommForm, ParamForm2, ModuleParamForm, P...
#!/usr/bin/env python3 import os import html import signal from chwall.gui.shared import ChwallGui from chwall.wallpaper import current_wallpaper_info from chwall.utils import get_binary_path, reset_pending_list import gi gi.require_version("Gtk", "3.0") from gi.repository import Gdk, GdkPixbuf, GLib, Gtk # noqa: E...
errors_semantic = [] def append_error_semantic(fila, column, error): errors_semantic.append(f'({fila}, {column}) - {error}') class Method: def __init__(self, id, parametros, returned_type): self.returnedType = returned_type self.id = id self.args = parametros class Attribute: def...
#!/usr/bin/env python import sys import codecs import csv import os from operator import itemgetter #from VUA_pylib.lexicon import MPQA_subjectivity_lexicon def get_first_term_id(token_data,term_data,this_ids): vector_tid_pos = [] for tid in this_ids: span_token = term_data[tid][2] min_token...
# @Author: Ivan # @Time: 2020/11/16 import os import time import argparse import torch from torch import nn import torch.optim as optim import torch.nn.functional as F from torchvision import utils import matplotlib.pyplot as plt from utils.datasets import create_dataloader from utils.util import parse_cfg from models ...
""" Created on Mar 1, 2014 @author: briank Get the internet address and make reports available for web interface. Since PyHouse is always running (as a daemon) this module will get the IP-v4 address that is assigned to our router by the ISP. It will then take that IP address and update our Dynamic DNS provider so w...
import numpy as np import logging import sys from enum import Enum import matplotlib.pyplot as plt from collections import namedtuple from sklearn.datasets import load_boston from sklearn.preprocessing import PolynomialFeatures from sklearn.model_selection import train_test_split, KFold logging.basicConfig(stream=sys....
import tkinter as tk import vlc import os import cv2 import HandTracking as ht import math import numpy as np import sys import time import platform if sys.version_info[0] < 3: import Tkinter as Tk from Tkinter import * from Tkinter.filedialog import askopenfilename else: import tkinter as Tk fro...
################################## 2222222222222222222 ##################################### #!/usr/bin/python3 import os import json import logging import requests logger = logging.Logger('catch_all') def query_az(query): json_cis=os.popen(query).read() return json.loads(json_cis) def check21...
#!/usr/bin/env python import os, sys import joblib from copy import deepcopy from typing import Optional, Dict, Tuple, List import numpy as np np.set_printoptions(precision=5, suppress=True) import wfdb import torch from torch import nn from scipy.signal import resample, resample_poly from easydict import EasyDict as...
import pandas as pd import os from os.path import join import logging from datetime import datetime import sys # TODO: Quota management # TODO: Fix file not fond error # TODO: Make filecount check - if 0 - do not continue def get_export_files(directory): """ Return a list of UPCC export files from given dire...
import numpy as np # Navigation Views import navigation_vis.Raster as NavGridView from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import cm as cm, pyplot as plt, colors as mplotcolors def plot_grid_data_helper(data, ann=None, ann_sz=12, ann_col="black", title=None, grid=None, cmap=cm.viridis, ...
from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, f1_score from sklearn import metrics from sklearn.metrics import precision_recall_curve from dataset import dataset_names import numpy as np import torc...
import sys import os import torch from allennlp.data.iterators import BucketIterator from allennlp.data.iterators import BasicIterator from allennlp.modules.text_field_embedders import TextFieldEmbedder import torch.optim as optim from acsa.acsc_pytorch.my_allennlp_trainer import Trainer from allennlp.data.vocabulary ...
from collections import defaultdict from openpyxl import Workbook, load_workbook from openpyxl.styles import Font, Alignment, PatternFill, Protection from openpyxl.utils import coordinate_to_tuple from .trie import OntTrie from .dataval import DataVal from .utils import resize_sheet def tagged_to_trie(tagged, onto_...
""" Chapter 5: Multivariate Outlier Detection """ import pandas as pd import json from pandas.plotting import parallel_coordinates import matplotlib.pyplot as plt import plotly.plotly as ply import plotly.graph_objs as go from plotly.offline import plot as plyplot import seaborn as sns from sklearn.decomposition impor...
""" Implement NST """ from __future__ import print_function import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from PIL import Image import matplotlib.pyplot as plt import torchvision.transforms as transforms import torchvision.models as models import copy import os ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import pandas as pd from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.mod...
#Import Libraries import signal import warnings warnings.filterwarnings('ignore') import sys import RPi.GPIO as GPIO import time import datetime import os import random from pydub import AudioSegment from pydub.playback import play import numpy as np from gtts import gTTS import os #Definition of motor pins on respec...
# BlueGraph: unifying Python framework for graph analytics and co-occurrence analysis. # Copyright 2020-2021 Blue Brain Project / EPFL # 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 a...
import json import websocket from tqdm.notebook import tqdm import requests import hashlib import hmac import time import requests import uuid import datetime from agents.stock_agent import BackTest from configparser import ConfigParser import uuid from urllib.parse import urlencode class LiveTrader(BackTest): de...
# Copyright (c) 2020 PaddlePaddle 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 appli...
from io import BytesIO from buidl.helper import ( encode_varint, hash256, int_to_little_endian, read_varint, read_varstr, ) from buidl.siphash import SipHash_2_4 BASIC_FILTER_TYPE = 0 GOLOMB_P = 19 GOLOMB_M = int(round(1.497137 * 2 ** GOLOMB_P)) def _siphash(key, value): if len(key) != 16: ...
import importlib from rest_framework import serializers class InvalidValue(Exception): def __init__(self, ref, expected_type=None): message = "The value for %s is invalid." % ref if expected_type is not None: message += " Expected type or types %s." % expected_type super().__i...
""" Module containing the ImageJ ROI encoder/decoder. This module was adapted from the mahotas-imread package (https://github.com/luispedro/imread) written by <NAME> (<<EMAIL>>) and published under the MIT license. ROI format definition: ImageJ/NIH Image 64 byte ROI outline header 2 byte numbers are big-endian signed...
from functools import partial import numpy as np import tensorflow as tf from sklearn.preprocessing import OneHotEncoder from cleverhans.attacks.fast_gradient_method import optimize_linear from cleverhans import utils_tf from cleverhans.utils_tf import clip_eta from .robust_nn.eps_separation import find_eps_separated...
#!/usr/bin/env python import json import pickle import numpy as np #======================================================================= PERIODIC_DICT = {'True': 1, 'False': 0} #======================================================================= def pickle_load(file_name): return pickle.load(open(file_n...
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by <NAME> (<EMAIL>) # ------------------------------------------------------------------------------ import os import pdb import sys sys.path[0] = os.getcwd() ...
#!/usr/bin/python3 import click import nisyscfg from nisyscfg.errors import LibraryError class DeviceNotFoundError(Exception): pass @click.group() def nisyscfgcli(): """Manipulate hardware resources detected by NI System Configuration API ==================================================================...
#!/usr/bin/env python # Copyright (C) 2014 Claudio "nex" Guarnieri. # This file is part of Habu - https://github.com/botherder/habu # See the file 'LICENSE' for copying permission. # Big up for @ochsff for allowing me to rip off part of his code. import os import re import sys import time import shutil import argpars...
import enum import os, sys current_path = os.path.dirname(os.path.realpath(__file__)) PROJECT_HOME = os.path.abspath(os.path.join(current_path, os.pardir)) if PROJECT_HOME not in sys.path: sys.path.append(PROJECT_HOME) class AgentMode(enum.Enum): TRAIN = "TRAIN" TEST = "TEST" PLAY = "PLAY" class OS...
# Copyright 2020 Polo Digital Assets, Ltd. # # 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, publis...
import tdl from sys import exit as closeProgram import time _SCREEN_WIDTH = 80#80 is default _SCREEN_HEIGHT = 25#25 is default _LIMIT_FPS = 10 # 20 frames-per-second maximum try: tdl.set_font('shadowpriest12x20.png', greyscale=False, altLayout=False) except: try: tdl.set_font('shadowpriest16x24_gs_r...