filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_20337
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import argparse from collections import defaultdict from functools import reduce import gc import logging import math import operator import pprint import time from datasets.wikitext2_data import get_real_dataloaders as get_real_wikitext2_dataloa...
the-stack_106_20338
import os import networkx as nx import numpy as np from six import iteritems from opensfm import types import opensfm.dataset def normalized(x): return x / np.linalg.norm(x) def camera_pose(position, lookat, up): ''' Pose from position and look at direction >>> position = [1.0, 2.0, 3.0] >>> ...
the-stack_106_20339
from typing import Any, Optional, Text, List, Type from rasa.nlu.config import RasaNLUModelConfig from rasa.nlu.components import Component from rasa.nlu.featurizers.featurizer import DenseFeaturizer from rasa.utils.features import Features from rasa.nlu.utils.hugging_face.hf_transformers import HFTransformersNLP from...
the-stack_106_20340
# Python program to reverse a singly linked list # Node class class Node: # Constructor to initialise data and next def __init__(self, data=None): self.data = data self.next = None class SinglyLinkedList: # Constructor to initialise head def __init__(self): self.head = None...
the-stack_106_20341
""" MIT License Copyright (c) 2017 Jaehyun Park 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_106_20343
import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Run3_dd4hep_cff import Run3_dd4hep process = cms.Process("GeometryTest", Run3_dd4hep) process.load("FWCore.MessageLogger.MessageLogger_cfi") # Choose Tracker Geometry process.load('Configuration.Geometry.GeometryDD4hepExtended2021Reco_cff') proces...
the-stack_106_20344
# 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) from spack import * class RTweenr(RPackage): """Interpolate Data for Smooth Animations. In order to create smoo...
the-stack_106_20345
import random from PIL import Image from time import sleep from states.base import BaseState import glob class State(BaseState): # module information name = "gifs" index = 0 delay = 12 # check function def check(self, _state): return True def get_image(self, path): imag...
the-stack_106_20346
#!/usr/bin/env python3 # # Copyright 2021 James Yoo. # # 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...
the-stack_106_20347
# -*- coding: utf-8 -*- """ pygments.lexers.hdl ~~~~~~~~~~~~~~~~~~~ Lexers for hardware descriptor languages. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, bygroups, include, using, ...
the-stack_106_20349
import discord, os from discord.ext import commands from utils import checks, output, parsing from aiohttp import ClientSession import urllib.request import json class Stats: def __init__(self, bot: discord.ext.commands.Bot): self.bot = bot @commands.command(pass_context=True) async def stats(self...
the-stack_106_20350
# Copyright 2018 Google 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 writing, ...
the-stack_106_20352
from django.db import models from django.forms import CharField from django.core.exceptions import ValidationError from connector import ElfinderConnector class ElfinderFile(object): """ This class represents an Elfinder file. """ def __init__(self, hash_, optionset): self.hash = hash_ ...
the-stack_106_20353
""" Numpy API for xhistogram. """ import dask import numpy as np from functools import reduce from collections.abc import Iterable from numpy import ( searchsorted, bincount, reshape, ravel_multi_index, concatenate, broadcast_arrays, ) # range is a keyword so save the builtin so they can use ...
the-stack_106_20354
from lxml import objectify, etree import pytest from controlled_vocabularies.vocabulary_handler import VocabularyHandler from . import factories pytestmark = pytest.mark.django_db # Namespaces RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' DC = 'http://purl.org/dc/elements/1.1/' RDFS = 'http://www.w3.org/2000/0...
the-stack_106_20355
# Copyright (c) 2019 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...
the-stack_106_20356
import json import uuid from loguru import logger import googleapiclient.discovery from google.oauth2 import service_account from cloudproxy.providers.config import set_auth from cloudproxy.providers.settings import config gcp = config["providers"]["gcp"] if gcp["enabled"] == 'True': try: credentials = ...
the-stack_106_20357
import matplotlib.pyplot as plt import numpy as np import warnings warnings.filterwarnings('ignore') SIZE = (14,14) class CrossRoadGridWorld(): def __init__(self, size=(14,14)): super(CrossRoadGridWorld, self).__init__() self.state = np.zeros(size) self.size = size self.init_state =...
the-stack_106_20358
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
the-stack_106_20359
# coding=utf-8 # Copyright 2020 The TF-Agents 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
the-stack_106_20360
import sys import pandas as pd import numpy as np import numpy.linalg as la from scipy import stats from collections import Counter def quantile_normalization(data): ''' This function does quantile normalization to input data. After normalization, the samples (rows) in output data follow the same distribut...
the-stack_106_20362
# coding: utf-8 import re import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class KeystoneListAuthDomainsResponse(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name ...
the-stack_106_20363
from __future__ import unicode_literals import django from future.builtins import int, zip from functools import reduce from operator import ior, iand from string import punctuation from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.db.models import Manager, Q, CharField...
the-stack_106_20364
# Copyright 2018 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_106_20366
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import, print_function, unicode_literals from subprocess import PIPE # Import salt libs import salt.modules.openscap as openscap # Import 3rd-party libs from salt.ext import six from tests.support.mock import MagicMock, Mock, patch # Impo...
the-stack_106_20371
""" string_util.py A sample repository for MolSSI Workshop. Misc. string processing functions """ def title_case(sentence): """ Convert a string to title case. Parameters ---------- sentence: string String to be converted to title case Returns ------- ret : string S...
the-stack_106_20372
"""""" """ Copyright (c) 2021 Olivier Sprangers as part of Airlab Amsterdam 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 ...
the-stack_106_20373
# -*- coding: utf-8 -*- #from pathos.multiprocessing import ProcessingPool as Pool #from pathos.helpers import mp import multiprocessing as mp import sys class mproc(): ''' This is a class that spawns N new processes to do the designated job @initializer params : - N : number of processes to spa...
the-stack_106_20374
from math import floor, ceil import numpy as np from pyspark import SparkContext from shapely.geometry import Point from geopyspark.geotrellis.constants import LayerType from geopyspark.geotrellis import SpaceTimeKey, Extent, Tile, get_spark_context from geopyspark.geotrellis.layer import TiledRasterLayer class Gdd...
the-stack_106_20375
from paida.paida_core.PAbsorber import * def dscal(n, da, dx, incx): """scales a vector by a constant. uses unrolled loops for increment equal to one. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) Python replacement by K. KISHI...
the-stack_106_20376
# Copyright 2020 Graphcore Ltd. from pathlib import Path import pytest # NOTE: The import below is dependent on 'pytest.ini' in the root of # the repository from examples_tests.test_util import SubProcessChecker working_path = Path(__file__).parent.parent class TestTensorFlowGroupedConvBenchmarks(SubProcessChecker)...
the-stack_106_20378
#!/usr/bin/env python # Quick flame color test based on the Unicorn pHat example code: # https://github.com/pimoroni/unicorn-hat/blob/master/examples/random_blinky.py import colorsys import time from sys import exit import numpy import unicornhat as unicorn def flame(hue, duration): """ Flicker flame effect for...
the-stack_106_20379
from django.conf.urls import url from . import views urlpatterns = [ url( regex=r'^loadData/$', view=views.LoadData.as_view(), name='load_data' ), url( regex=r'^hClustering/$', view=views.HClustering.as_view(), name='h_clustering' ), url( rege...
the-stack_106_20380
import os import io import discord import matplotlib.pyplot as plt from PIL import Image from gamestonk_terminal.helper_funcs import plot_autoscale from gamestonk_terminal.stocks.technical_analysis import finviz_model from gamestonk_terminal.config_plot import PLOT_DPI import discordbot.config_discordbot as cfg from ...
the-stack_106_20381
import os import numpy as np from srd import add_params_as_attr module_dir = os.path.dirname(os.path.dirname(__file__)) def create_stub(): lines = ['cerb', 'cesb', 'iprew'] return dict(zip(lines, np.zeros(len(lines)))) class policy: """ Mesures liées à la COVID-19. Permet de choi...
the-stack_106_20383
# # # from __future__ import absolute_import, division, print_function, \ unicode_literals from mock import Mock, call from os.path import dirname, join from requests import HTTPError from requests_mock import ANY, mock as requests_mock from unittest import TestCase from octodns.record import Record from octodn...
the-stack_106_20386
from CyberSource import * import os import json from importlib.machinery import SourceFileLoader config_file = os.path.join(os.getcwd(), "data", "Configuration.py") configuration = SourceFileLoader("module.name", config_file).load_module() # To delete None values in Input Request Json body def del_none(d): for ke...
the-stack_106_20390
from datetime import datetime from pandas.core.frame import DataFrame def parse_date(date: str): return datetime.strptime(date, '%m/%d/%y').isoformat() def parse_column_name(column: str): return column.split("(")[0].strip().replace(" ", "_").lower() def parse_boolean(string: str): return True if strin...
the-stack_106_20391
# Copyright 2019 Neural Networks and Deep Learning lab, MIPT # # 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 applicab...
the-stack_106_20394
from MOON_RouteRiderVanClass import * import networkx as nx import datetime as dt class Sim(object): def __init__(self, startTime, vehicles, riders, graph, timeDict, waitCoeff, driveCoeff, timeWindow, maxUberWaitTime): self.time = startTime # Start time is at 6:00am self.vehiclesDict = vehicles ...
the-stack_106_20397
# Always prefer setuptools over distutils from setuptools import setup, find_packages from os import path # io.open is needed for projects that support Python 2.7 # It ensures open() defaults to text mode with universal newlines, # and accepts an argument to specify the text encoding # Python 3 only projects can skip ...
the-stack_106_20400
import discord import meille_secret as secret import os import random from discord.ext import commands from modules.meille_settings import Settings as settings async def get_prefix (bot, msg): return settings.get_config (config, msg.guild.id) ['prefix'] intents = discord.Intents.default () intents.members = True bo...
the-stack_106_20401
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('records', '0006_auto_20170524_1851'), ] operations = [ migrations.CreateModel( name='Message', field...
the-stack_106_20402
#!/usr/bin/python # -*- coding: utf-8 -*- try: from PyQt5.QtGui import * from PyQt5.QtCore import * except ImportError: from PyQt4.QtGui import * from PyQt4.QtCore import * from libs.utils import distance import sys DEFAULT_LINE_COLOR = QColor(0, 255, 0, 128) DEFAULT_FILL_COLOR = QColor(255, 0, 0, 1...
the-stack_106_20404
# -*- coding: utf-8 -*- # # Copyright 2017 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 requir...
the-stack_106_20405
import numpy as np from OperatorBase import * class OAdd(TwoOperandOperator): def __init__(self,Name=""): super().__init__(Name) def Calculate(self): TensorInput1=self.Inputs[0] TensorInput2=self.Inputs[1] #print(TensorInput1.Data.shape) #print(TensorInput2.Data.shape) ...
the-stack_106_20406
#!/usr/bin/python3 from argparse import ArgumentParser from multiprocessing import Pool, cpu_count, Value from time import sleep from moviepy.editor import ( ImageClip, VideoFileClip, concatenate_videoclips, AudioFileClip, afx, CompositeAudioClip, ) from os import listdir, makedirs ...
the-stack_106_20409
# Copyright 2019 Red Hat, 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 ...
the-stack_106_20410
#!/usr/bin/env python from __future__ import unicode_literals, print_function import sys import sqlite3 from prompt_toolkit import PromptSession from prompt_toolkit.completion import WordCompleter from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.styles import Style from pygments.lexers import SqlLex...
the-stack_106_20411
""" A commandline tool for testing if RDF graphs are isomorpic, i.e. equal if BNode labels are ignored. """ from rdflib.graph import Graph from rdflib import BNode try: from itertools import combinations assert combinations except ImportError: # Python == 2.5 # Copied from # http://docs.python.org/2/l...
the-stack_106_20413
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import cv2 import logging project_path = '/Downloads/GL' def load_train_test_data(): pathToTrainData = 'Dataset/Car Images/Train Images' cars_train_data = load_data(pathToTrainData) logging.info("cars_train_data loaded and b...
the-stack_106_20414
#!/usr/bin/env python # -*- coding: utf-8 -*- # # finpie - a simple library to download some financial data # https://github.com/peterlacour/finpie # # Copyright (c) 2020 Peter la Cour # # Licensed under the MIT License # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software an...
the-stack_106_20418
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Copyright (c) 2018-2021 The CSPN Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node disconnect and ban behavior""" import time...
the-stack_106_20419
from kiwi.database.DataAccessor import DataAccessor import numpy import math class ActivationCalculator: def __init__(self, heuristics, data_accessor: DataAccessor): self.heuristics = heuristics self.accessor = data_accessor def g(self, x): return math.exp(-3.0*x)*100.0 def f...
the-stack_106_20421
import torch from ..logging.logger import Logger from ..losses.loss import DiscriminatorLoss, GeneratorLoss from ..models.model import Discriminator, Generator from .base_trainer import BaseTrainer __all__ = ["ProximalTrainer"] class ProximalTrainer(BaseTrainer): r"""Standard Trainer for various GANs. This has ...
the-stack_106_20422
# Embedded player in Armory Space import bpy from bpy.types import Header from bpy.app.translations import contexts as i18n_contexts import arm.utils import arm.make as make import arm.make_state as state import arm.log as log class ArmorySpaceHeader(Header): bl_space_type = 'VIEW_ARMORY' def draw(self, conte...
the-stack_106_20424
import unittest import pathlib from sourcehold.maps.sections.tools import TileIndexTranslator from sourcehold.maps.sections.types import TileSystem from sourcehold import load_map, expand_var_path import random class TestCoordinates(unittest.TestCase): def test_tile_index_translator(self): m = load_ma...
the-stack_106_20426
### # M4cs Keymap for dekuNukem/duckyPad QMK firmware # Copyright (C) 2020 Max Bridgland # 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)...
the-stack_106_20429
import os import sys import shutil from zipfile import ZipFile import sys sys.path.append("../") from lib.Version import VERSION baseTargetDir = "./build/dist/bundle/" targetDir = baseTargetDir + "pack/VGC_Analyze/" if os.path.exists(baseTargetDir): shutil.rmtree(baseTargetDir) if not os.path.exists(target...
the-stack_106_20430
"""Common methods used across tests for Bond.""" from typing import Any, Dict from homeassistant import core from homeassistant.components.bond.const import DOMAIN as BOND_DOMAIN from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST from homeassistant.setup import async_setup_component from tests.async_mock im...
the-stack_106_20431
from argparse import Namespace import csv from logging import Logger import pickle import random from typing import List, Set, Tuple import os from rdkit import Chem import numpy as np from tqdm import tqdm from .data import MoleculeDatapoint, MoleculeDataset from .scaffold import log_scaffold_stats, scaffold_split f...
the-stack_106_20432
#! /usr/bin/env python3 import math # QR分解の結果を比較する fout = open('../../InverceMatrix2/InverceMatrix2.sim/sim_1/behav/result.txt', 'r') fref = open('ref.txt', 'r') ok = True line_no = 1 lout = fout.readline() while lout: # シミュレーション結果を読み込む results = lout[:-1].split(' ') val = int(results[0], 16) # 負の値に対...
the-stack_106_20433
from itertools import islice from typing import Dict, Iterable, List, Union from modelforge import merge_strings, Model, register_model, split_strings import numpy from sourced.ml.models.license import DEFAULT_LICENSE @register_model class DocumentFrequencies(Model): """ Document frequencies - number of tim...
the-stack_106_20434
import os import torch import wandb from torch import nn import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from data.ljspeech import get_dataset from data.transforms import ( MelSpectrogram, Compose, AddLengths, Pad, TextPreprocess, ToNumpy, AudioSqueeze, ToGpu) from data.collate ...
the-stack_106_20435
#============================================================================================================= # Imports import os import bpy import codecs import xml.etree.ElementTree as ET from struct import unpack #====================================================================================================...
the-stack_106_20437
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import torch # Config that serves all environment GLOBAL_CONFIG = { "MODEL_PATH": "../model/model.pt", "SCALAR_PATH": "../model/scaler.joblib", "USE_CUDE_IF_AVAILABLE": True, "ROUND_DIGIT": 6 } # Environment specific config, or overwrite of GLO...
the-stack_106_20438
import curses, traceback, string, os import dmTxt2Html #-- Define the appearance of some interface elements hotkey_attr = curses.A_BOLD | curses.A_UNDERLINE menu_attr = curses.A_NORMAL #-- Define additional constants EXIT = 0 CONTINUE = 1 #-- Define default conversion dictionary cfg_dict = {'target': 'DEFAULT.HTML',...
the-stack_106_20439
#!/usr/bin/env python import os import numpy as np from tqdm import tqdm from OPTIMAS.utils.files_handling import images_list, read_image_size def merge_npy(input_data_folder, experiment): """ merge all the individual npy files into one bigger file for faster I/O """ path_input_npy_folder = f"{input_...
the-stack_106_20440
import mail1 from equipment.framework.Log.AbstractLog import AbstractLog from equipment.framework.Config.AbstractConfig import AbstractConfig from equipment.framework.Mail.AbstractMail import AbstractMail from typing import Union from equipment.framework.Mail.Email.Email import Email from equipment.framework.Mail.Email...
the-stack_106_20441
# Copyright 2017 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_106_20442
#!/usr/bin/env python3 # Created: 06.2020 # Copyright (c) 2020, Matthew Broadway # License: MIT License import argparse import signal import sys from functools import partial from typing import Optional from PyQt5 import QtWidgets as qw, QtCore as qc, QtGui as qg import ezdxf from ezdxf.addons.drawing import Frontend...
the-stack_106_20443
#!/usr/bin/env python # Copyright Contributors to the OpenCue Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
the-stack_106_20445
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
the-stack_106_20446
""" ==================================== Probabilistic Tracking on ODF fields ==================================== In this example we perform probabilistic fiber tracking on fields of ODF peaks. This example requires importing example `reconst_csa.py`. """ import numpy as np from reconst_csa import * from dipy.rec...
the-stack_106_20447
import numpy as np from logging import getLogger from PIL import Image logger = getLogger(__name__) def resize(x): """ 画像サイズが最低値以下の場合に最低値に拡大する """ width, height = 96, 96 x_out = [] for i in range(len(x)): img = x[i].reshape(x[i].shape[:-1]) img = Image.fromarray((img * 255).ast...
the-stack_106_20450
# coding: utf-8 """ Yapily API To access endpoints that require authentication, use your application key and secret created in the Dashboard (https://dashboard.yapily.com) # noqa: E501 OpenAPI spec version: 0.0.155 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pp...
the-stack_106_20452
#!/usr/bin/env python3 # # Copyright (c) 2019, AT&T Intellectual Property. # Copyright (c) 2015 Brocade Communications Systems, Inc. # All Rights Reserved. # # # Copyright (c) 2019, AT&T Intellectual Property. # # SPDX-License-Identifier: GPL-2.0-only from vplaned import Controller from collections import Counter, def...
the-stack_106_20453
import numpy as np from trainLinearReg import trainLinearReg from linearRegCostFunction import linearRegCostFunction def validationCurve(X, y, Xval, yval): """returns the train and validation errors (in error_train, error_val) for different values of lambda. You are given the training set (X, y) and ...
the-stack_106_20458
""" conftest ~~~~~~~~ Test fixtures and what not :copyright: (c) 2017 by CERN. :copyright: (c) 2019-2022 by J. Christopher Wagner (jwag). :license: MIT, see LICENSE for more details. """ import os import tempfile import time import typing as t from datetime import datetime from urllib.parse i...
the-stack_106_20459
"""Connection configuration =========================== .. highlight:: ini Every sparkplug instance is attached to a single ``connection``, usually named ``main``. The connection contains all the information necessary to connect to a single AMQP broker. The simplest possible connection is:: [connection:main] w...
the-stack_106_20460
import os import json from collections import namedtuple import copy # IF_RESET_TFGRAPH_SESS_RUN = False TF_DATASET_TO_NUMPY_MODE = "graph" # eager/graph # # autodl_global_config = { "meta_solution": { "cv_solution": "DeepWisdom", "nlp_solution": "upwind_flys", "speech_solution": "PASA_NJU...
the-stack_106_20463
#!/usr/bin/env python3 from qiime2 import Artifact def main(input_type, input_path, input_format, output_path): imported_artifact = Artifact.import_data( input_type, input_path, view_type=input_format ) imported_artifact.save(output_path) if __name__ == "__main__": INPUT_TYPE = "SampleData[...
the-stack_106_20464
import asyncio from aiokafka.consumer import AIOKafkaConsumer from aiokafka.errors import ConsumerStoppedError, NoOffsetForPartitionError from aiokafka.util import create_task from ._testutil import ( KafkaIntegrationTestCase, run_until_complete, random_string) class TestConsumerIteratorIntegration(KafkaIntegrati...
the-stack_106_20465
import numpy as np import string from nltk.corpus import stopwords from nltk.stem import PorterStemmer import sys, unicodedata import random table = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(unichr(i)).startswith('P')) english_stopwords = stopwords.words('english') english_stopwords ...
the-stack_106_20466
#!/usr/bin/env python3 import json import sys import os import argparse import amp.utils from amp.schema.speech_to_text import SpeechToText, SpeechToTextMedia, SpeechToTextResult # Convert kaldi output to standardized json def convert(media_file, kaldi_file, kaldi_transcript_file, output_json_file): amp.utils.exc...
the-stack_106_20467
# RT - Force Pinned Message from typing import Tuple, Dict, List from discord.ext import commands, tasks import discord from collections import defaultdict from rtlib import DatabaseManager from ujson import loads, dumps class DataManager(DatabaseManager): TABLE = "ForcePinnedMessage" def __init__(self, ...
the-stack_106_20469
import pymysql # input as grid list grid_list = ['23423444','7541496', '02343444', '00111122'] def select_grid_from_infos(cursor, grid_list): grid_list_str = ', '.join(grid_list) print(grid_list_str) query_list = ['SELECT * FROM infos'] query_list.append(f'WHERE grid_id IN ({grid_list_str})') q...
the-stack_106_20471
# Copyright 2017 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_106_20473
import numpy as np import visgeom as vg import matplotlib import matplotlib.pyplot as plt from pylie import SE3 """Exercise 2 - Estimate the mean pose from a set of random poses""" def draw_random_poses(mean_pose, cov_pose, n=100): """Draw random poses from a pose distribution. :param mean_pose: The mean pos...
the-stack_106_20476
#/!/usr/bin/env python3 import time import json import jwt from pathlib import Path import random, string from datetime import datetime, timedelta from common.api import api_get from common.params import Params from common.spinner import Spinner from common.basedir import PERSIST from selfdrive.controls.lib.alertmanag...
the-stack_106_20477
''' notebookutils.py 2012 Brandon Mechtley Arizona State University A few helpful routines for using IPython notebook. ''' from IPython.core.pylabtools import print_figure from IPython.core.display import display, HTML, Math, Latex from sympy import Matrix, latex import numpy as np def limitprec(m, prec=3): ''...
the-stack_106_20479
import time import sqlalchemy as tsa from sqlalchemy import create_engine from sqlalchemy import event from sqlalchemy import exc from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import pool from sqlalchemy import select from sqlalchemy import String from sqlalchemy import testing from sq...
the-stack_106_20481
# -*- 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_106_20482
import argparse import logging import os import os.path as osp import subprocess import time import torch import torch.utils.data as data import torchvision.transforms.functional as F from PIL import Image from tqdm import tqdm from trainer.ExtensibleTrainer import ExtensibleTrainer from utils import options as optio...
the-stack_106_20483
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from collections import OrderedDict from typing import Any, Callable, Dict, List, MutableMapping, Optional, T...
the-stack_106_20484
import os import glob import sys from matplotlib import pyplot as plt from PIL import Image import cv2 import numpy as np import yolo import fhi_unet as unet import fhi_lib.distance_estimator as de import fhi_lib.img_coordinate as ic import fhi_lib.geometry as ge def yolo_detection(user_input): img_dir = os.path.jo...
the-stack_106_20486
# 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 "License");...
the-stack_106_20488
from __future__ import print_function, division import torch from torchvision import datasets, models, transforms import torch.nn as nn from torch.nn import functional as F import torch.optim as optim import torchvision import numpy as np import matplotlib.pyplot as plt from PIL import Image from torch.utils.data impor...
the-stack_106_20489
# Problem: https://projecteuler.net/problem=227 """ . Define distance as the clockwise number of people between the dice. . Use the distance between the dices as a state. . Use Markov chain to track the probabilities. . T[distance1][distance2] is the probability of transitioning from distance 1 to distance 2 ...
the-stack_106_20490
def getMinimumNumber(numbers): minNumber = numbers[0] for currentNumber in numbers: if currentNumber < minNumber: minNumber = currentNumber return minNumber def getMinimumIndex(numbers): minNumber = numbers[0] currentIndex = 0 minIndex = currentIndex for currentNumber in...