content stringlengths 5 1.05M |
|---|
# coding: utf-8
# IoT 温度計 for MicroPython
# Copyright (c) 2018-2019 Wataru KUNINO
# Error ENOMEM や EADDRINUSE が出た場合はハードウェアリセットを実行してください
# machine.reset()
udp_to = '255.255.255.255' # UDPブロードキャスト
udp_port = 1024 # UDPポート番号
device_s = 'temp._3' ... |
import pytest
import sys
from composer.notes import Duration, NoteValue, Note, TimeSignature, duration_from_note_value, note_value_from_duration
from composer.pitches import KeySignature, Pitch
from composer.scales import ScaleMode
def test_duration_from_note_value():
duration = duration_from_note_value(note_val... |
settings = {
"settings": {
"analysis": {
"filter": {
"ngram_filter": {"type": "ngram", "min_gram": 2, "max_gram": 20}
},
"analyzer": {
"ngram_analyzer": {
"type": "custom",
"tokenizer": "standard",
... |
import os
baseLoc = os.path.dirname(os.path.realpath(__file__))+'/'
from gimpfu import *
import sys
sys.path.extend([baseLoc+'gimpenv/lib/python2.7',baseLoc+'gimpenv/lib/python2.7/site-packages',baseLoc+'gimpenv/lib/python2.7/site-packages/setuptools',baseLoc])
import shutil
import syncWeights
def update(flag) :... |
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Retrieve the list of the current build sheriffs."""
import datetime
import os
import re
class BuildSheriffs(object):
# File that contains the str... |
#!/usr/bin/env python3
#
# Copyright (C) 2017 Clifford Wolf <clifford@symbioticeda.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTW... |
#!/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");... |
from application_form.models.application import (
Applicant,
Application,
ApplicationApartment,
)
from application_form.models.lottery import LotteryEvent, LotteryEventResult
from application_form.models.reservation import (
ApartmentQueueChangeEvent,
ApartmentReservation,
)
__all__ = [
"Applic... |
# -*- coding: utf-8 -*-
"""
The file contains the code used for handling the dataset used to train and test the model.
Dataset - Class for handling the dynamic loading and augmentation of data.
get_datasets - Function to load the training, validation and testing datasets.
"""
# Built-in/Generic Imports
impo... |
from django.db import models
class Entry(models.Model):
time = models.DateTimeField(auto_now_add=True, verbose_name="Measurment time.")
ping = models.FloatField(verbose_name="Ping time (ms).", null=True)
class Meta:
verbose_name = "network status entry"
verbose_name_plural = "network stat... |
#!/usr/bin/env python3
# Processing the JSON files in this folder
# Chris Cheng 2018
import os
import os.path as op
import json
import csv
import re
import datetime
import time
import sys
from optparse import OptionParser, Option
from glob import glob
# FILE PATHS TO BE ESTABLISHED
bids_subject = 'qa'
bids_ds_path ... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from cmsplugin_cascade import __version__
with open('README.md', 'r') as fh:
long_description = fh.read()
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers'... |
class Solution:
def twoSum(s,n,t):r=[x for x in n if t-x in set(n)and t-x!=x]or[t//2,t//2];return [i for i,x in enumerate(n)if x in r]
|
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from simplesqlite.query import And, Where
from ._const import Tc, TrafficDirection
from ._network import is_anywhere_network
from .parser._model import Filter, Qdisc
from .parser.shaping_rule import TcShapingRuleParser
class TcShapingRuleFinde... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-11-02 08:16
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
na... |
#Importing the libraries
import random as r
from tkinter import *
import pandas as pd
#Creating the different Window and setting up its background image
window=Tk()
window.geometry("500x260")
bgimg=PhotoImage(file="Path Of the Image")
bgimg=bgimg.subsample(2,2)
bglab=Label(window,image=bgimg)
bglab.place(x=... |
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51249/Python-different-solutions-(two-pointer-dictionary-binary-search).
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
# two pointers
l, r = 0, len(numbers)-1
while l < r:
s = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""base_component."""
import abc
import datetime
import uuid
from enum import IntEnum
from .base_task import BaseTaskState
class BaseComponentState(IntEnum):
"""BaseComponentState."""
NONE = 0
READY = 1
WORKING = 2
FINISHED = -1
REMOVED = -2
c... |
# Make a new chat bot project
#
# Author: Romary Dupuis <romary@me.com>
#
# Copyright (C) 2017-2018 Romary Dupuis
import traceback
import os
from commis import Command, color
from lifoid.constants import HEADER
from lifoid.views import TemplatesLoader
PROJECT_TEMPLATE_PATH = os.path.join(os.path.dirname(
os.pat... |
# -*- coding: utf-8 -*-
import streamlit as st
import pandas as pd
import tempfile
import shutil
from pathlib import Path
import novel_downloader
from transformers import T5Tokenizer, AutoModelForCausalLM
from transformers import TextDataset,DataCollatorForLanguageModeling
from transformers import Trainer, TrainingArg... |
import collections
from decode_tree import decode_tree
class MutableMapping(collections.abc.MutableMapping):
def __init__(self, *args, **kwargs):
self.__dict = dict(*args, **kwargs)
def __getitem__(self, key):
return self.__dict[key]
def __setitem__(self, key, value):
self.__dict... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Battelle Energy Alliance, LLC. All rights reserved.
###################################################################################################
# Monitor a directory for PCAP files for processing (by publishing their filenames to a ZMQ socke... |
from efm32gg12b.halconfig import halconfig_types as types
from efm32gg12b.halconfig import halconfig_dependency as dep |
from typing import Dict
from botocore.paginate import Paginator
class ListMeshes(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
pass
class ListRoutes(Paginator):
def paginate(self, meshName: str, virtualRouterName: str, PaginationConfig: Dict = None) -> Dict:
pass
c... |
from sys import path
path.insert(1, '../')
import config
import renewableTimer
import spotipy
from spotipy import oauth2
import os
import fnmatch
import json
import time
import webbrowser
from random import randint
TRACKS_TO_SEARCH = config.TRACKS_TO_SEARCH
class SpotipyHandler:
def __init__(self, spotipyObject... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: k8s.io/apimachinery/pkg/api/resource/generated.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflec... |
import re
import sys
import extract
import gutenfetch
def main(nlp):
subjs = 'Western|Science fiction|Geology|Natural|Exploration|Discovery|Physical'
book_ids = [r['gutenberg_id'] for r in \
gutenfetch.search(
lambda x: any([re.search(subjs, t['identifier'], re.I) for t \
... |
"""Allow for Spring and Intro eval relationships
Revision ID: 5615d58892a1
Revises: 6f6b843e2b8f
Create Date: 2017-04-27 15:40:40.640402
"""
# revision identifiers, used by Alembic.
revision = '5615d58892a1'
down_revision = '6f6b843e2b8f'
from alembic import op
import sqlalchemy as sa
def upgrade():
### comma... |
from audiolipsum.exceptions import ExternalLibraryError
from audiolipsum.helpers import lame
from mock import patch
import pytest
class MockResult(object):
stdout = ''
def run_subprocess(cmd, shell, capture_output, text):
assert cmd == 'which lame'
assert shell
assert capture_output
assert text
... |
# with this we can reliably simulate situations where the database is available
# for queries and when it is NOT available for queries. We will mock the
# get_database function in django here
from unittest.mock import patch
# this allows us to call terminal commands from source code
from django.core.management import ... |
#! /usr/bin/env python
import sys
import pybindgen
from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink
def my_module_gen(out_file):
mod = Module('g')
mod.add_include('"g.h"')
mod.add_function('GDoA', None, [])
G = mod.add_cpp_namespace("G")
G.add_function('GDoB', None, [... |
#!/usr/bin/python
import os, urllib2, argparse
class ApacheConfigParser :
CGI_CONFIG_PATTERN = 'ScriptAlias /cgi-bin/'
def __init__(self, filename) :
self.config_file = filename
def get_cgi_dir(self) :
with open(self.config_file) as conf :
for line in conf :
if self.CGI_CONFIG_PATTERN in line :
ret... |
# Generated by Django 1.11.14 on 2018-10-11 00:12
import bitfield.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0196_add_realm_logo_fields'),
]
operations = [
migrations.AlterField(
model_name='realm',
... |
"""Data Base table modles.
See README file for documentation, and more insight on relevant information.
"""
from os import getenv
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, ForeignKey, Float
from sqlalchemy.ext.declarative import declarative_ba... |
# To use, add source /path/to/gdb.py to your $HOME/.gdbinit file.
import atexit
import os
import re
import subprocess
import tempfile
import textwrap as tw
def add_symbol_file(filename, baseaddr):
sections = []
textaddr = '0'
p = subprocess.Popen(["readelf", "-SW", filename], stdout=subprocess.PIPE)
... |
"""Various strategies for othello.
"""
from collections import deque
import random
from othello import OthelloGame
class Evenness:
"""Put disk based on evenness theory."""
def __init__(self):
return
def put_disk(self, othello):
"""Put disk based on evenness theory."""
even_strate... |
"""
Created on Jan 8, 2018
@author: nhan.nguyen
Verify that user can get stored claims by filtering by schema sequence no.
"""
import json
from indy import anoncreds, did, ledger
import pytest
from test_scripts.functional_tests.anoncreds.anoncreds_test_base \
import AnoncredsTestBase
from utilities import utils,... |
from __future__ import division
import numpy as np
class UCB1(object):
"""
The typical bandit upper confidence bounds algorithm.
"""
def __init__(self, c):
self.c = c
def __call__(self, action_node):
if self.c == 0: # assert that no nan values are returned
... |
import json
import tensorflow as tf
from . import models_utils
from .layer_normalization import LayerNormalization
from .transformer import TransformerEncoder
class BertConfig:
"""
Configuration of BertModel
vocab_size: Size of Vocab
hidden_size: Hidden size used in embedding, MHA, pooling layers
... |
import math
import os
import random
import re
import sys
def solve(meal_cost, tip_percent, tax_percent):
tip_amount = (meal_cost * tip_percent) / 100
tax_amount = (meal_cost * tax_percent) / 100
total_cost = int(round(meal_cost + tip_amount + tax_amount))
print(total_cost)
if __name__ == '__main__':
... |
#
# This is part of "python-cluster". A library to group similar items together.
# Copyright (C) 2006 Michel Albert
#
# 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 versi... |
from maintain_frontend import main
from flask import url_for
from flask_testing import TestCase
from unittest.mock import patch, call
from unit_tests.utilities import Utilities
from maintain_frontend.dependencies.session_api.session import Session
from maintain_frontend.models import LocalLandChargeItem
from maintain_f... |
import numpy as np
a = [
# NO DATA
]
f = np.array([[ 0.012339 , -0.02620502, -0.03098542, 0.07781701, -0.0270996 ],
[ 0.00468379, 0.00022547, 0.06944456, -0.0484358 , -0.02109563],
[-0.00247619, 0.0222133 , -0.02510456, 0.02109282, -0.01257638],
[-0.02556051, 0.00968766, -0.010597... |
import io
from contextlib import redirect_stdout
from pyfiguration.cli import cli
def test_cliInspectScript():
# Run the first example
f = io.StringIO()
with redirect_stdout(f):
cli(
args=["inspect", "script", "-s", "./examples/basic/basic.py",]
)
result = f.getvalue()
... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016-2017 Alex Forencich
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... |
# Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
# and Applied Computer Vision Lab, Helmholtz Imaging Platform
#
# 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 L... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10b1 on 2016-07-12 13:24
from __future__ import unicode_literals
import uuid
from django.db import migrations, models
from api.migrations._private.setup_database_initial_scripts import db_setup
class Migration(migrations.Migration):
initial = True
dependenc... |
###
# Copyright (c) 2003-2005, Jeremiah Fincher
# 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,
# this list of co... |
import functools
import time
import os
import logging
from .file_status import FileStatus
def _make_suffix_predicate(suffix):
return functools.partial(str.endswith, suffix=suffix)
class DirectoryChangeIterator(object):
def __init__(self, root, accepted_extensions, exclude_dirs=()):
super(DirectoryCha... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-11-13 10:02:11
# @Author : suke1900 (johnny824lee@gmail.com)
# @Link : http://www.makcyun.top
# @Version : $Id$
"""
遍历 stopwords 生成中文词云图
"""
import os
from os import path
import numpy as np
from wordcloud import WordCloud, STOPWORDS, ImageColorGene... |
<<<<<<< HEAD
#
# Title: add_exclusion_to_fileset.py
#
# Description: This script will take all fileset templates of a given type on a Rubrik system, and update the exclusion
# list to include an array of additional file types.
#
# Author: Stew Parkin (Assured DP), Tim Hynes (Rubrik)
#... |
class Solution:
def XXX(self, digits: List[int]) -> List[int]:
return [int(d) for d in str(int(''.join([str(i) for i in digits]))+1)]
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import unittest
import asyncio
import imagescraper
class ScrapeTest(unittest.TestCase):
"""Check if it can scrape google images"""
def setUp(self) -> None:
"""Set up test"""
async def setup_function():
return imagescraper.GoogleScraper()
self.loop = asyncio.new_event_loop(... |
import csv
import building as bld
# from building import Building, Story, Space
# LECTURE 18 Objectives
# Objectives
# 1. Develop understanding of class inheritance and class composition
# 2. Import and use a custom module (building.py)
# 3. Use super() to call the supertype's __init__() method
# 4. Work with superty... |
#
# PySNMP MIB module Nortel-Magellan-Passport-CallRedirectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-CallRedirectionMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:17:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by use... |
# -*- coding: utf-8 -*-
from datetime import datetime
from pyExcelerator import *
def salary_xls(compact, bureaucrat, params, year, month):
title = Font()
title.name = 'Arial'
title.bold = True
title.height = 600
subtitle = Font()
subtitle.height = 260
subtitle.bold = True
subtitle.i... |
import pytest
from dataclasses import dataclass
from fractions import Fraction
from typing import Union, Any, List, Dict
from marshmallow import ValidationError
from grahamcracker import dataclass_schema, DataSchemaConcrete
from zdevelop.tests.conftest import min_version
from zdevelop.tests.test_schema import (
Ha... |
"""
CARPI DAEMON COMMONS
(C) 2018, Raphael "rGunti" Guntersweiler
Licensed under MIT
"""
from setuptools import setup
with open('README.md', 'r') as f:
long_description = f.read()
setup(name='carpi-daemoncommons',
version='0.2.0',
description='A library providing utilities for writing Python daemons.... |
from distutils.core import setup
import py2exe
import sys
setup(
name = 'Video2Theora',
description = """Video2Theora is a small program thats sole purpose is to
convert any video to the new theora video format for use with firefox 3.1 online
video.""",
url = 'http://www.majorsilence.com... |
from collections import namedtuple
from operator import add
from teagles_advent_2021.day_9.lib import parse_input, Point, valid
CumulativeState = namedtuple('CumulativeState', ['matrix', 'cumulative_flashes', 'last_flashes'])
_ADJACENCIES = [Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1), Point(1, 1), Point(-1,... |
'''
组织列表
'''
#使用sort()对列表进行永久性排序
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
#倒序排序 reverse=True 永久性修改
cars.sort(reverse=True)
print(cars)
print(cars[0].title())
#使用函数sorted()对列表进行临时排序
cars=['bmw','audi','toyota','subaru']
print(cars)
print(sorted(cars))
#又变回来了
print(cars)
#倒着打印列表
cars=['bmw','audi'... |
# This sample tests the special-case handling of the __add__ operator
# when two tuples of known types are added together.
from typing import Literal, Tuple
v1 = () + ()
t1: Literal["tuple[()]"] = reveal_type(v1)
def func1(a: Tuple[int, int, int], b: Tuple[str, str]):
t2: Literal["tuple[int, int, int, str, str... |
from django.shortcuts import render
import json
import urllib.request
# Create your views here.
def index(request):
data={}
if request.method=='POST':
city=request.POST['city']
source=urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=06907b5faf6f34... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from werkzeug import run_simple
from pyamf.remoting.gateway.wsgi import WSGIGateway
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s'
)
def echo(data):
return data
services = {'... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from ray.rllib.agents.a3c.a3c_tf_policy_graph import A3CPolicyGraph
from ray.rllib.agents.impala.vtrace_policy_graph import VTracePolicyGraph
from ray.rllib.agents.agent import Agent, with_common_c... |
from librarian.exceptions import EnvironmentVariableLoadException
import json
import os
def load_env_json(tag):
""" Load a configuration dict from environment variable
Args:
tag (str): Environment variable to load
Returns:
Loaded dict from enc variable
Raises:
ValueError: i... |
from .model import efficientnetv2
|
#Instance Methods
class Stuff(object):
def add(self, x, y):
return x+y
S = Stuff()
print S.add(2, 3)
#classmethod
class Branch(object):
branch = "Electronics and Comm."
@classmethod
def new_branch(cls):
return cls.branch
print Branch.new_branch()
#staticmethod
class Laugh(object)... |
import os
import sys
import yaml
def exec_cmd(cmd):
print cmd
os.system(cmd)
def reset_baremetal(dha_info):
print "reset_baremetal"
hosts_info = yaml.load(open(dha_info))
#print hosts_info
ipmiUserDf = hosts_info.get('ipmiUser', 'root')
ipmiPassDf = hosts_info.get('ipmiPass', 'Huawei@123... |
# unit tests for pd-message.py
import init_domain
import logging
import unittest
import sys
sys.path.append('../src')
import init_domain
from logging.config import fileConfig
logging.config.fileConfig("logging_config.ini")
logger = logging.getLogger(__name__)
logger.info("Hi from test_init_domain.py")
class InitDoma... |
import sys
sys.path.append('/home/jlmarks/dangerzone/scripts/p1')
from turtleRelated import fvh
class particle(object):
"""
The particle class will implement a turtle that has
the ability to determine if it has impacted something
and then react progmatically. It will initially only
... |
import hypothesis.strategies as st
from hypothesis import given
from .typeclass import Type
from haskpy.testing import assert_output
from haskpy.internal import class_function, abstract_function
class Semigroup(Type):
"""Semigroup typeclass
Minimal complete definition:
..
append
For prope... |
import re
import textwrap
import jinja2
from markdown import markdown
from pyvecorg import app
@app.template_filter('markdown')
def convert_markdown(text):
text = textwrap.dedent(text)
result = jinja2.Markup(markdown(text))
return result
@app.template_filter('url')
def normalize_url(url):
return r... |
import sys
sys.path.insert(1,'/home/pi/pi3d') # to use local 'develop' branch version
import pi3d
import numpy as np
import math
import random
RANGE = 100.0
HIT_DIST = 5.0
MODEL_PATH = '{}'
display = pi3d.Display.create(background=(0.0, 0.0, 0.0, 0.0))
camera = pi3d.Camera()
shader = pi3d.Shader('uv_light')
laser_shad... |
# -*- coding: utf-8 -*-
"""
fki_challenge.models
~~~~~~~~~~~~~~~~~~~~
"""
import peewee
class SqliteFKDatabase(peewee.SqliteDatabase):
"""Custom SQLite database for enforcing foreign key constraints."""
def initialize_connection(self, conn):
self.execute_sql('PRAGMA foreign_keys=ON;')
# un-unitia... |
# this allows us to define different paths in our app
from django.urls import path
from user import views
# the name of the app we are creating the url for
app_name = 'user'
# the path function is used to create a new path
# we used create here because we want the path to be
# users/create for create_user
# Also, r... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django import forms
from .models import Order
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions, InlineField
class O... |
"""
PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net)
Copyright (C) 2004-2020 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved,
Brett G. Olivier (bgoli@users.sourceforge.net)
Triple-J Group for Molecular Cell Physiology
Stellenbosch University, South Africa.
Permission to us... |
def unslugify(slug):
return (slug.replace('-', ' ')).capitalize()
|
# -*- encoding: utf-8 -*-
import dsl
from . import FixtureTest
class BuildingAddressPointsMissingMinZooms(FixtureTest):
def test_address_point_gen_has_min_zoom_17(self):
import dsl
z, x, y = (17, 19299, 24630)
self.generate_fixtures(
# https://www.openstreetmap.org/way/2653... |
import arm_unit_test
import arm_functional_test
import arm_sim_test
import arm_upload_test
import hand_functional_test
import manipulator_test
import sim_test
import robot_replay_test
use_sim = True
if __name__ == '__main__':
arm_unit_test.run()
arm_functional_test.run(use_sim=use_sim)
arm_sim_test.run()
... |
import requests, glob, re, os
# taken from here: http://stackoverflow.com/a/13641746
def replace(file, pattern, subst):
# Read contents from file as a single string
file_handle = open(file, 'r')
file_string = file_handle.read()
file_handle.close()
# Use RE package to allow for replacement (also al... |
from skrt.utils import rmap
def square(x):
return x ** 2
def test_list():
list_ = [1, 2, 3, 4, 5]
assert rmap(square, list_, int) == [1, 4, 9, 16, 25]
def test_tuple():
tuple_ = (1, 2, 3, 4, 5)
assert rmap(square, tuple_, int) == (1, 4, 9, 16, 25)
def test_set():
set_ = {1, 2, 3, 4, 5}
... |
# Copyright (c) Regents of the University of Minnesota
# Copyright (c) Michael Gilbert
# Distributed under the terms of the Modified BSD License.
"""Batch spawners
This file contains an abstraction layer for batch job queueing systems, and implements
Jupyterhub spawners for Torque, SLURM, and eventually others.
Comm... |
"""
Calculate d/dp from downloaded pressure level variable and save to files
"""
import sys
sys.path.append('/home/jwalker/dynamics/python/atmos-tools')
sys.path.append('/home/jwalker/dynamics/python/atmos-read')
import numpy as np
import xarray as xray
import pandas as pd
import collections
import atmos as atm
# --... |
from rest_framework.exceptions import APIException
class DynamoNotEnabledError(APIException):
status_code = 400
default_detail = "Dynamo DB is not enabled for this project"
|
import json
from collections import OrderedDict
from pprint import pprint
'''COCO 2017 Dataset '''
TRAIN_FILE_PATH = 'D:\\100_dataset\\coco\\train\\train2017\\'
VALIDATION_FILE_PATH = 'D:\100_dataset\coco\validation\val2017\\'
TEST_FILE_PATH = 'D:\100_dataset\coco\test\test2017\\'
ANNOTATION_FILE_PATH = 'D:\\100_datas... |
import argparse
import dataclasses
import json
import os
import re
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import List, Dict, Callable, Optional, Union, Any
from ActionConditions import ActionConditionData, get_action_condition_data
from Asset_Extract import check_t... |
# This file is Copyright 2021 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import logging
from typing import List, Iterator, Tuple, Generator
from abc import ABC, abstractmethod
from enum import Enum
from v... |
import sys
import numpy as np
# from lib.datasets.lane_dataset import LaneDataset
EXPS_DIR = 'experiments'
class Evaluator(object):
def __init__(self, dataset, exp_dir, poly_degree=3):
self.dataset = dataset
# self.predictions = np.zeros((len(dataset.annotations), dataset.max_lanes, 4 + poly_de... |
from polyphony import testbench
def while06(x):
i = 1
j = 0
while i:
if j == x:
i = 0
j += 1
return j
@testbench
def test():
assert 1 == while06(0)
assert 2 == while06(1)
assert 3 == while06(2)
test()
|
clear_all()
p4_pd.register_reset_all_agtr_time()
p4_pd.register_reset_all_appID_and_Seq()
p4_pd.register_reset_all_bitmap()
p4_pd.register_reset_all_register1()
p4_pd.register_reset_all_register2()
p4_pd.register_reset_all_register3()
p4_pd.register_reset_all_register4()
p4_pd.register_reset_all_register5()
p4_pd.r... |
# Applying Nose-Hoover thermostat to an MCE of ions
# in molten NaCl with periodic boundary conditions
# - Shrohan Mohapatra
# University of Massachusetts, Amherst
# The methodology uses Euler forward integration technique ....
# Here for molten N... |
import dask.array as da
import numpy as np
from dask import is_dask_collection
from dask.array import Array, asarray
from dask.array.routines import _linspace_from_delayed
from dask.core import flatten
from dask.delayed import Delayed, tokenize, unpack_collections
from dask.highlevelgraph import HighLevelGraph
from fas... |
from setuptools import setup, find_packages
with open('requirements.txt') as fp:
install_requires = fp.read()
setup(name='auto-evaluation',
version='0.1',
description='Auto Evalution',
url='https://github.com/LenzDu/auto-evaluation',
author='Lingzhi, Shuwen',
author_email='vrtjso@gmail.com',
packages=fi... |
#CALCULADORABASICA
a = 3
b= 20
suma=a+b
resta=a-b
multi=a*b
divi=a/b
print("LA SUMA ES ", suma)
print("LA RESTA ES ", resta)
print("LA MULTIPLICACION ES ", multi)
print("LA DIVICION ES ", divi) |
# Copyright (c) 2013, Blue Lynx and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns, data = [], []
if filters:
columns = get_column()
data = get_data(filters)
return columns, data
def g... |
import numpy as np
from smac.facade.smac_ac_facade import SMAC4AC
from smac.epm.gaussian_process_mcmc import GaussianProcessMCMC, GaussianProcess
from smac.epm.gp_base_prior import HorseshoePrior, LognormalPrior
from smac.epm.util_funcs import get_types, get_rng
from smac.initial_design.sobol_design import SobolDesign... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.