filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_20665 | import sys
import os
pjoin = os.path.join
import shutil
import time
import argparse
import numpy as np
from PIL import Image
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# torch
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import torchvision.utils as v... |
the-stack_106_20666 | # Include the Flask framework
from flask import Flask, url_for, request, redirect, render_template, session
app = Flask(__name__)
# Include the Dwolla REST Client
from dwolla import DwollaGateway
# Include any required keys
import _keys
# Instantiate a new Dwolla Gateway...
# And set the redircet URL to '/redirect'
... |
the-stack_106_20667 | # coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
the-stack_106_20670 | from invoke import task
DOCKER_COMPOSE = 'common/dockerfiles/docker-compose.yml'
DOCKER_COMPOSE_SEARCH = 'common/dockerfiles/docker-compose-search.yml'
DOCKER_COMPOSE_WEBPACK = 'common/dockerfiles/docker-compose-webpack.yml'
DOCKER_COMPOSE_ASSETS = 'dockerfiles/docker-compose-assets.yml'
DOCKER_COMPOSE_OVERRIDE = 'doc... |
the-stack_106_20671 | """
1. 只支持单币种保证金模式
2. 只支持全仓模式
3. 只支持单向持仓模式
"""
import base64
import hashlib
import hmac
import json
import sys
import time
from copy import copy
from datetime import datetime
from urllib.parse import urlencode
from typing import Dict, List, Set
from types import TracebackType
from requests import Response
from pytz ... |
the-stack_106_20675 | from arm.logicnode.arm_nodes import *
class MathNode(ArmLogicTreeNode):
"""Mathematical operations on values."""
bl_idname = 'LNMathNode'
bl_label = 'Math'
arm_version = 1
@staticmethod
def get_enum_id_value(obj, prop_name, value):
return obj.bl_rna.properties[prop_name].enum_items... |
the-stack_106_20677 | from os.path import join
import os
from django.test import TestCase
from wham.httmock import HTTMock
from wham.apis.spotify.models import SpotifyTrack, SpotifyArtist
from wham.tests import build_httmock_functions
APP_DIR = os.path.dirname(__file__)
MOCK_RESPONSES_DIR = join(APP_DIR, 'mock_responses')
mock_functions ... |
the-stack_106_20681 | #!/usr/bin/env python
__all__ = ['get_body_from_horizon']
from astroquery.jplhorizons import Horizons
G = 6.67408e-20 # units of km^3/kg/s^2
def get_body_from_horizon(name, epochs=None, body_type='majorbody',
mass=None, plane='ecliptic'):
if not isinstance(name, str):
rais... |
the-stack_106_20683 | #!/usr/bin/python3
from __future__ import print_function
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.serializer import MsgPackSerializer
from autobahn.wamp.types import ComponentConfig
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunn... |
the-stack_106_20684 | #!/usr/bin/python2.5
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
the-stack_106_20686 | import logging
from fabric import io
OutputLooper = io.OutputLooper
class RoroliteOutputLooper(OutputLooper):
"""Replacement to OutputLooper of Fabric that doesn't print prefix
in the output.
"""
def __init__(self, *args, **kwargs):
OutputLooper.__init__(self, *args, **kwargs)
self.pre... |
the-stack_106_20690 | # Copyright 2012 OpenStack Foundation.
# 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 req... |
the-stack_106_20692 | #!/usr/bin/env python
#############
# CSQ: Consequence|Codons|Amino_acids|Gene|hgnc|Feature|EXON|polyphen|sift
# non_synonymous_codon|gaT/gaG|D/E|ENSG00000116254|CHD5|ENST00000378006|18/25|benign(0.011)|tolerated(0.3)
# nc_transcript_variant|||ENSG00000116254|CHD5|ENST00000491020|5/6|||
#############
import re
from ... |
the-stack_106_20694 | from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .models import Image, Profile
from .forms import ImageForm, ProfileForm
# Create your views here.
def home_page(request):
current_user = request.user
images = Image.objects.all()
profile = Profile.o... |
the-stack_106_20695 | # coding=utf-8
"""Face Detection and Recognition"""
# MIT License
#
# Copyright (c) 2017 François Gervais
#
# This is the work of David Sandberg and shanren7 remodelled into a
# high level container. It's an attempt to simplify the use of such
# technology and provide an easy to use facial recognition package.
#
# http... |
the-stack_106_20696 | import numpy as np
from numpy import array
def NearZero(z):
return abs(z) < 1e-6
##########################################################################
######### Conversion between S03 and euler angle, quaternion #########
##########################################################################
"""
All conve... |
the-stack_106_20698 | """
0504. Base 7
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
"""
class Solution:
def convertToBase7(self, num: int):
n, res = abs(num), ''
while n:
res ... |
the-stack_106_20700 | import string
def dataEncryption(data):
keyLoader=open('HL_Engine\HL_Crypto\key.txt','r')
key=keyLoader.read()
dataModel=[]
ASCER=(string.printable)
for i in ASCER:
dataModel.append(i)
keyModel=str(key)
Position_Generator=[]
Data=str(data)
for i in Data:
#print(i)
... |
the-stack_106_20701 | from typing import List, Tuple, Callable, Optional, Sequence, cast
from thinc.initializers import glorot_uniform_init
from thinc.util import partial
from thinc.types import Ragged, Floats2d, Floats1d, Ints1d
from thinc.api import Model, Ops, registry
from ..tokens import Doc
from ..errors import Errors
from ..vectors ... |
the-stack_106_20702 | import numpy as np
import pytest
from scipy.ndimage import gaussian_filter as scipy_gaussian_filter
from scipy.optimize import curve_fit
from scipy.stats import binned_statistic
from ..field_operations import gaussian_filter, top_hat_filter
N1 = 1000
R1 = 50
N3, N3_large = 64, 128
R3 = 20
@pytest.fixture
def x_1D(... |
the-stack_106_20704 | # First Party
from smdebug.core.logger import get_logger
from smdebug.exceptions import (
RuleEvaluationConditionMet,
StepUnavailable,
TensorUnavailable,
TensorUnavailableForStep,
)
logger = get_logger()
def invoke_rule(rule_obj, start_step=0, end_step=None, raise_eval_cond=False):
step = start_s... |
the-stack_106_20706 | import torch
from onnxruntime.capi.ort_trainer import ORTTrainer, IODescription
from orttraining_test_data_loader import create_ort_test_dataloader, BatchArgsOption, split_batch
from orttraining_test_bert_postprocess import postprocess_model
def warmup_cosine(x, warmup=0.002):
if x < warmup:
return x/war... |
the-stack_106_20710 | """
The tool to check the availability or syntax of domain, IP or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ █... |
the-stack_106_20711 | import unittest
import tiling
EXAMPLE_INPUT = tiling.read_input(filename="example-input.txt")
class TilingTestGroup(unittest.TestCase):
def setUp(self):
self.floor = tiling.Floor.from_instructions(EXAMPLE_INPUT)
def test_nwwswee_flips_reference_tile_itself(self):
self.assertEqual(
... |
the-stack_106_20712 | """
Content Provider: Wikimedia Commons
ETL Process: Use the API to identify all CC-licensed images.
Output: TSV file containing the image, the respective
meta-data.
Notes: https://commons.wikimedia.org/wiki/API:Main_page
... |
the-stack_106_20713 | # Copyright 2013 IBM Corp.
#
# 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 agree... |
the-stack_106_20715 | from avalon import api, style, io
import nuke
import nukescripts
from pype.nuke import lib as pnlib
from avalon.nuke import lib as anlib
from avalon.nuke import containerise, update_container
reload(pnlib)
class LoadBackdropNodes(api.Loader):
"""Loading Published Backdrop nodes (workfile, nukenodes)"""
repres... |
the-stack_106_20716 | # -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2021 IBM Corp. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
... |
the-stack_106_20718 | #!/usr/bin/env python3
####################################################################################################
# #
# get_g09_geom.py ... |
the-stack_106_20719 | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import json
import requests
import base64
import email
import hashlib
from typing import List
from dateutil.parser import parse
from typing import Dict, Tuple, Any, Optional, Union
from threading import ... |
the-stack_106_20721 | import operator
import sys
import warnings
from contextlib import contextmanager
from typing import Any, Callable, ClassVar, Dict, Set
from pydantic import BaseModel, PrivateAttr, main, utils
from ...utils.misc import pick_equality_operator
from .custom_types import JSON_ENCODERS
from .event import EmitterGroup, Even... |
the-stack_106_20722 | """Module for Regression Testing the InVEST Wind Energy module."""
import unittest
import csv
import shutil
import tempfile
import os
import pickle
import re
import numpy
import numpy.testing
from shapely.geometry import Polygon
from shapely.geometry import Point
from osgeo import gdal
from osgeo import ... |
the-stack_106_20723 | import hashlib
from bisect import bisect_left, bisect_right
from queue import PriorityQueue
class SMT:
def __init__(self, hash_function=hashlib.sha256, presence_data='1', absence_data='0', debug=False):
self.hash_function = hash_function
self.digest_size = hash_function().digest_size * 8
... |
the-stack_106_20724 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.layers import Embedding, Dense, Input, concatenate, Layer, Lambda, Dropout, Activation
from tensorflow.keras import backend as K
import tensorflow_... |
the-stack_106_20726 | """Support for monitoring Repetier Server Sensors."""
from datetime import datetime
import logging
import time
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import DEVICE_CLASS_TIMESTAMP
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispa... |
the-stack_106_20727 | import MELC.utils.myFiles as myF
import pandas as pd
from os.path import join
import cv2
import tifffile as tiff
from numpy import unique, where
from config import *
import sys
SEPARATOR = '/'
class RawDataset:
"""RawDataset loader.
works with RAW folder structure of MELC images.
Basicaly ... |
the-stack_106_20734 | import glob
import os
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import ward, dendrogram
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.manifold import MDS
corpus = ''
# Concatenate all files and make a 'band' corpus, ... |
the-stack_106_20735 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_106_20739 | #! -*- coding:utf-8 -*-
import sys
import os
import math
import random
class SumTree(object):
def __init__(self, max_size, name, args):
self.max_size = max_size
self.tree_level = math.ceil(math.log(max_size + 1, 2)) + 1
self.tree_size = 2 ** self.tree_level - 1
self.tree = [0 for i in range(self.tree_size)]... |
the-stack_106_20741 | # third-party imports
from datetime import datetime
# local imports
from app import db
class User(db.Model):
"""
Create a User table
"""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(100), unique=False, nullable=False)
last_name = db... |
the-stack_106_20742 | # Copyright 2019 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_20743 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 1 23:08:23 2021
@author: Connor
"""
import numpy as np
def parse_input(filename):
with open(filename, "r") as fh:
lines = fh.readlines()
output = np.array([int(ll) for ll in lines])
return output
def main():
# Parse input input numpy a... |
the-stack_106_20744 | import torch
def quat_to_rot(rot, conv='wxyz', device='cpu'):
"""converts quat into rotation matrix
Args:
rot ([type]): [description]
conv (str, optional): [description]. Defaults to 'wxyz'.
Raises:
Exception: [description]
Returns:
[type]: [description]
"""
i... |
the-stack_106_20745 | import torch
from torch.utils.data.sampler import Sampler
import numpy as np
class RadioSampler(Sampler):
def __init__(self, data_source, p2n_radio=1, num=None):
super(RadioSampler,self).__init__(data_source)
self.p2n_radio = p2n_radio
# manage data_source into two set
self.pos_idic... |
the-stack_106_20746 | #!../env/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 15:46:30 2020
@author: vilas
"""
from PyQt5 import QtWidgets, uic
# from PyQt5.QtWidgets import QFileDialog
# import os
import icons
from libraries.plot_module import plotFSC
from libraries.plotWindow import PlotAgainstResolution, PlotAngular
fro... |
the-stack_106_20750 | from __future__ import print_function
import inspect
import types
import sys
import operator as op
from collections import namedtuple
from jedi._compatibility import unicode, is_py3, builtins, \
py_version, force_unicode
from jedi.evaluate.compiled.getattr_static import getattr_static
ALLOWED_GETITEM_TYPES = (str... |
the-stack_106_20751 | from argparse import ArgumentParser
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchmetrics import MeanSquaredError
from lit_data import LitDataModule
class LitModel(pl.LightningModule):
"""Template Lightning Module to train model"""... |
the-stack_106_20752 | from os import path
from threading import Thread
from tkinter import HORIZONTAL, BooleanVar, PhotoImage, StringVar, Tk, ttk
from traceback import print_exc
class Gui(Thread):
def __init__(self, agent):
super().__init__(daemon=True)
self.agent = agent
def run(self):
root = Tk()
... |
the-stack_106_20753 | import logging
import hashlib
logger = logging.getLogger(__name__)
BLOCKSIZE = 65536
def hash_file(f):
if not hasattr(f, "read"):
with open(f, "rb") as f_obj:
return hash_file(f_obj)
hasher = hashlib.md5()
buf = f.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
... |
the-stack_106_20754 | if __name__ == '__main__':
import argparse
import glob
import os
import random
import sys
import numpy as np
import tensorflow as tf
from tqdm import tqdm
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
parser = argparse.ArgumentParser()
parser.add_argument('in_dir', type=str)
parser.add_argumen... |
the-stack_106_20758 | import requests
from aiClientInterface import AIClientInterface
import json
import time
import useful
import urllib.parse
# WikiLibs AI Client python module
VERIFY = True # Set to false when working with local API
#API_URL = "https://localhost:5001"
API_URL = "https://wikilibs-dev-api.azurewebsites.net"
APP_KEY = ""
... |
the-stack_106_20760 | import argparse
from utils.data_plotting import plot_summarized_data
def main():
parser = argparse.ArgumentParser(description='Plot summarized data')
# setting
parser.add_argument('--y_min', type=float, default=0.0,
help='Min value of y axis')
parser.add_argument('--y_max', t... |
the-stack_106_20761 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
from mpl_toolkits.axes_grid1 import make_axes_locatable
class ImgView(object):
def __init__(self, img, fig_id=None, imin=None, imax=None):
self.fig = plt.figure(fig_id)
self.ax = self.fig.add_axes([0.1,... |
the-stack_106_20763 | import abc
import copy
import json
import string
class JSONObject(metaclass=abc.ABCMeta):
@abc.abstractmethod
def __to_json__(self):
pass
@staticmethod
@abc.abstractclassmethod
def from_json(action, selector):
pass
def to_instance(self, target):
return copy.copy(self... |
the-stack_106_20764 | """
unit tests for the git_pillar runner
"""
import errno
import logging
import tempfile
import salt.runners.git_pillar as git_pillar
import salt.utils.files
import salt.utils.gitfs
from tests.support.gitfs import _OPTS
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import patch
from ... |
the-stack_106_20766 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
''' Voting module: generate votes from XYZ and features of seed points.
Date: July, 2019
Author: Charles R. Qi and Or Litany
'''
import torc... |
the-stack_106_20767 | # -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.recovery.meng2015` module.
"""
import numpy as np
import unittest
from colour.colorimetry import (MSDS_CMFS_STANDARD_OBSERVER, SDS_ILLUMINANTS,
SpectralShape, reshape_msds, reshape_sd,
... |
the-stack_106_20768 | # Copyright (c) 2021 - present / Neuralmagic, 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 b... |
the-stack_106_20770 | #!/usr/bin/env python
############################################################################
# Copyright (c) 2011-2014 Saint-Petersburg Academic University
# All Rights Reserved
# See file LICENSE for details.
############################################################################
import sys
import os
impo... |
the-stack_106_20771 | #!/usr/bin/python
# Copyright: Ansible Project
# 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: cloudwatchlogs_log_group_metric_filter
version_added: 1.0.0
... |
the-stack_106_20775 | import click
from copy import deepcopy
from corgie import scheduling, argparsers, helpers, stack
from corgie.log import logger as corgie_logger
from corgie.layers import get_layer_types, DEFAULT_LAYER_TYPE, str_to_layer_type
from corgie.boundingcube import get_bcube_from_coords
from corgie.argparsers import (
LA... |
the-stack_106_20777 | import csv
import PYSHP
from PYSHP import Writer
vorige = ''
n = 0
with open('data.geo.ict.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=',', quotechar='"')
kolomnamen = next(data)
k_bird =kolomnamen.index('bird_name')
k_lat = kolomnamen.index('latitude')... |
the-stack_106_20778 | from unittest import TestCase
from nose_parameterized import parameterized, param
from samcli.lib.utils.colors import Colored
class TestColored(TestCase):
def setUp(self):
self.msg = "message"
@parameterized.expand(
[
param("red", "\x1b[31m"),
param("green", "\x1b[32m... |
the-stack_106_20779 | # -*- coding: utf-8 -*-
"""SF DECONVOLVE ARGUMENTS
This module sets the arguments for sf_deconvolve.py.
:Author: Samuel Farrens <samuel.farrens@gmail.com>
:Version: 2.4
:Date: 23/10/2017
"""
import argparse as ap
from argparse import ArgumentDefaultsHelpFormatter as formatter
from . import __version__
class Ar... |
the-stack_106_20780 | from faker import Faker
from examples import settings
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
def generate_tasks(context):
tasks_list = ctx.web.lists.get_by_title("Tasks")
for idx in range(0, 10):
tit... |
the-stack_106_20782 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import ExtraTreesClass... |
the-stack_106_20783 | # -*- coding: utf-8 -*-
"""
babel.messages.jslexer
~~~~~~~~~~~~~~~~~~~~~~
A simple JavaScript 1.5 lexer which is used for the JavaScript
extractor.
:copyright: (c) 2013-2018 by the Babel Team.
:license: BSD, see LICENSE for more details.
"""
from collections import namedtuple
import re
from ba... |
the-stack_106_20786 | import traceback
from pathlib import Path
from typing import Iterator, Set, Tuple
from .ast_node import GherkinDocument
from .errors import (
BaseError,
EmptySources,
EquivalentError,
InternalError,
NothingChanged,
StableError,
)
from .formatter import LineGenerator
from .options import Newline... |
the-stack_106_20787 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... |
the-stack_106_20788 | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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_20790 | from basedbinpy import Client
from basedbinpy.exceptions import PasteNotFound, InvalidObjectId, InvalidMimeType
import sys
import argparse
parser = argparse.ArgumentParser(
prog="basedbinpy",
description="CLI for basedbin pastebin-like API service.",
allow_abbrev=False,
)
subparsers = parser.add_subparsers... |
the-stack_106_20793 | from typing import Union, Dict, Optional, Any, IO, TYPE_CHECKING
from thinc.api import Config, fix_random_seed, set_gpu_allocator
from thinc.api import ConfigValidationError
from pathlib import Path
import srsly
import numpy
import tarfile
import gzip
import zipfile
import tqdm
from itertools import islice
import warni... |
the-stack_106_20795 | # Copyright 2021 The Cirq Developers
#
# 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 ... |
the-stack_106_20796 | # coding: utf-8
from __future__ import division, print_function
import tensorflow as tf
import numpy as np
import argparse
import cv2
import time
from utils.misc_utils import parse_anchors, read_class_names
from utils.nms_utils import gpu_nms
from utils.plot_utils import get_color_table, plot_one_box
from utils.data... |
the-stack_106_20797 | """ File for plots describing proportion of missing data in US dataset.
"""
import os
import pandas as pd
import numpy as np
import US_utils
import matplotlib.pyplot as plt
# Select a subset of people missing some entry I.E. age, number of counts missing, etc.
##########################
# Single frame missingness
#... |
the-stack_106_20802 | # Copyright 2019 T-Mobile US, 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 wri... |
the-stack_106_20803 | import math
import torch
import torch.distributed as dist
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from collections import defaultdict
from deepspeed.runtime.zero.utils import _initialize_parameter_parallel_groups
from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossSc... |
the-stack_106_20804 | from pylagrit.pexpect import spawn
from subprocess import call, PIPE
import os,sys
import glob
import re
from collections import OrderedDict
import numpy
import warnings
from itertools import product
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from xml.dom im... |
the-stack_106_20805 | # Copyright (c) 2009-2010, Cloud Matrix Pty. Ltd.
# Copyright (c) 2016-2016, Ilya Petrash (aka gil9red)
# All rights reserved; available under the terms of the BSD License.
"""
PySideKick.Console: a simple embeddable python shell
=====================================================
This module provides the call ... |
the-stack_106_20806 | __licence__ = 'MIT'
__author__ = 'kuyaki'
__credits__ = ['kuyaki']
__maintainer__ = 'kuyaki'
__date__ = '2021/04/22'
from program_slicing.graph.cdg import ControlDependenceGraph
from program_slicing.graph.cfg import ControlFlowGraph
from program_slicing.graph.ddg import DataDependenceGraph
from program_slicing.graph.p... |
the-stack_106_20807 | #!/usr/bin/env python3
# Plot DNNMark time logs from .log files
# Run with one option in filenames: algoconfig
import re
import sys
import os
import io
from cycler import cycler
import matplotlib
matplotlib.use("Agg")
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
fr... |
the-stack_106_20808 | ans=[]
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
m = min(l)
temp = l
temp=sorted(temp)
flag = 1
for i in range(n):
if l[i] % m != 0:
if l[i] != temp[i]:
flag = 0
break
if flag==1:
ans.app... |
the-stack_106_20809 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattergeo"
_path_str = "scattergeo.line"
_valid_props = {"color", "dash", "width"}
# col... |
the-stack_106_20813 | #!/usr/bin/env python
import flask
from flask import Flask
from flask import render_template, request
class Square(object):
def __init__(self, name, image="", url="#"):
self.name = name
self.image = image
self.url = url
app = Flask(__name__)
@app.route('/')
def index():
projects ... |
the-stack_106_20814 | from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from classDefinitions import Request, Material
from settings import GetApplicationName, GetClientSecret, GetCalendarSetti... |
the-stack_106_20815 | from io import BytesIO
import aiohttp
class SnowClient:
def __init__(self, api_key):
self.api_key = api_key
async def _get_json(self, url, params: dict = None) -> dict:
async with aiohttp.ClientSession() as session:
async with session.get(
url, headers={"Authoriza... |
the-stack_106_20816 |
# Standardized testing interface.
def test():
import os
dir_name = os.path.dirname(os.path.abspath(__file__))
test_name = os.path.basename(dir_name)
fort_file = os.path.join(dir_name, f"{test_name}.f03")
build_dir = os.path.join(dir_name, f"fmodpy_{test_name}")
print(f" {test_name}..", end=" ... |
the-stack_106_20817 | import drake
import drake.cxx
import subprocess
def _default_make_binary():
from drake.which import which
to_try = [
'make',
'gmake',
'mingw32-make',
'mingw64-make',
]
for binary in to_try:
path = which(binary)
if path is not None:
return path
_DEFAULT_MAKE_BINARY = _default_mak... |
the-stack_106_20818 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2009,2012 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either vers... |
the-stack_106_20819 | #!/usr/bin/env python
# cardinal_pythonlib/pyramid/responses.py
"""
===============================================================================
Original code copyright (C) 2009-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Versio... |
the-stack_106_20821 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015 Philipp Ludwig <git@philippludwig.net>
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 ... |
the-stack_106_20823 | """
Reference: Dawen, Liang, et al. "Variational autoencoders for collaborative filtering." in WWW2018
@author: wubin
"""
import tensorflow as tf
import numpy as np
from time import time
from util import learner, tool
from tensorflow.contrib.layers import apply_regularization, l2_regularizer
from model.AbstractRecommen... |
the-stack_106_20824 | """Kerasの損失関数を実装するための関数など。"""
import numpy as np
import tensorflow as tf
import pytoolkit as tk
@tk.backend.name_scope
def reduce(x, reduce_mode):
"""バッチ次元だけ残して合計や平均を取る。"""
tf.debugging.assert_rank_at_least(x, 1)
if reduce_mode is None:
return x
axes = list(range(1, x.shape.rank))
if len... |
the-stack_106_20825 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Abstract: excel operation
import os
import random
import string
import datetime
from cStringIO import StringIO
import xlrd
import xlwt
class Excel(object):
'''
excel processing
'''
def __init__(self, home='/tmp', trans=None):
self.home = home... |
the-stack_106_20827 | from __future__ import unicode_literals
from copy import copy
import difflib
import errno
from functools import wraps
import json
import os
import re
import sys
import select
import socket
import threading
import unittest
from unittest import skipIf # Imported here for backward compatibility
from unittest.util... |
the-stack_106_20828 | from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.forms import (
UserCreationForm,
AuthenticationForm
)
from django.contrib import messages
from django.shortcuts import render, redirect
... |
the-stack_106_20829 | import os
import re
from xml.etree import ElementTree
import requests
import platform
from webdriver_manager.logger import log
from webdriver_manager.utils import (
validate_response,
chrome_version,
ChromeType,
os_name,
OSType,
firefox_version,
)
class Driver(object):
def __init__(self,... |
the-stack_106_20830 | # Copyright (c) 2020 Graphcore Ltd. All rights reserved.
"""
Main training script for the CosmoFlow Keras benchmark
"""
# System imports
import os
import argparse
import logging
import pickle
from functools import partial
# External imports
import yaml
import numpy as np
import pandas as pd
import json
# import tens... |
the-stack_106_20831 | """Patients views."""
# Django Rest Framework
from rest_framework import viewsets, mixins, status
from rest_framework.response import Response
# Permissions
from rest_framework.permissions import IsAuthenticated
from weight.patients.permissions import IsDoctorPatient
# Models
from weight.patients.models import Patie... |
the-stack_106_20834 | from django import template
register=template.Library()
@register.filter
def choice(value, choices):
'''
Get the choice displayable value
Example Given:
class Model(models.model):
STATUS_DRAFT = 0
STATUS_PENDDING = 1
STATUS_APPROVING = 2
STATUS_CONFIRMED ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.