filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_15005
"""Basic tests for quadrature GPy wrappers.""" import GPy import numpy as np import pytest from pytest_lazyfixture import lazy_fixture from emukit.model_wrappers.gpy_quadrature_wrappers import ( BaseGaussianProcessGPy, BrownianGPy, ProductBrownianGPy, ProductMatern32GPy, ProductMatern52GPy, RB...
the-stack_0_15007
#!/usr/bin/env python #===- lib/asan/scripts/asan_symbolize.py -----------------------------------===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===----------------------------------------...
the-stack_0_15008
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). # Adapted from https://mypyc.readthedocs.io/en/latest/getting_started.html#example-program import time def fib(n: int) -> int: if n <= 1: return n else: return f...
the-stack_0_15009
#!/usr/bin/python3 from pathlib import Path import pytest priv_key = "0x416b8a7d9290502f5661da81f0cf43893e3d19cb9aea3c426cfb36e8186e9c09" addr = "0x14b0Ed2a7C4cC60DD8F676AE44D0831d3c9b2a9E" @pytest.fixture(autouse=True) def no_pass(monkeypatch): monkeypatch.setattr("brownie.network.account.getpass", lambda x: "...
the-stack_0_15011
""" data collector """ from random import randint from time import sleep import csv import re import concurrent.futures import datetime from bs4 import BeautifulSoup import urllib3 import requests from utils.utilities import ProjectCommon OUTPUT_FILE_PATH = 'reviews_with_ranks.csv' SCRAPER_FINAL_OUTPUT = [] MOVIE_REVI...
the-stack_0_15012
import os import numpy as np from scipy.io import netcdf_file from pychemia.utils.periodic import atomic_symbol from .htmlparser import MyHTMLParser """ This module provides general routines used by abipython but not requiring the abipython classes """ __author__ = "Guillermo Avendano-Franco" __copyright__ = "Copyrig...
the-stack_0_15016
'''Michael Lange <klappnase (at) freakmail (dot) de> The ToolTip class provides a flexible tooltip widget for Tkinter; it is based on IDLE's ToolTip module which unfortunately seems to be broken (at least the version I saw). INITIALIZATION OPTIONS: anchor : where the text should be positioned inside the widg...
the-stack_0_15017
import json from collections import Counter class Sorter(object): def __init__(self): # These are playlists that are to be edited, this can be changed from configparser import ConfigParser; config = ConfigParser(); \ config.read('config.ini'); \ self.target_playlis...
the-stack_0_15018
#!/usr/bin/env python3 # Copyright (c) 2014-2017 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 the -alertnotify, -blocknotify and -walletnotify options.""" import os from test_framework.test_f...
the-stack_0_15019
import os def rename_files(): # (1) get file names from a folder file_list = os.listdir("prank") print(file_list) saved_path = os.getcwd() print("Current Working Directory is %s" % saved_path) os.chdir("prank") # (2) for each file, rename filename for file_name in file_list: ...
the-stack_0_15020
from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017/") database = "mydb" collections = ["cars", "cops"] database = client[database] cars = database[collections[0]] cops = database[collections[1]] def get_all_cars(): return cars.find() def get_free_cars(): return cars.find({"resolv...
the-stack_0_15021
"""Utilities related archives. """ # The following comment should be removed at some point in the future. # mypy: strict-optional=False # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import os import shutil import stat import tarfile import zipfile from pip._internal.excep...
the-stack_0_15022
# -*- coding: utf-8 -*- """ Deeplabv3+ model for Keras. This model is based on TF repo: https://github.com/tensorflow/models/tree/master/research/deeplab On Pascal VOC, original model gets to 84.56% mIOU Now this model is only available for the TensorFlow backend, due to its reliance on `SeparableConvolution` layers,...
the-stack_0_15025
# 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 ...
the-stack_0_15026
''' Copyright 2016 Tom Kenter Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
the-stack_0_15028
# -*- coding: utf-8 -*- """ <application name> Copyright ©<year> <author> Licensed under the terms of the <LICENSE>. See LICENSE for details. @author: <author> """ # Setup PyQt's v2 APIs import sip API_NAMES = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"] API_VERSION = 2 ...
the-stack_0_15032
import datetime import pytz import calendar import os cdt = datetime.datetime.now().date() str_cdt=cdt.strftime("%d/%B") print(str_cdt) #заношу в виде строки date_to_str=str(cdt) #меняю в строке - на _ clear_str=date_to_str.replace('-',' ') #разбиваю на отдельные слова slice_str=clear_str.split() #cоздаю новую дату ...
the-stack_0_15033
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divisio...
the-stack_0_15035
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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://w...
the-stack_0_15036
# coding: utf-8 """ Schemas The CRM uses schemas to define how custom objects should store and represent information in the HubSpot CRM. Schemas define details about an object's type, properties, and associations. The schema can be uniquely identified by its **object type ID**. # noqa: E501 The version ...
the-stack_0_15038
from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt, QBasicTimer from PyQt5.QtGui import QPen, QColor, QBrush import time class Settings: BLOCK_WIDTH = 10 BLOCK_HEIGHT = 10 NUM_BLOCKS_X = 50 NUM_BLOCKS_Y = 50 SCREEN_WIDTH = BLOCK_WIDTH * NUM_BLOCKS_X SCREEN_HEIGHT = BLOCK_HEIGHT * NUM_B...
the-stack_0_15039
import os import shutil from conans.client.source import complete_recipe_sources from conans.errors import ConanException from conans.model.ref import ConanFileReference, PackageReference from conans.util.files import rmdir def _prepare_sources(cache, ref, remote_manager, loader, remotes): conan_file_path = cach...
the-stack_0_15040
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="layout.xaxis.rangeselector.font", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotl...
the-stack_0_15044
import cv2 cv2_data_dir = '/usr/local/lib/python3.7/dist-packages/cv2/data/' face_cascade = cv2.CascadeClassifier(cv2_data_dir + 'haarcascade_frontalface_default.xml') img = cv2.imread('faces.jpg', cv2.IMREAD_GRAYSCALE) scale_factor = 1.4 min_neighbours = 5 faces = face_cascade.detectMultiScale(img, scale_factor, m...
the-stack_0_15046
import base64 import datetime import plotly import plotly.figure_factory as ff import os import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate import json import dashUI.run as run import dashUI.run...
the-stack_0_15048
# Copyright (C) 2019 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from datetime import date from datetime import datetime from freezegun import freeze_time from mock import patch from ggrc.app import db from ggrc.notifications import common from ggrc.models import Notifica...
the-stack_0_15049
#!/usr/bin/env python3 import argparse import logging from db_test_meter.database import Database from db_test_meter.util import init_logger, collect_user_input, AppConfig def create_db(db: Database) -> None: """ Utility to create the db and table for the sync check :param db: :return: """ t...
the-stack_0_15051
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1. / np.sqrt(fan_in) return -lim, lim class Actor(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, f...
the-stack_0_15052
from functools import reduce from operator import __mul__ import pytest from treevalue.tree import func_treelize, TreeValue, method_treelize, classmethod_treelize, delayed # noinspection DuplicatedCode @pytest.mark.unittest class TestTreeFuncFunc: def test_tree_value_type(self): class _MyTreeValue(TreeV...
the-stack_0_15054
__author__ = 'Simon' import json import re import urllib.request import html fnc_base_url = 'http://cbateam.github.io/CBA_A3/docs/index/' fnc_page_names = ['Functions', 'Functions2', 'Functions3'] fncPrefix = 'CBA_fnc_' macro_base_url = 'http://cbateam.github.io/CBA_A3/docs/files/main/script_macros_common-hpp.html' ...
the-stack_0_15056
""" Post-processing function that takes a case_data_set and outputs a csv file """ import csv # pylint: disable=E0611,F0401 from openmdao.main.case import flatten_obj def caseset_query_to_csv(data, filename='cases.csv', delimiter=',', quotechar='"'): """ Post-processing function that takes a case_data_se...
the-stack_0_15058
from tkinter import Frame, Canvas, Tk, Text, LEFT, INSERT, END, messagebox, Button, X from alarming_service import time_diff def GUI_present(): root = Tk() canvas = Canvas(root) canvas.pack() frame = Frame(canvas) frame.pack() top_text = Text(frame) top_text.insert( INSERT, ...
the-stack_0_15059
""" This is a file includes the main function for gym atari reinforcement learning. """ import os import gym import numpy as np from argparse_decorate import init_parser, add_arg from deep_q_learning import DQLAtari from sac_discrete import SoftActorCriticsDiscrete @init_parser() @add_arg('--start_episode', type=int...
the-stack_0_15060
class GPX: def __init__(self,filename): self.fd = open(filename,"w") self.fd.write('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n') self.fd.write('<gpx version="1.1"\n') self.fd.write(' creator="Osmawalk - https://github.com/xtompok/osmawalk"\n') self.fd.wr...
the-stack_0_15063
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, publish, ...
the-stack_0_15065
import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) ...
the-stack_0_15066
import os import sys import psutil from monk.pytorch_prototype import prototype from monk.compare_prototype import compare from monk.pip_unit_tests.pytorch.common import print_start from monk.pip_unit_tests.pytorch.common import print_status import torch import numpy as np from monk.pytorch.losses.return_loss import...
the-stack_0_15067
import asyncio import logging import time from typing import Iterable import uvicorn from fastapi import FastAPI from fastapi.responses import RedirectResponse from async_batch.batch_processor import BatchProcessor, TaskQueue log = logging.getLogger(__file__) LOGGING_CONFIG = { "version": 1, "disable_existi...
the-stack_0_15068
"""Registers functions to be called if an exception or signal occurs.""" import functools import logging import signal import traceback # pylint: disable=unused-import, no-name-in-module from acme.magic_typing import Any, Callable, Dict, List, Union # pylint: enable=unused-import, no-name-in-module from certbot impor...
the-stack_0_15069
# -*- 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_15070
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenAuthAppCancelModel(object): def __init__(self): self._auth_app_id = None self._auth_scene = None self._operator_user_id = None @property d...
the-stack_0_15071
# -*- coding: utf-8 -*- import click import json from ..utils.spinner import ( init_spinner, start_spinner, stop_spinner, ) from ..utils.print import ( tbprint, eprint, oprint, opprint, ) @click.group() @click.pass_obj @click.pass_context def command_runner(ctx, obj): """DNA Center Com...
the-stack_0_15074
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
the-stack_0_15076
# Import the modules import cv2 import numpy as np import os import imutils from imutils.video import WebcamVideoStream DEBUG = True # Custom functions # define rotate function def rotate(image, angle, center=None, scale=1.0): # get image size (h, w) = image.shape[:2] # if dosen't assign image center, ...
the-stack_0_15078
# # Copyright 2018 Analytics Zoo 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 or agreed to...
the-stack_0_15079
"""Support to interface with the Plex API.""" from functools import wraps import json import logging import plexapi.exceptions import requests.exceptions from homeassistant.components.media_player import DOMAIN as MP_DOMAIN, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_MU...
the-stack_0_15080
from django import template register = template.Library() @register.filter_function def attr(obj, arg1): """ Use in templates: {% load field_attrs %} then, in a form field: {{ form.phone|attr:"style=width:143px;background-color:yellow"|attr:"size=30" }} """ att, value = arg1.split("=") ...
the-stack_0_15085
import os from celery.schedules import crontab # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! # Set in local_settings.py SECRET_KEY = 'SECRET_SECRET_SECRET...
the-stack_0_15086
#!/usr/bin/env python3 import os import stat def getFileList(fileDir): fileList = os.listdir(fileDir) newFileList = [] for eachFile in fileList: if eachFile[:31] not in newFileList: newFileList.append(eachFile) return newFileList def createSubmitFile(eventRootName): fileNam...
the-stack_0_15087
import autofit as af import autolens as al from test_autolens.integration.tests.imaging import runner test_type = "lens__source_inversion" test_name = "lens_both__source_rectangular" data_type = "lens_light__source_smooth" data_resolution = "lsst" def make_pipeline(name, phase_folders, optimizer_class=af.MultiNest):...
the-stack_0_15089
from pymixconf.jsonconf import JSONConf import os def test_yamlconf(): loader = JSONConf(config_directory="test/fixtures", environment_key="TEST_ENV") os.environ["TEST_ENV"] = "dev" data = loader.load_config() expected = { "flask": { "port": 7000 }, "logging": { ...
the-stack_0_15090
""" Defines repositories and register toolchains for versions of the tools built from source """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") _ALL_CONTENT = """\ filegroup( name = "all_srcs", srcs = glob(["**"]), visibi...
the-stack_0_15091
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
the-stack_0_15092
from igramscraper.instagram import Instagram import urllib.request import argparse import os def get_media_from_hashtag(tag, media_type, quality, max_images, path): instagram = Instagram() medias = instagram.get_medias_by_tag(tag, count=max_images) count = 1 for media in medias: media.type = '...
the-stack_0_15093
from cricsheet.io_xml.parsers.parser import Parser class MatchParser(Parser): def __init__(self, match_id): self.match_id = match_id self.metadata_parser = MatchMetadataParser() self.outcome_parser = MatchOutcomeParser() self.umpire_parser = UmpireParser() def parse(self, raw)...
the-stack_0_15095
"""Remove processed notebooks from disk""" import argparse import shutil from reproducemegit.jupyter_reproducibility import config import os from reproducemegit.jupyter_reproducibility import consts from reproducemegit.jupyter_reproducibility.db import Repository, Notebook, connect from reproducemegit.jupyter_reproduc...
the-stack_0_15096
# Lab 4 Multi-variable linear regression import tensorflow as tf import numpy as np tf.set_random_seed(777) # for reproducibility xy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype=np.float32) x_data = xy[:, 0:-1] y_data = xy[:, [-1]] # Make sure the sape and data are OK print(x_data.shape, x_data, len(x...
the-stack_0_15097
import os import subprocess import glob import hashlib import shutil from common.basedir import BASEDIR from selfdrive.swaglog import cloudlog android_packages = ("ai.comma.plus.offroad",) def get_installed_apks(): dat = subprocess.check_output(["pm", "list", "packages", "-f"], encoding='utf8').strip().split("\n") ...
the-stack_0_15100
import os import argparse import pandas as pd from typing import Dict from utils import parse_date, load_colnames from parsers import ( confirmados_diarios_por_estado, negativos_diarios_por_estado, pruebas_pendientes_diarias_por_estado, defunciones_diarias_por_estado, hospitalizados_diarios_por_es...
the-stack_0_15103
import numpy as np import os import cv2 def imread(file_path, c=None): if c is None: im = cv2.imread(file_path) else: im = cv2.imread(file_path, c) if im is None: raise 'Can not read image' if im.ndim == 3 and im.shape[2] == 3: im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)...
the-stack_0_15105
import tty import sys import curses import datetime import locale from decimal import Decimal import getpass import electrum from electrum.util import format_satoshis, set_verbosity from electrum.bitcoin import is_address, COIN, TYPE_ADDRESS from electrum.transaction import TxOutput from electrum.wallet import Wallet ...
the-stack_0_15106
from flask import Flask, render_template, request import sqlite3 as sql app = Flask(__name__) import sqlite3 conn = sqlite3.connect('database.db') # print("Opened database successfully") # conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)') # print("Table created successfully") # conn.c...
the-stack_0_15107
"""Module/script to byte-compile all .py files to .pyc (or .pyo) files. When called as a script with arguments, this compiles the directories given as arguments recursively; the -l option prevents it from recursing into directories. Without arguments, if compiles all modules on sys.path, without recursing into...
the-stack_0_15109
########################################################################################################################################## ## License: Apache 2.0. See LICENSE file in root directory. ## #############################################...
the-stack_0_15110
#!/usr/bin/env python3 import binascii import os import struct import time from collections import namedtuple import numpy as np from opendbc import DBC_PATH from common.realtime import Ratekeeper from selfdrive.config import Conversions as CV import selfdrive.messaging as messaging from selfdrive.services import ser...
the-stack_0_15114
# coding=utf-8 import os import xml.etree.ElementTree as ET import matplotlib.pyplot as plt path = os.path.join(os.getcwd(), 'images', 'annotations') if not os.path.exists(path): raise ValueError('The images\\annotations firectory does not exist') else: files = os.listdir(path) results = {} files =...
the-stack_0_15119
#!/usr/bin/env python3 # Copyright (c) 2016-2019 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 segwit transactions and blocks on P2P network.""" from decimal import Decimal import math import r...
the-stack_0_15121
# -*- coding: utf-8 -*- from .models import Team from rest_framework import serializers class TeamSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Team fields = ('code', 'name', 'strength_defence_home', 'strength_attack_home', 'strength_overall_home', 'stre...
the-stack_0_15123
import pytest from numbers import Number from numpy import ndarray from hypothesis import given import hypothesis.strategies as hst from qcodes.dataset.param_spec import ParamSpec @pytest.fixture def version_0_serializations(): sers = [] sers.append({'name': 'dmm_v1', 'paramtype': 'numeric'...
the-stack_0_15124
# # Copyright 2021- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # import numpy as np from scipy.sparse import issparse from sklearn.utils.extmath import row_norms class PHKMeansOptimizer: def __init__(self, n_clusters, n_features, n_samples, x, x_squared_norm): self.n_clusters = n_...
the-stack_0_15125
# Copyright 2013-2022 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) """The pty module handles pseudo-terminals. Currently, the infrastructure here is only used to test llnl.util.tty.log. I...
the-stack_0_15128
# MIT License # # Copyright (c) 2018 Mahmoud Aslan # # 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_15129
from unittest import TestCase from mock import Mock, patch from data import FlixsterMovieDetails, Actor, RottenTomatoesMovieDetails, Movie from data.parsers.movies import get_flixster_movie_details, get_rotten_tomatoes_movie_details, parse_actors, \ parse_release_date, parse_trailer_url, parse_flixster_movie_detai...
the-stack_0_15130
# -*- coding=utf -*- from __future__ import absolute_import from cubes.browser import * from cubes.errors import * from cubes.model import * from .store import DEFAULT_TIME_HIERARCHY from .utils import * from collections import defaultdict from datetime import datetime import pytz class _MixpanelResponseAggregator...
the-stack_0_15131
# -*- coding: utf-8 -*- """Test that models can be executed.""" import importlib import os import unittest from typing import Optional import numpy import torch import pykeen.experiments import pykeen.models from pykeen.models import ( ERModel, EntityEmbeddingModel, EntityRelationEmbeddingModel, Model, Multimod...
the-stack_0_15132
import grpc import hello_pb2 import hello_pb2_grpc def run(): # connect grpc server channel = grpc.insecure_channel('localhost:8089') # send grpc stub = hello_pb2_grpc.GreeterStub(channel) response = stub.SayHello(hello_pb2.Request(name = 'cpx')) print("Greeter client received: " + response.me...
the-stack_0_15134
# -*- coding: utf-8 -*- from __future__ import absolute_import from datetime import datetime, timedelta from sentry.constants import STATUS_RESOLVED, STATUS_UNRESOLVED from sentry.models import GroupBookmark, GroupTagValue from sentry.search.django.backend import DjangoSearchBackend from sentry.testutils import Test...
the-stack_0_15135
#!/usr/bin/env python """Unit test for the linux cmd parser.""" import os from grr.lib import flags from grr.lib import rdfvalue from grr.lib import test_lib from grr.parsers import linux_cmd_parser class LinuxCmdParserTest(test_lib.GRRBaseTest): """Test parsing of linux command output.""" def testDpkgCmdPars...
the-stack_0_15139
from logging import getLogger from typing import Optional from state_manager.models.state_managers.base import back_to_pre_state_, BaseStateManager from state_manager.models.state import StateData from state_manager.types.aiogram import aiogram_context from state_manager.types.generals import Data logger = getLogger(...
the-stack_0_15140
# -*- coding:utf-8 -*- # # Copyright (C) 2020-2021, Saarland University # Copyright (C) 2020-2021, Maximilian Köhl <koehl@cs.uni-saarland.de> # Copyright (C) 2020-2021, Michaela Klauck <klauck@cs.uni-saarland.de> from __future__ import annotations import dataclasses as d import typing as t import enum from . import...
the-stack_0_15141
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition class TestSpatialPyramidPooling2D(unittest.TestCase): pyramid_height = 3 ou...
the-stack_0_15142
from conans import ConanFile, tools, CMake import os class SDL2ImageConan(ConanFile): name = "sdl2_image" description = "SDL_image is an image file loading library" topics = ("sdl2_image", "sdl_image", "sdl2", "sdl", "images", "opengl") url = "https://github.com/bincrafters/community" homepage = "...
the-stack_0_15143
"""LaTeX Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os from traitlets import Unicode, default from traitlets.config import Config from nbconvert.filters.highlight import Highlight2Latex from nbconvert.filters.filter_links import reso...
the-stack_0_15145
""" Solves problem 7 of the One Hundred Dollars, One Hundred Digits Challenge. """ import numpy as np from pysparse.sparse import spmatrix from pysparse.itsolvers.krylov import minres from pysparse.precon import precon def get_primes(nofPrimes): primes = np.zeros(nofPrimes, 'i') primes[0] = 2 nof = 1 ...
the-stack_0_15147
import numpy as np import scipy.interpolate as si import tools def stdextr(data, x1, x2, variance=None, mask=None, interp=False): """ Standard box extraction of spectrum. Step 4 of Horne (1989). Parameters: ----------- data: 2D float ndarray Sky-subtracted spectrum image of shape [nwavelength, ...
the-stack_0_15149
# Copyright (c) OpenMMLab. All rights reserved. import argparse import copy import os import os.path as osp import time import warnings import mmcv import torch from mmcv import Config, DictAction from mmcv.runner import get_dist_info, init_dist from mmcls import __version__ from mmcls.apis import init_random_seed, s...
the-stack_0_15150
import numpy as np import logging from pyrfr import regression from smac.epm.base_epm import AbstractEPM from smac.configspace import ( CategoricalHyperparameter, UniformFloatHyperparameter, UniformIntegerHyperparameter, Constant, ) class RandomForestWithInstances(AbstractEPM): """ Base EPM....
the-stack_0_15152
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('training', '0003_training_published_mecc_url'), ] operations = [ migrations.AddField( model_name='training', ...
the-stack_0_15154
"""Computes the similarity of molecular scaffolds between two datasets.""" from itertools import product import math import os import sys from typing import List from typing_extensions import Literal import numpy as np from rdkit import Chem from rdkit import DataStructs from rdkit.Chem import AllChem from tqdm impo...
the-stack_0_15156
""" Windowing processes for windowing over days """ import udatetime import datetime from numpy import argmin, abs, array from sit2standpy.v2.base import _BaseProcess, PROC, DATA __all__ = ['WindowDays'] class WindowDays(_BaseProcess): def __init__(self, hours=[8, 20], **kwargs): """ Window dat...
the-stack_0_15157
import logging from PyQt5 import QtCore, QtGui, QtWidgets from hackedit.app import settings from hackedit.app.forms import dlg_preferences_ui from hackedit.app.widgets import preference_pages from hackedit.api import system def _logger(): return logging.getLogger(__name__) class DlgPreferences(QtWidgets.QDial...
the-stack_0_15158
import urllib.request as urlr import urllib.parse as urlp import urllib.error as urle import http.cookiejar as ck import pickle as pk import re import zlib import time import random as r from datetime import datetime, timedelta import os from lxml import etree import tkinter.messagebox from tkinter import * def get_Pk...
the-stack_0_15160
"""Provides macros for working with yoga library.""" YOGA_ROOTS = ["//..."] JAVA_TARGET = "//java:java" INFER_ANNOTATIONS_TARGET = "//lib/infer-annotations:infer-annotations" JSR_305_TARGET = "//lib/jsr-305:jsr-305" JUNIT_TARGET = "//lib/junit:junit" PROGRUARD_ANNOTATIONS_TARGET = "//java/proguard-annotations/src...
the-stack_0_15161
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from botbuilder.core import CardFactory, MessageFactory from botbuilder.dialogs import ( ComponentDialog, DialogSet, DialogTurnStatus, WaterfallDialog, WaterfallStepContext, ) from botbuilder.dialogs.promp...
the-stack_0_15162
# ParallelContext transfer functionality tests. # This uses nonsense models and values to verify transfer takes place correctly. import sys from io import StringIO from neuron import h #h.nrnmpi_init() pc = h.ParallelContext() rank = pc.id() nhost = pc.nhost() if nhost > 1: if rank == 0: print("nhost > 1 so c...
the-stack_0_15163
import argparse import sys sys.setrecursionlimit(100000) from interpreter import executeFunctions as executionFunctions from interpreter import imageFunctions as imageWrapper from GUI import main as GUIMain parser = argparse.ArgumentParser(description='Interprets a piet image') parser.add_argument("-f", "--file", re...
the-stack_0_15167
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the Lic...
the-stack_0_15168
import socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #绑定 sock.bind(("0.0.0.0",5566)) #监听 sock.listen(20) #接收 conn,addr = sock.accept(); print("address is :",addr) data = conn.recv(1024) print(data) msg = """HTTP/1.1 200 OK Content-Type:text/html <meta charset='utf-8'> <h1>人生苦短,我用python</h1> """ # ...
the-stack_0_15170
import cv2 import numpy as np import threading class Webcam2rgb(): def start(self, callback, cameraNumber=0, width = None, height = None, fps = None, directShow = False): self.callback = callback try: self.cam = cv2.VideoCapture(cameraNumber + cv2.CAP_DSHOW if directShow else cv2.CA...
the-stack_0_15173
import random from raiden.constants import ABSENT_SECRET from raiden.settings import DEFAULT_WAIT_BEFORE_LOCK_REMOVAL from raiden.transfer import channel, routes from raiden.transfer.architecture import Event, TransitionResult from raiden.transfer.events import EventPaymentSentFailed, EventPaymentSentSuccess from raid...