text
stringlengths
3.07k
22.1k
import math import collections class Cell(object): def __repr__(self): return 'C{val}'.format(val=self.val) def __str__(self): return self.__repr__() def __init__(self, board, val, x, y): self.val = val self.change = False self.x = x self.y = y sel...
import os import json import random import numpy as np import spacy import pickle # from from collections import Counter from tqdm import tqdm nlp = spacy.blank("en") def word_tokenize(sent): doc = nlp(sent) return [token.text for token in doc] def convert_idx(text, tokens): current = 0 spans = []...
from torch.utils.data import DataLoader, Dataset, Sampler from pathlib import Path from collections import defaultdict import json import random from multiprocessing import Pool import h5py import pickle import math from tqdm import tqdm import torch import numpy as np from copy import deepcopy import re import glob f...
from typing import Tuple, List, Union, Any, Callable, Optional from copy import deepcopy import pickle from threading import Thread from selenium import webdriver from selenium.webdriver import ChromeOptions from selenium.common.exceptions import TimeoutException, WebDriverException from selenium.webdriver.remot...
"""Subscriber for the Smart Device Management event based API.""" import asyncio import concurrent.futures import json import logging import re from abc import ABC, abstractmethod from typing import Awaitable, Callable, Optional from aiohttp.client_exceptions import ClientError from google.api_core.exceptions import G...
# coding: utf-8 from __future__ import unicode_literals import json import logging from base64 import b64encode import requests from admitad.constants import DEFAULT_PAGINATION_LIMIT, DEFAULT_PAGINATION_OFFSET, \ DEFAULT_REQUEST_TIMEOUT, MAX_PAGINATION_LIMIT, TOKEN_URL from admitad.exceptions import HttpExceptio...
#!/usr/bin/env python # coding:utf-8 import subprocess import shutil from xml.dom import minidom import zipfile import os import re import glob import sys import codecs import random import string import time # from elf_header import ELF # from study.day14_jiagu.apk_auto_enforce.elf_header import ELF ...
from collections import deque, defaultdict import unittest def gen_parikh_set(w, k, sigma_size=2): """Generates the P_k set of the given w word.""" pi_k_set = set() n = len(w) assert k <= n t = [0] * sigma_size # create the first slice for i in xrange(k): t[w[i]] += 1 pi_k_set...
#!/bin/env python # Author : <NAME> # GitHub : https://github.com/unix121 # Date : 2 December, 2017 # Description : Python script used to export URLs from ClueWeb09 database # Usage : python clueweb_export.py /input/directory/ /output/directory/ import gzip import sys import...
# License: BSD 3 clause """ This script produces experiments with defaults hyper-parameters (Table 2 and 4) from the WildWood's paper. """ import sys import os import subprocess import time from datetime import datetime import logging import pickle as pkl import numpy as np import pandas as pd import argparse fro...
from mpl_toolkits.axes_grid1.inset_locator import inset_axes import pandas as pd import matplotlib from matplotlib.colors import ListedColormap from matplotlib.patches import Patch, PathPatch import numpy as np matplotlib.rcParams['hatch.linewidth'] = 0.4 class Symbology: """ This is the symbology definition...
from tkinter import * from tkinter import messagebox from tkinter import ttk import math import heapq import numpy as np import time class Node(): def __init__(self, parent = None, position = None): self.parent = parent self.position = position self.h = 0 self.g = 0 self...
# -*- coding: utf-8 -*- """ Created on Sun Sep 13 14:27:14 2020 @author: niels """ import os import sys import re import zipfile from shutil import rmtree from scroll_pdf import save_jpg,save_pycode_jpg import matplotlib.pyplot as plt def sstr(s): return s.encode('ascii', errors='ignore').decode('utf-8') class ...
''' Decode ''' import argparse import json import torch from torch.utils.data import DataLoader from nltk.translate import bleu_score from config import DEVICE, MAX_LENGTH from main import init, load_dataset from src.voc import voc from src.dataset import ExtBuilder from src.decoder import SearchDecoder, ExtractDec...
import os import pickle import re import urllib.request import zipfile from datetime import timedelta, datetime, date import pandas as pd from matilda import config def resample_df(df: pd.DataFrame): # infer frequency test_0, test_1 = df.index[:2] # take two consecutive elements delta = (test_1 - test_0)...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange from util import log from pprint import pprint from model import Model from input_ops import create_input_ops import os import time import numpy as np import tensorflow.contrib.s...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, <NAME> <<EMAIL>> # # 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 version 3 of the License, or # (at your option) any later version....
""" Plot land ice from GRACE Website : https://climate.nasa.gov/vital-signs/land-ice/ Author : <NAME> Date : 28 June 2017 """ ### Import modules import numpy as np import datetime import matplotlib.pyplot as plt import matplotlib.animation as animation import math ### Directory and time directoryfigure = ...
#%% import re import numpy as np import cv2 import os import argparse import csv def csv_to_dictionary(csv_file: str,object_classes: str): ''' DESCRIPTION: Converts a .csv file with image paths, labels, and ROIs to a python dictionary. ARGUMENTS: csv_file: input csv file path obj...
import pandas as pd import toml from bs4 import BeautifulSoup import requests # from rich import print_json from pathlib import Path, PosixPath from openpyxl import load_workbook import xlrd import zipfile import itertools import os from loguru import logger OTHER_VARS_TO_STORE = ["long_name", "code", "short_name", "m...
""" this uses cnn_trainer.py and Dijkstra algorithm to identify a melody in scores in """ import time import math import numpy as np import sklearn.metrics from scipy.sparse import csgraph from sklearn.model_selection import train_test_split import misc_tools import settings try: import cPickle as pickle except...
#realtor_graph.py #from neo4j_connect_2 import NeoSandboxApp #import neo4j_connect_2 as neo #import GoogleServices as google #from pyspark.sql import SparkSession #from pyspark.sql.functions import struct from cgitb import lookup import code from dbm import dumb from doctest import master from hmac import trans_36 im...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Interface used by Cyclus to calculate the spent fuel composition.""" __all__ = ["predict", "run_kernel"] import json import numpy as np import os from . import kernel #TODO # - Find a workaround for the ugly calculations that are currently # performed in 'get_inp...
from uuid import uuid4 import boto3 import requests import os import json import time import copy import urllib.request from jose import jwk, jwt from jose.utils import base64url_decode # Setup the AWS clients client = boto3.client('iot-data') ddb_client = boto3.client('dynamodb') # Define the lights available LIGHTS...
import socket import threading from typing import Dict, List, Callable from src.system.controller.python.messaging.parser import decode_message from src.system.controller.python.messaging.messages.hello import HelloMessage from src.system.controller.python.messaging.messages.welcome import WelcomeMessage from src.sys...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 18-5-23 上午11:33 # @Author : MaybeShewill-CV # @Site : https://github.com/MaybeShewill-CV/lanenet-lane-detection # @File : test_lanenet.py # @IDE: PyCharm Community Edition """ test LaneNet model on single image """ import sys sys.path.append("D:\\self-...
#!/usr/bin/env python # Copyright 2015 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. """This script runs an automated Cronet performance benchmark. This script: 1. Sets up "USB reverse tethering" which allow network tra...
import site import os import sys import glob import time from mpi4py import MPI from settings import req_dirs, models_folder, ray_folder from shutil import copyfile import subprocess pathname = os.getcwd() homepath = os.path.expanduser("~") s3pathname = homepath+'/s3-drive/groups/Behavior/Pinaki' def makedirpath(pa...
import math import numpy as np import matplotlib.pyplot as plt import pandas as pd import setting class Nucleation(): def __init__(self, main, df = None): self.main = main self.metal_list = main.metal_list self.collider = main.collider self.Gas = main.Gas self.pure_groups ...
import numpy as np import tensorflow as tf import math from tqdm import tqdm from skimage import io from skimage.transform import resize from skimage.morphology import label from models.unet.common import IoU, mIoU, dice, SEGMENTATION_THRESHOLD from models.unet.data_provider import TestDataProvider cla...
from __future__ import annotations import json import pickle from copy import copy from datetime import date, datetime from pathlib import Path, PurePath from typing import Any, ByteString, Callable, Mapping, Optional, Sequence from typing import Tuple as Tup from typing import Type, TypeVar, Union import orjson impo...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
""" A simple mean reversion strategy with back testing result. The strategy only works when market is ranging, which is around 70% of the time. Rules: Entry: 1. Place a long limit order if: 1) price breaks 20 days low 2) RSI between 30 to 70 3) with entry price as: 20 d...
import glob import os import torch from torch.utils.data import Dataset, DataLoader import numpy as np import matplotlib.image as mpimg import pandas as pd import cv2 class FacialKeypointsDataset(Dataset): """Face Landmarks dataset.""" def __init__(self, csv_file, root_dir, transform=None): """ ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mush_converter.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. import os import...
#!/usr/bin/env python # This Software (Dioptra) is being made available as a public service by the # National Institute of Standards and Technology (NIST), an Agency of the United # States Department of Commerce. This software was developed in part by employees of # NIST and in part by NIST contractors. Copyright in po...
import os import subprocess import json import matplotlib.pyplot as plt from run_benchmarks import cartesian from itertools import zip_longest # meson.debug.linux.x86_64 ROOT = "build/default/benchmarks/" APP_BASIC = "hash_vs_rb_tree_vs_b_tree" # APP_PREFIX = "prefix_combinations" APP_PREFIX = "ovs/ovs_tss_prefix_exe"...
############################################################################### # RTSP server # 2022 Initial Release # <NAME> ############################################################################### # Implementing GstRtspServer # https://github.com/mad4ms/python-opencv-gstreamer-examples/blob/master/gst_rtsp_s...
#!/usr/bin/env python3 __version__ = "1.0" import logging import mimetypes import multiprocessing as mp import os import traceback import warnings import time from contextlib import redirect_stderr, contextmanager from multiprocessing import Pool, Semaphore import click import cv2 import numpy as np from peewee impo...
import base64 import json from traceback import print_exc from typing import Any from typing import Dict from typing import List from typing import Union import requests from fastapi.applications import FastAPI from pyDes import ECB from pyDes import PAD_PKCS5 from pyDes import des from pydantic import BaseModel from ...
""" Automatically generate SGE submission scripts from a template. """ import os import random import subprocess import textwrap class SGEScript(object): """ Base class for SGE submission scripts. Just the bare basics for an SGE submission without any actual code. Parameters: ----------- nam...
import re import subprocess import tempfile import six from tambo import Transport import gbp.patch_series import rhcephpkg.util as util BZ_REGEX = r'rhbz#(\d+)' class BzNotFound(Exception): pass def read_rules_file(): """ Return contents of debian/rules as a single multiline string. """ with open('de...
""" """ import importlib import os import pydoc import shutil import subprocess from datetime import datetime from json.decoder import JSONDecodeError from multiprocessing import Pool import click import terra.database as tdb from terra import Task, _get_task_dir from terra.settings import TERRA_CONFIG from terra.uti...
import contextlib import cmd_ir.instructions as i from .types import Type, DecimalType, UserDefinedInstance, UserDefSymbol from .containers import Temporary, LiteralInt, LiteralDec class EntityFilterExpression: def __init__(self, ptr, key, value): self.ptr = ptr self.sel_key = key self.s...
import tensorflow as tf from meta_policy_search.utils.utils import get_original_tf_name, get_last_scope import tensorflow_probability as tfp tfd = tfp.distributions import os def output_weights(model_out,fast_weights): j=0 #print('len_fast_weights=',len(fast_weights)) for i, layer in enumerate(model_out.l...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import csv import itertools import os import queue import threading import numpy as np import scipy as sp import scipy.ndimage import pandas as pd import pydicom import tensorflow as tf from object_detection.utils import dataset_util from object_detection.utils.visuali...
import rbs_oracle_common import click import logging import sys import datetime import pytz import base64 from configparser import ConfigParser @click.command() @click.option('--source_host_db', '-s', type=str, required=True, help='The source <host or RAC cluster>:<database>') @click.option('--host_target', '-h', ty...
import base64 class RC4: def __init__(self): pass # ------------------------------------ # Verificar se a chave é menor ou igual a 128 bits (128/8) def check_key_size(self, key): if (len(key) > 16): print("\n !! O comprimento da chave não pode ser superior a 128 bits !!") ...
from tensorflow.keras.layers import * from layers import * def create_BridgeNet(name=None, *args, **kwargs): inp = Input((None, None, 18)) c = 64 inp1 = inp[:, :, :, 0:6] inp2 = inp[:, :, :, 6:12] inp3 = inp[:, :, :, 12:18] x1 = Conv2D(c, (3, 3), padding='same', activation=LeakyReLU(...
""" :copyright: Copyright 2021 by the <NAME>. :license: BSD, see LICENSE for details. """ import logging import json import os from enum import Enum from ..datatypes.basic import \ Boolean, \ Uint8, Uint16, Uint32, Uint64, \ Sint8, Sint16, Sint32, Sint64, \ Float32, Float64 from ..dat...
import numpy as np import pickle import random import functools as ft from mcts import MCTSPolicy, CalculateScore, UniformActionPrior, getSoftmaxActionDist, SelectChild, Expand, RollOut, backup, InitializeChildren def greedyActionFromDist(actionDist): actions = list(actionDist.keys()) probs = list(actionDist.values...
"""Main Graph editor widget which is attached to a page of the graphnote book, Each editor houses a graphicsview and graphicsScene. """ import os, logging from functools import partial from qt import QtWidgets, QtCore, QtGui from zoo.libs.pyqt.widgets.graphics import graphicsview from zoo.libs.pyqt.widgets.graphics ...
#!/usr/bin/env python3 # Author: <NAME> (Arinerron) <<EMAIL>> # Writeup: https://aaronesau.com/blog/posts/6 # Product: uftpd 2.6-2.10 # CVE ID: CVE-2020-5221 # This exploit uses a directory traversal vulnerability and escapes uftpd's # crappy implementation of a chroot jail. It does not require authentication. # It ...
import time from collections import defaultdict import torch import math from transformers import AutoTokenizer, GPT2LMHeadModel, GPT2Tokenizer loss_fct = torch.nn.CrossEntropyLoss(reduction='none',ignore_index=0) model = GPT2LMHeadModel.from_pretrained('gpt2').cuda() model.eval() tokenizer = GPT2Tokenizer.from_pretra...
import tensorflow as tf import numpy as np import platform use_xla = 'Windows' in platform.system() import time from types import SimpleNamespace from utils.nerf_utils import * from utils.projection_utils import * from utils.sampling_utils import * from utils.temporal_utils import * from utils.tof_utils import * from...
############################### # # ADD DATE FEATURES # ############################### import numpy as np import pandas as pd import re def add_date_features(df, date_vars, drop = True, ...
"""@package vcu_parameter_identification Top level functions for parameter identification using the updated Voce-Chaboche model. """ from __future__ import print_function import numpy as np from .scipy_constr_opt_factory import scipy_factory from .sqp_factory import sqp_factory from .auglag_factory import auglag_facto...
"""This module contains Module implementations for Kalman filtering. """ import numpy as np import scipy.linalg as spl from modprop.core.modules_core import ModuleBase, InputPort, OutputPort, iterative_invalidate from modprop.core.backprop import sum_accumulators def transpose_matrix(m, n): '''Generate the vecto...
from keras.models import Sequential, Model from keras.utils import plot_model import numpy as np import scipy import sys import argparse from random import randint, uniform import time import matplotlib.pyplot as plt import tensorflow as t import random import cv2 import dlib from imutils.face_utils import rect_to_bb, ...
#!/bin/python3 # # Annual Return Calculator # # File: annual.py # Authors: <NAME> (<EMAIL>) # Date: Tue Aug 31 03:33:42 EDT 2021 # # The authors have placed this program in the public # domain; they make no warranty and accept no liability # for this program. import sys import math import re docu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Copyright (c) 2021 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of t...
import datetime import sys import threading import time import re import RPi.GPIO as GPIO import pymysql from termcolor import colored import credentials from tau_num import tau GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) for pin in range(2, 13): GPIO.setup(pin, GPIO.OUT) GPIO.output(2, 1) ...
import numpy as np from distancematrix.generator.znorm_euclidean import ZNormEuclidean import time def find_variable_length_motifs(series, min_motif_length, max_motif_length, cache_size=3, noise_std=0.): """ Finds the top motif for each subsequence length in the given range. The top motif is defined as the ...
""" Train SNGAN """ import torch from torchvision.utils import save_image import numpy as np import os import timeit from metrics.Inception_Score import inception_score from torch.utils.tensorboard import SummaryWriter import gc from utils import IMGs_dataset NC=3 IMG_SIZE=64 NFAKE_IS_TRAIN = 10000 BATCH_SIZE_IS_TR...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Install script for sktime.""" # adapted from https://github.com/scikit-learn/scikit-learn/blob/master # /setup.py #################### # Helpers for OpenMP support during the build. # adapted fom https://github.com/scikit-learn/scikit-learn/blob/master # /sklearn/_b...
# # Copyright (c) 2016, AnyWi Technologies BV # All rights reserved. # # 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 conditi...
import sys,os import pandas from Bio import SeqIO """ Converter script for Percolator output to create Fido-readable files. By <NAME>, SLIGHTLY MODIFIED BY <NAME> (LABORATORY OF JAMES A WOHLSCHLEGEL) These modifications allow input of multiple tab delimited peptide-level percolator outputs. These outputs will be mer...
#!/usr/bin/env python import rospy import math import csv import numpy as np import scipy from scipy import interpolate from scipy.interpolate import CubicHermiteSpline from nav_msgs.msg import * from hybrid_astar.srv import * from std_msgs.msg import * import pylab as pl import numpy as np import matplotlib.pyplot as...
#! /usr/bin/env python """A script to generate code for high order explicit or implicit BDF methods. By default code for eBDF3 is generated. Play with the code in the main() function to generate other methods. Tested with python 2.76 (but hopefully compatible with python 3+) and sympy version 0.7.4.1. """ from __f...
from random import choice from random import uniform numerical_player_strengh = ["hp", "mp", "sp", "ep"] non_numerical_player_strength = ["strength", "agility", "vitality", "dexterity", "smartness", "magic_power", "mental_strength"] # Used for returning a certain value for a certain situation. # The enemy strength...
import csv import json import os from datetime import datetime import discord from discord.ext import commands from loguru import logger from sqlalchemy import create_engine, and_ from sqlalchemy.orm import sessionmaker # declaration for User class is in here from .utils.easyembed import embed as easyembed from creat...
""" # daycolor daycolor allows you to choose a (RGB) colors for multiple times of the day and fluidly return HSV-interpolated "in-between" colors. The times of the day plus the color may be specified in a the daycolordict as shown below. The daycolordict automagically "wraps around", that means unless desire...
import os from collections import defaultdict import PySimpleGUI as sg from consts import LANGAUGES from utils import create_price_proposal, send_whatsapp, parse_amadeus_code TIMES = [f"{str(h).zfill(2)}:{str(m).zfill(2)}" for h in range(24) for m in range(0, 60,10)] TRAVELERS = ['Child', 'Adult'] COMPARTEMENTS = [...
from collections import defaultdict import tensorflow as tf from smart_compose.utils.parsing_utils import InternalFtrType class KeyValueArrayDict(tf.Module): """A dictionary holding mapping of key -> sparse values In prefix lookup, we need to return tokens starting with user input. A naive approach is to b...
import os import json import pickle import re import numpy as np import matplotlib.pyplot as plt from utils import get_configs, make_dirs def sort_lat_lon(element): return element[0], element[1] def read_dex(file): data = [] all_egg_codes = { 'FAST': -7, 'ICEGLACE': -6, 'BW': -5, 'OW': -4, 'IF':...
import copy from typing import List, Tuple import cirq import numpy as np class MeasurementCircuit: def __init__( self, circuit: cirq.Circuit, stabilizer_matrix: np.ndarray, num_qubits: int, qubits: List[cirq.LineQubit], ) -> None: self.circuit = circuit ...
#!/usr/bin/env python3 from enum import Enum import z3 import attr import pdb import sys num_vars = 24 FLAG = "xB^r_En}INc4v" # This is the true output of the actual flag real_output = (120, 64, 94, 116, 190, 19, 160, 125, 73, 130, 99, 52, 118) # This is the fake answer absolute tease: list(map(ord, "xB^r_En}INc4v"...
# -*- coding: utf-8 -*- """ Created on Sat Jun 5 14:23:25 2021 @author: dan """ import config as cf; import numpy as np; from scipy.spatial import distance; import bpy; import os; def scale_to_root(locs,l_sh,r_sh,root): """ Scale a model to its shoulder width with pelvis at the orgin. Takes a set o...
""" from quickai import TextFineTuning """ from pathlib import Path import json import os import re import numpy as np import tensorflow as tf from transformers import TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, \ DistilBertTokenizerFast, TFDistilBertForQuestionAnswering from sklearn...
from api.db_utils import * import random # Database-Client Interactions def get_weapon_id(name): data = exec_get_one("SELECT id FROM weapons WHERE name=%(name)s;", {'name': name}) if (data is not None): return data[0] else: return None def get_victim_id(name): data = exec_get_one("SEL...
#!/usr/bin/env python from __future__ import unicode_literals from __future__ import print_function """ Builds input/output space. Author: <NAME> Email: <EMAIL> """ import numpy as np from toolz import itemmap __all__ = ['build_vocabulary', 'index_sequence', 'encode_questions_index','encode_questions_one_...
from __future__ import absolute_import import numpy as np import nengo.utils.numpy as npext class Distribution(object): """A base class for probability distributions. The only thing that a probabilities distribution need to define is a ``sample`` function. This base class ensures that all distributions...
# Copyright 2019 Quantapix 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 applicable l...
# Copyright (c) 2018 Copyright holder of the paper Generative Adversarial Model Learning # submitted to NeurIPS 2019 for review # All rights reserved. # modified file from rlrl repo import torch import math import numpy as np import scipy from rllab.torch.utils import torch as torch_utils from rllab.torch.algos.base ...
from abc import ABC import collections import csv from io import BytesIO, StringIO from django.contrib.auth.decorators import login_required from django.contrib import messages from django.core.exceptions import ValidationError from django.db import transaction from django.db.models import Count from django.http impor...
from ast import literal_eval import pandas as pd from shapely.geometry import shape, Point from shapely.ops import transform from rtree import index import pyproj def create_index(poly_gdf): idx = index.Index() for poly in poly_gdf.itertuples(): idx.insert(poly.Index, shape(poly.geometry).bounds) ...
""" ModuBot: A modular discord bot with dependency management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The MIT License (MIT) Copyright (c) 2019 TheerapakG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation f...
'''``ttk.TreeView`` control augmented by editing capabilities. For basic information, see official Tkinter (``ttk``) docs. The following additional functionality is provided: * Mark column as editable using :any:`TreeEdit.editable`. * allow= parameter to specify legal structural operations. ``allow`` is a list of...
#!/usr/bin/env python3 import copy, json, os, pprint, re, sys, urllib import requests, unidecode def printerr(*args, **kwargs): """Wrapper around print, to print to stderr""" print(*args, file=sys.stderr, **kwargs) def remove_prefix_and_suffix(s, prefix, suffix): """Try and remove the prefix and suffix from the...
from commit import _get_service_file import jsonschema import subprocess import fnmatch import os from fileio import dirio from log import log import glob import tempfile import stat _action_schema = { 'type': 'object', 'properties': { 'commands': { 'description': 'commands to run', ...
from __future__ import annotations from typing import Any import argparse import os import sys import json import textwrap import shlex import re from datetime import timedelta from dataclasses import dataclass, replace from . import commands from . import make_uml from . import protocol from . import resume from . ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) IBM Corporation 2018 # # 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 # # U...
import bisect import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore import numpy as np import itertools Vec = np.array def Vec2(x, y): return np.array([x,y], dtype=float) def Vec3(x, y, z): return np.array([x,y,z], dtype=float) def lerp(a,b,t): """ Linear interpolation between from @a to @b as @t ...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # Reference: https://github.com/facebookresearch/music-translation/blob/master/src/utils.py import errno import logging i...
from ...core.utils import general from ...core.devio.interface import IDevice from .misc import default_placing_message, load_lib import os.path import ctypes import time class SmarActError(RuntimeError): """Generic SmarAct error.""" class SCU3D(IDevice): """ SmarAct SCU3D translation stage. Args: ...
#!/usr/bin/env python3 # coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. 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/L...
from enum import Enum from collections import namedtuple from subprocess import check_output import re import signal import gstreamer import parec import info import cut import ac def get_sources_list(): out = check_output(["pacmd", "list-sources"]) return out.decode("utf-8") def _get_sources_names(raw): ...
import numpy as np import random from collections import namedtuple, deque from model import QNetwork from model import DuelingDQN import torch import torch.nn.functional as F import torch.optim as optim BUFFER_SIZE = int(5e4) # replay buffer size BATCH_SIZE = 64 # minibatch size GAMMA = 0.99 # ...
import sys from sklearn.externals.six.moves import cStringIO as StringIO import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_raises_regexp ...
import pandas as pd import datetime import matplotlib.pyplot as plt from Bio import SeqIO import argparse import os def process_dat(dat, groupby_var, max_date, datetime_fmt): # groups and sums dat = dat.groupby(groupby_var).agg('sum') # converts columns to datetime dat.columns = pd.to_datetime(dat.co...