text stringlengths 3.07k 12.6k |
|---|
from engpy.misc.abilities import numable
from engpy.misc.miscs import num
from engpy.errors.exceptions import OperationNotAllowed
from .primary import break_pq, count_powers
from .assorted import C, CD, GCD
from engpy.misc.imports import create
from engpy.misc.abilities import intable
from engpy.Standard import stdli... |
import tempfile
from typing import *
import imageio
import numpy as np
from .types import ArrayInfo
__all__ = ['image_array_to_rgb', 'make_images_grid', 'save_image_to_file']
def _check_images_channel(images: np.ndarray,
channel_last: Optional[bool] = None,
requi... |
#!/usr/bin/env python
#
# Public Domain 2014-2016 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compil... |
# -*- encoding: utf-8 -*-
from __future__ import print_function, absolute_import, unicode_literals
import copy
import operator as op
import inspect
def _ensure_callable(obj):
if isinstance(obj, KwCalc):
return obj
if callable(obj):
return SimpleFunc(obj)
return Const(obj)
def fmap(func,... |
import csv
from urllib.request import Request, urlopen
from datetime import date
import re
from sys import argv
from os import system
import scrape_util
default_sale, base_url, prefix = scrape_util.get_market(argv)
report_path = '/market_cards/scan.PDF'
temp_raw = scrape_util.ReportRaw(argv, prefix)
#CONVERT_SPEC = '... |
#!/usr/bin/env python
# coding=utf-8
"""
Python script whose purpose is to initialize the Mifare Classic 1K Smart Card with some data.
MIT License
Smart Card Contactless Raspberry Pi sample project
Copyright (c) 2022 <NAME> (<NAME>'s Blog - https://www.dontesta.it)
Permission is hereby granted, free of charge, to a... |
#!python3
"""
Training script: load a config file, create a new model using it,
then train that model.
"""
import json
import yaml
import argparse
import os.path
import numpy as np
import torch
import h5py
from mrcqa import BidafModel
from dataset import load_data, tokenize_data, EpochGen
from dataset import SymbolE... |
# Testing, Searching, and Manipulating Strings (Title)
# Reading
# Testing strings with 'in' and 'not' in (section)
# General Format:
# string1 in string2
text = 'Four score and seven years ago'
if 'seven' in text:
print('The string "seven" was found.')
else:
print('The string "seven" was not fou... |
import glob
import os
from tokenizer import SpacyTokenizer
from tqdm import tqdm
import nltk
# noinspection DuplicatedCode
def load_articles(article_folder): # , techniques_folder):
"""
Function for loading the articles
(based on the baseline model coming with the task)
"""
file_list = glob.glob... |
from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
from django.http import Http404
from django.template import Template
from django.utils.decorators import method_decorator
from django.views import generic
from django.views.generic.base import TemplateResponseMixin
from fein... |
"""Command handler for datum.
This module deals with built-ins and processing of custom queries.
"""
from . import connect
from string import Formatter as _Formatter
_config = {}
_help_text = """
--Available commands--
:help Prints the command list.
:rows [number] How many rows to print out of the res... |
import logging
import os
import sys
import numpy as np
import pandas as pd
from transformers import HfArgumentParser
from lingcomp.args import SimilarityArguments
from lingcomp.plotting_utils import create_heatmap, create_lineplot
from lingcomp.similarity import (
SimilarityFunction,
SimilarityPlotMode,
b... |
#!/usr/bin/python
# flow_fairness.py
#
# Runs a simulation with objects continually messaging each other.
# The analysis then generates statistics about the actual rates
# achieved and the weights. The output can be used to generate
# fairness graphs.
import sys
import subprocess
import os.path
# FIXME It would be ... |
"""
Contains the worker for training the model using recorded game data rather than self-play
"""
import os
import re
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import datetime
from logging import getLogger
from threading import Thread
from time import time
import chess.pgn
from ch... |
from konlpy.tag import Komoran
import nltk
import os
import pymysql
import re
'''
코드 설명
1. 데이터베이스에서 tag 필드가 NULL 인것을 찾음.
2. 데이터베이스의 Content에서 값을 이용하여 키워드를 붙임.
3. 각각 id 값을 기준으로 다시 데이터베이스 tag 필드에 넣음.
* LOGSTASH랑 엮어서 쓰므로 주의 필요
추가 설명
1. 키워드 추출은 빈도수 기준으로 추출
2. stop_words.txt은 제외할 단어 목록
3. user_dic.txt는 사용자 단어 목록
'''
... |
from __future__ import print_function, unicode_literals, division
from future_builtins import *
import binascii
import os
import socket
import struct
import pprint
import cStringIO
NETLINK_GENERIC = 16
NETLINK_ROUTE = 0
RTM_GETROUTE = 26
RTM_GETRULE = 34
RTPROT_BOOT = 3
RT_SCOPE_UNIVERSE = 0
RT_SCOPE_LINK = 253
RT_... |
import argparse
from datetime import datetime
import json
import sys
import time
from prompt_toolkit import print_formatted_text, HTML
import pytz
from requests_html import HTMLSession
import schedule
from tabulate import tabulate
from yaspin import yaspin
import database
# color from https://en.wikipedia.org/wiki/X... |
# local
from unix_socket import UnixSocket
# create socket client with dragonfly handling
import logging
import dragonfly
from dragonfly import *
sock_keyboard = UnixSocket('/tmp/evdev_keypress.sock', 100)
sock_keyboard.connect()
sock_gui = UnixSocket('/tmp/speech_gui.sock', 100)
modifiers = set()
hold_modifiers ... |
from todo import pick_tokens
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch, pdb
import torch.nn.functional as F
import numpy as np
class LanguageModel:
# based on: https://github.com/huggingface/transformers/blob/master/examples/run_generation.py
def __init__(self, use_cuda=True):
... |
#!/usr/bin/python
# Copyright (c) 2015 VMware, Inc. All Rights Reserved.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
from pathlib import Path
from PIL import Image
from io import BytesIO
import base64
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from tweetshot.webdrivers.set_webdriver import get_driver
class Twee... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math, copy, time
from torch.autograd import Variable
from Model import subsequent_mask
import matplotlib.pyplot as plt
import seaborn
from HyperParameter import epoches_of_loss_record, epoches_of_model_save, beam_search_number,... |
import copy
import itertools
import logging
import os
from typing import List, Optional, Union
from amlb.utils import Namespace, config_load, str_sanitize
log = logging.getLogger(__name__)
default_tag = '_'
def load_framework_definitions(frameworks_file: Union[str, List[str]], config: Namespace) -> Namespace:
... |
# --- START OF SCC/TENSORFLOW CONFIG ---
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
print(os.getenv("CUDA_VISIBLE_DEVICES"))
tf.config.set_soft_device_placement(
True
)
tf.keras.backend.set_... |
import pyvisa
import numpy
import time
# functions for power supply
class Fuente:
def __init__(self, instrument, name=None, tipoFuente=False):
self.instrument = instrument
self.name = name # Nombre para identificar en depuracion
self.delay_enable = tipoFuente
self.modo = "2W"
... |
from hydrus.core import HydrusData
from hydrus.core import HydrusSerialisable
from hydrus.client.gui.pages import ClientGUISession
class GUISessionLegacy( HydrusSerialisable.SerialisableBaseNamed ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_GUI_SESSION_LEGACY
SERIALISABLE_NAME = 'Legacy GU... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-01-15 09:43:28
# @Author : <NAME> (<EMAIL>)
import os
import streamlit as st
def crud(c2, params, func, func_params, tag):
_action = c2.radio('', ['New', 'Edit', 'Remove'])
_msg, flag, is_delete = None, False, False
if _action == 'New':
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from sklearn.feature_extraction.text import CountVectorizer
from catboost import CatBoostClassifier,Pool
import os
import time
from sklearn.model_selection import train_test_split
# Defin... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 16:34:42 2021
@author: Admin
"""
import time
from torch.autograd import Variable
import torch
import torch.optim as optim
from effnet_model import Classifier
from effnet_early_stopping import EarlyStopping
from effnet_metrics import error_plot, acc_plot, wrong_plot, pl... |
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... |
# coding=utf-8
from peewee import Model, Database, DoesNotExist
from playhouse.postgres_ext import PostgresqlExtDatabase
from .utils.log import logger
import pickle
ObjectDoesNotExist = object()
class DumyCacheClient(object):
@staticmethod
def set(key, value):
del key, value
@staticmethod
de... |
from typing import Text, Dict, Any
from cachetools import cached
from sagas.nlu.inferencer import extensions, DomainToken, InferPart
from sagas.nlu.rules_header import *
from sagas.nlu.inspector_common import Context
import sagas.tracker_fn as tc
import logging
from sagas.nlu.utils import get_possible_mean
logger =... |
import sublime
import json
from .. import utils
SIDE_COLOR = "color(#336B81 blend(var(--background) 60%))"
testbox = {"completions": {}, "documentation": {}}
def plugin_loaded():
sublime.set_timeout_async(load)
def load():
global testbox
completions_data = load_json_data("completions")
for key ... |
# 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
# distributed under t... |
#!/usr/bin/env python
# license removed for brevity
import rospy
import cv2
import numpy as np
import time
import math
from std_msgs.msg import String
import rospkg
#from core_msgs.msg import VehicleState
#from core_msgs.msg import Control
#DEBUG MODE : True / False
Z_DEBUG = True
#Minimun number of points required... |
from math import *
import math
import sys
import random
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
xAxisLimits = [-300, 300]
yAxisLimits = [-300, 300]
def randomColor():
return [i/255 for i in random.choices(range(256), k=3)]
def ROUND(a):
return int(a + 0.5... |
import json
import logging
import requests
import sys
import vcf
from mando import command, main
logger = logging.getLogger('vcf_to_json')
IMPACTS = {
'LOW': 0,
'MODIFIER': 1,
'MODERATE': 2,
'HIGH': 3
}
_IDS = [
{
'field_name': 'CHROM',
'db_name': 'chrom_s'
},
{
'... |
from spidermon import Monitor, MonitorSuite, monitors
from spidermon.exceptions import NotConfigured
from spidermon.utils.settings import getdictorlist
from ..monitors.mixins.spider import SpiderMonitorMixin
SPIDERMON_MIN_ITEMS = "SPIDERMON_MIN_ITEMS"
SPIDERMON_MAX_ERRORS = "SPIDERMON_MAX_ERRORS"
SPIDERMON_EXPECTED_F... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import mujoco as mj
import nlopt
import numpy as np
from mujoco.glfw import glfw
from mujoco_base import MuJoCoBase
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
plt.rcParams["font.size"] = 16
class Manipulat... |
#
# This file is part of m.css.
#
# Copyright © 2017, 2018 <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 Software without restriction, including without limitation
# t... |
import hashlib
import statistics
from .. import errors
from ..check import Check
class duplicate_row(Check):
"""Check for duplicate rows
API | Usage
-------- | --------
Public | `from frictionless import checks`
Implicit | `validate(checks=[{"code": "duplicate-row"}])`
This check can ... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# Modified by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
from __future__ import absolute_impo... |
import numpy as np
import torch.nn.functional as F
import torch.distributions as D
from torch import nn
import torch
from .policies import Policy
from rllib.utils.netutils import to_tensor, to_numpy, get_flat_params, get_flat_grad, set_flat_params, set_flat_grad
class MLPBase(nn.Module):
def __init__(self, obs_... |
from typing import Optional, Tuple, Union
import cv2
import numpy as np
from cilissa.images import Image
from cilissa.operations import Transformation
class Blur(Transformation):
"""
Blurs an image.
Args:
gaussian (bool): If True, uses a Gaussian filter to blur the image.
If False, ... |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""FederatedFastEstimator module."""
import os
from logging import getLogger
from pathlib import Path
import openfl.native as fx
from openfl.federated import Plan
from openfl.federated.data import FastEstimatorDataLoader
from openfl.fed... |
"""This example lets you dynamically create static walls and dynamic balls
"""
__docformat__ = "reStructuredText"
import pygame
from pygame.locals import *
from pygame.color import *
import pymunk
from pymunk import Vec2d
X, Y = 0, 1
### Physics collision types
COLLTYPE_DEFAULT = 0
COLLTYPE_MOUSE = 1
COLLTYPE_BALL =... |
########## PRU-ICSS interrupt controller #######################################
##
## Instance of the Common Platform Interrupt Controller (cpintc)
## configurable nesting supported
##
## 64 irq inputs with configurable mapping to channels:
## 0-15 from local subsystem
## 16-31 software events genera... |
import itertools
import pytest
import numpy as np
import tensorflow as tf
from dlutils.dataset.cropping import random_crop
CROP_TEST_PARAMS = list(
itertools.product(
[(5, 10, 11, 2), (20, 10, 3), (5, 10)], # patch_size
[2, 5])) # n_inputs
def pairwise(iterable):
'''s -> (s0,s1), (s1,s2),... |
"""Test fixtures setup for pytest
https://docs.pytest.org/en/latest/fixture.html
"""
import pytest
from typing import List
@pytest.fixture
def make_wav():
"""Fixture for convenience in creating real WAV files for tests that require them.
This is necessary for functionality that requires WAV files such as FFMP... |
import math
import numpy as np
import yaml
from lc_planner.transformations import euler_matrix
########################################################################################################################
# region Helper functions
#############################################################################... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
import os
from typing import Any, Union
from interactions ... |
"""A simple multi-agent env with two agents playing rock paper scissors.
This demonstrates running the following policies in competition:
(1) heuristic policy of repeating the same move
(2) heuristic policy of beating the last opponent move
(3) LSTM/feedforward PG policies
(4) LSTM policy with custom e... |
import os
import tensorflow as tf
import tensorflow_datasets as tfds
def download_dataset(dataset_name):
train = None
test = None
if dataset_name == 'svhn':
dataset = tfds.load(name='svhn_cropped')
train = dataset['train']
test = dataset['test']
elif dataset_name == 'svhn+ext... |
# importing relavent libraries
from string import punctuation as punkts
import re
# loading data
file = open('brown.txt')# data file in argv[1]
data = file.read()
data = data.split('.')
#data cleaning
import re
def clean(string):
string = string.encode('ascii', 'ignore').decode('ascii')
string = re.sub('^\[... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
import pytest
da = pytest.importorskip("dask.array")
import sys
import tiledb
from tiledb.tests.common import DiskTestCase
import numpy as np
from numpy.testing import assert_array_equal, assert_approx_equal
# override the no_output fixture because it conflicts with these tests
# eg: "ResourceWarning: unclosed ev... |
import time
from math import pi, cos, sin, tan
from random import randrange, random
import breakdown
#test program to spit words back. . .
class spit:
num = 16
mindelay = 3
modedelay = 333
def fill(self, c, a="+", b="-"):
self. num = c
temp = ''
for i in range(0, c):
... |
# coding: utf-8
"""
Name: detecter.py
detecting low pressure.
Usage: python3 detecter.py
Author: <NAME>
Date: 2021/12/14
"""
from typing import Tuple
import math
import os
from datetime import datetime
from os.path import abspath, join
import re
import numpy as np
from scipy.signal import argrelmin
from scipy impor... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import numpy as np
from PIL import Image
import torch
import torchvision
from platforms.platform import get_platform
class Datase... |
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from collections import OrderedDict
import PIL
from PIL import Image
import numpy as np
import seaborn as sns
import argparse
from get_input_arg... |
#!/usr/bin/python
from __future__ import print_function
import csv
import os
import sys
from datetime import date
from datetime import datetime
from datetime import time
from json import dumps
DAY_BEGIN = time(00, 00, 00)
DAY_END = time(23, 59, 00)
ANALYSIS_DIR = 'analysis'
WEEK_DAYS = [
'monday',
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Light-weight JSON-RPC over standard IO.
"""
import atexit
import io
import json
import pathlib
import subprocess
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from typing import BinaryIO,... |
import os, sys, shutil, tempfile, subprocess, os, random, glob, compiler.ast
try:
import xml.etree.ElementTree as etree
except ImportError:
import elementtree.ElementTree as etree
import unittest
PYDOCM = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', 'pydo... |
import json
import pytest
import datetime
from flask import jsonify, url_for
from pytest_factoryboy import register
import app.models as m
from tests.factories import ExerciseFactory
register(ExerciseFactory, 'exercise1')
register(ExerciseFactory, 'exercise2')
register(ExerciseFactory, 'exercise3')
def test_put_wor... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import gc
import glob
import datetime
import argparse
import numpy as np
import nibabel as nib
from global_dict.w_global import gbl_set_value, gbl_get_value
from blurring.w_blurring import data_generator, enhance_data_generator
from model.w_train import train_a_unet
f... |
"""Convert dict into dataclass"""
import dataclasses
import logging
from typing import Any, Dict, Iterable, List, Sized, Type, TypeVar, Union, cast
from dataclass_utils.error import Error, Error0, MissingKeyError
from dataclass_utils.typing import Literal, get_args, get_origin
T = TypeVar("T")
V = Union[Dict[Any, An... |
from asyncio import create_task
from dataclasses import dataclass
from importlib import resources
import logging
from random import choice, randint
import re
from typing import List
from fastapi import APIRouter, FastAPI, Request
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
import yam... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... |
#
# Copyright (C) Intel Corporation. All rights reserved.
# Licensed under the MIT License.
#
import sys
import os
import json
import xml.dom.minidom
# get the first valid node
def getFirstNode(nodes):
for i in nodes:
if i.nodeType == i.ELEMENT_NODE:
return i
return None
# strip empty nod... |
# Copyright (c) 2014 Mirantis 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 writ... |
import json
import re
from rasa_core.actions.action import Action
from rasa_core.events import SlotSet
from schema import Schema, And, Optional
class Disambiguator(object):
def __init__(self, disamb_rule=None, fallback_rule=None):
self.disamb_schema = Schema({
"trigger": And(str, len),
... |
"""
Tests at the CLI command level
"""
import filecmp
import json
import os
import time
from pathlib import Path
from unittest import mock
from click.testing import CliRunner
from stramp.cli import main
org_sample_1_hashes = [
[0, 2427, '6b29201f695a0a1ec220461b8625f54ab1c6ef0719c996189c951e495938dcde'],
[... |
# -*- coding: utf-8 -*-
import os
import json
import quantaq
import requests
import logging
from requests.models import Response
from typing import Optional, Union
try:
import urlparse
except ImportError:
from urllib import parse as urlparse
from .exceptions import QuantAQAPIException
GET = "GET"
PUT = "PUT"... |
# Copyright (c) 2007-2018 UShareSoft, 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 requi... |
import contextlib
import os
import platform
import shutil
import sys
from numba.tests.support import (
captured_stdout,
SerialMixin,
redirect_c_stdout,
)
from numba.cuda.cuda_paths import get_conda_ctk
from numba.cuda.cudadrv import driver, devices, libs
from numba.core import config
from numba.tests.suppo... |
import os
import logging
import anomalytransfer as at
from typing import Sequence, Tuple, Dict, Optional
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--th", type=float)
args = parser.parse_args()
def make_base_model(kpi: at.transfer.data.KPI, model_path: str, epochs: int):
kpi.complete... |
import numpy as _np
class Camera:
"""
Represents the camera info of a nao with additional methods for the geometry.
"""
def __init__(self, width=640, height=480, opening_angle_diagonal=_np.radians(72.6)):
self._width = width
self._height = height
self._opening_angle_diagonal =... |
from torch_geometric.nn import GCNConv, GATConv, APPNP
from torch_geometric.nn.pool.topk_pool import topk
import torch
from torch.nn import Parameter
from functions.sparse_tensor_func import degree_normalize_sparse_tensor, sparse_gumbel_softmax
from functions.pooling_aux_func import filter_target, cadicate_selection, r... |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import dataclasses
from enum import Enum
PRESS_DURATION = 50
@dataclasses.dataclass
class Direction:
name: str
idx: int
class Directions(Enum):
LEFT = Direction("Left", 0)
DOWN = Direction("Down", 1)
UP = Direction("Up", 2)
RIGHT = Direction("Right", 3)
TAB = " " * 2
DIRS = {
0: Dire... |
import aiohttp
from datetime import datetime
import json
from urllib.parse import urljoin, quote as urlquote
from uuid import UUID
from .filters import And, Combinatoric, Filter
class Error(aiohttp.ClientResponseError):
def __init__(self, request_info, history, error_data, status=None, headers=None):
self... |
import argparse, logging, sys, os, time
from utils import dataprep as dp
from datasource.data import DataSet
from sklearn.model_selection import StratifiedShuffleSplit
import numpy as np
def process_args(args) :
'''
Parses the commandline arguments
:param args: the commandline arguments
:return: pars... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import time
import threading
import traceback
import ray
LOG_POINT = 0
LOG_SPAN_START = 1
LOG_SPAN_END = 2
class _NullLogSpan(object):
"""A log span context manager that does nothing"""
... |
"""
Utility method for Sublime Text editor
"""
import re
import os.path
import sublime
import sublime_plugin
from zlib import adler32 # adler32 considered faster than crc32
# List of LiveStyle-supported file extensions
supported_syntaxes = ['css', 'less', 'scss']
_settings = None
_sels = {}
try:
isinstance("", bas... |
"""
Takes the IARPA Janus-format annotations CS6/protocols/cs6_face_detection_ground_truth.csv
and converts it into FDDB-style format.
Format:
data/CS6_annot/
frames/<video-name>/*.jpg
video_annots/<video-name>.txt
This is done one video at a time, the video name being specified as... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
import argparse
from cocoprep.archive_load_data import parse_range, read_best_values, write_best_values
from cocoprep.archive_functions import ArchiveInfo
from cocoprep.coco_archive import A... |
# imports
from __future__ import unicode_literals, print_function
from psychopy import visual, event, core, monitors
from random import choice
# With Psychopy, we have to manually create a monitor
m = monitors.Monitor("default", width=28.8, distance=200)
m.setSizePix([800, 600])
win = visua... |
import discord
from discord.ext import commands
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# sqlite
import sqlite3
import configparser
import datetime
# stuff that handles user analytics
# no commands are associated with this
class Analytics(commands.Cog):
"""Set of handler... |
# Copyright © 2017, 2019, 2020 by <NAME>. All rights reserved.
# Licensed under MIT License.
# See LICENSE in the project root for license information.
"""A Pocket Classifier."""
import numpy as np
from typing import List, Tuple
class Pocket:
"""The class keeps the best weights seen so far in the learning pro... |
"""
▉▊▋▌▍▎▏MANIFOLD FINANCE ▎▍▌▋▊▉
EVO Protocol firesale pytest
Manifold Finance
Usage:
ls test_evo
cd ./test && pytest
evo_trade must be symlinked to ../evo-trade (parent) repository.
"""
from evo_trade.contract import ContractProvider
from evo_trade.simulation import Simulation
from evo_trade.config ... |
from lxml import etree
import lxml
import re
import logging
import os
from lxml.etree import LxmlError
from tqdm import tqdm
from acl.utils import normalize_title
logger = logging.getLogger(__name__)
def get_parsecit_files(parscit_dir):
parscit_files = []
for d in os.listdir(parscit_dir):
if os.pa... |
import os
import re
import sys
import platform
import sysconfig
import subprocess
from setuptools import setup, Extension, find_packages
from setuptools.command.build_ext import build_ext
from setuptools.command.test import test as TestCommand
from distutils.version import LooseVersion
# Package meta-data.
NAME = 'j... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import os, sys
def grid_sample_on_img(img, xy):
'''
use xy to grid sample on image using bilinear interpolation.
Inputs:
img: [B, C, Hin, Win]
xy : [B, 2, Hout, Wout]
Outputs:
output: [B, C, Hout, Wout]
'''
B, C,... |
import numpy as np
def cer(reference, hypothesis, ignore_case=False, remove_space=False):
"""Calculate charactor error rate (CER). CER compares reference text and
hypothesis text in char-level. CER is defined as:
.. math::
CER = (Sc + Dc + Ic) / Nc
where
.. code-block:: text
Sc is t... |
import numpy as np
#import numba
def get_particles(lattice):
"""
return the number of particles, regarless of
its state.
occupied state == lattice[k] > 0
empty state == lattice[k] = 0
"""
return np.sum(lattice > 0)
def get_state(iQ,Lx,Ly,lattice):
"""
return a vector with the n... |
# 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 u... |
"""
Custom Authenticator to use AWSCognito with JupyterHub
Derived using the Globus and Generic OAuthenticator implementations as examples.
The following environment variables may be used for configuration:
AWSCOGNITO_DOMAIN - Your AWSCognito domain, either AWS provided or custom
AWSCOGNITO_USERNAME_KEY - Yo... |
# coding: utf-8
import unittest.mock
import numpy as np
from spectrum import marple_data
from hrv.classical import (time_domain, frequency_domain, _auc, _poincare,
_nn50, _pnn50, _calc_pburg_psd)
from tests.test_utils import FAKE_RRI, open_rri
class TimeDomainIndexesTestCase(unittest.Test... |
import argparse
import Levenshtein
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
from src.read_localization_file import (
file_to_keys_and_lines,
get_key_value_and_version,
BadLocalizationException,
file_to_keys_and_values,
)
def get_args():
par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.