filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_22367 | import pytest
from tests.actions.support.keys import Keys
from tests.actions.support.refine import filter_dict, get_keys, get_events
def test_null_response_value(session, key_chain):
value = key_chain.key_up("a").perform()
assert value is None
value = session.actions.release()
assert value is None
... |
the-stack_106_22371 | # -*- coding: utf-8 -*-
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _
# models
from comments.models import Comment
from comments.models import CommentLike
from comments.models import CommentImage
# forms
from base.forms import BaseModelForm
class CommentForm(BaseMo... |
the-stack_106_22372 | # Webhooks for external integrations.
from typing import Any, Dict, Optional
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_s... |
the-stack_106_22374 | """
UP42 authentication mechanism and base requests functionality
"""
import json
from pathlib import Path
from typing import Dict, Optional, Union
import requests
import requests.exceptions
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicati... |
the-stack_106_22375 | # -*- coding: utf-8 -*-
'''
Operations on regular files, special files, directories, and symlinks
=====================================================================
Salt States can aggressively manipulate files on a system. There are a number
of ways in which files can be managed.
Regular files can be enforced wit... |
the-stack_106_22376 | #!/usr/bin/env python3
##############################################################################
#
# Module: mcci-catena-provision-helium.py
#
# Function:
# Provision a catena device through Helium cli
#
# Copyright and License:
# This file copyright (c) 2021 by
#
# MCCI Corporation
# 352... |
the-stack_106_22377 | import nipype.pipeline.engine as pe
import nipype.interfaces.utility as util
import nipype.interfaces.fsl as fsl
import nipype.interfaces.c3 as c3
def create_nonlinear_register(name='nonlinear_register'):
"""
Performs non-linear registration of an input file to a reference file.
Parameters
----------... |
the-stack_106_22378 | import random
import sys
import numpy as np
import pandas as pd
from scipy import stats
from tqdm import tqdm
import torch
import train_network
import network as net
import functions as f
from parameters import BATCH_SIZE, RESOLUTION, N_ACTIONS, DATA_PATH_TEST, TRANSFORM, Q_TABLE_TEST, DEVICE
def generate_random(i... |
the-stack_106_22379 | from inspect import getframeinfo, currentframe
from os.path import dirname, abspath
from sys import path
import numpy as np
from torch import ones, zeros, mean, tensor, cat, log, clamp, sigmoid, dist, Tensor
from torch.nn import MSELoss, BCELoss, BCEWithLogitsLoss, Module, L1Loss
from torch.autograd import grad
from ... |
the-stack_106_22381 | import pytest
import tiflash
class TestMemoryApi():
def test_basic_memory_read_single_byte(self, tdev):
"""Tests simple memory read"""
result = tiflash.memory_read(tdev['read-address'], 1,
serno=tdev['serno'],
connection=tdev['connection'],
... |
the-stack_106_22382 | import json
import requests
# Cargamos los usuarios
with open('usuarios.json') as f: usuarios = json.load(f)
# Funciones de ayuda
def save_users():
"Guarda los usuarios en nuestro fichero de usuarios"
with open('usuarios.json', 'w') as f: json.dump(usuarios, f, indent=2)
def is_user(cid):
"Comprueba si un ID e... |
the-stack_106_22383 | # -*- coding: utf-8 -*-
"""Tests for the xml module."""
from __future__ import unicode_literals
from soco import xml
def test_register_namespace():
assert xml.register_namespace
def test_ns_tag():
"""Test the ns_tag function."""
namespaces = ['http://purl.org/dc/elements/1.1/',
'urn... |
the-stack_106_22384 | from urllib.parse import urlparse
import vobject
from csp.decorators import csp_update
from django.conf import settings
from django.contrib import messages
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, render
from django.utils.decorators im... |
the-stack_106_22386 | # pylint: skip-file
#
# All modification made by Intel Corporation: Copyright (c) 2016 Intel Corporation
#
# All contributions by the University of California:
# Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
# All rights reserved.
#
# All other contributions:
# Copyright (c) 2014, ... |
the-stack_106_22387 | import uuid
import os
import tarfile
from pymongo import MongoClient
from server.files import list_all_img_in_folder
client = MongoClient('mongodb://localhost:27017/')
db = client.details
def retrieve_article(id):
result = db.articles.find_one({'id': id}, {'_id': 0})
return result
def retrie... |
the-stack_106_22388 | from torch.optim.lr_scheduler import _LRScheduler, CosineAnnealingLR
import math
class RestartCosineAnnealingLR(_LRScheduler):
def __init__(self, optimizer, T_max, eta_min=0, last_epoch=-1):
self.T_max = T_max
self.eta_min = eta_min
super(RestartCosineAnnealingLR, self).__init__(optimizer, last_epoch)
def g... |
the-stack_106_22389 |
from python_interface.gecco_interface import *
from python_spec.mrcc_response.get_response_data import _response_data, _pop_data, _cmp_data, _calc_data
from python_spec.mrcc_response.set_mrcc_response_targets import relax_ref
import math
_inp = GeCCo_Input()
# Get the name of the package GeCCo uses the integrals fro... |
the-stack_106_22391 | # This code is part of Mthree.
#
# (C) Copyright IBM 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 derivative wo... |
the-stack_106_22393 | r"""
Morphisms of Toric Varieties
There are three "obvious" ways to map toric varieties to toric
varieties:
1. Polynomial maps in local coordinates, the usual morphisms in
algebraic geometry.
2. Polynomial maps in the (global) homogeneous coordinates.
3. Toric morphisms, that is, algebraic morphisms equivariant ... |
the-stack_106_22394 | #--------------------------------------------------------------------------------
# DESCRIPTION:
# a. This example uses the Keithley DAQ6510 to perform temperature
# scanning
# b. For storing results to the cloud, we introduce the streaming
# tools provided by Initial State
# ... |
the-stack_106_22395 | ################################################################################
# Copyright (c) 2020-2021, Berkeley Design Technology, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to ... |
the-stack_106_22396 | import os
from pathlib import Path
from torchaudio.datasets.libritts import LIBRITTS
from torchaudio_unittest.common_utils import (
TempDirMixin,
TorchaudioTestCase,
get_whitenoise,
save_wav,
normalize_wav,
)
class TestLibriTTS(TempDirMixin, TorchaudioTestCase):
backend = 'default'
root... |
the-stack_106_22398 | import contextlib
from subprocess import list2cmdline
from rrmngmnt.executor import Executor
import six
class FakeFile(six.StringIO):
def __init__(self, *args, **kwargs):
six.StringIO.__init__(self, *args, **kwargs)
self.data = None
def __exit__(self, *args):
self.close()
def __e... |
the-stack_106_22399 | # module corpus.py
#
# Copyright (c) 2015 Rafael Reis
#
"""
corpus module - Classes and functions to read and process corpus data.
"""
__version__="1.0"
__author__ = "Rafael Reis <rafael2reis@gmail.com>"
import re
def groupByFeed(c):
feeds = []
p = c.next()
lastIndex = p.index
text = p.sentence.re... |
the-stack_106_22400 | # Copyright 2014, Doug Wiegley, A10 Networks.
#
# 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_22403 | from abc import ABC, abstractmethod
from color_palette import ColorPalette
from functools import reduce
from random import randint
class DoomFire(ABC):
def __init__(self, width, height, pixel_size = 4, decay_rate = 2, \
windforce = 1, fire_source_inc = (4, 6), \
fire_source_enabled = True, ... |
the-stack_106_22406 | """
Created on Feb 9, 2016
@author: Chris Smith
"""
from __future__ import division, print_function, absolute_import, unicode_literals
import os
from warnings import warn
import numpy as np
import h5py
from skimage.measure import block_reduce
from skimage.util import crop
from sidpy.sid import Translator
from sidp... |
the-stack_106_22407 | import requests
from bs4 import BeautifulSoup
from .classes import work
from .utility import file_management, parse_paths
from .classes import author
from .utility import pdf_generation
"""
ACADEMIA.EDU WEB SCRAPER and AUTOMATIC (Basic) PDF CV GENERATOR
A PYTHON-A-THON 2016 PROJECT by ... |
the-stack_106_22408 | import os
import tensorflow as tf
class LogSaver:
def __init__(self, logs_path, model_name, dateset_name, mode):
if not os.path.isdir(logs_path):
os.makedirs(logs_path)
self.train_writer = tf.summary.create_file_writer(
'{}/{}/{}/{}/train/'.format(logs_path, dateset_name, model_name, mode))
self.vali... |
the-stack_106_22411 | # Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
the-stack_106_22412 | import vcr
from time import sleep
from unittest import TestCase
from contentful_management.environment import Environment
from contentful_management.errors import NotFoundError
from .test_helper import CLIENT, PLAYGROUND_SPACE
BASE_ENVIRONMENT_ITEM = {
'sys': {
'id': 'foo',
'type': 'Environment',
... |
the-stack_106_22413 | import json
from collections import Counter
import re
from VQA.PythonHelperTools.vqaTools.vqa import VQA
import random
import numpy as np
from VQAGenerator import VQAGenerator
import VQAModel
from matplotlib import pyplot as plt
import os
from PIL import Image, ImageOps
from keras.models import load_model
from random ... |
the-stack_106_22414 | """
Classes allowing "generic" relations through ContentType and object-id fields.
"""
from __future__ import unicode_literals
from collections import defaultdict
from functools import partial
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.db import models, router, ... |
the-stack_106_22416 | # content of conftest.py
from kueventparser import events
def make_test_event(uri: str, ) -> events.Event:
"""テスト用のEventクラス作成関数.
Args:
uri('str'): URI
Returns:
list: list for event
"""
import datetime as dt
import pytz
from bs4 import BeautifulSoup
# jst の設定
jst ... |
the-stack_106_22419 | import os
import random
import StringIO
from datetime import datetime
import dj_database_url
from fabric.api import cd, env, execute, get, local, put, require, run, settings, shell_env, task
from fabric.context_managers import quiet
from fabric.operations import prompt
from gitric import api as gitric
# This is the d... |
the-stack_106_22421 | # Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
# 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/LICEN... |
the-stack_106_22422 | import pytest
import cftime
from datetime import datetime
from unittest.mock import Mock, call, patch, sentinel
import unittest
import iris
import numpy as np
from forest.drivers import gridded_forecast
class Test_empty_image(unittest.TestCase):
def test(self):
result = gridded_forecast.empty_image()
... |
the-stack_106_22423 | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from xml.etree.ElementTree import ParseError
import requests
from lxml import etree
from six import ensure_text
from checks import AgentCheck
from utils.util import _is_affirmative
from . import metrics... |
the-stack_106_22425 | #!/usr/bin/env python
import sys
import os
from setuptools import setup, find_packages, __version__
v = sys.version_info
if sys.version_info < (3, 5):
msg = "FAIL: Requires Python 3.5 or later, " \
"but setup.py was run using {}.{}.{}"
v = sys.version_info
print(msg.format(v.major, v.minor, v.m... |
the-stack_106_22428 | from collections import deque
import gym
import gym_minigrid
import numpy as np
import sys
import unittest
import ray
from ray import tune
from ray.rllib.agents.callbacks import DefaultCallbacks
import ray.rllib.agents.ppo as ppo
from ray.rllib.utils.test_utils import check_learning_achieved, \
framework_iterator
... |
the-stack_106_22430 | # -*- coding: utf-8 -*-
import re, json, glob, argparse
from gensim.corpora import WikiCorpus, Dictionary
from gensim.utils import to_unicode
"""
Creates a corpus from Wikipedia dump file.
Inspired by:
https://www.kdnuggets.com/2017/11/building-wikipedia-text-corpus-nlp.html
"""
def make_corpus(in_f, out_f):
"""Co... |
the-stack_106_22435 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import os
from fvcore.common.timer import Timer
from detectron2.structures import BoxMode
from fvcore.common.file_io import PathManager
from detectron2.data import DatasetCatalog, MetadataCatalog
from .lvis_v0_5_categories import LV... |
the-stack_106_22438 | from typing import Any, Dict, List, Optional
import attr
import numpy as np
import habitat_sim.agent
import habitat_sim.bindings as hsim
from habitat_sim import errors, utils
@attr.s(auto_attribs=True)
class GreedyGeodesicFollower(object):
r"""Greedily fits actions to follow the geodesic shortest path
Args... |
the-stack_106_22439 | import random
from hashlib import md5
from getpass import getpass
import pickle
import subprocess as sp
def randomPass():
def randomString():
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
return ''.join(random.choice(letters) for i in range(4))
def randomNum():
return ''.join(str(random.randint(0,9)) for i... |
the-stack_106_22440 | # Copyright 2012-2013 Eric Ptak - trouch.com
#
# 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 l... |
the-stack_106_22442 | #!/usr/bin/env python
from ansible.module_utils.basic import *
import sys
import re
from collections import defaultdict
MODULE_FIELDS = {
'file': {'type': str, 'default': '/etc/hosts'},
'hosts': {'type': set, 'required': True},
'ips': {'type': set, 'required': True},
'append': {'type': bool, 'required... |
the-stack_106_22443 | # -*- coding: utf-8 -*-
__author__ = "Ngoc Huynh Bao"
__email__ = "ngoc.huynh.bao@nmbu.no"
import os
import h5py
import numpy as np
import warnings
from deoxys.keras.callbacks import CSVLogger
from ..model.callbacks import DeoxysModelCheckpoint, PredictionCheckpoint, \
DBLogger
from ..model import model_from_fu... |
the-stack_106_22445 | import tensorflow as tf
import time, os, sys
from py.fm_model import LocalFmModel, DistFmModel
PREDICT_BATCH_SIZE = 10000
def _predict(sess, supervisor, is_master_worker, model, model_file, predict_files, score_path, need_to_init):
with sess as sess:
if is_master_worker:
if need_to_init:
... |
the-stack_106_22446 | from __future__ import absolute_import, division, print_function
from stripe import error, util, six
from stripe.stripe_object import StripeObject
from stripe.six.moves.urllib.parse import quote_plus
class APIResource(StripeObject):
@classmethod
def retrieve(cls, id, api_key=None, **params):
instanc... |
the-stack_106_22447 | import math
import warnings
import tlz as toolz
from fsspec.core import get_fs_token_paths
from fsspec.implementations.local import LocalFileSystem
from fsspec.utils import stringify_path
from packaging.version import parse as parse_version
from ....base import compute_as_if_collection, tokenize
from ....delayed impo... |
the-stack_106_22448 | import eel
import os
from FaceRecogniser import FaceRecogniser
sr = None
@eel.expose
def set_known_folder(folder):
if folder:
try:
global sr
sr = FaceRecogniser(folder)
if sr:
return "Success initializing"
except Exception as ex:
retu... |
the-stack_106_22452 | import tensorflow as tf
from .support import initializer, visualize_filters
import numpy as np
def softmax_layer (input, name = 'softmax'):
"""
Creates the softmax normalization
Args:
input: Where is the input of the layer coming from
name: Name scope of the layer
Returns:
tu... |
the-stack_106_22453 | # -*- coding: utf-8 -*-
"""Extract *all* xrefs from OBO documents available."""
import gzip
import os
from collections import Counter
import click
import pandas as pd
from .xrefs_pipeline import Canonicalizer, _iter_ooh_na_na, _iter_synonyms, get_xref_df, summarize_xref_df
from ..cli_utils import verbose_option
fro... |
the-stack_106_22454 | import hashlib
import os
import urlparse
from abc import ABCMeta, abstractmethod
from Queue import Empty
from collections import defaultdict, deque
from multiprocessing import Queue
import manifestinclude
import manifestexpected
import wpttest
from mozlog import structured
manifest = None
manifest_update = None
downl... |
the-stack_106_22456 | """
Modder classes used for domain randomization. Largely based off of the mujoco-py
implementation below.
https://github.com/openai/mujoco-py/blob/1fe312b09ae7365f0dd9d4d0e453f8da59fae0bf/mujoco_py/modder.py
"""
import os
import numpy as np
from collections import defaultdict
from PIL import Image
from mujoco_py im... |
the-stack_106_22457 | # Copyright 2019 Extreme Networks, 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 i... |
the-stack_106_22458 | import warnings
class OnceTrigger(object):
"""Trigger based on the starting point of the iteration.
This trigger accepts only once at starting point of the iteration. There
are two ways to specify the starting point: only starting point in whole
iteration or called again when training resumed.
... |
the-stack_106_22459 | # -*- coding: UTF8 -*-
from pupylib.PupyModule import *
__class_name__="GetPrivsModule"
@config(compat=["windows"], cat="manage")
class GetPrivsModule(PupyModule):
""" try to get SeDebugPrivilege for the current process """
dependencies=["psutil", "pupwinutils.security"]
def init_argparse(self):
s... |
the-stack_106_22461 | import serial
import time
class BaseCtrl:
COMMAND_DELAY = 0.05
def __init__(self, app, device='/dev/ttyUSB0', baudrate=9600, channels=8):
self.verify_wait = -1
self.channels = channels
self.log = app.log
self.log.info("Init %s(%s, baudrate: %d)", self.__class__.__name__, devic... |
the-stack_106_22463 | import logging
from time import sleep
from typing import List
from django.utils import timezone
from river.adapters.progression_counter import ProgressionCounter
from river.adapters.topics import TopicsManager
from river.models import Batch
logger = logging.getLogger(__name__)
def teardown_after_batch(batch: Batch... |
the-stack_106_22464 | # 2021 - Borworntat Dendumrongkul
class Notify :
_version = "1.0.0"
_token = ""
def __init__(self, _token=""):
self.token = _token
def version(self):
return self._version
def setKey(self, token):
try:
self._token = token
return True
exce... |
the-stack_106_22465 | # -*- coding: utf-8 -*-
import os
from unittest import TestCase
from unittest.mock import patch, MagicMock
from pathlib import Path
from collections import namedtuple
from sfzlint.cli import sfzlint, sfzlist
from sfzlint import settings
fixture_dir = Path(__file__).parent / 'fixtures'
is_fs_case_insensitive = (
... |
the-stack_106_22468 | #-*-coding:utf-8-*-
"""
@FileName:observation.py
@Description:
@Author:qiwenhao
@Time:2021/5/12 20:11
@Department:AIStudio研发部
@Copyright:©2011-2021 北京华如科技股份有限公司
@Project:601
"""
_OBSINIT = None
class ObservationProcessor(object):
# 解析数据包
@staticmethod
def get_obs(Data):
"""
解析状态信息并组包
... |
the-stack_106_22469 | """Utility functions for DBus use within Bluezero."""
# Standard libraries
import re
import subprocess
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
# D-Bus import
import dbus
import d... |
the-stack_106_22471 | # Copyright 2017 The Bazel 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 applicable la... |
the-stack_106_22472 | import names
import os
from tqdm import tqdm
to_change_path = '../static/artwork/face-terrors'
other_path = '../static/artwork/almost-human'
for filename in tqdm(os.listdir(to_change_path)):
if not filename.endswith(".png"):
continue
fn = names.get_first_name()
fname = f'{to_change_path}/{fn}.png'
fnam... |
the-stack_106_22474 | import json
import sys
def main():
samples = 1
if len(sys.argv) > 1:
samples = sys.argv[1]
output_path = sys.argv[2]
print ("Generating " + samples + " samples")
h_cli_sc = []
broker = open(output_path+"/broker.json", "w")
broker_json = json.dumps(
{ "federates": [{"di... |
the-stack_106_22476 | ## factory boy
import factory
# Own
from portfolio.models import Account
class AccountFactory(factory.django.DjangoModelFactory):
"""
Factory for creating accounts
"""
class Meta:
model = Account
# Account name by default will be 'Account 1' for the first created
# account, 'Account... |
the-stack_106_22477 | ######### global settings #########
GPU = True # running on GPU is highly suggested
GPU_ID = 0
TEST_MODE = False # turning on the testmode means the code will run on a small dataset.
CLEAN = True # set to "True" if you want to cle... |
the-stack_106_22480 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 31 18:29:48 2022
@author: fabian
"""
import pytest
import os
import pypsa
import pandas as pd
import numpy as np
@pytest.fixture(scope="module")
def scipy_network():
csv_folder = os.path.join(
os.path.dirname(__file__),
"..",
... |
the-stack_106_22482 | import math
import torch
import torch.nn as nn
import numpy as np
# from skimage.measure.simple_metrics import compare_psnr
from skimage.metrics import peak_signal_noise_ratio
import matplotlib.pyplot as plt
def weights_init_kaiming(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
... |
the-stack_106_22485 | import torch
import torch.nn as nn
from SelfAttention import SelfAttention
class TransformerBlock(nn.Module):
def __init__(self, embedding_size, heads, dropout, forward_expansion):
super(TransformerBlock, self).__init__()
self.attention = SelfAttention(embedding_size, heads)
self.norm1 = nn... |
the-stack_106_22486 | #!/usr/bin/env python
from __future__ import print_function
import io
import logging
import argparse
from parser import Box
from construct import setglobalfullprinting
from summary import Summary
log = logging.getLogger(__name__)
setglobalfullprinting(True)
def dump(input_file):
with open(input_file, 'rb') as f... |
the-stack_106_22488 | #import sys
#sys.path.append('c:\\Users\\Thoma\\OneDrive\\Documents\\2021_ORNL\\CartanCodeGit\\cartan-quantum-synthesizer')
# -*- coding: utf-8 -*-
__docformat__ = 'google'
"""
A collection of functions useful for exact diagonalization and converting KHK decomposition to a matrix
"""
import numpy as np
from numpy impo... |
the-stack_106_22490 | # coding: utf-8
from __future__ import unicode_literals
import base64
import collections
import hashlib
import itertools
import json
import netrc
import os
import random
import re
import sys
import time
import math
from ..compat import (
compat_cookiejar_Cookie,
compat_cookies_SimpleCookie,
compat_etree_E... |
the-stack_106_22492 | #!/usr/bin/env python
# CREATED:2014-01-18 14:09:05 by Brian McFee <brm2132@columbia.edu>
# unit tests for util routines
# Disable cache
import os
try:
os.environ.pop('LIBROSA_CACHE_DIR')
except:
pass
import platform
import numpy as np
import scipy.sparse
from nose.tools import raises, eq_
import six
import w... |
the-stack_106_22494 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Modifications for Guinet et al.
# TODO
import io, os, ot, argparse, random
... |
the-stack_106_22495 | import numpy as np
from matplotlib import pyplot as plt
import cv2
img = cv2.imread('wiki.jpg',0)
hist,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(img.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256... |
the-stack_106_22497 | #!/usr/bin/python
"""
anybadge
A Python module for generating badges for your projects, with a focus on
simplicity and flexibility.
"""
import os
import re
# Package information
version = __version__ = "0.0.0"
__version_info__ = tuple(re.split('[.-]', __version__))
__title__ = "anybadge"
__summary__ = "A simple, fle... |
the-stack_106_22499 | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.common_utils import try_contiguous
def _extract_patches(x, kernel_size, stride, padding):
"""
:param x: The input feature maps. (batch_size, in_c, h, w)
:param kernel_size: the kernel size of the conv filter (tuple of two elem... |
the-stack_106_22500 | # Copyright 2020 Google LLC. 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 or a... |
the-stack_106_22501 | # coding: utf-8
"""
Unofficial python library for the SmartRecruiters API
The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it.
... |
the-stack_106_22503 | """
File:
JetSegGraph.py
Contents and purpose:
Draws the event graph and progress bar
Copyright (c) 2008 Android Open Source 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 Li... |
the-stack_106_22504 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016 Michael Gruener <michael.gruener@chaosmoon.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_versio... |
the-stack_106_22505 | """Email sensor support."""
from collections import deque
import datetime
import email
import imaplib
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_DATE,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,... |
the-stack_106_22506 | # -*- coding: utf-8 -*-
from collections import defaultdict
from datetime import datetime, timedelta
from io import StringIO
import math
import operator
import re
import numpy as np
import pytest
import pandas._config.config as cf
from pandas._libs.tslib import Timestamp
from pandas.compat import PY36, lrange, lzip... |
the-stack_106_22507 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... |
the-stack_106_22508 | # Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <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 S... |
the-stack_106_22509 | import math
import torch
from torch import nn
class PositionalEncoding(nn.Module):
"""
Implementation of the positional encoding from Vaswani et al. 2017
"""
def __init__(self, d_model, dropout=0., max_len=5000, affinity=False, batch_first=True):
super(PositionalEncoding, self).__init__()
... |
the-stack_106_22510 | #!/usr/bin/env python3
#coding=utf-8
import numpy as np
import time
from math import cos, sin, sqrt, pi, atan, asin, atan, atan2
from scipy.optimize import least_squares
from scipy.spatial.transform import Rotation
from std_msgs.msg import String
from angles import normalize_angle
import rospy
from origarm_ros.srv imp... |
the-stack_106_22512 | import cv2
def check_area(area, image_area):
return area / image_area < 0.95
def crop_image(image_path):
img = cv2.imread(image_path)
height, width, channels = img.shape
image_area = height * width
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
retval, thresh_gray = cv2.threshold(gray, thresh... |
the-stack_106_22513 | import random
import math
import unittest
from unittest.mock import patch
from parameterized import parameterized
import pyEpiabm as pe
from pyEpiabm.routine import ToyPopulationFactory
numReps = 1
class TestPopConfig(unittest.TestCase):
"""Test the 'ToyPopConfig' class.
"""
@parameterized.expand([(ran... |
the-stack_106_22515 | # --------------------------------------------
# Main part of the plugin
#
# JL Diaz (c) 2019
# MIT License
# --------------------------------------------
from collections import defaultdict
from pathlib import Path
import os
import yaml
import jinja2
from jinja2.ext import Extension
from mkdocs.structure.files import ... |
the-stack_106_22516 | class ClockWidget():
def __init__(self):
self.name = "Clock"
self.template = "widget_clock.html"
class PingWidget():
def __init__(self, addrs: list):
self.name = "Ping"
self.template = "widget_ping.html"
self.addrs = addrs
self.targets = self.addrs |
the-stack_106_22517 |
import PyPluMA
import sys
def quote(s):
return '\"' + s + '\"'
def unquote(s):
return s[1:len(s)-1]
class CSV2PLSDAPlugin:
def input(self, filename):
# Parameter file
self.parameters = dict()
paramfile = open(filename, 'r')
for line in paramfile:
contents = line.split('... |
the-stack_106_22519 | import parser_with_time
import queue
import uuid
import json
inter_communication_time = 0.1
node_cnt = 10
node_ip = ['', '', '', '', '', '', '', '', '', '']
def init_graph(workflow, group_set):
in_degree_vec = dict()
q = queue.Queue()
q.put(workflow.start)
group_set.append({workflow.start.name})
... |
the-stack_106_22520 | """
Pyramid views (controllers in the classical meaning) for traversal resources.
Each class of :class:`spree.rest.traversal.APIResource`
and :class:`spree.rest.traversal.APIAction` defines it's own view.
"""
from marshmallow import ValidationError, MarshalResult
from . import events
from .endpoints import (
API... |
the-stack_106_22521 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import os
import pickle as pk
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, LSTM, Dense, Embedding
from tensorflow.keras.optimize... |
the-stack_106_22523 | #!/usr/bin/env python
import contextlib
import glob
import io
import os
import pathlib
import re
header_restrictions = {
"barrier": "!defined(_LIBCPP_HAS_NO_THREADS)",
"future": "!defined(_LIBCPP_HAS_NO_THREADS)",
"latch": "!defined(_LIBCPP_HAS_NO_THREADS)",
"mutex": "!defined(_LIBCPP_HAS_NO_THREADS)"... |
the-stack_106_22526 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.