filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_29343 | import warnings, numpy as np
from keras import backend as K
class IncreaseBSOnPlateau:
"""Increase batch size when a metric has stopped improving.
Models often benefit from increasing the batch size by a factor
of 2-10 once learning stagnates. This callback monitors a
quantity and if no improvement is ... |
the-stack_106_29345 | import os
from setuptools import setup
def get_version():
v = "0.0.0"
return v
setup(
name = "hivevo",
version = get_version(),
author = "Fabio Zanini and Richard Neher",
author_email = "richard.neher@unibas.ch",
description = ("HIVevo access"),
long_descriptio... |
the-stack_106_29347 |
import pandas as pd
import numpy as np
import pickle
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
nSamples = 400
trainSamples = int( 0.7*nSamples)
testSamples = int(0.1*nSamples)
valSamples = int(0.2*nSamples)
refinement = 1
lenGrid = 300
inputShape = 300
def getL... |
the-stack_106_29350 | r"""
Bijection between rigged configurations for `B(\infty)` and marginally large tableaux
AUTHORS:
- Travis Scrimshaw (2015-07-01): Initial version
REFERENCES:
.. [RC-MLT] Ben Salisbury and Travis Scrimshaw. *Connecting marginally
large tableaux and rigged configurations via crystals*.
Preprint. :arxiv:`1505... |
the-stack_106_29351 | from threading import Timer
import time
class Device:
def __init__(self, config, callback):
self.is_switch = False
self.input_outputs = {}
self.callback = callback
self.config = config
self.board = self.config["board_type"]
def read_value(self, callback=None):
data = {}
success = False
while not s... |
the-stack_106_29352 | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""
This script will prepare a release by:
- Generating the JSON and MO files for all language packages from PO files
- Update the contributors list
- Bumping the version
"""
# Standard library imports
import argparse... |
the-stack_106_29354 | # -*- coding: utf-8 -*-
import csv
import logging
import os.path
from functools import wraps
from html import escape
from io import StringIO
from itertools import chain
from time import time
import gevent
from flask import Flask, make_response, jsonify, render_template, request
from flask_basicauth import BasicAuth
f... |
the-stack_106_29355 | import math
import types
from typing import Optional, Union
import numba
import numba.experimental
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.compute as pc
from pandas.core.strings import StringMethods
from fletcher._algorithms import _extract_isnull_bitmap
from fletcher.algorithms.boo... |
the-stack_106_29356 | #!/usr/bin/env python
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Setup linked packages required for GGRC
"""
import subprocess
def run_shell(script):
proc = subprocess.Popen(script, shell=True, stdout=subprocess.PIPE)
proc.wait()
return ... |
the-stack_106_29358 | import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import xavier_init
from ..registry import NECKS
from ..utils import ConvModule
@NECKS.register_module
class FPN(nn.Module):
def __init__(self,
in_channels,
out_channels,
num_outs,
... |
the-stack_106_29359 | from inputs import Input
from urllib.parse import urljoin
from util.constants import PMS_WATCH_HISTORY, EB_NEW_SEEN_EP, bus
from util.video import Video, VideoType, VideoSchema
from joblib import Memory
import requests
import xml.etree.ElementTree as ET
import time
import re
import logging
import os
import discord
impo... |
the-stack_106_29360 | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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 requi... |
the-stack_106_29361 | class ShortMapExit():
DATA_SIZE = 0x06
def __init__(self):
self.x = 0
self.y = 0
def from_data(self, data):
assert(len(data) == self.DATA_SIZE)
self.x = data[0]
self.y = data[1]
self.dest_map = data[2] | (data[3] & 0x01) << 8
self.unknown = data[3] ... |
the-stack_106_29364 | import codecs
class Sia30Flagger():
def __init__(self):
self.sensitiveWords = ["جمهوری", "ج.ا", "اسلامی", "ایران", "مرگ", "جاعش", "خامنه", "احمدی نژاد",
"روحانی", "@azarijahromi", "اینا", "مجلس", "قوه قضاییه", "رئیس", "آخوند", "شاه ", "حجاب", "آمریکا"]
def filterSia30(... |
the-stack_106_29368 | # BSD 2-Clause License
#
# Copyright (c) 2021-2022, Hewlett Packard Enterprise
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright... |
the-stack_106_29370 | #
# Single Particle Model with Electrolyte (SPMe)
#
import pybamm
from .base_lithium_ion_model import BaseModel
class SPMe(BaseModel):
"""Single Particle Model with Electrolyte (SPMe) of a lithium-ion battery, from
[1]_.
Parameters
----------
options : dict, optional
A dictionary of optio... |
the-stack_106_29371 | import os
import numpy as np
import pandas as pd
from larval_gonad.io import pickle_load
def main():
fbgn2chrom = get_fbgn2chrom()
yogn2fbgn = pickle_load(snakemake.input.orthologs)
adult_counts = get_counts(yogn2fbgn)
df = (
adult_counts.reset_index()
.melt(id_vars="FBgn", var_name=... |
the-stack_106_29373 | import os
from os.path import join
from .. import run_nbgrader
from .base import BaseTestApp
from .conftest import notwindows
@notwindows
class TestNbGraderFetch(BaseTestApp):
def _release(self, assignment, exchange, course_dir, course="abc101"):
self._copy_file(join("files", "test.ipynb"), join(course_... |
the-stack_106_29374 | """Stuff that differs in different Python versions and platform
distributions."""
# The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
import codecs
import locale
import logging
import os
import sys
from pip._internal.utils.typing import M... |
the-stack_106_29375 | #!/usr/bin/env python
from __future__ import division
import random
import math
import numpy as np
def process_statistics(F):
Flux1 = np.zeros(128)
Flux2 = np.zeros(128)
Flux1_squared = np.zeros(128)
Flux2_squared = np.zeros(128)
Current1 = np.zeros(129)
Current2 = np.zeros(129)
Current1_squared = np.zeros(12... |
the-stack_106_29376 | # Copyright 2019 The Feast 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 law or agreed to in wr... |
the-stack_106_29377 | # Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import numpy as np
import sys,json,os
import numpy.random as rnd
try:
import itimer as it
now = it.itime
get_mops = it.itime_mops_now
except:
from timeit import default_timer
now = default_timer
get_mops = lambda t0,... |
the-stack_106_29378 | #
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
from mlos.Exceptions import PointOutOfDomainException
from mlos.Spaces.Dimensions.Dimension import Dimension
from mlos.Spaces.Hypergrid import Hypergrid
from mlos.Spaces.Point import Point
class SimpleHypergrid(Hypergrid):
"""... |
the-stack_106_29380 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... |
the-stack_106_29382 | #!/usr/bin/env python
# encoding: utf-8
class Solution:
def maxArea(self, height: List[int]) -> int:
n = len(height)
ans, left, right = float('-inf'), 0, n-1
while left < right:
if height[left] < height[right]:
ans = max(ans, height[left] * (right - left))
... |
the-stack_106_29383 | import numpy as np
import cv2, PIL
from cv2 import aruco
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
#matplotlib nbagg
aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)
frame = cv2.imread("tmp.png")
#plt.figure()
#plt.imshow(frame)
#plt.show()
## time
gray = cv2.cvtColor(frame, ... |
the-stack_106_29384 | import argparse
import logging
import spotipy
from spotipy.oauth2 import SpotifyOAuth
logger = logging.getLogger('examples.add_a_saved_album')
logging.basicConfig(level='DEBUG')
scope = 'user-library-modify'
def get_args():
parser = argparse.ArgumentParser(description='Creates a playlist for user')
parser.... |
the-stack_106_29385 | # Copyright The PyTorch Lightning team.
#
# 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 i... |
the-stack_106_29386 | import glob
import os
from print_utils import *
def get_mappings(root_dir, files, annot_name):
pairs = []
for f in files:
f = f.replace(root_dir, '/')
img_f = f.replace(annot_name, 'leftImg8bit')
img_f = img_f.replace('_labelTrainIds.png', '.png')
if not os.path.isfile(root_dir ... |
the-stack_106_29387 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# 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 modif... |
the-stack_106_29388 | from django.db import models
from app.validators import ingredients_validator
# Create your models here.
class Recipe(models.Model):
title = models.CharField(max_length=30)
image_url = models.URLField()
description = models.TextField()
ingredients = models.CharField(
max_length=250,
va... |
the-stack_106_29390 | # coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
the-stack_106_29391 | """
Once a model is learned, use this to play it.
"""
import carmunk
import numpy as np
from nn import neural_net
NUM_SENSORS = 3
def play(model):
car_distance = 0
game_state = carmunk.GameState()
# Do nothing to get initial.
_, state = game_state.frame_step((2))
# Move.
while True:
... |
the-stack_106_29393 | TEST_OCF_ACCOUNTS = (
'sanjay', # an old, sorried account with kerberos princ
'alec', # an old, sorried account with no kerberos princ
'guser', # an account specifically made for testing
'nonexist', # this account does not exist
)
TESTER_CALNET_UIDS = (
872544, # daradib
1034192, # ckueh... |
the-stack_106_29394 | """Sonarr Models."""
# pylint: disable=invalid-name, too-many-instance-attributes
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from ..const import DATE, EPISODE_ID, PATH, SERIES_ID
from .base import BaseModel
from .request_common import (
... |
the-stack_106_29396 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 28 2020
Evgeniya Zhukova
ID: 101239316
"""
#classes
class Toy:
#constructor
def __init__(self, id=0, name=None, age=0,
price=0, category=None, discount_price=0):
self.id = id
self.name = name
self.age = age
self... |
the-stack_106_29397 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Copyright (C) 2020 Inspur Inc. All Rights Reserved.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
---
module: edit_pri... |
the-stack_106_29399 |
from matplotlib import lines, pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
data = np.load('../../data/Orbits.npy')
Positions = data[:,:,(0,1)]
figure, ax = plt.subplots()
# Setting limits for x and y axis
r = 2
ax.set_xlim(-r, r)
ax.set_ylim(-r, r)
ax2 = ax.twinx()
ax2.set_xlim(... |
the-stack_106_29403 | from .normalize import _normalize
class _Edition:
@staticmethod
def _edition(body):
return body.find("div", type="edition") # Note: limit to xml:space="preserve"?
@staticmethod
def language(body):
edition = _Edition._edition(body)
if edition:
return _normalize(edi... |
the-stack_106_29404 | """
A collection of classes used to manipulate Ordnance Survey GB GML data,
used with prepgml4ogr.py.
"""
import os
import re
import json
import lxml
from lxml import etree
from lxml import objectify
class prep_osgml():
"""
Base class that provides the main interface methods `prepare_feature` and
`get_fe... |
the-stack_106_29405 | # 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 u... |
the-stack_106_29406 | #!/usr/bin/env python3
import sys
from collections import deque
def is_safe(grid, x, y, distances):
return x >= 0 and x < len(grid) and y >= 0 and y < len(grid) and distances[x][y] == -1 and grid[x][y] != 'X'
def get_safe_moves(grid, node, distances):
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
vari... |
the-stack_106_29407 | from __future__ import absolute_import
from __future__ import print_function
import math
import numpy as np
import unittest
import ray
import cython_examples as cyth
def get_ray_result(cython_func, *args):
func = ray.remote(cython_func)
return ray.get(func.remote(*args))
class CythonTest(unittest.TestCase... |
the-stack_106_29408 | from django.shortcuts import render
from index.models import *
from django.http import StreamingHttpResponse
# Create your views here.
def playView(request,song_id):
# 热搜歌曲
search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:6]
# 歌曲信息
song_info = Song.objects.get(son... |
the-stack_106_29409 | import os
import re
import shlex
import stat
import winreg
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import date, datetime
from pathlib import Path
from typing import Optional, Generator, Any, Tuple, Callable, Mapping, ContextManager, Colle... |
the-stack_106_29410 | '''注意,这个模块可能死锁'''
from ..fakepath import fakepath_abs , new_fakefolder
import os
import random
import os.path as P
my_id = "{pid}_{seed}".format( pid = os.getpid() , seed = random.randint(0,233333)) #进程相关的id
name = "YFILELOCK/"
new_fakefolder(name)
def get_path(foldername):
'''给定lock的文件夹名,创建对应文件夹'''
pt = fakepath_... |
the-stack_106_29412 | from rl_agents.policies.gaussian import GaussianActor, ContinuousSample
from tensorflow_probability import distributions
import tensorflow as tf
import numpy as np
class LayerTest(tf.test.TestCase):
def setUp(self):
super(LayerTest, self).setUp()
self.layer = ContinuousSample((3,))
def testS... |
the-stack_106_29414 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""TsFeatures is a module for performing adhoc feature engineering on time series
data using different statistics.
The module process time ... |
the-stack_106_29416 | """
Copyright (C) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
the-stack_106_29417 | class Solution(object):
def twoSum(self, nums, target):
numbers = dict()
for key, value in enumerate(nums):
numbers[value] = key
solution = list()
for index in range(len(nums)):
value = nums[index]
total = target - value
temp = numbe... |
the-stack_106_29418 | """A script converting old ontologies to new ones.
Old ontology typically have entity names in ALL_UPPERCASE.
Newer ontology usually have entity names in CamelCase.
"""
import argparse
import yaml
import logging
import re
import shutil
import os
from copy import deepcopy
from pathlib import Path
from osp.core.ontolog... |
the-stack_106_29419 | import torch as t
import torch.nn as nn
import numpy as np
from typing import Union, Iterable
from torch.utils.data import IterableDataset
from pgportfolio.marketdata.coin_data_manager import \
coin_data_manager_init_helper
from pgportfolio.utils.misc import get_feature_list, parse_time
class PGPDataset(IterableD... |
the-stack_106_29420 | """The builtin dict implementation"""
from rpython.rlib import jit, rerased, objectmodel
from rpython.rlib.debug import mark_dict_non_null
from rpython.rlib.objectmodel import newlist_hint, r_dict, specialize
from rpython.tool.sourcetools import func_renamer, func_with_new_name
from pypy.interpreter.baseobjspace impo... |
the-stack_106_29422 | def patternMatch(sentences):
deconstructedSentences = []
totalWords = []
for sentence in sentences:
words = sentence.split()
deconstructedSentences.append(words)
totalWords.extend(words)
allWords = set(totalWords)
pattern = []
patterns = []
for word in allWords:
offset = 0
for x in range(0, 5):
sen... |
the-stack_106_29426 | import os
import subprocess
import json
from voter import create_toxic_result, create_binary_result
from argparse import ArgumentParser
def list_configs(path):
files = []
if not os.path.isdir(path):
raise Exception(f"The path given is not valid. Path: {path}")
for config_file in os.listdir(path):
... |
the-stack_106_29428 | """
Facebook's Prophet
Since Prophet install can be finicky on Windows, it will be an optional dependency.
"""
import datetime
import numpy as np
import pandas as pd
from autots.models.base import ModelObject, PredictionObject
import logging
# https://stackoverflow.com/questions/27361427/how-to-properly-deal-with-op... |
the-stack_106_29431 | # -*- coding: utf-8 -*-
'''
Project: Product Aesthetic Design: A Machine Learning Augmentation
Authors: Alex Burnap, Yale University
Email: alex.burnap@yale.edu
License: MIT License
OSS Code Attribution (see Licensing Inheritance):
Portions of Code From or Modified from... |
the-stack_106_29434 | #!/usr/bin/env python3
import os
import sys
import subprocess
import argparse
def main():
parser = argparse.ArgumentParser(description='GATK SplitIntervals')
parser.add_argument('-j', '--jvm-mem', dest='jvm_mem', type=int,
help='JVM max memory in MB', default=1000)
parser.add_arg... |
the-stack_106_29435 | """engine.SCons.Tool.f03
Tool-specific initialization for the generic Posix f03 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permis... |
the-stack_106_29436 | # -*- coding: utf-8 -*-
"""
Utilities
=========
Miscellaneous utilities.
"""
# Author: Eric Larson
# License: 3-clause BSD
from __future__ import division, absolute_import, print_function
import hashlib
import os
from shutil import move, copyfile
def scale_image(in_fname, out_fname, max_width, max_height):
"""... |
the-stack_106_29437 | from dataclasses import dataclass, field
from typing import Optional
from xsdata.models.datatype import XmlPeriod
__NAMESPACE__ = "NISTSchema-SV-IV-atomic-gMonth-minExclusive-4-NS"
@dataclass
class NistschemaSvIvAtomicGMonthMinExclusive4:
class Meta:
name = "NISTSchema-SV-IV-atomic-gMonth-minExclusive-4"... |
the-stack_106_29438 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, ESS LLP and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe.model.document import Document
from frappe.utils import cstr
from frappe import _
from hms_tz.hms_t... |
the-stack_106_29439 | # Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_106_29441 |
class Node(object):
"""Node Classs."""
def __init__(self, data=None, next_data=None):
"""Initialize a new Node."""
self.data = data
self.next = next_data
class Stack(object):
"""Stack data strcuture."""
def __init__(self, iterable=None):
"""Initialize a new instance ... |
the-stack_106_29442 | import math
import traceback
from random import randint
import discord
from discord.ext import commands
import cogs.utils.context as context
class Xp(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member) -> None:
... |
the-stack_106_29443 | import sys, logging, os, random, math, open_color, arcade
#check to make sure we are running the right version of Python
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
#turn on logging, in case we have to leave ourselves debugging messa... |
the-stack_106_29444 | """
Geographically weighted regression
"""
import numpy as np
from .gwr.base.gwr import GWR as PySAL_GWR
from .gwr.base.sel_bw import Sel_BW
import json
from crankshaft.analysis_data_provider import AnalysisDataProvider
import plpy
class GWR:
def __init__(self, data_provider=None):
if data_provider:
... |
the-stack_106_29446 | r"""
Doubly stochastic gradient descent
==================================
In this tutorial we investigate and implement the doubly stochastic gradient descent
paper from `Ryan Sweke et al. (2019) <https://arxiv.org/abs/1910.01155>`__. In this paper,
it is shown that quantum gradient descent, where a finite numb... |
the-stack_106_29449 | # Copyright (c) 2017 Tigera, 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_29450 | import numpy as np
def noise_replace(iris, upper_occlusion_theta, lower_occlusion_theta):
'''
Replaces portions of the iris with continuous uniform noise.
Input:
iris - numpy array of pixel intensities of transformed iris.
upper_occlusion_theta - tuple that defines the angular bounds of th... |
the-stack_106_29451 | # Original Code here:
# https://github.com/pytorch/examples/blob/master/mnist/main.py
from contextlib import contextmanager
import os
import logging
import shutil
import tempfile
from typing import Callable, Dict, Generator, Optional, Type, Any
import torch
from datetime import timedelta
import ray
from ray import tu... |
the-stack_106_29452 | from pathlib import Path
import pytest
from pydantic import BaseModel, ValidationError
from beanie.odm.fields import PydanticObjectId
from beanie.odm.utils.encoder import bson_encoder
from tests.odm.models import (
DocumentWithCustomFiledsTypes,
DocumentWithBsonEncodersFiledsTypes,
Sample,
)
class M(Base... |
the-stack_106_29455 | import time
import dateparser
import pytz
import json
from datetime import datetime
from binance import Client
import binance.constants as bc
def date_to_milliseconds(date_str):
"""Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See d... |
the-stack_106_29456 | import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from lymph.utils.autoencoder import Autoencoder
def get_random_block_from_data(data, batch_size):
start_index = np.random.randint(0, len(data) - batch_size)
return data[start_index: (start_index + batch_size)... |
the-stack_106_29457 | # coding=utf-8
# Copyright (c) DIRECT Contributors
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Taken from Detectron 2, licensed under Apache 2.0.
# https://github.com/facebookresearch/detectron2/blob/60d7a1fd33cc48e58968659cd3301f3300b2786b/detectron2/solver/lr_scheduler.py
# Changes:
# - ... |
the-stack_106_29458 | ##########################################################################
#
# Copyright (c) 2011, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... |
the-stack_106_29459 | import pygame
import random
pygame.init()
# Colors
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 190, 0)
# Creating window
screen_width = 900
screen_height = 600
gameWindow = pygame.display.set_mode((screen_width, screen_height))
# Game Title
pygame.display.set_caption("Snake King")
pygame.display.update()... |
the-stack_106_29460 | # Copyright 2013-2019 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 PyNotebook(PythonPackage):
"""Jupyter Interactive Notebook"""
homepage = "https://git... |
the-stack_106_29461 | import numpy as np
import io
import soundfile as sf
def syncToVideo(video, audio):
"""
:arg video is the wav from the video
:arg audio is the enhanced audio
:returns (video_offset, audio_offset), the values for syncing the two videos
"""
# step 1 -> extract numpy arrays from the two audio
... |
the-stack_106_29462 | """Support for Latticework AmberOS sensors."""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
import logging
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordina... |
the-stack_106_29463 | import asyncio
import logging
import sys
import traceback
import warnings
from kafka.partitioner.default import DefaultPartitioner
from kafka.codec import has_gzip, has_snappy, has_lz4, has_zstd
from aiokafka.client import AIOKafkaClient
from aiokafka.errors import (
MessageSizeTooLargeError, UnsupportedVersionEr... |
the-stack_106_29464 | """时间: 2019/12/24
作者: liyongfang@cyai.com
更改记录:
重要说明:
"""
import json
import logging
import os
import threading
from django.conf import settings
import django
import pika
from utils import config
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wol_server.settings")
django.setup()
logger = logging.getLogger... |
the-stack_106_29466 | class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
dummy_1 = ListNode(0, head)
dummy_2 = ListNode(0, head)
p, h = dummy_1, head
n = dummy_2
while h:
if h.val<x:
n.next = h
n = n.next
p.next = ... |
the-stack_106_29468 | import xarray as xr
import numpy as np
from loaders.mappers._base import GeoMapper
from loaders.mappers._xarray import XarrayMapper
from loaders._config import mapper_functions
from loaders.mappers._fine_res import (
open_zarr,
standardize_coords,
MLTendencies,
)
from loaders.mappers._fine_res_budget impor... |
the-stack_106_29470 | # -*- 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_29472 | # coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class BatchUpdateDevicesStatusResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribu... |
the-stack_106_29473 | #!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable code object** utilities.
This private submodule implements utility functions dynamically introspecting
**c... |
the-stack_106_29474 | # -*- coding:utf-8 -*-
#
# Name :FPGA based DES design,python上位机,下位机IC:CY7C68013A
# Origin:190415
# Author:helrori
#
import usb.core
import usb.util
import sys
import time
from pyDes import des, PAD_NORMAL,ECB
import binascii
import numpy as np
pkg_1 = 1 #该值最大值由FPGA 内FIFO大小决定 fifo_size/512 详见usb.v内说明
... |
the-stack_106_29476 |
import struct
from bprocessor import RecordProcessor, UnexpectedRecordException, RecordDescriptor
from btypes import BinaryRecordType
class ACUid:
@staticmethod
def read(stream):
rprocessor = RecordProcessor.resolve(stream)
ac = AlternatContent.read(rprocessor)
r = rprocesso... |
the-stack_106_29477 | #########################
# Star Wars Dice Roller #
#########################
import gc
import random
from ..menus import base_menus as m
# Define the dice
class dice:
def __init__(self, colour, name, sides, results, pool):
self.colour = colour
self.name = name
self.sides = sides
... |
the-stack_106_29478 | import pytest
from graphapi.schema import schema
from openstates.data.models import Organization, Person
from .utils import populate_db
@pytest.mark.django_db
def setup():
populate_db()
@pytest.mark.django_db
def test_jurisdictions(django_assert_num_queries):
with django_assert_num_queries(2):
resul... |
the-stack_106_29479 | """Default tags used by the template system, available to all templates."""
from __future__ import unicode_literals
import sys
import re
from datetime import datetime
from itertools import groupby, cycle as itertools_cycle
import warnings
from django.conf import settings
from django.template.base import (Node, NodeLi... |
the-stack_106_29480 | #!/usr/bin/env python3
"""
Test suite for remote module
"""
import pytest
import requests_mock
from pathlib import Path
from cblaster import remote, helpers
TEST_DIR = Path(__file__).resolve().parent
def test_start_no_input():
with pytest.raises(ValueError):
# No query_file/ids
remote.start... |
the-stack_106_29481 | import re
import os
import math
import logging
logger = logging.getLogger(__name__)
import numpy as np
from scipy.ndimage.filters import median_filter
import scipy.interpolate as intp
import scipy.signal as sg
import scipy.optimize as opt
import astropy.io.fits as fits
from astropy.table import Table
import matplotli... |
the-stack_106_29484 | import inspect
import json
import logging
import urllib.error
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
import vat_moss.exchange_rates
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.serializers.json import DjangoJSONEncoder
from dj... |
the-stack_106_29487 | import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Phase2C11_cff import Phase2C11
process = cms.Process("HGCalParametersTest",Phase2C11)
process.load("SimGeneral.HepPDTESSource.pdt_cfi")
#process.load("Geometry.CMSCommonData.cmsExtendedGeometry2026D71XML_cfi")
process.load("Geometry.HGCalCommonData.t... |
the-stack_106_29490 | # Copyright 2019 Atalaya Tech, 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_29491 | from django.test import SimpleTestCase
from ..services.chinese import LACChineseTokenizer
class LACChineseTokenizerTests(SimpleTestCase):
def test_prepare_for_segmentation(self):
"""
prepare_for_segmentation() strips carriage returns from input (for
better LAC segmentation)
"""
... |
the-stack_106_29494 | import logging
import os
from collections import OrderedDict
from typing import Union, TextIO, Optional, Set, List, cast, Dict, Mapping, Tuple, Iterator
from urllib.parse import urlparse
from jsonasobj2 import values
from linkml_runtime.linkml_model.meta import SchemaDefinition, SlotDefinition, SlotDefinitionName, Cla... |
the-stack_106_29495 | # -*- coding: utf-8 -*-
# from __future__ import annotations
"""
Type variables, Type aliases and Protocol Types.
"""
__author__ = "Anders Åström"
__contact__ = "anders@lyngon.com"
__copyright__ = "2021, Lyngon Pte. Ltd."
__licence__ = """The MIT License
Copyright © 2021 Lyngon Pte. Ltd.
Permission is hereby granted,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.