text stringlengths 2 999k |
|---|
import socket
import ssl
import pytest
pytest.importorskip('trio')
from yarl import URL # noqa
from python_socks import (
ProxyType,
ProxyError,
ProxyTimeoutError,
ProxyConnectionError
)
from python_socks._proxy_async import AsyncProxy # noqa
from python_socks.async_.trio import Proxy
from python_s... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 10
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_9_0_0.models.provid... |
# -*- coding: utf-8 -*-
# @Author: MR_Radish
# @Date: 2018-07-25 15:54:44
# @E-mail: ty_2016@foxmail.com
# @FileName: masking.py
# @TODO: 按照指定图形覆盖图片
import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "---image", required=True, help="Path to the image")
args ... |
import torch
import os
import random
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms
import torchvision.transforms.functional as FN
from torchvision.datasets import ImageFolder, MNIST
from PIL import Image
import json
import numpy as np
import random
from ... |
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 7) or TYPE_CHECKING:
from ._zsrc import ZsrcValidator
from ._zmin import ZminValidator
from ._zmid import ZmidValidator
from ._zmax import ZmaxValidator
from ._zauto import ZautoValidator
from ._z import ZValidator
from .... |
import os
from twisted.trial import unittest
from scrapy.utils.iterators import csviter, xmliter, _body_or_str, xmliter_lxml
from scrapy.http import XmlResponse, TextResponse, Response
from tests import get_testdata
class XmliterTestCase(unittest.TestCase):
xmliter = staticmethod(xmliter)
def test_xmliter... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Gopi and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestValiant(unittest.TestCase):
pass
|
""" An adapter model that inverts all of its row/column targets. Use
this class with the CompositeGridModel to make models with different
orientations match, or use it to visually flip the data without modifying
the underlying model's sense of row and column. """
# Enthought library imports
from traits.api import Inst... |
# Copyright 2014 Rackspace Hosting
# 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 require... |
from pynput import keyboard, mouse
import datetime, sys, time, os
import logging, logging.config
# Check if log file is not too big
try:
size = int(os.stat("./logs.log").st_size)
# If file is larger than 10 MiB remove it
if size > 10*1024*1024:
os.remove("./logs.log")
except:
pass
from Screen... |
"""add project owner
Revision ID: 467fc59e6a76
Revises: 252ce5626f65
Create Date: 2021-04-09 11:03:30.072623
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '467fc59e6a76'
down_revision = '252ce5626f65'
branch_labels = None
depends_on = None
def upgrade():
... |
from ..decorators import closure, delete_op, get_op
from ..error import BadRequest
from ..state.generic import Map, Tuple
from ..state.number import Bool, UInt
from ..state.ref import If, Ref
from ..state import State, Stream
from ..util import form_of, to_json, uri, URI
from .base import Collection
from .bound import... |
#!/usr/bin/env python
# Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
from . import settings, utils
class Config(object):
"""
The global config wrapper that handles the backend.
"""
def __init__(self):
super(Config, self).__setattr__('_backend',
utils.import_module_attr(settings.BACKEND)())
def __getattr__(self, key):
try:
de... |
# Write your remainder function here:
def remainder(num1, num2):
num1 *= 2
num2 /= 2
return num1 % num2
# Uncomment these function calls to test your remainder function:
print(remainder(15, 14))
# should print 2
print(remainder(9, 6))
# should print 0 |
# Copyright 2016-2020, Pulumi 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 t... |
for i in range(5):
if i == 3:
continue # skip the rest of the code inside loop for current i value
print(i)
for x in range(10):
if Check if x is even:
continue # skip print(x) for this loop
print(x)
|
#!/usr/bin/python
from __future__ import division
from functools import lru_cache
from persistent_lru_cache import persistent_lru_cache
import timeit
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
@persistent_lru_cache(filename='fib.db', maxsize=None)
def pfib(n):... |
# qubit number=2
# total number=6
import cirq
import qiskit
from qiskit import IBMQ
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as... |
"""
ASGI config for disney project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTIN... |
from django.apps import apps
from rest_flex_fields import FlexFieldsModelSerializer
from rest_framework import serializers
from ..fields import MoneyField, TaxedMoneyField, MeasurementField
from .account.address import AddressSerializer
from .order_line import OrderLineSerializer
from .order_extension import OrderExte... |
#!/usr/bin/env python3
import subprocess
import argparse
import glob
import os
import pickle
# NOTE: MUST BE RUN FROM ROOT FOLDER
# Also, for this to work properly for now, DB names can't have underscores
# Attack video naming scheme: NameInDB_kindofattack.*
def main():
python_folder = os.path.abspath(os.path.dir... |
import unittest
import os
import shutil
from utils import file_utils
from enums.file_enums import FileFormat
from errors.custom_exceptions import FileCreationError, InputDataError
from constants.feed_constants import SANDBOX_CHUNK_SIZE
class TestFileUtils(unittest.TestCase):
def test_append_response_to_file(self)... |
from .application import ApplicationCore
from .experiment import ExperimentCore
from .instance_solution import InstanceSolutionCore
from .instance import InstanceCore
from .solution import SolutionCore
|
#
# Copyright (C) 2013 Andrian Nord. See Copyright Notice in main.py
#
import ljd.ast.nodes as nodes
import ljd.bytecode.instructions as ins
import ljd.config.version_config
from ljd.bytecode.constants import T_FALSE, T_NIL, T_TRUE
from ljd.bytecode.helpers import get_jump_destination
class _State:
def __init__(... |
class travelerApi():
"""
The class for a travelers bot.\n
Correct usage is (accountToken, captchaToken).\n
I recommend doing openBrowser = true also while testing the bot so you can see what is going on.
"""
def __init__(self, token:str, captchaToken:str, openBrowser=False, printInitialize... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('employees', '0008_userdata_is_billable'),
]
operations = [
migrations.AlterField(
model_name='userdata',
... |
# Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
#
# 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... |
#!/usr/bin/env python3
import pyrogue as pr
import rogue.protocols
import surf.axi
import axipcie
import surf.protocols.clink
import surf.protocols.ssi
import time
import TimeTool
import pyrogue.utilities.fileio
import pyrogue.utilities.prbs
from XilinxKcu1500Pgp2b import *
import numpy as np
class PrbsSummary(pr.Dev... |
from .send import DeliveryMan
from flask import Flask
from flask.json import jsonify
app = Flask(__name__)
rabbitmq_delivery = DeliveryMan()
@app.route('/')
def home():
return jsonify({'statusCode': 200})
@app.route('/matchs/<player_name>')
def start_find_mathcs(player_name: str):
if player_name is None:
... |
""" Camera extractor functions
This module handles extraction of camera timestamps for both Bpod and FPGA.
"""
import logging
from functools import partial
import cv2
import numpy as np
import matplotlib.pyplot as plt
from oneibl.stream import VideoStreamer
import ibllib.dsp.utils as dsp
from ibllib.misc import range... |
# Copyright (c) 2018-2020 by Rocky Bernstein
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is... |
import difflib
import os
import numpy as np
from .core import Array
from ..async import get_sync
def assert_eq(a, b, **kwargs):
if isinstance(a, Array):
adt = a._dtype
a = a.compute(get=get_sync)
else:
adt = getattr(a, 'dtype', None)
if isinstance(b, Array):
bdt = b._dtype
... |
from sklearn2sql_heroku.tests.classification import generic as class_gen
class_gen.test_model("GaussianNB" , "FourClass_100" , "postgresql")
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
import argparse
import collections
import functools
import json
import logging
import os
import sys
import warnings
from typing import (IO, Any, Callable, Dict, List, Text, Tuple,
Union, cast, Mapping... |
import csv
import os
import matplotlib.pyplot as plt
import numpy as np
import glob
# dpi of figure
DPI=500
# number of previous values to calculate average
TREND_ACCURACY=1000
colors = ["#000000", "#0000FF", "#A52A2A", "#7FFF00", "#DC143C", "#006400", "#FF8C00", "#FF1493", "#FFD700", "#808080", "#669900", "#ff66ff"]... |
def test_total_balance(wallet, wallet_stub):
assert wallet.total_balance is not None
def test_total_pending(wallet, wallet_stub):
assert wallet.total_pending is not None
def test_accounts_when_has_accounts(wallet, account, wallet_stub):
accounts = wallet.accounts
assert len(wallet.accounts) == 1
... |
# Used by pkgs/misc/vim-plugins/update.py and pkgs/applications/editors/kakoune/plugins/update.py
# format:
# $ nix run nixpkgs.python3Packages.black -c black update.py
# type-check:
# $ nix run nixpkgs.python3Packages.mypy -c mypy update.py
# linted:
# $ nix run nixpkgs.python3Packages.flake8 -c flake8 --ignore E501,... |
"""
求最大公约数和最小公倍数
"""
x = int(input("x: "))
y = int(input("y: "))
# 如果x大于y就交换x和y的值
if x > y:
# 通过下面的操作将y的值赋给x, 将x的值赋给y
x, y = y, x
# 从两个数中较的数开始做递减的循环
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print('%d和%d的最大公约数是%d' % (x, y, factor))
print('%d和%d的最小公倍数是%d' % (x, ... |
#coding:utf8
#2019-03
#authors : yqq , junying
import logging
import json
from utils import decimal_default,get_linenumber
from base_handler import BaseHandler
from .proxy import AuthServiceProxy
from constants import OMNI_RPC_URL,OMNI_PROPERTY_ID,OMNI_TRANSACTION_FEE,OMNI_TRANSACTION_RECIPIENT_GAIN
# from utils imp... |
#!/usr/bin/python3.7
# fasta2GTF.py
#
# by Daniel Leite
# 4.12.2019
# ---------- script info ---------- #
desc="""Script to generate a GTF from a fasta file"""
# ---------- import modules ---------- #
import sys,os
from Bio import SeqIO
import argparse
print(sys.version)
# ---------- setup | user options ----------... |
# Genie
from genie.ops.base import Base
# IOSXE Ops
from genie.libs.ops.eigrp.iosxe.eigrp import Eigrp as EigrpXE
class Eigrp(EigrpXE):
'''
Eigrp Ops Object
'''
pass
|
import numpy as np
import lenstronomy.Util.util as util
import lenstronomy.Util.image_util as image_util
from scipy.optimize import minimize
class LensEquationSolver(object):
"""
class to solve for image positions given lens model and source position
"""
def __init__(self, lensModel):
"""
... |
# model settings
# Voxel size for voxel encoder
# Usually voxel size is changed consistently with the point cloud range
# If point cloud range is modified, do remember to change all related
# keys in the config.
voxel_size = [0.32, 0.32, 6]
model = dict(
type='MVXFasterRCNN',
pts_voxel_layer=dict(
max_n... |
# -*- coding: utf-8 -*-
import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.description = "Linear Algebra PACKage."
self.webpage = "https://www.netlib.org/lapack"
self.displayName = "lapack"
self.patchToApply['3.9.0'] = [... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... |
#!/usr/bin/env python2
import models
def initiate_db():
models.db.connect()
models.db.create_tables([models.WebQuery, models.Pokemon, models.Pokestop])
if __name__=="__main__":
initiate_db()
|
from .baseclass import PreambleBaseClass
class Definition(PreambleBaseClass):
def __init__(self, command, replacement, parameter_string=None):
super()
self.command = command
self.parameter_string = parameter_string
self.replacement = replacement
def __repr__(self):
rep... |
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
h = [-x for x in stones]
heapq.heapify(h)
while len(h) >= 2:
a = heapq.heappop(h)
b = heapq.heappop(h)
heapq.heappush(h, a - b)
if len(h) == 0:
return 0
el... |
# Generated by Django 3.1.1 on 2021-02-16 16:27
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('about', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Skill',
fields... |
import numpy as np
from numpy import random as rnd
import matplotlib.pyplot as plt
import torch
from myterial import salmon, light_green_dark, indigo_light
from pyrnn._plot import clean_axes
import torch.utils.data as data
import sys
from rich.progress import track
"""
3 bit memory task
input is a 3xN tens... |
"""Object-oriented interface to an experiment's data."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os
import re
from itertools import chain
from collections import OrderedDict
import ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
#
# This program 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 3 of the License, or
# (at you... |
'''
Input event payload expected to be in the following format:
{
"Batch_start": "MAC000001",
"Batch_end": "MAC000010",
"Data_start": "2013-06-01",
"Data_end": "2014-01-01",
"Forecast_period": 7
}
'''
import boto3, os
import json
import pandas as pd
import numpy as np
from pyathena import connect
REGION = os.envir... |
class Node:
def __init__(self, k, v):
self.key = k
self.val = v
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.dic = dict()
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.h... |
# Copyright 2012 Nebula, 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 agree... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Test the initialize_chain function by setting up a normal chain.
This is just to exercise initialize_chain... |
import os
import numpy as np
import atpy
import pyfits
from hyperion.util.meshgrid import meshgrid_nd
# Set global parameters
R_max = 15.0 # kpc (outer radius)
z_max = 3.0 # kpc (max scaleheight for grid)
R_0 = 8.5 # kpc (solar radius)
h = 3.5 # kpc (scale-length)
R_r = 0.45 * R_0 # (ring radius)
sigma_r = 0.06... |
from django.conf.urls.defaults import *
from . import views
urlpatterns = patterns('',
url(r'^$', views.my_contact, name='satchless-contact-my_contact'),
url(r'^address/new/', views.address_edit, name='satchless-contact-address_new'),
url(r'^address/(?P<address_pk>[0-9]+)/edit/',
vi... |
import requests
from osbot_aws.apis.Lambda import Lambda
from gw_bot.api.API_Slack import API_Slack
from gw_bot.api.gw.API_Glasswall import API_Glasswall
from osbot_aws.helpers.Lambda_Helpers import slack_message
from osbot_utils.utils.Files import Files
class API_GW_Slack_File:
def __init__(self):
self.a... |
import serial, traceback, threading, time, sys, struct, os, array
import zipfile, shelve, random, binascii
import cPickle as pickle
import fakeserial
import itertools
################################################################################
# parsers.py
# A fairly lightweight threaded library for parsing HEG i... |
# This file was generated from metar_parser.peg
# See http://canopy.jcoglan.com/ for documentation.
from collections import defaultdict
import re
class TreeNode(object):
def __init__(self, text, offset, elements):
self.text = text
self.offset = offset
self.elements = elements
def __i... |
# Copyright 2016 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... |
# Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot
from UM.Application import Application
from UM.Scene.Selection import Selection
class SelectionProxy(QObject):
def __init__(self, parent = None):... |
# -*- coding: utf-8 -*-
import os
import os.path
import subprocess
import time
import urllib
import bottle
import ephemeral_port_reserve
import pytest
from bravado_core.content_type import APP_JSON
from bravado_core.content_type import APP_MSGPACK
from msgpack import packb
ROUTE_1_RESPONSE = b'HEY BUDDY'
ROUTE_2_RES... |
import argparse
import tensorflow as tf
import tensorflow_hub as hub
from prediction import main
parser = argparse.ArgumentParser(description='image classifier app')
#parser.add_argument('i',dest='image_path', action="store", type= str,required=True)
#parser.add_argument('m',dest='model_name', action="store",type= st... |
import argparse
import json
import os
import pickle
import sys
import sagemaker_containers
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data
from model import LSTMClassifier
from utils import review_to_words, convert_and_pad
def model_fn(mod... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'AlwaysLog',
'ApiType',
'ApimIdentityType',
'AppType',
'AuthorizationMethod',
'BackendProtoc... |
# Copyright (c) 2014 OpenStack 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 or agreed to ... |
"""
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... |
import logging
import unittest
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import librato
from mock_connection import MockConnect, server
#logging.basicConfig(level=logging.DEBUG)
# Mock the server
librato.HTTPSConnection = MockConnect
class TestLibrato(unittest.TestCase):
... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/booster/shared_bst_kse_bti2.iff"
result.attribute_t... |
""" Flask configuration variables. """
from os import environ, path
from dotenv import load_dotenv
basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, '.env'))
class Config:
""" Set Flask configuration from .env file. """
# General Config
SECRET_KEY = environ.get('SECRET_KEY')... |
"""
ASGI config for ChartApp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault... |
import os
from os import path
from setuptools import setup
from subprocess import check_call
from distutils.command.build import build
from distutils.dir_util import copy_tree, remove_tree
from setuptools.command.develop import develop
def get_submodules_and_fix_paths():
if path.exists('.git'):
# Get HEAD ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAnc... |
import threading
import time
import streamlit as st
class Worker(threading.Thread):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.counter = 0
self.should_stop = threading.Event()
def run(self):
while not self.should_stop.wait(0):
time.sleep... |
#!/usr/bin/env python
# Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>.
# Use of this source code is governed by MIT license that can be
# found in the LICENSE file.
import os
import random
import string
import sys
import tempfile
import warnings
from pyftpdlib._compat import getcwdu
from pyftpdlib._compa... |
from django.urls.base import reverse
from django.utils.translation import gettext_lazy as _
from jet.dashboard import modules
from jet.dashboard.dashboard import DefaultAppIndexDashboard
from jet.dashboard.modules import DashboardModule
from bluebottle.activities.models import Activity
class RecentActivities(Dashboa... |
# Copyright (c) 2021, Omid Erfanmanesh, All rights reserved.
import numpy as np
import pandas as pd
from eda.based import BasedAnalyzer
class BankAnalyzer(BasedAnalyzer):
def __init__(self, dataset, cfg):
super(BankAnalyzer, self).__init__(dataset, cfg)
def age(self):
self.description(col=... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class MultiHeadAttention(nn.Module):
"""
Multi-head attention as per https://arxiv.org/pdf/1706.03762.pdf
Refe... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import os
from PIL import Image
import sys
import torchvision
from datasets import base
from platforms.platform import get_... |
#!/usr/bin/env python3
import picamera
import file_utils
import os
class PiCam:
"""
Uses Raspberry Pi camera.
http://picamera.readthedocs.org/en/release-1.9/api.html
"""
def __init__(self):
self.camera = picamera.PiCamera()
""" PiCamera properties default values
camera.... |
#!/usr/bin/env python
from jip import *
def test_name_function_single_tool():
@tool()
class MyTool(object):
def setup(self):
self.name("Custom-Name")
def get_command(self):
return "true"
pipeline = Pipeline()
pipeline.run('MyTool')
jobs = create_jobs(pipeli... |
from spire.mesh import ModelController
from spire.schema import SchemaDependency
from lattice.server.resources import Profile as ProfileResource
from lattice.server.models import Profile, ProfileComponent
class ProfileController(ModelController):
resource = ProfileResource
version = (1, 0)
model = Profil... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from siem.sf_linux_os_syslog import (
extract_instance_id, extract_from_sshd, extract_from_sudo)
from siem import utils
def transform(logdata):
proc = logdata.get('proc', "")
linux_dict = {}
linux_di... |
import datetime
from vesper.tests.test_case import TestCase
import vesper.old_bird.clip_count_utils as clip_count_utils
_START_TIME = datetime.datetime(2017, 8, 3)
_10 = datetime.timedelta(seconds=10)
_16 = datetime.timedelta(seconds=16)
def _t(seconds):
return _START_TIME + datetime.timedelta(seconds=seconds)... |
"""Pin definitions for the Orange Pi Zero 2."""
from adafruit_blinka.microcontroller.allwinner.h616 import pin
PH5 = pin.PH5
SDA = pin.PH5
PH4 = pin.PH4
SCL = pin.PH4
PC9 = pin.PC9
PH3 = pin.PH3
UART5_RX = pin.PH3
PH2 = pin.PH2
UART5_TX = pin.PH2
PC8 = pin.PC8
PC10 = pin.PC10
PC11 = pin.PC11
PC6 = pin.PC6
PC5 = pin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : Wesley
# @Time : 2020.11.22 17:58
import torch
from torch import nn
class PNet(nn.Module):
def __init__(self):
super(PNet, self).__init__()
self.convolution = nn.Sequential(
# N * 3 * 12 * 12
nn.Conv2d(3, 10, 3... |
#
# This is a local (non-distributed), interative PageRank alorithm used for
# verification of distributed PageRank implemenatations such as in EC.
# Here we are calculating ranking of a N-size sub-graph of the entire web.
# In he code below we will refer to the N-size sub-graph as "the graph".
#
# the graph size
N = ... |
import datetime
import os.path
import googlemaps
from itertools import chain
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the f... |
# 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 ... |
import gym
import numpy as np
from tests.fixtures.envs.dummy import DummyEnv
class LazyFrames(object):
def __init__(self, frames):
"""
LazyFrames class from baselines.
Openai baselines use this class for FrameStack environment
wrapper. It is used for testing garage.envs.wrappers.... |
import unittest
import sys
import os
PROJECT_PATH = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-3])
ROOT_PATH = os.path.dirname(__file__)
def main():
path_setup()
tests = unittest.TestLoader().discover(ROOT_PATH, "*.py")
result = unittest.TextTestRunner().run(tests)
if not result.... |
""" Shape configurations for single operator and subgraph evaluation """
matmul_args = [
[1, 128, 128, 128],
[1, 256, 256, 256],
[1, 512, 512, 512],
[1, 1024, 1024, 1024],
[1, 64, 12544, 147],
[1,65,12544,147],
[1,65,3136,576],
[1,513,49,4608],
[1,2049,49,1024],
[1,129,784,115... |
import time
import os
import subprocess
class Design(object):
def __init__(self):
self.top_name = "design" + time.strftime("%Y-%m-%d", time.localtime())
self.is_Chisel_design = False
self.rtl_input = " "
self.Chisel_input = " "
self.result_dir = "./design/"
... |
# -*- coding: utf-8 -*-
from ogs5py import OGS
model = OGS(
task_root='creep_after_excavation_root',
task_id='creep_after_excavation',
output_dir='out',
)
model.msh.read_file('creep_after_excavation.msh')
model.gli.read_file('creep_after_excavation.gli')
model.pcs.add_block(
main_key='PROCESS',
PCS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of OTC Tool released under MIT license.
# Copyright (C) 2016 T-systems Kurt Garloff, Zsolt Nagy
from otcclient.core.OtcConfig import OtcConfig
from otcclient.core.otcpluginbase import otcpluginbase
from otcclient.utils import utils_output
class Jso... |
#!/bin/env python
import unittest
from unittest.mock import Mock
from ats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError,\
SchemaMissingKeyError
from genie.libs.parser.iosxe.show_authentication_sessions import ShowAuthenticationSession... |
'''Wrapper for Dragonfly_types.h
Generated with:
C:\Users\emd\Documents\_apps_\ctypesgen\ctypesgen.py --includedir="../include" -a -o Dragonfly_types.py C:\Users\emd\Documents\dragonfly\include\Dragonfly_types.h
Do not modify this file.
'''
__docformat__ = 'restructuredtext'
# Begin preamble
import ctypes, os, sy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.