content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '138JnT_HK_pUEQvupbAXUaFDe7Ttviw0dlsN_8nMrZ9I'
|
#!/usr/bin/env python3
""" Calculate monthly net worth """
import collections
import datetime
import logging
import time
import argparse
import logging
from dateutil import rrule
from dateutil.parser import parse
import pandas
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters... |
import numpy as np
with open("./input.txt", "r") as f:
energy_levels = [[int(energy_level) for energy_level in line.strip()] for line in f.readlines()]
paded_energy_levels = np.pad(energy_levels, 1, 'constant', constant_values=11)
step = 0
while True:
step += 1
stack = []
flashed = [[False for _ in paded_... |
with open('input.txt') as f:
input = f.read().splitlines()
def decode_hex_to_binary(string):
output = ""
for char in string:
if char == "0":
output += "0000"
elif char == "1":
output += "0001"
elif char == "2":
output += "0010"
elif char ... |
import psycopg2
class DBHandler:
def __init__(self, db_url):
self.db_url = db_url
self.conn = None
def get_connection(self):
return psycopg2.connect(self.db_url)
def execute(self, cmd, fetch=True):
self.conn = self.get_connection()
cur = self.conn.cursor()
... |
from setuptools import setup, find_packages
setup(name='resonantgeoview_server',
version='0.0.1',
description='',
url='',
install_requires=[
'girder==3.0.0a6.dev11',
'girder_worker==0.6.0',
'girder_worker_utils==0.8.4',
'girder-plugin-geometa',
'girder-plugin-geo... |
import random
import string
import time
from dataclasses import dataclass
from unittest.mock import ANY
import numpy as np
import pytest
from p4p.nt import NTEnum, NTScalar
from p4p.server import Server
from p4p.server.asyncio import SharedPV
from tartiflette import Engine
from coniql.app import make_context
@datac... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobufs/services/organization/actions/get_location.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_... |
from models import user
# create the basic tables
def migrate(db_conn):
db_conn.execute('''CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
admin INTEGER,
pwhash TEXT
)''')
db_conn.execu... |
from ._func_sig import FuncSig, get_func_sig
from ._gen_tip import gen_tip_exc
from ._i18n import I18n, I18nTypedDict, change_local, i18n_config_dict, i18n_local, join_i18n
from ._lazy_property import LazyProperty
from ._pydantic_util import create_pydantic_model, get_model_global_name, pait_get_model_name_map, pait_mo... |
__all__ = ["bitsharesnoderpc", "exceptions", "websocket"]
|
import pickle
from pathlib import Path
import numpy as np
import pandas as pd
import sklearn
def type_check(df):
for col in ['timestamp', 'value', 'below_threshold']:
assert pd.api.types.is_numeric_dtype(df[col])
return None
def feature_engineer(df, minutes=30, n_historical_cols=2):
"""Add... |
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n <= 1:
return 0
left_to_right = [0] * n
right_to_left = [0] * n
maxProfit = 0
# left to right
# finding max profit we can... |
import game
from ball import *
import random
screen = pygame.display.set_mode((800, 550))
pygame.display.set_caption("Combat")
coord = [[400, 275], [40, 120], [730, 120], [730, 400]]
class Tank(pygame.sprite.Sprite):
def __init__(self, tank, pos_x, pos_y, current_sprite):
super().__init__()
self.... |
#! /usr/bin/env python
from numpy.testing import TestCase, assert_equal, assert_almost_equal
from aubio import notes, source
import numpy as np
from utils import list_all_sounds
list_of_sounds = list_all_sounds('sounds')
AUBIO_DEFAULT_NOTES_SILENCE = -70.
AUBIO_DEFAULT_NOTES_RELEASE_DROP = 10.
AUBIO_DEFAULT_NOTES_MI... |
from typing import Union
from pydantic import ValidationError
from returns.functions import raise_exception
from returns.result import Failure, ResultE
from kaiba.mapper import map_data
from kaiba.models.kaiba_object import KaibaObject
def process(
input_data: dict,
configuration: dict,
) -> ResultE[Union[l... |
# -*- coding: utf-8 -*-
"""Base command for all Veld commands
"""
from typing import List
from typing import Optional
from wilderness import Command
from veld.stream_processor import StreamProcessor
class VeldCommand(Command):
def register(self):
self.add_argument(
"file",
hel... |
"""
Copyright 2015-2018 IBM
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, sof... |
import numpy as np
def test_update_p_3():
from scipy.special import logit
from update_params_linear_regression import update_p_3
N = 4
p0 = 0.3
res = update_p_3(p0, N)
expected_res = np.array([logit(p0), logit(p0), logit(p0), logit(p0)])
np.testing.assert_array_equal(res, expected_res)
... |
from mediasiteXMLGen.generator import generate
data = input('Enter your data here with correct extension: ')
generate(data) |
import re
import logging
def get_done(df, done_dir):
done_mnr = []
for p in done_dir.rglob("*.pdf"):
done_mnr.append(re.findall("\d+", p.stem)[0])
return df[df.MN.isin(done_mnr)]
def get_not_done(df, not_done_dir):
not_done_mnr = []
for p in not_done_dir.rglob("*.pdf"):
not_done_m... |
import os
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
def send_email(**kwargs):
"""
This function sends an email based on the arguments provided. Arguments
include template, data, subject and to_email. tem... |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField,SelectField
from wtforms.validators import Required
class UpdateProfile(FlaskForm):
bio = TextAreaField('Tell us about you.',validators = [Required()])
submit = SubmitField('Submit')
class OpinionForm(FlaskForm):
... |
from django.test import TestCase
from django.urls import reverse
class HomeTest(TestCase):
def test_home_redirect(self):
url = reverse('home')
response = self.client.get(url)
self.assertRedirects(response, '/forum/')
def test_home_forum(self):
url = reverse('posts_list')
... |
# State Machine-based Motion Lighting Implementation for AppDaemon
# Maintainer: Daniel Mason
# Version: v1.1.2
# Documentation: https://github.com/danobot/appdaemon-motion-lights
import appdaemon.plugins.hass.hassapi as hass
from transitions import Machine
from transitions.extensions import Hierarch... |
import contextlib
import dot
import errno
import glob
import os
import sh
import shutil
import signal
import sys
class Terminate(BaseException):
pass
def sigterm_exception(signum, stackframe):
raise Terminate()
def remove(*files):
"""Remove the specified files or directories"""
for f in files:
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Script for plotting 1D DG FEM data stored in VTK files
"""
import glob
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import argparse
from os.path import join as pjoin
import os
import sys
from glob import glob
from sfepy.discrete.dg.dg_1D... |
from infi.pyutils.lazy import cached_method
from infi.dtypes.wwn import WWN
from infi.dtypes.iqn import IQN
from infi.hbaapi import Port
import six
class FCConnectivity(object):
"""Fibre Channel Connectivity Information """
def __init__(self, device, local_port, remote_port):
super(FCConnectivity, sel... |
from .query import FindExcelFile
import numpy as np
import pandas as pd
def _check_zero(data, cols):
for col in cols:
data[col] = data[col].replace({'0': np.nan, 0: np.nan})
class DataCollector(object):
def __init__(self, *args):
self._excel_file = None
if args:
self._... |
from __future__ import absolute_import
import keras
import keras.backend as K
from .. import similarities
class PermanentDropout(keras.layers.Dropout):
"""Applies dropout to the input that isn't turned off during testing.
This is one possible improvement for your generator models.
Args:
p: flo... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name='returns_json',
version='0.0.1',
author='Momspresso',
author_email='rakesh.khulbe@mycity4kids.com',
description='response formatter decorator',
long_description=long_d... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
import wx
class MyMessageDialog(wx.MessageDialog):
"""
进行了一些基本的中文化工作
"""
def __init__(self, parent, message, caption=None, *args, **kwargs):
super(MyMessageDialog, self).__init__(parent, message, caption=caption,
... |
import socket
import sys
import threading
import elgamal
numBits = 32
keyOne = elgamal.generate_keys(iNumBits=numBits, iConfidence=1000)
privKeyB = keyOne["privateKey"]
pubKeyB = keyOne["publicKey"]
print(f"Public Key: {pubKeyB.p} {pubKeyB.g} {pubKeyB.h}")
# ----------------------------------------------------------... |
from enum import Enum, auto
class TYPE(Enum): # 자료형
INT = auto()
STR = auto()
class Variable:
def __init__(self):
self.var = dict()
def insert(self, name):
try:
self.var[name]
except KeyError:
self.var[name] = [f"var_{len(self.var)}", TYPE.INT]
... |
import os
import sys
import tensorflow as tf
from mllogger.logger import Logger
sys.path.append("../")
from configer.dmnconfig import DMNConfig
from trainer.dynmemnettrainer import DynMemNetTrainer
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer("num_classes", 15, "number of label")
tf.app.flags.DEFINE_float... |
"""This module can also be executed as a Command Line utility."""
import sys
if __name__ == '__main__':
import pyJsJson
success = pyJsJson.main.main(sys.argv[1:])
if not success:
sys.exit(1)
|
#to profile
#python -m cProfile -s tottime ifft_example.py
import phenom
import matplotlib
# matplotlib.use('MacOSX')
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from phenom.utils.utils import Constants, HztoMf, pad_to_pow_2
import lal
import lalsimulation as lalsim
from ifft import *... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import numpy as np
# Generic data augmentation
class Augmenter:
""" Generic data augmentation class with chained operations
"""
def __init__(self, ops=[]):
if not isinstance(ops, list):
print("Error: ops must be a list of fu... |
'''
Test cache lookup results in CACHE condition
'''
# 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 Ap... |
import numpy as np
import matplotlib.pyplot as plt
from utils import sigmoid , gradient_descent_logistic_regresion
X1=np.array([]) # grade 1
X2=np.array([]) # grade 2
Y=np.array([]) # admitted to university
file = open("data\\ex2data1.txt", "r")
for row in file:
ar = row.split(",")
X1 = np.append(X1,float(ar[0])) ... |
import os
import subprocess
from string import Template
from damn_at import logger
from damn_at.transcoder import TranscoderException
from damn_at.pluginmanager import ITranscoder
from damn_at.options import IntVectorOption, IntOption, expand_path_template
from damn_at.utilities import script_path, run_blender
clas... |
import os
import csv
import glob
import nibabel as nb
import numpy as np
# check if they have PyPEER installed
try:
import PyPEER
from PyPEER.peer_func import \
global_signal_regression, \
prepare_data_for_svr, \
train_model, \
save_model, \
load_model, \
predict... |
# Copyright (C) 2021 Open Source Robotics Foundation
#
# 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... |
names = []
while True:
string = input()
if string == ".":
break
names.append(string)
print(names)
print(len(names))
|
import models
import settings
import datetime
from optparse import OptionParser
option_parser = OptionParser()
option_parser.add_option(
"-s", "--settings",
dest="settings",
help="Settings",
metavar="SETTINGS"
)
(options, args) = option_parser.parse_args()
try:
settings_dict = settings.config[opt... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Adding items to a deque.
"""
__version__ = "$Id$"
#end_pymotw_header
import collections
# Add to the right
d1 = collections.deque()
d1.extend('abcdefg')
print 'extend :', d1
d1.append('h')
print 'append :', d... |
# This file holds the defensive layers. They can be selected to be put into a network.
# See ^^^chainer^^^ for this module's reference
import chainer
# The math^^^pythonmath^^^ module
import math
import common
# Idea defined by ^^^cutillielastic^^^
class ElasticSigmoid(chainer.Link):
def __init__(se... |
import sys
sys.path.append( "." )
from urlutil import *
def TestSingleObjectEditing(userpass, verbose=0):
#Create a changeset
createChangeset = "<?xml version='1.0' encoding='UTF-8'?>\n" +\
"<osm version='0.6' generator='JOSM'>\n" +\
" <changeset id='0' open='false'>\n" +\
" <tag k='comment' v='python test ... |
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(111, projection="aitoff")
plt.title("Aitoff")
plt.grid(True)
plt.figure()
plt.subplot(111, projection="hammer")
plt.title("Hammer")
plt.grid(True)
plt.figure()
plt.subplot(111, projection="lambert")
plt.title("Lambert")
plt.grid(True)
plt.figure()
plt.subplot... |
from fastavro import writer, parse_schema
schema = {
"name": "CertLog",
"type": "record",
"namespace": "nl.openintel.certlog",
"fields": [
{
"name": "cert_index",
"type": "int"
},
... |
from __future__ import print_function
import sys, time
from raspberrypy.control.myo import Myo
if __name__ == '__main__':
m = Myo(sys.argv[1] if len(sys.argv) >= 2 else None)
def proc_emg(emg, moving, times=[]):
print(emg)
## print framerate of received data
times.append(time.time())
if len(time... |
# -*- coding: utf-8 -*-
# Author : Manki Baek
# e-mail : manki.baek@seculayer.com
# Powered by Seculayer © 2021 Service Model Team, R&D Center.
import joblib
from typing import Callable
from mlps.common.Constants import Constants
from mlps.core.apeflow.interface.model.export.SavedModelAbstract import SavedModelAbstra... |
from __future__ import print_function, unicode_literals
import json
import pytest
import random
import ssl
import string
import sys
from websocket import ABNF
sys.path.append(".")
import wee_slack
from wee_slack import EventRouter, SlackRequest
class fakewebsocket(object):
def __init__(self):
self.retu... |
#!/usr/bin/env python
import sys
import time
import signal
import math
from geometry_msgs.msg import Twist
class avoid_obstacle:
priority = 2
flag_set = False
new_flag = False
initial_omega = 0.0
min_dist = 3.0
avoid_vectors = []
def __init__(self):
pass
def flag(self, clo... |
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import networkx.drawing.nx_pylab as nxp
import bisect, os, pickle
import numpy as np
from matplotlib.lines import Line2D
from ptsnet.utils.analytics import compute_wave_speed_error
from ptsnet.utils.io import get_temp_folder
def pl... |
from enum import Enum, auto
from os.path import join, dirname, abspath
from typing import Dict, Union
from numpy.ma import ceil
from qcore.config import (
determine_machine_config,
get_machine_config,
host,
qconfig,
__KnownMachines,
)
from qcore.constants import PLATFORM_CONFIG, ProcessType
WORKF... |
import pandas as pd
import numpy as np
import os
from bs4 import BeautifulSoup
from urllib.request import urlopen
# 観測所名が半角の方がいいのでENGLISH版ページを採用
sonde_sites_url = 'https://www.jma.go.jp/jma/en/Activities/upper/upper.html'
this_file_path = os.path.abspath(os.path.dirname(__file__))
sonde_sites_csv_path = os.path.join... |
import pandas as pd
from datetime import date
from .database import Database
class Slice(Database):
def __init__(self, path, date=None, lookback=250):
super().__init__(path)
self.date = self.latest_date if date == None else min([self.latest_date, date])
self.lookback = lookback
sel... |
import json
import os
from configparser import ConfigParser, ExtendedInterpolation
from django.conf import settings
from sandbox.libs.cmd_process import CmdProcessInteractive
from sandbox.libs.context.models import SandboxContext
from sandbox.libs.logger import logger_by_name
# predicate for actions which depend on ... |
def factorial(n):
if(n == 0):
return 1
else:
return n*factorial(n-1)
if __name__ == "__main__":
number = int(input("Enter number:"))
print(f'Factorial of {number} is {factorial(number)}')
|
import discord
from discord.ui import View
from .buttons import LinkBtn
class AboutView(View):
def __init__(self, bot, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_item(LinkBtn(_url=f"https://discord.com/oauth2/authorize?client_id={bot.user.id}&permissions=403041534&scope=bot+app... |
# -*- Mode: Python; tab-width: 8; python-indent-offset: 4 -*-
# This Source Code Form is subject to the terms of the MIT License.
# If a copy of the ML was not distributed with this
# file, You can obtain one at https://opensource.org/licenses/MIT
# author: JackRed <jackred@tuta.io>
def get_keywords(keywords, db):
... |
"""A logging module for use with elsapy.
Additional resources:
* https://github.com/ElsevierDev/elsapy
* https://dev.elsevier.com
* https://api.elsevier.com"""
__version__ = '0.2'
import time, logging
from pathlib import Path
## Following adapted from https://docs.python.org/3/howto/logging-cookbook.... |
'''
this code is for supervised learning the state-action pair
using the neural network approach
'''
from __future__ import print_function
import tensorflow as tf
import numpy as np
import random
import pickle
import matplotlib.pyplot as plt
import argparse
import math
import time
import gzip
from env_test import Reac... |
import cv2
import datetime
import math
import numpy
import random
import re
import subprocess
import sys
import caffe
import tempfile
def duration_string_to_timedelta(s):
[hours, minutes, seconds] = map(int, s.split(':'))
seconds = seconds + minutes * 60 + hours * 3600
return datetime.timedelta(seconds=sec... |
# -*- coding: utf-8 -*-
# A Survey on Negative Transfer
# https://github.com/chamwen/NT-Benchmark
import sklearn
import scipy
from cvxopt import matrix, solvers
from sklearn.model_selection import GridSearchCV
from sklearn.metrics.pairwise import linear_kernel, rbf_kernel
import numpy as np
import scipy.io
import scipy... |
#!/usr/bin/env python3
#
# Copyright 2019 Venafi, 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... |
#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
import numpy as np
import os
import json
from my_tools import first_module, second_module
EXE_PATH = os.getcwd() # 실행 경로
SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) # 스크립트 경로
UPPER_PATH = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 상위 경로
C... |
"""
Standalone script to load all bad odometers in an astropy table.
This can also be used for any other google sheet by changing the id and
the tab.
"""
import requests
from astropy.table import Table
URL_BASE = ('https://docs.google.com/spreadsheets/d/'
'{}/gviz/tq?tqx=out:csv&sheet={}')
SHEET_ID = '1gv... |
from uuid import uuid4, uuid5, NAMESPACE_DNS
from urllib.parse import urlencode
from django.conf import settings
from django.core.cache import caches
from django.http.response import HttpResponseNotModified
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError: # pragma: nocover
Middl... |
import pytest
import json
import numpy as np
from elfi.examples.ma2 import get_model
from elfie.bolfi_extensions import BolfiParams, BolfiFactory
def test_bolfi_params_can_be_serialized():
bp = BolfiParams()
json.dumps(bp.__str__())
def test_simple_inference_can_be_run():
n_samples = 4
true_params = ... |
import logging
import os
import time
import requests
import telegram
from dotenv import load_dotenv
from telegram.error import NetworkError, TelegramError
# Включаем поддержку записи UTF-8 в журналах
# noinspection PyArgumentList
logging.basicConfig(
handlers=[logging.FileHandler('hw_sp_bot.log', 'a', 'utf-8')],
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-28 11:27
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('OverApp', '0007_auto_20160619_0651'),
]
operations ... |
import csv
import datetime
import discord
import logging
from common.config import config
log = logging.getLogger("eris.voice_channel_tracker")
class VoiceChannelTracker:
def __init__(self, eris, signals):
self.eris = eris
self.signals = signals
signals.signal('ready').connect(self.enumerate_voice_channels)
... |
# -*- coding: utf-8 -*-
# @Time : 20/5/1 16:58
# @Author : qgking
# @Email : qgking@tju.edu.cn
# @Software: PyCharm
# @Desc : LungSegDataLoader.py
from skimage.transform import resize
from torch.utils.data import Dataset
from common.base_utls import *
from common.data_utils import *
import torch
from torchvisi... |
# coding: utf-8
from rest_framework import serializers
from . import models
class PhraseParam(serializers.ModelSerializer):
class Meta:
model = models.PhraseParam
exclude = ('id', 'phrase')
class Phrase(serializers.ModelSerializer):
params = PhraseParam(many=True)
aliases = serializers.S... |
import pathlib
import sys
from classes.Config import DowConfig
from classes.Database import DowDatabase
config = DowConfig(pathlib.Path(".").joinpath("config.json"))
db = DowDatabase(config.ROOT_DIR, config.DB_NAME)
o = db.SelectAllFilesLike(sys.argv[1])
if o is not None:
for f in o:
print(f[:-1])
print("\n... |
from decimal import Decimal
import pytest
from pricehist.format import Format
from pricehist.outputs.csv import CSV
from pricehist.price import Price
from pricehist.series import Series
@pytest.fixture
def out():
return CSV()
@pytest.fixture
def series():
prices = [
Price("2021-01-01", Decimal("24... |
# -*- coding: utf-8 -*-
import pytest
from excerpt_html import excerpt_html
@pytest.mark.parametrize('html_text, kwargs, expected_excerpt', [
# test cut mark
((u'<p>Howdy there<!--more--> you <em>pretty</em> thing!</p>'
u'<p>Another paragraph</p>'),
{},
u'<p>Howdy there</p>'),
# cut mark... |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
import sys
import os
import urllib.request, urllib.parse, urllib.error
from .models import *
class PnpfileApi(object):
def __init__(self, apiClien... |
"""Methods and classes related to executing Z-Wave commands and publishing these to hass."""
import logging
from openzwavemqtt.const import ATTR_LABEL, ATTR_POSITION, ATTR_VALUE
from openzwavemqtt.util.node import get_node_from_manager, set_config_parameter
import voluptuous as vol
from homeassistant.core import call... |
from PIL.PngImagePlugin import PngImageFile
from sparclur.parsers.present_parsers import get_sparclur_renderers
from sparclur._renderer import Renderer
import itertools
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import to_rgb
import warnings
import numpy as np
impor... |
"""Library implementing complex-valued normalization.
Authors
* Titouan Parcollet 2020
"""
import torch
from torch.nn import Parameter
import numpy as np
from speechbrain.nnet.complex_networks.c_ops import multi_mean
class CBatchNorm(torch.nn.Module):
"""This class is implements the complex-valued batch-normal... |
"""Tests for the storage helper."""
import asyncio
from datetime import timedelta
import json
from unittest.mock import Mock, patch
import pytest
from homeassistant.const import (
EVENT_HOMEASSISTANT_FINAL_WRITE,
EVENT_HOMEASSISTANT_STOP,
)
from homeassistant.core import CoreState
from homeassistant.helpers i... |
""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical
capabilities".
http://www.math.unm.edu/~wester/cas/book/Wester.pdf
See also http://math.unm.edu/~wester/cas_review.html for detailed output of
each tested system.
"""
from sympy import (
Rational,
symbols,
Dummy,
factorial,
sqr... |
#!/usr/bin/env python3
# http://rosalind.info/problems/revp/
from Bio import SeqIO
def main():
data_file = open("./rosalind_revp.txt", 'r')
dna_fasta = list(SeqIO.parse(data_file, "fasta"))
dna_string = dna_fasta[0].seq
print(dna_string)
palindromes = []
for i in range(len(dna_string)):... |
from .unpacker import Unpacker
|
"""
@Project: Real time stream processing of formula 1 racing car telemetry
@author: hemanth
"""
import socket
import structs
import rawutil
from pprint import pprint
UDP_IP = "127.0.0.1" # UDP listen IP-address
UDP_PORT = 20777 # UDP listen port
PACKET_SIZE = 1289 # Amount of bytes in packet
# create a socket
s... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 12 00:31:15 2020
@author: admin
"""
import utils
import time
import random
from colorama import Style, Fore
print('''
___ __ ___ ____ _
/ _ \___ ____/ /__ / _ \___ ____ ___ ____ / __/___(_)__ __... |
from flask import Flask, request, render_template
import pyrebase
import datetime
#Add Config APIs
config = {
"apiKey": "AIzaSyBJIrUUh_Sv20NdfKlt8SXdXujn64CTckk ",
"authDomain": "teachbotflask.firebaseapp.com",
"databaseURL": "https://teachbotflask.firebaseio.com",
"storageBucket": "teachbotflask.appspot.com... |
# -*- coding: utf-8 -*-
import copy
import logging
import os
import unittest
from configparser import ConfigParser
from unittest.mock import patch
import requests_mock
from mock import MagicMock
from execution_engine2.exceptions import (
CannotRetryJob,
RetryFailureException,
InvalidParameterForBatch,
)
f... |
"""
Django settings for onlinequiz project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os... |
import os
import time
import re
import unittest
import batch
from flask import Flask, Response, request
import requests
from .serverthread import ServerThread
class Test(unittest.TestCase):
def setUp(self):
self.batch = batch.client.BatchClient(url=os.environ.get('BATCH_URL'))
def test_job(self):
... |
# Copyright 2019 HTCondor Team, Computer Sciences Department,
# University of Wisconsin-Madison, WI.
#
# 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/LICE... |
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import histogram_module
import dist_module
def rgb2gray(rgb):
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
# model_images - list of file names of model images
# query_image... |
# Generated by Django 2.2 on 2019-05-19 11:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('content', '0001_initial'),
('lesson', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
#-
# Copyright (c) 2011 Robert N. M. Watson
# Copyright (c) 2013 Robert M. Norton
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @... |
import datetime
import uuid
from collections import OrderedDict
from marshmallow import fields
from typing import Type, Any, Mapping, List, Optional
from ._settings_classes import HandlerType
# These types exist so we can signal that str fields are e-mails or URLs
class EmailStr(str):
pass
class URLStr(str):
... |
_base_ = '../../../base.py'
# model settings
model = dict(
type='Classification',
pretrained=None,
with_sobel=False,
backbone=dict(
type='DynamicResNet',
in_channels=3,
stem_width=32,
#stem_width=64,
body_depth = [2, 4, 5, 3],
#body_depth = [2, 2, 5, 2],
... |
from appium.webdriver.common.appiumby import AppiumBy
from auto_clip_video_byandroid.common.ffmpeg_util import get_duration_from_ffmpeg
def edit_video_action(log_print,driver,force_sleep,video_show_1th_name,video_show_2th_name,elementIdPrefix,video_show_file,editor_tool_audio_import_position=None,editor_tool_paster_po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.