text stringlengths 3.07k 22.1k |
|---|
from tkinter import *
from tkinter import filedialog, messagebox
#----------------------------------#
import youtube_dl
#----------------------------------#
from os import makedirs, system, getcwd
#----------------------------------#
from wget import download
from zipfile import ZipFile
#-------------------------------... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: tdxDay
Description : 一、通达信日线*.day文件
文件名即股票代码
每32个字节为一天数据
每4个字节为一个字段,每个字段内低字节在前
00 ~ 03 字节:年月日, 整型
04 ~ 07 字节:开盘价*100, 整型
08 ~ 11 字节:最高价*100, 整型
12 ~ 15 字节:最低价*100, 整型
16 ~ 19 字节:收盘价*100, ... |
import numpy as np
import torch
import lmdb
import pickle
import sys
import os.path
from os import makedirs
from baselines.common.trex_utils import preprocess
from .constants import MUJOCO_ENVS
_print = print
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
def generate_demos(env, e... |
# Copyright 2020 The TensorFlow Probability Authors.
#
# 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 o... |
from django.contrib import admin
from django.db.models import Count, Max, Min
from django.utils.html import format_html
from django.contrib.admin.filters import AllValuesFieldListFilter
from .models import Build, Game, Title, Executable, XDKLibrary
class DropdownFilter(AllValuesFieldListFilter):
template = 'admin... |
import pickle
from os import path as osp
from torch.utils.data import Dataset
from torchvision.datasets.folder import default_loader
from augmentation import transform_train, transform_aug
from torchvision import transforms
import torch
import numpy as np
class CUB200_2011Dataset(Dataset):
def __init__(self, root... |
from __future__ import annotations
from typing import List
import numpy as np
from datetime import datetime
import logging
from . import api
class Report:
"""A report from the Boltwood II sensor."""
def __init__(self, raw_data: bytearray = None, content: str = None, columns: list = None, req_columns: int ... |
from discord.ext import commands
import discord
import random
import typing
import bisect
from difflib import SequenceMatcher
import utils
from discord.ext.commands.cooldowns import BucketType
class Dice(commands.Cog):
"Commands that rely a ton on random chance"
def __init__(self, bot):
self.bot = bo... |
import pytest
import numpy.testing as npt
from nose.tools import (assert_equal, assert_not_equal, assert_almost_equal,
raises, assert_true)
from nose.plugins.skip import Skip, SkipTest
import numpy.testing as npt
from .test_helpers import data_filename, assert_items_equal
import openpathsampli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Gene processing.
:Author: <NAME> <<EMAIL>>
:Date: 2018-01-22
:Copyright: 2018, <NAME>
:License: CC BY-SA
"""
import os
import re
import subprocess
import pandas as pd
import pysam
class Error(Exception):
"""Base class for exceptions in this module."""
pa... |
# -*- coding: utf-8 -*-
from os import environ
from enum import Enum
from importlib import import_module
import json
from peewee import *
from ..utils import rankdata
from ..core import cfg, ConfigError
from ..db_core import BaseModel
from ..team import Team
from ..game import Game, Pick
SWAMI_CONFIG = environ.get(... |
#!/usr/bin/env python3
from datetime import datetime, time, timedelta
import argparse
import random
import math
import json
import paho.mqtt.client as mqtt
import redis
import time as dtime
import os
import sys
from Session import Session
def applog(*a):
print(*a, file = sys.stderr)
def poisson_distribution(k, ... |
import ply.yacc
from .lexer import tokens # NOQA
from .ast import LabelNode, GlobalDirectiveNode, FileDirectiveNode, SectionDirectiveNode, DataSectionDirectiveNode, TextSectionDirectiveNode, SetDirectiveNode
from .ast import StringNode, AsciiNode, SpaceNode, AlignNode, ByteNode, ShortNode, WordNode, InstructionNode, ... |
import re
import json
from bson.objectid import ObjectId
from core import app, data, utils
from core.ctrl import servers, recipes, notifications
def list_sites(filter_data, sort_data=None):
finder = {
'collection': 'sites',
'filter': filter_data,
'sort': sort_data
}
return data.ex(... |
#!/usr/local/bin/python3
# MIT License
# Copyright (c) 2017 <NAME>
# https://cydy.io @claytondorsey
import numpy as np
from EmojiGrid import *
import random
from chars import *
def getSectionCords(inputCanvas, sectNum):
return np.argwhere(inputCanvas == sectNum)
def splitNum(parts, total):
elements = (np.... |
#!/usr/bin/env python
# coding=utf-8
# from __future__ import absolute_import
# from __future__ import division
# from __future__ import print_function
import time
import sys
import os
import glob
import json
from datetime import date, timedelta
import tensorflow as tf
#################### CMD Arguments ###########... |
# flake8: noqa
import os
from pathlib import Path
from tempfile import TemporaryDirectory
from pytest import mark
import torch
from torch import nn, optim
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn import functional as F
from torch.utils.data import DataLoader
from catalyst imp... |
import sublime, sublime_plugin
import re, socket
UDP_IP = "127.0.0.1"
UDP_PORT = 11211
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setblocking(False)
G = {"prompt": 10, "hist": 0, "namespace": " unknown=>"}
history = []
print("arcadia-repl loaded!")
def create_repl(window):
current_view = window... |
#counter.py
##############NETWORK CONFIG###############
import csv
import os
allfile = os.listdir()
def Save(data):
with open('config_counter.csv','w',newline='') as file:
#fw = 'file writer'
fw = csv.writer(file)
fw.writerows(data)
print('Save Done!')
def Read():
if 'config_counter.csv' n... |
from threading import Thread, Event
from contextlib import contextmanager
from queue import Queue
import numpy as np
import time
def _start(queue, stop_event):
"""
Thread target function. Starts the ImageQueue._populate function which runs
indefinitely until stop_event is set.
Args:
queue: ... |
"""
Tools for working with chord progressions.
"""
from collections import namedtuple
from typing import Hashable, List, Set, Union
from jchord.knowledge import REPETITION_SYMBOL
from jchord.core import CompositeObject
from jchord.chords import Chord
from jchord.midi import read_midi_file, notes_to_messages, ... |
# -*- coding: utf8 -*-
# Copyright (C) 2015 - <NAME> <<EMAIL>>
# This program is Free Software see LICENSE file for details
from datetime import *
from Utils import *
from local_db import *
import TheMovieDB as tmdb
TRAKT_KEY = 'e9a7fba3fa1b527c08c073770869c258804124c5d7c984ce77206e695fbaddd5'
BASE_URL = "https://ap... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Copyright 2019-2020 Airinnova AB and the CommonLibs authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
# Copyright 2012 OpenStack LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
"""This module is used to extract lexical features for the WriteprintsStatic class.
For every feature, we document the description of the original feature, the technical details we use to recover it, and
known differences between the original feature and our engineering.
"""
import string
# fmt: off
SPECIALS = ['~', ... |
# -*- coding: UTF-8 -*-
import re
import json
import pytz
import logging
import datetime
import hashlib
from common.utils.aliyun_sdk import Aliyun
from django.core import serializers
from django.db.models.functions import Trunc
from django.core.serializers.json import DjangoJSONEncoder
from django.views.decorators.cs... |
# 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 loop_tool_py as lt
import random
import numpy as np
import math
import time
def gen_pw_add():
ir = lt.IR()
a = ir.create_var(... |
from main import dp
import re
import sys
import argparse
from operator import itemgetter
from Bio.Seq import Seq
from Bio.Data import CodonTable
available_codon_tables = {'The Standard Code': 1,
'The Vertebrate Mitochondrial Code': 2,
'The Yeast Mitochondrial Code': 3,
'The Mold, Protozoan, and Coelenter... |
"""Adversarial training in the style of Madry et al [1]
[1] Madry et al, "Towards Deep Learning models resistant to adversarial attacks",
arXiv:1706.06083
"""
import random
import time, datetime
import os, shutil
import yaml
import ast, bisect
import csv
import numpy as np
import torch
import torch.nn as nn... |
"""
List of Deep learning layers
Example :
input -> linear -> activation -> output
"""
import numpy as np
from thesiaNet.tensor import tensor
class Linear:
def __init__(self, input_size, output_size):
"""
:param input_size: input size
:param output_size: output size
"""
se... |
#These imports are used for the dataset because torch has a better implementation of getting the data
from torch.utils.data import dataloader, TensorDataset
from torchvision import transforms, datasets
import torch
#These imports are for the network itself
import tensorflow as tf
from tensorflow import nn, layers
impo... |
# Copyright (c) 2016 by Revisify. All Rights Reserved.
from flask import Blueprint, render_template, redirect, send_from_directory, flash, g
from flask.ext.login import login_required, current_user
from werkzeug import secure_filename
from revisify.utils import *
from revisify.models import *
from revisify.forms impor... |
import requests
import requests.exceptions
_BASE_URL = "https://app.buymeapie.com"
class ProductGroup(object):
"""Group Colors"""
__COLORS = [
"b4bec6",
"524dcf",
"864f9e",
"ba2e38",
"e57542",
"ff5699",
"75b35a",
"26b0c7",
"c1c12f",
... |
from entities import *
from pprint import pprint
from textwrap import dedent
from types import FunctionType
import inspect
import json
import pdb; B=pdb.set_trace
import pprint
import sys
import uuid
from pprint import pprint
from configfile import configfile
# TODO Ensure tester.py won't run in non-dev environment
c... |
from enum import Enum, auto
from typing import Dict, List
import pendulum
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QComboBox, QDialog, QDialogButtonBox
from PyQt5.uic import loadUi
from brainframe.api.bf_codecs import (
Attribute,
Capsule,
Zone,
ZoneAlarm,
ZoneAlarmCountCondit... |
from flask import Flask, flash, request, jsonify, render_template, redirect, url_for, g, session, send_from_directory, abort
from flask_cors import CORS
from flask_api import status
from datetime import date, datetime, timedelta
from calendar import monthrange
from dateutil.parser import parse
import pytz
import... |
# python 3.8 is suggested
import numpy as np
from copy import deepcopy
from pdb import set_trace
from utmLib import utils
from utmLib.clses import Timer
from utmLib.parmapper import Xmap
from tinylib import evaluate_result, logmass_statistic
from spnflow.algorithms.mpe import mpe
from spnflow.structure.l... |
import unicodedata
import shutil as shutil
import sys
import os
import json
import jsonpickle
import codecs
from pyunpack import Archive
from collections import namedtuple
import pandas as pd
import textwrap
import re
jsonpickle.set_preferred_backend('json')
jsonpickle.set_encoder_options('json', ensure_ascii=False, i... |
import requests
from airpyllution.utils import convert_data_to_pandas
import plotly.express as px
import altair as alt
import pandas as pd
alt.renderers.enable("mimetype")
# import constants
OPEN_WEATHER_MAP_URL = "http://api.openweathermap.org/data/2.5/air_pollution"
def get_pollution_history(start_date, end_date,... |
from typing import Dict, Tuple, List
from pathfinding.finder.a_star import AStarFinder
from pathfinding.core.grid import Grid
from gupb.model import arenas, coordinates, tiles
from gupb.model import characters
from gupb.model.arenas import Arena, ArenaDescription
from gupb.model.characters import ChampionDescription, F... |
"""
MIT License
Copyright (c) 2020 GamingGeek
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, dis... |
"""
Demonstrates usage of the T7's SD card system.
https://labjack.com/support/datasheets/t-series/sd-card
Relevant Documentation:
LJM Library:
LJM Library Installer
https://labjack.com/support/software/installers/ljm
LJM Users Guide:
https://labjack.com/support/software/api/ljm
... |
import numpy as np
from numpy import ndarray
from yacs.config import CfgNode
from albumentations import OneOf, Compose, MotionBlur, MedianBlur, Blur, RandomBrightnessContrast, GaussNoise, \
GridDistortion, Rotate, HorizontalFlip, CoarseDropout, Cutout
from .grid_mask import GridMask
from typing import Union, List, ... |
"""
gridtools.py, part of gridtools
---
A small Python library to convert between maidenhead grid locators and lat/long coördinates.
Copyright 2020 classabbyamp, 0x5c
Released under the terms of the BSD 3-Clause license.
"""
from typing import Union, Tuple
import re
import math
__all__ = ["Grid", "LatLong", "check... |
import argparse
import os
import torch
from tensorboardX import SummaryWriter
from network.tubetk import TubeTK
from dataset.dataLoader import Data_Loader_MOT
from optim.solver import make_optimizer as makeOpt
from configs.default import __C, cfg_from_file
from utils.util import AverageMeter
from tqdm import tqdm
from ... |
# -*- coding: utf-8 -*-
import argparse
import io
import os
from threading import Lock
import cherrypy
from wsgiref.simple_server import make_server, WSGIServer
from SocketServer import ThreadingMixIn
import msgpack
import numpy as np
from PIL import Image
from PIL import ImageOps
from config import BRICA_CONFIG_FIL... |
import faiss #faiss
import tensorflow as tf
import numpy as np
import pandas as pd
from voctor.dataset import convert_text_to_feature
from voctor.models import MedicalQAModelwithBert
from voctor.tokenization import FullTokenizer
from tf_bert.loader import checkpoint_loader
from collections import defaultdict
from multi... |
import os
import pickle
from data_loader import SNLIDataset
from torch.utils.data import DataLoader
from model import SNLIModel
from utils import get_device, plot_measure
from torch import nn, optim
from time import time
import torch
import argparse
from utils import *
def train(num_epochs, train_data_loader, dev_da... |
"""Utilities for MLIR conversion."""
from typing import Dict, List, Optional, Tuple
import networkx as nx
from ..data_types.dtypes_helpers import (
value_is_clear_scalar_integer,
value_is_clear_tensor_integer,
value_is_encrypted_scalar_integer,
value_is_encrypted_tensor_integer,
value_is_integer,
... |
import os
import json
import numpy as np
from sklearn.model_selection import train_test_split
# regions
US = 0
EU = 1
RU = 2
AU = 3
AS = 4
SA = 5
ZA = 6
# cluster-to-region mappings
cluster_map = {
111: US,
112: US,
114: US,
121: US,
122: US,
123: US,
124: US,
131: EU,
132: EU,
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db import models
from django.contrib.sites.models import Site
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
fro... |
import pathlib
import numpy as np
import pytest
import xarray as xr
from xarray_sentinel import esa_safe, sentinel1
DATA_FOLDER = pathlib.Path(__file__).parent / "data"
SLC_IW = (
DATA_FOLDER
/ "S1B_IW_SLC__1SDV_20210401T052622_20210401T052650_026269_032297_EFA4.SAFE"
)
SLC_IW1_VV_annotation = (
SLC_IW
... |
#!/usr/bin/env python
from __future__ import print_function
import time
# ros std imports
import rospy
# tf imports
import tf
import tf_conversions
import tf2_ros
from tf.transformations import *
# msg imports
import std_msgs.msg
from geometry_msgs.msg import Twist, TransformStamped
from nav_msgs.msg import Odometry
# ... |
"""
This test file will test registration, login, activation, and session activity timeouts
"""
import datetime
import time
from unittest import mock
from ddt import data, ddt, unpack
from django.conf import settings
from django.core.cache import cache
from django.test.utils import override_settings
from django.urls... |
"""
filt.py
Filter a neural signal using a bandpass, highpass, lowpass, or bandstop filter.
"""
import numpy as np
import scipy as sp
from scipy import signal
import matplotlib.pyplot as plt
import warnings
def filter(x, Fs, pass_type, f_lo=None, f_hi=None, N_cycles=3, N_seconds=None,
iir=False, butterwor... |
import os
import torch
import numpy as np
import pytest
import h5py
from dqc.system.mol import Mol
from dqc.system.sol import Sol
from dqc.hamilton.intor.lattice import Lattice
# these tests to make sure the systems parse the inputs correctly
dtype = torch.float64
moldescs = [
"H 1.0 0.0 0.0; Be 2.0 0.0 0.0",
... |
#!/usr/bin/env python3
# -*- coding = utf-*-
from __future__ import absolute_import, division, unicode_literals
import os
import sys
import json
import time
import argparse
import cv2
import numpy as np
from matplotlib import style
style.use('seaborn-dark')
import matplotlib.pyplot as plt
import matplotlib.gridspec a... |
import json
import pytest
import responses
from httpie.cli.constants import PRETTY_MAP
from httpie.cli.exceptions import ParseError
from httpie.compat import is_windows
from httpie.output.formatters.colors import ColorFormatter
from httpie.utils import JsonDictPreservingDuplicateKeys
from .fixtures import JSON_WITH_... |
import collections
import os
import sys
import numpy as np
from numpy.random import rand
from pyspark import SparkContext
import time
import pyspark
MIN_EPS = 0.005
TINY_EPS = 0.0001
'''
word, h - col
doc, w - row
'''
def map_line(line):
temp = line.replace(' ', '').split(',')
return (int(temp[0]), int(temp[1])... |
import json
import os
import re
import sys
import subprocess
from os import walk
def run_command(command, cwd=None):
p = subprocess.Popen(command, cwd=cwd)
if p.wait() != 0:
print("command `{}` failed...".format(" ".join(command)))
sys.exit(1)
def clone_repository(repo_name, path, repo_url, ... |
# -*- coding: utf-8 -*-
#
# Authors: Swolf <<EMAIL>>
# Date: 2021/1/23
# License: MIT License
"""
Riemannian Procrustes Analysis.
Modified from https://github.com/plcrodrigues/RPA
"""
from typing import Union, List, Tuple, Dict, Optional, Callable
from functools import partial
import numpy as np
from numpy import ndarr... |
import networkx as nx
import numpy as np
from functools import reduce
class Leader_Identification(object):
def __init__(self, leader_epsilon):
self.overlap = leader_epsilon
@staticmethod
def __inclusion(c1, c2):
"""
:param c1: node neighbors
:param c2: node neighbors
... |
import os
import pandas as pd
from IPython.core.display import display, HTML
from recordsearch_tools.client import RSSeriesClient
import plotly.offline as py
import plotly.graph_objs as go
from textblob import TextBlob
import nltk
stopwords = nltk.corpus.stopwords.words('english')
py.init_notebook_mode()
def make_summ... |
from collections import defaultdict
from .util import Solution
"""
###############################
ALGO-PICKER
###############################
"""
def lrs_auto(s, verbosity=0):
if len(s) == 1:
return Solution(1, [[s[0]]])
sigma = list(set([run.char for run in s]))
# if alphabet size is too larg... |
# -*- coding: utf-8 -*-
"""Recipe staticlxml"""
import os
import re
import sys
import logging
import tempfile
import platform
import subprocess
import pkg_resources
from fnmatch import fnmatch
from distutils import sysconfig
from zc.buildout import UserError
from zc.recipe.egg.custom import Custom
import zc.recip... |
import numpy as np
import tensorflow.keras
def hor_con(x):
# Concatenate images side by side (horizontally)
y=x[0]
for i in range(1,len(x)):
y = np.concatenate((y, x[i]), axis=1)
return y
def ver_con(x):
# Concatenate images side by side (horizontally)
y=x[0]
for... |
import json
import multiprocessing as mp
import os
from pathlib import Path
from typing import Optional
import requests
from environs import Env
from lxml import html
from mvp_scraper.utils import download_img, get_output_path
def get_mvp_icon(mvp_id: str, output_path: Path) -> None:
download_img(
output_path... |
#!/usr/bin/env python3
"""
Author : <NAME>, <NAME>, <NAME>, <NAME>
Note : Parts of this code was initially developed by the AgPipeline and TERRA-REF teams.
Date : 2020-07-09
Purpose: Convert FLIR .bin files to .tif (Season 10)
"""
import argparse
import os
import sys
import logging
import json
import numpy as np
i... |
# -*- coding: utf8 -*-
"""
======================================
Project Name: NLP
File Name: build_datasets
Author: czh
Create Date: 2021/8/16
--------------------------------------
Change Activity:
======================================
"""
import json
import os
import logging
from tqdm import t... |
# Tokenize and Stem Data
# Convert words to Vector Space using TFIDF matrix
# Using KMeans clustering to find out clusters
# Calculate Cosine Similarity and generate the distance matrix
# Dimensionality reduction using MDS to results the KMeans output
import numpy as np
from nltk.tokenize import word_tokenize, sent_tok... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2009,2012 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either vers... |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.conf import settings
from django.core.exceptions import ValidationError
import random
import string
import datetime
import decimal
from random import randint
random_string = str(random.randint(100000, ... |
import gzip
from io import BytesIO
from unittest.mock import MagicMock
from flask import url_for
from flask_sqlalchemy import BaseQuery
from flask_tinyclients.vxstream import VxAPIClient, VxStream
from app.api.analysis.vxstream import _state_to_name, SUCCESS
from .conftest import assert_msg
import pytest
@pytest.fixt... |
# -*- coding: utf-8 -*-
# %% IMPORTS
# Built-in imports
from os import path
# Package imports
import e13tools as e13
from emcee import EnsembleSampler
import numpy as np
from py.path import local
import pytest
from sortedcontainers import SortedDict as sdict
# PRISM imports
from prism._internal import RequestError, ... |
"""
Core dataset implementation. BaseCore may be inherhit to create a new
DatasetCore
"""
import os
from abc import ABC, abstractmethod
import cv2
import numpy as np
import torch
from scipy import io
from experimenting.utils import Skeleton
from ..utils import get_file_paths
from .base import BaseCore
class DHP19... |
# -*- coding: utf-8 -*-
try:
import smartcard
except ImportError:
pass
from datetime import date
def check_result(func):
if isinstance(func, tuple) and len(func) == 2:
if func != (0x90, 0x00):
raise Exception('Wrong result code: %x %x' % func)
elif callable(func):
def de... |
import copy
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from typing import List, Optional, Dict
class TransformerEncoder(nn.Module):
def __init__(self, encoder_layer, num_layers, norm=None):
super().__init__()
self.layers = _get_clones(encoder_layer, num_layers)
... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.rnn as rnn_utils
# import torch.utils.data.sampler as sp
from collections import OrderedDict
from .vfe_template import VFETemplate
from ....ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_s... |
#--------------------------------------------------------------------
#
# PyGUI - Font - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32gui as gui, win32ui as ui, win32api as api
from GUI import export
from WinUtils import win_none
import GUI.GDI as gdi
impo... |
import os
import sys
from datetime import datetime
from functools import cmp_to_key
from requests.auth import HTTPBasicAuth
import tempfile
from requests import get
import zipfile
import argparse
parser = argparse.ArgumentParser(description='Scan a deployment for a dependency.')
parser.add_argument('--octopusUrl',
... |
'''
bert-serving-start -model_dir /home/rajesh/work/limbo/bert/uncased_L-12_H-768_A-12/ -num_worker=1 -cpu
pip install bert-serving-server
pip install bert-serving-client
python prepare_stories_data.py -d ../storiesgan/data/vids/ --ss 10s
'''
'''
adjust 500ms
handle case of empty frames
'''
import os,sys,time,glob,j... |
import os
import argparse
import random
import torch
import torch.optim as optim
import torchvision.transforms as transforms
import dataset
import model.backbone as backbone
import metric.loss as loss
import metric.pairsampler as pair
from tqdm import tqdm
from torch.utils.data import DataLoader
from metric.utils... |
#!/usr/bin/env python3
"""
jink.py
Interface for interacting with PACP devices through python rather than JLinkExe.
Utilises the JLink Library through the pylink package
"""
__author__ = "<NAME>"
import argparse
import os
import pylink
flash_progress = b"Compare"
def flash_print_progress(action, progress_string... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#! /usr/bin/env python3
from math import sqrt, pow, atan2, pi
import pygame
# problem: decorate a saturnalia tree
# input:
# - tree:
# - base radius
# - height
# - limb positions
# - height
# - angle
# - number of ornaments
# given (height, angle) of limb
# compute (x, y, z) of limb tip
# compute polar c... |
# Code from Chapter 8 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by <NAME> (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no warranty o... |
# Copyright (c) 2020 <NAME> and <NAME>.
#
# This file is part of Pixel Difference toolkit
# (see https://github.com/giuthas/pd/).
#
# 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... |
# -*- coding: utf-8 -*-
import logging
import pandas as pd
import numpy as np
from pathlib import Path
from typing import List, Tuple
def load_test_data() -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
"""
Load test dataframes from feature extracted test data.
:return: pd.DataFrame
... |
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
import lentil
def circle(shape, radius, shift=(0, 0)):
"""Compute a circle with anti-aliasing.
Parameters
----------
shape : array_like
Size of output in pixels (nrows, ncols)
radius : float
Radius of circ... |
#!/usr/bin/env python3
# Copyright (C) 2020, <NAME>
# Yamanishi laboratory,
# Department of Bioscience and Bioinformatics,
# Faculty of Computer Science and Systems Engineering,
# Kyushu Institute of Technology,
# 680-4 Kawazu, Iizuka, Fukuoka, 820-8502, Japan.
# txt fragment to smi
import argparse, rdkit, re, sys, ... |
# Copyright 2021 Xanadu Quantum Technologies 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 agre... |
import os
import sys
import numpy as np
import h5py
# import tensorflow as tf
import random
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
# for rsmix @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
def knn_points(k, xyz, query, nsample=512):
B, N, C = xyz.shape
_... |
import inspect
import sys
from typing import List, Optional
import numpy as np
from .config import (
SIMULATION_CONFIG,
get_observation_names,
get_reward_names_and_weights,
)
from .models import Direction, Node, Table
from .simulation import Factory
__all__ = ["get_observations", "get_reward", "get_done"... |
import datetime
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import random
import datetime
from data_access import GetData
from utils import read_yaml, split_groups, get_results, date_part
from configs import co... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import torchvision.datasets as dst
import argparse
import os
import time
from util import AverageMeter, accuracy, transform_time
fro... |
"""
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks
from . import spectrum as sp
def gaussian(x, mean, sigma):
"""
Gaussian function.
Parameters
----------
x : numpy array.
x-values.
mean : float or int.
mean of distribution.
si... |
"""
Neural network trainer class.
"""
import pickle
import time
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm, trange
from tqdm.notebook import tnrange, tqdm_notebook
from src.metrics import accuracy_score_tensors, f1_score_tensors
from src.plot_utils import plot_history
class Trainer:
... |
from abc import ABC, abstractmethod
import math
import numpy as np
import copy
from . import som
from . import utils
class EncodingScheme(ABC):
"""An abstract base class for encoders"""
@abstractmethod
def encode(self, attrs):
"""Encode a list of attributes into a binary vector
Args:
... |
#!/usr/bin/env python
import smbus
import time
import math
from talk import say
import RPi.GPIO as GPIO
import os
import yaml
ROOT_PATH = os.path.realpath(os.path.join(__file__, '..', '..'))
with open('{}/src/configuration.yaml'.format(ROOT_PATH),'r+', encoding='utf8') as conf:
sensor = yaml.load(conf, Loader=yam... |
"""Mixin class for errors, warnings and information
A class derived from `OWWidget` can include member classes `Error`, `Warning`
and `Information`, derived from the same-named `OWWidget` classes. Each of
those contains members that are instances of `UnboundMsg`, which is, for
convenience, also exposed as `Orange.widg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.