filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_14306 | # Copyright 2021 The Kubeflow 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_0_14307 | # -*- coding: utf-8 -*-
"""
Django settings for nectR Tutoring project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unic... |
the-stack_0_14309 | # -*- coding: utf-8 -*-
import argparse
from functools import partial
from moviepy.editor import VideoFileClip, CompositeVideoClip
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
import os
from PIL import Image, ImageDraw, ImageFont
from pprint import pprint
import subprocess
impo... |
the-stack_0_14311 | """
Shortest path algorithms for unweighted graphs.
"""
import networkx as nx
from multiprocessing import Pool
__all__ = ['bidirectional_shortest_path',
'single_source_shortest_path',
'single_source_shortest_path_length',
'single_target_shortest_path',
'single_target_shortes... |
the-stack_0_14315 | # -*- coding: utf-8 -*-
"""
Created on Wed May 20 12:30:52 2020
@author: nastavirs
"""
import tensorflow as tf
import numpy as np
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0,num_layers-1):
W = se... |
the-stack_0_14318 | import glob, imp, os
IPHONE_UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A403 Safari/602.1"
def discover_drivers():
cdir = os.path.dirname(os.path.realpath(__file__))
drivers = list(filter(lambda p: not os.path.basename(p).start... |
the-stack_0_14319 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 the HERA Project
# Licensed under the MIT License
from hera_qm import utils
from hera_qm.auto_metrics import auto_metrics_run
import sys
ap = utils.get_metrics_ArgumentParser('auto_metrics')
args = ap.parse_args()
history = ' '.join(sys.argv)
auto_me... |
the-stack_0_14325 | #import dependencies
import os
import csv
#declare csv file path
data = os.path.join("..", "Resources", "budget_data.csv")
#read csv file
with open(data, newline="") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
#determine total months and net amount of profit/loss
... |
the-stack_0_14326 | from django.apps import apps
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from .models import Mail, MailTemplate, Attachment, TemplateAttachment
from .tasks import send_asynchronous_mail
from .utils import create_and_send_mail
from django.cor... |
the-stack_0_14327 | # ------------------------------------------------------------------------
# Copyright (c) 2021 megvii-model. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
# Copyright (c) 2020 SenseT... |
the-stack_0_14328 | """
Module of functions involving great circles
(thus assuming spheroid model of the earth)
with points given in longitudes and latitudes.
"""
from __future__ import print_function
import math
import numpy
import numpy.random
# Equatorial radius of the earth in kilometers
EARTH_ER = 6378.137
# Authalic radius of th... |
the-stack_0_14329 | from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from proso.django.models import disable_for_loaddata
from proso_flashcards.models import Term, Context
class ExtendedTerm(Term):
extra_info = models.TextField()
def... |
the-stack_0_14331 | # https://github.com/wolny/pytorch-3dunet/tree/master/pytorch3dunet/unet3d
import argparse
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms
import torch.nn.functional as F
import os
import random
impo... |
the-stack_0_14332 | #!/usr/bin/env python3
# ====================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# ====================================
"""Runtime module. Contains runtime base class and language specific runtime classes."""
import signal
import subprocess
import sys
import time
import os
im... |
the-stack_0_14333 | # Copyright (c) 2019, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: MIT
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
import torch
from base.learners.skill_discovery.base import BaseSkillDiscoveryLearner
class BaseSMMLearner(BaseSkillDi... |
the-stack_0_14334 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 11:01:42 2020
@author: amarmore
"""
# Everything related to the segmentation of the autosimilarity.
import numpy as np
import math
from scipy.sparse import diags
import musicae.model.errors as err
import warnings
def get_autosimilarity(an_array, transpose = False, n... |
the-stack_0_14335 | from __future__ import print_function
from colorama import *
import webbrowser
import sys
import time
# Initialize colored output and set colors
init()
# Get settings from file
file = open('settings.txt', 'r')
settings = file.readlines()
file.close()
# Set timer in seconds
pomodoro = int(settings[1])*60
# Set URL t... |
the-stack_0_14336 | """
source: https://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array
"""
import numpy as np
import imageio
def polygon(a, vertices):
fill = np.ones(a.shape) * True
idx = np.indices(a.shape)
# loop over pairs of corner points
for k in range(vertices.shape[0]):
... |
the-stack_0_14339 | #________INDEX____________.
# |
# 3 functions |
# (6=3+2+1) |
# |
# -4 auxiliary |
# -1 main) |
# |
# (if __name__==__main__) |
#_________________________|
import sys
import re
import matplotlib... |
the-stack_0_14340 | _base_ = [
'../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py'
]
model = dict(
backbone=dict(
type='CBSwinTransformer',
),
neck=dict(
type='CBFPN',
),
test_cfg = dict(
rcnn=dict(
score_thr=0.001,
nms... |
the-stack_0_14341 | def strASCII(s):
c = []
for x in s:
c.append(format(ord(x), 'b').zfill(8))
c = "".join(c)
return c
def ascistr(l,r):
joi = [l,r]
joi = ''.join(joi)
joi = list(map("".join, zip(*[iter(joi)] * 8)))
#print joi
for x in range(len(joi)):
joi[x] = chr(int(joi[x]... |
the-stack_0_14343 | from django.conf import settings
from django.db import models
class PGPManager(models.Manager):
use_for_related_fields = True
use_in_migrations = True
@staticmethod
def _get_pgp_symmetric_decrypt_sql(field):
"""Decrypt sql for symmetric fields using the cast sql if required."""
sql = ... |
the-stack_0_14345 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: fenc=utf-8
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
#
"""
File name: image.py
Author: dhilipsiva <dhilipsiva@gmail.com>
Date created: 2017-02-10
"""
from PIL import ImageFilter
from PIL import Image
size = (128, 128)
im = Image.open("corgi.jpg")
#... |
the-stack_0_14346 | '''
2016 - 2017 ACSL American Computer Science League
SENIOR DIVISION
Contest #2 ASCENDING STRINGS
'''
from unittest import TestCase
def atFirst(snum):
'''
First thoughts
'''
h, r = 0, len(snum)
res = []
while r > h:
# forward
res.append(int(snum[s:e]))
# backward... |
the-stack_0_14348 | import numpy as np
import os
import torch
class Dataset(torch.utils.data.Dataset):
'Characterizes a dataset for PyTorch'
def __init__(self, trajs, device, steps=20):
'Initialization'
dim = trajs[0].shape[1]
self.x = []
self.x_n = np.zeros((0, dim))
for i in range(steps)... |
the-stack_0_14350 | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
# the name of the project
name = 'nbformat'
#-----------------------------------------------------------------------------
# Minimal Python... |
the-stack_0_14351 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# **************************************
# @Time : 2018/9/9 15:52
# @Author : Xiang Ling
# @Lab : nesa.zju.edu.cn
# @File : defenses.py
# **************************************
import os
from abc import ABCMeta
from abc import abstractmethod
class Defense(obje... |
the-stack_0_14353 | import argparse
import configparser
from collections import defaultdict
import itertools
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
import os
import random
import time
import numpy as np
import chainer
if chainer.backends.cuda.available:
import cupy as xp
else:
... |
the-stack_0_14355 | import scipy as sp
from timer import timer
def entropy(values):
"""A slow way to calculate the entropy of the input values"""
values = sp.asarray(values).flatten()
#calculate the probablility of a value in a vector
vUni = sp.unique(values)
lenval = float(values.size)
FreqData = sp.zeros(v... |
the-stack_0_14356 | """
Django settings for {{ project_name }} project.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_... |
the-stack_0_14360 | import sys
import time
from typing import Any, List, Optional
import tempfile
import pytest
import inspect
import requests
from fastapi import (Cookie, Depends, FastAPI, Header, Query, Request,
APIRouter, BackgroundTasks)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses im... |
the-stack_0_14362 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('settings', '0003_settings_action_delete_confirm'),
]
operations = [
migrations.RemoveField(... |
the-stack_0_14363 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# MicroPython documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 21 11:42:03 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... |
the-stack_0_14367 | import sys
import discord
token = sys.argv[1]
client = discord.Client()
@client.event
async def on_ready():
for server in client.guilds:
await server.leave()
await client.close()
client.run(token, bot=False)
|
the-stack_0_14368 | import hashlib
from scapy.all import IP, TCP, PcapReader, rdpcap, wrpcap
from tcp_reliable.packet_helper import getPacketTimestamp, changeTimestamp, writePcap, genKey
class Extractor:
def __init__(self, pcapConfig, BUFFER_SIZE):
self.pcapConfig = pcapConfig
self.BUFFER_SIZE = BUFFER_SIZE
def ... |
the-stack_0_14369 | """
Submodule for working with geochemical data.
"""
import logging
import pandas as pd
import numpy as np
logging.getLogger(__name__).addHandler(logging.NullHandler())
logger = logging.getLogger(__name__)
from ..util.meta import update_docstring_references
from ..util import units
from . import parse
from . import t... |
the-stack_0_14370 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.spider import SitemapSpider
from scrapy.http.request import Request
import json
from urllib.parse import urlencode
class BibaSpider(scrapy.Spider):
name = 'biba'
allowed_domains = ['www.biba.in']
start_urls = [
'https://www.biba.in/new-arrivals',
... |
the-stack_0_14374 | # This file contains dictionaries used in the Dalvik Format.
# https://source.android.com/devices/tech/dalvik/dex-format#type-codes
TYPE_MAP_ITEM = {
0x0: "TYPE_HEADER_ITEM",
0x1: "TYPE_STRING_ID_ITEM",
0x2: "TYPE_TYPE_ID_ITEM",
0x3: "TYPE_PROTO_ID_ITEM",
0x4: "TYPE_FIELD_ID_ITEM",
0x5: "TYPE_M... |
the-stack_0_14384 | # 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 ... |
the-stack_0_14387 | from ROAR.agent_module.agent import Agent
from pathlib import Path
from ROAR.control_module.pid_controller import PIDController
from ROAR.planning_module.local_planner.rl_local_planner import RLLocalPlanner
from ROAR.planning_module.behavior_planner.behavior_planner import BehaviorPlanner
from ROAR.planning_module.miss... |
the-stack_0_14390 | # coding=utf-8
# Copyright 2019 SK T-Brain 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... |
the-stack_0_14391 | import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers, models
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from PIL import Image
import os
import string
import ... |
the-stack_0_14392 | # Copyright 2013-2021 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.package import *
class RktCompilerLib(RacketPackage):
"""Stub package for packages which are currently pa... |
the-stack_0_14394 | #! /usr/bin/env python3
"""Interfaces for launching and remotely controlling Web browsers."""
# Maintained by Georg Brandl.
import os
import shlex
import shutil
import sys
import subprocess
__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
class Error(Exception):
pass
_browsers = {} ... |
the-stack_0_14397 | import argparse
import imp
import os
import re
from functools import wraps
from operator import methodcaller
import orca
from flask import (
Flask, abort, jsonify, request, render_template, redirect, url_for)
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import Htm... |
the-stack_0_14398 | import turtle
# -- Function Definitions
def draw_board(x, y, size):
color = "red"
turtle.color("red")
start = 1
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
for n in range(8):
for n in range(8):
if start == 0:
if color == "red":
... |
the-stack_0_14401 | #!/usr/bin/env python
# coding=utf-8
from setuptools import setup, find_packages
from setuptools.extension import Extension
from codecs import open
import os
import re
import sys
from Cython.Build import cythonize
here = os.path.abspath(os.path.dirname(__file__))
sys.path.append(here)
import versioneer # noqa: E40... |
the-stack_0_14402 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_0_14403 | import os
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import precision_score, recall_score
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
from transformers import BertModel
class RNN_RNN(nn.Module):
def __init__(self, device, hps, loss_weights):
... |
the-stack_0_14405 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
from epicteller.core.dao.message import MessageDAO
from epicteller.core.model.message import TextMessageContent
from epicteller.core.util.enum import MessageType
async def main():
start = 0
limit = 1000
while messages := await MessageDAO.scan_m... |
the-stack_0_14407 | # -*- coding: utf-8 -*-
"""
Parse Excel table to output compact JSON.
Always outputs to terms.json
Usage:
python TermExtractor.py <inputfile.xlsx>
Dependencies:
pandas
"""
# Importing the libraries
import argparse
import json
import sys
from collections import namedtuple
import pandas as pd
# Requires filename to rea... |
the-stack_0_14408 | #!/bin/python3.5
# call it the regression testing file
# @DEVI-if you wanna pipe the output, run with python -u. buffered output
# screws up the output
import sys
import os
from test_LEB128 import test_signed_LEB128
from test_LEB128 import test_unsigned_LEB128
from leb128s import leb128sencodedecodeexhaustive
from le... |
the-stack_0_14411 | try: from Tkinter import *
except: from tkinter import *
win = Tk()
win.title('Reality - Game')
win.iconbitmap('C:\Windows\System32')
win.geometry('400x200+100+100')
from os import startfile as s
fungtion_0 = lambda : s('R프롤로그')
fungtion_1 = lambda : s('R1화')
fungtion_2 = lambda : s('R2화')
fungtion_3 = lambda... |
the-stack_0_14412 | from gym.spaces import Discrete, Box, MultiDiscrete, Space
import numpy as np
import tree
from typing import Union, Optional
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.utils.annotations import override
from ray.rllib.utils.exploration.explora... |
the-stack_0_14416 | import logging
import time
from xml.etree.ElementTree import fromstring
import declxml as xml
import requests
from requests_cache import CachedSession
logger = logging.getLogger(__name__)
class BGGClient:
BASE_URL = "https://www.boardgamegeek.com/xmlapi2"
def __init__(self, cache=None, debug=False):
... |
the-stack_0_14417 | # Copyright 2011 OpenStack Foundation
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Grid Dynamics
# Copyright 2011 Eldar Nugaev, Kirill Shileev, Ilya Alekseyev
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... |
the-stack_0_14418 | import numpy as np
import pytest
from pandas._libs import iNaT
from pandas.core.dtypes.common import is_datetime64tz_dtype, needs_i8_conversion
import pandas as pd
import pandas._testing as tm
from pandas.tests.base.common import allow_na_ops
def test_unique(index_or_series_obj):
obj = index_or_series_obj
... |
the-stack_0_14419 | """
Обрабатываем/отправляем сообщения согласно протоколу:
сообщения разделены нулевым байтом \0.
"""
import select
import socket
HOST = "127.0.0.1"
PORT = 9999
clients = {}
SEP = b"\0"
class Client:
def __init__(self, sock):
self.sock = sock
self._out_stream = bytes()
self._accumulate... |
the-stack_0_14420 | #! /usr/bin/env python
"""
Module containing functions for cubes frame registration.
"""
__author__ = 'C. A. Gomez Gonzalez, V. Christiaens, G. Ruane, R. Farkas'
__all__ = ['frame_shift',
'cube_shift',
'shift_fft',
'frame_center_radon',
'frame_center_satspots',
... |
the-stack_0_14421 | #!/bin/env python
"""Log file
Author: Friedrich Schotte, Mar 2, 2016 - Oct 7, 2017
"""
__version__ = "1.1.5" # caching
from logging import debug,warn,info,error
class LogFile(object):
name = "logfile"
from persistent_property3 import persistent_property
filename = persistent_property("filename","")
de... |
the-stack_0_14422 | from WMCore.Configuration import Configuration
import os,sys
config = Configuration()
reqNamedFromArg = [ arg for arg in sys.argv if arg.startswith( 'General.requestName=' ) ][0].split( '=' )[-1]
puFromArg = reqNamedFromArg[ reqNamedFromArg.find('PU')+2:]
generationInfo = {'0p5':[0.5 , 200 , 500] ,
'... |
the-stack_0_14423 | import sublime
from .event_handler import EventHandler
from .settings import Settings
package_control_installed = False
LOCAL_PACKAGES_VERSION = "0.1.3"
evaluating = False
already_evaluate = False
retry_times = 3
def plugin_loaded():
Settings.reset()
Settings.startup()
print("[Local Packages] v%s" % (LOC... |
the-stack_0_14424 | """
Authorization for Admin API
"""
import re
from shared.models.dashboard_entities import AdminDashboardUser
from shared.service.jwt_auth_wrapper import JWTAuthManager
SCHOOL_REGEX: re.Pattern = re.compile('(?P<school>.+)-admin', flags=re.I)
# JWT Authentication Manager
AUTH_MANAGER = JWTAuthManager(oidc_vault_secr... |
the-stack_0_14425 | from urllib.robotparser import RobotFileParser
from urllib.request import urlopen, Request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
rp = RobotFileParser()
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:67.0) Gecko/20100101 Firefox/67.0'}
req = Request(ur... |
the-stack_0_14427 | # Import Python Libs
from __future__ import absolute_import
import os
import logging
import shutil
# Local imports
from . import constants
from . import util_which
from . import keyring
from . import ops_pool
from . import rados_client
log = logging.getLogger(__name__)
class Error(Exception):
"""
Error
... |
the-stack_0_14428 | #!/usr/bin/env python3
# -*- 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, ... |
the-stack_0_14430 | # -*- coding: utf-8 -*-
# Radproc - A GIS-compatible Python-Package for automated RADOLAN Composite Processing and Analysis.
# Copyright (c) 2018, Jennifer Kreklow.
# DOI: https://doi.org/10.5281/zenodo.1313701
#
# Distributed under the MIT License (see LICENSE.txt for more information), complemented with the following... |
the-stack_0_14431 | import random
# СЛОВАРИ
# Это структура данных, которая содержит неупорядоченную последовательность.
# Если в списках элементы упорядочены по индексам, то в Словарях объекты распалагаются в парах: ключ-значение
# Словари напоминают списки, но есть одно принцимпиальное различие: они состоят из ключей и значений.
# Ключ... |
the-stack_0_14433 | import pytest
import os
from g_code_parsing.g_code_engine import GCodeEngine
from g_code_parsing.g_code_program.supported_text_modes import (
SupportedTextModes,
)
from opentrons.hardware_control.emulation.settings import (
Settings,
SmoothieSettings,
PipetteSettings,
)
from g_code_parsing.utils import... |
the-stack_0_14436 | # -*- coding: utf-8 -*-
"""Plugin to create a Quantum Espresso neb.x input file."""
import copy
import os
from aiida import orm
from aiida.common import InputValidationError, CalcInfo, CodeInfo
from aiida.common.lang import classproperty
from aiida_quantumespresso.calculations.pw import PwCalculation
from aiida_quant... |
the-stack_0_14440 | # ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Defines an explainable lightgbm model."""
import inspect
import json
import logging
from packaging import version
from scipy.sparse im... |
the-stack_0_14442 | import datetime
def printAppBanner():
print("--------------------------------------")
print(" BIRTHDAY APP ")
print("--------------------------------------")
def getBirthday():
print("What is your birth date?")
year = int(input("Year [YYY]? "))
month = int(input("Mont... |
the-stack_0_14444 | '''
Trains a convolutional neural network, using a pre-trained ImageNet model,
to infer the name of a flower given its image.
'''
# -------------------- IMPORT PACKAGES --------------------
import argparse
import os
from copy import deepcopy
from time import time
import torch
from torch import nn, optim
from torchvi... |
the-stack_0_14446 | # 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_0_14448 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def _add_classification(df):
i = pd.read_csv("inputs.csv")
frags = set(i['fragment'])
leads = set(i['lead'])
classification = []
for a in list(df['other_id']):
if a in frags:
classifi... |
the-stack_0_14450 | from newton.db.seed import Trades
from .base import DaoBase
class TradesDao(DaoBase):
def _get_model(self):
return Trades
def history(self, from_datetime, to_datetime, filters=None):
with self._session() as s:
q = s.query(self._Model)
if from_datetime is not None:
... |
the-stack_0_14451 | from __future__ import division, print_function
from astropy.io import fits as pyfits
from astropy.utils.data import get_pkg_data_filename
from astropy import units as u
import matplotlib.pyplot as plt
import numpy as np
from numpy.testing import (assert_almost_equal, assert_array_equal,
as... |
the-stack_0_14452 | """empty message
Revision ID: 5b4a3e3232c8
Revises: 6b071c7c748f
Create Date: 2021-03-13 23:07:54.586777
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5b4a3e3232c8'
down_revision = '6b071c7c748f'
branch_labels = None
depends_on = None
def upgrade():
# ... |
the-stack_0_14455 | # engine/base.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import with_statement
import contextlib
import sys
from .interfaces ... |
the-stack_0_14456 | """Test the TcEx API Module."""
# standard library
import datetime
import os
import time
from random import randint
# third-party
import pytest
from pytest import FixtureRequest
# first-party
from tcex.api.tc.v3.tql.tql_operator import TqlOperator
from tests.api.tc.v3.v3_helpers import TestV3, V3Helper
class TestNo... |
the-stack_0_14458 | from collections import Counter
import logging
from .kad_peerinfo import KadPeerHeap, create_kad_peerinfo
from .utils import gather_dict
log = logging.getLogger(__name__)
class SpiderCrawl:
"""Crawl the network and look for given 160-bit keys."""
def __init__(self, protocol, node, peers, ksize, alpha):
... |
the-stack_0_14459 | from __future__ import division, unicode_literals, print_function, absolute_import # Ease the transition to Python 3
import os
import labscript_utils.excepthook
try:
from labscript_utils import check_version
except ImportError:
raise ImportError('Require labscript_utils > 2.1.0')
check_version('la... |
the-stack_0_14460 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. #... |
the-stack_0_14461 | from dataclasses import dataclass, asdict, field
from typing import (
Union,
Dict,
Optional,
TYPE_CHECKING,
Iterable,
)
import numpy as np
from ..base.backend import BaseBackendMixin
from ....helper import dataclass_from_dict
if TYPE_CHECKING:
from ....typing import DocumentArraySourceType, A... |
the-stack_0_14462 | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Editor Widget"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
# Standard library imports
import ... |
the-stack_0_14464 | import collections
import cv2
import face_recognition.detect_face as detect_face
import face_recognition.facenet as facenet
import math
import numpy as np
import os
import pickle
import sys
import tensorflow as tf
import time
import urllib.request as ur
from datetime import datetime
from object_detection.utils import ... |
the-stack_0_14466 | from .utils import methods
DEBUG_MODE = False
class Router():
def __init__(self):
self.routes = {}
self.num_middleware = 0
for method in methods:
self._generate_add_route_method(method)
# helper method for adding routes.
# if middleware is provided, mount the middlewa... |
the-stack_0_14467 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_0_14468 | """Module for intervention access strategy functions
Determining whether or not to provide access to a given intervention
for a user is occasionally tricky business. By way of the access_strategies
property on all interventions, one can add additional criteria by defining a
function here (or elsewhere) and adding it ... |
the-stack_0_14469 | # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import hashlib
import os
from pex.interpreter import PythonInterpreter
from pants.backend.python.interpreter_cache import PythonInterpreterCache
from pants.backend.python.targets.python_... |
the-stack_0_14473 | from pathlib import Path
new_keys = set()
for file in Path('/').glob('*.txt'):
with file.open('r') as f:
for line in f.readlines():
new_keys.add(line.strip('\n'))
with open('condenced.txt', 'w') as f:
for key in new_keys:
f.write(key + '\n')
|
the-stack_0_14474 | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *
generator = cms.EDFilter("Pythia8GeneratorFilter",
comEnergy = cms.double(13000.0),
pythiaHepMCVerbosity = cms.untracked.bool(False),
pythiaPylis... |
the-stack_0_14475 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Sarielsaz Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test a node with the -disablewallet option.
- Test that validateaddress RPC works when running with ... |
the-stack_0_14476 |
from cachelib import SimpleCache
from slickqaweb.api.project import get_project, get_release, get_build
cache = SimpleCache()
def get_project_release_build_ids(project_name, release_name, build_name):
retval = []
project = None
release = None
build = None
if project_name is None:
retva... |
the-stack_0_14484 | import os
from tqdm import tqdm
import numpy as np
import pandas as pd
import cv2
import time
import re
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import torch.utils.data as data
from torchvision import transforms
import torch
import pdb
import argparse
from src import Networks
from sklearn.... |
the-stack_0_14485 |
from itertools import product
import numpy as np
import pandas as pd
from pandas.testing import assert_series_equal
from numpy.testing import assert_array_equal, assert_array_almost_equal
from seaborn._core.moves import Dodge, Jitter, Shift, Stack
from seaborn._core.rules import categorical_order
from seaborn._core.... |
the-stack_0_14487 | """
Plotting model residuals
========================
"""
import numpy as np
import seaborn as sns
sns.set(style="whitegrid")
# Make an example dataset with y ~ x
rs = np.random.RandomState(7)
x = rs.normal(2, 1, 75)
y = 2 + 1.5 * x + rs.normal(0, 2, 75)
# Plot the residuals after fitting a linear model
sns.residplo... |
the-stack_0_14488 | import logging
from moneywagon import (
get_unspent_outputs, CurrentPrice, get_optimal_fee, PushTx,
get_onchain_exchange_rates,
get_current_price)
from moneywagon.core import get_optimal_services, get_magic_bytes
from bitcoin import mktx, sign, pubtoaddr, privtopub
from .crypto_data import crypto_data
from... |
the-stack_0_14489 | # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
import hashlib
import os.path
import platform
import re
import shutil
from flask_babel import lazy_gettext as _
def get_tree_size(start_path):
"""
return size (in bytes) of filesystem tree
"""
if not os.path.exists(start_path):
... |
the-stack_0_14490 | #!/usr/bin/env python3
# Write a Shannon entropy calculator: H = -sum(pi * log(pi))
# The values should come from the command line
# E.g. python3 entropy.py 0.4 0.3 0.2 0.1
# Put the probabilities into a new list
# Don't forget to convert them to numbers
import math
import sys
numbers = []
for item in sys.argv[1:]:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.