text stringlengths 1 927k |
|---|
"""Python STIX2 Memory Source/Sink"""
import io
import itertools
import json
import os
from stix2 import v20, v21
from stix2.base import _STIXBase
from stix2.datastore import DataSink, DataSource, DataStoreMixin
from stix2.datastore.filters import FilterSet, apply_common_filters
from stix2.parsing import parse
def ... |
from __future__ import annotations
import collections
import logging
import typing
from aoc.helpers import Puzzle
__all__ = ["part_one", "part_two", "prepare_puzzle"]
log = logging.getLogger(__name__)
class Instruction(typing.NamedTuple):
"""A ConsoleApplication instruction."""
operation: str
argument... |
import numpy as np
import scipy as sp
import pandas as pd
import numbers
from typing import Callable, List, Union
import logging
from .base import Epsilon
from ..distance import SCALE_LIN
from ..sampler import Sampler
from ..storage import save_dict_to_json
logger = logging.getLogger("Epsilon")
class TemperatureBas... |
"""Useful queries for profiling PostgreSQL databases
These queries are mainly adapted from
https://gist.github.com/anvk/475c22cbca1edc5ce94546c871460fdd
"""
from functools import wraps
from pathlib import Path
def execute_raw(raw):
from aiida.manage.manager import get_manager
backend = get_manager()._load_b... |
import time, sys
import httplib, urllib
#ip_address='192.168.0.100'
ip_address='10.12.19.67'
#ip_address='10.20.218.197'
cost='25'
l_amount='100'
sys.path.append('../..')
import spade
in_use=False
name="night_stand_agent"
class MyAgent(spade.Agent.Agent):
def _setup(self):
template = spade.Behaviour.ACLTemplate()... |
"""
Optimal piecewise binning for continuous target.
"""
# Guillermo Navas-Palencia <g.navas.palencia@gmail.com>
# Copyright (C) 2020
import time
import numpy as np
from .base import _check_parameters
from .base import BasePWBinning
from .binning_statistics import PWContinuousBinningTable
from .metrics import conti... |
import torch.optim as optim
import env as grounding_env
from models import *
from torch.autograd import Variable
import logging
def ensure_shared_grads(model, shared_model):
for param, shared_param in zip(model.parameters(),
shared_model.parameters()):
if shared_param.... |
from gym import envs, logger
import os
def should_skip_env_spec_for_tests(spec):
# We skip tests for envs that require dependencies or are otherwise
# troublesome to run frequently
ep = spec._entry_point
# Skip mujoco tests for pull request CI
skip_mujoco = not (os.environ.get('MUJOCO_KEY_BUNDLE') ... |
import asyncio
async def upper_cased(value: str) -> str:
await asyncio.sleep(1)
return value.upper()
coroutines = [
upper_cased("h"),
upper_cased("e"),
upper_cased("l"),
upper_cased("l"),
upper_cased("o"),
upper_cased(" "),
upper_cased("w"),
upper_cased("o"),
upper_cased("r... |
from knn import compare
from Knndisplay import display_knn
import time
def get_knn():
start_time=time.time()
compare()
display_knn()
end_time=time.time()
print end_time-start_time |
import glob
import struct
import wave
from collections import Counter
from operator import itemgetter
import librosa
import numpy as np
from tslearn.metrics import dtw
def compute_mfcc_from_file(file):
time_characteristic = create_time_characteristics_of_a_file(file)
mfcc = librosa.feature.mfcc(y=time_charac... |
import tkinter as tk
from Windows import StorageGui, NavBar
class Main:
root = tk.Tk()
root.geometry("1000x600")
root.title(" [EDD] Fase-1" )
app = StorageGui(master=root)
app.configure(bg='#2C3E50')
app.place(x=200,width=200,height=200)
app.mainloop()
start = Main() |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
def evaluate(clf, x_train, x_test, y_train, y_test, name, training_data_name, embedding, params=None):
predictions = clf.predict(x_train)
# train_tn, train_fp, train_fn, train_tp = confusi... |
sx, sy, gx, gy = map(int, input().split())
if sx == gx:
print(sx)
exit()
print(sx + sy*(gx-sx)/(gy+sy)) |
from ted_sws.rml_to_html.resources import get_sparql_query
class QueryRegistry:
@property
def TRIPLE_MAP(self):
return get_sparql_query(query_file_name="get_triple_maps.rq")
@property
def LOGICAL_SOURCE(self):
return get_sparql_query(query_file_name="get_logical_source.rq")
@pro... |
from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_mak... |
# -------------------------------------------------------------------
# Copyright 2021 Virtex authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.... |
from flask import Flask
from . import csrf
import ishuhui.data as data
import env
from flask_assets import Environment, Bundle
def create_app(config, should_register_blueprints=True):
app = Flask(__name__,static_folder = env.ASSETS,static_url_path='/assets')
assets = Environment(app)
js = Bundle('ap... |
from numbers import Integral
from numpy import ma
import numpy as np
from scipy.sparse import coo_matrix
from scipy.stats import mode
from prody.chromatin.norm import VCnorm, SQRTVCnorm, Filenorm
from prody.chromatin.functions import div0, showDomains, _getEigvecs
from prody import PY2K
from prody.dynamics import GNM... |
class Solution:
# @param {string} s
# @return {boolean}
def isPalindrome(self, s):
if not s:
return True
start = 0
end = len(s)-1
s = s.lower()
while start < end:
while start < end and not s[start].isalnum():
start += 1... |
"""Rolling Statistics"""
__docformat__ = "numpy"
import logging
from typing import Tuple
import pandas as pd
import pandas_ta as ta
from gamestonk_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def get_rolling_avg(df: pd.DataFrame, length: int) -> Tuple[pd... |
import tools
import os
from dataset import RandomCropper, sub_sampling
from utils import plot_flying_things3D
height = 240
width = 576
ratio = 1
height = height//ratio
width = width//ratio
train_files = os.listdir('/media/jack/data/Dataset/pytorch/flyingthings3d/TRAIN')
test_files = os.listdir('/media/jack/data/Data... |
import _plotly_utils.basevalidators
class LabelValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='label',
parent_name='sankey.link.concentrationscales',
**kwargs
):
super(LabelValidator, self).__init__(
plotly_name=plo... |
# Copyright 2018 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... |
class GPENCIL_UL_brush:
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
pass |
# -*- coding: utf-8 -*-
import pygame
import math
import time
import os
from rocket import Rocket
from watch import Watch
from button import Start
from button import Stop
from button import Pause
from button import Scroll
from button import Change_velocity
from button import Galileo
from button import Ruseng
def r... |
import os.path as osp
import logging
import time
import argparse
from collections import OrderedDict
import options.options as option
import utils.util as util
from data.util import bgr2ycbcr
from data import create_dataset, create_dataloader
from models import create_model
#### options
parser = argparse.ArgumentPars... |
#!/usr/bin/env python3
"""Generate an updated requirements_all.txt."""
import fnmatch
import importlib
import os
import pathlib
import pkgutil
import re
import sys
from script.hassfest.model import Integration
COMMENT_REQUIREMENTS = (
'Adafruit-DHT',
'Adafruit_BBIO',
'avion',
'beacontools',
'blink... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Christian Ledermann
#
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later vers... |
"""
# db module - database adapter functions
"""
from sqlalchemy import DateTime, TypeDecorator
# pylint: disable=abstract-method
class DateTimeUtc(TypeDecorator):
'''
Results returned as offset-aware datetimes.
'''
impl = DateTime
# pylint: disable=unused-argument
def process_result_value(... |
"""
Swagger Words
~~~~~~~~~~~~~
Python friendly aliases to reserved Swagger words.
:copyright: Copyright 2018 PlanGrid, Inc., see AUTHORS.
:license: MIT, see LICENSE for details.
"""
from __future__ import unicode_literals
additional_properties = "additionalProperties"
all_of = "allOf"
allow_empt... |
# Copyright (c) 2015 Red Hat, 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 ... |
import sys
from pathlib import Path
def mainwin32():
if len(sys.argv) < 2:
print(f'to use run: python set_activate_alias.py $profile')
return
profile = sys.argv[1]
profile = Path(profile)
# makr parent directory if not exist
if not profile.parent.exists():
profile.pare... |
from django import forms
from .models import UserAccount
class UserCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.Cha... |
# -*- coding: utf-8 -*-
"""
Attitude Estimators
===================
These are the most common attitude filters.
"""
from .angular import AngularRate
from .aqua import AQUA
from .complementary import Complementary
from .davenport import Davenport
from .ekf import EKF
from .famc import FAMC
from .flae import FLAE
from... |
from time import sleep
valor1 = int(input('Digite Primeiro valor: '))
valor2 = int(input('Digite segundo valor: '))
opção = 0
while opção != 5:
print(''' [ 1 ] SOMAR
[ 2 ] MULTIPLICAR
[ 3 ] MAIOR
[ 4 ] NOVOS NÚMEROS
[ 5 ] SAIR DO PROGRAMA''')
opção = int(input('Qual opção você deseja ? '))
... |
#
# 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... |
from .bam import *
from .cbam import * |
# Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
"""
MPC with open-loop Gaussian policies
"""
from .controller import Controller
from mjmpc.utils.control_utils import generate_noise, scale_ctrl
import copy
import numpy as np
import scipy.special
class OLGaussianMPC(Controller):
def __init__(self,
d_state,
d_obs,
... |
import abc
class CombinationIndicator(metaclass=abc.ABCMeta):
def __init__(self, threshold: float):
self.__threshold: float = threshold
@property
def threshold(self):
return self.__threshold
@threshold.setter
def threshold(self, new_threshold: float):
self.__threshold = n... |
"""PriorityStateMachine keeps track of stoping or halting in front of stop or halt lines.
See :mod:`simulation.src.simulation_evaluation.src.state_machine.states.priority` for
implementation details of the states used in this StateMachine.
"""
from typing import Callable
from simulation.src.simulation_evaluation.src... |
import unittest
from app.models import Pitch,User
from flask_login import current_user
from app import db
class TestComment(unittest.TestCase):
def setUp(self):
self.user_Lelabo = User(username = 'Lelabo',password = '123Pass', email = 'mail@lelabo.com')
self.new_pitch = Pitch(pitch_id=12345,pitch_... |
#!/usr/bin/env python
#
# Copyright 2012-2015 clowwindy
#
# 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 la... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 2 15:19:45 2018
@author: kite
"""
import datetime, time
from pymongo import UpdateOne, ASCENDING, UpdateMany
from database import DB_CONN
from stock_util import get_trading_dates, get_all_codes
import tushare as ts
import numpy as np
import pandas as pd
import requests
... |
import logging
import pathvalidate
import smtplib
import ssl
import tenacity
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from ..config import MailConfig
from ..context import Cont... |
import codecs
from os import path
from textwrap import dedent
from setuptools import setup
here = path.abspath(path.dirname(__file__))
with codecs.open(path.join(here, "README.rst"), encoding='utf-8') as f:
long_description = f.read()
setup(
name='python-jsonstore',
use_scm_version=True,
description... |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
"""Support for monitoring the rtorrent BitTorrent client API."""
import logging
import xmlrpc.client
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_URL, CONF_NAME,
CONF_MONITORED_VARIABLES, STATE_IDLE)
from homeassistant.helpers.enti... |
import glob
import sys
##### creatin dict that will have all control positions
def con_pos(con_MH):
con_dict = {}
f = open(con_MH, 'r')
for line in f:
s = line.split()
chr = s[0]
pos = s[1]
ref = int(s[7]) #ref depth
alt = int(s[9]) #alt depth
vaf = float(alt)/(ref+alt)
alt_type = s[8] #alt base
... |
from .scrape_objects_MVP import get_attributes, get_id
from pymongo import MongoClient
import os
DB_URL = os.environ['DB_URL']
CLIENT = MongoClient(DB_URL)
DB = CLIENT.compurator
PRODUCTS_COLLECTION = DB["products"]
def check_product_exists(url):
'''
:param url: url of amazon product
:return: false if pr... |
import os
import asposewordscloud
import asposewordscloud.models.requests
from asposewordscloud.rest import ApiException
from shutil import copyfile
words_api = WordsApi(client_id = '####-####-####-####-####', client_secret = '##################')
file_name = 'test_doc.docx'
# Upload original document to cloud stora... |
from __future__ import annotations
import copy
from sys import getsizeof
import re
from typing import Dict, Iterable, List, Tuple, Union, overload
from api.errors import InvalidBlockException
from utils import Int
class Block:
"""
Class to handle data about various blockstates and allow for extra blocks to ... |
"""Test component/platform setup."""
# pylint: disable=protected-access
import asyncio
import datetime
import threading
from unittest.mock import AsyncMock, Mock, patch
import pytest
import voluptuous as vol
from homeassistant import config_entries, setup
from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_... |
from .signal_stats import compute_signal_stats, SignalStats
from .hjorth_mobility import compute_hjorth_mobility, HjorthMobility
from .hjorth_complexity import compute_hjorth_complexity, HjorthComplexity
from .lyapunov_exponent import compute_lyapunov_exponent, LyapunovExponent
from .power_spectral_entropy import compu... |
# importing all modules
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib import cm
import matplotlib.tri as tri
from matplotlib.colors import LogNorm
import matplotlib.patches as mpatches
from matplotlib.ticker import LogFormatter
from col... |
from WonderPy.core.wwConstants import WWRobotConstants
from WonderPy.util import wwMath
from .wwCommandBase import WWCommandBase, do_not_call_within_connect_or_sensors
_rc = WWRobotConstants.RobotComponent
_rcv = WWRobotConstants.RobotComponentValues
_rp = WWRobotConstants.RobotProperties
class WWCommandHead(WWComma... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import sys
import subprocess
import os
import os.path
import glob
import tempfile
#
# run as
# python balibase_nbr.py in_dir out_dir nbr_exe_path
# how I ran :
# python balibase_nbr.py
# /Users/srirampc/work/phd/research/arakawa/data/balibase/tree
# /Users/srirampc/work/phd/research/arakawa/data/balibase/tree
... |
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRa... |
"""
`init` Command
"""
import os
import click
import bldr
import bldr.dep
import bldr.gen.render
from bldr.environment import Environment
from bldr.gen.render import CopyTemplatesRender
from bldr.cli import pass_environment, run_cmd
dotbldr_path = os.path.join(os.path.abspath(os.path.dirname(bldr.__file__)), "dotbl... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------------... |
import unittest
from .. import anoitypes
class TestANOITypes(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main() |
#@OUTPUT String xlabel
#@OUTPUT String ylabel
#@OUTPUT String title
# OUTPUT Double xmin
# OUTPUT Double xmax
# OUTPUT Double ymin
# OUTPUT Double ymax
# xmin = -2.0
# xmax = 2.0
# ymin = -2.0
# ymax = 2.0
# Set global outputs
xlabel = "X"
ylabel = "Y"
title = "XY Chart"
import math
from java.util import Random
from... |
array=[2,5,8,9,3,6]
a=[1,3,6]
matrix=[a,[2,5,7]]
array.append(1)
print(matrix)
print(array)
new_list=array+matrix
print(new_list)
new_list.pop(-3)
print(new_list)
new_list[0]="T"
print(new_list)
# new_list.clear()
# print(new_list)
print(new_list.index(5))
table=tuple(["Monday","Tuesday"])
print(table[1])
string="1234... |
# Emitter expects events obeying the following grammar:
# stream ::= STREAM-START document* STREAM-END
# document ::= DOCUMENT-START node DOCUMENT-END
# node ::= SCALAR | sequence | mapping
# sequence ::= SEQUENCE-START node* SEQUENCE-END
# mapping ::= MAPPING-START (node node)* MAPPING-END
__all__ = ['Emitter', 'Emit... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Puru
#
# 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 limi... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mixer/v1/config/client/api_spec.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... |
from pextant.lib.geoshapely import GeoPolygon, LONG_LAT
import numpy as np
import csv
class SEXTANTSolver(object):
def __init__(self, environmental_model, cost_function, viz):
self.env_model = environmental_model
self.cost_function = cost_function
self.viz = viz
self.searches = []
... |
import random
import warnings
class Client:
def __init__(self, client_id, group=None, train_data={'x' : [],'y' : []}, eval_data={'x' : [],'y' : []}, model=None):
self._model = model
self.id = client_id
self.group = group
self.train_data = train_data
self.eval_data = ev... |
"""
test_django-geonames-place
------------
Tests for `django-geonames-place` views module.
"""
import unittest
from django.conf import settings
from django.test import Client, TestCase
from django.urls import reverse
from geonames_place.models import Place
@unittest.skipUnless(
settings.GEONAMES_KEY, 'No GEO... |
from typing import Optional
from fastapi import Depends, FastAPI, Security
from fastapi.security import APIKeyHeader
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyHeader(name="key", auto_error=False)
class User(BaseModel):
username: str
def get_curre... |
import argparse
from datetime import datetime
from tensorflow.contrib.keras.python.keras.initializers import TruncatedNormal
from docqa import trainer
from docqa.data_processing.qa_training_data import ContextLenKey
from docqa.dataset import ClusteredBatcher
from docqa.encoder import DocumentAndQuestionEncoder, Singl... |
# encoding: utf-8
import logging
import datetime
from urllib import urlencode
from pylons.i18n import get_lang
import ckan.lib.base as base
import ckan.lib.helpers as h
import ckan.lib.navl.dictization_functions as dict_fns
import ckan.logic as logic
import ckan.lib.search as search
import ckan.model as model
import... |
# The MIT License (MIT)
# Copyright (c) 2021 Tom J. Sun
# 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, ... |
from django.conf.urls import patterns, url
from .views import (LocationDetail, CategoriesList, CategoryDetail, ArticleDetail,
ArticleList, KeywordDetail, AuthorDetail, ArchiveDetail, ArticleCarouselImageDetail)
urlpatterns = patterns('pari.article.views',
url(r'^categories/(?P<slug>.+)/$', Cat... |
from Tkinter import *
from PIL import ImageTk, Image
import tkMessageBox
import sys
import os
def getNoImagesInDirectory(dir):
return len(getImagesInDirectory(dir))
def getImagesInDirectory(dir):
files = os.listdir(dir)
images = []
for file in files:
if file.lower().endswith((".jpg", ".png",... |
#!/usr/bin/env python3
import random
from itertools import count
from collections import namedtuple
Point = namedtuple('Point', 'x y')
Point.from_spec = lambda st: Point(*[float(si) for si in st.split()])
Circle = namedtuple('Circle', 'c r')
Circle.__new__.__defaults__ = (Point(0, 0), 0)
Circle.__contains__ = lambd... |
# Copyright 2013 CentRin Data, 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... |
import sys
sys.path.append('../python-mbus')
import pytest
from mbus import MBus
@pytest.fixture
def mbus_tcp():
return MBus.MBus(host="127.0.0.1")
def test_connect(mbus_tcp):
mbus_tcp.connect() |
import numpy as np
def clean_data(df, out_df_dir=""):
df.dropna(axis=1, inplace=True)
if out_df_dir:
df.to_csv(out_df_dir)
return df
# Calculate log change of daily price
def log_change(series):
return np.log(series[1] / series[0])
# Calculate correaltion
def calculate_cor(df, start, end... |
# -*- coding: utf-8 -*-
info = {
"%%and-small": {
"(0, 99)": "og =%%spellout-cardinal-reale=;",
"(100, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%%and-small-f": {
"(0, 99)": "og =%spellout-cardinal-feminine=;",
"(100, 'inf')": "=%spellout-cardinal-feminine=;"
},
"%%... |
import os
import torch
from weaver.utils.logger import _logger
from weaver.utils.import_tools import import_module
ParticleTransformer = import_module(
os.path.join(os.path.dirname(__file__), 'ParticleTransformer.py'), 'ParT').ParticleTransformer
class ParticleTransformerWrapper(torch.nn.Module):
def __init_... |
"""The test translator package.""" |
# pylint: skip-file
ClearSamples()
SetSample(1, 'Alu1', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 208.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(2, 'Alu2', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 235.0, u'sam_trans_y': 202.5}, ti... |
"""
This is a framework for terminal interfaces built on top of urwid.Frame.
It must NOT contain any application specific code.
"""
import logging
import threading
from concurrent.futures.thread import ThreadPoolExecutor
import urwid
from sen.exceptions import NotifyError
from sen.tui.commands.base import (
Fron... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import json
from typing import Dict
from airbyte_protocol import AirbyteConnectionStatus, Status, SyncMode
from base_python import AirbyteLogger
from base_singer import BaseSingerSource, SyncModeInfo
class SourceMarketoSinger(BaseSingerSource):
tap_c... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import argparse
import logging
import math
import os
import time
import warnings
from benchmark_dataset import BenchmarkLMDataset, collate_sentences_lm
import torch
from torch.distributed import rpc
import torch.multiprocessing as mp
import torch... |
#!/usr/bin/env python
'''
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")... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Iterable
from .. import QuerySetReader, BaseRecursiveDriver
if False:
from ...proto import jina_pb2
class SliceQL(QuerySetReader, BaseRecursiveDriver):
"""Restrict the size of the ``docs... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 applica... |
# -*- coding: utf-8 -*-
'''
behaving.py raet ioflo behaviors
See raeting.py for data format and packet field details.
Layout in DataStore
raet.udp.stack.stack
value StackUdp
raet.udp.stack.txmsgs
value deque()
raet.udp.stack.rxmsgs
value deque()
raet.udp.stack.local
name host port sigkey prikey
raet... |
import copy
import numpy as np
import warnings
from .regularizer import Regularizer
class Oracle():
"""
Base class for all objectives. Can provide objective values,
gradients and its Hessians as functions that take parameters as input.
Takes as input the values of l1 and l2 regularization.
... |
from setuptools import setup
import re
def extract_version(filename):
contents = open(filename).read()
match = re.search('^__version__\s+=\s+[\'"](.*)[\'"]\s*$', contents, re.MULTILINE)
if match is not None:
return match.group(1)
setup(
name="bigsuds",
version=extract_version('bigsuds.py'... |
# Copyright 2018 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, ... |
# -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.