text
stringlengths
3.07k
22.1k
""" Hierarchical link clustering ============================ :Author: <NAME> (adapted to the CLICS use case by <NAME>) This is an implementation of the hierarchical link clustering algorithm of Ahn et al. The results provided by this implementation match those of the original Python implementation of the authors, bu...
"`gen_doc.nbdoc` generates notebook documentation from module functions and links to correct places" import inspect,importlib,enum,os,re from IPython.core.display import display, Markdown, HTML from typing import Dict, Any, AnyStr, List, Sequence, TypeVar, Tuple, Optional, Union from .docstrings import * from .core im...
import asyncio import json from statistics import mean from operator import sub import traceback import aiohttp import discord from discord.ext import tasks from yaml import load try: from yaml import CLoader as Loader except ImportError: from yaml import Loader config = load(open('config.yaml', 'r'), Loader...
#!/usr/bin/env python3 ''' A script for making topic models Copyright 2013-2018 RIKEN Copyright 2018-2020 Chiba Institute of Technology 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...
import datetime as dt import numpy as np from ravenpy.config.commands import LU from ravenpy.models import SACSMA, SACSMA_OST from ravenpy.utilities.testdata import get_local_testdata TS = get_local_testdata( "raven-gr4j-cemaneige/Salmon-River-Near-Prince-George_meteo_daily.nc" ) hru = SACSMA.HRU( area=4250...
""" Created: 2013-10-31 14:56:21 Author: <NAME> Various tools useful for doing standard econometric analysis. """ import numpy as np import numpy.linalg as la import pandas as pd import statsmodels.formula.api as sm from scipy import stats __all__ = ['iv2sls', 'bootstrap', 'wald', "wu_test", 'cluster_se'] def iv...
# -*- coding:utf-8 -*- import pytest from gitticket import github from gitticket import ticket from gitticket import config from gitticket import util def mock_git(): return {'ticket.name': 'user', 'ticket.repo': 'testrepo', 'ticket.service': 'github', 'ticket.format.list': 'l...
import os import shutil import xml.etree.ElementTree as ET from enum import Enum from collections import defaultdict import json import re class DF2(Enum): short_sleeve_top = 1 long_sleeve_top = 2 short_sleeve_outwear = 3 long_sleeve_outwear = 4 vest = 5 sling = 6 shorts = 7 trousers...
#!/usr/bin/env python import telebot from random import randint from timeSerial.mlp.mlp_class import mlp print("Entrenando redes") ann = {'19727': {}, '24325': {}, '24292': {}, '24344': {}, '24289': {}} ann['19727']['buy'] = mlp('buy', '19727', 12, 700, 15, 0.01) ann['24325']['buy'] = mlp('buy', '24325', 12, 700, 15,...
import torch import torch.nn as nn import numpy as np from utils import * from auto_LiRPA.bound_ops import * from datasets import cifar10_mean, cifar10_std from torch.autograd import Variable import pdb import random criterion = ce_loss def init_delta(X, epsilon, data_min, data_max): delta = torch.zeros_like(X) ...
import io from xml.dom.minidom import parseString from xml.sax.saxutils import XMLGenerator class DataCiteRenderer(object): scheme_uri_choices = { 'ORCID': 'https:/orcid.org', 'ROR': 'https://ror.org' } def __init__(self): self.stream = io.StringIO() self.xml = XMLGenerat...
# -------------------------------------------------------- # TAFSSL # Copyright (c) 2019 IBM Corp # Licensed under The Apache-2.0 License [see LICENSE for details] # -------------------------------------------------------- import numpy as np from utils.proto_semi import ProtoSemi import time import pickle from utils.m...
import glob import logging import os import shutil import subprocess from urlparse import urlparse from bd2k.util.exceptions import require from toil.lib.docker import dockerCall _log = logging.getLogger(__name__) def download_url(job, url, work_dir='.', name=None, s3_key_path=None, cghub_key_path=None): """ ...
""" Python API for interacting with edx-platform's new XBlock Runtime. For content in modulestore (currently all course content), you'll need to use the older runtime. Note that these views are only for interacting with existing blocks. Other Studio APIs cover use cases like adding/deleting/editing blocks. """ impor...
#-*- coding =utf-8 -*- import bpy import bgl import blf from bpy.types import Object, Scene, Panel, Operator,Menu from bpy.props import * from .Ops_Extra import get_region_size,CN_ON def set_store_ev(context): cam = context.scene.camera.ssm_cam cam.StoreEV = True def set_cam_ev(context): cam = context...
#!/usr/bin/env python import sys import csv __doc__ = """ Generates IPTables commands based on a simple CSV configuration file Ensures basic operation and uses some basic good practices: - Switches default policy on INPUT and OUTPUT chains to ACCEPT, so when you flush the rules you won't get kicked out of the se...
import collections from pyphonetics import RefinedSoundex from Levenshtein import distance from PyQt5.QtWidgets import QMainWindow, QApplication from PyQt5.QtGui import QStandardItemModel, QStandardItem from PyQt5 import QtGui from ui import speller from engine import classifier, frequency, utilities from db import wor...
# The MIT License (MIT) # Copyright (c) 2021-present foxwhite25 # # 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, ...
#!/usr/bin/env python import sys import functools as ft import argparse import logging import re import subprocess import itertools as it import tempfile import io import jinja2 from networkx.drawing.nx_pydot import read_dot import os def flatten(lss): if len(lss) == 0: return [] return ft.reduce(l...
# Copyright (c) 2013-2015 <NAME> et al. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, ...
from bs4 import BeautifulSoup import requests import json from bselib.getId import getScript_id headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'} invalid_script_code = {'info' : 'Not a valid script_code'} error = {'info' : 'E...
import pdb import numpy as np import mxnet as mx assert mx.__version__ > '0.11.0' # required for autograd.grad() from mxnet import nd from mxnet import gluon from mxnet import autograd from typing import Tuple from .layers import LatentLayer from .layers import ObservationLayer EPSILON = np.finfo(float).eps class...
#The MIT License (MIT) # #Copyright (c) 2016 <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, p...
# required by Sphinx from docutils import nodes from docutils.parsers.rst import Directive, directives from sphinx.locale import _ from sphinx.util.docutils import SphinxDirective from sphinx.errors import ExtensionError # required for file system path building import os import pathlib # required to generalte HTML fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology. # SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>> # NOTICE: authors should document their contributions in concisely in NOTICE # with details inline in source files...
"""Horus Media""" # Copyright(C) 2019, 2020 Horus View and Explore B.V. from dataclasses import dataclass from PIL import Image from itertools import chain from enum import Enum import urllib.parse import io import math import json import logging import http.client @dataclass class Point: x: float = 0 y: f...
from .utils import * import math import os from .label_config import max_step, max_param from misc import get_distance_to_center from .complex_base import draw_new_base ################################### # generate club chairs # seat-top can be: square, circle, rectangle # supports can be: circle, square # bottom bas...
#!/usr/bin/env python3 import re import os import json import numpy as np import multiprocessing as mp import matplotlib #matplotlib.use('TkAgg') import matplotlib.pyplot as plt import glob import measurement import datetime import webbrowser from pathlib import Path from markdown import markdown ...
"""Kalman filters for exact inference in linear-Gaussian state-space models.""" import abc from typing import Optional, Sequence, Tuple, Dict import numpy as np from numpy.random import Generator import numpy.linalg as nla import scipy.linalg as sla from dapy.models.base import AbstractLinearGaussianModel from dapy.ut...
from ast import literal_eval from copy import deepcopy import logging import math from pathlib import Path import torch from torch.nn import ( BatchNorm2d, Conv2d, LeakyReLU, Module, ModuleList, Parameter, ReLU, ReLU6, Sequential, SyncBatchNorm, ) import yaml # for torch hub f...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Openstack LLC. # 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/...
import os import sys import time import shutil import subprocess from itertools import permutations import pickle from pydub import AudioSegment import librosa import pandas as pd def print_progress(count, total): ''' Print a progress in the terminal :param count: :param total: :return: ''' ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 2 15:42:00 2018 @author: qpetit """ #For MacOSx from sys import platform as sys_pf if sys_pf == 'darwin': import matplotlib matplotlib.use("tkAgg") import numpy as np import sys if sys.version_info[0] < 3: from Tkinter import * i...
import copy import frappe from faker import Faker from frappe.model import (table_fields, data_fieldtypes, no_value_fields, display_fieldtypes, optional_fields, default_fields, numeric_fieldtypes, core_doctypes_list) from frappe.utils import cstr from renovation_core.utils.json_generator impo...
import sys from logging import getLogger from django_filters.constants import EMPTY_VALUES from rest_framework import exceptions from caluma.data_source.data_source_handlers import ( get_data_source_data, get_data_sources, ) from . import jexl from .format_validators import get_format_validators from .models...
# anchor_txt: attributes in markdown # # Copyright (C) 2019 <NAME> <github.com/vitiral> # # The source code is Licensed under either of # # * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or # http://www.apache.org/licenses/LICENSE-2.0) # * MIT license ([LICENSE-MIT](LICENSE-MIT) or # http://openso...
""" MIT License Copyright (c) 2019 Max Planck Institute of Molecular Physiology Author: <NAME> (<EMAIL>) Author: <NAME> (<EMAIL>) Author: <NAME> (<EMAIL>) 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 ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 10:02:26 2021 @author: lakri """ import math import vtk from random import random import numpy as np from vtk.numpy_interface import dataset_adapter as dsa def create_3d_grid(pd_in): points = vtk.vtkPoints() lines = vtk.vtkCellArray() bounds = pd_in.GetBo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # xarray-simlab documentation build configuration file, created by # sphinx-quickstart on Sun Jun 11 14:04:24 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in thi...
# Copyright (c) 2014 Rackspace, Inc. # # 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 wr...
import contextlib from typing import Dict, Optional, Tuple import websockets as ws from uuid import UUID import logging import asyncio import json from db import DBconn from mpc_manager import TallierManager, Tallier from mpc import MpcValidation, MpcWinner from mytypes import Election, ElectionType running_election...
import aiohttp from aiohttp import web import asyncio import logging import pprint import struct import pickle _proxies = {} _proxied_websockets = {} modes = ("http", "ws", "ws_create") def msg_pack(mode, header, payload): assert mode in modes, (mode, modes) if mode == "ws": if isinstance(pay...
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 <NAME> # # 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/...
# ############################################################################ # import os, sys from amanzi import input_tree # ############################################################################ # class AmanziDataOutput: CYCLE_REGEX_PATTERN = r".h5.(\d+).xmf" XMF_TIME_TAG = "Time" XMF_TIME_...
import common as c from config import qt_modules, qt_version, qt_dir, os_name import sys import xml.etree.ElementTree as ET import shutil import os qt_modules_list = list(qt_modules.split()) c.print('>> Downloading Qt {} ({}) for {}'.format(qt_version, qt_modules_list, os_name)) # 5.9.9 : mingw53 # 5.10.1 : mingw53 ...
"This module provides various low-level inter-Actor transport implementations." from datetime import timedelta from thespian.system.timing import ExpirationTimer, currentTime from thespian.system.utilis import thesplog import logging DEFAULT_MAX_TRANSMIT_PERIOD = timedelta(minutes=5) TRANSMIT_RETRY_PERIOD = ti...
import os import numpy as np import pandas as pd import codecs, json import math import time from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LinearRegression import statsmodels.api as sm from neighbors_generation import * def SplitBasedSelectionForm (data, target, k, model,lis...
#!/usr/bin/env python3 import os import time import tomlkit import shm from conf.vehicle import VEHICLE # The directory where the serial toml config files are located SERIAL_CONF_DIR = '/home/software/cuauv/software/serial/seriald/conf' # The name of the motor desires SHM group MOTOR_DESIRES = 'motor_desires' # The ...
""" The `link` step resolves the columns provided by each tabular node. * We start with the leaf `Box` node, which typically wraps a Select node, and add the columns used in the output to its `refs` list. * Then, we propagate upwards. * Each tabular node wrapped in a `Box` node reads the `refs` from its box, and...
import subprocess, sys, re, os, threading, shutil from threading import Thread from subprocess import PIPE, Popen from time import sleep def main_downloader(audio_or_video): global url_string global playlist global destination global playlistsettings global audio_format global video_format ...
""" Test Suites """ from __future__ import generators import sys import unittest from nose_helper.case import Test from nose_helper.config import Config from nose_helper.util import isclass, resolve_name, try_run PYTHON_VERSION_MAJOR = sys.version_info[0] class LazySuite(unittest.TestSuite): """A suite that may us...
import pytest import inspect from ipaddress import IPv4Address, IPv4Network from prettytable import PrettyTable import numpy as np from CybORG import CybORG from CybORG.Shared.Actions import Remove from CybORG.Shared.Enums import TrinaryEnum from CybORG.Agents.SimpleAgents.B_line import B_lineAgent from CybORG.Agents...
from subprocess import Popen from typing import List from typing import Optional from typing import Union import itertools import os import os.path import pytest import unittest import sys IBCOMM_INVALID_ARGUMENT = 1 IBCOMM_IBVERBS_ERROR = 2 IBCOMM_CUDA_ERROR = 3 IBCOMM_NOT_SUPPORTED = 4 ALGO_RING = "ring" ALGO_RABE...
import numpy as np import random from collections import namedtuple, deque import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from utils.replay_buffer import ReplayBuffer class DQNAgent(): """Interacts with and learns from the environment.""" def __init__(self, st...
from pathlib import Path,PosixPath from tqdm import tqdm import requests import shutil import multiprocessing from pqdm.threads import pqdm import librosa import string import os from fastcore.basics import patch,setify import numpy as np from fastcore.foundation import L from pdb import set_trace from sk.const import ...
import datetime import pytest import mock import jinja2 from h import presenters class TestAnnotationHTMLPresenter(object): def _annotation(self, annotation=None, **kwargs): """Return an AnnotationHTMLPresenter for the given annotation. If no annotation is given a mock will be used, and any ke...
import numpy as np import random import torch import sys import argparse from sys import argv, stdout import pathlib import copy from utils import get_config from environment import CircuitEnv import agents import time torch.set_num_threads(1) class Saver: def __init__(self, results_path, experiment_seed): ...
#!/usr/bin/env python3 """ 2x2 Rubiks cube model and solver """ import queue import numpy as np import sys def permutation_matrix(N, srcs, dsts): """Make an NxN permutation matrix that when multiplied by an Nx1 column vector takes entries at indices srcs to dsts. """ M = np.identity(N, dtype='int64')...
"""monitoring.py monitoring communications etc """ #print("module {0}".format(__name__)) from ..aid.sixing import * from .globaling import * from ..aio.udp import PeerUdp from . import excepting from . import tasking from ..aid.consoling import getConsole console = getConsole() #Class definitions class Monitor(t...
import os, sys; sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import numpy as np import pickle, h5py, time, argparse, itertools, datetime import torch import torch.nn as nn import torch.utils.data from libs import SynapseDataset, collate_fn, res_unet, res_unet_plus from libs import BCLos...
''' Script to collect sensor readings from an OkoFEN pellet boiler. ''' from datetime import datetime, timedelta, date import sys import io import urllib.parse import traceback import re import calendar import requests import pandas as pd import pytz # Parameters that are State-type values instead of continuous analog...
# -*- coding: utf-8 -*- """ @author:XuMing(<EMAIL>) @description: train seq2seq model # #### PyTorch代码 # - [seq2seq-tutorial](https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb) # - [Tutorial from <NAME>](https://github.com/bentrevett/pytorch-seq2seq) # - [IBM seq2seq](...
#!/usr/bin/env python3 # -*- coding: utf8 -*- import argparse import sys import os import numpy as np import modules.segmentation_points as segment from modules.data_set import DataSet from modules.segmentation_kind import * from modules.sensors import sensors from modules.constants import * from plotter import main_i...
# -*- coding: utf-8 -*- """ Created on Thu Aug 19 02:36:14 2021 @author: SONG """ import numpy as np import pandas as pd import datetime as dt # CBO Potential Output is computed from the Real Gross Domestic Product # including <nonfarm business, goverment, farm, household and non-profit institutions and ...
"""Sun position management. All relevant functionality is contained in the SunData class. """ import numpy as np import time import pandas as pd import requests import json import geopy import datetime as dt import matplotlib.pyplot as plt import io from scipy.interpolate import interp1d from scipy.constants import ...
'''Interfaces for supported data-structures''' from stdnet.utils import listPipeline, many2manyPipeline __all__ = ['PipeLine', 'pipelines', 'Structure', 'List', 'Set', 'OrderedSet', 'HashTable'] class keyconverter(object): @cl...
from __future__ import print_function import sys import cv2 import numpy import scipy.ndimage import skimage.feature import skimage.morphology import skimage.filters import skimage.measure import skimage.color from blob_finder import BlobFinder class BaseObjectFinder(object): def __init__(self,param): ...
""" Description: This library must load and manipulate data from the LIT dataset. Author: <NAME> (<EMAIL>) October 2020 """ import os from typing import TypeVar, Iterable, Tuple, List from enum import Enum from scipy.io import loadmat import numpy as np lit_path = os.path.join('LIT_Dataset','Matlab_Data') def set...
#!/usr/bin/env python import argparse import stringrnautils import collections import os import logging logger = logging.getLogger(os.path.basename(__file__)) logging.basicConfig(level=logging.INFO) __author__ = '<NAME> (<EMAIL>)' def is_valid_path(arg): if not os.path.exists(arg): parser.error("Given m...
#!/usr/bin/env python #* Team Id : SR#7147 #* Author List : <NAME> #* Filename: roi_detector.py #* Theme: Survay And Rescue #* Functioning : This script detects and store the ROI with their cell/block name. We used the pickle module to store ROI arrays, with name "rect_info.pkl" # We did this using OpenCV, detecte...
import importlib import peeps importlib.reload(peeps) from peeps import * (start_time, f, cam) = script_init(__file__, False) # a block moving around with a lamp in the midst def block_with_lamp(): # let's go as simple as we can, by starting with a red block block = Block(6, 6, 6, ORIGIN, RED) # just loo...
import functools import heapq import logging import time import tqdm import numpy as np import scipy import scipy.sparse import alsi.cuda from . import _als from .recommender_base import MatrixFactorizationBase from .utils import check_blas_config, nonzeros log = logging.getLogger("alsi") class AlternatingLeastSqu...
# %% import hashlib import json import re from pathlib import Path import geopandas import pandas as pd from IPython.display import display # noqa E401 from constants import CaseTypes, Columns, Locations, Paths GEO_DATA_DIR = Paths.DATA / "Geo" CODE = "code" DATA_DIR: Path = Paths.DOCS / "data" DATA_DIR.mkdir(exi...
import shutil import pandas as pd from tabulate import tabulate def get_terminal_size(): return shutil.get_terminal_size().columns def show_pos_merge_position(self, df, first_df): if "Strand" in df: pos = df.Chromosome.astype(str) + " " + df.Start.astype( str) + "-" + df.End.astype(s...
#!/usr/bin/env python3 """ Usage: app.py [-d FILE] app.py (-h | --help) Options: -h, --help -d, --db_url=FILE """ from flask import Flask, render_template, render_template_string, request, redirect, url_for from coffee_src import MysqlConnector from coffee_src import dynamic_form import os from werkzeug.datas...
""" PyMdown Settings. Manage Settings Licensed under MIT Copyright (c) 2014 - 2015 <NAME> <<EMAIL>> """ from __future__ import unicode_literals from __future__ import absolute_import import codecs import traceback import os.path as path import cgi from collections import OrderedDict from copy import deepcopy from .. ...
import os import collections class KeyValues(collections.MutableMapping): """Class for representing Key Values objects, with container behavior. This class implements the tree data structure used by KeyValues, exposing method for acting like a python Dictionary, but keeping the key order. It also imp...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import ndef import pytest import _test_record_base def pytest_generate_tests(metafunc): _test_record_base.generate_tests(metafunc) class TestUriRecord(_test_record_base._TestRecordBase): RECORD = ndef.uri.UriRecord ATTRIB = "iri,...
import json import logging from datetime import datetime, timedelta from unittest.mock import patch import boto3 import factory import faker import pytest import testing.postgresql from factory import fuzzy from jose import jwt from moto import mock_cognitoidp, mock_s3, mock_secretsmanager from sqlalchemy import creat...
# -*- coding: utf-8 -*- ''' 虽然是10线程,但好像没四线程的快。 这个是我测试用的,本来下用for循环,循环定义参数,但是。。。没成功……放弃了。 ''' from math import sqrt from sklearn import neighbors from os import listdir from os.path import isdir, join, isfile, splitext import pickle import face_recognition from face_recognition import face_locations from face_recognition...
import re from datetime import datetime from docassemble.base.util import DADateTime, as_datetime, validation_error from docassemble.base.core import DAObject from docassemble.base.functions import get_config from typing import List, Dict, Tuple, Any, Callable def convert_court_to_id(trial_court) -> str: if isinstan...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from config import _export_dir, _data_dir import pandas as pd import shapely as sp import shapely.geometry as shp import json import math import geopandas as gpd import numpy as np from scipy.spatial import Voronoi def get_dynamic_edgelist(data): """ Make an edge l...
# Copyright 2017 <NAME> import tensorflow as tf from layers import InputLayer from parameter import Parameter class INeuralNetwork: def get_input_layer(self, input_id): pass def set_input_layer(self, input_id, input_layer): pass def get_output_layer(self): pass def get_inpu...
from nlpia.data.loaders import get_data from nltk.tokenize import casual_tokenize import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from nltk.stem import PorterStemmer # import nltk # nltk.download('wordnet') # noqa # from nltk.stem.wordnet import WordNetLemmatizer corpus = get_data('ca...
""" Created on Fri Dec 24 2021 21:41 EST @author: ape-ron """ ''' Support functions for uniswap v3 math and requests on positions ''' from dotenv import load_dotenv load_dotenv('../.env') import numpy as np from web3.auto.infura import w3 from pathlib import Path import requests import datetime from .UNI_v3_funcs i...
""" dataclasses =========== Wrappers around Python's dataclasses to support slots and defaults. License ------- Copyright 2019 NEM 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 cop...
# ##### BEGIN BSD LICENSE BLOCK ##### # # Copyright 2017 Funjack # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions an...
from collections import ChainMap import llvm_util as lu from typeunion import TypeUnion import ltypes as lt import memory from dbg import * class MLtype: def isTypeVariable(self): return False def isDirectlyRecursive(self, subst): # this function doesn't really work. don't use check = [self] ...
#!/usr/bin/env python3 # coding: UTF-8 import json import pickle import random import re import time from collections import deque from datetime import datetime, timedelta from apscheduler.schedulers.background import BackgroundScheduler from cqsdk import CQBot, CQAt, RE_CQ_SPECIAL, RcvdPrivateMessage, \ RcvdGrou...
# -*- coding: utf-8 -*- """:Mod: public_no_access_json :Synopsis: Reports PASTA metadata and data resources that lack public read access, outputs the report as JSON formatted text. :Author: <NAME> :Created: 2/16/18 """ import logging import os import sys from base64 import b64decode, b64encode from...
import sys import os import pytest sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from whr import whole_history_rating from whr import utils def setup_game_with_elo(white_elo, black_elo, handicap): whr = whole_history_rating.Base() game = whr.create_game("black", "white", "W", 1, handicap) ...
import sys import argparse import os config_file_names = ['config', 'config_prep', 'config_rec', 'config_disp', 'config_data'] # Map file of before/after keys to remap config_map = {'beamline': 'beamline', 'specfile': 'specfile'} config_prep_map = {'darkfile': 'darkfield_filename', 'whitefile': 'whitefield_filename...
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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...
from contextlib import redirect_stdout, redirect_stderr import io import os import pathlib import shutil import tempfile import urllib.parse from docutils import nodes import docutils.core from qiime2.plugin import model from qiime2.plugins import ArtifactAPIUsage from qiime2.sdk.usage import Usage, ExecutionUsageVar...
#!/usr/bin/env python """ This manages the global state that the ssh client needs to validate servers and authenticate (hostkey(s), username, public key). """ import os import csv import base64 import hmac import sys from hashlib import sha1 from tempfile import mkstemp from twisted.python import log from sshproxy....
""" k means on the sphere Adapted from this stack overflow answer http://stackoverflow.com/questions/5529625/is-it-possible-to-specify-your-own-distance-function-using-scikit-learn-k-means """ from __future__ import print_function from __future__ import division import random import numpy _TOL_DEF=1.0e-5 _MAXITER_...
from threading import RLock as _Lock import numpy as np def _thread_safe(fn): """Decorator that expects a class method which has a _lock attribute. Args: fn: Method to be wrapped. Returns: method: The wrapper method """ def wrapper(*args, **kwargs): self = args[0] ...
import struct import time import traceback from math import pi from threading import Event, RLock, Thread from typing import NamedTuple, Union, Optional, Tuple from typing_extensions import Literal import serial import serialpackets # Wheel constants ENCODER_PPR = 2912 WHEEL_DIA_CM = 13.5 WHEEL_CIR_CM = pi * WHEEL_DI...
# The MIT License (MIT) # # Copyright (c) 2016 JustBurn # # 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, sys import numpy as np from pyhdf.SD import SD, SDC from scipy import ndimage import glob import pandas as pd import xarray as xr from joblib import Parallel, delayed ''' # Basic parameters lat_0 = 60 lon_0 = -180 res_x = 0.01 # 0.02 for the 2km grid res_y = 0.01 # 0.02 for th...