text stringlengths 3.07k 12.6k |
|---|
import pytz
import sys
import numpy as np
from datetime import datetime
from metrics import utils
QUERY_CONTENT = '*'
# return a list of throughputs computed per call
def get_service_throughput_per_hit(service, computation_timestamp, time_window):
print(service,file=sys.stderr)
query_ids = QUERY_CONTENT + f'... |
#!/usr/bin/env python3
"""querv
Usage:
querv list [-p PROP] [-f FILE] [-i ID] [-m METHOD] [-a PROFILE] [-r REGION]
querv save [-a PROFILE] [-r REGION]
querv -h | --help
querv --version
Any long-form option (id, file, profile, etc.) may also be specified as an environment variable of the form QUERV_$V... |
# -*- coding: utf-8 -*-
import os
import math
import codecs
import random
import numpy as np
from glob import glob
from PIL import Image
from keras.utils import np_utils, Sequence
from sklearn.model_selection import train_test_split
class BaseSequence(Sequence):
"""
基础的数据流生成器,每次迭代返回一个batch
BaseSequence可直... |
import csv
from termcolor import colored
from pycoingecko import CoinGeckoAPI
import sys
# Handling system args
if(len(sys.argv) > 1):
if(sys.argv[1] in ['-h', '--help']):
print(
'''Usage: python3 cryptoPortfolioManager.py [OPTION]...
Crypto Portfolio Manager - A CLI Tool to keep track ... |
#!/usr/bin/env python3
import os
import sys
import tempfile
import tracemalloc
import itertools
from operator import itemgetter
from heap import HeapNode
columnSize = {} # map of column names to size in bytes
columnList = [] # only column names with relative position
columnSort = [] # indices of columns to be sor... |
import argparse
import logging
import os
import re
import boto3
import pandas as pd
def arguments():
parser = argparse.ArgumentParser(description='Process hits in our DB to indicators for the application database.')
parser.add_argument('-run',
type=int,
help='R... |
import pytorch_lightning as pl
import torch
import torchmetrics
from prototorch.components.components import Components
from prototorch.functions.distances import euclidean_distance
from prototorch.functions.similarities import cosine_similarity
def rescaled_cosine_similarity(x, y):
"""Cosine Similarity rescaled ... |
from numpy import linalg as la
from scipy import linalg as sla
from sklearn.cluster import KMeans
import igraph as ig
import numpy as np
import math
import plotly.plotly as py
import plotly.graph_objs as go
py.sign_in('panbabybaby', 'JS2Punm2xSGm2MgZEFA3')
def normalized_clutering_ng(S, k):
print(S)
rows, col... |
# Solutions for Radon tutorial - PyData Global 2020 Tutorial
def radon_noise():
"""Create noise to add to projections
"""
sigman = 5e-1 # play with this...
n = np.random.normal(0., sigman, projection.shape)
projection_n = projection + n
projection1_n = projection1 + \
n[pro... |
# Copyright 2019 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
from termcolor import colored
import logging
import time
import os
import json
from pathlib import Path
import shutil
class Logger:
def __init__(self):
self.__logger = logging.getLogger()
Logger.mkdir_if_not_exist('logs')
__file_name = 'logs/' + time.strftime('%Y-%m-%d', time.localtime(tim... |
"""Load notebook and cells"""
import argparse
import tarfile
import os
import chardet
from reproducemegit.jupyter_reproducibility import config
from reproducemegit.jupyter_reproducibility import consts
from reproducemegit.jupyter_reproducibility.db import RequirementFile, Repository, connect
from reproducemegit.jupyt... |
import glob
from abc import ABC, abstractmethod
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from functools import reduce
from logging import getLogger
from pathlib import Path
from sys import stderr
from tempfile import TemporaryDirectory
from typing import Iterator, List, Optiona... |
# Copyright 2020 Advanced Micro Devices, 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... |
import pandas as pd
import tushare as ts
from StockAnalysisSystem.core.config import TS_TOKEN
from StockAnalysisSystem.core.Utility.common import *
from StockAnalysisSystem.core.Utility.time_utility import *
from StockAnalysisSystem.core.Utility.CollectorUtility import *
# -------------------------------------------... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
import os
import sha3
from ethereum.utils import privtoaddr, encode_hex
from hashlib import sha256
from web3 import Web3
import signal
import time
import logging.handlers
signal.alarm(0x60)
my_ipc = Web3.IPCProvider("/home/ubuntu/.ethereum/geth.ipc")
assert my_ipc.isConne... |
import os
from hashlib import sha256
import importlib
import json
import logging
import textwrap
from uuid import uuid4
from pathlib import Path
from pkg_resources import resource_filename
from tempfile import NamedTemporaryFile
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parser... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mailbox
import os
import optparse
import sys
# Input path with maildir data.
DEFAULT_PATH = os.path.expanduser('~/.mail')
# Path to store the attachments. The idea is to have an output folder per account
DEFAULT_OUTPATH = os.path.expanduser('~/detachments/') + DEFAU... |
import re
import click
from CollinsTrans import CollinsTranslator, Translated, NoAnswer
from googletrans import Translator
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from requests.exceptions import ReadTimeout
@click.... |
"""
@author zchholmes / https://github.com/zchholmes
@author syt123450 / https://github.com/syt123450
"""
import argparse
import os
import sys
sys.path.append(
os.path.abspath(
os.path.join(
__file__, os.pardir
)
)
)
from tf.tensorflow_conversion import show_tf_model_summary, prep... |
from datetime import datetime
from string import Template
from typing import Optional, Union
import discord
from redbot.core import Config, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import (
bold,
humanize_list,
humanize_number,
inline,
)
from .abc import Composit... |
import os
import requests
import json
import dateutil.parser
import time
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from util import load_ground_truth, get_sysnset_map, is_predict_correct
IMG_DIR = '/opt/client/data/val_img'
GROUND_TRUTH_FILE = './data/ILSVRC2012_validation_groun... |
# vim:ts=4:sts=4:sw=4:expandtab
from satori.client.common import want_import
want_import(globals(), '*')
from satori.web.utils.decorators import contest_view
from satori.web.utils.forms import StatusBar
from satori.web.utils.tables import *
from django import forms
from django.shortcuts import render_to_response
from d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... |
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
from transformers import BertTokenizer
from enum import Enum
InputDataClass = NewType("InputDataClass", Any)
class ExplicitEnum(Enum):
@classmethod
def _missing_(cls, value):
raise ValueErro... |
from pathlib import Path
import os
import pandas as pd
import tensorflow as tf
from six import StringIO
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import text_problems
from tensor2tensor.data_generators.function_docstring import GithubFunctionDocstring
from tensor2ten... |
#!/usr/bin/python
import sys
import os
import re
import subprocess
import time
import csv
import datetime
from signal import *
BASE_DIR = 'twitter_nlp.jar'
if 'TWITTER_NLP' in os.environ:
BASE_DIR = os.environ['TWITTER_NLP']
sys.path.append('%s/python' % (BASE_DIR))
sys.path.append('%s/python/ner' % (BASE_DIR))... |
import matplotlib.pyplot as plt
import numpy as np
import os
from shutil import copyfile
import pdb
data_dir = '/home/abel/DATA/ILSVRC/'
checkpoint_dir = '/home/abel/DATA/faster_rcnn/resnet101_coco/checkpoints/'
name = 'EntAllVideos-NeighCycle'
run = 1
data_info = {'data_dir': data_dir,
'annotations_dir'... |
#import wxversion
#wxversion.select("2.8")
import wx
import sys
#import ping
from ping3 import ping
import socket
from time import gmtime, strftime
from random import randint
from time import sleep
def pingScan(event):
#check start host <= end host
if hostEnd.GetValue() < hostStart.GetValue():
... |
# coding: utf-8
# Copyright (c) 2012, Machinalis S.R.L.
# This file is part of quepy and is distributed under the Modified BSD License.
# You should have received a copy of license in the LICENSE file.
#
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
"""
Domain specific language for DBpedia quepy.
"""
from ... |
#!/usr/bin/env python3
# coding: utf-8
"""
@file: writer.py
@description:
@author: <NAME>
@email: <EMAIL>
@last modified by: <NAME>
change log:
2021/07/05 create file.
2022/02/09 save raw data and result
"""
from stereo.core.stereo_exp_data import StereoExpData
from stereo.log_manager import logger
from sci... |
from io import BytesIO
from pynq import Overlay, DefaultIP
from ptp2.ptp import timer
import time
from protocol import Protocol, WaveInfo
g_overlay = None
debug = False
class AdBramAll(DefaultIP):
def __init__(self, description):
super().__init__(description=description)
bindto = ['chi... |
'''Q-learning demonstration on FrozenLake gym environment
'''
from os import system
from tqdm import tqdm
import numpy as np
import gym
# for training
MAX_EPISODES = 5000
MAX_MOVES_PER_EP = 200
# max number of hyperparamter combinations
MAX_COMBOS = 20
# max number of chances to be given to a hyperparameter combinati... |
# -*- coding: utf-8 -*-
"""
Clik extension for adding an interactive command shell to an application.
:author: <NAME> <<EMAIL>>
:copyright: Copyright (c) <NAME> and contributors, 2017-2019.
:license: BSD
"""
from __future__ import print_function
import cmd
import contextlib
import shlex
from clik.argparse import Arg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Import modules
from pcl_helper import *
import sensor_msgs.point_cloud2 as pc2
from sensor_msgs.msg import PointCloud2, PointField
import pcl
# DONE: Define functions as required
def voxel_filter(cloud, leaf_size = 0.01):
# Voxel Grid filter for input point cloud
... |
import battleship as ship
import pandas as pd
import numpy as np
def random_generation(generation_size, genes):
# create dataframe for gene pool
generation = pd.DataFrame(columns=['Sequence','Chromosome','Generation','Birth','Fitness','Parents'])
# for each chromosome
i = 0
while i < generation_s... |
#! /usr/bin/env nix-shell
#! nix-shell -i python3 leaflet.nix
import os
import folium
import glob
import pickle
from urllib.parse import urlsplit, urlunsplit
import html
import sys
from osgeo import gdal, osr
from branca.element import CssLink, Figure, JavascriptLink, MacroElement
from jinja2 import Template
import j... |
#!/usr/bin/env python3
"""Channel coding in L2.
This module contains functions used for conversion between type-1 and type-5
bits in lower MAC. These process individual bursts or blocks, and don't
store state in between calls."""
import ctypes
import numpy as np
import numba # to make things run faster
libcorrect =... |
#!/usr/bin/python
"""
UNHCR:
-----
Generates urls from the UNHCR microdata website.
"""
import logging
from hdx.data.dataset import Dataset
from hdx.data.hdxobject import HDXError
from hdx.location.country import Country
from hdx.utilities.dateparse import parse_date_range
from slugify import slugify
logger = loggi... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust
#
# 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:/... |
import os
import timeit
import pytest
import melina
datadir = os.path.abspath(__file__ + '/../data')
def parse(filename):
return melina.XmlParser.from_file(datadir + '/' + filename).parse()
def id_func(param):
if isinstance(param, str):
name, ext = os.path.splitext(param)
if ext == '.xml':
... |
import random
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
class PushGame1D:
NUM_CELLS = 10
PLAYER_VAL = 55
BOX_VAL = 155
TARGET_VAL = 255
def __init__(self):
self.stateSize = self.NUM_CELLS
self.actionSiz... |
# -*- coding:utf-8 -*-
# email:<EMAIL>
# create: 2021/2/1
import torch
from torch import nn
from networks.components.attention.base import PositionalEncoding
from networks.tr.tr_seq.transform_encoder import TransformEncoder
def get_pad_mask(seq, pad_idx):
return (seq == pad_idx).unsqueeze(-2)
class Torch_transf... |
'''
Created on 22.02.2021
@author: <NAME>
'''
from ImageBot.image_processing.general import expand_canvas
from math import sqrt
import numpy as np
import imgaug.augmenters as iaa
from ..Config import MODEL_MAX_SCALE, MODEL_MIN_SCALE, MODEL_MIN_ROT,\
MODEL_MAX_ROT, MODEL_PERCENTAGE_FLIP, MODEL_PERSPECTIVE_MIN_TRANS... |
from MovieRecommender import process_data
import numpy as np
from scipy.sparse import csr_matrix, load_npz
import random
import implicit
from sklearn import metrics
import os
import pickle
def test_train_split(sparse_user_item, pct_test=0.2):
'''
This function will take in the original user-item matrix and "m... |
"""
感知机模型:
1、训练数据样本;
2、选取初始值;
3、判断是否为误分类点;
4、若是误分类点,则随机梯度下降,并更新权值 w 与 偏置值 b;
5、直至无误分类点。
"""
#%%
import numpy as np
import matplotlib.pyplot as plt
#%%
class showPicture:
def __init__(self, xSample, ySample, w, b):
self.w = w
self.b = b
self.xData = np.linspace(-2, 2... |
# -*- coding: UTF-8 -*-
"""
Fazova trajektorie spinani ruznych typu zateze tranzistorem - myslim ze to byl KD503
"""
#pylint: disable=invalid-name
from matplotlib import pyplot as plt
import numpy as np
POINTS = 500
def graf_time(t, u, i, dt, dv, di, title):
t_ax = [time * dt for time in t]
i_ax = [curr * di... |
import itertools
import numpy as np
import sys
from collections import defaultdict, namedtuple
#Credit:
#https://github.com/dennybritz/reinforcement-learning
EpisodeStats = namedtuple("Stats",["episode_lengths", "episode_rewards"])
def make_epsilon_greedy_policy(Q, epsilon, decay, nA):
"""
Creates an epsilon... |
from abc import ABCMeta, abstractmethod
import logging
from raco.expression.visitor import ExpressionVisitor
LOG = logging.getLogger(__name__)
class Algebra(object):
__metaclass__ = ABCMeta
@abstractmethod
def opt_rules(self, **kwargs):
raise NotImplementedError("{op}.opt_rules()".format(op=typ... |
import pandas as pd
from torch import nn, manual_seed
import torch
import time
import os
import random
import numpy as np
from ast import literal_eval
from torch.nn import L1Loss
from torch.optim import Adam
def read_feature_table(path, target, variables):
feature_table = pd.read_csv(path)
for var in [tar... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Pysilhouette.
#
# Copyright (c) 2009 HDE, Inc.
#
# 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, in... |
import json
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pykeen.models import models
HERE = os.path.dirname(__file__)
RESULTS = os.path.join(HERE, 'results')
SUMMARY_DIRECTORY = os.path.join(HERE, 'summary')
os.makedirs(SUMMARY_DIRECTORY, exist_ok=True)
logger ... |
"""This module contains the general information for StatsThrFloatValue ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class StatsThrFloatValueConsts:
DIRECTION_ABOVE_NORMAL = "aboveNormal"
DIRECTION_BELOW_NORMAL = "bel... |
#!/usr/bin/env python
#++++++++++++++++++++++++++++++++++++++++
# LAPART 1 Test +++++++++++++++++++++++++
# +++++++++++++++++++++++++++++++++++++++
# Copyright C. 2017, <NAME> ++++++
#++++++++++++++++++++++++++++++++++++++++
import time
import math
import numpy as np
import pandas as pd
from .art import ART
def norm... |
#!/usr/bin/env python3
"""
Utilities for mkdocs-macros
"""
import subprocess
from copy import deepcopy
import os, sys, importlib.util
from termcolor import colored
# ------------------------------------------
# Trace and debug
# ------------------------------------------
TRACE_COLOR = 'green'
TRACE_PREFIX = 'macros... |
import torch
from torch import nn
from torch import optim
import cv2
import numpy as np
import torch.nn.functional as F
class DoubleConv2(nn.Module):
def __init__(self, in_ch, out_ch):
super(DoubleConv2, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1)... |
import argparse
import numpy as np
import copy
import os
import time
from concurrent.futures.process import ProcessPoolExecutor
from domains.witness import WitnessState
import random
class PuzzleGenerator:
def fill_region(self, state, region, color, prob):
"""
Fills the percentage specified i... |
# -*- coding:utf-8 -*-
"""
Implements a function for hoisting specially constructed comments in SQL
queries and using them to rewrite that query. This is done to support query
hints whilst obviating patching Django's ORM in complex ways.
"""
from __future__ import unicode_literals
import operator
import re
from collec... |
"""
Disclaimer
All investment strategies and investments involve risk of loss.
Nothing contained in this program, scripts, code or repositoy should be
construed as investment advice.Any reference to an investment's past or
potential performance is not, and should not be construed as, a recommendation
or as a guarantee... |
import logging
import aiohttp.web
from discord.ext.commands import Cog
from .errors import *
log = logging.getLogger(__name__)
def route(name=None):
"""
Used to register a coroutine as an endpoint when you don't have
access to an instance of :class:`.Server`
Parameters
----------
name: str... |
from os.path import dirname, join, realpath
import pytest
from numpy import array, dtype, nan
from numpy.testing import assert_array_equal, assert_equal
from pandas_plink import example_file_prefix, read_plink, read_plink1_bin
def test_read_plink():
datafiles = join(dirname(realpath(__file__)), "data_files")
... |
# -*- coding: utf-8 -*-
from rest_framework.test import APIRequestFactory
from olympia import amo
from olympia.access.models import Group, GroupUser
from olympia.accounts.serializers import (
BaseUserSerializer, PublicUserProfileSerializer,
UserNotificationSerializer, UserProfileSerializer)
from olympia.amo.te... |
import matplotlib.pyplot as plt
import numpy as np
def _enforce_ratio(goal_ratio, supx, infx, supy, infy):
"""
Computes the right value of `supx,infx,supy,infy` to obtain the desired
ratio in :func:`plot_eigs`. Ratio is defined as
::
dx = supx - infx
dy = supy - infy
max(dx,dy) ... |
#encoding=utf-8
import pygame, sys
import random
class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = sp... |
from copy import deepcopy
import torch
from torch import nn, optim
import torch.nn.functional as F
from transformers import AdamW, BertConfig, BertForSequenceClassification
from model.scapt import SCAPT
class LabelSmoothLoss(nn.Module):
def __init__(self, smoothing=0.0):
super(LabelSmoothLos... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
"""
Support for Honeywell Lyric devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/lyric/
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import ecstasy
import os
import pytest
import requests
import time
from collections import namedtuple
import tests.paths
import lnk.bitly.info
VERSION = 3
API = 'https://api-ssl.bitly.com/v{0}'.format(VERSION)
with op... |
import os
import json
import falcon
import pytest
from .dataset_fixtures import *
from datalad_service.tasks.snapshots import write_new_changes
def test_get_snapshot(client, celery_app):
# The main test dataset has one revision we can fetch
response = client.simulate_get(
'/datasets/{}/snapshots/{}'... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import redirect, render, get_object_or_404
from django.utils import timezone
from djang... |
# Copyright 2021 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software... |
#!/usr/bin/env python
# Author: <NAME>
# License: BSD 2-clause
# Last Change: Mon Apr 25, 2022 at 08:34 PM -0400
#
# Description: pidcalib2 wrapper (P)
import json
import re
from argparse import ArgumentParser
from os import system, chdir, makedirs
from os.path import basename, dirname, abspath
from glob import glob
... |
# -*- encoding: utf-8 -*-
"""
MIT License
Copyright (c) 2019 - present AppSeed.us
"""
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Sum
from django.shortcuts import render
from django.template import loader
from django.h... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 5 09:08:54 2021
根据research_field_0304v2.csv
对一个公司-->所在行业的所有公司研究领域求交集
"""
import csv
import pandas as pd
#先把一家公司所有年份研究领域合并
def get_field_list(orgpath,outpath):
orgdf = pd.read_csv(orgpath,dtype=str)
orgdf['stock_code'] = orgdf['stock_code'].astype(str).str.zfi... |
import torch
import torch.nn as nn
import torch.nn.functional as F
# import numpy as np
'''
reference from: https://github.com/auspicious3000/autovc/blob/master/model_vc.py
'''
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super(LinearNorm, self)._... |
# -*- coding: utf-8 -*-
"""
examples from: https://likegeeks.com/python-gui-examples-tkinter-tutorial/
"""
import numpy as np
from tkinter import *
window = Tk()
window.title("Welcome")
window.geometry('400x600')
# 1st func
n = 0
lbl = Label(window, text="Extract continuous pages")
lbl.grid(colu... |
"""
Nonnegative CP decomposition by Hierarchical alternating least squares (HALS).
Author: <NAME> <<EMAIL>>
"""
import numpy as np
import numba
from tensortools.operations import unfold, khatri_rao
from tensortools.tensors import KTensor
from tensortools.optimize import FitResult, optim_utils
def ncp_hals(
... |
from enum import Enum
from typing import Union
from meross_iot.cloud.timeouts import LONG_TIMEOUT
from meross_iot.cloud.abilities import HUB_MTS100_ALL, HUB_MTS100_TEMPERATURE, HUB_MTS100_MODE, HUB_TOGGLEX, HUB_ONLINE
from meross_iot.cloud.devices.subdevices.generic import GenericSubDevice
from meross_iot.logger impo... |
import appdaemon.plugins.hass.hassapi as hass
import time
class ButtonEventHub(hass.Hass):
pressed_time_stamp = None
released_time_stamp = None
last_hold_time_stamp = None
def initialize(self):
self.listen_state(self.pressed_button_event,
self.args["observed_button"]... |
import numpy as np
import pandas as pd
from scipy.linalg import toeplitz
import sys
import os
from config import config
import timecorr as tc
from matplotlib import pyplot as plt
import seaborn as sns
sim_function = sys.argv[1]
r = sys.argv[2] #reps
F = int(sys.argv[3]) #number of features
T = int(sys.argv[4]) #numbe... |
from Utilities.Database import database_data_line, database_record_logs
from Utilities import configure_functions
from Utilities.helpers import should_skip, detect_change
from shared_types import ConfigType
from typing import Dict
import pymongo
import re
#
# TODO: set MongoDB credentials
#
# specify mong... |
from django.contrib import messages
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
fro... |
import os
from classy_blocks.classes.mesh import Mesh
from classy_blocks.classes.operations import Face, Extrude
import numpy as np
def load_airfoil_file(filename, chord=1):
points_upper = []
points_lower = []
def line_to_numbers(line):
line = line.strip()
p2d = [float(s) for s in line.s... |
#!/usr/bin/env python3
import os, os.path, sys
from glob import glob
import lxml.etree
import re
from builder_common import *
def get_classes_conditional(doxy_xml_files, cond):
"""Get classes and members from a list of Doxygen XML files that
meet the given condition."""
found = {}
for xmlfile in d... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 05 16:40:31 2015
@author: <NAME>
"""
import numpy as np
import sklearn.metrics as skm
import sklearn.ensemble as ske
import sklearn.cross_validation as skcv
"""
Selects some trips from a main driver, and some trips from other drivers from the feature matrix... |
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# 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... |
"""Read and write notebooks as regular .py files.
Authors:
* <NAME>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed... |
"""Script to evaluate a dataset fold under a model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from magenta.models.coconet import lib_data
from magenta.models.coconet import lib_evaluation
from magenta.models.coconet import lib_graph
from ... |
'''
Module : Main
Description : The main entry point for the program.
Copyright : (c) <NAME>, 07 Dec 2018
License : MIT
Maintainer : <EMAIL>
Portability : POSIX
The program reads one or more input FASTA files. For each file it computes a
variety of statistics, and then prints a summary of the statistics as... |
from random import \
randrange as rand, \
choice as rand_choice, \
sample
from math import sqrt
def rand_sample(set_collection):
return sample(set_collection, 1)[0]
def prob_choice(set_collection, key=lambda x: x, revert=False):
arr_sum = sum(map(key, set_collection))
rand_pos = rand(0, arr_s... |
# Copyright 2018 Iguazio
#
# 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, softwa... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import division, print_function, unicode_literals
import argparse
import json
import os
import shutil
import time
import torch
from utils import util
from evaluate import MultiWozEvaluator
from model.model import Model
parser = argparse.ArgumentParser(descriptio... |
import os
import re
import attr
import tempfile
from avalon import aftereffects
import pyblish.api
from openpype.settings import get_project_settings
from openpype.lib import abstract_collect_render
from openpype.lib.abstract_collect_render import RenderInstance
@attr.s
class AERenderInstance(RenderInstance):
#... |
"""Config flow to configure the AIS Spotify Service component."""
import logging
import aiohttp
from homeassistant import config_entries
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.core import callback
from .const import DOMAIN
G_SPOTIFY_AUTH_URL = None
_LOGGER = logging.get... |
# import_export_google_civic/models.py
# Brought to you by We Vote. Be good.
# https://developers.google.com/resources/api-libraries/documentation/civicinfo/v2/python/latest/civicinfo_v2.elections.html
# -*- coding: UTF-8 -*-
from ballot.models import BallotItem
from datetime import date, timedelta
from django.db impo... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2017-2018 CNRS
# 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 limita... |
import streamlit as st
import pandas as pd
import plotly.express as px
def main():
# set parameter files
parm_file = './parms.xlsx'
# form the UI page & sidebar
st.set_page_config(
page_title="Zoo",
page_icon=":panda_face:",
layout="centered",
initial_sidebar_state="ex... |
# ------------------------------------------------------------------------------
# CodeHawk Java Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2017-2020 Kestrel Technology LLC
#
# Permission is hereby granted, free of... |
# In the paris version, pyaudio is not necessary,
# only an audio presentation will happen.
# note that if WavPlayer wants to be used, pyaudio needs to be set up
#import pyaudio
import wave
import time
import sys
import os
import zmq
import serial
import logging
import struct
import RPi.GPIO as GPIO
logger = logging.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.