filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_19978 | # -*- coding: utf-8 -*-
"""Some miscellaneous utility functions."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import fnmatch
import inspect
from io import StringIO
import logging
from math import log
import os
from string import Formatter
import subprocess
import sys
impor... |
the-stack_106_19979 | import json
import logging
import math
import pathlib
from carim.configuration import decorators
from carim.configuration.mods.trader.models import config, objects
from carim.global_resources import types, matching_model, resourcesdir
from carim.util import file_writing
log = logging.getLogger(__name__)
class Trade... |
the-stack_106_19980 | import operator as ops
import numpy as np
import pytest
import taichi as ti
from taichi import allclose
binary_func_table = [
(ops.add, ) * 2,
(ops.sub, ) * 2,
(ops.mul, ) * 2,
(ops.truediv, ) * 2,
(ops.floordiv, ) * 2,
(ops.mod, ) * 2,
(ops.pow, ) * 2,
(ops.and_, ) * 2,
(ops.or_,... |
the-stack_106_19983 | '''
Quick way to gather sites using Teamtailor with Google Custom Search API.
Note this is limited by Google to 100 entries, meaning max 10 pages with 10 results each page.
'''
## Loads key from single line keyfiles
def load_key(filename=''):
if not filename: return None
with open(filename, 'r') as f:
... |
the-stack_106_19984 | import filecmp
import os
import subprocess
from tests import TESTS, SAMPLE_WHITELISTS
from vulture_whitelist import __version__
def create_whitelist_from_test_sip_files(name):
path = os.path.join(TESTS, 'test-data', 'sip')
subprocess.call(['vulture-whitelist', 'sip', '--name', name], cwd=path)
def test_qt_... |
the-stack_106_19986 | from tronx import app, gen
from pytube import YouTube
from pyrogram.types import Message
app.CMD_HELP.update(
{"utube": (
"utube",
{
"yvinfo [link]" : "Get a youtube video information . . .",
"yvdl [link]" : "Download any video from YouTube . . ."
}
)
}
)
@app.on_message(gen("yvinfo", allow = ["s... |
the-stack_106_19988 | from collections import deque
from utils import stringify, get_collection_or_data_object, find_children
from irods_cli import cli
import click
from irods.collection import iRODSCollection
@cli.command()
@click.argument('path')
@click.option('--recursive','-R', is_flag=True,
help='use a long listing form... |
the-stack_106_19991 | ''' Proxlight Designer - Created By Pratyush Mishra (Proxlight)'''
from tkinter import *
from tkinter import filedialog, messagebox
############################################################################
import requests
import os
def generate_code(token, link, output_path):
def get_col... |
the-stack_106_19994 | """A setuptools based setup module.
See:
https://packaging.python.org/guides/distributing-packages-using-setuptools/
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
# Get th... |
the-stack_106_19997 | import unittest
import operator
import types
from saucebrush.filters import (Filter, YieldFilter, FieldFilter,
SubrecordFilter, ConditionalPathFilter,
ConditionalFilter, FieldModifier, FieldKeeper,
FieldRemover, FieldMerger,... |
the-stack_106_19998 | # Author: Markus Böck
import numpy as np
import pandas as pd
import os
import re
import csv
import datetime
class IICF:
def __init__(self, path_to_data, dataset_type):
self.path_to_data = path_to_data
expanded_path = os.path.expanduser(path_to_data)
part_files = [os.path.join(expa... |
the-stack_106_19999 | import pytest
from thinc.api import chain, ReLu, reduce_max, Softmax, with_ragged
from thinc.api import ParametricAttention, list2ragged, reduce_sum
from thinc.util import DataValidationError
def test_validation():
model = chain(ReLu(10), ReLu(10), with_ragged(reduce_max()), Softmax())
with pytest.raises(Data... |
the-stack_106_20002 | # protobuf_parser.py
#
# simple parser for parsing protobuf .proto files
#
# Copyright 2010, Paul McGuire
#
from pyparsing import (Word, alphas, alphanums, Regex, Suppress, Forward,
Group, oneOf, ZeroOrMore, Optional, delimitedList, Keyword,
restOfLine, quotedString, Dict)
ident = Word(alphas+"_"... |
the-stack_106_20003 | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import autograd
from models.layers import MLP
from models.reparam import NormalDistributionLinear
from utils import loss_kld_gaussian, loss_recon_gaussian, normal_energy_func
from utils import logprob_gaussian... |
the-stack_106_20004 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=19
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
class Opty(cirq.PointOptimizer):
def optimization_at(
... |
the-stack_106_20005 | from litex.build.generic_platform import *
from litex.build.lattice import LatticePlatform
from litex.build.openfpgaloader import OpenFPGALoader
from litex.soc.cores.bitbang import I2CMaster
from ..crg_ecp5 import CRG
from litespi.opcodes import SpiNorFlashOpCodes as Codes
from ..flash_modules import S25FL064L
from... |
the-stack_106_20007 | from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QVBoxLayout
import sys
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
layout = QVBoxLayout()
button1 = QPushButton()
button1.setText("Show dialog!")
button1.move(50,50)
bu... |
the-stack_106_20011 | ##########################################################################
#
# Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
# Copyright (c) 2012, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided t... |
the-stack_106_20012 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# robot_randomsearch.py
# Contact (ce fichier uniquement): nicolas.bredeche(at)upmc.fr
#
# Description:
# Template pour robotique evolutionniste simple
# Ce code utilise pySpriteWorld, développé par Yann Chevaleyre (U. Paris 13)
#
# Dépendances:
# Python 3.x
# ... |
the-stack_106_20014 | """
Utility functions that may prove useful when writing an ACME client.
"""
import uuid
from datetime import datetime, timedelta
from functools import wraps
from acme import jose
from acme.jose.errors import DeserializationError
from cryptography import x509
from cryptography.hazmat.backends import default_backend
fr... |
the-stack_106_20015 | import os
import pathlib
import deepdiff
import inflection
import pytest
import mlrun
import mlrun.errors
import mlrun.projects.project
import tests.conftest
def test_sync_functions():
project_name = "project-name"
project = mlrun.new_project(project_name)
project.set_function("hub://describe", "describ... |
the-stack_106_20016 | #!/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_106_20019 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
the-stack_106_20021 | from requests_html import HTMLSession
import mechanicalsoup
session = HTMLSession()
browser = mechanicalsoup.StatefulBrowser()
browser.addheaders = [('User-agent', 'Firefox')]
class Profile:
"""
Parse twitter profile and split informations into class as attribute.
Attributes:
- name... |
the-stack_106_20022 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('orders', '0007_usercheckout_braintree_id'),
]
operations = [
migrations.AddField(
model_name='order',
... |
the-stack_106_20024 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
class FluxCore(AutotoolsPackage):
""" A next-generation resource manager (pre-alpha) "... |
the-stack_106_20025 | #!/usr/bin/env python3
# pylint: disable=unused-wildcard-import
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox # Why
import tkbetter as tkb
import subprocess as sp
from pathlib import Path
from threading import Thread
from time import sleep
class LogWindow(tkb.Window):
def __init_... |
the-stack_106_20026 | import os
import paramiko
import string
import random
from common import log_orig as contrail_logging
from common.contrail_test_init import ContrailTestInit
logger = contrail_logging.getLogger('auth')
class Util:
templates = {
'pod': '/var/tmp/templates/pod.yaml',
'deployment': '/var/tmp/template... |
the-stack_106_20027 | ##############################################################################
#
# Copyright (c) 2010 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
the-stack_106_20028 | #!/usr/bin/env python
import os
from setuptools import setup
# load __version__
exec(open('trimesh/version.py').read())
long_description = ''
if os.path.exists('README.md'):
with open('README.md', 'r') as f:
long_description = f.read()
setup(name='trimesh',
version=__version__,
description=... |
the-stack_106_20029 | # -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
the-stack_106_20031 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
the-stack_106_20032 | # Copyright (c) 2021 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 appli... |
the-stack_106_20034 | # -*- coding: utf-8 -*-
"""Tools for handling LaTeX.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010 IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, ... |
the-stack_106_20036 |
#1 - Import library
import pygame, sys
import os
import math
import random
from pygame.locals import *
#2 - Initialize game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = [False, False, False, False, False]
playerpos = [150, 100]
acc=[0,0]
hats=[]
... |
the-stack_106_20037 | """
SVB - Model parameters
This module defines a set of classes of model parameters.
The factory methods which create priors/posteriors can
make use of the instance class to create the appropriate
type of vertexwise prior/posterior
"""
try:
import tensorflow.compat.v1 as tf
except ImportError:
import tensorfl... |
the-stack_106_20038 | # Bizzaro Francesco
# March 2020
#
# This script can be used to plot
# the results of all the GAs executed.
from matplotlib import pyplot as plt
import json
import datetime
import numpy as np
from math import exp,pow
from operator import add
mean_sing_best = []
mean_sing_avg = []
mean_coop_best = []
mean_coop_avg = [... |
the-stack_106_20039 | from flask import Flask, render_template, request, make_response, g
from redis import Redis
import os
import socket
import random
import json
option_a = os.getenv('OPTION_A', "Jubilee")
option_b = os.getenv('OPTION_B', "Sabretooth")
hostname = socket.gethostname()
app = Flask(__name__)
def get_redis():
if not ha... |
the-stack_106_20040 | """
Export CAT12 segmentation results as an xarray dataset.
"""
from typing import Dict, List
import dask.array as da
import nibabel as nib
import pandas as pd
import xarray as xr
from django.db.models import QuerySet
from django_mri.analysis.automation.cat12_segmentation.utils import (
get_node, get_run_set, rea... |
the-stack_106_20047 | import multiprocessing as mp
"""
Refer: Shared memory in multiprocessing
https://stackoverflow.com/questions/14124588/shared-memory-in-multiprocessing
https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes
"""
import time
import numpy as np
def process1(num, ary):
prin... |
the-stack_106_20048 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
the-stack_106_20049 | import json
import logging
import queue
import re
import socket
import ssl
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from threading import Event, RLock, Thread
from time import monotonic as now, sleep
from typing import Callable, List, Dict, Match, Optional, Pattern, Tuple, Uni... |
the-stack_106_20050 | """Utils for minibatch SGD across multiple RLlib policies."""
import numpy as np
import logging
from collections import defaultdict
import random
from ray.rllib.evaluation.metrics import LEARNER_STATS_KEY
from ray.rllib.policy.sample_batch import SampleBatch, DEFAULT_POLICY_ID, \
MultiAgentBatch
logger = logging... |
the-stack_106_20052 | import sys
import psana
from libtbx.phil import parse
from scitbx.array_family import flex
from dxtbx.format.FormatXTC import FormatXTC, locator_str
try:
from xfel.cxi.cspad_ana import rayonix_tbx
except ImportError:
# xfel not configured
pass
rayonix_locator_str = """
rayonix {
bin_size = None
... |
the-stack_106_20057 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import python libs
import re
import json
import argparse
import json
import random
import math
import os
import copy
import sys
from os import listdir
from os.path import isfile, join
from pprint import pprint as pp
# import project libs
sys.path.append('../Auswertun... |
the-stack_106_20059 | import json
import requests
from urllib.parse import urlencode
from zohocrm.exceptions import UnknownError, InvalidModuleError, NoPermissionError, MandatoryKeyNotFoundError, \
InvalidDataError, MandatoryFieldNotFoundError
BASE_URL = 'https://www.zohoapis.com/crm/v2/'
ZOHOCRM_AUTHORIZE_URL = 'https://accounts.zoho... |
the-stack_106_20062 | # Authors:
# Christian F. Baumgartner (c.f.baumgartner@gmail.com)
import tensorflow as tf
import numpy as np
from math import sqrt
def flatten(tensor):
'''
Flatten the last N-1 dimensions of a tensor only keeping the first one, which is typically
equal to the number of batches.
Example: A tensor of ... |
the-stack_106_20064 | #
# 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... |
the-stack_106_20065 | from __future__ import absolute_import, division, print_function
import io
import itertools
import math
import uuid
import warnings
from collections import defaultdict
from distutils.version import LooseVersion
from functools import wraps, partial
from operator import getitem
from random import Random
from toolz impo... |
the-stack_106_20067 | # mpirun -np 16 --ppn 16 python slowtest_performance_aposmm_only.py
# Should run in under 20 sec
import os
import sys
import numpy as np
import networkx as nx
import pickle
from functools import partial
from qiskit.optimization.ising.max_cut import get_operator as get_maxcut_operator
import scipy
from variationaltoolk... |
the-stack_106_20070 | """Support for Met.no weather service."""
from __future__ import annotations
import logging
from types import MappingProxyType
from typing import Any
import voluptuous as vol
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TIME,
ATTR_WEATHER_H... |
the-stack_106_20071 | from sphinx_testing import with_app
@with_app(buildername="html", srcdir="./tests/examples", copy_srcdir_to_tmpdir=True)
def sphinx_build(app, status, warning):
app.build()
with open(app.outdir + "/index.html", "r") as f:
html = f.read()
assert "python test.py -h" in html
assert "No such file ... |
the-stack_106_20074 | """
Implementation of a simple digital digit detector for thermometers
Author: Corentin Chauvin-Hameau
Date: 2021
License: Apache-2.0 License
"""
from math import atan2, degrees, pi, nan
import numpy as np
import cv2
import imutils
class DigitalDetector:
"""
Simple digital digit detector... |
the-stack_106_20075 | from __future__ import annotations
import numpy as np
from pandas._libs import (
lib,
missing as libmissing,
)
from pandas._typing import DtypeObj
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
is_bool_dtype,
is_float_dtype,
is_integer_dtype,
is_obj... |
the-stack_106_20076 | # -*- coding: utf-8 -*-
import csv
from operator import itemgetter
rent_file = open('tashu.csv', 'r')
station_file = open('station.csv', 'r')
tashu_dict = csv.DictReader(rent_file)
station_dict = csv.DictReader(station_file)
gu_dict = {'유성구': 0, '서구': 0, '대덕구': 0, '중구': 0, '동구': 0}
station_list = [{}]
for info in s... |
the-stack_106_20078 | # Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import pytest
from mmdet.ops.nms.nms_wrapper import get_nms_from_type
def test_get_nms_op_for_unsupported_type():
nms_type = 'definitely_not_nms_type'
with pytest.raises(RuntimeError):
get_nms_from_type(nms_type)
@py... |
the-stack_106_20081 | import argparse
import copy
import pickle
import datetime
import time
import shutil
import sys
import git
import os
import numpy as np
from multiprocessing import Pool
from multiprocessing import Manager
import core
import graph
import plots
import routing_policies
import restoration_policies
import logging
logging.b... |
the-stack_106_20084 | import RPi.GPIO as GPIO
from time import sleep
import subprocess
import sys
import pygame.mixer
pygame.mixer.init()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.output(11, False)
GPIO.output(12, False)
def detect():
"""Detects qr code from camera and returns string that represen... |
the-stack_106_20085 | import logging
import time
import os
import sys
import click
import click_log
import tqdm
import pysam
from construct import *
from ..utils import bam_utils
from ..annotate.command import get_segments
logging.basicConfig(stream=sys.stderr)
logger = logging.getLogger("extract")
click_log.basic_config(logger)
@clic... |
the-stack_106_20087 | #!/usr/bin/env python
# coding: utf-8
import sys
import setuptools
PACKAGE_NAME = 'pycsvsql'
MINIMUM_PYTHON_VERSION = '3.6'
def check_python_version():
"""Exit when the Python version is too low."""
if sys.version < MINIMUM_PYTHON_VERSION:
sys.exit("Python {0}+ is required.".format(MINIMUM_PYTHON_V... |
the-stack_106_20088 | # -*- coding: utf-8 -*-
import os
from datetime import datetime
import pandas as pd
import scrapy
from scrapy import Request
from scrapy import signals
from fooltrader.api.technical import parse_shfe_data, parse_shfe_day_data
from fooltrader.contract.files_contract import get_exchange_cache_dir, get_exchange_cache_p... |
the-stack_106_20089 | # Copyright 2018 Davide Spadini
#
# 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_20090 | _base_ = [
'../_base_/models/dpt_vit-b16.py','../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py','../_base_/schedules/schedule_160k.py'
]
model = dict(
backbone=dict(drop_path_rate=0.1, final_norm=True),
decode_head=dict(num_classes=150),
auxiliary_head=dict(num_classes=150),
test_c... |
the-stack_106_20095 | import os
import oneflow.experimental as flow
import argparse
import numpy as np
import time
from utils.data_utils import load_image
from utils.utils import to_numpy, to_tensor, save_images
from models.networks import Generator
def main(args):
test_x, test_y = load_image(args.image_path)
test_inp = to_tensor... |
the-stack_106_20096 | import unittest
import numpy
try:
import scipy.sparse # NOQA
scipy_available = True
except ImportError:
scipy_available = False
import cupy
import cupy.sparse
from cupy import testing
def _make(xp, sp, dtype):
data = xp.array([[0, 1, 2], [3, 4, 5]], dtype)
offsets = xp.array([0, -1], 'i')
... |
the-stack_106_20097 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from siem import utils
def transform(logdata):
identifier = utils.cluster_instance_identifier(logdata)
logdata['rds']['cluster_identifier'] = identifier['cluster']
logdata['rds']['instance_identifier'] =... |
the-stack_106_20100 | import _plotly_utils.basevalidators
class HovertextValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name='hovertext', parent_name='pie', **kwargs):
super(HovertextValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
the-stack_106_20101 | # originalString = str(input("Type in any string: "))
# You can use the input but for testing I used a predefined string
originalString = "Test"
def stringToAscii(string):
NumberDec = []
NumberBin = []
NumberHex = []
NumberOct = []
for i in string:
NumberBin.append(bin(ord(i)))
NumberHex.append(he... |
the-stack_106_20102 | """
This is (for instance) a Raspberry Pi only worker!
The libcamera project (in development), aims to offer an open source stack for
cameras for Linux, ChromeOS and Android.
It will be able to detect and manage all of the exposed camera on the system.
Connected via USB or CSI (Rasperry pi camera).
libcamera develope... |
the-stack_106_20104 | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import click
import pyperclip
from six import string_types
from ..console import (
CONTEXT_SETTINGS, abort, echo_failure, echo_info, echo_success, echo_waiting, echo_warning
)
from ...e2e import E2... |
the-stack_106_20105 | import tweepy
from pymongo import MongoClient
import time
# Get a cursor object
# CONSUMER_KEY = 'cwuOhOSiMHaqSjUsyfYRVltuE'
# CONSUMER_SECRET = 'JBZWaPi3ldDHgMo6NPr8MbRKEU2iHBW7xVzL094HjsoX33K4eJ'
# OAUTH_TOKEN = '842632842207203328-cNbwTaG4eW4rbQJwaG4RxtZkHJ51SoO'
# OAUTH_TOKEN_SECRET = 'IhypdlKWPYtpKJ8aWevWTPTyeTbt... |
the-stack_106_20108 | import datetime
#pegando ano de nascimento
anoUsu = int(input('Digite o seu ano de nascimento: '))
#ano atual
anoAtu = datetime.date.today().year
#calculo
calc = anoAtu - anoUsu
#validação das categorias
if calc <= 9:
print('Você está na categoria: \033[1;32mMIRIM')
elif calc > 9 and calc <= 14:
print('Você... |
the-stack_106_20111 | import os
from griddly import GymWrapperFactory, gd, GymWrapper
from griddly.RenderTools import VideoRecorder
if __name__ == "__main__":
wrapper = GymWrapperFactory()
name = "proximity_env"
current_path = os.path.dirname(os.path.realpath(__file__))
env = GymWrapper(
"proximity_env.yaml",
... |
the-stack_106_20112 | """
Example of running a Unity3D (MLAgents) Policy server that can learn
Policies via sampling inside many connected Unity game clients (possibly
running in the cloud on n nodes).
For a locally running Unity3D example, see:
`examples/unity3d_env_local.py`
To run this script against one or more possibly cloud-based cli... |
the-stack_106_20113 | import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep
def check_events(ai_settings,screen,ship,bullets,stats,play_button,aliens,sb):
#监视键盘和鼠标事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
... |
the-stack_106_20115 | # -*- coding: utf-8 -*-
from ....Classes.Arc1 import Arc1
from ....Classes.Arc3 import Arc3
from ....Classes.Segment import Segment
def build_geometry(self):
"""Compute the curve (Line) needed to plot the object.
The ending point of a curve is the starting point of the next curve
in the list
Paramet... |
the-stack_106_20116 | import model.m_mysql as db
from util.app_util import AppUtil
'''
账户历史信息表,记录账户每日现金资产和股票资产,以前一交易日收盘价
计算总现金资产
'''
class MAccountHist(object):
@staticmethod
def insert_account_hist(account_id, account_date,
cash_amount, stock_amount):
'''
向t_account_hist表中添加一条记录,记录用户某天的资产总值
... |
the-stack_106_20117 | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..registry import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.... |
the-stack_106_20119 | #!/usr/bin/env python2
from __future__ import unicode_literals
# Last.FM API libraries
import time
import urllib2
import json
# YouTube API libraries
import youtube_dl
from googleapiclient.discovery import build
# Playback libraries
from pydub import AudioSegment
from pydub.playback import play
from os import remove
... |
the-stack_106_20122 | import numpy as np
from pyQBTNs import QBTNs
### Steepest descent solver takes an arduous amount of time to compute. It should run fairly quickly for small ranks though.
qbtns = QBTNs(factorization_method="Matrix_Factorization", solver_method="classical-steepest-descent")
p = 0.5
N1 = 10
N2 = 10
RANK = 8
A = np.rand... |
the-stack_106_20123 | import torch.nn as nn
class HeightCompression(nn.Module):
def __init__(self, model_cfg, **kwargs):
"""
在高度方向上进行压缩
"""
super().__init__()
self.model_cfg = model_cfg
self.num_bev_features = self.model_cfg.NUM_BEV_FEATURES # 256
def forward(self, batch_dict):
... |
the-stack_106_20125 | """empty message
Revision ID: 0005 add team name to git_metric
Revises: 0004 use repo name not url
Create Date: 2019-01-25 15:09:08.178909
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0005 add team name to git_metric'
down_revision = '0004 use repo name not... |
the-stack_106_20126 | #!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import distutils.command.clean
import os
import shutil
import subprocess
import sys
from... |
the-stack_106_20132 | try:
from sql_helpers import SESSION, BASE
except ImportError:
raise AttributeError
from sqlalchemy import Column, String
class GMute(BASE):
__tablename__ = "gmute"
sender = Column(String(14), primary_key=True)
def __init__(self, sender):
self.sender = str(sender)
GMute.__table__.creat... |
the-stack_106_20133 | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import contextlib
import funsor
from pyro.contrib.funsor import to_data
from pyro.contrib.funsor.handlers import enum, plate, replay, trace
from pyro.contrib.funsor.infer.elbo import ELBO, Jit_ELBO
from pyro.contrib.funsor.infer.trac... |
the-stack_106_20135 | # -*- coding: utf-8 -*-
"""
=== 思路 ===
核心:每次落稳之后截图,根据截图算出棋子的坐标和下一个块顶面的中点坐标,
根据两个点的距离乘以一个时间系数获得长按的时间
识别棋子:靠棋子的颜色来识别位置,通过截图发现最下面一行大概是一条
直线,就从上往下一行一行遍历,比较颜色(颜色用了一个区间来比较)
找到最下面的那一行的所有点,然后求个中点,求好之后再让 Y 轴坐标
减小棋子底盘的一半高度从而得到中心点的坐标
识别棋盘:靠底色和方块的色差来做,从分数之下的位置开始,一行一行扫描,
由于圆形的块最顶上是一条线,方形的上面大概是一个点,所以就
用类似识别棋... |
the-stack_106_20136 | import numpy as np #necessary imports
import cv2
import time
import math
import serial
color=(255,0,0) #variable for contour color and thickness
thickness=2
cX = cY = 0 #centroid of ball contour
cap = cv2.VideoCapture(1) ... |
the-stack_106_20139 | import sqlite3 as sqlite3
from sqlite3 import Error
import os as os
class Project:
def __init__(self, db_file):
# Init connection
self.conn = None
# Create the database file
# If this is a new database file, create the tables
self.create_conn(db_file)
def create_con... |
the-stack_106_20141 | from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql import Row
#-----------------------------------------------------
# Create a DataFrame from a JSON file
# Input: JSON File
# In this example, there is one JSON object per line.
#-----------------------------------... |
the-stack_106_20142 | import asyncio
import functools
def event_handler(loop, stop=False):
print('Event handler called')
if stop:
print('stopping the loop')
loop.stop()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.call_soon(functools.partial(event_handler, loop))
pr... |
the-stack_106_20144 | from CommonServerPython import IncidentStatus, EntryType
response_incident = {"incident_id": "inc:afb5d1512a00480f53e9ad91dc3e4b55:1cf23a95678a421db810e11b5db693bd",
"cid": "24ab288b109b411aba970e570d1ddf58",
"host_ids": [
... |
the-stack_106_20145 | from discord.ext import commands
import os
import traceback
bot = commands.Bot(command_prefix='/')
token = os.environ['DISCORD_BOT_TOKEN']
@bot.event
async def on_command_error(ctx, error):
orig_error = getattr(error, "original", error)
error_msg = ''.join(traceback.TracebackException.from_exception(orig_er... |
the-stack_106_20150 | # Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2020 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... |
the-stack_106_20152 | import unittest
from transformers import XLMRobertaConfig
from transformers.testing_utils import require_torch
from .test_adapter import AdapterTestBase, make_config
from .test_adapter_conversion import ModelClassConversionTestMixin
@require_torch
class XLMRobertaClassConversionTest(
ModelClassConversionTestMix... |
the-stack_106_20153 | """Retrieve upstream datasets from a specified dataset."""
import argparse
from typing import List, Dict
import tamr_toolbox as tbox
from tamr_unify_client.dataset.resource import Dataset
def main(*, instance_connection_info: Dict[str, str], dataset_id: str) -> List[Dataset]:
"""Retrieve upstream datasets from ... |
the-stack_106_20157 | import abc
import json
import os
import traceback
import ray
import tensorflow as tf
class BaseEnsemble(abc.ABC):
"""Base class for ensembles, every new ensemble algorithms needs to extend this class.
Args:
model_dir (str): Path to directory containing saved Keras models in .h5 format.
... |
the-stack_106_20158 | import argparse
import ast
import sys
import traceback
import zmq
from mldebugger.utils import record_python_run
def workflow_function(kw_args, diagnosis):
clauses = []
for clause in diagnosis:
clauses.append("".join([' kw_args[\'%s\'] %s %s and' % (p,
... |
the-stack_106_20160 | from datetime import datetime, date, timedelta
import os
import pytz
import numpy as np
def quantile_sorted(sorted_arr, quantile):
# For small arrays (less than about 4000 items) np.quantile is significantly
# slower than sorting the array and picking the quantile out by index. Computing
# quantiles this w... |
the-stack_106_20161 | from datafaucet.metadata import reader
from datafaucet import paths
from datafaucet.utils import Singleton
import os
from textwrap import dedent
import pytest
from testfixtures import TempDirectory
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=4, sequence=4, offset=2)
... |
the-stack_106_20162 |
class QueryBuilder(object):
@staticmethod
def build(query_details):
if "columns" in query_details.keys():
num_columns = len(query_details["columns"])
select_stmt = 'SELECT ' + ", ".join(num_columns * ['{}'])
columns = query_details["columns"]
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.