filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_16567
#!/usr/bin/env python3.6 """ TODO: - docs/source links - how to find the source of a builtin module? - header - note that this is run on a Posix machine - sys.platform ? - footer - include propsed additions to pathlib - P for proposed? """ import collections import functools import inspect import itertool...
the-stack_0_16568
# qubit number=5 # total number=44 import cirq import qiskit from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from ma...
the-stack_0_16570
import torch import torch.nn as nn import torch.nn.functional as F # Based on # https://github.com/tensorflow/models/blob/master/research/struct2depth/model.py#L625-L641 class DepthSmoothnessLoss(nn.Module): r"""Criterion that computes image-aware depth smoothness loss. .. math:: \text{loss} = \lef...
the-stack_0_16571
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 07 13:30:00 2020 @author: Alan J.X. Guo """ import argparse import scipy.io as sio import numpy as np import random import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # os.environ["CUDA_VISIBLE_DEVICES"]="3" import sys sys.path.append('./VC...
the-stack_0_16572
#!/usr/bin/env python from django.conf.urls import patterns, url urlpatterns = patterns( 'pyhn.apps.account.views', url(r'^$', 'index', name='index'), url(r'^login/$', 'login', name='login'), ) urlpatterns += patterns( 'django.contrib.auth.views', url(r'^logout/$', 'logout', {'next_page': '/'}, ...
the-stack_0_16575
from PySide2.QtGui import * from PySide2.QtCore import * from PySide2.QtWidgets import * import sys import stylesheet import yaml from random import shuffle import meal from meal import Meal from functools import partial import logging from imp import reload reload(meal) class Window(QDialog): days = ['Sunday',...
the-stack_0_16576
__author__ = 'bmiller' ''' This is the start of something that behaves like the unittest module from cpython. ''' import re class _AssertRaisesContext(object): """A context manager used to implement TestCase.assertRaises* methods.""" def __init__(self, expected, test_case): self.test_case = test_case ...
the-stack_0_16578
#!/usr/bin/env python """give me some AFOS data please""" from __future__ import print_function import cgi import unittest from pyiem.util import get_dbconn, ssw def pil_logic(s): """Convert the CGI pil value into something we can query Args: s (str): The CGI variable wanted Returns: list o...
the-stack_0_16579
registros = [] def make_album(artista, album, num_musicas=None): dicionario = {"artista": artista, "album": album} if num_musicas: dicionario["num_musicas"] = num_musicas return dicionario def print_album(album): if "num_musicas" in album: print(f'Artista: {album["artista"]}, Album: ...
the-stack_0_16580
# Copyright 2020 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 applicable law or agreed to...
the-stack_0_16581
import time import boto3 import interfaces def _return_default_port_on_redshift_engines(): return 5439 def _return_default_custom_master_username_on_redshift_engines(): return 'awsuser' class Tester(interfaces.TesterInterface): def __init__(self): self.aws_redshift_client = boto3.client('redsh...
the-stack_0_16582
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-10-07 11:08 import functools from typing import Union, List, Dict, Any, Set from hanlp_trie import DictInterface, TrieDict from hanlp.common.dataset import SamplerBuilder from hanlp.components.taggers.transformers.transformer_tagger import TransformerTagger from ha...
the-stack_0_16584
import asyncio import logging import struct from . import package from .constants import MQTTv50, MQTTCommands logger = logging.getLogger(__name__) class BaseMQTTProtocol(asyncio.StreamReaderProtocol): def __init__(self, buffer_size=2**16, loop=None): if not loop: loop = asyncio.get_event_lo...
the-stack_0_16585
try: from kaggle.api.kaggle_api_extended import KaggleApi except Exception as error: try: from kaggle.api.kaggle_api_extended import KaggleApi except ImportError: raise ImportError('Kaggle API not properly set up') pass import datetime import glob import os import sys import pandas ...
the-stack_0_16586
#!/usr/bin/env python # -*- coding: utf-8 -*- # # py_tst documentation build configuration file. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default;...
the-stack_0_16587
import time from logging import LogRecord, getLogger, basicConfig from logging.handlers import BufferingHandler from multiprocessing.pool import ThreadPool from ...backend_api.services import events from ...config import config buffer_capacity = config.get('log.task_log_buffer_capacity', 100) class TaskHandler(Buff...
the-stack_0_16589
""" Various utilities for neural networks. """ import math import torch as th import torch.nn as nn import torch.nn.functional as F class GroupNorm32(nn.GroupNorm): def __init__(self, num_groups, num_channels, swish, eps=1e-5): super().__init__(num_groups=num_groups, num_channels=num_channels, eps=eps) ...
the-stack_0_16590
import sys from threading import RLock from typing import Dict, List, Optional, Tuple from ..constants import MAXIMUM_TXDATA_CACHE_SIZE_MB, MINIMUM_TXDATA_CACHE_SIZE_MB class Node: previous: 'Node' next: 'Node' key: bytes value: bytes def __init__(self, previous: Optional['Node']=None, next: Opti...
the-stack_0_16593
from great_expectations.core.usage_statistics.anonymizers.anonymizer import Anonymizer from great_expectations.core.usage_statistics.anonymizers.store_backend_anonymizer import ( StoreBackendAnonymizer, ) from great_expectations.data_context.store import ( EvaluationParameterStore, ExpectationsStore, Ht...
the-stack_0_16594
import torch import argparse import cv2 import os import numpy as np import torch from PIL import Image from torch.autograd import Function from torchvision import models, transforms # from utils.dataloader import MyDataSet from torch import nn class FeatureExtractor(): """ Class for extracting activations and ...
the-stack_0_16595
from django.conf.urls import include, url from core.tests.api import Api, NoteResource, UserResource from core.tests.resources import SubjectResource api = Api() api.register(NoteResource()) api.register(UserResource()) api.register(SubjectResource()) urlpatterns = [ url(r'^api/', include(api.urls)), ]
the-stack_0_16596
from abc import ( ABC, abstractmethod ) from argparse import ( ArgumentParser, Namespace, _SubParsersAction, ) from enum import ( auto, Enum, ) import logging from multiprocessing import ( Process ) from typing import ( Any, Dict, NamedTuple, ) from lahja.base import Endpoin...
the-stack_0_16598
import collections from datetime import timedelta import functools import gc import json import operator import pickle import re from textwrap import dedent from typing import ( Callable, Dict, FrozenSet, Hashable, List, Optional, Sequence, Set, Union, ) import warnings import weakre...
the-stack_0_16599
# !/usr/bin/env python # -*- coding: UTF-8 -*- # # # ================== # VIZ MARKDOWN - multiple file, markdown format # ================== import os, os.path, sys import json from ..utils import * from ..builder import * # loads and sets up Django from ..viz_factory import VizFactory class SPDXViz(VizFactory): ...
the-stack_0_16600
#!/usr/bin/env python from setuptools import setup def load_requirements(*requirements_paths): """ Load all requirements from the specified requirements files. Returns a list of requirement strings. """ requirements = set() for path in requirements_paths: with open(path) as reqs: ...
the-stack_0_16601
from detectors.mmdetection.mmdet.apis.inference import init_detector, inference_detector from detectors.base_detector import Base_detector from utilities.preprocessing import non_max_suppression from utilities.helper import many_xyxy2xywh import numpy as np from utilities.helper import bboxes_round_int import os impo...
the-stack_0_16604
# -*- coding: utf-8 -*- """ Created on Sun Nov 25 23:05:30 2018 @author: paulo """ # Standard imports import cv2 import numpy as np; # Read image im = cv2.imread('C:/Users/PauloRenato/Desktop/img3.jpg', cv2.IMREAD_GRAYSCALE) im = cv2.GaussianBlur(im, (3,3), 1) im = cv2.Canny(im.copy(),10, 80) #im = 255-im # Setup S...
the-stack_0_16605
"""Support for HDMI CEC devices as media players.""" from __future__ import annotations import logging from pycec.commands import CecCommand, KeyPressCommand, KeyReleaseCommand from pycec.const import ( KEY_BACKWARD, KEY_FORWARD, KEY_MUTE_TOGGLE, KEY_PAUSE, KEY_PLAY, KEY_STOP, KEY_VOLUME_D...
the-stack_0_16606
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 """ This module accesses the DB table object UserCourseDisplay """ import logging import traceback from django.db import IntegrityError from myuw.models import UserCourseDisplay from myuw.dao.user import get_user_model TOTAL_COURSE...
the-stack_0_16608
"""Support for Meteo-France raining forecast sensor.""" from meteofrance_api.helpers import ( get_warning_text_status_from_indice_color, readeable_phenomenoms_dict, ) from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import AT...
the-stack_0_16612
import errno import operator import os import shutil import site from optparse import SUPPRESS_HELP, Values from typing import Iterable, List, Optional from pip._vendor.packaging.utils import canonicalize_name from pip._internal.cache import WheelCache from pip._internal.cli import cmdoptions from pip._internal.cli.c...
the-stack_0_16613
# 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 use ...
the-stack_0_16614
from __future__ import unicode_literals from django.test import TestCase try: from unittest.mock import call, patch except ImportError: from mock import call, patch from ..forms import AggregateMetricForm, MetricCategoryForm class TestAggregateMetricForm(TestCase): def test_form(self): """Test t...
the-stack_0_16615
# # KTH Royal Institute of Technology # DD2424: Deep Learning in Data Science # Assignment 4 # # Carlo Rapisarda (carlora@kth.se) # import numpy as np from sys import stderr from model import RNNet Theta = RNNet.Theta def eprint(*args, **kwargs): print(*args, file=stderr, **kwargs) def unpickle(filename): ...
the-stack_0_16616
import pathlib from setuptools import setup # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # This call to setup() does all the work setup( name="my_package_chetan", version="2.0.0", description="Read the la...
the-stack_0_16617
from invoke.vendor import six import fabric.connection def create_connection(host, user, identity_file): return fabric.connection.Connection(host=host, user=user, connect_kwargs={ 'key_filename': identity_file, }) def mount_volume(conn, device, mounting_point, user, gro...
the-stack_0_16620
import numpy as np import tensorflow as tf from tensorflow.keras.models import Model, Sequential from tensorflow.keras.layers import Dense, BatchNormalization, ReLU, Input, LSTM, Concatenate, Masking, Reshape, Lambda, \ Bidirectional, GRU, LayerNormalization, Bidirectional, Conv2D, Conv1D, MaxPooling2D, Flatten, La...
the-stack_0_16623
# -*- coding: utf-8 -*- """ Copyright (c) 2018 Keijack Wu 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 rights to use, copy, modify, merge...
the-stack_0_16624
import os.path from data.base_dataset import BaseDataset, get_params, get_transform from data.image_folder import make_dataset from PIL import Image class AlignedDataset(BaseDataset): """A dataset class for paired image dataset. It assumes that the directory '/path/to/data/train' contains image pairs in the ...
the-stack_0_16625
import numpy as np from holoviews.core.overlay import NdOverlay from holoviews.element import Bars from bokeh.models import CategoricalColorMapper, LinearColorMapper from ..utils import ParamLogStream from .testplot import TestBokehPlot, bokeh_renderer class TestBarPlot(TestBokehPlot): def test_bars_hover_ens...
the-stack_0_16628
# Copyright (C) 2017 Adam Schubert <adam.schubert@sg1-game.net> # # 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 3 of the License, or # (at your option) any later version. # # Th...
the-stack_0_16629
_base_ = [ './ircsn_ig65m_pretrained_bnfrozen_r152_32x2x1_58e_kinetics400_rgb.py' ] # model settings model = dict( backbone=dict( norm_eval=True, bn_frozen=True, bottleneck_mode='ip', pretrained=None)) dataset_type = 'RawframeDataset' data_root = 'data/kinetics400/rawframes_train' data_root_val = 'dat...
the-stack_0_16630
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from flask.ext.script import Manager, Server from flask.ext.collect import Collect from quokka import create_app from quokka.core.db import db from quokka.ext.blueprints import load_blueprint_commands app = create_app() if app.config.get("LOGGER_ENABLED")...
the-stack_0_16633
from os import system, name import json class Eb2Utils: # Simple function to clear the console... def clear(): # for windows if name == 'nt': _ = system('cls') _ = system('TITLE Expertise Bot :: Rewrite v0.0.2') # for mac and linux(here, os.name is 'posix') ...
the-stack_0_16634
import tkinter as tk import tkinter.ttk as ttk import numpy as np import math import operator import sys import DataControls.ControlElements as DCCE import os import subprocess from datetime import datetime import matplotlib as mpl mpl.use('TkAgg') #mpl backend from matplotlib.backends.backend_tkagg import FigureCanva...
the-stack_0_16636
import flask import requests import argparse import json import websockets import uuid import asyncio import logging import sys import re import threading from flask import Flask, request from parlai.chat_service.services.api.config import HOST_URL, PARLAI_URL, PARLAI_PORT, HOST_PORT, DEBUG, LOG_FORMAT #...
the-stack_0_16638
# Copyright (c) 2019, 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...
the-stack_0_16640
# Copyright (c) Microsoft 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 in wri...
the-stack_0_16642
from django.conf.urls import url # URLconf maps URL patterns (described as regular expressions) to views from . import views app_name = 'polls' urlpatterns = [ # ex: /polls/ url(r'^$', views.IndexView.as_view(), name='index'), # ex. /polls/5/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ...
the-stack_0_16643
import collections import datetime try: from github import Github except ImportError: raise ImportError('Install PyGithub from https://github.com/PyGithub/PyGithub or via pip') API_TOKEN = None if API_TOKEN is None: raise ValueError('Need to specify an API token') p = Github(API_TOKEN) last_release = date...
the-stack_0_16648
#!/usr/bin/python # (c) 2018-2019, NetApp, Inc # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'],...
the-stack_0_16650
""" Normalization class for Matplotlib that can be used to produce colorbars. """ import inspect import warnings import numpy as np from numpy import ma from .interval import (PercentileInterval, AsymmetricPercentileInterval, ManualInterval, MinMaxInterval, BaseInterval) from .stretch import (...
the-stack_0_16651
import logging from airflow import DAG from operators.candles_aggregation import CandleAggregation from datetime import datetime, timedelta logger = logging.getLogger(__name__) default_args = { 'start_date': datetime(2020, 12, 23), 'owner': 'airflow', 'retries': 3, 'retry_delay': timedelta(minutes=1)...
the-stack_0_16652
"""Tests for the intent helpers.""" import unittest import voluptuous as vol from homeassistant.core import State from homeassistant.helpers import (intent, config_validation as cv) import pytest class MockIntentHandler(intent.IntentHandler): """Provide a mock intent handler.""" def __init__(self, slot_sch...
the-stack_0_16654
#! /usr/bin/env python # -*- coding: utf-8 -*- # # evaluate_mcd.py # Copyright (C) 2020 Wen-Chin HUANG # # Distributed under terms of the MIT license. # import sys import argparse import logging import numpy as np import scipy from fastdtw import fastdtw from joblib import Parallel, delayed from pathlib import Path i...
the-stack_0_16655
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as readme_file: readme = readme_file.read() requirements = [ "brainio @ git+https://github.com/brain-score/brainio", "brain-score @ git+https://github.com/brain-score/brain-score", "h5py",...
the-stack_0_16657
# -*- coding: utf-8 -*- """ Created on Sat Jan 9 15:36:04 2021 @author: TT User """ import numpy as np import matplotlib.pyplot as plt from time import gmtime, strftime #STRF time go praj vremeto vo string; GMtime go praj vremeto od pochetokot na epohata vo OBJEKT from scipy...
the-stack_0_16662
# coding=utf8 from models import c3d_model from keras.optimizers import SGD import numpy as np import cv2 import datetime import os import configparser os.environ["CUDA_VISIBLE_DEVICES"] = "1" def main(video_stream): # read config.txt root_dir=os.path.abspath(os.path.dirname(__file__)) #获取当前文件所在的目录 confi...
the-stack_0_16664
import os import jwt from functools import wraps from flask import request, make_response, jsonify,abort def verify_tokens(): """ Method to verify that auth token is valid """ token = None if 'Authorization' in request.headers: token = request.headers['Authorization'] if not token: ...
the-stack_0_16665
import zhdate from nonebot import on_command, CommandSession, permission, log from .get_divination_of_thing import get_divination_of_thing from omega_miya.plugins.Group_manage.group_permissions import * __plugin_name__ = '求签' __plugin_usage__ = r'''【求签】 使用这个命令可以对任何事求运势, 包括且不限于吃饭、睡懒觉、DD 用法: /求签 [所求之事]''' # on_com...
the-stack_0_16666
import os import base64 import hashlib import datetime # parse an ISO formatted timestamp string, converting it to a python datetime object; # note: this function is also defined in server code def parse_json_datetime(json_timestamp): assert json_timestamp.endswith('Z') format = '' if '.' in json_timestam...
the-stack_0_16667
import os class Config(object): """Parent configuration class.""" DEBUG = False TESTING = False SECRET_KEY = os.getenv('SECRET') class DevelopmentConfig(Config): """Configurations for Development.""" DEBUG = True TESTING = True class TestingConfig(Config): """Configurations for Testin...
the-stack_0_16668
# 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...
the-stack_0_16671
""" ESC/POS Commands (Constants) """ # Feed control sequences CTL_LF = '\x0a' # Print and line feed CTL_FF = '\x0c' # Form feed CTL_CR = '\x0d' # Carriage return CTL_HT = '\x09' # Horizontal tab CTL_VT = '\x0b' # Vertical tab # Printer hardware...
the-stack_0_16672
class Node(object): def __init__(self, name, which): self.name = name self.which = which self.next = next self.timestamp = 0 class AnimalShelter(object): def __init__(self): self.first_cat = None self.first_dog = None self.last_cat = None self.l...
the-stack_0_16674
import cv2 as cv import numpy as np import ctypes def Mbox(title, text, style): return ctypes.windll.user32.MessageBoxW(0, text, title, style) # https://docs.opencv.org/3.4/dc/d9b/classcv_1_1ppf__match__3d_1_1ICP.html def rotation(theta): tx, ty, tz = theta Rx = np.array([[1, 0, 0], [0, np.cos(tx), -np.si...
the-stack_0_16675
# # Copyright (c) [2021] Huawei Technologies Co.,Ltd.All rights reserved. # # OpenArkCompiler is licensed under Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WA...
the-stack_0_16676
import torch import numpy as np from sklearn.metrics.pairwise import cosine_similarity def grad_cosine(grad_1, grad_2): cos = np.zeros(len(grad_1)) for i in range(len(grad_1)): cos_arr = grad_1[i] * grad_2[i] cos_arr /= np.sqrt(np.sum(grad_1[i] ** 2)) cos_arr /= np.sqrt(np.sum(...
the-stack_0_16679
#!/usr/bin/env python3 # Copyright (c) 2014-2021 The Garliccoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in t...
the-stack_0_16680
import argparse import time import torch import torch.nn as nn from torch.utils import data import numpy as np import pickle import cv2 import torch.optim as optim import scipy.misc import torch.backends.cudnn as cudnn import sys import os from tqdm import tqdm import os.path as osp #from networks.gcne...
the-stack_0_16681
""" Try all efforts to minimize the distribution size of Depsland, then extract archived files on client side. WIP: This module is not stable to use. """ import os import shutil import subprocess import sys sys.path.append(os.path.abspath(f'{__file__}/../..')) # noinspection PyUnresolvedReferences from minimal_setup...
the-stack_0_16683
# -*- coding: utf-8 -*- ''' © 2012-2013 eBay Software Foundation Authored by: Tim Keefer Licensed under CDDL 1.0 ''' import os import sys import gevent from optparse import OptionParser sys.path.insert(0, '%s/../' % os.path.dirname(__file__)) from common import dump from ebaysdk.finding import Connection as finding...
the-stack_0_16684
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( clean_html, get_element_by_class, js_to_json, ) class TVNoeIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?tvnoe\.cz/video/(?P<id>[0-9]+)' _TEST = { 'url': 'http://www.tvno...
the-stack_0_16685
from collections import OrderedDict import logging LOG = logging.getLogger(__name__) class Dispatcher(object): def __init__(self, mount=None): self._endpoints = OrderedDict() self.mount = mount def add_endpoint(self, nickname, endpoint): if self.mount: endpoint = self.moun...
the-stack_0_16687
import json from . import indexDbAPIs from . import redisAPIs class IndexDataRequestHandlers: def __init__(self): self.indexDbAPIs = indexDbAPIs.IndexDbAPIs() async def handler_indexSymbolList(self, request): ''' Returns the list of symbols in cash market segment /api/{marketTy...
the-stack_0_16690
#!/usr/bin/python from __future__ import print_function from bcc import BPF import re, signal, sys from time import sleep # for influxdb from influxdb import InfluxDBClient import lmp_influxdb as db from db_modules import write2db from datetime import datetime DBNAME = 'lmp' client = db.connect(DBNAME,user='root',...
the-stack_0_16691
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform fro...
the-stack_0_16692
"""Sensor for Last.fm account status.""" import hashlib import logging import re import pylast as lastfm from pylast import WSError import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY import homeassistant.helpers.config_va...
the-stack_0_16693
import json import io def create_snippet(file_path, first_n=5): with open(file_path, 'r') as f: return [next(f) for _ in range(first_n)] def create_jtr_snippet(file_path): return convert_simplequestions(file_path, first_n=5) def convert_simplequestions(file_path, first_n=None): instances = [] ...
the-stack_0_16694
# Copyright 2019 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 ...
the-stack_0_16695
#add parent dir to find package. Only needed for source code build, pip install doesn't need it. import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) os.sys.path.insert(0,parentdir) import gym from pybullet_en...
the-stack_0_16696
from dataclasses import dataclass from typing import FrozenSet, Callable, List import heapq from contextlib import contextmanager from time import time @contextmanager def timing(description: str) -> None: start = time() yield elapsed_time = (time() - start) * 1000 print(f"{description}: {elapsed_time...
the-stack_0_16698
# -*- coding: utf-8 -*- import base64 import datetime import hashlib import io import uuid from lxml import etree, builder DS = builder.ElementMaker( namespace="http://www.w3.org/2000/09/xmldsig#", nsmap={ "ds": "http://www.w3.org/2000/09/xmldsig#", }, ) CanonicalizationMethod = DS.Canonicalizatio...
the-stack_0_16700
from .backend_template import BackendTemplate import warnings try: import pandas as pd # WHEN CHECKING FOR THE TYPE OF AN OBJECT IN A SERIES BEWARE THAT: # # series = pd.Series([1, 2, 3, 4]) # # for s in series: # print(str(type(s))) # outputs; # `<class 'int'> # `<cla...
the-stack_0_16701
import psycopg2 as psy import sqlalchemy import datetime as dt from sqlalchemy import ( Table, Column, Index, Integer, String, Text, Boolean, ForeignKey, UniqueConstraint, ) from sqlalchemy import text from sqlalchemy.dialects.postgresql import JSON,JSONB from sqlalchemy.ext.dec...
the-stack_0_16702
# -*- coding: utf-8 -*- """The filter file CLI arguments helper.""" from __future__ import unicode_literals import os from plaso.cli import tools from plaso.cli.helpers import interface from plaso.cli.helpers import manager from plaso.lib import errors class FilterFileArgumentsHelper(interface.ArgumentsHelper): ...
the-stack_0_16704
# (c) 2014, James Tanner <tanner.jc@gmail.com> # # Ansible 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 3 of the License, or # (at your option) any later version. # # Ansible is distributed i...
the-stack_0_16705
# -*- coding: utf-8 -*- # # 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 #...
the-stack_0_16706
''' This file will write and compile resume latex file. ''' import json import os import sys from GetLatex import * ''' Read init tex file and add content from pre-defined json args: filename: filename defined your resume file js: resume json object ''' def build(filename,js): with open(filename,'w') as...
the-stack_0_16707
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Bot that scrapes RSS feeds. Usage: Run python3 bot.py --help for help. Press Ctrl-C on the command line or send a signal to the process to stop the bot. """ import logging import feedparser import pytz import argparse import datetime as dt import yaml from sqlitedic...
the-stack_0_16710
from __future__ import print_function, division import numpy as np import pytest import itertools import os.path from skimage.transform import radon, iradon, iradon_sart, rescale from skimage.io import imread from skimage import data_dir from skimage._shared.testing import test_parallel from skimage._shared._warnings...
the-stack_0_16712
#!/usr/bin/env python3 # plot_shapely.py # %% from dataclasses import dataclass from typing import List, Tuple, Set import matplotlib.pyplot as plt from aray.problem import Problem from shapely.geometry import Polygon, Point, LineString ''' Datastructures we want to have point: integer pair, not the shapely kind d...
the-stack_0_16714
import ctypes from vivsys.common import * class ServiceControlManager: def __init__(self): self.hScm = None def __enter__(self): self.hScm = advapi32.OpenSCManagerW(None, None, SC_MANAGER_CREATE_SERVICE) if not self.hScm: raise ctypes.WinError() return self d...
the-stack_0_16715
#CODE2---For calculating pathway details---- #Python 3.6.5 |Anaconda, Inc. import sys import glob import errno import csv #path = '/home/16AT72P01/Excelra/SMPDB/output/metabolic_proteins.csv' path = '/home/16AT72P01/Excelra/SMPDB/output/metabolics.csv' files = glob.glob(path1) unique_pathway = set() with open(path...
the-stack_0_16719
#!/usr/bin/env python # coding: utf-8 # This file is a part of `qal`. # # Copyright (c) 2021, University of Nebraska Board of Regents. # # 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 witho...
the-stack_0_16720
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) def is_valid_python_version(): version_valid = False ver = sys.version_info if (2 == ver.major) and (7 <= ver.minor): version_valid = True ...
the-stack_0_16721
from PEPit import PEP from PEPit.functions import SmoothStronglyConvexFunction def wc_polyak_steps_in_function_value(L, mu, gamma, verbose=1): """ Consider the minimization problem .. math:: f_\\star \\triangleq \\min_x f(x), where :math:`f` is :math:`L`-smooth and :math:`\\mu`-strongly convex, and ...
the-stack_0_16722
import csv import itertools import json import os import threading from concurrent.futures import ThreadPoolExecutor from concurrent.futures import wait from pathlib import Path from subprocess import CalledProcessError from typing import TYPE_CHECKING from typing import Any from typing import Dict from typing import ...
the-stack_0_16726
# Copyright (c) OpenMMLab. All rights reserved. from collections import namedtuple import torch from torch.nn import (AdaptiveAvgPool2d, BatchNorm2d, Conv2d, MaxPool2d, Module, PReLU, ReLU, Sequential, Sigmoid) # yapf: disable """ ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/...
the-stack_0_16727
#!/usr/bin/env python3 import json import sys import os import subprocess import time description = """ process all data_set within a bundle """ def main(): try: args = parse_args() bundle = read_bundle_json(args["bundle_json"]) for data_set in bundle["DATA_SETS"]: process_one...