text stringlengths 2 999k |
|---|
"""Base classes for channels."""
from __future__ import annotations
import asyncio
from enum import Enum
from functools import partialmethod, wraps
import logging
from typing import Any
import zigpy.exceptions
from zigpy.zcl.foundation import Status
from homeassistant.const import ATTR_COMMAND
from homeassistant.cor... |
from karon.sample import Sample
def test_sample():
package = dict(foo='bar')
default = Sample()
populated = Sample(**package)
readable = Sample(**package, readable=True, writeable=False)
writeable = Sample(**package, readable=False, writeable=True)
immutable = Sample(**{**package,
... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import unittest
from databuilder.models.watermark import Watermark
from databuilder.models.neo4j_csv_serde import NODE_KEY, \
NODE_LABEL, RELATION_START_KEY, RELATION_START_LABEL, RELATION_END_KEY, \
RELATION_END_LABEL, RE... |
from flask_restful import Resource, abort
from flask import make_response, request
import config
from model import config_builder as cb
class CountGeneratedConfigs(Resource):
@staticmethod
def post():
try:
if request.json['strategy_type'] == "assembler_strategies":
conf_li... |
import os
import sys
dir = '/Users/wangjinchao/Desktop/ste/ll'
delpath = '/Users/wangjinchao/Desktop/ste/rr'
# for path in paths:
# if current_file in os.listdir(path) :
print('=='*12)
ll = os.listdir(dir)
dd = os.listdir(delpath)
result = []
for i in range(len(dd)):
if dd[i] not in ll:
print(dd[i])
... |
# TODO
# - Array conversion improvements:
# - return custom iterable object instead of Blob when converting to array
# - check array dim on conversion
# - On print extensions, print the reflected internal representation of the object (worth the extra ROM?)
# - Verify that when mp_obj is given it is indeed the righ... |
# -*- coding:utf-8 -*-
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# ... |
from torch.optim import Adam
from torch.utils.data import DataLoader
from dataset.sentiment_dataset_v2 import CLSDataset
from models.bert_sentiment_analysis_v2 import *
from sklearn import metrics
from metrics import *
import tqdm
import pandas as pd
import numpy as np
import configparser
import os
import json
clas... |
# Copyright 2018 New Vector Ltd
#
# 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 writin... |
import asyncio
from typing import List
from .crawler import Crawler
from .scraper import Scraper
async def crawl(scrapers: List[Scraper]):
crawler = Crawler(seeds=scrapers)
loop = asyncio.get_event_loop()
loop.run_until_complete(crawler.run())
loop.stop()
loop.run_forever()
loop.close()
... |
import argparse
import os
import sys
import torch
import json
from datetime import datetime
import numpy as np
cwd = os.getcwd()
current_time = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
class Bunch(object):
def __init__(self, adict):
self.__dict__.update(adict)
def check_file(filename,folder):
... |
# 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.mappin... |
class Solution:
def longestPalindrome(self, s: str) -> str:
p = []
for k in range(len(s)):
p.append([False] * len(s))
# 先初始化长度为 0 时的结果
for k in range(1, len(s)):
p[k][k - 1] = True
for k in range(len(s)):
# 最多只有 len (s) 次遍历,第 k 次遍历长度为 k + 1... |
import unittest
from unittest.mock import (
patch,
)
from minos.aggregate import (
DatabaseTransactionRepository,
TransactionRepository,
TransactionStatus,
)
from minos.aggregate.testing import (
TransactionRepositoryTestCase,
)
from minos.common import (
DatabaseClient,
ProgrammingExceptio... |
from discord import Embed
from discord.ext import commands
import re
import sqlite3
print("urlの読み込み完了")
regex_discord_message_url = (
'https://(ptb.|canary.)?discord(app)?.com/channels/'
'(?P<guild>[0-9]{18})/(?P<channel>[0-9]{18})/(?P<message>[0-9]{18})'
)
class url(commands.Cog):
def __init__(self, bo... |
from gemd.entity.object.process_spec import ProcessSpec
from gemd.entity.object.base_object import BaseObject
from gemd.entity.object.has_spec import HasSpec
from gemd.entity.object.has_conditions import HasConditions
from gemd.entity.object.has_parameters import HasParameters
from gemd.entity.object.has_source import ... |
# Copyright 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 ... |
"""
THIS IS A TEMPLATE FOR AN OFFLINE EXPERIMENT.
PARTS IN ALL CAPS ARE NOTES ON THE TEMPLATE, AND NEED UPDATING TO RUN.
Classes & Functions to run the .... experiment.
Notes:
- Here, set up to use LSL for sending event markers. This can be changed.
- The default set up is to use LSL for sending event markers. This c... |
"""PyMC3-specific conversion code."""
import logging
import warnings
from typing import Dict, List, Any, Optional, Iterable, Union, TYPE_CHECKING
from types import ModuleType
import numpy as np
import xarray as xr
from .. import utils
from .inference_data import InferenceData, concat
from .base import requires, dict_t... |
import tensorflow as tf
def fisher(data, num_instances: list, top_k_features=2):
"""
Performs Fisher feature selection method according to the following formula:
D(f) = (m1(f) - m2(f) / (std1(f) - std2(f))
:param data:
:param num_instances:
:param top_k_features:
:return: the list of most... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test new Nexalt multisig prefix functionality.
#
from test_framework.test_framework import BitcoinTe... |
"""
Basic functions on surface meshes.
"""
# Author: Oualid Benkarim <oualid.benkarim@mcgill.ca>
# License: BSD 3 clause
import warnings
import numpy as np
from vtk import (vtkDataObject, vtkThreshold, vtkGeometryFilter,
vtkAppendPolyData)
from .array_operations import get_connected_components
fro... |
import os
SETTINGS_MODULE = "config.settings.local"
if os.environ.get("ENVIRONMENT") == "dev":
SETTINGS_MODULE = "config.settings.dev"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import argparse
import numpy as np
import shlex
import subprocess
import sys
import wave
import ffmpeg
import json
import os
from pathlib import Path
from deepspeech import Model, version
from timeit import ... |
from importlib.machinery import SourceFileLoader
tweet = SourceFileLoader("tweet", "./lib/tweet.py").load_module()
def handler(event, context):
crc_token = event["queryStringParameters"]["crc_token"]
return tweet.generate_crc_response(crc_token)
|
import os
ref_dir = os.path.join(os.path.dirname(__file__))
__all__ = sorted(f[:-3] for f in os.listdir(ref_dir) if f.endswith('.py') and
not f.startswith('__'))
for f in __all__:
__import__(__name__ + '.' + f)
del f, ref_dir
__doc__ = """\
Topical documentation
=====================
... |
"""
Locate origin nodes
Inputs:
originNode: (point3d) position of origin node in form diagram
originNodeID: (integer) index of corresponding node
Outputs:
N: (origin-nodes) The assigned origin nodes
Remarks:
This generates a new instance of origin nodes
"""
import Rhino
... |
#
# Copyright 2016 Quantopian, 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 agreed to in wr... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'lexicon_game porject',
'author': 'Miaojun Zhang',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'mzhang56@horizon.csueastbay.edu',
've... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
import os
import sys
import time
import argparse
import numpy as np
sys.path.append("../../decode_rf_data")
import matplotlib.pyplot as plt
from colormap import spectral
import rf_data as rf
parser = argparse.ArgumentParser(
description="""
Will plot waterfall plots
"""
)
parser.add_argument(
... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys
class Binutils(AutotoolsPackage, GNUMirrorPackage):
"""GNU binutils, which contain the linker, assembler,... |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
parent_name="layout.ternary.aaxis.title.font",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotl... |
"""Visualize individual feature channels and their combinations to explore the space of patterns learned by the neural network
Based on http://nbviewer.jupyter.org/github/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
"""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
#... |
import pytest
from bs4 import BeautifulSoup
from django.core.mail import EmailMessage
from django.urls import reverse
from django.utils.dateparse import parse_datetime
from django.utils.timezone import datetime
from post_office.models import Email
from shop.models.cart import CartItemModel
from shop.models.order import... |
import os
import pytest
import json
import random
import django_rq
from datetime import datetime, timezone, timedelta
from mock import Mock, patch
from coordinator.api.models import Release, TaskService, Study, Task
from rest_framework.test import APIClient
from unittest import mock
import jwt
BASE_URL = "http://test... |
class tumblr():
scheme = 'https'
url = 'tumblr.com'
# use a text browser to avoid annoying/blocking javascript
headers = {'user-agent': 'Lynx/2.8.9dev.16 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.5.17'}
def getHandleUrl(self, handle):
return "{}://{}.{}".format(tumblr.scheme, handle, tumblr.url... |
#!/usr/bin/env python3
# Copyright (c) 2016-2018 The Readercoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Create a blockchain cache.
Creating a cache of the blockchain speeds up test execution when running... |
#!/usr/bin/env python3
import torch
import operator
from .lazy_tensor import LazyTensor
from .non_lazy_tensor import lazify
from ..utils.broadcasting import _matmul_broadcast_shape
from ..utils.memoize import cached
from functools import reduce
def _prod(iterable):
return reduce(operator.mul, iterable, 1)
def ... |
from functools import wraps
from django.http import HttpResponseRedirect
from .utils import get_dropbox_auth_flow
from .views import DROPBOX_ACCESS_TOKEN
def require_dropbox_session(next_url=None):
"""
Any view that is wrapped with this will redirect to the dropbox authorization site if the user does not
... |
print('ohter')
|
# Copyright 2015 Rackspace Inc.
#
# Author: Tim Simmons <tim.simmons@rackspace.com>
#
# 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
#
# Unl... |
# -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import torch
from ...wrapper import TargetWrapper, Batch
from ...utils import ChunksTagsTranslator
from ...nn.utils import unpad_seqs
from ...nn.modules import CombinedDropout, CRF
from ...nn.init import reinit_layer_
from ...metrics impor... |
# To use a consistent encoding
from __future__ import print_function
from codecs import open
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
setup(
name='shutit',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the p... |
#!/usr/bin/env python
import sys
import argparse
import glob
import os.path
import os
import logging
def parse_args(argv):
parser = argparse.ArgumentParser(description="Summarize inferred FIRE motifs.")
parser.add_argument('-i', '--dir_input', dest='dir_input', type=str)
parser.add_argument('-o', '--fn_o... |
from .targets.target import FilePath
from typing import Optional
from asyncio.subprocess import create_subprocess_shell, PIPE
from subprocess import CalledProcessError
from .utils import unindent
from .logger import logger, YELLOW, RESET
import inspect
async def sh(
script: str,
cwd: FilePath = '.',
silen... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import pyautogui
import time
from selenium.webdriver.common.keys import Keys
def signin(path,confidence=0.9):
... |
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
cluster = ClickHouseCluster(__file__)
instance = cluster.add_instance('instance')
def system_settings_profile(profile_name):
return TSV(instance.query(
"SELECT name, storage, num_elements, apply_to_all, apply_t... |
import requests
from requests.auth import HTTPBasicAuth
import keys
def generate_access_token():
consumer_key =keys.consumer_key
consumer_secret = keys.consumer_secret
api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
r = requests.get(api_URL, auth=HTTPBas... |
###############################################################################
#
# Test cases for xlsxwriter.lua.
#
# Copyright 2014-2015, John McNamara, jmcnamara@cpan.org
#
import base_test_class
class TestCompareXLSXFiles(base_test_class.XLSXBaseTest):
"""
Test file created with xlsxwriter.lua against a f... |
import multiprocessing
multiprocessing.set_start_method("spawn", True)
import os
import sys
import time
from collections import deque
import numpy as np
import torch
import torch.nn as nn
import wandb
from a2c_ppo_acktr import algo, utils
from a2c_ppo_acktr.model import NNBase, Policy
from a2c_ppo_acktr.storage impo... |
"""This file implements a threaded stream controller to return logs back from
the ray clientserver.
"""
import sys
import logging
import queue
import threading
import grpc
import ray.core.generated.ray_client_pb2 as ray_client_pb2
import ray.core.generated.ray_client_pb2_grpc as ray_client_pb2_grpc
logger = logging.g... |
import os
import torch
import torch.utils.data
import numpy as np
import skimage.io
import skimage.transform
MNIST_CLASSES = (
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
)
class MNISTMetaData():
def __init__(self):
self.cls = MNIST_CLASSES
def get_num_clas... |
import warnings
warnings.simplefilter('ignore')
from pygments.lexers import LEXERS, get_lexer_by_name
warnings.resetwarnings()
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pprint import pprint
import re
from django.utils.encoding import smart_unicode
class ListHtmlFormatter(HtmlFor... |
import os
from contextlib import contextmanager
@contextmanager
def working_directory(path):
"""
Temporarily change the current working directory.
Usage:
with working_directory(path):
do_things() # working in the given path
do_other_things() # back to original path
"""
current_di... |
# Copyright 2019 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
"""Configure nox as the task runner, including CI and pre-commit hooks.
Generic maintainance tasks:
- "init-project": set up the pre-commit hooks
- "clean-pwd": ~ `git clean -X` with minor exceptions
For local development, use the "format", "lint", and "test" sessions
as unified tasks to assure the quality of the ... |
#
# Copyright (c) 2022 by Kristoffer Paulsson <kristoffer.paulsson@talenten.se>.
#
# 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 SOFTWARE IS P... |
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.1.15.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# -*- coding:utf-8 -*-
# Copyright 2019 Huawei Technologies Co.,Ltd.
#
# 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... |
# Juntador
"""
frase = 'Curso em Vídeo Python'
dividido = frase.split()
print(''.join(frase))
"""
# Divisor split
"""
frase = 'Curso em Vídeo Python'
dividido = frase.split()
print(dividido[2][3])
-------------------------------
frase = 'Curso em Vídeo Python'
dividido = frase.split()
print(dividido[0])
---------------... |
#
# The Python Imaging Library
# $Id$
#
# WCK-style drawing interface operations
#
# History:
# 2003-12-07 fl created
# 2005-05-15 fl updated; added to PIL as ImageDraw2
# 2005-05-15 fl added text support
# 2005-05-20 fl added arc/chord/pieslice support
#
# Copyright (c) 2003-2005 by Secret Labs AB
# Copyright ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import FinanceDataReader as fdr
from pykrx import stock
import datetime
import requests
# from datetime import timedelta # 마이크로초 전, 마이크로초 후 를 구하고 싶다면 timedelta
from dateutil.relativedelta import relativedelta # 몇달 전, 몇달 후, 몇년 전, 몇년 후 를 구하고 싶다면 relat... |
"""
Example PSS Receive workflow
"""
# pylint: disable=invalid-name
import logging
import ska_ser_logging
from ska_sdp_workflow import workflow
# Initialise logging
ska_ser_logging.configure_logging()
log = logging.getLogger("pss_receive")
log.setLevel(logging.INFO)
# Claim Processing block
pb = workflow.Processing... |
"""
SimRank similarity measure.
"""
#!/usr/bin/env python
# Copyright (C) 2015 by
# Xiaming Chen <chen_xm@sjtu.edu.cn>
# All rights reserved.
# BSD license.
import itertools
import numpy as np
import networkx as nx
from typedecorator import params, returns
__author__ = "Xiaming Chen"
__email__ = "chen_xm@sjtu.edu.cn"... |
# -*- coding:utf-8 -*-
# author: chenliang @ Youtu Lab, Tencent
from visionseed import YtVisionSeed, YtDataLink
import serial
import matplotlib
import matplotlib.pyplot as plt
vs = YtVisionSeed( serial.Serial("/dev/ttyACM0",115200,timeout=0.5) )
class Chart:
def __init__(self, maxlen=100, title='', xlabel='frame... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import struct
def read():
try:
return sys.stdin.buffer.read()
except AttributeError:
return sys.stdin.read()
def write(out):
try:
sys.stdout.buffer.write(out)
except AttributeError:
sys.stdout.wri... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from ... import settings
# Module API
class MessageController(object):
"""Say message from settings.
"""
# Public
def __call_... |
#rudimentary MuJoCo mjcf to ROS URDF converter using the UrdfEditor
import pybullet_utils.bullet_client as bc
import pybullet_data as pd
import pybullet_utils.urdfEditor as ed
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--mjcf', help='M... |
"""
Having a registry of all available classes is convenient for retrieving an instance
based on a configuration at run-time.
"""
import logging
from collections import OrderedDict
from plato.config import Config
if hasattr(Config().trainer, 'use_mindspore'):
from plato.datasources.mindspore import (
mni... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('pacientes', '0004_auto_20150425_1459'),
]
operations = [
migrations.AlterField(
model_name='paci... |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from .bbx import invert_roi_bbx
from .misc import Empty
from .roi_sampling import roi_sampling
class PanopticPreprocessing:
def __init__(self,
score_threshold=0.5,
overlap_threshold=0.5,
min_stuff_... |
import os
import sys
from optparse import OptionParser
import datetime
from testutils.TestUtilsL23 import XenaScriptTools
class ScriptLoaderApp(object):
"""
Script loader application
"""
def __init__(self):
self.parser = self.buildParser()
(self.options, args) = self.parser.parse_ar... |
from copy import deepcopy
from max_priority_queue import MaxPriorityQueue
from typing import List
import time
from puzzle import Puzzle
from move import Move
class PuzzleSolver:
def __init__(self, puzzle: Puzzle):
self.puzzle = puzzle
self.queue = MaxPriorityQueue()
def enqueue(self, puzzl... |
from __future__ import absolute_import
import os
from .otb import ExperimentOTB
from ..datasets import NfS
class ExperimentNfS(ExperimentOTB):
"""Experiment pipeline and evaluation toolkit for NfS dataset.
Args:
root_dir (string): Root directory of NfS dataset.
result_dir (string, optio... |
#!/usr/bin/env python3
#
# Copyright (c) 2018 Roberto Riggio
#
# 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 applicabl... |
# Copyright (c) 2018, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
import pytest
import os
from uuid import uuid4
from datetime import date, time, datetime
import pygshe... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
class UResNet(torch.nn.Module):
def __init__(self, flags):
import sparseconvnet as scn
super(UResNet, self).__init__()
self._flags = flags
dimension = flags.DAT... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# stdlib imports
import json
import copy
import logging
from datetime import datetime
import getpass
import re
import inspect
# third party imports
import numpy as np
from obspy.core.trace import Trace
import prov
import prov.model
from obspy.core.utcdatetime import UTCDa... |
'''
Search code for Annokey.
Find matches of key terms within selected fields of
the NCBI gene database and Pubmed articles.
'''
import sys
import csv
from Bio import Entrez
import logging
from .process_xml import GeneParser
from .genecache import lookup_gene_cache_iter
from .report import report_hits
from .name impo... |
import json
import time
import jsondiff
from boto3 import Session
from moto.core import BaseBackend, BaseModel
from moto.core.utils import merge_dicts
from moto.iot import iot_backends
from .exceptions import (
ConflictException,
ResourceNotFoundException,
InvalidRequestException,
)
class FakeShadow(Base... |
from copy import deepcopy
import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.models import NaiveModel
from etna.transforms.missing_values import TimeSeriesImputerTransform
from etna.transforms.missing_values.imputation import _OneSegmentTimeSeriesImputerTransform
@pyt... |
# Backup all volumes all regions
# Skip those volumes with tag of Backup=No
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Get list of regions
regions = ec2.describe_regions().get('Regions',[] )
# Iterate over regions
for region in regions:
print "Checki... |
"""TODO"""
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
from hypothesis import given, example
from hypothesis.strategies import binary, integers
from mitmproxy.net.tls import ClientHello
from mitmproxy.proxy2.layers.tls import parse_client_hello
client_hello_with_extensions = bytes.fromhex(
"16030300bb" # record layer
"010000b7" # handshake layer
"0... |
# Copyright 2012 OpenStack Foundation
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 - 2012 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
#... |
from setuptools import setup
url = ""
version = "0.1.0"
readme = open('README.md').read()
# Note: psutil is needed for demo purposes only.
setup(
name="test_proxy_client",
packages=["test_proxy_client"],
version=version,
description="Tools for drawing 2d and 3d interactive visualizations using Jupyt... |
# -*- coding: utf-8 -*-
# Copyright 2016-2018 Ildar Nasyrov <https://it-projects.info/team/iledarn>
# Copyright 2017 Dinar Gabbasov <https://it-projects.info/team/GabbasovDinar>
# Copyright 2016-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
# License MIT (https://opensource.org/licenses/MIT).
import b... |
from flask import request
from src.atm_session.atm_session import ATMSession
ATM_SESSION_HEADER = 'X-Api-ATM-Key'
def session_required(f):
def wrapped_function(*args, **kwargs):
if ATM_SESSION_HEADER not in request.headers:
return 'Unauthorized', 401
session_key = request.headers[AT... |
"""
This file defines class DecisionModule.
@author: Clemens Rosenbaum :: cgbr@cs.umass.edu
@created: 6/7/18
"""
import abc
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.distribution import Distribution
from .PolicyStorage import ApproxPolicyStorage, TabularP... |
import logging
# Logging configuration
log = logging.getLogger(__name__) # noqa
log.addHandler(logging.NullHandler()) # noqa
from netmiko.ssh_dispatcher import ConnectHandler
from netmiko.ssh_dispatcher import ssh_dispatcher
from netmiko.ssh_dispatcher import redispatch
from netmiko.ssh_dispatcher import platforms
... |
import requests
from bs4 import BeautifulSoup
import os
import telegram
bot = telegram.Bot(os.environ['TELEGRAM_API_TOKEN'])
chat_id = bot.getUpdates()[-1].message.chat.id
# 파일의 위치
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 학사공지 게시판 크롤링
req = requests.get('http://builder.hufs.ac.kr/user/indexSub.action... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... |
#!/usr/bin/env python
# coding=utf-8
"""
This experiment showcases the concept of commands in Sacred.
By just using the ``@ex.command`` decorator we can add additional commands to
the command-line interface of the experiment::
$ ./05_my_commands.py greet
INFO - my_commands - Running command 'greet'
WARNING - my_... |
"""An example file showing how to make a geometry.
This particular example creates a 3x3 geometry, with 8 regular pins and one
Gd-157 2 wt-percent enriched. All pins are segmented.
"""
from collections import OrderedDict
import math
import numpy as np
import openmc
def density_to_mat(dens_dict):
"""Generates ... |
# This example is used to write structures to images in an automated manner.
# It is a very specific script! Not intended for general use.
import urllib
from time import sleep
from pathlib import Path
import dash
from dash import html
from dash import dcc
from dash.dependencies import Input, Output, State
from pymatge... |
"""Evaluates a model against examples from a .npy file as specified
in config.json"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import json
import math
import os
import sys
import time
import tensorflow as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.