content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
"""
Session library
Copyright 2020-2021 Leboncoin
Licensed under the Apache License, Version 2.0
Written by Nicolas BEGUIER (nicolas.beguier@adevinta.com)
"""
# Third party library imports
import boto3
PIVOTAL_ROLE = 'arn:aws:iam::xxxxxxxxxxxx:role/AWS-Tower'
def get_session(role_arn, region_n... |
from types import SimpleNamespace
from pandas import DataFrame
from .league import League
from .player import Player
from .user import User
from ..exceptions import RosterNotFoundException
class Team:
def __init__(self, context, user, league):
self._context = context
if type(league) == str:
... |
# -*- coding: utf-8 -*-
# Created on Fri Jun 15 13:59:04 2012
# @author: Merlijn van Deen <deen@physics.leidenuniv.nl>
"""
pyTables helper functions
Most of these are helper functions for `pytables_test.py` and
`pytables_import_shear.py`. The exception to this is `read_packing`,
which loads a packing from th... |
from pyopenproject.api_connection.exceptions.request_exception import RequestError
from pyopenproject.api_connection.requests.patch_request import PatchRequest
from pyopenproject.business.exception.business_error import BusinessError
from pyopenproject.business.services.command.query.query_command import QueryCommand
f... |
from ntp.kb import Atom, load_from_file, normalize
from ntp.nkb import kb2nkb, augment_with_templates, embed_symbol, rule2struct
from ntp.prover import prove, representation_match, is_tensor, is_parameter, neural_link_predict
from ntp.tp import rule2string
import tensorflow as tf
from pprint import pprint
from ntp.jtr.... |
'''
====================================================================
Copyright (c) 2003-2016 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
======================================================... |
#Example copied from the RxD tutorial
#http://www.neuron.yale.edu/neuron/static/docs/rxd/index.html
from neuron import crxd as rxd, h, gui
from matplotlib import pyplot
import numpy
pyplot.ion()
sec = h.Section()
sec.L=100
sec.diam=1
sec.nseg=100
h.CVode().active(1)
caDiff = 0.016
ip3Diff = 0.283
cac_init = 1.0e-4... |
from talon import Context, Module, actions, ui
ctx = Context()
ctx.matches = r"""
os: linux
"""
@ctx.action_class("user")
class Actions:
def desktop(number: int):
ui.switch_workspace(number)
def desktop_next():
actions.user.desktop(ui.active_workspace() + 1)
def desktop_last():
ac... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by vici on 20/07/2017
class ClassProperty:
def __init__(self, f):
self.f = f # where class.method input
print("init")
pass
def __get__(self, instance, owner):
print("get")
return self.f(owner)
def __set__(s... |
"""
simple io use case - run another process, send it input, receive output
"""
from childprocess import ChildProcessBuilder as CPB
with CPB("lua -i -e \"_PROMPT=''\"").spawn() as cp:
# hello world code from lua demos
cp.stdin.write(b'io.write("Hello world, from ",_VERSION,"!\n")\n')
print(cp.stdout.readli... |
###############################################################################
##
## Copyright (C) 2014 Tavendo GmbH
##
## 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 RPi.GPIO as GPIO
import time
import os
#from gopro import run
import subprocess
def pushbutton():
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
input_state = GPIO.input(18)
if input_state == False:
print('Button Pressed')
time.sleep(0.2)
... |
# -*-coding:utf-8-*-
import json
import markdown
from bson import ObjectId
from flask import request
from flask_babel import gettext
from flask_login import current_user
import time
from apps.core.flask.reqparse import arg_verify
from apps.modules.message.process.user_message import insert_user_msg
from apps.modules.up... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_Pr... |
# -*- coding: utf-8 -*-
import json
class ColorDump:
"""
Provide some method to dump ``colors.naming.ColorNames`` results as JSON
or Sass.
"""
def as_json(self, datas, fp=None):
"""
Dump given datas as JSON in a file or as a string
Args:
datas (object): Any obj... |
import uuid
from .. import models
from ...objects import PlotContext, PlotObject, recursively_traverse_plot_object
import logging
log = logging.getLogger(__name__)
def prune_and_get_valid_models(session, delete=False):
"""retrieve all models that the plot_context points to.
if delete is True,
wipe out any... |
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
import json
from functools import reduce
import re
def get_data(str_obj, keys):
"""Extract data from a string-like json object.
Returns a dictionary made up of the 'keys' passed as arguments (expressed in dot notation)
and the corresponding value.
if the key does not exist then the resulting dictiona... |
import timeit
import matplotlib.pyplot as plt
from Bubble_Sort import bubbleSort
from Merge_Sort import mergeSort
from Quick_Sort import quickSort
inputList = [8, 9, 1, 9, 8, 6, 5, 3, 2, 1, 57, 13, 23, 1, 123, 9, 1, 9, 8, 6,
5, 3, 2, 1, 57, 13, 23, 1, 123, 9, 1, 9, 8, 6, 5, 3, 2, 1, 57, 13, 23, 1, 123, 3, ... |
''' http://www.biopython.org/DIST/docs/api/Bio.KDTree.KDTree%27-module.html '''
def photoz(list):
import sys, pyfits, os
file = os.environ['sne'] + '/cosmos/cosmos_zphot_mag25.nums.fits'
hdulist = pyfits.open(file)
table = hdulist["OBJECTS"].data
r = []
for i in list[0]:
r.append(... |
from discord.ext import commands
from bot.exceptions import MemberNotRegistered
from bot.utils import create_embed
from bot.utils import get_tb_message
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.error_messages = {
commands.MissingRequiredArgument: "... |
import itertools
import multiprocessing
import os
import subprocess
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Tuple, Callable, Union
import pandas as pd
from memory_profiler import profile
from networkx import DiGraph
from simod.readers.log_splitter import L... |
"""
Functions for manipulating Widevine DRM
"""
from Crypto.Cipher import AES
from Crypto.Hash import SHA1
from Crypto.Util.Padding import pad
from base64 import b16decode, b64decode, b64encode
import requests
import json
from uuid import UUID
from .widevine_pb2 import WidevineCencHeader
from construct.core import Pref... |
# -*- coding: utf-8 -*-
"""
manager.py
Classes
---------------------------------------
StatisticsManager
WormStatistics
A translation of Matlab code written by Jim Hokanson,
in the SegwormMatlabClasses GitHub repo. Original code paths:
DONE:
# of lin... |
# [sublimelinter pyflakes-@python:2.7]
from globalvars import GAMEINFO, TILEMAP
from tileutils import coord_to_pixel
from tile import Sprite
class SnakeSeg(object):
def __init__(self, coords, prev=None, next=None):
self.spritemap = {
"toright": ("images/snake_bod_left.png", "images/snake_bod_... |
# SPDX-FileCopyrightText: 2021 Aaron Dewes <aaron.dewes@protonmail.com>
#
# SPDX-License-Identifier: MIT
def convertServicesToContainers(app: dict):
app['containers'] = []
# Loop through the dict app['services']
for container in app['services']:
app['services'][container]['name'] = container
... |
# -*- coding: utf-8 -*-
"""
webapp
======
CHANGELOG
=========
0.1.2 / 2021-12-08
------------------
- changes for Python 3.8
- use add_extension for jinja extensions
0.1.1 / 2021-05-19
------------------
- change cors header
0.1.0 / 2021-01-16
------------------
- First Release
"""
__author__ = "R. Bauer"
__c... |
from domain.classroom.attendee import Attendee
from domain.repository import Repository
class AttendeeRepository(Repository):
def _get_entity_type(self) -> str:
return Attendee.__name__
|
# -*- coding: utf-8 -*-
# TODO: refactor "complexity" visitors to be regular visitors
|
"""
Django settings for this project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib im... |
class Runnable(object):
def run(self):
raise NotImplementedError
def cleanup(self):
pass
|
from .event import Event
class LogEvent(Event):
"""Event for log entries."""
__module__ = 'pyobs.events'
def __init__(self, time=None, level=None, filename=None, function=None, line=None, message=None):
Event.__init__(self)
self.data = {
'time': time,
'level': leve... |
# 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
# distribu... |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^',include('home.urls')),
url(r'^admin/', admin.site.urls),
url(r'^admin_login/', include('admin_login.urls')),
url(r'^asr/', include('doctor_login.urls')),
url(r'^patient_login/', include('... |
from collections import deque
def solution(cacheSize, cities):
cache = deque([])
cnt = 0
for i in cities:
i = i.lower()
if i not in cache:
if cacheSize == 0:
return 5 * len(cities)
if len(cache) == cacheSize:
cache.popleft()
... |
import requests
from flask import current_app
from morio.task import celery
@celery.task()
def send_mail(to, subject, text=None, html=None):
config = current_app.config
domain = config.get('MAILGUN_DOMAIN')
key = config.get('MAILGUN_API_KEY')
mailgun_address = config.get('MAILGUN_ADDRESS')
return... |
import itertools
import os
import csv
import collections
import networkx
import numpy
import numpy.linalg
import bioparser.data
class DiseasomeMaker(object):
def __init__(self):
self.ontology = self.get_ontology()
@staticmethod
def transfer_annotations(node_to_genes, node_goto_node):
... |
#!/usr/bin/env python3
# _ ____ ____ ___ ___ _
# / \ / ___| / ___|_ _|_ _| __ _ _ __| |_
# / _ \ \___ \| | | | | | / _` | '__| __|
# / ___ \ ___) | |___ | | | | | (_| | | | |_
# /_/ \_\____/ \____|___|___| \__,_|_| \__|
#
# - from github.com/basnijholt/home-assistant-con... |
# -*- coding: utf-8 -*-
"""
Generate a package with IR implementations and tools.
"""
from __future__ import print_function, division, absolute_import
import os
from textwrap import dedent
from itertools import chain
from . import generator
from . import formatting
from . import astgen
from . import visitorgen
from... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-01-10 18:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("hosts", "0003_challengehostteam_team_url")]
operations = [
migrations.AlterField(
... |
import os
import numpy as np
import configparser as cfg_parser
import tensorflow as tf
import image_util
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
cp = cfg_parser.ConfigParser()
cp.read('net.cfg')
batch_size = cp.getint('train', 'batch_size')
noise_size = cp.getint('train', 'noise_size')
epochs = cp.getint('train', 'e... |
# -*- coding: utf-8 -*-
from .colors import colors as c
import os
def breachcomp_check(targets, breachcomp_path):
# https://gist.github.com/scottlinux/9a3b11257ac575e4f71de811322ce6b3
try:
import subprocess
c.info_news("Looking up targets in BreachCompilation")
query_bin = os.path.joi... |
from application.core.entity.account import Account
from application.core.exception.dashboardplus_exception import (
InputValidationException,
EntityAlreadyExistsException,
AccountAlreadyExistsException, PersitenceException,
UnexpectedFailureException
)
from application.core.port.create_account_port imp... |
from .base import AbstractRiskManager
from ..event import OrderEvent
class ExampleRiskManager(AbstractRiskManager):
def refine_orders(self, portfolio, sized_order):
"""
This ExampleRiskManager object simply lets the
sized order through, creates the corresponding
OrderEvent object a... |
"""
Setting the region
==================
Many of the plotting functions take the ``region`` parameter, which sets
the area that will be shown in the figure. This tutorial covers the different types of
inputs that it can accept.
.. note::
This tutorial assumes the use of a Python notebook, such as IPython or Jup... |
import laia.common.logging as log
def test_filepath(tmpdir):
filepath = tmpdir / "test"
log.config(filepath=filepath)
log.info("test!")
log.clear()
assert filepath.exists()
def test_filename(tmpdir):
with tmpdir.as_cwd():
filepath = "test"
log.config(filepath=filepath)
... |
from tkinter import *
from random import choice
import pandas
BACKGROUND_COLOR = "#B1DDC6"
to_learn = {}
word = {}
# ---------------------------- PANDAS LOGIC ------------------------------- #
try:
data = pandas.read_csv("./data/words_to_learn.csv")
except FileNotFoundError:
data = pandas.read_csv("./data/en_... |
# Copyright (c) 2018, NVIDIA CORPORATION.
#
# 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... |
# -*- coding: utf-8 -*-
### Variables globals ###
host = '' # Host que es passa al socket
port = 12345 # Port del socket
backlog = 5 # Int que es passa al listen
size = 1024 # Mida màxima del paquets
running = 1 # Per mantenir el loop
sockets = [] # Llista temporal de sockets
chat_id_admin = 000000 # Chat_id de l'empr... |
from django.views.generic import TemplateView
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from . import models
from . import forms
from . import filters
from . import consts
class Log(TemplateView):
template_name = None # must be specified by
model = models.Log
form_class ... |
import nltk
import ner
import re
import json
import os
import urllib2
from urllib import urlencode
from pprint import pprint
# open the contents
with open('CodeAssignmentDataSet.json') as json_file:
json_data = json.load(json_file)
json_file.close()
pprint(json_data[0:4])
# The OMDB API's constant fo... |
#! /usr/bin/env python3
# Copyright (c) 2021 Grumpy Cat Software S.L.
#
# This Source Code is licensed under the MIT 2.0 license.
# the terms can be found in LICENSE.md at the root of
# this project, or at http://mozilla.org/MPL/2.0/.
# %%
import numpy as np
import matplotlib.pyplot as plt
import shapelets.compute as... |
from .config import DOSIMode, FeatureFlags, InferenceAlgorithm
from .constants import (
LEAK_NODE,
DEFAULT_SYMPTOM_LEAK_PROPORTION,
DEFAULT_MAX_SYMPTOM_PRIOR,
DEFAULT_MAX_DISEASE_PRIOR,
DEFAULT_APPLY_CONCEPT_GROUPS,
DEFAULT_SINGLE_DISEASE_QUERY,
DEFAULT_IGNORE_OTHER_DISEASES,
DEFAULT_DOS... |
# Matthieu Brucher
# Last Change : 2007-08-29 15:48
"""
Computes a Newton step for a specific function at a specific point
"""
import numpy
import numpy.linalg
class NewtonStep(object):
"""
The Newton step
"""
def __call__(self, function, point, state):
"""
Computes a Newton step based on a function... |
import textwrap
import discretisedfield as df
class Mesh(df.Mesh):
@property
def _script(self):
mx3 = "SetGridSize({}, {}, {})\n".format(self.n[0], self.n[1], self.n[2])
mx3 += "SetCellSize({}, {}, {})\n\n".format(self.cell[0],
self.cell[1],
... |
import dataset
import generate_test_splits
import nltk
sentence = "At eight o'clock on Thursday morning... Arthur didn't feel very good."
tokens = nltk.word_tokenize(sentence)
dataset = DataSet()
generate_test_splits.generate_hold_out_split(dataset, training = 0.9, base_dir="splits") |
#!/usr/bin/env python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Main Madpack installation executable.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import sys
import getpass
import re
import os
import glob
import traceback
import subprocess
import datetime
import tempfile
import shutil... |
# -*- coding: utf-8 -*-
"""
Provides the ownbot User class.
"""
from ownbot.usermanager import UserManager
class User(object):
"""Represents a telegram user.
Args:
name (str): The user's unique telegram username.
user_id (str): The user's unique telegram id.
group ... |
import sqlite3
# Connect to sqlite database
sqliteDb = "../results/results.sqlite"
db = sqlite3.connect(sqliteDb)
try:
db.enable_load_extension(True)
db.load_extension("mod_spatialite")
cur = db.cursor()
# Calculate mean monthly flow rate for last 5 years of data
cur.execute("DROP TABLE IF EXISTS ... |
import pymel.core as pm
import lib.transform
import lib.attribute
class Handle(object):
"""Control class for handle objects."""
def __init__(self, handle):
if pm.nodeType(handle) == "transform":
handle = handle.getShape()
self.node = handle
@classmethod
def create(cls, g... |
import dataclasses
import dis
import inspect
import itertools
from typing import (
Any,
Callable,
List,
)
def all_slots(class_obj: Any) -> List[str]:
slots = itertools.chain.from_iterable(
getattr(cls, '__slots__', ()) for cls in inspect.getmro(class_obj))
return sorted(set(slots))
def ... |
import pandas as pd
import os
from dags.data.postgredb import DataWareHouse
from dags.data.mongodb import DataLake
import psycopg2.errors
from datetime import datetime
if not os.path.exists(os.getcwd()+ "/local_tools/csv/"):
os.mkdir(os.getcwd()+ "/local_tools/csv/")
import logging
logging.basicConfig(level=log... |
numeros = []
while True:
numero = int(input('Digite um número: '))
if numero not in numeros:
numeros.append(numero)
print('Núemro incluído na lista.')
else:
print('Número já informado. Não foi adicionado.')
op=str(input('Deseja continuar ? S/N' )).strip().upper()[0]
while op no... |
import json
import logging
from datetime import datetime
import requests
from uzemszunet.utils import convert_dotnet_date
from uzemszunet.exceptions import DownloadError
URL = 'https://elmuemasz.hu/elmu/ZavartatasTerkep/GetZavartatasok?vallalat=ELMUEMASZ'
logger = logging.getLogger('uzemszunet')
class Emasz:
... |
"""
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | | | | \ analysis
___/... |
from abc import ABCMeta, abstractmethod
# Definition of mothods to build complex objects
class JourneyBuilder(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def transportType(transport):
"Transport type"
@staticmethod
@abstractmethod
def originLocation(origin):
"Origin loc... |
from calc import get_expression, parse_args, evaluate_expression
def test_parses_arguments_simple():
expr = "2 2"
arg1, arg2 = parse_args(expr)
assert (arg1, arg2) == ("2", "2")
def test_gets_first_argument():
expr = "(add 2 (multiply 4 5)) 43"
assert get_expression(expr) == "(add 2 (multiply 4 5))"
def te... |
import re
from typing import List
from CookLangPy.ingredient import Ingredient
from CookLangPy.cookware import Cookware
from CookLangPy.timer import Timer
replaceSpecialReg = re.compile(r"(([#@])(?:[^#@\n{}]+{\S*}|\w+))")
stepOutReg = re.compile(r"(\$[CIT])(\d+)")
blockCommentReg = re.compile(r".*\[-(.*)-\]")
timerRe... |
class GetESIDataError(Exception):
pass
class GetESIDataNotFound(GetESIDataError):
pass
class InvTypesNotFound(Exception):
pass |
# Copyright (c) Hikvision Research Institute. All rights reserved.
import mmcv
import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon, Circle
from mmdet.core.visualization import imshow_det_bboxes, color_val_matplotlib
fr... |
# -*- coding: utf-8 -*-
"""
Éditeur de Spyder
Ceci est un script temporaire.
"""
from ctypes import *
from ctypes.wintypes import *
import win32file
import win32pipe
from pywin32_testutil import str2bytes
import numpy as np
import struct
import time
global lpszPipename
lpszPipename = u'\\\\.\\pipe\\scTDCserver'
... |
"""Backend for the ground station.
Manages satellites, computes passes and stores observations.
"""
import os
from flask import Flask
def create_app(config=None):
"""Perform set up for the backend."""
app = Flask(__name__, instance_path="/app/data", instance_relative_config=True)
app.config["SATS_DB"]... |
import uuid
from dotenv import load_dotenv
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine import ValidationError
from cassandra.cqlengine.models import Model
from flask import Flask, jsonify, request
from todos import Todos, session, KEYSPACE
from flask_cors import CORS
load_dotenv()
... |
import json
from enum import Enum
class SpriteParameter(Enum):
FILENAME = "file"
FILESNAME = "files"
SCALE = "scale"
ROTATION = "rotation"
TYPE_IMAGE = "typeImage"
TYPE = "type"
DURATION = "duration"
LOOPED = "looped"
class ObjectParameter(Enum):
THRUST = "thrust"
RESISTANCE =... |
from tests.scoring_engine.checks.check_test import CheckTest
class TestWordpressCheck(CheckTest):
check_name = 'WordpressCheck'
properties = {
'useragent': 'testagent',
'vhost': 'www.example.com',
'uri': '/wp-login.php'
}
accounts = {
'admin': 'password'
}
cmd =... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Softbank Robotics Europe
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, t... |
########################################################################
#
# File Name: ElementElement.py
#
#
"""
Implementation of the XSLT Spec element stylesheet element.
WWW: http://4suite.com/4XSLT e-mail: support@4suite.com
Copyright (c) 1999-2000 FourThought Inc, USA. All Rights Reserved.
Se... |
from django.shortcuts import render
from django.http import JsonResponse
import socket
# Create your views here.
def get_hosname(request):
data = {
'hostname': socket.gethostname()
}
return JsonResponse(data) |
# -*- coding: utf-8 -*-
# [问题描述]
# 计算输入的字符串中空格,换行符的个数
# [输入形式]
# 输入可以是键盘上的任意字符,最后一行末尾没有换行符
# [输出形式]
# 分别输出空格个数,换行符个数输出结果一行显示,数字之间空格隔开
# [样例输入]
# bb ss pp=
#
# fz
# [样例输出]
# 2 1
str1=''
print('请您输入字符,输入‘#’可结束输入:')
s = input()
while s!='#': # 请您输入字符,输入‘#’可结束输入:
str1 = str1+s+'\n'
s= input()
print('计算得:空格个数(左... |
class SimpleResult():
code = 0
message = ""
def __init__(self, code , message):
self.code = code
self.message = message
def json(self):
return {"code":self.code,"message":self.message}
|
import cv2
import numpy as np
import matplotlib.pyplot as plt
from gst_file import gst_file_loader
from draw_utils import draw_ped
# EXAMPLE 3.3.1 | Apply CUDA Contour Based Visual Inspection Engine for Video Stream
# Uncomment this if using OpenGL for image rendering
window_name_1 = "Detected Object"
window_name_2 ... |
#! /usr/bin/python3
from __future__ import division, print_function, unicode_literals
import sys
import wrf433
def callback(d):
print(d)
def main():
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: %s csvfile [vcdfile]\n" % sys.argv[0])
csv_fn = sys.argv[1]
print("Decoding CSV from ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the POSIX time implementation."""
from __future__ import unicode_literals
import decimal
import unittest
from dfdatetime import posix_time
class PosixTimeEpochTest(unittest.TestCase):
"""Tests for the POSIX time epoch."""
def testInitialize(self):
... |
from django import forms
from django.forms import fields
from django.forms.widgets import Select
ISSUES = [("Economy", "Economy"), ("Health Care", "Health Care"),
("Terrorism", "Terrorism"), ("Environment", "Environment"), ]
class IssueForm(forms.Form):
issue = fields.ChoiceField(widget=Select(attrs={... |
from __future__ import print_function
import math
from tqdm import tqdm
import numpy as np
import tensorflow as tf
def primes_in_range(low, high):
def _is_prime(v):
if v <= 3:
return v > 1
sqrt = int(math.sqrt(v))
i = 2
while i <= sqrt:
if v % i == 0:
... |
import unittest
from pizzerias import PizzeriasSample
class PizzeriasSampleTest(unittest.TestCase):
def test_sample(self):
n_of_block = 1000
n_of_shop = 10
seed = 42
sampler = PizzeriasSample(n_of_block, n_of_shops=n_of_shop, seed=seed)
res = [[(655, 693), 28], [(115, 759)... |
from typing import Dict
import pymongo
class GlobalMetadataStore(object):
def __init__(self, connection_string: str, db: str):
self.client = pymongo.MongoClient(connection_string)
self.db = self.client[db]
self.workers_collection = self.db["workers"]
def get_all(self, worker_id: str)... |
"""Riemann Theta Tests
References
----------
.. [CRTF] B. Deconinck, M. Heil, A. Bobenko, M. van Hoeij and M. Schmies,
Computing Riemann Theta Functions, Mathematics of Computation, 73, (2004),
1417-1442.
.. [DLMF] B. Deconinck, Digital Library of Mathematics Functions - Riemann Theta
Functions, http://dlm... |
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV3_Flat_Pbr_01_02MasterChefCan.py"
OUTPUT_DIR = "output/deepim/ycbvPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV3_Flat_ycbvPbr_SO/05_06MustardBottle"
DATASETS = dict(TRAIN=("ycbv_006_mustard_bottle_train_pbr",))
|
from audio_calculations import audio_calculations as ac
#One Channel 24-bit Wave File
def test_One_24():
a = ac('testfiles/SineWave.wav')
info = a.select_file()
assert 48000 == info[1]
assert 1 == info[2]
assert -9.1 == round(info[3],1)
assert -6.0 == round(info[4],1)
#One Channel 16-bi... |
# Copyright 2020 The TensorFlow 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 applica... |
import boto3
import json
import apiGatewayLogger as logger
def main():
#* load boto client
client = boto3.client('apigateway')
#* set logger
logger.setLogger('authorizer_enable_apiGateway_cognito.log')
#* get api key with default to prod
api_id = GetAPIId()
#* get a dict of resources for the API {resou... |
#-------------------------------------------------------------
#
# 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... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, caffe2_xavier_init
from ..builder import NECKS
from .decode_head import BaseDecodeHead
class PPM(nn.ModuleList):
"""Pooling Pyramid Module used in PSPNet.
Args:
pool_... |
import os
import sys
# All supported rounding modes
round_nearest = intern('n')
round_floor = intern('f')
round_ceiling = intern('c')
round_up = intern('u')
round_down = intern('d')
round_fast = round_down
def prec_to_dps(n):
"""Return number of accurate decimals that can be represented
with a precision of n... |
# -*- coding: utf-8 -*-
import numpy as np
from .datatuple import DataTuple
__all__ = [
'floatX', 'split_dataframe_to_arrays', 'split_numpy_array', 'slice_length',
'merge_slices', 'merge_slice_indices', 'merge_slice_masks',
'minibatch_indices_iterator', 'adaptive_density',
]
def floatX(array):
"""En... |
from cmd import Cmd
import typing as ty
from argparse_shell.namespace import Namespace
class InteractiveCmd(Cmd):
"""Subclass of the base :py:class:`cmd.Cmd`.
This class wraps a :py:class:`~argparse_shell.namespace.Namespace` and makes its commands available in an
interactive shell.
"""
_CMD_IM... |
import importlib
from pathlib import Path
from app import app
CURRENT_MODULE = __name__
for path in Path(__file__).parent.glob('./*.py'):
if path.stem == '__init__':
continue
module = importlib.import_module(f'.{path.stem}', CURRENT_MODULE)
if hasattr(app, 'router'):
app.include_router(m... |
"""
This module contains description of function and class
for normal (Gauss) distribution.
References
----------
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html
"""
from typing import Tuple
from scipy.stats import norm
from method_of_moments.continuous._base_continuous import BaseConti... |
"""
Copyright (c) 2019, Matt Pewsey
"""
import scipy.optimize
__all__ = ['fsolve']
def fsolve(*args, **kwargs):
"""
Finds the roots of a function. If the function fails to find a solution,
an exception is raised. See :func:`scipy.optimize.fsolve` for list of
parameters.
"""
kwargs['full_outp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.